diff --git a/convert_ja_tar.py b/convert_ja_tar.py new file mode 100644 index 0000000000000000000000000000000000000000..6be7d39d76db073083e554f758719549e9626a19 --- /dev/null +++ b/convert_ja_tar.py @@ -0,0 +1,23 @@ +import sys +import os + +# 将 scripts/speech_recognition 添加到 sys.path,以便导入 convert_to_tarred_audio_dataset +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "scripts", "speech_recognition"))) + +import convert_to_tarred_audio_dataset + +def main(): + convert_to_tarred_audio_dataset.create_tar_datasets( + manifest_path="data/common_voice_11_0/ja/train/train_common_voice_11_0_manifest.json", + target_dir="data/common_voice_11_0/ja/train_tarred_1bk", + num_shards=1024, + max_duration=15.0, + min_duration=1.0, + shuffle=True, + shuffle_seed=1, + sort_in_shards=True, + workers=-1 + ) + +if __name__ == "__main__": + main() diff --git a/how_to_use_cv11.py b/how_to_use_cv11.py deleted file mode 100644 index 689032d13f838cc14fb8ffc01547d8439d4aaf03..0000000000000000000000000000000000000000 --- a/how_to_use_cv11.py +++ /dev/null @@ -1,30 +0,0 @@ -# Load the dataset (locally) - -from datasets import load_dataset - -cv_11 = load_dataset("mozilla-foundation/common_voice_11_0", "hi", split="train") - -# Stream the dataset - -from datasets import load_dataset - -cv_11 = load_dataset("mozilla-foundation/common_voice_11_0", "hi", split="train", streaming=True) - -print(next(iter(cv_11))) - -# Create a PyTorch dataloader - -from datasets import load_dataset -from torch.utils.data.sampler import BatchSampler, RandomSampler - -cv_11 = load_dataset("mozilla-foundation/common_voice_11_0", "hi", split="train") -batch_sampler = BatchSampler(RandomSampler(cv_11), batch_size=32, drop_last=False) -dataloader = DataLoader(cv_11, batch_sampler=batch_sampler) - -# Create a streaming PyTorch dataloader - -from datasets import load_dataset -from torch.utils.data import DataLoader - -cv_11 = load_dataset("mozilla-foundation/common_voice_11_0", "hi", split="train") -dataloader = DataLoader(cv_11, batch_size=32) diff --git a/main.py b/main.py new file mode 100644 index 0000000000000000000000000000000000000000..bccd452e3f095e7bde2fa9346f69aba812904122 --- /dev/null +++ b/main.py @@ -0,0 +1,41 @@ + +def clear_text(): + """ + 好像不需要 + """ + import json + from tqdm import tqdm + + # dev_manifest = f"{YOUR_DATA_ROOT}/validation/validation_mozilla-foundation_common_voice_11_0_manifest.json" + # test_manifest = f"{YOUR_DATA_ROOT}/test/test_mozilla-foundation_common_voice_11_0_manifest.json" + train_manifest = f"data/common_voice_11_0/ja/train/train_common_voice_11_0_manifest.json" + + def compute_char_counts(manifest): + char_counts = {} + with open(manifest, 'r') as fn_in: + for line in tqdm(fn_in, desc="Compute counts.."): + line = line.replace("\n", "") + data = json.loads(line) + text = data["text"] + for word in text.split(): + for char in word: + if char not in char_counts: + char_counts[char] = 1 + else: + char_counts[char] += 1 + return char_counts + + char_counts = compute_char_counts(train_manifest) + + threshold = 10 + trash_char_list = [] + + for char in char_counts: + if char_counts[char] <= threshold: + trash_char_list.append(char) + + print(trash_char_list) + +if __name__ == "__main__": + # clear_text() + pass diff --git a/nemo/README.md b/nemo/README.md deleted file mode 100644 index d5cc00e74caef440c2ea28d4b56f268255973fe3..0000000000000000000000000000000000000000 --- a/nemo/README.md +++ /dev/null @@ -1,26 +0,0 @@ -NeMo (**Ne**ural **Mo**dules) is a toolkit for creating AI applications built around **neural modules**, conceptual blocks of neural networks that take *typed* inputs and produce *typed* outputs. - -## **collections/** -* **ASR** - Collection of modules and models for building speech recognition networks. -* **TTS** - Collection of modules and models for building speech synthesis networks. -* **Audio** - Collection of modules and models for building audio processing networks. -* **SpeechLM2** - Collection of modules and models for building multimodal LLM. - -## **core/** -Provides fundamental APIs and utilities for NeMo modules, including: -- **Classes** - Base classes for datasets, models, and losses. -- **Config** - Configuration management utilities. -- **Neural Types** - Typed inputs/outputs for module interaction. -- **Optim** - Optimizers and learning rate schedulers. - -## **lightning/** -Integration with PyTorch Lightning for training and distributed execution: -- **Strategies & Plugins** - Custom Lightning strategies. -- **Fabric** - Lightweight wrapper for model training. -- **Checkpointing & Logging** - Utilities for managing model states. - -## **utils/** -General utilities for debugging, distributed training, logging, and model management: -- **callbacks/** - Hooks for training processes. -- **loggers/** - Logging utilities for different backends. -- **debugging & profiling** - Performance monitoring tools. diff --git a/nemo/__init__.py b/nemo/__init__.py deleted file mode 100644 index 5b9fedbd1cc691ff5b16a78420965131787f37dd..0000000000000000000000000000000000000000 --- a/nemo/__init__.py +++ /dev/null @@ -1,28 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from nemo.package_info import ( - __contact_emails__, - __contact_names__, - __description__, - __download_url__, - __homepage__, - __keywords__, - __license__, - __package_name__, - __repository_url__, - __shortversion__, - __version__, -) diff --git a/nemo/agents/__init__.py b/nemo/agents/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/agents/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/agents/voice_agent/__init__.py b/nemo/agents/voice_agent/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/agents/voice_agent/pipecat/__init__.py b/nemo/agents/voice_agent/pipecat/__init__.py deleted file mode 100644 index 55fb128340afb58c4785a2c5cc7477a1d6867a33..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/pipecat/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -try: - import pipecat -except ImportError: - raise ImportError("pipecat is not installed. Please install it with `pip install pipecat-ai`.") diff --git a/nemo/agents/voice_agent/pipecat/frames/__init__.py b/nemo/agents/voice_agent/pipecat/frames/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/pipecat/frames/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/agents/voice_agent/pipecat/frames/frames.py b/nemo/agents/voice_agent/pipecat/frames/frames.py deleted file mode 100644 index df5f1c2c6fef3bede47251b2f0403fe3d124a192..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/pipecat/frames/frames.py +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from dataclasses import dataclass -import numpy as np -from pipecat.frames.frames import DataFrame - - -@dataclass -class DiarResultFrame(DataFrame): - """Diarization frame.""" - - diar_result: np.ndarray | int - stream_id: str = "default" diff --git a/nemo/agents/voice_agent/pipecat/processors/__init__.py b/nemo/agents/voice_agent/pipecat/processors/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/pipecat/processors/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/agents/voice_agent/pipecat/processors/frameworks/__init__.py b/nemo/agents/voice_agent/pipecat/processors/frameworks/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/pipecat/processors/frameworks/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/agents/voice_agent/pipecat/processors/frameworks/rtvi.py b/nemo/agents/voice_agent/pipecat/processors/frameworks/rtvi.py deleted file mode 100644 index 03106a41f2a873fd382799784f776d1df3b33493..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/pipecat/processors/frameworks/rtvi.py +++ /dev/null @@ -1,72 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from loguru import logger -from pipecat.frames.frames import Frame, LLMFullResponseEndFrame, LLMFullResponseStartFrame, TTSTextFrame -from pipecat.observers.base_observer import FramePushed -from pipecat.processors.frameworks.rtvi import ( - RTVIBotLLMStartedMessage, - RTVIBotLLMStoppedMessage, - RTVIBotTranscriptionMessage, - RTVIBotTTSTextMessage, -) -from pipecat.processors.frameworks.rtvi import RTVIObserver as _RTVIObserver -from pipecat.processors.frameworks.rtvi import RTVIProcessor, RTVITextMessageData -from pipecat.transports.base_output import BaseOutputTransport - - -class RTVIObserver(_RTVIObserver): - """ - An observer that processes RTVI frames and pushes them to the transport. - """ - - def __init__(self, rtvi: RTVIProcessor, *args, **kwargs): - super().__init__(rtvi, *args, **kwargs) - - async def on_push_frame(self, data: FramePushed): - """Process a frame being pushed through the pipeline. - - Args: - data: Frame push event data containing source, frame, direction, and timestamp. - """ - src = data.source - frame: Frame = data.frame - - if frame.id in self._frames_seen: - return - - if not self._params.bot_llm_enabled: - if isinstance(frame, LLMFullResponseStartFrame): - await self.send_rtvi_message(RTVIBotLLMStartedMessage()) - self._frames_seen.add(frame.id) - elif isinstance(frame, LLMFullResponseEndFrame): - await self.send_rtvi_message(RTVIBotLLMStoppedMessage()) - self._frames_seen.add(frame.id) - elif isinstance(frame, TTSTextFrame) and isinstance(src, BaseOutputTransport): - message = RTVIBotTTSTextMessage(data=RTVITextMessageData(text=frame.text)) - await self.send_rtvi_message(message) - await self._push_bot_transcription(frame.text) - self._frames_seen.add(frame.id) - else: - await super().on_push_frame(data) - else: - await super().on_push_frame(data) - - async def _push_bot_transcription(self, text: str): - """Push accumulated bot transcription as a message.""" - if len(text.strip()) > 0: - message = RTVIBotTranscriptionMessage(data=RTVITextMessageData(text=text)) - logger.debug(f"Pushing bot transcription: `{text}`") - await self.send_rtvi_message(message) diff --git a/nemo/agents/voice_agent/pipecat/services/__init__.py b/nemo/agents/voice_agent/pipecat/services/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/pipecat/services/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/agents/voice_agent/pipecat/services/nemo/__init__.py b/nemo/agents/voice_agent/pipecat/services/nemo/__init__.py deleted file mode 100644 index 1b96c38c91ce888fa1c761fb3b6bf1190ac497f0..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/pipecat/services/nemo/__init__.py +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from .diar import NemoDiarService -from .llm import HuggingFaceLLMService -from .stt import NemoSTTService -from .tts import NeMoFastPitchHiFiGANTTSService -from .turn_taking import NeMoTurnTakingService diff --git a/nemo/agents/voice_agent/pipecat/services/nemo/audio_logger.py b/nemo/agents/voice_agent/pipecat/services/nemo/audio_logger.py deleted file mode 100644 index 14d196d4c6dd8a4444df3b8462969068bb0b69de..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/pipecat/services/nemo/audio_logger.py +++ /dev/null @@ -1,844 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import json -import threading -import wave -from datetime import datetime -from pathlib import Path -from typing import Optional, Union - -import librosa -import numpy as np -from loguru import logger -from pipecat.frames.frames import TranscriptionFrame -from pipecat.observers.base_observer import BaseObserver, FramePushed - - -class AudioLogger: - """ - Utility class for logging audio data and transcriptions during voice agent interactions. - - This logger saves: - - Audio files in WAV format - - Transcriptions with metadata in JSON format - - Session information and metadata - - File structure: - log_dir/ - ├── session_YYYYMMDD_HHMMSS/ - │ ├── user/ - │ │ ├── 00001_HHMMSS.wav - │ │ ├── 00001_HHMMSS.json - │ │ ├── 00002_HHMMSS.wav - │ │ └── 00002_HHMMSS.json - │ ├── agent/ - │ │ ├── 00001_HHMMSS.wav - │ │ ├── 00001_HHMMSS.json - │ └── session_metadata.json - - Args: - log_dir: Base directory for storing logs (default: "./audio_logs") - session_id: Optional custom session ID. If None, auto-generated from timestamp - enabled: Whether logging is enabled (default: True) - - # 12/19/2025 Note: Stereo conversation recording is implemented, - # but -0.8 seconds offset needs to be applied to make the session sound synced. - """ - - def __init__( - self, - log_dir: Union[str, Path] = "./audio_logs", - session_id: Optional[str] = None, - enabled: bool = True, - user_audio_sample_rate: int = 16000, - pre_roll_time_sec: float = 0.8, - round_precision: int = 2, - ): - self.enabled = enabled - if not self.enabled: - logger.info("[AudioLogger] AudioLogger is disabled") - return - - self.log_dir = Path(log_dir) - - # Generate session ID if not provided - self.session_start_time = datetime.now() - if session_id is None: - session_id = f"session_{self.session_start_time.strftime('%Y%m%d_%H%M%S')}" - self.first_audio_timestamp = None - self.session_id = session_id - self.session_dir = self.log_dir / session_id - - # Create directories - self.user_dir = self.session_dir / "user" - self.agent_dir = self.session_dir / "agent" - - self.user_dir.mkdir(parents=True, exist_ok=True) - self.agent_dir.mkdir(parents=True, exist_ok=True) - - # Counters for file naming (thread-safe) - self._user_counter = 0 - self._agent_counter = 0 - self._turn_index = 0 # Turn index for conversation turns - self._current_speaker = None # Track current speaker for turn transitions - self._agent_turn_start_time = None # Captured when BotStartedSpeakingFrame is received - self._lock = threading.Lock() - self.staged_metadata = None - self._staged_audio_data = None - self._pre_roll_time_sec = pre_roll_time_sec - self._round_precision = round_precision - - self.turn_audio_buffer = [] - self.continuous_user_audio_buffer = [] - self.turn_transcription_buffer = [] - - # Stereo conversation recording (left=agent, right=user) - self._stereo_conversation_filename = "conversation_stereo.wav" - self._stereo_conversation_file = self.session_dir / self._stereo_conversation_filename - self._stereo_sample_rate = user_audio_sample_rate # Use user audio sample rate (downsample agent audio) - self._stereo_audio_buffer_left: list = [] # Agent audio (left channel) - self._stereo_audio_buffer_right: list = [] # User audio (right channel) - - # Session metadata - # agent_entries is a list of lists: each sublist contains segments for one turn - # e.g., [[seg1, seg2, seg3], [seg4, seg5], ...] where each [] is a turn - self.session_metadata = { - "session_id": session_id, - "start_time": self.session_start_time.isoformat(), - "user_entries": [], - "agent_entries": [], # List of turns, each turn is a list of segments - } - - logger.info(f"[AudioLogger] AudioLogger initialized: {self.session_dir}") - - def append_continuous_user_audio(self, audio_data: bytes): - """ - Append audio data to the continuous user audio buffer for stereo conversation. - - This method should be called for EVERY audio frame received from the user, - regardless of VAD state, to record the complete conversation audio. - - Args: - audio_data: Raw audio data as bytes - """ - if not self.enabled: - return - - self.continuous_user_audio_buffer.append(audio_data) - - def _resample_audio( - self, - audio_data: Union[bytes, np.ndarray], - orig_sr: int, - target_sr: int, - ) -> np.ndarray: - """ - Resample audio data to a target sample rate using librosa. - - Args: - audio_data: Audio data as bytes (int16) or numpy array - orig_sr: Original sample rate - target_sr: Target sample rate - - Returns: - Resampled audio as numpy array (float32) - """ - # Convert bytes to numpy array if needed - if isinstance(audio_data, bytes): - audio_array = np.frombuffer(audio_data, dtype=np.int16).astype(np.float32) / 32768.0 - elif audio_data.dtype == np.int16: - audio_array = audio_data.astype(np.float32) / 32768.0 - else: - audio_array = audio_data.astype(np.float32) - - # Resample if needed - if orig_sr != target_sr: - audio_array = librosa.resample(audio_array, orig_sr=orig_sr, target_sr=target_sr) - - return audio_array - - def _append_to_stereo_conversation( - self, - audio_data: Union[bytes, np.ndarray], - channel: str, - start_time: float, - sample_rate: int, - ): - """ - Append audio to the stereo conversation buffer at the correct time position. - - Args: - audio_data: Audio data as bytes or numpy array - channel: "left" for agent, "right" for user - start_time: Start time in seconds from session start - sample_rate: Sample rate of the input audio - """ - if not self.enabled: - return - - try: - # Resample to stereo sample rate if needed - audio_float = self._resample_audio(audio_data, sample_rate, self._stereo_sample_rate) - - # Calculate the sample position for this audio - start_sample = int(start_time * self._stereo_sample_rate) - - # Get the appropriate buffer - if channel == "left": - buffer = self._stereo_audio_buffer_left - else: - buffer = self._stereo_audio_buffer_right - - # Extend buffer with zeros if needed to reach start position - current_length = len(buffer) - if start_sample > current_length: - buffer.extend([0.0] * (start_sample - current_length)) - - # Append or overwrite audio samples - for i, sample in enumerate(audio_float): - pos = start_sample + i - if pos < len(buffer): - # Mix with existing audio (in case of overlap) - buffer[pos] = np.clip(buffer[pos] + sample, -1.0, 1.0) - else: - buffer.append(sample) - - logger.debug( - f"[AudioLogger] Appended {len(audio_float)} samples to {channel} channel " - f"at position {start_sample} (buffer now {len(buffer)} samples)" - ) - - except Exception as e: - logger.error(f"[AudioLogger] Error appending to stereo conversation: {e}") - - def save_stereo_conversation(self): - """ - Save the stereo conversation buffer to a WAV file. - Left channel = Agent, Right channel = User. - - User audio comes from continuous_user_audio_buffer (not affected by VAD). - """ - if not self.enabled: - return - - if not self._stereo_audio_buffer_left and not self.continuous_user_audio_buffer: - logger.warning("[AudioLogger] No stereo conversation audio to save") - return - - try: - # Build right channel (user) from continuous buffer - # This is raw bytes at user sample rate, no resampling needed since stereo uses user sample rate - if self.continuous_user_audio_buffer: - continuous_audio_bytes = b"".join(self.continuous_user_audio_buffer) - right_array = np.frombuffer(continuous_audio_bytes, dtype=np.int16).astype(np.float32) / 32768.0 - else: - right_array = np.array([], dtype=np.float32) - - left_array = np.array(self._stereo_audio_buffer_left, dtype=np.float32) - - # Pad the shorter buffer with zeros - max_length = max(len(left_array), len(right_array)) - - # Pad to same length - if len(left_array) < max_length: - left_array = np.pad(left_array, (0, max_length - len(left_array))) - if len(right_array) < max_length: - right_array = np.pad(right_array, (0, max_length - len(right_array))) - - # Create stereo array (interleaved: L, R, L, R, ...) - stereo_array = np.column_stack((left_array, right_array)) - - # Convert to int16 - stereo_int16 = (stereo_array * 32767).astype(np.int16) - - # Save as WAV - with wave.open(str(self._stereo_conversation_file), 'wb') as wav_file: # type: ignore[union-attr] - wav_file.setnchannels(2) # Stereo - wav_file.setsampwidth(2) # 16-bit - wav_file.setframerate(self._stereo_sample_rate) - wav_file.writeframes(stereo_int16.tobytes()) - - duration_sec = max_length / self._stereo_sample_rate - logger.info( - f"[AudioLogger] Saved stereo conversation: {self._stereo_conversation_file} " - f"({duration_sec:.2f} seconds, {max_length} samples)" - ) - - except Exception as e: - logger.error(f"[AudioLogger] Error saving stereo conversation: {e}") - - def get_time_from_start_of_session(self, timestamp: datetime = None) -> float: - """Get the time from the start of the session to the given datetime string.""" - # get the time difference in seconds. - if self.first_audio_timestamp is None: - raise ValueError("First audio timestamp is not set. Aborting time calculation.") - time_diff = (timestamp if timestamp else datetime.now()) - self.first_audio_timestamp - return time_diff.total_seconds() - - def _get_next_counter(self, speaker: str) -> int: - """Get the next counter value for a speaker in a thread-safe manner.""" - with self._lock: - if speaker == "user": - self._user_counter += 1 - return self._user_counter - else: - self._agent_counter += 1 - return self._agent_counter - - def increment_turn_index(self, speaker: str = None) -> int: - """ - Increment the turn index if the speaker has changed. - - Args: - speaker: "user" or "agent". If provided, only increments - if this is different from the current speaker. - If None, always increments. - - Returns: - The current turn index after any increment. - """ - with self._lock: - if speaker is None: - # Always increment if no speaker specified - self._turn_index += 1 - logger.debug(f"[AudioLogger] Turn index incremented to {self._turn_index}") - elif speaker != self._current_speaker: - # Only increment if speaker changed - self._current_speaker = speaker - self._turn_index += 1 - # Reset agent turn start time when speaker changes - if speaker == "agent": - self._agent_turn_start_time = None - logger.debug( - f"[AudioLogger] Speaker changed to {speaker}, turn index incremented to {self._turn_index}" - ) - # else: same speaker, no increment - return self._turn_index - - def set_agent_turn_start_time(self): - """ - Set the start time for the current agent turn. - - This should be called when BotStartedSpeakingFrame is received, - which indicates the audio is actually starting to play (not just generated). - This provides more accurate timing than capturing time during TTS generation. - """ - if not self.enabled: - return - - # Only set if not already set for this turn - if self._agent_turn_start_time is None: - self._agent_turn_start_time = self.get_time_from_start_of_session() - logger.debug(f"[AudioLogger] Agent turn start time set to {self._agent_turn_start_time:.3f}s") - - def _save_audio_wav( - self, - audio_data: Union[bytes, np.ndarray], - file_path: Path, - sample_rate: int, - num_channels: int = 1, - ): - """ - Save audio data to a WAV file. - - Args: - audio_data: Audio data as bytes or numpy array - file_path: Path to save the WAV file - sample_rate: Audio sample rate in Hz - num_channels: Number of audio channels (default: 1) - """ - try: - # Convert audio data to bytes if it's a numpy array - if isinstance(audio_data, np.ndarray): - if audio_data.dtype in [np.float32, np.float64]: - # Convert float [-1, 1] to int16 [-32768, 32767] - audio_data = np.clip(audio_data, -1.0, 1.0) - audio_data = (audio_data * 32767).astype(np.int16) - elif audio_data.dtype != np.int16: - audio_data = audio_data.astype(np.int16) - audio_bytes = audio_data.tobytes() - else: - audio_bytes = audio_data - - # Write WAV file - with wave.open(str(file_path), 'wb') as wav_file: # type: ignore[union-attr] - wav_file.setnchannels(num_channels) - wav_file.setsampwidth(2) # 16-bit audio - wav_file.setframerate(sample_rate) - wav_file.writeframes(audio_bytes) - - logger.debug(f"[AudioLogger] Saved audio to {file_path}") - except Exception as e: - logger.error(f"[AudioLogger] Error saving audio to {file_path}: {e}") - raise - - def _save_metadata_json(self, metadata: dict, file_path: Path): - """Save metadata to a JSON file.""" - try: - with open(file_path, 'w', encoding='utf-8') as f: - json.dump(metadata, f, indent=2, ensure_ascii=False) - logger.debug(f"[AudioLogger] Saved metadata to {file_path}") - except Exception as e: - logger.error(f"[AudioLogger] Error saving metadata to {file_path}: {e}") - raise - - def clear_user_audio_buffer(self): - """ - Clear the user audio buffer if the user stopped speaking detected by VAD. - """ - # Clear turn buffers if logging wasn't completed (e.g., no final transcription) - if len(self.turn_audio_buffer) > 0 or len(self.turn_transcription_buffer) > 0: - logger.debug( - "[AudioLogger] Clearing turn audio and transcription buffers due to VAD user stopped speaking" - ) - self.turn_audio_buffer = [] - self.turn_transcription_buffer = [] - - def stage_user_audio( - self, - timestamp_now: datetime, - transcription: str, - sample_rate: int = 16000, - num_channels: int = 1, - is_first_frame: bool = False, - is_backchannel: bool = False, - additional_metadata: Optional[dict] = None, - ) -> Optional[dict]: - """ - Stage user audio metadata and transcription (from STT). - This data will be saved when the turn is complete by `save_user_audio` method. - Audio data is retrieved from continuous_user_audio_buffer based on timestamps. - - Args: - timestamp_now: Timestamp when the audio was received - transcription: Transcribed text - sample_rate: Audio sample rate in Hz (default: 16000) - num_channels: Number of audio channels (default: 1) - is_first_frame: Whether this is the first frame of a turn (default: False) - is_backchannel: Whether this is a backchannel utterance (default: False) - additional_metadata: Additional metadata to include - - Returns: - Dictionary with logged file paths, or None if logging is disabled - """ - if not self.enabled: - return None - - try: - # Get counter and generate filenames - counter = self._get_next_counter("user") - # timestamp_now = datetime.now() - base_name = f"{counter:05d}_{timestamp_now.strftime('%H%M%S')}" - - audio_file = self.user_dir / f"{base_name}.wav" - metadata_file = self.user_dir / f"{base_name}.json" - - if is_first_frame or self.staged_metadata is None or "start_time" not in self.staged_metadata: - raw_start_time = self.get_time_from_start_of_session(timestamp=timestamp_now) - # Apply pre-roll: go back pre_roll_time_sec, but don't go before the last entry's end time - pre_roll_start = raw_start_time - self._pre_roll_time_sec - if self.session_metadata["user_entries"]: - last_entry_end_time = self.session_metadata["user_entries"][-1]["end_time"] - _start_time = max(pre_roll_start, last_entry_end_time) - else: - # No previous entries, just ensure we don't go negative - _start_time = max(pre_roll_start, 0.0) - else: - # start_time is stored as float (seconds from session start), not ISO string - _start_time = self.staged_metadata["start_time"] - - # Make end time into float (seconds from session start) - _end_time = self.get_time_from_start_of_session(timestamp=datetime.now()) - audio_duration_sec = round(_end_time - _start_time, self._round_precision) - - # Prepare metadata (initialize if None to allow update) - if self.staged_metadata is None: - self.staged_metadata = {} - self.staged_metadata.update( - { - "base_name": base_name, - "counter": counter, - "turn_index": self._turn_index, - "speaker": "user", - "timestamp": timestamp_now.isoformat(), - "start_time": _start_time, - "end_time": _end_time, - "transcription": transcription, - "audio_file": audio_file.name, - "sample_rate": sample_rate, - "num_channels": num_channels, - "audio_duration_sec": audio_duration_sec, - "is_backchannel": is_backchannel, - } - ) - - if additional_metadata: - self.staged_metadata.update(additional_metadata) - - return { - "audio_file": str(audio_file), - "metadata_file": str(metadata_file), - "counter": counter, - } - - except Exception as e: - logger.error(f"Error logging user audio: {e}") - return None - - def stage_turn_audio_and_transcription( - self, - timestamp_now: datetime, - is_first_frame: bool = False, - additional_metadata: Optional[dict] = None, - ): - """ - Stage the complete turn audio and accumulated transcriptions. - - This method is called when a final transcription is received. - It joins all accumulated audio and transcription chunks and stages them together. - - Args: - timestamp_now: Timestamp when the audio was received - is_first_frame: Whether this is the first frame of a turn (default: False) - additional_metadata: Additional metadata to include (e.g., model, backend info) - """ - if not self.turn_audio_buffer or not self.turn_transcription_buffer: - logger.debug("[AudioLogger] No audio or transcription to stage") - return - - try: - complete_transcription = "".join(self.turn_transcription_buffer) - - logger.debug( - f"[AudioLogger] Staging a turn with: {len(self.turn_audio_buffer)} audio chunks, " - f"{len(self.turn_transcription_buffer)} transcription chunks" - ) - - metadata = { - "num_transcription_chunks": len(self.turn_transcription_buffer), - "num_audio_chunks": len(self.turn_audio_buffer), - } - if additional_metadata: - metadata.update(additional_metadata) - - self.stage_user_audio( - timestamp_now=timestamp_now, - transcription=complete_transcription, - sample_rate=self._stereo_sample_rate, - num_channels=1, - is_first_frame=is_first_frame, - additional_metadata=metadata, - ) - - logger.info( - f"[AudioLogger] Staged the audio and transcription for turn: '{complete_transcription[:50]}...'" - ) - - except Exception as e: - logger.warning(f"[AudioLogger] Failed to stage user audio: {e}") - - def save_user_audio(self, is_backchannel: bool = False, float_divisor: float = 32768.0): - """Save the user audio to the disk. - - Args: - is_backchannel: Whether this audio is a backchannel utterance (default: False) - """ - # Safety check: ensure staged metadata exists and has required fields - if self.staged_metadata is None or "base_name" not in self.staged_metadata: - # This is expected - multiple TranscriptionFrames may be pushed but only one has audio staged - logger.debug("[AudioLogger] No staged metadata to save (this is normal for multiple frame pushes)") - return - - try: - # Add backchannel metadata (only set if not already True to preserve turn-taking detection) - if is_backchannel or not self.staged_metadata.get("is_backchannel", False): - self.staged_metadata["is_backchannel"] = is_backchannel - - audio_file = self.user_dir / f"{self.staged_metadata['base_name']}.wav" - metadata_file = self.user_dir / f"{self.staged_metadata['base_name']}.json" - - # Get the audio data from continuous user audio buffer - stt, end = self.staged_metadata["start_time"], self.staged_metadata["end_time"] - continuous_audio_bytes = b"".join(self.continuous_user_audio_buffer) - full_audio_array = np.frombuffer(continuous_audio_bytes, dtype=np.int16).astype(np.float32) / float_divisor - start_idx = int(stt * self._stereo_sample_rate) - end_idx = int(end * self._stereo_sample_rate) - staged_audio_data = full_audio_array[start_idx:end_idx] - - self._save_audio_wav( - audio_data=staged_audio_data, - file_path=audio_file, - sample_rate=self.staged_metadata["sample_rate"], - ) - - self._save_metadata_json(metadata=self.staged_metadata, file_path=metadata_file) - backchannel_label = " [BACKCHANNEL]" if is_backchannel else "" - transcription_preview = self.staged_metadata['transcription'][:50] - ellipsis = '...' if len(self.staged_metadata['transcription']) > 50 else '' - logger.info( - f"[AudioLogger] Saved user audio #{self.staged_metadata['counter']}" - f"{backchannel_label}: '{transcription_preview}{ellipsis}'" - ) - - # Note: User audio for stereo conversation is handled via continuous_user_audio_buffer - # which is populated in append_continuous_user_audio() (not affected by VAD) - - # Update session metadata - with self._lock: - self.session_metadata["user_entries"].append(self.staged_metadata) - self._save_session_metadata() - - self.clear_user_audio_buffer() - - # Clear staged data after successful save - self.staged_metadata = None - self._staged_audio_data = None - except Exception as e: - logger.error(f"[AudioLogger] Error saving user audio: {e}") - raise - - def log_agent_audio( - self, - audio_data: Union[bytes, np.ndarray], - text: str, - sample_rate: int = 22050, - num_channels: int = 1, - additional_metadata: Optional[dict] = None, - tts_generation_time: Optional[float] = None, - ) -> Optional[dict]: - """ - Log agent audio and text (from TTS). - - Args: - audio_data: Generated audio data as bytes or numpy array - text: Input text that was synthesized - sample_rate: Audio sample rate in Hz (default: 22050) - num_channels: Number of audio channels (default: 1) - additional_metadata: Additional metadata to include - tts_generation_time: Time when TTS generation started (seconds from session start). - Used to calculate actual start_time for first segment of a turn. - - Returns: - Dictionary with logged file paths, or None if logging is disabled - """ - if not self.enabled: - return None - - try: - # Get counter and generate filenames - counter = self._get_next_counter("agent") - timestamp_now = datetime.now() - base_name = f"{counter:05d}_{timestamp_now.strftime('%H%M%S')}" - - audio_file = self.agent_dir / f"{base_name}.wav" - metadata_file = self.agent_dir / f"{base_name}.json" - - # Save audio - self._save_audio_wav(audio_data, audio_file, sample_rate, num_channels) - - # Calculate audio duration - audio_duration_sec = ( - len(audio_data) / (sample_rate * num_channels * 2) - if isinstance(audio_data, bytes) - else len(audio_data) / sample_rate - ) - - # Determine start_time based on previous segment in the same turn - # If this is the first segment of the turn, use tts_generation_time - # Otherwise, use the previous segment's end_time for sequential playback - start_time = None - with self._lock: - agent_entries = self.session_metadata["agent_entries"] - # agent_entries is a list of turns, each turn is a list of segments - if agent_entries and agent_entries[-1]: # If there's a current turn with segments - last_segment = agent_entries[-1][-1] # Last segment of last turn - if last_segment["turn_index"] == self._turn_index: - # Same turn - start after previous segment ends - start_time = last_segment["end_time"] - - if start_time is None: - # First segment of the turn - use agent_turn_start_time (from BotStartedSpeakingFrame) - # This is more accurate than tts_generation_time as it reflects actual playback start - if self._agent_turn_start_time is not None: - start_time = self._agent_turn_start_time - elif tts_generation_time is not None: - # Fallback to tts_generation_time if agent_turn_start_time not set - start_time = tts_generation_time - else: - start_time = self.get_time_from_start_of_session(timestamp=timestamp_now) - - end_time = start_time + audio_duration_sec - - # Prepare metadata - # cutoff_time is None by default (no interruption) - # It will be set by set_agent_cutoff_time() if TTS is interrupted - metadata = { - "base_name": base_name, - "counter": counter, - "turn_index": self._turn_index, - "speaker": "agent", - "timestamp": timestamp_now.isoformat(), - "start_time": round(start_time, self._round_precision), - "end_time": round(end_time, self._round_precision), - "cutoff_time": None, # None means not interrupted; float if interrupted - "text": text, - "audio_file": audio_file.name, - "sample_rate": sample_rate, - "num_channels": num_channels, - "audio_duration_sec": round(audio_duration_sec, self._round_precision), - } - - if additional_metadata: - metadata.update(additional_metadata) - - # Save metadata - self._save_metadata_json(metadata, metadata_file) - - # Append to stereo conversation (left channel = agent) - self._append_to_stereo_conversation( - audio_data=audio_data, - channel="left", - start_time=start_time, - sample_rate=sample_rate, - ) - - # Update session metadata - # agent_entries is a list of turns, each turn is a list of segments - with self._lock: - agent_entries = self.session_metadata["agent_entries"] - # Check if we need to start a new turn or append to existing turn - if not agent_entries or agent_entries[-1][-1]["turn_index"] != self._turn_index: - # Start a new turn (new sublist) - agent_entries.append([metadata]) - else: - # Append to current turn - agent_entries[-1].append(metadata) - self._save_session_metadata() - - logger.info(f"[AudioLogger] Logged agent audio #{counter}: '{text[:50]}{'...' if len(text) > 50 else ''}'") - - return { - "audio_file": str(audio_file), - "metadata_file": str(metadata_file), - "counter": counter, - } - - except Exception as e: - logger.error(f"[AudioLogger] Error logging agent audio: {e}") - return None - - def set_agent_cutoff_time(self, cutoff_time: Optional[float] = None): - """ - Set the cutoff time for the most recent agent audio entry. - - This method should be called when TTS is interrupted by user speech. - The cutoff_time represents when the agent audio was actually cut off, - which may be earlier than the natural end_time. - - Args: - cutoff_time: The cutoff time in seconds from session start. - If None, uses current time from session start. - """ - if not self.enabled: - return - - if cutoff_time is None: - cutoff_time = self.get_time_from_start_of_session() - - with self._lock: - agent_entries = self.session_metadata["agent_entries"] - if not agent_entries or not agent_entries[-1]: - logger.warning("[AudioLogger] No agent entries to set cutoff time") - return - - # Get the current turn (last sublist) and update ALL segments in it - current_turn = agent_entries[-1] - turn_index = current_turn[0]["turn_index"] - - # Update cutoff_time for ALL segments in the current turn - for segment in current_turn: - segment["cutoff_time"] = cutoff_time - # Also update individual JSON files - try: - metadata_file = self.agent_dir / f"{segment['base_name']}.json" - self._save_metadata_json(segment, metadata_file) - except Exception as e: - logger.error(f"[AudioLogger] Error updating agent cutoff time for segment: {e}") - - # Truncate the stereo buffer (left channel = agent) at the cutoff point - cutoff_sample = int(cutoff_time * self._stereo_sample_rate) - if cutoff_sample < len(self._stereo_audio_buffer_left): - # Zero out agent audio after cutoff point - for i in range(cutoff_sample, len(self._stereo_audio_buffer_left)): - self._stereo_audio_buffer_left[i] = 0.0 - logger.debug( - f"[AudioLogger] Truncated agent stereo buffer at sample {cutoff_sample} " - f"(cutoff_time={cutoff_time:.3f}s)" - ) - - logger.info( - f"[AudioLogger] Set cutoff_time={cutoff_time:.3f}s for turn {turn_index} " - f"({len(current_turn)} segments)" - ) - - # Save updated session metadata - self._save_session_metadata() - - def _save_session_metadata(self): - """Save the session metadata to disk.""" - if not self.enabled: - return - - try: - metadata_file = self.session_dir / "session_metadata.json" - self.session_metadata["last_updated"] = datetime.now().isoformat() - self._save_metadata_json(self.session_metadata, metadata_file) - except Exception as e: - logger.error(f"[AudioLogger] Error saving session metadata: {e}") - - def finalize_session(self): - """Finalize the session and save final metadata.""" - if not self.enabled: - return - - # Save stereo conversation before finalizing - self.save_stereo_conversation() - - self.session_metadata["end_time"] = datetime.now().isoformat() - self.session_metadata["total_user_entries"] = self._user_counter - self.session_metadata["total_agent_segments"] = self._agent_counter - self.session_metadata["total_agent_turns"] = len(self.session_metadata["agent_entries"]) - self._save_session_metadata() - logger.info( - f"[AudioLogger] Session finalized: {self.session_id} " - f"(User: {self._user_counter}, Agent: {self._agent_counter} segments in " - f"{len(self.session_metadata['agent_entries'])} turns)" - ) - - -class RTVIAudioLoggerObserver(BaseObserver): - """Observer that triggers audio logging when TranscriptionFrame is pushed.""" - - def __init__(self, audio_logger: AudioLogger): - super().__init__() - self._audio_logger = audio_logger - - async def on_push_frame(self, data: FramePushed): - """Handle frame push events and save user audio on TranscriptionFrame.""" - frame = data.frame - if isinstance(frame, TranscriptionFrame) and self._audio_logger: - self._audio_logger.save_user_audio() - # Call parent class's on_push_frame method - await super().on_push_frame(data) diff --git a/nemo/agents/voice_agent/pipecat/services/nemo/diar.py b/nemo/agents/voice_agent/pipecat/services/nemo/diar.py deleted file mode 100644 index 0cc856b59c36c033a0d6dd94d75aafb21d0c3531..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/pipecat/services/nemo/diar.py +++ /dev/null @@ -1,360 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import asyncio -from typing import AsyncGenerator, Optional - -import numpy as np -from loguru import logger -from pipecat.frames.frames import ( - CancelFrame, - EndFrame, - ErrorFrame, - Frame, - StartFrame, - VADUserStartedSpeakingFrame, - VADUserStoppedSpeakingFrame, -) -from pipecat.processors.frame_processor import FrameDirection -from pipecat.services.stt_service import STTService -from pipecat.transcriptions.language import Language -from pipecat.utils.time import time_now_iso8601 -from pipecat.utils.tracing.service_decorators import traced_stt -from pydantic import BaseModel - -from nemo.agents.voice_agent.pipecat.frames.frames import DiarResultFrame -from nemo.agents.voice_agent.pipecat.services.nemo.streaming_diar import DiarizationConfig, NeMoStreamingDiarService - - -class NeMoDiarInputParams(BaseModel): - threshold: Optional[float] = ( - 0.4 # threshold value used to determine if a speaker exists or not, setting it to a lower value will increase the sensitivity of the diarization model - ) - language: Optional[Language] = Language.EN_US - frame_len_in_secs: Optional[float] = 0.08 # 80ms for FastConformer model - config_path: Optional[str] = None # path to the Niva ASR config file - raw_audio_frame_len_in_secs: Optional[float] = 0.016 # 16ms for websocket transport - buffer_size: Optional[int] = ( - 30 # number of audio frames to buffer, 1 frame is 16ms, streaming Sortformer was trained with 6*0.08=0.48s chunks - ) - - -class NemoDiarService(STTService): - def __init__( - self, - *, - model: Optional[str] = "", - device: Optional[str] = "cuda:0", - sample_rate: Optional[int] = 16000, - params: Optional[NeMoDiarInputParams] = None, - use_vad: bool = True, - audio_passthrough: bool = True, - backend: Optional[str] = "legacy", - enabled: bool = True, - **kwargs, - ): - super().__init__(audio_passthrough=audio_passthrough, **kwargs) - - self._enabled = enabled - self._queue = asyncio.Queue() - self._response_queue = asyncio.Queue() # Add response queue - self._processing_task = None # Add processing task - self._response_task = None # Add response task - self._device = device - self._sample_rate = sample_rate - self._audio_passthrough = audio_passthrough - params.buffer_size = params.frame_len_in_secs // params.raw_audio_frame_len_in_secs - self._params = params - self._model_name = model - self._use_vad = use_vad - self._backend = backend - if not params: - raise ValueError("params is required") - - self._load_model() - - self._vad_user_speaking = False - self._audio_buffer = [] - self._current_speaker_id = None - self._processing_running = False - - if not self._use_vad: - self._vad_user_speaking = True - - def _load_model(self): - if not self._enabled or not self._model_name: - self._model = None - self._enabled = False - return - - if self._backend == "legacy": - cfg = DiarizationConfig() - cfg.device = self._device - self._model = NeMoStreamingDiarService( - cfg, self._model_name, frame_len_in_secs=self._params.frame_len_in_secs, sample_rate=self.sample_rate - ) - else: - raise ValueError(f"Invalid backend: {self._backend}") - logger.info(f"Diarization service initialized on device: {self._device}") - - def can_generate_metrics(self) -> bool: - """Indicates whether this service can generate metrics. - - Returns: - bool: True, as this service supports metric generation. - """ - return True - - async def start(self, frame: StartFrame): - """Handle service start.""" - await super().start(frame) - - # Initialize the model if not already done - if not hasattr(self, "_model"): - self._load_model() - - # Start background processing task - if not self._processing_task: - self._processing_task = self.create_task(self._processing_task_handler()) - - # Start response handling task - if not self._response_task: - self._response_task = self.create_task(self._response_task_handler()) - - async def stop(self, frame: EndFrame): - """Handle service stop.""" - await super().stop(frame) - await self._stop_tasks() - - async def cancel(self, frame: CancelFrame): - """Handle service cancellation.""" - await super().cancel(frame) - await self._stop_tasks() - - async def _stop_tasks(self): - """Stop background processing tasks.""" - await self._queue.put(None) # Signal to stop processing - if self._processing_task: - await self.cancel_task(self._processing_task) - self._processing_task = None - - if self._response_task: - await self.cancel_task(self._response_task) - self._response_task = None - - def _diarization_processor(self): - """Background processor that handles diarization calls.""" - try: - while self._processing_running: - try: - # Get audio from queue - blocking call that will be interrupted by cancellation - future = asyncio.run_coroutine_threadsafe(self._queue.get(), self.get_event_loop()) - audio = future.result() - - if audio is None: # Stop signal - logger.debug("Received stop signal in background processor") - break - - # Process diarization - diar_result = self._model.diarize(audio) - - # Send result back to async loop - asyncio.run_coroutine_threadsafe(self._response_queue.put(diar_result), self.get_event_loop()) - - except Exception as e: - logger.error(f"Error in background diarization processor: {e}") - # Send error back to async loop - asyncio.run_coroutine_threadsafe(self._response_queue.put(('error', e)), self.get_event_loop()) - - except Exception as e: - logger.error(f"Background diarization processor fatal error: {e}") - finally: - logger.debug("Background diarization processor stopped") - - async def _processing_task_handler(self): - """Handler for background processing task.""" - try: - self._processing_running = True - logger.debug("Starting background processing task") - await asyncio.to_thread(self._diarization_processor) - except asyncio.CancelledError: - logger.debug("Background processing task cancelled") - self._processing_running = False - raise - finally: - self._processing_running = False - - async def _handle_diarization_result(self, diar_result): - """Handle diarization result from background processing.""" - try: - if diar_result is None: - return - dominant_speaker_id = self._get_dominant_speaker_id(diar_result) - # logger.debug(f"Dominant speaker ID: {dominant_speaker_id}") - if dominant_speaker_id is not None and dominant_speaker_id != self._current_speaker_id: - self._current_speaker_id = dominant_speaker_id - logger.debug(f"Pushing DiarResultFrame with speaker {dominant_speaker_id}") - await self.push_frame(DiarResultFrame(dominant_speaker_id, stream_id="default")) - except Exception as e: - logger.error(f"Error handling diarization result: {e}") - await self.push_frame( - ErrorFrame( - str(e), - time_now_iso8601(), - ) - ) - - async def _response_task_handler(self): - """Handler for processing diarization results.""" - logger.debug("Response task handler started") - try: - while True: - try: - result = await self._response_queue.get() - - if isinstance(result, tuple) and result[0] == 'error': - # Handle error from background processing - error = result[1] - logger.error(f"Error in NeMo Diarization processing: {error}") - await self.push_frame( - ErrorFrame( - str(error), - time_now_iso8601(), - ) - ) - else: - # Handle successful diarization result - await self._handle_diarization_result(result) - - except Exception as e: - logger.error(f"Error in response task handler: {e}") - except asyncio.CancelledError: - logger.debug("Response task handler cancelled") - raise - - async def run_stt(self, audio: bytes) -> AsyncGenerator[Frame, None]: - """Process audio data and generate transcription frames. - - Args: - audio: Raw audio bytes to transcribe - - Yields: - Frame: Transcription frames containing the results - """ - if self._vad_user_speaking and self._enabled: - self._audio_buffer.append(audio) - if len(self._audio_buffer) >= self._params.buffer_size: - await self.start_ttfb_metrics() - await self.start_processing_metrics() - audio = b"".join(self._audio_buffer) - self._audio_buffer = [] - # Queue audio for background processing - await self._queue.put(audio) - yield None - - @traced_stt - async def _handle_transcription(self, transcript: str, is_final: bool, language: Optional[str] = None): - """Handle a transcription result. - - Args: - transcript: The transcribed text - is_final: Whether this is a final transcription - language: The language of the transcription - """ - pass # Base implementation - can be extended for specific handling needs - - async def set_language(self, language: Language): - """Update the service's recognition language. - - Args: - language: New language for recognition - """ - if self._params: - self._params.language = language - else: - self._params = NeMoDiarInputParams(language=language) - - logger.info(f"Switching STT language to: {language}") - - async def set_model(self, model: str): - """Update the service's model. - - Args: - model: New model name/path to use - """ - await super().set_model(model) - self._model_name = model - self._load_model() - - async def process_frame(self, frame: Frame, direction: FrameDirection): - """Process audio data and generate transcription frames. - - Args: - audio: Raw audio bytes to transcribe - - Yields: - Frame: Transcription frames containing the results - """ - if not self._enabled: - # if diarization is disabled, just pass the frame through - await self.push_frame(frame, direction) - return - - await super().process_frame(frame, direction) - if isinstance(frame, VADUserStartedSpeakingFrame): - self._vad_user_speaking = True - self._audio_buffer = [] - logger.debug("VADUserStartedSpeakingFrame received") - elif isinstance(frame, VADUserStoppedSpeakingFrame): - self._vad_user_speaking = False - logger.debug("VADUserStoppedSpeakingFrame received") - self._current_speaker_id = None - self._audio_buffer = [] - - def reset(self): - """Reset the diarization service.""" - self._current_speaker_id = None - self._audio_buffer = [] - self._vad_user_speaking = False - self._model.reset_state() - - def _get_dominant_speaker_id(self, spk_pred: np.ndarray): - spk_pred = (spk_pred > self._params.threshold).astype(int) - dominant_speaker_id = None - if spk_pred.sum() > 0: - # get the dominant speaker id - # Filter to only keep frames that have any speaker probability > 0.0 - valid_frame_mask = spk_pred.sum(axis=1) > 0 - - # Filter diar_result to only keep valid frames - filtered_diar_result = spk_pred[valid_frame_mask] # ndarray of shape [num_valid_frames, num_speakers] - - # Get the primary speaker for each valid frame - primary_spk = np.argmax(filtered_diar_result, axis=1) # ndarray of shape [num_valid_frames] - # logger.debug(f"Primary speaker for valid frames: {primary_spk}") - - # count the number of different speakers in the primary speaker sequence - num_speakers = len(np.unique(primary_spk)) - # logger.debug(f"Number of different speakers: {num_speakers}") - - # If there are multiple speakers, get the dominant one - if num_speakers > 1: - # Count occurrences of each speaker - speaker_counts = np.bincount(primary_spk) - dominant_speaker_id = np.argmax(speaker_counts) - else: - # Only one speaker, return that speaker ID - dominant_speaker_id = primary_spk[0] - return dominant_speaker_id diff --git a/nemo/agents/voice_agent/pipecat/services/nemo/llm.py b/nemo/agents/voice_agent/pipecat/services/nemo/llm.py deleted file mode 100644 index 2e635a5078cae224c2f07558664447fe8beb0d6b..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/pipecat/services/nemo/llm.py +++ /dev/null @@ -1,760 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import asyncio -import os -import socket -import subprocess -import time -import uuid -from threading import Thread -from typing import AsyncGenerator, List, Mapping, Optional - -import psutil -import requests -from jinja2.exceptions import TemplateError -from loguru import logger -from omegaconf import DictConfig, OmegaConf -from openai import APITimeoutError, AsyncStream, BadRequestError -from openai.types.chat import ChatCompletionChunk, ChatCompletionMessageParam -from pipecat.adapters.services.open_ai_adapter import OpenAILLMInvocationParams -from pipecat.frames.frames import ( - CancelFrame, - EndFrame, - LLMFullResponseEndFrame, - LLMFullResponseStartFrame, - LLMTextFrame, -) -from pipecat.processors.aggregators.openai_llm_context import OpenAILLMContext -from pipecat.services.openai.llm import OpenAILLMService -from transformers import AsyncTextIteratorStreamer, AutoModelForCausalLM, AutoTokenizer -from vllm.config import ModelConfig as vllmModelConfig - -DEFAULT_GENERATION_KWARGS = { - "max_new_tokens": 256, - "temperature": 0.7, - "top_p": 0.9, - "do_sample": True, -} - - -class LLMUtilsMixin: - """Utils for local LLM services.""" - - def _maybe_add_user_message(self, messages: List[ChatCompletionMessageParam]) -> List[ChatCompletionMessageParam]: - """ - Some LLMs like "nvidia/Llama-3.1-Nemotron-Nano-8B-v1" requires a user turn after the system prompt, - this function is used to add a dummy user turn if the system prompt is followed by an assistant turn. - """ - if len(messages) > 1 and messages[0]["role"] == "system" and messages[1]["role"] == "assistant": - message = {"role": "user", "content": "Hi"} - messages.insert(1, message) - elif len(messages) == 1 and messages[0]["role"] == "system": - messages.append({"role": "user", "content": "Hi"}) - return messages - - def _maybe_merge_consecutive_user_turns( - self, messages: List[ChatCompletionMessageParam] - ) -> List[ChatCompletionMessageParam]: - """ - Merge consecutive user turns into a single turn, - since some LLMs like "nvidia/Llama-3.1-Nemotron-Nano-8B-v1" do not support consecutive user turns. - """ - if not messages: - return messages - - merged_messages = [] - - user_content = "" - for message in messages: - role = message["role"] - if role != "user": - # check if there's any preceeding user content, add them first - if user_content: - merged_messages.append({"role": "user", "content": user_content}) - user_content = "" - merged_messages.append(message) - else: - if user_content: - user_content += "; " + message["content"] - else: - user_content = message["content"] - - # add the last user content - if user_content: - merged_messages.append({"role": "user", "content": user_content}) - - return merged_messages - - -class HuggingFaceLLMLocalService(LLMUtilsMixin): - """ - HuggingFace LLM local service. - """ - - def __init__( - self, - model: str = "meta-llama/Meta-Llama-3-8B-Instruct", - device: str = "cuda:0", - dtype: str = "bfloat16", - thinking_budget: int = 0, - generation_kwargs: dict = None, - apply_chat_template_kwargs: dict = None, - ): - self.device = device - self.dtype = dtype - self.thinking_budget = thinking_budget - self.tokenizer = AutoTokenizer.from_pretrained(model) - self.model = AutoModelForCausalLM.from_pretrained( - model, device_map=device, dtype=dtype, trust_remote_code=True - ) # type: AutoModelForCausalLM - - self.generation_kwargs = generation_kwargs if generation_kwargs else DEFAULT_GENERATION_KWARGS - logger.debug(f"LLM generation kwargs: {self.generation_kwargs}") - - self.apply_chat_template_kwargs = apply_chat_template_kwargs if apply_chat_template_kwargs else {} - if "tokenize" in self.apply_chat_template_kwargs: - if self.apply_chat_template_kwargs["tokenize"] is not False: - logger.warning( - f"Found `tokenize=True` in apply_chat_template_kwargs={self.apply_chat_template_kwargs}," - "it will be ignored and forced to `False`" - ) - self.apply_chat_template_kwargs.pop("tokenize") - - logger.debug(f"LLM apply_chat_template kwargs: {self.apply_chat_template_kwargs}") - - def _apply_chat_template(self, messages: List[ChatCompletionMessageParam]) -> str: - """ - Apply the chat template to the messages. - """ - return self.tokenizer.apply_chat_template(messages, tokenize=False, **self.apply_chat_template_kwargs) - - def _get_prompt_from_messages(self, messages: List[ChatCompletionMessageParam]) -> str: - """ - Get the formatted prompt from the conversation history messages. - This function also tries to fix the messages if the LLM cannot handle consecutive turns of the same role, - or requires a user turn after the system prompt. - """ - try: - prompt = self._apply_chat_template(messages) - return prompt - except TemplateError as e: - logger.warning(f"Got TemplateError: {e}.") - - logger.debug(f"Input LLM messages: {messages}") - if len(messages) > 1 and messages[0]["role"] == "system" and messages[1]["role"] == "assistant": - logger.warning("Trying to fix by adding dummy user message after system prompt...") - try: - messages = self._maybe_add_user_message(messages) - logger.debug(f"LLM messages after adding dummy user message: {messages}") - prompt = self._apply_chat_template(messages) - return prompt - except TemplateError as e: - logger.warning(f"Got TemplateError: {e}. Trying to fix by merging consecutive turns if possible.") - - try: - new_messages = self._maybe_merge_consecutive_user_turns(messages) - logger.debug(f"LLM messages after merging consecutive user turns: {new_messages}") - prompt = self._apply_chat_template(new_messages) - # Update the messages in place if successful - messages.clear() - messages.extend(new_messages) - return prompt - except Exception as e: - logger.warning(f"Got Exception: {e}, messages: {messages}") - raise e - - async def generate_stream( - self, messages: List[ChatCompletionMessageParam], **kwargs - ) -> AsyncGenerator[ChatCompletionChunk, None]: - """ - Generate a stream of chat completion chunks from the messages. - """ - # Convert messages to prompt format - prompt = self._get_prompt_from_messages(messages) - - logger.debug(f"LLM prompt: {prompt}") - - inputs = self.tokenizer(prompt, add_special_tokens=False, return_tensors="pt").to(self.device) - - # Generate with streaming - streamer = AsyncTextIteratorStreamer(self.tokenizer, skip_prompt=True, skip_special_tokens=True) - generation_kwargs = { - **inputs, - "streamer": streamer, - **self.generation_kwargs, - } - - # Start generation in background - thread = Thread( - target=self.model.generate, - kwargs=generation_kwargs, - ) - thread.start() - - # Stream the output - async for text in streamer: - # logger.debug(f"Streamer yielded text: {text}") - chunk = ChatCompletionChunk( - id="hf-" + str(uuid.uuid4()), - choices=[{"delta": {"content": text}, "finish_reason": None, "index": 0}], - created=int(time.time()), - model=self.model.config._name_or_path, - object="chat.completion.chunk", - ) - yield chunk - - -class HuggingFaceLLMService(OpenAILLMService): - """ - LLM service that hosts a HuggingFace model. - """ - - def __init__( - self, - *, - model: str = "google/gemma-7b-it", - device: str = "cuda", - dtype: str = "bfloat16", - thinking_budget: int = 0, - generation_kwargs: dict = None, - apply_chat_template_kwargs: dict = None, - **kwargs, - ): - self._model_name = model - self._device = device - self._dtype = dtype - self._thinking_budget = thinking_budget - self._generation_kwargs = generation_kwargs if generation_kwargs is not None else DEFAULT_GENERATION_KWARGS - self._apply_chat_template_kwargs = apply_chat_template_kwargs if apply_chat_template_kwargs is not None else {} - super().__init__(model=model, **kwargs) - - def create_client(self, api_key=None, base_url=None, **kwargs): - """ - Create a HuggingFaceLLMLocalService client. - """ - return HuggingFaceLLMLocalService( - model=self._model_name, - device=self._device, - dtype=self._dtype, - thinking_budget=self._thinking_budget, - generation_kwargs=self._generation_kwargs, - apply_chat_template_kwargs=self._apply_chat_template_kwargs, - ) - - async def _process_context(self, context: OpenAILLMContext): - """Process a context through the LLM and push text frames. - - Args: - context (OpenAILLMContext): The context to process, containing messages - and other information needed for the LLM interaction. - """ - await self.push_frame(LLMFullResponseStartFrame()) - cumulative_text = "" - try: - await self.start_ttfb_metrics() - messages = context.get_messages() - async for chunk in self._client.generate_stream(messages): - if chunk.choices[0].delta.content: - await self.stop_ttfb_metrics() - text = chunk.choices[0].delta.content - cumulative_text += text - frame = LLMTextFrame(text) - await self.push_frame(frame) - except Exception as e: - logger.error(f"Error in _process_context: {e}", exc_info=True) - raise - finally: - cumulative_text = " ".join(cumulative_text.split()).strip() - if not cumulative_text: - logger.warning(f"LLM response is empty for context: {context}") - await self.push_frame(LLMFullResponseEndFrame()) - - async def get_chat_completions( - self, params_from_context: OpenAILLMInvocationParams - ) -> AsyncGenerator[ChatCompletionChunk, None]: - """Create a streaming chat completion using HuggingFace model. - - Args: - context (OpenAILLMContext): The context object containing tools configuration - and other settings for the chat completion. - messages (List[ChatCompletionMessageParam]): The list of messages comprising - the conversation history and current request. - - Returns: - AsyncGenerator[ChatCompletionChunk]: A streaming response of chat completion - chunks that can be processed asynchronously. - """ - messages = params_from_context["messages"] - - return self._client.generate_stream(messages) - - -class VLLMService(OpenAILLMService, LLMUtilsMixin): - """ - LLM service that hosts a vLLM server. - """ - - def __init__( - self, - *, - model: str, - device: str = "cuda", - api_key="None", - base_url="http://localhost:8000/v1", - organization="None", - project="None", - default_headers: Optional[Mapping[str, str]] = None, - params: Optional[OpenAILLMService.InputParams] = None, - thinking_budget: int = 0, - start_vllm_on_init: bool = False, - vllm_server_params: Optional[str] = None, - vllm_server_max_wait_time: int = 3600, # 1 hour max wait time - vllm_server_check_interval: int = 5, # check server every 5 seconds - **kwargs, - ): - self._device = device - self._vllm_server_max_wait_time = vllm_server_max_wait_time - self._vllm_server_check_interval = vllm_server_check_interval - if start_vllm_on_init: - base_url = self._start_vllm_server(model, vllm_server_params, base_url) - - super().__init__( - model=model, - api_key=api_key, - base_url=base_url, - organization=organization, - project=project, - default_headers=default_headers, - params=params, - **kwargs, - ) - self._thinking_budget = thinking_budget - self._vllm_server_params = vllm_server_params - self._start_vllm_on_init = start_vllm_on_init - - # TODO: handle thinking budget - logger.info( - f"VLLMService initialized with model: {model}, api_key: {api_key}, base_url: {base_url}," - f"params: {params}, thinking_budget: {thinking_budget}" - ) - - def _start_vllm_server( - self, model: str, vllm_server_params: Optional[str] = None, base_url: Optional[str] = None - ) -> str: - """ - Start a vllm server and return the base url. - """ - - requested_port = None - # If base_url is provided, extract port from it - if base_url: - try: - # Extract port from base_url like "http://localhost:8003/v1" - from urllib.parse import urlparse - - parsed_url = urlparse(base_url) - if parsed_url.port: - requested_port = parsed_url.port - except Exception as e: - logger.warning( - f"Could not parse port from base_url {base_url}: {e}, using port from vllm_server_params" - ) - - # Parse port from vllm_server_params, default to 8000 - if vllm_server_params: - params_list = vllm_server_params.split() - for i, param in enumerate(params_list): - if param == "--port" and i + 1 < len(params_list): - try: - param_port = int(params_list[i + 1]) - if requested_port is None: - requested_port = param_port - else: - if param_port != requested_port: - logger.warning( - f"Port {param_port} from vllm_server_params is different from base_url port" - f"{requested_port}, using new port {param_port}" - ) - requested_port = param_port - break - except ValueError: - logger.warning(f"Invalid port number: {params_list[i + 1]}, using default 8000") - - if requested_port is None: - # try to use default port - requested_port = 8000 - - def find_available_port(start_port: int) -> int: - """Find an available port starting from start_port""" - for port in range(start_port, start_port + 100): # Try up to 100 ports - try: - with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: - s.bind(('localhost', port)) - return port - except OSError: - continue - raise RuntimeError(f"Could not find an available port starting from {start_port}") - - def get_pid_on_port(port: int) -> Optional[int]: - for conn in psutil.net_connections(kind="inet"): - if conn.laddr.port == port and conn.status == psutil.CONN_LISTEN: - return conn.pid - return None - - def check_server_model(port: int, verbose: bool = False) -> tuple[bool, str]: - """Check if server is running on port and return (is_running, model_name)""" - try: - response = requests.get(f"http://localhost:{port}/v1/models", timeout=5) - if response.status_code == 200: - # get the PID for the server process - pid = get_pid_on_port(port) - if pid is not None and verbose: - logger.warning( - f"Found vLLM server process (PID: {pid}) on port {port}, you can use `lsof -i :{port}`" - "to find the process and kill it if you want to start a new server." - ) - models_data = response.json() - if "data" in models_data and models_data["data"]: - served_model = models_data["data"][0].get("id", "") - return True, served_model - return True, "" - return False, "" - except (requests.exceptions.RequestException, requests.exceptions.Timeout): - return False, "" - - # First, check if vLLM server is already running on the requested port - is_running, served_model = check_server_model(requested_port, verbose=True) - if is_running: - if served_model == model: - final_base_url = f"http://localhost:{requested_port}/v1" - logger.info(f"vLLM server is already running at {final_base_url} with the correct model: {model}") - return final_base_url - else: - logger.warning( - f"vLLM server on port {requested_port} is serving model '{served_model}' but we need '{model}'." - "Finding new port..." - ) - - # Find an available port for our model - port = find_available_port(requested_port) - if port != requested_port: - logger.info(f"Using port {port} instead of requested port {requested_port}") - - final_base_url = f"http://localhost:{port}/v1" - - # Check if there's already a vLLM process running on the same port and model - for proc in psutil.process_iter(['pid', 'name', 'cmdline']): - try: - if proc.info['cmdline'] and any('vllm' in arg and 'serve' in arg for arg in proc.info['cmdline']): - # Check if this process is using the same port and model - cmdline_str = ' '.join(proc.info['cmdline']) - if f"--port {port}" in cmdline_str: - # Extract the model from the command line - cmdline_parts = proc.info['cmdline'] - model_index = -1 - for i, arg in enumerate(cmdline_parts): - if arg == "serve" and i + 1 < len(cmdline_parts): - model_index = i + 1 - break - - if model_index != -1 and model_index < len(cmdline_parts): - running_model = cmdline_parts[model_index] - if running_model == model: - logger.info( - f"Found existing vLLM server process (PID: {proc.info['pid']}) on port {port}" - f"serving model {model}" - ) - # Wait a bit and check if it's responding - time.sleep(2) - is_running, served_model = check_server_model(port) - if is_running and served_model == model: - logger.info( - f"Existing vLLM server is responding at {final_base_url} with correct model" - ) - return final_base_url - else: - logger.warning( - f"Existing vLLM process found on port {port} but not responding correctly," - "will start new server" - ) - else: - logger.info( - f"Found vLLM process on port {port} but serving different model '{running_model}'" - f"(need '{model}'). Will start new server." - ) - except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): - continue - - # Build the command with the determined port - cmd_parts = ["vllm", "serve", model] - - # Parse and modify vllm_server_params to use the correct port - if vllm_server_params: - # parse the vllm_server_params and add the port to the command - params_list = vllm_server_params.split() - modified_params = [] - i = 0 - while i < len(params_list): - if params_list[i] == "--port" and i + 1 < len(params_list): - # Replace the port with our determined port - modified_params.extend(["--port", str(port)]) - i += 2 # Skip the original port value - else: - modified_params.append(params_list[i]) - i += 1 - cmd_parts.extend(modified_params) - else: - # Add port if vllm_server_params is not provided - cmd_parts.extend(["--port", str(port)]) - - logger.info(f"Starting vLLM server with command: {' '.join(cmd_parts)}") - logger.warning("It will take a while to download the model if it's not already downloaded.") - # Set up environment variables for device configuration - env = os.environ.copy() - if self._device and self._device != "cpu": - # Extract CUDA device number if it's in format "cuda:0", "cuda:1", etc. - if self._device.startswith("cuda:"): - device_id = self._device.split(":")[1] - env["CUDA_VISIBLE_DEVICES"] = device_id - logger.info(f"Setting CUDA_VISIBLE_DEVICES={device_id}") - elif self._device == "cuda": - # Use default CUDA device (don't set CUDA_VISIBLE_DEVICES) - logger.info("Using default CUDA device") - else: - # For other device strings, try to extract device number - logger.warning(f"Unknown device format: {self._device}, using as-is") - env["CUDA_VISIBLE_DEVICES"] = self._device - elif self._device == "cpu": - env["CUDA_VISIBLE_DEVICES"] = "" - logger.info("Setting CUDA_VISIBLE_DEVICES='' to use CPU") - - try: - # Start the vLLM server process with environment variables - process = subprocess.Popen( - cmd_parts, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - text=True, - env=env, - preexec_fn=os.setsid if os.name != 'nt' else None, # Create new process group - ) - - # Store the process for potential cleanup later - self._vllm_process = process - - # Wait for server to start up - max_wait_time = self._vllm_server_max_wait_time - check_interval = self._vllm_server_check_interval - waited_time = 0 - - logger.info(f"Waiting for vLLM server to start on port {port}...") - while waited_time < max_wait_time: - is_running, served_model = check_server_model(port) - if is_running and served_model == model: - logger.info(f"vLLM server started successfully at {final_base_url} serving model: {model}") - return final_base_url - elif is_running and served_model != model: - logger.warning( - f"vLLM server started but serving wrong model '{served_model}' instead of '{model}'." - "Continuing to wait..." - ) - - # Check if process is still running - if process.poll() is not None: - # Process has terminated - stdout, stderr = process.communicate() - logger.error(f"vLLM server process terminated unexpectedly. stdout: {stdout}, stderr: {stderr}") - raise RuntimeError(f"Failed to start vLLM server: {stderr}") - - time.sleep(check_interval) - waited_time += check_interval - logger.debug(f"Still waiting for vLLM server on port {port}... ({waited_time}s)") - - # If we get here, server didn't start in time - logger.error(f"vLLM server failed to start within {max_wait_time} seconds on port {port}") - process.terminate() - raise RuntimeError(f"vLLM server failed to start within {max_wait_time} seconds on port {port}") - - except FileNotFoundError: - logger.error("vLLM not found. Please install vLLM: pip install vllm") - raise RuntimeError("vLLM not found. Please install vLLM: pip install vllm") - except Exception as e: - logger.error(f"Failed to start vLLM server: {e}") - self._stop_vllm_server() - raise e - - def _stop_vllm_server(self): - """Stop the vLLM server process if it's running.""" - if hasattr(self, '_vllm_process') and self._vllm_process: - logger.info(f"Stopping vLLM server process {self._vllm_process.pid}") - self._vllm_process.terminate() - - async def stop(self, frame: EndFrame): - """Stop the LLM service. - - Args: - frame: The end frame. - """ - await super().stop(frame) - self._stop_vllm_server() - - async def cancel(self, frame: CancelFrame): - """Cancel the LLM service. - - Args: - frame: The cancel frame. - """ - await super().cancel(frame) - self._stop_vllm_server() - - async def get_chat_completions( - self, params_from_context: OpenAILLMInvocationParams - ) -> AsyncStream[ChatCompletionChunk]: - """Get streaming chat completions from OpenAI API. - - Args: - context: The LLM context containing tools and configuration. - messages: List of chat completion messages to send. - - Returns: - Async stream of chat completion chunks. - """ - - params = self.build_chat_completion_params(params_from_context) - messages = params_from_context["messages"] - if self._retry_on_timeout: - try: - chunks = await asyncio.wait_for( - self._get_response_from_client(messages, params), timeout=self._retry_timeout_secs - ) - return chunks - except (APITimeoutError, asyncio.TimeoutError): - # Retry, this time without a timeout so we get a response - logger.debug(f"{self}: Retrying chat completion due to timeout") - chunks = await self._get_response_from_client(messages, params) - return chunks - else: - chunks = await self._get_response_from_client(messages, params) - return chunks - - async def _get_response_from_client( - self, messages: List[ChatCompletionMessageParam], params: dict - ) -> AsyncStream[ChatCompletionChunk]: - """Get a response from the client.""" - - try: - chunks = await self._client.chat.completions.create(**params) - except BadRequestError as e: - logger.error(f"Error in _get_response_from_client: {e}, trying to fix...") - logger.debug(f"LLM messages before fixing: {messages}") - messages = self._maybe_add_user_message(messages) - messages = self._maybe_merge_consecutive_user_turns(messages) - logger.debug(f"LLM messages after fixing: {messages}") - params["messages"] = messages - chunks = await self._client.chat.completions.create(**params) - - return chunks - - -def get_llm_service_from_config(config: DictConfig) -> OpenAILLMService: - """Get an LLM service from the configuration.""" - backend = config.type - - logger.info(f"Initializing LLM service from config: {config}") - - # If backend is "auto", try to detect the best backend - if backend == "auto": - model_name = config.get("model") - if not model_name: - raise ValueError("Model name is required for LLM") - - try: - _ = vllmModelConfig(model_name, trust_remote_code=True) - backend = "vllm" - logger.info(f"Auto-detected vLLM as the best backend for model {model_name}") - except Exception as e: - logger.info( - f"The LLM doesn't seem to be supported by vLLM yet (error: {e}), using HuggingFace as the backend" - f"for model: {model_name}. If you are sure that the LLM is supported by vLLM, you can set `type: vllm`" - "in the config file to force using vLLM." - ) - backend = "hf" - - assert backend in [ - "hf", - "vllm", - "auto", - ], f"Invalid backend: {backend}, only `hf`, `vllm`, and `auto` are supported." - - if backend == "hf": - llm_model = config.model - llm_device = config.device - llm_dtype = config.dtype - llm_generation_kwargs = config.get("generation_kwargs", {}) - if llm_generation_kwargs is not None: - llm_generation_kwargs = OmegaConf.to_container(llm_generation_kwargs, resolve=True) - llm_apply_chat_template_kwargs = config.get("apply_chat_template_kwargs", None) - if llm_apply_chat_template_kwargs is not None: - llm_apply_chat_template_kwargs = OmegaConf.to_container(llm_apply_chat_template_kwargs, resolve=True) - llm_thinking_budget = config.get("thinking_budget", 0) - return HuggingFaceLLMService( - model=llm_model, - device=llm_device, - dtype=llm_dtype, - generation_kwargs=llm_generation_kwargs, - apply_chat_template_kwargs=llm_apply_chat_template_kwargs, - thinking_budget=llm_thinking_budget, - ) - elif backend == "vllm": - llm_model = config.get("model", "vllm_server") - llm_api_key = config.get("api_key", "None") - llm_base_url = config.get("base_url", "http://localhost:8000/v1") - llm_organization = config.get("organization", "None") - llm_project = config.get("project", "None") - llm_default_headers = config.get("default_headers", None) - llm_params = config.get("vllm_generation_params", None) - llm_dtype = config.dtype - vllm_server_params = config.get("vllm_server_params", None) - if vllm_server_params is not None: - if "dtype" not in vllm_server_params: - vllm_server_params = f"--dtype {llm_dtype} {vllm_server_params}" - logger.info(f"Adding dtype {llm_dtype} to vllm_server_params: {vllm_server_params}") - if llm_params is not None: - # cast into OpenAILLMService.InputParams object - llm_params = OmegaConf.to_container(llm_params, resolve=True) - extra = llm_params.get("extra", None) - # ensure extra is a dictionary - if extra is None: - llm_params["extra"] = {} - elif not isinstance(extra, dict): - raise ValueError(f"extra must be a dictionary, got {type(extra)}") - llm_params = OpenAILLMService.InputParams(**llm_params) - else: - llm_params = OpenAILLMService.InputParams() - llm_thinking_budget = config.get("thinking_budget", 0) - return VLLMService( - model=llm_model, - api_key=llm_api_key, - base_url=llm_base_url, - organization=llm_organization, - project=llm_project, - default_headers=llm_default_headers, - params=llm_params, - thinking_budget=llm_thinking_budget, - start_vllm_on_init=config.get("start_vllm_on_init", False), - vllm_server_params=vllm_server_params, - ) - else: - raise ValueError(f"Invalid LLM backend: {backend}") diff --git a/nemo/agents/voice_agent/pipecat/services/nemo/streaming_asr.py b/nemo/agents/voice_agent/pipecat/services/nemo/streaming_asr.py deleted file mode 100644 index aeb6674216762857712d9641e268fd6e471ea38a..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/pipecat/services/nemo/streaming_asr.py +++ /dev/null @@ -1,319 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# NOTE: This file will be deprecated in the future, as the new inference pipeline will replace it. - -import math -import time -from dataclasses import dataclass -from typing import List, Optional - -import numpy as np -import torch -from omegaconf import open_dict - -import nemo.collections.asr as nemo_asr -from nemo.agents.voice_agent.pipecat.services.nemo.utils import CacheFeatureBufferer -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis -from nemo.collections.common.tokenizers.sentencepiece_tokenizer import SentencePieceTokenizer - - -@dataclass -class ASRResult: - text: str - is_final: bool - eou_prob: Optional[float] = None - eob_prob: Optional[float] = None - eou_latency: Optional[float] = None - eob_latency: Optional[float] = None - processing_time: Optional[float] = None - - -class NemoStreamingASRService: - def __init__( - self, - model: str = "nvidia/parakeet_realtime_eou_120m-v1", - att_context_size: List[int] = [70, 1], - device: str = "cuda", - eou_string: str = "", - eob_string: str = "", - decoder_type: str = None, - chunk_size: int = -1, - shift_size: int = -1, - left_chunks: int = 2, - sample_rate: int = 16000, - frame_len_in_secs: float = 0.08, - use_amp: bool = False, - chunk_size_in_secs: float = 0.08, - ): - self.model = model - self.eou_string = eou_string - self.eob_string = eob_string - self.device = device - self.att_context_size = att_context_size - self.decoder_type = decoder_type - self.chunk_size = chunk_size - self.shift_size = shift_size - self.left_chunks = left_chunks - self.asr_model = self._load_model(model) - self.tokenizer: SentencePieceTokenizer = self.asr_model.tokenizer - self.use_amp = use_amp - self.pad_and_drop_preencoded = False - self.blank_id = self.get_blank_id() - self.chunk_size_in_secs = chunk_size_in_secs - - assert len(self.att_context_size) == 2, "Att context size must be a list of two integers" - assert ( - self.att_context_size[0] >= 0 - ), f"Left att context size must be greater than 0: {self.att_context_size[0]}" - assert ( - self.att_context_size[1] >= 0 - ), f"Right att context size must be greater than 0: {self.att_context_size[1]}" - - window_stride_in_secs = self.asr_model.cfg.preprocessor.window_stride - model_stride = self.asr_model.cfg.encoder.subsampling_factor - self.model_chunk_size = self.asr_model.encoder.streaming_cfg.chunk_size - if isinstance(self.model_chunk_size, list): - self.model_chunk_size = self.model_chunk_size[1] - self.pre_encode_cache_size = self.asr_model.encoder.streaming_cfg.pre_encode_cache_size - if isinstance(self.pre_encode_cache_size, list): - self.pre_encode_cache_size = self.pre_encode_cache_size[1] - self.pre_encode_cache_size_in_secs = self.pre_encode_cache_size * window_stride_in_secs - - self.tokens_per_frame = math.ceil(np.trunc(self.chunk_size_in_secs / window_stride_in_secs) / model_stride) - # overwrite the encoder streaming params with proper shift size for cache aware streaming - self.asr_model.encoder.setup_streaming_params( - chunk_size=self.model_chunk_size // model_stride, shift_size=self.tokens_per_frame - ) - - model_chunk_size_in_secs = self.model_chunk_size * window_stride_in_secs - - self.buffer_size_in_secs = self.pre_encode_cache_size_in_secs + model_chunk_size_in_secs - - self._audio_buffer = CacheFeatureBufferer( - sample_rate=sample_rate, - buffer_size_in_secs=self.buffer_size_in_secs, - chunk_size_in_secs=self.chunk_size_in_secs, - preprocessor_cfg=self.asr_model.cfg.preprocessor, - device=self.device, - ) - self._reset_cache() - self._previous_hypotheses = self._get_blank_hypothesis() - self._last_transcript_timestamp = time.time() - print(f"NemoStreamingASRService initialized with model `{model}` on device `{self.device}`") - - def _reset_cache(self): - ( - self._cache_last_channel, # [17, B, 70, 512] - self._cache_last_time, # [17, B, 512, 8] - self._cache_last_channel_len, # B - ) = self.asr_model.encoder.get_initial_cache_state( - 1 - ) # batch size is 1 - - def _get_blank_hypothesis(self) -> List[Hypothesis]: - blank_hypothesis = Hypothesis(score=0.0, y_sequence=[], dec_state=None, timestamp=[], last_token=None) - return [blank_hypothesis] - - @property - def drop_extra_pre_encoded(self): - return self.asr_model.encoder.streaming_cfg.drop_extra_pre_encoded - - def get_blank_id(self): - return len(self.tokenizer.vocab) - - def get_text_from_tokens(self, tokens: List[int]) -> str: - sep = "\u2581" # '▁' - tokens = [int(t) for t in tokens if t != self.blank_id] - if tokens: - pieces = self.tokenizer.ids_to_tokens(tokens) - text = "".join([p.replace(sep, ' ') if p.startswith(sep) else p for p in pieces]) - else: - text = "" - return text - - def _load_model(self, model: str): - if model.endswith(".nemo"): - asr_model = nemo_asr.models.ASRModel.restore_from(model, map_location=torch.device(self.device)) - else: - asr_model = nemo_asr.models.ASRModel.from_pretrained(model, map_location=torch.device(self.device)) - - if self.decoder_type is not None and hasattr(asr_model, "cur_decoder"): - asr_model.change_decoding_strategy(decoder_type=self.decoder_type) - elif isinstance(asr_model, nemo_asr.models.EncDecCTCModel): - self.decoder_type = "ctc" - elif isinstance(asr_model, nemo_asr.models.EncDecRNNTModel): - self.decoder_type = "rnnt" - else: - raise ValueError("Decoder type not supported for this model.") - - if self.att_context_size is not None: - if hasattr(asr_model.encoder, "set_default_att_context_size"): - asr_model.encoder.set_default_att_context_size(att_context_size=self.att_context_size) - else: - raise ValueError("Model does not support multiple lookaheads.") - else: - self.att_context_size = asr_model.cfg.encoder.att_context_size - - decoding_cfg = asr_model.cfg.decoding - with open_dict(decoding_cfg): - decoding_cfg.strategy = "greedy" - decoding_cfg.compute_timestamps = False - decoding_cfg.preserve_alignments = True - if hasattr(asr_model, 'joint'): # if an RNNT model - decoding_cfg.greedy.max_symbols = 10 - decoding_cfg.fused_batch_size = -1 - asr_model.change_decoding_strategy(decoding_cfg) - - if hasattr(asr_model.encoder, "set_default_att_context_size"): - asr_model.encoder.set_default_att_context_size(att_context_size=self.att_context_size) - - # chunk_size is set automatically for models trained for streaming. - # For models trained for offline mode with full context, we need to pass the chunk_size explicitly. - if self.chunk_size > 0: - if self.shift_size < 0: - shift_size = self.chunk_size - else: - shift_size = self.shift_size - asr_model.encoder.setup_streaming_params( - chunk_size=self.chunk_size, left_chunks=self.left_chunks, shift_size=shift_size - ) - - asr_model.eval() - return asr_model - - def _get_best_hypothesis(self, encoded, encoded_len, partial_hypotheses=None): - if self.decoder_type == "ctc": - best_hyp = self.asr_model.decoding.ctc_decoder_predictions_tensor( - encoded, - encoded_len, - return_hypotheses=True, - ) - elif self.decoder_type == "rnnt": - best_hyp = self.asr_model.decoding.rnnt_decoder_predictions_tensor( - encoded, encoded_len, return_hypotheses=True, partial_hypotheses=partial_hypotheses - ) - else: - raise ValueError("Decoder type not supported for this model.") - return best_hyp - - def _get_tokens_and_probs_from_alignments(self, alignments): - tokens = [] - probs = [] - if self.decoder_type == "ctc": - all_logits = alignments[0] - all_tokens = alignments[1] - for i in range(len(all_tokens)): - token_id = int(all_tokens[i]) - if token_id != self.blank_id: - tokens.append(token_id) - logits = all_logits[i] # shape (vocab_size,) - probs_i = torch.softmax(logits, dim=-1)[token_id].item() - probs.append(probs_i) - elif self.decoder_type == "rnnt": - for t in range(len(alignments)): - for u in range(len(alignments[t])): - logits, token_id = alignments[t][u] # (logits, token_id) - token_id = int(token_id) - if token_id != self.blank_id: - tokens.append(token_id) - probs_i = torch.softmax(logits, dim=-1)[token_id].item() - probs.append(probs_i) - else: - raise ValueError("Decoder type not supported for this model.") - - return tokens, probs - - def transcribe(self, audio: bytes, stream_id: str = "default") -> ASRResult: - start_time = time.time() - - # Convert bytes to numpy array - audio_array = np.frombuffer(audio, dtype=np.int16).astype(np.float32) / 32768.0 - - self._audio_buffer.update(audio_array) - - features = self._audio_buffer.get_feature_buffer() - feature_lengths = torch.tensor([features.shape[1]], device=self.device) - features = features.unsqueeze(0) # Add batch dimension - - with torch.no_grad(): - ( - encoded, - encoded_len, - cache_last_channel, - cache_last_time, - cache_last_channel_len, - ) = self.asr_model.encoder.cache_aware_stream_step( - processed_signal=features, - processed_signal_length=feature_lengths, - cache_last_channel=self._cache_last_channel, - cache_last_time=self._cache_last_time, - cache_last_channel_len=self._cache_last_channel_len, - keep_all_outputs=False, - drop_extra_pre_encoded=self.drop_extra_pre_encoded, - ) - - best_hyp = self._get_best_hypothesis(encoded, encoded_len, partial_hypotheses=self._previous_hypotheses) - - self._previous_hypotheses = best_hyp - self._cache_last_channel = cache_last_channel - self._cache_last_time = cache_last_time - self._cache_last_channel_len = cache_last_channel_len - - tokens, probs = self._get_tokens_and_probs_from_alignments(best_hyp[0].alignments) - - text = self.get_text_from_tokens(tokens) - - is_final = False - eou_latency = None - eob_latency = None - eou_prob = None - eob_prob = None - current_timestamp = time.time() - if self.eou_string in text or self.eob_string in text: - is_final = True - if self.eou_string in text: - eou_latency = ( - current_timestamp - self._last_transcript_timestamp if text.strip() == self.eou_string else 0.0 - ) - eou_prob = self.get_eou_probability(tokens, probs, self.eou_string) - if self.eob_string in text: - eob_latency = ( - current_timestamp - self._last_transcript_timestamp if text.strip() == self.eob_string else 0.0 - ) - eob_prob = self.get_eou_probability(tokens, probs, self.eob_string) - self.reset_state(stream_id=stream_id) - if text.strip(): - self._last_transcript_timestamp = current_timestamp - - processing_time = time.time() - start_time - return ASRResult( - text=text, - is_final=is_final, - eou_latency=eou_latency, - eob_latency=eob_latency, - eou_prob=eou_prob, - eob_prob=eob_prob, - processing_time=processing_time, - ) - - def reset_state(self, stream_id: str = "default"): - self._audio_buffer.reset() - self._reset_cache() - self._previous_hypotheses = self._get_blank_hypothesis() - self._last_transcript_timestamp = time.time() - - def get_eou_probability(self, tokens: List[int], probs: List[float], eou_string: str = "") -> float: - text_tokens = self.tokenizer.ids_to_tokens(tokens) - eou_index = text_tokens.index(eou_string) - return probs[eou_index] diff --git a/nemo/agents/voice_agent/pipecat/services/nemo/streaming_diar.py b/nemo/agents/voice_agent/pipecat/services/nemo/streaming_diar.py deleted file mode 100644 index 21bda1174c01308e6b71335c0837891de181fa19..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/pipecat/services/nemo/streaming_diar.py +++ /dev/null @@ -1,212 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# NOTE: This file will be deprecated in the future, as the new inference pipeline will replace it. - -from dataclasses import dataclass -from typing import Tuple - -import numpy as np -import torch -from torch import Tensor - -from nemo.agents.voice_agent.pipecat.services.nemo.utils import CacheFeatureBufferer -from nemo.collections.asr.models import SortformerEncLabelModel - -from nemo.collections.asr.modules.sortformer_modules import StreamingSortformerState - - -@dataclass -class DiarizationConfig: - """Diarization configuration parameters for inference.""" - - model_path: str = "nvidia/diar_streaming_sortformer_4spk-v2" - device: str = "cuda" - - log: bool = False # If True, log will be printed - max_num_speakers: int = 4 - spkcache_len: int = 188 - spkcache_refresh_rate: int = 144 - fifo_len: int = 188 - chunk_len: int = 6 - chunk_left_context: int = 1 - chunk_right_context: int = 7 - - -class NeMoStreamingDiarService: - def __init__( - self, - cfg: DiarizationConfig, - model: str, - frame_len_in_secs: float = 0.08, - sample_rate: int = 16000, - left_offset: int = 8, - right_offset: int = 8, - use_amp: bool = False, - compute_dtype: torch.dtype = torch.float32, - ): - self.model = model - self.cfg = cfg - self.cfg.model_path = model - self.diarizer = self.build_diarizer() - self.device = cfg.device - self.use_amp = use_amp - self.compute_dtype = compute_dtype - self.frame_len_in_secs = frame_len_in_secs - self.left_offset = left_offset - self.right_offset = right_offset - self.chunk_size = self.cfg.chunk_len - self.buffer_size_in_secs = ( - self.cfg.chunk_len * self.frame_len_in_secs + (self.left_offset + self.right_offset) * 0.01 - ) - self.max_num_speakers = self.cfg.max_num_speakers - - self.feature_bufferer = CacheFeatureBufferer( - sample_rate=sample_rate, - buffer_size_in_secs=self.buffer_size_in_secs, - chunk_size_in_secs=self.cfg.chunk_len * self.frame_len_in_secs, - preprocessor_cfg=self.diarizer.cfg.preprocessor, - device=self.device, - ) - self.streaming_state = self.init_streaming_state(batch_size=1) - self.total_preds = torch.zeros((1, 0, self.max_num_speakers), device=self.diarizer.device) - - print(f"NeMoStreamingDiarService initialized with model `{model}` on device `{self.device}`") - - def build_diarizer(self): - if self.cfg.model_path.endswith(".nemo"): - diar_model = SortformerEncLabelModel.restore_from(self.cfg.model_path, map_location=self.cfg.device) - else: - diar_model = SortformerEncLabelModel.from_pretrained(self.cfg.model_path, map_location=self.cfg.device) - - # Steaming mode setup - diar_model.sortformer_modules.chunk_len = self.cfg.chunk_len - diar_model.sortformer_modules.spkcache_len = self.cfg.spkcache_len - diar_model.sortformer_modules.chunk_left_context = self.cfg.chunk_left_context - diar_model.sortformer_modules.chunk_right_context = self.cfg.chunk_right_context - diar_model.sortformer_modules.fifo_len = self.cfg.fifo_len - diar_model.sortformer_modules.log = self.cfg.log - diar_model.sortformer_modules.spkcache_refresh_rate = self.cfg.spkcache_refresh_rate - diar_model.eval() - - return diar_model - - def print_diar_result(self, diar_result: np.ndarray): - for t in range(diar_result.shape[0]): - spk_probs = "" - for s in range(diar_result.shape[1]): - spk_probs += f"{diar_result[t, s]:.2f} " - print(f"Time {t}: {spk_probs}") - - def diarize(self, audio: bytes, stream_id: str = "default") -> str: - - audio_array = np.frombuffer(audio, dtype=np.int16).astype(np.float32) / 32768.0 - - self.feature_bufferer.update(audio_array) - - features = self.feature_bufferer.get_feature_buffer() - feature_buffers = features.unsqueeze(0) # add batch dimension - feature_buffers = feature_buffers.transpose(1, 2) # [batch, feature, time] -> [batch, time, feature] - feature_buffer_lens = torch.tensor([feature_buffers.shape[1]], device=self.device) - self.streaming_state, chunk_preds = self.stream_step( - processed_signal=feature_buffers, - processed_signal_length=feature_buffer_lens, - streaming_state=self.streaming_state, - total_preds=self.total_preds, - left_offset=self.left_offset, - right_offset=self.right_offset, - ) - self.total_preds = chunk_preds - diar_result = chunk_preds[:, -self.chunk_size :, :].clone().cpu().numpy() - return diar_result[0] # tensor of shape [6, 4] - - def reset_state(self, stream_id: str = "default"): - self.feature_bufferer.reset() - self.streaming_state = self.init_streaming_state(batch_size=1) - self.total_preds = torch.zeros((1, 0, self.max_num_speakers), device=self.diarizer.device) - - def init_streaming_state(self, batch_size: int = 1) -> StreamingSortformerState: - """ - Initialize the streaming state for the diarization model. - - Args: - batch_size: The batch size to use. - - Returns: - SortformerStreamingState: The initialized streaming state. - """ - # Use the model's init_streaming_state method but convert to SortformerStreamingState format - nemo_state = self.diarizer.sortformer_modules.init_streaming_state( - batch_size=batch_size, async_streaming=self.diarizer.async_streaming, device=self.device - ) - - return nemo_state - - def stream_step( - self, - processed_signal: Tensor, - processed_signal_length: Tensor, - streaming_state: StreamingSortformerState, - total_preds: Tensor, - left_offset: int = 0, - right_offset: int = 0, - ) -> Tuple[StreamingSortformerState, Tensor]: - """ - Execute a single streaming step for diarization. - - Args: - processed_signal: The processed audio signal. - processed_signal_length: The length of the processed signal. - streaming_state: The current streaming state. - total_preds: The total predictions so far. - left_offset: The left offset for the current chunk. - right_offset: The right offset for the current chunk. - - Returns: - Tuple[SortformerStreamingState, Tensor]: The updated streaming state and predictions. - """ - # Move tensors to correct device - if processed_signal.device != self.device: - processed_signal = processed_signal.to(self.device) - - if processed_signal_length.device != self.device: - processed_signal_length = processed_signal_length.to(self.device) - - if total_preds is not None and total_preds.device != self.device: - total_preds = total_preds.to(self.device) - - with ( - torch.amp.autocast(device_type=self.device, dtype=self.compute_dtype, enabled=self.use_amp), - torch.inference_mode(), - torch.no_grad(), - ): - try: - # Call the model's forward_streaming_step method - streaming_state, diar_pred_out_stream = self.diarizer.forward_streaming_step( - processed_signal=processed_signal, - processed_signal_length=processed_signal_length, - streaming_state=streaming_state, - total_preds=total_preds, - left_offset=left_offset, - right_offset=right_offset, - ) - except Exception as e: - print(f"Error in diarizer streaming step: {e}") - # print the stack trace - import traceback - - traceback.print_exc() - # Return the existing state and preds if there's an error - return streaming_state, total_preds - - return streaming_state, diar_pred_out_stream diff --git a/nemo/agents/voice_agent/pipecat/services/nemo/stt.py b/nemo/agents/voice_agent/pipecat/services/nemo/stt.py deleted file mode 100644 index bb048f50805e4b32a7590144c95baff68404a04c..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/pipecat/services/nemo/stt.py +++ /dev/null @@ -1,316 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import asyncio -from datetime import datetime -from typing import AsyncGenerator, List, Optional - -from loguru import logger -from pipecat.frames.frames import ( - CancelFrame, - EndFrame, - ErrorFrame, - Frame, - InterimTranscriptionFrame, - StartFrame, - TranscriptionFrame, - VADUserStartedSpeakingFrame, - VADUserStoppedSpeakingFrame, -) -from pipecat.processors.frame_processor import FrameDirection -from pipecat.services.stt_service import STTService -from pipecat.transcriptions.language import Language -from pipecat.utils.time import time_now_iso8601 -from pipecat.utils.tracing.service_decorators import traced_stt -from pydantic import BaseModel - -from nemo.agents.voice_agent.pipecat.services.nemo.audio_logger import AudioLogger -from nemo.agents.voice_agent.pipecat.services.nemo.streaming_asr import NemoStreamingASRService - -ASR_EOU_MODELS = ["nvidia/parakeet_realtime_eou_120m-v1"] - -try: - # disable nemo logging - from nemo.utils import logging - - level = logging.getEffectiveLevel() - logging.setLevel(logging.CRITICAL) - - -except ModuleNotFoundError as e: - logger.error(f"Exception: {e}") - logger.error('In order to use NVIDIA NeMo STT, you need to `pip install "nemo_toolkit[all]"`.') - raise Exception(f"Missing module: {e}") - - -class NeMoSTTInputParams(BaseModel): - """Input parameters for NeMo STT service.""" - - language: Optional[Language] = Language.EN_US - att_context_size: Optional[List] = [70, 1] - frame_len_in_secs: Optional[float] = 0.08 # 80ms for FastConformer model - config_path: Optional[str] = None # path to the Niva ASR config file - raw_audio_frame_len_in_secs: Optional[float] = 0.016 # 16ms for websocket transport - buffer_size: Optional[int] = 5 # number of audio frames to buffer, 1 frame is 16ms - - -class NemoSTTService(STTService): - """NeMo Speech-to-Text service for Pipecat integration.""" - - def __init__( - self, - *, - model: Optional[str] = "nnvidia/parakeet_realtime_eou_120m-v1", - device: Optional[str] = "cuda:0", - sample_rate: Optional[int] = 16000, - params: Optional[NeMoSTTInputParams] = None, - has_turn_taking: Optional[bool] = None, # if None, it will be set by the model name - backend: Optional[str] = "legacy", - decoder_type: Optional[str] = "rnnt", - audio_logger: Optional[AudioLogger] = None, - **kwargs, - ): - super().__init__(**kwargs) - self._queue = asyncio.Queue() - self._sample_rate = sample_rate - self._params = params or NeMoSTTInputParams() - self._model_name = model - if has_turn_taking is None: - has_turn_taking = True if model in ASR_EOU_MODELS else False - logger.info(f"Setting has_turn_taking to `{has_turn_taking}` based on model name: `{model}`") - self._has_turn_taking = has_turn_taking - self._backend = backend - self._decoder_type = decoder_type - self._audio_logger = audio_logger - self._is_vad_active = False - logger.info(f"NeMoSTTInputParams: {self._params}") - - self._device = device - - self._load_model() - - self.audio_buffer = [] - self.user_is_speaking = False - - def _load_model(self): - if self._backend == "legacy": - self._model = NemoStreamingASRService( - self._model_name, - self._params.att_context_size, - device=self._device, - decoder_type=self._decoder_type, - frame_len_in_secs=self._params.frame_len_in_secs, - ) - else: - raise ValueError(f"Invalid ASR backend: {self._backend}") - - def can_generate_metrics(self) -> bool: - """Indicates whether this service can generate metrics. - - Returns: - bool: True, as this service supports metric generation. - """ - return True - - async def start(self, frame: StartFrame): - """Handle service start. - - Args: - frame: StartFrame containing initial configuration - """ - await super().start(frame) - - # Initialize the model if not already done - if not hasattr(self, "_model"): - self._load_model() - - async def stop(self, frame: EndFrame): - """Handle service stop. - - Args: - frame: EndFrame that triggered this method - """ - await super().stop(frame) - # Clear any internal state if needed - await self._queue.put(None) # Signal to stop processing - - async def cancel(self, frame: CancelFrame): - """Handle service cancellation. - - Args: - frame: CancelFrame that triggered this method - """ - await super().cancel(frame) - # Clear any internal state - await self._queue.put(None) # Signal to stop processing - self._queue = asyncio.Queue() # Reset the queue - - async def run_stt(self, audio: bytes) -> AsyncGenerator[Frame, None]: - """Process audio data and generate transcription frames. - - Args: - audio: Raw audio bytes to transcribe - - Yields: - Frame: Transcription frames containing the results - """ - timestamp_now = datetime.now() - await self.start_ttfb_metrics() - await self.start_processing_metrics() - if self._audio_logger is not None and self._audio_logger.first_audio_timestamp is None: - self._audio_logger.first_audio_timestamp = timestamp_now - - try: - is_final = False - user_has_finished = False - transcription = None - self.audio_buffer.append(audio) - if len(self.audio_buffer) >= self._params.buffer_size: - audio = b"".join(self.audio_buffer) - self.audio_buffer = [] - - # Append to continuous user audio buffer for stereo conversation recording - if self._audio_logger is not None: - self._audio_logger.append_continuous_user_audio(audio) - - asr_result = self._model.transcribe(audio) - transcription = asr_result.text - is_final = asr_result.is_final - if self._audio_logger is not None: - if self._is_vad_active: - is_first_frame = False - self._audio_logger.turn_audio_buffer.append(audio) - # Accumulate transcriptions for turn-based logging - if transcription: - self._audio_logger.turn_transcription_buffer.append(transcription) - self._audio_logger.stage_turn_audio_and_transcription( - timestamp_now=timestamp_now, - is_first_frame=is_first_frame, - additional_metadata={ - "model": self._model_name, - "backend": self._backend, - }, - ) - eou_latency = asr_result.eou_latency - eob_latency = asr_result.eob_latency - eou_prob = asr_result.eou_prob - eob_prob = asr_result.eob_prob - if eou_latency is not None: - logger.debug( - f"EOU latency: {eou_latency: .4f} seconds. EOU probability: {eou_prob: .2f}." - f"Processing time: {asr_result.processing_time: .4f} seconds." - ) - user_has_finished = True - if eob_latency is not None: - logger.debug( - f"EOB latency: {eob_latency: .4f} seconds. EOB probability: {eob_prob: .2f}." - f"Processing time: {asr_result.processing_time: .4f} seconds." - ) - user_has_finished = True - await self.stop_ttfb_metrics() - await self.stop_processing_metrics() - - if transcription: - logger.debug(f"Transcription (is_final={is_final}): `{transcription}`") - self.user_is_speaking = True if not user_has_finished else False - - # Get the language from params or default to EN_US - language = self._params.language if self._params else Language.EN_US - - # Create and push the transcription frame - if self._has_turn_taking: - # if turn taking is enabled, we push interim transcription frames - # and let the turn taking service handle the final transcription - frame_type = InterimTranscriptionFrame - else: - # otherwise, we use the is_final flag to determine the frame type - frame_type = TranscriptionFrame if is_final else InterimTranscriptionFrame - await self.push_frame( - frame_type( - transcription, - "", # No speaker ID in this implementation - time_now_iso8601(), - language, - result={"text": transcription}, - ) - ) - - # Handle the transcription - await self._handle_transcription( - transcript=transcription, - is_final=is_final, - language=language, - ) - - yield None - - except Exception as e: - logger.error(f"Error in NeMo STT processing: {e}") - await self.push_frame( - ErrorFrame( - str(e), - time_now_iso8601(), - ) - ) - yield None - - @traced_stt - async def _handle_transcription(self, transcript: str, is_final: bool, language: Optional[str] = None): - """Handle a transcription result. - - Args: - transcript: The transcribed text - is_final: Whether this is a final transcription - language: The language of the transcription - """ - pass # Base implementation - can be extended for specific handling needs - - async def set_language(self, language: Language): - """Update the service's recognition language. - - Args: - language: New language for recognition - """ - if self._params: - self._params.language = language - else: - self._params = NeMoSTTInputParams(language=language) - - logger.info(f"Switching STT language to: {language}") - - async def set_model(self, model: str): - """Update the service's model. - - Args: - model: New model name/path to use - """ - await super().set_model(model) - self._model_name = model - self._load_model() - - async def process_frame(self, frame: Frame, direction: FrameDirection): - """Process incoming frames and handle VAD events.""" - if isinstance(frame, VADUserStoppedSpeakingFrame) and isinstance(self._model, NemoStreamingASRService): - # manualy reset the state of the model when end of utterance is detected by VAD - logger.debug("Resetting state of the model due to VADUserStoppedSpeakingFrame") - if self.user_is_speaking: - logger.debug( - "[EOU missing] STT failed to detect end of utterance before VAD detected user stopped speaking" - ) - self._model.reset_state() - self._is_vad_active = False - elif isinstance(frame, VADUserStartedSpeakingFrame): - self._is_vad_active = True - - await super().process_frame(frame, direction) diff --git a/nemo/agents/voice_agent/pipecat/services/nemo/tts.py b/nemo/agents/voice_agent/pipecat/services/nemo/tts.py deleted file mode 100644 index f226d6da0f406df8018c29f15fae18681a20af73..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/pipecat/services/nemo/tts.py +++ /dev/null @@ -1,892 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import asyncio -import inspect -import uuid -from collections.abc import AsyncGenerator -from datetime import datetime -from typing import Iterator, List, Optional - -import numpy as np -import torch -from loguru import logger -from omegaconf import DictConfig, OmegaConf -from pipecat.frames.frames import ( - CancelFrame, - EndFrame, - ErrorFrame, - Frame, - LLMTextFrame, - StartFrame, - TTSAudioRawFrame, - TTSStartedFrame, - TTSStoppedFrame, -) -from pipecat.services.llm_service import FunctionCallParams -from pipecat.services.tts_service import TTSService - -from nemo.agents.voice_agent.pipecat.services.nemo.audio_logger import AudioLogger -from nemo.agents.voice_agent.pipecat.utils.text.simple_text_aggregator import SimpleSegmentedTextAggregator -from nemo.agents.voice_agent.utils.tool_calling.mixins import ToolCallingMixin -from nemo.collections.tts.models import FastPitchModel, HifiGanModel - - -class BaseNemoTTSService(TTSService, ToolCallingMixin): - """Text-to-Speech service using Nemo TTS models. - - This service works with any TTS model that exposes a generate(text) method - that returns audio data. The TTS generation runs in a dedicated background thread to - avoid blocking the main asyncio event loop, following the same pattern as NemoDiarService. - - Args: - model: TTS model instance with a generate(text) method - sample_rate: Audio sample rate in Hz (defaults to 22050) - **kwargs: Additional arguments passed to TTSService - """ - - def __init__( - self, - *, - model, - device: str = "cuda", - sample_rate: int = 22050, - think_tokens: Optional[List[str]] = None, - audio_logger: Optional[AudioLogger] = None, - ignore_strings: Optional[List[str]] = None, - **kwargs, - ): - super().__init__(sample_rate=sample_rate, **kwargs) - logger.info(f"Initializing TTS service with model: {model} and device: {device}") - self._model_name = model - self._device = device - self._model = self._setup_model() - self._think_tokens = think_tokens - self._audio_logger = audio_logger - if think_tokens is not None: - assert ( - isinstance(think_tokens, list) and len(think_tokens) == 2 - ), f"think_tokens must be a list of two strings, but got type {type(think_tokens)}: {think_tokens}" - self._ignore_strings = set(ignore_strings) if ignore_strings is not None else None - # Background processing infrastructure - no response handler needed - self._tts_queue = asyncio.Queue() - self._processing_task = None - self._processing_running = False - - # Track pending requests with their response queues - self._pending_requests = {} - self._have_seen_think_tokens = False - - def reset(self): - """Reset the TTS service.""" - self._text_aggregator.reset() - - def setup_tool_calling(self): - """ - Setup the tool calling mixin by registering all available tools. - """ - pass # No tools by default - - def _setup_model(self): - raise NotImplementedError("Subclass must implement _setup_model") - - def _generate_audio(self, text: str) -> Iterator[np.ndarray]: - raise NotImplementedError("Subclass must implement _generate_audio") - - def can_generate_metrics(self) -> bool: - """If the TTS service can generate metrics.""" - return True - - async def start(self, frame: StartFrame): - """Handle service start.""" - await super().start(frame) - - # Initialize the model if not already done - if not hasattr(self, "_model") or self._model is None: - self._model = self._setup_model() - - # Only start background processing task - no response handler needed - if not self._processing_task: - self._processing_task = self.create_task(self._processing_task_handler()) - - async def stop(self, frame: EndFrame): - """Handle service stop.""" - await super().stop(frame) - await self._stop_tasks() - - async def cancel(self, frame: CancelFrame): - """Handle service cancellation.""" - await super().cancel(frame) - await self._stop_tasks() - - async def _stop_tasks(self): - """Stop background processing tasks.""" - self._processing_running = False - await self._tts_queue.put(None) # Signal to stop processing - - if self._processing_task: - await self.cancel_task(self._processing_task) - self._processing_task = None - - def _tts_processor(self): - """Background processor that handles TTS generation calls.""" - try: - while self._processing_running: - try: - future = asyncio.run_coroutine_threadsafe(self._tts_queue.get(), self.get_event_loop()) - request = future.result() - - if request is None: # Stop signal - logger.debug("Received stop signal in TTS background processor") - break - - text, request_id = request - logger.debug(f"Processing TTS request for text: [{text}]") - - # Get the response queue for this request - response_queue = None - future = asyncio.run_coroutine_threadsafe( - self._get_response_queue(request_id), self.get_event_loop() - ) - response_queue = future.result() - - if response_queue is None: - logger.warning(f"No response queue found for request {request_id}") - continue - - # Process TTS generation - try: - audio_result = self._generate_audio(text) - - # Send result directly to the waiting request - asyncio.run_coroutine_threadsafe( - response_queue.put(('success', audio_result)), self.get_event_loop() - ) - except Exception as e: - logger.error(f"Error in TTS generation: {e}") - # Send error directly to the waiting request - asyncio.run_coroutine_threadsafe(response_queue.put(('error', e)), self.get_event_loop()) - - except Exception as e: - logger.error(f"Error in background TTS processor: {e}") - - except Exception as e: - logger.error(f"Background TTS processor fatal error: {e}") - finally: - logger.debug("Background TTS processor stopped") - - async def _get_response_queue(self, request_id: str): - """Get the response queue for a specific request.""" - return self._pending_requests.get(request_id) - - async def _processing_task_handler(self): - """Handler for background processing task.""" - try: - self._processing_running = True - logger.debug("Starting background TTS processing task") - await asyncio.to_thread(self._tts_processor) - except asyncio.CancelledError: - logger.debug("Background TTS processing task cancelled") - self._processing_running = False - raise - finally: - self._processing_running = False - - def _handle_think_tokens(self, text: str) -> Optional[str]: - """ - Handle the thinking tokens for TTS. - If the thinking tokens are not provided, return the text as it is. - Otherwise: - If both thinking tokens appear in the text, return the text after the end of thinking tokens. - If the LLM is thinking, return None. - If the LLM is done thinking, return the text after the end of thinking tokens. - If the LLM starts thinking, return the text before the start of thinking tokens. - If the LLM is not thinking, return the text as is. - """ - if not self._think_tokens or not text: - return text - elif self._think_tokens[0] in text and self._think_tokens[1] in text: - # LLM finishes thinking in one chunk or outputs dummy thinking tokens - logger.debug(f"LLM finishes thinking: {text}") - idx = text.index(self._think_tokens[1]) - # only return the text after the end of thinking tokens - text = text[idx + len(self._think_tokens[1]) :] - self._have_seen_think_tokens = False - logger.debug(f"Returning text after thinking: {text}") - return text - elif self._have_seen_think_tokens: - # LLM is thinking - if self._think_tokens[1] not in text: - logger.debug(f"LLM is still thinking: {text}") - # LLM is still thinking - return None - else: - # LLM is done thinking - logger.debug(f"LLM is done thinking: {text}") - idx = text.index(self._think_tokens[1]) - # only return the text after the end of thinking tokens - text = text[idx + len(self._think_tokens[1]) :] - self._have_seen_think_tokens = False - logger.debug(f"Returning text after thinking: {text}") - return text - elif self._think_tokens[0] in text: - # LLM now starts thinking - logger.debug(f"LLM starts thinking: {text}") - self._have_seen_think_tokens = True - # return text before the start of thinking tokens - idx = text.index(self._think_tokens[0]) - text = text[:idx] - logger.debug(f"Returning text before thinking: {text}") - return text - else: - # LLM is not thinking - return text - - def _drop_special_tokens(self, text: str) -> Optional[str]: - """ - Drop the special tokens from the text. - """ - if self._ignore_strings is None: - return text - for ignore_string in self._ignore_strings: - if ignore_string in text: - logger.debug(f"Dropping string `{ignore_string}` from text: `{text}`") - text = text.replace(ignore_string, "") - return text - - async def run_tts(self, text: str) -> AsyncGenerator[Frame, None]: - """Generate speech from text using the Nemo TTS model.""" - - if self._think_tokens is not None: - text = self._handle_think_tokens(text) - - if not text: - yield None - return - - if self._ignore_strings is not None: - text = self._drop_special_tokens(text) - - logger.debug(f"{self}: Generating TTS [{text}]") - - try: - await self.start_ttfb_metrics() - yield TTSStartedFrame() - - # Increment turn index at the start of agent speaking (only if speaker changed) - if self._audio_logger is not None: - self._audio_logger.increment_turn_index(speaker="agent") - - # Generate unique request ID - - request_id = str(uuid.uuid4()) - - # Create response queue for this specific request - request_queue = asyncio.Queue() - self._pending_requests[request_id] = request_queue - - try: - # Queue the TTS request for background processing - await self._tts_queue.put((text, request_id)) - - # Wait for the result directly from our request queue - result = await request_queue.get() - status, data = result - - if status == 'error': - logger.error(f"{self} TTS generation error: {data}") - yield ErrorFrame(error=f"TTS generation error: {str(data)}") - return - - audio_result = data - if audio_result is None: - logger.error(f"{self} TTS model returned None for text: [{text}]") - yield ErrorFrame(error="TTS generation failed - no audio returned") - return - - await self.start_tts_usage_metrics(text) - - # Collect all audio for logging - all_audio_bytes = b"" - # Capture the start time when TTS begins (not when it ends) - if self._audio_logger is not None and self._audio_logger.first_audio_timestamp is None: - self._audio_logger.first_audio_timestamp = datetime.now() - - # Process the audio result (same as before) - if ( - inspect.isgenerator(audio_result) - or hasattr(audio_result, '__iter__') - and hasattr(audio_result, '__next__') - ): - # Handle generator case - first_chunk = True - for audio_chunk in audio_result: - if first_chunk: - await self.stop_ttfb_metrics() - first_chunk = False - # Capture start time on first chunk - if self._audio_logger is not None: - tts_start_time = self._audio_logger.get_time_from_start_of_session() - - if audio_chunk is None: - break - - audio_bytes = self._convert_to_bytes(audio_chunk) - all_audio_bytes += audio_bytes - chunk_size = self.chunk_size - for i in range(0, len(audio_bytes), chunk_size): - audio_chunk_bytes = audio_bytes[i : i + chunk_size] - if not audio_chunk_bytes: - break - - frame = TTSAudioRawFrame( - audio=audio_chunk_bytes, sample_rate=self.sample_rate, num_channels=1 - ) - yield frame - else: - # Handle single result case - await self.stop_ttfb_metrics() - # Capture start time for single result - if self._audio_logger is not None: - tts_start_time = self._audio_logger.get_time_from_start_of_session() - audio_bytes = self._convert_to_bytes(audio_result) - all_audio_bytes = audio_bytes - - chunk_size = self.chunk_size - for i in range(0, len(audio_bytes), chunk_size): - chunk = audio_bytes[i : i + chunk_size] - if not chunk: - break - - frame = TTSAudioRawFrame(audio=chunk, sample_rate=self.sample_rate, num_channels=1) - yield frame - - # Log the complete audio if logger is available - if self._audio_logger is not None and all_audio_bytes: - try: - self._audio_logger.log_agent_audio( - audio_data=all_audio_bytes, - text=text, - sample_rate=self.sample_rate, - num_channels=1, - additional_metadata={ - "model": self._model_name, - }, - tts_generation_time=tts_start_time, - ) - except Exception as e: - logger.warning(f"Failed to log agent audio: {e}") - - yield TTSStoppedFrame() - - finally: - # Clean up the pending request - if request_id in self._pending_requests: - del self._pending_requests[request_id] - - except Exception as e: - logger.exception(f"{self} error generating TTS: {e}") - error_message = f"TTS generation error: {str(e)}" - yield ErrorFrame(error=error_message) - - def _convert_to_bytes(self, audio_data) -> bytes: - """Convert various audio data formats to bytes.""" - if isinstance(audio_data, (bytes, bytearray)): - return bytes(audio_data) - - if isinstance(audio_data, np.ndarray): - # Ensure it's in the right format (16-bit PCM) - if audio_data.dtype in [np.float32, np.float64]: - # Convert float [-1, 1] to int16 [-32768, 32767] - audio_data = np.clip(audio_data, -1.0, 1.0) # Ensure values are in range - audio_data = (audio_data * 32767).astype(np.int16) - elif audio_data.dtype != np.int16: - # Convert other integer types to int16 - audio_data = audio_data.astype(np.int16) - return audio_data.tobytes() - elif hasattr(audio_data, 'tobytes'): - return audio_data.tobytes() - else: - return bytes(audio_data) - - -class NeMoFastPitchHiFiGANTTSService(BaseNemoTTSService): - """Text-to-Speech service using NeMo FastPitch-Hifigan model. - - More info: https://huggingface.co/nvidia/tts_en_fastpitch - - Args: - fastpitch_model: FastPitch model name - hifigan_model: Hifigan model name - device: Device to run on (default: 'cuda') - **kwargs: Additional arguments passed to BaseNemoTTSService - """ - - def __init__( - self, - fastpitch_model: str = "nvidia/tts_en_fastpitch", - hifigan_model: str = "nvidia/tts_hifigan", - device: str = "cuda", - **kwargs, - ): - model_name = f"{fastpitch_model}+{hifigan_model}" - self._fastpitch_model_name = fastpitch_model - self._hifigan_model_name = hifigan_model - super().__init__(model=model_name, device=device, **kwargs) - self.setup_tool_calling() - - def _setup_model(self): - logger.info( - f"Loading FastPitch model={self._fastpitch_model_name} and HiFiGAN model={self._hifigan_model_name}" - ) - self._fastpitch_model = self._setup_fastpitch_model(self._fastpitch_model_name) - self._hifigan_model = self._setup_hifigan_model(self._hifigan_model_name) - return self._fastpitch_model, self._hifigan_model - - def _setup_fastpitch_model(self, model_name: str): - if model_name.endswith(".nemo"): - fastpitch_model = FastPitchModel.restore_from(model_name, map_location=torch.device(self._device)) - else: - fastpitch_model = FastPitchModel.from_pretrained(model_name, map_location=torch.device(self._device)) - fastpitch_model.eval() - return fastpitch_model - - def _setup_hifigan_model(self, model_name: str): - if model_name.endswith(".nemo"): - hifigan_model = HifiGanModel.restore_from(model_name, map_location=torch.device(self._device)) - else: - hifigan_model = HifiGanModel.from_pretrained(model_name, map_location=torch.device(self._device)) - hifigan_model.eval() - return hifigan_model - - def _generate_audio(self, text: str) -> Iterator[np.ndarray]: - with torch.no_grad(): - parsed = self._fastpitch_model.parse(text) - spectrogram = self._fastpitch_model.generate_spectrogram(tokens=parsed) - audio = self._hifigan_model.convert_spectrogram_to_audio(spec=spectrogram) - audio = audio.detach().view(-1).cpu().numpy() - yield audio - - -class KokoroTTSService(BaseNemoTTSService): - """Text-to-Speech service using Kokoro-82M model. - - Kokoro is an open-weight TTS model with 82 million parameters. - More info: https://huggingface.co/hexgrad/Kokoro-82M - - Args: - lang_code: Language code for the model (default: 'a' for American English) - voice: Voice to use (default: 'af_heart') - device: Device to run on (default: 'cuda') - sample_rate: Audio sample rate in Hz (default: 24000 for Kokoro) - download_all: Download all models for different languages (default: True) - cache_models: Cache models on GPU for faster switching between languages (default: True) - **kwargs: Additional arguments passed to BaseNemoTTSService - """ - - def __init__( - self, - model: str = "hexgrad/Kokoro-82M", - lang_code: str = "a", - voice: str = "af_heart", - device: str = "cuda", - sample_rate: int = 24000, - speed: float = 1.0, - download_all: bool = True, - cache_models: bool = True, - **kwargs, - ): - self._lang_code = lang_code - self._voice = voice - self._speed = speed - assert speed > 0, "Speed must be greater than 0" - self._original_speed = speed - self._original_voice = voice - self._gender = 'female' if voice[1] == 'f' else 'male' - self._original_gender = self._gender - self._original_lang_code = self._lang_code - if download_all: - self._model_maps = self._download_all_models( - lang_code=["a", "b"], device=device, repo_id=model, cache_models=cache_models - ) - else: - self._model_maps = {} - super().__init__(model=model, device=device, sample_rate=sample_rate, **kwargs) - self.setup_tool_calling() - - def _setup_model(self, lang_code: Optional[str] = None, voice: Optional[str] = None): - """Initialize the Kokoro pipeline.""" - try: - from kokoro import KPipeline - except ImportError: - raise ImportError( - "kokoro package is required for KokoroTTSService. Install it with: `pip install kokoro>=0.9.2`" - ) - if lang_code is None: - lang_code = self._lang_code - if voice is None: - voice = self._voice - logger.info(f"Loading Kokoro TTS model with model={self._model_name}, lang_code={lang_code}, voice={voice}") - if lang_code in self._model_maps: - pipeline = self._model_maps[lang_code] - else: - pipeline = KPipeline(lang_code=lang_code, device=self._device, repo_id=self._model_name) - self._model_maps[lang_code] = pipeline - return pipeline - - def _download_all_models( - self, lang_code: List[str] = ['a', 'b'], device="cuda", repo_id="hexgrad/Kokoro-82M", cache_models=True - ): - """Download all models for Kokoro TTS service.""" - logger.info(f"Downloading all models for Kokoro TTS service with lang_code={lang_code}") - from kokoro import KPipeline - - model_maps = {} - - for lang in lang_code: - pipeline = KPipeline(lang_code=lang, device=device, repo_id=repo_id) - if cache_models: - model_maps[lang] = pipeline - torch.cuda.empty_cache() - return model_maps - - def _generate_audio(self, text: str) -> Iterator[np.ndarray]: - """Generate audio using the Kokoro pipeline. - - Args: - text: Text to convert to speech - - Yields: - Audio data as numpy arrays - """ - try: - # Generate audio using Kokoro pipeline - generator = self._model(text, voice=self._voice, speed=self._speed) - - # The generator yields tuples of (gs, ps, audio) - # We only need the audio component - for i, (gs, ps, audio) in enumerate(generator): - logger.debug( - f"Kokoro generated audio chunk {i}: gs={gs}, ps={ps}," - f"audio_shape={audio.shape if hasattr(audio, 'shape') else len(audio)}" - ) - if isinstance(audio, torch.Tensor): - audio = audio.detach().cpu().numpy() - # Kokoro returns audio as numpy array in float32 format [-1, 1] - # The base class will handle conversion to int16 bytes - yield audio - - except Exception as e: - logger.error(f"Error generating audio with Kokoro: {e}") - raise - - async def tool_tts_set_speed(self, params: FunctionCallParams, speed_lambda: float): - """ - Set a specific speaking speed of the assistant's voice. - This tool should be called only when the user specifies the speed explicitly, - such as "speak twice as fast" or "speak half as slow" or "speak 1.5 times as fast". - - Inform user of the result of this tool call. After calling this tool, continue the previous - response if it was unfinished and was interrupted by the user, otherwise start a new response - and ask if the user needs help on anything else. Avoid repeating previous responses. - - Args: - speed_lambda: positive float, the relative change of the speaking speed to the original speed. - E.g., 1.0 for original speed, 1.25 for 25% faster than original speed, - 0.8 for 20% slower than original speed. - - """ - if speed_lambda <= 0: - result = { - "success": False, - "message": f"Speed remains unchanged since the change is not a positive number: {speed_lambda}", - } - logger.debug(f"Speed remains unchanged since the change is not a positive number: {speed_lambda}") - else: - self._speed = speed_lambda * self._speed - result = { - "success": True, - "message": f"Speed set to {speed_lambda} of the previous speed", - } - logger.debug(f"Speed set to {speed_lambda} of the previous speed {self._original_speed}") - await params.result_callback(result) - - async def tool_tts_reset_speed(self, params: FunctionCallParams): - """ - Reset the speaking speed to the original speed. - - Inform user of the result of this tool call. After calling this tool, continue the previous - response if it was unfinished and was interrupted by the user, otherwise start a new response - and ask if the user needs help on anything else. Avoid repeating previous responses. - """ - self._speed = self._original_speed - result = {"success": True, "message": "Speaking speed is reset to the original one"} - logger.debug(f"Speaking speed is reset to the original speed {self._original_speed}") - await params.result_callback(result) - - async def tool_tts_speak_faster(self, params: FunctionCallParams): - """ - Speak faster by increasing the speaking speed 15% faster each time this function is called. - - Inform user of the result of this tool call. After calling this tool, continue the previous - response if it was unfinished and was interrupted by the user, otherwise start a new response - and ask if the user needs help on anything else. Avoid repeating previous responses. - """ - speed_lambda = 1.15 - self._speed = speed_lambda * self._speed - result = { - "success": True, - "message": f"Speaking speed is increased to {speed_lambda} of the previous speed", - } - logger.debug(f"Speed is set to {speed_lambda} of the previous speed, new speed is {self._speed}") - await params.result_callback(result) - - async def tool_tts_speak_slower(self, params: FunctionCallParams): - """ - Speak slower by decreasing the speaking speed 15% slower each time this function is called. - - Inform user of the result of this tool call. After calling this tool, continue the previous - response if it was unfinished and was interrupted by the user, otherwise start a new response - and ask if the user needs help on anything else. Avoid repeating previous responses. - """ - speed_lambda = 0.85 - self._speed = speed_lambda * self._speed - result = { - "success": True, - "message": f"Speaking speed is decreased to {speed_lambda} of the previous speed", - } - logger.debug(f"Speed is set to {speed_lambda} of the previous speed, new speed is {self._speed}") - await params.result_callback(result) - - async def tool_tts_set_voice(self, params: FunctionCallParams, accent: str, gender: str): - """ - Set the accent and gender of the assistant's voice. - This tool should be called only when the user specifies the accent and/or gender explicitly. - - Inform user of the result of this tool call. After calling this tool, continue the previous - response if it was unfinished and was interrupted by the user, otherwise start a new response - and ask if the user needs help on anything else. Avoid repeating previous responses. - - Args: - accent: Accent for the TTS model. Must be one of 'American English', 'British English' - or 'current' for keeping the current accent. - gender: gender of the assistant's voice. Must be one of 'male', 'female', - or 'current' for keeping the current gender. - """ - await params.llm.push_frame(LLMTextFrame("Just a moment.")) - - lang_code = "a" if accent == "American English" else "b" if accent == "British English" else "current" - new_lang_code = self._lang_code - new_gender = self._gender - if lang_code != 'current': - new_lang_code = lang_code - if gender != 'current': - new_gender = gender - - if new_lang_code == 'a': - new_voice = 'af_heart' if new_gender == 'female' else 'am_michael' - elif new_lang_code == 'b': - new_voice = 'bf_emma' if new_gender == 'female' else 'bm_george' - else: - await params.result_callback( - { - "success": False, - "message": f"Invalid language code: {new_lang_code} or gender: {new_gender}", - } - ) - return - - new_model = await asyncio.to_thread(self._setup_model, new_lang_code, new_voice) - self._model = new_model - self._lang_code = new_lang_code - self._gender = new_gender - self._voice = new_voice - logger.debug(f"Language and voice are set to {new_lang_code} and {new_voice}") - await params.result_callback({"success": True, "message": "Voice has been updated."}) - - async def tool_tts_reset_voice(self, params: FunctionCallParams): - """ - Reset the accent and voice to the original ones. - - Inform user of the result of this tool call. After calling this tool, continue the previous - response if it was unfinished and was interrupted by the user, otherwise start a new response - and ask if the user needs help on anything else. Avoid repeating previous responses. - - """ - await params.llm.push_frame(LLMTextFrame("Of course.")) - - new_model = await asyncio.to_thread(self._setup_model, self._original_lang_code, self._original_voice) - self._model = new_model - self._lang_code = self._original_lang_code - self._gender = self._original_gender - self._voice = self._original_voice - logger.debug( - f"Language and voice are reset to the original ones {self._original_lang_code} and {self._original_voice}" - ) - await params.result_callback({"success": True, "message": "Voice has been reset to the original one."}) - - def setup_tool_calling(self): - """ - Setup the tool calling mixin by registering all available tools. - """ - self.register_direct_function("tool_tts_reset_speed", self.tool_tts_reset_speed) - self.register_direct_function("tool_tts_speak_faster", self.tool_tts_speak_faster) - self.register_direct_function("tool_tts_speak_slower", self.tool_tts_speak_slower) - self.register_direct_function("tool_tts_set_speed", self.tool_tts_set_speed) - self.register_direct_function("tool_tts_set_voice", self.tool_tts_set_voice) - self.register_direct_function("tool_tts_reset_voice", self.tool_tts_reset_voice) - - def reset(self): - """ - Reset the voice and speed to the original ones. - """ - self._text_aggregator.reset() - self._speed = self._original_speed - self._model = self._setup_model(self._original_lang_code, self._original_voice) - self._lang_code = self._original_lang_code - self._gender = self._original_gender - self._voice = self._original_voice - - -class MagpieTTSService(BaseNemoTTSService): - """Text-to-Speech service using Magpie TTS model. - - Magpie is a multilingual TTS model with 357 million parameters. - More info: https://huggingface.co/nvidia/magpie_tts_multilingual_357m - - Args: - model: Model name or path to the Magpie TTS model. - language: Language code for the model (default: 'en' for English) - speaker: Speaker to use for the model (default: 'Sofia') - apply_TN: Whether to apply text normalization (default: False) - device: Device to run on (default: 'cuda') - **kwargs: Additional arguments passed to BaseNemoTTSService - """ - - SPEAKER_MAP = {"John": 0, "Sofia": 1, "Aria": 2, "Jason": 3, "Leo": 4} - - def __init__( - self, - model: str = "nvidia/magpie_tts_multilingual_357m", - language: str = "en", - speaker: str = "Sofia", - apply_TN: bool = False, - device: str = "cuda", - **kwargs, - ): - if speaker not in self.SPEAKER_MAP: - raise ValueError(f"Invalid speaker: {speaker}, must be one of {list(self.SPEAKER_MAP.keys())}") - self._language = language - self._current_speaker = speaker - self._apply_TN = apply_TN - super().__init__(model=model, device=device, **kwargs) - self.setup_tool_calling() - - def _setup_model(self): - from nemo.collections.tts.models import MagpieTTSModel - - if self._model_name.endswith(".nemo"): - model = MagpieTTSModel.restore_from(self._model_name, map_location=torch.device(self._device)) - else: - model = MagpieTTSModel.from_pretrained(self._model_name, map_location=torch.device(self._device)) - model.eval() - - text = "Warming up the Magpie TTS model, this will help the model to respond faster for later requests." - with torch.no_grad(): - _, _ = model.do_tts( - text, - language=self._language, - apply_TN=self._apply_TN, - speaker_index=self.SPEAKER_MAP[self._current_speaker], - ) - torch.cuda.empty_cache() - return model - - def _generate_audio(self, text: str) -> Iterator[np.ndarray]: - audio, audio_len = self._model.do_tts( - text, - language=self._language, - apply_TN=self._apply_TN, - speaker_index=self.SPEAKER_MAP[self._current_speaker], - ) - audio_len = audio_len.view(-1).item() - audio = audio.detach().view(-1).cpu().numpy() - yield audio[:audio_len] - - def setup_tool_calling(self): - """No tools for now for Magpie TTS service.""" - pass - - -def get_tts_service_from_config(config: DictConfig, audio_logger: Optional[AudioLogger] = None) -> BaseNemoTTSService: - """Get the TTS service from the configuration. - - Args: - config: The DictConfig object containing the TTS configuration. - audio_logger: The audio logger to use for audio logging. - Returns: - The TTS service. - """ - if isinstance(config, DictConfig): - config = OmegaConf.to_container(config, resolve=True) - model = config.get("model", None) - device = config.get("device", "cuda") - if config.get("type", None) != "nemo": - raise ValueError(f"Invalid TTS type: {config.get('type', None)}, only 'nemo' is supported") - if model is None: - raise ValueError("Model is required for Nemo TTS service") - - text_aggregator = SimpleSegmentedTextAggregator( - punctuation_marks=config.get("extra_separator", None), - ignore_marks=config.get("ignore_strings", None), - min_sentence_length=config.get("min_sentence_length", 5), - use_legacy_eos_detection=config.get("use_legacy_eos_detection", False), - ) - - if model == "fastpitch-hifigan": - return NeMoFastPitchHiFiGANTTSService( - fastpitch_model=config.get("main_model_id", None), - hifigan_model=config.get("sub_model_id", None), - device=device, - text_aggregator=text_aggregator, - think_tokens=config.get("think_tokens", None), - audio_logger=audio_logger, - ignore_strings=config.get("ignore_strings", None), - ) - elif model == "magpie": - return MagpieTTSService( - model=config.get("main_model_id", None), - language=config.get("language", "en"), - speaker=config.get("speaker", "Sofia"), - apply_TN=config.get("apply_TN", False), - device=device, - text_aggregator=text_aggregator, - think_tokens=config.get("think_tokens", None), - audio_logger=audio_logger, - ignore_strings=config.get("ignore_strings", None), - ) - elif model == "kokoro": - return KokoroTTSService( - model=config.get("main_model_id", "hexgrad/Kokoro-82M"), - voice=config.get("sub_model_id", "af_heart"), - device=device, - speed=config.get("speed", 1.0), - text_aggregator=text_aggregator, - think_tokens=config.get("think_tokens", None), - sample_rate=24000, - audio_logger=audio_logger, - ignore_strings=config.get("ignore_strings", None), - ) - else: - raise ValueError(f"Invalid model: {model}, only 'fastpitch-hifigan', 'magpie' and 'kokoro' are supported") diff --git a/nemo/agents/voice_agent/pipecat/services/nemo/turn_taking.py b/nemo/agents/voice_agent/pipecat/services/nemo/turn_taking.py deleted file mode 100644 index 0c593e359e8c410e1a154224ade3ec561ba8fc82..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/pipecat/services/nemo/turn_taking.py +++ /dev/null @@ -1,441 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import time -from datetime import datetime -from pathlib import Path -from typing import List, Optional, Union - -import yaml -from loguru import logger -from pipecat.frames.frames import ( - BotStartedSpeakingFrame, - BotStoppedSpeakingFrame, - Frame, - InterimTranscriptionFrame, - StartInterruptionFrame, - TranscriptionFrame, - UserStartedSpeakingFrame, - UserStoppedSpeakingFrame, - VADUserStartedSpeakingFrame, - VADUserStoppedSpeakingFrame, -) -from pipecat.processors.frame_processor import FrameDirection, FrameProcessor -from pipecat.transcriptions.language import Language -from pipecat.utils.time import time_now_iso8601 - -from nemo.agents.voice_agent.pipecat.frames.frames import DiarResultFrame -from nemo.agents.voice_agent.pipecat.services.nemo.audio_logger import AudioLogger - - -class NeMoTurnTakingService(FrameProcessor): - """Service for handling turn-taking in voice conversations with backchannel detection.""" - - def __init__( - self, - backchannel_phrases: Union[str, List[str]] = None, - eou_string: str = "", - eob_string: str = "", - language: Language = Language.EN_US, - use_vad: bool = True, - use_diar: bool = False, - max_buffer_size: int = 2, - bot_stop_delay: float = 0.5, - audio_logger: Optional[AudioLogger] = None, - can_create_user_frames: bool = True, - **kwargs, - ): - super().__init__(**kwargs) - self.eou_string = eou_string - self.eob_string = eob_string - self.language = language - self.use_vad = use_vad - self.use_diar = use_diar - self.max_buffer_size = max_buffer_size - - self.backchannel_phrases = self._load_backchannel_phrases(backchannel_phrases) - self.backchannel_phrases_nopc = set([self.clean_text(phrase) for phrase in self.backchannel_phrases]) - self.bot_stop_delay = bot_stop_delay - self.can_create_user_frames = can_create_user_frames - # internal data - self._current_speaker_id = None - self._prev_speaker_id = None - self._bot_stop_time = None - self._bot_speaking = False - self._vad_user_speaking = False - self._have_sent_user_started_speaking = False - self._user_speaking_buffer = "" - self._audio_logger = audio_logger - if not self.use_vad: - # if vad is not used, we assume the user is always speaking - self._vad_user_speaking = True - - def _load_backchannel_phrases(self, backchannel_phrases: Optional[Union[str, List[str]]] = None): - if not backchannel_phrases: - return [] - - if isinstance(backchannel_phrases, str) and Path(backchannel_phrases).is_file(): - logger.info(f"Loading backchannel phrases from file: {backchannel_phrases}") - if not Path(backchannel_phrases).exists(): - raise FileNotFoundError(f"Backchannel phrases file not found: {backchannel_phrases}") - with open(backchannel_phrases, "r") as f: - backchannel_phrases = yaml.safe_load(f) - if not isinstance(backchannel_phrases, list): - raise ValueError(f"Backchannel phrases must be a list, got {type(backchannel_phrases)}") - logger.info(f"Loaded {len(backchannel_phrases)} backchannel phrases from file: {backchannel_phrases}") - elif isinstance(backchannel_phrases, list): - logger.info(f"Using backchannel phrases from list: {backchannel_phrases}") - else: - raise ValueError(f"Invalid backchannel phrases: {backchannel_phrases}") - return backchannel_phrases - - def reset(self): - """ - Reset the turn-taking service. - """ - self._current_speaker_id = None - self._prev_speaker_id = None - self._bot_stop_time = None - self._bot_speaking = False - self._vad_user_speaking = False - self._have_sent_user_started_speaking = False - self._user_speaking_buffer = "" - if not self.use_vad: - # if vad is not used, we assume the user is always speaking - self._vad_user_speaking = True - logger.debug("TurnTaking service reset complete") - - def clean_text(self, text: str) -> str: - """ - Clean the text so that it can be used for backchannel detection. - """ - if self.language != Language.EN_US: - raise ValueError(f"Language {self.language} not supported, currently only English is supported.") - for eou_string in [self.eou_string, self.eob_string]: - if text.endswith(eou_string): - text = text[: -len(eou_string)].strip() - text = text.lower() - valid_chars = "abcdefghijklmnopqrstuvwxyz'" - text = ''.join([c for c in text if c in valid_chars or c.isspace() or c == "'"]) - return " ".join(text.split()).strip() - - def is_backchannel(self, text: str) -> bool: - """ - Check if the text is a backchannel phrase. - """ - if not self.backchannel_phrases: - return False - if text.startswith("") :] - text = self.clean_text(text) - return text in self.backchannel_phrases_nopc - - async def process_frame(self, frame: Frame, direction: FrameDirection): - """Process incoming frames and handle turn-taking logic.""" - await super().process_frame(frame, direction) - - if self._bot_stop_time is not None: - # check if the bot has stopped speaking for more than the delay - if time.time() - self._bot_stop_time > self.bot_stop_delay: - # set the _bot_speaking flag to False to actually consider the bot as stopped speaking - logger.debug( - f"Bot stopped speaking for more than {self.bot_stop_delay} seconds, setting _bot_speaking to False" - ) - self._bot_stop_time = None - self._bot_speaking = False - - if isinstance(frame, (TranscriptionFrame, InterimTranscriptionFrame)): - await self._handle_transcription(frame, direction) - elif isinstance(frame, VADUserStartedSpeakingFrame): - await self._handle_vad_user_started_speaking(frame, direction) - elif isinstance(frame, VADUserStoppedSpeakingFrame): - await self._handle_vad_user_stopped_speaking(frame, direction) - elif isinstance(frame, BotStartedSpeakingFrame): - logger.debug("BotStartedSpeakingFrame received") - self._bot_speaking = True - # Capture the actual start time when audio starts playing - # This is more accurate than capturing during TTS generation - if self._audio_logger: - self._audio_logger.set_agent_turn_start_time() - elif isinstance(frame, BotStoppedSpeakingFrame): - logger.debug("BotStoppedSpeakingFrame received") - self._bot_stop_time = time.time() - if self.bot_stop_delay is None or self.bot_stop_delay <= 0: - # only set the flag if the delay is not set or is 0 - self._bot_speaking = False - logger.debug("Setting _bot_speaking to False") - elif isinstance(frame, DiarResultFrame): - logger.debug("DiarResultFrame received") - await self._handle_diar_result(frame, direction) - else: - await self.push_frame(frame, direction) - - async def _handle_backchannel_text(self, text: str): - # ignore the backchannel string while bot is speaking - # push the backchannel string upstream, not downstream - await self.push_frame( - TranscriptionFrame( - text=f"({text})", - user_id="", - timestamp=time_now_iso8601(), - language=self.language if self.language else Language.EN_US, - result={"text": f"Backchannel detected: {text}"}, - ), - direction=FrameDirection.UPSTREAM, - ) - - async def _handle_transcription( - self, frame: TranscriptionFrame | InterimTranscriptionFrame, direction: FrameDirection - ): - text_segment = frame.text - if self._vad_user_speaking: - self._user_speaking_buffer += text_segment - has_eou = self._user_speaking_buffer.endswith(self.eou_string) - has_eob = self._user_speaking_buffer.endswith(self.eob_string) - if has_eou: - # EOU detected, user is done speaking - push completed text and interrupt bot - logger.debug(f" Detected: `{self._user_speaking_buffer}`") - completed_text = self._user_speaking_buffer[: -len(self.eou_string)].strip() - if self._bot_speaking and self.is_backchannel(completed_text): - logger.debug(f" detected for a backchannel phrase while bot is speaking: `{completed_text}`") - await self._handle_backchannel_text(completed_text) - if self._audio_logger: - if self._audio_logger.staged_metadata is None: - self._audio_logger.staged_metadata = {"is_backchannel": True, "start_time": datetime.now()} - else: - self._audio_logger.staged_metadata["is_backchannel"] = True - - else: - await self._handle_completed_text(completed_text, direction) - await self._handle_user_interruption(UserStoppedSpeakingFrame()) - self._user_speaking_buffer = "" - self._have_sent_user_started_speaking = False # user is done speaking, so we reset the flag - elif has_eob and self._bot_speaking: - logger.debug(f" detected while bot is speaking: `{self._user_speaking_buffer}`") - await self._handle_backchannel_text(str(self._user_speaking_buffer)) - if self._audio_logger: - if self._audio_logger.staged_metadata is None: - self._audio_logger.staged_metadata = {"is_backchannel": True, "start_time": datetime.now()} - else: - self._audio_logger.staged_metadata["is_backchannel"] = True - self._user_speaking_buffer = "" - self._have_sent_user_started_speaking = False # user is done speaking, so we reset the flag - else: - # if bot is not speaking, the backchannel string is not considered a backchannel phrase - # user is still speaking, so we append the text segment to the buffer - logger.debug(f"User is speaking: `{self._user_speaking_buffer}`") - if has_eob: - logger.debug( - f"{self.eob_string} detected but ignored (bot NOT speaking): " - f"`{self._user_speaking_buffer}`" - ) - self._user_speaking_buffer = self._user_speaking_buffer[: -len(self.eob_string)].strip() - # assume the last word is not completed - completed_words = self._user_speaking_buffer.strip().split()[:-1] - if len(completed_words) >= self.max_buffer_size: - completed_text = " ".join(completed_words) - await self._handle_completed_text(completed_text, direction, is_final=False) - - else: - # if vad is not detecting user speaking - logger.debug( - f"VAD is not detecting user speaking, but still received text segment from STT: `{text_segment}`" - ) - is_backchannel = self.is_backchannel(text_segment) - if text_segment.endswith(self.eob_string): - is_backchannel = True - logger.debug(f"Dropping EOB token: `{text_segment}`") - text_segment = text_segment[: -len(self.eob_string)].strip() - elif text_segment.endswith(self.eou_string): - logger.debug(f"Dropping EOU token: `{text_segment}`") - text_segment = text_segment[: -len(self.eou_string)].strip() - - if not text_segment.strip(): - return - if is_backchannel and self._bot_speaking: - logger.debug(f"Backchannel detected while bot is speaking: `{text_segment}`") - # push the backchannel string upstream, not downstream - curr_text = str(self._user_speaking_buffer + text_segment) - self._user_speaking_buffer = "" - if self._audio_logger: - if self._audio_logger.staged_metadata is None: - self._audio_logger.staged_metadata = {"is_backchannel": True, "start_time": datetime.now()} - else: - self._audio_logger.staged_metadata["is_backchannel"] = True - await self.push_frame( - TranscriptionFrame( - text=f"({curr_text})", - user_id="", - timestamp=time_now_iso8601(), - language=self.language if self.language else Language.EN_US, - result={"text": f"Backchannel detected: {self._user_speaking_buffer+text_segment}"}, - ), - direction=FrameDirection.UPSTREAM, - ) - - else: - # if the text segment is not empty and have non-space characters, we append it to the buffer - self._user_speaking_buffer += text_segment - if self.is_backchannel(self._user_speaking_buffer): - logger.debug(f"Backchannel detected: `{self._user_speaking_buffer}`") - self._user_speaking_buffer = "" - self._have_sent_user_started_speaking = False - return - logger.debug(f"Appending text segment to user speaking buffer: `{self._user_speaking_buffer}`") - - async def _handle_completed_text(self, completed_text: str, direction: FrameDirection, is_final: bool = True): - if not self._have_sent_user_started_speaking: - # if we haven't sent the user started speaking frame, we send it now - # so that the bot can be interrupted and be ready to respond to the new user turn - await self._handle_user_interruption(UserStartedSpeakingFrame()) - self._have_sent_user_started_speaking = True - - completed_text = completed_text.strip() - completed_text = completed_text.replace(self.eou_string, "").replace(self.eob_string, "") - - if self.use_diar and not completed_text.startswith(" {completed_text}" - - frame_type = TranscriptionFrame if is_final else InterimTranscriptionFrame - text_frame = frame_type( - text=completed_text, - user_id="", # No speaker ID in this implementation - timestamp=time_now_iso8601(), - language=self.language if self.language else Language.EN_US, - result={"text": completed_text}, - ) - logger.debug(f"Pushing text frame: {text_frame}") - await self.push_frame(text_frame, direction) - - def _contains_only_speaker_tags(self, text: str) -> bool: - """ - Check if the text contains only speaker tags. - """ - return text.strip().startswith("") - - async def _handle_vad_user_started_speaking(self, frame: VADUserStartedSpeakingFrame, direction: FrameDirection): - """ - Handle the user started speaking frame. - - If there are no backchannel phrases and we haven't sent the user started speaking frame, we send it now - so that the bot can be interrupted and be ready to respond to the new user turn - """ - self._vad_user_speaking = True - logger.debug("NeMoTurnTakingService: VADUserStartedSpeakingFrame") - await self.push_frame(frame, direction) - if not self.backchannel_phrases and not self._have_sent_user_started_speaking: - await self._handle_user_interruption(UserStartedSpeakingFrame()) - self._have_sent_user_started_speaking = True - - async def _handle_vad_user_stopped_speaking(self, frame: VADUserStoppedSpeakingFrame, direction: FrameDirection): - """ - Handle the user stopped speaking frame. - - If the buffer is not empty: - - If bot is not speaking: push completed text regardless of backchannel - - If bot is speaking: ignore backchannel strings - If the buffer is empty, do nothing. - """ - if self.use_vad: - self._vad_user_speaking = False - logger.debug("NeMoTurnTakingService: VADUserStoppedSpeakingFrame") - await self.push_frame(frame, direction) - - # if user buffer only contains speaker tags, we don't push the completed text frame - if self._contains_only_speaker_tags(self._user_speaking_buffer): - logger.debug(f"User buffer only contains speaker tags: `{self._user_speaking_buffer}`, ignoring") - return - - is_backchannel = self.is_backchannel(self._user_speaking_buffer) - if not self._user_speaking_buffer: - return - if not self._bot_speaking or not is_backchannel: - logger.debug(f"Bot talking: {self._bot_speaking}, backchannel: {is_backchannel}") - logger.debug(f"Pushing completed text frame for VAD user stopped speaking: {self._user_speaking_buffer}") - await self._handle_completed_text(self._user_speaking_buffer, direction) - self._user_speaking_buffer = "" - if self._have_sent_user_started_speaking: - await self._handle_user_interruption(UserStoppedSpeakingFrame()) - self._have_sent_user_started_speaking = False - elif is_backchannel: - logger.debug(f"Backchannel detected: `{self._user_speaking_buffer}`") - if self._audio_logger: - self._audio_logger.save_user_audio(is_backchannel=True) - logger.debug( - f"[TurnTakingService] Saved backchannel audio (VAD stopped): {self._user_speaking_buffer}" - ) - - await self.push_frame( - TranscriptionFrame( - text=f"({self._user_speaking_buffer})", - user_id="", - timestamp=time_now_iso8601(), - language=self.language if self.language else Language.EN_US, - result={"text": f"Backchannel detected: {self._user_speaking_buffer}"}, - ), - direction=FrameDirection.UPSTREAM, - ) - self._user_speaking_buffer = "" - self._have_sent_user_started_speaking = False - - async def _handle_user_interruption(self, frame: Frame): - # Adapted from BaseInputTransport._handle_user_interruption - if isinstance(frame, UserStartedSpeakingFrame): - logger.debug("User started speaking") - if self.can_create_user_frames: - logger.debug("Pushing UserStartedSpeakingFrame and StartInterruptionFrame") - await self.push_frame(frame) - await self.push_frame(StartInterruptionFrame(), direction=FrameDirection.DOWNSTREAM) - else: - logger.debug( - "Skipping UserStartedSpeakingFrame and StartInterruptionFrame because can_create_user_frames is False" - ) - # Record cutoff time for agent audio when TTS is interrupted - if self._audio_logger and self._bot_speaking: - self._audio_logger.set_agent_cutoff_time() - # Increment turn index when user starts speaking (only if speaker changed) - if self._audio_logger: - self._audio_logger.increment_turn_index(speaker="user") - elif isinstance(frame, UserStoppedSpeakingFrame): - logger.debug("User stopped speaking") - if self.can_create_user_frames: - logger.debug("Pushing UserStoppedSpeakingFrame") - await self.push_frame(frame) - else: - logger.debug("Skipping UserStoppedSpeakingFrame because can_create_user_frames is False") - else: - logger.debug(f"Unknown frame type for _handle_user_interruption: {type(frame)}") - - async def _handle_diar_result(self, frame: DiarResultFrame, direction: FrameDirection): - if not self.use_diar: - logger.debug("Diarization is disabled, skipping") - return - - new_speaker_id = frame.diar_result # speaker id of the dominant speaker - - # logger.debug(f"Dominant speaker ID: {dominant_speaker_id}") - self._prev_speaker_id = self._current_speaker_id - last_speaker_id = self._current_speaker_id - - if not self._user_speaking_buffer.startswith(" to the beginning of the current utterance - self._user_speaking_buffer = f" {self._user_speaking_buffer}" - elif last_speaker_id != new_speaker_id: - # change the speaker tag to the dominant speaker id - self._user_speaking_buffer = self._user_speaking_buffer[len("") :] - self._user_speaking_buffer = f" {self._user_speaking_buffer}" - logger.debug(f"Speaker changed from {last_speaker_id} to {new_speaker_id}") - self._current_speaker_id = new_speaker_id diff --git a/nemo/agents/voice_agent/pipecat/services/nemo/utils.py b/nemo/agents/voice_agent/pipecat/services/nemo/utils.py deleted file mode 100644 index 421bf9823b5a2c6a1caac704b57b195074befc48..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/pipecat/services/nemo/utils.py +++ /dev/null @@ -1,197 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# NOTE: This file will be deprecated in the future, as the new inference pipeline will replace it. - -import math - -import numpy as np -import torch -from omegaconf import DictConfig - -import nemo.collections.asr as nemo_asr - -LOG_MEL_ZERO = -16.635 - - -class AudioBufferer: - def __init__(self, sample_rate: int, buffer_size_in_secs: float): - self.buffer_size = int(buffer_size_in_secs * sample_rate) - self.sample_buffer = torch.zeros(self.buffer_size, dtype=torch.float32) - - def reset(self) -> None: - """ - Reset the buffer to zero - """ - self.sample_buffer.zero_() - - def update(self, audio: np.ndarray) -> None: - """ - Update the buffer with the new frame - Args: - frame (Frame): frame to update the buffer with - """ - if not isinstance(audio, torch.Tensor): - audio = torch.from_numpy(audio) - - audio_size = audio.shape[0] - if audio_size > self.buffer_size: - raise ValueError(f"Frame size ({audio_size}) exceeds buffer size ({self.buffer_size})") - - shift = audio_size - self.sample_buffer[:-shift] = self.sample_buffer[shift:].clone() - self.sample_buffer[-shift:] = audio.clone() - - def get_buffer(self) -> torch.Tensor: - """ - Get the current buffer - Returns: - torch.Tensor: current state of the buffer - """ - return self.sample_buffer.clone() - - def is_buffer_empty(self) -> bool: - """ - Check if the buffer is empty - Returns: - bool: True if the buffer is empty, False otherwise - """ - return self.sample_buffer.sum() == 0 - - -class CacheFeatureBufferer: - def __init__( - self, - sample_rate: int, - buffer_size_in_secs: float, - chunk_size_in_secs: float, - preprocessor_cfg: DictConfig, - device: torch.device, - fill_value: float = LOG_MEL_ZERO, - ): - - if buffer_size_in_secs < chunk_size_in_secs: - raise ValueError( - f"Buffer size ({buffer_size_in_secs}s) should be no less than chunk size ({chunk_size_in_secs}s)" - ) - - self.sample_rate = sample_rate - self.buffer_size_in_secs = buffer_size_in_secs - self.chunk_size_in_secs = chunk_size_in_secs - self.device = device - - if hasattr(preprocessor_cfg, 'log') and preprocessor_cfg.log: - self.ZERO_LEVEL_SPEC_DB_VAL = LOG_MEL_ZERO # Log-Mel spectrogram value for zero signals - else: - self.ZERO_LEVEL_SPEC_DB_VAL = fill_value - - self.n_feat = preprocessor_cfg.features - self.timestep_duration = preprocessor_cfg.window_stride - self.n_chunk_look_back = int(self.timestep_duration * self.sample_rate) - self.chunk_size = int(self.chunk_size_in_secs * self.sample_rate) - self.sample_buffer = AudioBufferer(sample_rate, buffer_size_in_secs) - - self.feature_buffer_len = int(buffer_size_in_secs / self.timestep_duration) - self.feature_chunk_len = int(chunk_size_in_secs / self.timestep_duration) - self.feature_buffer = torch.full( - [self.n_feat, self.feature_buffer_len], - self.ZERO_LEVEL_SPEC_DB_VAL, - dtype=torch.float32, - device=self.device, - ) - - self.preprocessor = nemo_asr.models.ASRModel.from_config_dict(preprocessor_cfg) - self.preprocessor.to(self.device) - - def is_buffer_empty(self) -> bool: - """ - Check if the buffer is empty - Returns: - bool: True if the buffer is empty, False otherwise - """ - return self.sample_buffer.is_buffer_empty() - - def reset(self) -> None: - """ - Reset the buffer to zero - """ - self.sample_buffer.reset() - self.feature_buffer.fill_(self.ZERO_LEVEL_SPEC_DB_VAL) - - def _update_feature_buffer(self, feat_chunk: torch.Tensor) -> None: - """ - Add an extracted feature to `feature_buffer` - """ - self.feature_buffer[:, : -self.feature_chunk_len] = self.feature_buffer[:, self.feature_chunk_len :].clone() - self.feature_buffer[:, -self.feature_chunk_len :] = feat_chunk.clone() - - def preprocess(self, audio_signal: torch.Tensor) -> torch.Tensor: - """ - Preprocess the audio signal using the preprocessor - Args: - audio_signal (torch.Tensor): audio signal - Returns: - torch.Tensor: preprocessed features - """ - audio_signal = audio_signal.unsqueeze_(0).to(self.device) - audio_signal_len = torch.tensor([audio_signal.shape[1]], device=self.device) - features, _ = self.preprocessor( - input_signal=audio_signal, - length=audio_signal_len, - ) - features = features.squeeze() - return features - - def update(self, audio: np.ndarray) -> None: - """ - Update the sample anf feature buffers with the new frame - Args: - frame (Frame): frame to update the buffer with - """ - - # Update the sample buffer with the new frame - self.sample_buffer.update(audio) - - if math.isclose(self.buffer_size_in_secs, self.chunk_size_in_secs): - # If the buffer size is equal to the chunk size, just take the whole buffer - samples = self.sample_buffer.sample_buffer.clone() - else: - # Add look_back to have context for the first feature - samples = self.sample_buffer.sample_buffer[-(self.n_chunk_look_back + self.chunk_size) :] - - # Get the mel spectrogram - features = self.preprocess(samples) - - # If the features are longer than supposed to be, drop the last frames - # Drop the last diff frames because they might be incomplete - if (diff := features.shape[1] - self.feature_chunk_len - 1) > 0: - features = features[:, :-diff] - - # Update the feature buffer with the new features - self._update_feature_buffer(features[:, -self.feature_chunk_len :]) - - def get_buffer(self) -> torch.Tensor: - """ - Get the current sample buffer - Returns: - torch.Tensor: current state of the buffer - """ - return self.sample_buffer.get_buffer() - - def get_feature_buffer(self) -> torch.Tensor: - """ - Get the current feature buffer - Returns: - torch.Tensor: current state of the feature buffer - """ - return self.feature_buffer.clone() diff --git a/nemo/agents/voice_agent/pipecat/transports/__init__.py b/nemo/agents/voice_agent/pipecat/transports/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/pipecat/transports/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/agents/voice_agent/pipecat/transports/base_input.py b/nemo/agents/voice_agent/pipecat/transports/base_input.py deleted file mode 100644 index 79a477ad34169de78fc7da62312f6dfebaeda006..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/pipecat/transports/base_input.py +++ /dev/null @@ -1,58 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from loguru import logger -from pipecat.audio.vad.vad_analyzer import VADState -from pipecat.frames.frames import ( - InputAudioRawFrame, - UserStartedSpeakingFrame, - UserStoppedSpeakingFrame, - VADUserStartedSpeakingFrame, - VADUserStoppedSpeakingFrame, -) -from pipecat.transports.base_input import BaseInputTransport as _BaseInputTransport - - -class BaseInputTransport(_BaseInputTransport): - async def _handle_vad(self, audio_frame: InputAudioRawFrame, vad_state: VADState): - """Handle Voice Activity Detection results and generate appropriate frames.""" - new_vad_state = await self._vad_analyze(audio_frame) - if new_vad_state != vad_state and new_vad_state != VADState.STARTING and new_vad_state != VADState.STOPPING: - frame = None - # If the turn analyser is enabled, this will prevent: - # - Creating the UserStoppedSpeakingFrame - # - Creating the UserStartedSpeakingFrame multiple times - can_create_user_frames = ( - self._params.turn_analyzer is None or not self._params.turn_analyzer.speech_triggered - ) and self._params.can_create_user_frames - - if new_vad_state == VADState.SPEAKING: - await self.push_frame(VADUserStartedSpeakingFrame()) - if can_create_user_frames: - frame = UserStartedSpeakingFrame() - else: - logger.debug("base_input: VAD state changed to SPEAKING but can_create_user_frames is False") - elif new_vad_state == VADState.QUIET: - await self.push_frame(VADUserStoppedSpeakingFrame()) - if can_create_user_frames: - frame = UserStoppedSpeakingFrame() - else: - logger.debug("base_input: VAD state changed to QUIET but can_create_user_frames is False") - - if frame: - await self._handle_user_interruption(frame) - - vad_state = new_vad_state - return vad_state diff --git a/nemo/agents/voice_agent/pipecat/transports/base_transport.py b/nemo/agents/voice_agent/pipecat/transports/base_transport.py deleted file mode 100644 index eb57024611b6bac3b1656e493ab58bad53ef4f05..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/pipecat/transports/base_transport.py +++ /dev/null @@ -1,20 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from pipecat.transports.base_transport import TransportParams as _TransportParams - - -class TransportParams(_TransportParams): - can_create_user_frames: bool = True diff --git a/nemo/agents/voice_agent/pipecat/transports/network/__init__.py b/nemo/agents/voice_agent/pipecat/transports/network/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/pipecat/transports/network/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/agents/voice_agent/pipecat/transports/network/websocket_server.py b/nemo/agents/voice_agent/pipecat/transports/network/websocket_server.py deleted file mode 100644 index 800d9ddb860e40b1c85e19fed32a5fddb9317dad..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/pipecat/transports/network/websocket_server.py +++ /dev/null @@ -1,304 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import asyncio -from typing import Optional - -from loguru import logger -from pipecat.frames.frames import CancelFrame, EndFrame, InputAudioRawFrame, StartFrame -from pipecat.serializers.base_serializer import FrameSerializer -from pipecat.transports.base_transport import BaseTransport -from pipecat.transports.network.websocket_server import ( - WebsocketServerCallbacks, - WebsocketServerOutputTransport, - WebsocketServerParams, -) - -from nemo.agents.voice_agent.pipecat.transports.base_input import BaseInputTransport -from nemo.agents.voice_agent.pipecat.transports.base_transport import TransportParams - -try: - import websockets -except ModuleNotFoundError as e: - logger.error(f"Exception: {e}") - logger.error("In order to use websockets, you need to `pip install pipecat-ai[websocket]`.") - raise Exception(f"Missing module: {e}") - - -class WebsocketServerParams(TransportParams): - """Configuration parameters for WebSocket server transport. - - Parameters: - add_wav_header: Whether to add WAV headers to audio frames. - serializer: Frame serializer for message encoding/decoding. - session_timeout: Timeout in seconds for client sessions. - """ - - add_wav_header: bool = False - serializer: Optional[FrameSerializer] = None - session_timeout: Optional[int] = None - - -class WebsocketServerInputTransport(BaseInputTransport): - """WebSocket server input transport for receiving client data. - - Handles incoming WebSocket connections, message processing, and client - session management including timeout monitoring and connection lifecycle. - """ - - def __init__( - self, - transport: BaseTransport, - host: str, - port: int, - params: WebsocketServerParams, - callbacks: WebsocketServerCallbacks, - **kwargs, - ): - """Initialize the WebSocket server input transport. - - Args: - transport: The parent transport instance. - host: Host address to bind the WebSocket server to. - port: Port number to bind the WebSocket server to. - params: WebSocket server configuration parameters. - callbacks: Callback functions for WebSocket events. - **kwargs: Additional arguments passed to parent class. - """ - super().__init__(params, **kwargs) - - self._transport = transport - self._host = host - self._port = port - self._params = params - self._callbacks = callbacks - - self._websocket: Optional[websockets.WebSocketServerProtocol] = None - - self._server_task = None - - # This task will monitor the websocket connection periodically. - self._monitor_task = None - - self._stop_server_event = asyncio.Event() - - # Whether we have seen a StartFrame already. - self._initialized = False - - async def start(self, frame: StartFrame): - """Start the WebSocket server and initialize components. - - Args: - frame: The start frame containing initialization parameters. - """ - await super().start(frame) - - if self._initialized: - return - - self._initialized = True - - if self._params.serializer: - await self._params.serializer.setup(frame) - if not self._server_task: - self._server_task = self.create_task(self._server_task_handler()) - await self.set_transport_ready(frame) - - async def stop(self, frame: EndFrame): - """Stop the WebSocket server and cleanup resources. - - Args: - frame: The end frame signaling transport shutdown. - """ - await super().stop(frame) - self._stop_server_event.set() - if self._monitor_task: - await self.cancel_task(self._monitor_task) - self._monitor_task = None - if self._server_task: - await self.wait_for_task(self._server_task) - self._server_task = None - - async def cancel(self, frame: CancelFrame): - """Cancel the WebSocket server and stop all processing. - - Args: - frame: The cancel frame signaling immediate cancellation. - """ - await super().cancel(frame) - if self._monitor_task: - await self.cancel_task(self._monitor_task) - self._monitor_task = None - if self._server_task: - await self.cancel_task(self._server_task) - self._server_task = None - - async def cleanup(self): - """Cleanup resources and parent transport.""" - await super().cleanup() - await self._transport.cleanup() - - async def _server_task_handler(self): - """Handle WebSocket server startup and client connections.""" - logger.info(f"Starting websocket server on {self._host}:{self._port}") - async with websockets.serve(self._client_handler, self._host, self._port) as server: - await self._callbacks.on_websocket_ready() - await self._stop_server_event.wait() - - async def _client_handler(self, websocket: websockets.WebSocketServerProtocol, path: Optional[str] = None): - """Handle individual client connections and message processing.""" - logger.info(f"New client connection from {websocket.remote_address}") - if self._websocket: - await self._websocket.close() - logger.warning("Only one client connected, using new connection") - - self._websocket = websocket - - # Notify - await self._callbacks.on_client_connected(websocket) - - # Create a task to monitor the websocket connection - if not self._monitor_task and self._params.session_timeout: - self._monitor_task = self.create_task(self._monitor_websocket(websocket, self._params.session_timeout)) - - # Handle incoming messages - try: - async for message in websocket: - if not self._params.serializer: - continue - - frame = await self._params.serializer.deserialize(message) - - if not frame: - continue - - if isinstance(frame, InputAudioRawFrame): - await self.push_audio_frame(frame) - else: - await self.push_frame(frame) - except Exception as e: - logger.error(f"{self} exception receiving data: {e.__class__.__name__} ({e})") - - # Notify disconnection - await self._callbacks.on_client_disconnected(websocket) - - await self._websocket.close() - self._websocket = None - - logger.info(f"Client {websocket.remote_address} disconnected") - - async def _monitor_websocket(self, websocket: websockets.WebSocketServerProtocol, session_timeout: int): - """Monitor WebSocket connection for session timeout.""" - try: - await asyncio.sleep(session_timeout) - if not websocket.closed: - await self._callbacks.on_session_timeout(websocket) - except asyncio.CancelledError: - logger.info(f"Monitoring task cancelled for: {websocket.remote_address}") - raise - - -class WebsocketServerTransport(BaseTransport): - """WebSocket server transport for bidirectional real-time communication. - - Provides a complete WebSocket server implementation with separate input and - output transports, client connection management, and event handling for - real-time audio and data streaming applications. - """ - - def __init__( - self, - params: WebsocketServerParams, - host: str = "localhost", - port: int = 8765, - input_name: Optional[str] = None, - output_name: Optional[str] = None, - ): - """Initialize the WebSocket server transport. - - Args: - params: WebSocket server configuration parameters. - host: Host address to bind the server to. Defaults to "localhost". - port: Port number to bind the server to. Defaults to 8765. - input_name: Optional name for the input processor. - output_name: Optional name for the output processor. - """ - super().__init__(input_name=input_name, output_name=output_name) - self._host = host - self._port = port - self._params = params - - self._callbacks = WebsocketServerCallbacks( - on_client_connected=self._on_client_connected, - on_client_disconnected=self._on_client_disconnected, - on_session_timeout=self._on_session_timeout, - on_websocket_ready=self._on_websocket_ready, - ) - self._input: Optional[WebsocketServerInputTransport] = None - self._output: Optional[WebsocketServerOutputTransport] = None - self._websocket: Optional[websockets.WebSocketServerProtocol] = None - - # Register supported handlers. The user will only be able to register - # these handlers. - self._register_event_handler("on_client_connected") - self._register_event_handler("on_client_disconnected") - self._register_event_handler("on_session_timeout") - self._register_event_handler("on_websocket_ready") - - def input(self) -> WebsocketServerInputTransport: - """Get the input transport for receiving client data. - - Returns: - The WebSocket server input transport instance. - """ - if not self._input: - self._input = WebsocketServerInputTransport( - self, self._host, self._port, self._params, self._callbacks, name=self._input_name - ) - return self._input - - def output(self) -> WebsocketServerOutputTransport: - """Get the output transport for sending data to clients. - - Returns: - The WebSocket server output transport instance. - """ - if not self._output: - self._output = WebsocketServerOutputTransport(self, self._params, name=self._output_name) - return self._output - - async def _on_client_connected(self, websocket): - """Handle client connection events.""" - if self._output: - await self._output.set_client_connection(websocket) - await self._call_event_handler("on_client_connected", websocket) - else: - logger.error("A WebsocketServerTransport output is missing in the pipeline") - - async def _on_client_disconnected(self, websocket): - """Handle client disconnection events.""" - if self._output: - await self._output.set_client_connection(None) - await self._call_event_handler("on_client_disconnected", websocket) - else: - logger.error("A WebsocketServerTransport output is missing in the pipeline") - - async def _on_session_timeout(self, websocket): - """Handle client session timeout events.""" - await self._call_event_handler("on_session_timeout", websocket) - - async def _on_websocket_ready(self): - """Handle WebSocket server ready events.""" - await self._call_event_handler("on_websocket_ready") diff --git a/nemo/agents/voice_agent/pipecat/utils/__init__.py b/nemo/agents/voice_agent/pipecat/utils/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/pipecat/utils/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/agents/voice_agent/pipecat/utils/text/__init__.py b/nemo/agents/voice_agent/pipecat/utils/text/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/pipecat/utils/text/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/agents/voice_agent/pipecat/utils/text/simple_text_aggregator.py b/nemo/agents/voice_agent/pipecat/utils/text/simple_text_aggregator.py deleted file mode 100644 index 9767ac937d32a926e422b47e851b47b412cfdb19..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/pipecat/utils/text/simple_text_aggregator.py +++ /dev/null @@ -1,238 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import re -from typing import AsyncIterator, Optional - -from loguru import logger -from pipecat.utils.string import match_endofsentence -from pipecat.utils.text.base_text_aggregator import Aggregation, AggregationType -from pipecat.utils.text.simple_text_aggregator import SimpleTextAggregator - - -def has_partial_decimal(text: str) -> bool: - """Check if the text ends with a partial decimal. - - Returns True if the text ends with a number that looks like it could - be a partial decimal (e.g., "3.", "3.14", "($3.14)"), but NOT if it's - clearly a complete sentence (e.g., "It costs $3.14.") or a bullet point - (e.g., "1. Alpha; 2."). - """ - - # Check for bullet point pattern: ends with 1-3 digits followed by period - # Examples: "1.", "12.", "123.", or "text; 2." - # Bullet points are typically small numbers (1-999) at the end - bullet_match = re.search(r'(?:^|[\s;,]|[^\d])(\d{1,3})\.$', text) - if bullet_match: - # It's likely a bullet point, not a partial decimal - return False - - # Pattern to find decimal numbers near the end, allowing for trailing - # non-word characters like ), ], ", ', etc. - # Match: digit(s) + period + optional digit(s) + optional trailing non-word chars - match = re.search(r'\d+\.(?:\d+)?([^\w\s]*)$', text) - - if not match: - return False - - trailing = match.group(1) # e.g., ")" or "" or "." - - # If trailing contains a period, it's sentence-ending punctuation - # e.g., "3.14." means complete sentence - if '.' in trailing: - return False - - # Otherwise, it's a partial decimal (either incomplete like "3." - # or complete number but sentence not finished like "($3.14)") - return True - - -def find_last_period_index(text: str) -> int: - """ - Find the last occurrence of a period in the text, - but return -1 if the text doesn't seem to be a complete sentence. - """ - num_periods = text.count(".") - if num_periods == 0: - return -1 - - if num_periods == 1: - if has_partial_decimal(text): - # if the only period in the text is part of a number, return -1 - return -1 - # Check if the only period is a bullet point (e.g., "1. Alpha" or incomplete "1.") - if re.search(r'(?:^|[\s;,]|[^\d])(\d{1,3})\.(?:\s+\w|\s*$)', text): - # The period is after a bullet point number, either: - # - followed by content (e.g., "1. Alpha") - # - or at the end with optional whitespace (e.g., "1." or "1. ") - return -1 - - # Check if any of the abbreviations "e.", "i." "g.", "etc." are present in the text - if re.search(r'\b(e\.|i\.|g\.)\b', text): - # The period is after a character/word that is likely to be a abbreviation, return -1 - return -1 - - # otherwise, check the last occurrence of a period - idx = text.rfind(".") - if idx <= 0: - return idx - if text[idx - 1].isdigit(): - # if the period is after a digit, it's likely a partial decimal, return -1 - return -1 - elif text[idx - 1].isupper(): - # if the period is after a capital letter (e.g., "Washington, D.C."), it's likely a abbreviation, return -1 - return -1 - elif idx > 1 and text[idx - 2 : idx + 1].lower() in ["a.m.", "p.m."]: - # if the period is after a.m. or p.m., it's likely a time, return -1 - return -1 - elif idx > 2 and text[idx - 3 : idx + 1] in ["e.g.", "i.e.", "etc."]: - # The period is after a character/word that is likely to be a abbreviation, return -1 - return -1 - elif idx >= 2 and text[idx - 2 : idx + 1].lower() in ["st.", "mr.", "mrs.", "ms.", "dr."]: - # if the period is after a character/word that is likely to be a abbreviation, return -1 - return -1 - - # the text seems to have a complete sentence, return the index of the last period - return idx - - -def find_last_comma_index(text: str, min_residual_length: int = 5) -> int: - """ - Find the last occurrence of a valid comma in the text, - ignoring the commas in the numbers (e.g., "1,234,567"). - If the leftover text after the comma is too short, it may be an abbreviation, return -1. - - Args: - text: The text to find the last occurrence of a valid comma. - min_residual_length: The minimum length of the leftover text after the rightmost comma - to be considered as a valid sentence (e.g., "Santa Clara, CA, US."). - Returns: - The index of the last occurrence of a valid comma, or -1 if no valid comma is found. - """ - # find the last occurrence of a comma in the text - idx = text.rfind(",") - if idx == -1: - return -1 - # check if the comma is in a number - if re.search(r'\d+,\d+', text[: idx + 1]): - # the comma is in a number, return -1 - return -1 - - # check if the leftover text after the comma is too short - if len(text[idx + 1 :]) <= min_residual_length: - # the leftover text is too short, it may be an abbreviation, return -1 - return -1 - - # the comma is not in a number, return the index of the comma - return idx - - -class SimpleSegmentedTextAggregator(SimpleTextAggregator): - """A simple text aggregator that segments the text into sentences based on punctuation marks.""" - - def __init__( - self, - punctuation_marks: str | list[str] = ".,!?;:\n", - ignore_marks: str | list[str] = "*", - min_sentence_length: int = 0, - use_legacy_eos_detection: bool = False, - **kwargs, - ): - """ - Args: - punctuation_marks: The punctuation marks to use for sentence detection. - ignore_marks: The strings to ignore in the text (e.g., "*"). - min_sentence_length: The minimum length of a sentence to be considered. - use_legacy_eos_detection: Whether to use the legacy EOS detection from pipecat. - **kwargs: Additional arguments to pass to the SimpleTextAggregator constructor. - """ - super().__init__(**kwargs) - self._use_legacy_eos_detection = use_legacy_eos_detection - self._min_sentence_length = min_sentence_length - self._ignore_marks = set(["*"] if ignore_marks is None else set(ignore_marks)) - if not punctuation_marks: - self._punctuation_marks = list() - else: - punctuation_marks = ( - [c for c in punctuation_marks] if isinstance(punctuation_marks, str) else punctuation_marks - ) - if "." in punctuation_marks: - punctuation_marks.remove(".") - # put period at the end of the list to ensure it's the last punctuation mark to be matched - punctuation_marks += ["."] - self._punctuation_marks = punctuation_marks - - def _find_segment_end(self, text: str) -> Optional[int]: - """find the end of text segment. - - Args: - text: The text to find the end of the segment. - - Returns: - The index of the end of the segment, or None if the text is too short. - """ - # drop leading whitespace but keep trailing whitespace to - # allow "\n" to trigger the end of the sentence - text_len = len(text) - text = text.lstrip() - offset = text_len - len(text) - if len(text) < self._min_sentence_length: - return None - - for punc in self._punctuation_marks: - if punc == ".": - idx = find_last_period_index(text) - elif punc == ",": - idx = find_last_comma_index(text) - else: - idx = text.find(punc) - if idx != -1: - # add the offset to the index to account for the leading whitespace - return idx + 1 + offset - return None - - async def aggregate(self, text: str) -> AsyncIterator[Aggregation]: - """Aggregate the input text and return the first complete sentence in the text. - - Args: - text: The text to aggregate. - - Returns: - The first complete sentence in the text, or None if none is found. - """ - result: Optional[str] = None - self._text += str(text) - - eos_end_index = self._find_segment_end(self._text) - - if not eos_end_index and not has_partial_decimal(self._text) and self._use_legacy_eos_detection: - # if the text doesn't have partial decimal, and no punctuation marks, - # we use match_endofsentence to find the end of the sentence - eos_end_index = match_endofsentence(self._text) - - if eos_end_index: - result = self._text[:eos_end_index] - if len(result.strip()) < self._min_sentence_length: - logger.debug( - f"Text is too short, skipping: `{result}`, full text: `{self._text}`, input text: `{text}`" - ) - result = None - else: - logger.debug(f"Text Aggregator Result: `{result}`, full text: `{self._text}`, input text: `{text}`") - self._text = self._text[eos_end_index:] - - if result: - for ignore_mark in self._ignore_marks: - result = result.replace(ignore_mark, "") - yield Aggregation(text=result, type=AggregationType.SENTENCE) diff --git a/nemo/agents/voice_agent/utils/__init__.py b/nemo/agents/voice_agent/utils/__init__.py deleted file mode 100644 index 928a5f56cce66a05563e4a8c5fab0d0a704e1d98..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/utils/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.agents.voice_agent.utils.config_manager import ConfigManager diff --git a/nemo/agents/voice_agent/utils/config_manager.py b/nemo/agents/voice_agent/utils/config_manager.py deleted file mode 100644 index 15e8a09bb2429ae5cd11b4f18bd2134eac5ca60e..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/utils/config_manager.py +++ /dev/null @@ -1,312 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os -from typing import Any, Dict, Optional - -from loguru import logger -from omegaconf import OmegaConf -from pipecat.audio.vad.silero import VADParams - -from nemo.agents.voice_agent.pipecat.services.nemo.diar import NeMoDiarInputParams -from nemo.agents.voice_agent.pipecat.services.nemo.stt import NeMoSTTInputParams - - -class ConfigManager: - """ - Manages configuration for the voice agent server. - Handles loading, merging, and providing access to all configuration parameters. - """ - - def __init__(self, server_base_path: str, server_config_path: Optional[str] = None): - """ - Initialize the configuration manager. - - Args: - config_path: Path to the main server configuration file. - If None, uses default path from environment variable. - """ - if not os.path.exists(server_base_path): - raise FileNotFoundError(f"Server base path not found at {server_base_path}") - - self._server_base_path = server_base_path - if server_config_path is not None: - self._server_config_path = server_config_path - else: - self._server_config_path = f"{os.path.abspath(self._server_base_path)}/server_configs/default.yaml" - - if not os.path.exists(self._server_config_path): - raise FileNotFoundError(f"Server configuration file not found at {self._server_config_path}") - - # Load model registry - self.model_registry_path = f"{os.path.abspath(self._server_base_path)}/model_registry.yaml" - self.model_registry = self._load_model_registry() - - # Load and process main configuration - self.server_config = self._load_server_config() - - # Initialize configuration parameters - self._initialize_config_parameters() - - self._generic_hf_llm_model_id = "hf_llm_generic" - - logger.info(f"Configuration loaded from: {self._server_config_path}") - logger.info(f"Model registry loaded from: {self.model_registry_path}") - - def _load_model_registry(self) -> Dict[str, Any]: - """Load model registry from YAML file.""" - try: - return OmegaConf.load(self.model_registry_path) - except Exception as e: - logger.error(f"Failed to load model registry: {e}") - raise ValueError(f"Failed to load model registry: {e}") - - def _load_server_config(self) -> OmegaConf: - """Load and process the main server configuration.""" - server_config = OmegaConf.load(self._server_config_path) - server_config = OmegaConf.to_container(server_config, resolve=True) - server_config = OmegaConf.create(server_config) - return server_config - - def _initialize_config_parameters(self): - """Initialize all configuration parameters from the loaded config.""" - # Default constants - self.SAMPLE_RATE = 16000 - self.RAW_AUDIO_FRAME_LEN_IN_SECS = 0.016 - self.SYSTEM_PROMPT = " ".join( - [ - "You are a helpful AI agent named Lisa.", - "Begin by warmly greeting the user and introducing yourself in one sentence.", - "Keep your answers concise and to the point.", - ] - ) - - # Transport configuration - self.TRANSPORT_AUDIO_OUT_10MS_CHUNKS = self.server_config.transport.audio_out_10ms_chunks - - # VAD configuration - self.vad_params = VADParams( - confidence=self.server_config.vad.confidence, - start_secs=self.server_config.vad.start_secs, - stop_secs=self.server_config.vad.stop_secs, - min_volume=self.server_config.vad.min_volume, - ) - # STT configuration - self._configure_stt() - - # Diarization configuration - self._configure_diarization() - - # Turn taking configuration - self._configure_turn_taking() - - # LLM configuration - self._configure_llm() - - # TTS configuration - self._configure_tts() - - def _configure_stt(self): - """Configure STT parameters.""" - self.STT_MODEL = self.server_config.stt.model - self.STT_DEVICE = self.server_config.stt.device - # Apply STT-specific configuration based on model type - # Try to get STT config file name from server config first - if self.server_config.stt.get("model_config", None) is not None: - yaml_file_name = os.path.basename(self.server_config.stt.model_config) - else: - # Get STT configuration from registry - if str(self.STT_MODEL).endswith(".nemo"): - model_name = os.path.splitext(os.path.basename(self.STT_MODEL))[0] - else: - model_name = self.STT_MODEL - if model_name in self.model_registry.stt_models: - yaml_file_name = self.model_registry.stt_models[model_name].yaml_id - else: - error_msg = f"STT model {model_name} is not in model registry: {self.model_registry.stt_models}." - logger.error(error_msg) - raise ValueError(error_msg) - - stt_config_path = f"{os.path.abspath(self._server_base_path)}/server_configs/stt_configs/{yaml_file_name}" - if not os.path.exists(stt_config_path): - raise FileNotFoundError(f"STT config file not found at {stt_config_path}") - stt_config = OmegaConf.load(stt_config_path) - - # merge stt config with server config - for key in stt_config: - if key in self.server_config.stt and self.server_config.stt[key] != stt_config[key]: - logger.info( - f"STT config field `{key}` is overridden from `{self.server_config.stt[key]}` " - f"to `{stt_config[key]}` by {stt_config_path}" - ) - self.server_config.stt[key] = stt_config[key] - - logger.info(f"Final STT config: {self.server_config.stt}") - - audio_chunk_size_in_secs = self.server_config.stt.get("audio_chunk_size_in_secs", 0.08) - buffer_size = audio_chunk_size_in_secs // self.RAW_AUDIO_FRAME_LEN_IN_SECS - self.stt_params = NeMoSTTInputParams( - att_context_size=self.server_config.stt.att_context_size, - frame_len_in_secs=self.server_config.stt.frame_len_in_secs, - raw_audio_frame_len_in_secs=self.RAW_AUDIO_FRAME_LEN_IN_SECS, - buffer_size=buffer_size, - ) - - def _configure_diarization(self): - """ - Configure diarization parameters. - Currently only NeMo End-to-End Diarization is supported. - """ - self.DIAR_MODEL = self.server_config.diar.model - self.USE_DIAR = self.server_config.diar.enabled - self.diar_params = NeMoDiarInputParams( - frame_len_in_secs=self.server_config.diar.frame_len_in_secs, - threshold=self.server_config.diar.threshold, - ) - - def _configure_turn_taking(self): - """Configure turn taking parameters.""" - self.TURN_TAKING_BACKCHANNEL_PHRASES_PATH = self.server_config.turn_taking.backchannel_phrases_path - self.TURN_TAKING_MAX_BUFFER_SIZE = self.server_config.turn_taking.max_buffer_size - self.TURN_TAKING_BOT_STOP_DELAY = self.server_config.turn_taking.bot_stop_delay - - def _configure_llm(self): - """Configure LLM parameters.""" - llm_model_id = self.server_config.llm.model - is_registry_model = False - - # Try to get LLM config file name from server config first - if self.server_config.llm.get("model_config", None) is not None: - yaml_file_name = os.path.basename(self.server_config.llm.model_config) - else: - # Get LLM configuration from registry - if llm_model_id in self.model_registry.llm_models: - yaml_file_name = self.model_registry.llm_models[llm_model_id].yaml_id - is_registry_model = True - else: - logger.warning( - f"LLM model {llm_model_id} is not included in the model registry. " - "Using a generic HuggingFace LLM config instead." - ) - yaml_file_name = self.model_registry.llm_models[self._generic_hf_llm_model_id].yaml_id - - # Load and merge LLM configuration - llm_config_path = f"{os.path.abspath(self._server_base_path)}/server_configs/llm_configs/{yaml_file_name}" - - if ( - is_registry_model - and self.model_registry.llm_models[llm_model_id].get("reasoning_supported", False) - and self.server_config.llm.get("enable_reasoning", False) - ): - llm_config_path = llm_config_path.replace(".yaml", "_think.yaml") - - if not os.path.exists(llm_config_path): - raise FileNotFoundError(f"LLM config file not found at {llm_config_path}") - logger.info(f"Loading LLM config from: {llm_config_path}") - - llm_config = OmegaConf.load(llm_config_path) - # merge llm config with server config - # print the override keys - for key in llm_config: - if key in self.server_config.llm and self.server_config.llm[key] != llm_config[key]: - logger.info( - f"LLM config field `{key}` is overridden from `{self.server_config.llm[key]}` to " - f"`{llm_config[key]}` by {llm_config_path}" - ) - self.server_config.llm[key] = llm_config[key] - - logger.info(f"Final LLM config: {self.server_config.llm}") - - # Configure system prompt - self.SYSTEM_ROLE = self.server_config.llm.get("system_role", "system") - if self.server_config.llm.get("system_prompt", None) is not None: - system_prompt = self.server_config.llm.system_prompt - if os.path.isfile(system_prompt): - with open(system_prompt, "r") as f: - system_prompt = f.read() - self.SYSTEM_PROMPT = system_prompt - else: - logger.info(f"No system prompt provided, using default system prompt: {self.SYSTEM_PROMPT}") - - if self.server_config.llm.get("system_prompt_suffix", None) is not None: - self.SYSTEM_PROMPT += "\n" + self.server_config.llm.system_prompt_suffix - logger.info(f"Adding system prompt suffix: {self.server_config.llm.system_prompt_suffix}") - - logger.info(f"System prompt: {self.SYSTEM_PROMPT}") - - def _configure_tts(self): - """Configure TTS parameters.""" - tts_model_id = self.server_config.tts.model - - # Try to get TTS config file name from server config first - if self.server_config.tts.get("model_config", None) is not None: - yaml_file_name = os.path.basename(self.server_config.tts.model_config) - else: - # Get TTS configuration from registry - if tts_model_id in self.model_registry.tts_models: - yaml_file_name = self.model_registry.tts_models[tts_model_id].yaml_id - else: - error_msg = f"TTS model {tts_model_id} is not in model registry: {self.model_registry.tts_models}" - logger.error(error_msg) - raise ValueError(error_msg) - - tts_config_path = f"{os.path.abspath(self._server_base_path)}/server_configs/tts_configs/{yaml_file_name}" - if not os.path.exists(tts_config_path): - raise FileNotFoundError(f"Default TTS config file not found at {tts_config_path}") - tts_config = OmegaConf.load(tts_config_path) - - # merge tts config with server config - for key in tts_config: - if key in self.server_config.tts and self.server_config.tts[key] != tts_config[key]: - logger.info( - f"TTS config field `{key}` is overridden from `{self.server_config.tts[key]}` to " - f"`{tts_config[key]}` by {tts_config_path}" - ) - self.server_config.tts[key] = tts_config[key] - - logger.info(f"Final TTS config: {self.server_config.tts}") - - # Extract TTS parameters - self.TTS_MAIN_MODEL_ID = self.server_config.tts.get("main_model_id", None) - self.TTS_SUB_MODEL_ID = self.server_config.tts.get("sub_model_id", None) - self.TTS_DEVICE = self.server_config.tts.get("device", None) - - # Handle optional TTS parameters - self.TTS_THINK_TOKENS = self.server_config.tts.get("think_tokens", None) - if self.TTS_THINK_TOKENS is not None: - self.TTS_THINK_TOKENS = OmegaConf.to_container(self.TTS_THINK_TOKENS) - - self.TTS_EXTRA_SEPARATOR = self.server_config.tts.get("extra_separator", None) - if self.TTS_EXTRA_SEPARATOR is not None: - self.TTS_EXTRA_SEPARATOR = OmegaConf.to_container(self.TTS_EXTRA_SEPARATOR) - - def get_server_config(self) -> OmegaConf: - """Get the complete server configuration.""" - return self.server_config - - def get_model_registry(self) -> Dict[str, Any]: - """Get the model registry configuration.""" - return self.model_registry - - def get_vad_params(self) -> VADParams: - """Get VAD parameters.""" - return self.vad_params - - def get_stt_params(self) -> NeMoSTTInputParams: - """Get STT parameters.""" - return self.stt_params - - def get_diar_params(self) -> NeMoDiarInputParams: - """Get diarization parameters.""" - return self.diar_params diff --git a/nemo/agents/voice_agent/utils/tool_calling/__init__.py b/nemo/agents/voice_agent/utils/tool_calling/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/utils/tool_calling/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/agents/voice_agent/utils/tool_calling/basic_tools.py b/nemo/agents/voice_agent/utils/tool_calling/basic_tools.py deleted file mode 100644 index 6e35af85273c48cda5c83b59f7b24ceb17db8f13..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/utils/tool_calling/basic_tools.py +++ /dev/null @@ -1,72 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import asyncio -import python_weather -from loguru import logger -from pipecat.frames.frames import LLMTextFrame, TTSSpeakFrame -from pipecat.processors.frame_processor import FrameDirection -from pipecat.services.llm_service import FunctionCallParams - -HTTP_REQUEST_TIMEOUT = 10.0 - - -async def tool_get_city_weather(params: FunctionCallParams, city_name: str): - """Get the current weather of a city. The result includes city name, weather description, - temperature, wind speed, wind direction, precipitation, humidity, visibility, and UV index. - - Args: - city_name: The name of the city to get the weather of. For example, "London", "Beijing", "Paris". - Other examples are: "Paris, TX, US", "Paris, FR" and "Tokyo, JP". - """ - message = f"Looking up weather data for {city_name}. Please wait a moment..." - # Send the message to upstream so that RTVI can log it while doesn't block the actual tool call. - await params.llm.push_frame(LLMTextFrame(message), direction=FrameDirection.UPSTREAM) - # Send the message to TTS directly so that the user can hear it immediately. - await params.llm.push_frame(TTSSpeakFrame(message)) - - # The measuring unit defaults to metric (Celsius) - # Use imperial for Fahrenheit: python_weather.IMPERIAL - async with python_weather.Client(unit=python_weather.METRIC) as client: - # Fetch a weather forecast from a city - logger.debug(f"Fetching weather forecast for `{city_name}`") - try: - weather: python_weather.Forecast = await asyncio.wait_for( - client.get(city_name), - timeout=HTTP_REQUEST_TIMEOUT, - ) - except asyncio.TimeoutError: - error_msg = f"python_weather API request timed out after {HTTP_REQUEST_TIMEOUT} seconds for `{city_name}`" - logger.error(error_msg) - await params.result_callback({"error": error_msg}) - return - except Exception as e: - error_msg = f"Error fetching weather forecast for `{city_name}`: {str(e)}" - logger.error(error_msg) - await params.result_callback({"error": error_msg}) - return - - results = { - "city": city_name, - "description": str(weather.description), - "temperature": f"{weather.temperature} degrees Celsius", - "wind_speed": f"{weather.wind_speed} kilometers per hour", - "wind_direction": str(weather.wind_direction.name), - "precipitation": f"{weather.precipitation} millimeters", - "humidity": f"{weather.humidity} percent", - "visibility": f"{weather.visibility} kilometers", - "uv_index": str(weather.ultraviolet), - } - logger.debug(f"Weather results for {city_name}: {results}") - await params.result_callback(results) diff --git a/nemo/agents/voice_agent/utils/tool_calling/mixins.py b/nemo/agents/voice_agent/utils/tool_calling/mixins.py deleted file mode 100644 index 1024c6dad681d52c8dd9a7c710ae3983646362a1..0000000000000000000000000000000000000000 --- a/nemo/agents/voice_agent/utils/tool_calling/mixins.py +++ /dev/null @@ -1,104 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from loguru import logger -from pipecat.adapters.schemas.direct_function import DirectFunction -from pipecat.adapters.schemas.tools_schema import ToolsSchema -from pipecat.processors.aggregators.openai_llm_context import OpenAILLMContext -from pipecat.services.openai.llm import OpenAILLMService - - -class ToolCallingMixin: - """ - A mixin class for tool calling. - Subclasses must implement the `setup_tool_calling` method to register all available tools - using `self.register_direct_function()`. Then the `__init__` method of the subclass should - call the `setup_tool_calling` method to register the tools. - """ - - def setup_tool_calling(self): - """ - Setup the tool calling mixin by registering all available tools using self.register_direct_function(). - """ - raise NotImplementedError( - "Subclasses must implement this method to register all available functions " - "using self.register_direct_function()" - ) - - def register_direct_function(self, function_name: str, function: DirectFunction): - """ - Register a direct function to be called by the LLM. - - Args: - function_name: The name of the function to register. - function: The direct function to register. - """ - if not hasattr(self, "direct_functions"): - self.direct_functions = {} - logger.info( - f"[{self.__class__.__name__}] Registering direct function name {function_name} to " - f"{function.__module__ + '.' + function.__qualname__}" - ) - self.direct_functions[function_name] = function - - @property - def available_tools(self) -> dict[str, DirectFunction]: - """ - Return a dictionary of available tools, where the key is the tool name and the value is the direct function. - """ - tools = {} - for function_name, function in self.direct_functions.items(): - tools[function_name] = function - return tools - - -def register_direct_tools_to_llm( - *, - llm: OpenAILLMService, - context: OpenAILLMContext, - tool_mixins: list[ToolCallingMixin] = [], - tools: list[DirectFunction] = [], - cancel_on_interruption: bool = True, -) -> None: - """ - Register direct tools to the LLM. - Args: - llm: The LLM service to use. - context: The LLM context to use. - tools: The list of tools (instances of either `DirectFunction` or `ToolCallingMixin`) to use. - """ - all_tools = [] - for tool in tool_mixins: - if not isinstance(tool, ToolCallingMixin): - logger.warning(f"Tool {tool.__class__.__name__} is not a ToolCallingMixin, skipping.") - continue - for function_name, function in tool.available_tools.items(): - logger.info(f"Registering direct function {function_name} from {tool.__class__.__name__}") - all_tools.append(function) - - for tool in tools: - logger.info(f"Registering direct function: {tool.__module__ + '.' + tool.__qualname__}") - all_tools.append(tool) - - if not all_tools: - logger.warning("No direct tools provided.") - return - else: - logger.info(f"Registering {len(all_tools)} direct tools to the LLM.") - - tools_schema = ToolsSchema(standard_tools=all_tools) - context.set_tools(tools_schema) - - for tool in all_tools: - llm.register_direct_function(tool, cancel_on_interruption=cancel_on_interruption) diff --git a/nemo/collections/__init__.py b/nemo/collections/__init__.py deleted file mode 100644 index 9e3250071955216f6abc505e6181fb59931baa8d..0000000000000000000000000000000000000000 --- a/nemo/collections/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/asr/README.md b/nemo/collections/asr/README.md deleted file mode 100644 index 27f9472f1ac8963f51c05b9679b2737b3b7daa07..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/README.md +++ /dev/null @@ -1,37 +0,0 @@ -# Automatic Speech Recognition (ASR) - -## Key Features - -* [HuggingFace Space for Audio Transcription (File, Microphone and YouTube)](https://huggingface.co/spaces/smajumdar/nemo_multilingual_language_id) -* [Pretrained models](https://ngc.nvidia.com/catalog/collections/nvidia:nemo_asr) available in 14+ languages -* [Automatic Speech Recognition (ASR)](https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/main/asr/intro.html) - * Supported ASR [models](https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/stable/asr/models.html): - * Jasper, QuartzNet, CitriNet, ContextNet - * Conformer-CTC, Conformer-Transducer, FastConformer-CTC, FastConformer-Transducer - * Squeezeformer-CTC and Squeezeformer-Transducer - * LSTM-Transducer (RNNT) and LSTM-CTC - * Supports the following decoders/losses: - * CTC - * Transducer/RNNT - * Hybrid Transducer/CTC - * NeMo Original [Multi-blank Transducers](https://arxiv.org/abs/2211.03541) and [Token-and-Duration Transducers (TDT)](https://arxiv.org/abs/2304.06795) - * Streaming/Buffered ASR (CTC/Transducer) - [Chunked Inference Examples](https://github.com/NVIDIA/NeMo/tree/stable/examples/asr/asr_chunked_inference) - * [Cache-aware Streaming Conformer](https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/stable/asr/models.html#cache-aware-streaming-conformer) with multiple lookaheads (including microphone streaming [tutorial](https://github.com/NVIDIA/NeMo/blob/main/tutorials/asr/Online_ASR_Microphone_Demo_Cache_Aware_Streaming.ipynb). - * Beam Search decoding - * [Language Modelling for ASR (CTC and RNNT)](https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/main/asr/asr_language_modeling.html): N-gram LM in fusion with Beam Search decoding, Neural Rescoring with Transformer - * [Support of long audios for Conformer with memory efficient local attention](https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/main/asr/results.html#inference-on-long-audio) -* [Speech Classification, Speech Command Recognition and Language Identification](https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/main/asr/speech_classification/intro.html): MatchboxNet (Command Recognition), AmberNet (LangID) -* [Voice activity Detection (VAD)](https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/stable/asr/speech_classification/models.html#marblenet-vad): MarbleNet - * ASR with VAD Inference - [Example](https://github.com/NVIDIA/NeMo/tree/stable/examples/asr/asr_vad) -* [Speaker Recognition](https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/main/asr/speaker_recognition/intro.html): TitaNet, ECAPA_TDNN, SpeakerNet -* [Speaker Diarization](https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/main/asr/speaker_diarization/intro.html) - * Clustering Diarizer: TitaNet, ECAPA_TDNN, SpeakerNet - * Neural Diarizer: Sortformer -* [Speech Intent Detection and Slot Filling](https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/main/asr/speech_intent_slot/intro.html): Conformer-Transformer - -You can also get a high-level overview of NeMo ASR by watching the talk *NVIDIA NeMo: Toolkit for Conversational AI*, presented at PyData Yerevan 2022: - - -[![NVIDIA NeMo: Toolkit for Conversational AI](https://img.youtube.com/vi/J-P6Sczmas8/maxres3.jpg -)](https://www.youtube.com/embed/J-P6Sczmas8?mute=0&start=14&autoplay=0 - "NeMo presentation at PyData@Yerevan 2022") diff --git a/nemo/collections/asr/__init__.py b/nemo/collections/asr/__init__.py deleted file mode 100644 index cd14a4395006b23564424aa7d2f90a1069d5894f..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/__init__.py +++ /dev/null @@ -1,25 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.asr import data, losses, models, modules -from nemo.package_info import __version__ - -# Set collection version equal to NeMo version. -__version = __version__ - -# Authorship. -__author__ = "NVIDIA Corporation" - -# Set collection name. -__description__ = "Automatic Speech Recognition collection" diff --git a/nemo/collections/asr/data/__init__.py b/nemo/collections/asr/data/__init__.py deleted file mode 100644 index 9e3250071955216f6abc505e6181fb59931baa8d..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/data/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/asr/data/audio_to_ctm_dataset.py b/nemo/collections/asr/data/audio_to_ctm_dataset.py deleted file mode 100644 index 54503053ae367d2f84a9fdc055699371809dc88c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/data/audio_to_ctm_dataset.py +++ /dev/null @@ -1,95 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import json -import os -from dataclasses import dataclass -from pathlib import Path -from typing import Any, List, Tuple - -from nemo.collections.asr.data.audio_to_text_dataset import ASRPredictionWriter -from nemo.utils import logging - - -@dataclass -class FrameCtmUnit: - """A container class for one CTM unit with start and length countable in frames. - """ - - label: str - start_frame: int - length: int - probability: float - - def __repr__(self) -> str: - return f"{self.label}\t({self.probability:1.3f}): [{self.start_frame:6d}, {self.length:6d}]" - - @property - def end_frame(self): - return self.start_frame + self.length - - def to_ctm_str(self, time_per_frame: int) -> str: - """Represents the data as part of the CTM line. - - The CTM line format is - - This method prepares the last four entities.""" - return f"{self.start_frame * time_per_frame :.3f} {self.length * time_per_frame :.3f} {self.label} {self.probability :1.3f}" - - -class ASRCTMPredictionWriter(ASRPredictionWriter): - def __init__(self, dataset, output_file: str, output_ctm_dir: str, time_per_frame: float): - super().__init__(dataset, output_file) - self.output_ctm_dir = output_ctm_dir - self.time_per_frame = time_per_frame - os.makedirs(self.output_ctm_dir, exist_ok=True) - - def write_ctm(self, name, filepath, frameCtmUnits): - with open(filepath, "tw", encoding="utf-8") as f: - for unit in frameCtmUnits: - f.write(f"{name} 1 {unit.to_ctm_str(self.time_per_frame)}\n") - - def write_on_batch_end( - self, - trainer, - pl_module: 'LightningModule', - prediction: Tuple[int, List[FrameCtmUnit]], - batch_indices: List[int], - batch: Any, - batch_idx: int, - dataloader_idx: int, - ): - for sample_id, units in prediction: - sample = self.dataset.get_manifest_sample(sample_id) - with_ctm = True - if len(units) == 0: - logging.warning( - f"""Do not producing CTM output for item `{sample.audio_file}`. - Check if text is empty or if duration is too short: `{sample.text_raw}`, {sample.duration}""" - ) - with_ctm = False - item = {} - item["audio_filepath"] = sample.audio_file - item["duration"] = sample.duration - item["text"] = sample.text_raw - if with_ctm: - utt_name = Path(sample.audio_file).stem - ctm_filepath = os.path.join(self.output_ctm_dir, utt_name) + ".ctm" - self.write_ctm(utt_name, ctm_filepath, units) - item["ctm_filepath"] = ctm_filepath - else: - item["ctm_filepath"] = "" - self.outf.write(json.dumps(item) + "\n") - self.samples_num += 1 - return diff --git a/nemo/collections/asr/data/audio_to_diar_label.py b/nemo/collections/asr/data/audio_to_diar_label.py deleted file mode 100644 index 72781b4a10bf9fc90fd6a3312a03b1027640b849..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/data/audio_to_diar_label.py +++ /dev/null @@ -1,562 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os -from typing import Dict, List, Optional, Tuple - -import numpy as np -import torch - -from nemo.collections.asr.parts.utils.speaker_utils import convert_rttm_line, get_subsegments -from nemo.collections.common.parts.preprocessing.collections import EndtoEndDiarizationSpeechLabel -from nemo.core.classes import Dataset -from nemo.core.neural_types import AudioSignal, LengthsType, NeuralType, ProbsType -from nemo.utils import logging - - -def get_subsegments_to_timestamps( - subsegments: List[Tuple[float, float]], feat_per_sec: int = 100, max_end_ts: float = None, decimals=2 -): - """ - Convert subsegment timestamps to scale timestamps by multiplying with the feature rate (`feat_per_sec`) - and rounding. Segment is consisted of many subsegments and sugsegments are equivalent to `frames` - in end-to-end speaker diarization models. - - Args: - subsegments (List[Tuple[float, float]]): - A list of tuples where each tuple contains the start and end times of a subsegment - (frames in end-to-end models). - >>> subsegments = [[t0_start, t0_duration], [t1_start, t1_duration],..., [tN_start, tN_duration]] - feat_per_sec (int, optional): - The number of feature frames per second. Defaults to 100. - max_end_ts (float, optional): - The maximum end timestamp to clip the results. If None, no clipping is applied. Defaults to None. - decimals (int, optional): - The number of decimal places to round the timestamps. Defaults to 2. - - Example: - Segments starting from 0.0 and ending at 69.2 seconds. - If hop-length is 0.08 and the subsegment (frame) length is 0.16 seconds, - there are 864 = (69.2 - 0.16)/0.08 + 1 subsegments (frames in end-to-end models) in this segment. - >>> subsegments = [[[0.0, 0.16], [0.08, 0.16], ..., [69.04, 0.16], [69.12, 0.08]] - - Returns: - ts (torch.tensor): - A tensor containing the scaled and rounded timestamps for each subsegment. - """ - seg_ts = (torch.tensor(subsegments) * feat_per_sec).float() - ts_round = torch.round(seg_ts, decimals=decimals) - ts = ts_round.long() - ts[:, 1] = ts[:, 0] + ts[:, 1] - if max_end_ts is not None: - ts = np.clip(ts, 0, int(max_end_ts * feat_per_sec)) - return ts - - -def extract_frame_info_from_rttm(offset, duration, rttm_lines, round_digits=3): - """ - Extracts RTTM lines containing speaker labels, start time, and end time for a given audio segment. - - Args: - uniq_id (str): Unique identifier for the audio file and corresponding RTTM file. - offset (float): The starting time offset for the segment of interest. - duration (float): The duration of the segment of interest. - rttm_lines (list): List of RTTM lines in string format. - round_digits (int, optional): Number of decimal places to round the start and end times. Defaults to 3. - - Returns: - rttm_mat (tuple): A tuple containing lists of start times, end times, and speaker labels. - sess_to_global_spkids (dict): A mapping from session-specific speaker indices to global speaker identifiers. - """ - rttm_stt, rttm_end = offset, offset + duration - stt_list, end_list, speaker_list, speaker_set = [], [], [], [] - sess_to_global_spkids = dict() - - for rttm_line in rttm_lines: - start, end, speaker = convert_rttm_line(rttm_line) - - # Skip invalid RTTM lines where the start time is greater than the end time. - if start > end: - continue - - # Check if the RTTM segment overlaps with the specified segment of interest. - if (end > rttm_stt and start < rttm_end) or (start < rttm_end and end > rttm_stt): - # Adjust the start and end times to fit within the segment of interest. - start, end = max(start, rttm_stt), min(end, rttm_end) - else: - continue - - # Round the start and end times to the specified number of decimal places. - end_list.append(round(end, round_digits)) - stt_list.append(round(start, round_digits)) - - # Assign a unique index to each speaker and maintain a mapping. - if speaker not in speaker_set: - speaker_set.append(speaker) - speaker_list.append(speaker_set.index(speaker)) - sess_to_global_spkids.update({speaker_set.index(speaker): speaker}) - - rttm_mat = (stt_list, end_list, speaker_list) - return rttm_mat, sess_to_global_spkids - - -def get_frame_targets_from_rttm( - rttm_timestamps: list, - offset: float, - duration: float, - round_digits: int, - feat_per_sec: int, - max_spks: int, -): - """ - Create a multi-dimensional vector sequence containing speaker timestamp information in RTTM. - The unit-length is the frame shift length of the acoustic feature. The feature-level annotations - `feat_level_target` will later be converted to base-segment level diarization label. - - Args: - rttm_timestamps (list): - List containing start and end time for each speaker segment label. - stt_list, end_list and speaker_list are contained. - feat_per_sec (int): - Number of feature frames per second. - This quantity is determined by window_stride variable in preprocessing module. - target_spks (tuple): - Speaker indices that are generated from combinations. If there are only one or two speakers, - only a single target_spks variable is generated. - - Returns: - feat_level_target (torch.tensor): - Tensor containing label for each feature level frame. - """ - stt_list, end_list, speaker_list = rttm_timestamps - sorted_speakers = sorted(list(set(speaker_list))) - total_fr_len = int(duration * feat_per_sec) - if len(sorted_speakers) > max_spks: - logging.warning( - f"Number of speakers in RTTM file {len(sorted_speakers)} exceeds the maximum number of speakers: " - f"{max_spks}! Only {max_spks} first speakers remain, and this will affect frame metrics!" - ) - feat_level_target = torch.zeros(total_fr_len, max_spks) - for count, (stt, end, spk_rttm_key) in enumerate(zip(stt_list, end_list, speaker_list)): - if end < offset or stt > offset + duration: - continue - stt, end = max(offset, stt), min(offset + duration, end) - spk = spk_rttm_key - if spk < max_spks: - stt_fr, end_fr = int((stt - offset) * feat_per_sec), int((end - offset) * feat_per_sec) - feat_level_target[stt_fr:end_fr, spk] = 1 - return feat_level_target - - -class _AudioToSpeechE2ESpkDiarDataset(Dataset): - """ - Dataset class that loads a json file containing paths to audio files, - RTTM files and number of speakers. This Dataset class is designed for - training or fine-tuning speaker embedding extractor and diarization decoder - at the same time. - - Example: - {"audio_filepath": "/path/to/audio_0.wav", "num_speakers": 2, - "rttm_filepath": "/path/to/diar_label_0.rttm} - ... - {"audio_filepath": "/path/to/audio_n.wav", "num_speakers": 2, - "rttm_filepath": "/path/to/diar_label_n.rttm} - - Args: - manifest_filepath (str): - Path to input manifest json files. - multiargs_dict (dict): - Dictionary containing the parameters for multiscale segmentation and clustering. - soft_label_thres (float): - Threshold that determines the label of each segment based on RTTM file information. - featurizer: - Featurizer instance for generating audio_signal from the raw waveform. - window_stride (float): - Window stride for acoustic feature. This value is used for calculating the numbers of feature-level frames. - """ - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - """Returns definitions of module output ports.""" - output_types = { - "audio_signal": NeuralType(('B', 'T'), AudioSignal()), - "audio_length": NeuralType(('B'), LengthsType()), - "targets": NeuralType(('B', 'T', 'C'), ProbsType()), - "target_len": NeuralType(('B'), LengthsType()), - } - - return output_types - - def __init__( - self, - *, - manifest_filepath: str, - soft_label_thres: float, - session_len_sec: float, - num_spks: int, - featurizer, - fb_featurizer, - window_stride: float, - min_subsegment_duration: float = 0.03, - global_rank: int = 0, - dtype=torch.float16, - round_digits: int = 2, - soft_targets: bool = False, - subsampling_factor: int = 8, - device: str = 'cpu', - ): - super().__init__() - self.collection = EndtoEndDiarizationSpeechLabel( - manifests_files=manifest_filepath.split(','), - round_digits=round_digits, - ) - self.featurizer = featurizer - self.fb_featurizer = fb_featurizer - # STFT and subsampling factor parameters - self.n_fft = self.fb_featurizer.n_fft - self.hop_length = self.fb_featurizer.hop_length - self.stft_pad_amount = self.fb_featurizer.stft_pad_amount - self.subsampling_factor = subsampling_factor - # Annotation and target length parameters - self.round_digits = round_digits - self.feat_per_sec = int(1 / window_stride) - self.diar_frame_length = round(subsampling_factor * window_stride, round_digits) - self.session_len_sec = session_len_sec - self.soft_label_thres = soft_label_thres - self.max_spks = num_spks - self.min_subsegment_duration = min_subsegment_duration - self.dtype = dtype - self.use_asr_style_frame_count = True - self.soft_targets = soft_targets - self.round_digits = 2 - self.floor_decimal = 10**self.round_digits - self.device = device - self.global_rank = global_rank - - def __len__(self): - return len(self.collection) - - def get_frame_count_from_time_series_length(self, seq_len): - """ - This function is used to get the sequence length of the audio signal. This is required to match - the feature frame length with ASR (STT) models. This function is copied from - NeMo/nemo/collections/asr/parts/preprocessing/features.py::FilterbankFeatures::get_seq_len. - - Args: - seq_len (int): - The sequence length of the time-series data. - - Returns: - seq_len (int): - The sequence length of the feature frames. - """ - pad_amount = self.stft_pad_amount * 2 if self.stft_pad_amount is not None else self.n_fft // 2 * 2 - seq_len = torch.floor_divide((seq_len + pad_amount - self.n_fft), self.hop_length).to(dtype=torch.long) - frame_count = int(np.ceil(seq_len / self.subsampling_factor)) - return frame_count - - def get_uniq_id_with_range(self, sample, deci=3): - """ - Generate unique training sample ID from unique file ID, offset and duration. The start-end time added - unique ID is required for identifying the sample since multiple short audio samples are generated from a single - audio file. The start time and end time of the audio stream uses millisecond units if `deci=3`. - - Args: - sample: - `EndtoEndDiarizationSpeechLabel` instance from collections. - - Returns: - uniq_id (str): - Unique sample ID which includes start and end time of the audio stream. - Example: abc1001_3122_6458 - """ - bare_uniq_id = os.path.splitext(os.path.basename(sample.rttm_file))[0] - offset = str(int(round(sample.offset, deci) * pow(10, deci))) - endtime = str(int(round(sample.offset + sample.duration, deci) * pow(10, deci))) - uniq_id = f"{bare_uniq_id}_{offset}_{endtime}" - return uniq_id - - def parse_rttm_for_targets_and_lens(self, rttm_file, offset, duration, target_len): - """ - Generate target tensor variable by extracting groundtruth diarization labels from an RTTM file. - This function converts (start, end, speaker_id) format into base-scale (the finest scale) segment level - diarization label in a matrix form. - - Example of seg_target: - [[0., 1.], [0., 1.], [1., 1.], [1., 0.], [1., 0.], ..., [0., 1.]] - """ - if rttm_file in [None, '']: - num_seg = torch.max(target_len) - targets = torch.zeros(num_seg, self.max_spks) - return targets - - with open(rttm_file, 'r') as f: - rttm_lines = f.readlines() - - rttm_timestamps, sess_to_global_spkids = extract_frame_info_from_rttm(offset, duration, rttm_lines) - - fr_level_target = get_frame_targets_from_rttm( - rttm_timestamps=rttm_timestamps, - offset=offset, - duration=duration, - round_digits=self.round_digits, - feat_per_sec=self.feat_per_sec, - max_spks=self.max_spks, - ) - - soft_target_seg = self.get_soft_targets_seg(feat_level_target=fr_level_target, target_len=target_len) - if self.soft_targets: - step_target = soft_target_seg - else: - step_target = (soft_target_seg >= self.soft_label_thres).float() - return step_target - - def get_soft_targets_seg(self, feat_level_target, target_len): - """ - Generate the final targets for the actual diarization step. - Here, frame level means step level which is also referred to as segments. - We follow the original paper and refer to the step level as "frames". - - Args: - feat_level_target (torch.tensor): - Tensor variable containing hard-labels of speaker activity in each feature-level segment. - target_len (torch.tensor): - Numbers of ms segments - - Returns: - soft_target_seg (torch.tensor): - Tensor variable containing soft-labels of speaker activity in each step-level segment. - """ - num_seg = torch.max(target_len) - targets = torch.zeros(num_seg, self.max_spks) - stride = int(self.feat_per_sec * self.diar_frame_length) - for index in range(num_seg): - if index == 0: - seg_stt_feat = 0 - else: - seg_stt_feat = stride * index - 1 - int(stride / 2) - if index == num_seg - 1: - seg_end_feat = feat_level_target.shape[0] - else: - seg_end_feat = stride * index - 1 + int(stride / 2) - targets[index] = torch.mean(feat_level_target[seg_stt_feat : seg_end_feat + 1, :], axis=0) - return targets - - def get_segment_timestamps( - self, - duration: float, - offset: float = 0, - sample_rate: int = 16000, - ): - """ - Get start and end time of segments in each scale. - - Args: - sample: - `EndtoEndDiarizationSpeechLabel` instance from preprocessing.collections - Returns: - segment_timestamps (torch.tensor): - Tensor containing Multiscale segment timestamps. - target_len (torch.tensor): - Number of segments for each scale. This information is used for reshaping embedding batch - during forward propagation. - """ - subsegments = get_subsegments( - offset=offset, - window=round(self.diar_frame_length * 2, self.round_digits), - shift=self.diar_frame_length, - duration=duration, - min_subsegment_duration=self.min_subsegment_duration, - use_asr_style_frame_count=self.use_asr_style_frame_count, - sample_rate=sample_rate, - feat_per_sec=self.feat_per_sec, - ) - if self.use_asr_style_frame_count: - effective_dur = ( - np.ceil((1 + duration * sample_rate) / int(sample_rate / self.feat_per_sec)).astype(int) - / self.feat_per_sec - ) - else: - effective_dur = duration - ts_tensor = get_subsegments_to_timestamps( - subsegments, self.feat_per_sec, decimals=2, max_end_ts=(offset + effective_dur) - ) - target_len = torch.tensor([ts_tensor.shape[0]]) - return target_len - - def __getitem__(self, index): - sample = self.collection[index] - if sample.offset is None: - sample.offset = 0 - offset = sample.offset - if self.session_len_sec < 0: - session_len_sec = sample.duration - else: - session_len_sec = min(sample.duration, self.session_len_sec) - - audio_signal = self.featurizer.process(sample.audio_file, offset=offset, duration=session_len_sec) - - # We should resolve the length mis-match from the round-off errors between these two variables: - # `session_len_sec` and `audio_signal.shape[0]` - session_len_sec = ( - np.floor(audio_signal.shape[0] / self.featurizer.sample_rate * self.floor_decimal) / self.floor_decimal - ) - audio_signal = audio_signal[: round(self.featurizer.sample_rate * session_len_sec)] - audio_signal_length = torch.tensor(audio_signal.shape[0]).long() - - # Target length should be following the ASR feature extraction convention: Use self.get_frame_count_from_time_series_length. - target_len = self.get_segment_timestamps(duration=session_len_sec, sample_rate=self.featurizer.sample_rate) - target_len = torch.clamp(target_len, max=self.get_frame_count_from_time_series_length(audio_signal.shape[0])) - - targets = self.parse_rttm_for_targets_and_lens( - rttm_file=sample.rttm_file, offset=offset, duration=session_len_sec, target_len=target_len - ) - targets = targets[:target_len, :] - return audio_signal, audio_signal_length, targets, target_len - - -def _eesd_train_collate_fn(self, batch): - """ - Collate a batch of variables needed for training the end-to-end speaker diarization (EESD) model - from raw waveforms to diarization labels. The following variables are included in the training/validation batch: - - Args: - batch (tuple): - A tuple containing the variables for diarization training. - - Returns: - audio_signal (torch.Tensor): - A tensor containing the raw waveform samples (time series) loaded from the `audio_filepath` - in the input manifest file. - feature_length (torch.Tensor): - A tensor containing the lengths of the raw waveform samples. - targets (torch.Tensor): - Groundtruth speaker labels for the given input embedding sequence. - target_lens (torch.Tensor): - A tensor containing the number of segments for each sample in the batch, necessary for - reshaping inputs to the EESD model. - """ - packed_batch = list(zip(*batch)) - audio_signal, feature_length, targets, target_len = packed_batch - audio_signal_list, feature_length_list = [], [] - target_len_list, targets_list = [], [] - - max_raw_feat_len = max([x.shape[0] for x in audio_signal]) - max_target_len = max([x.shape[0] for x in targets]) - if max([len(feat.shape) for feat in audio_signal]) > 1: - max_ch = max([feat.shape[1] for feat in audio_signal]) - else: - max_ch = 1 - for feat, feat_len, tgt, segment_ct in batch: - seq_len = tgt.shape[0] - if len(feat.shape) > 1: - pad_feat = (0, 0, 0, max_raw_feat_len - feat.shape[0]) - else: - pad_feat = (0, max_raw_feat_len - feat.shape[0]) - if feat.shape[0] < feat_len: - feat_len_pad = feat_len - feat.shape[0] - feat = torch.nn.functional.pad(feat, (0, feat_len_pad)) - pad_tgt = (0, 0, 0, max_target_len - seq_len) - padded_feat = torch.nn.functional.pad(feat, pad_feat) - padded_tgt = torch.nn.functional.pad(tgt, pad_tgt) - if max_ch > 1 and padded_feat.shape[1] < max_ch: - feat_ch_pad = max_ch - padded_feat.shape[1] - padded_feat = torch.nn.functional.pad(padded_feat, (0, feat_ch_pad)) - audio_signal_list.append(padded_feat) - feature_length_list.append(feat_len.clone().detach()) - target_len_list.append(segment_ct.clone().detach()) - targets_list.append(padded_tgt) - audio_signal = torch.stack(audio_signal_list) - feature_length = torch.stack(feature_length_list) - target_lens = torch.stack(target_len_list).squeeze(1) - targets = torch.stack(targets_list) - return audio_signal, feature_length, targets, target_lens - - -class AudioToSpeechE2ESpkDiarDataset(_AudioToSpeechE2ESpkDiarDataset): - """ - Dataset class for loading a JSON file containing paths to audio files, - RTTM (Rich Transcription Time Marked) files, and the number of speakers. - This class is designed for training or fine-tuning a speaker embedding - extractor and diarization decoder simultaneously. - - The JSON manifest file should have entries in the following format: - - Example: - { - "audio_filepath": "/path/to/audio_0.wav", - "num_speakers": 2, - "rttm_filepath": "/path/to/diar_label_0.rttm" - } - ... - { - "audio_filepath": "/path/to/audio_n.wav", - "num_speakers": 2, - "rttm_filepath": "/path/to/diar_label_n.rttm" - } - - Args: - manifest_filepath (str): - Path to the input manifest JSON file containing paths to audio and RTTM files. - soft_label_thres (float): - Threshold for assigning soft labels to segments based on RTTM file information. - session_len_sec (float): - Duration of each session (in seconds) for training or fine-tuning. - num_spks (int): - Number of speakers in the audio files. - featurizer: - Instance of a featurizer for generating features from the raw waveform. - window_stride (float): - Window stride (in seconds) for extracting acoustic features, used to calculate - the number of feature frames. - global_rank (int): - Global rank of the current process (used for distributed training). - soft_targets (bool): - Whether or not to use soft targets during training. - - Methods: - eesd_train_collate_fn(batch): - Collates a batch of data for end-to-end speaker diarization training. - """ - - def __init__( - self, - *, - manifest_filepath: str, - soft_label_thres: float, - session_len_sec: float, - num_spks: int, - featurizer, - fb_featurizer, - window_stride, - global_rank: int, - soft_targets: bool, - device: str, - ): - super().__init__( - manifest_filepath=manifest_filepath, - soft_label_thres=soft_label_thres, - session_len_sec=session_len_sec, - num_spks=num_spks, - featurizer=featurizer, - fb_featurizer=fb_featurizer, - window_stride=window_stride, - global_rank=global_rank, - soft_targets=soft_targets, - device=device, - ) - - def eesd_train_collate_fn(self, batch): - """Collate a batch of data for end-to-end speaker diarization training.""" - return _eesd_train_collate_fn(self, batch) diff --git a/nemo/collections/asr/data/audio_to_diar_label_lhotse.py b/nemo/collections/asr/data/audio_to_diar_label_lhotse.py deleted file mode 100644 index e35780ec23eae5bbe42f3aece33ecac1115e70aa..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/data/audio_to_diar_label_lhotse.py +++ /dev/null @@ -1,114 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import Dict, Optional, Tuple - -import torch.utils.data -from lhotse.dataset import AudioSamples -from lhotse.dataset.collation import collate_matrices - -from nemo.collections.asr.parts.utils.asr_multispeaker_utils import ( - get_hidden_length_from_sample_length, - speaker_to_target, -) -from nemo.core.neural_types import AudioSignal, LabelsType, LengthsType, NeuralType -from nemo.utils import logging - - -class LhotseAudioToSpeechE2ESpkDiarDataset(torch.utils.data.Dataset): - """ - This dataset is a Lhotse version of diarization dataset in audio_to_diar_label.py. - Unlike native NeMo datasets, Lhotse dataset defines only the mapping from - a CutSet (meta-data) to a mini-batch with PyTorch tensors. - Specifically, it performs tokenization, I/O, augmentation, and feature extraction (if any). - Managing data, sampling, de-duplication across workers/nodes etc. is all handled - by Lhotse samplers instead. - """ - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - """Define the output types of the dataset.""" - return { - 'audio_signal': NeuralType(('B', 'T'), AudioSignal()), - 'a_sig_length': NeuralType(tuple('B'), LengthsType()), - 'targets': NeuralType(('B', 'T', 'N'), LabelsType()), - 'target_length': NeuralType(tuple('B'), LengthsType()), - 'sample_id': NeuralType(tuple('B'), LengthsType(), optional=True), - } - - def __init__(self, cfg): - super().__init__() - self.load_audio = AudioSamples(fault_tolerant=True) - self.cfg = cfg - self.num_speakers = self.cfg.get('num_speakers', 4) - self.num_sample_per_mel_frame = int( - self.cfg.get('window_stride', 0.01) * self.cfg.get('sample_rate', 16000) - ) # 160 samples for every 1ms by default - self.num_mel_frame_per_target_frame = int(self.cfg.get('subsampling_factor', 8)) - - def __getitem__(self, cuts) -> Tuple[torch.Tensor, ...]: - # NOTE: This end-to-end diarization dataloader only loads the 1st ch of the audio file. - # Process cuts in a single loop: convert to mono and compute speaker activities - mono_cuts = [] - speaker_activities = [] - for cut in cuts: - if cut.num_channels is not None and cut.num_channels > 1: - logging.warning( - "Multiple channels detected in cut '%s' (%d channels). " - "Only the first channel will be used; remaining channels are ignored.", - cut.id, - cut.num_channels, - ) - mono_cut = cut.with_channels(channels=[0]) - mono_cuts.append(mono_cut) - - speaker_activity = speaker_to_target( - a_cut=mono_cut, - num_speakers=self.num_speakers, - num_sample_per_mel_frame=self.num_sample_per_mel_frame, - num_mel_frame_per_asr_frame=self.num_mel_frame_per_target_frame, - boundary_segments=True, - ) - # This line prevents dimension mismatch error in the collate_matrices function. - if speaker_activity.shape[1] > self.num_speakers: - logging.warning( - "Number of speakers in the target %s is greater than " - "the maximum number of speakers %s. Truncating extra speakers. " - "Set the `num_speakers` to higher value to avoid this warning.", - speaker_activity.shape[1], - self.num_speakers, - ) - speaker_activity = speaker_activity[:, : self.num_speakers] - speaker_activities.append(speaker_activity) - - cuts = type(cuts).from_cuts(mono_cuts) - audio, audio_lens, cuts = self.load_audio(cuts) - targets = collate_matrices(speaker_activities).to(audio.dtype) # (B, T, N) - - if targets.shape[2] > self.num_speakers: - targets = targets[:, :, : self.num_speakers] - elif targets.shape[2] < self.num_speakers: - targets = torch.nn.functional.pad( - targets, (0, self.num_speakers - targets.shape[2]), mode='constant', value=0 - ) - - target_lens_list = [] - for audio_len in audio_lens: - target_fr_len = get_hidden_length_from_sample_length( - audio_len, self.num_sample_per_mel_frame, self.num_mel_frame_per_target_frame - ) - target_lens_list.append(target_fr_len) - target_lens = torch.tensor(target_lens_list) - - return audio, audio_lens, targets, target_lens diff --git a/nemo/collections/asr/data/audio_to_eou_label_lhotse.py b/nemo/collections/asr/data/audio_to_eou_label_lhotse.py deleted file mode 100644 index 725ccd994f04da2ac8a169d902ea7a85e8c2e630..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/data/audio_to_eou_label_lhotse.py +++ /dev/null @@ -1,524 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import math -from dataclasses import dataclass -from typing import Dict, List, Optional - -import numpy as np -import torch.utils.data -from lhotse.cut import Cut, CutSet, MixedCut -from lhotse.dataset import AudioSamples -from lhotse.dataset.collation import collate_vectors -from omegaconf import DictConfig, OmegaConf - -from nemo.collections.asr.parts.preprocessing.perturb import process_augmentations -from nemo.collections.asr.parts.preprocessing.segment import AudioSegment -from nemo.collections.common.tokenizers.aggregate_tokenizer import TokenizerWrapper -from nemo.collections.common.tokenizers.tokenizer_spec import TokenizerSpec -from nemo.core.neural_types import AudioSignal, LabelsType, LengthsType, NeuralType -from nemo.utils import logging - -NON_SPEECH_LABEL = 0 -SPEECH_LABEL = 1 -EOU_LABEL = 2 -EOB_LABEL = 3 -EOU_STRING = '' -EOB_STRING = '' - -# These augmentations are not supported yet, since they will need to change the SOU/EOU timestamps -EOU_INVALID_AUGMENTATIONS = ['random_segment', 'speed', 'time_stretch'] - - -@dataclass -class AudioToTextEOUBatch: - """ - Data class for ASR-EOU batch. - """ - - sample_ids: List | None = None - audio_filepaths: List | None = None - audio_signal: torch.Tensor | None = None - audio_lengths: torch.Tensor | None = None - text_tokens: torch.Tensor | None = None - text_token_lengths: torch.Tensor | None = None - eou_targets: torch.Tensor | None = None - eou_target_lengths: torch.Tensor | None = None - - -@dataclass -class RandomPaddingConfig: - prob: float = 0.9 # probability of applying padding - min_pad_duration: float = 0.0 # minimum duration of pre/post padding in seconds - max_pad_duration: float = 5.0 # maximum duration of pre/post padding in seconds - max_total_duration: float = 40.0 # maximum total duration of the padded audio in seconds - min_pre_pad_duration: float = 0.0 # minimum duration of pre-padding in seconds - min_post_pad_duration: float = 2.0 # minimum duration of post-padding in seconds - pad_distribution: str = 'uniform' # distribution of padding duration, 'uniform' or 'normal' or 'constant' - normal_mean: float = 0.5 # mean of normal distribution for padding duration - normal_std: float = 2.0 # standard deviation of normal distribution for padding duration - pre_pad_duration: float = 0.2 # amount of left-padding when pad_distribution='constant' - post_pad_duration: float = 3.0 # amount of right-padding when pad_distribution='constant' - - -class LhotseSpeechToTextBpeEOUDataset(torch.utils.data.Dataset): - """ - This dataset processes the audio data and the corresponding text data to generate the ASR labels, - along with EOU labels for each frame. The audios used in this dataset should only contain speech with - NO precedding or following silence. The dataset also randomly pads non-speech frames before and after - the audio signal for training EOU prediction task. - - To generate EOU labels, the last frame of utterance will be marked as "end of utterance" (labeled as `2`), - while if it's a backchannel utterance it'll be marked asd "end of backchannel" (labeled as `3`). - The rest of the speech frames will be marked as "speech" (labeled as `1`). - The padded non-speech signals will be marked as "non-speech" (labeled as 0). - - Args: - cfg: DictConfig object container following keys, usually taken from your `model.train_ds` - or `model.validation_ds` config: - ``` - sample_rate: # int, Sample rate of the audio signal - window_stride: # float, Window stride for audio encoder - subsampling_factor: # Subsampling factor for audio encoder - random_padding: # Random padding configuration - prob: 0.9 # probability of applying padding - min_pad_duration: 0.5 # minimum duration of pre/post padding in seconds - max_pad_duration: 2.0 # maximum duration of pre/post padding in seconds - max_total_duration: 30.0 # maximum total duration of the padded audio in seconds - pad_distribution: 'uniform' # distribution of padding duration, 'uniform' or 'normal' or 'constant' - normal_mean: 0.5 # mean of normal distribution for padding duration - normal_std: 2.0 # standard deviation of normal distribution for padding duration - pre_pad_duration: 0.2 # amount of left-padding when pad_distribution='constant' - post_pad_duration: 3.0 # amount of right-padding when pad_distribution='constant' - ``` - - Returns: - audio: torch.Tensor of audio signal - audio_lens: torch.Tensor of audio signal length - text_tokens: torch.Tensor of text text_tokens - text_token_lens: torch.Tensor of text token length - eou_targets (optional): torch.Tensor of EOU labels - eou_target_lens (optional): torch.Tensor of EOU label length - - The input manifest should be a jsonl file where each line is a python dictionary. - Example manifest sample: - { - "audio_filepath": "/path/to/audio.wav", - "offset": 0.0, - "duration": 6.0, - "sou_time": [0.3, 4.0], - "eou_time": [1.3, 4.5], - "utterances": ["Tell me a joke", "Ah-ha"], - "is_backchannel": [False, True], - } - - Padding logic: - 0. Don't pad when `random_padding` is None or during validation/test - 1. randomly draw a probability to decide whether to apply padding - 2. if not padding or audio duration is longer than the maximum duration, - 1) return the original audio and EOU labels - 3. if apply padding, - 1) get the max padding duration based on the maximum total duration and the audio duration - 2) randomly draw a total padding duration based on the given distribution - 3) randomly split the total padding duration into pre-padding and post-padding - 4) randomly generate the non-speech signal (audio signal=0) for pre-padding and post-padding - 5) concatenate the pre-padding, audio, and post-padding to get the padded audio signal - 6) update the EOU labels accordingly - - """ - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - """Define the output types of the dataset.""" - return { - 'audio': NeuralType(('B', 'T'), AudioSignal()), - 'audio_lens': NeuralType(tuple('B'), LengthsType()), - 'eou_targets': NeuralType(('B', 'T'), LabelsType()), - 'eou_target_lens': NeuralType(tuple('B'), LengthsType()), - 'text_tokens': NeuralType(tuple('B', 'T'), LengthsType(), optional=True), - 'text_token_lens': NeuralType(tuple('B'), LengthsType(), optional=True), - } - - def __init__(self, cfg: DictConfig, tokenizer: TokenizerSpec, return_cuts: bool = False): - super().__init__() - self.cfg = cfg - self.return_cuts = return_cuts - self.eou_string = self.cfg.get('eou_string', EOU_STRING) - self.eob_string = self.cfg.get('eob_string', EOB_STRING) - if cfg.get('check_tokenizer', True): - self._check_special_tokens(tokenizer) - - self.tokenizer = TokenizerWrapper(tokenizer) - self.load_audio = AudioSamples(fault_tolerant=True) - self.sample_rate = self.cfg.get('sample_rate', 16000) - self.window_stride = self.cfg.get('window_stride', 0.01) - self.num_sample_per_mel_frame = int( - self.window_stride * self.sample_rate - ) # 160 samples for every 1ms by default - self.num_mel_frame_per_target_frame = int(self.cfg.get('subsampling_factor', 8)) - self.add_sep_before_eou = self.cfg.get('add_sep_before_eou', False) - self.add_eou_to_text = self.cfg.get('add_eou_to_text', True) - self.pad_eou_label_secs = self.cfg.get('pad_eou_label_secs', 0.0) - self.padding_cfg = self.cfg.get('random_padding', None) - if self.padding_cfg is not None: - self.padding_cfg = OmegaConf.to_container(self.padding_cfg, resolve=True) - self.padding_cfg = RandomPaddingConfig(**self.padding_cfg) - self.ignore_eob_label = self.cfg.get('ignore_eob_label', False) - self.augmentor = None - if self.cfg.get('augmentor', None) is not None: - augmentor = {} - aug_cfg = OmegaConf.to_container(self.cfg.augmentor, resolve=True) - for k, v in aug_cfg.items(): - if k in EOU_INVALID_AUGMENTATIONS: - logging.warning(f"EOU dataset does not support {k} augmentation yet, skipping.") - continue - augmentor[k] = v - - if len(augmentor) > 0: - logging.info(f"EOU dataset will apply augmentations: {augmentor}") - self.augmentor = process_augmentations(augmentor) - - def _check_special_tokens(self, tokenizer: TokenizerSpec): - """ - Check if the special tokens are in the tokenizer vocab. - """ - special_tokens = set([self.eou_string, self.eob_string]) - vocab_size = tokenizer.vocab_size - special_tokens_in_vocab = set([tokenizer.ids_to_text(vocab_size - 1), tokenizer.ids_to_text(vocab_size - 2)]) - if special_tokens != special_tokens_in_vocab: - raise ValueError( - f"Input special tokens {special_tokens} don't match with the tokenizer vocab {special_tokens_in_vocab}. " - f"Please add them to tokenizer or change input `eou_string` and/or `eob_string` accordingly. " - "Special tokens should be added as the last two tokens in the new tokenizer. " - "Please refer to scripts/asr_end_of_utterance/tokenizers/add_special_tokens_to_sentencepiece.py for details." - ) - - def __getitem__(self, cuts: CutSet) -> AudioToTextEOUBatch: - audio, audio_lens, cuts = self.load_audio(cuts) - audio_signals = [] - audio_lengths = [] - eou_targets = [] - text_tokens = [] - sample_ids = [] - audio_filepaths = [] - - for i in range(len(cuts)): - c = cuts[i] - if isinstance(c, MixedCut): - c = c.first_non_padding_cut - - sample_ids.append(c.id) - audio_filepaths.append(c.recording.sources[0].source) - - audio_i = audio[i] - audio_len_i = audio_lens[i] - - # Get EOU labels and text tokens - eou_targets_i = self._get_frame_labels(c, audio_len_i) - text_tokens_i = self._get_text_tokens(c) - - # Maybe apply random padding to both sides of the audio - audio_i, audio_len_i, eou_targets_i = self._random_pad_audio(audio_i, audio_len_i, eou_targets_i) - - # Maybe apply augmentations to the audio signal after padding - audio_i, audio_len_i = self._maybe_augment_audio(audio_i, audio_len_i) - - # Append the processed audio, EOU labels, and text tokens to the lists - audio_signals.append(audio_i) - audio_lengths.append(audio_len_i) - eou_targets.append(eou_targets_i) - text_tokens.append(text_tokens_i) - - audio_signals = collate_vectors(audio_signals, padding_value=0) - audio_lengths = torch.tensor(audio_lengths, dtype=torch.long) - eou_target_lens = torch.tensor([t.size(0) for t in eou_targets], dtype=torch.long) - eou_targets = collate_vectors(eou_targets, padding_value=0) - text_token_lens = torch.tensor([t.size(0) for t in text_tokens], dtype=torch.long) - text_tokens = collate_vectors(text_tokens, padding_value=0) - - if self.return_cuts: - return audio_signals, audio_lengths, cuts - - return AudioToTextEOUBatch( - sample_ids=sample_ids, - audio_filepaths=audio_filepaths, - audio_signal=audio_signals, - audio_lengths=audio_lengths, - text_tokens=text_tokens, - text_token_lengths=text_token_lens, - eou_targets=eou_targets, - eou_target_lengths=eou_target_lens, - ) - - def _audio_len_to_frame_len(self, num_samples: int): - """ - Convert the raw audio length to the number of frames after audio encoder. - - self.num_sample_per_mel_frame = int( - self.cfg.get('window_stride', 0.01) * self.cfg.get('sample_rate', 16000) - ) # 160 samples for every 1ms by default - self.num_mel_frame_per_target_frame = int(self.cfg.get('subsampling_factor', 8)) - """ - mel_frame_count = math.ceil((num_samples + 1) / self.num_sample_per_mel_frame) - hidden_length = math.ceil(mel_frame_count / self.num_mel_frame_per_target_frame) - return hidden_length - - def _repeat_eou_labels(self, eou_targets: torch.Tensor) -> torch.Tensor: - """ - Repeat EOU labels according to self.pad_eou_label_secs - Args: - eou_targets: torch.Tensor of EOU labels, shape [T] - Returns: - eou_targets: torch.Tensor of padded EOU labels, shape [T] - """ - if not self.pad_eou_label_secs or self.pad_eou_label_secs <= 0: - return eou_targets - - eou_len = self._audio_len_to_frame_len(int(self.pad_eou_label_secs * self.sample_rate)) - - i = 0 - while i < eou_targets.size(0): - if eou_targets[i] == EOU_LABEL or eou_targets[i] == EOB_LABEL: - # repeat the label for the next eou_len samples - start = i - end = min(i + eou_len, eou_targets.size(0)) - j = start + 1 - while j < end: - if eou_targets[j] != NON_SPEECH_LABEL: - # do not overwrite the label if it's not non-speech - break - j += 1 - end = min(j, end) - # fill the non-speech label with the current EOU/EOB label - eou_targets[start:end] = eou_targets[i] - i = end - else: - i += 1 - return eou_targets - - def _get_frame_labels(self, cut: Cut, num_samples: int): - """ - Get the frame-level EOU labels for a single audio segment. - Args: - cut: Cut object - num_samples: int, the number of samples in the audio segment - Returns: - eou_targets: torch.Tensor of EOU labels, shape [T] - """ - hidden_length = self._audio_len_to_frame_len(num_samples) - if not "sou_time" in cut.custom or not "eou_time" in cut.custom: - # assume only single speech segment - text = cut.supervisions[0].text - if not text: - # skip empty utterances - return torch.zeros(hidden_length).long() - eou_targets = torch.ones(hidden_length).long() # speech label - eou_targets[-1] = EOU_LABEL # by default it's end of utterance - if cut.has_custom("is_backchannel") and cut.custom["is_backchannel"] and not self.ignore_eob_label: - eou_targets[-1] = EOB_LABEL # end of backchannel - return eou_targets - - sou_time = cut.custom["sou_time"] - eou_time = cut.custom["eou_time"] - if not isinstance(sou_time, list): - sou_time = [sou_time] - if not isinstance(eou_time, list): - eou_time = [eou_time] - - assert len(sou_time) == len( - eou_time - ), f"Number of SOU time and EOU time do not match: SOU ({sou_time}) vs EOU ({eou_time})" - - if cut.has_custom("is_backchannel"): - is_backchannel = cut.custom["is_backchannel"] - if not isinstance(is_backchannel, list): - is_backchannel = [is_backchannel] - assert len(sou_time) == len( - is_backchannel - ), f"Number of SOU and backchannel do not match: SOU ({len(sou_time)}) vs backchannel ({len(is_backchannel)})" - else: - is_backchannel = [False] * len(sou_time) - - eou_targets = torch.zeros(hidden_length).long() - for i in range(len(sou_time)): - if sou_time[i] is None or eou_time[i] is None or sou_time[i] < 0 or eou_time[i] < 0: - # skip empty utterances - continue - sou_idx = self._audio_len_to_frame_len(int((sou_time[i] - cut.start) * self.sample_rate)) - seg_len_in_secs = eou_time[i] - sou_time[i] - seg_len = self._audio_len_to_frame_len(int(seg_len_in_secs * self.sample_rate)) - eou_targets[sou_idx : sou_idx + seg_len] = SPEECH_LABEL - last_idx = min(sou_idx + seg_len - 1, hidden_length - 1) - if is_backchannel[i] and not self.ignore_eob_label: - eou_targets[last_idx] = EOB_LABEL # end of backchannel - else: - eou_targets[last_idx] = EOU_LABEL # end of utterance - - return eou_targets - - def _get_text_tokens(self, cut: Cut): - """ - Add EOU labels to the text and get the text tokens for a single audio segment. - Args: - cut: Cut object - Returns: - text_tokens: torch.Tensor of text tokens, shape [T] - """ - if not cut.has_custom("sou_time") or not cut.has_custom("eou_time") or not cut.has_custom("utterances"): - # assume only single speech segment - utterances = [cut.supervisions[0].text] - else: - utterances = cut.custom["utterances"] - - if not isinstance(utterances, list): - utterances = [utterances] - - if cut.has_custom("is_backchannel"): - is_backchannel = cut.custom["is_backchannel"] - if not isinstance(is_backchannel, list): - is_backchannel = [is_backchannel] - assert len(utterances) == len( - is_backchannel - ), f"Number of utterances and backchannel do not match: utterance ({len(utterances)}) vs backchannel ({len(is_backchannel)})" - else: - is_backchannel = [False] * len(utterances) - - total_text = "" - for i, text in enumerate(utterances): - if not text: - # skip empty utterances - continue - if self.add_eou_to_text: - eou_string = self.eob_string if is_backchannel[i] and not self.ignore_eob_label else self.eou_string - if self.add_sep_before_eou: - eou_string = " " + eou_string - else: - eou_string = "" - total_text += text + eou_string + " " - total_text = total_text.strip() - return torch.as_tensor(self.tokenizer(total_text)) - - def _random_pad_audio(self, audio: torch.Tensor, audio_len: torch.Tensor, eou_targets: torch.Tensor): - """ - Randomly pad the audio signal with non-speech signal before and after the audio signal. - Args: - audio: torch.Tensor of a single audio signal, shape [T] - audio_len: torch.Tensor of audio signal length, shape [1] - eou_targets: torch.Tensor of EOU labels, shape [T] - Returns: - padded_audio: torch.Tensor of padded audio signal, shape [T+padding] - padded_audio_len: torch.Tensor of padded audio signal length, shape [1] - padded_eou_targets: torch.Tensor of padded EOU labels, shape [T+padding] - padded_eou_targets_len: torch.Tensor of padded EOU label length, shape [1] - """ - p = np.random.rand() - if self.padding_cfg is None or p > self.padding_cfg.prob: - # don't apply padding - eou_targets = self._repeat_eou_labels(eou_targets) - return audio, audio_len, eou_targets - - duration = audio_len.item() / self.cfg.sample_rate - # if already longer than the maximum duration, return the original audio - if duration >= self.padding_cfg.max_total_duration: - return audio, audio_len, eou_targets - - # apply padding - audio = audio[:audio_len] - - self.padding_cfg.min_pre_pad_duration = max( - self.padding_cfg.min_pre_pad_duration, self.padding_cfg.min_pad_duration - ) - self.padding_cfg.min_post_pad_duration = max( - self.padding_cfg.min_post_pad_duration, self.padding_cfg.min_pad_duration - ) - - max_padding_duration = max(0, self.padding_cfg.max_total_duration - duration) - if max_padding_duration <= self.padding_cfg.min_pre_pad_duration + self.padding_cfg.min_post_pad_duration: - min_padding_duration = 0 - else: - min_padding_duration = self.padding_cfg.min_pre_pad_duration + self.padding_cfg.min_post_pad_duration - - pre_padding_duration = None - post_padding_duration = None - - if self.padding_cfg.pad_distribution == 'uniform': - total_padding_duration = np.random.uniform(min_padding_duration, max_padding_duration) - elif self.padding_cfg.pad_distribution == 'normal': - total_padding_duration = np.random.normal(self.padding_cfg.normal_mean, self.padding_cfg.normal_std) - total_padding_duration = max(min_padding_duration, min(max_padding_duration, total_padding_duration)) - elif self.padding_cfg.pad_distribution == 'constant': - pass - else: - raise ValueError(f"Unknown padding distribution: {self.padding_cfg.pad_distribution}") - - if self.padding_cfg.pad_distribution == 'constant': - pre_padding_duration = self.padding_cfg.pre_pad_duration - post_padding_duration = self.padding_cfg.post_pad_duration - elif min_padding_duration == 0: - pre_padding_duration = total_padding_duration / 2 - post_padding_duration = total_padding_duration / 2 - else: - post_padding_duration = np.random.uniform( - self.padding_cfg.min_post_pad_duration, total_padding_duration - self.padding_cfg.min_pre_pad_duration - ) - pre_padding_duration = total_padding_duration - post_padding_duration - - if self.padding_cfg.max_pad_duration is not None: - pre_padding_duration = min(pre_padding_duration, self.padding_cfg.max_pad_duration) - post_padding_duration = min(post_padding_duration, self.padding_cfg.max_pad_duration) - - pre_padding_len = math.ceil(pre_padding_duration * self.cfg.sample_rate) - post_padding_len = math.ceil(post_padding_duration * self.cfg.sample_rate) - - # pad the audio signal - pre_padding = torch.zeros(pre_padding_len, dtype=audio.dtype) - post_padding = torch.zeros(post_padding_len, dtype=audio.dtype) - padded_audio = torch.cat((pre_padding, audio, post_padding), dim=0) - padded_audio_len = audio_len + pre_padding_len + post_padding_len - - # pad the EOU labels - pre_padding_eou_len = self._audio_len_to_frame_len(pre_padding_len) - post_padding_eou_len = self._audio_len_to_frame_len(post_padding_len) - pre_padding_eou = torch.zeros(pre_padding_eou_len, dtype=eou_targets.dtype) - post_padding_eou = torch.zeros(post_padding_eou_len, dtype=eou_targets.dtype) - padded_eou_targets = torch.cat((pre_padding_eou, eou_targets, post_padding_eou), dim=0) - padded_eou_targets = self._repeat_eou_labels(padded_eou_targets) - return padded_audio, padded_audio_len, padded_eou_targets - - def _maybe_augment_audio(self, audio: torch.Tensor, audio_len: torch.Tensor): - """ - Apply augmentation to the audio signal if augmentor is provided. - Args: - audio: torch.Tensor of a single audio signal, shape [T] - audio_len: torch.Tensor of audio signal length, shape [1] - Returns: - augmented_audio: torch.Tensor of augmented audio signal, shape [T] - augmented_audio_len: torch.Tensor of augmented audio signal length, shape [1] - """ - if self.augmentor is None: - return audio, audio_len - - # Cast to AudioSegment - audio_segment = AudioSegment( - samples=audio[:audio_len].numpy(), - sample_rate=self.sample_rate, - offset=0, - duration=audio_len.item() / self.sample_rate, - ) - # Apply augmentation - self.augmentor.perturb(audio_segment) - audio = torch.from_numpy(audio_segment.samples).float() - audio_len = audio.size(0) - - return audio, audio_len diff --git a/nemo/collections/asr/data/audio_to_label.py b/nemo/collections/asr/data/audio_to_label.py deleted file mode 100644 index c7402e3085b3442b51dc416d1e7feca3b76c53b8..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/data/audio_to_label.py +++ /dev/null @@ -1,1422 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import io -import os -from typing import Dict, List, Optional, Union - -import torch - -from nemo.collections.asr.data.audio_to_text import cache_datastore_manifests, expand_sharded_filepaths -from nemo.collections.asr.parts.preprocessing.features import WaveformFeaturizer -from nemo.collections.asr.parts.preprocessing.segment import available_formats as valid_sf_formats -from nemo.collections.common.parts.preprocessing import collections -from nemo.core.classes import Dataset, IterableDataset -from nemo.core.neural_types import AudioSignal, LabelsType, LengthsType, NeuralType, RegressionValuesType -from nemo.utils import logging -from nemo.utils import webdataset as wds -from nemo.utils.distributed import webdataset_split_by_workers - -# List of valid file formats (prioritized by order of importance) -VALID_FILE_FORMATS = ';'.join(['wav', 'mp3', 'flac', 'opus'] + [fmt.lower() for fmt in valid_sf_formats.keys()]) - - -def repeat_signal(signal: torch.Tensor, sig_len: int, required_length: int) -> torch.Tensor: - """repeat signal to make short signal to have required_length - Args: - signal (Tensor): input signal - sig_len (int): length of input signal - required_length (int): length of generated signal - Returns: - signal (Tensor): generated signal of required_length by repeating itself. - """ - sub: torch.Tensor = torch.tensor([]) - repeat = int(required_length // sig_len) - rem = int(required_length % sig_len) - sub: torch.Tensor = torch.tensor([]) - rep_sig: torch.Tensor = torch.cat(repeat * [signal]) - if rem > 0: - sub = signal[-rem:] - signal = torch.cat((rep_sig, sub)) - else: - signal = rep_sig - return signal - - -def normalize(signal): - """normalize signal - Args: - signal(FloatTensor): signal to be normalized. - """ - signal_minusmean = signal - signal.mean() - return signal_minusmean / signal_minusmean.abs().max() - - -def count_occurence(manifest_file_id): - """Count number of wav files in Dict manifest_file_id. Use for _TarredAudioToLabelDataset. - Args: - manifest_file_id (Dict): Dict of files and their corresponding id. {'A-sub0' : 1, ..., 'S-sub10':100} - Returns: - count (Dict): Dict of wav files {'A' : 2, ..., 'S':10} - """ - count = dict() - for i in manifest_file_id: - audio_filename = i.split("-sub")[0] - count[audio_filename] = count.get(audio_filename, 0) + 1 - return count - - -def _speech_collate_fn(batch, pad_id): - """collate batch of audio sig, audio len, tokens, tokens len - Args: - batch (Optional[FloatTensor], Optional[LongTensor], LongTensor, - LongTensor): A tuple of tuples of signal, signal lengths, - encoded tokens, and encoded tokens length. This collate func - assumes the signals are 1d torch tensors (i.e. mono audio). - """ - _, audio_lengths, _, tokens_lengths = zip(*batch) - max_audio_len = 0 - has_audio = audio_lengths[0] is not None - if has_audio: - max_audio_len = max(audio_lengths).item() - max_tokens_len = max(tokens_lengths).item() - - audio_signal, tokens = [], [] - for sig, sig_len, tokens_i, tokens_i_len in batch: - if has_audio: - sig_len = sig_len.item() - if sig_len < max_audio_len: - pad = (0, max_audio_len - sig_len) - sig = torch.nn.functional.pad(sig, pad) - audio_signal.append(sig) - tokens_i_len = tokens_i_len.item() - if tokens_i_len < max_tokens_len: - pad = (0, max_tokens_len - tokens_i_len) - tokens_i = torch.nn.functional.pad(tokens_i, pad, value=pad_id) - tokens.append(tokens_i) - - if has_audio: - audio_signal = torch.stack(audio_signal) - audio_lengths = torch.stack(audio_lengths) - else: - audio_signal, audio_lengths = None, None - tokens = torch.stack(tokens) - tokens_lengths = torch.stack(tokens_lengths) - - return audio_signal, audio_lengths, tokens, tokens_lengths - - -def _fixed_seq_collate_fn(self, batch): - """collate batch of audio sig, audio len, tokens, tokens len - Args: - batch (Optional[FloatTensor], Optional[LongTensor], LongTensor, - LongTensor): A tuple of tuples of signal, signal lengths, - encoded tokens, and encoded tokens length. This collate func - assumes the signals are 1d torch tensors (i.e. mono audio). - """ - _, audio_lengths, _, tokens_lengths = zip(*batch) - - has_audio = audio_lengths[0] is not None - fixed_length = int(max(audio_lengths)) - - audio_signal, tokens, new_audio_lengths = [], [], [] - for sig, sig_len, tokens_i, _ in batch: - if has_audio: - sig_len = sig_len.item() - chunck_len = sig_len - fixed_length - - if chunck_len < 0: - repeat = fixed_length // sig_len - rem = fixed_length % sig_len - sub = sig[-rem:] if rem > 0 else torch.tensor([]) - rep_sig = torch.cat(repeat * [sig]) - sig = torch.cat((rep_sig, sub)) - new_audio_lengths.append(torch.tensor(fixed_length)) - - audio_signal.append(sig) - - tokens.append(tokens_i) - - if has_audio: - audio_signal = torch.stack(audio_signal) - audio_lengths = torch.stack(new_audio_lengths) - else: - audio_signal, audio_lengths = None, None - tokens = torch.stack(tokens) - tokens_lengths = torch.stack(tokens_lengths) - - return audio_signal, audio_lengths, tokens, tokens_lengths - - -def _vad_frame_seq_collate_fn(self, batch): - """collate batch of audio sig, audio len, tokens, tokens len - Args: - batch (Optional[FloatTensor], Optional[LongTensor], LongTensor, - LongTensor): A tuple of tuples of signal, signal lengths, - encoded tokens, and encoded tokens length. This collate func - assumes the signals are 1d torch tensors (i.e. mono audio). - batch size equals to 1. - """ - slice_length = int(self.featurizer.sample_rate * self.window_length_in_sec) - _, audio_lengths, _, tokens_lengths = zip(*batch) - slice_length = int(min(slice_length, max(audio_lengths))) - shift = int(self.featurizer.sample_rate * self.shift_length_in_sec) - has_audio = audio_lengths[0] is not None - - audio_signal, num_slices, tokens, audio_lengths = [], [], [], [] - - append_len_start = slice_length // 2 - append_len_end = slice_length - slice_length // 2 - for sig, sig_len, tokens_i, _ in batch: - if self.normalize_audio: - sig = normalize(sig) - start = torch.zeros(append_len_start) - end = torch.zeros(append_len_end) - sig = torch.cat((start, sig, end)) - sig_len += slice_length - - if has_audio: - slices = torch.div(sig_len - slice_length, shift, rounding_mode='trunc') - for slice_id in range(slices): - start_idx = slice_id * shift - end_idx = start_idx + slice_length - signal = sig[start_idx:end_idx] - audio_signal.append(signal) - - num_slices.append(slices) - tokens.extend([tokens_i] * slices) - audio_lengths.extend([slice_length] * slices) - - if has_audio: - audio_signal = torch.stack(audio_signal) - audio_lengths = torch.tensor(audio_lengths) - else: - audio_signal, audio_lengths = None, None - - tokens = torch.stack(tokens) - tokens_lengths = torch.tensor(num_slices) - return audio_signal, audio_lengths, tokens, tokens_lengths - - -class _AudioLabelDataset(Dataset): - """ - Dataset that loads tensors via a json file containing paths to audio files, - labels, and durations and offsets(in seconds). Each new line is a - different sample. Example below: - and their target labels. JSON files should be of the following format:: - {"audio_filepath": "/path/to/audio_wav_0.wav", "duration": time_in_sec_0, "label": \ -target_label_0, "offset": offset_in_sec_0} - ... - {"audio_filepath": "/path/to/audio_wav_n.wav", "duration": time_in_sec_n, "label": \ -target_label_n, "offset": offset_in_sec_n} - Args: - manifest_filepath (Union[str, List[str]]): Dataset parameter. Path to JSON containing data. - labels (list): Dataset parameter. List of target classes that can be output by the speaker recognition model. - featurizer - min_duration (float): Dataset parameter. All training files which have a duration less than min_duration - are dropped. Note: Duration is read from the manifest JSON. - Defaults to 0.1. - max_duration (float): Dataset parameter. - All training files which have a duration more than max_duration - are dropped. Note: Duration is read from the manifest JSON. - Defaults to None. - trim (bool): Whether to use trim silence from beginning and end of audio signal using librosa.effects.trim(). - Defaults to False. - channel selector (Union[str, int, List[int]]): string denoting the downmix mode, an integer denoting the channel to be selected, or an iterable - of integers denoting a subset of channels. Channel selector is using zero-based indexing. - If set to `None`, the original signal will be used. - """ - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - """Returns definitions of module output ports.""" - - output_types = { - 'audio_signal': NeuralType( - ('B', 'T'), - ( - AudioSignal(freq=self._sample_rate) - if self is not None and hasattr(self, '_sample_rate') - else AudioSignal() - ), - ), - 'a_sig_length': NeuralType(tuple('B'), LengthsType()), - } - - if self.is_regression_task: - output_types.update( - { - 'targets': NeuralType(tuple('B'), RegressionValuesType()), - 'targets_length': NeuralType(tuple('B'), LengthsType()), - } - ) - else: - - output_types.update( - { - 'label': NeuralType(tuple('B'), LabelsType()), - 'label_length': NeuralType(tuple('B'), LengthsType()), - } - ) - - return output_types - - def __init__( - self, - *, - manifest_filepath: Union[str, List[str]], - labels: List[str], - featurizer, - min_duration: Optional[float] = 0.1, - max_duration: Optional[float] = None, - trim: bool = False, - channel_selector: Union[str, int, List[int]] = None, - is_regression_task: bool = False, - cal_labels_occurrence: Optional[bool] = False, - ): - super().__init__() - if isinstance(manifest_filepath, str): - manifest_filepath = manifest_filepath.split(',') - cache_datastore_manifests(manifest_filepaths=manifest_filepath, cache_audio=True) - self.collection = collections.ASRSpeechLabel( - manifests_files=manifest_filepath, - min_duration=min_duration, - max_duration=max_duration, - is_regression_task=is_regression_task, - cal_labels_occurrence=cal_labels_occurrence, - ) - - self.featurizer = featurizer - self.trim = trim - self.channel_selector = channel_selector - self.is_regression_task = is_regression_task - - if not is_regression_task: - self.labels = labels if labels else self.collection.uniq_labels - self.num_classes = len(self.labels) if self.labels is not None else 1 - self.label2id, self.id2label = {}, {} - self.id2occurrence, self.labels_occurrence = {}, [] - - for label_id, label in enumerate(self.labels): - self.label2id[label] = label_id - self.id2label[label_id] = label - if cal_labels_occurrence: - self.id2occurrence[label_id] = self.collection.labels_occurrence[label] - - if cal_labels_occurrence: - self.labels_occurrence = [self.id2occurrence[k] for k in sorted(self.id2occurrence)] - - for idx in range(len(self.labels[:5])): - logging.debug(" label id {} and its mapped label {}".format(idx, self.id2label[idx])) - - else: - self.labels = [] - self.num_classes = 1 - - def __len__(self): - return len(self.collection) - - def __getitem__(self, index): - sample = self.collection[index] - - offset = sample.offset - - if offset is None: - offset = 0 - - features = self.featurizer.process( - sample.audio_file, - offset=offset, - duration=sample.duration, - trim=self.trim, - channel_selector=self.channel_selector, - ) - f, fl = features, torch.tensor(features.shape[0]).long() - - if not self.is_regression_task: - t = torch.tensor(self.label2id[sample.label]).long() - else: - t = torch.tensor(sample.label).float() - - tl = torch.tensor(1).long() # For compatibility with collate_fn used later - - return f, fl, t, tl - - -# Ported from https://github.com/NVIDIA/OpenSeq2Seq/blob/master/open_seq2seq/data/speech2text/speech_commands.py -class AudioToClassificationLabelDataset(_AudioLabelDataset): - """ - Dataset that loads tensors via a json file containing paths to audio - files, command class, and durations (in seconds). Each new line is a - different sample. Example below: - {"audio_filepath": "/path/to/audio_wav_0.wav", "duration": time_in_sec_0, "label": \ - target_label_0, "offset": offset_in_sec_0} - ... - {"audio_filepath": "/path/to/audio_wav_n.wav", "duration": time_in_sec_n, "label": \ - target_label_n, "offset": offset_in_sec_n} - Args: - manifest_filepath (Union[str, List[str]]): Path to manifest json as described above. Can - be comma-separated paths. - labels (Optional[list]): String containing all the possible labels to map to - if None then automatically picks from ASRSpeechLabel collection. - featurizer: Initialized featurizer class that converts paths of - audio to feature tensors - max_duration: If audio exceeds this length, do not include in dataset - min_duration: If audio is less than this length, do not include - in dataset - trim: Boolean flag whether to trim the audio - """ - - def _collate_fn(self, batch): - return _speech_collate_fn(batch, pad_id=0) - - -class AudioToSpeechLabelDataset(_AudioLabelDataset): - """ - Dataset that loads tensors via a json file containing paths to audio - files, command class, and durations (in seconds). Each new line is a - different sample. Example below: - {"audio_filepath": "/path/to/audio_wav_0.wav", "duration": time_in_sec_0, "label": \ - target_label_0, "offset": offset_in_sec_0} - ... - {"audio_filepath": "/path/to/audio_wav_n.wav", "duration": time_in_sec_n, "label": \ - target_label_n, "offset": offset_in_sec_n} - Args: - manifest_filepath (Union[str, List[str]]): Path to manifest json as described above. Can - be comma-separated paths. - labels (Optional[list]): String containing all the possible labels to map to - if None then automatically picks from ASRSpeechLabel collection. - min_duration (float): Dataset parameter. - All training files which have a duration less than min_duration - are dropped. Note: Duration is read from the manifest JSON. - Defaults to 0.1. - max_duration (float): Dataset parameter. - All training files which have a duration more than max_duration - are dropped. Note: Duration is read from the manifest JSON. - Defaults to None. - trim (bool): Whether to use trim silence from beginning and end - of audio signal using librosa.effects.trim(). - Defaults to False. - channel selector (Union[str, int, List[int]]): string denoting the downmix mode, an integer denoting the channel to be selected, or an iterable - of integers denoting a subset of channels. Channel selector is using zero-based indexing. - If set to `None`, the original signal will be used. - window_length_in_sec (float): length of window/slice (in seconds) - Use this for speaker recognition and VAD tasks. - shift_length_in_sec (float): amount of shift of window for generating the frame for VAD task in a batch - Use this for VAD task during inference. - normalize_audio (bool): Whether to normalize audio signal. - Defaults to False. - is_regression_task (bool): Whether the dataset is for a regression task instead of classification. - Defaults to False. - cal_labels_occurrence (bool): Whether to calculate occurrence of labels - Defaults to False. - """ - - def __init__( - self, - *, - manifest_filepath: Union[str, List[str]], - labels: List[str], - featurizer, - min_duration: Optional[float] = 0.1, - max_duration: Optional[float] = None, - trim: bool = False, - channel_selector: Optional[Union[str, int, List[int]]] = None, - window_length_in_sec: Optional[float] = 8, - shift_length_in_sec: Optional[float] = 1, - normalize_audio: bool = False, - is_regression_task: bool = False, - cal_labels_occurrence: Optional[bool] = False, - ): - self.window_length_in_sec = window_length_in_sec - self.shift_length_in_sec = shift_length_in_sec - self.normalize_audio = normalize_audio - - logging.debug("Window/slice length considered for collate func is {}".format(self.window_length_in_sec)) - logging.debug("Shift length considered for collate func is {}".format(self.shift_length_in_sec)) - - super().__init__( - manifest_filepath=manifest_filepath, - labels=labels, - featurizer=featurizer, - min_duration=min_duration, - max_duration=max_duration, - trim=trim, - channel_selector=channel_selector, - is_regression_task=is_regression_task, - cal_labels_occurrence=cal_labels_occurrence, - ) - - def fixed_seq_collate_fn(self, batch): - return _fixed_seq_collate_fn(self, batch) - - def vad_frame_seq_collate_fn(self, batch): - return _vad_frame_seq_collate_fn(self, batch) - - -class _TarredAudioLabelDataset(IterableDataset): - """ - A similar Dataset to the AudioLabelDataSet, but which loads tarred audio files. - - Accepts a single comma-separated JSON manifest file (in the same style as for the AudioToSpeechLabelDataset), - as well as the path(s) to the tarball(s) containing the wav files. Each line of the manifest should - contain the information for one audio file, including at least the label and name of the audio - file within the tarball. - - Valid formats for the audio_tar_filepaths argument include: - (1) a single string that can be brace-expanded, e.g. 'path/to/audio.tar' or 'path/to/audio_{1..100}.tar.gz', or - (2) a list of file paths that will not be brace-expanded, e.g. ['audio_1.tar', 'audio_2.tar', ...]. - - Note: For brace expansion in (1), there may be cases where `{x..y}` syntax cannot be used due to shell interference. - This occurs most commonly inside SLURM scripts. Therefore we provide a few equivalent replacements. - Supported opening braces - { <=> (, [, < and the special tag _OP_. - Supported closing braces - } <=> ), ], > and the special tag _CL_. - For SLURM based tasks, we suggest the use of the special tags for ease of use. - - See the documentation for more information about accepted data and input formats. - - If using multiple processes the number of shards should be divisible by the number of workers to ensure an - even split among workers. If it is not divisible, logging will give a warning but training will proceed. - In addition, if using mutiprocessing, each shard MUST HAVE THE SAME NUMBER OF ENTRIES after filtering - is applied. We currently do not check for this, but your program may hang if the shards are uneven! - - Notice that a few arguments are different from the AudioLabelDataSet; for example, shuffle (bool) has been - replaced by shuffle_n (int). - - Additionally, please note that the len() of this DataLayer is assumed to be the length of the manifest - after filtering. An incorrect manifest length may lead to some DataLoader issues down the line. - - Args: - audio_tar_filepaths: Either a list of audio tarball filepaths, or a - string (can be brace-expandable). - manifest_filepath (str): Path to the manifest. - labels (list): Dataset parameter. - List of target classes that can be output by the speaker recognition model. - featurizer - shuffle_n (int): How many samples to look ahead and load to be shuffled. - See WebDataset documentation for more details. - Defaults to 0. - min_duration (float): Dataset parameter. - All training files which have a duration less than min_duration - are dropped. Note: Duration is read from the manifest JSON. - Defaults to 0.1. - max_duration (float): Dataset parameter. - All training files which have a duration more than max_duration - are dropped. Note: Duration is read from the manifest JSON. - Defaults to None. - trim(bool): Whether to use trim silence from beginning and end - of audio signal using librosa.effects.trim(). - Defaults to False. - window_length_in_sec (float): length of slice/window (in seconds) # Pass this only for speaker recognition and VAD task - 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. - normalize_audio (bool): Whether to normalize audio signal. Defaults to False. - shard_strategy (str): Tarred dataset shard distribution strategy chosen as a str value during ddp. - - `scatter`: The default shard strategy applied by WebDataset, where each node gets - a unique set of shards, which are permanently pre-allocated and never changed at runtime. - - `replicate`: Optional shard strategy, where each node gets all of the set of shards - available in the tarred dataset, which are permanently pre-allocated and never changed at runtime. - The benefit of replication is that it allows each node to sample data points from the entire - dataset independently of other nodes, and reduces dependence on the value of `shuffle_n`. - - .. warning:: - Replicated strategy allows every node to sample the entire set of available tarfiles, - and therefore more than one node may sample the same tarfile, and even sample the same - data points! As such, there is no assured guarantee that all samples in the dataset will be - sampled at least once during 1 epoch. Scattered strategy, on the other hand, on specific - occasions (when the number of shards is not divisible with ``world_size``), will not sample - the entire dataset. For these reasons it is not advisable to use tarred datasets as validation - or test datasets. - global_rank (int): Worker rank, used for partitioning shards. Defaults to 0. - world_size (int): Total number of processes, used for partitioning shards. Defaults to 0. - is_regression_task (bool): Whether it is a regression task. Defualts to False. - """ - - def __init__( - self, - *, - audio_tar_filepaths: Union[str, List[str]], - manifest_filepath: Union[str, List[str]], - labels: List[str], - featurizer, - shuffle_n: int = 0, - min_duration: Optional[float] = 0.1, - max_duration: Optional[float] = None, - trim: bool = False, - shard_strategy: str = "scatter", - global_rank: int = 0, - world_size: int = 0, - is_regression_task: bool = False, - ): - cache_datastore_manifests(manifest_filepaths=manifest_filepath) - self.collection = collections.ASRSpeechLabel( - manifests_files=manifest_filepath, - min_duration=min_duration, - max_duration=max_duration, - index_by_file_id=True, # Must set this so the manifest lines can be indexed by file ID - ) - - self.file_occurence = count_occurence(self.collection.mapping) - - self.featurizer = featurizer - self.trim = trim - - self.labels = labels if labels else self.collection.uniq_labels - self.num_classes = len(self.labels) - - self.label2id, self.id2label = {}, {} - for label_id, label in enumerate(self.labels): - self.label2id[label] = label_id - self.id2label[label_id] = label - - for idx in range(len(self.labels[:5])): - logging.debug(" label id {} and its mapped label {}".format(idx, self.id2label[idx])) - - audio_tar_filepaths = expand_sharded_filepaths( - sharded_filepaths=audio_tar_filepaths, - shard_strategy=shard_strategy, - world_size=world_size, - global_rank=global_rank, - ) - - # Put together WebDataset - self._dataset = wds.DataPipeline( - wds.SimpleShardList(urls=audio_tar_filepaths), - webdataset_split_by_workers, - wds.shuffle(shuffle_n), - wds.tarfile_to_samples(), - wds.rename(audio=VALID_FILE_FORMATS, key='__key__'), - wds.to_tuple('audio', 'key'), - self._filter, - wds.map(self._build_sample), - ) - - def _filter(self, iterator): - """This function is used to remove samples that have been filtered out by ASRSpeechLabel already. - Otherwise, we would get a KeyError as _build_sample attempts to find the manifest entry for a sample - that was filtered out (e.g. for duration). - Note that if using multi-GPU training, filtering may lead to an imbalance in samples in each shard, - which may make your code hang as one process will finish before the other. - """ - - class TarredAudioFilter: - def __init__(self, collection, file_occurence): - self.iterator = iterator - self.collection = collection - self.file_occurence = file_occurence - self._iterable = self._internal_generator() - - def __iter__(self): - self._iterable = self._internal_generator() - return self - - def __next__(self): - try: - values = next(self._iterable) - except StopIteration: - # reset generator - self._iterable = self._internal_generator() - values = next(self._iterable) - - return values - - def _internal_generator(self): - """ - WebDataset requires an Iterator, but we require an iterable that yields 1-or-more - values per value inside self.iterator. - - Therefore wrap the iterator with a generator function that will yield 1-or-more - values per sample in the iterator. - """ - for _, tup in enumerate(self.iterator): - audio_bytes, audio_filename = tup - - file_id, _ = os.path.splitext(os.path.basename(audio_filename)) - if audio_filename in self.file_occurence: - for j in range(0, self.file_occurence[file_id]): - if j == 0: - audio_filename = file_id - else: - audio_filename = file_id + "-sub" + str(j) - yield audio_bytes, audio_filename - - return TarredAudioFilter(self.collection, self.file_occurence) - - def _build_sample(self, tup): - """Builds the training sample by combining the data from the WebDataset with the manifest info.""" - audio_bytes, audio_filename = tup - # Grab manifest entry from self.collection - file_id, _ = os.path.splitext(os.path.basename(audio_filename)) - - manifest_idx = self.collection.mapping[file_id] - manifest_entry = self.collection[manifest_idx] - - offset = manifest_entry.offset - if offset is None: - offset = 0 - - # Convert audio bytes to IO stream for processing (for SoundFile to read) - audio_filestream = io.BytesIO(audio_bytes) - features = self.featurizer.process( - audio_filestream, - offset=offset, - duration=manifest_entry.duration, - trim=self.trim, - ) - - audio_filestream.close() - - # Audio features - f, fl = features, torch.tensor(features.shape[0]).long() - - t = self.label2id[manifest_entry.label] - tl = 1 # For compatibility with collate_fn used later - - return f, fl, torch.tensor(t).long(), torch.tensor(tl).long() - - def __iter__(self): - return self._dataset.__iter__() - - def __len__(self): - return len(self.collection) - - -class TarredAudioToClassificationLabelDataset(_TarredAudioLabelDataset): - """ - A similar Dataset to the AudioToClassificationLabelDataset, but which loads tarred audio files. - - Accepts a single comma-separated JSON manifest file (in the same style as for the AudioToClassificationLabelDataset), - as well as the path(s) to the tarball(s) containing the wav files. Each line of the manifest should - contain the information for one audio file, including at least the transcript and name of the audio - file within the tarball. - - Valid formats for the audio_tar_filepaths argument include: - (1) a single string that can be brace-expanded, e.g. 'path/to/audio.tar' or 'path/to/audio_{1..100}.tar.gz', or - (2) a list of file paths that will not be brace-expanded, e.g. ['audio_1.tar', 'audio_2.tar', ...]. - - See the WebDataset documentation for more information about accepted data and input formats. - - If using multiple processes the number of shards should be divisible by the number of workers to ensure an - even split among workers. If it is not divisible, logging will give a warning but training will proceed. - In addition, if using mutiprocessing, each shard MUST HAVE THE SAME NUMBER OF ENTRIES after filtering - is applied. We currently do not check for this, but your program may hang if the shards are uneven! - - Notice that a few arguments are different from the AudioToBPEDataset; for example, shuffle (bool) has been - replaced by shuffle_n (int). - - Additionally, please note that the len() of this DataLayer is assumed to be the length of the manifest - after filtering. An incorrect manifest length may lead to some DataLoader issues down the line. - - Args: - audio_tar_filepaths: Either a list of audio tarball filepaths, or a - string (can be brace-expandable). - manifest_filepath (str): Path to the manifest. - labels (list): Dataset parameter. - List of target classes that can be output by the speaker recognition model. - featurizer - shuffle_n (int): How many samples to look ahead and load to be shuffled. - See WebDataset documentation for more details. - Defaults to 0. - min_duration (float): Dataset parameter. - All training files which have a duration less than min_duration - are dropped. Note: Duration is read from the manifest JSON. - Defaults to 0.1. - max_duration (float): Dataset parameter. - All training files which have a duration more than max_duration - are dropped. Note: Duration is read from the manifest JSON. - Defaults to None. - trim(bool): Whether to use trim silence from beginning and end - of audio signal using librosa.effects.trim(). - Defaults to False. - shard_strategy (str): Tarred dataset shard distribution strategy chosen as a str value during ddp. - - `scatter`: The default shard strategy applied by WebDataset, where each node gets - a unique set of shards, which are permanently pre-allocated and never changed at runtime. - - `replicate`: Optional shard strategy, where each node gets all of the set of shards - available in the tarred dataset, which are permanently pre-allocated and never changed at runtime. - The benefit of replication is that it allows each node to sample data points from the entire - dataset independently of other nodes, and reduces dependence on value of `shuffle_n`. - - .. warning:: - Replicated strategy allows every node to sample the entire set of available tarfiles, - and therefore more than one node may sample the same tarfile, and even sample the same - data points! As such, there is no assured guarantee that all samples in the dataset will be - sampled at least once during 1 epoch. Scattered strategy, on the other hand, on specific - occasions (when the number of shards is not divisible with ``world_size``), will not sample - the entire dataset. For these reasons it is not advisable to use tarred datasets as validation - or test datasets. - global_rank (int): Worker rank, used for partitioning shards. Defaults to 0. - world_size (int): Total number of processes, used for partitioning shards. Defaults to 0. - is_regression_task (bool): Whether it is a regression task. Defualts to False. - """ - - def _collate_fn(self, batch): - return _speech_collate_fn(batch, pad_id=0) - - -class TarredAudioToSpeechLabelDataset(_TarredAudioLabelDataset): - """ - A similar Dataset to the AudioToSpeechLabelDataset, but which loads tarred audio files. - - Accepts a single comma-separated JSON manifest file (in the same style as for the AudioToSpeechLabelDataset), - as well as the path(s) to the tarball(s) containing the wav files. Each line of the manifest should - contain the information for one audio file, including at least the transcript and name of the audio - file within the tarball. - - Valid formats for the audio_tar_filepaths argument include: - (1) a single string that can be brace-expanded, e.g. 'path/to/audio.tar' or 'path/to/audio_{1..100}.tar.gz', or - (2) a list of file paths that will not be brace-expanded, e.g. ['audio_1.tar', 'audio_2.tar', ...]. - - See the WebDataset documentation for more information about accepted data and input formats. - - If using multiple processes the number of shards should be divisible by the number of workers to ensure an - even split among workers. If it is not divisible, logging will give a warning but training will proceed. - In addition, if using mutiprocessing, each shard MUST HAVE THE SAME NUMBER OF ENTRIES after filtering - is applied. We currently do not check for this, but your program may hang if the shards are uneven! - - Notice that a few arguments are different from the AudioToBPEDataset; for example, shuffle (bool) has been - replaced by shuffle_n (int). - - Additionally, please note that the len() of this DataLayer is assumed to be the length of the manifest - after filtering. An incorrect manifest length may lead to some DataLoader issues down the line. - - Args: - audio_tar_filepaths: Either a list of audio tarball filepaths, or a - string (can be brace-expandable). - manifest_filepath (str): Path to the manifest. - labels (list): Dataset parameter. - List of target classes that can be output by the speaker recognition model. - featurizer - shuffle_n (int): How many samples to look ahead and load to be shuffled. - See WebDataset documentation for more details. - Defaults to 0. - min_duration (float): Dataset parameter. - All training files which have a duration less than min_duration - are dropped. Note: Duration is read from the manifest JSON. - Defaults to 0.1. - max_duration (float): Dataset parameter. - All training files which have a duration more than max_duration - are dropped. Note: Duration is read from the manifest JSON. - Defaults to None. - trim(bool): Whether to use trim silence from beginning and end - of audio signal using librosa.effects.trim(). - Defaults to False. - window_length_in_sec (float): time length of window/slice (in seconds) # Pass this only for speaker recognition and VAD task - 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. - normalize_audio (bool): Whether to normalize audio signal. Defaults to False. - shard_strategy (str): Tarred dataset shard distribution strategy chosen as a str value during ddp. - - `scatter`: The default shard strategy applied by WebDataset, where each node gets - a unique set of shards, which are permanently pre-allocated and never changed at runtime. - - `replicate`: Optional shard strategy, where each node gets all of the set of shards - available in the tarred dataset, which are permanently pre-allocated and never changed at runtime. - The benefit of replication is that it allows each node to sample data points from the entire - dataset independently of other nodes, and reduces dependence on value of `shuffle_n`. - - .. warning:: - Replicated strategy allows every node to sample the entire set of available tarfiles, - and therefore more than one node may sample the same tarfile, and even sample the same - data points! As such, there is no assured guarantee that all samples in the dataset will be - sampled at least once during 1 epoch. Scattered strategy, on the other hand, on specific - occasions (when the number of shards is not divisible with ``world_size``), will not sample - the entire dataset. For these reasons it is not advisable to use tarred datasets as validation - or test datasets. - global_rank (int): Worker rank, used for partitioning shards. Defaults to 0. - world_size (int): Total number of processes, used for partitioning shards. Defaults to 0. - """ - - def __init__( - self, - *, - audio_tar_filepaths: Union[str, List[str]], - manifest_filepath: Union[str, List[str]], - labels: List[str], - featurizer, - shuffle_n: int = 0, - min_duration: Optional[float] = 0.1, - max_duration: Optional[float] = None, - trim: bool = False, - window_length_in_sec: Optional[float] = 8, - shift_length_in_sec: Optional[float] = 1, - normalize_audio: bool = False, - shard_strategy: str = "scatter", - global_rank: int = 0, - world_size: int = 0, - ): - logging.info("Window/slice length considered for collate func is {}".format(window_length_in_sec)) - logging.info("Shift length considered for collate func is {}".format(shift_length_in_sec)) - self.window_length_in_sec = window_length_in_sec - self.shift_length_in_sec = shift_length_in_sec - self.normalize_audio = normalize_audio - - super().__init__( - audio_tar_filepaths=audio_tar_filepaths, - manifest_filepath=manifest_filepath, - labels=labels, - featurizer=featurizer, - shuffle_n=shuffle_n, - min_duration=min_duration, - max_duration=max_duration, - trim=trim, - shard_strategy=shard_strategy, - global_rank=global_rank, - world_size=world_size, - ) - - def fixed_seq_collate_fn(self, batch): - return _fixed_seq_collate_fn(self, batch) - - def sliced_seq_collate_fn(self, batch): - raise NotImplementedError - - def vad_frame_seq_collate_fn(self, batch): - return _vad_frame_seq_collate_fn(self, batch) - - -class AudioToMultiLabelDataset(Dataset): - """ - Dataset that loads a json file containing paths to audio files, durations (in seconds), and a sequence of labels. - Each new line is a different sample. Example below: - {"audio_filepath": "/path/to/audio_wav_0.wav", "duration": time_in_sec_0, "label": \ - "0 1 1 0 1", "offset": offset_in_sec_0} - ... - {"audio_filepath": "/path/to/audio_wav_n.wav", "duration": time_in_sec_n, "label": \ - "0 1 0 0 1", "offset": offset_in_sec_n} - Args: - manifest_filepath (Union[str, List[str]]): Path to manifest json as described above. Can - be comma-separated paths. - labels (Optional[list]): String containing all the possible labels to map to - if None then automatically picks from ASRSpeechLabel collection. - min_duration (float): Dataset parameter. - All training files which have a duration less than min_duration - are dropped. Note: Duration is read from the manifest JSON. - Defaults to 0.1. - max_duration (float): Dataset parameter. - All training files which have a duration more than max_duration - are dropped. Note: Duration is read from the manifest JSON. - Defaults to None. - trim_silence (bool): Whether to use trim silence from beginning and end - of audio signal using librosa.effects.trim(). - Defaults to False. - channel selector (Union[str, int, List[int]]): string denoting the downmix mode, an integer denoting the channel to be selected, or an iterable - of integers denoting a subset of channels. Channel selector is using zero-based indexing. - If set to `None`, the original signal will be used. - window_length_in_sec (float): length of window/slice (in seconds) - Use this for speaker recognition and VAD tasks. - shift_length_in_sec (float): amount of shift of window for generating the frame for VAD task in a batch - Use this for VAD task during inference. - normalize_audio (bool): Whether to normalize audio signal. - Defaults to False. - is_regression_task (bool): Whether the dataset is for a regression task instead of classification. - Defaults to False. - cal_labels_occurrence (bool): Whether to calculate occurrence of labels - Defaults to False. - delimiter (Optional[str]): Delimiter to use when splitting the label string, default to None. - normalize_audio_db (Optional[float]): normalize audio signal to a target db, default to None. - """ - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - """Returns definitions of module output ports.""" - - output_types = { - 'audio_signal': NeuralType( - ('B', 'T'), - ( - AudioSignal(freq=self._sample_rate) - if self is not None and hasattr(self, '_sample_rate') - else AudioSignal() - ), - ), - 'a_sig_length': NeuralType(tuple('B'), LengthsType()), - } - - if self.is_regression_task: - output_types.update( - { - 'targets': NeuralType(tuple('B, T'), RegressionValuesType()), - 'targets_length': NeuralType(tuple('B'), LengthsType()), - } - ) - else: - output_types.update( - { - 'label': NeuralType(('B', 'T'), LabelsType()), - 'label_length': NeuralType(tuple('B'), LengthsType()), - } - ) - - return output_types - - def __init__( - self, - *, - manifest_filepath: Union[str, List[str]], - sample_rate: int, - labels: Optional[List[str]] = None, - int_values: bool = False, - augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None, - min_duration: Optional[float] = 0.1, - max_duration: Optional[float] = None, - trim_silence: bool = False, - channel_selector: Optional[Union[str, int, List[int]]] = None, - is_regression_task: bool = False, - cal_labels_occurrence: Optional[bool] = False, - delimiter: Optional[str] = None, - normalize_audio_db: Optional[float] = None, - ): - super().__init__() - if isinstance(manifest_filepath, str): - manifest_filepath = manifest_filepath.split(',') - - self.delimiter = delimiter - self.normalize_audio_db = normalize_audio_db - - self.collection = collections.ASRSpeechLabel( - manifests_files=manifest_filepath, - min_duration=min_duration, - max_duration=max_duration, - is_regression_task=is_regression_task, - cal_labels_occurrence=cal_labels_occurrence, - delimiter=delimiter, - ) - - self.featurizer = WaveformFeaturizer(sample_rate=sample_rate, int_values=int_values, augmentor=augmentor) - self.trim = trim_silence - self.channel_selector = channel_selector - self.is_regression_task = is_regression_task - self.id2occurrence = {} - self.labels_occurrence = None - - if not is_regression_task: - self.labels = labels if labels else self._get_label_set() - self.num_classes = len(self.labels) if self.labels is not None else 1 - self.label2id, self.id2label = {}, {} - for label_id, label in enumerate(self.labels): - self.label2id[label] = label_id - self.id2label[label_id] = label - if cal_labels_occurrence: - self.id2occurrence[label_id] = self.collection.labels_occurrence[label] - self.labels_occurrence.append(self.id2occurrence[label_id]) - - for idx in range(len(self.labels[:5])): - logging.debug(" label id {} and its mapped label {}".format(idx, self.id2label[idx])) - else: - self.labels = [] - self.num_classes = 1 - - def _get_label_set(self): - labels = [] - for sample in self.collection: - label_str = sample.label - if label_str: - label_str_list = label_str.split(self.delimiter) if self.delimiter else label_str.split() - labels.extend(label_str_list) - return sorted(set(labels)) - - def _label_str_to_tensor(self, label_str: str): - labels = label_str.split(self.delimiter) if self.delimiter else label_str.split() - - if self.is_regression_task: - labels = [float(s) for s in labels] - labels = torch.tensor(labels).float() - else: - labels = [self.label2id[s] for s in labels] - labels = torch.tensor(labels).long() - return labels - - def __len__(self): - return len(self.collection) - - def __getitem__(self, index): - sample = self.collection[index] - - offset = sample.offset - - if offset is None: - offset = 0 - - features = self.featurizer.process( - sample.audio_file, - offset=offset, - duration=sample.duration, - trim=self.trim, - channel_selector=self.channel_selector, - normalize_db=self.normalize_audio_db, - ) - - f, fl = features, torch.tensor(features.size(0)).long() - - t = self._label_str_to_tensor(sample.label) - - tl = torch.tensor(t.size(0)).long() - - return f, fl, t, tl - - def _collate_fn(self, batch): - return _speech_collate_fn(batch, pad_id=0) - - -class TarredAudioToMultiLabelDataset(IterableDataset): - """ - A similar Dataset to the AudioToMultiLabelDataset, but which loads tarred audio files. - - Accepts a single comma-separated JSON manifest file (in the same style as for the AudioToSpeechLabelDataset), - as well as the path(s) to the tarball(s) containing the wav files. Each line of the manifest should - contain the information for one audio file, including at least the transcript and name of the audio - file within the tarball. - - Valid formats for the audio_tar_filepaths argument include: - (1) a single string that can be brace-expanded, e.g. 'path/to/audio.tar' or 'path/to/audio_{1..100}.tar.gz', or - (2) a list of file paths that will not be brace-expanded, e.g. ['audio_1.tar', 'audio_2.tar', ...]. - - See the WebDataset documentation for more information about accepted data and input formats. - - If using multiple processes the number of shards should be divisible by the number of workers to ensure an - even split among workers. If it is not divisible, logging will give a warning but training will proceed. - In addition, if using mutiprocessing, each shard MUST HAVE THE SAME NUMBER OF ENTRIES after filtering - is applied. We currently do not check for this, but your program may hang if the shards are uneven! - - Notice that a few arguments are different from the AudioToBPEDataset; for example, shuffle (bool) has been - replaced by shuffle_n (int). - - Additionally, please note that the len() of this DataLayer is assumed to be the length of the manifest - after filtering. An incorrect manifest length may lead to some DataLoader issues down the line. - - Args: - audio_tar_filepaths: Either a list of audio tarball filepaths, or a - string (can be brace-expandable). - manifest_filepath (str): Path to the manifest. - labels (list): Dataset parameter. - List of target classes that can be output by the speaker recognition model. - shuffle_n (int): How many samples to look ahead and load to be shuffled. - See WebDataset documentation for more details. - Defaults to 0. - min_duration (float): Dataset parameter. - All training files which have a duration less than min_duration - are dropped. Note: Duration is read from the manifest JSON. - Defaults to 0.1. - max_duration (float): Dataset parameter. - All training files which have a duration more than max_duration - are dropped. Note: Duration is read from the manifest JSON. - Defaults to None. - trim(bool): Whether to use trim silence from beginning and end - of audio signal using librosa.effects.trim(). - Defaults to False. - window_length_in_sec (float): time length of window/slice (in seconds) # Pass this only for speaker recognition and VAD task - 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. - normalize_audio (bool): Whether to normalize audio signal. Defaults to False. - shard_strategy (str): Tarred dataset shard distribution strategy chosen as a str value during ddp. - - `scatter`: The default shard strategy applied by WebDataset, where each node gets - a unique set of shards, which are permanently pre-allocated and never changed at runtime. - - `replicate`: Optional shard strategy, where each node gets all of the set of shards - available in the tarred dataset, which are permanently pre-allocated and never changed at runtime. - The benefit of replication is that it allows each node to sample data points from the entire - dataset independently of other nodes, and reduces dependence on value of `shuffle_n`. - - .. warning:: - Replicated strategy allows every node to sample the entire set of available tarfiles, - and therefore more than one node may sample the same tarfile, and even sample the same - data points! As such, there is no assured guarantee that all samples in the dataset will be - sampled at least once during 1 epoch. Scattered strategy, on the other hand, on specific - occasions (when the number of shards is not divisible with ``world_size``), will not sample - the entire dataset. For these reasons it is not advisable to use tarred datasets as validation - or test datasets. - global_rank (int): Worker rank, used for partitioning shards. Defaults to 0. - world_size (int): Total number of processes, used for partitioning shards. Defaults to 0. - delimiter (Optional[str]): Delimiter to use when splitting the label string, default to None. - normalize_audio_db (Optional[float]): normalize audio signal to a target db, default to None. - """ - - def __init__( - self, - *, - audio_tar_filepaths: Union[str, List[str]], - manifest_filepath: Union[str, List[str]], - sample_rate: int, - labels: Optional[List[str]] = None, - shuffle_n: int = 0, - int_values: bool = False, - augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None, - min_duration: Optional[float] = 0.1, - max_duration: Optional[float] = None, - trim_silence: bool = False, - is_regression_task: bool = False, - shard_strategy: str = "scatter", - global_rank: int = 0, - world_size: int = 0, - delimiter: Optional[str] = None, - normalize_audio_db: Optional[float] = None, - ): - super().__init__() - if isinstance(manifest_filepath, str): - manifest_filepath = manifest_filepath.split(',') - - self.trim = trim_silence - self.is_regression_task = is_regression_task - self.delimiter = delimiter - self.normalize_audio_db = normalize_audio_db - - self.collection = collections.ASRSpeechLabel( - manifests_files=manifest_filepath, - min_duration=min_duration, - max_duration=max_duration, - is_regression_task=is_regression_task, - index_by_file_id=True, - ) - self.file_occurence = count_occurence(self.collection.mapping) - - self.featurizer = WaveformFeaturizer(sample_rate=sample_rate, int_values=int_values, augmentor=augmentor) - - if not is_regression_task: - self.labels = labels if labels else self._get_label_set() - self.num_classes = len(self.labels) if self.labels is not None else 1 - self.label2id, self.id2label = {}, {} - for label_id, label in enumerate(self.labels): - self.label2id[label] = label_id - self.id2label[label_id] = label - for idx in range(len(self.labels[:5])): - logging.debug(" label id {} and its mapped label {}".format(idx, self.id2label[idx])) - else: - self.labels = [] - self.num_classes = 1 - - audio_tar_filepaths = expand_sharded_filepaths( - sharded_filepaths=audio_tar_filepaths, - shard_strategy=shard_strategy, - world_size=world_size, - global_rank=global_rank, - ) - - # Put together WebDataset - self._dataset = wds.DataPipeline( - wds.SimpleShardList(urls=audio_tar_filepaths), - webdataset_split_by_workers, - wds.shuffle(shuffle_n), - wds.tarfile_to_samples(), - wds.rename(audio=VALID_FILE_FORMATS, key='__key__'), - wds.to_tuple('audio', 'key'), - self._filter, - wds.map(self._build_sample), - ) - - def _get_label_set(self): - labels = [] - for sample in self.collection: - label_str = sample.label - if label_str: - label_str_list = label_str.split(self.delimiter) if self.delimiter else label_str.split() - labels.extend(label_str_list) - return sorted(set(labels)) - - def _label_str_to_tensor(self, label_str: str): - labels = label_str.split(self.delimiter) if self.delimiter else label_str.split() - - if self.is_regression_task: - labels = [float(s) for s in labels] - labels = torch.tensor(labels).float() - else: - labels = [self.label2id[s] for s in labels] - labels = torch.tensor(labels).long() - return labels - - def _filter(self, iterator): - """This function is used to remove samples that have been filtered out by ASRSpeechLabel already. - Otherwise, we would get a KeyError as _build_sample attempts to find the manifest entry for a sample - that was filtered out (e.g. for duration). - Note that if using multi-GPU training, filtering may lead to an imbalance in samples in each shard, - which may make your code hang as one process will finish before the other. - """ - - class TarredAudioFilter: - def __init__(self, collection, file_occurence): - self.iterator = iterator - self.collection = collection - self.file_occurence = file_occurence - self._iterable = self._internal_generator() - - def __iter__(self): - self._iterable = self._internal_generator() - return self - - def __next__(self): - try: - values = next(self._iterable) - except StopIteration: - # reset generator - self._iterable = self._internal_generator() - values = next(self._iterable) - - return values - - def _internal_generator(self): - """ - WebDataset requires an Iterator, but we require an iterable that yields 1-or-more - values per value inside self.iterator. - - Therefore wrap the iterator with a generator function that will yield 1-or-more - values per sample in the iterator. - """ - for _, tup in enumerate(self.iterator): - audio_bytes, audio_filename = tup - - file_id, _ = os.path.splitext(os.path.basename(audio_filename)) - if audio_filename in self.file_occurence: - for j in range(0, self.file_occurence[file_id]): - if j == 0: - audio_filename = file_id - else: - audio_filename = file_id + "-sub" + str(j) - yield audio_bytes, audio_filename - - return TarredAudioFilter(self.collection, self.file_occurence) - - def _build_sample(self, tup): - """Builds the training sample by combining the data from the WebDataset with the manifest info.""" - audio_bytes, audio_filename = tup - # Grab manifest entry from self.collection - file_id, _ = os.path.splitext(os.path.basename(audio_filename)) - - manifest_idx = self.collection.mapping[file_id] - manifest_entry = self.collection[manifest_idx] - - offset = manifest_entry.offset - if offset is None: - offset = 0 - - # Convert audio bytes to IO stream for processing (for SoundFile to read) - audio_filestream = io.BytesIO(audio_bytes) - features = self.featurizer.process( - audio_filestream, - offset=offset, - duration=manifest_entry.duration, - trim=self.trim, - normalize_db=self.normalize_audio_db, - ) - - audio_filestream.close() - - # Audio features - f, fl = features, torch.tensor(features.shape[0]).long() - - t = self._label_str_to_tensor(manifest_entry.label) - - tl = torch.tensor(t.size(0)).long() - - return f, fl, t, tl - - def __iter__(self): - return self._dataset.__iter__() - - def __len__(self): - return len(self.collection) - - def _collate_fn(self, batch): - return _speech_collate_fn(batch, pad_id=0) - - -class AudioPairToLabelDataset(AudioToSpeechLabelDataset): - """ - Dataset class for audio pairs classification tasks, such as calculating EER for speaker verification. - The input manifest file should contain pairs of audio files and a label. It's format is almost the same as - `AudioToSpeechLabelDataset` except that the `audio_filepath` field should be a list of two audio file paths - instead of one, and that `offset` and `duration` are not used as the dataset class will load the whole audio. - - Example of a line in the manifest file: - { - "audio_filepath": ["/path/to/audio_wav_0.wav", "/path/to/audio_wav_1.wav"], - "duration": null, # not used, will load the whole audio - "offset": 0.0, # not used, will load the whole audio - "label": "0" # label for the pair, can be a string or an integer - } - - """ - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - """Returns definitions of module output ports.""" - - output_types = { - 'audio_signal': NeuralType( - ('B', 'T'), - ( - AudioSignal(freq=self._sample_rate) - if self is not None and hasattr(self, '_sample_rate') - else AudioSignal() - ), - ), - 'a_sig_length': NeuralType(tuple('B'), LengthsType()), - 'audio_signal_2': NeuralType( - ('B', 'T'), - ( - AudioSignal(freq=self._sample_rate) - if self is not None and hasattr(self, '_sample_rate') - else AudioSignal() - ), - ), - 'a_sig_length_2': NeuralType(tuple('B'), LengthsType()), - 'label': NeuralType(tuple('B'), LabelsType()), - 'label_length': NeuralType(tuple('B'), LengthsType()), - } - - return output_types - - def __init__( - self, - *, - manifest_filepath: str | List[str], - labels: List[str], - featurizer, - min_duration: float | None = 0.1, - max_duration: float | None = None, - trim: bool = False, - window_length_in_sec: float | None = 8, - shift_length_in_sec: float | None = 1, - normalize_audio: bool = False, - **kwargs, - ): - super().__init__( - manifest_filepath=manifest_filepath, - labels=labels, - featurizer=featurizer, - min_duration=min_duration, - max_duration=max_duration, - trim=trim, - window_length_in_sec=window_length_in_sec, - shift_length_in_sec=shift_length_in_sec, - normalize_audio=normalize_audio, - is_regression_task=False, - cal_labels_occurrence=False, - ) - - def __getitem__(self, index): - sample = self.collection[index] - - audio_pair = sample.audio_file - - features = self.featurizer.process(audio_pair[0], offset=0, duration=None, trim=self.trim) - f, fl = features, torch.tensor(features.shape[0]).long() - - features2 = self.featurizer.process(audio_pair[1], offset=0, duration=None, trim=self.trim) - f2, fl2 = features2, torch.tensor(features2.shape[0]).long() - - t = torch.tensor(self.label2id[sample.label]).long() - tl = torch.tensor(1).long() # For compatibility with collate_fn used later - - return f, fl, f2, fl2, t, tl - - def fixed_seq_collate_fn(self, batch): - audio1, audio_len1, audio2, audio_len2, label, label_len = zip(*batch) - - batch1 = list(zip(audio1, audio_len1, label, label_len)) - a_sig1, a_sig_len1, pair_label, pair_label_len = _fixed_seq_collate_fn(self, batch1) - batch2 = list(zip(audio2, audio_len2, label, label_len)) - a_sig2, a_sig_len2, _, _ = _fixed_seq_collate_fn(self, batch2) - return a_sig1, a_sig_len1, a_sig2, a_sig_len2, pair_label, pair_label_len diff --git a/nemo/collections/asr/data/audio_to_label_dataset.py b/nemo/collections/asr/data/audio_to_label_dataset.py deleted file mode 100644 index dcead6df94b8c898038c2ffc744ad478bb4e74fc..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/data/audio_to_label_dataset.py +++ /dev/null @@ -1,304 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import copy - -from omegaconf import DictConfig - -from nemo.collections.asr.data import audio_to_label -from nemo.collections.asr.data.audio_to_text_dataset import convert_to_config_list, get_chain_dataset -from nemo.collections.asr.parts.preprocessing.perturb import process_augmentations -from nemo.collections.common.data.dataset import ConcatDataset - - -def get_classification_label_dataset(featurizer, config: dict) -> audio_to_label.AudioToClassificationLabelDataset: - """ - Instantiates a Classification AudioLabelDataset. - - Args: - config: Config of the AudioToClassificationLabelDataset. - - Returns: - An instance of AudioToClassificationLabelDataset. - """ - dataset = audio_to_label.AudioToClassificationLabelDataset( - manifest_filepath=config['manifest_filepath'], - labels=config['labels'], - featurizer=featurizer, - max_duration=config.get('max_duration', None), - min_duration=config.get('min_duration', None), - trim=config.get('trim_silence', False), - is_regression_task=config.get('is_regression_task', False), - cal_labels_occurrence=config.get('cal_labels_occurrence', False), - ) - return dataset - - -def get_speech_label_dataset(featurizer, config: dict) -> audio_to_label.AudioToSpeechLabelDataset: - """ - Instantiates a Speech Label (e.g. VAD, speaker recognition) AudioLabelDataset. - - Args: - config: Config of the AudioToSpeechLabelDataSet. - - Returns: - An instance of AudioToSpeechLabelDataset. - """ - dataset = audio_to_label.AudioToSpeechLabelDataset( - manifest_filepath=config['manifest_filepath'], - labels=config['labels'], - featurizer=featurizer, - max_duration=config.get('max_duration', None), - min_duration=config.get('min_duration', None), - trim=config.get('trim_silence', False), - window_length_in_sec=config.get('window_length_in_sec', 0.31), - shift_length_in_sec=config.get('shift_length_in_sec', 0.01), - normalize_audio=config.get('normalize_audio', False), - cal_labels_occurrence=config.get('cal_labels_occurrence', False), - ) - return dataset - - -def get_tarred_classification_label_dataset( - featurizer, config: dict, shuffle_n: int, global_rank: int, world_size: int -) -> audio_to_label.TarredAudioToClassificationLabelDataset: - """ - Instantiates a Classification TarredAudioLabelDataset. - - Args: - config: Config of the TarredAudioToClassificationLabelDataset. - shuffle_n: How many samples to look ahead and load to be shuffled. - See WebDataset documentation for more details. - global_rank: Global rank of this device. - world_size: Global world size in the training method. - - Returns: - An instance of TarredAudioToClassificationLabelDataset. - """ - tarred_audio_filepaths = config['tarred_audio_filepaths'] - manifest_filepaths = config['manifest_filepath'] - datasets = [] - tarred_audio_filepaths = convert_to_config_list(tarred_audio_filepaths) - manifest_filepaths = convert_to_config_list(manifest_filepaths) - - bucketing_weights = config.get('bucketing_weights', None) # For upsampling buckets - if bucketing_weights: - for idx, weight in enumerate(bucketing_weights): - if not isinstance(weight, int) or weight <= 0: - raise ValueError(f"bucket weights must be positive integers") - - if len(manifest_filepaths) != len(tarred_audio_filepaths): - raise ValueError( - f"manifest_filepaths (length={len(manifest_filepaths)}) and tarred_audio_filepaths (length={len(tarred_audio_filepaths)}) need to have the same number of buckets." - ) - - for dataset_idx, (tarred_audio_filepath, manifest_filepath) in enumerate( - zip(tarred_audio_filepaths, manifest_filepaths) - ): - if len(tarred_audio_filepath) == 1: - tarred_audio_filepath = tarred_audio_filepath[0] - dataset = audio_to_label.TarredAudioToClassificationLabelDataset( - audio_tar_filepaths=tarred_audio_filepath, - manifest_filepath=manifest_filepath, - labels=config['labels'], - featurizer=featurizer, - shuffle_n=shuffle_n, - max_duration=config.get('max_duration', None), - min_duration=config.get('min_duration', None), - trim=config.get('trim_silence', False), - shard_strategy=config.get('tarred_shard_strategy', 'scatter'), - global_rank=global_rank, - world_size=world_size, - is_regression_task=config.get('is_regression_task', False), - ) - - if bucketing_weights: - [datasets.append(dataset) for _ in range(bucketing_weights[dataset_idx])] - else: - datasets.append(dataset) - - return get_chain_dataset(datasets=datasets, ds_config=config, rank=global_rank) - - -def get_concat_tarred_speech_label_dataset( - featurizer, config: dict, shuffle_n: int, global_rank: int, world_size: int, -): - tarred_audio_filepaths = config['tarred_audio_filepaths'] - manifest_filepaths = config['manifest_filepath'] - datasets = [] - for dataset_idx, (tarred_audio_filepath, manifest_filepath) in enumerate( - zip(tarred_audio_filepaths, manifest_filepaths) - ): - conf = copy.deepcopy(config) - conf['manifest_filepath'] = manifest_filepath - conf['tarred_audio_filepaths'] = tarred_audio_filepath - dataset = get_tarred_speech_label_dataset( - config=conf, featurizer=featurizer, shuffle_n=shuffle_n, global_rank=global_rank, world_size=world_size, - ) - datasets.append(dataset) - - dataset = ConcatDataset( - datasets, - sampling_technique=config.get('concat_sampling_technique', 'temperature'), - sampling_temperature=config.get('concat_sampling_temperature', 5), - sampling_probabilities=config.get('concat_sampling_probabilities', None), - global_rank=global_rank, - world_size=world_size, - shuffle=config['shuffle'], - ) - return dataset - - -def get_tarred_speech_label_dataset( - featurizer, config: dict, shuffle_n: int, global_rank: int, world_size: int, -) -> audio_to_label.TarredAudioToSpeechLabelDataset: - """ - InInstantiates a Speech Label (e.g. VAD, speaker recognition) TarredAudioLabelDataset. - - Args: - config: Config of the TarredAudioToSpeechLabelDataset. - shuffle_n: How many samples to look ahead and load to be shuffled. - See WebDataset documentation for more details. - global_rank: Global rank of this device. - world_size: Global world size in the training method. - - Returns: - An instance of TarredAudioToSpeechLabelDataset. - """ - tarred_audio_filepaths = config['tarred_audio_filepaths'] - manifest_filepaths = config['manifest_filepath'] - datasets = [] - tarred_audio_filepaths = convert_to_config_list(tarred_audio_filepaths) - manifest_filepaths = convert_to_config_list(manifest_filepaths) - - bucketing_weights = config.get('bucketing_weights', None) # For upsampling buckets - if bucketing_weights: - for idx, weight in enumerate(bucketing_weights): - if not isinstance(weight, int) or weight <= 0: - raise ValueError(f"bucket weights must be positive integers") - - if len(manifest_filepaths) != len(tarred_audio_filepaths): - raise ValueError( - f"manifest_filepaths (length={len(manifest_filepaths)}) and tarred_audio_filepaths (length={len(tarred_audio_filepaths)}) need to have the same number of buckets." - ) - - for dataset_idx, (tarred_audio_filepath, manifest_filepath) in enumerate( - zip(tarred_audio_filepaths, manifest_filepaths) - ): - if len(tarred_audio_filepath) == 1: - tarred_audio_filepath = tarred_audio_filepath[0] - dataset = audio_to_label.TarredAudioToSpeechLabelDataset( - audio_tar_filepaths=tarred_audio_filepath, - manifest_filepath=manifest_filepath, - labels=config['labels'], - featurizer=featurizer, - shuffle_n=shuffle_n, - max_duration=config.get('max_duration', None), - min_duration=config.get('min_duration', None), - trim=config.get('trim_silence', False), - window_length_in_sec=config.get('window_length_in_sec', 8), - shift_length_in_sec=config.get('shift_length_in_sec', 0.075), - normalize_audio=config.get('normalize_audio', False), - shard_strategy=config.get('tarred_shard_strategy', 'scatter'), - global_rank=global_rank, - world_size=world_size, - ) - - if bucketing_weights: - [datasets.append(dataset) for _ in range(bucketing_weights[dataset_idx])] - else: - datasets.append(dataset) - - return get_chain_dataset(datasets=datasets, ds_config=config, rank=global_rank) - - -def get_audio_multi_label_dataset(cfg: DictConfig) -> audio_to_label.AudioToMultiLabelDataset: - if "augmentor" in cfg: - augmentor = process_augmentations(cfg.augmentor) - else: - augmentor = None - - dataset = audio_to_label.AudioToMultiLabelDataset( - manifest_filepath=cfg.get("manifest_filepath"), - sample_rate=cfg.get("sample_rate"), - labels=cfg.get("labels", None), - int_values=cfg.get("int_values", False), - augmentor=augmentor, - min_duration=cfg.get("min_duration", None), - max_duration=cfg.get("max_duration", None), - trim_silence=cfg.get("trim_silence", False), - is_regression_task=cfg.get("is_regression_task", False), - cal_labels_occurrence=cfg.get("cal_labels_occurrence", False), - delimiter=cfg.get("delimiter", None), - normalize_audio_db=cfg.get("normalize_audio_db", None), - ) - return dataset - - -def get_tarred_audio_multi_label_dataset( - cfg: DictConfig, shuffle_n: int, global_rank: int, world_size: int -) -> audio_to_label.TarredAudioToMultiLabelDataset: - - if "augmentor" in cfg: - augmentor = process_augmentations(cfg.augmentor) - else: - augmentor = None - - tarred_audio_filepaths = cfg['tarred_audio_filepaths'] - manifest_filepaths = cfg['manifest_filepath'] - datasets = [] - tarred_audio_filepaths = convert_to_config_list(tarred_audio_filepaths) - manifest_filepaths = convert_to_config_list(manifest_filepaths) - - bucketing_weights = cfg.get('bucketing_weights', None) # For upsampling buckets - if bucketing_weights: - for idx, weight in enumerate(bucketing_weights): - if not isinstance(weight, int) or weight <= 0: - raise ValueError(f"bucket weights must be positive integers") - - if len(manifest_filepaths) != len(tarred_audio_filepaths): - raise ValueError( - f"manifest_filepaths (length={len(manifest_filepaths)}) and tarred_audio_filepaths (length={len(tarred_audio_filepaths)}) need to have the same number of buckets." - ) - - for dataset_idx, (tarred_audio_filepath, manifest_filepath) in enumerate( - zip(tarred_audio_filepaths, manifest_filepaths) - ): - if len(tarred_audio_filepath) == 1: - tarred_audio_filepath = tarred_audio_filepath[0] - - dataset = audio_to_label.TarredAudioToMultiLabelDataset( - audio_tar_filepaths=tarred_audio_filepath, - manifest_filepath=manifest_filepath, - sample_rate=cfg["sample_rate"], - labels=cfg['labels'], - shuffle_n=shuffle_n, - int_values=cfg.get("int_values", False), - augmentor=augmentor, - min_duration=cfg.get('min_duration', None), - max_duration=cfg.get('max_duration', None), - trim_silence=cfg.get('trim_silence', False), - is_regression_task=cfg.get('is_regression_task', False), - delimiter=cfg.get("delimiter", None), - shard_strategy=cfg.get('tarred_shard_strategy', 'scatter'), - global_rank=global_rank, - world_size=world_size, - normalize_audio_db=cfg.get("normalize_audio_db", None), - ) - - if bucketing_weights: - [datasets.append(dataset) for _ in range(bucketing_weights[dataset_idx])] - else: - datasets.append(dataset) - - return get_chain_dataset(datasets=datasets, ds_config=cfg, rank=global_rank) diff --git a/nemo/collections/asr/data/audio_to_text.py b/nemo/collections/asr/data/audio_to_text.py deleted file mode 100644 index 4fb18dedbd92f63fbfa57d9c84be1a9c6c661b65..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/data/audio_to_text.py +++ /dev/null @@ -1,1389 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import io -import json -import math -import multiprocessing -import os -from collections.abc import Iterable as IterableABC -from typing import Callable, Dict, Iterable, List, Optional, Tuple, Union - -import braceexpand -import numpy as np -import torch -from torch.utils.data import ChainDataset -from tqdm import tqdm - -from nemo.collections.asr.parts.preprocessing.features import WaveformFeaturizer -from nemo.collections.asr.parts.preprocessing.segment import ChannelSelectorType -from nemo.collections.asr.parts.preprocessing.segment import available_formats as valid_sf_formats -from nemo.collections.common import tokenizers -from nemo.collections.common.parts.preprocessing import collections, parsers -from nemo.core.classes import Dataset, IterableDataset -from nemo.core.neural_types import * -from nemo.utils import logging -from nemo.utils import webdataset as wds -from nemo.utils.data_utils import DataStoreObject, datastore_object_get, is_datastore_cache_shared, is_datastore_path -from nemo.utils.decorators import deprecated -from nemo.utils.distributed import webdataset_split_by_workers -from nemo.utils.get_rank import is_global_rank_zero - -__all__ = [ - 'AudioToCharDataset', - 'AudioToBPEDataset', - 'TarredAudioToCharDataset', - 'TarredAudioToBPEDataset', -] - -VALID_FILE_FORMATS = ';'.join(['wav', 'mp3', 'flac', 'opus'] + [fmt.lower() for fmt in valid_sf_formats.keys()]) - - -def _speech_collate_fn(batch, pad_id): - """collate batch of audio sig, audio len, tokens, tokens len - Args: - batch (Optional[FloatTensor], Optional[LongTensor], LongTensor, - LongTensor): A tuple of tuples of signal, signal lengths, - encoded tokens, and encoded tokens length. This collate func - assumes the signals are 1d torch tensors (i.e. mono audio). - """ - packed_batch = list(zip(*batch)) - if len(packed_batch) == 5: - _, audio_lengths, _, tokens_lengths, sample_ids = packed_batch - elif len(packed_batch) == 4: - sample_ids = None - _, audio_lengths, _, tokens_lengths = packed_batch - else: - raise ValueError("Expects 4 or 5 tensors in the batch!") - max_audio_len = 0 - has_audio = audio_lengths[0] is not None - if has_audio: - max_audio_len = max(audio_lengths).item() - has_tokens = tokens_lengths[0] is not None - if has_tokens: - max_tokens_len = max(tokens_lengths).item() - - audio_signal, tokens = [], [] - for b in batch: - if len(b) == 5: - sig, sig_len, tokens_i, tokens_i_len, _ = b - else: - sig, sig_len, tokens_i, tokens_i_len = b - if has_audio: - sig_len = sig_len.item() - if sig_len < max_audio_len: - pad = (0, max_audio_len - sig_len) - sig = torch.nn.functional.pad(sig, pad) - audio_signal.append(sig) - if has_tokens: - tokens_i_len = tokens_i_len.item() - if tokens_i_len < max_tokens_len: - pad = (0, max_tokens_len - tokens_i_len) - tokens_i = torch.nn.functional.pad(tokens_i, pad, value=pad_id) - tokens.append(tokens_i) - - if has_audio: - audio_signal = torch.stack(audio_signal) - audio_lengths = torch.stack(audio_lengths) - else: - audio_signal, audio_lengths = None, None - if has_tokens: - tokens = torch.stack(tokens) - tokens_lengths = torch.stack(tokens_lengths) - else: - tokens = None - tokens_lengths = None - if sample_ids is None: - return audio_signal, audio_lengths, tokens, tokens_lengths - else: - sample_ids = torch.tensor(sample_ids, dtype=torch.int32) - return audio_signal, audio_lengths, tokens, tokens_lengths, sample_ids - - -class ASRManifestProcessor: - """ - Class that processes a manifest json file containing paths to audio files, transcripts, and durations (in seconds). - Each new line is a different sample. Example below: - {"audio_filepath": "/path/to/audio.wav", "text_filepath": "/path/to/audio.txt", "duration": 23.147} - ... - {"audio_filepath": "/path/to/audio.wav", "text": "the transcription", "offset": 301.75, "duration": 0.82, "utt": - "utterance_id", "ctm_utt": "en_4156", "side": "A"} - Args: - manifest_filepath: Path to manifest json as described above. Can be comma-separated paths. - parser: Str for a language specific preprocessor or a callable. - max_duration: If audio exceeds this length, do not include in dataset. - min_duration: If audio is less than this length, do not include in dataset. - max_utts: Limit number of utterances. - bos_id: Id of beginning of sequence symbol to append if not None. - eos_id: Id of end of sequence symbol to append if not None. - pad_id: Id of pad symbol. Defaults to 0. - """ - - def __init__( - self, - manifest_filepath: str, - parser: Union[str, Callable], - max_duration: Optional[float] = None, - min_duration: Optional[float] = None, - max_utts: int = 0, - bos_id: Optional[int] = None, - eos_id: Optional[int] = None, - pad_id: int = 0, - index_by_file_id: bool = False, - manifest_parse_func: Optional[Callable] = None, - ): - self.parser = parser - - self.collection = collections.ASRAudioText( - manifests_files=manifest_filepath, - parser=parser, - min_duration=min_duration, - max_duration=max_duration, - max_number=max_utts, - index_by_file_id=index_by_file_id, - parse_func=manifest_parse_func, - ) - - self.eos_id = eos_id - self.bos_id = bos_id - self.pad_id = pad_id - - def process_text_by_id(self, index: int) -> Tuple[List[int], int]: - sample = self.collection[index] - return self.process_text_by_sample(sample) - - def process_text_by_file_id(self, file_id: str) -> Tuple[List[int], int]: - manifest_idx = self.collection.mapping[file_id][0] - sample = self.collection[manifest_idx] - return self.process_text_by_sample(sample) - - def process_text_by_sample(self, sample: collections.ASRAudioText.OUTPUT_TYPE) -> Tuple[List[int], int]: - t, tl = sample.text_tokens, len(sample.text_tokens) - - if self.bos_id is not None: - t = [self.bos_id] + t - tl += 1 - if self.eos_id is not None: - t = t + [self.eos_id] - tl += 1 - - return t, tl - - -def expand_sharded_filepaths(sharded_filepaths, shard_strategy: str, world_size: int, global_rank: int): - valid_shard_strategies = ['scatter', 'replicate'] - if shard_strategy not in valid_shard_strategies: - raise ValueError(f"`shard_strategy` must be one of {valid_shard_strategies}") - - if isinstance(sharded_filepaths, str): - # Replace '(' and '[' with '{' - brace_keys_open = ['(', '[', '<', '_OP_'] - for bkey in brace_keys_open: - if bkey in sharded_filepaths: - sharded_filepaths = sharded_filepaths.replace(bkey, "{") - - # Replace ')' and ']' with '}' - brace_keys_close = [')', ']', '>', '_CL_'] - for bkey in brace_keys_close: - if bkey in sharded_filepaths: - sharded_filepaths = sharded_filepaths.replace(bkey, "}") - - if isinstance(sharded_filepaths, str): - # Brace expand, set escape=False for Windows compatibility - sharded_filepaths = list(braceexpand.braceexpand(sharded_filepaths, escape=False)) - - # Check for distributed and partition shards accordingly - if world_size > 1: - if shard_strategy == 'scatter': - logging.info("All tarred dataset shards will be scattered evenly across all nodes.") - - if len(sharded_filepaths) % world_size != 0: - logging.warning( - f"Number of shards in tarred dataset ({len(sharded_filepaths)}) is not divisible " - f"by number of distributed workers ({world_size})." - ) - - begin_idx = (len(sharded_filepaths) // world_size) * global_rank - end_idx = begin_idx + len(sharded_filepaths) // world_size - sharded_filepaths = sharded_filepaths[begin_idx:end_idx] - logging.info( - "Partitioning tarred dataset: process (%d) taking shards [%d, %d)", global_rank, begin_idx, end_idx - ) - - elif shard_strategy == 'replicate': - logging.info("All tarred dataset shards will be replicated across all nodes.") - else: - raise ValueError(f"Invalid shard strategy ! Allowed values are : {valid_shard_strategies}") - - return sharded_filepaths - - -def cache_datastore_manifests( - manifest_filepaths: Union[str, List[str]], - cache_audio: bool = False, - shared_cache: Optional[bool] = None, - num_workers: Optional[int] = None, - max_num_workers: int = 20, -): - """Cache manifests and audio from an object store. - It is assumed that remote manifests are using relative paths. - - Args: - manifest_filepaths: list of paths to manifest files (list of strings or a string with `,` as separator) - cache_audio: If True, audio from manifest will also be cached - shared_cache: Optional, True if cache is shared across all nodes - num_workers: Optional, number of workers to be used for download - max_num_workers: max number of workers to be used for download, used when setting num_workers automatically - """ - if isinstance(manifest_filepaths, str): - manifest_filepaths = manifest_filepaths.split(',') - - num_datastore_manifests = sum([is_datastore_path(f) for f in manifest_filepaths]) - - if num_datastore_manifests > 0: - # Local utility function - def cache_data(manifest_filepaths, cache_audio, num_workers, max_num_workers): - """Cache manifests and audio data from object store.""" - # Determine the number of workers to use - if num_workers is None: - num_workers = os.cpu_count() - 1 - num_workers = min(num_workers, max_num_workers) - - # Process each manifest file - for manifest_file in manifest_filepaths: - # If manifest is on a data store, then cache it. - # Otherwise, nothing to do. - if is_datastore_path(manifest_file): - logging.info('Cache manifest file: %s', manifest_file) - cached_manifest_file = DataStoreObject(manifest_file).get() - logging.info('Cached at: %s', str(cached_manifest_file)) - - if cache_audio: - # Each audio file from manifest will be cached. - logging.info('Cache audio from manifest file: %s', manifest_file) - # Assumes that manifest is using relative paths - manifest_dir = os.path.dirname(manifest_file) - # Prepare all store objects - audio_objects = [] - with open(cached_manifest_file, 'r') as f: - for line in f: - item = json.loads(line) - store_path = os.path.join(manifest_dir, item['audio_filepath']) - audio_objects.append(DataStoreObject(store_path=store_path)) - - if num_workers is not None and num_workers > 1: - logging.debug('Using multiprocessing with num_workers: %d.', num_workers) - with multiprocessing.Pool(processes=num_workers) as p: - result = list( - tqdm(p.imap(datastore_object_get, audio_objects), total=len(audio_objects)) - ) - else: - logging.debug('Using a single process.') - result = [] - for audio_object in tqdm(audio_objects): - result.append(audio_object.get() is not None) - - if not all(result): - raise RuntimeError('Some files not downloaded successfully') - logging.info('Caching complete') - - else: - # Nothing to do here - logging.debug('Manifest is not on a data store: %s', manifest_file) - - if torch.distributed.is_available() and torch.distributed.is_initialized(): - logging.debug('Distributed environment is available and initialized.') - - # Handle distributed environment - if shared_cache is None: - shared_cache = is_datastore_cache_shared() - - if shared_cache: - logging.debug('Cache is shared among nodes, cache data on global rank zero.') - is_rank_zero = is_global_rank_zero() - else: - logging.debug('Cache is not shared among nodes, cache data on local rank zero.') - local_rank = int(os.environ.get("LOCAL_RANK", 0)) - is_rank_zero = local_rank == 0 - - if is_rank_zero: - logging.info('Cache data from %s rank 0', 'global' if shared_cache else 'local') - cache_data( - manifest_filepaths=manifest_filepaths, - cache_audio=cache_audio, - num_workers=num_workers, - max_num_workers=max_num_workers, - ) - logging.debug('Reached barrier') - torch.distributed.barrier() - - elif is_global_rank_zero(): - # Handle non-distributed environment, e.g., if running on a single GPU - logging.warning( - 'Torch distributed is not initialized and caching may be prone to data race conditions. ' - 'Now caching data from global rank 0. If there are other ranks and they pass this ' - 'before rank 0, errors might result.' - ) - cache_data( - manifest_filepaths=manifest_filepaths, - cache_audio=cache_audio, - num_workers=num_workers, - max_num_workers=max_num_workers, - ) - else: - raise RuntimeError( - 'Torch distributed is not initialized and caching on nodes other than global rank zero is disabled ' - 'to avoid race condition between different ranks. To ensure distributed environment is ' - 'initialized, please update data config to use `defer_setup = True`.' - ) - - -"""Optionally expand / shard the list of manifests - This is made to use the same notation as the sharded audio files - - Args: - manifest_filepaths: list of manifest files (the sharded notation) - shard_strategy: scatter or replicate (scatter by default) - shard_manifests: bool, if False, no sharding / manifest filepath expansion will be attempted - global_rank: int, the rank of this worker - world_size: int, total number of workers -""" - - -def shard_manifests_if_needed( - manifest_filepaths: Union[str, List[str]], - shard_strategy: str, - shard_manifests: bool, - global_rank: int, - world_size: int, -): - if shard_manifests: - if not torch.distributed.is_available(): - logging.warning("Not running in torch.distributed mode. Manifest sharding not available") - return manifest_filepaths - - if not torch.distributed.is_initialized(): - logging.warning( - 'Manifest sharding was requested but torch.distributed is not initialized ' - 'Did you intend to set the defer_setup flag?' - ) - return manifest_filepaths - - manifest_filepaths = expand_sharded_filepaths( - sharded_filepaths=manifest_filepaths, - shard_strategy=shard_strategy, - world_size=world_size, - global_rank=global_rank, - ) - - return manifest_filepaths - - -class _AudioTextDataset(Dataset): - """ - Dataset that loads tensors via a json file containing paths to audio files, transcripts, and durations (in seconds). - Each new line is a different sample. Example below: - {"audio_filepath": "/path/to/audio.wav", "text_filepath": "/path/to/audio.txt", "duration": 23.147} - ... - {"audio_filepath": "/path/to/audio.wav", "text": "the transcription", "offset": 301.75, "duration": 0.82, "utt": - "utterance_id", "ctm_utt": "en_4156", "side": "A"} - Args: - manifest_filepath: Path to manifest json as described above. Can be comma-separated paths. - parser: Str for a language specific preprocessor or a callable. - sample_rate (int): Sample rate to resample loaded audio to - int_values (bool): If true, load samples as 32-bit integers. Defauts to False. - augmentor (nemo.collections.asr.parts.perturb.AudioAugmentor): An AudioAugmentor object used to augment loaded - audio - max_duration: If audio exceeds this length, do not include in dataset - min_duration: If audio is less than this length, do not include in dataset - max_utts: Limit number of utterances - trim: whether or not to trim silence. Defaults to False - bos_id: Id of beginning of sequence symbol to append if not None - eos_id: Id of end of sequence symbol to append if not None - pad_id: Id of pad symbol. Defaults to 0 - return_sample_id (bool): whether to return the sample_id as a part of each sample - 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. - manifest_parse_func: Optional function to parse manifest entries. Defaults to None. - """ - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - """Returns definitions of module output ports.""" - return { - 'audio_signal': NeuralType(('B', 'T'), AudioSignal()), - 'a_sig_length': NeuralType(tuple('B'), LengthsType()), - 'transcripts': NeuralType(('B', 'T'), LabelsType()), - 'transcript_length': NeuralType(tuple('B'), LengthsType()), - 'sample_id': NeuralType(tuple('B'), LengthsType(), optional=True), - } - - def __init__( - self, - manifest_filepath: str, - parser: Union[str, Callable], - sample_rate: int, - int_values: bool = False, - augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None, - max_duration: Optional[int] = None, - min_duration: Optional[int] = None, - max_utts: int = 0, - trim: bool = False, - bos_id: Optional[int] = None, - eos_id: Optional[int] = None, - pad_id: int = 0, - return_sample_id: bool = False, - channel_selector: Optional[ChannelSelectorType] = None, - manifest_parse_func: Optional[Callable] = None, - ): - if type(manifest_filepath) == str: - manifest_filepath = manifest_filepath.split(",") - - # If necessary, cache manifests and audio from object store - cache_datastore_manifests(manifest_filepaths=manifest_filepath, cache_audio=True) - - self.manifest_processor = ASRManifestProcessor( - manifest_filepath=manifest_filepath, - parser=parser, - max_duration=max_duration, - min_duration=min_duration, - max_utts=max_utts, - bos_id=bos_id, - eos_id=eos_id, - pad_id=pad_id, - manifest_parse_func=manifest_parse_func, - ) - self.featurizer = WaveformFeaturizer(sample_rate=sample_rate, int_values=int_values, augmentor=augmentor) - self.trim = trim - self.return_sample_id = return_sample_id - self.channel_selector = channel_selector - - def get_manifest_sample(self, sample_id): - return self.manifest_processor.collection[sample_id] - - def __getitem__(self, index): - if isinstance(index, IterableABC): - return [self._process_sample(_index) for _index in index] - else: - return self._process_sample(index) - - def _process_sample(self, index): - sample = self.manifest_processor.collection[index] - offset = sample.offset - - if offset is None: - offset = 0 - - features = self.featurizer.process( - sample.audio_file, - offset=offset, - duration=sample.duration, - trim=self.trim, - orig_sr=sample.orig_sr, - channel_selector=self.channel_selector, - ) - f, fl = features, torch.tensor(features.shape[0]).long() - - t, tl = self.manifest_processor.process_text_by_sample(sample=sample) - - if self.return_sample_id: - output = f, fl, torch.tensor(t).long(), torch.tensor(tl).long(), index - else: - output = f, fl, torch.tensor(t).long(), torch.tensor(tl).long() - - return output - - def __len__(self): - return len(self.manifest_processor.collection) - - def _collate_fn(self, batch): - return _speech_collate_fn(batch, pad_id=self.manifest_processor.pad_id) - - -class AudioToCharDataset(_AudioTextDataset): - """ - Dataset that loads tensors via a json file containing paths to audio - files, transcripts, and durations (in seconds). Each new line is a - different sample. Example below: - {"audio_filepath": "/path/to/audio.wav", "text_filepath": - "/path/to/audio.txt", "duration": 23.147} - ... - {"audio_filepath": "/path/to/audio.wav", "text": "the - transcription", "offset": 301.75, "duration": 0.82, "utt": - "utterance_id", "ctm_utt": "en_4156", "side": "A"} - - Args: - manifest_filepath: Path to manifest json as described above. Can - be comma-separated paths. - labels: String containing all the possible characters to map to - sample_rate (int): Sample rate to resample loaded audio to - int_values (bool): If true, load samples as 32-bit integers. Defauts to False. - augmentor (nemo.collections.asr.parts.perturb.AudioAugmentor): An AudioAugmentor - object used to augment loaded audio - max_duration: If audio exceeds this length, do not include in dataset - min_duration: If audio is less than this length, do not include - in dataset - max_utts: Limit number of utterances - blank_index: blank character index, default = -1 - unk_index: unk_character index, default = -1 - normalize: whether to normalize transcript text (default): True - bos_id: Id of beginning of sequence symbol to append if not None - eos_id: Id of end of sequence symbol to append if not None - return_sample_id (bool): whether to return the sample_id as a part of each sample - 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. - manifest_parse_func: Optional function to parse manifest entries. Defaults to None. - """ - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - """Returns definitions of module output ports.""" - return { - 'audio_signal': NeuralType(('B', 'T'), AudioSignal()), - 'a_sig_length': NeuralType(tuple('B'), LengthsType()), - 'transcripts': NeuralType(('B', 'T'), LabelsType()), - 'transcript_length': NeuralType(tuple('B'), LengthsType()), - 'sample_id': NeuralType(tuple('B'), LengthsType(), optional=True), - } - - def __init__( - self, - manifest_filepath: str, - labels: Union[str, List[str]], - sample_rate: int, - int_values: bool = False, - augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None, - max_duration: Optional[float] = None, - min_duration: Optional[float] = None, - max_utts: int = 0, - blank_index: int = -1, - unk_index: int = -1, - normalize: bool = True, - trim: bool = False, - bos_id: Optional[int] = None, - eos_id: Optional[int] = None, - pad_id: int = 0, - parser: Union[str, Callable] = 'en', - return_sample_id: bool = False, - channel_selector: Optional[ChannelSelectorType] = None, - manifest_parse_func: Optional[Callable] = None, - ): - self.labels = labels - - parser = parsers.make_parser( - labels=labels, name=parser, unk_id=unk_index, blank_id=blank_index, do_normalize=normalize - ) - - super().__init__( - manifest_filepath=manifest_filepath, - parser=parser, - sample_rate=sample_rate, - int_values=int_values, - augmentor=augmentor, - max_duration=max_duration, - min_duration=min_duration, - max_utts=max_utts, - trim=trim, - bos_id=bos_id, - eos_id=eos_id, - pad_id=pad_id, - return_sample_id=return_sample_id, - channel_selector=channel_selector, - manifest_parse_func=manifest_parse_func, - ) - - -class AudioToBPEDataset(_AudioTextDataset): - """ - Dataset that loads tensors via a json file containing paths to audio - files, transcripts, and durations (in seconds). Each new line is a - different sample. Example below: - {"audio_filepath": "/path/to/audio.wav", "text_filepath": - "/path/to/audio.txt", "duration": 23.147} - ... - {"audio_filepath": "/path/to/audio.wav", "text": "the - transcription", "offset": 301.75, "duration": 0.82, "utt": - "utterance_id", "ctm_utt": "en_4156", "side": "A"} - - In practice, the dataset and manifest used for character encoding and byte pair encoding - are exactly the same. The only difference lies in how the dataset tokenizes the text in - the manifest. - - Args: - manifest_filepath: Path to manifest json as described above. Can - be comma-separated paths. - tokenizer: A subclass of the Tokenizer wrapper found in the common collection, - nemo.collections.common.tokenizers.TokenizerSpec. ASR Models support a subset of - all available tokenizers. - sample_rate (int): Sample rate to resample loaded audio to - int_values (bool): If true, load samples as 32-bit integers. Defauts to False. - augmentor (nemo.collections.asr.parts.perturb.AudioAugmentor): An AudioAugmentor - object used to augment loaded audio - max_duration: If audio exceeds this length, do not include in dataset - min_duration: If audio is less than this length, do not include - in dataset - max_utts: Limit number of utterances - trim: Whether to trim silence segments - use_start_end_token: Boolean which dictates whether to add [BOS] and [EOS] - tokens to beginning and ending of speech respectively. - return_sample_id (bool): whether to return the sample_id as a part of each sample - 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. - manifest_parse_func: Optional function to parse manifest entries. Defaults to None. - """ - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - """Returns definitions of module output ports.""" - return { - 'audio_signal': NeuralType(('B', 'T'), AudioSignal()), - 'a_sig_length': NeuralType(tuple('B'), LengthsType()), - 'transcripts': NeuralType(('B', 'T'), LabelsType()), - 'transcript_length': NeuralType(tuple('B'), LengthsType()), - 'sample_id': NeuralType(tuple('B'), LengthsType(), optional=True), - } - - def __init__( - self, - manifest_filepath: str, - tokenizer: 'nemo.collections.common.tokenizers.TokenizerSpec', - sample_rate: int, - int_values: bool = False, - augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None, - max_duration: Optional[int] = None, - min_duration: Optional[int] = None, - max_utts: int = 0, - trim: bool = False, - use_start_end_token: bool = True, - return_sample_id: bool = False, - channel_selector: Optional[ChannelSelectorType] = None, - manifest_parse_func: Optional[Callable] = None, - ): - if use_start_end_token and hasattr(tokenizer, "bos_id") and tokenizer.bos_id > 0: - bos_id = tokenizer.bos_id - else: - bos_id = None - - if use_start_end_token and hasattr(tokenizer, "eos_id") and tokenizer.eos_id > 0: - eos_id = tokenizer.eos_id - else: - eos_id = None - - if hasattr(tokenizer, "pad_id") and tokenizer.pad_id > 0: - pad_id = tokenizer.pad_id - else: - pad_id = 0 - - class TokenizerWrapper: - def __init__(self, tokenizer): - if isinstance(tokenizer, tokenizers.aggregate_tokenizer.AggregateTokenizer): - self.is_aggregate = True - else: - self.is_aggregate = False - self._tokenizer = tokenizer - - def __call__(self, *args): - if isinstance(args[0], List) and self.is_aggregate: - t = [] - for span in args[0]: - t.extend(self._tokenizer.text_to_ids(span['str'], span['lang'])) - return t - - t = self._tokenizer.text_to_ids(*args) - return t - - super().__init__( - manifest_filepath=manifest_filepath, - parser=TokenizerWrapper(tokenizer), - sample_rate=sample_rate, - int_values=int_values, - augmentor=augmentor, - max_duration=max_duration, - min_duration=min_duration, - max_utts=max_utts, - bos_id=bos_id, - eos_id=eos_id, - pad_id=pad_id, - trim=trim, - return_sample_id=return_sample_id, - channel_selector=channel_selector, - manifest_parse_func=manifest_parse_func, - ) - - -@deprecated( - explanation='Webdataset support will be removed in v2.1.0 versions, please use LhotseSpeechToTextBpeDataset class instead' -) -class _TarredAudioToTextDataset(IterableDataset): - """ - A similar Dataset to the AudioToCharDataset/AudioToBPEDataset, but which loads tarred audio files. - - Accepts a single comma-separated JSON manifest file (in the same style as for the AudioToCharDataset/AudioToBPEDataset), - as well as the path(s) to the tarball(s) containing the wav files. Each line of the manifest should - contain the information for one audio file, including at least the transcript and name of the audio - file within the tarball. - - Valid formats for the audio_tar_filepaths argument include: - (1) a single string that can be brace-expanded, e.g. 'path/to/audio.tar' or 'path/to/audio_{1..100}.tar.gz', or - (2) a list of file paths that will not be brace-expanded, e.g. ['audio_1.tar', 'audio_2.tar', ...]. - - Note: For brace expansion in (1), there may be cases where `{x..y}` syntax cannot be used due to shell interference. - This occurs most commonly inside SLURM scripts. Therefore we provide a few equivalent replacements. - Supported opening braces - { <=> (, [, < and the special tag _OP_. - Supported closing braces - } <=> ), ], > and the special tag _CL_. - For SLURM based tasks, we suggest the use of the special tags for ease of use. - - See the WebDataset documentation for more information about accepted data and input formats. - - If using multiple workers the number of shards should be divisible by world_size to ensure an - even split among workers. If it is not divisible, logging will give a warning but training will proceed. - In addition, if using mutiprocessing, each shard MUST HAVE THE SAME NUMBER OF ENTRIES after filtering - is applied. We currently do not check for this, but your program may hang if the shards are uneven! - - Notice that a few arguments are different from the AudioToCharDataset; for example, shuffle (bool) has been - replaced by shuffle_n (int). - - Additionally, please note that the len() of this DataLayer is assumed to be the length of the manifest - after filtering. An incorrect manifest length may lead to some DataLoader issues down the line. - - Args: - audio_tar_filepaths: Either a list of audio tarball filepaths, or a - string (can be brace-expandable). - manifest_filepath (str): Path to the manifest. - parser (callable): A callable which is used to pre-process the text output. - sample_rate (int): Sample rate to resample loaded audio to - int_values (bool): If true, load samples as 32-bit integers. Defauts to False. - augmentor (nemo.collections.asr.parts.perturb.AudioAugmentor): An AudioAugmentor - object used to augment loaded audio - shuffle_n (int): How many samples to look ahead and load to be shuffled. - See WebDataset documentation for more details. - Defaults to 0. - min_duration (float): Dataset parameter. - All training files which have a duration less than min_duration - are dropped. Note: Duration is read from the manifest JSON. - Defaults to 0.1. - max_duration (float): Dataset parameter. - All training files which have a duration more than max_duration - are dropped. Note: Duration is read from the manifest JSON. - Defaults to None. - blank_index (int): Blank character index, defaults to -1. - unk_index (int): Unknown character index, defaults to -1. - normalize (bool): Dataset parameter. - Whether to use automatic text cleaning. - It is highly recommended to manually clean text for best results. - Defaults to True. - trim (bool): Whether to use trim silence from beginning and end - of audio signal using librosa.effects.trim(). - Defaults to False. - bos_id (id): Dataset parameter. - Beginning of string symbol id used for seq2seq models. - Defaults to None. - eos_id (id): Dataset parameter. - End of string symbol id used for seq2seq models. - Defaults to None. - pad_id (id): Token used to pad when collating samples in batches. - If this is None, pads using 0s. - Defaults to None. - shard_strategy (str): Tarred dataset shard distribution strategy chosen as a str value during ddp. - - `scatter`: The default shard strategy applied by WebDataset, where each node gets - a unique set of shards, which are permanently pre-allocated and never changed at runtime. - - `replicate`: Optional shard strategy, where each node gets all of the set of shards - available in the tarred dataset, which are permanently pre-allocated and never changed at runtime. - The benefit of replication is that it allows each node to sample data points from the entire - dataset independently of other nodes, and reduces dependence on value of `shuffle_n`. - - .. warning:: - Replicated strategy allows every node to sample the entire set of available tarfiles, - and therefore more than one node may sample the same tarfile, and even sample the same - data points! As such, there is no assured guarantee that all samples in the dataset will be - sampled at least once during 1 epoch. Scattered strategy, on the other hand, on specific - occasions (when the number of shards is not divisible with ``world_size``), will not sample - the entire dataset. For these reasons it is not advisable to use tarred datasets as validation - or test datasets. - shard_manifests (bool): Whether or not to try / shard manifests. Defaults to False. - global_rank (int): Worker rank, used for partitioning shards. Defaults to 0. - world_size (int): Total number of processes, used for partitioning shards. Defaults to 0. - return_sample_id (bool): whether to return the sample_id as a part of each sample - manifest_parse_func: Optional function to parse manifest entries. Defaults to None. - """ - - def __init__( - self, - audio_tar_filepaths: Union[str, List[str]], - manifest_filepath: str, - parser: Callable, - sample_rate: int, - int_values: bool = False, - augmentor: Optional['nemo.collections.asr.parts.perturb.AudioAugmentor'] = None, - shuffle_n: int = 0, - min_duration: Optional[float] = None, - max_duration: Optional[float] = None, - trim: bool = False, - bos_id: Optional[int] = None, - eos_id: Optional[int] = None, - pad_id: int = 0, - shard_strategy: str = "scatter", - shard_manifests: bool = False, - global_rank: int = 0, - world_size: int = 0, - return_sample_id: bool = False, - manifest_parse_func: Optional[Callable] = None, - ): - self.shard_manifests = shard_manifests - - # Shard manifests if necessary and possible and then expand the paths - manifest_filepath = shard_manifests_if_needed( - shard_manifests=shard_manifests, - shard_strategy=shard_strategy, - manifest_filepaths=manifest_filepath, - world_size=world_size, - global_rank=global_rank, - ) - - # If necessary, cache manifests from object store - cache_datastore_manifests(manifest_filepaths=manifest_filepath) - - self.manifest_processor = ASRManifestProcessor( - manifest_filepath=manifest_filepath, - parser=parser, - max_duration=max_duration, - min_duration=min_duration, - max_utts=0, - bos_id=bos_id, - eos_id=eos_id, - pad_id=pad_id, - index_by_file_id=True, # Must set this so the manifest lines can be indexed by file ID - manifest_parse_func=manifest_parse_func, - ) - - self.len = self._compute_len() - - self.featurizer = WaveformFeaturizer(sample_rate=sample_rate, int_values=int_values, augmentor=augmentor) - self.trim = trim - self.eos_id = eos_id - self.bos_id = bos_id - self.pad_id = pad_id - self.return_sample_id = return_sample_id - - audio_tar_filepaths = expand_sharded_filepaths( - sharded_filepaths=audio_tar_filepaths, - shard_strategy=shard_strategy, - world_size=world_size, - global_rank=global_rank, - ) - - # Put together WebDataset pipeline - self._dataset = wds.DataPipeline( - wds.SimpleShardList(urls=audio_tar_filepaths), - webdataset_split_by_workers, - wds.shuffle(shuffle_n), - wds.tarfile_to_samples(), - wds.rename(audio=VALID_FILE_FORMATS, key='__key__'), - wds.to_tuple('audio', 'key'), - self._filter, - self._loop_offsets, - wds.map(self._build_sample), - ) - - def _filter(self, iterator): - """This function is used to remove samples that have been filtered out by ASRAudioText already. - Otherwise, we would get a KeyError as _build_sample attempts to find the manifest entry for a sample - that was filtered out (e.g. for duration). - Note that if using multi-GPU training, filtering may lead to an imbalance in samples in each shard, - which may make your code hang as one process will finish before the other. - """ - - class TarredAudioFilter: - def __init__(self, collection): - self.iterator = iterator - self.collection = collection - - def __iter__(self): - return self - - def __next__(self): - while True: - audio_bytes, audio_filename = next(self.iterator) - file_id, _ = os.path.splitext(os.path.basename(audio_filename)) - if file_id in self.collection.mapping: - return audio_bytes, audio_filename - - return TarredAudioFilter(self.manifest_processor.collection) - - def _loop_offsets(self, iterator): - """This function is used to iterate through utterances with different offsets for each file.""" - - class TarredAudioLoopOffsets: - def __init__(self, collection): - self.iterator = iterator - self.collection = collection - self.current_fn = None - self.current_bytes = None - self.offset_id = 0 - - def __iter__(self): - return self - - def __next__(self): - if self.current_fn is None: - self.current_bytes, self.current_fn = next(self.iterator) - self.offset_id = 0 - else: - offset_list = self.collection.mapping[self.current_fn] - if len(offset_list) == self.offset_id + 1: - self.current_bytes, self.current_fn = next(self.iterator) - self.offset_id = 0 - else: - self.offset_id += 1 - - return self.current_bytes, self.current_fn, self.offset_id - - return TarredAudioLoopOffsets(self.manifest_processor.collection) - - def _collate_fn(self, batch): - return _speech_collate_fn(batch, self.pad_id) - - def _build_sample(self, tup): - """Builds the training sample by combining the data from the WebDataset with the manifest info.""" - audio_bytes, audio_filename, offset_id = tup - - # Grab manifest entry from self.manifest_preprocessor.collection - file_id, _ = os.path.splitext(os.path.basename(audio_filename)) - - manifest_idx = self.manifest_processor.collection.mapping[file_id][offset_id] - manifest_entry = self.manifest_processor.collection[manifest_idx] - - offset = manifest_entry.offset - if offset is None: - offset = 0 - - # Convert audio bytes to IO stream for processing (for SoundFile to read) - audio_filestream = io.BytesIO(audio_bytes) - features = self.featurizer.process( - audio_filestream, - offset=offset, - duration=manifest_entry.duration, - trim=self.trim, - orig_sr=manifest_entry.orig_sr, - ) - audio_filestream.close() - - # Audio features - f, fl = features, torch.tensor(features.shape[0]).long() - - # Text features - t, tl = manifest_entry.text_tokens, len(manifest_entry.text_tokens) - - self.manifest_processor.process_text_by_sample(sample=manifest_entry) - - if self.bos_id is not None: - t = [self.bos_id] + t - tl += 1 - if self.eos_id is not None: - t = t + [self.eos_id] - tl += 1 - - if self.return_sample_id: - return f, fl, torch.tensor(t).long(), torch.tensor(tl).long(), manifest_idx - else: - return f, fl, torch.tensor(t).long(), torch.tensor(tl).long() - - def get_manifest_sample(self, sample_id): - return self.manifest_processor.collection[sample_id] - - def __iter__(self): - return self._dataset.__iter__() - - def _compute_len(self): - if self.shard_manifests and torch.distributed.is_available() and torch.distributed.is_initialized(): - my_len = torch.tensor(len(self.manifest_processor.collection), dtype=torch.int32).cuda() - torch.distributed.all_reduce(my_len) - my_len = my_len.int() - logging.info(f'Sharded manifests: Total length: {my_len}') - else: - my_len = len(self.manifest_processor.collection) - - return my_len - - def __len__(self): - return self.len - - -class TarredAudioToCharDataset(_TarredAudioToTextDataset): - """ - A similar Dataset to the AudioToCharDataset, but which loads tarred audio files. - - Accepts a single comma-separated JSON manifest file (in the same style as for the AudioToCharDataset), - as well as the path(s) to the tarball(s) containing the wav files. Each line of the manifest should - contain the information for one audio file, including at least the transcript and name of the audio - file within the tarball. - - Valid formats for the audio_tar_filepaths argument include: - (1) a single string that can be brace-expanded, e.g. 'path/to/audio.tar' or 'path/to/audio_{1..100}.tar.gz', or - (2) a list of file paths that will not be brace-expanded, e.g. ['audio_1.tar', 'audio_2.tar', ...]. - - See the WebDataset documentation for more information about accepted data and input formats. - - If using multiple workers the number of shards should be divisible by world_size to ensure an - even split among workers. If it is not divisible, logging will give a warning but training will proceed. - In addition, if using mutiprocessing, each shard MUST HAVE THE SAME NUMBER OF ENTRIES after filtering - is applied. We currently do not check for this, but your program may hang if the shards are uneven! - - Notice that a few arguments are different from the AudioToCharDataset; for example, shuffle (bool) has been - replaced by shuffle_n (int). - - Additionally, please note that the len() of this DataLayer is assumed to be the length of the manifest - after filtering. An incorrect manifest length may lead to some DataLoader issues down the line. - - Args: - audio_tar_filepaths: Either a list of audio tarball filepaths, or a - string (can be brace-expandable). - manifest_filepath (str): Path to the manifest. - labels (list): List of characters that can be output by the ASR model. - For Jasper, this is the 28 character set {a-z '}. The CTC blank - symbol is automatically added later for models using ctc. - sample_rate (int): Sample rate to resample loaded audio to - int_values (bool): If true, load samples as 32-bit integers. Defauts to False. - augmentor (nemo.collections.asr.parts.perturb.AudioAugmentor): An AudioAugmentor - object used to augment loaded audio - shuffle_n (int): How many samples to look ahead and load to be shuffled. - See WebDataset documentation for more details. - Defaults to 0. - min_duration (float): Dataset parameter. - All training files which have a duration less than min_duration - are dropped. Note: Duration is read from the manifest JSON. - Defaults to 0.1. - max_duration (float): Dataset parameter. - All training files which have a duration more than max_duration - are dropped. Note: Duration is read from the manifest JSON. - Defaults to None. - blank_index (int): Blank character index, defaults to -1. - unk_index (int): Unknown character index, defaults to -1. - normalize (bool): Dataset parameter. - Whether to use automatic text cleaning. - It is highly recommended to manually clean text for best results. - Defaults to True. - trim (bool): Whether to use trim silence from beginning and end - of audio signal using librosa.effects.trim(). - Defaults to False. - bos_id (id): Dataset parameter. - Beginning of string symbol id used for seq2seq models. - Defaults to None. - eos_id (id): Dataset parameter. - End of string symbol id used for seq2seq models. - Defaults to None. - pad_id (id): Token used to pad when collating samples in batches. - If this is None, pads using 0s. - Defaults to None. - shard_strategy (str): Tarred dataset shard distribution strategy chosen as a str value during ddp. - - - `scatter`: The default shard strategy applied by WebDataset, where each node gets - a unique set of shards, which are permanently pre-allocated and never changed at runtime. - - `replicate`: Optional shard strategy, where each node gets all of the set of shards - available in the tarred dataset, which are permanently pre-allocated and never changed at runtime. - The benefit of replication is that it allows each node to sample data points from the entire - dataset independently of other nodes, and reduces dependence on value of `shuffle_n`. - - .. warning:: - - Replicated strategy allows every node to sample the entire set of available tarfiles, - and therefore more than one node may sample the same tarfile, and even sample the same - data points! As such, there is no assured guarantee that all samples in the dataset will be - sampled at least once during 1 epoch. Scattered strategy, on the other hand, on specific - occasions (when the number of shards is not divisible with ``world_size``), will not sample - the entire dataset. For these reasons it is not advisable to use tarred datasets as validation - or test datasets. - - global_rank (int): Worker rank, used for partitioning shards. Defaults to 0. - world_size (int): Total number of processes, used for partitioning shards. Defaults to 0. - return_sample_id (bool): whether to return the sample_id as a part of each sample - manifest_parse_func: Optional function to parse manifest entries. Defaults to None. - """ - - def __init__( - self, - audio_tar_filepaths: Union[str, List[str]], - manifest_filepath: str, - labels: List[str], - sample_rate: int, - int_values: bool = False, - augmentor: Optional['nemo.collections.asr.parts.perturb.AudioAugmentor'] = None, - shuffle_n: int = 0, - min_duration: Optional[float] = None, - max_duration: Optional[float] = None, - blank_index: int = -1, - unk_index: int = -1, - normalize: bool = True, - trim: bool = False, - bos_id: Optional[int] = None, - eos_id: Optional[int] = None, - parser: Optional[str] = 'en', - pad_id: int = 0, - shard_strategy: str = "scatter", - shard_manifests: bool = False, - global_rank: int = 0, - world_size: int = 0, - return_sample_id: bool = False, - manifest_parse_func: Optional[Callable] = None, - ): - self.labels = labels - - parser = parsers.make_parser( - labels=labels, name=parser, unk_id=unk_index, blank_id=blank_index, do_normalize=normalize - ) - - super().__init__( - audio_tar_filepaths=audio_tar_filepaths, - manifest_filepath=manifest_filepath, - parser=parser, - sample_rate=sample_rate, - int_values=int_values, - augmentor=augmentor, - shuffle_n=shuffle_n, - min_duration=min_duration, - max_duration=max_duration, - trim=trim, - bos_id=bos_id, - eos_id=eos_id, - pad_id=pad_id, - shard_strategy=shard_strategy, - shard_manifests=shard_manifests, - global_rank=global_rank, - world_size=world_size, - return_sample_id=return_sample_id, - manifest_parse_func=manifest_parse_func, - ) - - -class TarredAudioToBPEDataset(_TarredAudioToTextDataset): - """ - A similar Dataset to the AudioToBPEDataset, but which loads tarred audio files. - - Accepts a single comma-separated JSON manifest file (in the same style as for the AudioToBPEDataset), - as well as the path(s) to the tarball(s) containing the wav files. Each line of the manifest should - contain the information for one audio file, including at least the transcript and name of the audio - file within the tarball. - - Valid formats for the audio_tar_filepaths argument include: - (1) a single string that can be brace-expanded, e.g. 'path/to/audio.tar' or 'path/to/audio_{1..100}.tar.gz', or - (2) a list of file paths that will not be brace-expanded, e.g. ['audio_1.tar', 'audio_2.tar', ...]. - - See the WebDataset documentation for more information about accepted data and input formats. - - If using multiple workers the number of shards should be divisible by world_size to ensure an - even split among workers. If it is not divisible, logging will give a warning but training will proceed. - In addition, if using mutiprocessing, each shard MUST HAVE THE SAME NUMBER OF ENTRIES after filtering - is applied. We currently do not check for this, but your program may hang if the shards are uneven! - - Notice that a few arguments are different from the AudioToBPEDataset; for example, shuffle (bool) has been - replaced by shuffle_n (int). - - Additionally, please note that the len() of this DataLayer is assumed to be the length of the manifest - after filtering. An incorrect manifest length may lead to some DataLoader issues down the line. - - Args: - audio_tar_filepaths: Either a list of audio tarball filepaths, or a - string (can be brace-expandable). - manifest_filepath (str): Path to the manifest. - tokenizer (TokenizerSpec): Either a Word Piece Encoding tokenizer (BERT), - or a Sentence Piece Encoding tokenizer (BPE). The CTC blank - symbol is automatically added later for models using ctc. - sample_rate (int): Sample rate to resample loaded audio to - int_values (bool): If true, load samples as 32-bit integers. Defauts to False. - augmentor (nemo.collections.asr.parts.perturb.AudioAugmentor): An AudioAugmentor - object used to augment loaded audio - shuffle_n (int): How many samples to look ahead and load to be shuffled. - See WebDataset documentation for more details. - Defaults to 0. - min_duration (float): Dataset parameter. - All training files which have a duration less than min_duration - are dropped. Note: Duration is read from the manifest JSON. - Defaults to 0.1. - max_duration (float): Dataset parameter. - All training files which have a duration more than max_duration - are dropped. Note: Duration is read from the manifest JSON. - Defaults to None. - trim (bool): Whether to use trim silence from beginning and end - of audio signal using librosa.effects.trim(). - Defaults to False. - use_start_end_token: Boolean which dictates whether to add [BOS] and [EOS] - tokens to beginning and ending of speech respectively. - pad_id (id): Token used to pad when collating samples in batches. - If this is None, pads using 0s. - Defaults to None. - shard_strategy (str): Tarred dataset shard distribution strategy chosen as a str value during ddp. - - - `scatter`: The default shard strategy applied by WebDataset, where each node gets - a unique set of shards, which are permanently pre-allocated and never changed at runtime. - - `replicate`: Optional shard strategy, where each node gets all of the set of shards - available in the tarred dataset, which are permanently pre-allocated and never changed at runtime. - The benefit of replication is that it allows each node to sample data points from the entire - dataset independently of other nodes, and reduces dependence on value of `shuffle_n`. - - .. warning:: - - Replicated strategy allows every node to sample the entire set of available tarfiles, - and therefore more than one node may sample the same tarfile, and even sample the same - data points! As such, there is no assured guarantee that all samples in the dataset will be - sampled at least once during 1 epoch. Scattered strategy, on the other hand, on specific - occasions (when the number of shards is not divisible with ``world_size``), will not sample - the entire dataset. For these reasons it is not advisable to use tarred datasets as validation - or test datasets. - - global_rank (int): Worker rank, used for partitioning shards. Defaults to 0. - world_size (int): Total number of processes, used for partitioning shards. Defaults to 0. - return_sample_id (bool): whether to return the sample_id as a part of each sample - manifest_parse_func: Optional function to parse manifest entries. Defaults to None. - """ - - def __init__( - self, - audio_tar_filepaths: Union[str, List[str]], - manifest_filepath: str, - tokenizer: 'nemo.collections.common.tokenizers.TokenizerSpec', - sample_rate: int, - int_values: bool = False, - augmentor: Optional['nemo.collections.asr.parts.perturb.AudioAugmentor'] = None, - shuffle_n: int = 0, - min_duration: Optional[float] = None, - max_duration: Optional[float] = None, - trim: bool = False, - use_start_end_token: bool = True, - shard_strategy: str = "scatter", - shard_manifests: bool = False, - global_rank: int = 0, - world_size: int = 0, - return_sample_id: bool = False, - manifest_parse_func: Optional[Callable] = None, - ): - if use_start_end_token and hasattr(tokenizer, "bos_id") and tokenizer.bos_id > 0: - bos_id = tokenizer.bos_id - else: - bos_id = None - - if use_start_end_token and hasattr(tokenizer, "eos_id") and tokenizer.eos_id > 0: - eos_id = tokenizer.eos_id - else: - eos_id = None - - if hasattr(tokenizer, "pad_id") and tokenizer.pad_id > 0: - pad_id = tokenizer.pad_id - else: - pad_id = 0 - - class TokenizerWrapper: - def __init__(self, tokenizer): - if isinstance(tokenizer, tokenizers.aggregate_tokenizer.AggregateTokenizer): - self.is_aggregate = True - else: - self.is_aggregate = False - self._tokenizer = tokenizer - - def __call__(self, *args): - if isinstance(args[0], List) and self.is_aggregate: - t = [] - for span in args[0]: - t.extend(self._tokenizer.text_to_ids(span['str'], span['lang'])) - return t - - t = self._tokenizer.text_to_ids(*args) - return t - - super().__init__( - audio_tar_filepaths=audio_tar_filepaths, - manifest_filepath=manifest_filepath, - parser=TokenizerWrapper(tokenizer), - sample_rate=sample_rate, - int_values=int_values, - augmentor=augmentor, - shuffle_n=shuffle_n, - min_duration=min_duration, - max_duration=max_duration, - trim=trim, - bos_id=bos_id, - eos_id=eos_id, - pad_id=pad_id, - shard_strategy=shard_strategy, - shard_manifests=shard_manifests, - global_rank=global_rank, - world_size=world_size, - return_sample_id=return_sample_id, - manifest_parse_func=manifest_parse_func, - ) - - -class BucketingDataset(IterableDataset): - """ - A Dataset which wraps another IterableDataset and adopts it for bucketing - Args: - dataset (IterableDataset): The IterableDataset to get wrapped - bucketing_batch_size (int): Number of samples to build a batch - """ - - def __init__( - self, - dataset: IterableDataset, - bucketing_batch_size: int, - ): - self.wrapped_dataset = dataset - self.bucketing_batch_size = bucketing_batch_size - super().__init__() - - def _collate_fn(self, batch): - return _speech_collate_fn(batch[0], self.wrapped_dataset.pad_id) - - def __iter__(self): - return BucketingIterator( - wrapped_ds=self.wrapped_dataset._dataset, bucketing_batch_size=self.bucketing_batch_size - ).__iter__() - - def __len__(self): - return int(math.ceil(len(self.wrapped_dataset) / float(self.bucketing_batch_size))) - - -class BucketingIterator: - def __init__(self, wrapped_ds, bucketing_batch_size): - self.wrapped_ds = wrapped_ds - self.wrapped_iter = None - self.bucketing_batch_size = bucketing_batch_size - - def __iter__(self): - self.wrapped_iter = iter(self.wrapped_ds) - return self - - def __next__(self): - batches = [] - for idx in range(self.bucketing_batch_size): - try: - sample = next(self.wrapped_iter) - except StopIteration: - break - batches.append(sample) - if len(batches) == 0: - raise StopIteration - return batches - - -class RandomizedChainDataset(ChainDataset): - def __init__(self, datasets: Iterable[Dataset], rnd_seed=0) -> None: - super(RandomizedChainDataset, self).__init__(list(datasets)) - self.rnd_gen = np.random.RandomState(rnd_seed) - - def __iter__(self): - shuffled_order = self.rnd_gen.permutation(len(self.datasets)) - for dataset_idx in shuffled_order: - d = self.datasets[dataset_idx] - assert isinstance(d, IterableDataset), "ChainDataset only supports IterableDataset" - for idx, x in enumerate(d): - yield x - # in case d is an infinite dataset, we want to break the loop - # so that the other datasets get a chance to yield too - if idx >= len(d) - 1: - break diff --git a/nemo/collections/asr/data/audio_to_text_dali.py b/nemo/collections/asr/data/audio_to_text_dali.py deleted file mode 100644 index e7fba35ce27cef21f663c24d135d86f9deb57376..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/data/audio_to_text_dali.py +++ /dev/null @@ -1,777 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import math -import operator -import os.path -import time -from collections.abc import Iterator -from typing import Callable, List, Optional, Union - -import torch -from omegaconf import DictConfig - -from nemo.collections.asr.data.audio_to_text import ASRManifestProcessor, expand_sharded_filepaths -from nemo.collections.common.parts.preprocessing import parsers -from nemo.utils import logging, model_utils - -try: - import nvidia.dali as dali - from nvidia.dali.pipeline import Pipeline - from nvidia.dali.plugin.pytorch import DALIGenericIterator as DALIPytorchIterator - from nvidia.dali.plugin.pytorch import LastBatchPolicy as LastBatchPolicy - - HAVE_DALI = True -except (ImportError, ModuleNotFoundError): - HAVE_DALI = False - -__all__ = [ - 'AudioToCharDALIDataset', - 'AudioToBPEDALIDataset', -] - -""" -Below minimum version is required to access the "read_idxs" argument in -dali.fn.readers.nemo_asr -""" -__DALI_MINIMUM_VERSION__ = "1.11" - -DALI_INSTALLATION_MESSAGE = ( - "Could not import `nvidia.dali`.\n" - "Please install DALI by following the steps provided here - \n" - "https://docs.nvidia.com/deeplearning/dali/user-guide/docs/installation.html" -) - - -def is_dali_supported(min_version: str, verbose: bool = False) -> bool: - """ - Checks if DALI in installed, and version is >= min_verion. - - Args: - min_version: A semver str that is the minimum requirement. - verbose: Whether to log the installation instructions if DALI is not found. - - Returns: - bool - whether DALI could be imported or not. - """ - module_available, _ = model_utils.check_lib_version( - 'nvidia.dali', checked_version=min_version, operator=operator.ge - ) - - # If DALI is not installed - if module_available is None: - if verbose: - logging.info(DALI_INSTALLATION_MESSAGE) - - return False - - return module_available - - -class DALIOutputs(object): - def __init__(self, out_dict): - self._has_processed_signal = 'processed_signal' in out_dict and 'processed_signal_len' in out_dict - if not self._has_processed_signal: - assert 'audio' in out_dict and 'audio_len' in out_dict - assert 'transcript' in out_dict and 'transcript_len' in out_dict - if self._has_processed_signal: - self._outs = ( - out_dict['processed_signal'], - out_dict['processed_signal_len'].reshape(-1), - out_dict['transcript'], - out_dict['transcript_len'].reshape(-1), - ) - else: - self._outs = ( - out_dict['audio'], - out_dict['audio_len'].reshape(-1), - out_dict['transcript'], - out_dict['transcript_len'].reshape(-1), - ) - - @property - def has_processed_signal(self): - return self._has_processed_signal - - def __getitem__(self, key): - return self._outs[key] - - def __len__(self): - return len(self._outs) - - -class _AudioTextDALIDataset(Iterator): - """ - NVIDIA DALI pipeline that loads tensors via one or more manifest files where each line containing a sample descriptor in JSON, - including audio files, transcripts, and durations (in seconds). - Here's an example: - {"audio_filepath": "/path/to/audio.wav", "text_filepath": "/path/to/audio.txt", "duration": 23.147} - ... - {"audio_filepath": "/path/to/audio.wav", "text": "the transcription", "offset": 301.75, "duration": 0.82, "utt": - "utterance_id", "ctm_utt": "en_4156", "side": "A"} - - Args: - manifest_filepath: Path to manifest file with the format described above. Can be comma-separated paths. - device (str): Determines the device type to be used for preprocessing. Allowed values are: 'cpu', 'gpu'. - batch_size (int): Number of samples in a batch. - parser (str, callable): A str for an inbuilt parser, or a callable with signature f(str) -> List[int]. - sample_rate (int): Sample rate to resample loaded audio to. - num_threads (int): Number of CPU processing threads to be created by the DALI pipeline. - max_duration (float): Determines the maximum allowed duration, in seconds, of the loaded audio files. - min_duration (float): Determines the minimum allowed duration, in seconds, of the loaded audio files. - bos_id (int): Id of beginning of sequence symbol to append if not None - eos_id (int): Id of end of sequence symbol to append if not None - pad_id (int): Id used to pad the input. Defaults to 0 if not provided. - trim (bool): If True, it will extract the nonsilent region of the loaded audio signal. - shuffle (bool): If set to True, the dataset will shuffled after loading. - 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. - If set to False and the size of dataset is not divisible by the batch size, then the last batch will be smaller. - device_id (int): Index of the GPU to be used (local_rank). Only applicable when device == 'gpu'. Defaults to 0. - global_rank (int): Worker rank, used for partitioning shards. Defaults to 0. - world_size (int): Total number of processes, used for partitioning shards. Defaults to 1. - preprocessor_cfg (DictConfig): Preprocessor configuration. Supports AudioToMelSpectrogramPreprocessor and AudioToMFCCPreprocessor. - return_sample_id (bool): whether to return the sample_id as a part of each sample (not supported yet). - """ - - def __init__( - self, - manifest_filepath: str, - device: str, - batch_size: int, - parser: Union[str, Callable], - audio_tar_filepaths: Optional[Union[str, List[str]]] = None, - audio_tar_index_filepaths: Optional[Union[str, List[str]]] = None, - sample_rate: int = 16000, - num_threads: int = 4, - max_duration: float = 0.0, - min_duration: float = 0.0, - bos_id: Optional[int] = None, - eos_id: Optional[int] = None, - pad_id: int = 0, - trim: bool = False, - shuffle: bool = False, - drop_last: bool = False, - shard_strategy: str = "scatter", - device_id: int = 0, - global_rank: int = 0, - world_size: int = 1, - preprocessor_cfg: DictConfig = None, - return_sample_id: bool = False, - ): - self.drop_last = drop_last # used by lr_scheduler - if return_sample_id: - raise ValueError( - "Currently DALI data layers don't support returning the sample_id and return_sample_id can not be enabled." - ) - self.return_sample_id = return_sample_id - - if not HAVE_DALI: - raise ModuleNotFoundError( - f"{self} requires NVIDIA DALI to be installed. " - f"See: https://docs.nvidia.com/deeplearning/dali/user-guide/docs/installation.html#id1" - ) - - if device not in ('cpu', 'gpu'): - raise ValueError( - f"{self} received an unexpected device argument {device}. Supported values are: 'cpu', 'gpu'" - ) - - device_id = device_id if device == 'gpu' else None - - self.batch_size = batch_size # Used by NeMo - - self.device = device - self.device_id = device_id - - if world_size > 1: - self.shard_id = global_rank - self.num_shards = world_size - else: - self.shard_id = None - self.num_shards = None - - self.eos_id = eos_id - self.bos_id = bos_id - self.sample_rate = sample_rate - - self.pipe = Pipeline( - batch_size=batch_size, - num_threads=num_threads, - device_id=self.device_id, - exec_async=True, - exec_pipelined=True, - ) - - has_preprocessor = preprocessor_cfg is not None - if has_preprocessor: - if preprocessor_cfg._target_ == "nemo.collections.asr.modules.AudioToMelSpectrogramPreprocessor": - feature_type = "mel_spectrogram" - elif preprocessor_cfg._target_ == "nemo.collections.asr.modules.AudioToMFCCPreprocessor": - feature_type = "mfcc" - else: - raise ValueError( - f"{self} received an unexpected preprocessor configuration: {preprocessor_cfg._target_}." - f" Supported preprocessors are: AudioToMelSpectrogramPreprocessor, AudioToMFCCPreprocessor" - ) - - # Default values taken from AudioToMelSpectrogramPreprocessor - params = preprocessor_cfg - self.dither = params['dither'] if 'dither' in params else 0.0 - self.preemph = params['preemph'] if 'preemph' in params else 0.97 - self.window_size_sec = params['window_size'] if 'window_size' in params else 0.02 - self.window_stride_sec = params['window_stride'] if 'window_stride' in params else 0.01 - self.sample_rate = params['sample_rate'] if 'sample_rate' in params else sample_rate - self.window_size = int(self.window_size_sec * self.sample_rate) - self.window_stride = int(self.window_stride_sec * self.sample_rate) - - normalize = params['normalize'] if 'normalize' in params else 'per_feature' - if normalize == 'per_feature': # Each freq channel independently - self.normalization_axes = (1,) - elif normalize == 'all_features': - self.normalization_axes = (0, 1) - else: - raise ValueError( - f"{self} received {normalize} for the normalize parameter." - f" It must be either 'per_feature' or 'all_features'." - ) - - self.window = None - window_name = params['window'] if 'window' in params else 'hann' - torch_windows = { - 'hann': torch.hann_window, - 'hamming': torch.hamming_window, - 'blackman': torch.blackman_window, - 'bartlett': torch.bartlett_window, - 'none': None, - } - - if window_name == 'ones': - window_tensor = torch.ones(self.window_size) - else: - try: - window_fn = torch_windows.get(window_name, None) - except: - raise ValueError( - f"{self} received '{window_name}' for the window parameter." - f" It must be one of: ('hann', 'ones', 'hamming', 'blackman', 'bartlett', None)." - f" None is equivalent to 'hann'." - ) - window_tensor = window_fn(self.window_size, periodic=False) if window_fn else None - self.window = window_tensor.numpy().tolist() if window_tensor is not None else None - - self.n_fft = params['n_fft'] if 'n_fft' in params else 2 ** math.ceil(math.log2(self.window_size)) - self.n_mels = params['n_mels'] if 'n_mels' in params else 64 - self.n_mfcc = params['n_mfcc'] if 'n_mfcc' in params else 64 - - features = params['features'] if 'features' in params else 0 - if features > 0: - if feature_type == 'mel_spectrogram': - self.n_mels = features - elif feature_type == 'mfcc': - self.n_mfcc = features - - # TODO Implement frame splicing - if 'frame_splicing' in params: - assert params['frame_splicing'] == 1, "Frame splicing is not implemented" - - self.freq_low = params['lowfreq'] if 'lowfreq' in params else 0.0 - self.freq_high = params['highfreq'] if 'highfreq' in params else self.sample_rate / 2.0 - self.log_features = params['log'] if 'log' in params else True - - # We want to avoid taking the log of zero - # There are two options: either adding or clamping to a small value - - self.log_zero_guard_type = params['log_zero_guard_type'] if 'log_zero_guard_type' in params else 'add' - if self.log_zero_guard_type not in ["add", "clamp"]: - raise ValueError( - f"{self} received {self.log_zero_guard_type} for the " - f"log_zero_guard_type parameter. It must be either 'add' or " - f"'clamp'." - ) - - self.log_zero_guard_value = params['log_zero_guard_value'] if 'log_zero_guard_value' in params else 2**-24 - if isinstance(self.log_zero_guard_value, str): - if self.log_zero_guard_value == "tiny": - self.log_zero_guard_value = torch.finfo(torch.float32).tiny - elif self.log_zero_guard_value == "eps": - self.log_zero_guard_value = torch.finfo(torch.float32).eps - else: - raise ValueError( - f"{self} received {self.log_zero_guard_value} for the log_zero_guard_type parameter." - f"It must be either a number, 'tiny', or 'eps'" - ) - - self.mag_power = params['mag_power'] if 'mag_power' in params else 2 - if self.mag_power != 1.0 and self.mag_power != 2.0: - raise ValueError( - f"{self} received {self.mag_power} for the mag_power parameter." f" It must be either 1.0 or 2.0." - ) - - self.pad_to = max(params['pad_to'], 1) if 'pad_to' in params else 16 - self.pad_value = params['pad_value'] if 'pad_value' in params else 0.0 - - with self.pipe: - if audio_tar_filepaths is None and audio_tar_index_filepaths is None: - audio, indices = dali.fn.readers.nemo_asr( - name="Reader", - manifest_filepaths=manifest_filepath.split(','), - dtype=dali.types.FLOAT, - downmix=True, - sample_rate=float(self.sample_rate), - min_duration=min_duration, - max_duration=max_duration, - read_sample_rate=False, - read_text=False, - read_idxs=True, - random_shuffle=shuffle, - shard_id=self.shard_id, - num_shards=self.num_shards, - pad_last_batch=True, - ) - - self.is_tarred_dataset = False - - elif audio_tar_filepaths is not None and audio_tar_index_filepaths is not None: - audio_tar_filepaths = expand_sharded_filepaths( - audio_tar_filepaths, - shard_strategy=shard_strategy, - world_size=world_size, - global_rank=global_rank, - ) - - audio_tar_index_filepaths = expand_sharded_filepaths( - audio_tar_index_filepaths, - shard_strategy=shard_strategy, - world_size=world_size, - global_rank=global_rank, - ) - - if len(audio_tar_filepaths) != len(audio_tar_index_filepaths) and len(audio_tar_index_filepaths) != 0: - raise ValueError( - f"Number of filepaths provided for `audio_tar_filepaths` must match " - f"`audio_tar_index_filepaths`. Got {len(audio_tar_filepaths)} audio_tar_filepaths and " - f"{len(audio_tar_index_filepaths)} audio_tar_index_filepaths." - ) - - tar_file = dali.fn.readers.webdataset( - paths=audio_tar_filepaths, - index_paths=audio_tar_index_filepaths, - name="Reader", - ext=["wav"], - missing_component_behavior="error", - random_shuffle=shuffle, - shard_id=self.shard_id, - num_shards=self.num_shards, - pad_last_batch=True, - ) - audio, _ = dali.fn.decoders.audio( - tar_file, - dtype=dali.types.FLOAT, - downmix=True, - sample_rate=float(self.sample_rate), - ) - indices = dali.fn.get_property(tar_file, key="source_info") - indices = dali.fn.pad(indices) - - self.is_tarred_dataset = True - - else: - raise RuntimeError( - "When using DALI datasets, either `audio_tar_filepaths` " - "and `audio_tar_index_filepaths` should either both be None (sequential dataset)" - "or provided (tarred dataset)." - ) - - # Extract nonsilent region, if necessary - if trim: - # Need to extract non-silent region before moving to the GPU - roi_start, roi_len = dali.fn.nonsilent_region(audio, cutoff_db=-60) - audio = audio.gpu() if self.device == 'gpu' else audio - audio = dali.fn.slice( - audio, roi_start, roi_len, normalized_anchor=False, normalized_shape=False, axes=[0] - ) - else: - audio = audio.gpu() if self.device == 'gpu' else audio - - if not has_preprocessor: - # No preprocessing, the output is the audio signal - audio_len = dali.fn.shapes(dali.fn.reshape(audio, shape=[-1])) - audio = dali.fn.pad(audio) - self.pipe.set_outputs(audio, audio_len, indices) - else: - # Additive gaussian noise (dither) - if self.dither > 0.0: - gaussian_noise = dali.fn.random.normal(audio) - audio = audio + self.dither * gaussian_noise - - # Preemphasis filter - if self.preemph > 0.0: - audio = dali.fn.preemphasis_filter(audio, preemph_coeff=self.preemph, border='zero') - - # Power spectrogram - spec = dali.fn.spectrogram( - audio, - nfft=self.n_fft, - window_length=self.window_size, - window_step=self.window_stride, - window_fn=self.window, - ) - - if feature_type == 'mel_spectrogram' or feature_type == 'mfcc': - # Spectrogram to Mel Spectrogram - spec = dali.fn.mel_filter_bank( - spec, - sample_rate=self.sample_rate, - nfilter=self.n_mels, - normalize=True, - freq_low=self.freq_low, - freq_high=self.freq_high, - ) - # Mel Spectrogram to MFCC - if feature_type == 'mfcc': - spec = dali.fn.mfcc(spec, n_mfcc=self.n_mfcc) - - # Logarithm - if self.log_zero_guard_type == 'add': - spec = spec + self.log_zero_guard_value - - spec = dali.fn.to_decibels( - spec, multiplier=math.log(10), reference=1.0, cutoff_db=math.log(self.log_zero_guard_value) - ) - - # Normalization - spec = dali.fn.normalize(spec, axes=self.normalization_axes, epsilon=1e-5**2, ddof=1) - - # Extracting the length of the spectrogram - spec_len = dali.fn.slice(dali.fn.shapes(spec), 1, 1, axes=(0,)) - - # Pads feature dimension to be a multiple of `pad_to` and the temporal dimension to be as big as the largest sample (shape -1) - spec = dali.fn.pad(spec, fill_value=self.pad_value, axes=(0, 1), align=(self.pad_to, 1), shape=(1, -1)) - self.pipe.set_outputs(spec, spec_len, indices) - - x = time.time() - # Building DALI pipeline - self.pipe.build() - y = time.time() - - logging.info(f"Time for pipe.build() : {(y - x)} seconds") - - if has_preprocessor: - output_names = ['processed_signal', 'processed_signal_len', 'manifest_indices'] - else: - output_names = ['audio', 'audio_len', 'manifest_indices'] - - x = time.time() - last_batch_policy = LastBatchPolicy.DROP if drop_last else LastBatchPolicy.PARTIAL - self._iter = DALIPytorchIterator( - [self.pipe], - output_map=output_names, - reader_name="Reader", - last_batch_policy=last_batch_policy, - dynamic_shape=True, - auto_reset=True, - ) - y = time.time() - logging.info(f"Time for DALIPytorchIterator to initialize : {(y - x)} seconds") - - # TODO come up with a better solution - class DummyDataset: - def __init__(self, parent): - self.parent = parent - - def __len__(self): - return self.parent.size - - self.dataset = DummyDataset(self) # Used by NeMo - - x = time.time() - self.manifest_processor = ASRManifestProcessor( - manifest_filepath=manifest_filepath, - parser=parser, - max_duration=max_duration, - min_duration=min_duration, - max_utts=0, - bos_id=bos_id, - eos_id=eos_id, - pad_id=pad_id, - index_by_file_id=self.is_tarred_dataset, - ) - y = time.time() - logging.info(f"Time to build nemo manifest processor - {(y - x)} seconds") - - def reset(self): - self._iter.reset() - - def __iter__(self): - return self - - def next(self): - return self.__next__() - - @property - def size(self): - return self._iter.size - - def __len__(self): - return len(self._iter) - - def __next__(self): - outputs = self._iter.next() - assert len(outputs) == 1 - dali_out = outputs[0] - manifest_indices = dali_out['manifest_indices'].numpy() - - out = {} - out_names = ['processed_signal', 'processed_signal_len', 'audio', 'audio_len'] - for out_name in out_names: - if out_name in dali_out: - out[out_name] = dali_out[out_name].detach().clone() - - text_tokens = [] - text_tokens_len = [] - max_len = 0 - batch_size = manifest_indices.shape[0] - for i, manifest_index in enumerate(manifest_indices): - - if not self.is_tarred_dataset: - # Loose-file dataset. Index is integer based. - manifest_index = manifest_index[0] - text, text_length = self.manifest_processor.process_text_by_id(manifest_index) - else: - # Tarred-file dataset. Index is filename based. - resolved_manifest_indices = manifest_index.tobytes().decode().split(":") - resolved_manifest_index = resolved_manifest_indices[2] # we require just the filename segment - resolved_manifest_index = os.path.splitext(resolved_manifest_index)[0] # we dont need file extension - text, text_length = self.manifest_processor.process_text_by_file_id(resolved_manifest_index) - - text_tokens_len.append(text_length) - text_tokens.append(text) - if text_length > max_len: - max_len = text_length - - transcript_out = torch.full([batch_size, max_len], fill_value=self.manifest_processor.pad_id, dtype=torch.long) - for i, n in enumerate(text_tokens_len): - transcript_out[i, :n] = torch.tensor(text_tokens[i], dtype=torch.long) - transcript_len_out = torch.tensor(text_tokens_len, dtype=torch.long) - - out['transcript'] = transcript_out - out['transcript_len'] = transcript_len_out - return DALIOutputs(out) - - -class AudioToCharDALIDataset(_AudioTextDALIDataset): - """ - Character based NVIDIA DALI pipeline that loads tensors via one or more manifest files where each line containing a - sample descriptor in JSON, including audio files, transcripts, and durations (in seconds). - Here's an example: - {"audio_filepath": "/path/to/audio.wav", "text_filepath": "/path/to/audio.txt", "duration": 23.147} - ... - {"audio_filepath": "/path/to/audio.wav", "text": "the transcription", "offset": 301.75, "duration": 0.82, "utt": - "utterance_id", "ctm_utt": "en_4156", "side": "A"} - - Args: - manifest_filepath: Path to manifest file with the format described above. Can be comma-separated paths. - device (str): Determines the device type to be used for preprocessing. Allowed values are: 'cpu', 'gpu'. - batch_size (int): Number of samples in a batch. - labels (List[str]): String containing all the possible characters to map to. - sample_rate (int): Sample rate to resample loaded audio to. - num_threads (int): Number of CPU processing threads to be created by the DALI pipeline. - max_duration (float): Determines the maximum allowed duration, in seconds, of the loaded audio files. - min_duration (float): Determines the minimum allowed duration, in seconds, of the loaded audio files. - blank_index (int): blank character index, default = -1 - unk_index (int): unk_character index, default = -1 - normalize (bool): whether to normalize transcript text (default): True - bos_id (int): Id of beginning of sequence symbol to append if not None - eos_id (int): Id of end of sequence symbol to append if not None - pad_id (int): Id used to pad the input. Defaults to 0 if not provided. - trim (bool): If True, it will extract the nonsilent region of the loaded audio signal. - shuffle (bool): If set to True, the dataset will shuffled after loading. - 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. - If set to False and the size of dataset is not divisible by the batch size, then the last batch will be smaller. - parser (str, callable): A str for an inbuilt parser, or a callable with signature f(str) -> List[int]. - device_id (int): Index of the GPU to be used (local_rank). Only applicable when device == 'gpu'. Defaults to 0. - global_rank (int): Worker rank, used for partitioning shards. Defaults to 0. - world_size (int): Total number of processes, used for partitioning shards. Defaults to 1. - preprocessor_cfg (DictConfig): Preprocessor configuration. Supports AudioToMelSpectrogramPreprocessor and AudioToMFCCPreprocessor. - return_sample_id (bool): whether to return the sample_id as a part of each sample (not supported yet). - """ - - def __init__( - self, - manifest_filepath: str, - device: str, - batch_size: int, - labels: Union[str, List[str]], - sample_rate: int = 16000, - audio_tar_filepaths: Optional[Union[str, List[str]]] = None, - audio_tar_index_filepaths: Optional[Union[str, List[str]]] = None, - num_threads: int = 4, - max_duration: float = 0.0, - min_duration: float = 0.0, - blank_index: int = -1, - unk_index: int = -1, - normalize: bool = True, - bos_id: Optional[int] = None, - eos_id: Optional[int] = None, - pad_id: int = 0, - trim: bool = False, - shuffle: bool = False, - drop_last: bool = False, - parser: Union[str, Callable] = 'en', - shard_strategy: str = "scatter", - device_id: int = 0, - global_rank: int = 0, - world_size: int = 1, - preprocessor_cfg: DictConfig = None, - return_sample_id: bool = False, - ): - self.labels = labels - - parser = parsers.make_parser( - labels=labels, name=parser, unk_id=unk_index, blank_id=blank_index, do_normalize=normalize - ) - - super().__init__( - manifest_filepath=manifest_filepath, - device=device, - batch_size=batch_size, - audio_tar_filepaths=audio_tar_filepaths, - audio_tar_index_filepaths=audio_tar_index_filepaths, - sample_rate=sample_rate, - num_threads=num_threads, - max_duration=max_duration, - min_duration=min_duration, - bos_id=bos_id, - eos_id=eos_id, - pad_id=pad_id, - trim=trim, - shuffle=shuffle, - drop_last=drop_last, - parser=parser, - shard_strategy=shard_strategy, - device_id=device_id, - global_rank=global_rank, - world_size=world_size, - preprocessor_cfg=preprocessor_cfg, - return_sample_id=return_sample_id, - ) - - -class AudioToBPEDALIDataset(_AudioTextDALIDataset): - """ - Subword based NVIDIA DALI pipeline that loads tensors via one or more manifest files where each line containing a - sample descriptor in JSON, including audio files, transcripts, and durations (in seconds). - Here's an example: - {"audio_filepath": "/path/to/audio.wav", "text_filepath": "/path/to/audio.txt", "duration": 23.147} - ... - {"audio_filepath": "/path/to/audio.wav", "text": "the transcription", "offset": 301.75, "duration": 0.82, "utt": - "utterance_id", "ctm_utt": "en_4156", "side": "A"} - - Args: - manifest_filepath: Path to manifest file with the format described above. Can be comma-separated paths. - tokenizer (TokenizerSpec): A TokenizerSpec implementation that wraps a tokenization implementation. - device (str): Determines the device type to be used for preprocessing. Allowed values are: 'cpu', 'gpu'. - batch_size (int): Number of samples in a batch. - sample_rate (int): Sample rate to resample loaded audio to. - num_threads (int): Number of CPU processing threads to be created by the DALI pipeline. - max_duration (float): Determines the maximum allowed duration, in seconds, of the loaded audio files. - min_duration (float): Determines the minimum allowed duration, in seconds, of the loaded audio files. - bos_id (int): Id of beginning of sequence symbol to append if not None. Injected from the tokenizer. - eos_id (int): Id of end of sequence symbol to append if not None. Injected from the tokenizer. - pad_id (int): Id used to pad the input. Defaults to 0 if not provided. Injected from the tokenizer. - trim (bool): If True, it will extract the nonsilent region of the loaded audio signal. - shuffle (bool): If set to True, the dataset will shuffled after loading. - 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. - If set to False and the size of dataset is not divisible by the batch size, then the last batch will be smaller. - - device_id (int): Index of the GPU to be used (local_rank). Only applicable when device == 'gpu'. Defaults to 0. - global_rank (int): Worker rank, used for partitioning shards. Defaults to 0. - world_size (int): Total number of processes, used for partitioning shards. Defaults to 1. - preprocessor_cfg (DictConfig): Preprocessor configuration. Supports AudioToMelSpectrogramPreprocessor and AudioToMFCCPreprocessor. - use_start_end_token (bool): Boolean which dictates whether to add [BOS] and [EOS] tokens to beginning and - ending of speech respectively. - return_sample_id (bool): whether to return the sample_id as a part of each sample (not supported yet). - """ - - def __init__( - self, - manifest_filepath: str, - tokenizer: 'nemo.collections.common.tokenizers.TokenizerSpec', - device: str, - batch_size: int, - sample_rate: int = 16000, - audio_tar_filepaths: Optional[Union[str, List[str]]] = None, - audio_tar_index_filepaths: Optional[Union[str, List[str]]] = None, - num_threads: int = 4, - max_duration: float = 0.0, - min_duration: float = 0.0, - trim: bool = False, - shuffle: bool = False, - drop_last: bool = False, - shard_strategy: str = "scatter", - device_id: int = 0, - global_rank: int = 0, - world_size: int = 1, - preprocessor_cfg: DictConfig = None, - use_start_end_token: bool = True, - return_sample_id: bool = False, - ): - - if use_start_end_token and hasattr(tokenizer, 'bos_token'): - bos_id = tokenizer.bos_id - else: - bos_id = None - - if use_start_end_token and hasattr(tokenizer, 'eos_token'): - eos_id = tokenizer.eos_id - else: - eos_id = None - - if hasattr(tokenizer, 'pad_token'): - pad_id = tokenizer.pad_id - else: - pad_id = 0 - - class TokenizerWrapper: - def __init__(self, tokenizer): - self._tokenizer = tokenizer - - def __call__(self, text): - t = self._tokenizer.text_to_ids(text) - return t - - super().__init__( - manifest_filepath=manifest_filepath, - device=device, - batch_size=batch_size, - sample_rate=sample_rate, - audio_tar_filepaths=audio_tar_filepaths, - audio_tar_index_filepaths=audio_tar_index_filepaths, - num_threads=num_threads, - max_duration=max_duration, - min_duration=min_duration, - bos_id=bos_id, - eos_id=eos_id, - pad_id=pad_id, - trim=trim, - shuffle=shuffle, - drop_last=drop_last, - parser=TokenizerWrapper(tokenizer), - shard_strategy=shard_strategy, - device_id=device_id, - global_rank=global_rank, - world_size=world_size, - preprocessor_cfg=preprocessor_cfg, - return_sample_id=return_sample_id, - ) diff --git a/nemo/collections/asr/data/audio_to_text_dataset.py b/nemo/collections/asr/data/audio_to_text_dataset.py deleted file mode 100644 index afb7a86a5f0e81ca7684f04571a16efc89163d04..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/data/audio_to_text_dataset.py +++ /dev/null @@ -1,997 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import copy -import json -import random -from math import isclose -from typing import Any, List, Optional, Union - -import numpy as np -import torch -from lightning.pytorch import LightningModule -from lightning.pytorch.callbacks import BasePredictionWriter -from omegaconf import DictConfig, OmegaConf, open_dict -from omegaconf.listconfig import ListConfig -from torch.utils.data import ChainDataset - -from nemo.collections.asr.data import audio_to_text, audio_to_text_dali -from nemo.collections.asr.data.huggingface.hf_audio_to_text_dataset import ( - get_hf_audio_to_text_bpe_dataset, - get_hf_audio_to_text_char_dataset, -) -from nemo.collections.asr.parts.preprocessing.perturb import AudioAugmentor, process_augmentations -from nemo.collections.common.data.dataset import CodeSwitchedDataset, ConcatDataset -from nemo.collections.common.tokenizers import TokenizerSpec -from nemo.utils import logging - - -def inject_dataloader_value_from_model_config(model_cfg: dict, dataloader_cfg: DictConfig, key: str): - """ - Extracts the label set provided at the top level of the model, and propagates it to the dataloader - config. - - Args: - model_cfg: A DictConfig representing the model's config. - dataloader_cfg: A DictConfig representing the individual data loader - key: A str value representing a key in the model_cfg whose value will be propagated to the - dataloader config. - """ - if key not in model_cfg: - logging.info( - f"Model level config does not contain `{key}`, please explicitly provide `{key}` to the dataloaders." - ) - return - - if not isinstance(dataloader_cfg, DictConfig): - dataloader_cfg = DictConfig(dataloader_cfg) - - # If key exists in the data loader config (either set explicitly or as a placeholder (via None)) - if key in dataloader_cfg: - # Dataloader `labels` is provided and is non-null - if dataloader_cfg[key] is not None and model_cfg[key] != dataloader_cfg[key]: - # Model level `labels` dont match Dataloader level `labels` - logging.warning( - f'`{key}` is explicitly provided to the data loader, and is different from ' - f'the `{key}` provided at the model level config.\n' - f'If this is incorrect, please set the dataloader\'s `{key}` to None.' - ) - - else: - # Dataloader `key` is None or values match - # Propagate from model level `key` (even if they match) - with open_dict(dataloader_cfg): - dataloader_cfg[key] = model_cfg[key] - - else: - # If key key doesnt even exist in dataloader_cfg, inject it explicitly - with open_dict(dataloader_cfg): - dataloader_cfg[key] = model_cfg[key] - - -def get_concat_char_dataset( - config: dict, global_rank: int, world_size: int, augmentor: Optional['AudioAugmentor'] = None -) -> ConcatDataset: - """ - Instantiates an instance of ConcatDataset containing one or more intances of - Character Encoding based AudioToCharDataset. - - Args: - config: Config of the AudioToCharDataset. - global_rank: Global rank of this device. - world_size: Global world size in the training method. - augmentor: Optional AudioAugmentor object for augmentations on audio data. - - Returns: - An instance of ConcatDataset containing one or more instances of AudioToCharDataset. - """ - if 'labels' not in config: - logging.warning("dataset does not have explicitly defined labels") - - manifest_filepaths = config['manifest_filepath'] - datasets = [] - - # needed to support validation Concat Datasets that arrive here as - # [[dataset1,dataset2]] otherwise ModelPT would interfere - if len(manifest_filepaths) == 1 and not isinstance(manifest_filepaths[0], str): - logging.info(f"removing an extra nesting level from {manifest_filepaths}") - manifest_filepaths = config['manifest_filepath'][0] - - for manifest_filepath in manifest_filepaths: - conf = copy.deepcopy(config) - conf['manifest_filepath'] = manifest_filepath - - dataset = get_char_dataset(config=conf, augmentor=augmentor) - datasets.append(dataset) - - dataset = ConcatDataset( - datasets, - sampling_technique=config.get('concat_sampling_technique', 'temperature'), - sampling_temperature=config.get('concat_sampling_temperature', 5), - sampling_scale=config.get('concat_sampling_scale', 1), - sampling_probabilities=config.get('concat_sampling_probabilities', None), - shuffle=config.get('concat_shuffle', True), - seed=config.get('concat_sampling_seed', None), - global_rank=global_rank, - world_size=world_size, - ) - return dataset - - -def get_char_dataset(config: dict, augmentor: Optional['AudioAugmentor'] = None) -> audio_to_text.AudioToCharDataset: - """ - Instantiates a Character Encoding based AudioToCharDataset. - - Args: - config: Config of the AudioToCharDataset. - augmentor: Optional AudioAugmentor object for augmentations on audio data. - - Returns: - An instance of AudioToCharDataset. - """ - if 'labels' not in config: - logging.warning("dataset does not have explicitly defined labels") - - dataset = audio_to_text.AudioToCharDataset( - manifest_filepath=config['manifest_filepath'], - labels=config.get('labels', None), - sample_rate=config['sample_rate'], - int_values=config.get('int_values', False), - augmentor=augmentor, - max_duration=config.get('max_duration', None), - min_duration=config.get('min_duration', None), - max_utts=config.get('max_utts', 0), - blank_index=config.get('blank_index', -1), - unk_index=config.get('unk_index', -1), - normalize=config.get('normalize_transcripts', False), - trim=config.get('trim_silence', False), - parser=config.get('parser', 'en'), - return_sample_id=config.get('return_sample_id', False), - channel_selector=config.get('channel_selector', None), - ) - return dataset - - -def get_concat_bpe_dataset( - config: dict, - tokenizer: 'TokenizerSpec', - global_rank: int, - world_size: int, - augmentor: Optional['AudioAugmentor'] = None, -) -> ConcatDataset: - """ - Instantiates a ContactDataset based on several Byte Pair Encoding / Word Piece Encoding based AudioToBPEDatasets. - - Args: - config: Config of the AudioToBPEDataset. - tokenizer: An instance of a TokenizerSpec object. - global_rank: Global rank of this device. - world_size: Global world size in the training method. - augmentor: Optional AudioAugmentor object for augmentations on audio data. - - Returns: - An instance of ConcatDataset containing several instances of AudioToBPEDataset. - """ - manifest_filepaths = config['manifest_filepath'] - datasets = [] - - # needed to support validation Concat Datasets that arrive here as - # [[dataset1,dataset2]] otherwise ModelPT would interfere - if len(manifest_filepaths) == 1 and not isinstance(manifest_filepaths[0], str): - logging.info(f"removing an extra nesting level from {manifest_filepaths}") - manifest_filepaths = config['manifest_filepath'][0] - - for manifest_filepath in manifest_filepaths: - conf = copy.deepcopy(config) - conf['manifest_filepath'] = manifest_filepath - dataset = get_bpe_dataset(config=conf, tokenizer=tokenizer, augmentor=augmentor) - datasets.append(dataset) - - dataset = ConcatDataset( - datasets, - sampling_technique=config.get('concat_sampling_technique', 'temperature'), - sampling_temperature=config.get('concat_sampling_temperature', 5), - sampling_scale=config.get('concat_sampling_scale', 1), - sampling_probabilities=config.get('concat_sampling_probabilities', None), - shuffle=config.get('concat_shuffle', True), - seed=config.get('concat_sampling_seed', None), - global_rank=global_rank, - world_size=world_size, - ) - return dataset - - -def get_bpe_dataset( - config: dict, tokenizer: 'TokenizerSpec', augmentor: Optional['AudioAugmentor'] = None -) -> audio_to_text.AudioToBPEDataset: - """ - Instantiates a Byte Pair Encoding / Word Piece Encoding based AudioToBPEDataset. - - Args: - config: Config of the AudioToBPEDataset. - tokenizer: An instance of a TokenizerSpec object. - augmentor: Optional AudioAugmentor object for augmentations on audio data. - - Returns: - An instance of AudioToBPEDataset. - """ - dataset = audio_to_text.AudioToBPEDataset( - manifest_filepath=config['manifest_filepath'], - tokenizer=tokenizer, - sample_rate=config['sample_rate'], - int_values=config.get('int_values', False), - augmentor=augmentor, - max_duration=config.get('max_duration', None), - min_duration=config.get('min_duration', None), - max_utts=config.get('max_utts', 0), - trim=config.get('trim_silence', False), - use_start_end_token=config.get('use_start_end_token', True), - return_sample_id=config.get('return_sample_id', False), - channel_selector=config.get('channel_selector', None), - ) - return dataset - - -def get_concat_tarred_dataset( - config: dict, - shuffle_n: int, - global_rank: int, - world_size: int, - tokenizer: Optional['TokenizerSpec'] = None, - augmentor: Optional['AudioAugmentor'] = None, -) -> ConcatDataset: - """ - Instantiates a ConcatDataset containing multiple Word Piece/BPE Encoding based TarredAudioToBPEDataset or a char based TarredAudioToCharDataset. - - Args: - config: Config of the TarredAudioToBPEDataset or TarredAudioToCharDataset. - shuffle_n: How many samples to look ahead and load to be shuffled. - See WebDataset documentation for more details. - tokenizer: An instance of a TokenizerSpec object if BPE dataset is needed. - global_rank: Global rank of this device. - world_size: Global world size in the training method. - Passsing None would return a char-based dataset. - augmentor: Optional AudioAugmentor object for augmentations on audio data. - - Returns: - An instance of ConcatDataset containing one or more TarredAudioToBPEDatasets or TarredAudioToCharDatasets. - """ - - tarred_audio_filepaths = config['tarred_audio_filepaths'] - manifest_filepaths = config['manifest_filepath'] - datasets = [] - for dataset_idx, (tarred_audio_filepath, manifest_filepath) in enumerate( - zip(tarred_audio_filepaths, manifest_filepaths) - ): - conf = copy.deepcopy(config) - conf['manifest_filepath'] = manifest_filepath - conf['tarred_audio_filepaths'] = tarred_audio_filepath - dataset = get_tarred_dataset( - config=conf, - tokenizer=tokenizer, - shuffle_n=shuffle_n, - global_rank=global_rank, - world_size=world_size, - augmentor=augmentor, - ) - datasets.append(dataset) - - dataset = ConcatDataset( - datasets, - sampling_technique=config.get('concat_sampling_technique', 'temperature'), - sampling_temperature=config.get('concat_sampling_temperature', 5), - sampling_scale=config.get('concat_sampling_scale', 1), - sampling_probabilities=config.get('concat_sampling_probabilities', None), - shuffle=config.get('concat_shuffle', True), - seed=config.get('concat_sampling_seed', None), - global_rank=global_rank, - world_size=world_size, - ) - return dataset - - -def get_tarred_dataset( - config: dict, - shuffle_n: int, - global_rank: int, - world_size: int, - tokenizer: Optional['TokenizerSpec'] = None, - augmentor: Optional['AudioAugmentor'] = None, -) -> Union[audio_to_text.TarredAudioToBPEDataset, audio_to_text.TarredAudioToCharDataset]: - """ - Instantiates a Word Piece/BPE Encoding based TarredAudioToBPEDataset or a char based TarredAudioToCharDataset. - - Args: - config: Config of the TarredAudioToBPEDataset or TarredAudioToCharDataset. - shuffle_n: How many samples to look ahead and load to be shuffled. - See WebDataset documentation for more details. - tokenizer: An instance of a TokenizerSpec object if BPE dataset is needed. - global_rank: Global rank of this device. - world_size: Global world size in the training method. - Passsing None would return a char-based dataset. - augmentor: Optional AudioAugmentor object for augmentations on audio data. - - Returns: - An instance of TarredAudioToBPEDataset or TarredAudioToCharDataset. - """ - tarred_audio_filepaths = config['tarred_audio_filepaths'] - manifest_filepaths = config['manifest_filepath'] - datasets = [] - tarred_audio_filepaths = convert_to_config_list(tarred_audio_filepaths) - manifest_filepaths = convert_to_config_list(manifest_filepaths) - - bucketing_weights = config.get('bucketing_weights', None) # For upsampling buckets - if bucketing_weights: - for idx, weight in enumerate(bucketing_weights): - if not isinstance(weight, int) or weight <= 0: - raise ValueError("bucket weights must be positive integers") - - if len(manifest_filepaths) != len(tarred_audio_filepaths): - raise ValueError( - f"manifest_filepaths (length={len(manifest_filepaths)}) and tarred_audio_filepaths (length={len(tarred_audio_filepaths)}) need to have the same number of buckets." - ) - - if 'labels' not in config: - logging.warning("dataset does not have explicitly defined labels") - - if 'max_utts' in config: - logging.warning('"max_utts" parameter is not supported for tarred datasets') - - for dataset_idx, (tarred_audio_filepath, manifest_filepath) in enumerate( - zip(tarred_audio_filepaths, manifest_filepaths) - ): - if len(tarred_audio_filepath) == 1: - tarred_audio_filepath = tarred_audio_filepath[0] - if len(manifest_filepath) == 1: - manifest_filepath = manifest_filepath[0] - - if tokenizer is None: - dataset = audio_to_text.TarredAudioToCharDataset( - audio_tar_filepaths=tarred_audio_filepath, - manifest_filepath=manifest_filepath, - labels=config.get('labels', None), - sample_rate=config['sample_rate'], - int_values=config.get('int_values', False), - augmentor=augmentor, - shuffle_n=shuffle_n, - max_duration=config.get('max_duration', None), - min_duration=config.get('min_duration', None), - blank_index=config.get('blank_index', -1), - unk_index=config.get('unk_index', -1), - normalize=config.get('normalize_transcripts', False), - trim=config.get('trim_silence', False), - parser=config.get('parser', 'en'), - shard_strategy=config.get('tarred_shard_strategy', 'scatter'), - shard_manifests=config.get('shard_manifests', False), - global_rank=global_rank, - world_size=world_size, - return_sample_id=config.get('return_sample_id', False), - ) - else: - dataset = audio_to_text.TarredAudioToBPEDataset( - audio_tar_filepaths=tarred_audio_filepath, - manifest_filepath=manifest_filepath, - tokenizer=tokenizer, - sample_rate=config['sample_rate'], - int_values=config.get('int_values', False), - augmentor=augmentor, - shuffle_n=shuffle_n, - max_duration=config.get('max_duration', None), - min_duration=config.get('min_duration', None), - trim=config.get('trim_silence', False), - use_start_end_token=config.get('use_start_end_token', True), - shard_strategy=config.get('tarred_shard_strategy', 'scatter'), - shard_manifests=config.get('shard_manifests', False), - global_rank=global_rank, - world_size=world_size, - return_sample_id=config.get('return_sample_id', False), - ) - if bucketing_weights: - [datasets.append(dataset) for _ in range(bucketing_weights[dataset_idx])] - else: - datasets.append(dataset) - - return get_chain_dataset(datasets=datasets, ds_config=config, rank=global_rank) - - -def get_code_switched_dataset( - config: dict, - shuffle_n: int, - global_rank: int, - world_size: int, - tokenizer: Optional['TokenizerSpec'] = None, - augmentor: Optional['AudioAugmentor'] = None, -) -> CodeSwitchedDataset: - - if 'manifest_filepath' not in config: - raise ValueError("`manifest_filepath` must be provided in the dataset config if `is_code_switched=True`") - if 'code_switched' not in config: - raise ValueError("`code_switched` param group must be in the dataset config if `is_code_switched=True`") - - manifest_filepaths = config['manifest_filepath'] - tarred_audio_filepaths = config.get('tarred_audio_filepaths', None) - - cs_config = OmegaConf.to_container(config['code_switched']) - - # needed to support validation Datasets that arrive here as - # [[dataset1,dataset2]] otherwise ModelPT would interfere - if len(manifest_filepaths) == 1 and not isinstance(manifest_filepaths[0], str): - manifest_filepaths = config['manifest_filepath'][0] - if tarred_audio_filepaths is None: - tarred_audio_filepaths = [None] * len(manifest_filepaths) - - if len(manifest_filepaths) != len(tarred_audio_filepaths): - raise ValueError( - f"manifest_filepaths (length={len(manifest_filepaths)}) and tarred_audio_filepaths (length={len(tarred_audio_filepaths)}) need to have the same number of items." - ) - - datasets = [] - for dataset_idx, (tarred_audio_filepath, manifest_filepath) in enumerate( - zip(tarred_audio_filepaths, manifest_filepaths) - ): - conf = copy.deepcopy(config) - conf['manifest_filepath'] = manifest_filepath - with open_dict(conf): - conf['tarred_audio_filepaths'] = tarred_audio_filepath - if tarred_audio_filepath is None or len(tarred_audio_filepath) == 0: - if tokenizer is None: - dataset = get_char_dataset(config=conf, augmentor=None) - else: - dataset = get_bpe_dataset(config=conf, tokenizer=tokenizer, augmentor=None) - else: - dataset = get_tarred_dataset( - config=conf, - tokenizer=tokenizer, - shuffle_n=shuffle_n, - global_rank=global_rank, - world_size=world_size, - augmentor=None, - ) - datasets.append(dataset) - - config = OmegaConf.to_container(config) - - dataset = CodeSwitchedDataset( - datasets, - shuffle=cs_config.get('shuffle', True), - min_duration=cs_config.get('min_duration', 4), - max_duration=cs_config.get('max_duration', 20), - min_monolingual=cs_config.get('min_monolingual', 0.3), - lang_probs=cs_config.get('probs', None), - db_norm=cs_config.get('db_norm', -25.0), - pause_start=cs_config.get('pause_start', 0), - pause_join=cs_config.get('pause_join', 0), - pause_end=cs_config.get('pause_end', 0), - sampling_scales=cs_config.get('sampling_scales', None), - seed=cs_config.get('seed', None), - global_rank=global_rank, - world_size=world_size, - pure_random=cs_config.get('pure_random', False), - force_monochannel=cs_config.get('force_monochannel', True), - infinity_mode=cs_config.get('infinity_mode', False), - sample_rate=config['sample_rate'], - augmentor=augmentor, - ) - - return dataset - - -def get_dali_char_dataset( - config: dict, - shuffle: bool, - device_id: int, - global_rank: int, - world_size: int, - preprocessor_cfg: Optional[DictConfig] = None, -) -> audio_to_text_dali.AudioToCharDALIDataset: - """ - Instantiates a Character Encoding based AudioToCharDALIDataset. - - Args: - config: Config of the AudioToCharDALIDataset. - shuffle: Bool flag whether to shuffle the dataset. - device_id: Index of the GPU to be used (local_rank). Only applicable when device == 'gpu'. Defaults to 0. - global_rank: Global rank of this device. - world_size: Global world size in the training method. - augmentor: Optional AudioAugmentor object for augmentations on audio data. - preprocessor_cfg: Preprocessor configuration. Supports AudioToMelSpectrogramPreprocessor and AudioToMFCCPreprocessor. - - Returns: - An instance of AudioToCharDALIDataset. - """ - device = 'gpu' if torch.cuda.is_available() else 'cpu' - dataset = audio_to_text_dali.AudioToCharDALIDataset( - manifest_filepath=config['manifest_filepath'], - device=device, - batch_size=config['batch_size'], - labels=config['labels'], - sample_rate=config['sample_rate'], - audio_tar_filepaths=config.get('tarred_audio_filepaths', None), - audio_tar_index_filepaths=config.get('tarred_audio_index_filepaths', None), - max_duration=config.get('max_duration', None), - min_duration=config.get('min_duration', None), - blank_index=config.get('blank_index', -1), - unk_index=config.get('unk_index', -1), - normalize=config.get('normalize_transcripts', False), - trim=config.get('trim_silence', False), - parser=config.get('parser', 'en'), - shuffle=shuffle, - shard_strategy=config.get('tarred_shard_strategy', 'scatter'), - device_id=device_id, - global_rank=global_rank, - world_size=world_size, - preprocessor_cfg=preprocessor_cfg, - return_sample_id=config.get('return_sample_id', False), - ) - return dataset - - -def get_dali_bpe_dataset( - config: dict, - tokenizer, - shuffle: bool, - device_id: int, - global_rank: int, - world_size: int, - preprocessor_cfg: Optional[DictConfig] = None, -) -> audio_to_text_dali.AudioToCharDALIDataset: - """ - Instantiates a Subword Encoding based AudioToBPEDALIDataset. - - Args: - config: Config of the AudioToBPEDALIDataset. - tokenizer: An implementation of NeMo TokenizerSpec. - shuffle: Bool flag whether to shuffle the dataset. - device_id: Index of the GPU to be used (local_rank). Only applicable when device == 'gpu'. Defaults to 0. - global_rank: Global rank of this device. - world_size: Global world size in the training method. - preprocessor_cfg: Preprocessor configuration. Supports AudioToMelSpectrogramPreprocessor and AudioToMFCCPreprocessor. - - Returns: - An instance of AudioToCharDALIDataset. - """ - device = 'gpu' if torch.cuda.is_available() else 'cpu' - dataset = audio_to_text_dali.AudioToBPEDALIDataset( - manifest_filepath=config['manifest_filepath'], - tokenizer=tokenizer, - device=device, - batch_size=config['batch_size'], - sample_rate=config['sample_rate'], - audio_tar_filepaths=config.get('tarred_audio_filepaths', None), - audio_tar_index_filepaths=config.get('tarred_audio_index_filepaths', None), - max_duration=config.get('max_duration', None), - min_duration=config.get('min_duration', None), - trim=config.get('trim_silence', False), - use_start_end_token=config.get('use_start_end_token', True), - shuffle=shuffle, - shard_strategy=config.get('tarred_shard_strategy', 'scatter'), - device_id=device_id, - global_rank=global_rank, - world_size=world_size, - preprocessor_cfg=preprocessor_cfg, - return_sample_id=config.get('return_sample_id', False), - ) - return dataset - - -def get_audio_to_text_char_dataset_from_config( - config, local_rank: int, global_rank: int, world_size: int, preprocessor_cfg: Optional[DictConfig] = None -): - """ - Construct Audio-To-Text Char dataset from a config. - Args: - config: dataset config - local_rank: model local rank - global_rank: model global rand - world_size: world size - preprocessor_cfg: preprocessor config, for DALI dataset - - Returns: - constructed dataset or None if dataset config is invalid or nothing to load - """ - if 'augmentor' in config: - augmentor = process_augmentations(config['augmentor'], global_rank=global_rank, world_size=world_size) - else: - augmentor = None - - if 'hf_data_cfg' in config: - return get_hf_audio_to_text_char_dataset( - config=config, global_rank=global_rank, world_size=world_size, augmentor=augmentor - ) - - is_concat = config.get('is_concat', False) - if is_concat: - if 'concat_sampling_technique' in config and config['concat_sampling_technique'] is None: - logging.warning( - f"Concat dataset requires `concat_sampling_technique` but it was not provided. Config: {config}" - ) - return None - if config['concat_sampling_technique'] == 'random': - if not 'concat_sampling_probabilities' in config: - logging.warning(f"Concat dataset requires `concat_sampling_probabilities` list. Config: {config}") - return None - else: - if not isclose(sum(config['concat_sampling_probabilities']), 1, abs_tol=1e-6): - logging.warning(f"`concat_sampling_probabilities` need to sum to 1. Config: {config}") - return None - - shuffle = config['shuffle'] - device = 'gpu' if torch.cuda.is_available() else 'cpu' - if config.get('use_dali', False): - device_id = local_rank if device == 'gpu' else None - dataset = get_dali_char_dataset( - config=config, - shuffle=shuffle, - device_id=device_id, - global_rank=global_rank, - world_size=world_size, - preprocessor_cfg=preprocessor_cfg, - ) - return dataset - - # Instantiate a code-switched dataset if config is present - if config.get('is_code_switched', False): - if 'manifest_filepath' in config and config['manifest_filepath'] is None: - logging.warning(f"Could not load dataset as `manifest_filepath` was None. Provided config : {config}") - return None - if not ('code_switched' in config and config['code_switched'] is not None): - logging.warning( - f"Code switched dataset requires `*_ds.code_switched.*` dict but it was not provided. Config: {config}" - ) - return None - if ( - ('probs' in config['code_switched']) - and (config['code_switched']['probs'] is not None) - and (not isclose(sum(config['code_switched']['probs']), 1, abs_tol=1e-6)) - ): - logging.warning(f"`.code_switched.probs` need to sum to 1. Config: {config['code_switched']}") - return None - - shuffle_n = config.get('shuffle_n', 4 * config['batch_size']) if shuffle else 0 - dataset = get_code_switched_dataset( - config=config, - shuffle_n=shuffle_n, - global_rank=global_rank, - world_size=world_size, - tokenizer=None, - augmentor=augmentor, - ) - # Instantiate tarred dataset loader or normal dataset loader - elif config.get('is_tarred', False): - if ('tarred_audio_filepaths' in config and config['tarred_audio_filepaths'] is None) or ( - 'manifest_filepath' in config and config['manifest_filepath'] is None - ): - logging.warning( - "Could not load dataset as `manifest_filepath` was None or " - f"`tarred_audio_filepaths` is None. Provided config : {config}" - ) - return None - - shuffle_n = config.get('shuffle_n', 4 * config['batch_size']) if shuffle else 0 - if is_concat: - dataset = get_concat_tarred_dataset( - config=config, - shuffle_n=shuffle_n, - global_rank=global_rank, - world_size=world_size, - augmentor=augmentor, - ) - else: - dataset = get_tarred_dataset( - config=config, - shuffle_n=shuffle_n, - global_rank=global_rank, - world_size=world_size, - augmentor=augmentor, - ) - else: - if 'manifest_filepath' in config and config['manifest_filepath'] is None: - logging.warning(f"Could not load dataset as `manifest_filepath` was None. Provided config : {config}") - return None - if is_concat: - dataset = get_concat_char_dataset( - config=config, global_rank=global_rank, world_size=world_size, augmentor=augmentor - ) - else: - dataset = get_char_dataset(config=config, augmentor=augmentor) - return dataset - - -def get_audio_to_text_bpe_dataset_from_config( - config, - local_rank: int, - global_rank: int, - world_size: int, - tokenizer, - preprocessor_cfg: Optional[DictConfig] = None, -): - """ - Construct Audio-To-Text BPE dataset from a config. - Args: - config: BPE dataset config - local_rank: model local rank - global_rank: model global rand - world_size: world size - tokenizer: BPE tokenizer - preprocessor_cfg: preprocessor config, for DALI BPE dataset - - Returns: - constructed dataset or None if dataset config is invalid or nothing to load - """ - if 'augmentor' in config: - augmentor = process_augmentations(config['augmentor'], global_rank=global_rank, world_size=world_size) - else: - augmentor = None - - if 'hf_data_cfg' in config: - return get_hf_audio_to_text_bpe_dataset( - config=config, global_rank=global_rank, world_size=world_size, tokenizer=tokenizer, augmentor=augmentor - ) - - is_concat = config.get('is_concat', False) - if is_concat: - if 'concat_sampling_technique' in config and config['concat_sampling_technique'] is None: - logging.warning( - f"Concat dataset requires `concat_sampling_technique` but it was not provided. Config: {config}" - ) - return None - - if config['concat_sampling_technique'] == 'random': - if not 'concat_sampling_probabilities' in config: - logging.warning(f"Concat dataset requires `concat_sampling_probabilities` list. Config: {config}") - return None - else: - if not isclose(sum(config['concat_sampling_probabilities']), 1, abs_tol=1e-6): - logging.warning(f"`concat_sampling_probabilities` need to sum to 1. Config: {config}") - return None - - shuffle = config['shuffle'] - device = 'gpu' if torch.cuda.is_available() else 'cpu' - if config.get('use_dali', False): - device_id = local_rank if device == 'gpu' else None - dataset = get_dali_bpe_dataset( - config=config, - tokenizer=tokenizer, - shuffle=shuffle, - device_id=device_id, - global_rank=global_rank, - world_size=world_size, - preprocessor_cfg=preprocessor_cfg, - ) - return dataset - - # Instantiate a code-switched dataset if config is present - if config.get('is_code_switched', False): - if 'manifest_filepath' in config and config['manifest_filepath'] is None: - logging.warning(f"Could not load dataset as `manifest_filepath` was None. Provided config : {config}") - return None - if not ('code_switched' in config and config['code_switched'] is not None): - logging.warning( - f"Code switched dataset requires `*_ds.code_switched.*` dict but it was not provided. Config: {config}" - ) - return None - if ( - ('probs' in config['code_switched']) - and (config['code_switched']['probs'] is not None) - and (not isclose(sum(config['code_switched']['probs']), 1, abs_tol=1e-6)) - ): - logging.warning(f"`.code_switched.probs` need to sum to 1. Config: {config['code_switched']}") - return None - - shuffle_n = config.get('shuffle_n', 4 * config['batch_size']) if shuffle else 0 - dataset = get_code_switched_dataset( - config=config, - shuffle_n=shuffle_n, - global_rank=global_rank, - world_size=world_size, - tokenizer=tokenizer, - augmentor=augmentor, - ) - # Instantiate tarred dataset loader or normal dataset loader - elif config.get('is_tarred', False): - if ('tarred_audio_filepaths' in config and config['tarred_audio_filepaths'] is None) or ( - 'manifest_filepath' in config and config['manifest_filepath'] is None - ): - logging.warning( - "Could not load dataset as `manifest_filepath` was None or " - f"`tarred_audio_filepaths` is None. Provided config : {config}" - ) - return None - - shuffle_n = config.get('shuffle_n', 4 * config['batch_size']) if shuffle else 0 - if is_concat: - dataset = get_concat_tarred_dataset( - config=config, - tokenizer=tokenizer, - shuffle_n=shuffle_n, - global_rank=global_rank, - world_size=world_size, - augmentor=augmentor, - ) - else: - dataset = get_tarred_dataset( - config=config, - tokenizer=tokenizer, - shuffle_n=shuffle_n, - global_rank=global_rank, - world_size=world_size, - augmentor=augmentor, - ) - else: - if 'manifest_filepath' in config and config['manifest_filepath'] is None: - logging.warning(f"Could not load dataset as `manifest_filepath` was None. Provided config : {config}") - return None - if is_concat: - dataset = get_concat_bpe_dataset( - config=config, - global_rank=global_rank, - world_size=world_size, - tokenizer=tokenizer, - augmentor=augmentor, - ) - else: - dataset = get_bpe_dataset(config=config, tokenizer=tokenizer, augmentor=augmentor) - return dataset - - -class ASRPredictionWriter(BasePredictionWriter): - def __init__(self, dataset, output_file: str): - super().__init__(write_interval="batch") - self.outf = open(output_file, 'w', encoding='utf-8') - self.dataset = dataset - self.samples_num = 0 - - def write_on_batch_end( - self, - trainer, - pl_module: 'LightningModule', - prediction: Any, - batch_indices: List[int], - batch: Any, - batch_idx: int, - dataloader_idx: int, - ): - import lhotse - - for sample_id, hypotheses in prediction: - item = {} - if isinstance(sample_id, lhotse.cut.Cut): - sample = sample_id - if isinstance(sample, lhotse.cut.MixedCut): - sample = sample.first_non_padding_cut - if sample.recording.sources[0].source != '': - item["audio_filepath"] = sample.recording.sources[0].source - else: - item["audio_filepath"] = sample.id - item["offset"] = sample.start - item["duration"] = sample.duration - item["text"] = sample.supervisions[0].text or '' - if hasattr(sample, 'shard_id'): - item["shard_id"] = sample.shard_id - item["pred_text"] = hypotheses.text - - else: - sample = self.dataset.get_manifest_sample(sample_id) - item["audio_filepath"] = sample.audio_file - item["offset"] = sample.offset - item["duration"] = sample.duration - item["text"] = sample.text_raw - item["pred_text"] = hypotheses.text - - if hasattr(hypotheses, "timestamp") and isinstance(hypotheses.timestamp, dict): - for timestamp_type, timestamps in hypotheses.timestamp.items(): - if timestamp_type in ['char', 'word', 'segment']: - item[f'{timestamp_type}_timestamps'] = [ - { - key: int(value) if isinstance(value, np.int64) else value - for key, value in offset.items() - } - for offset in timestamps - ] - - self.outf.write(json.dumps(item) + "\n") - self.samples_num += 1 - return - - def close_output_file(self): - self.outf.close() - return self.samples_num - - -def convert_to_config_list(initial_list): - if type(initial_list) is str: - initial_list = initial_list.split(",") - if initial_list is None or initial_list == []: - raise ValueError("manifest_filepaths and tarred_audio_filepaths must not be empty.") - if not isinstance(initial_list, ListConfig): - initial_list = ListConfig([initial_list]) - - for list_idx, list_val in enumerate(initial_list): - if type(list_val) != type(initial_list[0]): - raise ValueError( - "manifest_filepaths and tarred_audio_filepaths need to be a list of lists for bucketing or just a list of strings" - ) - if type(initial_list[0]) is not ListConfig: - initial_list = ListConfig([initial_list]) - return initial_list - - -def get_chain_dataset(datasets, ds_config, rank=0): - if len(datasets) > 1: - if ds_config.get('bucketing_batch_size', None) is not None: - bucketing_batch_sizes = calc_bucketing_batch_sizes(ds_config, len(datasets)) - logging.info( - f"Batch bucketing is enabled for {len(datasets)} buckets with adaptive batch sizes of {bucketing_batch_sizes}!" - ) - for idx, dataset in enumerate(datasets): - datasets[idx] = audio_to_text.BucketingDataset( - dataset=dataset, bucketing_batch_size=bucketing_batch_sizes[idx] - ) - else: - logging.info( - f"Batch bucketing is enabled for {len(datasets)} buckets with fixed batch size of {ds_config['batch_size']}!" - ) - - if len(datasets) == 1: - return datasets[0] - bucketing_strategy = ds_config.get('bucketing_strategy', 'synced_randomized') - if bucketing_strategy == 'fixed_order': - return ChainDataset(datasets) - elif bucketing_strategy == 'synced_randomized': - return audio_to_text.RandomizedChainDataset(datasets=datasets, rnd_seed=0) - elif bucketing_strategy == 'fully_randomized': - return audio_to_text.RandomizedChainDataset(datasets=datasets, rnd_seed=random.randint(0, 30000) + rank) - else: - raise ValueError( - f'bucketing_strategy={bucketing_strategy} is not supported! Supported strategies are [fixed_order, fully_randomized, synced_randomized].' - ) - - -def calc_bucketing_batch_sizes(ds_config, datasets_len): - bucketing_batch_size = ds_config['bucketing_batch_size'] - bucketing_weights = ds_config.get('bucketing_weights', None) # To adjust for upsampled buckets - - bucketing_batch_sizes = [] - - if ds_config['batch_size'] != 1: - raise ValueError( - 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']}!" - ) - if type(bucketing_batch_size) == int: # linear scaling - if bucketing_weights: # Want same batchsize for the same duplicated bucket - for idx, weight in enumerate(bucketing_weights): - scale_factor = datasets_len - idx - [bucketing_batch_sizes.append(scale_factor * bucketing_batch_size) for _ in range(weight)] - else: - for idx in range(datasets_len): - scale_factor = datasets_len - idx - bucketing_batch_sizes.append(scale_factor * bucketing_batch_size) - elif isinstance(bucketing_batch_size, ListConfig) or isinstance( - bucketing_batch_size, list - ): # assigned bucket sizes - if bucketing_weights: # Want same batchsize for same duplicated bucket - for idx, weight in enumerate(bucketing_weights): - [bucketing_batch_sizes.append(bucketing_batch_size[idx]) for _ in range(weight)] - else: - bucketing_batch_sizes = bucketing_batch_size - else: - raise ValueError( - f"bucketing_batch_size should be an integer or a list (bucketing_batch_size={bucketing_batch_size})!" - ) - - if len(bucketing_batch_sizes) != datasets_len: - raise ValueError( - f"batch_size should have the same length as the number of buckets ({len(bucketing_batch_sizes)}!={datasets_len}) " - ) - return bucketing_batch_sizes diff --git a/nemo/collections/asr/data/audio_to_text_lhotse.py b/nemo/collections/asr/data/audio_to_text_lhotse.py deleted file mode 100644 index 46c301be082254a6fc087b84261a45efbaae1b23..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/data/audio_to_text_lhotse.py +++ /dev/null @@ -1,89 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os -from typing import Dict, Optional, Tuple - -import torch.utils.data -from lhotse.dataset import AudioSamples -from lhotse.dataset.collation import collate_vectors - -from nemo.collections.common.tokenizers.aggregate_tokenizer import TokenizerWrapper -from nemo.collections.common.tokenizers.tokenizer_spec import TokenizerSpec -from nemo.core.neural_types import AudioSignal, LabelsType, LengthsType, NeuralType - - -class LhotseSpeechToTextBpeDataset(torch.utils.data.Dataset): - """ - This dataset is based on BPE datasets from audio_to_text.py. - Unlike native NeMo datasets, Lhotse dataset defines only the mapping from - a CutSet (meta-data) to a mini-batch with PyTorch tensors. - Specifically, it performs tokenization, I/O, augmentation, and feature extraction (if any). - Managing data, sampling, de-duplication across workers/nodes etc. is all handled - by Lhotse samplers instead. - - NOTE: - If the environment variable ``USE_AIS_GET_BATCH`` is set to ``true`` (case-insensitive), - then batch audio loading from AIStore will be enabled for this dataset. This will use the - AISBatchLoader to load the audio from AIStore. This can improve data loading efficiency in some setups. - """ - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - return { - 'audio_signal': NeuralType(('B', 'T'), AudioSignal()), - 'a_sig_length': NeuralType(tuple('B'), LengthsType()), - 'transcripts': NeuralType(('B', 'T'), LabelsType()), - 'transcript_length': NeuralType(tuple('B'), LengthsType()), - 'sample_id': NeuralType(tuple('B'), LengthsType(), optional=True), - } - - def __init__(self, tokenizer: TokenizerSpec, return_cuts: bool = False): - super().__init__() - self.tokenizer = TokenizerWrapper(tokenizer) - self.use_ais_get_batch = os.environ.get("USE_AIS_GET_BATCH", "False").lower() == "true" - - # Try to use use_batch_loader if available (Lhotse >= 1.32.0) - try: - self.load_audio = AudioSamples(fault_tolerant=True, use_batch_loader=self.use_ais_get_batch) - except TypeError: - # Lhotse < 1.32.0 doesn't support use_batch_loader - if self.use_ais_get_batch: - import logging - - logging.warning( - "AIS batch loading requested but not supported by this Lhotse version. " - "Please upgrade to Lhotse >= 1.32.0" - ) - self.load_audio = AudioSamples(fault_tolerant=True) - - self.return_cuts = return_cuts - - def __getitem__(self, cuts) -> Tuple[torch.Tensor, ...]: - audio, audio_lens, cuts = self.load_audio(cuts) - tokens = [ - torch.cat( - [ - torch.as_tensor(s.tokens if hasattr(s, "tokens") else self.tokenizer(s.text or "", s.language)) - for s in c.supervisions - ], - dim=0, - ) - for c in cuts - ] - token_lens = torch.tensor([t.size(0) for t in tokens], dtype=torch.long) - tokens = collate_vectors(tokens, padding_value=0) - if self.return_cuts: - return audio, audio_lens, tokens, token_lens, cuts.drop_in_memory_data() - return audio, audio_lens, tokens, token_lens diff --git a/nemo/collections/asr/data/audio_to_text_lhotse_prompt.py b/nemo/collections/asr/data/audio_to_text_lhotse_prompt.py deleted file mode 100644 index 181825b34372d5c3016a8f43d78d2baa401ada38..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/data/audio_to_text_lhotse_prompt.py +++ /dev/null @@ -1,177 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import math -from typing import Dict, Optional, Tuple - -import numpy as np -import torch -import torch.utils.data -from lhotse.dataset import AudioSamples -from lhotse.dataset.collation import collate_matrices, collate_vectors - -from nemo.collections.common.tokenizers.aggregate_tokenizer import AggregateTokenizer -from nemo.collections.common.tokenizers.tokenizer_spec import TokenizerSpec -from nemo.core.neural_types import AudioSignal, LabelsType, LengthsType, NeuralType - - -class LhotseSpeechToTextBpeDatasetWithPrompt(torch.utils.data.Dataset): - """ - Dataset class for speech-to-text with prompt vectors. - Supports both language ID and custom prompts. - """ - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - return { - 'audio_signal': NeuralType(('B', 'T'), AudioSignal()), - 'audio_signal_length': NeuralType(tuple('B'), LengthsType()), - 'transcripts': NeuralType(('B', 'T'), LabelsType()), - 'transcript_length': NeuralType(tuple('B'), LengthsType()), - 'prompt': NeuralType(('B', 'T', 'D'), LabelsType()), - } - - def __init__(self, tokenizer, cfg): - super().__init__() - self.tokenizer = TokenizerWrapper(tokenizer) - self.load_audio = AudioSamples(fault_tolerant=True) - self.cfg = cfg - - # Calculate num_sample_per_mel_frame from config - sample_rate = cfg.get('sample_rate', 16000) - window_stride = cfg.get('window_stride', 0.01) - self.num_sample_per_mel_frame = int(sample_rate * window_stride) - - self.subsampling_factor = cfg.get('subsampling_factor', 8) - - # Load prompt dictionary from config if provided - self.prompt_dict = cfg.get('prompt_dictionary') - if self.prompt_dict: - # Set num_prompts based on the length of prompt_dictionary or a minimum value - # This ensures we have enough dimensions in our embedding space to add scale up without changing the model - self.num_prompts = cfg.get('num_prompts', 128) - - # Field to use for prompt key (default to 'language') - self.prompt_field = cfg.get('prompt_field', 'language') - - def _get_prompt_index(self, prompt_key: str) -> int: - """ - Maps prompt keys to indices using the prompt dictionary. - """ - if not self.prompt_dict: - raise ValueError("Prompt dictionary is empty. Please provide a valid prompt_dictionary in the config.") - - if prompt_key not in self.prompt_dict: - available_keys = list(self.prompt_dict.keys()) - raise ValueError( - f"Unknown prompt key: '{prompt_key}'. Available prompts: {available_keys[:10]}{'...' if len(available_keys) > 10 else ''}" - ) - - return self.prompt_dict[prompt_key] - - def prompt_to_target(self, cut, num_prompts: int, window_stride: int, subsampling_factor: int): - """ - Create prompt target tensor for the sequence. - """ - # Calculate encoder output length based on subsampling factor - encoder_hidden_len = self.get_hidden_length_from_sample_length(cut.num_samples) - - # Initialize prompt target matrix - mask = np.zeros((num_prompts, encoder_hidden_len)) - - # Get prompt index - default to language if prompt not specified - # revise supervisions to include prompt key - # prompt_key = getattr(cut.supervisions[0].custom_fields, cut.supervisions[0].language)cut.supervisions[0].custom_fields, - prompt_id = self._get_prompt_index(cut.supervisions[0].language) - - # Set the corresponding prompt ID to 1 for all time steps - mask[prompt_id, :] = 1 - - return mask - - def get_hidden_length_from_sample_length(self, num_samples: int) -> int: - """ - Calculate the hidden length from the given number of samples. - - Parameters: - num_samples (int): The total number of audio samples. - - Returns: - hidden_length (int): The calculated hidden length in terms of the number of frames. - """ - mel_frame_count = math.ceil((num_samples + 1) / self.num_sample_per_mel_frame) - hidden_length = math.ceil(mel_frame_count / self.subsampling_factor) - return int(hidden_length) - - def __getitem__(self, cuts) -> Tuple[torch.Tensor, ...]: - audio, audio_lens, cuts = self.load_audio(cuts) - tokens = [torch.as_tensor(self.tokenizer(c.supervisions[0].text, c.supervisions[0].language)) for c in cuts] - - # Create prompt targets - prompt_targets = [ - torch.transpose( - torch.as_tensor( - self.prompt_to_target( - c, - self.num_prompts, - self.num_sample_per_mel_frame, - self.subsampling_factor, - ), - dtype=torch.float32, - ), - 0, - 1, - ) - for c in cuts - ] - - # Create final tensors - token_lens = torch.tensor([t.size(0) for t in tokens], dtype=torch.long) - tokens = collate_vectors(tokens, padding_value=0) - prompt_targets = collate_matrices(prompt_targets) - - return ( - audio, # Audio signal - audio_lens, # Audio lengths - tokens, # Text tokens - token_lens, # Token lengths - prompt_targets, # Prompt targets - ) - - -class TokenizerWrapper: - """ - Provide a unified interface for NeMo Tokenizer, AggregateTokenizer, and (char) Parser. - """ - - def __init__(self, tokenizer): - self._tokenizer = tokenizer - if isinstance(tokenizer, AggregateTokenizer): - self._impl = self._call_agg_tokenizer - elif isinstance(tokenizer, TokenizerSpec): - self._impl = self._call_tokenizer - else: - self._impl = self._call_parser - - def __call__(self, text: str, lang: Optional[str] = None): - return self._impl(text, lang) - - def _call_agg_tokenizer(self, text: str, lang: Optional[str] = None): - assert lang is not None, "Expected 'lang' to be set for AggregateTokenizer." - return self._tokenizer.text_to_ids(text, lang) - - def _call_tokenizer(self, text: str, lang: Optional[str] = None): - return self._tokenizer.text_to_ids(text) - - def _call_parser(self, text: str, lang: Optional[str] = None): - return self._tokenizer(text) diff --git a/nemo/collections/asr/data/audio_to_text_lhotse_prompted.py b/nemo/collections/asr/data/audio_to_text_lhotse_prompted.py deleted file mode 100644 index a3510a78836a47f137a2c70e0de9875feef3b590..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/data/audio_to_text_lhotse_prompted.py +++ /dev/null @@ -1,269 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import os -from dataclasses import dataclass -from typing import Optional, Union - -import torch.utils.data -from lhotse import CutSet -from lhotse.cut import MixedCut -from lhotse.dataset import AudioSamples -from lhotse.dataset.collation import collate_vectors - -from nemo.collections.common.data import apply_prompt_format_fn -from nemo.collections.common.prompts import PromptFormatter -from nemo.collections.common.tokenizers import TokenizerSpec - - -@dataclass -class PromptedAudioToTextMiniBatch: - audio: torch.Tensor - audio_lens: torch.Tensor - transcript: torch.Tensor - transcript_lens: torch.Tensor - prompt: torch.Tensor - prompt_lens: torch.Tensor - prompted_transcript: torch.Tensor - prompted_transcript_lens: torch.Tensor - cuts: Optional[CutSet] = None - - def get_decoder_inputs_outputs(self) -> tuple[torch.Tensor, torch.Tensor]: - """ - Returns the inputs and outputs of transformer decoder for training. - The input is ``prompted_transcript`` (minus last token), - and the output is ``prompted_transcript`` (minus first token). - """ - return self.prompted_transcript[:, :-1], self.prompted_transcript[:, 1:] - - -class PromptedAudioToTextLhotseDataset(torch.utils.data.Dataset): - """ - This dataset is based on :class:`~nemo.collections.asr.data.audio_to_text_lhotse.LhotseSpeechToTextBpeDataset`. - It is a Lhotse-style dataset that converts a mini-batch of Cuts into tensors. - The main difference from ``LhotseSpeechToTextBpeDataset`` is that we introduce - a special prompt format for multitask encoder-decoder models. - - To perform the prompt formatting, we accept a ``prompt_format_fn``. - It's expected to accept: - * a ``CutSet`` which it will internally iterate over for utterances, and - * a ``TokenizerWrapper`` object that will be internally used to tokenize the utterances - - Tokenized utterances will be extended with special prompt tokens according to ``prompt_format_fn`` logic. - We support cuts with multiple supervision segments -- their tokenized texts will be concatenated before we add the prompt tokens. - This is useful, for example, in code-switched scenarios where each segment is spoken in a different language. - - Chunking: - If `enable_chunking` is True, each audio sample is split into optimally sized chunks - (see `find_optimal_chunk_size` and `chunk_waveform`). This is useful for long audio inputs, - allowing the model to process them in manageable segments. - - NOTE: - If the environment variable `USE_AIS_GET_BATCH` is set to `true` (case-insensitive), - then batch audio loading from AIStore will be enabled for this dataset. This will use the - AISBatchLoader to load the audio from AIStore. This can improve data loading efficiency in some setups. - """ - - def __init__( - self, - tokenizer: TokenizerSpec, - prompt: PromptFormatter, - enable_chunking: bool = False, - ): - super().__init__() - self.tokenizer = tokenizer - self.use_ais_get_batch = os.environ.get("USE_AIS_GET_BATCH", "False").lower() == "true" - - # Try to use use_batch_loader if available (Lhotse >= 1.32.0) - try: - self.load_audio = AudioSamples(fault_tolerant=True, use_batch_loader=self.use_ais_get_batch) - except TypeError: - # Lhotse < 1.32.0 doesn't support use_batch_loader - if self.use_ais_get_batch: - import logging - - logging.warning( - "AIS batch loading requested but not supported by this Lhotse version. " - "Please upgrade to Lhotse >= 1.32.0" - ) - self.load_audio = AudioSamples(fault_tolerant=True) - - self.padding_value = self.tokenizer.pad_id - self.prompt = prompt - self.enable_chunking = enable_chunking - - def __getitem__(self, cuts: CutSet) -> PromptedAudioToTextMiniBatch: - # Load the audio's from AIS and add them to the CutSet - audio, audio_lens, cuts = self.load_audio(cuts) - - # Will work if batch_size is set to 1. - if self.enable_chunking: - # If dynamic chunking is enabled, split each audio sample into chunks. - new_audio = [] - new_audio_lens = [] - for i in range(audio.shape[0]): - waveform = audio[i, : audio_lens[i]] - # Split the waveform into chunks and get their lengths. - chunks, chunk_lens = self._chunk_waveform(waveform) - new_audio.extend(chunks) - new_audio_lens.extend(chunk_lens) - # Stack all chunks into a batch. - audio = torch.stack(new_audio) - audio_lens = torch.tensor(new_audio_lens, dtype=torch.long) - # Adding this to allow gathering results of the same audio from different batches - if cuts[0].start != 0: - cuts[0].id = cuts[0].id + '_cut_segmented' - # Fast-path: the tokenization and prompt format ting was already done before sampling. - attrs = ("input_ids", "context_ids", "answer_ids") - pre_formatted = all(hasattr(c, a) for c in cuts for a in attrs) - if pre_formatted: - prompts_with_answers, prompts, answers = zip(*((c.input_ids, c.context_ids, c.answer_ids) for c in cuts)) - else: - formatted = [apply_prompt_format_fn(cut, self.prompt) for cut in cuts] - prompts_with_answers = [ex["input_ids"] for ex in formatted] - prompts = [ex["context_ids"] for ex in formatted] - answers = [ex["answer_ids"] for ex in formatted] - - transcript, transcript_lens = self._collate_tokens(answers) - prompts_with_answers, prompts_with_answers_lens = self._collate_tokens(prompts_with_answers) - prompts, prompt_lens = self._collate_tokens(prompts) - - return PromptedAudioToTextMiniBatch( - audio=audio, - audio_lens=audio_lens, - transcript=transcript, - transcript_lens=transcript_lens, - prompt=prompts, - prompt_lens=prompt_lens, - prompted_transcript=prompts_with_answers, - prompted_transcript_lens=prompts_with_answers_lens, - cuts=_drop_in_memory_data(cuts), - ) - - def _collate_tokens(self, tokens: list[Union[list[int], torch.Tensor]]) -> tuple[torch.Tensor, torch.Tensor]: - tokens = [torch.as_tensor(t) for t in tokens] - token_lens = torch.tensor([t.size(0) for t in tokens], dtype=torch.long) - tokens = collate_vectors(tokens, padding_value=self.padding_value) - return tokens, token_lens - - def _find_optimal_chunk_size( - self, total_len: int, min_sec: int = 30, max_sec: int = 40, sample_rate: int = 16000, overlap_sec: float = 1.0 - ) -> int: - """ - Find the optimal chunk size for audio processing that minimizes paddings to the last chunk. - - Args: - total_len (int): Total length of the audio waveform in samples - min_sec (int, optional): Minimum chunk size in seconds. Defaults to 30. - max_sec (int, optional): Maximum chunk size in seconds. Defaults to 40. - sample_rate (int, optional): Audio sample rate in Hz. Defaults to 16000. - overlap_sec (float, optional): Overlap duration between consecutive chunks in seconds. - Defaults to 1.0. - - Returns: - int: Optimal chunk size in samples that maximizes the last chunk length - """ - best_chunk_size = min_sec * sample_rate - best_last_chunk_len = 0 - if total_len < max_sec * sample_rate: - return total_len - # Try each possible chunk duration in the range - for sec in range(min_sec, max_sec + 1): - chunk_size = sec * sample_rate - overlap_size = int(overlap_sec * sample_rate) - step_size = chunk_size - overlap_size - - if step_size <= 0: # Invalid overlap - continue - if chunk_size > total_len: - continue - - # Calculate how many chunks we'd need and the last chunk's length - n_chunks = (total_len + step_size - 1) // step_size - last_chunk_len = total_len - step_size * (n_chunks - 1) - - if last_chunk_len > best_last_chunk_len: - best_last_chunk_len = last_chunk_len - best_chunk_size = chunk_size - - return best_chunk_size - - def _chunk_waveform( - self, waveform: torch.Tensor, chunk_size: int = None, overlap_sec: float = 1.0, sample_rate: int = 16000 - ) -> tuple[list[torch.Tensor], list[int]]: - """ - Split a waveform tensor into overlapping chunks. - - Args: - waveform (torch.Tensor): Input audio waveform tensor of shape (time_samples,) - chunk_size (int, optional): Size of each chunk in samples. If None, automatically - determines optimal chunk size using find_optimal_chunk_size(). - Defaults to None. - sample_rate (int, optional): Audio sample rate in Hz. Defaults to 16000. - overlap_sec (float, optional): Overlap duration between consecutive chunks in seconds. - Used to calculate step size. Defaults to 2. - - Returns: - tuple[list[torch.Tensor], list[int]]: A tuple containing: - - List of chunk tensors, each of shape (chunk_size,) - - List of original lengths for each chunk before padding (useful for masking - padded regions during processing. - """ - # If chunk_size is None, find the optimal chunk size for this waveform - total_len = waveform.shape[0] - if chunk_size is None: - chunk_size = self._find_optimal_chunk_size(total_len, overlap_sec=overlap_sec) - if chunk_size >= total_len: - return [waveform], [total_len] - overlap_size = int(overlap_sec * sample_rate) - step_size = chunk_size - overlap_size - chunks = [] - chunk_lens = [] - start = 0 - while start + overlap_size < total_len: - end = min(start + chunk_size, total_len) - chunk = waveform[start:end] - length = chunk.shape[0] - if length < chunk_size: - pad = torch.zeros(chunk_size - length, dtype=chunk.dtype, device=chunk.device) - chunk = torch.cat([chunk, pad], dim=0) - chunks.append(chunk) - chunk_lens.append(length) - start += step_size - - return chunks, chunk_lens - - -class ProbablyIncorrectLanguageKeyError(RuntimeError): - pass - - -def _drop_in_memory_data( - cuts: CutSet, - _fields=frozenset(MixedCut.__dataclass_fields__.keys()), -) -> CutSet: - """Workaround for an edge case in cuts.drop_in_memory_data() on MixedCut with Lhotse<1.29.0""" - ans = [] - for c in cuts: - # Not a mixed cut or a mixed cut that wasn't assigned any extra attributes. - if not isinstance(c, MixedCut) or _fields.issuperset(c.__dict__.keys()): - ans.append(c.drop_in_memory_data()) - else: - extra_attrs = {k: v for k, v in c.__dict__.items() if k not in _fields} - for k in extra_attrs: - delattr(c, k) - ans.append(c.drop_in_memory_data()) - for k, v in extra_attrs.items(): - setattr(ans[-1], k, v) - setattr(c, k, v) - return CutSet(ans) diff --git a/nemo/collections/asr/data/audio_to_text_lhotse_speaker.py b/nemo/collections/asr/data/audio_to_text_lhotse_speaker.py deleted file mode 100644 index 65cb68a3175118394de4c6a6ba761f9f38ecd91e..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/data/audio_to_text_lhotse_speaker.py +++ /dev/null @@ -1,97 +0,0 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import random -from typing import Dict, Optional, Tuple - -import torch.utils.data -from lhotse.dataset import AudioSamples -from lhotse.dataset.collation import collate_vectors - -from nemo.collections.asr.data.audio_to_text_lhotse import TokenizerWrapper -from nemo.collections.asr.parts.utils.asr_multispeaker_utils import speaker_to_target -from nemo.collections.common.tokenizers.tokenizer_spec import TokenizerSpec -from nemo.core.neural_types import AudioSignal, LabelsType, LengthsType, NeuralType - - -class LhotseSpeechToTextSpkBpeDataset(torch.utils.data.Dataset): - """ - This dataset is based on BPE datasets from audio_to_text.py. It has the same functionality of LhotseSpeechToTextBpeDataset but also yield speaker target tensor. - Unlike native NeMo datasets, Lhotse dataset defines only the mapping from - a CutSet (meta-data) to a mini-batch with PyTorch tensors. - Specifically, it performs tokenization, I/O, augmentation, and feature extraction (if any). - Managing data, sampling, de-duplication across workers/nodes etc. is all handled - by Lhotse samplers instead. - """ - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - return { - 'audio_signal': NeuralType(('B', 'T'), AudioSignal()), - 'a_sig_length': NeuralType(tuple('B'), LengthsType()), - 'transcripts': NeuralType(('B', 'T'), LabelsType()), - 'transcript_length': NeuralType(tuple('B'), LengthsType()), - 'spk_targets': NeuralType(('B', 'T'), LabelsType()), - 'bg_spk_targets': NeuralType(('B', 'T'), LabelsType()), - } - - def __init__(self, cfg, tokenizer: TokenizerSpec): - super().__init__() - self.tokenizer = TokenizerWrapper(tokenizer) - self.load_audio = AudioSamples(fault_tolerant=True) - self.cfg = cfg - self.num_speakers = self.cfg.get('num_speakers', 4) - self.num_sample_per_mel_frame = self.cfg.get('num_sample_per_mel_frame', 160) - self.num_mel_frame_per_asr_frame = self.cfg.get('num_mel_frame_per_asr_frame', 8) - self.fixed_spk_id = self.cfg.get('fixed_spk_id', None) - self.inference_mode = self.cfg.get('inference_mode', False) - - def __getitem__(self, cuts) -> Tuple[torch.Tensor, ...]: - - audio, audio_lens, cuts = self.load_audio(cuts) - - tokens = [] - spk_targets = [] - bg_spk_targets = [] - - if self.inference_mode: - return audio, audio_lens, None, None, None, None - - for idx, cut in enumerate(cuts): - - speaker_targets, texts = speaker_to_target( - a_cut=cut, - num_speakers=self.num_speakers, - num_sample_per_mel_frame=self.num_sample_per_mel_frame, - num_mel_frame_per_asr_frame=self.num_mel_frame_per_asr_frame, - return_text=True, - ) - speaker_targets = speaker_targets.transpose(0, 1)[: len(texts)] - - target_speaker_id = random.choice(range(len(texts))) - non_target_speaker_ids = [i for i in range(len(texts)) if i != target_speaker_id] - text = texts[target_speaker_id] - speaker_target = speaker_targets[target_speaker_id] - bg_speaker_target = speaker_targets[non_target_speaker_ids].sum(dim=0) > 0 - - tokens.append(torch.as_tensor(self.tokenizer(text, cut.supervisions[0].language))) - spk_targets.append(speaker_target) - bg_spk_targets.append(bg_speaker_target) - - token_lens = torch.tensor([t.size(0) for t in tokens], dtype=torch.long) - tokens = collate_vectors(tokens, padding_value=0) - spk_targets = collate_vectors(spk_targets, padding_value=0) - bg_spk_targets = collate_vectors(bg_spk_targets, padding_value=0) - - return audio, audio_lens, tokens, token_lens, spk_targets, bg_spk_targets diff --git a/nemo/collections/asr/data/data_simulation.py b/nemo/collections/asr/data/data_simulation.py deleted file mode 100644 index 2138a8d2eedae263d1d3cb4a9f2a8a973acf3ec1..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/data/data_simulation.py +++ /dev/null @@ -1,1666 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import concurrent -import os -import warnings -from typing import Dict, List, Tuple - -import numpy as np -import soundfile as sf -import torch -from omegaconf import OmegaConf -from scipy.signal import convolve -from scipy.signal.windows import cosine, hamming, hann -from tqdm import tqdm - -from nemo.collections.asr.parts.preprocessing.perturb import process_augmentations -from nemo.collections.asr.parts.utils.data_simulation_utils import ( - DataAnnotator, - SpeechSampler, - build_speaker_samples_map, - get_background_noise, - get_cleaned_base_path, - get_random_offset_index, - get_speaker_ids, - get_speaker_samples, - get_split_points_in_alignments, - load_speaker_sample, - normalize_audio, - per_speaker_normalize, - perturb_audio, - read_audio_from_buffer, - read_noise_manifest, -) -from nemo.collections.asr.parts.utils.manifest_utils import read_manifest -from nemo.collections.asr.parts.utils.speaker_utils import get_overlap_range, is_overlap, merge_float_intervals -from nemo.utils import logging - -try: - import pyroomacoustics as pra - from pyroomacoustics.directivities import CardioidFamily, DirectionVector, DirectivityPattern - - PRA = True -except ImportError: - PRA = False -try: - from gpuRIR import att2t_SabineEstimator, beta_SabineEstimation, simulateRIR, t2n - - GPURIR = True -except ImportError: - GPURIR = False - - -class MultiSpeakerSimulator(object): - """ - Multispeaker Audio Session Simulator - Simulates multispeaker audio sessions using single-speaker audio files and - corresponding word alignments. - - Args: - cfg: OmegaConf configuration loaded from yaml file. - - Configuration parameters (YAML):: - - Parameters: - manifest_filepath (str): Manifest file with paths to single speaker audio files - sr (int): Sampling rate of the input audio files from the manifest - random_seed (int): Seed to random number generator - - session_config: - num_speakers (int): Number of unique speakers per multispeaker audio session - num_sessions (int): Number of sessions to simulate - session_length (int): Length of each simulated multispeaker audio session (seconds) - - session_params: - max_audio_read_sec (int): Max audio length in seconds when loading an audio file - sentence_length_params (list): k,p values for a negative_binomial distribution - dominance_var (float): Variance in speaker dominance - min_dominance (float): Minimum percentage of speaking time per speaker - turn_prob (float): Probability of switching speakers after each utterance - mean_silence (float): Mean proportion of silence to speaking time [0, 1) - mean_silence_var (float): Variance for mean silence in all audio sessions - per_silence_var (float): Variance for each silence in an audio session - per_silence_min (float): Minimum duration for each silence (default: 0) - per_silence_max (float): Maximum duration for each silence (default: -1, no max) - mean_overlap (float): Mean proportion of overlap in non-silence duration [0, 1) - mean_overlap_var (float): Variance for mean overlap in all audio sessions - per_overlap_var (float): Variance for per overlap in each session - per_overlap_min (float): Minimum per overlap duration in seconds - per_overlap_max (float): Maximum per overlap duration in seconds (-1 for no max) - start_window (bool): Whether to window the start of sentences - window_type (str): Type of windowing ("hamming", "hann", "cosine") - window_size (float): Length of window at start/end of segmented utterance (seconds) - start_buffer (float): Buffer of silence before the start of the sentence - split_buffer (float): Split RTTM labels if greater than twice this amount of silence - release_buffer (float): Buffer before window at end of sentence - normalize (bool): Normalize speaker volumes - normalization_type (str): "equal" or "var" volume per speaker - normalization_var (str): Variance in speaker volume - min_volume (float): Minimum speaker volume (variable normalization only) - max_volume (float): Maximum speaker volume (variable normalization only) - end_buffer (float): Buffer at the end of the session to leave blank - - outputs: - output_dir (str): Output directory for audio sessions and label files - output_filename (str): Output filename for the wav and RTTM files - overwrite_output (bool): If true, delete the output directory if it exists - output_precision (int): Number of decimal places in output files - - background_noise: - add_bg (bool): Add ambient background noise if true - background_manifest (str): Path to background noise manifest file - snr (int): SNR for background noise (using average speaker power) - snr_min (int): Min random SNR (set null to use fixed SNR) - snr_max (int): Max random SNR (set null to use fixed SNR) - - segment_augmentor: - add_seg_aug (bool): Enable augmentation on each speech segment (Default: False) - segmentor.gain: - prob (float): Probability of gain augmentation - min_gain_dbfs (float): minimum gain in dB - max_gain_dbfs (float): maximum gain in dB - - session_augmentor: - add_sess_aug (bool): Enable audio augmentation on the whole session (Default: False) - segmentor.white_noise: - prob (float): Probability of adding white noise (Default: 1.0) - min_level (float): minimum gain in dB - max_level (float): maximum gain in dB - - speaker_enforcement: - enforce_num_speakers (bool): Enforce all requested speakers are present - enforce_time (list): Percentage through session that enforcement triggers - - segment_manifest: - window (float): Window length for segmentation - shift (float): Shift length for segmentation - step_count (int): Number of unit segments per utterance - deci (int): Rounding decimals for segment manifest file - """ - - def __init__(self, cfg): - self._params = cfg - self.annotator = DataAnnotator(cfg) - self.sampler = SpeechSampler(cfg) - # internal params - self._manifest = read_manifest(self._params.data_simulator.manifest_filepath) - self._speaker_samples = build_speaker_samples_map(self._manifest) - self._noise_samples = [] - self._sentence = None - self._text = "" - self._words = [] - self._alignments = [] - # minimum number of alignments for a manifest to be considered valid - self._min_alignment_count = 2 - self._merged_speech_intervals = [] - # keep track of furthest sample per speaker to avoid overlapping same speaker - self._furthest_sample = [0 for n in range(self._params.data_simulator.session_config.num_speakers)] - # use to ensure overlap percentage is correct - self._missing_overlap = 0 - # creating manifests during online data simulation - self.base_manifest_filepath = None - self.segment_manifest_filepath = None - self._max_audio_read_sec = self._params.data_simulator.session_params.max_audio_read_sec - self._turn_prob_min = self._params.data_simulator.session_params.get("turn_prob_min", 0.5) - # variable speaker volume - self._volume = None - self._speaker_ids = None - self._device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") - self._audio_read_buffer_dict = {} - self.add_missing_overlap = self._params.data_simulator.session_params.get("add_missing_overlap", False) - - if ( - self._params.data_simulator.segment_augmentor.get("augmentor", None) - and self._params.data_simulator.segment_augmentor.add_seg_aug - ): - self.segment_augmentor = process_augmentations( - augmenter=self._params.data_simulator.segment_augmentor.augmentor - ) - else: - self.segment_augmentor = None - - if ( - self._params.data_simulator.session_augmentor.get("augmentor", None) - and self._params.data_simulator.session_augmentor.add_sess_aug - ): - self.session_augmentor = process_augmentations( - augmenter=self._params.data_simulator.session_augmentor.augmentor - ) - else: - self.session_augmentor = None - - # Error check the input arguments for simulation - self._check_args() - - # Initialize speaker permutations to maximize the number of speakers in the created dataset - self._permutated_speaker_inds = self._init_speaker_permutations( - num_sess=self._params.data_simulator.session_config.num_sessions, - num_speakers=self._params.data_simulator.session_config.num_speakers, - all_speaker_ids=self._speaker_samples.keys(), - random_seed=self._params.data_simulator.random_seed, - ) - - # Intialize multiprocessing related variables - self.num_workers = self._params.get("num_workers", 1) - self.multiprocessing_chunksize = self._params.data_simulator.get('multiprocessing_chunksize', 10000) - self.chunk_count = self._init_chunk_count() - - def _init_speaker_permutations(self, num_sess: int, num_speakers: int, all_speaker_ids: List, random_seed: int): - """ - Initialize the speaker permutations for the number of speakers in the session. - When generating the simulated sessions, we want to include as many speakers as possible. - This function generates a set of permutations that can be used to sweep all speakers in - the source dataset to make sure we maximize the total number of speakers included in - the simulated sessions. - - Args: - num_sess (int): Number of sessions to generate - num_speakers (int): Number of speakers in each session - all_speaker_ids (list): List of all speaker IDs - - Returns: - permuted_inds (np.array): - Array of permuted speaker indices to use for each session - Dimensions: (num_sess, num_speakers) - """ - np.random.seed(random_seed) - all_speaker_id_counts = len(list(all_speaker_ids)) - - # Calculate how many permutations are needed - perm_set_count = int(np.ceil(num_speakers * num_sess / all_speaker_id_counts)) - - target_count = num_speakers * num_sess - for count in range(perm_set_count): - if target_count < all_speaker_id_counts: - seq_len = target_count - else: - seq_len = all_speaker_id_counts - if seq_len <= 0: - raise ValueError(f"seq_len is {seq_len} at count {count} and should be greater than 0") - - if count == 0: - permuted_inds = np.random.permutation(len(all_speaker_ids))[:seq_len] - else: - permuted_inds = np.hstack((permuted_inds, np.random.permutation(len(all_speaker_ids))[:seq_len])) - target_count -= seq_len - - logging.info(f"Total {all_speaker_id_counts} speakers in the source dataset.") - logging.info(f"Initialized speaker permutations for {num_sess} sessions with {num_speakers} speakers each.") - return permuted_inds.reshape(num_sess, num_speakers) - - def _init_chunk_count(self): - """ - Initialize the chunk count for multi-processing to prevent over-flow of job counts. - The multi-processing pipeline can freeze if there are more than approximately 10,000 jobs - in the pipeline at the same time. - """ - return int(np.ceil(self._params.data_simulator.session_config.num_sessions / self.multiprocessing_chunksize)) - - def _check_args(self): - """ - Checks YAML arguments to ensure they are within valid ranges. - """ - if self._params.data_simulator.session_config.num_speakers < 1: - raise Exception("At least one speaker is required for making audio sessions (num_speakers < 1)") - if ( - self._params.data_simulator.session_params.turn_prob < 0 - or self._params.data_simulator.session_params.turn_prob > 1 - ): - raise Exception("Turn probability is outside of [0,1]") - if ( - self._params.data_simulator.session_params.turn_prob < 0 - or self._params.data_simulator.session_params.turn_prob > 1 - ): - raise Exception("Turn probability is outside of [0,1]") - elif ( - self._params.data_simulator.session_params.turn_prob < self._turn_prob_min - and self._params.data_simulator.speaker_enforcement.enforce_num_speakers == True - ): - logging.warning( - "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." - ) - self._params.data_simulator.session_params.turn_prob = self._turn_prob_min - if self._params.data_simulator.session_params.max_audio_read_sec < 2.5: - raise Exception("Max audio read time must be greater than 2.5 seconds") - - if self._params.data_simulator.session_params.sentence_length_params[0] <= 0: - raise Exception( - "k (number of success until the exp. ends) in Sentence length parameter value must be a positive number" - ) - - if not (0 < self._params.data_simulator.session_params.sentence_length_params[1] <= 1): - raise Exception("p (success probability) value in sentence length parameter must be in range (0,1]") - - if ( - self._params.data_simulator.session_params.mean_overlap < 0 - or self._params.data_simulator.session_params.mean_overlap > 1 - ): - raise Exception("Mean overlap is outside of [0,1]") - if ( - self._params.data_simulator.session_params.mean_silence < 0 - or self._params.data_simulator.session_params.mean_silence > 1 - ): - raise Exception("Mean silence is outside of [0,1]") - if self._params.data_simulator.session_params.mean_silence_var < 0: - raise Exception("Mean silence variance is not below 0") - if ( - self._params.data_simulator.session_params.mean_silence > 0 - and self._params.data_simulator.session_params.mean_silence_var - >= self._params.data_simulator.session_params.mean_silence - * (1 - self._params.data_simulator.session_params.mean_silence) - ): - raise Exception("Mean silence variance should be lower than mean_silence * (1-mean_silence)") - if self._params.data_simulator.session_params.per_silence_var < 0: - raise Exception("Per silence variance is below 0") - - if self._params.data_simulator.session_params.mean_overlap_var < 0: - raise Exception("Mean overlap variance is not larger than 0") - if ( - self._params.data_simulator.session_params.mean_overlap > 0 - and self._params.data_simulator.session_params.mean_overlap_var - >= self._params.data_simulator.session_params.mean_overlap - * (1 - self._params.data_simulator.session_params.mean_overlap) - ): - raise Exception("Mean overlap variance should be lower than mean_overlap * (1-mean_overlap)") - if self._params.data_simulator.session_params.per_overlap_var < 0: - raise Exception("Per overlap variance is not larger than 0") - - if ( - self._params.data_simulator.session_params.min_dominance < 0 - or self._params.data_simulator.session_params.min_dominance > 1 - ): - raise Exception("Minimum dominance is outside of [0,1]") - if ( - self._params.data_simulator.speaker_enforcement.enforce_time[0] < 0 - or self._params.data_simulator.speaker_enforcement.enforce_time[0] > 1 - ): - raise Exception("Speaker enforcement start is outside of [0,1]") - if ( - self._params.data_simulator.speaker_enforcement.enforce_time[1] < 0 - or self._params.data_simulator.speaker_enforcement.enforce_time[1] > 1 - ): - raise Exception("Speaker enforcement end is outside of [0,1]") - - if ( - self._params.data_simulator.session_params.min_dominance - * self._params.data_simulator.session_config.num_speakers - > 1 - ): - raise Exception("Number of speakers times minimum dominance is greater than 1") - - if ( - self._params.data_simulator.session_params.window_type not in ['hamming', 'hann', 'cosine'] - and self._params.data_simulator.session_params.window_type is not None - ): - raise Exception("Incorrect window type provided") - - if len(self._manifest) == 0: - raise Exception("Manifest file is empty. Check that the source path is correct.") - - def clean_up(self): - """ - Clear the system memory. Cache data for audio files and alignments are removed. - """ - self._sentence = None - self._words = [] - self._alignments = [] - self._audio_read_buffer_dict = {} - torch.cuda.empty_cache() - - def _get_speaker_dominance(self) -> List[float]: - """ - Get the dominance value for each speaker, accounting for the dominance variance and - the minimum per-speaker dominance. - - Returns: - dominance (list): Per-speaker dominance - """ - dominance_mean = 1.0 / self._params.data_simulator.session_config.num_speakers - dominance = np.random.normal( - loc=dominance_mean, - scale=self._params.data_simulator.session_params.dominance_var, - size=self._params.data_simulator.session_config.num_speakers, - ) - dominance = np.clip(dominance, a_min=0, a_max=np.inf) - # normalize while maintaining minimum dominance - total = np.sum(dominance) - if total == 0: - for i in range(len(dominance)): - dominance[i] += self._params.data_simulator.session_params.min_dominance - # scale accounting for min_dominance which has to be added after - dominance = (dominance / total) * ( - 1 - - self._params.data_simulator.session_params.min_dominance - * self._params.data_simulator.session_config.num_speakers - ) - for i in range(len(dominance)): - dominance[i] += self._params.data_simulator.session_params.min_dominance - if ( - i > 0 - ): # dominance values are cumulative to make it easy to select the speaker using a random value in [0,1] - dominance[i] = dominance[i] + dominance[i - 1] - return dominance - - def _increase_speaker_dominance( - self, base_speaker_dominance: List[float], factor: int - ) -> Tuple[List[float], bool]: - """ - Increase speaker dominance for unrepresented speakers (used only in enforce mode). - Increases the dominance for these speakers by the input factor (and then re-normalizes the probabilities to 1). - - Args: - base_speaker_dominance (list): Dominance values for each speaker. - factor (int): Factor to increase dominance of unrepresented speakers by. - Returns: - dominance (list): Per-speaker dominance - enforce (bool): Whether to keep enforce mode turned on - """ - increase_percent = [] - for i in range(self._params.data_simulator.session_config.num_speakers): - if self._furthest_sample[i] == 0: - increase_percent.append(i) - # ramp up enforce counter until speaker is sampled, then reset once all speakers have spoken - if len(increase_percent) > 0: - # extract original per-speaker probabilities - dominance = np.copy(base_speaker_dominance) - for i in range(len(dominance) - 1, 0, -1): - dominance[i] = dominance[i] - dominance[i - 1] - # increase specified speakers by the desired factor - for i in increase_percent: - dominance[i] = dominance[i] * factor - # renormalize - dominance = dominance / np.sum(dominance) - for i in range(1, len(dominance)): - dominance[i] = dominance[i] + dominance[i - 1] - enforce = True - else: # no unrepresented speakers, so enforce mode can be turned off - dominance = base_speaker_dominance - enforce = False - return dominance, enforce - - def _set_speaker_volume(self): - """ - Set the volume for each speaker (either equal volume or variable speaker volume). - """ - if self._params.data_simulator.session_params.normalization_type == 'equal': - self._volume = np.ones(self._params.data_simulator.session_config.num_speakers) - elif self._params.data_simulator.session_params.normalization_type == 'variable': - self._volume = np.random.normal( - loc=1.0, - scale=self._params.data_simulator.session_params.normalization_var, - size=self._params.data_simulator.session_config.num_speakers, - ) - self._volume = np.clip( - np.array(self._volume), - a_min=self._params.data_simulator.session_params.min_volume, - a_max=self._params.data_simulator.session_params.max_volume, - ).tolist() - - def _get_next_speaker(self, prev_speaker: int, dominance: List[float]) -> int: - """ - Get the next speaker (accounting for turn probability and dominance distribution). - - Args: - prev_speaker (int): Previous speaker turn. - dominance (list): Dominance values for each speaker. - Returns: - prev_speaker/speaker_turn (int): Speaker turn - """ - if self._params.data_simulator.session_config.num_speakers == 1: - prev_speaker = 0 if prev_speaker is None else prev_speaker - return prev_speaker - else: - if ( - np.random.uniform(0, 1) > self._params.data_simulator.session_params.turn_prob - and prev_speaker is not None - ): - return prev_speaker - else: - speaker_turn = prev_speaker - while speaker_turn == prev_speaker: # ensure another speaker goes next - rand = np.random.uniform(0, 1) - speaker_turn = 0 - while rand > dominance[speaker_turn]: - speaker_turn += 1 - return speaker_turn - - def _get_window(self, window_amount: int, start: bool = False): - """ - Get window curve to alleviate abrupt change of time-series signal when segmenting audio samples. - - Args: - window_amount (int): Window length (in terms of number of samples). - start (bool): If true, return the first half of the window. - - Returns: - window (tensor): Half window (either first half or second half) - """ - if self._params.data_simulator.session_params.window_type == 'hamming': - window = hamming(window_amount * 2) - elif self._params.data_simulator.session_params.window_type == 'hann': - window = hann(window_amount * 2) - elif self._params.data_simulator.session_params.window_type == 'cosine': - window = cosine(window_amount * 2) - else: - raise Exception("Incorrect window type provided") - - window = torch.from_numpy(window).to(self._device) - - # return the first half or second half of the window - if start: - return window[:window_amount] - else: - return window[window_amount:] - - def _get_start_buffer_and_window(self, first_alignment: int) -> Tuple[int, int]: - """ - Get the start cutoff and window length for smoothing the start of the sentence. - - Args: - first_alignment (int): Start of the first word (in terms of number of samples). - Returns: - start_cutoff (int): Amount into the audio clip to start - window_amount (int): Window length - """ - window_amount = int(self._params.data_simulator.session_params.window_size * self._params.data_simulator.sr) - start_buffer = int(self._params.data_simulator.session_params.start_buffer * self._params.data_simulator.sr) - - if first_alignment < start_buffer: - window_amount = 0 - start_cutoff = 0 - elif first_alignment < start_buffer + window_amount: - window_amount = first_alignment - start_buffer - start_cutoff = 0 - else: - start_cutoff = first_alignment - start_buffer - window_amount - - return start_cutoff, window_amount - - def _get_end_buffer_and_window( - self, current_sample_cursor: int, remaining_dur_samples: int, remaining_len_audio_file: int - ) -> Tuple[int, int]: - """ - Get the end buffer and window length for smoothing the end of the sentence. - - Args: - current_sample_cursor (int): Current location in the target file (in terms of number of samples). - remaining_dur_samples (int): Remaining duration in the target file (in terms of number of samples). - remaining_len_audio_file (int): Length remaining in audio file (in terms of number of samples). - Returns: - release_buffer (int): Amount after the end of the last alignment to include - window_amount (int): Window length - """ - window_amount = int(self._params.data_simulator.session_params.window_size * self._params.data_simulator.sr) - release_buffer = int( - self._params.data_simulator.session_params.release_buffer * self._params.data_simulator.sr - ) - - if current_sample_cursor + release_buffer > remaining_dur_samples: - release_buffer = remaining_dur_samples - current_sample_cursor - window_amount = 0 - elif current_sample_cursor + window_amount + release_buffer > remaining_dur_samples: - window_amount = remaining_dur_samples - current_sample_cursor - release_buffer - - if remaining_len_audio_file < release_buffer: - release_buffer = remaining_len_audio_file - window_amount = 0 - elif remaining_len_audio_file < release_buffer + window_amount: - window_amount = remaining_len_audio_file - release_buffer - - return release_buffer, window_amount - - def _check_missing_speakers(self, num_missing: int = 0): - """ - Check if any speakers were not included in the clip and display a warning. - - Args: - num_missing (int): Number of missing speakers. - """ - for k in range(len(self._furthest_sample)): - if self._furthest_sample[k] == 0: - num_missing += 1 - if num_missing != 0: - warnings.warn( - f"{self._params.data_simulator.session_config.num_speakers - num_missing}" - "speakers were included in the clip instead of the requested amount of " - f"{self._params.data_simulator.session_config.num_speakers}" - ) - - def _add_file( - self, - audio_manifest: dict, - audio_file, - sentence_word_count: int, - max_word_count_in_sentence: int, - max_samples_in_sentence: int, - random_offset: bool = False, - ) -> Tuple[int, torch.Tensor]: - """ - Add audio file to current sentence (up to the desired number of words). - Uses the alignments to segment the audio file. - NOTE: 0 index is always silence in `audio_manifest['words']`, so we choose `offset_idx=1` as the first word - - Args: - audio_manifest (dict): Line from manifest file for current audio file - audio_file (tensor): Current loaded audio file - sentence_word_count (int): Running count for number of words in sentence - max_word_count_in_sentence (int): Maximum count for number of words in sentence - max_samples_in_sentence (int): Maximum length for sentence in terms of samples - - Returns: - sentence_word_count+current_word_count (int): Running word count - len(self._sentence) (tensor): Current length of the audio file - """ - # In general, random offset is not needed since random silence index has already been chosen - if random_offset: - offset_idx = np.random.randint(low=1, high=len(audio_manifest['words'])) - else: - offset_idx = 1 - - first_alignment = int(audio_manifest['alignments'][offset_idx - 1] * self._params.data_simulator.sr) - start_cutoff, start_window_amount = self._get_start_buffer_and_window(first_alignment) - if not self._params.data_simulator.session_params.start_window: # cut off the start of the sentence - start_window_amount = 0 - - # Ensure the desired number of words are added and the length of the output session isn't exceeded - sentence_samples = len(self._sentence) - - remaining_dur_samples = max_samples_in_sentence - sentence_samples - remaining_duration = max_word_count_in_sentence - sentence_word_count - prev_dur_samples, dur_samples, curr_dur_samples = 0, 0, 0 - current_word_count = 0 - word_idx = offset_idx - silence_count = 1 - while ( - current_word_count < remaining_duration - and dur_samples < remaining_dur_samples - and word_idx < len(audio_manifest['words']) - ): - dur_samples = int(audio_manifest['alignments'][word_idx] * self._params.data_simulator.sr) - start_cutoff - - # check the length of the generated sentence in terms of sample count (int). - if curr_dur_samples + dur_samples > remaining_dur_samples: - # if the upcoming loop will exceed the remaining sample count, break out of the loop. - break - - word = audio_manifest['words'][word_idx] - - if silence_count > 0 and word == "": - break - - self._words.append(word) - self._alignments.append( - float(sentence_samples * 1.0 / self._params.data_simulator.sr) - - float(start_cutoff * 1.0 / self._params.data_simulator.sr) - + audio_manifest['alignments'][word_idx] - ) - - if word == "": - word_idx += 1 - silence_count += 1 - continue - elif self._text == "": - self._text += word - else: - self._text += " " + word - - word_idx += 1 - current_word_count += 1 - prev_dur_samples = dur_samples - curr_dur_samples += dur_samples - - # add audio clip up to the final alignment - if self._params.data_simulator.session_params.window_type is not None: # cut off the start of the sentence - if start_window_amount > 0: # include window - window = self._get_window(start_window_amount, start=True) - self._sentence = self._sentence.to(self._device) - self._sentence = torch.cat( - ( - self._sentence, - torch.multiply(audio_file[start_cutoff : start_cutoff + start_window_amount], window), - ), - 0, - ) - self._sentence = torch.cat( - ( - self._sentence, - audio_file[start_cutoff + start_window_amount : start_cutoff + prev_dur_samples], - ), - 0, - ).to(self._device) - - else: - self._sentence = torch.cat( - (self._sentence, audio_file[start_cutoff : start_cutoff + prev_dur_samples]), 0 - ).to(self._device) - - # windowing at the end of the sentence - if ( - word_idx < len(audio_manifest['words']) - ) and self._params.data_simulator.session_params.window_type is not None: - release_buffer, end_window_amount = self._get_end_buffer_and_window( - prev_dur_samples, - remaining_dur_samples, - len(audio_file[start_cutoff + prev_dur_samples :]), - ) - self._sentence = torch.cat( - ( - self._sentence, - audio_file[start_cutoff + prev_dur_samples : start_cutoff + prev_dur_samples + release_buffer], - ), - 0, - ).to(self._device) - - if end_window_amount > 0: # include window - window = self._get_window(end_window_amount, start=False) - sig_start = start_cutoff + prev_dur_samples + release_buffer - sig_end = start_cutoff + prev_dur_samples + release_buffer + end_window_amount - windowed_audio_file = torch.multiply(audio_file[sig_start:sig_end], window) - self._sentence = torch.cat((self._sentence, windowed_audio_file), 0).to(self._device) - - del audio_file - return sentence_word_count + current_word_count, len(self._sentence) - - def _build_sentence( - self, - speaker_turn: int, - speaker_ids: List[str], - speaker_wav_align_map: Dict[str, list], - max_samples_in_sentence: int, - ): - """ - Build a new sentence by attaching utterance samples together until the sentence has reached a desired length. - While generating the sentence, alignment information is used to segment the audio. - - Args: - speaker_turn (int): Current speaker turn. - speaker_ids (list): LibriSpeech speaker IDs for each speaker in the current session. - speaker_wav_align_map (dict): Dictionary containing speaker IDs and their corresponding wav filepath and alignments. - max_samples_in_sentence (int): Maximum length for sentence in terms of samples - """ - # select speaker length - sl = ( - np.random.negative_binomial( - self._params.data_simulator.session_params.sentence_length_params[0], - self._params.data_simulator.session_params.sentence_length_params[1], - ) - + 1 - ) - - # initialize sentence, text, words, alignments - self._sentence = torch.zeros(0, dtype=torch.float64, device=self._device) - self._text = "" - self._words, self._alignments = [], [] - sentence_word_count, sentence_samples = 0, 0 - - # build sentence - while sentence_word_count < sl and sentence_samples < max_samples_in_sentence: - audio_manifest = load_speaker_sample( - speaker_wav_align_map=speaker_wav_align_map, - speaker_ids=speaker_ids, - speaker_turn=speaker_turn, - min_alignment_count=self._min_alignment_count, - ) - - offset_index = get_random_offset_index( - audio_manifest=audio_manifest, - audio_read_buffer_dict=self._audio_read_buffer_dict, - offset_min=0, - max_audio_read_sec=self._max_audio_read_sec, - min_alignment_count=self._min_alignment_count, - ) - - audio_file, sr, audio_manifest = read_audio_from_buffer( - audio_manifest=audio_manifest, - buffer_dict=self._audio_read_buffer_dict, - offset_index=offset_index, - device=self._device, - max_audio_read_sec=self._max_audio_read_sec, - min_alignment_count=self._min_alignment_count, - read_subset=True, - ) - - # Step 6-2: Add optional perturbations to the specific audio segment (i.e. to `self._sentnece`) - if self._params.data_simulator.segment_augmentor.add_seg_aug: - audio_file = perturb_audio(audio_file, sr, self.segment_augmentor, device=self._device) - - sentence_word_count, sentence_samples = self._add_file( - audio_manifest, audio_file, sentence_word_count, sl, max_samples_in_sentence - ) - - # per-speaker normalization (accounting for active speaker time) - if self._params.data_simulator.session_params.normalize and torch.max(torch.abs(self._sentence)) > 0: - splits = get_split_points_in_alignments( - words=self._words, - alignments=self._alignments, - split_buffer=self._params.data_simulator.session_params.split_buffer, - sr=self._params.data_simulator.sr, - sentence_audio_len=len(self._sentence), - ) - self._sentence = per_speaker_normalize( - sentence_audio=self._sentence, - splits=splits, - speaker_turn=speaker_turn, - volume=self._volume, - device=self._device, - ) - - def _add_silence_or_overlap( - self, - speaker_turn: int, - prev_speaker: int, - start: int, - length: int, - session_len_samples: int, - prev_len_samples: int, - enforce: bool, - ) -> int: - """ - Returns new overlapped (or shifted) start position after inserting overlap or silence. - - Args: - speaker_turn (int): The integer index of the current speaker turn. - prev_speaker (int): The integer index of the previous speaker turn. - start (int): Current start of the audio file being inserted. - length (int): Length of the audio file being inserted. - session_len_samples (int): Maximum length of the session in terms of number of samples - prev_len_samples (int): Length of previous sentence (in terms of number of samples) - enforce (bool): Whether speaker enforcement mode is being used - Returns: - new_start (int): New starting position in the session accounting for overlap or silence - """ - running_len_samples = start + length - # `length` is the length of the current sentence to be added, so not included in self.sampler.running_speech_len_samples - non_silence_len_samples = self.sampler.running_speech_len_samples + length - - # compare silence and overlap ratios - add_overlap = self.sampler.silence_vs_overlap_selector(running_len_samples, non_silence_len_samples) - - # choose overlap if this speaker is not the same as the previous speaker and add_overlap is True. - if prev_speaker != speaker_turn and prev_speaker is not None and add_overlap: - desired_overlap_amount = self.sampler.sample_from_overlap_model(non_silence_len_samples) - new_start = start - desired_overlap_amount - - # avoid overlap at start of clip - if new_start < 0: - desired_overlap_amount -= 0 - new_start - self._missing_overlap += 0 - new_start - new_start = 0 - - # if same speaker ends up overlapping from any previous clip, pad with silence instead - if new_start < self._furthest_sample[speaker_turn]: - desired_overlap_amount -= self._furthest_sample[speaker_turn] - new_start - self._missing_overlap += self._furthest_sample[speaker_turn] - new_start - new_start = self._furthest_sample[speaker_turn] - - prev_start = start - prev_len_samples - prev_end = start - new_end = new_start + length - - # check overlap amount to calculate the actual amount of generated overlaps - overlap_amount = 0 - if is_overlap([prev_start, prev_end], [new_start, new_end]): - overlap_range = get_overlap_range([prev_start, prev_end], [new_start, new_end]) - overlap_amount = max(overlap_range[1] - overlap_range[0], 0) - - if overlap_amount < desired_overlap_amount: - self._missing_overlap += desired_overlap_amount - overlap_amount - self.sampler.running_overlap_len_samples += overlap_amount - - # if we are not adding overlap, add silence - else: - silence_amount = self.sampler.sample_from_silence_model(running_len_samples) - if start + length + silence_amount > session_len_samples and not enforce: - new_start = max(session_len_samples - length, start) - else: - new_start = start + silence_amount - return new_start - - def _get_session_meta_data(self, array: np.ndarray, snr: float) -> dict: - """ - Get meta data for the current session. - - Args: - array (np.ndarray): audio array - snr (float): signal-to-noise ratio - - Returns: - dict: meta data - """ - meta_data = { - "duration": array.shape[0] / self._params.data_simulator.sr, - "silence_mean": self.sampler.sess_silence_mean, - "overlap_mean": self.sampler.sess_overlap_mean, - "bg_snr": snr, - "speaker_ids": self._speaker_ids, - "speaker_volumes": list(self._volume), - } - return meta_data - - def _get_session_silence_from_rttm(self, rttm_list: List[str], running_len_samples: int): - """ - Calculate the total speech and silence duration in the current session using RTTM file. - - Args: - rttm_list (list): - List of RTTM timestamps - running_len_samples (int): - Total number of samples generated so far in the current session - - Returns: - sess_speech_len_rttm (int): - The total number of speech samples in the current session - sess_silence_len_rttm (int): - The total number of silence samples in the current session - """ - all_sample_list = [] - for x_raw in rttm_list: - x = [token for token in x_raw.split()] - all_sample_list.append([float(x[0]), float(x[1])]) - - self._merged_speech_intervals = merge_float_intervals(all_sample_list) - total_speech_in_secs = sum([x[1] - x[0] for x in self._merged_speech_intervals]) - total_silence_in_secs = running_len_samples / self._params.data_simulator.sr - total_speech_in_secs - sess_speech_len = int(total_speech_in_secs * self._params.data_simulator.sr) - sess_silence_len = int(total_silence_in_secs * self._params.data_simulator.sr) - return sess_speech_len, sess_silence_len - - def _add_sentence_to_array( - self, start: int, length: int, array: torch.Tensor, is_speech: torch.Tensor - ) -> Tuple[torch.Tensor, torch.Tensor, int]: - """ - Add a sentence to the session array containing time-series signal. - - Args: - start (int): Starting position in the session - length (int): Length of the sentence - array (torch.Tensor): Session array - is_speech (torch.Tensor): Session array containing speech/non-speech labels - - Returns: - array (torch.Tensor): Session array in torch.Tensor format - is_speech (torch.Tensor): Session array containing speech/non-speech labels in torch.Tensor format - """ - end = start + length - if end > len(array): # only occurs in enforce mode - array = torch.nn.functional.pad(array, (0, end - len(array))) - is_speech = torch.nn.functional.pad(is_speech, (0, end - len(is_speech))) - array[start:end] += self._sentence - is_speech[start:end] = 1 - return array, is_speech, end - - def _generate_session( - self, - idx: int, - basepath: str, - filename: str, - speaker_ids: List[str], - speaker_wav_align_map: Dict[str, list], - noise_samples: list, - device: torch.device, - enforce_counter: int = 2, - ): - """ - _generate_session function without RIR simulation. - Generate a multispeaker audio session and corresponding label files. - - Args: - idx (int): Index for current session (out of total number of sessions). - basepath (str): Path to output directory. - filename (str): Filename for output files. - speaker_ids (list): List of speaker IDs that will be used in this session. - speaker_wav_align_map (dict): Dictionary containing speaker IDs and their corresponding wav filepath and alignments. - noise_samples (list): List of randomly sampled noise source files that will be used for generating this session. - device (torch.device): Device to use for generating this session. - enforce_counter (int): In enforcement mode, dominance is increased by a factor of enforce_counter for unrepresented speakers - """ - random_seed = self._params.data_simulator.random_seed - np.random.seed(random_seed + idx) - - self._device = device - speaker_dominance = self._get_speaker_dominance() # randomly determine speaker dominance - base_speaker_dominance = np.copy(speaker_dominance) - self._set_speaker_volume() - - running_len_samples, prev_len_samples = 0, 0 - prev_speaker = None - self.annotator.init_annotation_lists() - self._noise_samples = noise_samples - self._furthest_sample = [0 for n in range(self._params.data_simulator.session_config.num_speakers)] - self._missing_silence = 0 - - # hold enforce until all speakers have spoken - enforce_time = np.random.uniform( - self._params.data_simulator.speaker_enforcement.enforce_time[0], - self._params.data_simulator.speaker_enforcement.enforce_time[1], - ) - enforce = self._params.data_simulator.speaker_enforcement.enforce_num_speakers - - session_len_samples = int( - (self._params.data_simulator.session_config.session_length * self._params.data_simulator.sr) - ) - array = torch.zeros(session_len_samples).to(self._device) - is_speech = torch.zeros(session_len_samples).to(self._device) - - self.sampler.get_session_silence_mean() - self.sampler.get_session_overlap_mean() - - while running_len_samples < session_len_samples or enforce: - # Step 1: Prepare parameters for sentence generation - # Enforce speakers depending on running length - if running_len_samples > enforce_time * session_len_samples and enforce: - speaker_dominance, enforce = self._increase_speaker_dominance(base_speaker_dominance, enforce_counter) - if enforce: - enforce_counter += 1 - - # Step 2: Select a speaker - speaker_turn = self._get_next_speaker(prev_speaker, speaker_dominance) - - # Calculate parameters for building a sentence (only add if remaining length > specific time) - max_samples_in_sentence = session_len_samples - running_len_samples - if enforce: - max_samples_in_sentence = float('inf') - elif ( - max_samples_in_sentence - < self._params.data_simulator.session_params.end_buffer * self._params.data_simulator.sr - ): - break - - # Step 3: Generate a sentence - self._build_sentence(speaker_turn, speaker_ids, speaker_wav_align_map, max_samples_in_sentence) - length = len(self._sentence) - - # Step 4: Generate a timestamp for either silence or overlap - start = self._add_silence_or_overlap( - speaker_turn=speaker_turn, - prev_speaker=prev_speaker, - start=running_len_samples, - length=length, - session_len_samples=session_len_samples, - prev_len_samples=prev_len_samples, - enforce=enforce, - ) - # step 5: add sentence to array - array, is_speech, end = self._add_sentence_to_array( - start=start, - length=length, - array=array, - is_speech=is_speech, - ) - - # Step 6: Build entries for output files - new_rttm_entries = self.annotator.create_new_rttm_entry( - words=self._words, - alignments=self._alignments, - start=start / self._params.data_simulator.sr, - end=end / self._params.data_simulator.sr, - speaker_id=speaker_ids[speaker_turn], - ) - - self.annotator.annote_lists['rttm'].extend(new_rttm_entries) - - new_json_entry = self.annotator.create_new_json_entry( - text=self._text, - wav_filename=os.path.join(basepath, filename + '.wav'), - start=start / self._params.data_simulator.sr, - length=length / self._params.data_simulator.sr, - speaker_id=speaker_ids[speaker_turn], - rttm_filepath=os.path.join(basepath, filename + '.rttm'), - ctm_filepath=os.path.join(basepath, filename + '.ctm'), - ) - self.annotator.annote_lists['json'].append(new_json_entry) - - new_ctm_entries, _ = self.annotator.create_new_ctm_entry( - words=self._words, - alignments=self._alignments, - session_name=filename, - speaker_id=speaker_ids[speaker_turn], - start=float(start / self._params.data_simulator.sr), - ) - - self.annotator.annote_lists['ctm'].extend(new_ctm_entries) - - running_len_samples = np.maximum(running_len_samples, end) - ( - self.sampler.running_speech_len_samples, - self.sampler.running_silence_len_samples, - ) = self._get_session_silence_from_rttm( - rttm_list=self.annotator.annote_lists['rttm'], running_len_samples=running_len_samples - ) - - self._furthest_sample[speaker_turn] = running_len_samples - prev_speaker = speaker_turn - prev_len_samples = length - - # Step 7-1: Add optional perturbations to the whole session, such as white noise. - if self._params.data_simulator.session_augmentor.add_sess_aug: - # NOTE: This perturbation is not reflected in the session SNR in meta dictionary. - array = perturb_audio(array, self._params.data_simulator.sr, self.session_augmentor, device=array.device) - - # Step 7-2: Additive background noise from noise manifest files - if self._params.data_simulator.background_noise.add_bg: - if len(self._noise_samples) > 0: - avg_power_array = torch.mean(array[is_speech == 1] ** 2) - bg, snr, _ = get_background_noise( - len_array=len(array), - power_array=avg_power_array, - noise_samples=self._noise_samples, - audio_read_buffer_dict=self._audio_read_buffer_dict, - snr_min=self._params.data_simulator.background_noise.snr_min, - snr_max=self._params.data_simulator.background_noise.snr_max, - background_noise_snr=self._params.data_simulator.background_noise.snr, - seed=(random_seed + idx), - device=self._device, - ) - array += bg - else: - raise ValueError('No background noise samples found in self._noise_samples.') - else: - snr = "N/A" - - # Step 7: Normalize and write to disk - array = normalize_audio(array) - - if torch.is_tensor(array): - array = array.cpu().numpy() - sf.write(os.path.join(basepath, filename + '.wav'), array, self._params.data_simulator.sr) - - self.annotator.write_annotation_files( - basepath=basepath, - filename=filename, - meta_data=self._get_session_meta_data(array=array, snr=snr), - ) - - # Step 8: Clean up memory - del array - self.clean_up() - return basepath, filename - - def generate_sessions(self, random_seed: int = None): - """ - Generate several multispeaker audio sessions and corresponding list files. - - Args: - random_seed (int): random seed for reproducibility - """ - logging.info("Generating Diarization Sessions") - if random_seed is None: - random_seed = self._params.data_simulator.random_seed - np.random.seed(random_seed) - - output_dir = self._params.data_simulator.outputs.output_dir - - basepath = get_cleaned_base_path( - output_dir, overwrite_output=self._params.data_simulator.outputs.overwrite_output - ) - OmegaConf.save(self._params, os.path.join(output_dir, "params.yaml")) - - tp = concurrent.futures.ProcessPoolExecutor(max_workers=self.num_workers) - futures = [] - - num_sessions = self._params.data_simulator.session_config.num_sessions - source_noise_manifest = read_noise_manifest( - add_bg=self._params.data_simulator.background_noise.add_bg, - background_manifest=self._params.data_simulator.background_noise.background_manifest, - ) - queue = [] - - # add radomly sampled arguments to a list(queue) for multiprocessing - for sess_idx in range(num_sessions): - filename = self._params.data_simulator.outputs.output_filename + f"_{sess_idx}" - speaker_ids = get_speaker_ids( - sess_idx=sess_idx, - speaker_samples=self._speaker_samples, - permutated_speaker_inds=self._permutated_speaker_inds, - ) - speaker_wav_align_map = get_speaker_samples(speaker_ids=speaker_ids, speaker_samples=self._speaker_samples) - noise_samples = self.sampler.sample_noise_manifest(noise_manifest=source_noise_manifest) - - if torch.cuda.is_available(): - device = torch.device(f"cuda:{sess_idx % torch.cuda.device_count()}") - else: - device = self._device - queue.append((sess_idx, basepath, filename, speaker_ids, speaker_wav_align_map, noise_samples, device)) - - # for multiprocessing speed, we avoid loading potentially huge manifest list and speaker sample files into each process. - if self.num_workers > 1: - self._manifest = None - self._speaker_samples = None - - # Chunk the sessions into smaller chunks for very large number of sessions (10K+ sessions) - for chunk_idx in range(self.chunk_count): - futures = [] - stt_idx, end_idx = ( - chunk_idx * self.multiprocessing_chunksize, - min((chunk_idx + 1) * self.multiprocessing_chunksize, num_sessions), - ) - for sess_idx in range(stt_idx, end_idx): - self._furthest_sample = [0 for n in range(self._params.data_simulator.session_config.num_speakers)] - self._audio_read_buffer_dict = {} - if self.num_workers > 1: - futures.append(tp.submit(self._generate_session, *queue[sess_idx])) - else: - futures.append(queue[sess_idx]) - - if self.num_workers > 1: - generator = concurrent.futures.as_completed(futures) - else: - generator = futures - - for future in tqdm( - generator, - desc=f"[{chunk_idx+1}/{self.chunk_count}] Waiting jobs from {stt_idx+1: 2} to {end_idx: 2}", - unit="jobs", - total=len(futures), - ): - if self.num_workers > 1: - basepath, filename = future.result() - else: - self._noise_samples = self.sampler.sample_noise_manifest( - noise_manifest=source_noise_manifest, - ) - basepath, filename = self._generate_session(*future) - - self.annotator.add_to_filename_lists(basepath=basepath, filename=filename) - - # throw warning if number of speakers is less than requested - self._check_missing_speakers() - - tp.shutdown() - self.annotator.write_filelist_files(basepath=basepath) - logging.info(f"Data simulation has been completed, results saved at: {basepath}") - - -class RIRMultiSpeakerSimulator(MultiSpeakerSimulator): - """ - RIR Augmented Multispeaker Audio Session Simulator - simulates multispeaker audio sessions using single-speaker - audio files and corresponding word alignments, as well as simulated RIRs for augmentation. - - Args: - cfg: OmegaConf configuration loaded from yaml file. - - Additional configuration parameters (on top of ``MultiSpeakerSimulator``):: - - rir_generation: - use_rir (bool): Whether to generate synthetic RIR - toolkit (str): Which toolkit to use ("pyroomacoustics", "gpuRIR") - room_config: - room_sz (list): Size of the shoebox room environment - pos_src (list): Positions of the speakers in the simulated room - noise_src_pos (list): Position in room for background noise source - mic_config: - num_channels (int): Number of output audio channels - pos_rcv (list): Microphone positions in the simulated room - orV_rcv (list or null): Microphone orientations - mic_pattern (str): Microphone type ("omni") - absorbtion_params: - abs_weights (list): Absorption coefficient ratios for each surface - T60 (float): Room reverberation time (decay by 60dB) - att_diff (float): Starting attenuation for diffuse reverberation model - att_max (float): End attenuation for diffuse reverberation model (gpuRIR) - """ - - def __init__(self, cfg): - super().__init__(cfg) - self._check_args_rir() - - def _check_args_rir(self): - """ - Checks RIR YAML arguments to ensure they are within valid ranges - """ - - if not (self._params.data_simulator.rir_generation.toolkit in ['pyroomacoustics', 'gpuRIR']): - raise Exception("Toolkit must be pyroomacoustics or gpuRIR") - if self._params.data_simulator.rir_generation.toolkit == 'pyroomacoustics' and not PRA: - raise ImportError("pyroomacoustics should be installed to run this simulator with RIR augmentation") - - if self._params.data_simulator.rir_generation.toolkit == 'gpuRIR' and not GPURIR: - raise ImportError("gpuRIR should be installed to run this simulator with RIR augmentation") - - if len(self._params.data_simulator.rir_generation.room_config.room_sz) != 3: - raise Exception("Incorrect room dimensions provided") - if self._params.data_simulator.rir_generation.mic_config.num_channels == 0: - raise Exception("Number of channels should be greater or equal to 1") - if len(self._params.data_simulator.rir_generation.room_config.pos_src) < 2: - raise Exception("Less than 2 provided source positions") - for sublist in self._params.data_simulator.rir_generation.room_config.pos_src: - if len(sublist) != 3: - raise Exception("Three coordinates must be provided for sources positions") - if len(self._params.data_simulator.rir_generation.mic_config.pos_rcv) == 0: - raise Exception("No provided mic positions") - for sublist in self._params.data_simulator.rir_generation.room_config.pos_src: - if len(sublist) != 3: - raise Exception("Three coordinates must be provided for mic positions") - - if self._params.data_simulator.session_config.num_speakers != len( - self._params.data_simulator.rir_generation.room_config.pos_src - ): - raise Exception("Number of speakers is not equal to the number of provided source positions") - if self._params.data_simulator.rir_generation.mic_config.num_channels != len( - self._params.data_simulator.rir_generation.mic_config.pos_rcv - ): - raise Exception("Number of channels is not equal to the number of provided microphone positions") - - if ( - not self._params.data_simulator.rir_generation.mic_config.orV_rcv - and self._params.data_simulator.rir_generation.mic_config.mic_pattern != 'omni' - ): - raise Exception("Microphone orientations must be provided if mic_pattern != omni") - if self._params.data_simulator.rir_generation.mic_config.orV_rcv is not None: - if len(self._params.data_simulator.rir_generation.mic_config.orV_rcv) != len( - self._params.data_simulator.rir_generation.mic_config.pos_rcv - ): - raise Exception("A different number of microphone orientations and microphone positions were provided") - for sublist in self._params.data_simulator.rir_generation.mic_config.orV_rcv: - if len(sublist) != 3: - raise Exception("Three coordinates must be provided for orientations") - - def _generate_rir_gpuRIR(self): - """ - Create simulated RIR using the gpuRIR library - - Returns: - RIR (tensor): Generated RIR - RIR_pad (int): Length of padding added when convolving the RIR with an audio file - """ - room_sz_tmp = np.array(self._params.data_simulator.rir_generation.room_config.room_sz) - if room_sz_tmp.ndim == 2: # randomize - room_sz = np.zeros(room_sz_tmp.shape[0]) - for i in range(room_sz_tmp.shape[0]): - room_sz[i] = np.random.uniform(room_sz_tmp[i, 0], room_sz_tmp[i, 1]) - else: - room_sz = room_sz_tmp - - pos_src_tmp = np.array(self._params.data_simulator.rir_generation.room_config.pos_src) - if pos_src_tmp.ndim == 3: # randomize - pos_src = np.zeros((pos_src_tmp.shape[0], pos_src_tmp.shape[1])) - for i in range(pos_src_tmp.shape[0]): - for j in range(pos_src_tmp.shape[1]): - pos_src[i] = np.random.uniform(pos_src_tmp[i, j, 0], pos_src_tmp[i, j, 1]) - else: - pos_src = pos_src_tmp - - if self._params.data_simulator.background_noise.add_bg: - pos_src = np.vstack((pos_src, self._params.data_simulator.rir_generation.room_config.noise_src_pos)) - - mic_pos_tmp = np.array(self._params.data_simulator.rir_generation.mic_config.pos_rcv) - if mic_pos_tmp.ndim == 3: # randomize - mic_pos = np.zeros((mic_pos_tmp.shape[0], mic_pos_tmp.shape[1])) - for i in range(mic_pos_tmp.shape[0]): - for j in range(mic_pos_tmp.shape[1]): - mic_pos[i] = np.random.uniform(mic_pos_tmp[i, j, 0], mic_pos_tmp[i, j, 1]) - else: - mic_pos = mic_pos_tmp - - orV_rcv = self._params.data_simulator.rir_generation.mic_config.orV_rcv - if orV_rcv: # not needed for omni mics - orV_rcv = np.array(orV_rcv) - mic_pattern = self._params.data_simulator.rir_generation.mic_config.mic_pattern - abs_weights = self._params.data_simulator.rir_generation.absorbtion_params.abs_weights - T60 = self._params.data_simulator.rir_generation.absorbtion_params.T60 - att_diff = self._params.data_simulator.rir_generation.absorbtion_params.att_diff - att_max = self._params.data_simulator.rir_generation.absorbtion_params.att_max - sr = self._params.data_simulator.sr - - beta = beta_SabineEstimation(room_sz, T60, abs_weights=abs_weights) # Reflection coefficients - Tdiff = att2t_SabineEstimator(att_diff, T60) # Time to start the diffuse reverberation model [s] - Tmax = att2t_SabineEstimator(att_max, T60) # Time to stop the simulation [s] - nb_img = t2n(Tdiff, room_sz) # Number of image sources in each dimension - RIR = simulateRIR( - room_sz, beta, pos_src, mic_pos, nb_img, Tmax, sr, Tdiff=Tdiff, orV_rcv=orV_rcv, mic_pattern=mic_pattern - ) - RIR_pad = RIR.shape[2] - 1 - return RIR, RIR_pad - - def _generate_rir_pyroomacoustics(self) -> Tuple[torch.Tensor, int]: - """ - Create simulated RIR using the pyroomacoustics library - - Returns: - RIR (tensor): Generated RIR - RIR_pad (int): Length of padding added when convolving the RIR with an audio file - """ - - rt60 = self._params.data_simulator.rir_generation.absorbtion_params.T60 # The desired reverberation time - sr = self._params.data_simulator.sr - - room_sz_tmp = np.array(self._params.data_simulator.rir_generation.room_config.room_sz) - if room_sz_tmp.ndim == 2: # randomize - room_sz = np.zeros(room_sz_tmp.shape[0]) - for i in range(room_sz_tmp.shape[0]): - room_sz[i] = np.random.uniform(room_sz_tmp[i, 0], room_sz_tmp[i, 1]) - else: - room_sz = room_sz_tmp - - pos_src_tmp = np.array(self._params.data_simulator.rir_generation.room_config.pos_src) - if pos_src_tmp.ndim == 3: # randomize - pos_src = np.zeros((pos_src_tmp.shape[0], pos_src_tmp.shape[1])) - for i in range(pos_src_tmp.shape[0]): - for j in range(pos_src_tmp.shape[1]): - pos_src[i] = np.random.uniform(pos_src_tmp[i, j, 0], pos_src_tmp[i, j, 1]) - else: - pos_src = pos_src_tmp - - # We invert Sabine's formula to obtain the parameters for the ISM simulator - e_absorption, max_order = pra.inverse_sabine(rt60, room_sz) - room = pra.ShoeBox(room_sz, fs=sr, materials=pra.Material(e_absorption), max_order=max_order) - - if self._params.data_simulator.background_noise.add_bg: - pos_src = np.vstack((pos_src, self._params.data_simulator.rir_generation.room_config.noise_src_pos)) - for pos in pos_src: - room.add_source(pos) - - # currently only supports omnidirectional microphones - mic_pattern = self._params.data_simulator.rir_generation.mic_config.mic_pattern - if self._params.data_simulator.rir_generation.mic_config.mic_pattern == 'omni': - mic_pattern = DirectivityPattern.OMNI - dir_vec = DirectionVector(azimuth=0, colatitude=90, degrees=True) - else: - raise Exception("Currently, microphone pattern must be omni. Aborting RIR generation.") - dir_obj = CardioidFamily( - orientation=dir_vec, - pattern_enum=mic_pattern, - ) - - mic_pos_tmp = np.array(self._params.data_simulator.rir_generation.mic_config.pos_rcv) - if mic_pos_tmp.ndim == 3: # randomize - mic_pos = np.zeros((mic_pos_tmp.shape[0], mic_pos_tmp.shape[1])) - for i in range(mic_pos_tmp.shape[0]): - for j in range(mic_pos_tmp.shape[1]): - mic_pos[i] = np.random.uniform(mic_pos_tmp[i, j, 0], mic_pos_tmp[i, j, 1]) - else: - mic_pos = mic_pos_tmp - - room.add_microphone_array(mic_pos.T, directivity=dir_obj) - - room.compute_rir() - rir_pad = 0 - for channel in room.rir: - for pos in channel: - if pos.shape[0] - 1 > rir_pad: - rir_pad = pos.shape[0] - 1 - return room.rir, rir_pad - - def _convolve_rir(self, input, speaker_turn: int, RIR: torch.Tensor) -> Tuple[list, int]: - """ - Augment one sentence (or background noise segment) using a synthetic RIR. - - Args: - input (torch.tensor): Input audio. - speaker_turn (int): Current speaker turn. - RIR (torch.tensor): Room Impulse Response. - Returns: - output_sound (list): List of tensors containing augmented audio - length (int): Length of output audio channels (or of the longest if they have different lengths) - """ - output_sound = [] - length = 0 - for channel in range(self._params.data_simulator.rir_generation.mic_config.num_channels): - if self._params.data_simulator.rir_generation.toolkit == 'gpuRIR': - out_channel = convolve(input, RIR[speaker_turn, channel, : len(input)]).tolist() - elif self._params.data_simulator.rir_generation.toolkit == 'pyroomacoustics': - out_channel = convolve(input, RIR[channel][speaker_turn][: len(input)]).tolist() - else: - raise Exception("Toolkit must be pyroomacoustics or gpuRIR. Aborting RIR convolution.") - if len(out_channel) > length: - length = len(out_channel) - output_sound.append(torch.tensor(out_channel)) - return output_sound, length - - def _generate_session( - self, - idx: int, - basepath: str, - filename: str, - speaker_ids: list, - speaker_wav_align_map: dict, - noise_samples: list, - device: torch.device, - enforce_counter: int = 2, - ): - """ - Generate a multispeaker audio session and corresponding label files. - - Args: - idx (int): Index for current session (out of total number of sessions). - basepath (str): Path to output directory. - filename (str): Filename for output files. - speaker_ids (list): List of speaker IDs that will be used in this session. - speaker_wav_align_map (dict): Dictionary containing speaker IDs and their corresponding wav filepath and alignments. - noise_samples (list): List of randomly sampled noise source files that will be used for generating this session. - device (torch.device): Device to use for generating this session. - enforce_counter (int): In enforcement mode, dominance is increased by a factor of enforce_counter for unrepresented speakers - """ - random_seed = self._params.data_simulator.random_seed - np.random.seed(random_seed + idx) - - self._device = device - speaker_dominance = self._get_speaker_dominance() # randomly determine speaker dominance - base_speaker_dominance = np.copy(speaker_dominance) - self._set_speaker_volume() - - running_len_samples, prev_len_samples = 0, 0 # starting point for each sentence - prev_speaker = None - self.annotator.init_annotation_lists() - self._noise_samples = noise_samples - self._furthest_sample = [0 for n in range(self._params.data_simulator.session_config.num_speakers)] - - # Room Impulse Response Generation (performed once per batch of sessions) - if self._params.data_simulator.rir_generation.toolkit == 'gpuRIR': - RIR, RIR_pad = self._generate_rir_gpuRIR() - elif self._params.data_simulator.rir_generation.toolkit == 'pyroomacoustics': - RIR, RIR_pad = self._generate_rir_pyroomacoustics() - else: - raise Exception("Toolkit must be pyroomacoustics or gpuRIR") - - # hold enforce until all speakers have spoken - enforce_time = np.random.uniform( - self._params.data_simulator.speaker_enforcement.enforce_time[0], - self._params.data_simulator.speaker_enforcement.enforce_time[1], - ) - enforce = self._params.data_simulator.speaker_enforcement.enforce_num_speakers - - session_len_samples = int( - (self._params.data_simulator.session_config.session_length * self._params.data_simulator.sr) - ) - array = torch.zeros((session_len_samples, self._params.data_simulator.rir_generation.mic_config.num_channels)) - is_speech = torch.zeros(session_len_samples) - - while running_len_samples < session_len_samples or enforce: - # Step 1: Prepare parameters for sentence generation - # Enforce speakers depending on running length - if running_len_samples > enforce_time * session_len_samples and enforce: - speaker_dominance, enforce = self._increase_speaker_dominance(base_speaker_dominance, enforce_counter) - if enforce: - enforce_counter += 1 - - # Step 2: Select a speaker - speaker_turn = self._get_next_speaker(prev_speaker, speaker_dominance) - - # Calculate parameters for building a sentence (only add if remaining length > specific time) - max_samples_in_sentence = ( - session_len_samples - running_len_samples - RIR_pad - ) # sentence will be RIR_len - 1 longer than the audio was pre-augmentation - if enforce: - max_samples_in_sentence = float('inf') - elif ( - max_samples_in_sentence - < self._params.data_simulator.session_params.end_buffer * self._params.data_simulator.sr - ): - break - - # Step 3: Generate a sentence - self._build_sentence(speaker_turn, speaker_ids, speaker_wav_align_map, max_samples_in_sentence) - augmented_sentence, length = self._convolve_rir(self._sentence, speaker_turn, RIR) - - # Step 4: Generate a time-stamp for either silence or overlap - start = self._add_silence_or_overlap( - speaker_turn=speaker_turn, - prev_speaker=prev_speaker, - start=running_len_samples, - length=length, - session_len_samples=session_len_samples, - prev_len_samples=prev_len_samples, - enforce=enforce, - ) - # step 5: add sentence to array - end = start + length - if end > len(array): - array = torch.nn.functional.pad(array, (0, 0, 0, end - len(array))) - is_speech = torch.nn.functional.pad(is_speech, (0, end - len(is_speech))) - is_speech[start:end] = 1 - - for channel in range(self._params.data_simulator.rir_generation.mic_config.num_channels): - len_ch = len(augmented_sentence[channel]) # accounts for how channels are slightly different lengths - array[start : start + len_ch, channel] += augmented_sentence[channel] - - # Step 6: Build entries for output files - new_rttm_entries = self.annotator.create_new_rttm_entry( - self._words, - self._alignments, - start / self._params.data_simulator.sr, - end / self._params.data_simulator.sr, - speaker_ids[speaker_turn], - ) - - self.annotator.annote_lists['rttm'].extend(new_rttm_entries) - - new_json_entry = self.annotator.create_new_json_entry( - self._text, - os.path.join(basepath, filename + '.wav'), - start / self._params.data_simulator.sr, - length / self._params.data_simulator.sr, - speaker_ids[speaker_turn], - os.path.join(basepath, filename + '.rttm'), - os.path.join(basepath, filename + '.ctm'), - ) - self.annotator.annote_lists['json'].append(new_json_entry) - - new_ctm_entries, _ = self.annotator.create_new_ctm_entry( - words=self._text, - alignments=self._alignments, - session_name=filename, - speaker_id=speaker_ids[speaker_turn], - start=start / self._params.data_simulator.sr, - ) - self.annotator.annote_lists['ctm'].extend(new_ctm_entries) - - running_len_samples = np.maximum(running_len_samples, end) - self._furthest_sample[speaker_turn] = running_len_samples - prev_speaker = speaker_turn - prev_len_samples = length - - # Step 7-1: Add optional perturbations to the whole session, such as white noise. - if self._params.data_simulator.session_augmentor.add_sess_aug: - # NOTE: This perturbation is not reflected in the session SNR in meta dictionary. - array = perturb_audio(array, self._params.data_simulator.sr, self.session_augmentor) - - # Step 7-2: Additive background noise from noise manifest files - if self._params.data_simulator.background_noise.add_bg and len(self._noise_samples) > 0: - avg_power_array = torch.mean(array[is_speech == 1] ** 2) - bg, snr, _ = get_background_noise( - len_array=len(array), - power_array=avg_power_array, - noise_samples=self._noise_samples, - audio_read_buffer_dict=self._audio_read_buffer_dict, - snr_min=self._params.data_simulator.background_noise.snr_min, - snr_max=self._params.data_simulator.background_noise.snr_max, - background_noise_snr=self._params.data_simulator.background_noise.snr, - seed=(random_seed + idx), - device=self._device, - ) - array += bg - length = array.shape[0] - augmented_bg, _ = self._convolve_rir(bg, -1, RIR) - for channel in range(self._params.data_simulator.rir_generation.mic_config.num_channels): - array[:, channel] += augmented_bg[channel][:length] - else: - snr = "N/A" - - # Step 7: Normalize and write to disk - array = normalize_audio(array) - - if torch.is_tensor(array): - array = array.cpu().numpy() - sf.write(os.path.join(basepath, filename + '.wav'), array, self._params.data_simulator.sr) - - self.annotator.write_annotation_files( - basepath=basepath, - filename=filename, - meta_data=self._get_session_meta_data(array=array, snr=snr), - ) - - del array - self.clean_up() - return basepath, filename diff --git a/nemo/collections/asr/data/feature_to_label.py b/nemo/collections/asr/data/feature_to_label.py deleted file mode 100644 index 058d0157fcbd123f9029d08b2ad32037d6375b40..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/data/feature_to_label.py +++ /dev/null @@ -1,497 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -from typing import Dict, List, Optional - -import torch - -from nemo.collections.asr.parts.preprocessing.feature_loader import ExternalFeatureLoader -from nemo.collections.common.parts.preprocessing import collections -from nemo.core.classes import Dataset -from nemo.core.neural_types import AcousticEncodedRepresentation, LabelsType, LengthsType, NeuralType -from nemo.utils import logging - - -def _feature_collate_fn(batch): - """collate batch of feat sig, feat len, labels, labels len, assuming all features have the same shape. - Args: - batch (FloatTensor, LongTensor, LongTensor, LongTensor): A tuple of tuples of feature, feature lengths, - encoded labels, and encoded labels length. - """ - packed_batch = list(zip(*batch)) - if len(packed_batch) == 5: - _, feat_lengths, _, labels_lengths, sample_ids = packed_batch - elif len(packed_batch) == 4: - sample_ids = None - _, feat_lengths, _, labels_lengths = packed_batch - else: - raise ValueError("Expects 4 or 5 tensors in the batch!") - - features, labels = [], [] - for b in batch: - feat_i, labels_i = b[0], b[2] - features.append(feat_i) - labels.append(labels_i) - - features = torch.stack(features) - feat_lengths = torch.stack(feat_lengths) - - labels = torch.stack(labels) - labels_lengths = torch.stack(labels_lengths) - - if sample_ids is None: - return features, feat_lengths, labels, labels_lengths - else: - sample_ids = torch.tensor(sample_ids, dtype=torch.int32) - return features, feat_lengths, labels, labels_lengths, sample_ids - - -def _audio_feature_collate_fn(batch, feat_pad_val, label_pad_id): - """collate batch of audio feature, audio len, labels, labels len - Args: - batch (Optional[FloatTensor], Optional[LongTensor], LongTensor, - LongTensor): A tuple of tuples of feature, feature lengths, - labels, and label lengths. This collate func assumes the - features are torch tensors of Log-Melspectrogram (i.e. [N_MEL, T]). - """ - packed_batch = list(zip(*batch)) - if len(packed_batch) == 5: - _, feat_lengths, _, labels_lengths, sample_ids = packed_batch - elif len(packed_batch) == 4: - sample_ids = None - _, feat_lengths, _, labels_lengths = packed_batch - else: - raise ValueError("Expects 4 or 5 tensors in the batch!") - max_feat_len = 0 - has_feat = feat_lengths[0] is not None - if has_feat: - max_feat_len = max(feat_lengths).item() - max_labels_len = max(labels_lengths).item() - - features, labels = [], [] - for b in batch: - feat_i, feat_i_len, label_i, label_i_len = b[0], b[1], b[2], b[3] - - if has_feat: - feat_i_len = feat_i_len.item() - if feat_i_len < max_feat_len: - pad = (0, max_feat_len - feat_i_len) - feat_i = torch.nn.functional.pad(feat_i, pad, value=feat_pad_val) - features.append(feat_i) - - label_i_len = label_i_len.item() - if label_i_len < max_labels_len: - pad = (0, max_labels_len - label_i_len) - label_i = torch.nn.functional.pad(label_i, pad, value=label_pad_id) - labels.append(label_i) - - if has_feat: - features = torch.stack(features) - feature_lengths = torch.stack(feat_lengths) - else: - features, feat_lengths = None, None - labels = torch.stack(labels) - labels_lengths = torch.stack(labels_lengths) - - if sample_ids is None: - return features, feature_lengths, labels, labels_lengths - else: - sample_ids = torch.tensor(sample_ids, dtype=torch.int32) - return features, feature_lengths, labels, labels_lengths, sample_ids - - -def _vad_feature_segment_collate_fn(batch, window_length_in_sec, shift_length_in_sec, frame_unit_in_sec): - """collate batch of audio features, features len, tokens, tokens len - Args: - batch (Optional[FloatTensor], Optional[LongTensor], LongTensor, - LongTensor): A tuple of tuples of signal, signal lengths, - encoded tokens, and encoded tokens length. This collate func - assumes the signals are 1d torch tensors (i.e. mono audio). - batch size equals to 1. - """ - slice_length = int(window_length_in_sec / frame_unit_in_sec) - audio_features, feat_lengths, _, tokens_lengths = zip(*batch) - - slice_length = int(min(slice_length, max(feat_lengths))) - shift = int(shift_length_in_sec / frame_unit_in_sec) - has_audio = feat_lengths[0] is not None - - f_dim = audio_features[0].shape[0] - audio_features, num_slices, tokens, feat_lengths = [], [], [], [] - append_len_start = torch.div(slice_length, 2, rounding_mode='trunc') - append_len_end = slice_length - torch.div(slice_length, 2, rounding_mode='trunc') - for feat_i, feat_i_len, tokens_i, _ in batch: - start = torch.zeros(f_dim, append_len_start) - end = torch.zeros(f_dim, append_len_end) - feat_i = torch.cat((start, feat_i, end), dim=1) - feat_i_len += slice_length - - if has_audio: - slices = max(1, torch.div(feat_i_len - slice_length, shift, rounding_mode='trunc')) - - for slice_id in range(slices): - start_idx = slice_id * shift - end_idx = start_idx + slice_length - feat_slice = feat_i[:, start_idx:end_idx] - audio_features.append(feat_slice) - - num_slices.append(slices) - tokens.extend([tokens_i] * slices) - feat_lengths.extend([slice_length] * slices) - - if has_audio: - audio_features = torch.stack(audio_features) - feat_lengths = torch.tensor(feat_lengths) - else: - audio_features, feat_lengths = None, None - - tokens = torch.stack(tokens) - tokens_lengths = torch.tensor(num_slices) - return audio_features, feat_lengths, tokens, tokens_lengths - - -class _FeatureSeqSpeakerLabelDataset(Dataset): - """ - Dataset that loads tensors via a json file containing paths to feature files, sequences of labels. - Each new line is a different sample. Example below: - and their target labels. JSON files should be of the following format: - {"feature_filepath": "/path/to/feature_0.p", "seq_label": speakerA speakerB SpeakerA ....} \ - ... - {"feature_filepath": "/path/to/feature_n.p", "seq_label": target_seq_label_n} - target_seq_label_n is the string of sequence of speaker label, separated by space. - - Args: - manifest_filepath (str): Dataset parameter. Path to JSON containing data. - labels (Optional[list]): Dataset parameter. List of unique labels collected from all samples. - feature_loader : Dataset parameter. Feature loader to load (external) feature. - """ - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - """Returns definitions of module output ports. - """ - # TODO output type for external features - output_types = { - 'external_feat': NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), - 'feat_length': NeuralType(tuple('B'), LengthsType()), - } - - if self.is_speaker_emb: - output_types.update( - { - 'embs': NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), - 'embs_length': NeuralType(tuple('B'), LengthsType()), - 'label': NeuralType(('B', 'T'), LabelsType()), - 'label_length': NeuralType(tuple('B'), LengthsType()), - } - ) - else: - output_types.update( - {'label': NeuralType(('B', 'T'), LabelsType()), 'label_length': NeuralType(tuple('B'), LengthsType()),} - ) - - return output_types - - def __init__( - self, *, manifest_filepath: str, labels: List[str], feature_loader, is_speaker_emb: bool = False, - ): - super().__init__() - self.collection = collections.ASRFeatureSequenceLabel(manifests_files=manifest_filepath.split(','),) - - self.feature_loader = feature_loader - self.labels = labels if labels else self.collection.uniq_labels - self.is_speaker_emb = is_speaker_emb - - self.label2id, self.id2label = {}, {} - for label_id, label in enumerate(self.labels): - self.label2id[label] = label_id - self.id2label[label_id] = label - - for idx in range(len(self.labels[:5])): - logging.debug(" label id {} and its mapped label {}".format(idx, self.id2label[idx])) - - def __len__(self): - return len(self.collection) - - def __getitem__(self, index): - sample = self.collection[index] - - features = self.feature_loader.process(sample.feature_file) - f, fl = features, torch.tensor(features.shape[0]).long() - - t = torch.tensor(sample.seq_label).float() - tl = torch.tensor(len(sample.seq_label)).long() - - return f, fl, t, tl - - -class FeatureToSeqSpeakerLabelDataset(_FeatureSeqSpeakerLabelDataset): - """ - Dataset that loads tensors via a json file containing paths to feature - files and sequence of speakers. Each new line is a - different sample. Example below: - {"feature_filepath": "/path/to/feature_0.p", "seq_label": speakerA speakerB SpeakerA ....} \ - ... - {"feature_filepath": "/path/to/feature_n.p", "seq_label": target_seq_label_n} - target_seq_label_n is the string of sequence of speaker label, separated by space. - - Args: - manifest_filepath (str): Path to manifest json as described above. Canbe comma-separated paths. - labels (Optional[list]): String containing all the possible labels to map to - if None then automatically picks from ASRFeatureSequenceLabel collection. - feature_loader, Feature load to loader (external) feature. - - """ - - def _collate_fn(self, batch): - return _feature_collate_fn(batch) - - -class FeatureToLabelDataset(Dataset): - """ - Dataset that loads tensors via a json file containing paths to feature files and their labels. - Each new line is a different sample. Example below: - and their target labels. JSON files should be of the following format: - {"feature_filepath": "/path/to/audio_feature.pt", "label": "1"} - ... - {"feature_filepath": "/path/to/audio_feature.pt", "label": "0"} - Args: - manifest_filepath (str): Path to JSON containing data. - labels (Optional[list]): List of unique labels collected from all samples. - augmentor (Optional): feature augmentation - window_length_in_sec (float): Window length in seconds. - shift_length_in_sec (float): Shift length in seconds. - is_regression_task (bool): if True, the labels are treated as for a regression task. - cal_labels_occurrence (bool): if True, the labels occurrence will be calculated. - zero_spec_db_val (float): Value to replace non-speech signals in log-melspectrogram. - min_duration (float): Minimum duration of the audio file in seconds. - max_duration (float): Maximum duration of the audio file in seconds. - """ - - ZERO_LEVEL_SPEC_DB_VAL = -16.635 # Log-Melspectrogram value for zero signal - FRAME_UNIT_TIME_SECS = 0.01 - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - """Returns definitions of module output ports. - """ - output_types = { - 'audio_feat': NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), - 'feat_length': NeuralType(tuple('B'), LengthsType()), - 'labels': NeuralType(('B'), LabelsType()), - 'labels_length': NeuralType(tuple('B'), LengthsType()), - } - - return output_types - - def __init__( - self, - *, - manifest_filepath: str, - labels: List[str] = None, - augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None, - window_length_in_sec: float = 0.63, - shift_length_in_sec: float = 0.01, - is_regression_task: bool = False, - cal_labels_occurrence: Optional[bool] = False, - zero_spec_db_val: float = -16.635, - min_duration: Optional[float] = None, - max_duration: Optional[float] = None, - ): - super().__init__() - self.window_length_in_sec = window_length_in_sec - self.shift_length_in_sec = shift_length_in_sec - self.zero_spec_db_val = zero_spec_db_val - - if isinstance(manifest_filepath, str): - manifest_filepath = manifest_filepath.split(',') - - self.collection = collections.ASRFeatureLabel( - manifests_files=manifest_filepath, - is_regression_task=is_regression_task, - cal_labels_occurrence=cal_labels_occurrence, - min_duration=min_duration, - max_duration=max_duration, - ) - - self.feature_loader = ExternalFeatureLoader(augmentor=augmentor) - self.labels = labels if labels else self.collection.uniq_labels - - self.is_regression_task = is_regression_task - - if not is_regression_task: - self.labels = labels if labels else self.collection.uniq_labels - self.num_classes = len(self.labels) if self.labels is not None else 1 - self.label2id, self.id2label = {}, {} - self.id2occurrence, self.labels_occurrence = {}, [] - - for label_id, label in enumerate(self.labels): - self.label2id[label] = label_id - self.id2label[label_id] = label - if cal_labels_occurrence: - self.id2occurrence[label_id] = self.collection.labels_occurrence[label] - - if cal_labels_occurrence: - self.labels_occurrence = [self.id2occurrence[k] for k in sorted(self.id2occurrence)] - - for idx in range(len(self.labels[:5])): - logging.debug(" label id {} and its mapped label {}".format(idx, self.id2label[idx])) - else: - self.labels = [] - self.num_classes = 1 - - def __len__(self): - return len(self.collection) - - def __getitem__(self, index): - sample = self.collection[index] - - features = self.feature_loader.process(sample.feature_file) - f, fl = features, torch.tensor(features.shape[1]).long() - - t = torch.tensor(self.label2id[sample.label]) - tl = torch.tensor(1).long() - - return f, fl, t, tl - - def _collate_fn(self, batch): - return _audio_feature_collate_fn(batch, self.zero_spec_db_val, 0) - - def _vad_segment_collate_fn(self, batch): - return _vad_feature_segment_collate_fn( - batch, self.window_length_in_sec, self.shift_length_in_sec, self.FRAME_UNIT_TIME_SECS - ) - - -class FeatureToMultiLabelDataset(Dataset): - """ - Dataset that loads tensors via a json file containing paths to feature files and their labels. - Each new line is a different sample. Example below: - and their target labels. JSON files should be of the following format: - {"feature_filepath": "/path/to/audio_feature.pt", "label": "1 1 0 0 1"} - ... - {"feature_filepath": "/path/to/audio_feature.pt", "label": "0 1 0 0"} - Args: - manifest_filepath (str): Path to JSON containing data. - labels (Optional[list]): List of unique labels collected from all samples. - augmentor (Optional): feature augmentation - delimiter (str): delimiter to split the labels. - is_regression_task (bool): if True, the labels are treated as for a regression task. - cal_labels_occurrence (bool): if True, the labels occurrence will be calculated. - zero_spec_db_val (float): Value to replace non-speech signals in log-melspectrogram. - min_duration (float): Minimum duration of the audio file in seconds. - max_duration (float): Maximum duration of the audio file in seconds. - """ - - ZERO_LEVEL_SPEC_DB_VAL = -16.635 # Log-Melspectrogram value for zero signal - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - """Returns definitions of module output ports. - """ - output_types = { - 'audio_feat': NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), - 'feat_length': NeuralType(tuple('B'), LengthsType()), - 'labels': NeuralType(('B', 'T'), LabelsType()), - 'labels_length': NeuralType(tuple('B'), LengthsType()), - } - - return output_types - - def __init__( - self, - *, - manifest_filepath: str, - labels: List[str] = None, - augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None, - delimiter: Optional[str] = None, - is_regression_task: bool = False, - cal_labels_occurrence: Optional[bool] = False, - zero_spec_db_val: float = -16.635, - min_duration: Optional[float] = None, - max_duration: Optional[float] = None, - ): - super().__init__() - self.delimiter = delimiter - self.zero_spec_db_val = zero_spec_db_val - - if isinstance(manifest_filepath, str): - manifest_filepath = manifest_filepath.split(',') - - self.collection = collections.ASRFeatureLabel( - manifests_files=manifest_filepath, - is_regression_task=is_regression_task, - cal_labels_occurrence=cal_labels_occurrence, - delimiter=delimiter, - min_duration=min_duration, - max_duration=max_duration, - ) - - self.is_regression_task = is_regression_task - self.feature_loader = ExternalFeatureLoader(augmentor=augmentor) - self.labels = labels if labels else self.collection.uniq_labels - - self.label2id, self.id2label = {}, {} - if not is_regression_task: - self.labels = labels if labels else self._get_label_set() - self.num_classes = len(self.labels) if self.labels is not None else 1 - self.label2id, self.id2label = {}, {} - for label_id, label in enumerate(self.labels): - self.label2id[label] = label_id - self.id2label[label_id] = label - if cal_labels_occurrence: - self.id2occurrence[label_id] = self.collection.labels_occurrence[label] - self.labels_occurrence.append(self.id2occurrence[label_id]) - - for idx in range(len(self.labels[:5])): - logging.debug(" label id {} and its mapped label {}".format(idx, self.id2label[idx])) - else: - self.labels = [] - self.num_classes = 1 - - def _get_label_set(self): - labels = [] - for sample in self.collection: - label_str = sample.label - if label_str: - label_str_list = label_str.split(self.delimiter) if self.delimiter else label_str.split() - labels.extend(label_str_list) - return sorted(set(labels)) - - def _label_str_to_tensor(self, label_str: str): - labels = label_str.split(self.delimiter) if self.delimiter else label_str.split() - - if self.is_regression_task: - labels = [float(s) for s in labels] - labels = torch.tensor(labels).float() - else: - labels = [self.label2id[s] for s in labels] - labels = torch.tensor(labels).long() - return labels - - def __len__(self): - return len(self.collection) - - def __getitem__(self, index): - sample = self.collection[index] - - features = self.feature_loader.process(sample.feature_file) - f, fl = features, torch.tensor(features.shape[1]).long() - - t = self._label_str_to_tensor(sample.label) - tl = torch.tensor(t.size(0)).long() - - return f, fl, t, tl - - def _collate_fn(self, batch): - return _audio_feature_collate_fn(batch, self.zero_spec_db_val, 0) diff --git a/nemo/collections/asr/data/feature_to_label_dataset.py b/nemo/collections/asr/data/feature_to_label_dataset.py deleted file mode 100644 index 08803f43ce8d8fc65e69afb785ecdc2290b267ab..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/data/feature_to_label_dataset.py +++ /dev/null @@ -1,68 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -from typing import Optional - -from nemo.collections.asr.data import feature_to_label - - -def get_feature_seq_speakerlabel_dataset( - feature_loader, config: dict -) -> feature_to_label.FeatureToSeqSpeakerLabelDataset: - """ - Instantiates a FeatureSeqSpeakerLabelDataset. - Args: - config: Config of the FeatureToSeqSpeakerLabelDataset. - - Returns: - An instance of FeatureToSeqSpeakerLabelDataset. - """ - dataset = feature_to_label.FeatureToSeqSpeakerLabelDataset( - manifest_filepath=config['manifest_filepath'], labels=config['labels'], feature_loader=feature_loader, - ) - return dataset - - -def get_feature_label_dataset( - config: dict, augmentor: Optional['FeatureAugmentor'] = None -) -> feature_to_label.FeatureToLabelDataset: - dataset = feature_to_label.FeatureToLabelDataset( - manifest_filepath=config['manifest_filepath'], - labels=config['labels'], - augmentor=augmentor, - window_length_in_sec=config.get("window_length_in_sec", 0.63), - shift_length_in_sec=config.get("shift_length_in_sec", 0.08), - is_regression_task=config.get("is_regression_task", False), - cal_labels_occurrence=config.get("cal_labels_occurrence", False), - zero_spec_db_val=config.get("zero_spec_db_val", -16.635), - max_duration=config.get('max_duration', None), - min_duration=config.get('min_duration', None), - ) - return dataset - - -def get_feature_multi_label_dataset( - config: dict, augmentor: Optional['FeatureAugmentor'] = None -) -> feature_to_label.FeatureToMultiLabelDataset: - dataset = feature_to_label.FeatureToMultiLabelDataset( - manifest_filepath=config['manifest_filepath'], - labels=config['labels'], - augmentor=augmentor, - delimiter=config.get('delimiter', None), - is_regression_task=config.get("is_regression_task", False), - cal_labels_occurrence=config.get("cal_labels_occurrence", False), - zero_spec_db_val=config.get("zero_spec_db_val", -16.635), - max_duration=config.get('max_duration', None), - min_duration=config.get('min_duration', None), - ) - return dataset diff --git a/nemo/collections/asr/data/feature_to_text.py b/nemo/collections/asr/data/feature_to_text.py deleted file mode 100644 index b0b524d374f17baea9a1e36be5c9a0d60fd58a64..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/data/feature_to_text.py +++ /dev/null @@ -1,487 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import Callable, Dict, List, Optional, Tuple, Union - -import torch - -from nemo.collections.asr.data.feature_to_label import _audio_feature_collate_fn -from nemo.collections.asr.parts.preprocessing.feature_loader import ExternalFeatureLoader -from nemo.collections.asr.parts.preprocessing.features import normalize_batch -from nemo.collections.asr.parts.preprocessing.segment import ChannelSelectorType -from nemo.collections.asr.parts.utils.vad_utils import load_speech_segments_from_rttm -from nemo.collections.common import tokenizers -from nemo.collections.common.parts.preprocessing import collections, parsers -from nemo.core.classes import Dataset -from nemo.core.neural_types import AcousticEncodedRepresentation, LabelsType, LengthsType, NeuralType - - -class ASRFeatureManifestProcessor: - def __init__( - self, - manifest_filepath: str, - parser: Union[str, Callable], - max_duration: Optional[float] = None, - min_duration: Optional[float] = None, - max_utts: int = 0, - bos_id: Optional[int] = None, - eos_id: Optional[int] = None, - pad_id: int = 0, - index_by_file_id: bool = False, - ): - self.parser = parser - self.collection = collections.ASRFeatureText( - manifests_files=manifest_filepath, - parser=parser, - min_duration=min_duration, - max_duration=max_duration, - max_number=max_utts, - index_by_file_id=index_by_file_id, - ) - - self.eos_id = eos_id - self.bos_id = bos_id - self.pad_id = pad_id - - def process_text_by_id(self, index: int) -> Tuple[List[int], int]: - sample = self.collection[index] - return self.process_text_by_sample(sample) - - def process_text_by_file_id(self, file_id: str) -> Tuple[List[int], int]: - manifest_idx = self.collection.mapping[file_id][0] - sample = self.collection[manifest_idx] - return self.process_text_by_sample(sample) - - def process_text_by_sample(self, sample: collections.ASRAudioText.OUTPUT_TYPE) -> Tuple[List[int], int]: - t, tl = sample.text_tokens, len(sample.text_tokens) - - if self.bos_id is not None: - t = [self.bos_id] + t - tl += 1 - if self.eos_id is not None: - t = t + [self.eos_id] - tl += 1 - - return t, tl - - -class _FeatureTextDataset(Dataset): - """ - Dataset that loads tensors via a json file containing paths to audio feature files, transcripts, - durations (in seconds) and optional RTTM files. Each new line is a different sample. Example below: - {"feature_filepath": "/path/to/audio_feature.pt", "text_filepath": "/path/to/audio.txt", - "rttm_filepath": "/path/to/audio_rttm.rttm", "duration": 23.147} - ... - {"feature_filepath": "/path/to/audio_feature.pt", "text": "the transcription", "offset": 301.75, "duration": 0.82, "utt": - "utterance_id", "ctm_utt": "en_4156", "side": "A"} - Args: - manifest_filepath (str): Path to manifest json as described above. Can be comma-separated paths. - parser: Str for a language specific preprocessor or a callable. - normalize (bool): whether and where to normalize feature, must be one of [None, "post_norm", "pre_norm"] - normalize_type (Union[str, dict]): how to normalize feature, see `nemo.collections.asr.parts.preprocessing.features.normalize_batch` - use_rttm (bool): whether to use RTTM files if there is any, default to False - rttm_mode (str): how to use RTTM files, must be one of ['mask', 'drop'], default to 'mask' - feat_min_len (int): minimum length of feature when rttm_mode=deop, default to 4. - feat_mask_val (Optional[float]): value used to mask features with RTTM files, default to None to use zero mel-spectralgram - frame_unit_time_secs (float): time in seconds for each frame - sample_rate (int): Sample rate to resample loaded audio to - int_values (bool): If true, load samples as 32-bit integers. Defauts to False. - augmentor (nemo.collections.asr.parts.perturb.AudioAugmentor): An AudioAugmentor object used to augment loaded audio - max_duration (float): If audio exceeds this length, do not include in dataset - min_duration (float): If audio is less than this length, do not include in dataset - max_utts (int): Limit number of utterances - trim (bool): whether or not to trim silence. Defaults to False - bos_id (int): Id of beginning of sequence symbol to append if not None - eos_id (int): Id of end of sequence symbol to append if not None - pad_id (int): Id of pad symbol. Defaults to 0 - return_sample_id (bool): whether to return the sample_id as a part of each sample - 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. - """ - - ZERO_LEVEL_SPEC_DB_VAL = -16.635 # Log-Melspectrogram value for zero signal - NORM_MODES = ["pre_norm", "post_norm"] - RTTM_MODES = ["mask", "drop"] - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - """Returns definitions of module output ports.""" - return { - 'features': NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), - 'feature_length': NeuralType(tuple('B'), LengthsType()), - 'transcripts': NeuralType(('B', 'T'), LabelsType()), - 'transcript_length': NeuralType(tuple('B'), LengthsType()), - 'sample_id': NeuralType(tuple('B'), LengthsType(), optional=True), - } - - def __init__( - self, - manifest_filepath: str, - parser: Union[str, Callable], - normalize: Optional[str] = "post_norm", - normalize_type: Union[str, dict] = "per_feature", - use_rttm: bool = False, - rttm_mode: str = "mask", - feat_min_len: int = 4, - feat_mask_val: Optional[float] = None, - frame_unit_time_secs: float = 0.01, - sample_rate: Optional[int] = 16000, - augmentor: 'nemo.collections.asr.parts.perturb.FeatureAugmentor' = None, - max_duration: Optional[int] = None, - min_duration: Optional[int] = None, - max_utts: int = 0, - trim: bool = False, - bos_id: Optional[int] = None, - eos_id: Optional[int] = None, - pad_id: int = 0, - return_sample_id: bool = False, - channel_selector: Optional[ChannelSelectorType] = None, - ): - if type(manifest_filepath) == str: - manifest_filepath = manifest_filepath.split(",") - - self.sample_rate = sample_rate - self.normalize = normalize - self.normalize_type = normalize_type - self.use_rttm = use_rttm - self.rttm_mode = rttm_mode - if self.use_rttm and self.rttm_mode not in self.RTTM_MODES: - raise ValueError(f"`rttm_mode` must be one of {self.RTTM_MODES}, got `{rttm_mode}` instead") - - self.feat_min_len = feat_min_len - if feat_mask_val is not None: - self.feat_mask_val = feat_mask_val - elif normalize == "pre_norm": - self.feat_mask_val = 0.0 # similar to SpectralAugmentation - else: - self.feat_mask_val = self.ZERO_LEVEL_SPEC_DB_VAL - - if normalize is not None and normalize not in self.NORM_MODES: - raise ValueError(f"`normalize` must be one of {self.NORM_MODES}, got `{normalize}` instead") - - self.frame_unit_time_secs = frame_unit_time_secs - - self.manifest_processor = ASRFeatureManifestProcessor( - manifest_filepath=manifest_filepath, - parser=parser, - max_duration=max_duration, - min_duration=min_duration, - max_utts=max_utts, - bos_id=bos_id, - eos_id=eos_id, - pad_id=pad_id, - ) - self.featurizer = ExternalFeatureLoader(augmentor=augmentor) - self.trim = trim - self.return_sample_id = return_sample_id - self.channel_selector = channel_selector - - def get_manifest_sample(self, sample_id): - return self.manifest_processor.collection[sample_id] - - def __getitem__(self, index): - sample = self.manifest_processor.collection[index] - offset = sample.offset - - if offset is None: - offset = 0 - - features = self.featurizer.process(sample.feature_file) - - f, fl = features, torch.tensor(features.shape[1]).long() - - t, tl = self.manifest_processor.process_text_by_sample(sample=sample) - - # Feature normalization - if self.normalize is None: - if self.use_rttm and sample.rttm_file: - f = self.process_features_with_rttm(f, offset, sample.rttm_file, self.feat_mask_val) - elif self.normalize == "post_norm": - # (Optional) Masking based on RTTM file - if self.use_rttm and sample.rttm_file: - f = self.process_features_with_rttm(f, offset, sample.rttm_file, self.feat_mask_val) - - f = self.normalize_feature(f) - else: # pre-norm - f = self.normalize_feature(f) - # (Optional) Masking based on RTTM file - if self.use_rttm and sample.rttm_file: - f = self.process_features_with_rttm(f, offset, sample.rttm_file, self.feat_mask_val) - - if self.return_sample_id: - output = f, fl, torch.tensor(t).long(), torch.tensor(tl).long(), index - else: - output = f, fl, torch.tensor(t).long(), torch.tensor(tl).long() - - return output - - def process_features_with_rttm(self, features, offset, rttm_file, mask_val): - segments = load_speech_segments_from_rttm(rttm_file) - new_features = features.clone() - sid, fid = 0, 0 - for i in range(features.size(1)): - t = offset + i * self.frame_unit_time_secs - while sid < len(segments) - 1 and segments[sid][1] < t: - sid += 1 - if segments[sid][1] == 0 or t < segments[sid][0] or t > segments[sid][1]: - # not in speech segment - if self.rttm_mode == "drop": - # drop the frame - continue - else: - # mask the frame with specified value - new_features[:, i] = mask_val - fid += 1 - else: - # in speech segment - new_features[:, fid] = features[:, i] - fid += 1 - - if fid < self.feat_min_len and self.rttm_mode == "drop": - new_features[:, : self.feat_min_len] = mask_val - return new_features[:, : self.feat_min_len] - return new_features[:, :fid] - - def __len__(self): - return len(self.manifest_processor.collection) - - def _collate_fn(self, batch): - return _audio_feature_collate_fn( - batch, feat_pad_val=self.feat_mask_val, label_pad_id=self.manifest_processor.pad_id - ) - - def normalize_feature(self, feat): - """ - Args: - feat: feature tensor of shape [M, T] - """ - feat = feat.unsqueeze(0) # add batch dim - feat, _, _ = normalize_batch(feat, torch.tensor([feat.size(-1)]), self.normalize_type) - return feat.squeeze(0) # delete batch dim - - -class FeatureToCharDataset(_FeatureTextDataset): - """ - Dataset that loads tensors via a json file containing paths to audio feature - files, transcripts, durations (in seconds) and optional RTTM files. Each new line is a - different sample. Example below: - {"feature_filepath": "/path/to/audio_feature.pt", "text_filepath": - "/path/to/audio.txt", "duration": 23.147, "rttm_filepath": "/path/to/audio_rttm.rttm",} - ... - {"feature_filepath": "/path/to/audio_feature.pt", "text": "the - transcription", "offset": 301.75, "duration": 0.82, "utt": - "utterance_id", "ctm_utt": "en_4156", "side": "A"} - - Args: - manifest_filepath (str): Path to manifest json as described above. Can - be comma-separated paths. - labels (str): String containing all the possible characters to map to - normalize (str): how to normalize feature, must be one of [None, "post_norm", "pre_norm"] - normalize_type (Union[str, dict]): how to normalize feature, see `nemo.collections.asr.parts.preprocessing.features.normalize_batch` - use_rttm (bool): whether to use RTTM files if there is any, default to False - rttm_mode (str): how to use RTTM files, must be one of ['mask', 'drop'], default to 'mask' - feat_min_len (int): minimum length of feature, default to 4 - feat_mask_val (Optional[float]): value used to mask features with RTTM files, default to None to use zero mel-spectralgram - frame_unit_time_secs: time in seconds for each frame - sample_rate (int): Sample rate to resample loaded audio to - int_values (bool): If true, load samples as 32-bit integers. Defauts to False. - augmentor (nemo.collections.asr.parts.perturb.AudioAugmentor): An AudioAugmentor - object used to augment loaded audio - max_duration: If audio exceeds this length, do not include in dataset - min_duration: If audio is less than this length, do not include - in dataset - max_utts: Limit number of utterances - blank_index: blank character index, default = -1 - unk_index: unk_character index, default = -1 - bos_id: Id of beginning of sequence symbol to append if not None - eos_id: Id of end of sequence symbol to append if not None - return_sample_id (bool): whether to return the sample_id as a part of each sample - 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. - """ - - def __init__( - self, - manifest_filepath: str, - labels: Union[str, List[str]], - normalize: Optional[str] = "post_norm", - normalize_type: Union[str, dict] = "per_feature", - use_rttm: bool = False, - rttm_mode: str = "mask", - feat_min_len: int = 4, - feat_mask_val: Optional[float] = None, - frame_unit_time_secs: float = 0.01, - sample_rate: Optional[int] = 16000, - augmentor: 'nemo.collections.asr.parts.perturb.FeatureAugmentor' = None, - max_duration: Optional[int] = None, - min_duration: Optional[int] = None, - max_utts: int = 0, - blank_index: int = -1, - unk_index: int = -1, - trim: bool = False, - bos_id: Optional[int] = None, - eos_id: Optional[int] = None, - pad_id: int = 0, - parser: Union[str, Callable] = 'en', - return_sample_id: bool = False, - channel_selector: Optional[ChannelSelectorType] = None, - ): - self.labels = labels - - parser = parsers.make_parser( - labels=labels, name=parser, unk_id=unk_index, blank_id=blank_index, do_normalize=normalize - ) - - super().__init__( - manifest_filepath=manifest_filepath, - parser=parser, - normalize=normalize, - normalize_type=normalize_type, - use_rttm=use_rttm, - rttm_mode=rttm_mode, - feat_min_len=feat_min_len, - feat_mask_val=feat_mask_val, - frame_unit_time_secs=frame_unit_time_secs, - sample_rate=sample_rate, - augmentor=augmentor, - max_duration=max_duration, - min_duration=min_duration, - max_utts=max_utts, - trim=trim, - bos_id=bos_id, - eos_id=eos_id, - pad_id=pad_id, - return_sample_id=return_sample_id, - channel_selector=channel_selector, - ) - - -class FeatureToBPEDataset(_FeatureTextDataset): - """ - Dataset that loads tensors via a json file containing paths to audio feature - files, transcripts, durations (in seconds) and optional RTTM files. Each new line is a different sample. - Example below: - {"audio_filepath": "/path/to/audio.wav", "text_filepath": - "/path/to/audio.txt", "duration": 23.147, "rttm_filepath": "/path/to/audio_rttm.rttm",} - ... - {"audio_filepath": "/path/to/audio.wav", "text": "the - transcription", "offset": 301.75, "duration": 0.82, "utt": - "utterance_id", "ctm_utt": "en_4156", "side": "A"} - - In practice, the dataset and manifest used for character encoding and byte pair encoding - are exactly the same. The only difference lies in how the dataset tokenizes the text in - the manifest. - - Args: - manifest_filepath (str): Path to manifest json as described above. Can - be comma-separated paths. - tokenizer: A subclass of the Tokenizer wrapper found in the common collection, - nemo.collections.common.tokenizers.TokenizerSpec. ASR Models support a subset of - all available tokenizers. - normalize (str): how to normalize feature, must be one of [None, "post_norm", "pre_norm"] - normalize_type (Union[str, dict]): how to normalize feature, see `nemo.collections.asr.parts.preprocessing.features.normalize_batch` - use_rttm (bool): whether to use RTTM files if there is any, default to False - rttm_mode (str): how to use RTTM files, must be one of ['mask', 'drop'], default to 'mask' - feat_min_len (int): minimum length of feature, default to 4 - feat_mask_val (Optional[float]): value used to mask features with RTTM files, default to None to use zero mel-spectralgram - frame_unit_time_secs: time in seconds for each frame - sample_rate (int): Sample rate to resample loaded audio to - int_values (bool): If true, load samples as 32-bit integers. Defauts to False. - augmentor (nemo.collections.asr.parts.perturb.AudioAugmentor): An AudioAugmentor - object used to augment loaded audio - max_duration: If audio exceeds this length, do not include in dataset - min_duration: If audio is less than this length, do not include - in dataset - max_utts: Limit number of utterances - trim: Whether to trim silence segments - use_start_end_token: Boolean which dictates whether to add [BOS] and [EOS] - tokens to beginning and ending of speech respectively. - return_sample_id (bool): whether to return the sample_id as a part of each sample - 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. - """ - - def __init__( - self, - manifest_filepath: str, - tokenizer: 'nemo.collections.common.tokenizers.TokenizerSpec', - normalize: Optional[str] = "post_norm", - normalize_type: Union[str, dict] = "per_feature", - use_rttm: bool = False, - rttm_mode: str = "mask", - feat_min_len: int = 4, - feat_mask_val: Optional[float] = None, - frame_unit_time_secs: float = 0.01, - sample_rate: Optional[int] = 16000, - augmentor: 'nemo.collections.asr.parts.perturb.FeatureAugmentor' = None, - max_duration: Optional[int] = None, - min_duration: Optional[int] = None, - max_utts: int = 0, - use_start_end_token: bool = True, - trim: bool = False, - return_sample_id: bool = False, - channel_selector: Optional[ChannelSelectorType] = None, - ): - if use_start_end_token and hasattr(tokenizer, "bos_id") and tokenizer.bos_id > 0: - bos_id = tokenizer.bos_id - else: - bos_id = None - - if use_start_end_token and hasattr(tokenizer, "eos_id") and tokenizer.eos_id > 0: - eos_id = tokenizer.eos_id - else: - eos_id = None - - if hasattr(tokenizer, "pad_id") and tokenizer.pad_id > 0: - pad_id = tokenizer.pad_id - else: - pad_id = 0 - - class TokenizerWrapper: - def __init__(self, tokenizer): - if isinstance(tokenizer, tokenizers.aggregate_tokenizer.AggregateTokenizer): - self.is_aggregate = True - else: - self.is_aggregate = False - self._tokenizer = tokenizer - - def __call__(self, *args): - if isinstance(args[0], List) and self.is_aggregate: - t = [] - for span in args[0]: - t.extend(self._tokenizer.text_to_ids(span['str'], span['lang'])) - return t - - t = self._tokenizer.text_to_ids(*args) - return t - - super().__init__( - manifest_filepath=manifest_filepath, - parser=TokenizerWrapper(tokenizer), - normalize=normalize, - normalize_type=normalize_type, - use_rttm=use_rttm, - rttm_mode=rttm_mode, - feat_min_len=feat_min_len, - feat_mask_val=feat_mask_val, - frame_unit_time_secs=frame_unit_time_secs, - sample_rate=sample_rate, - augmentor=augmentor, - max_duration=max_duration, - min_duration=min_duration, - max_utts=max_utts, - trim=trim, - bos_id=bos_id, - eos_id=eos_id, - pad_id=pad_id, - return_sample_id=return_sample_id, - channel_selector=channel_selector, - ) diff --git a/nemo/collections/asr/data/feature_to_text_dataset.py b/nemo/collections/asr/data/feature_to_text_dataset.py deleted file mode 100644 index 6bc03bc0b33df3e08f16e383d8dc522c68563bce..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/data/feature_to_text_dataset.py +++ /dev/null @@ -1,94 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import Optional - -from nemo.collections.asr.data.feature_to_text import FeatureToBPEDataset, FeatureToCharDataset -from nemo.utils import logging - - -def get_char_dataset(config: dict, augmentor: Optional['FeatureAugmentor'] = None) -> FeatureToCharDataset: - """ - Instantiates a Character Encoding based FeatureToCharDataset. - - Args: - config: Config of the FeatureToCharDataset. - augmentor: Optional AudioAugmentor object for augmentations on audio data. - - Returns: - An instance of FeatureToCharDataset. - """ - if 'labels' not in config: - logging.warning(f"dataset does not have explicitly defined labels") - - dataset = FeatureToCharDataset( - manifest_filepath=config['manifest_filepath'], - labels=config.get('labels', None), - normalize=config.get('normalize', 'post_norm'), - normalize_type=config.get('normalize_type', 'per_feature'), - use_rttm=config.get('use_rttm', False), - rttm_mode=config.get('rttm_mode', 'mask'), - feat_min_len=config.get('feat_min_len', 4), - feat_mask_val=config.get('feat_mask_val', None), - frame_unit_time_secs=config.get('frame_unit_time_secs', 0.01), - sample_rate=config.get('sample_rate', 16000), - augmentor=augmentor, - max_duration=config.get('max_duration', None), - min_duration=config.get('min_duration', None), - max_utts=config.get('max_utts', 0), - blank_index=config.get('blank_index', -1), - unk_index=config.get('unk_index', -1), - trim=config.get('trim_silence', False), - parser=config.get('parser', 'en'), - return_sample_id=config.get('return_sample_id', False), - channel_selector=config.get('channel_selector', None), - ) - return dataset - - -def get_bpe_dataset( - config: dict, tokenizer: 'TokenizerSpec', augmentor: Optional['FeatureAugmentor'] = None -) -> FeatureToBPEDataset: - """ - Instantiates a Byte Pair Encoding / Word Piece Encoding based FeatureoToBPEDataset. - - Args: - config: Config of the FeatureToBPEDataset. - tokenizer: An instance of a TokenizerSpec object. - augmentor: Optional FeatureAugmentor object for augmentations on audio features. - - Returns: - An instance of FeatureToBPEDataset. - """ - dataset = FeatureToBPEDataset( - manifest_filepath=config['manifest_filepath'], - tokenizer=tokenizer, - normalize=config.get('normalize', 'post_norm'), - normalize_type=config.get('normalize_type', 'per_feature'), - use_rttm=config.get('use_rttm', False), - rttm_mode=config.get('rttm_mode', 'mask'), - feat_min_len=config.get('feat_min_len', 4), - feat_mask_val=config.get('feat_mask_val', None), - frame_unit_time_secs=config.get('frame_unit_time_secs', 0.01), - sample_rate=config.get('sample_rate', 16000), - augmentor=augmentor, - max_duration=config.get('max_duration', None), - min_duration=config.get('min_duration', None), - max_utts=config.get('max_utts', 0), - trim=config.get('trim_silence', False), - use_start_end_token=config.get('use_start_end_token', True), - return_sample_id=config.get('return_sample_id', False), - channel_selector=config.get('channel_selector', None), - ) - return dataset diff --git a/nemo/collections/asr/data/huggingface/__init__.py b/nemo/collections/asr/data/huggingface/__init__.py deleted file mode 100644 index 4fc50543f1d247a021674eaea55ba5f4c224c56e..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/data/huggingface/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/asr/data/huggingface/hf_audio_to_text.py b/nemo/collections/asr/data/huggingface/hf_audio_to_text.py deleted file mode 100644 index da4aeb3f888c04ccbe4f1958d597904876eb103f..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/data/huggingface/hf_audio_to_text.py +++ /dev/null @@ -1,694 +0,0 @@ -# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import Callable, Dict, List, Optional, Tuple, Union - -import datasets as hf_datasets -import torch -from datasets import concatenate_datasets -from datasets.distributed import split_dataset_by_node -from omegaconf import DictConfig, ListConfig, open_dict - -from nemo.collections.asr.data.audio_to_text import _speech_collate_fn -from nemo.collections.asr.parts.preprocessing.perturb import AudioAugmentor -from nemo.collections.asr.parts.preprocessing.segment import AudioSegment, ChannelSelectorType -from nemo.collections.common import tokenizers -from nemo.collections.common.parts.preprocessing import parsers -from nemo.core.classes import Dataset, IterableDataset -from nemo.core.neural_types import AudioSignal, LabelsType, LengthsType, NeuralType -from nemo.utils import logging - - -class HFTextProcessor: - """ - Text processor for huggingface datasets, mimicing the behavior of - `nemo.collections.asr.data.audio_to_text.ASRManifestProcessor`. - Basic text cleaning is also supported. - Args: - parser: Str for a language specific preprocessor or a callable. - bos_id: BOS token id to add to the beginning of the transcript. - eos_id: EOS token id to add to the end of the transcript. - pad_id: PAD token id to pad transcripts to the same length. - normalize_text: If true, normalizes text in HFTextProcessor - symbols_to_keep: If not None, only keeps symbols in this list when normalizing text - """ - - def __init__( - self, - parser: Union[str, Callable], - bos_id: Optional[int] = None, - eos_id: Optional[int] = None, - pad_id: int = 0, - normalize_text: bool = False, - symbols_to_keep: Optional[str | List[str]] = None, - ): - self.parser = parser - self.eos_id = eos_id - self.bos_id = bos_id - self.pad_id = pad_id - self.normalize_text = normalize_text - self.symbols_to_keep = [x for x in symbols_to_keep] if symbols_to_keep is not None else [] - - def process_text(self, text: str, lang: Optional[str] = None) -> List[int]: - - if self.normalize_text: - text = text.lower() - # only keep alphanumeric characters, spaces and symbols defined in self.symbols_to_keep - text = ''.join([c for c in text if c.isalnum() or c.isspace() or c in self.symbols_to_keep]) - - if hasattr(self.parser, "is_aggregate") and self.parser.is_aggregate and isinstance(text, str): - if lang is not None: - text_tokens = self.parser(text, lang) - # for future use if want to add language bypass to audio_to_text classes - # elif hasattr(parser, "lang") and parser.lang is not None: - # text_tokens = parser(text, parser.lang) - else: - raise ValueError("lang required in manifest when using aggregate tokenizers") - else: - text_tokens = self.parser(text) - text_tokens_length = len(text_tokens) - if self.bos_id is not None: - text_tokens = [self.bos_id] + text_tokens - text_tokens_length += 1 - if self.eos_id is not None: - text_tokens = text_tokens + [self.eos_id] - text_tokens_length += 1 - return text_tokens, text_tokens_length - - -def get_nested_dict_value(dictionary: dict, key: str): - """ - the key should be a string of nested keys separated by `.`, e.g. `key1.key2.key3`, - then the returned value will be `dictionary[key1][key2][key3]` - """ - nested_keys = key.split(".") - result = dictionary - for k in nested_keys: - if k not in result: - raise KeyError( - f"Key `{key}` not found in [{result.keys()}], target is {nested_keys}, input is {dictionary}" - ) - result = result[k] - return result - - -class _HFAudioTextDataset(Dataset): - """ - A Dataset wrapper that loads from HuggingFace datasets and converts to NeMo compatible format. - Args: - audio_key: key to access audio data from the dataset - text_key: key to access text data from the dataset - sample_rate_key: key to access sample rate data from the dataset - hf_data_cfg: HuggingFace dataset config, all params in this config will be passed to `hf_datasets.load_dataset` - parser: Str for a language specific preprocessor or a callable. - augmentor: An instance of `nemo.collections.asr.parts.perturb.AudioAugmentor` to apply on audio. - trim: If true, trims silence using `nemo.collections.asr.parts.preprocessing.segment.AudioSegment` - bos_id: BOS token id to add to the beginning of the transcript. - eos_id: EOS token id to add to the end of the transcript. - pad_id: PAD token id to pad transcripts to the same length. - return_sample_id: If true, returns sample id from the dataset. - channel_selector: ChannelSelectorType, which channel(s) to use for audio. - normalize_db: Target RMS value for audio normalization. - ref_channel: Reference channel for normalization. - id_key: key to access sample id from the dataset - normalize_text: If true, normalizes text in HFTextProcessor - symbols_to_keep: If not None, only keeps symbols in this list when normalizing text - """ - - def __init__( - self, - audio_key: str, - text_key: str, - sample_rate_key: str, - hf_data_cfg: Union[DictConfig, ListConfig], - parser: Union[str, Callable], - sample_rate: int, - augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None, - trim: bool = False, - bos_id: Optional[int] = None, - eos_id: Optional[int] = None, - pad_id: int = 0, - return_sample_id: bool = False, - channel_selector: Optional[ChannelSelectorType] = None, - normalize_db: Optional[float] = None, - ref_channel: Optional[int] = None, - id_key: Optional[str] = None, - normalize_text: bool = False, - symbols_to_keep: Optional[str] = None, - ) -> None: - super().__init__() - self.audio_key = audio_key - self.text_key = text_key - self.sample_rate_key = sample_rate_key - self.id_key = id_key - self.sample_rate = sample_rate - self.augmentor = augmentor if augmentor is not None else AudioAugmentor() - self.trim = trim - self.return_sample_id = return_sample_id - self.channel_selector = channel_selector - self.normalize_db = normalize_db - self.ref_channel = ref_channel - - self.text_processor = HFTextProcessor(parser, bos_id, eos_id, pad_id, normalize_text, symbols_to_keep) - - data_config_list = [hf_data_cfg] if isinstance(hf_data_cfg, DictConfig) else hf_data_cfg - dataset_list = [] - for data_cfg in data_config_list: - with open_dict(data_cfg): - if "streaming" in data_cfg and data_cfg.streaming: - logging.warning( - "streaming must be False for random access dataset, but you use streaming=True. Forcing streaming=False" - ) - data_cfg.streaming = False - logging.info(f"Loading HuggingFace Dataset with cfg: {data_cfg}") - dataset_list.append(hf_datasets.load_dataset(**data_cfg)) - logging.info(f"Dataset loaded with {len(dataset_list[-1])} samples") - self.dataset = concatenate_datasets(dataset_list) - - logging.info(f"Total number of samples loaded: {len(self.dataset)}") - - def __len__(self): - return len(self.dataset) - - def __getitem__(self, index) -> Tuple: - item = self.dataset[index] - - audio_array = get_nested_dict_value(item, self.audio_key) - origin_sr = get_nested_dict_value(item, self.sample_rate_key) - audio_segment = AudioSegment( - samples=audio_array, - sample_rate=origin_sr, - target_sr=self.sample_rate, - trim=self.trim, - channel_selector=self.channel_selector, - normalize_db=self.normalize_db, - ref_channel=self.ref_channel, - ) - self.augmentor.perturb(audio_segment) - f = torch.tensor(audio_segment.samples, dtype=torch.float) - fl = torch.tensor(f.shape[0], dtype=torch.long) - - text = get_nested_dict_value(item, self.text_key) - t, tl = self.text_processor.process_text(text) - - index = get_nested_dict_value(item, self.id_key) if self.id_key else index - if self.return_sample_id: - output = f, fl, torch.tensor(t).long(), torch.tensor(tl).long(), index - else: - output = f, fl, torch.tensor(t).long(), torch.tensor(tl).long() - - return output - - def _collate_fn(self, batch): - return _speech_collate_fn(batch, pad_id=self.text_processor.pad_id) - - -class HFAudioToCharDataset(_HFAudioTextDataset): - """ - Wrapper class for loading HuggingFace dataset for a char-based ASR model - """ - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - """Returns definitions of module output ports.""" - return { - 'audio_signal': NeuralType(('B', 'T'), AudioSignal()), - 'a_sig_length': NeuralType(tuple('B'), LengthsType()), - 'transcripts': NeuralType(('B', 'T'), LabelsType()), - 'transcript_length': NeuralType(tuple('B'), LengthsType()), - 'sample_id': NeuralType(tuple('B'), LengthsType(), optional=True), - } - - def __init__( - self, - audio_key: str, - text_key: str, - sample_rate_key: str, - hf_data_cfg: DictConfig, - labels: List[str], - sample_rate: int, - augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None, - trim: bool = False, - bos_id: Optional[int] = None, - eos_id: Optional[int] = None, - pad_id: int = 0, - return_sample_id: bool = False, - channel_selector: Optional[ChannelSelectorType] = None, - normalize_db: Optional[float] = None, - ref_channel: Optional[int] = None, - parser: Union[str, Callable] = 'en', - blank_index: int = -1, - unk_index: int = -1, - normalize: bool = True, - id_key: Optional[str] = None, - normalize_text: bool = False, - symbols_to_keep: Optional[str] = None, - ): - self.labels = labels - - parser = parsers.make_parser( - labels=labels, name=parser, unk_id=unk_index, blank_id=blank_index, do_normalize=normalize - ) - - super().__init__( - audio_key=audio_key, - text_key=text_key, - sample_rate_key=sample_rate_key, - hf_data_cfg=hf_data_cfg, - parser=parser, - sample_rate=sample_rate, - augmentor=augmentor, - trim=trim, - bos_id=bos_id, - eos_id=eos_id, - pad_id=pad_id, - return_sample_id=return_sample_id, - channel_selector=channel_selector, - normalize_db=normalize_db, - ref_channel=ref_channel, - id_key=id_key, - normalize_text=normalize_text, - symbols_to_keep=symbols_to_keep, - ) - - -class HFAudioToBPEDataset(_HFAudioTextDataset): - """ - Wrapper class for loading a HuggingFace dataset for a BPE-based ASR model - """ - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - """Returns definitions of module output ports.""" - return { - 'audio_signal': NeuralType(('B', 'T'), AudioSignal()), - 'a_sig_length': NeuralType(tuple('B'), LengthsType()), - 'transcripts': NeuralType(('B', 'T'), LabelsType()), - 'transcript_length': NeuralType(tuple('B'), LengthsType()), - 'sample_id': NeuralType(tuple('B'), LengthsType(), optional=True), - } - - def __init__( - self, - audio_key: str, - text_key: str, - sample_rate_key: str, - hf_data_cfg: DictConfig, - tokenizer: 'nemo.collections.common.tokenizers.TokenizerSpec', - sample_rate: int, - augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None, - trim: bool = False, - return_sample_id: bool = False, - channel_selector: Optional[ChannelSelectorType] = None, - normalize_db: Optional[float] = None, - ref_channel: Optional[int] = None, - use_start_end_token: bool = True, - id_key: Optional[str] = None, - normalize_text: bool = False, - symbols_to_keep: Optional[str] = None, - ): - if use_start_end_token and hasattr(tokenizer, "bos_id") and tokenizer.bos_id > 0: - bos_id = tokenizer.bos_id - else: - bos_id = None - - if use_start_end_token and hasattr(tokenizer, "eos_id") and tokenizer.eos_id > 0: - eos_id = tokenizer.eos_id - else: - eos_id = None - - if hasattr(tokenizer, "pad_id") and tokenizer.pad_id > 0: - pad_id = tokenizer.pad_id - else: - pad_id = 0 - - class TokenizerWrapper: - def __init__(self, tokenizer): - if isinstance(tokenizer, tokenizers.aggregate_tokenizer.AggregateTokenizer): - self.is_aggregate = True - else: - self.is_aggregate = False - self._tokenizer = tokenizer - - def __call__(self, *args): - if isinstance(args[0], List) and self.is_aggregate: - t = [] - for span in args[0]: - t.extend(self._tokenizer.text_to_ids(span['str'], span['lang'])) - return t - - t = self._tokenizer.text_to_ids(*args) - return t - - super().__init__( - audio_key=audio_key, - text_key=text_key, - sample_rate_key=sample_rate_key, - hf_data_cfg=hf_data_cfg, - parser=TokenizerWrapper(tokenizer), - sample_rate=sample_rate, - augmentor=augmentor, - trim=trim, - bos_id=bos_id, - eos_id=eos_id, - pad_id=pad_id, - return_sample_id=return_sample_id, - channel_selector=channel_selector, - normalize_db=normalize_db, - ref_channel=ref_channel, - id_key=id_key, - normalize_text=normalize_text, - symbols_to_keep=symbols_to_keep, - ) - - -class _HFIterableAudioTextDataset(IterableDataset): - """ - Wrapper class for loading HuggingFace IterableDataset and converts to NeMo compatible format. - Args: - audio_key: key to access audio data from the dataset - text_key: key to access text data from the dataset - sample_rate_key: key to access sample rate data from the dataset - hf_data_cfg: HuggingFace dataset config, all params in this config will be passed to `hf_datasets.load_dataset` - parser: Str for a language specific preprocessor or a callable. - augmentor: An instance of `nemo.collections.asr.parts.perturb.AudioAugmentor` to apply on audio. - trim: If true, trims silence using `nemo.collections.asr.parts.preprocessing.segment.AudioSegment` - bos_id: BOS token id to add to the beginning of the transcript. - eos_id: EOS token id to add to the end of the transcript. - pad_id: PAD token id to pad transcripts to the same length. - return_sample_id: If true, returns sample id from the dataset. - channel_selector: ChannelSelectorType, which channel(s) to use for audio. - normalize_db: Target RMS value for audio normalization. - ref_channel: Reference channel for normalization. - id_key: key to access sample id from the dataset - global_rank: global rank of the current worker - world_size: total number of workers - shuffle_n: buffer size for shuffling - shuffle_seed: seed for shuffling - normalize_text: If true, normalizes text in HFTextProcessor - symbols_to_keep: If not None, only keeps symbols in this list when normalizing text - """ - - def __init__( - self, - audio_key: str, - text_key: str, - sample_rate_key: str, - hf_data_cfg: Union[DictConfig, ListConfig], - parser: Union[str, Callable], - sample_rate: int, - augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None, - trim: bool = False, - bos_id: Optional[int] = None, - eos_id: Optional[int] = None, - pad_id: int = 0, - return_sample_id: bool = False, - channel_selector: Optional[ChannelSelectorType] = None, - normalize_db: Optional[float] = None, - ref_channel: Optional[int] = None, - id_key: Optional[str] = None, - global_rank: int = 0, - world_size: int = 0, - shuffle_n: int = 0, - shuffle_seed: Optional[int] = None, - normalize_text: bool = False, - symbols_to_keep: Optional[str] = None, - ) -> None: - super().__init__() - - if return_sample_id and id_key is None: - raise ValueError("return_sample_id is True, but id_key is None") - - self.audio_key = audio_key - self.text_key = text_key - self.sample_rate_key = sample_rate_key - self.id_key = id_key - self.sample_rate = sample_rate - self.augmentor = augmentor if augmentor is not None else AudioAugmentor() - self.trim = trim - self.return_sample_id = return_sample_id - self.channel_selector = channel_selector - self.normalize_db = normalize_db - self.ref_channel = ref_channel - - self.text_processor = HFTextProcessor(parser, bos_id, eos_id, pad_id, normalize_text, symbols_to_keep) - - data_config_list = [hf_data_cfg] if isinstance(hf_data_cfg, DictConfig) else hf_data_cfg - dataset_list = [] - for data_cfg in data_config_list: - with open_dict(data_cfg): - if "streaming" in data_cfg and not data_cfg.streaming: - logging.warning( - "streaming must be True for streaming dataset, but you use streaming=False. Forcing streaming=True" - ) - # streaming must be True for iterable dataset - data_cfg.streaming = True - logging.info(f"Streaming HuggingFace IterableDataset with cfg: {data_cfg}") - dataset_list.append(hf_datasets.load_dataset(**data_cfg)) - - self.dataset = concatenate_datasets(dataset_list) - logging.info(f"Total number of samples cannot be extracted from HF streaming dataset") - - if shuffle_n > 0: - self.dataset = self.dataset.shuffle(seed=shuffle_seed, buffer_size=shuffle_n) - - self.dataset = split_dataset_by_node(self.dataset, global_rank, world_size) - self.dataset = self.dataset.map(self._build_sample) - - def __len__(self): - raise NotImplementedError( - f"len() is not supported for {self.__class__.__name__}. Please set `trainer.max_steps` to explicitly set the number of steps to train for." - ) - - def __iter__(self): - return self.dataset.__iter__() - - def _collate_fn(self, batch): - a_signal = [b['audio_signal'] for b in batch] - a_sig_length = [b['a_sig_length'] for b in batch] - transcripts = [b['transcripts'] for b in batch] - transcript_length = [b['transcript_length'] for b in batch] - if self.return_sample_id: - sample_id = [b['sample_id'] for b in batch] - batch_list = list(zip(a_signal, a_sig_length, transcripts, transcript_length, sample_id)) - else: - batch_list = list(zip(a_signal, a_sig_length, transcripts, transcript_length)) - - return _speech_collate_fn(batch_list, pad_id=self.text_processor.pad_id) - - def _build_sample(self, sample): - audio_array = get_nested_dict_value(sample, self.audio_key) - origin_sr = get_nested_dict_value(sample, self.sample_rate_key) - audio_segment = AudioSegment( - samples=audio_array, - sample_rate=origin_sr, - target_sr=self.sample_rate, - trim=self.trim, - channel_selector=self.channel_selector, - normalize_db=self.normalize_db, - ref_channel=self.ref_channel, - ) - self.augmentor.perturb(audio_segment) - f = torch.tensor(audio_segment.samples, dtype=torch.float) - fl = torch.tensor(f.shape[0], dtype=torch.long) - - text = get_nested_dict_value(sample, self.text_key) - t, tl = self.text_processor.process_text(text) - - output = { - 'audio_signal': f, - 'a_sig_length': fl, - 'transcripts': torch.tensor(t).long(), - 'transcript_length': torch.tensor(tl).long(), - } - - if self.return_sample_id: - output['sample_id'] = get_nested_dict_value(sample, self.id_key) - return output - - -class HFIterableAudioToCharDataset(_HFIterableAudioTextDataset): - """ - Wrapper class for loading HuggingFace IterableDataset for a char-based ASR model - """ - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - """Returns definitions of module output ports.""" - return { - 'audio_signal': NeuralType(('B', 'T'), AudioSignal()), - 'a_sig_length': NeuralType(tuple('B'), LengthsType()), - 'transcripts': NeuralType(('B', 'T'), LabelsType()), - 'transcript_length': NeuralType(tuple('B'), LengthsType()), - 'sample_id': NeuralType(tuple('B'), LengthsType(), optional=True), - } - - def __init__( - self, - labels: List[str], - audio_key: str, - text_key: str, - sample_rate_key: str, - hf_data_cfg: DictConfig, - sample_rate: int, - augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None, - trim: bool = False, - bos_id: int | None = None, - eos_id: int | None = None, - pad_id: int = 0, - return_sample_id: bool = False, - id_key: str | None = None, - channel_selector: ChannelSelectorType | None = None, - normalize_db: float | None = None, - ref_channel: int | None = None, - global_rank: int = 0, - world_size: int = 0, - shuffle_n: int = 0, - shuffle_seed: Optional[int] = None, - parser: Union[str, Callable] = 'en', - blank_index: int = -1, - unk_index: int = -1, - normalize: bool = True, - normalize_text: bool = False, - symbols_to_keep: Optional[str] = None, - ) -> None: - self.labels = labels - - parser = parsers.make_parser( - labels=labels, name=parser, unk_id=unk_index, blank_id=blank_index, do_normalize=normalize - ) - - super().__init__( - audio_key=audio_key, - text_key=text_key, - sample_rate_key=sample_rate_key, - hf_data_cfg=hf_data_cfg, - parser=parser, - sample_rate=sample_rate, - augmentor=augmentor, - trim=trim, - bos_id=bos_id, - eos_id=eos_id, - pad_id=pad_id, - return_sample_id=return_sample_id, - id_key=id_key, - channel_selector=channel_selector, - normalize_db=normalize_db, - ref_channel=ref_channel, - global_rank=global_rank, - world_size=world_size, - shuffle_n=shuffle_n, - shuffle_seed=shuffle_seed, - normalize_text=normalize_text, - symbols_to_keep=symbols_to_keep, - ) - - -class HFIterableAudioToBPEDataset(_HFIterableAudioTextDataset): - """ - Wrapper class for loading HuggingFace IterableDataset for a BPE-based ASR model - """ - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - """Returns definitions of module output ports.""" - return { - 'audio_signal': NeuralType(('B', 'T'), AudioSignal()), - 'a_sig_length': NeuralType(tuple('B'), LengthsType()), - 'transcripts': NeuralType(('B', 'T'), LabelsType()), - 'transcript_length': NeuralType(tuple('B'), LengthsType()), - 'sample_id': NeuralType(tuple('B'), LengthsType(), optional=True), - } - - def __init__( - self, - audio_key: str, - text_key: str, - sample_rate_key: str, - hf_data_cfg: DictConfig, - tokenizer: 'nemo.collections.common.tokenizers.TokenizerSpec', - sample_rate: int, - augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None, - trim: bool = False, - return_sample_id: bool = False, - id_key: str | None = None, - channel_selector: ChannelSelectorType | None = None, - normalize_db: float | None = None, - ref_channel: int | None = None, - global_rank: int = 0, - world_size: int = 0, - shuffle_n: int = 0, - shuffle_seed: Optional[int] = None, - use_start_end_token: bool = True, - normalize_text: bool = False, - symbols_to_keep: Optional[str] = None, - ) -> None: - - if use_start_end_token and hasattr(tokenizer, "bos_id") and tokenizer.bos_id > 0: - bos_id = tokenizer.bos_id - else: - bos_id = None - - if use_start_end_token and hasattr(tokenizer, "eos_id") and tokenizer.eos_id > 0: - eos_id = tokenizer.eos_id - else: - eos_id = None - - if hasattr(tokenizer, "pad_id") and tokenizer.pad_id > 0: - pad_id = tokenizer.pad_id - else: - pad_id = 0 - - class TokenizerWrapper: - def __init__(self, tokenizer): - if isinstance(tokenizer, tokenizers.aggregate_tokenizer.AggregateTokenizer): - self.is_aggregate = True - else: - self.is_aggregate = False - self._tokenizer = tokenizer - - def __call__(self, *args): - if isinstance(args[0], List) and self.is_aggregate: - t = [] - for span in args[0]: - t.extend(self._tokenizer.text_to_ids(span['str'], span['lang'])) - return t - - t = self._tokenizer.text_to_ids(*args) - return t - - super().__init__( - audio_key=audio_key, - text_key=text_key, - sample_rate_key=sample_rate_key, - hf_data_cfg=hf_data_cfg, - parser=TokenizerWrapper(tokenizer), - sample_rate=sample_rate, - augmentor=augmentor, - trim=trim, - bos_id=bos_id, - eos_id=eos_id, - pad_id=pad_id, - return_sample_id=return_sample_id, - id_key=id_key, - channel_selector=channel_selector, - normalize_db=normalize_db, - ref_channel=ref_channel, - global_rank=global_rank, - world_size=world_size, - shuffle_n=shuffle_n, - shuffle_seed=shuffle_seed, - normalize_text=normalize_text, - symbols_to_keep=symbols_to_keep, - ) diff --git a/nemo/collections/asr/data/huggingface/hf_audio_to_text_dataset.py b/nemo/collections/asr/data/huggingface/hf_audio_to_text_dataset.py deleted file mode 100644 index 0b36d58666f699c9f258d2a41b03095c75817c01..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/data/huggingface/hf_audio_to_text_dataset.py +++ /dev/null @@ -1,132 +0,0 @@ -# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from omegaconf import DictConfig - -from nemo.collections.asr.data.huggingface.hf_audio_to_text import ( - HFAudioToBPEDataset, - HFAudioToCharDataset, - HFIterableAudioToBPEDataset, - HFIterableAudioToCharDataset, -) - - -def get_hf_audio_to_text_bpe_dataset( - config: DictConfig, global_rank: int, world_size: int, tokenizer, augmentor=None, -): - if "streaming" in config and config["streaming"]: - dataset = HFIterableAudioToBPEDataset( - audio_key=config.get('audio_key', 'audio.array'), - text_key=config["text_key"], - sample_rate_key=config.get('sample_rate_key', 'audio.sampling_rate'), - tokenizer=tokenizer, - hf_data_cfg=config["hf_data_cfg"], - sample_rate=config["sample_rate"], - augmentor=augmentor, - trim=config.get('trim_silence', False), - return_sample_id=config.get('return_sample_id', False), - id_key=config.get("id_key", None), - channel_selector=config.get('channel_selector', None), - normalize_db=config.get('normalize_db', None), - ref_channel=config.get('ref_channel', None), - global_rank=global_rank, - world_size=world_size, - shuffle_n=config.get("shuffle_n", 2048), - shuffle_seed=config.get("shuffle_seed", None), - use_start_end_token=config.get('use_start_end_token', True), - normalize_text=config.get('normalize_text', False), - symbols_to_keep=config.get('symbols_to_keep', None), - ) - else: - dataset = HFAudioToBPEDataset( - audio_key=config.get('audio_key', 'audio.array'), - text_key=config["text_key"], - sample_rate_key=config.get('sample_rate_key', 'audio.sampling_rate'), - tokenizer=tokenizer, - hf_data_cfg=config["hf_data_cfg"], - sample_rate=config["sample_rate"], - augmentor=augmentor, - trim=config.get('trim_silence', False), - return_sample_id=config.get('return_sample_id', False), - id_key=config.get("id_key", None), - channel_selector=config.get('channel_selector', None), - normalize_db=config.get('normalize_db', None), - ref_channel=config.get('ref_channel', None), - use_start_end_token=config.get('use_start_end_token', True), - normalize_text=config.get('normalize_text', False), - symbols_to_keep=config.get('symbols_to_keep', None), - ) - - return dataset - - -def get_hf_audio_to_text_char_dataset( - config: DictConfig, global_rank: int, world_size: int, augmentor=None, -): - if "streaming" in config and config["streaming"]: - dataset = HFIterableAudioToCharDataset( - labels=config["labels"], - audio_key=config.get('audio_key', 'audio.array'), - text_key=config["text_key"], - sample_rate_key=config.get('sample_rate_key', 'audio.sampling_rate'), - hf_data_cfg=config["hf_data_cfg"], - sample_rate=config["sample_rate"], - augmentor=augmentor, - trim=config.get('trim_silence', False), - return_sample_id=config.get('return_sample_id', False), - id_key=config.get("id_key", None), - channel_selector=config.get('channel_selector', None), - normalize_db=config.get('normalize_db', None), - ref_channel=config.get('ref_channel', None), - global_rank=global_rank, - world_size=world_size, - shuffle_n=config.get("shuffle_n", 2048), - shuffle_seed=config.get("shuffle_seed", None), - parser=config.get("parser", "en"), - blank_index=config.get("blank_index", -1), - unk_index=config.get("unk_index", -1), - normalize=config.get("normalize", False), - normalize_text=config.get('normalize_text', False), - symbols_to_keep=config.get('symbols_to_keep', None), - pad_id=config.get('pad_id', 0), - bos_id=config.get('bos_id', None), - eos_id=config.get('eos_id', None), - ) - else: - dataset = HFAudioToCharDataset( - labels=config["labels"], - audio_key=config.get('audio_key', 'audio.array'), - text_key=config["text_key"], - sample_rate_key=config.get('sample_rate_key', 'audio.sampling_rate'), - hf_data_cfg=config["hf_data_cfg"], - sample_rate=config["sample_rate"], - augmentor=augmentor, - trim=config.get('trim_silence', False), - bos_id=config.get('bos_id', None), - eos_id=config.get('eos_id', None), - pad_id=config.get('pad_id', 0), - return_sample_id=config.get('return_sample_id', False), - id_key=config.get("id_key", None), - channel_selector=config.get('channel_selector', None), - normalize_db=config.get('normalize_db', None), - ref_channel=config.get('ref_channel', None), - parser=config.get("parser", "en"), - blank_index=config.get("blank_index", -1), - unk_index=config.get("unk_index", -1), - normalize=config.get("normalize", False), - normalize_text=config.get('normalize_text', False), - symbols_to_keep=config.get('symbols_to_keep', None), - ) - - return dataset diff --git a/nemo/collections/asr/data/ssl_dataset.py b/nemo/collections/asr/data/ssl_dataset.py deleted file mode 100644 index 2fc644f197035d7adee4252218e71762548317b5..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/data/ssl_dataset.py +++ /dev/null @@ -1,697 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import copy -import io -import json -import os -from dataclasses import dataclass -from math import isclose -from typing import Any, Dict, List, Optional, Union - -import numpy as np -import torch -from lhotse.dataset import AudioSamples -from omegaconf import DictConfig, ListConfig, open_dict -from torch import Tensor - -from nemo.collections.asr.data import audio_to_text, audio_to_text_dataset -from nemo.collections.asr.parts.preprocessing.perturb import WhiteNoisePerturbation, process_augmentations -from nemo.collections.asr.parts.preprocessing.segment import AudioSegment -from nemo.collections.asr.parts.utils.manifest_utils import read_manifest -from nemo.collections.common.data.dataset import ConcatDataset -from nemo.collections.common.parts.preprocessing.manifest import get_full_path -from nemo.core.classes import Serialization -from nemo.utils import logging - - -@dataclass -class AudioNoiseItem: - sample_id: str | None = None - audio: Union[Tensor, None] = None - audio_len: Union[Tensor, None] = None - noise: Union[Tensor, None] = None - noise_len: Union[Tensor, None] = None - noisy_audio: Union[Tensor, None] = None - noisy_audio_len: Union[Tensor, None] = None - - -@dataclass -class AudioNoiseBatch: - sample_id: list | None = None - audio: Union[Tensor, None] = None - audio_len: Union[Tensor, None] = None - noise: Union[Tensor, None] = None - noise_len: Union[Tensor, None] = None - noisy_audio: Union[Tensor, None] = None - noisy_audio_len: Union[Tensor, None] = None - - -def _parse_manifest_item(line: str, manifest_file: str) -> Dict[str, Any]: - """ - Specialized function to parse the manifest file by ignoring text, - such that nemo dataset can save time on tokenizing text. - """ - item = json.loads(line) - - # Audio file - if 'audio_filename' in item: - item['audio_file'] = item.pop('audio_filename') - elif 'audio_filepath' in item: - item['audio_file'] = item.pop('audio_filepath') - else: - raise KeyError(f"No 'audio_filename' or 'audio_filepath' in manifest item: {item}") - - item['audio_file'] = get_full_path(audio_file=item['audio_file'], manifest_file=manifest_file) - - # Duration. - if 'duration' not in item: - item['duration'] = None - - # dummy text - item['text'] = "" - - item = dict( - audio_file=item['audio_file'], - duration=item['duration'], - text=item['text'], - offset=item.get('offset', None), - speaker=item.get('speaker', None), - orig_sr=item.get('orig_sample_rate', None), - token_labels=item.get('token_labels', None), - lang=item.get('lang', None), - ) - return item - - -def _audio_noise_collate_fn(batch: List[AudioNoiseItem], batch_augmentor: Any = None) -> AudioNoiseBatch: - audios = [x.audio for x in batch] - audio_lengths = [x.audio_len for x in batch] - max_audio_len = max(audio_lengths).item() - - noises = [x.noise for x in batch] - noise_lengths = [x.noise_len for x in batch] - - audio_signal_list = [] - noise_signal_list = [] - for i, audio in enumerate(audios): - audio_len = audio.size(0) - if audio_len < max_audio_len: - pad = (0, max_audio_len - audio_len) - audio = torch.nn.functional.pad(audio, pad) - audio_signal_list.append(audio) - - noise = noises[i] - noise_len = noise.size(0) - if noise_len < max_audio_len: - pad = (0, max_audio_len - noise_len) - noise = torch.nn.functional.pad(noise, pad) - noise_signal_list.append(noise[:max_audio_len]) - - audio_signal = torch.stack(audio_signal_list).float() - audio_lengths = torch.stack(audio_lengths).long() - noise_signal = torch.stack(noise_signal_list).float() - noise_lengths = torch.stack(noise_lengths).long() - - output = AudioNoiseBatch( - audio=audio_signal, - audio_len=audio_lengths, - noise=noise_signal, - noise_len=noise_lengths, - ) - - if batch_augmentor is not None: - output = batch_augmentor(output) - else: - output.noisy_audio = output.audio + output.noise - output.noisy_audio_len = output.audio_len - - return output - - -def load_noise_manifest(noise_manifest: Union[str, ListConfig, None]): - """ - load noise manifest from a single or a list of manifest files - """ - if noise_manifest is None: - return [] - - if isinstance(noise_manifest, str): - noise_manifest = noise_manifest.split(',') - - noise_data = [] - for manifest in noise_manifest: - curr_data = read_manifest(manifest) - for i in range(len(curr_data)): - curr_data[i]['audio_filepath'] = get_full_path(curr_data[i]['audio_filepath'], manifest) - noise_data.extend(curr_data) - return noise_data - - -def load_noise_audio( - sample: Dict[str, Any], - sample_rate: int, - max_audio_len: Optional[int] = None, - pad_to_max: bool = True, - min_white_noise_db: int = -90, - max_white_noise_db: int = -46, - max_trial: int = 100, -): - """ - Load noise audio from the manifest item, and apply white noise if the loaded noise audio is empty. - Args: - sample: a sample from the noise manifest - sample_rate: target sample rate to resample the noise audio - max_audio_len: the maximum audio length to load - pad_to_max: whether to pad the audio to max_audio_len - min_white_noise_db: the minimum white noise level in dB - max_white_noise_db: the maximum white noise level in dB - max_trial: the maximum number of trials to load noise audio before giving up - Returns: - noise: the loaded noise audio - noise_len: the length of the loaded noise audio - """ - max_dur = None if max_audio_len is None else max_audio_len / sample_rate - duration = sample.get('duration', None) - offset = sample.get('offset', 0.0) - - if max_dur is not None and duration is not None and duration > max_dur: - cnt = 0 - while cnt < max_trial: - # randomly sample a segment of the noise - offset = np.random.uniform(0, duration - max_dur) - - audio_segment = AudioSegment.from_file( - audio_file=sample['audio_filepath'], - offset=offset, - duration=max_dur, - target_sr=sample_rate, - ) - - if sum(audio_segment.samples) > 0: - # break if the segment is not empty - break - cnt += 1 - else: - audio_segment = AudioSegment.from_file( - audio_file=sample['audio_filepath'], - offset=offset, - duration=duration, - target_sr=sample_rate, - ) - - if sum(audio_segment.samples) == 0: - logging.warning( - f"Loaded noise audio is empty: {sample}, with sampled offset={offset}, duration={max_dur}. Adding white noise." - ) - WhiteNoisePerturbation(min_level=min_white_noise_db, max_level=max_white_noise_db).perturb(audio_segment) - - noise = torch.tensor(audio_segment.samples, dtype=torch.float) - noise_len = torch.tensor(noise.size(0)).long() - # pad to max_audio_len if necessary - if max_audio_len is not None and pad_to_max: - if noise.size(0) < max_audio_len: - pad = (0, max_audio_len - noise.size(0)) - noise = torch.nn.functional.pad(noise, pad) - else: - noise = noise[:max_audio_len] - noise_len = torch.tensor(max_audio_len).long() - return noise, noise_len - - -def sample_noise(noise_data: List[Dict], sample_rate: int, max_audio_len: int | None = None, max_trial: int = 20): - """ - Randomly sample noise audio from the noise manifest. - Args: - noise_data: the noise manifest data - sample_rate: target sample rate to resample the noise audio - max_audio_len: the maximum audio length to load - max_trial: the maximum number of trials to load noise audio before giving up - Returns: - noise_audio: the sampled noise audio - noise_len: the length of the sampled noise audio - """ - cnt = 0 - noise_audio = torch.zeros(max_audio_len).float() - noise_len = torch.tensor(max_audio_len).long() - while cnt < max_trial and len(noise_data) > 0: - try: - noise_sample = noise_data[np.random.randint(len(noise_data))] - noise_audio, noise_len = load_noise_audio(noise_sample, sample_rate, max_audio_len) - break - except Exception as e: - logging.warning(f"Error loading noise audio with config {noise_sample} and exception: {e}, retrying.") - cnt += 1 - if cnt == max_trial: - logging.warning(f"Failed to load noise audio after {max_trial} attempts, returning zero noise.") - return torch.zeros(max_audio_len).float(), torch.tensor(max_audio_len).long() - return noise_audio, noise_len - - -def pad_audio(audio: Tensor, min_len: int, pad_audio_mode) -> Tensor: - """ - Pad audio to min_len with the specified mode - Args: - audio: the input audio tensor - min_len: the minimum length to pad to - pad_audio_mode: the padding mode, either 'repeat' or 'zero' - Returns: - audio: the padded audio tensor - """ - allowed_mode = ['repeat', 'zero'] - if audio.size(0) < min_len: - if pad_audio_mode == 'repeat' and audio.size(0) > 0: - num_repeats = int(np.ceil(min_len / audio.size(0))) - audio = audio.repeat(num_repeats)[:min_len] - elif pad_audio_mode == 'zero' or audio.size(0) == 0: - audio = torch.nn.functional.pad(audio, (0, min_len - audio.size(0))) - else: - raise ValueError(f"Unsupported pad_audio_mode: {pad_audio_mode}, must be one of {allowed_mode}") - return audio - - -class AudioNoiseDataset(audio_to_text.AudioToCharDataset): - @property - def output_types(self): - # disable type checking for since it doesn't support dataclass - return None - - def __init__( - self, - noise_manifest: str | None = None, - batch_augmentor: Any | None = None, - min_audio_len_secs: float = 1.0, - pad_audio_mode: str = 'repeat', - **kwargs, - ): - # add bos_id=0 to avoid empty text token - super().__init__(bos_id=0, manifest_parse_func=_parse_manifest_item, **kwargs) - self.noise_manifest = noise_manifest - self.batch_augmentor = batch_augmentor - self.noise_data = load_noise_manifest(noise_manifest) - self.min_audio_len_secs = min_audio_len_secs - self.pad_audio_mode = pad_audio_mode - - def __getitem__(self, index) -> AudioNoiseItem: - sample = self.manifest_processor.collection[index] - offset = sample.offset - - if offset is None: - offset = 0 - - audio = self.featurizer.process( - sample.audio_file, - offset=offset, - duration=sample.duration, - trim=self.trim, - orig_sr=sample.orig_sr, - channel_selector=self.channel_selector, - ) - if audio.size(0) == 0: - logging.warning(f"Loaded audio has zero length: {sample}.") - - min_len = int(self.min_audio_len_secs * self.featurizer.sample_rate) - audio = pad_audio(audio, min_len, self.pad_audio_mode) - audio_len = torch.tensor(audio.shape[0]).long() - noise, noise_len = sample_noise(self.noise_data, self.featurizer.sample_rate, audio_len.item()) - - item = AudioNoiseItem( - sample_id=str(index), - audio=audio, - audio_len=audio_len, - noise=noise, - noise_len=noise_len, - ) - return item - - def _collate_fn(self, batch: List[AudioNoiseItem]) -> AudioNoiseBatch: - return _audio_noise_collate_fn(batch, self.batch_augmentor) - - -class TarredAudioNoiseDataset(audio_to_text.TarredAudioToCharDataset): - @property - def output_types(self): - # disable type checking for since it doesn't support dataclass - return None - - def __init__( - self, - noise_manifest: str | None = None, - batch_augmentor: Any | None = None, - min_audio_len_secs: float = 1.0, - pad_audio_mode: str = 'repeat', - **kwargs, - ): - """ - Args: - noise_manifest: the noise manifest file - batch_augmentor: the batch augmentor - min_audio_len_secs: the minimum audio length in seconds, audios shorter than this will be padded - pad_audio_mode: the padding mode for audios shorter than min_audio_len_secs, either 'repeat' or 'zero' - **kwargs: other arguments for TarredAudioToCharDataset - - """ - super().__init__(bos_id=0, manifest_parse_func=_parse_manifest_item, **kwargs) - self.noise_manifest = noise_manifest - self.batch_augmentor = batch_augmentor - self.noise_data = load_noise_manifest(noise_manifest) - self.min_audio_len_secs = min_audio_len_secs - self.pad_audio_mode = pad_audio_mode - - def _build_sample(self, tup): - """Builds the training sample by combining the data from the WebDataset with the manifest info.""" - audio_bytes, audio_filename, offset_id = tup - - # Grab manifest entry from self.manifest_preprocessor.collection - file_id, _ = os.path.splitext(os.path.basename(audio_filename)) - manifest_idx = self.manifest_processor.collection.mapping[file_id][offset_id] - manifest_entry = self.manifest_processor.collection[manifest_idx] - - offset = manifest_entry.offset - if offset is None: - offset = 0 - - try: - # Convert audio bytes to IO stream for processing (for SoundFile to read) - audio_filestream = io.BytesIO(audio_bytes) - audio = self.featurizer.process( - audio_filestream, - offset=offset, - duration=manifest_entry.duration, - trim=self.trim, - orig_sr=manifest_entry.orig_sr, - ) - audio_filestream.close() - except Exception as e: - raise RuntimeError(f"Error reading audio sample: {manifest_entry}, with exception: {e}.") - - min_len = int(self.min_audio_len_secs * self.featurizer.sample_rate) - audio = pad_audio(audio, min_len, self.pad_audio_mode) - audio_len = torch.tensor(audio.shape[0]).long() - noise, noise_len = sample_noise(self.noise_data, self.featurizer.sample_rate, audio_len.item()) - - item = AudioNoiseItem( - sample_id=str(manifest_idx), - audio=audio, - audio_len=audio_len, - noise=noise, - noise_len=noise_len, - ) - return item - - def _pad_audio(self, audio: Tensor) -> Tensor: - min_len = int(self.min_audio_len_secs * self.featurizer.sample_rate) - if audio.size(0) < min_len: - if self.pad_audio_mode == 'repeat': - num_repeats = int(np.ceil(min_len / audio.size(0))) - audio = audio.repeat(num_repeats)[:min_len] - elif self.pad_audio_mode == 'zero': - audio = torch.nn.functional.pad(audio, (0, min_len - audio.size(0))) - else: - raise ValueError( - f"Unsupported pad_audio_mode: {self.pad_audio_mode}, must be one of ['repeat', 'zero']" - ) - return audio - - def _collate_fn(self, batch: List[AudioNoiseItem]) -> AudioNoiseBatch: - return _audio_noise_collate_fn(batch, self.batch_augmentor) - - -class LhotseAudioNoiseDataset(torch.utils.data.Dataset): - def __init__(self, noise_manifest: str | None = None, batch_augmentor_cfg: DictConfig = None): - super().__init__() - - if batch_augmentor_cfg: - batch_augmentor = Serialization.from_config_dict(batch_augmentor_cfg) - else: - batch_augmentor = None - - self.batch_augmentor = batch_augmentor - self.noise_data = load_noise_manifest(noise_manifest) - self.load_audio = AudioSamples(fault_tolerant=True) - - def __getitem__(self, cuts): - - audios, audio_lens, cuts = self.load_audio(cuts) - if len(self.noise_data) > 0: - sampled_noises = [sample_noise(self.noise_data, cut.sampling_rate, cut.num_samples) for cut in cuts] - sampled_noises, sampled_noises_lens = zip(*sampled_noises) - sampled_noises = torch.stack(sampled_noises).float() - sampled_noises_lens = torch.tensor(sampled_noises_lens).long() - else: - sampled_noises = torch.zeros_like(audios) - sampled_noises_lens = audio_lens - - output = AudioNoiseBatch( - audio=audios, - audio_len=audio_lens, - noise=sampled_noises, - noise_len=sampled_noises_lens, - ) - - if self.batch_augmentor is not None: - output = self.batch_augmentor(output) - else: - output.noisy_audio = output.audio + output.noise - output.noisy_audio_len = output.audio_len - - return output - - -def get_audio_noise_dataset( - config: Dict[str, Any], augmentor: Any = None, batch_augmentor: Any = None -) -> AudioNoiseDataset: - dataset = AudioNoiseDataset( - noise_manifest=config.get('noise_manifest', None), - batch_augmentor=batch_augmentor, - manifest_filepath=config['manifest_filepath'], - labels=config.get('labels', None), - sample_rate=config['sample_rate'], - int_values=config.get('int_values', False), - augmentor=augmentor, - max_duration=config.get('max_duration', None), - min_duration=config.get('min_duration', None), - trim=config.get('trim_silence', False), - channel_selector=config.get('channel_selector', None), - ) - return dataset - - -def get_concat_audio_noise_dataset( - config: Dict[str, Any], global_rank: int, world_size: int, augmentor: Any = None, batch_augmentor: Any = None -) -> ConcatDataset: - manifest_filepaths = config['manifest_filepath'] - datasets = [] - - # needed to support validation Concat Datasets that arrive here as - # [[dataset1,dataset2]] otherwise ModelPT would interfere - if len(manifest_filepaths) == 1 and not isinstance(manifest_filepaths[0], str): - logging.info(f"removing an extra nesting level from {manifest_filepaths}") - manifest_filepaths = config['manifest_filepath'][0] - - for manifest_filepath in manifest_filepaths: - conf = copy.deepcopy(config) - conf['manifest_filepath'] = manifest_filepath - - dataset = get_audio_noise_dataset(config=conf, augmentor=augmentor) - datasets.append(dataset) - - dataset = ConcatDataset( - datasets, - sampling_technique=config.get('concat_sampling_technique', 'temperature'), - sampling_temperature=config.get('concat_sampling_temperature', 5), - sampling_scale=config.get('concat_sampling_scale', 1), - sampling_probabilities=config.get('concat_sampling_probabilities', None), - shuffle=config.get('concat_shuffle', True), - seed=config.get('concat_sampling_seed', None), - global_rank=global_rank, - world_size=world_size, - ) - return dataset - - -def get_tarred_audio_noise_dataset(config, shuffle_n, global_rank, world_size, augmentor, batch_augmentor: Any = None): - tarred_audio_filepaths = config['tarred_audio_filepaths'] - manifest_filepaths = config['manifest_filepath'] - datasets = [] - tarred_audio_filepaths = audio_to_text_dataset.convert_to_config_list(tarred_audio_filepaths) - manifest_filepaths = audio_to_text_dataset.convert_to_config_list(manifest_filepaths) - - bucketing_weights = config.get('bucketing_weights', None) # For upsampling buckets - if bucketing_weights: - for idx, weight in enumerate(bucketing_weights): - if not isinstance(weight, int) or weight <= 0: - raise ValueError("bucket weights must be positive integers") - - if len(manifest_filepaths) != len(tarred_audio_filepaths): - raise ValueError( - f"manifest_filepaths (length={len(manifest_filepaths)}) and tarred_audio_filepaths (length={len(tarred_audio_filepaths)}) need to have the same number of buckets." - ) - - for dataset_idx, (tarred_audio_filepath, manifest_filepath) in enumerate( - zip(tarred_audio_filepaths, manifest_filepaths) - ): - if len(tarred_audio_filepath) == 1: - tarred_audio_filepath = tarred_audio_filepath[0] - if len(manifest_filepath) == 1: - manifest_filepath = manifest_filepath[0] - - is_sharded_manifest = True if "_OP_" in manifest_filepath and "_CL_" in manifest_filepath else False - logging.info( - f"Loading TarredAudioNoiseDataset from {tarred_audio_filepath} and {manifest_filepath}, shard={is_sharded_manifest}" - ) - dataset = TarredAudioNoiseDataset( - noise_manifest=config.get('noise_manifest', None), - batch_augmentor=batch_augmentor, - audio_tar_filepaths=tarred_audio_filepath, - manifest_filepath=manifest_filepath, - labels=config.get('labels', None), - sample_rate=config['sample_rate'], - int_values=config.get('int_values', False), - augmentor=augmentor, - shuffle_n=shuffle_n, - max_duration=config.get('max_duration', None), - min_duration=config.get('min_duration', None), - trim=config.get('trim_silence', False), - shard_strategy=config.get('tarred_shard_strategy', 'scatter'), - shard_manifests=is_sharded_manifest, - global_rank=global_rank, - world_size=world_size, - ) - if bucketing_weights: - [datasets.append(dataset) for _ in range(bucketing_weights[dataset_idx])] - else: - datasets.append(dataset) - - return audio_to_text_dataset.get_chain_dataset(datasets=datasets, ds_config=config, rank=global_rank) - - -def get_concat_tarred_audio_noise_dataset( - config, shuffle_n, global_rank, world_size, augmentor, batch_augmentor: Any = None -): - tarred_audio_filepaths = config['tarred_audio_filepaths'] - manifest_filepaths = config['manifest_filepath'] - datasets = [] - for dataset_idx, (tarred_audio_filepath, manifest_filepath) in enumerate( - zip(tarred_audio_filepaths, manifest_filepaths) - ): - conf = copy.deepcopy(config) - conf['manifest_filepath'] = manifest_filepath - conf['tarred_audio_filepaths'] = tarred_audio_filepath - dataset = get_tarred_audio_noise_dataset( - config=conf, - shuffle_n=shuffle_n, - global_rank=global_rank, - world_size=world_size, - augmentor=augmentor, - batch_augmentor=batch_augmentor, - ) - datasets.append(dataset) - - dataset = ConcatDataset( - datasets, - sampling_technique=config.get('concat_sampling_technique', 'temperature'), - sampling_temperature=config.get('concat_sampling_temperature', 5), - sampling_scale=config.get('concat_sampling_scale', 1), - sampling_probabilities=config.get('concat_sampling_probabilities', None), - shuffle=config.get('concat_shuffle', True), - seed=config.get('concat_sampling_seed', None), - global_rank=global_rank, - world_size=world_size, - ) - return dataset - - -def get_audio_noise_dataset_from_config( - config, - global_rank: int, - world_size: int, -): - if 'augmentor' in config: - augmentor = process_augmentations(config['augmentor'], global_rank=global_rank, world_size=world_size) - else: - augmentor = None - - if 'batch_augmentor' in config: - batch_augmentor = Serialization.from_config_dict(config['batch_augmentor']) - else: - batch_augmentor = None - - is_concat = config.get('is_concat', False) - if is_concat: - if config.get('concat_sampling_technique', None) is None: - logging.warning( - f"Concat dataset requires `concat_sampling_technique` but it was not provided, using round-robin. Config: {config}" - ) - config['concat_sampling_technique'] = 'round-robin' - - if config['concat_sampling_technique'] == 'random': - if not 'concat_sampling_probabilities' in config: - logging.warning( - f"Concat dataset requires `concat_sampling_probabilities` list, using uniform weights. Config: {config}" - ) - with open_dict(config): - config['concat_sampling_probabilities'] = [1 / len(config['manifest_filepath'])] * len( - config['manifest_filepath'] - ) - elif not isclose(sum(config['concat_sampling_probabilities']), 1, abs_tol=1e-6): - raise ValueError( - f"`concat_sampling_probabilities` need to sum to 1 with 1e-6 tolerance. Config: {config}" - ) - - shuffle = config['shuffle'] - if config.get('is_tarred', False): - if ('tarred_audio_filepaths' in config and config['tarred_audio_filepaths'] is None) or ( - 'manifest_filepath' in config and config['manifest_filepath'] is None - ): - logging.warning( - "Could not load dataset as `manifest_filepath` was None or " - f"`tarred_audio_filepaths` is None. Provided config : {config}" - ) - return None - - shuffle_n = config.get('shuffle_n', 4 * config['batch_size']) if shuffle else 0 - if is_concat: - dataset = get_concat_tarred_audio_noise_dataset( - config=config, - shuffle_n=shuffle_n, - global_rank=global_rank, - world_size=world_size, - augmentor=augmentor, - batch_augmentor=batch_augmentor, - ) - else: - dataset = get_tarred_audio_noise_dataset( - config=config, - shuffle_n=shuffle_n, - global_rank=global_rank, - world_size=world_size, - augmentor=augmentor, - batch_augmentor=batch_augmentor, - ) - else: - if 'manifest_filepath' in config and config['manifest_filepath'] is None: - logging.warning(f"Could not load dataset as `manifest_filepath` was None. Provided config : {config}") - return None - if is_concat: - dataset = get_concat_audio_noise_dataset( - config=config, - global_rank=global_rank, - world_size=world_size, - augmentor=augmentor, - batch_augmentor=batch_augmentor, - ) - else: - dataset = get_audio_noise_dataset(config=config, augmentor=augmentor, batch_augmentor=batch_augmentor) - return dataset diff --git a/nemo/collections/asr/data/text_to_text.py b/nemo/collections/asr/data/text_to_text.py deleted file mode 100644 index 28f5c5f445b588965b63a3c6e3facee3b2c81374..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/data/text_to_text.py +++ /dev/null @@ -1,484 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from __future__ import annotations - -import concurrent.futures -import copy -import gc -import json -import math -import random -from pathlib import Path -from typing import Any, Callable, Dict, Iterable, List, NamedTuple, Optional, Set, Union - -import numpy as np -import torch -import torch.utils.data -from torch.nn.utils.rnn import pad_sequence -from tqdm.auto import tqdm - -from nemo.collections.asr.data.audio_to_text import _speech_collate_fn -from nemo.collections.common.tokenizers import TokenizerSpec -from nemo.core.classes import Dataset, IterableDataset -from nemo.utils import logging - -try: - from nemo_text_processing.text_normalization.normalize import Normalizer -except Exception as e: - pass # Normalizer imported only for annotation purposes, error can be ignored - -AnyPath = Union[Path, str] - - -class TextToTextItem(NamedTuple): - tts_text: torch.Tensor # normalized and tokenized text for TTS - transcript: torch.Tensor # tokenized text for ASR - speaker: int # speaker id for multi-speaker TTS - - -class TextToTextBatch(NamedTuple): - tts_texts: torch.Tensor # tokenized texts for tts - tts_text_lengths: torch.Tensor - transcripts: torch.Tensor # tokenized texts for ASR - transcript_lengths: torch.Tensor - speakers: torch.Tensor # speaker ids for multi-speaker TTS - - @staticmethod - def collate_fn(batch: List[TextToTextItem], asr_pad_id: int, tts_text_pad_id: int) -> TextToTextBatch: - return TextToTextBatch( - tts_texts=pad_sequence([item.tts_text for item in batch], batch_first=True, padding_value=tts_text_pad_id), - tts_text_lengths=torch.tensor([item.tts_text.shape[0] for item in batch]).long(), - transcripts=pad_sequence([item.transcript for item in batch], batch_first=True, padding_value=asr_pad_id), - transcript_lengths=torch.tensor([item.transcript.shape[0] for item in batch]).long(), - speakers=torch.tensor([item.speaker for item in batch]).long(), - ) - - -class TextOrAudioToTextBatch(NamedTuple): - audio_signals: torch.Tensor - audio_signal_lengths: torch.Tensor - tts_texts: torch.Tensor - tts_text_lengths: torch.Tensor - speakers: torch.Tensor - transcripts: torch.Tensor - transcript_lengths: torch.Tensor - - @staticmethod - def collate_fn( - batch: List[Union[TextToTextItem, tuple]], tts_text_pad_id: int, asr_pad_id: int - ) -> Union[TextToTextBatch, TextOrAudioToTextBatch, tuple]: - """ - Collate function for dataloader - Can accept mixed batch of text-to-text items and audio-text items (typical for ASR) - """ - text_items: List[TextToTextItem] = [item for item in batch if isinstance(item, TextToTextItem)] - if not text_items: - # pure audio-text batch - return _speech_collate_fn(batch=batch, pad_id=asr_pad_id) - - asr_items = [item for item in batch if not isinstance(item, TextToTextItem)] - - if not asr_items: - # pure text-to-text batch - return TextToTextBatch.collate_fn(batch=text_items, asr_pad_id=asr_pad_id, tts_text_pad_id=tts_text_pad_id) - - # mixed batch - - # each asr item is a tuple: - # audio_signal (0), audio_length (1), transcript (2), transcript_length (3), sample_id (4, optional) - audio_signals = pad_sequence([item[0] for item in asr_items], batch_first=True, padding_value=0.0) - audio_signal_lengths = torch.tensor([item[1] for item in asr_items]).long() - - tts_texts = pad_sequence( - [item.tts_text for item in text_items], batch_first=True, padding_value=tts_text_pad_id - ) - tts_text_lengths = torch.tensor([item.tts_text.shape[0] for item in text_items]).long() - speakers = torch.tensor([item.speaker for item in text_items]).long() - - transcripts = pad_sequence( - [item.transcript for item in text_items] + [item[2] for item in asr_items], - batch_first=True, - padding_value=asr_pad_id, - ) - transcript_lengths = torch.tensor( - [item.transcript.shape[0] for item in text_items] + [item[3] for item in asr_items] - ).long() - - return TextOrAudioToTextBatch( - audio_signals=audio_signals, - audio_signal_lengths=audio_signal_lengths, - tts_texts=tts_texts, - tts_text_lengths=tts_text_lengths, - speakers=speakers, - transcripts=transcripts, - transcript_lengths=transcript_lengths, - ) - - -def _asr_text_to_tokens(text: str) -> np.ndarray: - """ - Helper function for asr tokenization with multiprocessing pool only. - Must be defined on the top level. - Expects asr_tokenizer_global, asr_bos_id_global, asr_eos_id_global to exist in the current pool process - """ - ids = asr_tokenizer_global.text_to_ids(text) - if asr_bos_id_global is not None: - ids = [asr_bos_id_global] + ids - if asr_eos_id_global is not None: - ids.append(asr_eos_id_global) - return np.asarray(ids) - - -def _tts_text_to_tokens(text: str) -> np.ndarray: - """ - Helper function for asr tokenization with multiprocessing pool only. - Must be defined on the top level. - Expects tts_tokenizer_global to exist in the current pool process - """ - return np.asarray(tts_tokenizer_global(text)) - - -def _iterate_manifest(filepath: AnyPath) -> Iterable[Dict[str, Any]]: - """ - Helper function to iterate manifest - """ - with open(filepath, "r", encoding="utf-8") as f: - for line in f: - record = json.loads(line) - yield record - - -class TextToTextDatasetBase: - """ - Base class for loading text-to-text manifests - Map-style and Iterable datasets should inherit this class - """ - - asr_pad_id: int - tts_text_pad_id: int - asr_bos_id: Optional[int] = None - asr_eos_id: Optional[int] = None - data: List[Dict[str, Any]] - - def __init__( - self, - manifest_filepath: Union[AnyPath, List[AnyPath]], - speakers_filepath: Union[AnyPath, List[AnyPath]], - asr_tokenizer: TokenizerSpec, - asr_use_start_end_token: bool, - tts_parser: Callable, - tts_text_pad_id: int, - tts_text_normalizer: "Normalizer", - tts_text_normalizer_call_kwargs: Dict, - min_words: int = 1, - max_words: int = 1_000_000, - tokenizer_workers: int = 1, - num_parts: int = 1, - current_part_index: int = 0, - ): - super().__init__() - # ASR tokenizer setup - if asr_use_start_end_token and hasattr(asr_tokenizer, 'bos_token'): - self.asr_bos_id = asr_tokenizer.bos_id - - if asr_use_start_end_token and hasattr(asr_tokenizer, 'eos_token'): - self.asr_eos_id = asr_tokenizer.eos_id - - if hasattr(asr_tokenizer, 'pad_token'): - self.asr_pad_id = asr_tokenizer.pad_id - else: - self.asr_pad_id = 0 - - self.asr_tokenizer = asr_tokenizer - - # TTS tokenizer setup - self.tts_parser = tts_parser - self.tts_normalizer = tts_text_normalizer - self.tts_normalizer_kwargs = tts_text_normalizer_call_kwargs - self.tts_text_pad_id = tts_text_pad_id - - # Load speakers - if isinstance(speakers_filepath, str): - speakers_filepath = speakers_filepath.split(",") - elif isinstance(speakers_filepath, Path): - speakers_filepath = [speakers_filepath] - speakers: Set[int] = set() - for filepath in speakers_filepath: - with open(Path(filepath).expanduser(), "r") as f: - speakers.update(map(int, f.read().split())) - self.speakers = np.asarray(sorted(speakers)) - logging.info(f"Loaded {len(self.speakers)} speakers") - - # Load manifest - if isinstance(manifest_filepath, str): - manifest_filepath = manifest_filepath.split(",") - elif isinstance(manifest_filepath, Path): - manifest_filepath = [manifest_filepath] - self.manifest_paths = [Path(filepath) for filepath in manifest_filepath] - - num_skipped_words = 0 - num_skipped_utterances = 0 - asr_texts = [] - tts_texts = [] - need_normalization = False - - for manifest_path in self.manifest_paths: - for tmp_item in tqdm(_iterate_manifest(manifest_path)): - text = tmp_item["text"] - num_words = len(text.split()) - # skip if number of works not in desired range - # TODO: maybe it would be valuable to sample sub-utterances from long utterances - if not (min_words <= num_words <= max_words): - num_skipped_words += num_words - num_skipped_utterances += 1 - continue - asr_texts.append(tmp_item["text"]) - if "tts_text_normalized" in tmp_item: - tts_texts.append(tmp_item["tts_text_normalized"]) - else: - tts_texts.append(tmp_item["tts_text"]) - need_normalization = True - - if need_normalization: - logging.warning("TTS normalization is extremely slow! It is recommended to normalize TTS text") - - if num_skipped_utterances: - logging.warning(f"Skipped {num_skipped_utterances} utterances " f"with {num_skipped_words}") - - num_utterances = len(asr_texts) - # preprocessing is very costly, if we need only part - remove unnecessary utterances - if num_parts > 1: - # NB: floor division, full dataset can contain fewer utterances than original, like in tarred dataset - num_utterances_part = num_utterances // num_parts - start = num_utterances_part * current_part_index - end = start + num_utterances_part - logging.info( - f"Taking part of the dataset: {current_part_index} index, total {num_parts} from {start} to {end}" - ) - asr_texts = asr_texts[start:end] - tts_texts = tts_texts[start:end] - num_utterances = num_utterances_part - - self.data = [dict() for _ in range(num_utterances)] - - if len(asr_texts) == 0: - # no data was loaded - logging.warning("Text-to-text dataset is empty") - return - - if tokenizer_workers == 1: - logging.warning( - "Preprocessing large text with tokenizer_workers=1 may be slow with TTS tokenizer. " - "Prefer tokenizer_workers=(num_cpu_cores/num_gpus_per_node)" - ) - for i, tokenized_text in enumerate( - tqdm((self._asr_text_to_tokens(text) for text in asr_texts), total=len(asr_texts)) - ): - self.data[i]["asr_text_tokens"] = tokenized_text - else: - # Multiprocessing hack: use global variables for every process (not really global in program context) - def _init_asr_tokenize_process(tokenizer, bos_id, eos_id): - global asr_tokenizer_global, asr_bos_id_global, asr_eos_id_global # process-global - # deepcopy to avoid serialization of parent models - asr_tokenizer_global = copy.deepcopy(tokenizer) - asr_bos_id_global = copy.deepcopy(bos_id) - asr_eos_id_global = copy.deepcopy(eos_id) - - with concurrent.futures.ProcessPoolExecutor( - initializer=_init_asr_tokenize_process, - initargs=(asr_tokenizer, self.asr_bos_id, self.asr_eos_id), - max_workers=tokenizer_workers, - ) as pool: - # chunk size for pool map is empirically chosen as a trade-off between speed and responsiveness - for i, tokenized_text in enumerate( - tqdm(pool.map(_asr_text_to_tokens, asr_texts, chunksize=1000), total=len(asr_texts)) - ): - self.data[i]["asr_text_tokens"] = tokenized_text - # force free memory - del asr_texts - gc.collect() - - if tokenizer_workers == 1: - logging.warning( - "Preprocessing large text with tokenizer_workers=1 may be slow with TTS tokenizer. " - "Prefer tokenizer_workers=(num_cpu_cores/num_gpus_per_node)" - ) - for i, tokenized_text in enumerate( - tqdm( - (self._tts_text_to_tokens(text, normalize=need_normalization) for text in tts_texts), - total=len(tts_texts), - ) - ): - self.data[i]["tts_text_tokens"] = tokenized_text - else: - if need_normalization: - # TODO: implement, if we really need normalization inplace - raise NotImplementedError( - "Normalization with tokenizer_workers > 1 is not implemented. " - "It is not recommended to use normalization on the fly at all, since it's extremely slow" - ) - - def _init_tts_tokenize_process(tokenizer): - global tts_tokenizer_global # process-global - tts_tokenizer_global = copy.deepcopy(tokenizer) - - with concurrent.futures.ProcessPoolExecutor( - initializer=_init_tts_tokenize_process, - initargs=(tts_parser,), - max_workers=tokenizer_workers, - ) as pool: - # chunk size for pool map is empirically chosen as a trade-off between speed and responsiveness - for i, tokenized_text in enumerate( - tqdm(pool.map(_tts_text_to_tokens, tts_texts, chunksize=1000), total=len(tts_texts)) - ): - self.data[i]["tts_text_tokens"] = tokenized_text - # force free memory - del tts_texts - gc.collect() - - def _asr_text_to_tokens(self, text: str) -> np.ndarray: - ids = self.asr_tokenizer.text_to_ids(text) - if self.asr_bos_id is not None: - ids = [self.asr_bos_id] + ids - if self.asr_eos_id is not None: - ids.append(self.asr_eos_id) - return np.asarray(ids) - - def _tts_text_to_tokens(self, text: str, normalize=True) -> np.ndarray: - if normalize: - text = self.tts_normalizer.normalize(text, **self.tts_normalizer_kwargs) - tokens = self.tts_parser(text) - return np.asarray(tokens) - - def __getitem__(self, index): - item = self.data[index] - return TextToTextItem( - transcript=torch.from_numpy(item["asr_text_tokens"]).long(), - tts_text=torch.from_numpy(item["tts_text_tokens"]).long(), - speaker=random.choice(self.speakers), - ) - - def __len__(self): - return len(self.data) - - -class TextToTextDataset(TextToTextDatasetBase, Dataset): - """Text-to-Text Map-style Dataset.""" - - def __init__( - self, - manifest_filepath: Union[AnyPath, List[AnyPath]], - speakers_filepath: Union[AnyPath, List[AnyPath]], - asr_tokenizer: TokenizerSpec, - asr_use_start_end_token: bool, - tts_parser: Callable, - tts_text_pad_id: int, - tts_text_normalizer: "Normalizer", - tts_text_normalizer_call_kwargs: Dict, - min_words: int = 1, - max_words: int = 1_000_000, - tokenizer_workers: int = 1, - ): - super().__init__( - manifest_filepath=manifest_filepath, - speakers_filepath=speakers_filepath, - asr_tokenizer=asr_tokenizer, - asr_use_start_end_token=asr_use_start_end_token, - tts_parser=tts_parser, - tts_text_pad_id=tts_text_pad_id, - tts_text_normalizer=tts_text_normalizer, - tts_text_normalizer_call_kwargs=tts_text_normalizer_call_kwargs, - min_words=min_words, - max_words=max_words, - tokenizer_workers=tokenizer_workers, - num_parts=1, - ) - - def collate_fn( - self, batch: List[Union[TextToTextItem, tuple]] - ) -> Union[TextToTextBatch, TextOrAudioToTextBatch, tuple]: - """ - Collate function for dataloader - Can accept mixed batch of text-to-text items and audio-text items (typical for ASR) - """ - return TextOrAudioToTextBatch.collate_fn( - batch=batch, asr_pad_id=self.asr_pad_id, tts_text_pad_id=self.tts_text_pad_id - ) - - -class TextToTextIterableDataset(TextToTextDatasetBase, IterableDataset): - """ - Text-to-Text Iterable Dataset. - Only part necessary for current process should be loaded and stored. - """ - - def __init__( - self, - manifest_filepath: Union[AnyPath, List[AnyPath]], - speakers_filepath: Union[AnyPath, List[AnyPath]], - asr_tokenizer: TokenizerSpec, - asr_use_start_end_token: bool, - tts_parser: Callable, - tts_text_pad_id: int, - tts_text_normalizer: "Normalizer", - tts_text_normalizer_call_kwargs: Dict, - min_words: int = 1, - max_words: int = 1_000_000, - tokenizer_workers: int = 1, - num_parts: int = 1, - current_part_index: int = 0, - ): - super().__init__( - manifest_filepath=manifest_filepath, - speakers_filepath=speakers_filepath, - asr_tokenizer=asr_tokenizer, - asr_use_start_end_token=asr_use_start_end_token, - tts_parser=tts_parser, - tts_text_pad_id=tts_text_pad_id, - tts_text_normalizer=tts_text_normalizer, - tts_text_normalizer_call_kwargs=tts_text_normalizer_call_kwargs, - min_words=min_words, - max_words=max_words, - tokenizer_workers=tokenizer_workers, - num_parts=num_parts, - current_part_index=current_part_index, - ) - - def __iter__(self): - # Implementation based on docs: https://pytorch.org/docs/stable/data.html#torch.utils.data.IterableDataset - worker_info = torch.utils.data.get_worker_info() - if worker_info is None: # single-process data loading, return the full iterator - start = 0 - end = len(self) - else: # in a worker process - # split workload - per_worker = int(math.ceil(len(self) / float(worker_info.num_workers))) - worker_id = worker_info.id - start = worker_id * per_worker - end = min(start + per_worker, len(self)) - indices = np.arange(start, end) - np.random.shuffle(indices) - return map(self.__getitem__, indices) - - def collate_fn( - self, batch: List[Union[TextToTextItem, tuple]] - ) -> Union[TextToTextBatch, TextOrAudioToTextBatch, tuple]: - """ - Collate function for dataloader - Can accept mixed batch of text-to-text items and audio-text items (typical for ASR) - """ - return TextOrAudioToTextBatch.collate_fn( - batch=batch, asr_pad_id=self.asr_pad_id, tts_text_pad_id=self.tts_text_pad_id - ) diff --git a/nemo/collections/asr/inference/__init__.py b/nemo/collections/asr/inference/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/asr/inference/factory/__init__.py b/nemo/collections/asr/inference/factory/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/factory/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/asr/inference/factory/base_builder.py b/nemo/collections/asr/inference/factory/base_builder.py deleted file mode 100644 index cae8b8a4ded42555bdda87568489d55ccd5300af..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/factory/base_builder.py +++ /dev/null @@ -1,172 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from __future__ import annotations - -from typing import TYPE_CHECKING, Any - -from omegaconf import open_dict -from omegaconf.dictconfig import DictConfig - -from nemo.collections.asr.inference.model_wrappers.cache_aware_ctc_inference_wrapper import ( - CacheAwareCTCInferenceWrapper, -) -from nemo.collections.asr.inference.model_wrappers.cache_aware_rnnt_inference_wrapper import ( - CacheAwareRNNTInferenceWrapper, -) -from nemo.collections.asr.inference.model_wrappers.ctc_inference_wrapper import CTCInferenceWrapper -from nemo.collections.asr.inference.model_wrappers.rnnt_inference_wrapper import RNNTInferenceWrapper -from nemo.collections.asr.inference.model_wrappers.salm_asr_inference_wrapper import SALMASRInferenceWrapper -from nemo.collections.asr.inference.utils.enums import ASRDecodingType, PipelineType -from nemo.collections.asr.parts.submodules.ctc_decoding import CTCDecodingConfig -from nemo.collections.asr.parts.submodules.rnnt_decoding import RNNTDecodingConfig -from nemo.utils import logging - -if TYPE_CHECKING: - from nemo.collections.asr.inference.itn.inverse_normalizer import AlignmentPreservingInverseNormalizer - from nemo.collections.asr.inference.nmt.llm_translator import LLMTranslator - - -class BaseBuilder: - """ - Base Builder class. - Builds the ASR/ITN components. - Derived classes should implement the `build` method which should include the logic of creating concrete pipeline. - """ - - @classmethod - def _build_nmt(cls, cfg: DictConfig) -> LLMTranslator | None: - """ - Build the NMT model based on the config. - Args: - cfg: (DictConfig) Config - Returns: - (LLMTranslator | None) NMT model - """ - nmt_model = None - if cfg.enable_nmt: - from nemo.collections.asr.inference.nmt.llm_translator import LLMTranslator - - nmt_model = LLMTranslator( - model_name=cfg.nmt.model_name, - source_language=cfg.nmt.source_language, - target_language=cfg.nmt.target_language, - waitk=cfg.nmt.waitk, - device=cfg.nmt.device, - device_id=cfg.nmt.device_id, - batch_size=cfg.nmt.batch_size, - llm_params=cfg.nmt.llm_params, - sampling_params=cfg.nmt.sampling_params, - ) - logging.info(f"NMT model `{cfg.nmt.model_name}` loaded") - return nmt_model - - @classmethod - def _build_asr(cls, cfg: DictConfig, decoding_cfg: CTCDecodingConfig | RNNTDecodingConfig | None) -> Any: - """ - Build the ASR model based on the config. - Args: - cfg: (DictConfig) Config - decoding_cfg: (CTCDecodingConfig | RNNTDecodingConfig | None) Decoding config - Returns: - (Any) ASR inference model - """ - - asr_decoding_type = ASRDecodingType.from_str(cfg.asr_decoding_type) - pipeline_type = PipelineType.from_str(cfg.pipeline_type) - model_params = { - "model_name": cfg.asr.model_name, - "device": cfg.asr.device, - "device_id": cfg.asr.device_id, - "compute_dtype": cfg.asr.compute_dtype, - "use_amp": cfg.asr.use_amp, - "decoding_cfg": decoding_cfg, - } - match (asr_decoding_type, pipeline_type): - case (ASRDecodingType.CTC, PipelineType.BUFFERED): - asr_class = CTCInferenceWrapper - case (ASRDecodingType.RNNT, PipelineType.BUFFERED): - asr_class = RNNTInferenceWrapper - case (ASRDecodingType.SALM, PipelineType.BUFFERED): - asr_class = SALMASRInferenceWrapper - # remove decoding_cfg, SALM AED does not use decoding_cfg yet - model_params.pop("decoding_cfg") - case (ASRDecodingType.CTC, PipelineType.CACHE_AWARE): - asr_class = CacheAwareCTCInferenceWrapper - case (ASRDecodingType.RNNT, PipelineType.CACHE_AWARE): - asr_class = CacheAwareRNNTInferenceWrapper - case _: - raise ValueError( - f"Wrong combination of ASR decoding type and pipeline type: {asr_decoding_type, pipeline_type}" - ) - - asr_model = asr_class(**model_params) - logging.info(f"ASR model `{cfg.asr.model_name}` loaded") - return asr_model - - @classmethod - def _build_itn(cls, cfg: DictConfig, input_is_lower_cased: bool) -> AlignmentPreservingInverseNormalizer | None: - """ - Build the ITN model based on the config. - Args: - cfg: (DictConfig) Config - input_is_lower_cased: (bool) Whether the input is lower cased - Returns: - (AlignmentPreservingInverseNormalizer | None) ITN model - """ - itn_model = None - if cfg.enable_itn: - # Do not remove this import. It is used to avoid nemo_text_processing import when verbatim transcripts is enabled. - from nemo.collections.asr.inference.itn.inverse_normalizer import AlignmentPreservingInverseNormalizer - - input_case = ( - AlignmentPreservingInverseNormalizer.LOWER_CASED - if input_is_lower_cased - else AlignmentPreservingInverseNormalizer.UPPER_CASED - ) - - target_lang = getattr(cfg, "lang", getattr(cfg, "target_lang", None)) - if target_lang is None: - raise ValueError("Language is not specified. Cannot load ITN model.") - - itn_cfg = cfg.itn - with open_dict(itn_cfg): - itn_cfg.lang = target_lang - itn_cfg.input_case = input_case - itn_cfg.cache_dir = cfg.cache_dir - - itn_model = AlignmentPreservingInverseNormalizer( - lang=itn_cfg.lang, - input_case=itn_cfg.input_case, - whitelist=itn_cfg.whitelist, - cache_dir=itn_cfg.cache_dir, - overwrite_cache=itn_cfg.overwrite_cache, - max_number_of_permutations_per_split=itn_cfg.max_number_of_permutations_per_split, - ) - logging.info(f"Built inverse text normalizer with the input case: `{input_case}`.") - - if itn_model is not None: - logging.info("ITN model loaded") - return itn_model - - @classmethod - def build(cls, cfg: DictConfig) -> Any: - """ - Build the pipeline based on the config. - Args: - cfg: (DictConfig) Config - Returns: - Returns object responsible for the inference - """ - raise NotImplementedError("This method should be implemented in subclasses.") diff --git a/nemo/collections/asr/inference/factory/buffered_pipeline_builder.py b/nemo/collections/asr/inference/factory/buffered_pipeline_builder.py deleted file mode 100644 index 17815e578cb4e4706ab6b862443e887833e1fc7f..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/factory/buffered_pipeline_builder.py +++ /dev/null @@ -1,147 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from omegaconf import DictConfig, OmegaConf - -from nemo.collections.asr.inference.factory.base_builder import BaseBuilder -from nemo.collections.asr.inference.pipelines.buffered_ctc_pipeline import BufferedCTCPipeline -from nemo.collections.asr.inference.pipelines.buffered_rnnt_pipeline import BufferedRNNTPipeline -from nemo.collections.asr.inference.pipelines.buffered_salm_pipeline import BufferedSALMPipeline -from nemo.collections.asr.inference.utils.enums import ASRDecodingType -from nemo.collections.asr.parts.submodules.ctc_decoding import CTCDecodingConfig -from nemo.collections.asr.parts.submodules.rnnt_decoding import RNNTDecodingConfig -from nemo.utils import logging - - -class BufferedPipelineBuilder(BaseBuilder): - """ - Buffered Pipeline Builder class. - Builds: - - buffered CTC/RNNT/TDT pipelines. - - buffered SALM pipeline. - """ - - @classmethod - def build(cls, cfg: DictConfig) -> BufferedRNNTPipeline | BufferedCTCPipeline | BufferedSALMPipeline: - """ - Build the buffered streaming pipeline based on the config. - Args: - cfg: (DictConfig) Config - Returns: - Returns BufferedRNNTPipeline, BufferedCTCPipeline, or BufferedSALMPipeline object - """ - asr_decoding_type = ASRDecodingType.from_str(cfg.asr_decoding_type) - - if asr_decoding_type is ASRDecodingType.RNNT: - return cls.build_buffered_rnnt_pipeline(cfg) - elif asr_decoding_type is ASRDecodingType.CTC: - return cls.build_buffered_ctc_pipeline(cfg) - elif asr_decoding_type is ASRDecodingType.SALM: - return cls.build_buffered_salm_pipeline(cfg) - - raise ValueError("Invalid asr decoding type for buffered streaming. Need to be one of ['CTC', 'RNNT', 'SALM']") - - @classmethod - def get_rnnt_decoding_cfg(cls, cfg: DictConfig) -> RNNTDecodingConfig: - """ - Get the decoding config for the RNNT pipeline. - Returns: - (RNNTDecodingConfig) Decoding config - """ - base_cfg_structured = OmegaConf.structured(RNNTDecodingConfig) - base_cfg = OmegaConf.create(OmegaConf.to_container(base_cfg_structured)) - decoding_cfg = OmegaConf.merge(base_cfg, cfg.asr.decoding) - return decoding_cfg - - @classmethod - def get_ctc_decoding_cfg(cls) -> CTCDecodingConfig: - """ - Get the decoding config for the CTC pipeline. - Returns: - (CTCDecodingConfig) Decoding config - """ - decoding_cfg = CTCDecodingConfig() - decoding_cfg.strategy = "greedy" - return decoding_cfg - - @classmethod - def build_buffered_rnnt_pipeline(cls, cfg: DictConfig) -> BufferedRNNTPipeline: - """ - Build the RNNT streaming pipeline based on the config. - Args: - cfg: (DictConfig) Config - Returns: - Returns BufferedRNNTPipeline object - """ - # building ASR model - decoding_cfg = cls.get_rnnt_decoding_cfg(cfg) - asr_model = cls._build_asr(cfg, decoding_cfg) - - # building ITN model - itn_model = cls._build_itn(cfg, input_is_lower_cased=True) - - # building NMT model - nmt_model = cls._build_nmt(cfg) - - # building RNNT pipeline - rnnt_pipeline = BufferedRNNTPipeline(cfg, asr_model, itn_model, nmt_model) - logging.info(f"`{type(rnnt_pipeline).__name__}` pipeline loaded") - return rnnt_pipeline - - @classmethod - def build_buffered_ctc_pipeline(cls, cfg: DictConfig) -> BufferedCTCPipeline: - """ - Build the CTC buffered streaming pipeline based on the config. - Args: - cfg: (DictConfig) Config - Returns: - Returns BufferedCTCPipeline object - """ - # building ASR model - decoding_cfg = cls.get_ctc_decoding_cfg() - asr_model = cls._build_asr(cfg, decoding_cfg) - - # building ITN model - itn_model = cls._build_itn(cfg, input_is_lower_cased=True) - - # building NMT model - nmt_model = cls._build_nmt(cfg) - - # building CTC pipeline - ctc_pipeline = BufferedCTCPipeline(cfg, asr_model, itn_model, nmt_model) - logging.info(f"`{type(ctc_pipeline).__name__}` pipeline loaded") - return ctc_pipeline - - @classmethod - def build_buffered_salm_pipeline(cls, cfg: DictConfig) -> BufferedSALMPipeline: - """ - Build the buffered SALM pipeline based on the config. - Args: - cfg: (DictConfig) Config - Returns: - Returns BufferedSALMPipeline object - """ - # building ASR model - asr_model = cls._build_asr(cfg, decoding_cfg=None) - - # building ITN model - itn_model = cls._build_itn(cfg, input_is_lower_cased=True) - - # building NMT model - nmt_model = cls._build_nmt(cfg) - - # building SALM pipeline - salm_pipeline = BufferedSALMPipeline(cfg, asr_model, itn_model, nmt_model) - logging.info(f"`{type(salm_pipeline).__name__}` pipeline loaded") - return salm_pipeline diff --git a/nemo/collections/asr/inference/factory/cache_aware_pipeline_builder.py b/nemo/collections/asr/inference/factory/cache_aware_pipeline_builder.py deleted file mode 100644 index d8c31e1d4548c19a2350d46b3e489e656a03aabb..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/factory/cache_aware_pipeline_builder.py +++ /dev/null @@ -1,120 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from omegaconf import DictConfig, OmegaConf - -from nemo.collections.asr.inference.factory.base_builder import BaseBuilder -from nemo.collections.asr.inference.pipelines.cache_aware_ctc_pipeline import CacheAwareCTCPipeline -from nemo.collections.asr.inference.pipelines.cache_aware_rnnt_pipeline import CacheAwareRNNTPipeline -from nemo.collections.asr.inference.utils.enums import ASRDecodingType -from nemo.collections.asr.parts.submodules.ctc_decoding import CTCDecodingConfig -from nemo.collections.asr.parts.submodules.rnnt_decoding import RNNTDecodingConfig -from nemo.utils import logging - - -class CacheAwarePipelineBuilder(BaseBuilder): - """ - Cache Aware Pipeline Builder class. - Builds the cache aware CTC/RNNT pipelines. - """ - - @classmethod - def build(cls, cfg: DictConfig) -> CacheAwareCTCPipeline | CacheAwareRNNTPipeline: - """ - Build the cache aware streaming pipeline based on the config. - Args: - cfg: (DictConfig) Config - Returns: - Returns CacheAwareCTCPipeline or CacheAwareRNNTPipeline object - """ - asr_decoding_type = ASRDecodingType.from_str(cfg.asr_decoding_type) - - if asr_decoding_type is ASRDecodingType.RNNT: - return cls.build_cache_aware_rnnt_pipeline(cfg) - elif asr_decoding_type is ASRDecodingType.CTC: - return cls.build_cache_aware_ctc_pipeline(cfg) - - raise ValueError("Invalid asr decoding type for cache aware streaming. Need to be one of ['CTC', 'RNNT']") - - @classmethod - def get_rnnt_decoding_cfg(cls, cfg: DictConfig) -> RNNTDecodingConfig: - """ - Get the decoding config for the RNNT pipeline. - Returns: - (RNNTDecodingConfig) Decoding config - """ - base_cfg_structured = OmegaConf.structured(RNNTDecodingConfig) - base_cfg = OmegaConf.create(OmegaConf.to_container(base_cfg_structured)) - decoding_cfg = OmegaConf.merge(base_cfg, cfg.asr.decoding) - return decoding_cfg - - @classmethod - def get_ctc_decoding_cfg(cls) -> CTCDecodingConfig: - """ - Get the decoding config for the CTC pipeline. - Returns: - (CTCDecodingConfig) Decoding config - """ - decoding_cfg = CTCDecodingConfig() - decoding_cfg.strategy = "greedy" - decoding_cfg.preserve_alignments = False - return decoding_cfg - - @classmethod - def build_cache_aware_rnnt_pipeline(cls, cfg: DictConfig) -> CacheAwareRNNTPipeline: - """ - Build the cache aware RNNT streaming pipeline based on the config. - Args: - cfg: (DictConfig) Config - Returns: - Returns CacheAwareRNNTPipeline object - """ - # building ASR model - decoding_cfg = cls.get_rnnt_decoding_cfg(cfg) - asr_model = cls._build_asr(cfg, decoding_cfg) - - # building ITN model - itn_model = cls._build_itn(cfg, input_is_lower_cased=True) - - # building NMT model - nmt_model = cls._build_nmt(cfg) - - # building cache aware RNNT pipeline - ca_rnnt_pipeline = CacheAwareRNNTPipeline(cfg, asr_model, itn_model, nmt_model) - logging.info(f"`{type(ca_rnnt_pipeline).__name__}` pipeline loaded") - return ca_rnnt_pipeline - - @classmethod - def build_cache_aware_ctc_pipeline(cls, cfg: DictConfig) -> CacheAwareCTCPipeline: - """ - Build the cache aware CTC streaming pipeline based on the config. - Args: - cfg: (DictConfig) Config - Returns: - Returns CacheAwareCTCPipeline object - """ - # building ASR model - decoding_cfg = cls.get_ctc_decoding_cfg() - asr_model = cls._build_asr(cfg, decoding_cfg) - - # building ITN model - itn_model = cls._build_itn(cfg, input_is_lower_cased=True) - - # building NMT model - nmt_model = cls._build_nmt(cfg) - - # building cache aware CTC pipeline - ca_ctc_pipeline = CacheAwareCTCPipeline(cfg, asr_model, itn_model, nmt_model) - logging.info(f"`{type(ca_ctc_pipeline).__name__}` pipeline loaded") - return ca_ctc_pipeline diff --git a/nemo/collections/asr/inference/factory/pipeline_builder.py b/nemo/collections/asr/inference/factory/pipeline_builder.py deleted file mode 100644 index 54a58ad3332c408c861dee64cadba8f15bf4e32d..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/factory/pipeline_builder.py +++ /dev/null @@ -1,74 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import torch -from omegaconf.dictconfig import DictConfig - -from nemo.collections.asr.inference.factory.buffered_pipeline_builder import BufferedPipelineBuilder -from nemo.collections.asr.inference.factory.cache_aware_pipeline_builder import CacheAwarePipelineBuilder -from nemo.collections.asr.inference.pipelines.base_pipeline import BasePipeline -from nemo.collections.asr.inference.utils.enums import PipelineType -from nemo.utils import logging - - -class PipelineBuilder: - """Router for building the pipeline based on the pipeline type.""" - - @staticmethod - def set_matmul_precision(matmul_precision: str) -> None: - """ - Set the matmul precision. - Args: - matmul_precision: (str) Matmul precision: highest, high, medium - """ - choices = ["highest", "high", "medium"] - matmul_precision = matmul_precision.lower() - if matmul_precision not in choices: - raise ValueError(f"Invalid matmul precision: {matmul_precision}. Need to be one of {choices}") - torch.set_float32_matmul_precision(matmul_precision) - logging.info(f"Using matmul precision: {matmul_precision}") - - @staticmethod - def set_log_level(log_level: int) -> None: - """ - Set the logging level. - Args: - log_level: (int) Logging level: 0 (NOTSET), 10 (DEBUG), 20 (INFO), 30 (WARNING), 40 (ERROR), 50 (CRITICAL) - """ - choices = [0, 10, 20, 30, 40, 50] - if log_level not in choices: - raise ValueError(f"Invalid log level: {log_level}. Need to be one of {choices}") - logging.setLevel(log_level) - - @staticmethod - def build_pipeline(cfg: DictConfig) -> BasePipeline: - """ - Build the pipeline based on the config. - Args: - cfg: (DictConfig) Config - Returns: - Returns Pipeline object - """ - PipelineBuilder.set_log_level(cfg.log_level) - PipelineBuilder.set_matmul_precision(cfg.matmul_precision) - pipeline_type = PipelineType.from_str(cfg.pipeline_type) - if pipeline_type is PipelineType.BUFFERED: - builder = BufferedPipelineBuilder - elif pipeline_type is PipelineType.CACHE_AWARE: - builder = CacheAwarePipelineBuilder - else: - raise ValueError(f"Invalid pipeline type: {cfg.pipeline_type}") - - return builder.build(cfg) diff --git a/nemo/collections/asr/inference/itn/__init__.py b/nemo/collections/asr/inference/itn/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/itn/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/asr/inference/itn/batch_inverse_normalizer.py b/nemo/collections/asr/inference/itn/batch_inverse_normalizer.py deleted file mode 100644 index 99f52dd55882d5793d1c6772fa7ec8cebc65e4e4..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/itn/batch_inverse_normalizer.py +++ /dev/null @@ -1,185 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import itertools -from typing import Callable - -from joblib import Parallel, delayed - -from nemo.collections.asr.inference.itn.inverse_normalizer import AlignmentPreservingInverseNormalizer -from nemo.collections.asr.inference.utils.text_segment import Word - - -def merge_punctuation_and_itn_tags( - input_words: list[str], - output_words: list[str], - word_alignment: list[tuple], - pnc_words: list[Word], - punct_marks: set, - sep: str, - conf_aggregate_fn: Callable, -) -> list[Word]: - """ - Merge the punctuation marks and ITN tags to the final text. - It will also preserve first letter capitalization, start and end time of the span. - Args: - input_words: (list[str]) List of input words - output_words: (list[str]) List of output words - word_alignment: (list[tuple[list[int], list[int]]]) Word alignment between the input and output words - pnc_words: (list[Word]) List of words with punctuation marks - punct_marks: (set) Punctuation marks - sep: (str) Separator - conf_aggregate_fn: (Callable) Confidence aggregation function - Returns: - (list[Word]) Final words after merging the punctuation marks and ITN tags - """ - assert len(input_words) == len(pnc_words) - spans = [] - for s_idx, t_idx, semiotic_class in word_alignment: - if len(t_idx) == 1 and len(s_idx) == 1 and input_words[s_idx[0]] == output_words[t_idx[0]]: - span = pnc_words[s_idx[0]] - span.semiotic_class = semiotic_class - else: - span_text = sep.join([output_words[i] for i in t_idx]) - last_char = pnc_words[s_idx[-1]].text[-1] - first_char = pnc_words[s_idx[0]].text[0] - - # preserve the first char capitalization - first_word = pnc_words[s_idx[0]].copy() - first_char_is_upper = first_word.text[0].isupper() - first_word.normalize_text_inplace(punct_marks, sep) - if span_text.startswith(first_word.text): - if first_char_is_upper: - span_text = span_text[0].upper() + span_text[1:] - - # preserve the last punctuation mark - if last_char in punct_marks: - span_text += last_char - - # preserve the first punctuation mark - if first_char in punct_marks: - span_text = first_char + span_text - - scores = [pnc_words[i].conf for i in s_idx] - conf = conf_aggregate_fn(scores) if len(scores) > 0 else 0.0 - span = Word( - text=span_text, - start=pnc_words[s_idx[0]].start, - end=pnc_words[s_idx[-1]].end, - semiotic_class=semiotic_class, - conf=conf, - ) - spans.append(span) - return spans - - -class BatchAlignmentPreservingInverseNormalizer: - """ - Batch Alignment Preserving Inverse Text Normalizer. It is used to apply ITN to a batch of texts. - joblib.Parallel is used to parallelize the processing. - """ - - def __init__( - self, - itn_model: AlignmentPreservingInverseNormalizer, - sep: str, - asr_supported_puncts: set[str], - post_word_punctuation: set[str], - conf_aggregate_fn: Callable, - ): - """ - Batch Alignment Preserving Inverse Text Normalizer. It is used to apply ITN to a batch of texts. - Args: - itn_model: (AlignmentPreservingInverseNormalizer) Alignment Preserving Inverse Text Normalizer - sep: (str) Separator - asr_supported_puncts: (Set[str]) Punctuation marks supported by ASR model - post_word_punctuation: (Set[str]) Punctuation marks which usually appear after a word - conf_aggregate_fn: (Callable) Confidence aggregation function - """ - self.itn_model = itn_model - self.sep = sep - self.asr_supported_puncts = asr_supported_puncts - self.conf_aggregate_fn = conf_aggregate_fn - self.punct_marks = self.asr_supported_puncts | post_word_punctuation - - def apply_itn( - self, asr_words: list[Word], pnc_words: list[Word], return_alignment: bool = False - ) -> list[Word] | tuple[list[Word], list]: - """ - Apply Alignment Preserving Inverse Text Normalization. - Args: - asr_words: (list[Word]) List of ASR words - pnc_words: (list[Word]) List of words with punctuation/capitalization - return_alignment: (bool) Flag to return the word alignment - Returns: - (list[Word]) List of words after applying ITN - """ - input_words = [] - for word in asr_words: - word.normalize_text_inplace(self.asr_supported_puncts, self.sep) - input_words.append(word.text) - - input_words, output_words, word_alignment = self.itn_model.get_word_alignment(input_words, sep=self.sep) - spans = merge_punctuation_and_itn_tags( - input_words, output_words, word_alignment, pnc_words, self.punct_marks, self.sep, self.conf_aggregate_fn - ) - - if return_alignment: - # word alignment is needed for streaming inference - return spans, word_alignment - return spans - - def __call__( - self, - asr_words_list: list[list[Word]], - pnc_words_list: list[list[Word]], - itn_params: dict, - return_alignment: bool = False, - ) -> list[list[Word]] | list[tuple]: - """ - Batch Alignment Preserving Inverse Text Normalization. - Args: - asr_words_list: (list[list[Word]]) List of ASR words - pnc_words_list: (list[list[Word]]) List of words with punctuation/capitalization - itn_params: (dict) Parameters for the ITN model - return_alignment: (bool) Flag to return the word alignment - Returns: - (list[list[Word]]) List of words after applying ITN - """ - if len(asr_words_list) == 0: - return [] - - batch_size = itn_params.get("batch_size", 1) - n_texts = len(asr_words_list) - batch_size = min(n_texts, batch_size) - - def process_batch(batch_words, batch_words_with_pnc): - return [ - self.apply_itn(words, words_with_pnc, return_alignment) - for words, words_with_pnc in zip(batch_words, batch_words_with_pnc) - ] - - if n_texts <= 3 * batch_size or n_texts == 1: - # If the number of texts is less than 3 * batch_size, process the batch sequentially - # For small batch size, it is faster to process the batch sequentially - return process_batch(asr_words_list, pnc_words_list) - - n_jobs = itn_params.get("n_jobs", 1) - itn_words_list = Parallel(n_jobs=n_jobs)( - delayed(process_batch)(asr_words_list[i : i + batch_size], pnc_words_list[i : i + batch_size]) - for i in range(0, n_texts, batch_size) - ) - itn_words_list = list(itertools.chain(*itn_words_list)) - return itn_words_list diff --git a/nemo/collections/asr/inference/itn/inverse_normalizer.py b/nemo/collections/asr/inference/itn/inverse_normalizer.py deleted file mode 100644 index 38546d7caa89ebf0ee2c57b7a3fb4ed3f762ac0a..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/itn/inverse_normalizer.py +++ /dev/null @@ -1,355 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import os -import re -from multiprocessing import Manager - -from nemo.collections.asr.inference.utils.itn_utils import ( - DEFAULT_SEMIOTIC_CLASS, - fallback_to_trivial_alignment, - find_tokens, - get_semiotic_class, - split_text, -) -from nemo.utils import logging - -IN_MEM_CACHE = Manager().dict(lock=False) - -try: - import pynini - from nemo_text_processing.inverse_text_normalization.inverse_normalize import InverseNormalizer, Normalizer - from nemo_text_processing.text_normalization.en.graph_utils import INPUT_CASED, INPUT_LOWER_CASED - - HAVE_NEMO_TEXT_PROCESSING = True -except ImportError: - INPUT_CASED, INPUT_LOWER_CASED = "undefined", "undefined" - HAVE_NEMO_TEXT_PROCESSING = False - -try: - import diskcache - - CACHING_FROM_DISK = True -except ImportError: - logging.warning("diskcache package is not installed, caching from disk is disabled") - CACHING_FROM_DISK = False - - -class AlignmentPreservingInverseNormalizer: - """ - Inverse Text Normalizer that preserves the word alignment. - It is used to convert the spoken text to written text and preserve the alignment between the input and output words. - """ - - LOWER_CASED = INPUT_LOWER_CASED - UPPER_CASED = INPUT_CASED - GRAMMAR = "itn" - - def __init__( - self, - input_case: str = LOWER_CASED, - lang: str = "en", - whitelist: str = None, - cache_dir: str = None, - overwrite_cache: bool = False, - max_number_of_permutations_per_split: int = 729, - ): - """ - Inverse normalizer that converts text from spoken to written form. - Args: - input_case: Input text capitalization, set to 'cased' if text contains capital letters. - This flag affects normalization rules applied to the text. Note, `lower_cased` won't lower case input. - lang: language specifying the ITN - whitelist: path to a file with whitelist replacements. (each line of the file: written_form\tspoken_form\n), - e.g. nemo_text_processing/inverse_text_normalization/en/data/whitelist.tsv - cache_dir: path to a dir with .far grammar file. Set to None to avoid using cache. - overwrite_cache: set to True to overwrite .far files - max_number_of_permutations_per_split: a maximum number - of permutations which can be generated from input sequence of tokens. - """ - if not HAVE_NEMO_TEXT_PROCESSING: - raise RuntimeError( - "In order to use AlignmentPreservingInverseNormalizer, " - "please install the nemo_text_processing and pynini packages." - ) - self.itn_model = InverseNormalizer( - lang=lang, - input_case=input_case, - whitelist=whitelist, - cache_dir=cache_dir, - overwrite_cache=overwrite_cache, - max_number_of_permutations_per_split=max_number_of_permutations_per_split, - ) - if cache_dir and CACHING_FROM_DISK: - self.DISK_TAG_CACHE = diskcache.Cache(os.path.join(cache_dir, "itn_tag_cache")) - self.DISK_VERB_CACHE = diskcache.Cache(os.path.join(cache_dir, "itn_verb_cache")) - self.caching_from_disk_enabled = True - else: - self.DISK_TAG_CACHE = None - self.DISK_VERB_CACHE = None - self.caching_from_disk_enabled = False - - def inverse_normalize_list(self, texts: list[str], params: dict) -> list[str]: - """ - Applies Inverse Text Normalization to the list of texts. - Args: - texts: (list[str]) list of input strings. - params: (dict) dictionary of runtime parameters. - Returns: - (list[str]) Returns converted list of input strings. - """ - normalized_texts = self.itn_model.normalize_list( - texts, - verbose=params.get('verbose', False), - punct_pre_process=params.get("punct_pre_process", False), - punct_post_process=params.get("punct_post_process", False), - batch_size=params.get("batch_size", 1), - n_jobs=params.get("n_jobs", 1), - ) - return normalized_texts - - def verbalize(self, tokens: list, sep: str) -> str | None: - """ - Appplies verbalization to the list of tokens. - Args: - tokens: (list) list of tokens - sep: (str) word separator - Returns: - (str | None) Returns verbalized text. If verbalization fails, returns None. - """ - split_tokens = self.itn_model._split_tokens_to_reduce_number_of_permutations(tokens) - output_str = "" - for s in split_tokens: - try: - tags_reordered = self.itn_model.generate_permutations(s) - verbalizer_lattice = None - for tagged_text_r in tags_reordered: - tagged_text_r = pynini.escape(tagged_text_r) - - verbalizer_lattice = self.itn_model.find_verbalizer(tagged_text_r) - if verbalizer_lattice.num_states() != 0: - break - - if verbalizer_lattice is None: - return None - - verbalized_text = Normalizer.select_verbalizer(verbalizer_lattice) - output_str += sep + verbalized_text - except Exception as e: - logging.warning("Failed to verbalize tagged text: " + str(e)) - return None - - output_str = output_str.strip(sep) - return re.sub(r"({sep})+".format(sep=sep), sep, output_str) - - def tag(self, text: str, no_cache: bool = False) -> str: - """ - Tags the input text. - Args: - text: (str) input text - no_cache: (bool) whether to use cache - Returns: - (str) tagged text - """ - if not no_cache: - # In-memory cache check - if text in IN_MEM_CACHE: - return IN_MEM_CACHE[text] - - # Disk cache check - if self.caching_from_disk_enabled and text in self.DISK_TAG_CACHE: - x = self.DISK_TAG_CACHE[text] - IN_MEM_CACHE[text] = x - return x - - text = text.strip() - if not text: - return text - - text = pynini.escape(text) - tagged_lattice = self.itn_model.find_tags(text) - tagged_text = Normalizer.select_tag(tagged_lattice) - IN_MEM_CACHE[text] = tagged_text - if self.caching_from_disk_enabled: - self.DISK_TAG_CACHE[text] = tagged_text - return tagged_text - - def parse_and_verbalize(self, tagged_text: str, sep: str) -> tuple[str, str]: - """ - Tags and verbalizes the input text. - Args: - tagged_text: (str) tagged input text - sep: (str) word separator - Returns: - (str, str) Returns the verbalized text, and the semiotic class. - """ - - # In-memory cache check - if tagged_text in IN_MEM_CACHE: - return IN_MEM_CACHE[tagged_text] - - # Disk cache check - if self.caching_from_disk_enabled and tagged_text in self.DISK_VERB_CACHE: - x = self.DISK_VERB_CACHE[tagged_text] - IN_MEM_CACHE[tagged_text] = x - return x - - self.itn_model.parser(tagged_text) - tokens = self.itn_model.parser.parse() - span_text = self.verbalize(tokens, sep) - semiotic_class = DEFAULT_SEMIOTIC_CLASS if span_text is None else get_semiotic_class(tokens) - - IN_MEM_CACHE[tagged_text] = (span_text, semiotic_class) - if self.caching_from_disk_enabled: - self.DISK_VERB_CACHE[tagged_text] = (span_text, semiotic_class) - return span_text, semiotic_class - - def find_token_words( - self, token: str, start_idx: int, input_words: list[str], sep: str - ) -> tuple[list[int], bool, int]: - """ - Finds the words that make up the token. - Args: - token: (str) token - start_idx: (int) start index - input_words: (list[str]) list of input words - sep: (str) word separator - Returns: - (tuple) Returns a tuple of indices, success, and the new start index - """ - indices, tmp_text, success = [], "", False - length = len(input_words) - for i in range(start_idx, length): - tmp_text = tmp_text + sep + input_words[i] if tmp_text else input_words[i] - tmp_tagged_text = self.tag(tmp_text) - - if tmp_tagged_text == token: - indices.append(i) - - # Try to extend the token by one word - if i + 1 < length: - extended_tmp_text = tmp_text + sep + input_words[i + 1] - extended_tmp_tagged_text = self.tag(extended_tmp_text) - if extended_tmp_tagged_text == token: - continue - - success = True - break - else: - indices.append(i) - - return indices, success, i - - def find_alignment( - self, - tokens: list[str], - input_words: list[str], - sep: str, - iwords: list[str], - owords: list[str], - word_alignment: list[tuple], - ) -> bool: - """ - Finds the word alignment for the input text. - Args: - tokens: (list[str]) list of tokens - input_words: (list[str]) list of input words - sep: (str) word separator - iwords: (list[str]) list of input words to be updated - owords: (list[str]) list of output words to be updated - word_alignment: (list[tuple]) list of word alignments to be updated - Returns: - (bool) True if the word alignment is found, False otherwise - """ - success = True - token_start_idx = word_start_idx = 0 - iwords_len = owords_len = 0 - - while token_start_idx < len(tokens): - token = tokens[token_start_idx] - current_word = input_words[word_start_idx] - if token == f"tokens {{ name: \"{current_word}\" }}": - word_alignment.append(([iwords_len], [owords_len], DEFAULT_SEMIOTIC_CLASS)) - iwords.append(current_word) - owords.append(current_word) - iwords_len += 1 - owords_len += 1 - else: - indices, success, word_start_idx = self.find_token_words(token, word_start_idx, input_words, sep) - if success: - span_text, semiotic_class = self.parse_and_verbalize(token, sep) - if span_text is None: - logging.warning(f"Failed to verbalize the token: {token}") - return False - - span_words, n_span_words = split_text(span_text, sep) - word_alignment.append( - ( - [iwords_len + i for i in range(len(indices))], - [owords_len + i for i in range(n_span_words)], - semiotic_class, - ) - ) - owords.extend(span_words) - iwords.extend([input_words[i] for i in indices]) - iwords_len += len(indices) - owords_len += n_span_words - else: - success = False - break - - token_start_idx += 1 - word_start_idx += 1 - - return success - - def get_word_alignment(self, input: str | list[str], sep: str) -> tuple[list[str], list[str], list[tuple]]: - """ - Returns a word alignment for the input text. - Args: - input: (str | list[str]) input text or list of input words - sep: (str) word separator - Returns: - (tuple) Returns a tuple of input words, output words, and a word alignment between input and output words - """ - - if isinstance(input, str): - input_text = input - input_words, n_words = split_text(input_text, sep) - else: - input_words, n_words = input, len(input) - input_text = sep.join(input_words) - - # If input_text is empty, return empty lists - if n_words == 0: - return [], [], [] - - # Tag the input text - tagged_text = self.tag(input_text, no_cache=False) - - # Find the tokens in the tagged text - tokens = find_tokens(tagged_text) - - # Find the word alignment - iwords, owords, word_alignment = [], [], [] - success = self.find_alignment( - tokens, input_words, sep, iwords=iwords, owords=owords, word_alignment=word_alignment - ) - - # If the word alignment is not found, fallback to the trivial alignment - if not success: - return fallback_to_trivial_alignment(input_words, i_shift=0, o_shift=0) - - return iwords, owords, word_alignment diff --git a/nemo/collections/asr/inference/model_wrappers/__init__.py b/nemo/collections/asr/inference/model_wrappers/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/model_wrappers/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/asr/inference/model_wrappers/asr_inference_wrapper.py b/nemo/collections/asr/inference/model_wrappers/asr_inference_wrapper.py deleted file mode 100644 index 305ec894b6d264b69ed9781464bbc88782d74bf5..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/model_wrappers/asr_inference_wrapper.py +++ /dev/null @@ -1,285 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import copy -from functools import cached_property -from typing import Callable - -import torch -from omegaconf import DictConfig, open_dict - -from nemo.collections.asr.inference.utils.constants import SENTENCEPIECE_UNDERSCORE -from nemo.collections.asr.inference.utils.device_utils import setup_device -from nemo.collections.asr.inference.utils.pipeline_utils import make_preprocessor_deterministic -from nemo.collections.asr.models import ASRModel, EncDecHybridRNNTCTCModel -from nemo.collections.asr.parts.submodules.ctc_decoding import CTCDecodingConfig -from nemo.collections.asr.parts.submodules.rnnt_decoding import RNNTDecodingConfig -from nemo.collections.asr.parts.utils.asr_confidence_utils import get_confidence_aggregation_bank - -SUPPORTED_CONFIDENCE_AGGREGATORS = get_confidence_aggregation_bank() - - -class ASRInferenceWrapper: - """ - Base class for ASR inference wrappers. - It provides a common interface for ASR inference wrappers. - Derived classes MUST implement the following methods: - - __post_init__: Additional post initialization steps that must be implemented in the derived classes. - - get_blank_id: Returns the blank id for the model. - - get_vocabulary: Returns the vocabulary for the model. - - get_subsampling_factor: Returns the subsampling factor for the model. - """ - - def __init__( - self, - model_name: str, - decoding_cfg: CTCDecodingConfig | RNNTDecodingConfig, - device: str = 'cuda', - device_id: int = 0, - compute_dtype: str = 'bfloat16', - use_amp: bool = True, - ): - """ - Initialize the ASR inference wrapper. - Args: - model_name: (str) path to the model checkpoint or a model name from the NGC cloud. - decoding_cfg: (CTCDecodingConfig | RNNTDecodingConfig) decoding configuration. - device: (str) device to run the model on. - device_id: (int) device ID to run the model on. - compute_dtype: (str) compute dtype to run the model on. - use_amp: (bool) Use Automatic Mixed Precision - """ - - self.decoding_cfg = decoding_cfg - self.device_str, self.device_id, self.compute_dtype = setup_device(device.strip(), device_id, compute_dtype) - self.device = torch.device(self.device_str) - self.use_amp = use_amp - self.asr_model = self.load_model(model_name, self.device) - self.asr_model_cfg = self.asr_model._cfg - self.set_dither_to_zero() - self.tokenizer = self.asr_model.tokenizer - - # post initialization steps that must be implemented in the derived classes - self.__post_init__() - - @staticmethod - def load_model(model_name: str, map_location: torch.device) -> ASRModel: - """ - Load the ASR model. - Args: - model_name: (str) path to the model checkpoint or a model name from the NGC cloud. - map_location: (torch.device) device to load the model on. - Returns: - (ASRModel) loaded ASR model. - """ - try: - if model_name.endswith('.nemo'): - asr_model = ASRModel.restore_from(model_name, map_location=map_location) - else: - asr_model = ASRModel.from_pretrained(model_name, map_location=map_location) - asr_model.eval() - return asr_model - except Exception as e: - raise RuntimeError(f"Failed to load model {model_name}: {str(e)}") - - @property - def word_separator(self) -> str: - """ - Returns word separator. - Returns: - (str) word separator. - """ - return self.decoding_cfg.word_seperator - - @property - def confidence_aggregator(self) -> Callable: - """ - Returns confidence aggregator function. - Returns: - (Callable) confidence aggregator function. - """ - return SUPPORTED_CONFIDENCE_AGGREGATORS[self.decoding_cfg.confidence_cfg.aggregation] - - def copy_asr_config(self) -> DictConfig: - """ - Copies the ASR model config. - Returns: - (DictConfig) copy of the ASR model configuration. - """ - return copy.deepcopy(self.asr_model_cfg) - - def create_preprocessor(self) -> tuple[Callable, DictConfig]: - """ - Creates a deterministic preprocessor from the ASR model configuration. - Disables normalization, dither and padding. - Returns: - (Callable, DictConfig) deterministic preprocessor and its configuration. - """ - new_asr_config = self.copy_asr_config() - new_asr_config = make_preprocessor_deterministic(new_asr_config) - preprocessor_config = copy.deepcopy(new_asr_config.preprocessor) - preprocessor = ASRModel.from_config_dict(preprocessor_config) - preprocessor.to(self.device) - return preprocessor, preprocessor_config - - def supports_capitalization(self) -> bool: - """ - Checks if the ASR model supports capitalization. - Returns: - (bool) True if the ASR model supports capitalization, False otherwise. - """ - return self.tokenizer.supports_capitalization - - def supports_punctuation(self) -> bool: - """ - Checks if the ASR model supports punctuation. - Returns: - (bool) True if the ASR model supports punctuation, False otherwise. - """ - return self.supported_punctuation() != set() - - def supported_punctuation(self) -> set: - """ - Returns supported punctuation symbol set without single quote. - Returns: - (set) Set of supported punctuation symbols. - """ - return self.tokenizer.supported_punctuation - set("'") - - @cached_property - def punctuation_ids(self) -> set: - """ - Returns ids of supported punctuation symbols. - Returns: - (set) Set of punctuation ids. - """ - punctuation_ids = set() - if self.supports_punctuation(): - for punctuation in self.supported_punctuation(): - punctuation_ids.add(self.tokenizer.tokens_to_ids(punctuation)[0]) - return punctuation_ids - - @cached_property - def underscore_id(self) -> int: - """ - Returns id of the underscore token. - Returns: - (int) underscore id for the model. - """ - if getattr(self.asr_model.tokenizer, "spm_separator_id", None) is not None: - return self.asr_model.tokenizer.spm_separator_id - else: - return self.asr_model.tokenizer.tokens_to_ids(SENTENCEPIECE_UNDERSCORE) - - @cached_property - def language_token_ids(self) -> set: - """ - This property is used for some Riva models that have language tokens included in the vocabulary. - Returns: - (set) Set of language token ids. - """ - vocab = self.get_vocabulary() - language_token_ids = set() - for token in vocab: - if token.startswith("<") and token.endswith(">") and token != "": - language_token_ids.add(self.asr_model.tokenizer.tokens_to_ids(token)[0]) - return language_token_ids - - def reset_decoding_strategy(self, decoder_type: str) -> None: - """ - Reset the decoding strategy for the model. - Args: - decoder_type: (str) decoding type either 'ctc', 'rnnt'. - """ - if isinstance(self.asr_model, EncDecHybridRNNTCTCModel): - self.asr_model.change_decoding_strategy(decoding_cfg=None, decoder_type=decoder_type) - else: - self.asr_model.change_decoding_strategy(None) - - def set_decoding_strategy(self, decoder_type: str) -> None: - """ - Set the decoding strategy for the model. - Args: - decoder_type: (str) decoding type either 'ctc', 'rnnt'. - """ - if isinstance(self.asr_model, EncDecHybridRNNTCTCModel): - self.asr_model.change_decoding_strategy(decoding_cfg=self.decoding_cfg, decoder_type=decoder_type) - else: - self.asr_model.change_decoding_strategy(self.decoding_cfg) - - def set_dither_to_zero(self) -> None: - """ - To remove randomness from preprocessor set the dither value to zero. - """ - self.asr_model.preprocessor.featurizer.dither = 0.0 - with open_dict(self.asr_model_cfg): - self.asr_model_cfg.preprocessor.dither = 0.0 - - def get_window_stride(self) -> float: - """ - Get the window stride for the model. - Returns: - (float) window stride for the model. - """ - return self.asr_model_cfg.preprocessor.window_stride - - def get_model_stride(self, in_secs: bool = False, in_milliseconds: bool = False) -> float: - """ - Get the model stride in seconds for the model. - Args: - in_secs: (bool) Whether to return the model stride in seconds. - in_milliseconds: (bool) Whether to return the model stride in milliseconds. - Returns: - (float) model stride in seconds or milliseconds. - """ - if in_secs and in_milliseconds: - raise ValueError("Cannot return both seconds and milliseconds at the same time.") - if in_secs: - return self.get_window_stride() * self.get_subsampling_factor() - if in_milliseconds: - return self.get_window_stride() * self.get_subsampling_factor() * 1000 - - return self.get_window_stride() * self.get_subsampling_factor() - - # Methods that must be implemented in the derived classes. - def __post_init__(self): - """ - Additional post initialization steps that must be implemented in the derived classes. - """ - raise NotImplementedError() - - def get_blank_id(self) -> int: - """ - Returns id of the blank token. - Returns: - (int) blank id for the model. - """ - raise NotImplementedError() - - def get_vocabulary(self) -> list[str]: - """ - Returns the list of vocabulary tokens. - Returns: - (list[str]) list of vocabulary tokens. - """ - raise NotImplementedError() - - def get_subsampling_factor(self) -> int: - """ - Returns the subsampling factor for the model. - Returns: - (int) subsampling factor for the model. - """ - raise NotImplementedError() diff --git a/nemo/collections/asr/inference/model_wrappers/cache_aware_asr_inference_wrapper.py b/nemo/collections/asr/inference/model_wrappers/cache_aware_asr_inference_wrapper.py deleted file mode 100644 index e05c0d029e0b6e4cca9a15e5efbde69f008c670d..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/model_wrappers/cache_aware_asr_inference_wrapper.py +++ /dev/null @@ -1,136 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from typing import Any - -from torch import Tensor - -from nemo.collections.asr.inference.model_wrappers.asr_inference_wrapper import ASRInferenceWrapper - - -class CacheAwareASRInferenceWrapper(ASRInferenceWrapper): - """ - Base class for Cache-Aware inference wrappers. - It provides a common interface for Cache-Aware models. - Derived classes MUST implement the following methods: - - stream_step: Executes a single streaming step. - """ - - def get_input_features(self) -> int: - """ - Returns the number of channels in the input features. - Returns: - (int) number of channels in the input features. - """ - return self.asr_model.encoder._feat_in - - def get_sampling_frames(self) -> list[int] | int | None: - """ - It is used for checking to make sure the audio chunk has enough frames to produce at least one output after downsampling. - Returns: - (list[int] | int | None) sampling frames for the encoder. - """ - self.sampling_frames = None - if hasattr(self.asr_model.encoder, "pre_encode") and hasattr( - self.asr_model.encoder.pre_encode, "get_sampling_frames" - ): - self.sampling_frames = self.asr_model.encoder.pre_encode.get_sampling_frames() - return self.sampling_frames - - def get_initial_cache_state(self, batch_size: int) -> tuple[Tensor, Tensor, Tensor]: - """ - Returns the initial cache state for the encoder. - Returns: - (tuple[Tensor, Tensor, Tensor]) the initial cache state of the encoder. - """ - return self.asr_model.encoder.get_initial_cache_state(batch_size=batch_size) - - def get_drop_extra_pre_encoded(self) -> int: - """ - Returns the number of extra pre-encoded frames to drop. - Returns: - (int) drop_extra_pre_encoded. - """ - return self.asr_model.encoder.streaming_cfg.drop_extra_pre_encoded - - def get_chunk_size(self) -> list[int] | int: - """ - Returns the chunk size for the encoder. - Returns: - (list[int] | int) the chunk size. - """ - return self.asr_model.encoder.streaming_cfg.chunk_size - - def get_shift_size(self) -> list[int] | int: - """ - Returns the shift size for the encoder. - Returns: - (list[int] | int) the shift size. - """ - return self.asr_model.encoder.streaming_cfg.shift_size - - def get_pre_encode_cache_size(self) -> list[int] | int: - """ - Returns the pre-encode cache size for the encoder. - Returns: - (list[int] | int) the pre_encode cache size. - """ - return self.asr_model.encoder.streaming_cfg.pre_encode_cache_size - - def get_subsampling_factor(self) -> int: - """ - Returns the subsampling factor for the ASR encoder. - Returns: - (int) subsampling factor for the ASR encoder model. - """ - return self.asr_model.encoder.subsampling_factor - - def get_att_context_size(self) -> list: - """ - Returns the attention context size for the encoder. - Returns: - (list) copy of the attention context size. - """ - return self.asr_model.encoder.att_context_size.copy() - - def set_default_att_context_size(self, att_context_size: list) -> None: - """ - Set the default attention context size for the encoder. - The list of the supported look-ahead: [[70, 13], [70, 6], [70, 1], [70, 0]] - Args: - att_context_size: (list) the attention context size. - """ - if hasattr(self.asr_model.encoder, "set_default_att_context_size"): - self.asr_model.encoder.set_default_att_context_size(att_context_size=att_context_size) - else: - raise ValueError("Model does not support multiple lookaheads.") - - def setup_streaming_params(self, chunk_size: int, shift_size: int) -> None: - """ - Setup the streaming parameters (chunk_size, shift_size) for the encoder. - Args: - chunk_size: (int) the chunk size. - shift_size: (int) the shift size. - """ - self.asr_model.encoder.setup_streaming_params(chunk_size=chunk_size, shift_size=shift_size) - - def stream_step(self, *args, **kwargs) -> Any: - """ - Executes a single streaming step. - Each derived class must implement this method, with arguments and return types specific to that class. - """ - raise NotImplementedError( - "`stream_step` method is not implemented. It is required for cache-aware transcribers." - ) diff --git a/nemo/collections/asr/inference/model_wrappers/cache_aware_ctc_inference_wrapper.py b/nemo/collections/asr/inference/model_wrappers/cache_aware_ctc_inference_wrapper.py deleted file mode 100644 index d644e2eda14cc13af66a8fef007bcae165251e18..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/model_wrappers/cache_aware_ctc_inference_wrapper.py +++ /dev/null @@ -1,203 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import torch -from torch import Tensor - -from nemo.collections.asr.inference.model_wrappers.cache_aware_asr_inference_wrapper import ( - CacheAwareASRInferenceWrapper, -) -from nemo.collections.asr.inference.utils.context_manager import CacheAwareContext -from nemo.collections.asr.models import EncDecCTCModel, EncDecHybridRNNTCTCModel -from nemo.collections.asr.parts.mixins.streaming import StreamingEncoder - - -class CacheAwareCTCInferenceWrapper(CacheAwareASRInferenceWrapper): - """ - Provides a unified interface to work with Cache-Aware CTC models. - """ - - def __post_init__(self) -> None: - """ - Additional post initialization step - Checks if the model is a ctc model and sets the decoding strategy to ctc. - """ - - if not isinstance(self.asr_model, (EncDecCTCModel, EncDecHybridRNNTCTCModel)): - raise ValueError( - "Provided model is not a CTC type. You are trying to use a CTC Inference with a non-CTC model." - ) - - if not isinstance(self.asr_model.encoder, StreamingEncoder): - raise NotImplementedError("Encoder of this model does not support streaming!") - - decoder_type = 'ctc' - if isinstance(self.asr_model, EncDecHybridRNNTCTCModel): - self.asr_model.cur_decoder = decoder_type - - # reset the decoding strategy - self.reset_decoding_strategy(decoder_type) - self.set_decoding_strategy(decoder_type) - - # setup streaming parameters - if self.asr_model.encoder.streaming_cfg is None: - self.asr_model.encoder.setup_streaming_params() - - self.drop_extra_pre_encoded = self.get_drop_extra_pre_encoded() - - def get_blank_id(self) -> int: - """ - Returns id of the blank token. - Returns: - (int) blank id for the model. - """ - if isinstance(self.asr_model, EncDecCTCModel): - blank_id = len(self.asr_model.decoder.vocabulary) - else: - blank_id = len(self.asr_model.ctc_decoder.vocabulary) - return blank_id - - def get_vocabulary(self) -> list[str]: - """ - Returns the list of vocabulary tokens. - Returns: - (list[str]) list of vocabulary tokens. - """ - if isinstance(self.asr_model, EncDecCTCModel): - return self.asr_model.decoder.vocabulary - else: - return self.asr_model.ctc_decoder.vocabulary - - def execute_step( - self, - processed_signal: Tensor, - processed_signal_length: Tensor, - context: CacheAwareContext, - drop_extra_pre_encoded: int | None, - keep_all_outputs: bool, - drop_left_context: int | None = None, - valid_out_len: int | None = None, - return_tail_result: bool = False, - ) -> tuple[Tensor, Tensor | None, CacheAwareContext]: - """ - Executes a single streaming step. - Args: - processed_signal: (Tensor) input signal tensor. - processed_signal_length: (Tensor) input signal length tensor. - context: (CacheAwareContext) context object. - drop_extra_pre_encoded: (int | None) number of extra pre-encoded frames to drop. - keep_all_outputs: (bool) whether to keep all outputs or not. - drop_left_context: (int | None) number of left context frames to drop. - valid_out_len: (int | None) number of valid output frames. - return_tail_result: (bool) whether to return tail result or not. - Returns: - (tuple[Tensor, Tensor | None, CacheAwareContext]) log probabilities, tail log probabilities and new context. - """ - - ( - encoded, - encoded_len, - cache_last_channel, - cache_last_time, - cache_last_channel_len, - ) = self.asr_model.encoder.cache_aware_stream_step( - processed_signal=processed_signal, - processed_signal_length=processed_signal_length, - cache_last_channel=context.cache_last_channel, - cache_last_time=context.cache_last_time, - cache_last_channel_len=context.cache_last_channel_len, - keep_all_outputs=keep_all_outputs, - drop_extra_pre_encoded=drop_extra_pre_encoded, - ) - - if drop_left_context: - # drop left context - encoded = encoded[:, :, drop_left_context:] - - if isinstance(self.asr_model, EncDecHybridRNNTCTCModel): - all_log_probs = self.asr_model.ctc_decoder(encoder_output=encoded) - else: - all_log_probs = self.asr_model.decoder(encoder_output=encoded) - - tail_log_probs = None - if valid_out_len and not keep_all_outputs: - # drop right context if any - log_probs = all_log_probs[:, :valid_out_len, :] - if return_tail_result: - tail_log_probs = all_log_probs[:, valid_out_len:, :] - else: - log_probs = all_log_probs - - # create a new context - new_context = CacheAwareContext( - cache_last_channel=cache_last_channel, - cache_last_time=cache_last_time, - cache_last_channel_len=cache_last_channel_len, - ) - return log_probs, tail_log_probs, new_context - - def stream_step( - self, - processed_signal: Tensor, - processed_signal_length: Tensor, - context: CacheAwareContext = None, - drop_extra_pre_encoded: int | None = None, - keep_all_outputs: bool = False, - drop_left_context: int | None = None, - valid_out_len: int | None = None, - return_tail_result: bool = False, - ) -> tuple[Tensor, Tensor | None, CacheAwareContext]: - """ - Executes a single streaming step. - Args: - processed_signal: (Tensor) input signal tensor. - processed_signal_length: (Tensor) input signal length tensor. - context: (CacheAwareContext) context object. - drop_extra_pre_encoded: (int | None) number of extra pre-encoded frames to drop. - keep_all_outputs: (bool) whether to keep all outputs or not. - drop_left_context: (int | None) number of left context frames to drop. - valid_out_len: (int | None) number of valid output frames. - return_tail_result: (bool) whether to return tail result or not. - Returns: - (tuple[Tensor, Tensor | None, CacheAwareContext]) log probabilities, tail log probabilities and new context. - """ - - if processed_signal.device != self.device: - processed_signal = processed_signal.to(self.device) - - if processed_signal_length.device != self.device: - processed_signal_length = processed_signal_length.to(self.device) - - if context is None: - # create a dummy context - context = CacheAwareContext() - - with ( - torch.amp.autocast(device_type=self.device_str, dtype=self.compute_dtype, enabled=self.use_amp), - torch.inference_mode(), - torch.no_grad(), - ): - - log_probs, tail_log_probs, new_context = self.execute_step( - processed_signal, - processed_signal_length, - context, - drop_extra_pre_encoded, - keep_all_outputs, - drop_left_context, - valid_out_len, - return_tail_result, - ) - return log_probs, tail_log_probs, new_context diff --git a/nemo/collections/asr/inference/model_wrappers/cache_aware_rnnt_inference_wrapper.py b/nemo/collections/asr/inference/model_wrappers/cache_aware_rnnt_inference_wrapper.py deleted file mode 100644 index 3aedcab10abc84c96411ed6c7e14ce098b1501a9..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/model_wrappers/cache_aware_rnnt_inference_wrapper.py +++ /dev/null @@ -1,195 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import torch -from torch import Tensor - -from nemo.collections.asr.inference.model_wrappers.cache_aware_asr_inference_wrapper import ( - CacheAwareASRInferenceWrapper, -) -from nemo.collections.asr.inference.utils.context_manager import CacheAwareContext -from nemo.collections.asr.models import EncDecHybridRNNTCTCModel, EncDecRNNTModel -from nemo.collections.asr.parts.mixins.streaming import StreamingEncoder -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis - - -class CacheAwareRNNTInferenceWrapper(CacheAwareASRInferenceWrapper): - """ - Provides a unified interface to work with Cache-Aware RNNT models. - """ - - def __post_init__(self) -> None: - """ - Additional post initialization step - Checks if the model is a rnnt model and sets the decoding strategy to rnnt. - """ - if not isinstance(self.asr_model, (EncDecRNNTModel, EncDecHybridRNNTCTCModel)): - raise ValueError( - "Provided model is not a RNNT type. You are trying to use a RNNT Inference with a non-RNNT model." - ) - - if not isinstance(self.asr_model.encoder, StreamingEncoder): - raise NotImplementedError("Encoder of this model does not support streaming!") - - decoder_type = 'rnnt' - if isinstance(self.asr_model, EncDecHybridRNNTCTCModel): - self.asr_model.cur_decoder = decoder_type - - # reset the decoding strategy - self.reset_decoding_strategy(decoder_type) - self.set_decoding_strategy(decoder_type) - - # setup streaming parameters - if self.asr_model.encoder.streaming_cfg is None: - self.asr_model.encoder.setup_streaming_params() - - self.drop_extra_pre_encoded = self.get_drop_extra_pre_encoded() - - def get_blank_id(self) -> int: - """ - Returns id of the blank token. - Returns: - (int) blank id for the model. - """ - blank_id = len(self.asr_model.joint.vocabulary) - return blank_id - - def get_vocabulary(self) -> list[str]: - """ - Returns the list of vocabulary tokens. - Returns: - (list[str]) list of vocabulary tokens. - """ - return self.asr_model.joint.vocabulary - - def execute_step( - self, - processed_signal: Tensor, - processed_signal_length: Tensor, - context: CacheAwareContext, - previous_hypotheses: list[Hypothesis] | None, - drop_extra_pre_encoded: int | None, - keep_all_outputs: bool, - drop_left_context: int | None = None, - valid_out_len: int | None = None, - prompt_vectors: Tensor | None = None, - ) -> tuple[list[Hypothesis], CacheAwareContext]: - """ - Executes a single streaming step. - Args: - processed_signal: (Tensor) input signal tensor. - processed_signal_length: (Tensor) input signal length tensor. - context: (CacheAwareContext) context object. - previous_hypotheses: (list[Hypothesis] | None) list of previous hypotheses for RNNT decoding. - drop_extra_pre_encoded: (int | None) number of extra pre-encoded frames to drop. - keep_all_outputs: (bool) whether to keep all outputs or not. - drop_left_context: (int | None) number of left context frames to drop. - valid_out_len: (int | None) number of valid output frames. - prompt_vectors: (Tensor | None) Optional prompt vectors of shape [B, num_prompts]. - Returns: - (tuple[list[Hypothesis], CacheAwareContext]) best hypothesis and new context. - """ - ( - encoded, - encoded_len, - cache_last_channel, - cache_last_time, - cache_last_channel_len, - ) = self.asr_model.encoder.cache_aware_stream_step( - processed_signal=processed_signal, - processed_signal_length=processed_signal_length, - cache_last_channel=context.cache_last_channel, - cache_last_time=context.cache_last_time, - cache_last_channel_len=context.cache_last_channel_len, - keep_all_outputs=keep_all_outputs, - drop_extra_pre_encoded=drop_extra_pre_encoded, - ) - new_context = CacheAwareContext( - cache_last_channel=cache_last_channel, - cache_last_time=cache_last_time, - cache_last_channel_len=cache_last_channel_len, - ) - - if drop_left_context: - # drop left context - encoded = encoded[:, :, drop_left_context:] - encoded_len = encoded_len - drop_left_context - - if valid_out_len and not keep_all_outputs: - # drop right context if any - encoded = encoded[:, :, :valid_out_len] - encoded_len = torch.ones_like(encoded_len) * valid_out_len - - best_hyp = self.asr_model.decoding.rnnt_decoder_predictions_tensor( - encoded, encoded_len, return_hypotheses=True, partial_hypotheses=previous_hypotheses - ) - return best_hyp, new_context - - def stream_step( - self, - processed_signal: Tensor, - processed_signal_length: Tensor, - context: CacheAwareContext = None, - previous_hypotheses: list[Hypothesis] | None = None, - drop_extra_pre_encoded: int | None = None, - keep_all_outputs: bool = False, - drop_left_context: int | None = None, - valid_out_len: int | None = None, - prompt_vectors: Tensor | None = None, - ) -> tuple[list[Hypothesis], CacheAwareContext]: - """ - Executes a single streaming step. - Args: - processed_signal: (Tensor) input signal tensor. - processed_signal_length: (Tensor) input signal length tensor. - context: (CacheAwareContext) context object. - previous_hypotheses: (list[Hypothesis] | None) list of previous hypotheses for RNNT decoding. - drop_extra_pre_encoded: (int | None) number of extra pre-encoded frames to drop. - keep_all_outputs: (bool) whether to keep all outputs or not. - drop_left_context: (int | None) number of left context frames to drop. - valid_out_len: (int | None) number of valid output frames. - prompt_vectors: (Tensor | None) Optional prompt vectors of shape [B, num_prompts]. - Returns: - (tuple[list[Hypothesis], CacheAwareContext]) best hypothesis and new context. - """ - - if processed_signal.device != self.device: - processed_signal = processed_signal.to(self.device) - - if processed_signal_length.device != self.device: - processed_signal_length = processed_signal_length.to(self.device) - - if context is None: - # create a dummy context - context = CacheAwareContext() - - with ( - torch.amp.autocast(device_type=self.device_str, dtype=self.compute_dtype, enabled=self.use_amp), - torch.inference_mode(), - torch.no_grad(), - ): - - best_hyp, new_context = self.execute_step( - processed_signal, - processed_signal_length, - context, - previous_hypotheses, - drop_extra_pre_encoded, - keep_all_outputs, - drop_left_context, - valid_out_len, - prompt_vectors, - ) - - return best_hyp, new_context diff --git a/nemo/collections/asr/inference/model_wrappers/ctc_inference_wrapper.py b/nemo/collections/asr/inference/model_wrappers/ctc_inference_wrapper.py deleted file mode 100644 index 64304f6611bead0ed8f6bc8422a69467f546b69f..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/model_wrappers/ctc_inference_wrapper.py +++ /dev/null @@ -1,109 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import torch -from torch import Tensor - -from nemo.collections.asr.inference.model_wrappers.asr_inference_wrapper import ASRInferenceWrapper -from nemo.collections.asr.models import EncDecCTCModel, EncDecHybridRNNTCTCModel - - -class CTCInferenceWrapper(ASRInferenceWrapper): - """ - Provides a unified interface to work with CTC/Hybrid-CTC models. - """ - - def __post_init__(self) -> None: - """ - Additional post initialization step - Checks if the model is a ctc model and sets the decoding strategy to ctc. - """ - if not isinstance(self.asr_model, (EncDecCTCModel, EncDecHybridRNNTCTCModel)): - raise ValueError( - "Provided model is not a CTC type. You are trying to use a CTC transcriber with a non-CTC model." - ) - - decoder_type = 'ctc' - if isinstance(self.asr_model, EncDecHybridRNNTCTCModel): - self.asr_model.cur_decoder = decoder_type - - # reset the decoding strategy - self.reset_decoding_strategy(decoder_type) - self.set_decoding_strategy(decoder_type) - - self.cast_dtype = torch.float32 if self.use_amp else self.compute_dtype - self.asr_model.to(self.cast_dtype) - - def get_blank_id(self) -> int: - """ - Returns id of the blank token. - Returns: - (int) blank id for the model. - """ - if isinstance(self.asr_model, EncDecCTCModel): - blank_id = len(self.asr_model.decoder.vocabulary) - else: - blank_id = len(self.asr_model.ctc_decoder.vocabulary) - return blank_id - - def get_vocabulary(self) -> list[str]: - """ - Returns the list of vocabulary tokens. - Returns: - (list[str]) list of vocabulary tokens. - """ - if isinstance(self.asr_model, EncDecCTCModel): - return self.asr_model.decoder.vocabulary - else: - return self.asr_model.ctc_decoder.vocabulary - - def get_subsampling_factor(self) -> int: - """ - Returns the subsampling factor for the ASR encoder. - Returns: - (int) subsampling factor for the ASR encoder model. - """ - return self.asr_model.encoder.subsampling_factor - - def get_logprobs(self, processed_signal: Tensor, processed_signal_length: Tensor) -> Tensor: - """ - Get log probabilities from the model. It is used for streaming inference. - Args: - processed_signal: (Tensor) processed signal. Shape is torch.Size([B, C, T]). - processed_signal_length: (Tensor) processed signal length. Shape is torch.Size([B]). - Returns: - (Tensor) log probabilities. Shape is torch.Size([B, T, V+1]). - """ - if processed_signal.device != self.device: - processed_signal = processed_signal.to(self.device) - - if processed_signal_length.device != self.device: - processed_signal_length = processed_signal_length.to(self.device) - - with ( - torch.amp.autocast(device_type=self.device_str, dtype=self.compute_dtype, enabled=self.use_amp), - torch.inference_mode(), - torch.no_grad(), - ): - - forward_outs = self.asr_model( - processed_signal=processed_signal.to(self.cast_dtype), processed_signal_length=processed_signal_length - ) - - if isinstance(self.asr_model, EncDecHybridRNNTCTCModel): - encoded, encoded_len = forward_outs - log_probs = self.asr_model.ctc_decoder(encoder_output=encoded.clone()) - else: - log_probs, encoded_len, predictions = forward_outs - return log_probs diff --git a/nemo/collections/asr/inference/model_wrappers/rnnt_inference_wrapper.py b/nemo/collections/asr/inference/model_wrappers/rnnt_inference_wrapper.py deleted file mode 100644 index a554b960f0714c03c947abf2d02264cc7682fac2..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/model_wrappers/rnnt_inference_wrapper.py +++ /dev/null @@ -1,147 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import torch -from torch import Tensor - -from nemo.collections.asr.inference.model_wrappers.asr_inference_wrapper import ASRInferenceWrapper -from nemo.collections.asr.models import EncDecHybridRNNTCTCModel, EncDecRNNTModel - - -class RNNTInferenceWrapper(ASRInferenceWrapper): - """ - Provides a unified interface to work with RNNT/TDT/Hybrid models. - """ - - def __post_init__(self) -> None: - """ - Additional post initialization step - Checks if the model is a rnnt model and sets the decoding strategy to rnnt. - """ - if not isinstance(self.asr_model, (EncDecRNNTModel, EncDecHybridRNNTCTCModel)): - raise ValueError( - "Provided model is not a RNNT type. You are trying to use a RNNT transcriber with a non-RNNT model." - ) - - decoder_type = 'rnnt' - if isinstance(self.asr_model, EncDecHybridRNNTCTCModel): - self.asr_model.cur_decoder = decoder_type - - # reset the decoding strategy - self.reset_decoding_strategy(decoder_type) - self.set_decoding_strategy(decoder_type) - - self.cast_dtype = torch.float32 if self.use_amp else self.compute_dtype - self.asr_model.to(self.cast_dtype) - - def get_blank_id(self) -> int: - """ - Returns id of the blank token. - Returns: - (int) blank id for the model. - """ - blank_id = len(self.asr_model.joint.vocabulary) - return blank_id - - def get_vocabulary(self) -> list[str]: - """ - Returns the list of vocabulary tokens. - Returns: - (list[str]) list of vocabulary tokens. - """ - return self.asr_model.joint.vocabulary - - def get_subsampling_factor(self) -> int: - """ - Returns the subsampling factor for the ASR encoder. - Returns: - (int) subsampling factor for the ASR encoder model. - """ - return self.asr_model.encoder.subsampling_factor - - def encode( - self, processed_signal: Tensor, processed_signal_length: Tensor, prompt_vectors: Tensor | None = None - ) -> tuple[Tensor, Tensor]: - """ - Get encoder output from the model. It is used for streaming inference. - Args: - processed_signal: (Tensor) processed signal. Shape is torch.Size([B, C, T]). - processed_signal_length: (Tensor) processed signal length. Shape is torch.Size([B]). - prompt_vectors: (Tensor | None) Optional prompt vectors for multilingual models. - Shape can be torch.Size([B, num_prompts]) or torch.Size([B, T_enc, num_prompts]) if already expanded. - Returns: - (tuple[Tensor, Tensor]) encoder output and encoder output length of shape torch.Size([B, T, D]), torch.Size([B]). - """ - if processed_signal.device != self.device: - processed_signal = processed_signal.to(self.device) - - if processed_signal_length.device != self.device: - processed_signal_length = processed_signal_length.to(self.device) - - with ( - torch.amp.autocast(device_type=self.device_str, dtype=self.compute_dtype, enabled=self.use_amp), - torch.inference_mode(), - torch.no_grad(), - ): - - # Prepare model arguments - model_args = { - 'processed_signal': processed_signal.to(self.cast_dtype), - 'processed_signal_length': processed_signal_length, - } - if prompt_vectors is not None: - model_args['prompt'] = prompt_vectors - - forward_outs = self.asr_model(**model_args) - - encoded, encoded_len = forward_outs - return encoded, encoded_len - - def decode(self, encoded: Tensor, encoded_len: Tensor, partial_hypotheses: list) -> list: - """ - Decode the encoder output using the RNNT decoder. - Args: - encoded: (Tensor) encoder output. - encoded_len: (Tensor) encoder output length. - partial_hypotheses: (list) list of partial hypotheses for stateful decoding. - Returns: - (list) list of best hypotheses. - """ - best_hyp = self.asr_model.decoding.rnnt_decoder_predictions_tensor( - encoded.to(self.cast_dtype), encoded_len, return_hypotheses=True, partial_hypotheses=partial_hypotheses - ) - return best_hyp - - def encode_with_prompts( - self, processed_signal: Tensor, processed_signal_length: Tensor, prompt_vectors: Tensor - ) -> tuple[Tensor, Tensor]: - """ - Convenience wrapper for prompt-enabled encoding. - Expands prompt vectors across the time dimension before calling encode. - Args: - processed_signal: (Tensor) processed signal. Shape is torch.Size([B, C, T]). - processed_signal_length: (Tensor) processed signal length. Shape is torch.Size([B]). - prompt_vectors: (Tensor) prompt vectors. Shape is torch.Size([B, num_prompts]). - Returns: - (tuple[Tensor, Tensor]) encoder output and encoder output length. - """ - encoder_time_steps = processed_signal.shape[2] // self.get_subsampling_factor() - # Expand prompts: [B, num_prompts] -> [B, T_enc, num_prompts] - prompt_vectors = prompt_vectors.unsqueeze(1).expand(-1, encoder_time_steps, -1) - return self.encode( - processed_signal=processed_signal, - processed_signal_length=processed_signal_length, - prompt_vectors=prompt_vectors, - ) diff --git a/nemo/collections/asr/inference/model_wrappers/salm_asr_inference_wrapper.py b/nemo/collections/asr/inference/model_wrappers/salm_asr_inference_wrapper.py deleted file mode 100644 index 5a27b121d55d38cd900386efe0ca50c0b44a43e5..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/model_wrappers/salm_asr_inference_wrapper.py +++ /dev/null @@ -1,166 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from __future__ import annotations - - -from typing import TYPE_CHECKING -import torch - -from nemo.collections.asr.inference.utils.device_utils import setup_device -from nemo.collections.common.prompts import PromptFormatter - -if TYPE_CHECKING: - from nemo.collections.speechlm2.models import SALM - - -class SALMASRInferenceWrapper: - - def __init__( - self, - model_name: str, - device: str = 'cuda', - device_id: int = 0, - compute_dtype: str = 'bfloat16', - use_amp: bool = True, - ): - """ - Initialize the SALM ASR inference wrapper. - Args: - model_name: (str) model name at Hugging Face or NGC cloud. - device: (str) device to run the model on. - device_id: (int) device ID to run the model on. - compute_dtype: (str) compute dtype to run the model on. - use_amp: (bool) Use Automatic Mixed Precision - """ - - self.device_str, self.device_id, self.compute_dtype = setup_device(device.strip(), device_id, compute_dtype) - self.use_amp = use_amp - self.device = torch.device(self.device_str) - self.salm_model = self.load_model(model_name, self.device) - self.audio_locator_tag = self.salm_model.audio_locator_tag - self.tokenizer = self.salm_model.tokenizer - self.set_dither_to_zero() - - @property - def eos_token_ids(self) -> list[int]: - """Returns the end of sentence token ids.""" - return [self.salm_model.text_eos_id] - - @property - def word_separator(self) -> str: - """Returns word separator.""" - return ' ' - - @property - def word_separator_ids(self) -> list[int]: - """Returns the word separator token ids.""" - return self.tokenizer.text_to_ids(self.word_separator) - - @staticmethod - def load_model(model_name: str, device: torch.device) -> SALM: - """ - Load the SALM model. - Args: - model_name: (str) model name at Hugging Face or NGC cloud. - device: (torch.device) device to load the model on. - Returns: - (SALM) loaded SALM model. - """ - try: - from nemo.collections.speechlm2.models import SALM - - model = SALM.from_pretrained(model_name).eval() - model.to(device) - return model - except Exception as e: - raise RuntimeError(f"Failed to load model {model_name}: {str(e)}") - - def get_window_stride(self) -> float: - """Returns the window stride of the model.""" - return self.salm_model.cfg.perception.preprocessor.window_stride - - def get_subsampling_factor(self) -> int: - """Returns the subsampling factor of the model.""" - return self.salm_model.cfg.perception.encoder.subsampling_factor - - def get_model_stride(self, in_secs: bool = False, in_milliseconds: bool = False) -> float: - """ - Returns the model stride in seconds or milliseconds. - Args: - in_secs: (bool) Whether to return the model stride in seconds. - in_milliseconds: (bool) Whether to return the model stride in milliseconds. - Returns: - (float) model stride in seconds or milliseconds. - """ - if in_secs and in_milliseconds: - raise ValueError("Cannot return both seconds and milliseconds at the same time.") - token_duration = self.salm_model.token_equivalent_duration - if in_secs: - return token_duration - if in_milliseconds: - return token_duration * 1000 - return token_duration - - def set_dither_to_zero(self) -> None: - """Sets the dither to zero.""" - self.salm_model.cfg.perception.preprocessor.dither = 0.0 - self.salm_model.perception.preprocessor.featurizer.dither = 0.0 - - def generate( - self, - prompts: list[list[dict[str]]] | torch.Tensor, - audios: torch.Tensor, - audio_lens: torch.Tensor, - max_new_tokens: int = 128, - ) -> torch.Tensor: - """ - Generate the model output. - Args: - prompts: (list[list[dict[str]]] | torch.Tensor) List of prompts or token ids. - audios: (torch.Tensor) Audio tensor of shape (batch_size, num_samples). - audio_lens: (torch.Tensor) Audio length tensor of shape (batch_size). - max_new_tokens: (int) Maximum number of new tokens to generate. - Returns: - (torch.Tensor) Model output. - """ - with ( - torch.amp.autocast(device_type=self.device_str, dtype=self.compute_dtype, enabled=self.use_amp), - torch.inference_mode(), - torch.no_grad(), - ): - answer_ids = self.salm_model.generate( - prompts=prompts, - audios=audios, - audio_lens=audio_lens, - max_new_tokens=max_new_tokens, - ) - return answer_ids - - def preprocess_prompts(self, prompts: list[list[dict[str]]]) -> torch.Tensor: - """ - Convert the prompts to token ids. - Args: - prompts: (list[list[dict[str]]]) List of prompts. - Returns: - (torch.Tensor) Token ids of size (batch_size, max_prompt_length). - """ - from nemo.collections.speechlm2.data.salm_dataset import left_collate_vectors - - formatter = PromptFormatter.resolve(self.salm_model.cfg.prompt_format)(self.tokenizer) - tokens = left_collate_vectors( - [formatter.encode_dialog(turns=prompt)["input_ids"] for prompt in prompts], - padding_value=self.salm_model.text_pad_id, - ).to(self.device) - return tokens diff --git a/nemo/collections/asr/inference/nmt/__init__.py b/nemo/collections/asr/inference/nmt/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/nmt/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/asr/inference/nmt/llm_translator.py b/nemo/collections/asr/inference/nmt/llm_translator.py deleted file mode 100644 index f4fb4e9b96a7fbb0bb78db863c4ddd1528f1f98a..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/nmt/llm_translator.py +++ /dev/null @@ -1,296 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import os -import string - -import torch -from omegaconf import DictConfig, OmegaConf - -from nemo.collections.asr.inference.nmt.prompts import EuroLLMTranslatorPromptTemplate, PromptTemplate - -try: - from vllm import LLM, SamplingParams -except ImportError as e: - raise ImportError("Failed to import vLLM.") from e - -from nemo.utils import logging - -EURO_LLM_INSTRUCT_SMALL = "utter-project/EuroLLM-1.7B-Instruct" -EURO_LLM_INSTRUCT_LARGE = "utter-project/EuroLLM-9B-Instruct" -SUPPORTED_TRANSLATION_MODELS = [EURO_LLM_INSTRUCT_SMALL, EURO_LLM_INSTRUCT_LARGE] - - -class LLMTranslator: - """ - A vLLM-based LLM translator for ASR transcripts. - It takes ASR transcripts and prefixes to start translation from, and returns corresponding continuations of translations. - """ - - def __init__( - self, - model_name: str, - source_language: str, - target_language: str, - waitk: int = -1, - device: str = "cuda", - device_id: int = 0, - batch_size: int = -1, - llm_params: dict | DictConfig | None = None, - sampling_params: dict | DictConfig | None = None, - ): - """ - A model for translating ASR transcripts with LLM. - Args: - model_name: (str) path to the model name on HuggingFace. - source_language: (str) source language - target_language: (str) target language - waitk: (int) sets the maximum number of words the translation is allowed to lag behind the ASR transcript. - If the translation falls more than waitk words behind, it automatically extends the prefix - using the current translation. -1 disables this rule and relies on the longest common prefix (LCP) - between current and previous translations. Larger values of waitk lead to more coherent translations, - but the cost of generating the translation increases, because the model needs to generate more tokens. - device: (str) device to run the model on - device_id: (int) device ID to run the model on - batch_size: (int) batch size for the LLM model, in case of -1, the batch size is set to the number of ASR transcripts - llm_params: (dict | DictConfig | None) parameters for the LLM model - sampling_params: (dict | DictConfig | None) parameters for the sampling - """ - self.model_name = model_name - if model_name not in SUPPORTED_TRANSLATION_MODELS: - raise ValueError( - f"Model {model_name} is not supported for translation. Supported models are: {SUPPORTED_TRANSLATION_MODELS}" - ) - - llm_params = self.convert_to_dict(llm_params) - sampling_params = self.convert_to_dict(sampling_params) - - self.device_str, self.device_id = self.setup_device(device, device_id) - - self.batch_size = batch_size - self.split_batch = self.batch_size > 0 - - self.nmt_model = self.load_model(llm_params) - self.sampling_params = SamplingParams(**sampling_params) - - self.source_language = source_language - self.target_language = target_language - self.prompt_template = self.get_prompt_template(model_name) - self.waitk = waitk - - @staticmethod - def convert_to_dict(params: dict | DictConfig | None) -> dict: - """ - Convert DictConfig to dict. - Args: - params: (dict | DictConfig | None) parameters to convert - Returns: - dict: converted parameters - """ - if params is None: - return dict() - if isinstance(params, DictConfig): - return OmegaConf.to_container(params) - return params - - @staticmethod - def setup_device(device: str, device_id: int) -> tuple[str, int]: - """ - Setup device for the LLM model. - Args: - device: (str) device to run the model on - device_id: (int) device ID to run the model on - Returns: - device_str: (str) device string, e.g. "cuda:1" - device_id: (int) device ID, e.g. 1 - Raises: - ValueError: if device is not supported, or CUDA is not available - """ - if device == "cpu": - raise ValueError("Currently, CPU is not supported for vLLM.") - - if device == "cuda": - if not torch.cuda.is_available(): - raise ValueError("CUDA is not available.") - - if device_id >= torch.cuda.device_count(): - logging.warning(f"Device ID {device_id} is not available. Using GPU 0 instead.") - device_id = 0 - - device_str = f"cuda:{device_id}" - return device_str, device_id - - raise ValueError(f"Unsupported device: {device}") - - @staticmethod - def get_prompt_template(model_name: str) -> PromptTemplate: - """ - Returns prompt template for the LLM model. - Args: - model_name: (str) name of the model to get prompt template for - Returns: - PromptTemplate: prompt template for the LLM model - Raises: - ValueError: if model is not supported for translation - """ - if model_name in [EURO_LLM_INSTRUCT_SMALL, EURO_LLM_INSTRUCT_LARGE]: - return EuroLLMTranslatorPromptTemplate - - raise ValueError( - f"Model {model_name} is not supported for translation. Supported models are: {SUPPORTED_TRANSLATION_MODELS}" - ) - - def load_model(self, llm_params: dict) -> LLM: - """ - Load NMT model in vLLM format. - Args: - llm_params: (dict) parameters for the LLM model - Returns: - Loaded LLM instance. - Raises: - RuntimeError: If model loading fails. - """ - try: - os.environ["CUDA_VISIBLE_DEVICES"] = str(self.device_id) - model = LLM(model=self.model_name, **llm_params) - return model - except Exception as e: - raise RuntimeError(f"Model loading failed: {str(e)}") - - def translate_batch( - self, - asr_transcripts: list[str], - prefixes: list[str], - src_langs: list[str], - tgt_langs: list[str], - src_contexts: list[str], - tgt_contexts: list[str], - ) -> list[str]: - """ - Translate ASR transcripts starting from pre-defined prefixes in target language. - Args: - asr_transcripts: (list[str]) batch of ASR transcripts to be translated - prefixes: (list[str]) batch of prefixes to start translation from - src_langs: (list[str]) batch of source languages - tgt_langs: (list[str]) batch of target languages - src_contexts: (list[str]) batch of source contexts - tgt_contexts: (list[str]) batch of target contexts - Returns: - list[str] translations of ASR transcripts - """ - input_texts = [] - for src_lang, tgt_lang, src_prefix, tgt_prefix, src_context, tgt_context in zip( - src_langs, tgt_langs, asr_transcripts, prefixes, src_contexts, tgt_contexts - ): - text = self.prompt_template.format(src_lang, tgt_lang, src_prefix, tgt_prefix, src_context, tgt_context) - input_texts.append(text) - - outputs = self.nmt_model.generate(input_texts, self.sampling_params, use_tqdm=False) - translations = [] - for tgt_prefix, output in zip(prefixes, outputs): - output_text = output.outputs[0].text - output_text = self.prompt_template.extract(output_text) - translations.append(f"{tgt_prefix}{output_text}") - return translations - - def translate( - self, - asr_transcripts: list[str], - prefixes: list[str], - src_langs: list[str], - tgt_langs: list[str], - src_contexts: list[str], - tgt_contexts: list[str], - ) -> list[str]: - """ - Translate ASR transcript starting from pre-defined prefix in target language. - Args: - asr_transcripts: (list[str]) ASR transcripts to be translated - prefixes: (list[str]) prefixes to start translation from - src_langs: (list[str]) source languages - tgt_langs: (list[str]) target languages - src_contexts: (list[str]) source contexts - tgt_contexts: (list[str]) target contexts - Returns: - list[str] translations of ASR transcripts - """ - all_translations = [] - n_requests = len(asr_transcripts) - bs = self.batch_size if self.split_batch else n_requests - for i in range(0, n_requests, bs): - all_translations.extend( - self.translate_batch( - asr_transcripts=asr_transcripts[i : i + bs], - prefixes=prefixes[i : i + bs], - src_langs=src_langs[i : i + bs], - tgt_langs=tgt_langs[i : i + bs], - src_contexts=src_contexts[i : i + bs], - tgt_contexts=tgt_contexts[i : i + bs], - ) - ) - return all_translations - - def get_prefixes( - self, - asr_transcripts: list[str], - translations: list[str], - prev_translations: list[str], - ) -> list[str]: - """ - Generates new prefixes in target language for the next translation step. - Args: - asr_transcripts: (list[str]) current ASR transcripts to be translated - translations: (list[str]) translations obtained with LLM on current step - prev_translations: (list[str]) translations obtained with LLM on previous step - Returns: - list[str] new prefixes for LLM translation - """ - - new_prefixes = [] - for asr, trans, prev_trans in zip(asr_transcripts, translations, prev_translations): - - # Longest common prefix of translations on current and previous steps - lcp = os.path.commonprefix([prev_trans, trans]) - had_leading_space = lcp.startswith(" ") - - # If lcp happens mid-word, remove generated ending up to the first full word - if (len(lcp) > 0) and (lcp[-1] not in f"{string.punctuation} "): - lcp = " ".join(lcp.split()[:-1]) - - # Remove trailing whitespaces - lcp = lcp.strip() - - # Remove hallucinations if ASR transcript is empty string - if len(asr) == 0: - lcp = "" - - # If the LLM-generated translations disagree too much between steps, - # and the translation falls more than waitk words behind the ASR transcript, - # the algorithm forcibly advances the prefix based on the current translation. - n_asr_words = len(asr.split()) - n_lcp_words = len(lcp.split()) - if (self.waitk > 0) and (n_asr_words - n_lcp_words > self.waitk): - num_words_to_pick = n_asr_words - self.waitk - new_prefix = " ".join(trans.split()[:num_words_to_pick]) - else: - new_prefix = lcp - - # Preserve leading space if it was present in the previous translation - if len(new_prefix) > 0 and had_leading_space and not new_prefix.startswith(" "): - new_prefix = " " + new_prefix - - new_prefixes.append(new_prefix) - - return new_prefixes diff --git a/nemo/collections/asr/inference/nmt/prompts.py b/nemo/collections/asr/inference/nmt/prompts.py deleted file mode 100644 index c2f62a5ebae861a88298303a8c4266610e0f1c73..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/nmt/prompts.py +++ /dev/null @@ -1,96 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import re -from abc import ABC, abstractmethod - - -class PromptTemplate(ABC): - """ - Base class for prompt templates. - Derived classes should implement the format and extract methods. - - format: format the prompt template with the given arguments - - extract: extract the answer from the response - """ - - @classmethod - @abstractmethod - def format(cls, **kwargs) -> str: - """ - Format the prompt template with the given arguments. - """ - raise NotImplementedError() - - @classmethod - @abstractmethod - def extract(cls, response: str) -> str: - """ - Extract the answer from the response. - """ - raise NotImplementedError() - - -class EuroLLMTranslatorPromptTemplate(PromptTemplate): - """ - Provides a prompt template for the EuroLLM model to perform translation. - """ - - PROMPT_TEMPLATE = ( - "<|im_start|>system\n<|im_end|>\n" - "<|im_start|>user\n" - "Translate the following {src_lang} source text to {tgt_lang}. Always output text in the {tgt_lang} language:\n" - "{src_lang}: {src_text}\n" - "{tgt_lang}: <|im_end|>\n" - "<|im_start|>assistant\n" - "{tgt_text}" - ) - - @classmethod - def format( - cls, - src_lang: str, - tgt_lang: str, - src_prefix: str, - tgt_prefix: str, - src_context: str = "", - tgt_context: str = "", - ) -> str: - """ - Generate a translation prompt for the EuroLLM model. - Args: - src_lang (str): Source language name. - tgt_lang (str): Target language name. - src_prefix (str): Source text to translate. - tgt_prefix (str): Optional target prefix or placeholder for completion. - src_context (str): Optional source context to start translation from. - tgt_context (str): Optional target context to start translation from. - Returns: - str: Formatted translation prompt. - """ - src_text = f"{src_context} {src_prefix}" - tgt_text = f"{tgt_context} {tgt_prefix}" - src_text = re.sub(r'\s+', ' ', src_text).strip() - tgt_text = re.sub(r'\s+', ' ', tgt_text).strip() - return cls.PROMPT_TEMPLATE.format(src_lang=src_lang, tgt_lang=tgt_lang, src_text=src_text, tgt_text=tgt_text) - - @classmethod - def extract(cls, response: str) -> str: - """ - Extract the first line of text from a model response. - Args: - response (str): The full response from the model. - Returns: - str: The text before the first newline. - """ - return response.split('\n')[0] diff --git a/nemo/collections/asr/inference/pipelines/__init__.py b/nemo/collections/asr/inference/pipelines/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/pipelines/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/asr/inference/pipelines/base_pipeline.py b/nemo/collections/asr/inference/pipelines/base_pipeline.py deleted file mode 100644 index 07669989d307ef0b90819a1837aae0799afde066..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/pipelines/base_pipeline.py +++ /dev/null @@ -1,642 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from __future__ import annotations - -import json -import os -import re -from abc import abstractmethod -from dataclasses import dataclass -from typing import TYPE_CHECKING, Iterable - -import torch -from omegaconf import DictConfig -from torch import Tensor - -from nemo.collections.asr.inference.model_wrappers.asr_inference_wrapper import ASRInferenceWrapper -from nemo.collections.asr.inference.pipelines.pipeline_interface import PipelineInterface -from nemo.collections.asr.inference.streaming.buffering.audio_bufferer import BatchedAudioBufferer -from nemo.collections.asr.inference.streaming.buffering.cache_feature_bufferer import BatchedCacheFeatureBufferer -from nemo.collections.asr.inference.streaming.buffering.feature_bufferer import BatchedFeatureBufferer -from nemo.collections.asr.inference.streaming.framing.multi_stream import ContinuousBatchedRequestStreamer -from nemo.collections.asr.inference.streaming.framing.request import FeatureBuffer, Frame, Request -from nemo.collections.asr.inference.streaming.framing.request_options import ASRRequestOptions -from nemo.collections.asr.inference.streaming.state.state import StreamingState -from nemo.collections.asr.inference.streaming.text.text_processing import StreamingTextProcessor -from nemo.collections.asr.inference.utils.bpe_decoder import BPEDecoder -from nemo.collections.asr.inference.utils.context_manager import CacheAwareContextManager -from nemo.collections.asr.inference.utils.enums import RequestType -from nemo.collections.asr.inference.utils.pipeline_utils import ( - check_existance_of_required_attributes, - get_leading_punctuation_regex_pattern, - ids_to_text_without_stripping, -) -from nemo.collections.asr.inference.utils.progressbar import ProgressBar -from nemo.collections.asr.inference.utils.text_segment import TextSegment -from nemo.collections.common.tokenizers.tokenizer_spec import TokenizerSpec - -if TYPE_CHECKING: - from nemo.collections.asr.inference.itn.inverse_normalizer import AlignmentPreservingInverseNormalizer - from nemo.collections.asr.inference.nmt.llm_translator import LLMTranslator - - -@dataclass -class TranscribeStepOutput: - """ - Stores the output of a single transcribe step. - """ - - stream_id: int - # Final transcript is the transcript generated started from the previous EoU to the current EoU - # It is finalized transcript, optionally punctuated and ITN-normalized. It's not subject to further modifications. - # Final segments contains metadata for each word/segment in the final transcript. - final_transcript: str = "" - final_segments: list[TextSegment] | None = None - final_translation: str = "" - # Partial transcript is the transcript generated started from the previous EoU up to the current frame - # It is not finalized transcript, it may be subject to further modifications. - # It can also contain transcript from future frames. - partial_transcript: str = "" - partial_translation: str = "" - # Current step transcript/translation is the transcript/translation generated from the current frame - current_step_transcript: str = "" - current_step_translation: str = "" - - @classmethod - def from_state(cls, state: StreamingState, request: Request, sep: str = ' ') -> 'TranscribeStepOutput': - """ - Create a TranscribeStepOutput from a StreamingState - Args: - state (StreamingState): The state to create the output from. - request (Request): The request to create the output from. - sep (str): The separator for the text postprocessor. - Returns: - TranscribeStepOutput: The output for the step. - """ - final_transcript = state.final_transcript.strip() - final_segments = [seg.copy() for seg in state.final_segments] - if len(final_segments) > 0: - final_segments[0].text = final_segments[0].text.lstrip(sep) - final_segments[-1].text = final_segments[-1].text.rstrip(sep) - - if final_transcript: - separator = '' - if not request.is_first and state.concat_with_space: - separator = sep - final_transcript = separator + final_transcript - if len(final_segments) > 0: - final_segments[0].text = separator + final_segments[0].text - return cls( - stream_id=request.stream_id, - final_transcript=final_transcript, - final_segments=final_segments, - partial_transcript=state.partial_transcript, - current_step_transcript=state.current_step_transcript, - ) - - def __str__(self) -> str: - """ - Return a string representation of the TranscribeStepOutput - """ - info = { - "final_transcript": self.final_transcript, - "final_translation": self.final_translation, - "partial_transcript": self.partial_transcript, - "partial_translation": self.partial_translation, - "current_step_transcript": self.current_step_transcript, - } - return json.dumps(info, indent=4, ensure_ascii=False) - - -class BasePipeline(PipelineInterface): - """ - Base class for all pipelines. - """ - - def __init__(self): - """Initialize state pool to store the state for each stream""" - self._state_pool: dict[int, StreamingState] = {} - - def get_state(self, stream_id: int) -> StreamingState: - """Retrieve state for a given stream ID.""" - return self._state_pool.get(stream_id, None) - - def get_states(self, stream_ids: Iterable[int]) -> list[StreamingState]: - """Retrieve states for a list of stream IDs.""" - return [self.get_state(stream_id) for stream_id in stream_ids] - - def delete_state(self, stream_id: int) -> None: - """Delete the state from the state pool.""" - if stream_id in self._state_pool: - del self._state_pool[stream_id] - - def delete_states(self, stream_ids: Iterable[int]) -> None: - """Delete states for a list of stream IDs.""" - for stream_id in stream_ids: - self.delete_state(stream_id) - - def init_state(self, stream_id: int, options: ASRRequestOptions) -> StreamingState: - """Initialize the state of the stream""" - if stream_id not in self._state_pool: - state = self.create_state(options) - self._state_pool[stream_id] = state - return self._state_pool[stream_id] - - def reset_session(self) -> None: - """Reset the frame buffer and internal state pool""" - self._state_pool.clear() - - def open_session(self) -> None: - """Start a new session by resetting the internal state pool""" - self.reset_session() - - def close_session(self) -> None: - """Close the session by resetting the internal state pool""" - self.reset_session() - - @abstractmethod - def transcribe_step_for_frames(self, frames: list[Frame]) -> None: - """Transcribe a step for frames""" - pass - - @abstractmethod - def transcribe_step_for_feature_buffers(self, fbuffers: list[FeatureBuffer]) -> None: - """Transcribe a step for feature buffers""" - pass - - @abstractmethod - def get_request_generator(self) -> ContinuousBatchedRequestStreamer: - """Return the request generator.""" - pass - - @abstractmethod - def get_sep(self) -> str: - """Return the separator for the text postprocessor.""" - pass - - def translate_step(self, states: list[StreamingState], step_outputs: list[TranscribeStepOutput]) -> None: - """ - Translate step - Args: - states (list[StreamingState]): List of StreamingState objects. - step_outputs (list[TranscribeStepOutput]): List of TranscribeStepOutput objects. - """ - src_langs, tgt_langs = [], [] - asr_transcripts, current_prefixes, previous_translations = [], [], [] - final_transcript_mask = [] - states_to_translate = [] - - src_contexts, tgt_contexts = [], [] - for state, step_output in zip(states, step_outputs): - if not state.options.enable_nmt: - continue - - src_lang = state.options.source_language - tgt_lang = state.options.target_language - if not src_lang or not tgt_lang: - raise ValueError("Source and target languages must be set when NMT is enabled") - - final = step_output.final_transcript - partial = step_output.partial_transcript - if not (final.strip() or partial.strip()): - continue - - transcript = final or partial - is_final = bool(final) - prev_translation, prefix = state.previous_translation_info - - states_to_translate.append((state, step_output)) - src_langs.append(src_lang) - tgt_langs.append(tgt_lang) - asr_transcripts.append(transcript) - current_prefixes.append(prefix) - previous_translations.append(prev_translation) - final_transcript_mask.append(is_final) - - src_context, tgt_context = state.previous_context - src_contexts.append(src_context) - tgt_contexts.append(tgt_context) - - if len(states_to_translate) == 0: - return - - translations = self.nmt_model.translate( - asr_transcripts, current_prefixes, src_langs, tgt_langs, src_contexts, tgt_contexts - ) - new_prefixes = self.nmt_model.get_prefixes(asr_transcripts, translations, previous_translations) - - for (state, step_output), translation, new_prefix, prev_prefix, is_final in zip( - states_to_translate, translations, new_prefixes, current_prefixes, final_transcript_mask - ): - if is_final: - step_output.final_translation = translation - step_output.partial_translation = "" - state.cleanup_translation_info_after_eou() - state.set_translation_context(step_output.final_transcript, translation) - new_prefix = translation - else: - step_output.partial_translation = translation - step_output.final_translation = "" - state.set_translation_info(translation, new_prefix) - - lcp = os.path.commonprefix([prev_prefix, new_prefix]) - step_output.current_step_translation = new_prefix[len(lcp) :] - - def transcribe_step(self, requests: list[Request]) -> list[TranscribeStepOutput]: - """ - Transcribe step - Args: - requests (list[Request]): List of Request objects. - Returns: - list[TranscribeStepOutput]: List of TranscribeStepOutput objects. - """ - - # Initialize the state if it is the first request for the stream - states = [] - for request in requests: - if request.is_first: - self.init_state(request.stream_id, request.options) - states.append(self.get_state(request.stream_id)) - - # Perform the transcribe step for the frames or feature buffers - if isinstance(requests[0], Frame): - self.transcribe_step_for_frames(frames=requests) - elif isinstance(requests[0], FeatureBuffer): - self.transcribe_step_for_feature_buffers(fbuffers=requests) - else: - raise ValueError(f"Invalid request type: {type(requests[0])}") - - # Create current step output for each request - outputs = [] - sep = self.get_sep() - for request, state in zip(requests, states): - step_output = TranscribeStepOutput.from_state(state=state, request=request, sep=sep) - outputs.append(step_output) - - # Perform the translation step - if self.nmt_enabled: - self.translate_step(states=states, step_outputs=outputs) - - # Cleanup the states after the response is sent - # If last request, delete state from the state pool to free memory - for state, request in zip(states, requests): - state.cleanup_after_response() - if request.is_last: - self.delete_state(request.stream_id) - return outputs - - def copy_asr_model_attributes(self, asr_model: ASRInferenceWrapper) -> None: - """ - Copy the attributes from the ASR model - Args: - asr_model (ASRInferenceWrapper): ASR model to copy the attributes from. - """ - self.asr_model = asr_model - self.tokenizer = asr_model.tokenizer - self.device = asr_model.device - self.supports_punctuation = asr_model.supports_punctuation() - self.asr_supported_puncts = asr_model.supported_punctuation() - self.leading_regex_pattern = get_leading_punctuation_regex_pattern(self.asr_supported_puncts) - self.blank_id = asr_model.get_blank_id() - self.vocabulary = asr_model.get_vocabulary() - self.sep = asr_model.word_separator - self.underscore_id = asr_model.underscore_id - self.punctuation_ids = asr_model.punctuation_ids - self.language_token_ids = asr_model.language_token_ids - self.preprocessor, self.preprocessor_config = asr_model.create_preprocessor() - self.subsampling_factor = asr_model.get_subsampling_factor() - self.window_stride = asr_model.get_window_stride() - self.model_stride_in_secs = asr_model.get_model_stride(in_secs=True) - self.model_stride_in_milliseconds = asr_model.get_model_stride(in_milliseconds=True) - - def update_partial_transcript( - self, requests: list[Request], tokenizer: TokenizerSpec, leading_regex_pattern: str - ) -> None: - """ - Update partial and current step transcripts from the state. - Args: - requests (list[Request]): List of Request objects. - tokenizer (TokenizerSpec): Used to convert tokens into text - leading_regex_pattern (str): Regex pattern for the punctuation marks. - """ - word_separator = self.get_sep() - for request in requests: - state = self.get_state(request.stream_id) - # state tokens represent all tokens accumulated since the EOU - # incomplete segment tokens are the remaining tokens on the right side of the buffer after EOU - all_tokens = state.tokens + state.incomplete_segment_tokens - if len(all_tokens) > 0: - pt_string = ids_to_text_without_stripping(all_tokens, tokenizer, word_separator) - if leading_regex_pattern: - pt_string = re.sub(leading_regex_pattern, r'\1', pt_string) - state.partial_transcript = pt_string - else: - state.partial_transcript = "" - - current_step_tokens = state.current_step_tokens - if len(current_step_tokens) > 0: - step_transcript = ids_to_text_without_stripping(current_step_tokens, tokenizer, word_separator) - state.current_step_transcript = step_transcript - else: - state.current_step_transcript = "" - - def init_bpe_decoder(self) -> None: - """Initialize the BPE decoder""" - check_existance_of_required_attributes( - self, - [ - 'vocabulary', - 'tokenizer', - 'confidence_aggregator', - 'asr_supported_puncts', - 'word_boundary_tolerance', - 'model_stride_in_secs', - ], - ) - - self.bpe_decoder = BPEDecoder( - vocabulary=self.vocabulary, - tokenizer=self.tokenizer, - confidence_aggregator=self.confidence_aggregator, - asr_supported_puncts=self.asr_supported_puncts, - word_boundary_tolerance=self.word_boundary_tolerance, - token_duration_in_secs=self.model_stride_in_secs, - ) - - def init_text_processor( - self, - cfg: DictConfig, - itn_model: AlignmentPreservingInverseNormalizer | None, - ) -> None: - """ - Initialize the text processor. - Args: - cfg: (DictConfig) Configuration parameters. - itn_model: (AlignmentPreservingInverseNormalizer | None) Inverse Text Normalization model. - """ - check_existance_of_required_attributes( - self, - [ - 'asr_supported_puncts', - 'supports_punctuation', - 'confidence_aggregator', - 'sep', - ], - ) - - self.text_processor = StreamingTextProcessor( - itn_cfg=cfg.itn, - itn_model=itn_model, - asr_supported_puncts=self.asr_supported_puncts, - asr_supports_punctuation=self.supports_punctuation, - confidence_aggregator=self.confidence_aggregator, - sep=self.sep, - enable_pnc=cfg.enable_pnc, - enable_itn=cfg.enable_itn, - ) - - def init_nmt_model(self, nmt_model: LLMTranslator | None) -> None: - """ - Initialize the Translation model. - Args: - nmt_model: (LLMTranslator | None) LLM based translation model. - """ - self.nmt_model = nmt_model - self.nmt_enabled = nmt_model is not None - - def init_bufferer_for_buffered_streaming(self) -> None: - """Initialize the bufferer.""" - check_existance_of_required_attributes( - self, - [ - 'request_type', - 'sample_rate', - 'buffer_size_in_secs', - 'preprocessor_config', - 'device', - ], - ) - - if self.request_type is RequestType.FEATURE_BUFFER: - # Feature buffering: It will be used when the input is feature buffers - self.bufferer = BatchedFeatureBufferer( - sample_rate=self.sample_rate, - buffer_size_in_secs=self.buffer_size_in_secs, - preprocessor_cfg=self.preprocessor_config, - device=self.device, - ) - elif self.request_type is RequestType.FRAME: - # Audio buffering: It will be used when the input is audio frames - self.bufferer = BatchedAudioBufferer( - sample_rate=self.sample_rate, buffer_size_in_secs=self.buffer_size_in_secs - ) - else: - raise ValueError(f"Unknown request type: {self.request_type}") - - def init_bufferer_for_cache_aware_streaming(self) -> None: - """Initialize the bufferer for cache-aware streaming.""" - check_existance_of_required_attributes( - self, - [ - 'num_slots', - 'use_feat_cache', - 'chunk_size_in_secs', - 'buffer_size_in_secs', - 'sample_rate', - 'preprocessor_config', - 'device', - ], - ) - - if self.use_feat_cache: - # Only calculate mel-spec features for last chunk - chunk_size_for_feature_buffer = self.chunk_size_in_secs - else: - # Calculate mel-spec features for the whole buffer - chunk_size_for_feature_buffer = self.buffer_size_in_secs - - self.bufferer = BatchedCacheFeatureBufferer( - num_slots=self.num_slots, - sample_rate=self.sample_rate, - buffer_size_in_secs=self.buffer_size_in_secs, - chunk_size_in_secs=chunk_size_for_feature_buffer, - preprocessor_cfg=self.preprocessor_config, - device=self.device, - ) - - def init_context_manager(self) -> None: - """Initialize the context manager.""" - check_existance_of_required_attributes(self, ['asr_model', 'num_slots', 'use_cache']) - self.context_manager = CacheAwareContextManager( - cache_aware_model=self.asr_model, num_slots=self.num_slots, use_cache=self.use_cache - ) - - def init_prompt_support(self) -> None: - """Initialize prompt support for multilingual models.""" - self.prompt_enabled = hasattr(self.asr_model.asr_model, 'concat') and self.asr_model.asr_model.concat - - if self.prompt_enabled: - self._prompt_config = self._load_prompt_config() - - def _load_prompt_config(self) -> dict: - """ - Load prompt configuration from model. - Returns: - (dict) Prompt configuration containing num_prompts, prompt_dict, and compute_dtype. - """ - cfg = self.asr_model.asr_model.cfg - if cfg and hasattr(cfg, 'model_defaults'): - model_defaults = cfg.model_defaults - num_prompts = model_defaults.get('num_prompts', None) - prompt_dict = model_defaults.get('prompt_dictionary', None) - - # Validate and convert types once - num_prompts_int = int(num_prompts) if num_prompts is not None else 0 - - is_dict_like = isinstance(prompt_dict, dict) or ( - hasattr(prompt_dict, 'get') and hasattr(prompt_dict, '__contains__') - ) - - if num_prompts_int > 0 and is_dict_like: - return { - 'num_prompts': num_prompts_int, - 'prompt_dict': prompt_dict, - 'compute_dtype': getattr(self.asr_model.asr_model, 'dtype', torch.float32), - } - - return {} - - def _resolve_prompt_index(self, language_code: str) -> int: - """ - Resolve language_code to a strict prompt index; raise if invalid. - Args: - language_code: (str) Language code to resolve (e.g., "en-US", "es-ES"). - Returns: - (int) Prompt index corresponding to the language code. - Raises: - RuntimeError: If prompt configuration is missing. - ValueError: If language_code is not found in prompt dictionary. - """ - if not hasattr(self, '_prompt_config') or not self._prompt_config: - raise RuntimeError("Prompt configuration is missing for a prompt-enabled model.") - prompt_dict = self._prompt_config['prompt_dict'] - lang_index = prompt_dict.get(language_code, None) - if lang_index is None: - raise ValueError( - f"Language code '{language_code}' not found in prompt dictionary. " - f"Available languages: {list(prompt_dict.keys())}" - ) - return lang_index - - def _create_one_hot_prompts(self, indices: Tensor) -> Tensor: - """ - Create one-hot prompt vectors from indices. - Args: - indices: (Tensor) Prompt indices of shape [B]. - Returns: - (Tensor) One-hot prompt vectors of shape [B, num_prompts]. - """ - num_prompts = self._prompt_config['num_prompts'] - return torch.nn.functional.one_hot(indices, num_classes=num_prompts).to(self._prompt_config['compute_dtype']) - - def _build_prompt_vectors(self, states: list) -> Tensor: - """ - Build prompt vectors for a batch of states using one-hot encoding. - Args: - states: (list) List of streaming states. - Returns: - (Tensor) Prompt vectors of shape [B, num_prompts]. - Raises: - ValueError: If any prompt index is out of range. - """ - indices = torch.tensor([getattr(s, 'prompt_idx', 0) for s in states], device=self.device, dtype=torch.long) - num_prompts = self._prompt_config['num_prompts'] - if torch.any((indices < 0) | (indices >= num_prompts)): - raise ValueError("Found out-of-range prompt index in batch.") - return self._create_one_hot_prompts(indices) - - def run( - self, - audio_filepaths: list[str], - options: list[ASRRequestOptions] | None = None, - progress_bar: ProgressBar | None = None, - ) -> dict: - """ - Orchestrates reading from audio_filepaths in a streaming manner, - transcribes them, and packs the results into a PipelineOutput. - Args: - audio_filepaths (list[str]): List of audio filepaths to transcribe. - options (list[ASRRequestOptions] | None): List of RequestOptions for each stream. - progress_bar (ProgressBar | None): Progress bar to show the progress. Default is None. - Returns: - dict: A dictionary containing transcriptions and segments for each stream. - """ - if progress_bar is not None and not isinstance(progress_bar, ProgressBar): - raise ValueError("progress_bar must be an instance of ProgressBar.") - - if options is None: - # Use default options if not provided - options = [ASRRequestOptions() for _ in audio_filepaths] - - if len(options) != len(audio_filepaths): - raise ValueError("options must be the same length as audio_filepaths") - - request_generator = self.get_request_generator() - request_generator.set_audio_filepaths(audio_filepaths, options) - request_generator.set_progress_bar(progress_bar) - - pipeline_output = {} - sep = self.get_sep() - self.open_session() - for requests in request_generator: - step_outputs = self.transcribe_step(requests) - for step_output in step_outputs: - stream_id = step_output.stream_id - if stream_id not in pipeline_output: - pipeline_output[stream_id] = { - "text": "", - "translation": "", - "segments": [], - "audio_filepath": request_generator.get_audio_filepath(stream_id), - "translation_segments": [], - } - - accumulated_text = pipeline_output[stream_id]["text"] - accumulated_translation = pipeline_output[stream_id]["translation"] - final_transcript = step_output.final_transcript - final_translation = step_output.final_translation - final_segments = step_output.final_segments - if not accumulated_text: - final_transcript = final_transcript.lstrip(sep) - if len(final_segments) > 0: - first_segment = final_segments[0] - first_segment.text = first_segment.text.lstrip(sep) - - if not accumulated_translation: - final_translation = final_translation.lstrip(sep) - - accumulated_text += final_transcript - accumulated_translation += final_translation - pipeline_output[stream_id]["text"] = accumulated_text - pipeline_output[stream_id]["translation"] = accumulated_translation - pipeline_output[stream_id]["segments"].extend(final_segments) - - if self.nmt_enabled: - step_translation = step_output.current_step_translation - delay = request_generator.get_elapsed_duration(stream_id) - pipeline_output[stream_id]["translation_segments"].append((step_translation, delay)) - - self.close_session() - return pipeline_output diff --git a/nemo/collections/asr/inference/pipelines/buffered_ctc_pipeline.py b/nemo/collections/asr/inference/pipelines/buffered_ctc_pipeline.py deleted file mode 100644 index ba10c2fbfd2e85e367f280eca2c146603ae28ef7..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/pipelines/buffered_ctc_pipeline.py +++ /dev/null @@ -1,447 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from __future__ import annotations - -import math -from typing import TYPE_CHECKING - -import torch -from omegaconf import DictConfig -from torch import Tensor - -from nemo.collections.asr.inference.model_wrappers.ctc_inference_wrapper import CTCInferenceWrapper -from nemo.collections.asr.inference.pipelines.base_pipeline import BasePipeline -from nemo.collections.asr.inference.streaming.decoders.greedy.greedy_ctc_decoder import ClippedCTCGreedyDecoder -from nemo.collections.asr.inference.streaming.endpointing.greedy.greedy_ctc_endpointing import CTCGreedyEndpointing -from nemo.collections.asr.inference.streaming.framing.multi_stream import ContinuousBatchedRequestStreamer -from nemo.collections.asr.inference.streaming.framing.request import FeatureBuffer, Frame, Request -from nemo.collections.asr.inference.streaming.framing.request_options import ASRRequestOptions -from nemo.collections.asr.inference.streaming.state.ctc_state import CTCStreamingState -from nemo.collections.asr.inference.utils.enums import FeatureBufferPaddingMode, RequestType -from nemo.collections.asr.inference.utils.pipeline_utils import ( - check_existance_of_required_attributes, - drop_trailing_features, - get_confidence_utils, - normalize_features, - normalize_log_probs, -) - -if TYPE_CHECKING: - from nemo.collections.asr.inference.itn.inverse_normalizer import AlignmentPreservingInverseNormalizer - from nemo.collections.asr.inference.nmt.llm_translator import LLMTranslator - - -class BufferedCTCPipeline(BasePipeline): - """Buffered CTC pipeline.""" - - def __init__( - self, - cfg: DictConfig, - asr_model: CTCInferenceWrapper, - itn_model: AlignmentPreservingInverseNormalizer | None = None, - nmt_model: LLMTranslator | None = None, - ): - """ - Initialize the BufferedCTCPipeline. - Args: - cfg: (DictConfig) Configuration parameters. - asr_model: (CTCInferenceWrapper) ASR model. - itn_model: (AlignmentPreservingInverseNormalizer | None) Inverse Text Normalization model. - nmt_model: (LLMTranslator | None) LLM based translation model. - """ - self.copy_asr_model_attributes(asr_model) - self.init_parameters(cfg) - self.init_bufferer_for_buffered_streaming() - self.conf_func, self.confidence_aggregator = get_confidence_utils(cfg.confidence) - self.init_endpointer() - self.init_bpe_decoder() - self.init_greedy_ctc_decoder() - self.init_text_processor(cfg, itn_model) - self.init_nmt_model(nmt_model) - super().__init__() - - def init_parameters(self, cfg: DictConfig) -> None: - """ - Initialize the configuration parameters. - Args: - cfg: (DictConfig) Configuration parameters. - """ - self.sample_rate = cfg.streaming.sample_rate - self.asr_output_granularity = cfg.asr_output_granularity - self.batch_size = cfg.streaming.batch_size - - self.chunk_size = cfg.streaming.chunk_size - self.left_padding_size = cfg.streaming.left_padding_size - self.right_padding_size = cfg.streaming.right_padding_size - self.buffer_size_in_secs = self.chunk_size + self.left_padding_size + self.right_padding_size - self.expected_feature_buffer_len = int(self.buffer_size_in_secs / self.window_stride) - self.tokens_per_frame_float = self.chunk_size / self.model_stride_in_secs - self.tokens_per_frame = math.ceil(self.tokens_per_frame_float) - self.initial_delay = (self.left_padding_size + self.right_padding_size) / self.model_stride_in_secs - self.mid_delay = math.ceil((self.chunk_size + self.right_padding_size) / self.model_stride_in_secs) - - self.stop_history_eou_in_milliseconds = cfg.endpointing.stop_history_eou - self.residue_tokens_at_end = cfg.endpointing.residue_tokens_at_end - self.request_type = RequestType.from_str(cfg.streaming.request_type) - self.word_boundary_tolerance = cfg.streaming.word_boundary_tolerance - self.padding_mode = FeatureBufferPaddingMode.from_str(cfg.streaming.padding_mode) - self.right_padding = self.padding_mode is FeatureBufferPaddingMode.RIGHT - self.return_tail_result = cfg.return_tail_result - - # Keep small amount of extra padding - self.tail_padding_in_samples = max(int(self.chunk_size * self.sample_rate * 0.45), 6400) - self.zero_log_probs = self.init_zero_log_probs() if self.right_padding else None - - def init_endpointer(self) -> None: - """Initialize the endpointing.""" - check_existance_of_required_attributes( - self, - [ - 'vocabulary', - 'model_stride_in_milliseconds', - 'stop_history_eou_in_milliseconds', - 'residue_tokens_at_end', - ], - ) - - self.endpointer = CTCGreedyEndpointing( - vocabulary=self.vocabulary, - ms_per_timestep=self.model_stride_in_milliseconds, - stop_history_eou=self.stop_history_eou_in_milliseconds, - residue_tokens_at_end=self.residue_tokens_at_end, - ) - - def init_greedy_ctc_decoder(self) -> None: - """Initialize the CTC decoder.""" - check_existance_of_required_attributes(self, ['vocabulary', 'conf_func', 'endpointer', 'tokens_per_frame']) - self.greedy_ctc_decoder = ClippedCTCGreedyDecoder( - vocabulary=self.vocabulary, - conf_func=self.conf_func, - endpointer=self.endpointer, - tokens_per_frame=self.tokens_per_frame, - ) - - def init_zero_log_probs(self) -> Tensor: - """ - Initialize the log probabilities for the zero buffer. - Returns: - (Tensor) Log probabilities for the zero buffer. - """ - check_existance_of_required_attributes( - self, ['asr_model', 'buffer_size_in_secs', 'sample_rate', 'device', 'expected_feature_buffer_len'] - ) - buffer_size_in_samples = int(self.buffer_size_in_secs * self.sample_rate) - zero_buffer = torch.zeros(1, buffer_size_in_samples, device=self.device) - zero_features, zero_features_len = self.preprocess( - buffers=zero_buffer, - buffer_lens=torch.tensor([zero_buffer.shape[1]], device=self.device), - expected_feature_buffer_len=self.expected_feature_buffer_len, - ) - return self.asr_model.get_logprobs(processed_signal=zero_features, processed_signal_length=zero_features_len)[ - 0 - ] - - def create_state(self, options: ASRRequestOptions) -> CTCStreamingState: - """ - Create new empty state. - Args: - options: (ASRRequestOptions) Request options for particular stream. - Returns: - (CTCStreamingState) New empty state. - """ - state = CTCStreamingState() - state.set_global_offset(-self.initial_delay) - new_options = options.augment_with_defaults( - default_enable_itn=self.text_processor.is_itn_enabled(), - default_enable_pnc=self.text_processor.is_pnc_enabled(), - default_enable_nmt=self.nmt_enabled, - default_source_language=self.nmt_model.source_language if self.nmt_enabled else None, - default_target_language=self.nmt_model.target_language if self.nmt_enabled else None, - default_stop_history_eou=self.stop_history_eou_in_milliseconds, - default_asr_output_granularity=self.asr_output_granularity, - ) - state.set_options(new_options) - return state - - def get_sep(self) -> str: - """Return the separator for the text processor.""" - return self.sep - - def get_cut_off_range(self, T: int, is_last: bool) -> tuple[int, int]: - """ - Compute the start and end indices to clip the log probs. - Args: - T: (int) Time dimension of the log probabilities. - is_last: (bool) Whether the last frame is reached. - Returns: - (tuple[int, int]) Start and end indices to clip the log probs. - """ - start = max(T - 1 - self.mid_delay, 0) - end = T if is_last else min(start + self.tokens_per_frame, T) - return start, end - - def preprocess( - self, buffers: Tensor, buffer_lens: Tensor, expected_feature_buffer_len: int - ) -> tuple[Tensor, Tensor]: - """ - Preprocess the buffered frames and extract features. - Args: - buffers: (Tensor) Audio buffers. - buffer_lens: (Tensor) Lengths of the audio buffers. - expected_feature_buffer_len: (int) Expected length of the feature buffers. - Returns: - (tuple[Tensor, Tensor]) Processed feature buffers and their lengths. - """ - feature_buffers, feature_buffer_lens = self.preprocessor(input_signal=buffers, length=buffer_lens) - feature_buffers = drop_trailing_features(feature_buffers, expected_feature_buffer_len) - feature_buffers = normalize_features(feature_buffers, feature_buffer_lens) - feature_buffer_lens = feature_buffer_lens.clamp(max=feature_buffers.shape[2]) - return feature_buffers, feature_buffer_lens - - def get_logprobs_given_raw_signals( - self, frames: list[Frame], raw_signals: list[Tensor], left_paddings: list[int] - ) -> Tensor: - """ - Get log probs from the CTC model. - Args: - frames: (list[Frame]) Frames to transcribe. - raw_signals: (list[Tensor]) Audio buffers. - left_paddings: (list[int]) Left paddings for audio buffers. - Returns: - (Tensor) Log probabilities. - """ - - if self.right_padding: - left_paddings = torch.tensor(left_paddings, dtype=torch.int64, device=self.device) - - buffers = [] - for i in range(len(raw_signals)): - buffer = raw_signals[i] - # Roll the buffered frames to the left by the left padding - # This is done to avoid the padding at the beginning of the buffered frames - # which can cause the performance degradation - if self.right_padding: - lpad = left_paddings[i].item() - if lpad > 0: - buffer = buffer.roll(shifts=-lpad) - buffers.append(buffer.unsqueeze_(0)) - - # Only final frames have right padding - # Keep some amount of extra padding to avoid the performance degradation - right_paddings = torch.tensor( - [frame.size - frame.valid_size - self.tail_padding_in_samples for frame in frames], device=self.device - ).clamp(min=0) - - # Create and adjust the buffer lens - buffer_lens = torch.tensor([buffers[0].size(1)] * len(buffers), device=self.device) - buffer_lens = buffer_lens - right_paddings - if self.right_padding: - buffer_lens = buffer_lens - left_paddings - - # Preprocess the buffers with corresponding buffer lens - feature_buffers, feature_buffer_lens = self.preprocess( - buffers=torch.cat(buffers).to(self.device), - buffer_lens=buffer_lens, - expected_feature_buffer_len=self.expected_feature_buffer_len, - ) - - # Get the log probabilities from the ASR model - log_probs = self.asr_model.get_logprobs( - processed_signal=feature_buffers, processed_signal_length=feature_buffer_lens - ).clone() - - # Roll back the log probabilities to the right - if self.right_padding: - for i in range(len(log_probs)): - lpad = left_paddings[i] - if lpad > 0: - lpad = int(lpad / self.sample_rate / self.model_stride_in_secs) - log_probs[i] = log_probs[i].roll(lpad, dims=0) - log_probs[i][:lpad, :] = self.zero_log_probs[:lpad, :] - return log_probs - - def get_logprobs_given_processed_signals( - self, fbuffers: list[FeatureBuffer], processed_signals: list[Tensor] - ) -> Tensor: - """ - Get log probs from the ASR model. - Args: - fbuffers: (list[FeatureBuffer]) Feature buffers. - processed_signals: (list[Tensor]) Processed buffers. - Returns: - (Tensor) Log probabilities. - """ - processed_signals = torch.cat([sig.unsqueeze_(0) for sig in processed_signals]).to(self.device) - processed_signals = drop_trailing_features(processed_signals, self.expected_feature_buffer_len) - processed_signal_lengths = torch.tensor([f.valid_size for f in fbuffers], device=self.device) - processed_signals = normalize_features(processed_signals, processed_signal_lengths) - processed_signal_lengths = processed_signal_lengths.clamp(max=processed_signals.shape[2]) - - log_probs = self.asr_model.get_logprobs( - processed_signal=processed_signals, processed_signal_length=processed_signal_lengths - ).clone() - - if self.right_padding: - for i in range(len(log_probs)): - lpad = int(fbuffers[i].roll_size / self.subsampling_factor) - if lpad > 0: - log_probs[i] = log_probs[i].roll(lpad, dims=0) - log_probs[i][:lpad, :] = self.zero_log_probs[:lpad, :] - return log_probs - - def compute_logprobs_from_frames(self, frames: list[Frame]) -> Tensor: - """ - Buffer the frames and get the log probabilities. - Args: - frames: (list[Frame]) List of frames to transcribe. - Returns: - (Tensor) Log probabilities. - """ - raw_signals, left_paddings = self.bufferer.update(frames) - log_probs = None - if len(raw_signals) > 0: - log_probs = self.get_logprobs_given_raw_signals(frames, raw_signals, left_paddings) - return log_probs - - def compute_logprobs_from_feature_buffers(self, fbuffers: list[FeatureBuffer]) -> Tensor: - """ - Buffer the feature buffers and get the log probabilities. - Args: - fbuffers: (list[FeatureBuffer]) List of feature buffers to transcribe. - Returns: - (Tensor) Log probabilities. - """ - processed_signals = self.bufferer.update(fbuffers) - log_probs = None - if len(processed_signals) > 0: - log_probs = self.get_logprobs_given_processed_signals(fbuffers, processed_signals) - return log_probs - - def run_greedy_decoder( - self, state: CTCStreamingState, request: Request, buffer_log_probs: Tensor, start: int, end: int - ) -> bool: - """ - Run Greedy decoder, update state and trigger EOU detection. - Args: - state: (CTCStreamingState) Current state for the particular stream. - request: (Request) Current request for the particular stream. - buffer_log_probs: (Tensor) Log probabilities. - start: (int) Start index of the log probabilities. - end: (int) End index of the log probabilities. - Returns: - (bool) Whether EOU is detected. - """ - clipped_output, tail_output, eou_detected, start_idx, end_idx = self.greedy_ctc_decoder( - buffer_log_probs, - start, - end, - request.is_last, - is_start=request.is_first, - return_partial_result=self.return_tail_result, - state_start_idx=state.decoder_start_idx, - state_end_idx=state.decoder_end_idx, - stop_history_eou=state.options.stop_history_eou, - compute_confidence=True, - ) - - state.update_state(clipped_output, eou_detected) - state.set_last_token(clipped_output["last_token"], clipped_output["last_token_idx"]) - state.update_from_decoder_results(start_idx, end_idx) - state.increment_global_offset(self.tokens_per_frame_float) - state.set_incomplete_segment_tokens(tail_output["tokens"]) - return eou_detected - - def shared_transcribe_step(self, requests: list[Request], log_probs: Tensor) -> None: - """ - Shared transcribe step for frames and feature buffers. - Args: - requests: (list[Request]) List of frames or feature buffers to transcribe. - log_probs: (Tensor) Log probabilities. - """ - postponed_requests = [(ridx, request.stream_id) for ridx, request in enumerate(requests)] - next_postponed_requests = [] - - while len(postponed_requests) > 0: - - ready_state_ids = set() - for ridx, stream_id in postponed_requests: - - if stream_id in ready_state_ids: - # Skip if the state is already ready - next_postponed_requests.append((ridx, stream_id)) - continue - - request = requests[ridx] - state = self.get_state(stream_id) - lp = log_probs[ridx].cpu() - start, end = self.get_cut_off_range(lp.shape[0], request.is_last) - eou_detected = self.run_greedy_decoder(state, request, lp, start, end) - - if eou_detected: - self.bpe_decoder.decode_bpe_tokens(state) - state.cleanup_after_eou() - ready_state_ids.add(stream_id) - - if len(ready_state_ids) > 0: - self.text_processor.process([self.get_state(stream_id) for stream_id in ready_state_ids]) - ready_state_ids.clear() - - postponed_requests = next_postponed_requests.copy() - next_postponed_requests.clear() - - self.update_partial_transcript(requests, self.tokenizer, self.leading_regex_pattern) - - def transcribe_step_for_feature_buffers(self, fbuffers: list[FeatureBuffer]) -> None: - """ - Transcribe a step for feature buffers. - Args: - fbuffers: (list[FeatureBuffer]) List of feature buffers to transcribe. - """ - log_probs = self.compute_logprobs_from_feature_buffers(fbuffers) - if log_probs is not None: - log_probs = normalize_log_probs(log_probs) - self.shared_transcribe_step(requests=fbuffers, log_probs=log_probs) - - def transcribe_step_for_frames(self, frames: list[Frame]) -> None: - """ - Transcribe step for frames. - Args: - frames: (list[Frame]) List of frames to transcribe. - """ - log_probs = self.compute_logprobs_from_frames(frames) - if log_probs is not None: - log_probs = normalize_log_probs(log_probs) - self.shared_transcribe_step(requests=frames, log_probs=log_probs) - - def get_request_generator(self) -> ContinuousBatchedRequestStreamer: - """ - Initialize the request generator. - Returns: - (ContinuousBatchedRequestStreamer) Request generator. - """ - request_generator = ContinuousBatchedRequestStreamer( - n_frames_per_stream=1, - frame_size_in_secs=self.chunk_size, - sample_rate=self.sample_rate, - batch_size=self.batch_size, - request_type=self.request_type, - preprocessor=self.preprocessor, - buffer_size_in_secs=self.buffer_size_in_secs, - device=self.device, - pad_last_frame=True, - right_pad_features=self.right_padding, - tail_padding_in_samples=self.tail_padding_in_samples, - ) - return request_generator diff --git a/nemo/collections/asr/inference/pipelines/buffered_rnnt_pipeline.py b/nemo/collections/asr/inference/pipelines/buffered_rnnt_pipeline.py deleted file mode 100644 index e7a390e458dab1dc0399cc122188ecc78d033b79..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/pipelines/buffered_rnnt_pipeline.py +++ /dev/null @@ -1,813 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from __future__ import annotations - -import math -from typing import TYPE_CHECKING - -import numpy as np -import torch -from omegaconf import DictConfig -from torch import Tensor - -from nemo.collections.asr.inference.model_wrappers.rnnt_inference_wrapper import RNNTInferenceWrapper -from nemo.collections.asr.inference.pipelines.base_pipeline import BasePipeline -from nemo.collections.asr.inference.streaming.decoders.greedy.greedy_rnnt_decoder import ClippedRNNTGreedyDecoder -from nemo.collections.asr.inference.streaming.endpointing.greedy.greedy_rnnt_endpointing import RNNTGreedyEndpointing -from nemo.collections.asr.inference.streaming.framing.multi_stream import ContinuousBatchedRequestStreamer -from nemo.collections.asr.inference.streaming.framing.request import FeatureBuffer, Frame, Request -from nemo.collections.asr.inference.streaming.framing.request_options import ASRRequestOptions -from nemo.collections.asr.inference.streaming.state.rnnt_state import RNNTStreamingState -from nemo.collections.asr.inference.utils.enums import FeatureBufferPaddingMode, RequestType -from nemo.collections.asr.inference.utils.pipeline_utils import ( - adjust_vad_segments, - check_existance_of_required_attributes, - drop_trailing_features, - get_confidence_utils, - normalize_features, - update_punctuation_and_language_tokens_timestamps, -) -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis as NemoHypothesis -from nemo.collections.asr.parts.utils.rnnt_utils import batched_hyps_to_hypotheses -from nemo.utils import logging - -if TYPE_CHECKING: - from nemo.collections.asr.inference.itn.inverse_normalizer import AlignmentPreservingInverseNormalizer - from nemo.collections.asr.inference.nmt.llm_translator import LLMTranslator - - -class BufferedRNNTPipeline(BasePipeline): - """Buffered RNN-T/TDT pipeline.""" - - def __init__( - self, - cfg: DictConfig, - asr_model: RNNTInferenceWrapper, - itn_model: AlignmentPreservingInverseNormalizer | None = None, - nmt_model: LLMTranslator | None = None, - ): - """ - Initialize the BufferedRNNTPipeline. - Args: - cfg: (DictConfig) Configuration parameters. - asr_model: (RNNTInferenceWrapper) ASR model. - itn_model: (AlignmentPreservingInverseNormalizer | None) Inverse Text Normalization model. - nmt_model: (LLMTranslator | None) LLM based translation model. - """ - - self.copy_asr_model_attributes(asr_model) - self.init_prompt_support() - self.init_parameters(cfg) - self.init_bufferer_for_buffered_streaming() - self.conf_func, self.confidence_aggregator = get_confidence_utils(cfg.confidence) - self.init_endpointer() - self.init_greedy_rnnt_decoder() - self.init_bpe_decoder() - self.init_decoding_computer() - self.init_text_processor(cfg, itn_model) - self.init_nmt_model(nmt_model) - super().__init__() - - def init_parameters(self, cfg: DictConfig) -> None: - """ - Initialize the configuration parameters. - Args: - cfg: (DictConfig) Configuration parameters. - """ - self.asr_output_granularity = cfg.asr_output_granularity - self.sample_rate = cfg.streaming.sample_rate - self.stateful = cfg.streaming.stateful - self.stateless = not self.stateful - self.batch_size = cfg.streaming.batch_size - - self.chunk_size = cfg.streaming.chunk_size - self.left_padding_size = cfg.streaming.left_padding_size - self.right_padding_size = cfg.streaming.right_padding_size - self.buffer_size_in_secs = self.chunk_size + self.left_padding_size + self.right_padding_size - self.expected_feature_buffer_len = int(self.buffer_size_in_secs / self.window_stride) - - self.mid_delay = math.ceil((self.chunk_size + self.right_padding_size) / self.model_stride_in_secs) - self.tokens_per_frame_float = self.chunk_size / self.model_stride_in_secs - self.tokens_per_left_padding_float = self.left_padding_size / self.model_stride_in_secs - self.tokens_per_right_padding_float = self.right_padding_size / self.model_stride_in_secs - self.tokens_per_frame = math.ceil(self.tokens_per_frame_float) - self.tokens_per_left_padding = math.ceil(self.tokens_per_left_padding_float) - self.tokens_per_right_padding = math.ceil(self.tokens_per_right_padding_float) - - if self.stateful: - self.initial_delay = self.right_padding_size / self.model_stride_in_secs - else: - self.initial_delay = (self.left_padding_size + self.right_padding_size) / self.model_stride_in_secs - - if self.stateful and ( - abs(self.tokens_per_frame_float - self.tokens_per_frame) > 1e-5 - or abs(self.tokens_per_left_padding_float - self.tokens_per_left_padding) > 1e-5 - or abs(self.tokens_per_right_padding_float - self.tokens_per_right_padding) > 1e-5 - ): - self.tokens_per_frame_float = self.tokens_per_frame - self.tokens_per_left_padding_float = self.tokens_per_left_padding - self.left_padding_size = self.tokens_per_left_padding * self.model_stride_in_secs - self.chunk_size = self.tokens_per_frame * self.model_stride_in_secs - self.right_padding_size = self.tokens_per_right_padding * self.model_stride_in_secs - self.buffer_size_in_secs = self.chunk_size + self.left_padding_size + self.right_padding_size - - self.request_type = RequestType.from_str(cfg.streaming.request_type) - self.padding_mode = FeatureBufferPaddingMode.from_str(cfg.streaming.padding_mode) - self.right_padding = self.padding_mode is FeatureBufferPaddingMode.RIGHT - self.stop_history_eou_in_milliseconds = cfg.endpointing.stop_history_eou - self.residue_tokens_at_end = cfg.endpointing.residue_tokens_at_end - self.word_boundary_tolerance = cfg.streaming.word_boundary_tolerance - self.return_tail_result = cfg.return_tail_result - self.tokens_to_move = self.punctuation_ids.union(self.language_token_ids) - - # Keep small amount of extra padding - self.tail_padding_in_samples = max(int(self.chunk_size * self.sample_rate * 0.45), 6400) - self.zero_encoded = self.init_zero_enc() if self.right_padding else None - - def init_endpointer(self) -> None: - """Initialize the endpointer.""" - check_existance_of_required_attributes( - self, - [ - 'stateful', - 'chunk_size', - 'right_padding_size', - 'buffer_size_in_secs', - 'vocabulary', - 'model_stride_in_milliseconds', - 'stop_history_eou_in_milliseconds', - 'residue_tokens_at_end', - ], - ) - - if self.stateful: - effective_buffer_size_in_secs = self.chunk_size + self.right_padding_size - else: - effective_buffer_size_in_secs = self.buffer_size_in_secs - - self.endpointer = RNNTGreedyEndpointing( - vocabulary=self.vocabulary, - ms_per_timestep=self.model_stride_in_milliseconds, - effective_buffer_size_in_secs=effective_buffer_size_in_secs, - stop_history_eou=self.stop_history_eou_in_milliseconds, - residue_tokens_at_end=self.residue_tokens_at_end, - ) - - def init_greedy_rnnt_decoder(self) -> None: - """Initialize the greedy RNNT decoder.""" - check_existance_of_required_attributes(self, ['vocabulary', 'conf_func', 'endpointer', 'tokens_per_frame']) - self.greedy_rnnt_decoder = ClippedRNNTGreedyDecoder( - vocabulary=self.vocabulary, - conf_func=self.conf_func, - endpointer=self.endpointer, - tokens_per_frame=self.tokens_per_frame, - ) - - def init_decoding_computer(self) -> None: - """Initialize the decoding computer.""" - check_existance_of_required_attributes(self, ['stateful', 'asr_model']) - self.decoding_computer = None - if self.stateful: - self.decoding_computer = self.asr_model.asr_model.decoding.decoding.decoding_computer - - def init_zero_enc(self) -> Tensor: - """ - Initialize the encoder output for the zero buffer. - Returns: - (Tensor) Encoder output for the zero buffer. - """ - check_existance_of_required_attributes( - self, ['buffer_size_in_secs', 'sample_rate', 'device', 'expected_feature_buffer_len'] - ) - buffer_size_in_samples = int(self.buffer_size_in_secs * self.sample_rate) - zero_buffer = torch.zeros(1, buffer_size_in_samples, device=self.device) - zero_features, zero_features_len = self.preprocess( - buffers=zero_buffer, - buffer_lens=torch.tensor([zero_buffer.shape[1]], device=self.device), - expected_feature_buffer_len=self.expected_feature_buffer_len, - ) - - if self.prompt_enabled: - # Use "en-US" as the default prompt for zero encoding - # This region is sliced out before decoding, so language choice doesn't matter - default_prompt_idx = self._resolve_prompt_index("en-US") - prompt_indices = torch.tensor([default_prompt_idx], device=self.device, dtype=torch.long) - prompt_vector = self._create_one_hot_prompts(prompt_indices) # [1, num_prompts] - - zero_encoded, _ = self.asr_model.encode_with_prompts( - processed_signal=zero_features, - processed_signal_length=zero_features_len, - prompt_vectors=prompt_vector, - ) - else: - zero_encoded, _ = self.asr_model.encode( - processed_signal=zero_features, processed_signal_length=zero_features_len - ) - - return zero_encoded[0] - - def create_state(self, options: ASRRequestOptions) -> RNNTStreamingState: - """ - Create new empty state. - Args: - options: (ASRRequestOptions) Request options for particular stream. - Returns: - (RNNTStreamingState) New empty state. - """ - state = RNNTStreamingState() - state.set_global_offset(-self.initial_delay) - new_options = options.augment_with_defaults( - default_enable_itn=self.text_processor.is_itn_enabled(), - default_enable_pnc=self.text_processor.is_pnc_enabled(), - default_enable_nmt=self.nmt_enabled, - default_source_language=self.nmt_model.source_language if self.nmt_enabled else None, - default_target_language=self.nmt_model.target_language if self.nmt_enabled else None, - default_stop_history_eou=self.stop_history_eou_in_milliseconds, - default_asr_output_granularity=self.asr_output_granularity, - default_language_code="en-US" if self.prompt_enabled else None, - ) - state.set_options(new_options) - - # Create per-stream prompt index for prompt-enabled models - if self.prompt_enabled: - lang_code = getattr(new_options, "language_code", None) - if not isinstance(lang_code, str) or len(lang_code) == 0: - raise ValueError("Prompt-enabled model requires a valid language_code in request options.") - prompt_idx = self._resolve_prompt_index(lang_code) - state.set_prompt_index(prompt_idx) - - return state - - def get_sep(self) -> str: - """Return the separator for the text processor.""" - return self.sep - - def preprocess( - self, buffers: Tensor, buffer_lens: Tensor, expected_feature_buffer_len: int - ) -> tuple[Tensor, Tensor]: - """ - Preprocess the buffered frames and extract features. - Args: - buffers: (Tensor) Audio buffers. - buffer_lens: (Tensor) Lengths of the audio buffers. - expected_feature_buffer_len: (int) Expected length of the feature buffers. - Returns: - (tuple[Tensor, Tensor]) Processed feature buffers and their lengths. - """ - feature_buffers, feature_buffer_lens = self.preprocessor(input_signal=buffers, length=buffer_lens) - feature_buffers = drop_trailing_features(feature_buffers, expected_feature_buffer_len) - feature_buffers = normalize_features(feature_buffers, feature_buffer_lens) - feature_buffer_lens = feature_buffer_lens.clamp(max=feature_buffers.shape[2]) - return feature_buffers, feature_buffer_lens - - def get_cut_off_range(self, T: int, is_last: bool) -> tuple[int, int]: - """ - Compute the start and end indices to clip. - Args: - T: (int) Time dimension of the alignment. - is_last: (bool) Whether the last frame is reached. - Returns: - (tuple[int, int]) Start and end indices to clip. - """ - start = max(T - 1 - self.mid_delay, 0) - end = T if is_last else min(start + self.tokens_per_frame, T) - return start, end - - def encode_raw_signals( - self, frames: list[Frame], raw_signals: list[Tensor], left_paddings: list[int] - ) -> tuple[Tensor, Tensor]: - """ - Run Encoder part on the audio buffers. - Args: - frames: (list[Frame]) Frames to transcribe. - raw_signals: (list[Tensor]) Audio buffers. - left_paddings: (list[int]) Left paddings for audio buffers. - Returns: - (tuple[Tensor, Tensor]) Encoded signals and their lengths. - """ - - if self.right_padding: - left_paddings = torch.tensor(left_paddings, dtype=torch.int64, device=self.device) - - buffers = [] - for i in range(len(raw_signals)): - buffer = raw_signals[i] - if self.right_padding: - # Roll the buffered frames to the left by the left padding - # This is done to avoid the padding at the beginning of the buffered frames - # which can cause the performance degradation - lpad = left_paddings[i].item() - if lpad > 0: - buffer = buffer.roll(shifts=-lpad) - buffers.append(buffer.unsqueeze_(0)) - - # Only final frames have right padding - # Keep some amount of extra padding to avoid the performance degradation - right_paddings = torch.tensor( - [frame.size - frame.valid_size - self.tail_padding_in_samples for frame in frames], device=self.device - ).clamp(min=0) - - # Create and adjust the buffer lens - buffer_lens = torch.tensor([buffers[0].size(1)] * len(buffers), device=self.device) - buffer_lens = buffer_lens - right_paddings - if self.right_padding: - buffer_lens = buffer_lens - left_paddings - - feature_buffers, feature_buffer_lens = self.preprocess( - buffers=torch.cat(buffers).to(self.device), - buffer_lens=buffer_lens, - expected_feature_buffer_len=self.expected_feature_buffer_len, - ) - - # Build prompt vectors if prompts are enabled - if self.prompt_enabled: - requests_states = [self.get_state(f.stream_id) for f in frames] - prompt_vectors = self._build_prompt_vectors(requests_states) - - # Use encode_with_prompts which handles dimension expansion - encoded, encoded_len = self.asr_model.encode_with_prompts( - processed_signal=feature_buffers, - processed_signal_length=feature_buffer_lens, - prompt_vectors=prompt_vectors, - ) - else: - encoded, encoded_len = self.asr_model.encode( - processed_signal=feature_buffers, processed_signal_length=feature_buffer_lens - ) - encoded = encoded.clone() - encoded_len = encoded_len.clone() - - # Roll back the encoded signals to the right - if self.right_padding: - for i in range(encoded.shape[0]): - lpad = left_paddings[i] - if lpad > 0: - lpad = int(lpad / self.sample_rate / self.model_stride_in_secs) - encoded[i] = encoded[i].roll(lpad, dims=1) - encoded[i][:, :lpad] = self.zero_encoded[:, :lpad] - encoded_len[i] = encoded_len[i] + lpad - - return encoded, encoded_len - - def encode_processed_signals( - self, fbuffers: list[FeatureBuffer], processed_signals: list[Tensor] - ) -> tuple[Tensor, Tensor]: - """ - Run Encoder part on the feature buffers. - Args: - fbuffers: (list[FeatureBuffer]) Feature buffers. - processed_signals: (list[Tensor]) Processed buffers. - Returns: - (tuple[Tensor, Tensor]) Encoder output and their lengths. - """ - - processed_signals = torch.cat([sig.unsqueeze_(0) for sig in processed_signals]).to(self.device) - processed_signals = drop_trailing_features(processed_signals, self.expected_feature_buffer_len) - processed_signal_lengths = torch.tensor([f.valid_size for f in fbuffers], device=self.device) - processed_signals = normalize_features(processed_signals, processed_signal_lengths) - processed_signal_lengths = processed_signal_lengths.clamp(max=processed_signals.shape[2]) - - # Build prompt vectors if prompts are enabled - if self.prompt_enabled: - requests_states = [self.get_state(f.stream_id) for f in fbuffers] - prompt_vectors = self._build_prompt_vectors(requests_states) - - # Use encode_with_prompts which handles dimension expansion - encoded, encoded_len = self.asr_model.encode_with_prompts( - processed_signal=processed_signals, - processed_signal_length=processed_signal_lengths, - prompt_vectors=prompt_vectors, - ) - else: - encoded, encoded_len = self.asr_model.encode( - processed_signal=processed_signals, processed_signal_length=processed_signal_lengths - ) - encoded = encoded.clone() - encoded_len = encoded_len.clone() - - if self.right_padding: - for i in range(encoded.shape[0]): - lpad = int(fbuffers[i].roll_size / self.subsampling_factor) - if lpad > 0: - encoded[i] = encoded[i].roll(lpad, dims=1) - encoded[i][:, :lpad] = self.zero_encoded[:, :lpad] - encoded_len[i] = encoded_len[i] + lpad - return encoded, encoded_len - - def encode_frames(self, frames: list[Frame]) -> tuple[Tensor, Tensor]: - """ - Encode the frames using the Encoder part of the ASR model. - Args: - frames: (list[Frame]) Frames to transcribe. - Returns: - (tuple[Tensor, Tensor]) Encoder output and their lengths. - """ - raw_signals, left_paddings = self.bufferer.update(frames) - encs, enc_lens = None, None - if len(raw_signals) > 0: - encs, enc_lens = self.encode_raw_signals(frames, raw_signals, left_paddings) - return encs, enc_lens - - def encode_feature_buffers(self, fbuffers: list[FeatureBuffer]) -> tuple[Tensor, Tensor]: - """ - Encode the feature buffers using the Encoder part of the ASR model. - Args: - fbuffers: (list[FeatureBuffer]) Feature buffers to transcribe. - Returns: - (tuple[Tensor, Tensor]) Encoder output and their lengths. - """ - processed_signals = self.bufferer.update(fbuffers) - encs, enc_lens = None, None - if len(processed_signals) > 0: - encs, enc_lens = self.encode_processed_signals(fbuffers, processed_signals) - return encs, enc_lens - - def run_greedy_decoder( - self, - state: RNNTStreamingState, - request: Request, - timesteps: torch.Tensor, - tokens: torch.Tensor, - start: int, - end: int, - alignment_length: int, - timestamp_offset: int = 0, - vad_segments: torch.Tensor = None, - ) -> bool: - """ - Greedy RNN-T decoder. - Args: - state: (RNNTStreamingState) Current state for the particular stream. - request: (Request) Current request for the particular stream. - timesteps: (Tensor) Timesteps. - tokens: (Tensor) Tokens. - start: (int) Start index. - end: (int) End index. - alignment_length: (int) Length of the alignment. - timestamp_offset: (int) Timestamp offset. - vad_segments: (Tensor) VAD segments. - Returns: - (bool) Whether EOU is detected. - """ - if self.stateful and vad_segments is not None: - vad_segments = adjust_vad_segments(vad_segments, self.left_padding_size) - - clipped_output, tail_output, eou_detected, start_idx, end_idx = self.greedy_rnnt_decoder( - global_timesteps=timesteps, - tokens=tokens, - alignment_length=alignment_length, - clip_start=start, - clip_end=end, - is_last=request.is_last, - is_start=request.is_first, - return_tail_result=self.return_tail_result, - state_start_idx=state.decoder_start_idx, - state_end_idx=state.decoder_end_idx, - timestamp_offset=timestamp_offset, - vad_segments=vad_segments, - stop_history_eou=state.options.stop_history_eou, - ) - state.update_state(clipped_output, eou_detected) - state.update_from_decoder_results(start_idx, end_idx) - if self.stateless: - # For stateless mode, we need to set the last token, it will be used for filtering duplicate token - state.set_last_token(clipped_output["last_token"], clipped_output["last_token_idx"]) - # For stateless mode, we need to increment the global offset - state.increment_global_offset(self.tokens_per_frame_float) - state.set_incomplete_segment_tokens(tail_output["tokens"]) - return eou_detected - - def stateless_transcribe_step( - self, requests: list[Request], encs: Tensor, enc_lens: Tensor, ready_state_ids: set - ) -> None: - """ - Stateless transcribe step. - Stateless assumes that we don't keep track of partial hypotheses (partial_hypotheses=None). - Args: - requests: (list[Request]) List of requests to transcribe. - encs: (Tensor) Encoder output. - enc_lens: (Tensor) Encoder output lengths. - ready_state_ids: (set) Set of ready state IDs. - """ - states = [self.get_state(request.stream_id) for request in requests] - best_hyp = self.asr_model.decode(encs, enc_lens, partial_hypotheses=None) - # For stateless mode, use zero timestamp offsets since we don't track timestamps - ready_states = self.decode_step(best_hyp, requests, states) - ready_state_ids.update(ready_states) - - def stateful_transcribe_step( - self, requests: list[Request], encs: Tensor, enc_lens_chunk: Tensor, enc_lens: Tensor, ready_state_ids: set - ) -> None: - """ - Stateful transcribe step. - Stateful assumes that we keep track of partial hypotheses. - Args: - requests: (list[Request]) List of requests to transcribe. - encs: (Tensor) Encoder output. - enc_lens_chunk: (Tensor) Encoder output lengths for the chunk. - enc_lens: (Tensor) Encoder output lengths. - ready_state_ids: (set) Set of ready state IDs. - """ - states = [self.get_state(request.stream_id) for request in requests] - partial_hypotheses, rnnt_states = [], [] - all_rnnt_states_are_none = True - all_multi_biasing_models_empty = True - multi_biasing_ids = np.full([len(states)], fill_value=-1) - for i, state in enumerate(states): - hyp_state = state.hyp_decoding_state - rnnt_states.append(hyp_state) - if hyp_state is not None: - all_rnnt_states_are_none = False - if state.has_biasing_request(): - if state.options.biasing_cfg.multi_model_id is not None: - all_multi_biasing_models_empty = False - multi_biasing_ids[i] = state.options.biasing_cfg.multi_model_id - elif state.options.biasing_cfg.auto_manage_multi_model: - state.options.biasing_cfg.add_to_multi_model( - tokenizer=self.asr_model.tokenizer, - biasing_multi_model=self.decoding_computer.biasing_multi_model, - ) - multi_biasing_ids[i] = state.options.biasing_cfg.multi_model_id - all_multi_biasing_models_empty = False - else: - logging.warning("Biasing request is not empty, not auto managed and not compiled. Skipping") - if hyp_state is not None or state.has_biasing_request(): - partial_hypotheses.append( - NemoHypothesis( - score=0.0, - y_sequence=torch.zeros([0], dtype=torch.long), - dec_state=hyp_state, - biasing_cfg=state.options.biasing_cfg, - ) - ) - else: - partial_hypotheses.append(None) - - batched_rnnt_states = None - if not all_rnnt_states_are_none: - batched_rnnt_states = self.decoding_computer.merge_to_batched_state(rnnt_states) - - if all_multi_biasing_models_empty: - multi_biasing_ids = None - else: - multi_biasing_ids = torch.from_numpy(multi_biasing_ids).to(device=enc_lens_chunk.device) - - encs_dim_last = encs.transpose(1, 2) - # decode chunk - with torch.inference_mode(), torch.no_grad(): - best_batched_hyps_chunk, _, batched_state = self.decoding_computer( - encs_dim_last, - enc_lens_chunk, - batched_rnnt_states, - multi_biasing_ids=multi_biasing_ids, - ) - best_hyps = batched_hyps_to_hypotheses(best_batched_hyps_chunk, batch_size=enc_lens.shape[0]) - - # save state (after chunk) - for state, rnnt_state in zip(states, self.decoding_computer.split_batched_state(batched_state)): - state.hyp_decoding_state = rnnt_state - - if self.tokens_per_right_padding > 0: - # decode right context - _, max_time, feat_dim = encs_dim_last.shape - device = encs.device - # we are indexing `encs_dim_last` with `shift_indices` to get a tensor where right context is at the start - # everything after right context is padded with `0` index (first encoder vector) - # padding will be ignored by decoder_computer since we pass the lengths - shift_indices = torch.arange(max_time, device=device, dtype=torch.long)[None, :] + enc_lens_chunk[:, None] - # pad with zeros everything beyond needed context - shift_indices = torch.where(shift_indices < max_time, shift_indices, torch.zeros_like(shift_indices)) - with torch.inference_mode(), torch.no_grad(): - best_batched_hyps_rc, _, _ = self.decoding_computer( - torch.gather(encs_dim_last, dim=1, index=shift_indices[:, :, None].expand(-1, -1, feat_dim)), - enc_lens - enc_lens_chunk, - batched_state, - multi_biasing_ids=multi_biasing_ids, - ) - best_hyps_rc = batched_hyps_to_hypotheses(best_batched_hyps_rc, batch_size=enc_lens.shape[0]) - # merge right context to chunk hypothesis - for hyp, hyp_rc in zip(best_hyps, best_hyps_rc): - hyp.merge_(hyp_rc) - - ready_states = self.decode_step(best_hyps, requests, states) - for curr_state in states: - curr_state.timestamp_offset += self.tokens_per_frame_float - ready_state_ids.update(ready_states) - - for request, state in zip(requests, states): - # only the first request contains biasing options; biasing options for the stream are stored in state - if request.is_last and state.has_biasing_request(): - if state.options.biasing_cfg.auto_manage_multi_model: - state.options.biasing_cfg.remove_from_multi_model( - biasing_multi_model=self.decoding_computer.biasing_multi_model - ) - - def decode_step(self, best_hyp: list, requests: list[Request], states: list[RNNTStreamingState]) -> set: - """ - Perform greedy RNNT decoding to get the best hypothesis and update the state. - If EOU is detected, push the words to the state and cleanup the state. - Args: - best_hyp: (list) Best hypothesis. - requests: (list[Request]) List of requests to transcribe. - states: (list[RNNTStreamingState]) List of states. - Returns: - (set) Set of ready state IDs. - """ - ready_state_ids = set() - for idx, hyp in enumerate(best_hyp): - state = states[idx] - request = requests[idx] - # Perform timestamp based decoding for the hypothesis - if self.stateful: - alignment_length = self.tokens_per_right_padding + self.tokens_per_frame - else: - if self.request_type is RequestType.FEATURE_BUFFER: - alignment_length = math.ceil(request.size / self.subsampling_factor) - else: # RequestType.FRAME - alignment_length = math.ceil(self.expected_feature_buffer_len / self.subsampling_factor) - - if self.stateful: - start, end = 0, self.tokens_per_frame - else: - # For stateless mode - if request.is_first and request.is_last: - start, end = 0, alignment_length - else: - start, end = self.get_cut_off_range(alignment_length, request.is_last) - - timestamp = hyp.timestamp - tokens = hyp.y_sequence - timestamp = torch.tensor(timestamp) if isinstance(timestamp, list) else timestamp - tokens = torch.tensor(tokens) if isinstance(tokens, list) else tokens - timestamp = update_punctuation_and_language_tokens_timestamps( - tokens, timestamp, self.tokens_to_move, self.underscore_id - ) - vad_segments = request.vad_segments - eou_detected = self.run_greedy_decoder( - state=state, - request=request, - timesteps=timestamp, - tokens=tokens, - start=start, - end=end, - alignment_length=alignment_length, - timestamp_offset=state.timestamp_offset, - vad_segments=vad_segments, - ) - - if eou_detected: - self.bpe_decoder.decode_bpe_tokens(state) - state.cleanup_after_eou() - ready_state_ids.add(request.stream_id) - return ready_state_ids - - def shared_transcribe_step_stateful(self, requests: list[Request], encs: Tensor, enc_lens: Tensor) -> None: - """ - Stateful transcribe step. - After detecting EOU, it updates the state and run text processor. - If there are multiple streams, it waits until all states are ready to run text processor. - Args: - requests: (list[Request]) List of requests to transcribe. - encs: (Tensor) Encoder output. - enc_lens: (Tensor) Encoder output lengths. - """ - tokens_per_left_padding_tensor = torch.tensor(self.tokens_per_left_padding, device=self.device) - tokens_per_frame_tensor = torch.tensor(self.tokens_per_frame, device=self.device) - postponed_requests = [(ridx, request.stream_id) for ridx, request in enumerate(requests)] - next_postponed_requests = [] - ready_state_ids = set() - while len(postponed_requests) > 0: - request_ids_to_process = [] - for ridx, stream_id in postponed_requests: - if stream_id in ready_state_ids: - next_postponed_requests.append((ridx, stream_id)) - continue - request_ids_to_process.append(ridx) - if len(request_ids_to_process) > 0: - requests_to_process = [requests[jdx] for jdx in request_ids_to_process] - request_is_last = torch.tensor( - [request.is_last for request in requests_to_process], dtype=torch.bool, device=self.device - ) - enc_lens_dec = enc_lens - tokens_per_left_padding_tensor - enc_lens_dec_trimmed = torch.where( - request_is_last, - enc_lens_dec, - torch.minimum(enc_lens_dec, tokens_per_frame_tensor.expand_as(enc_lens_dec)), - ) - self.stateful_transcribe_step( - requests_to_process, - encs[request_ids_to_process][:, :, self.tokens_per_left_padding :], - enc_lens_dec_trimmed, - enc_lens_dec, - ready_state_ids, - ) - if len(ready_state_ids) > 0: - self.text_processor.process([self.get_state(stream_id) for stream_id in ready_state_ids]) - ready_state_ids.clear() - postponed_requests = next_postponed_requests.copy() - next_postponed_requests.clear() - - self.update_partial_transcript(requests, self.tokenizer, self.leading_regex_pattern) - - def shared_transcribe_step(self, requests: list[Request], encs: Tensor, enc_lens: Tensor) -> None: - """ - Stateless transcribe step. - After detecting EOU, it updates the state and run text processor. - If there are multiple streams, it waits until all stated are ready to run text processor. - Args: - requests: (list[Request]) List of requests to transcribe. - encs: (Tensor) Encoder output. - enc_lens: (Tensor) Encoder output lengths. - """ - postponed_requests = [(ridx, request.stream_id) for ridx, request in enumerate(requests)] - next_postponed_requests = [] - ready_state_ids = set() - - while len(postponed_requests) > 0: - - request_ids_to_process = [] - for ridx, stream_id in postponed_requests: - - if stream_id in ready_state_ids: - # Skip if the state is already ready - next_postponed_requests.append((ridx, stream_id)) - continue - - request_ids_to_process.append(ridx) - - if len(request_ids_to_process) > 0: - requests_to_process = [requests[jdx] for jdx in request_ids_to_process] - self.stateless_transcribe_step( - requests_to_process, - encs=encs[request_ids_to_process], - enc_lens=enc_lens[request_ids_to_process], - ready_state_ids=ready_state_ids, - ) - - if len(ready_state_ids) > 0: - self.text_processor.process([self.get_state(stream_id) for stream_id in ready_state_ids]) - ready_state_ids.clear() - - postponed_requests = next_postponed_requests.copy() - next_postponed_requests.clear() - - self.update_partial_transcript(requests, self.tokenizer, self.leading_regex_pattern) - - def transcribe_step_for_feature_buffers(self, fbuffers: list[FeatureBuffer]) -> None: - """ - Transcribe a step for feature buffers. - Args: - fbuffers: (list[FeatureBuffer]) List of feature buffers to transcribe. - """ - encs, enc_lens = self.encode_feature_buffers(fbuffers) - if encs is not None: - if self.stateful: - self.shared_transcribe_step_stateful(requests=fbuffers, encs=encs, enc_lens=enc_lens) - else: - self.shared_transcribe_step(requests=fbuffers, encs=encs, enc_lens=enc_lens) - - def transcribe_step_for_frames(self, frames: list[Frame]) -> None: - """ - Transcribe a step for frames. - Args: - frames: (list[Frame]) List of frames to transcribe. - """ - encs, enc_lens = self.encode_frames(frames) - if encs is not None: - if self.stateful: - self.shared_transcribe_step_stateful(requests=frames, encs=encs, enc_lens=enc_lens) - else: - self.shared_transcribe_step(requests=frames, encs=encs, enc_lens=enc_lens) - - def get_request_generator(self) -> ContinuousBatchedRequestStreamer: - """ - Initialize the request generator. - Returns: - (ContinuousBatchedRequestStreamer) Request generator. - """ - request_generator = ContinuousBatchedRequestStreamer( - n_frames_per_stream=1, - frame_size_in_secs=self.chunk_size, - sample_rate=self.sample_rate, - batch_size=self.batch_size, - request_type=self.request_type, - preprocessor=self.preprocessor, - buffer_size_in_secs=self.buffer_size_in_secs, - device=self.device, - pad_last_frame=True, - right_pad_features=self.right_padding, - tail_padding_in_samples=self.tail_padding_in_samples, - ) - return request_generator diff --git a/nemo/collections/asr/inference/pipelines/buffered_salm_pipeline.py b/nemo/collections/asr/inference/pipelines/buffered_salm_pipeline.py deleted file mode 100644 index b81c6cca8ebb43401531ca838a1faefd61d23903..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/pipelines/buffered_salm_pipeline.py +++ /dev/null @@ -1,249 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from __future__ import annotations - -from typing import TYPE_CHECKING - -import torch -from omegaconf import DictConfig - -from nemo.collections.asr.inference.model_wrappers.salm_asr_inference_wrapper import SALMASRInferenceWrapper -from nemo.collections.asr.inference.pipelines.base_pipeline import BasePipeline -from nemo.collections.asr.inference.streaming.buffering.incremental_audio_bufferer import ( - BatchedIncrementalAudioBufferer, -) -from nemo.collections.asr.inference.streaming.framing.multi_stream import ContinuousBatchedRequestStreamer -from nemo.collections.asr.inference.streaming.framing.request import FeatureBuffer, Frame -from nemo.collections.asr.inference.streaming.framing.request_options import ASRRequestOptions -from nemo.collections.asr.inference.streaming.state.salm_state import SALMStreamingState -from nemo.collections.asr.inference.utils.enums import ASROutputGranularity, MergingStrategy, RequestType -from nemo.collections.asr.inference.utils.lcs_merge import lcs_merge -from nemo.utils.decorators import experimental - -if TYPE_CHECKING: - from nemo.collections.asr.inference.itn.inverse_normalizer import AlignmentPreservingInverseNormalizer - from nemo.collections.asr.inference.nmt.llm_translator import LLMTranslator - - -def parse_hyp(answer: torch.Tensor, eos_tokens: list[int]): - """ - Parse the hypothesis. Extract the tokens before the EOS tokens. - Args: - answer: (torch.Tensor) Answer tensor. - eos_tokens: (list[int]) EOS tokens. - Returns: - (torch.Tensor) Parsed hypothesis. - """ - end = torch.isin(answer, torch.tensor(eos_tokens)).nonzero(as_tuple=True)[0] - if end.numel() == 0: - return answer - end = end[0] - return answer[:end] - - -@experimental -class BufferedSALMPipeline(BasePipeline): - """Buffered SALM pipeline.""" - - def __init__( - self, - cfg: DictConfig, - asr_model: SALMASRInferenceWrapper, - itn_model: AlignmentPreservingInverseNormalizer | None = None, - nmt_model: LLMTranslator | None = None, - ): - """ - Initialize the BufferedSALMPipeline. - Args: - cfg: (DictConfig) Configuration parameters. - asr_model: (SALMASRInferenceWrapper) ASR model. - itn_model: (AlignmentPreservingInverseNormalizer | None) Inverse Text Normalization model. - nmt_model: (LLMTranslator | None) LLM based translation model. - """ - self.asr_model = asr_model - self.init_parameters(cfg) - self.init_nmt_model(nmt_model) - super().__init__() - - def init_parameters(self, cfg: DictConfig) -> None: - """ - Initialize the parameters. - Args: - cfg: (DictConfig) Configuration parameters. - """ - self.sample_rate = cfg.streaming.sample_rate - self.asr_output_granularity = ASROutputGranularity.from_str(cfg.asr_output_granularity) - if self.asr_output_granularity is ASROutputGranularity.WORD: - raise ValueError("Word level output granularity is not supported for SALM AED pipeline") - - self.batch_size = cfg.streaming.batch_size - self.max_new_tokens = cfg.streaming.max_new_tokens - self.device = self.asr_model.device - self.stop_history_eou_in_milliseconds = cfg.endpointing.stop_history_eou - - self.chunk_size_in_secs = cfg.streaming.chunk_size - self.buffer_size_in_secs = cfg.streaming.buffer_size - self.overlap_size_in_secs = cfg.streaming.overlap_size - self.overlap_ratio = self.overlap_size_in_secs / self.buffer_size_in_secs - self.extra_overlap_tokens = 2 # extra tokens for better overlap detection - self.merging_strategy = MergingStrategy.from_str(cfg.streaming.merging_strategy) - - self.audio_bufferer = BatchedIncrementalAudioBufferer( - self.sample_rate, - self.buffer_size_in_secs, - self.chunk_size_in_secs, - self.overlap_size_in_secs, - ) - - self.request_type = RequestType.from_str(cfg.streaming.request_type) - if self.request_type is RequestType.FEATURE_BUFFER: - raise ValueError("Feature buffer request type is not supported for SALM pipeline") - - self.prompts = [[{"role": "user", "content": f"Transcribe the following: {self.asr_model.audio_locator_tag}"}]] - self.tokens = self.asr_model.preprocess_prompts(self.prompts) - - def create_state(self, options: ASRRequestOptions) -> SALMStreamingState: - """ - Create new empty state. - Args: - options: (ASRRequestOptions) Request options for particular stream. - Returns: - (SALMStreamingState) New empty state. - """ - state = SALMStreamingState() - state.set_global_offset(0) - new_options = options.augment_with_defaults( - default_enable_itn=False, - default_enable_pnc=False, - default_enable_nmt=False, - default_source_language=None, - default_target_language=None, - default_stop_history_eou=self.stop_history_eou_in_milliseconds, - default_asr_output_granularity=self.asr_output_granularity, - default_language_code=None, - ) - state.set_options(new_options) - return state - - def get_sep(self) -> str: - """Return the separator for the text processor.""" - return self.asr_model.word_separator - - def lcs_merge(self, state: SALMStreamingState, data: list[int]) -> None: - """ - Merge the buffer and data using the LCS algorithm. - Args: - state: (SALMStreamingState) The state of the streaming pipeline. - data: (list[int]) The new tokens to merge with the buffer. - """ - if len(state.tokens) == 0: - state.tokens.extend(data) - return - - # extra overlap tokens for better overlap detection - delay = int(self.overlap_ratio * len(data)) + self.extra_overlap_tokens - state.tokens = lcs_merge( - buffer=state.tokens, - data=data[:delay], - search_size=delay, - sep_id=self.asr_model.word_separator_ids, - min_lcs_length=1, - merging_strategy=self.merging_strategy, - ) - state.tokens.extend(data[delay:]) - - def transcribe_step_for_frames(self, frames: list[Frame]) -> None: - """ - Perform the transcribe step for frames. - Args: - frames: (list[Frame]) List of frames to transcribe. - """ - buffers, paddings = self.audio_bufferer.update(frames) - paddings = torch.tensor(paddings, dtype=torch.int64, device=self.device) - - # Right paddings for the final frames - # Only for last frames frame.size is greater than frame.valid_size - right_paddings = torch.tensor( - [int(frame.size - frame.valid_size) for frame in frames], dtype=torch.int64, device=self.device - ).clamp(min=0) - - # stack buffers - audios = torch.cat([buffer.unsqueeze_(0) for buffer in buffers]).to(self.device) - audio_lens = torch.tensor([audios.size(1)] * audios.size(0), dtype=torch.int64, device=self.device) - audio_lens = audio_lens - paddings - right_paddings - - answer_ids = self.asr_model.generate( - prompts=self.tokens.expand(len(audios), -1), - audios=audios, - audio_lens=audio_lens, - max_new_tokens=self.max_new_tokens, - ).cpu() - - for i, frame in enumerate(frames): - state = self.get_state(frame.stream_id) - new_tokens = parse_hyp(answer_ids[i], self.asr_model.eos_token_ids).tolist() - state.incomplete_segment_tokens.clear() - if self.audio_bufferer.is_full(frame.stream_id) or frame.is_last: - self.lcs_merge(state, new_tokens) - else: - state.incomplete_segment_tokens.extend(new_tokens) - - if frame.is_last: - state.final_transcript = self.asr_model.tokenizer.ids_to_text(state.tokens) - state.partial_transcript = "" - else: - all_tokens = state.tokens.copy() - if len(state.incomplete_segment_tokens) > 0: - # extra overlap tokens for better overlap detection - delay = int(self.overlap_ratio * len(state.incomplete_segment_tokens)) + self.extra_overlap_tokens - all_tokens = lcs_merge( - buffer=all_tokens, - data=state.incomplete_segment_tokens[:delay], - search_size=delay, - sep_id=self.asr_model.word_separator_ids, - min_lcs_length=1, - merging_strategy=self.merging_strategy, - ) - all_tokens.extend(state.incomplete_segment_tokens[delay:]) - - if len(all_tokens) > 0: - state.partial_transcript = self.asr_model.tokenizer.ids_to_text(all_tokens) - else: - state.partial_transcript = "" - - def transcribe_step_for_feature_buffers(self, fbuffers: list[FeatureBuffer]) -> None: - """ - Transcribe a step for feature buffers. - Args: - fbuffers: (list[FeatureBuffer]) List of feature buffers to transcribe. - """ - raise NotImplementedError("Feature buffer request type is not supported for SALM pipeline") - - def get_request_generator(self) -> ContinuousBatchedRequestStreamer: - """ - Initialize the request generator. - Returns: - (ContinuousBatchedRequestStreamer) Request generator. - """ - request_generator = ContinuousBatchedRequestStreamer( - n_frames_per_stream=1, - frame_size_in_secs=self.chunk_size_in_secs, - sample_rate=self.sample_rate, - batch_size=self.batch_size, - request_type=self.request_type, - pad_last_frame=True, - ) - return request_generator diff --git a/nemo/collections/asr/inference/pipelines/cache_aware_ctc_pipeline.py b/nemo/collections/asr/inference/pipelines/cache_aware_ctc_pipeline.py deleted file mode 100644 index 91c86072d62f1a70c98f66681bdf46bee74cacd9..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/pipelines/cache_aware_ctc_pipeline.py +++ /dev/null @@ -1,432 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from __future__ import annotations - -import math -from typing import TYPE_CHECKING - -import numpy as np -import torch -from omegaconf import DictConfig -from torch import Tensor - -from nemo.collections.asr.inference.model_wrappers.cache_aware_ctc_inference_wrapper import ( - CacheAwareCTCInferenceWrapper, -) -from nemo.collections.asr.inference.pipelines.base_pipeline import BasePipeline -from nemo.collections.asr.inference.streaming.decoders.greedy.greedy_ctc_decoder import CTCGreedyDecoder -from nemo.collections.asr.inference.streaming.endpointing.greedy.greedy_ctc_endpointing import CTCGreedyEndpointing -from nemo.collections.asr.inference.streaming.framing.multi_stream import ContinuousBatchedRequestStreamer -from nemo.collections.asr.inference.streaming.framing.request import FeatureBuffer, Frame, Request -from nemo.collections.asr.inference.streaming.framing.request_options import ASRRequestOptions -from nemo.collections.asr.inference.streaming.state.cache_aware_ctc_state import CacheAwareCTCStreamingState -from nemo.collections.asr.inference.utils.endpointing_utils import millisecond_to_frames -from nemo.collections.asr.inference.utils.enums import RequestType -from nemo.collections.asr.inference.utils.pipeline_utils import ( - check_existance_of_required_attributes, - drop_trailing_features, - get_confidence_utils, - normalize_log_probs, -) - -if TYPE_CHECKING: - from nemo.collections.asr.inference.itn.inverse_normalizer import AlignmentPreservingInverseNormalizer - from nemo.collections.asr.inference.nmt.llm_translator import LLMTranslator - - -class CacheAwareCTCPipeline(BasePipeline): - """Cache Aware CTC pipeline.""" - - def __init__( - self, - cfg: DictConfig, - asr_model: CacheAwareCTCInferenceWrapper, - itn_model: AlignmentPreservingInverseNormalizer | None = None, - nmt_model: LLMTranslator | None = None, - ): - """ - Initialize the CacheAwareCTCPipeline. - Args: - cfg: (DictConfig) Configuration parameters. - asr_model: (CacheAwareCTCInferenceWrapper) ASR model. - itn_model: (AlignmentPreservingInverseNormalizer | None) Inverse Text Normalization model. - """ - self.copy_asr_model_attributes(asr_model) - self.init_parameters(cfg) - self.init_context_manager() - self.init_bufferer_for_cache_aware_streaming() - self.conf_func, self.confidence_aggregator = get_confidence_utils(cfg.confidence) - self.init_bpe_decoder() - self.init_greedy_ctc_decoder() - self.init_endpointer() - self.init_text_processor(cfg, itn_model) - self.init_nmt_model(nmt_model) - super().__init__() - - def init_parameters(self, cfg: DictConfig) -> None: - """ - Initialize the configuration parameters. - Args: - cfg: (DictConfig) Configuration parameters. - """ - if cfg.streaming.att_context_size is not None: - self.asr_model.set_default_att_context_size(att_context_size=cfg.streaming.att_context_size) - self.sample_rate = cfg.streaming.sample_rate - self.asr_output_granularity = cfg.asr_output_granularity - - self.use_cache = cfg.streaming.use_cache - self.use_feat_cache = cfg.streaming.use_feat_cache - self.batch_size = cfg.streaming.batch_size - self.num_slots = cfg.streaming.num_slots - if self.num_slots < self.batch_size: - raise ValueError( - f"Number of slots in the context manager must be >= batch_size: {self.num_slots} < {self.batch_size}" - ) - self.request_type = RequestType.from_str(cfg.streaming.request_type) - self.word_boundary_tolerance = cfg.streaming.word_boundary_tolerance - self.stop_history_eou_in_milliseconds = cfg.endpointing.stop_history_eou - self.residue_tokens_at_end = cfg.endpointing.residue_tokens_at_end - self.return_tail_result = cfg.return_tail_result - - self.pre_encode_cache_size = self.asr_model.get_pre_encode_cache_size() - self.model_chunk_size = self.asr_model.get_chunk_size() - if isinstance(self.model_chunk_size, list): - self.model_chunk_size = self.model_chunk_size[1] - - if cfg.streaming.get("chunk_size_in_secs", None) is not None: - self.chunk_size_in_secs = cfg.streaming.chunk_size_in_secs - self.tokens_per_frame = math.ceil( - np.trunc(self.chunk_size_in_secs / self.window_stride) / self.subsampling_factor - ) - # overwrite the encoder streaming params with proper shift size for cache aware streaming - self.asr_model.setup_streaming_params( - chunk_size=self.model_chunk_size // self.subsampling_factor, shift_size=self.tokens_per_frame - ) - else: - self.chunk_size_in_secs = self.model_chunk_size * self.window_stride - self.tokens_per_frame = math.ceil(self.model_chunk_size / self.subsampling_factor) - - if isinstance(self.pre_encode_cache_size, list): - self.pre_encode_cache_size = self.pre_encode_cache_size[1] - self.pre_encode_cache_size_in_secs = self.pre_encode_cache_size * self.window_stride - - model_chunk_size_in_secs = self.model_chunk_size * self.window_stride - - if self.use_cache: - # if using cache, we need to pad some samples for pre_encode - self.buffer_size_in_secs = self.pre_encode_cache_size_in_secs + model_chunk_size_in_secs - self.drop_left_context = None - self.valid_out_len = None - else: - # if not using cache, we need to keep left context in buffer, but no extra padding in pre_encode - left_context_size = self.asr_model.get_att_context_size()[0] - if left_context_size < 0: - raise ValueError(f"Left context size should not be a negative value: {left_context_size}") - self.buffer_size_in_secs = ( - model_chunk_size_in_secs + left_context_size * self.subsampling_factor * self.window_stride - ) - self.drop_left_context = left_context_size - self.valid_out_len = self.tokens_per_frame - - # Expected feature buffer length for trimming (safeguard for feature buffer inputs) - self.expected_feature_buffer_len = int(self.buffer_size_in_secs / self.window_stride) - - def init_greedy_ctc_decoder(self) -> None: - """Initialize the CTC decoder.""" - check_existance_of_required_attributes(self, ['vocabulary', 'conf_func']) - self.greedy_ctc_decoder = CTCGreedyDecoder(vocabulary=self.vocabulary, conf_func=self.conf_func) - - def init_endpointer(self) -> None: - """Initialize the endpointer.""" - check_existance_of_required_attributes( - self, - [ - 'vocabulary', - 'model_stride_in_milliseconds', - 'stop_history_eou_in_milliseconds', - 'residue_tokens_at_end', - ], - ) - - self.endpointer = CTCGreedyEndpointing( - vocabulary=self.vocabulary, - ms_per_timestep=self.model_stride_in_milliseconds, - stop_history_eou=self.stop_history_eou_in_milliseconds, - residue_tokens_at_end=self.residue_tokens_at_end, - ) - - def create_state(self, options: ASRRequestOptions) -> CacheAwareCTCStreamingState: - """ - Create new empty state. - Args: - options: (ASRRequestOptions) Request options for particular stream. - Returns: - (CacheAwareCTCStreamingState) New empty state. - """ - state = CacheAwareCTCStreamingState() - state.set_global_offset(0) - new_options = options.augment_with_defaults( - default_enable_itn=self.text_processor.is_itn_enabled(), - default_enable_pnc=self.text_processor.is_pnc_enabled(), - default_enable_nmt=self.nmt_enabled, - default_source_language=self.nmt_model.source_language if self.nmt_enabled else None, - default_target_language=self.nmt_model.target_language if self.nmt_enabled else None, - default_stop_history_eou=self.stop_history_eou_in_milliseconds, - default_asr_output_granularity=self.asr_output_granularity, - ) - - eou_label_buffer_size = 0 - if new_options.stop_history_eou > 0: - eou_label_buffer_size = millisecond_to_frames( - new_options.stop_history_eou, math.ceil(self.model_stride_in_milliseconds) - ) - eou_label_buffer_size += self.residue_tokens_at_end - state.setup_label_buffer(eou_label_buffer_size, self.blank_id) - state.set_options(new_options) - return state - - def get_sep(self) -> str: - """Return the separator for the text processor.""" - return self.sep - - def preprocess(self, buffers: list[Tensor], right_paddings: list[int] | None = None) -> tuple[Tensor, Tensor]: - """ - Preprocess the feature buffers by stacking them and computing the lengths - Args: - buffers: (list[Tensor]) List of feature buffers. - right_paddings: (list[int] | None) List of right paddings. - Returns: - (tuple[Tensor, Tensor]) Processed feature buffers and their lengths. - """ - feature_buffers = [f_buffer.unsqueeze_(0) for f_buffer in buffers] - # Trim to expected feature buffer length (safeguard for external feature buffer inputs) - feature_buffers = [ - drop_trailing_features(f_buffer, self.expected_feature_buffer_len) for f_buffer in feature_buffers - ] - feature_buffer_lens = torch.tensor([f_buffer.shape[2] for f_buffer in feature_buffers], device=self.device) - if right_paddings is not None: - right_paddings = torch.tensor(right_paddings, device=feature_buffer_lens.device) - feature_buffer_lens = feature_buffer_lens - right_paddings - feature_buffers = torch.cat(feature_buffers).to(self.device) - return feature_buffers, feature_buffer_lens - - def run_greedy_decoder(self, state: CacheAwareCTCStreamingState, request: Request, log_probs: Tensor): - """ - Run the greedy CTC decoder on the log_probs and update the state - Args: - state: (CacheAwareCTCStreamingState) The state of the stream - request: (Request) The current request (frame or feature buffer) - log_probs: (Tensor) The log probabilities of the current request - Returns: - (bool) Whether EOU is detected. - """ - eou_detected = request.is_last - last_token = state.label_buffer[-1] if len(state.label_buffer) > 0 else self.blank_id - cur_output = self.greedy_ctc_decoder(log_probs, compute_confidence=True, previous=last_token) - state.update_label_buffer(cur_output["labels"]) - - if not eou_detected: - emissions = state.get_label_buffer() - pivot_point = len(emissions) - 1 - eou_detected, _ = self.endpointer.detect_eou_near_pivot( - emissions, pivot_point, stop_history_eou=state.options.stop_history_eou - ) - - state.update_state(cur_output, eou_detected=eou_detected) - state.increment_global_offset(self.tokens_per_frame) - return eou_detected - - def decode_log_probs( - self, - requests: list[Request], - log_probs: Tensor, - tail_log_probs: Tensor | None, - ready_state_ids: set, - ) -> None: - """ - Decode the log probabilities and update the state - Args: - requests: (list[Request]) List of requests (frames or feature buffers) to transcribe. - log_probs: (Tensor) Log probabilities. - tail_log_probs: (Tensor | None) Tail log probabilities. - ready_state_ids: (set) Set of ready state IDs. - """ - - for idx, request in enumerate(requests): - state = self.get_state(request.stream_id) - eou_detected = self.run_greedy_decoder(state, request, log_probs[idx]) - - if eou_detected: - self.bpe_decoder.decode_bpe_tokens(state) - state.cleanup_after_eou() - ready_state_ids.add(request.stream_id) - - if tail_log_probs is not None: - last_token = state.label_buffer[-1] if len(state.label_buffer) > 0 else self.blank_id - tail_output = self.greedy_ctc_decoder( - tail_log_probs[idx], compute_confidence=False, previous=last_token - ) - state.set_incomplete_segment_tokens(tail_output["tokens"]) - - def cache_aware_transcribe_step( - self, - requests: list[Request], - buffered_features: list[Tensor], - right_paddings: list[int] | None, - ready_state_ids: set, - keep_all_outputs: bool = False, - ) -> None: - """ - Cache Aware Transcribe Step - It receives a list of requests (Frame or FeatureBuffer) and features and do the following: - - 1. Preprocess the features by stacking them and computing the lengths - 2. Get the context and mapping from the context manager for cache aware streaming - 3. Perform a streaming step with the ASR model - 4. Update the cache and reset the cache slots for the streams that has ended - 5. Decode the log probabilities and update the state - - Args: - requests: (list[Request]) List of requests (frames or feature buffers) to transcribe. - buffered_features: (list[Tensor]) List of buffered features. - right_paddings: (list[int] | None) List of right paddings. - ready_state_ids: (set) Set of ready state IDs. - keep_all_outputs: (bool) Whether to keep all outputs or not. - """ - feature_buffers, feature_buffer_lens = self.preprocess(buffered_features, right_paddings) - - stream_ids = [request.stream_id for request in requests] - eos_flags = [request.is_last for request in requests] - context, mapping = self.context_manager.get_context(stream_ids) - - drop_extra_pre_encoded = 0 if not self.use_cache else self.asr_model.drop_extra_pre_encoded - log_probs, tail_log_probs, new_context = self.asr_model.stream_step( - processed_signal=feature_buffers, - processed_signal_length=feature_buffer_lens, - context=context, - drop_extra_pre_encoded=drop_extra_pre_encoded, - keep_all_outputs=keep_all_outputs, - drop_left_context=self.drop_left_context, - valid_out_len=self.valid_out_len, - return_tail_result=self.return_tail_result, - ) - - if log_probs is not None: - log_probs = normalize_log_probs(log_probs) - self.context_manager.update_cache(stream_ids, new_context, mapping) - self.context_manager.reset_slots(stream_ids, eos_flags) - self.decode_log_probs(requests, log_probs, tail_log_probs, ready_state_ids) - - def transcribe_step_for_frames(self, frames: list[Frame]) -> None: - """ - Transcribes the frames in a streaming manner. - After detecting EOU, it updates the state and run text processor. - If there are multiple streams, it waits until all states are ready to run text processor. - Args: - frames: (list[Frame]) List of frames to transcribe. - """ - all_fbuffers, right_paddings = self.bufferer.update(frames) - - ready_state_ids = set() - if len(all_fbuffers) > 0: - nonfinal_frames, nonfinal_fbuffers = [], [] - final_frames, final_fbuffers = [], [] - final_right_paddings = [] - for jdx, bfeature in enumerate(all_fbuffers): - frame = frames[jdx] - if frame.is_last: - final_frames.append(frame) - final_fbuffers.append(bfeature) - final_right_paddings.append(right_paddings[jdx]) - else: - nonfinal_frames.append(frame) - nonfinal_fbuffers.append(bfeature) - - if len(nonfinal_frames) > 0: - self.cache_aware_transcribe_step( - nonfinal_frames, nonfinal_fbuffers, None, ready_state_ids, keep_all_outputs=False - ) - if len(final_frames) > 0: - self.cache_aware_transcribe_step( - final_frames, final_fbuffers, final_right_paddings, ready_state_ids, keep_all_outputs=True - ) - - # Postprocess the ready states - if len(ready_state_ids) > 0: - self.text_processor.process([self.get_state(stream_id) for stream_id in ready_state_ids]) - ready_state_ids.clear() - - self.update_partial_transcript(frames, self.tokenizer, self.leading_regex_pattern) - - def transcribe_step_for_feature_buffers(self, fbuffers: list[FeatureBuffer]) -> None: - """ - Transcribes the feature buffers in a streaming manner. - After detecting EOU, it updates the state and run text processor. - If there are multiple streams, it waits until all states are ready to run text processor. - Args: - fbuffers: (list[FeatureBuffer]) List of feature buffers to transcribe. - """ - ready_state_ids = set() - - final_fbuffers, final_features = [], [] - nonfinal_fbuffers, nonfinal_features = [], [] - final_right_paddings = [] - - for fbuffer in fbuffers: - feature = fbuffer.features - right_padding = max(0, self.expected_feature_buffer_len - fbuffer.valid_size) - - if fbuffer.is_last: - final_fbuffers.append(fbuffer) - final_features.append(feature) - final_right_paddings.append(right_padding) - else: - nonfinal_fbuffers.append(fbuffer) - nonfinal_features.append(feature) - - if len(nonfinal_fbuffers) > 0: - self.cache_aware_transcribe_step( - nonfinal_fbuffers, nonfinal_features, None, ready_state_ids, keep_all_outputs=False - ) - - if len(final_fbuffers) > 0: - self.cache_aware_transcribe_step( - final_fbuffers, final_features, final_right_paddings, ready_state_ids, keep_all_outputs=True - ) - - if len(ready_state_ids) > 0: - self.text_processor.process([self.get_state(stream_id) for stream_id in ready_state_ids]) - ready_state_ids.clear() - - self.update_partial_transcript(fbuffers, self.tokenizer, self.leading_regex_pattern) - - def get_request_generator(self) -> ContinuousBatchedRequestStreamer: - """ - Initialize the request generator. - Returns: - (ContinuousBatchedRequestStreamer) Request generator. - """ - request_generator = ContinuousBatchedRequestStreamer( - n_frames_per_stream=1, - frame_size_in_secs=self.chunk_size_in_secs, - sample_rate=self.sample_rate, - batch_size=self.batch_size, - request_type=self.request_type, - preprocessor=self.preprocessor, - buffer_size_in_secs=self.buffer_size_in_secs, - device=self.device, - pad_last_frame=True, - ) - return request_generator diff --git a/nemo/collections/asr/inference/pipelines/cache_aware_rnnt_pipeline.py b/nemo/collections/asr/inference/pipelines/cache_aware_rnnt_pipeline.py deleted file mode 100644 index 2b4de83dac1ca345719fada152a225d9116dedb6..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/pipelines/cache_aware_rnnt_pipeline.py +++ /dev/null @@ -1,494 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from __future__ import annotations - -import math -from typing import TYPE_CHECKING - -import numpy as np -import torch -from omegaconf import DictConfig -from torch import Tensor - -from nemo.collections.asr.inference.model_wrappers.cache_aware_rnnt_inference_wrapper import ( - CacheAwareRNNTInferenceWrapper, -) -from nemo.collections.asr.inference.pipelines.base_pipeline import BasePipeline -from nemo.collections.asr.inference.streaming.decoders.greedy.greedy_rnnt_decoder import RNNTGreedyDecoder -from nemo.collections.asr.inference.streaming.endpointing.greedy.greedy_rnnt_endpointing import RNNTGreedyEndpointing -from nemo.collections.asr.inference.streaming.framing.multi_stream import ContinuousBatchedRequestStreamer -from nemo.collections.asr.inference.streaming.framing.request import FeatureBuffer, Frame, Request -from nemo.collections.asr.inference.streaming.framing.request_options import ASRRequestOptions -from nemo.collections.asr.inference.streaming.state.cache_aware_rnnt_state import CacheAwareRNNTStreamingState -from nemo.collections.asr.inference.utils.endpointing_utils import millisecond_to_frames -from nemo.collections.asr.inference.utils.enums import RequestType -from nemo.collections.asr.inference.utils.pipeline_utils import ( - check_existance_of_required_attributes, - drop_trailing_features, - get_confidence_utils, -) -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis -from nemo.utils import logging - -if TYPE_CHECKING: - from nemo.collections.asr.inference.itn.inverse_normalizer import AlignmentPreservingInverseNormalizer - from nemo.collections.asr.inference.nmt.llm_translator import LLMTranslator - - -class CacheAwareRNNTPipeline(BasePipeline): - """Cache Aware RNNT pipeline.""" - - def __init__( - self, - cfg: DictConfig, - asr_model: CacheAwareRNNTInferenceWrapper, - itn_model: AlignmentPreservingInverseNormalizer | None = None, - nmt_model: LLMTranslator | None = None, - ): - """ - Initialize the CacheAwareRNNTPipeline. - Args: - cfg: (DictConfig) Configuration parameters. - asr_model: (CacheAwareRNNTInferenceWrapper) ASR model. - itn_model: (AlignmentPreservingInverseNormalizer | None) Inverse Text Normalization model. - nmt_model: (LLMTranslator | None) LLM based translation model. - """ - self.copy_asr_model_attributes(asr_model) - self.init_prompt_support() - self.init_parameters(cfg) - self.init_context_manager() - self.init_bufferer_for_cache_aware_streaming() - self.conf_func, self.confidence_aggregator = get_confidence_utils(cfg.confidence) - self.init_bpe_decoder() - self.init_greedy_rnnt_decoder() - self.init_endpointer() - self.init_text_processor(cfg, itn_model) - self.init_nmt_model(nmt_model) - super().__init__() - - def init_parameters(self, cfg: DictConfig) -> None: - """ - Initialize the parameters. - Args: - cfg: (DictConfig) Configuration parameters. - """ - if cfg.streaming.att_context_size is not None: - self.asr_model.set_default_att_context_size(att_context_size=cfg.streaming.att_context_size) - - self.sample_rate = cfg.streaming.sample_rate - self.asr_output_granularity = cfg.asr_output_granularity - self.pre_encode_cache_size = self.asr_model.get_pre_encode_cache_size() - self.model_chunk_size = self.asr_model.get_chunk_size() - if isinstance(self.model_chunk_size, list): - self.model_chunk_size = self.model_chunk_size[1] - - self.use_cache = cfg.streaming.use_cache - self.use_feat_cache = cfg.streaming.use_feat_cache - - if cfg.streaming.get("chunk_size_in_secs", None) is not None: - self.chunk_size_in_secs = cfg.streaming.chunk_size_in_secs - self.tokens_per_frame = math.ceil( - np.trunc(self.chunk_size_in_secs / self.window_stride) / self.subsampling_factor - ) - # overwrite the encoder streaming params with proper shift size for cache aware streaming - self.asr_model.setup_streaming_params( - chunk_size=self.model_chunk_size // self.subsampling_factor, shift_size=self.tokens_per_frame - ) - else: - self.chunk_size_in_secs = self.model_chunk_size * self.window_stride - self.tokens_per_frame = math.ceil(self.model_chunk_size / self.subsampling_factor) - - if isinstance(self.pre_encode_cache_size, list): - self.pre_encode_cache_size = self.pre_encode_cache_size[1] - self.pre_encode_cache_size_in_secs = self.pre_encode_cache_size * self.window_stride - - # Context Manager - self.batch_size = cfg.streaming.batch_size - self.num_slots = cfg.streaming.num_slots - if self.num_slots < self.batch_size: - raise ValueError( - f"Number of slots in the context manager must be >= batch_size: {self.num_slots} < {self.batch_size}" - ) - model_chunk_size_in_secs = self.model_chunk_size * self.window_stride - - if self.use_cache: - # if using cache, we need to pad some samples for pre_encode - self.buffer_size_in_secs = self.pre_encode_cache_size_in_secs + model_chunk_size_in_secs - self.drop_left_context = None - self.valid_out_len = None - else: - # if not using cache, we need to keep left context in buffer, but no extra padding in pre_encode - left_context_size = self.asr_model.get_att_context_size()[0] - if left_context_size < 0: - raise ValueError(f"Left context size should not be a negative value: {left_context_size}") - self.buffer_size_in_secs = ( - model_chunk_size_in_secs + left_context_size * self.subsampling_factor * self.window_stride - ) - self.drop_left_context = left_context_size - self.valid_out_len = self.tokens_per_frame - - # Expected feature buffer length for trimming (safeguard for feature buffer inputs) - self.expected_feature_buffer_len = int(self.buffer_size_in_secs / self.window_stride) - - self.stop_history_eou_in_milliseconds = cfg.endpointing.stop_history_eou - self.residue_tokens_at_end = cfg.endpointing.residue_tokens_at_end - self.word_boundary_tolerance = cfg.streaming.word_boundary_tolerance - self.return_tail_result = cfg.return_tail_result - - self.request_type = RequestType.from_str(cfg.streaming.request_type) - - def init_greedy_rnnt_decoder(self) -> None: - """Initialize the RNNT decoder.""" - check_existance_of_required_attributes(self, ['vocabulary', 'conf_func']) - self.greedy_rnnt_decoder = RNNTGreedyDecoder(vocabulary=self.vocabulary, conf_func=self.conf_func) - - def init_endpointer(self) -> None: - """Initialize the endpointer.""" - check_existance_of_required_attributes( - self, - [ - 'vocabulary', - 'model_stride_in_milliseconds', - 'stop_history_eou_in_milliseconds', - 'residue_tokens_at_end', - ], - ) - - self.endpointer = RNNTGreedyEndpointing( - vocabulary=self.vocabulary, - ms_per_timestep=self.model_stride_in_milliseconds, - stop_history_eou=self.stop_history_eou_in_milliseconds, - residue_tokens_at_end=self.residue_tokens_at_end, - ) - - def create_state(self, options: ASRRequestOptions) -> CacheAwareRNNTStreamingState: - """ - Create new empty state. - Args: - options: (ASRRequestOptions) Request options for particular stream. - Returns: - (CacheAwareRNNTStreamingState) New empty state. - """ - state = CacheAwareRNNTStreamingState() - state.set_global_offset(0) - new_options = options.augment_with_defaults( - default_enable_itn=self.text_processor.is_itn_enabled(), - default_enable_pnc=self.text_processor.is_pnc_enabled(), - default_enable_nmt=self.nmt_enabled, - default_source_language=self.nmt_model.source_language if self.nmt_enabled else None, - default_target_language=self.nmt_model.target_language if self.nmt_enabled else None, - default_stop_history_eou=self.stop_history_eou_in_milliseconds, - default_asr_output_granularity=self.asr_output_granularity, - default_language_code="en-US" if self.prompt_enabled else None, - ) - - eou_label_buffer_size = 0 - if new_options.stop_history_eou > 0: - eou_label_buffer_size = millisecond_to_frames( - new_options.stop_history_eou, math.ceil(self.model_stride_in_milliseconds) - ) - eou_label_buffer_size += self.residue_tokens_at_end - state.setup_label_buffer(eou_label_buffer_size, self.blank_id) - state.set_previous_hypothesis(None) - state.set_options(new_options) - - # Create per-stream prompt index for prompt-enabled models - if self.prompt_enabled: - lang_code = getattr(new_options, "language_code", None) - if not isinstance(lang_code, str) or len(lang_code) == 0: - raise ValueError("Prompt-enabled model requires a valid language_code in request options.") - prompt_idx = self._resolve_prompt_index(lang_code) - state.set_prompt_index(prompt_idx) - - return state - - def get_sep(self) -> str: - """Return the separator for the text processor.""" - return self.sep - - def preprocess(self, buffers: list[Tensor], right_paddings: list[int] | None = None) -> tuple[Tensor, Tensor]: - """ - Preprocess the feature buffers by stacking them and computing the lengths - Args: - buffers: (list[Tensor]) List of feature buffers. - right_paddings: (list[int] | None) List of right paddings. - Returns: - (tuple[Tensor, Tensor]) Processed feature buffers and their lengths. - """ - feature_buffers = [f_buffer.unsqueeze_(0) for f_buffer in buffers] - # Trim to expected feature buffer length (safeguard for external feature buffer inputs) - feature_buffers = [ - drop_trailing_features(f_buffer, self.expected_feature_buffer_len) for f_buffer in feature_buffers - ] - feature_buffer_lens = torch.tensor([f_buffer.shape[2] for f_buffer in feature_buffers], device=self.device) - if right_paddings is not None: - right_paddings = torch.tensor(right_paddings, device=feature_buffer_lens.device) - feature_buffer_lens = feature_buffer_lens - right_paddings - feature_buffers = torch.cat(feature_buffers).to(self.device) - return feature_buffers, feature_buffer_lens - - def run_greedy_decoder(self, state: CacheAwareRNNTStreamingState, request: Request, hyp: Hypothesis) -> bool: - """ - Run the greedy RNNT decoder on the hypothesis and update the state - Args: - state: (CacheAwareRNNTStreamingState) The state of the stream - request: (Request) The current request (frame or feature buffer) - hyp: (Hypothesis) The hypothesis of the current request - Returns: - (bool) Whether EOU is detected. - """ - eou_detected = request.is_last - cur_output, cur_labels, new_offset = self.greedy_rnnt_decoder( - global_timestamps=hyp.timestamp, - tokens=hyp.y_sequence, - length=self.tokens_per_frame, - offset=state.offset, - ) - state.set_offset(new_offset) - - # cur labels contains blank tokens as well, it is needed for EOU detection - state.update_label_buffer(cur_labels) - - if not eou_detected: - emissions = state.get_label_buffer() - pivot_point = len(emissions) - 1 - eou_detected, _ = self.endpointer.detect_eou_near_pivot( - emissions, pivot_point, stop_history_eou=state.options.stop_history_eou - ) - - state.update_state(cur_output, eou_detected=eou_detected) - return eou_detected - - def cache_aware_transcribe_step( - self, - requests: list[Request], - features: list[Tensor], - right_paddings: list[int], - ready_state_ids: set, - keep_all_outputs: bool = False, - ) -> None: - """ - Cache Aware Transcribe Step - It receives a list of requests (Frame or FeatureBuffer) and features and do the following: - - 1. Preprocess the features by stacking them and computing the lengths - 2. Collecting previous hypotheses for stateful decoding - 3. Get the context and mapping from the context manager for cache aware streaming - 4. Perform a streaming step with the ASR model - 5. Update the cache and reset the cache slots for the streams that has ended - 6. Update the previous hypothesis and reset the previous hypothesis for the streams that has ended - 7. Perform greedy RNNT decoding to get the best hypothesis and update the states - 8. Update the ready states to indicate that the state is ready for text post-processing - Args: - requests: (list[Request]) List of requests (frames or feature buffers) to transcribe. - features: (list[Tensor]) List of feature buffers. - right_paddings: (list[int] | None) List of right paddings. - ready_state_ids: (set) Set of ready state IDs. - keep_all_outputs: (bool) Whether to keep all outputs or not. - """ - - feature_buffers, feature_buffer_lens = self.preprocess(features, right_paddings) - states, stream_ids, eos_flags = [], [], [] - for request in requests: - states.append(self.get_state(request.stream_id)) - stream_ids.append(request.stream_id) - eos_flags.append(request.is_last) - - previous_hypotheses = [state.get_previous_hypothesis() for state in states] - - try: - decoding_computer = self.asr_model.asr_model.decoding.decoding.decoding_computer - biasing_enabled = decoding_computer.per_stream_biasing_enabled - except AttributeError: - decoding_computer = None - biasing_enabled = False - - if not biasing_enabled and any(state.has_biasing_request() for state in states): - logging.warning("Biasing request is not empty, but decoder does not support per-stream biasing. Skipping") - - # Handle per-stream biasing: add biasing models to multi_model if needed - if biasing_enabled: - for i, (request, state, previous_hyp) in enumerate(zip(requests, states, previous_hypotheses)): - if state.has_biasing_request(): - if state.options.biasing_cfg.multi_model_id is None: - if state.options.biasing_cfg.auto_manage_multi_model: - state.options.biasing_cfg.add_to_multi_model( - tokenizer=self.asr_model.tokenizer, - biasing_multi_model=decoding_computer.biasing_multi_model, - ) - else: - logging.warning( - "Biasing request is not empty, not auto managed and not compiled. Skipping" - ) - if previous_hyp is None: - previous_hypotheses[i] = Hypothesis.empty_with_biasing_cfg(state.options.biasing_cfg) - else: - previous_hyp.biasing_cfg = state.options.biasing_cfg - - context, mapping = self.context_manager.get_context(stream_ids) - - prompt_vectors = None - if self.prompt_enabled: - prompt_vectors = self._build_prompt_vectors(states) - - drop_extra_pre_encoded = 0 if not self.use_cache else self.asr_model.drop_extra_pre_encoded - best_hyp, new_context = self.asr_model.stream_step( - processed_signal=feature_buffers, - processed_signal_length=feature_buffer_lens, - context=context, - previous_hypotheses=previous_hypotheses, - drop_extra_pre_encoded=drop_extra_pre_encoded, - keep_all_outputs=keep_all_outputs, - drop_left_context=self.drop_left_context, - valid_out_len=self.valid_out_len, - prompt_vectors=prompt_vectors, - ) - - # update the cache and reset the cache slots for the streams that has ended - self.context_manager.update_cache(stream_ids, new_context, mapping) - self.context_manager.reset_slots(stream_ids, eos_flags) - - # update the previous hypothesis and reset the previous hypothesis for the streams that has ended - for state, hyp, eos in zip(states, best_hyp, eos_flags): - if eos: - state.reset_previous_hypothesis() - else: - state.set_previous_hypothesis(hyp) - - # run greedy decoder for each request-state-hypothesis tuple - for request, state, hyp in zip(requests, states, best_hyp): - eou_detected = self.run_greedy_decoder(state, request, hyp) - if eou_detected: - self.bpe_decoder.decode_bpe_tokens(state) - state.cleanup_after_eou() - ready_state_ids.add(request.stream_id) - - # Cleanup per-stream biasing models when stream ends - if biasing_enabled: - for request, state in zip(requests, states): - # only the first request contains biasing options; biasing options for the stream are stored in state - if request.is_last and state.has_biasing_request(): - if state.options.biasing_cfg.auto_manage_multi_model: - state.options.biasing_cfg.remove_from_multi_model( - biasing_multi_model=decoding_computer.biasing_multi_model - ) - - def transcribe_step_for_feature_buffers(self, fbuffers: list[FeatureBuffer]) -> None: - """ - Transcribes the feature buffers in a streaming manner. - After detecting EOU, it updates the state and run text processor. - If there are multiple streams, it waits until all states are ready to run text processor. - Args: - fbuffers: (list[FeatureBuffer]) List of feature buffers to transcribe. - """ - ready_state_ids = set() - - final_fbuffers, final_features = [], [] - nonfinal_fbuffers, nonfinal_features = [], [] - final_right_paddings = [] - - for fbuffer in fbuffers: - feature = fbuffer.features - right_padding = max(0, self.expected_feature_buffer_len - fbuffer.valid_size) - - if fbuffer.is_last: - final_fbuffers.append(fbuffer) - final_features.append(feature) - final_right_paddings.append(right_padding) - else: - nonfinal_fbuffers.append(fbuffer) - nonfinal_features.append(feature) - - if len(nonfinal_fbuffers) > 0: - self.cache_aware_transcribe_step( - nonfinal_fbuffers, nonfinal_features, None, ready_state_ids, keep_all_outputs=False - ) - - if len(final_fbuffers) > 0: - self.cache_aware_transcribe_step( - final_fbuffers, final_features, final_right_paddings, ready_state_ids, keep_all_outputs=True - ) - - if len(ready_state_ids) > 0: - self.text_processor.process([self.get_state(stream_id) for stream_id in ready_state_ids]) - ready_state_ids.clear() - - self.update_partial_transcript(fbuffers, self.tokenizer, self.leading_regex_pattern) - - def transcribe_step_for_frames(self, frames: list[Frame]) -> None: - """ - Transcribes the frames in a streaming manner. - After detecting EOU, it updates the state and run text processor. - If there are multiple streams, it waits until all states are ready to run text processor. - Args: - frames: (list[Frame]) List of frames to transcribe. - """ - - all_fbuffers, right_paddings = self.bufferer.update(frames) - ready_state_ids = set() - - # streams that contains multiple frames - if len(all_fbuffers) > 0: - final_frames, final_fbuffers = [], [] - nonfinal_frames, nonfinal_fbuffers = [], [] - final_right_paddings = [] - - for jdx, bfeature in enumerate(all_fbuffers): - bframe = frames[jdx] - - if bframe.is_last: - final_frames.append(bframe) - final_fbuffers.append(bfeature) - final_right_paddings.append(right_paddings[jdx]) - else: - nonfinal_frames.append(bframe) - nonfinal_fbuffers.append(bfeature) - - if len(nonfinal_frames) > 0: - self.cache_aware_transcribe_step( - nonfinal_frames, nonfinal_fbuffers, None, ready_state_ids, keep_all_outputs=False - ) - - if len(final_frames) > 0: - self.cache_aware_transcribe_step( - final_frames, final_fbuffers, final_right_paddings, ready_state_ids, keep_all_outputs=True - ) - - # post-process the ready states - if len(ready_state_ids) > 0: - self.text_processor.process([self.get_state(stream_id) for stream_id in ready_state_ids]) - ready_state_ids.clear() - - self.update_partial_transcript(frames, self.tokenizer, self.leading_regex_pattern) - - def get_request_generator(self) -> ContinuousBatchedRequestStreamer: - """ - Initialize the request generator. - Returns: - (ContinuousBatchedRequestStreamer) Request generator. - """ - # for cache aware streaming we need to process one frame at a time -> n_frames_per_stream=1 - request_generator = ContinuousBatchedRequestStreamer( - n_frames_per_stream=1, - frame_size_in_secs=self.chunk_size_in_secs, - sample_rate=self.sample_rate, - batch_size=self.batch_size, - request_type=self.request_type, - preprocessor=self.preprocessor, - buffer_size_in_secs=self.buffer_size_in_secs, - device=self.device, - pad_last_frame=True, - ) - return request_generator diff --git a/nemo/collections/asr/inference/pipelines/pipeline_interface.py b/nemo/collections/asr/inference/pipelines/pipeline_interface.py deleted file mode 100644 index a66f879f21fcb4189d73845d2bde142f16f4be22..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/pipelines/pipeline_interface.py +++ /dev/null @@ -1,79 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from abc import ABC, abstractmethod - -from nemo.collections.asr.inference.streaming.framing.request import Request -from nemo.collections.asr.inference.streaming.framing.request_options import ASRRequestOptions - - -class PipelineInterface(ABC): - """ - The base interface for streaming speech pipelines - Base usage for all pipelines: - pipeline.start_session() - for requests in request_generator: - pipeline.transcribe_step(requests) - pipeline.close_session() - """ - - @abstractmethod - def open_session(self): - """ - Open a new session - """ - raise NotImplementedError - - @abstractmethod - def close_session(self): - """ - End the current session - """ - raise NotImplementedError - - @abstractmethod - def get_state(self, stream_id: int): - """ - Get the state of the stream - """ - raise NotImplementedError - - @abstractmethod - def delete_state(self, stream_id: int): - """ - Delete the state of the stream - """ - raise NotImplementedError - - @abstractmethod - def create_state(self, options: ASRRequestOptions): - """ - Create a new empty state - """ - raise NotImplementedError - - @abstractmethod - def init_state(self, stream_id: int, options: ASRRequestOptions): - """ - Initialize the state of the stream - """ - raise NotImplementedError - - @abstractmethod - def transcribe_step(self, requests: list[Request]): - """ - Transcribe a step - """ - raise NotImplementedError diff --git a/nemo/collections/asr/inference/streaming/__init__.py b/nemo/collections/asr/inference/streaming/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/asr/inference/streaming/buffering/__init__.py b/nemo/collections/asr/inference/streaming/buffering/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/buffering/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/asr/inference/streaming/buffering/audio_bufferer.py b/nemo/collections/asr/inference/streaming/buffering/audio_bufferer.py deleted file mode 100644 index c1bc862f3652b06caa22baf6541e870f54f6e309..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/buffering/audio_bufferer.py +++ /dev/null @@ -1,131 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import torch -from torch import Tensor -from nemo.collections.asr.inference.streaming.framing.request import Frame - - -class AudioBufferer: - """ - Audio bufferer class - It buffers the audio chunks and maintains the buffer. - """ - - def __init__(self, sample_rate: int, buffer_size_in_secs: float): - """ - Args: - sample_rate (int): sample rate - buffer_size_in_secs (float): buffer size in seconds - """ - self.buffer_size = int(buffer_size_in_secs * sample_rate) - self.sample_buffer = torch.zeros(self.buffer_size, dtype=torch.float32) - self.left_padding = self.buffer_size - - def reset(self) -> None: - """ - Reset the buffer to zero - """ - self.sample_buffer.zero_() - self.left_padding = self.buffer_size - - def update(self, frame: Frame) -> None: - """ - Update the buffer with the new frame - Args: - frame (Frame): frame to update the buffer with - """ - if frame.size > self.buffer_size: - raise RuntimeError(f"Frame size ({frame.size}) exceeds buffer size ({self.buffer_size})") - - shift = frame.size - self.sample_buffer = torch.roll(self.sample_buffer, -shift) - self.sample_buffer[-shift:].copy_(frame.samples) - self.left_padding = max(0, self.left_padding - shift) - - def get_buffer(self) -> Tensor: - """ - Get the current buffer - Returns: - Tensor: current state of the buffer - """ - return self.sample_buffer.clone() - - def get_left_padding(self) -> int: - """ - Get the left padding - Returns: - int: left padding - """ - return self.left_padding - - -class BatchedAudioBufferer: - """ - Batched audio bufferer class - It buffers the audio chunks from multiple streams and returns the buffers. - """ - - def __init__(self, sample_rate: int, buffer_size_in_secs: float): - """ - Args: - sample_rate (int): sample rate - buffer_size_in_secs (float): buffer size in seconds - """ - self.sample_rate = sample_rate - self.buffer_size_in_secs = buffer_size_in_secs - self.bufferers = {} - - def reset(self) -> None: - """ - Reset bufferers - """ - self.bufferers = {} - - def rm_bufferer(self, stream_id: int) -> None: - """ - Remove bufferer for the given stream id - Args: - stream_id (int): stream id - """ - self.bufferers.pop(stream_id, None) - - def update(self, frames: list[Frame]) -> tuple[list[Tensor], list[int]]: - """ - Update the bufferers with the new frames. - Frames can come from different streams (audios), so we need to maintain a bufferer for each stream - Args: - frames (list[Frame]): list of frames - Returns: - tuple[list[Tensor], list[int]]: - buffers: list of buffered audio tensors, one per input frame - left_paddings: list of left paddings, one per input frame - """ - buffers, left_paddings = [], [] - for frame in frames: - bufferer = self.bufferers.get(frame.stream_id, None) - - if bufferer is None: - bufferer = AudioBufferer(self.sample_rate, self.buffer_size_in_secs) - self.bufferers[frame.stream_id] = bufferer - - bufferer.update(frame) - buffers.append(bufferer.get_buffer()) - left_paddings.append(bufferer.get_left_padding()) - - if frame.is_last: - self.rm_bufferer(frame.stream_id) - - return buffers, left_paddings diff --git a/nemo/collections/asr/inference/streaming/buffering/cache_feature_bufferer.py b/nemo/collections/asr/inference/streaming/buffering/cache_feature_bufferer.py deleted file mode 100644 index a469ceeeee06becd6c8bb941a16416c239ad5c98..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/buffering/cache_feature_bufferer.py +++ /dev/null @@ -1,225 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import math -from queue import Queue - -import torch -from omegaconf import DictConfig -from torch import Tensor - -from nemo.collections.asr.inference.streaming.buffering.audio_bufferer import AudioBufferer -from nemo.collections.asr.inference.streaming.framing.request import Frame -from nemo.collections.asr.inference.utils.constants import LOG_MEL_ZERO -from nemo.collections.asr.models import ASRModel - - -class BatchedCacheFeatureBufferer: - """ - Batched cache feature bufferer class - Buffers feature chunks from multiple audio streams and manages their storage. - Maintains a tensor of shape (num_slots, n_feat, feature_buffer_len), where each slot - corresponds to a single audio stream. The number of slots equals the number of - active (or open) audio streams. - """ - - def __init__( - self, - num_slots: int, - sample_rate: int, - buffer_size_in_secs: float, - chunk_size_in_secs: float, - preprocessor_cfg: DictConfig, - device: torch.device, - fill_value: float = LOG_MEL_ZERO, - right_padding_ratio: float = 0.8, - ): - """ - Args: - num_slots (int): number of slots, where each slot contains feature buffer for a single audio stream - sample_rate (int): sample rate - buffer_size_in_secs (float): buffer size in seconds - chunk_size_in_secs (float): chunk size in seconds - preprocessor_cfg (DictConfig): preprocessor configuration - device (torch.device): device - fill_value (float): fill value for the feature buffer - right_padding_ratio (float): right padding ratio - """ - if buffer_size_in_secs < chunk_size_in_secs: - raise ValueError( - f"Buffer size ({buffer_size_in_secs}s) should be no less than chunk size ({chunk_size_in_secs}s)" - ) - - self.num_slots = num_slots - self.sample_rate = sample_rate - self.buffer_size_in_secs = buffer_size_in_secs - self.chunk_size_in_secs = chunk_size_in_secs - self.preprocessor_cfg = preprocessor_cfg - self.device = device - self.right_padding_ratio = right_padding_ratio - - self.is_buffer_size_equal_to_chunk_size = math.isclose(self.buffer_size_in_secs, self.chunk_size_in_secs) - self.plus_one = 0 if self.is_buffer_size_equal_to_chunk_size else 1 - - if hasattr(preprocessor_cfg, 'log') and preprocessor_cfg.log: - self.ZERO_LEVEL_SPEC_DB_VAL = LOG_MEL_ZERO # Log-Mel spectrogram value for zero signals - else: - self.ZERO_LEVEL_SPEC_DB_VAL = fill_value # Custom fill value for the feature buffer - - self.n_feat = preprocessor_cfg.features - self.timestep_duration = preprocessor_cfg.window_stride - self.n_chunk_look_back = int(self.timestep_duration * self.sample_rate) - self.chunk_size = int(self.chunk_size_in_secs * self.sample_rate) - self.extended_chunk_size = self.n_chunk_look_back + self.chunk_size - self.audio_bufferers = [ - AudioBufferer(self.sample_rate, self.buffer_size_in_secs) for _ in range(self.num_slots) - ] - - self.feature_buffer_len = int(buffer_size_in_secs / self.timestep_duration) - self.feature_chunk_len = int(chunk_size_in_secs / self.timestep_duration) - self.feature_buffer = torch.full( - [self.num_slots, self.n_feat, self.feature_buffer_len], - self.ZERO_LEVEL_SPEC_DB_VAL, - dtype=torch.float32, - device=self.device, - ) - - self.preprocessor = ASRModel.from_config_dict(preprocessor_cfg) - self.preprocessor.to(self.device) - - self.streamidx2slotidx, self.slotidx2streamidx = {}, {} - self.available_slots = Queue(self.num_slots) - for i in range(self.num_slots): - self.available_slots.put(i) - - def free_slots(self, slot_ids: list[int]) -> None: - """ - Free the slots for the given slot_ids - Args: - slot_ids (list[int]): list of slot ids - """ - for slot_id in slot_ids: - self.available_slots.put(slot_id) - stream_id = self.slotidx2streamidx[slot_id] - del self.slotidx2streamidx[slot_id], self.streamidx2slotidx[stream_id] - - def reset_slots(self, slot_ids: list[int]) -> None: - """ - Reset the slots for the given slot_ids - Args: - slot_ids (list[int]): list of slot ids - """ - slot_ids_tensor = torch.tensor(slot_ids, device=self.device, dtype=torch.long) - self.feature_buffer.index_fill_(0, slot_ids_tensor, self.ZERO_LEVEL_SPEC_DB_VAL) - for slot_id in slot_ids: - self.audio_bufferers[slot_id].reset() - - def preprocess( - self, audio_buffers: list[Tensor], right_paddings: Tensor, expected_feat_len: int - ) -> tuple[Tensor, Tensor]: - """ - Preprocess the audio buffers with the given right paddings and expected feature length - Args: - audio_buffers (list[Tensor]): list of audio buffers - right_paddings (Tensor): right paddings: right paddings are not zero for last frames - expected_feat_len (int): expected feature length - Returns: - tuple[Tensor, Tensor]: features and right paddings - """ - signals = torch.vstack(audio_buffers).to(self.device) # B x T - signals_len = torch.tensor([signals.shape[1]] * signals.shape[0], device=self.device, dtype=torch.long) # B - right_paddings = right_paddings * self.right_padding_ratio - signals_len = signals_len - right_paddings.long() - features, _ = self.preprocessor(input_signal=signals, length=signals_len) - if features.shape[2] > expected_feat_len: - features = features[:, :, :expected_feat_len] # B x F x T - right_padding = torch.floor(right_paddings / self.sample_rate / self.timestep_duration) # B - return features, right_padding - - def _update_feature_buffer(self, slot_ids: int, feat_chunk: Tensor) -> None: - """ - Add an extracted feature to `feature_buffer` - Args: - slot_ids (list[int]): list of slot ids - feat_chunk (Tensor): feature chunk of shape (B, F, T) - """ - for i, slot_id in enumerate(slot_ids): - chunk_len = feat_chunk[i].shape[-1] - if chunk_len > self.feature_buffer_len: - raise ValueError(f"feat_chunk ({chunk_len}) longer than buffer ({self.feature_buffer_len})") - - self.feature_buffer[slot_id, :, :-chunk_len].copy_(self.feature_buffer[slot_id, :, chunk_len:]) - self.feature_buffer[slot_id, :, -chunk_len:].copy_(feat_chunk[i]) - - def update(self, frames: list[Frame]) -> tuple[list[Tensor], list[int]]: - """ - Update the feature bufferers with the new frames. - Args: - frames (list[Frame]): list of frames with length equal to batch size - Returns: - tuple[list[Tensor], list[int]]: feature buffers and right paddings - """ - # if there are no frames, return empty lists - if len(frames) == 0: - return [], [] - - # if the stream_id is new, we need to assign a slot to it - slot_ids, slots_to_reset, slots_to_free = [], [], [] - for frame in frames: - stream_id = frame.stream_id - slot_idx = self.streamidx2slotidx.get(stream_id, None) - if stream_id not in self.streamidx2slotidx: - if self.available_slots.empty(): - raise RuntimeError("No free slots available") - slot_idx = self.available_slots.get() - self.streamidx2slotidx[stream_id] = slot_idx - self.slotidx2streamidx[slot_idx] = stream_id - slots_to_reset.append(slot_idx) - - slot_ids.append(slot_idx) - if frame.is_last: - slots_to_free.append(slot_idx) - - # reset the slots for the new stream_ids - if len(slots_to_reset) > 0: - self.reset_slots(slots_to_reset) - - right_paddings = torch.zeros(len(frames), dtype=torch.long, device=self.device) - audio_buffers = [] - for i, frame in enumerate(frames): - slot_id = slot_ids[i] - right_paddings[i] = frame.size - frame.valid_size - self.audio_bufferers[slot_id].update(frame) - - buffer = self.audio_bufferers[slot_id].sample_buffer - if not self.is_buffer_size_equal_to_chunk_size: - # Add look_back to have context for the first feature - audio_buffers.append(buffer[-(self.n_chunk_look_back + self.chunk_size) :]) - else: - # If the buffer size is equal to the chunk size, just take the whole buffer - audio_buffers.append(buffer) - - features, right_paddings = self.preprocess( - audio_buffers=audio_buffers, - right_paddings=right_paddings, - expected_feat_len=self.feature_chunk_len + self.plus_one, - ) - self._update_feature_buffer(slot_ids=slot_ids, feat_chunk=features[:, :, -self.feature_chunk_len :]) - fbuffers = list(self.feature_buffer[slot_ids].unbind(0)) - - if len(slots_to_free) > 0: - self.free_slots(slots_to_free) - - return fbuffers, right_paddings.tolist() diff --git a/nemo/collections/asr/inference/streaming/buffering/feature_bufferer.py b/nemo/collections/asr/inference/streaming/buffering/feature_bufferer.py deleted file mode 100644 index c1372bab61b0e83da6cad9caa0b8ea5c9899078f..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/buffering/feature_bufferer.py +++ /dev/null @@ -1,160 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import torch -from omegaconf import DictConfig - -from nemo.collections.asr.inference.streaming.framing.request import FeatureBuffer -from nemo.collections.asr.inference.utils.constants import LOG_MEL_ZERO - - -class FeatureBufferer: - """ - Feature bufferer class - It buffers the feature chunks and maintains the buffer. - """ - - def __init__( - self, - sample_rate: int, - buffer_size_in_secs: float, - preprocessor_cfg: DictConfig, - device: torch.device, - fill_value: float = LOG_MEL_ZERO, - ): - """ - Args: - sample_rate (int): sample rate - buffer_size_in_secs (float): buffer size in seconds - preprocessor_cfg (DictConfig): preprocessor config - device (torch.device): device - fill_value (float): value to fill the feature buffer with - """ - self.sample_rate = sample_rate - self.buffer_size_in_secs = buffer_size_in_secs - self.device = device - - if hasattr(preprocessor_cfg, 'log') and preprocessor_cfg.log: - self.ZERO_LEVEL_SPEC_DB_VAL = LOG_MEL_ZERO - else: - self.ZERO_LEVEL_SPEC_DB_VAL = fill_value - - self.n_feat = preprocessor_cfg.features - self.feature_buffer_len = int(buffer_size_in_secs / preprocessor_cfg.window_stride) - self.feature_buffer = torch.full( - [self.n_feat, self.feature_buffer_len], - self.ZERO_LEVEL_SPEC_DB_VAL, - dtype=torch.float32, - device=self.device, - ) - - def reset(self) -> None: - """ - Reset the buffer to zero - """ - self.feature_buffer.fill_(self.ZERO_LEVEL_SPEC_DB_VAL) - - def update(self, fbuffer: FeatureBuffer) -> None: - """ - Replace feature buffer with new data - Args: - fbuffer (FeatureBuffer): feature buffer to update - """ - # Resize if needed (optional) - if fbuffer.size != self.feature_buffer.shape[1]: - self.feature_buffer = torch.full( - [self.n_feat, fbuffer.size], - self.ZERO_LEVEL_SPEC_DB_VAL, - dtype=torch.float32, - device=self.device, - ) - - self.feature_buffer.copy_(fbuffer.features) - - def get_feature_buffer(self) -> torch.Tensor: - """ - Get the current feature buffer - Returns: - torch.Tensor: current state of the feature buffer - """ - return self.feature_buffer.clone() - - -class BatchedFeatureBufferer: - """ - Batched feature bufferer class - It buffers the feature chunks from multiple streams and maintains the buffers. - """ - - def __init__( - self, - sample_rate: int, - buffer_size_in_secs: float, - preprocessor_cfg: DictConfig, - device: torch.device, - ): - """ - Args: - sample_rate (int): sample rate - buffer_size_in_secs (float): buffer size in seconds - preprocessor_cfg (DictConfig): preprocessor config - device (torch.device): device - """ - self.sample_rate = sample_rate - self.buffer_size_in_secs = buffer_size_in_secs - self.preprocessor_cfg = preprocessor_cfg - self.device = device - self.bufferers = {} - - def reset(self) -> None: - """Reset bufferers""" - self.bufferers = {} - - def rm_bufferer(self, stream_id: int) -> None: - """ - Remove bufferer for the given stream id - Args: - stream_id (int): stream id - """ - self.bufferers.pop(stream_id, None) - - def update(self, fbuffers: list[FeatureBuffer]) -> list[torch.Tensor]: - """ - Update the feature bufferers with the new feature buffers. - Feature buffers can come from different streams (audios), so we need to maintain a bufferer for each stream. - Args: - fbuffers (list[FeatureBuffer]): list of feature buffers - Returns: - list[torch.Tensor]: list of feature buffers, one per input frame - """ - result_buffers = [] - for fbuffer in fbuffers: - bufferer = self.bufferers.get(fbuffer.stream_id, None) - - if bufferer is None: - bufferer = FeatureBufferer( - self.sample_rate, - self.buffer_size_in_secs, - self.preprocessor_cfg, - self.device, - ) - self.bufferers[fbuffer.stream_id] = bufferer - - bufferer.update(fbuffer) - result_buffers.append(bufferer.get_feature_buffer()) - - if fbuffer.is_last: - self.rm_bufferer(fbuffer.stream_id) - - return result_buffers diff --git a/nemo/collections/asr/inference/streaming/buffering/incremental_audio_bufferer.py b/nemo/collections/asr/inference/streaming/buffering/incremental_audio_bufferer.py deleted file mode 100644 index 19f6e1b88b15fd6db7f05103ec09be500dc22b86..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/buffering/incremental_audio_bufferer.py +++ /dev/null @@ -1,173 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import torch -from torch import Tensor -from nemo.collections.asr.inference.streaming.framing.request import Frame - - -class IncrementalAudioBufferer: - """ - Incremental Audio bufferer class - It buffers the audio chunks and maintains the buffer. - """ - - def __init__( - self, - sample_rate: int, - buffer_size_in_secs: float, - chunk_size_in_secs: float, - overlap_size_in_secs: float, - ) -> None: - """ - Args: - sample_rate (int): sample rate - buffer_size_in_secs (float): buffer size in seconds - chunk_size_in_secs (float): chunk size in seconds - overlap_size_in_secs (float): overlap size in seconds - """ - self.sample_rate = sample_rate - self.buffer_size = int(buffer_size_in_secs * sample_rate) - self.chunk_size = int(chunk_size_in_secs * sample_rate) - self.overlap_size = int(overlap_size_in_secs * sample_rate) - - # Ensure overlap is within buffer bounds to keep drop_size non-negative and meaningful. - if not (0 <= self.overlap_size <= self.buffer_size): - raise ValueError( - f"Overlap size in samples ({self.overlap_size}) must satisfy " - f"0 <= overlap_size <= buffer_size ({self.buffer_size})." - ) - - if self.buffer_size % self.chunk_size != 0: - raise ValueError(f"Buffer size ({self.buffer_size}) must be divisible by chunk size ({self.chunk_size})") - - if self.overlap_size % self.chunk_size != 0: - raise ValueError(f"Overlap size ({self.overlap_size}) must be divisible by chunk size ({self.chunk_size})") - - self.drop_size = self.buffer_size - self.overlap_size - self.sample_buffer = torch.zeros(self.buffer_size, dtype=torch.float32) - self.remaining_capacity = self.buffer_size - self.head = 0 - - def is_full(self) -> bool: - """ - Check if the buffer is full - Returns: - bool: True if the buffer is full, False otherwise - """ - return self.remaining_capacity == 0 - - def update(self, frame: Frame) -> None: - """ - Update the buffer with the new frame - Args: - frame (Frame): frame to update the buffer with - """ - if frame.size > self.buffer_size: - raise RuntimeError(f"Frame size ({frame.size}) exceeds buffer size ({self.buffer_size})") - - if self.is_full(): - # Drop the oldest chunk to make space for the new chunk - self.sample_buffer[0 : self.drop_size].zero_() - self.sample_buffer = torch.roll(self.sample_buffer, -self.drop_size) - self.head -= self.drop_size - self.remaining_capacity += self.drop_size - - self.sample_buffer[self.head : self.head + frame.size].copy_(frame.samples) - self.head += frame.size - self.remaining_capacity = max(0, self.remaining_capacity - frame.size) - - -class BatchedIncrementalAudioBufferer: - """ - Batched incremental audio bufferer class - It buffers the audio chunks from multiple streams and returns the buffers. - """ - - def __init__( - self, - sample_rate: int, - buffer_size_in_secs: float, - chunk_size_in_secs: float, - overlap_size_in_secs: float, - ) -> None: - """ - Args: - sample_rate (int): sample rate - buffer_size_in_secs (float): buffer size in seconds - chunk_size_in_secs (float): chunk size in seconds - overlap_size_in_secs (float): overlap size in seconds - """ - self.sample_rate = sample_rate - self.buffer_size_in_secs = buffer_size_in_secs - self.chunk_size_in_secs = chunk_size_in_secs - self.overlap_size_in_secs = overlap_size_in_secs - self.bufferers = {} - - def reset(self) -> None: - """ - Reset bufferers - """ - self.bufferers = {} - - def rm_bufferer(self, stream_id: int) -> None: - """ - Remove bufferer for the given stream id - Args: - stream_id (int): stream id - """ - self.bufferers.pop(stream_id, None) - - def is_full(self, stream_id: int) -> bool | None: - """ - Check if the buffer is full for the given stream id - Returns: - bool | None: True if the buffer is full, False otherwise - """ - if stream_id not in self.bufferers: - return None - return self.bufferers[stream_id].is_full() - - def update(self, frames: list[Frame]) -> tuple[list[Tensor], list[int]]: - """ - Update the bufferers with the new frames. - Frames can come from different streams (audios), so we need to maintain a bufferer for each stream - Args: - frames (list[Frame]): list of frames - Returns: - tuple[list[Tensor], list[int]]: - buffers: list of buffered audio tensors, one per input frame - paddings: list of paddings, one per input frame - """ - buffers, paddings = [], [] - for frame in frames: - bufferer = self.bufferers.get(frame.stream_id, None) - - if bufferer is None: - bufferer = IncrementalAudioBufferer( - self.sample_rate, - self.buffer_size_in_secs, - self.chunk_size_in_secs, - self.overlap_size_in_secs, - ) - self.bufferers[frame.stream_id] = bufferer - - bufferer.update(frame) - buffers.append(bufferer.sample_buffer.clone()) - paddings.append(bufferer.remaining_capacity) - - if frame.is_last: - self.rm_bufferer(frame.stream_id) - - return buffers, paddings diff --git a/nemo/collections/asr/inference/streaming/decoders/__init__.py b/nemo/collections/asr/inference/streaming/decoders/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/decoders/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/asr/inference/streaming/decoders/greedy/__init__.py b/nemo/collections/asr/inference/streaming/decoders/greedy/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/decoders/greedy/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/asr/inference/streaming/decoders/greedy/greedy_ctc_decoder.py b/nemo/collections/asr/inference/streaming/decoders/greedy/greedy_ctc_decoder.py deleted file mode 100644 index cc7001da95782868d87a026b42f95693aeca1c49..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/decoders/greedy/greedy_ctc_decoder.py +++ /dev/null @@ -1,199 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from typing import Callable -import torch - -from nemo.collections.asr.inference.streaming.decoders.greedy.greedy_decoder import GreedyDecoder - - -class CTCGreedyDecoder(GreedyDecoder): - """CTC Greedy decoder class""" - - def __init__(self, vocabulary: list[str], conf_func: Callable = None): - """ - Initialize the CTCGreedyDecoder - Args: - vocabulary (list[str]): list of vocabulary tokens - conf_func (Callable): function to compute confidence - """ - - super().__init__(vocabulary, conf_func) - - @staticmethod - def get_labels(log_probs: torch.Tensor) -> list[int]: - """ - Perform greedy decoding on the log probabilities - Args: - log_probs (torch.Tensor): log probabilities - Returns: - list[int]: list of tokens - """ - if log_probs.dim() != 2: - raise ValueError("log_probs must be 2D tensor") - - labels = log_probs.argmax(dim=-1).cpu() # T - return labels.tolist() - - def __call__(self, log_probs: torch.Tensor, compute_confidence: bool = True, previous: int = None) -> dict: - """ - Greedy decode the log probabilities - Args: - log_probs (torch.Tensor): log probabilities - compute_confidence (bool): compute confidence or not - Returns: - dict: output dictionary containing tokens, timesteps, and confidences - """ - - compute_confidence = compute_confidence and self.conf_func is not None - - if log_probs.dim() != 2: - raise ValueError("log_probs must be 2D tensor") - - if compute_confidence: - # Add batch dimension - log_probs = log_probs.unsqueeze(0) # 1 x T x N - # Compute confidences - confidences = torch.zeros(log_probs.shape[0], log_probs.shape[1]) # 1 x T - confidences[0] = self.conf_func(log_probs[0], v=log_probs.shape[2]) # 1 x T - # Remove batch dimension and convert to list - confidences = confidences.squeeze(0).tolist() # T - # Remove batch dimension - log_probs = log_probs.squeeze(0) # T x N - - labels = self.get_labels(log_probs) # T - output = {"tokens": [], "timesteps": [], "confidences": []} - previous = self.blank_id if previous is None else previous - for i, p in enumerate(labels): - if p != previous and p != self.blank_id: - output["tokens"].append(p) - output["timesteps"].append(i) - if compute_confidence: - output["confidences"].append(confidences[i]) - previous = p - - output["labels"] = labels - return output - - -class ClippedCTCGreedyDecoder: - """ - Clipped CTC Greedy decoder class - Decodes the tokens within a given clip range and returns the clipped tokens and timestamps. - """ - - def __init__(self, vocabulary: list[str], tokens_per_frame: int, conf_func: Callable = None, endpointer=None): - """ - Initialize the ClippedCTCGreedyDecoder - Args: - vocabulary (list[str]): list of vocabulary tokens - tokens_per_frame (int): number of tokens per frame - conf_func (Callable): function to compute confidence - endpointer (Any): endpointer to detect EOU - """ - self.greedy_decoder = CTCGreedyDecoder(vocabulary, conf_func) - self.endpointer = endpointer - self.tokens_per_frame = tokens_per_frame - - def __call__( - self, - log_probs: torch.Tensor, - clip_start: int, - clip_end: int, - is_last: bool = False, - is_start: bool = True, - return_partial_result: bool = True, - state_start_idx: int = 0, - state_end_idx: int = 0, - stop_history_eou: int = None, - compute_confidence: bool = True, - ) -> tuple[dict, dict, bool, int, int]: - """ - Decode the log probabilities within the clip range (clip_start, clip_end) - Args: - log_probs (torch.Tensor): log probabilities - clip_start (int): start index of the clip - clip_end (int): end index of the clip - is_last (bool): is the last frame or not - is_start (bool): is the first frame for this stream or not - return_partial_result (bool): return partial result left after clip_end in the buffer - state_start_idx (int): start index from stream state - state_end_idx (int): end index from stream state - stop_history_eou (int): stop history of EOU, if None then use the default stop history - compute_confidence (bool): compute confidence or not - Returns: - tuple[dict, dict, bool, int, int]: - clipped output, tail output, is_eou, updated start_idx, updated end_idx - """ - - is_eou = is_last - eou_detected_at = len(log_probs) - # Initialize state tracking variables from input parameters - start_idx, end_idx = state_start_idx, state_end_idx - # Update indices for next processing step - if end_idx > clip_start: - end_idx -= self.tokens_per_frame - start_idx = end_idx - - if is_start or end_idx <= clip_start: - start_idx, end_idx = clip_start, clip_end - - all_output = self.greedy_decoder(log_probs, compute_confidence=compute_confidence) - - clipped_output = {"tokens": [], "timesteps": [], "confidences": [], "last_token": None, "last_token_idx": None} - tail_output = {"tokens": []} - - # check if EOU is detected or is the last frame - if not is_eou and self.endpointer is not None: - is_eou, eou_detected_at = self.endpointer.detect_eou( - log_probs, pivot_point=start_idx, search_start_point=clip_start, stop_history_eou=stop_history_eou - ) - - # if EOU is detected, and it is after the clip end, update the end index to the EOU - if is_eou and eou_detected_at > end_idx: - end_idx = eou_detected_at - - # if the end index is within the clip range, update the end index to the clip end - if clip_start <= end_idx < clip_end: - end_idx = clip_end - is_eou = False - - # clip the output within the clip range [clip_start, clip_end) - timesteps = all_output["timesteps"] - i = 0 - while i < len(timesteps): - if start_idx <= timesteps[i] < end_idx: - clipped_output["tokens"].append(all_output["tokens"][i]) - clipped_output["timesteps"].append(timesteps[i]) - if compute_confidence: - clipped_output["confidences"].append(all_output["confidences"][i]) - elif timesteps[i] >= end_idx: - break - i += 1 - - if end_idx - 1 < len(all_output["labels"]): - clipped_output["last_token"] = all_output["labels"][end_idx - 1] - clipped_output["last_token_idx"] = end_idx - 1 - - # return the partial result left after clip_end in the buffer - if return_partial_result: - while i < len(timesteps): - if timesteps[i] >= end_idx: - tail_output["tokens"] = all_output["tokens"][i:] - break - else: - i += 1 - - return clipped_output, tail_output, is_eou, start_idx, end_idx diff --git a/nemo/collections/asr/inference/streaming/decoders/greedy/greedy_decoder.py b/nemo/collections/asr/inference/streaming/decoders/greedy/greedy_decoder.py deleted file mode 100644 index 9412330eb7a891a1a6a29040290ee7ff43abf7b1..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/decoders/greedy/greedy_decoder.py +++ /dev/null @@ -1,102 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from typing import Callable - -from nemo.collections.asr.inference.utils.constants import SENTENCEPIECE_UNDERSCORE - - -class GreedyDecoder: - """Base class for the greedy decoder""" - - def __init__(self, vocabulary: list[str], conf_func: Callable = None): - """ - Initialize the GreedyDecoder - Args: - vocabulary (list[str]): list of vocabulary tokens - conf_func (Callable): function to compute confidence - """ - - self.vocabulary = vocabulary - self.blank_id = len(vocabulary) - self.conf_func = conf_func - self.is_start_tokens = [token.startswith(SENTENCEPIECE_UNDERSCORE) for token in vocabulary] - - def count_silent_tokens(self, tokens: list[int], start: int, end: int) -> int: - """ - Count how many silent tokens appear in [start, end). - Args: - tokens (list[int]): list of tokens - start (int): start index - end (int): end index - Returns: - int: number of silent tokens - """ - if end <= start or start >= len(tokens): - return 0 - return sum(self.is_token_silent(tokens[i]) for i in range(start, min(end, len(tokens)))) - - def is_token_start_of_word(self, token_id: int) -> bool: - """ - Check if the token is the start of a word - Args: - token_id (int): token id - Returns: - bool: True if the token is the start of a word, False otherwise - """ - return self.is_start_tokens[token_id] - - def is_token_silent(self, token_id: int) -> bool: - """ - Check if the token is silent - Args: - token_id (int): token id - Returns: - bool: True if the token is silent, False otherwise - """ - return token_id == self.blank_id - - def first_non_silent_token(self, tokens: list[int], start: int, end: int) -> int: - """ - Return the index of the first non-silent token in [start, end). - If none found, return -1. - Args: - tokens (list[int]): list of tokens - start (int): start index - end (int): end index - Returns: - int: index of the first non-silent token - """ - for i in range(start, min(end, len(tokens))): - if not self.is_token_silent(tokens[i]): - return i - return -1 - - def count_non_silent_tokens(self, tokens: list[int], start: int, end: int) -> int: - """ - Count how many non-silent tokens appear in [start, end). - Args: - tokens (list[int]): list of tokens - start (int): start index - end (int): end index - Returns: - int: number of non-silent tokens - """ - if end <= start or start >= len(tokens): - return 0 - return sum(not self.is_token_silent(tokens[i]) for i in range(start, min(end, len(tokens)))) - - def __call__(self, *args, **kwds): - raise NotImplementedError("Subclass of GreedyDecoder should implement `__call__` method!") diff --git a/nemo/collections/asr/inference/streaming/decoders/greedy/greedy_rnnt_decoder.py b/nemo/collections/asr/inference/streaming/decoders/greedy/greedy_rnnt_decoder.py deleted file mode 100644 index 223462409a18bac6c6c4cc71a163446538b5327c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/decoders/greedy/greedy_rnnt_decoder.py +++ /dev/null @@ -1,235 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from typing import Callable - -import torch - -from nemo.collections.asr.inference.streaming.decoders.greedy.greedy_decoder import GreedyDecoder - - -class RNNTGreedyDecoder(GreedyDecoder): - """RNNT Greedy decoder class""" - - def __init__(self, vocabulary: list[str], conf_func: Callable = None): - """ - Initialize the RNNTGreedyDecoder - Args: - vocabulary (list[str]): list of vocabulary tokens - conf_func (Callable): function to compute confidence - """ - super().__init__(vocabulary, conf_func) - - def __call__( - self, - global_timestamps: torch.Tensor | list[int], - tokens: torch.Tensor | list[int], - length: int, - offset: int = 0, - ) -> tuple[dict, list[int], int]: - """ - Decode the RNNT hypothesis using timestamps - Args: - global_timestamps (torch.Tensor | list[int]): global timestamps since the start of the stream - tokens (torch.Tensor | list[int]): tokens since the start of the stream - length (int): length of the alignment - offset (int): offset to apply to the timestamps to make them local - Returns: - tuple[dict, list[int], int]: - output: dictionary containing the decoded tokens, timestamps, and confidences - current labels: list of current labels including the blank token - new offset: new offset value for the next decoding step - """ - if isinstance(global_timestamps, list): - global_timestamps = torch.tensor(global_timestamps) - if isinstance(tokens, list): - tokens = torch.tensor(tokens) - - output = {"tokens": [], "timesteps": [], "confidences": [], "last_token": None, "last_token_idx": None} - cur_labels = [self.blank_id] * length - new_offset = len(tokens) - if offset > 0: - trimmed_tokens = tokens[offset:].tolist() - trimmed_timestamps = global_timestamps[offset:].tolist() - else: - trimmed_tokens = tokens.tolist() - trimmed_timestamps = global_timestamps.tolist() - - if len(trimmed_tokens) == 0: - return output, cur_labels, new_offset - - output["tokens"].extend(trimmed_tokens) - output["timesteps"].extend(trimmed_timestamps) - output["confidences"].extend([0.0] * len(trimmed_tokens)) - output["last_token"] = trimmed_tokens[-1] - output["last_token_idx"] = trimmed_timestamps[-1] - - for t, token in zip(trimmed_timestamps, trimmed_tokens): - cur_labels[t % length] = token - return output, cur_labels, new_offset - - -class ClippedRNNTGreedyDecoder: - """ - Clipped RNNT Greedy decoder class - Decodes the tokens within a given clip range and returns the clipped tokens and timestamps. - """ - - def __init__(self, vocabulary: list[str], tokens_per_frame: int, conf_func: Callable = None, endpointer=None): - """ - Initialize the ClippedRNNTGreedyDecoder - Args: - vocabulary (list[str]): list of vocabulary tokens - tokens_per_frame (int): number of tokens per frame - conf_func (Callable): function to compute confidence - endpointer (Any): endpointer to detect EOU - """ - self.greedy_decoder = RNNTGreedyDecoder(vocabulary, conf_func) - self.endpointer = endpointer - self.tokens_per_frame = tokens_per_frame - - @staticmethod - def extract_clipped_and_tail_single_pass( - timesteps: torch.Tensor, tokens: torch.Tensor, start_idx: int, end_idx: int, return_tail_result: bool - ) -> tuple[list[int], list[int], list[int]]: - """ - Extract clipped and tail data using tensor operations - no conversion overhead - """ - if len(timesteps) == 0: - return [], [], [] - clipped_mask = (timesteps >= start_idx) & (timesteps < end_idx) - clipped_timesteps = timesteps[clipped_mask].tolist() - clipped_tokens = tokens[clipped_mask].tolist() - tail_tokens = [] - if return_tail_result: - tail_mask = timesteps >= end_idx - if tail_mask.any(): - tail_tokens = tokens[tail_mask].tolist() - - return clipped_timesteps, clipped_tokens, tail_tokens - - def __call__( - self, - global_timesteps: torch.Tensor, - tokens: torch.Tensor, - clip_start: int, - clip_end: int, - alignment_length: int, - is_last: bool = False, - is_start: bool = True, - return_tail_result: bool = False, - state_start_idx: int = 0, - state_end_idx: int = 0, - timestamp_offset: int = 0, - vad_segments: torch.Tensor = None, - stop_history_eou: int = None, - ) -> tuple[dict, dict, bool, int, int]: - """ - Decode using timestamps instead of dense alignment - Optimized version with vectorized operations and single-pass processing - Args: - global_timesteps (torch.Tensor): global timestamps since the start of the stream - tokens (torch.Tensor): tokens - clip_start (int): start index of the clip - clip_end (int): end index of the clip - alignment_length (int): length of the alignment - is_last (bool): is the last frame or not. - is_start (bool): is the first frame for this stream or not. - return_tail_result (bool): return tail result left after clip_end in the buffer - state_start_idx (int): start index from stream state - state_end_idx (int): end index from stream state - timestamp_offset (int): offset to apply to the timestamps to make them local - vad_segments (torch.Tensor): Optional VAD segments to use for end-of-utterance detection - stop_history_eou (int): stop history of EOU, if None then use the default stop history - Returns: - tuple[dict, dict, bool, int, int]: - clipped output, tail output, is_eou, updated start_idx, updated end_idx - """ - # Initialize end-of-utterance state based on input parameters - if timestamp_offset: - timesteps = global_timesteps - timestamp_offset - else: - timesteps = global_timesteps - is_eou = is_last - eou_detected_at = alignment_length - start_idx, end_idx = state_start_idx, state_end_idx - if end_idx > clip_start: - end_idx -= self.tokens_per_frame - start_idx = end_idx - if is_start: - start_idx, end_idx = clip_start, clip_start - elif end_idx <= clip_start: - start_idx, end_idx = clip_start, clip_end - - if len(timesteps) == 0 or len(tokens) == 0: - return ( - {"tokens": [], "timesteps": [], "confidences": [], "last_token": None, "last_token_idx": None}, - {"tokens": []}, - True, - start_idx, - end_idx, - ) - - mask = timesteps >= start_idx - timesteps_trimmed = timesteps[mask] - tokens_trimmed = tokens[mask] - # If not already at end of utterance and endpointer exists, try to detect end of utterance - if not is_eou and self.endpointer is not None: - if vad_segments is not None and len(vad_segments) > 0: - if vad_segments[-1][1] != 0.0: - is_eou, eou_detected_at = self.endpointer.detect_eou_vad( - vad_segments=vad_segments, search_start_point=start_idx, stop_history_eou=stop_history_eou - ) - else: - is_eou = True - eou_detected_at = -1 - else: - is_eou, eou_detected_at = self.endpointer.detect_eou_given_timestamps( - timesteps=timesteps_trimmed, - tokens=tokens_trimmed, - alignment_length=alignment_length, - stop_history_eou=stop_history_eou, - ) - # If EOU is detected beyond current end frame, extend end frame to include it - if is_eou and eou_detected_at > end_idx: - end_idx = min(eou_detected_at, alignment_length) - - # If the end frame is within the clip range, set the end frame to the clip end - if clip_start <= end_idx < clip_end: - end_idx = clip_end - is_eou = False - clipped_timesteps, clipped_tokens, tail_tokens = self.extract_clipped_and_tail_single_pass( - timesteps, tokens, start_idx, end_idx, return_tail_result - ) - # Make timestamps global again - if timestamp_offset: - clipped_timesteps = [t + timestamp_offset for t in clipped_timesteps] - # Initialize output with last_token tracking like in __call__ method - clipped_output = { - "tokens": clipped_tokens, - "timesteps": clipped_timesteps, - "confidences": [0.0] * len(clipped_tokens) if len(clipped_tokens) > 0 else [], - "last_token": None, - "last_token_idx": None, - } - - # Set last_token and last_token_idx if there are tokens - if len(clipped_tokens) > 0: - clipped_output["last_token"] = clipped_tokens[-1] - clipped_output["last_token_idx"] = clipped_timesteps[-1] if len(clipped_timesteps) > 0 else None - - # Create tail output - tail_output = {"tokens": tail_tokens} - return clipped_output, tail_output, is_eou, start_idx, end_idx diff --git a/nemo/collections/asr/inference/streaming/endpointing/__init__.py b/nemo/collections/asr/inference/streaming/endpointing/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/endpointing/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/asr/inference/streaming/endpointing/greedy/__init__.py b/nemo/collections/asr/inference/streaming/endpointing/greedy/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/endpointing/greedy/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/asr/inference/streaming/endpointing/greedy/greedy_ctc_endpointing.py b/nemo/collections/asr/inference/streaming/endpointing/greedy/greedy_ctc_endpointing.py deleted file mode 100644 index 446c513ed49f6e50851cda372c9037b00418d7ad..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/endpointing/greedy/greedy_ctc_endpointing.py +++ /dev/null @@ -1,85 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import torch -from nemo.collections.asr.inference.streaming.decoders.greedy.greedy_ctc_decoder import CTCGreedyDecoder -from nemo.collections.asr.inference.streaming.endpointing.greedy.greedy_endpointing import GreedyEndpointing - - -class CTCGreedyEndpointing(GreedyEndpointing): - """Greedy endpointing for the streaming CTC pipeline""" - - def __init__( - self, - vocabulary: list[str], - ms_per_timestep: int, - effective_buffer_size_in_secs: float = None, - stop_history_eou: int = -1, - residue_tokens_at_end: int = 0, - ) -> None: - """ - Initialize the CTCGreedyEndpointing class - Args: - vocabulary: (list[str]) List of vocabulary - ms_per_timestep: (int) Number of milliseconds per timestep - effective_buffer_size_in_secs: (float, optional) Effective buffer size for VAD-based EOU detection. Not used for CTC. - stop_history_eou: (int) Number of silent tokens to trigger a EOU, if -1 then it is disabled - residue_tokens_at_end: (int) Number of residue tokens at the end, if 0 then it is disabled - """ - super().__init__( - vocabulary, ms_per_timestep, effective_buffer_size_in_secs, stop_history_eou, residue_tokens_at_end - ) - self.greedy_ctc_decoder = CTCGreedyDecoder(self.vocabulary, conf_func=None) - - def detect_eou( - self, - probs_seq: torch.Tensor, - pivot_point: int, - search_start_point: int = 0, - stop_history_eou: int | None = None, - ) -> tuple[bool, int]: - """ - Detect end of utterance (EOU) given the probabilities sequence and pivot point - Args: - probs_seq (torch.Tensor): probabilities sequence - pivot_point (int): pivot point - search_start_point (int): start point for searching EOU - stop_history_eou (int | None): stop history of EOU, if None then use the stop history of EOU from the class - Returns: - bool: True if EOU is detected, False otherwise - int: index of the EOU detected at - """ - emissions = self.greedy_ctc_decoder.get_labels(probs_seq) - return self.detect_eou_given_emissions(emissions, pivot_point, search_start_point, stop_history_eou) - - def is_token_start_of_word(self, token_id: int) -> bool: - """ - Check if the token is the start of a word - Args: - token_id (int): token id - Returns: - bool: True if the token is the start of a word, False otherwise - """ - return self.greedy_ctc_decoder.is_token_start_of_word(token_id=token_id) - - def is_token_silent(self, token_id: int) -> bool: - """ - Check if the token is silent - Args: - token_id (int): token id - Returns: - bool: True if the token is silent, False otherwise - """ - return self.greedy_ctc_decoder.is_token_silent(token_id=token_id) diff --git a/nemo/collections/asr/inference/streaming/endpointing/greedy/greedy_endpointing.py b/nemo/collections/asr/inference/streaming/endpointing/greedy/greedy_endpointing.py deleted file mode 100644 index 1442043ae7117ffd9874ab4ffa95d90825beaec6..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/endpointing/greedy/greedy_endpointing.py +++ /dev/null @@ -1,312 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import torch - -from nemo.collections.asr.inference.utils.endpointing_utils import get_custom_stop_history_eou, millisecond_to_frames - - -class GreedyEndpointing: - """Greedy endpointing for the streaming ASR pipelines""" - - def __init__( - self, - vocabulary: list[str], - ms_per_timestep: int, - effective_buffer_size_in_secs: float = None, - stop_history_eou: int = -1, - residue_tokens_at_end: int = 0, - ) -> None: - """ - Initialize the GreedyEndpointing class - Args: - vocabulary: (list[str]) List of vocabulary - ms_per_timestep: (int) Number of milliseconds per timestep - effective_buffer_size_in_secs: (float, optional) Effective buffer size for VAD-based EOU detection. - stop_history_eou: (int) Number of silent tokens to trigger a EOU, if -1 then it is disabled - residue_tokens_at_end: (int) Number of residue tokens at the end, if 0 then it is disabled - """ - - self.vocabulary = vocabulary - self.ms_per_timestep = ms_per_timestep - self.sec_per_timestep = ms_per_timestep / 1000 - self.stop_history_eou = stop_history_eou - self.stop_history_eou_ms = stop_history_eou - self.effective_buffer_size_in_secs = effective_buffer_size_in_secs - if self.stop_history_eou > 0: - self.stop_history_eou = millisecond_to_frames(self.stop_history_eou, ms_per_timestep) - self.residue_tokens_at_end = residue_tokens_at_end - - def detect_eou_given_emissions( - self, - emissions: list[int], - pivot_point: int, - search_start_point: int = 0, - stop_history_eou: int | None = None, - ) -> tuple[bool, int]: - """ - Detect end of utterance (EOU) given the emissions and pivot point - Args: - emissions (list[int]): list of emissions at each timestep - pivot_point (int): pivot point around which to detect EOU - search_start_point (int): start point for searching EOU - stop_history_eou (int | None): stop history of EOU, if None then use the stop history of EOU from the class - Returns: - Tuple[bool, int]: True if EOU is detected, False otherwise, and the point at which EOU is detected - """ - sequence_length = len(emissions) - if pivot_point < 0 or pivot_point >= sequence_length: - raise ValueError("Pivot point is out of range") - - if search_start_point > pivot_point: - raise ValueError("Search start point is greater than pivot_point") - - if self.residue_tokens_at_end > 0: - sequence_length = max(0, sequence_length - self.residue_tokens_at_end) - - stop_history_eou = get_custom_stop_history_eou(stop_history_eou, self.stop_history_eou, self.ms_per_timestep) - eou_detected, eou_detected_at = False, -1 - - if stop_history_eou > 0: - n_silent_tokens = 0 - silence_start_position = -1 - fst_non_silent_token = None - end_point = max(0, search_start_point, pivot_point - stop_history_eou) - current_position = max(0, sequence_length - 1) - while current_position >= end_point: - if self.is_token_silent(emissions[current_position]): - n_silent_tokens += 1 - eou_detected = n_silent_tokens > stop_history_eou - is_token_start_of_word = (fst_non_silent_token is None) or self.is_token_start_of_word( - fst_non_silent_token - ) - eou_detected = eou_detected and is_token_start_of_word - if eou_detected: - silence_start_position = current_position - else: - if eou_detected: - break - n_silent_tokens = 0 - eou_detected = False - silence_start_position = -1 - fst_non_silent_token = emissions[current_position] - current_position -= 1 - - eou_detected = n_silent_tokens > stop_history_eou - if eou_detected: - eou_detected_at = int(silence_start_position + stop_history_eou // 2) - - return eou_detected, eou_detected_at - - def detect_eou_given_timestamps( - self, - timesteps: torch.Tensor, - tokens: torch.Tensor, - alignment_length: int, - stop_history_eou: int | None = None, - ) -> tuple[bool, int]: - """ - Detect end of utterance (EOU) given timestamps and tokens using tensor operations. - Args: - timesteps (torch.Tensor): timestamps of the tokens - tokens (torch.Tensor): tokens - alignment_length (int): length of the alignment - stop_history_eou (int | None): stop history of EOU, if None then use the stop history of EOU from the class - Returns: - tuple[bool, int]: True if EOU is detected, False otherwise, and the point at which EOU is detected - """ - eou_detected, eou_detected_at = False, -1 - - if len(timesteps) != len(tokens): - raise ValueError("timesteps and tokens must have the same length") - - stop_history_eou = get_custom_stop_history_eou(stop_history_eou, self.stop_history_eou, self.ms_per_timestep) - - # If stop_history_eou is negative, don't detect EOU. - if len(timesteps) == 0 or stop_history_eou < 0: - return eou_detected, eou_detected_at - - # This is the condition for Riva streaming offline mode. The output of entire buffer needs to be sent as is to the client. - if stop_history_eou == 0: - return True, alignment_length - - if self.residue_tokens_at_end > 0: - alignment_length = max(0, alignment_length - self.residue_tokens_at_end) - - # Check trailing silence at the end - last_timestamp = timesteps[-1].item() - trailing_silence = max(0, alignment_length - last_timestamp - 1) - if trailing_silence > stop_history_eou: - eou_detected = True - eou_detected_at = last_timestamp + 1 + stop_history_eou // 2 - return eou_detected, eou_detected_at - - # Check gaps between consecutive non-silent tokens - if len(timesteps) > 1: - gaps = timesteps[1:] - timesteps[:-1] - 1 - large_gap_mask = gaps > stop_history_eou - if large_gap_mask.any(): - # Get the last (rightmost) large gap index for backwards compatibility - large_gap_indices = torch.where(large_gap_mask)[0] - gap_idx = large_gap_indices[-1].item() - - eou_detected = True - eou_detected_at = timesteps[gap_idx].item() + 1 + stop_history_eou // 2 - return eou_detected, eou_detected_at - return eou_detected, eou_detected_at - - def detect_eou_vad( - self, vad_segments: torch.Tensor, search_start_point: float = 0, stop_history_eou: int | None = None - ) -> tuple[bool, float]: - """ - Detect end of utterance (EOU) using VAD segments. - - Args: - vad_segments (torch.Tensor): VAD segments in format [N, 2] where each row is [start_time, end_time] - search_start_point (float): Start time for searching EOU in seconds - stop_history_eou (int | None): Stop history of EOU in milliseconds, if None then use the stop history of EOU from the class - Returns: - tuple[bool, float]: (is_eou, eou_detected_at_time) - """ - if self.effective_buffer_size_in_secs is None: - raise ValueError("Effective buffer size in seconds is required for VAD-based EOU detection") - - # Use default stop history of EOU from the class if stop_history_eou is not provided - stop_history_eou = self.stop_history_eou_ms if stop_history_eou is None else stop_history_eou - if stop_history_eou < 0: - return False, -1 - - search_start_point = search_start_point * self.sec_per_timestep - stop_history_eou_in_secs = stop_history_eou / 1000 - # Round to 4 decimal places first (vectorized) - rounded_segments = torch.round(vad_segments, decimals=4) - - # Filter segments where end_time > search_start_point - valid_mask = rounded_segments[:, 1] > search_start_point - if not valid_mask.any(): - return False, -1 - - filtered_segments = rounded_segments[valid_mask] - - # Clip start times to search_start_point - filtered_segments[:, 0] = torch.clamp(filtered_segments[:, 0], min=search_start_point) - # Initialize EOU detection variables - is_eou = False - eou_detected_at = -1 - - # Check gap to buffer end - last_segment = filtered_segments[-1] - gap_to_buffer_end = self.effective_buffer_size_in_secs - last_segment[1] - if gap_to_buffer_end > stop_history_eou_in_secs: - # EOU detected at buffer end - is_eou = True - eou_detected_at = last_segment[1] + stop_history_eou_in_secs / 2 - - elif len(filtered_segments) >= 2: - # Check gaps between segments (reverse order to find last gap) - for i in range(len(filtered_segments) - 2, -1, -1): - segment = filtered_segments[i] - next_segment = filtered_segments[i + 1] - gap = next_segment[0] - segment[1] - if gap > stop_history_eou_in_secs: - is_eou = True - eou_detected_at = segment[1] + stop_history_eou_in_secs / 2 - break - - # Convert to timesteps (only if EOU was detected) - if is_eou: - eou_detected_at = int(eou_detected_at // self.sec_per_timestep) - else: - eou_detected_at = -1 - - return is_eou, eou_detected_at - - def is_token_start_of_word(self, token_id: int) -> bool: - """Check if the token is the start of a word""" - raise NotImplementedError("Subclass of GreedyEndpointing should implement `is_token_start_of_word` method!") - - def is_token_silent(self, token_id: int) -> bool: - """Check if the token is silent""" - raise NotImplementedError("Subclass of GreedyEndpointing should implement `is_token_silent` method!") - - def detect_eou_near_pivot( - self, - emissions: list[int], - pivot_point: int, - search_start_point: int = 0, - stop_history_eou: int | None = None, - ) -> tuple[bool, int]: - """ - Detect end of utterance (EOU) given the emissions and pivot point - Args: - emissions (list[int]): list of emissions at each timestep - pivot_point (int): pivot point around which to detect EOU - search_start_point (int): start point for searching EOU - stop_history_eou (int | None): stop history of EOU, if None then use the stop history of EOU from the class - Returns: - tuple[bool, int]: True if EOU is detected, False otherwise, and the point at which EOU is detected - """ - - sequence_length = len(emissions) - - if pivot_point < 0 or pivot_point >= sequence_length: - raise ValueError("Pivot point is out of range") - - if search_start_point > pivot_point: - raise ValueError("Search start point is greater then pivot_point") - - if self.residue_tokens_at_end > 0: - sequence_length = max(0, sequence_length - self.residue_tokens_at_end) - - stop_history_eou = get_custom_stop_history_eou(stop_history_eou, self.stop_history_eou, self.ms_per_timestep) - eou_detected, eou_detected_at = False, -1 - - if stop_history_eou > 0: - - # number of silent tokens in the range [search_start_point, pivot_point) - n_silent_tokens_before = 0 - i = pivot_point - 1 - while i >= search_start_point: - if self.is_token_silent(emissions[i]): - n_silent_tokens_before += 1 - else: - break - i -= 1 - - # number of silent tokens in the range [pivot_point, sequence_length) - n_silent_tokens_after = 0 - i = pivot_point - fst_non_silent_token_after = None - while i < sequence_length: - if self.is_token_silent(emissions[i]): - n_silent_tokens_after += 1 - else: - fst_non_silent_token_after = emissions[i] - break - i += 1 - - # additional check for the first non-silent token after the pivot point - if fst_non_silent_token_after is not None: - if not self.is_token_start_of_word(fst_non_silent_token_after): - eou_detected, eou_detected_at = False, -1 - else: - # check if the number of silent tokens before and after the pivot point is greater than the threshold - val_cnt = n_silent_tokens_before + n_silent_tokens_after - eou_detected = val_cnt > stop_history_eou - eou_detected_at = ( - int(pivot_point - n_silent_tokens_before + stop_history_eou // 2) if eou_detected else -1 - ) - - return eou_detected, eou_detected_at diff --git a/nemo/collections/asr/inference/streaming/endpointing/greedy/greedy_rnnt_endpointing.py b/nemo/collections/asr/inference/streaming/endpointing/greedy/greedy_rnnt_endpointing.py deleted file mode 100644 index 71598fdc3809e0ca0522b6ad9430c453109c61c5..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/endpointing/greedy/greedy_rnnt_endpointing.py +++ /dev/null @@ -1,63 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from nemo.collections.asr.inference.streaming.decoders.greedy.greedy_rnnt_decoder import RNNTGreedyDecoder -from nemo.collections.asr.inference.streaming.endpointing.greedy.greedy_endpointing import GreedyEndpointing - - -class RNNTGreedyEndpointing(GreedyEndpointing): - """Greedy endpointing for the streaming RNNT pipeline""" - - def __init__( - self, - vocabulary: list[str], - ms_per_timestep: int, - effective_buffer_size_in_secs: float = None, - stop_history_eou: int = -1, - residue_tokens_at_end: int = 0, - ) -> None: - """ - Initialize the RNNTGreedyEndpointing class - Args: - vocabulary: (list[str]) List of vocabulary - ms_per_timestep: (int) Number of milliseconds per timestep - effective_buffer_size_in_secs: (float, optional) Effective buffer size for VAD-based EOU detection for stateless and stateful RNNT. If None, VAD functionality is disabled. - stop_history_eou: (int) Number of silent tokens to trigger a EOU, if -1 then it is disabled - residue_tokens_at_end: (int) Number of residue tokens at the end, if 0 then it is disabled - """ - super().__init__( - vocabulary, ms_per_timestep, effective_buffer_size_in_secs, stop_history_eou, residue_tokens_at_end - ) - self.greedy_rnnt_decoder = RNNTGreedyDecoder(self.vocabulary, conf_func=None) - - def is_token_start_of_word(self, token_id: int) -> bool: - """ - Check if the token is the start of a word - Args: - token_id (int): token id - Returns: - bool: True if the token is the start of a word, False otherwise - """ - return self.greedy_rnnt_decoder.is_token_start_of_word(token_id=token_id) - - def is_token_silent(self, token_id: int) -> bool: - """ - Check if the token is silent - Args: - token_id (int): token id - Returns: - bool: True if the token is silent, False otherwise - """ - return self.greedy_rnnt_decoder.is_token_silent(token_id=token_id) diff --git a/nemo/collections/asr/inference/streaming/framing/__init__.py b/nemo/collections/asr/inference/streaming/framing/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/framing/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/asr/inference/streaming/framing/mono_stream.py b/nemo/collections/asr/inference/streaming/framing/mono_stream.py deleted file mode 100644 index f942d6d57712993693df87567cf93dd5f3d8ef3e..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/framing/mono_stream.py +++ /dev/null @@ -1,114 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import torch -from nemo.collections.asr.inference.streaming.framing.request import Frame, RequestOptions -from nemo.collections.asr.inference.streaming.framing.stream import Stream -from nemo.collections.asr.inference.utils.audio_io import read_audio - - -class MonoStream(Stream): - """ - Streamer for mono wav files. - Iterates over the frames of the audio file - """ - - def __init__(self, rate: int, frame_size_in_secs: float, stream_id: int, pad_last_frame: bool = False): - """ - Initialize the MonoStream - Args: - rate (int): sampling rate - frame_size_in_secs (int): frame length in seconds - stream_id (int): stream id - """ - - self.rate = rate - self.frame_size = int(frame_size_in_secs * rate) - self.pad_last_frame = pad_last_frame - - self.samples = None - self.n_samples = None - self.options = None - super().__init__(stream_id) - - def load_audio(self, audio: str | torch.Tensor, options: RequestOptions | None = None) -> None: - """ - Load the audio file either from a file or from a torch tensor - Args: - audio (str | torch.Tensor): audio file path or torch tensor of audio samples - options (RequestOptions | None): optional options for the request - """ - if isinstance(audio, str): - # Read the audio file and convert to mono - self.samples = read_audio(audio, target_sr=self.rate, mono=True) - else: - self.samples = audio - self.n_samples = len(self.samples) - self.frame_count = 0 # Reset frame count - self.options = options - - def __iter__(self): - """Returns the frame iterator object""" - self.start = 0 - self.frame_count = 0 - return self - - def __next__(self) -> list[Frame]: - """ - Get the next frame in the stream - Returns: - list[Frame]: The next frame in the stream - """ - if self.samples is None: - raise RuntimeError("No audio samples loaded. Please call load_audio() first.") - - if self.start < self.n_samples: - - end = min(self.start + self.frame_size, self.n_samples) - - # Check if this is the last frame - is_end = False - chunk_length = end - self.start - if (end - self.start < self.frame_size) or (end == self.n_samples): - is_end = True - - # Pad the last frame if needed - if not is_end: - chunk_samples = self.samples[self.start : end] - else: - if self.pad_last_frame: - chunk_samples = torch.zeros(self.frame_size) - chunk_samples[:chunk_length] = self.samples[self.start : end] - else: - chunk_samples = self.samples[self.start : end] - - # Package the frame - is_first = self.frame_count == 0 - frame = Frame( - samples=chunk_samples, - stream_id=self.stream_id, - is_first=is_first, - is_last=is_end, - length=chunk_length, - options=self.options if is_first else None, - ) - - self.frame_count += 1 - self.start += frame.size - - return [frame] - - # End of stream - raise StopIteration diff --git a/nemo/collections/asr/inference/streaming/framing/multi_stream.py b/nemo/collections/asr/inference/streaming/framing/multi_stream.py deleted file mode 100644 index b46e0821072891a68ffdb38b38f948af4d614b78..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/framing/multi_stream.py +++ /dev/null @@ -1,403 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from typing import Callable, Iterator - -import torch - -from nemo.collections.asr.inference.streaming.buffering.audio_bufferer import BatchedAudioBufferer -from nemo.collections.asr.inference.streaming.framing.mono_stream import MonoStream -from nemo.collections.asr.inference.streaming.framing.request import FeatureBuffer, Frame, Request, RequestOptions -from nemo.collections.asr.inference.streaming.framing.stream import Stream -from nemo.collections.asr.inference.utils.enums import RequestType -from nemo.collections.asr.inference.utils.progressbar import ProgressBar - - -class MultiStream: - """MultiStreamer for multiple streams""" - - def __init__(self, n_frames_per_stream: int): - """ - Args: - n_frames_per_stream (int): Number of frames per stream - """ - self.n_frames_per_stream = n_frames_per_stream - self.streams = {} - - def add_stream(self, stream: Stream, stream_id: int) -> None: - """ - Add a stream to the streamer - Args: - stream (Stream): The stream to add - stream_id (int): The id of the stream - """ - self.streams[stream_id] = iter(stream) - - def rm_stream(self, stream_id: int) -> None: - """ - Remove a stream from the streamer - Args: - stream_id (int): The id of the stream - """ - self.streams.pop(stream_id, None) - - def __len__(self) -> int: - """Number of running streams""" - return len(self.streams) - - def __iter__(self) -> Iterator: - """Returns the iterator object""" - return self - - def __next__(self) -> list[Frame]: - """ - Get the next batch of frames - Returns: - list[Frame]: The next batch of frames - """ - frame_batch = [] - ids_to_remove = [] - for stream_id, stream_iter in self.streams.items(): - # Get n_frames_per_stream frames from each stream - for _ in range(self.n_frames_per_stream): - frame = next(stream_iter)[0] - frame_batch.append(frame) - if frame.is_last: - ids_to_remove.append(stream_id) - - # Remove streams that have ended - for stream_id in ids_to_remove: - self.rm_stream(stream_id) - - # If no frames are generated, raise StopIteration - if len(frame_batch) == 0: - raise StopIteration - - return frame_batch - - -class ContinuousBatchedFrameStreamer: - """ - A class that manages continuous streaming of audio frames from multiple audio files, providing - frame generation in batches. The class supports dynamically adding audio streams, updating - a progress bar, and yielding batches of frames for further processing. - """ - - def __init__( - self, - sample_rate: int, - frame_size_in_secs: float, - batch_size: int, - n_frames_per_stream: int, - pad_last_frame: bool = False, - ): - """ - Args: - sample_rate (int): The sample rate of the audio - frame_size_in_secs (float): The size of the frame in seconds - batch_size (int): The batch size - n_frames_per_stream (int): The number of frames per stream - pad_last_frame (bool): Whether to pad the last frame - """ - - self.sample_rate = sample_rate - self.frame_size_in_secs = frame_size_in_secs - self.batch_size = batch_size - self.pad_last_frame = pad_last_frame - - self.multi_streamer = MultiStream(n_frames_per_stream=n_frames_per_stream) - self.stream_id = 0 - - self._progress_bar = None - self.processed_streams = set() - - def set_audio_filepaths(self, audio_filepaths: list[str], options: list[RequestOptions]) -> None: - """ - Set the audio filepaths - Args: - audio_filepaths (list[str]): The list of audio filepaths - options (list[RequestOptions]): The list of options - """ - if len(audio_filepaths) != len(options): - raise ValueError("audio_filepaths and options must have the same length") - - self.audio_filepaths = audio_filepaths - self.options = options - self.n_audio_files = len(audio_filepaths) - self.total_progress_steps = self.n_audio_files * 2 # One step for adding, one for processing - self.sid2filepath = {} - self.elapsed_durations = {} - - def set_progress_bar(self, progress_bar: ProgressBar) -> None: - """ - Set the progress bar - Args: - progress_bar (ProgressBar): The progress bar to set - """ - self._progress_bar = progress_bar - self.restart_progress_bar() - - def restart_progress_bar(self) -> None: - """Restart the progress bar""" - if self._progress_bar: - self._progress_bar.restart() - - def update_progress_bar(self) -> None: - """Update the progress bar""" - if self._progress_bar: - self._progress_bar.update_bar(1 / self.total_progress_steps) - - def finish_progress_bar(self) -> None: - """Finish the progress bar""" - if self._progress_bar: - self._progress_bar.finish() - - def __iter__(self) -> Iterator: - """Returns the iterator object""" - return self - - def add_stream(self) -> None: - """Create a new stream and add it to the streamer""" - if self.stream_id >= self.n_audio_files: - return # No more files to add - - # Create a new stream - stream = MonoStream( - self.sample_rate, self.frame_size_in_secs, stream_id=self.stream_id, pad_last_frame=self.pad_last_frame - ) - # Load the next audio file - audio_filepath = self.audio_filepaths[self.stream_id] - options = self.options[self.stream_id] - self.sid2filepath[self.stream_id] = audio_filepath - self.elapsed_durations[self.stream_id] = 0.0 - stream.load_audio(audio_filepath, options) - - # Add the stream to the multi streamer - self.multi_streamer.add_stream(stream, stream_id=self.stream_id) - self.stream_id += 1 - - # Update the progress bar - self.update_progress_bar() - - def __next__(self) -> list[Frame]: - """ - Get the next batch of frames, continuously adding streams - Returns: - list[Frame]: The next batch of frames - """ - # If there are fewer streams than batch size, add more streams - while len(self.multi_streamer) < self.batch_size and self.stream_id < self.n_audio_files: - self.add_stream() - - try: - frames = next(self.multi_streamer) - # Update progress when a stream is fully processed - for frame in frames: - sid = frame.stream_id - self.elapsed_durations[sid] += frame.valid_size / self.sample_rate - if sid not in self.processed_streams and frame.is_last: - self.processed_streams.add(sid) - self.update_progress_bar() - return frames - except StopIteration: - # if there are remaining streams, add them - if self.stream_id < self.n_audio_files: - return self.__next__() - - if self.stream_id == self.n_audio_files: - self.finish_progress_bar() - raise StopIteration - - raise ValueError("stream_id > self.n_audio_files unexpected") - - -class ContinuousBatchedRequestStreamer: - """ - A class that manages continuous streaming of requests from multiple audio files, providing - request generation in batches. Requests can be frames or feature buffers. - The class supports dynamically adding audio streams, updating a progress bar, - and yielding batches of requests for further processing. - """ - - def __init__( - self, - sample_rate: int, - frame_size_in_secs: float, - batch_size: int, - n_frames_per_stream: int, - request_type: RequestType = RequestType.FRAME, - preprocessor: Callable = None, - buffer_size_in_secs: float = None, - device: torch.device = None, - pad_last_frame: bool = False, - right_pad_features: bool = False, - tail_padding_in_samples: int = 0, - ): - """ - Args: - sample_rate (int): The sample rate of the audio - frame_size_in_secs (float): The size of the frame in seconds - batch_size (int): The batch size - n_frames_per_stream (int): The number of frames per stream - request_type (RequestType): The type of request - preprocessor (Callable): Preprocessor object, required for request type FEATURE_BUFFER - buffer_size_in_secs (float): The size of the buffer in seconds, required for request type FEATURE_BUFFER - device (torch.device): The device to use, required for request type FEATURE_BUFFER - pad_last_frame (bool): Whether to pad the last frame - right_pad_features (bool): Whether to right pad the features, optional for request type FEATURE_BUFFER - tail_padding_in_samples (int): The tail padding in samples, optional for request type FEATURE_BUFFER - """ - - if request_type is RequestType.FEATURE_BUFFER: - if buffer_size_in_secs is None: - raise ValueError("buffer_size_in_secs must be provided for request type FEATURE_BUFFER") - if preprocessor is None: - raise ValueError("preprocessor must be provided for request type FEATURE_BUFFER") - if device is None: - raise ValueError("device must be provided for request type FEATURE_BUFFER") - - self.request_type = request_type - self.multi_streamer = ContinuousBatchedFrameStreamer( - sample_rate=sample_rate, - frame_size_in_secs=frame_size_in_secs, - batch_size=batch_size, - n_frames_per_stream=n_frames_per_stream, - pad_last_frame=pad_last_frame, - ) - - if self.request_type is RequestType.FEATURE_BUFFER: - self.preprocessor = preprocessor - self.device = device - self.audio_bufferer = BatchedAudioBufferer( - sample_rate=sample_rate, buffer_size_in_secs=buffer_size_in_secs - ) - self.right_pad_features = right_pad_features - self.tail_padding_in_samples = tail_padding_in_samples - - def set_audio_filepaths(self, audio_filepaths: list[str], options: list[RequestOptions]) -> None: - """ - Set the audio filepaths - Args: - audio_filepaths (list[str]): The list of audio filepaths - options (list[RequestOptions]): The list of options - """ - self.multi_streamer.set_audio_filepaths(audio_filepaths, options) - - def set_progress_bar(self, progress_bar: ProgressBar) -> None: - """ - Set the progress bar - Args: - progress_bar (ProgressBar): The progress bar to set - """ - self.multi_streamer.set_progress_bar(progress_bar) - - def get_audio_filepath(self, stream_id: int) -> str: - """ - Get the audio filepath for a given stream id - Args: - stream_id (int): The id of the stream - Returns: - str: The audio filepath for the given stream id - """ - return self.multi_streamer.sid2filepath[stream_id] - - def get_elapsed_duration(self, stream_id: int) -> float: - """ - Get the elapsed audio duration for a given stream id - Args: - stream_id (int): The id of the stream - Returns: - float: The elapsed audio duration for the given stream id - """ - return self.multi_streamer.elapsed_durations[stream_id] - - def to_feature_buffers(self, frames: list[Frame]) -> list[FeatureBuffer]: - """ - Convert frames to feature buffers - Args: - frames (list[Frame]): The list of frames - Returns: - list[FeatureBuffer]: The list of feature buffers - """ - - # Buffer input frames - buffered_frames, left_paddings = self.audio_bufferer.update(frames) - buffers = [] - - # If right padding is enabled, convert left paddings to tensor - if self.right_pad_features: - left_paddings = torch.tensor(left_paddings, dtype=torch.int64, device=self.device) - - # If right padding is enabled, roll the frames to the left - for i in range(len(buffered_frames)): - if self.right_pad_features: - lpad = left_paddings[i].item() - if lpad > 0: - buffered_frames[i] = buffered_frames[i].roll(shifts=-lpad) - buffers.append(buffered_frames[i].unsqueeze_(0)) - - buffer_lens = torch.tensor([buffers[0].size(1)] * len(buffers), device=self.device) - - # Calculate right paddings and subtract from buffer lens - # tail_padding_in_samples is used to keep some amount of padding at the end of the buffer - # some models perform better with this padding - right_paddings = torch.tensor( - [frame.size - frame.valid_size - self.tail_padding_in_samples for frame in frames], device=self.device - ).clamp(min=0) - - # Subtract right paddings from buffer lens - buffer_lens = buffer_lens - right_paddings - - # If right padding is enabled, subtract left paddings from buffer lens - # Becouse we rolled the frames to the left - if self.right_pad_features: - buffer_lens = buffer_lens - left_paddings - - # Apply preprocessor to get mel spectrograms - feature_buffers, feature_buffer_lens = self.preprocessor( - input_signal=torch.cat(buffers).to(self.device), length=buffer_lens - ) - - # Adjust left paddings after preprocessor - if self.right_pad_features: - left_paddings = left_paddings / self.preprocessor.featurizer.hop_length - left_paddings = left_paddings.to(torch.int64) - - return [ - FeatureBuffer( - features=feature_buffers[i], - is_first=frame.is_first, - is_last=frame.is_last, - stream_id=frame.stream_id, - right_pad_features=self.right_pad_features, - length=feature_buffer_lens[i].item(), - left_padding_length=left_paddings[i].item() if self.right_pad_features else 0, - options=frame.options, - ) - for i, frame in enumerate(frames) - ] - - def __iter__(self) -> Iterator: - """Returns the iterator object""" - return self - - def __next__(self) -> list[Request]: - """Get the next batch of requests. - Returns: - list of frames or feature buffers. - """ - if self.request_type is RequestType.FRAME: - return next(self.multi_streamer) - return self.to_feature_buffers(next(self.multi_streamer)) diff --git a/nemo/collections/asr/inference/streaming/framing/request.py b/nemo/collections/asr/inference/streaming/framing/request.py deleted file mode 100644 index 5706bcc31232e754eb4109c08a609a6c23b85dc4..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/framing/request.py +++ /dev/null @@ -1,107 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from dataclasses import dataclass -from typing import TypeAlias - -import torch - -from nemo.collections.asr.inference.streaming.framing.request_options import RequestOptions - - -@dataclass(frozen=True, slots=True) -class Frame: - """ - Immutable dataclass representing - - Args: - samples (torch.Tensor): The actual frame data. For audio, shape is (T,). - stream_id (int): Unique identifier for the stream this frame belongs to - is_first (bool): Flag indicating if this is the first frame in the stream - is_last (bool): Flag indicating if this is the last frame in the stream - length (int): Length of the frame without padding. - If -1, returns the size of the frame including padding. - vad_segments (torch.Tensor | None): Optional VAD segments to use for end-of-utterance detection. - Shape is [num_vad_segments, 2] where each segment contains - [start_time, end_time]. Variable for each stream. - options (RequestOptions | None): Optional options for the request - """ - - samples: torch.Tensor - stream_id: int - is_first: bool = False - is_last: bool = False - length: int = -1 - vad_segments: torch.Tensor | None = None - options: RequestOptions | None = None - - @property - def size(self) -> int: - """Returns the size of the frame including padding""" - return self.samples.shape[0] - - @property - def valid_size(self) -> int: - """Returns the size of the frame without padding""" - return self.size if self.length == -1 else self.length - - -@dataclass(frozen=True, slots=True) -class FeatureBuffer: - """ - Immutable dataclass representing a buffer of features. - Args: - features (torch.Tensor): The actual frame data. For features, shape is (feature_dim, T). - stream_id (int): Unique identifier for the stream this frame belongs to - is_first (bool): Flag indicating if this is the first frame in the stream - is_last (bool): Flag indicating if this is the last frame in the stream - right_pad_features (bool): Flag indicating if the features are right padded - length (int): Length of the valid features in the buffer - If -1, returns the size of the buffer including padding - left_padding_length (int): Length of the left padding in the buffer - It is used to roll features to the right - vad_segments (torch.Tensor | None): Optional VAD segments to use for end-of-utterance detection. - Shape is [num_vad_segments, 2] where each segment contains - [start_time, end_time]. Variable for each stream. - options (RequestOptions | None): Optional options for the request - """ - - features: torch.Tensor - stream_id: int - is_first: bool = False - is_last: bool = False - right_pad_features: bool = False - length: int = -1 - left_padding_length: int = 0 - vad_segments: torch.Tensor | None = None - options: RequestOptions | None = None - - @property - def size(self) -> int: - """Returns the number of features in the buffer including padding""" - return self.features.shape[1] - - @property - def valid_size(self) -> int: - """Returns the size of the buffer without padding. It is a actual length of the signal""" - return self.size if self.length == -1 else self.length - - @property - def roll_size(self) -> int: - """Returns the size of the buffer to roll to the right. It only makes sense for right padded feature buffers""" - return self.left_padding_length if self.right_pad_features else 0 - - -Request: TypeAlias = Frame | FeatureBuffer diff --git a/nemo/collections/asr/inference/streaming/framing/request_options.py b/nemo/collections/asr/inference/streaming/framing/request_options.py deleted file mode 100644 index 78b9c1867dcc88a192ccac8296590fe48c0912d3..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/framing/request_options.py +++ /dev/null @@ -1,138 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from dataclasses import dataclass -from typing import Any, TypeAlias - -from nemo.collections.asr.inference.utils.enums import ASROutputGranularity -from nemo.collections.asr.parts.context_biasing.biasing_multi_model import BiasingRequestItemConfig - - -@dataclass(slots=True) -class ASRRequestOptions: - """ - Immutable dataclass representing options for a request - None value means that the option is not set and the default value will be used - """ - - enable_itn: bool = None - enable_pnc: bool = None - stop_history_eou: int = None - asr_output_granularity: ASROutputGranularity | str = None - language_code: str | None = None - enable_nmt: bool = None - source_language: str = None - target_language: str = None - biasing_cfg: BiasingRequestItemConfig | None = None - - def __post_init__(self) -> None: - """ - Post-init hook: - Converts the asr_output_granularity to ASROutputGranularity if it is a string - """ - if isinstance(self.asr_output_granularity, str): - self.asr_output_granularity = ASROutputGranularity.from_str(self.asr_output_granularity) - - if not self.enable_nmt: - # Forcibly set the source and target languages to None - self.source_language = None - self.target_language = None - - def is_word_level_output(self) -> bool: - """ - Check if the output granularity is word level. - """ - return self.asr_output_granularity is ASROutputGranularity.WORD - - def is_segment_level_output(self) -> bool: - """ - Check if the output granularity is segment level. - """ - return self.asr_output_granularity is ASROutputGranularity.SEGMENT - - @staticmethod - def _with_default(value: Any, default: Any) -> Any: - """ - Return the value if it is not None, otherwise return the default value. - Args: - value: The value to check. - default: The default value to return if the value is None. - Returns: - The value if it is not None, otherwise return the default value. - """ - return default if value is None else value - - def augment_with_defaults( - self, - default_enable_itn: bool, - default_enable_pnc: bool, - default_enable_nmt: bool, - default_source_language: str, - default_target_language: str, - default_stop_history_eou: int, - default_asr_output_granularity: ASROutputGranularity | str, - default_language_code: str | None = None, - biasing_cfg: BiasingRequestItemConfig | None = None, - ) -> "ASRRequestOptions": - """ - Fill unset fields with the passed default values. - Args: - default_enable_itn (bool): Default enable ITN. - default_enable_pnc (bool): Default enable PNC. - default_enable_nmt (bool): Default enable NMT. - default_source_language (str): Default source language. - default_target_language (str): Default target language. - default_stop_history_eou (int): Default stop history EOU. - default_asr_output_granularity (ASROutputGranularity | str): Default output granularity. - default_language_code (str | None): Default language code for prompt-enabled models. - biasing_cfg: Default biasing config or None - Returns: - ASRRequestOptions: Augmented options. - """ - if isinstance(default_asr_output_granularity, str): - default_asr_output_granularity = ASROutputGranularity.from_str(default_asr_output_granularity) - - enable_itn = self._with_default(self.enable_itn, default_enable_itn) - enable_pnc = self._with_default(self.enable_pnc, default_enable_pnc) - enable_nmt = self._with_default(self.enable_nmt, default_enable_nmt) - if not enable_nmt: - # Forcibly set the source and target languages to None - source_language, target_language = None, None - else: - source_language = self._with_default(self.source_language, default_source_language) - target_language = self._with_default(self.target_language, default_target_language) - - stop_history_eou = self._with_default(self.stop_history_eou, default_stop_history_eou) - granularity = self._with_default(self.asr_output_granularity, default_asr_output_granularity) - language_code = self._with_default(self.language_code, default_language_code) - - return ASRRequestOptions( - enable_itn=enable_itn, - enable_pnc=enable_pnc, - enable_nmt=enable_nmt, - source_language=source_language, - target_language=target_language, - stop_history_eou=stop_history_eou, - asr_output_granularity=granularity, - language_code=language_code, - biasing_cfg=self.biasing_cfg or biasing_cfg, - ) - - def has_biasing_request(self): - """Return True if contains non-empty biasing request""" - return self.biasing_cfg is not None and (not self.biasing_cfg.is_empty()) - - -RequestOptions: TypeAlias = ASRRequestOptions diff --git a/nemo/collections/asr/inference/streaming/framing/stream.py b/nemo/collections/asr/inference/streaming/framing/stream.py deleted file mode 100644 index ecf2731d3f5b405213d65fed288aedd77421d6d9..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/framing/stream.py +++ /dev/null @@ -1,40 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -class Stream: - """ - Minimal interface for a stream - """ - - def __init__(self, stream_id: int): - """ - Args: - stream_id: (int) The id of the stream. - """ - self._stream_id = stream_id - self.frame_count = 0 - - def __iter__(self): - """Returns the iterator object""" - return self - - def __next__(self): - """Get the next frame in the stream""" - raise NotImplementedError("Subclasses must implement __next__ method") - - @property - def stream_id(self) -> int: - """Get the stream id""" - return self._stream_id diff --git a/nemo/collections/asr/inference/streaming/state/__init__.py b/nemo/collections/asr/inference/streaming/state/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/state/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/asr/inference/streaming/state/cache_aware_ctc_state.py b/nemo/collections/asr/inference/streaming/state/cache_aware_ctc_state.py deleted file mode 100644 index 5b0beda8b2cb399ac1a5ce9eeabbab8fc3cd7941..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/state/cache_aware_ctc_state.py +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from nemo.collections.asr.inference.streaming.state.cache_aware_state import CacheAwareStreamingState - - -class CacheAwareCTCStreamingState(CacheAwareStreamingState): - """ - State of the cache aware CTC streaming pipelines - """ - - pass diff --git a/nemo/collections/asr/inference/streaming/state/cache_aware_rnnt_state.py b/nemo/collections/asr/inference/streaming/state/cache_aware_rnnt_state.py deleted file mode 100644 index c9374c37ba264b400d12c5eb71c4d2cca099b13c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/state/cache_aware_rnnt_state.py +++ /dev/null @@ -1,66 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from nemo.collections.asr.inference.streaming.state.cache_aware_state import CacheAwareStreamingState -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis - - -class CacheAwareRNNTStreamingState(CacheAwareStreamingState): - """ - State of the cache aware RNNT streaming pipelines - """ - - def __init__(self): - """ - Initialize the CacheAwareRNNTStreamingState - """ - super().__init__() - self._additional_params_reset() - - def reset(self) -> None: - """ - Reset the state - """ - super().reset() - self._additional_params_reset() - - def _additional_params_reset(self) -> None: - """ - Reset non-inherited parameters - """ - super()._additional_params_reset() - self.previous_hypothesis = None - - def set_previous_hypothesis(self, previous_hypothesis: Hypothesis) -> None: - """ - Set the previous hypothesis - Args: - previous_hypothesis: (Hypothesis) The previous hypothesis to store for the next transcribe step - """ - self.previous_hypothesis = previous_hypothesis - - def get_previous_hypothesis(self) -> Hypothesis | None: - """ - Get the previous hypothesis - Returns: - (Hypothesis) The previous hypothesis - """ - return self.previous_hypothesis - - def reset_previous_hypothesis(self) -> None: - """ - Reset the previous hypothesis to None - """ - self.previous_hypothesis = None diff --git a/nemo/collections/asr/inference/streaming/state/cache_aware_state.py b/nemo/collections/asr/inference/streaming/state/cache_aware_state.py deleted file mode 100644 index f87b18edc002ec452017f2565ff6600e7d667586..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/state/cache_aware_state.py +++ /dev/null @@ -1,101 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from nemo.collections.asr.inference.streaming.state.state import StreamingState - - -class CacheAwareStreamingState(StreamingState): - """ - State of the cache aware CTC/RNNT streaming pipelines - """ - - def __init__(self): - """ - Initialize the CacheAwareStreamingState - """ - super().__init__() - self._additional_params_reset() - - def reset(self) -> None: - """ - Reset the state - """ - super().reset() - self._additional_params_reset() - - def _additional_params_reset(self) -> None: - """ - Reset non-inherited parameters - """ - # label_buffer will be used to detect EoU - self.label_buffer = [] - self.label_buffer_size = 0 - self.offset = 0 - - def set_offset(self, offset: int) -> None: - """ - Set the offset - Args: - offset: (int) offset - """ - self.offset = offset - - def setup_label_buffer(self, label_buffer_size: int, blank_id: int) -> None: - """ - Set up the label buffer - Args: - label_buffer_size: (int) size of the label buffer - blank_id: (int) blank id - """ - self.label_buffer_size = label_buffer_size - self.label_buffer = [blank_id] * self.label_buffer_size - - def update_label_buffer(self, labels: list[int]) -> None: - """ - Update the label buffer - Args: - labels: (list[int]) list of labels - """ - shift = len(labels) - self.label_buffer[:-shift] = self.label_buffer[shift:].copy() - self.label_buffer[-shift:] = labels.copy() - - def get_label_buffer(self) -> list[int]: - """ - Get the current label buffer - Returns: - list[int]: current state of the label buffer - """ - return self.label_buffer.copy() - - def update_state(self, completed_output: dict, eou_detected: bool) -> None: - """ - Update the state with the completed output - Args: - completed_output: (dict) completed output - eou_detected: (bool) is EoU detected - """ - - if len(completed_output) == 0 or len(completed_output["tokens"]) == 0: - return - - timesteps = completed_output["timesteps"] - for i, t in enumerate(timesteps): - timesteps[i] = t + self.global_offset - - # we will not perform overlap aware merging of the tokens for CacheAware Models - # It is too error-prone to do this in the streaming mode -> skip=0 - self._update_state(completed_output, skip=0) - self.eou_detected_before = eou_detected diff --git a/nemo/collections/asr/inference/streaming/state/ctc_state.py b/nemo/collections/asr/inference/streaming/state/ctc_state.py deleted file mode 100644 index 0ad5f21901d8ca0dbcfdf5dc9779e33b2b858613..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/state/ctc_state.py +++ /dev/null @@ -1,23 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.asr.inference.streaming.state.state import StreamingState - - -class CTCStreamingState(StreamingState): - """ - State of the streaming CTC pipeline - """ - - pass diff --git a/nemo/collections/asr/inference/streaming/state/rnnt_state.py b/nemo/collections/asr/inference/streaming/state/rnnt_state.py deleted file mode 100644 index b2eade1badc54d3fe45dc8fd53eee4258e35d4a8..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/state/rnnt_state.py +++ /dev/null @@ -1,42 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.asr.inference.streaming.state.state import StreamingState - - -class RNNTStreamingState(StreamingState): - """ - State of the streaming RNNT pipeline - """ - - def __init__(self): - """ - Initialize the RNNTStreamingState - """ - super().__init__() - self._additional_params_reset() - - def reset(self) -> None: - """ - Reset the state - """ - super().reset() - self._additional_params_reset() - - def _additional_params_reset(self) -> None: - """ - Reset non-inherited parameters - """ - self.timestamp_offset = 0 - self.hyp_decoding_state = None diff --git a/nemo/collections/asr/inference/streaming/state/salm_state.py b/nemo/collections/asr/inference/streaming/state/salm_state.py deleted file mode 100644 index 20025fa1e0567503bcc9e7e2bab7d88568dc2fc4..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/state/salm_state.py +++ /dev/null @@ -1,23 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.asr.inference.streaming.state.state import StreamingState - - -class SALMStreamingState(StreamingState): - """ - State of the streaming SALM pipeline - """ - - pass diff --git a/nemo/collections/asr/inference/streaming/state/state.py b/nemo/collections/asr/inference/streaming/state/state.py deleted file mode 100644 index 2e311a2900ee68efb85e3ebafd2f322f99ef30e6..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/state/state.py +++ /dev/null @@ -1,385 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import re -from typing import Callable - -from nemo.collections.asr.inference.streaming.framing.request import RequestOptions -from nemo.collections.asr.inference.utils.constants import POST_WORD_PUNCTUATION -from nemo.collections.asr.inference.utils.state_management_utils import ( - detect_overlap, - merge_segment_tail, - merge_timesteps, - merge_word_tail, -) -from nemo.collections.asr.inference.utils.text_segment import TextSegment, Word - -CLOSE_IN_TIME_TH = 2.0 -OVERLAP_SEARCH_TH = 3 - - -class StreamingState: - """ - Generic state for the streaming ASR pipeline - """ - - options: RequestOptions | None - - def __init__(self): - """ - Initialize the StreamingState - """ - self._reset_streaming_state() - - def reset(self) -> None: - """ - Reset the state to its initial values - """ - self._reset_streaming_state() - - def _reset_streaming_state(self) -> None: - """ - Initialize the state with default values - """ - - # Global offset is used to keep track of the timestamps - self.global_offset = 0 - - # All tokens, timestamps and conf scores that have been processed since the last EOU - self.tokens = [] - self.timesteps = [] - self.confidences = [] - - # Predicted tokens for the current step - self.current_step_tokens = [] - - # Last token and its index are used to detect overlap between the current and the previous output - self.last_token = None - self.last_token_idx = None - - # Tokens left in the right padding segment of the buffer - self.incomplete_segment_tokens = [] - - # final_transcript, partial_transcript, current_step_transcript and final_segments will be sent to the client - self.final_transcript = "" - self.partial_transcript = "" - self.current_step_transcript = "" - self.concat_with_space = True - self.final_segments = [] - - # Translation attributes - self.previous_translation_info = ("", "") - self.previous_context = ("", "") - - # Word-level ASR output attributes (cleared after cleanup_after_response): - # - words: Raw word-level ASR output - # - pnc_words: Words with punctuation and capitalization applied - # * When automatic punctuation is ENABLED: Contains punctuation marks and capitalization - # (from either external PnC model or built-in ASR model PnC) - # * When automatic punctuation is DISABLED: No punctuation or capitalization - # (any punctuation in raw ASR output will be removed) - # - itn_words: Words after applying both PnC and ITN (Inverse Text Normalization) - # - word_alignment: ITN word alignment - # Segment-level ASR output attributes (cleared after cleanup_after_response): - # - segments: Raw segment-level ASR output - # - processed_segment_mask: Mask indicating which segments have been processed - # - final_segments: Final segment-level ASR output - self.words = [] - self.pnc_words = [] - self.itn_words = [] - self.word_alignment = [] - self.segments = [] - self.processed_segment_mask = [] - - # Flag to indicate if EOU was detected before, used in merging logic - self.eou_detected_before = False - - # Used in EoU detection logic - self.decoder_start_idx = 0 - self.decoder_end_idx = 0 - - # Request options - self.options = None - - # Prompt-related index (set by pipelines that use prompts) - self.prompt_idx = None - - def set_options(self, options: RequestOptions) -> None: - """ - Set the options - Args: - options: (RequestOptions) The request options to store in the state - """ - self.options = options - - def set_prompt_index(self, prompt_idx: int) -> None: - """ - Store the resolved prompt index for prompt-enabled models. - Args: - prompt_idx: (int) The prompt index to store in the state - """ - self.prompt_idx = prompt_idx - - def set_incomplete_segment_tokens(self, incomplete_segment_tokens: list) -> None: - """ - Set the partial tokens - Args: - incomplete_segment_tokens: (list) The partial tokens to store in the state - """ - self.incomplete_segment_tokens = incomplete_segment_tokens - - def set_global_offset(self, start_offset: float) -> None: - """ - Set the global offset - Args: - start_offset: (float) The global offset to store in the state - """ - self.global_offset = start_offset - - def set_last_token(self, token: int | None, idx: int | None) -> None: - """ - Set the last token - Args: - token: (int | None) The last token to store in the state - idx: (int | None) The index of the last token to store in the state - """ - if None not in [token, idx]: - self.last_token_idx = idx + self.global_offset - self.last_token = token - else: - self.last_token_idx = None - self.last_token = None - - def increment_global_offset(self, shift: float) -> None: - """ - Increment the global offset by the given shift - Args: - shift: (float) The shift to increment the global offset by - """ - self.global_offset += shift - - def _update_state(self, output: dict, skip: int) -> None: - """ - Extend the tokens, timesteps and confidences, optionally skipping the first few tokens - Args: - output: (dict) The output to update the state with - skip: (int) The number of tokens to skip - """ - current_tokens = output["tokens"] - current_timesteps = output["timesteps"] - current_confidences = output["confidences"] - if skip > 0: - current_tokens = current_tokens[skip:] - current_timesteps = current_timesteps[skip:] - current_confidences = current_confidences[skip:] - - self.current_step_tokens.extend(current_tokens) - self.tokens.extend(current_tokens) - self.confidences.extend(current_confidences) - self.timesteps = merge_timesteps(self.timesteps, current_timesteps) - - def update_state(self, completed_output: dict, eou_detected: bool) -> None: - """ - Update the state with the completed output - Args: - completed_output: (dict) The completed output to update the state with - eou_detected: (bool) Whether EOU was detected - """ - - if len(completed_output) == 0 or len(completed_output["tokens"]) == 0: - self.last_token = None - self.last_token_idx = None - return - - timesteps = completed_output["timesteps"] - for i, t in enumerate(timesteps): - timesteps[i] = t + self.global_offset - - overlap = 0 - if not self.eou_detected_before: - overlap = detect_overlap( - state_tokens=self.tokens, - state_timesteps=self.timesteps, - new_tokens=completed_output["tokens"], - new_timesteps=timesteps, - overlap_search_th=OVERLAP_SEARCH_TH, - close_in_time_th=CLOSE_IN_TIME_TH, - ) - - # In case when the tokens are empty after EoU, - # we need to check if the last token is the same as the first token of the completed output - if ( - self.eou_detected_before - and self.last_token == completed_output["tokens"][0] - and self.last_token_idx is not None - and abs(self.last_token_idx - timesteps[0]) <= CLOSE_IN_TIME_TH - ): - overlap = max(overlap, 1) - - self._update_state(completed_output, overlap) - self.eou_detected_before = eou_detected - - def update_from_decoder_results(self, start_idx: int, end_idx: int) -> None: - """ - Update state based on decoder results - This is used to dynamically understand current token start and end indices - Args: - start_idx: (int) The start index of the decoder results - end_idx: (int) The end index of the decoder results - """ - self.decoder_start_idx = start_idx - self.decoder_end_idx = end_idx - - def cleanup_translation_info_after_eou(self) -> None: - """ - Cleanup the translation info after an EOU is detected - """ - self.previous_translation_info = ("", "") - - def set_translation_info(self, translation: str, prefix: str) -> None: - """ - Set the translation info - Args: - translation: (str) The translation to store in the state - prefix: (str) The prefix to store in the state - """ - self.previous_translation_info = (translation, prefix) - - def set_translation_context(self, src_context: str, tgt_context: str) -> None: - """ - Set the translation context - Args: - src_context: (str) The source context to store in the state - tgt_context: (str) The target context to store in the state - """ - src_context = re.sub(r'\s+', ' ', src_context).strip() - tgt_context = re.sub(r'\s+', ' ', tgt_context).strip() - if not (src_context and tgt_context): - src_context = tgt_context = "" - - self.previous_context = (src_context, tgt_context) - - def cleanup_after_eou(self) -> None: - """ - Cleanup the state after an EOU is detected - """ - self.tokens.clear() - self.timesteps.clear() - self.confidences.clear() - - def cleanup_after_response(self) -> None: - """ - Cleanup the state after a response is sent - Specifically used to clean the state after final transcript is sent - """ - - if self.options.is_word_level_output(): - self.words.clear() - self.pnc_words.clear() - self.itn_words.clear() - self.word_alignment.clear() - else: - self.segments.clear() - self.processed_segment_mask.clear() - - self.final_transcript = "" - self.final_segments.clear() - self.current_step_transcript = "" - self.current_step_tokens.clear() - self.concat_with_space = True - - def push_back_segment( - self, - segment: TextSegment, - need_merge: bool, - conf_aggregator: Callable = None, - ) -> None: - """ - Push back the decoded segment to the state - Args: - segment: (TextSegment) The decoded segment to push back to the state - need_merge: (bool) Whether to merge the segment with the last segment in the state - conf_aggregator: (Callable) The function to aggregate the confidence - """ - - # concat_with_space is used to determine if the final transcript should be concatenated with a space - if len(self.final_segments) == 0 and need_merge: - self.concat_with_space = False - else: - self.concat_with_space = True - - if need_merge and len(self.segments) > 0: - head = merge_segment_tail( - segment_head=self.segments[-1], - segment_tail=segment, - conf_aggregator=conf_aggregator, - ) - self.segments[-1] = head - self.processed_segment_mask[-1] = False - else: - self.segments.append(segment) - self.processed_segment_mask.append(False) - - def push_back_words( - self, - decoded_words: list[Word], - merge_first_word: bool = False, - merge_first_word_punctuation: bool = True, - conf_aggregator: Callable = None, - ) -> None: - """ - Push back the decoded words to the state - Args: - decoded_words: (list[Word]) The decoded words to push back to the state - merge_first_word: (bool) Whether to merge the first word with the last word in the state - merge_first_word_punctuation: (bool) Whether to merge the first word punctuation with the last word in the state - conf_aggregator: (Callable) The function to aggregate the confidence - """ - if not decoded_words: - return - - # concat_with_space is used to determine if the final transcript should be concatenated with a space - if len(self.final_segments) == 0 and merge_first_word: - self.concat_with_space = False - else: - self.concat_with_space = True - - if ( - (fst_word_txt := decoded_words[0].text) - and fst_word_txt in POST_WORD_PUNCTUATION - and merge_first_word_punctuation - ): - # if the first word is a punctuation mark, merge it with the last word stored in the state - if len(self.words) > 0: - self.words[-1].text += fst_word_txt - decoded_words = decoded_words[1:] - - elif merge_first_word and len(self.words) > 0: - head, pnc_head = merge_word_tail( - word_head=self.words[-1], - word_tail=decoded_words[0], - pnc_word_head=self.pnc_words[-1] if len(self.pnc_words) > 0 else None, - conf_aggregator=conf_aggregator, - ) - self.words[-1] = head - if pnc_head is not None: - self.pnc_words[-1] = pnc_head - decoded_words = decoded_words[1:] - - self.words.extend(decoded_words) - - def has_biasing_request(self) -> bool: - """Return True if options contains non-empty biasing request""" - return self.options is not None and self.options.has_biasing_request() diff --git a/nemo/collections/asr/inference/streaming/text/__init__.py b/nemo/collections/asr/inference/streaming/text/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/text/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/asr/inference/streaming/text/text_processing.py b/nemo/collections/asr/inference/streaming/text/text_processing.py deleted file mode 100644 index 13f7c259ce1bc20896a52300c543b71988964ce7..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/streaming/text/text_processing.py +++ /dev/null @@ -1,414 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from __future__ import annotations - -import re -from functools import partial -from typing import TYPE_CHECKING, Callable - -from omegaconf import DictConfig - -from nemo.collections.asr.inference.streaming.state.state import StreamingState -from nemo.collections.asr.inference.utils.constants import POST_WORD_PUNCTUATION -from nemo.collections.asr.inference.utils.pipeline_utils import ( - get_leading_punctuation_regex_pattern, - get_repeated_punctuation_regex_pattern, -) -from nemo.collections.asr.inference.utils.text_segment import Word, normalize_segments_inplace - -if TYPE_CHECKING: - from nemo.collections.asr.inference.itn.inverse_normalizer import AlignmentPreservingInverseNormalizer - - -class StreamingTextProcessor: - """ - A streaming text post-processing module that applies punctuation & capitalization (PnC) and - inverse text normalization (ITN) to ASR transcriptions in real-time. - - This class supports configurable pipelines where PnC and ITN can be enabled/disabled dynamically. - It ensures that the final output adheres to proper punctuation, capitalization, and normalized text. - """ - - def __init__( - self, - itn_cfg: DictConfig, - itn_model: AlignmentPreservingInverseNormalizer | None, - asr_supported_puncts: set, - asr_supports_punctuation: bool, - confidence_aggregator: Callable, - sep: str, - enable_pnc: bool = False, - enable_itn: bool = False, - ): - """ - Initialize the streaming text processor. - - Args: - itn_cfg (DictConfig): ITN parameters. - itn_model (AlignmentPreservingInverseNormalizer | None): Model for inverse text normalization (ITN). - asr_supported_puncts (set): Set of punctuation marks recognized by the ASR model. - asr_supports_punctuation (bool): Boolean indicating if the ASR model outputs punctuation. - confidence_aggregator (Callable): Function for aggregating confidence scores. - sep (str): String separator used in ASR output processing. - enable_pnc (bool): Boolean to enable PnC. Default is False. - enable_itn (bool): Boolean to enable ITN. Default is False. - """ - - self.pnc_enabled = enable_pnc and asr_supports_punctuation - self.supports_punctuation = asr_supports_punctuation - - self.itn_model = itn_model - self.itn_enabled = False - if enable_itn: - self.itn_enabled = itn_model is not None - - self.itn_runtime_params = { - "batch_size": itn_cfg.batch_size, - "n_jobs": itn_cfg.n_jobs, - } - self.itn_left_padding_size = itn_cfg.left_padding_size - - self.asr_supported_puncts = asr_supported_puncts - self.asr_supported_puncts_str = ''.join(self.asr_supported_puncts) - self.sep = sep - self.rm_punctuation_capitalization_from_segments_fn = partial( - normalize_segments_inplace, punct_marks=self.asr_supported_puncts, sep=self.sep - ) - - puncts_to_process = self.asr_supported_puncts - self.leading_punctuation_regex_pattern = get_leading_punctuation_regex_pattern(puncts_to_process) - self.repeated_punctuation_regex_pattern = get_repeated_punctuation_regex_pattern(puncts_to_process) - - self.alignment_aware_itn_model = None - if self.itn_enabled: - from nemo.collections.asr.inference.itn.batch_inverse_normalizer import ( - BatchAlignmentPreservingInverseNormalizer, - ) - - self.alignment_aware_itn_model = BatchAlignmentPreservingInverseNormalizer( - itn_model=self.itn_model, - sep=self.sep, - asr_supported_puncts=self.asr_supported_puncts, - post_word_punctuation=POST_WORD_PUNCTUATION, - conf_aggregate_fn=confidence_aggregator, - ) - - def is_itn_enabled(self) -> bool: - """Check if ITN is enabled""" - return self.itn_enabled - - def is_pnc_enabled(self) -> bool: - """Check if PnC is enabled""" - return self.pnc_enabled - - def is_enabled(self) -> bool: - """Check if PnC or ITN is enabled""" - return self.is_pnc_enabled() or self.is_itn_enabled() - - def process(self, states: list[StreamingState]) -> None: - """ - Apply PnC and ITN on the states. - Args: - states: (list[StreamingState]) List of StreamingState objects - """ - word_boundary_states, segment_boundary_states = [], [] - for state in states: - if state.options.is_word_level_output(): - word_boundary_states.append(state) - else: - segment_boundary_states.append(state) - - # Process states with word boundaries - if word_boundary_states: - self.process_states_with_word_boundaries(word_boundary_states) - - # Process states with segment boundaries - if segment_boundary_states: - self.process_states_with_segment_boundaries(segment_boundary_states) - - # Generate final transcript - self.generate_final_transcript(word_boundary_states, segment_boundary_states) - - def process_states_with_segment_boundaries(self, states: list[StreamingState]) -> None: - """ - Process states with segment boundaries. - Args: - states (list[StreamingState]): List of StreamingState objects that have segments - """ - states_with_text = [state for state in states if len(state.segments) > 0] - if len(states_with_text) == 0: - return - - # if PnC & ITN DISABLED globally, remove PnC from the words if ASR supports punctuation - if not self.is_enabled(): - if self.supports_punctuation: - segments = [] - for state in states_with_text: - for i, seg in enumerate(state.segments): - if not state.processed_segment_mask[i]: - segments.append(seg) - state.processed_segment_mask[i] = True - self.rm_punctuation_capitalization_from_segments_fn(segments) - return - - # Remove PnC from states where PnC is disabled - for state in states_with_text: - if (not state.options.enable_pnc) or (not self.is_pnc_enabled()): - if self.supports_punctuation: - self.rm_punctuation_capitalization_from_segments_fn(state.segments) - - # Apply ITN - if self.is_itn_enabled(): # If ITN ENABLED globally - # collect texts - texts = [] - for i, state in enumerate(states_with_text): - # if ITN is disabled for this state - if not state.options.enable_itn: - continue - - for j, seg in enumerate(state.segments): - if state.processed_segment_mask[j]: # if the segment is already processed, skip it - continue - texts.append((i, j, seg.text)) - - if len(texts) > 0: - # apply ITN - processed_texts = self.itn_model.inverse_normalize_list( - texts=[text for _, _, text in texts], params=self.itn_runtime_params - ) - # update states with ITN-processed texts - for (i, j, _), processed_text in zip(texts, processed_texts): - states_with_text[i].segments[j].text = processed_text - - # --> Apply External PnC here (if needed) - - # mark all segments as processed - for state in states_with_text: - if state.options.enable_pnc: - for seg in state.segments: - if self.leading_punctuation_regex_pattern: - seg.text = re.sub(self.leading_punctuation_regex_pattern, r'\1', seg.text) - if self.repeated_punctuation_regex_pattern: - seg.text = re.sub(self.repeated_punctuation_regex_pattern, r'\1', seg.text) - state.processed_segment_mask = [True] * len(state.segments) - - def process_states_with_word_boundaries(self, states: list[StreamingState]) -> None: - """ - Apply PnC and ITN on the states. - Args: - states: (list[StreamingState]) List of StreamingState objects - """ - # Get the indices of the states that have new words to process - indices, asr_words_list = self.prepare_asr_words(states) - - # If PnC & ITN DISABLED globally, remove PnC from the words - # Does not matter that individual request has enabled itn or pnc - if not self.is_enabled(): - self.handle_plain_asr_transcriptions(states, indices, asr_words_list) - return - - # Keep or remove PnC from the words - for idx, jdx, z in indices: - if not states[idx].options.enable_pnc and self.supports_punctuation: - self.rm_punctuation_capitalization_from_segments_fn(asr_words_list[jdx]) - states[idx].pnc_words[-z:] = asr_words_list[jdx][-z:] - - # If ITN is disabled globally, do nothing - if not self.itn_enabled: - return - - # Apply Inverse Text Normalization (ITN) - self.apply_itn(states, indices) - self.realign_punctuated_words(states, indices) - - def realign_punctuated_words(self, states: list[StreamingState], indices: list[tuple]) -> None: - """ - Realign punctuation and capitalization after applying ITN. - Ensures that capitalization and punctuation marks from the original ASR output - are properly reflected in the final ITN-processed text. - - Args: - states (list[StreamingState]): List of StreamingState objects to be updated. - indices (list[tuple]): Indices of words within states that need realignment. - """ - for idx, _, z in indices: - state = states[idx] - if not state.options.enable_itn: - continue - - z_idx = len(state.words) - z - - itn_idx = len(state.itn_words) - for sids, _, _ in reversed(state.word_alignment): - st, et = sids[0], sids[-1] - itn_idx -= 1 - if st < z_idx and et < z_idx: - break - - last_char = state.pnc_words[et].text[-1] - first_char = state.pnc_words[st].text[0] - - itn_word_orig = state.itn_words[itn_idx] - itn_word_copy = itn_word_orig.copy() - itn_word_text = itn_word_copy.text.lower() - - # preserve the first char capitalization - first_word = state.pnc_words[st].copy() - first_char_is_upper = first_word.text[0].isupper() - first_word.normalize_text_inplace(self.asr_supported_puncts, self.sep) - if first_char_is_upper and itn_word_text.startswith(first_word.text): - itn_word_orig.capitalize() - - # preserve the last punctuation mark - if last_char in self.asr_supported_puncts: - itn_word_orig.text = itn_word_orig.text.rstrip(self.asr_supported_puncts_str) + last_char - - # preserve the first punctuation mark - if first_char in self.asr_supported_puncts: - itn_word_orig.text = first_char + itn_word_orig.text.lstrip(self.asr_supported_puncts_str) - - state.itn_words[itn_idx] = itn_word_orig - - def prepare_asr_words(self, states: list[StreamingState]) -> tuple[list[tuple], list[list[Word]]]: - """ - Find the indices of the states that have words to process. - Args: - states: (list[StreamingState]) List of StreamingState objects - Returns: - tuple[list[tuple], list[list[Word]]]: - indices: list of indices of the states that have words to process - asr_words_list: list of words to process - """ - indices, asr_words_list = [], [] - - jdx = 0 - for idx, state in enumerate(states): - if (n_not_punctuated_words := len(state.words) - len(state.pnc_words)) == 0: - continue - - words_list = [word.copy() for word in state.words[-n_not_punctuated_words:]] - asr_words_list.append(words_list) - state.pnc_words.extend([None] * n_not_punctuated_words) - indices.append((idx, jdx, len(words_list))) - jdx += 1 - - return indices, asr_words_list - - def handle_plain_asr_transcriptions( - self, states: list[StreamingState], indices: list[tuple], asr_words_list: list[list[Word]] - ) -> None: - """ - Handle scenarios where PnC and ITN are disabled. - In such cases, remove Punctuation and Capitalization from the words. - Args: - states: (list[StreamingState]) List of StreamingState objects - indices: (list[tuple]) List of indices of the states that have words to process - asr_words_list: (list[list[Word]]) List of words - """ - if self.supports_punctuation: - self.rm_punctuation_capitalization_from_segments_fn(asr_words_list) - - for idx, jdx, z in indices: - states[idx].pnc_words[-z:] = asr_words_list[jdx][-z:] - - def apply_itn(self, states: list[StreamingState], indices: list[tuple]) -> None: - """ - Apply Inverse Text Normalization (ITN) on the states. - Calculates the lookback for ITN and updates the states with the ITN results. - Args: - states: (list[StreamingState]) List of StreamingState objects - indices: (list[tuple]) List of indices of the states that have words to process - """ - itn_indices, asr_words_list, pnc_words_list = [], [], [] - jdx = 0 - for state_idx, _, _ in indices: - state = states[state_idx] - if not state.options.enable_itn: - continue - s, t, cut_point = self.calculate_itn_lookback(state) - asr_words_list.append([word.copy() for word in state.words[s:]]) - pnc_words_list.append([word.copy() for word in state.pnc_words[s:]]) - itn_indices.append((state_idx, jdx, s, t, cut_point)) - jdx += 1 - output = self.alignment_aware_itn_model( - asr_words_list, pnc_words_list, self.itn_runtime_params, return_alignment=True - ) - self.update_itn_words(states, output, itn_indices) - - def calculate_itn_lookback(self, state: StreamingState) -> tuple[int, int, int]: - """ - Calculate the lookback for ITN. - Args: - state: (StreamingState) StreamingState object - Returns: - Start index (int): Start index of the source (non itn-ed) words - Target index (int): Start index of the target (itn-ed) words - Cut point (int): Index to cut the source words - """ - s, t, cut_point = 0, 0, len(state.itn_words) - word_alignment = list(reversed(state.word_alignment)) - for idx, (sidx, tidx, _) in enumerate(word_alignment, start=1): - s, t = sidx[0], tidx[0] - state.word_alignment.pop() - cut_point -= 1 - if idx == self.itn_left_padding_size: - break - return s, t, cut_point - - @staticmethod - def update_itn_words(states: list[StreamingState], output: list[tuple], indices: list[tuple]) -> None: - """ - Update the states with the ITN results. - Updates the word_alignment and itn_words in the states. - Args: - states: (list[StreamingState]) List of StreamingState objects - output: (list[tuple]) List of output tuples containing the spans and alignment - indices: (list[tuple]) List of indices of the states that have words to process - """ - for state_idx, jdx, s, t, cut_point in indices: - state = states[state_idx] - spans, alignment = output[jdx] - for sidx, tidx, sclass in alignment: - sidx = [k + s for k in sidx] - tidx = [k + t for k in tidx] - state.word_alignment.append((sidx, tidx, sclass)) - - state.itn_words = state.itn_words[:cut_point] + spans - assert len(state.word_alignment) == len(state.itn_words) - - def generate_final_transcript( - self, word_boundary_states: list[StreamingState], segment_boundary_states: list[StreamingState] - ) -> None: - """ - Generate final transcript based on enabled features and word count. - Args: - word_boundary_states (list[StreamingState]): The streaming state containing words - segment_boundary_states (list[StreamingState]): The streaming state containing segments - """ - # Generate final transcript for word boundary states - for state in word_boundary_states: - attr_name = "itn_words" if state.options.enable_itn else "pnc_words" - words = getattr(state, attr_name) - for word in words: - state.final_segments.append(word.copy()) - state.final_transcript += word.text + self.sep - state.final_transcript = state.final_transcript.rstrip(self.sep) - - # Generate final transcript for segment boundary states - for state in segment_boundary_states: - for segment in state.segments: - state.final_segments.append(segment.copy()) - state.final_transcript += segment.text + self.sep - state.final_transcript = state.final_transcript.rstrip(self.sep) diff --git a/nemo/collections/asr/inference/utils/__init__.py b/nemo/collections/asr/inference/utils/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/utils/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/asr/inference/utils/audio_io.py b/nemo/collections/asr/inference/utils/audio_io.py deleted file mode 100644 index 17fc9d1a9a3f1b64d2a83ca7ca070f4eebe84090..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/utils/audio_io.py +++ /dev/null @@ -1,29 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import librosa -import torch - - -def read_audio(audio_file: str, target_sr: int, mono: bool = True) -> torch.Tensor: - """ - Read audio file and return samples with target sampling rate - Args: - audio_file: (str) audio file path - target_sr: (int) target sampling rate - mono: (bool) whether to convert to mono - Returns: - (torch.Tensor) audio samples - """ - return torch.tensor(librosa.load(audio_file, sr=target_sr, mono=mono)[0]).float() diff --git a/nemo/collections/asr/inference/utils/bpe_decoder.py b/nemo/collections/asr/inference/utils/bpe_decoder.py deleted file mode 100644 index 18148801c64e4a31755d7f59bc8f2e6a679e9739..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/utils/bpe_decoder.py +++ /dev/null @@ -1,269 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from functools import lru_cache -from typing import Callable - -import numpy as np - -from nemo.collections.asr.inference.streaming.state.state import StreamingState -from nemo.collections.asr.inference.utils.constants import ( - POST_WORD_PUNCTUATION, - ROUND_PRECISION, - SENTENCEPIECE_UNDERSCORE, -) -from nemo.collections.asr.inference.utils.text_segment import TextSegment, Word -from nemo.collections.common.tokenizers.tokenizer_spec import TokenizerSpec - - -class BPEDecoder: - """ - BPEDecoder class for decoding BPE (Byte Pair Encoding) tokens into words and segments by preserving timestamps and confidence scores - """ - - def __init__( - self, - vocabulary: list[str], - tokenizer: TokenizerSpec, - confidence_aggregator: Callable, - asr_supported_puncts: set, - word_boundary_tolerance: float, - token_duration_in_secs: float, - ): - """ - Initialize the BPEDecoder. - Args: - vocabulary (list[str]): List of vocabulary tokens. - tokenizer (TokenizerSpec): Tokenizer object. - confidence_aggregator (Callable): Confidence aggregator function. - asr_supported_puncts (set): Set of supported punctuation symbols. - word_boundary_tolerance (float): Word boundary tolerance for timestamp refinement. - token_duration_in_secs (float): Token duration in seconds. - """ - - self.vocabulary = vocabulary - self.tokenizer = tokenizer - self.confidence_aggregator = confidence_aggregator - self.asr_supported_puncts = asr_supported_puncts - self.punct_marks_with_underscore = asr_supported_puncts.union({SENTENCEPIECE_UNDERSCORE}) - self.word_boundary_tolerance = word_boundary_tolerance - self.token_duration_in_secs = token_duration_in_secs - self.start_of_word_cache = { - token_id: token.startswith(SENTENCEPIECE_UNDERSCORE) for token_id, token in enumerate(self.vocabulary) - } - self.punct_cache = { - token_id: (token in self.asr_supported_puncts, token in self.punct_marks_with_underscore) - for token_id, token in enumerate(self.vocabulary) - } - - @lru_cache(maxsize=10000) - def cached_ids_to_text(self, tokens_slice: tuple[int]) -> str: - """ - Cached tokenizer output to avoid repeated calls to the tokenizer. - Args: - tokens_slice (tuple): Tuple of token indices to be detokenized. - Returns: - str: Detokenized text. - """ - word_text = self.tokenizer.ids_to_text(list(tokens_slice)).strip() - return word_text - - def decode_bpe_tokens(self, state: StreamingState) -> None: - """ - Decodes BPE tokens into words or segments with timestamps and confidence scores. - Args: - state (StreamingState): The state object containing the BPE tokens, timestamps, and confidence scores. - """ - if state.options.is_word_level_output(): - # Form words and push them to the state - decoded_words, need_merge = self.group_tokens_into_words(state.tokens, state.timesteps, state.confidences) - state.push_back_words(decoded_words, need_merge, self.confidence_aggregator) - elif state.options.is_segment_level_output(): - # Form text segment and push it to the state - if state.tokens: - decoded_segment, need_merge = self.group_tokens_into_segment( - state.tokens, state.timesteps, state.confidences - ) - state.push_back_segment(decoded_segment, need_merge, self.confidence_aggregator) - else: - raise ValueError(f"Invalid output granularity: {state.options.asr_output_granularity}") - - def group_tokens_into_segment( - self, tokens: list, timesteps: list, confidences: list - ) -> tuple[TextSegment | None, bool]: - """ - Group tokens into a text segment with timestamps and confidence scores. - Args: - tokens (list): List of token indices. - timesteps (list): List of token timestamps. - confidences (list): List of token confidence scores. - Returns: - (tuple[TextSegment | None, bool]) Text segment with text, start time, end time, and confidence score. - Also returns a boolean to indicate if the text segment should be merged with the last segment stored in the state - """ - n_tokens = len(tokens) - - if n_tokens != len(timesteps) or n_tokens != len(confidences): - raise ValueError("tokens, timesteps and confidences must have the same length") - - if n_tokens == 0: - return None, False - - need_merge = not bool(self.start_of_word_cache[tokens[0]]) - - # Get the segment text - segment_text = self.tokenizer.ids_to_text(tokens).strip() - - # Refine the start and end timestamps of the text segment - start, end = self.refine_text_segment_timestamp(tokens, timesteps) - - # Convert token timestamps to seconds - start = round(start * self.token_duration_in_secs, ROUND_PRECISION) - end = round(end * self.token_duration_in_secs, ROUND_PRECISION) - - # Aggregate the confidence score of the text segment - conf = self.confidence_aggregator(confidences) - - # Create a text segment - return TextSegment(text=segment_text, start=start, end=end, conf=conf), need_merge - - def group_tokens_into_words(self, tokens: list, timesteps: list, confidences: list) -> tuple[list[Word], bool]: - """ - Decodes BPE tokens into words with timestamps and confidence scores. - Args: - tokens (list): List of token indices. - timesteps (list): List of token timesteps. - confidences (list): List of token confidence scores. - Returns: - (tuple[list[Word], bool]) List of decoded words with text, start time, end time, and confidence score. - Also returns a boolean to indicate if the first word should be merged with the last word stored in the state - """ - n_tokens = len(tokens) - - if n_tokens != len(timesteps) or n_tokens != len(confidences): - raise ValueError("tokens, timesteps and confidences must have the same length") - - if n_tokens == 0: - return [], False - - # Group tokens into words - is_start_mask = np.fromiter((self.start_of_word_cache[tok] for tok in tokens), dtype=np.int32) - word_ids = np.cumsum(is_start_mask) - - start_indices = np.nonzero(np.diff(word_ids, prepend=word_ids[0] - 1))[0] - end_indices = np.append(start_indices[1:], n_tokens) - - decoded_words, prev_word_end = [], None - - # If the first word is the start of a word, we need to merge it with the last word stored in the state - need_merge = not bool(is_start_mask[0]) - - for start_idx, end_idx in zip(start_indices, end_indices): - - tokens_slice = tokens[start_idx:end_idx] - time_slice = timesteps[start_idx:end_idx] - conf_slice = confidences[start_idx:end_idx] - - word_text = self.cached_ids_to_text(tuple(tokens_slice)) - - # Ignore empty text - if not word_text: - continue - - # Append the post word punctuation to the previous word - if word_text in POST_WORD_PUNCTUATION and len(decoded_words) > 0: - prev_word = decoded_words[-1] - prev_word.text += word_text - continue - - # Refine timestamps - word_start_tms, word_end_tms = self.refine_text_segment_timestamp( - current_tokens=tokens_slice, - current_timesteps=time_slice, - next_segment_start_timestep=timesteps[end_idx] if end_idx < n_tokens else None, - need_merge_with_next_segment=( - self.start_of_word_cache[tokens[end_idx]] if end_idx < n_tokens else None - ), - prev_segment_end=prev_word_end, - ) - prev_word_end = word_end_tms - - # Aggregate confidence - word_conf = self.confidence_aggregator(conf_slice) - - # Convert token timestamps to seconds - start_sec = round(word_start_tms * self.token_duration_in_secs, ROUND_PRECISION) - end_sec = round(word_end_tms * self.token_duration_in_secs, ROUND_PRECISION) - - decoded_words.append(Word(text=word_text, start=start_sec, end=end_sec, conf=word_conf)) - - return decoded_words, need_merge - - def refine_text_segment_timestamp( - self, - current_tokens: list[int], - current_timesteps: list[float], - next_segment_start_timestep: float | None = None, - need_merge_with_next_segment: bool | None = None, - prev_segment_end: float | None = None, - ) -> tuple[float, float]: - """ - Refines the text segment timestamp based on the current tokens, timestamps, and the next segment start timestamp. - Args: - current_tokens (list[int]): List of token indices. - current_timesteps (list[float]): List of token timestamps. - next_segment_start_timestep (float | None): The start timestamp of the next segment. - need_merge_with_next_segment (bool | None): True if the current segment should be merged with the next segment. - prev_segment_end (float | None): The end timestamp of the previous segment. - Returns: - tuple(float, float): The refined start and end timestamps. - """ - - start, end = current_timesteps[0], current_timesteps[-1] - - # --- Correct the start timestamp if the first token is underscore or punctuation --- - first_token = current_tokens[0] - if self.punct_cache[first_token][1]: - start = next( - (tms for tms, token in zip(current_timesteps, current_tokens) if not self.punct_cache[token][1]), - start, - ) - - # --- Correct the end timestamp if the last token is punctuation --- - last_token = current_tokens[-1] - if self.punct_cache[last_token][0]: - end = next( - ( - current_timesteps[i] - for i in reversed(range(len(current_tokens))) - if not self.punct_cache[current_tokens[i]][0] - ), - end, - ) - - # --- If the next segment is close to the end of the current segment, merge timestamps --- - if next_segment_start_timestep is not None and need_merge_with_next_segment: - if next_segment_start_timestep - end <= self.word_boundary_tolerance: - end = next_segment_start_timestep - - # --- Adjust the start and end timestamps based on the previous segment end --- - delta = 0 - if prev_segment_end is not None: - if prev_segment_end > start: - delta = prev_segment_end - start - - start = start + delta - end = end + delta - return start, end + (1 if start == end else 0) diff --git a/nemo/collections/asr/inference/utils/config_io.py b/nemo/collections/asr/inference/utils/config_io.py deleted file mode 100644 index e4e2fea982a51fc5a3a03faa8a38350bdca475be..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/utils/config_io.py +++ /dev/null @@ -1,40 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os - -from hydra import compose, initialize -from hydra.core.global_hydra import GlobalHydra -from omegaconf import DictConfig - - -def read_config(config_path: str, config_name: str) -> DictConfig: - """ - Read configuration file - Args: - config_path: (str) Absolute path to the configuration file - config_name: (str) Name of the configuration file - Returns: - (DictConfig) Configuration object - """ - - rel_to = os.path.dirname(os.path.realpath(__file__)) - - # Reset the global Hydra instance if already initialized to prevent duplicate initialization errors - if GlobalHydra.instance().is_initialized(): - GlobalHydra.instance().clear() - - with initialize(version_base=None, config_path=os.path.relpath(config_path, rel_to)): - cfg = compose(config_name=config_name) - return cfg diff --git a/nemo/collections/asr/inference/utils/constants.py b/nemo/collections/asr/inference/utils/constants.py deleted file mode 100644 index c67488a96f76f44db082161f76f6a799cfd200d5..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/utils/constants.py +++ /dev/null @@ -1,33 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Precision related constants -BIG_EPSILON = 1e-5 -SMALL_EPSILON = 1e-10 -ROUND_PRECISION = 9 - -# ASR Preprocessing related constants -LOG_MEL_ZERO = -16.635 - -# Punctuation related constants -POST_WORD_PUNCTUATION = set(".,?") -PRE_WORD_PUNCTUATION = set("¿") -SEP_REPLACEABLE_PUNCTUATION = set("-_") -SENTENCEPIECE_UNDERSCORE = "▁" - -# ITN related constants -DEFAULT_SEMIOTIC_CLASS = "name" - -# Default output directory name -DEFAULT_OUTPUT_DIR_NAME = "jsons" diff --git a/nemo/collections/asr/inference/utils/context_manager.py b/nemo/collections/asr/inference/utils/context_manager.py deleted file mode 100644 index 012fa2477623dbe996c24994e55e15e6649b9527..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/utils/context_manager.py +++ /dev/null @@ -1,197 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from queue import Queue -from typing import Any - -import torch -from torch import Tensor - - -class CacheAwareContext: - """ - Stores the cache state for the Cache-Aware models. - """ - - def __init__( - self, - cache_last_channel: Tensor | None = None, - cache_last_time: Tensor | None = None, - cache_last_channel_len: Tensor | None = None, - ): - """ - Args: - cache_last_channel (Tensor | None): Last channel of the cache. - cache_last_time (Tensor | None): Last time of the cache. - cache_last_channel_len (Tensor | None): Last channel length of the cache. - """ - self.cache_last_channel = cache_last_channel - self.cache_last_time = cache_last_time - self.cache_last_channel_len = cache_last_channel_len - - -class CacheAwareContextManager: - """ - Manager class to manipulate the cached states for the Cache-Aware models. - """ - - def __init__( - self, - cache_aware_model: Any, - num_slots: int, - use_cache: bool = True, - ): - """ - Initialize the CacheAwareContextManager. - Args: - cache_aware_model (Any): Cache-Aware model object. It should have the get_initial_cache_state method. - num_slots (int): Number of slots to use for the cache. It should be greater than or equal to the batch size. - use_cache (bool): Whether to use the cache. Default is True. If False, the cache is disabled. - """ - self.cache_aware_model = cache_aware_model - # Cache aware model should have the following methods: - if not hasattr(self.cache_aware_model, "get_initial_cache_state"): - raise ValueError("Cache aware model should have the get_initial_cache_state method") - - self.num_slots = num_slots - self.cache_disabled = not use_cache - self.cache_last_channel = None - self.cache_last_time = None - self.cache_last_channel_len = None - self.reset() - - def reset(self) -> None: - """Resets the context manager""" - if self.cache_disabled: - return - - self.streamidx2slotidx = {} - self.slotidx2streamidx = {} - self.free_slots = Queue(self.num_slots) - for i in range(self.num_slots): - self.free_slots.put(i) - ( - self.cache_last_channel, # [17, B, 70, 512] - self.cache_last_time, # [17, B, 512, 8] - self.cache_last_channel_len, # B - ) = self.cache_aware_model.get_initial_cache_state(self.num_slots) - self.device = self.cache_last_channel.device - - def _reset_slots(self, slot_ids: list[int]) -> None: - """ - Resets the slots for the given slot_ids - Args: - slot_ids: list of slot indices to reset - """ - if self.cache_disabled: - return - - slot_ids_tensor = torch.tensor(slot_ids, device=self.device, dtype=torch.long) - self.cache_last_channel.index_fill_(1, slot_ids_tensor, 0.0) - self.cache_last_time.index_fill_(1, slot_ids_tensor, 0.0) - self.cache_last_channel_len.index_fill_(0, slot_ids_tensor, 0) - - # free the slot, so that it can be used by other streams - # remove the stream from the mappings - for slot_id in slot_ids: - self.free_slots.put(slot_id) - stream_id = self.slotidx2streamidx[slot_id] - del self.slotidx2streamidx[slot_id] - del self.streamidx2slotidx[stream_id] - - def update_cache(self, stream_ids: list[int], new_context: CacheAwareContext, mapping: dict) -> None: - """ - Updates the cache for the given stream_ids with the new_context - Args: - stream_ids (list[int]): list of stream ids - new_context (CacheAwareContext): new context to update corresponding to the stream_ids - mapping (dict): mapping between the old and new slots - """ - if self.cache_disabled: - return - - slot_ids_list = [self.streamidx2slotidx[sid] for sid in stream_ids] - slot_ids = torch.tensor(slot_ids_list, device=self.device, dtype=torch.long) - tgt_slot_ids = torch.tensor( - [mapping[sid] for sid in slot_ids_list], - device=self.device, - dtype=torch.long, - ) - - # In-place copy along batch/slot dimension - self.cache_last_channel.index_copy_(1, slot_ids, new_context.cache_last_channel.index_select(1, tgt_slot_ids)) - self.cache_last_time.index_copy_(1, slot_ids, new_context.cache_last_time.index_select(1, tgt_slot_ids)) - self.cache_last_channel_len.index_copy_( - 0, slot_ids, new_context.cache_last_channel_len.index_select(0, tgt_slot_ids) - ) - - def reset_slots(self, stream_ids: list[int], eos_flags: list[bool]) -> None: - """ - Resets the slots for the finished streams - Args: - stream_ids (list[int]): list of stream ids - eos_flags (list[bool]): list of eos flags indicating whether the stream has finished - """ - if self.cache_disabled: - return - - if len(stream_ids) != len(eos_flags): - raise ValueError("stream_ids and eos_flags must have the same length") - - if len(stream_ids) == 0: - return - - # reset the slots for finished streams - self._reset_slots([self.streamidx2slotidx[sid] for sid, eos in zip(stream_ids, eos_flags) if eos]) - - def get_context(self, stream_ids: list[int]) -> tuple[CacheAwareContext, dict]: - """ - Retrieves the context from the cache for the given stream_ids - Args: - stream_ids (list[int]): list of stream ids - Returns: - context (CacheAwareContext): context for the given stream_ids - mapping (dict): mapping between the cache and retrieved context - """ - - if len(stream_ids) == 0 or self.cache_disabled: - # Create a dummy context with None values - return CacheAwareContext(), {} - - # if the stream_id is new, we need to assign a slot to it - for stream_id in stream_ids: - if stream_id not in self.streamidx2slotidx: - if self.free_slots.empty(): - raise RuntimeError("No free slots available") - slot_idx = self.free_slots.get() - self.streamidx2slotidx[stream_id] = slot_idx - self.slotidx2streamidx[slot_idx] = stream_id - - # get the cache for the particular stream_ids - slot_ids = [self.streamidx2slotidx[stream_id] for stream_id in stream_ids] - cache_last_channel = self.cache_last_channel[:, slot_ids, :, :] - cache_last_time = self.cache_last_time[:, slot_ids, :, :] - cache_last_channel_len = self.cache_last_channel_len[slot_ids] - - # create a context object - context = CacheAwareContext( - cache_last_channel=cache_last_channel, - cache_last_time=cache_last_time, - cache_last_channel_len=cache_last_channel_len, - ) - - # mapping between cache and context - mapping = dict(zip(slot_ids, range(len(slot_ids)))) - return context, mapping diff --git a/nemo/collections/asr/inference/utils/device_utils.py b/nemo/collections/asr/inference/utils/device_utils.py deleted file mode 100644 index 320a6da5c8386046e0273ec4d6997f2887d693ea..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/utils/device_utils.py +++ /dev/null @@ -1,68 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import torch -from nemo.utils import logging - -COMPUTE_DTYPE_MAP = { - 'bfloat16': torch.bfloat16, - 'float16': torch.float16, - 'float32': torch.float32, -} - -DEVICE_TYPES = ["cuda", "mps", "cpu"] - - -def setup_device(device: str, device_id: int | None, compute_dtype: str) -> tuple[str, int, torch.dtype]: - """ - Set up the compute device for the model. - - Args: - device (str): Requested device type ('cuda', 'mps' or 'cpu'). - device_id (int | None): Requested CUDA device ID (None for CPU or MPS). - compute_dtype (str): Requested compute dtype. - - Returns: - tuple(str, int, torch.dtype): Tuple of (device_string, device_id, compute_dtype) for model initialization. - """ - device = device.strip() - if device not in DEVICE_TYPES: - raise ValueError(f"Invalid device type: {device}. Must be one of {DEVICE_TYPES}") - - device_id = int(device_id) if device_id is not None else 0 - - # Handle CUDA devices - if torch.cuda.is_available() and device == "cuda": - if device_id >= torch.cuda.device_count(): - logging.warning(f"Device ID {device_id} is not available. Using GPU 0 instead.") - device_id = 0 - - compute_dtype = COMPUTE_DTYPE_MAP.get(compute_dtype, None) - if compute_dtype is None: - raise ValueError( - f"Invalid compute dtype: {compute_dtype}. Must be one of {list(COMPUTE_DTYPE_MAP.keys())}" - ) - - device_str = f"cuda:{device_id}" - return device_str, device_id, compute_dtype - - # Handle MPS devices - if torch.backends.mps.is_available() and device == "mps": - return "mps", -1, torch.float32 - - # Handle CPU devices - if device == "cpu": - return "cpu", -1, torch.float32 - - raise ValueError(f"Device {device} is not available.") diff --git a/nemo/collections/asr/inference/utils/endpointing_utils.py b/nemo/collections/asr/inference/utils/endpointing_utils.py deleted file mode 100644 index c72a6230164c197dcf2ee76596220cbbbf7b3114..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/utils/endpointing_utils.py +++ /dev/null @@ -1,44 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -def millisecond_to_frames(millisecond: int, ms_per_timestep: int) -> int: - """ - Convert milliseconds to frames - Args: - millisecond (int): milliseconds to convert - ms_per_timestep (int): milliseconds per timestep - Returns: - int: number of frames - """ - return (millisecond + ms_per_timestep - 1) // ms_per_timestep - - -def get_custom_stop_history_eou( - stop_history_eou: int | None, default_stop_history_eou: int, ms_per_timestep: int -) -> int: - """ - Get the custom stop history of EOU - Args: - stop_history_eou (int): stop history of EOU - default_stop_history_eou (int): default stop history of EOU - ms_per_timestep (int): milliseconds per timestep - Returns: - int: custom stop history of EOU - """ - if stop_history_eou is None: - return default_stop_history_eou - if stop_history_eou > 0: - return millisecond_to_frames(stop_history_eou, ms_per_timestep) - return 0 if stop_history_eou == 0 else -1 diff --git a/nemo/collections/asr/inference/utils/enums.py b/nemo/collections/asr/inference/utils/enums.py deleted file mode 100644 index 87c1092dc9ac040afe90607a078ee4b14636b634..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/utils/enums.py +++ /dev/null @@ -1,84 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from enum import Enum, auto - - -class StrEnumMixin: - @classmethod - def from_str(cls, name: str): - """Convert a string to an Enum value (case-insensitive).""" - normalized = name.lower() - for member in cls: - if member.name.lower() == normalized or str(member.value).lower() == normalized: - return member - - choices = [member.name.lower() for member in cls] - raise ValueError(f"Invalid {cls.__name__} `{name}`: must be one of {choices}") - - -class ASRDecodingType(StrEnumMixin, Enum): - """ - Enumeration of the ASR decoding types. - """ - - CTC = auto() - RNNT = auto() - SALM = auto() - - -class ASROutputGranularity(StrEnumMixin, Enum): - """ - Enumeration of the ASR output granularity. - """ - - WORD = auto() - SEGMENT = auto() - - -class PipelineType(StrEnumMixin, Enum): - """ - Enumeration of the pipeline types. - """ - - BUFFERED = auto() - CACHE_AWARE = auto() - - -class RequestType(StrEnumMixin, Enum): - """ - Enumeration of the request types. - """ - - FRAME = auto() - FEATURE_BUFFER = auto() - - -class FeatureBufferPaddingMode(StrEnumMixin, Enum): - """ - Enumeration of the feature buffer padding modes. - """ - - LEFT = auto() - RIGHT = auto() - - -class MergingStrategy(StrEnumMixin, Enum): - """ - Enumeration of the tokens merging strategies for the buffered inference. - """ - - LCS = auto() # Longest Common Subsequence - LCSUBSTR = auto() # Longest Common Substring diff --git a/nemo/collections/asr/inference/utils/itn_utils.py b/nemo/collections/asr/inference/utils/itn_utils.py deleted file mode 100644 index 1316e099b77197bbd7cdd19f11987779ea998470..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/utils/itn_utils.py +++ /dev/null @@ -1,88 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import re -from collections import OrderedDict - -from nemo.collections.asr.inference.utils.constants import DEFAULT_SEMIOTIC_CLASS - - -# Compile regex pattern once at module level for better performance -TOKEN_PATTERN = re.compile(r'tokens \{.*?(?=tokens \{|$)', re.DOTALL) - - -def get_semiotic_class(tokens: list[OrderedDict]) -> str: - """ - Returns the semiotic class of the given tokens. - """ - return list(tokens[0]["tokens"].keys())[0] - - -def split_text(text: str, sep: str = " ") -> tuple[list, int]: - """ - Splits the text into words based on the separator. - Args: - text: (str) input text - sep: (str) separator to split the text - Returns: - words: (list) list of words - n_words: (int) number of words - """ - words = [w for w in text.split(sep) if w] - return words, len(words) - - -def find_tokens(text: str) -> list[str]: - """ - Find the start and end positions of token blocks in the given text. - Args: - text: (str) input text containing token blocks - Returns: - token_blocks: (list[str]) list of token blocks - """ - - # Use compiled regex to find all token blocks in a single pass - token_blocks = TOKEN_PATTERN.findall(text) - - # Strip whitespace from each block - return [block.strip() for block in token_blocks] - - -def get_trivial_alignment(N: int, i_shift: int = 0, o_shift: int = 0) -> list[tuple]: - """ - Returns a trivial word alignment for N input words. - Args: - N: (int) number of input words - i_shift: (int) input shift - o_shift: (int) output shift - Returns: - (list) Returns a trivial word alignment - """ - return [([i + i_shift], [i + o_shift], DEFAULT_SEMIOTIC_CLASS) for i in range(N)] - - -def fallback_to_trivial_alignment( - input_words: list[str], i_shift: int = 0, o_shift: int = 0 -) -> tuple[list[str], list[str], list[tuple]]: - """ - Returns a trivial word alignment for the input words. - Args: - input_words: (list[str]) list of input words - i_shift: (int) input shift - o_shift: (int) output shift - Returns: - (tuple) Returns a tuple of input words, output words, and a trivial word alignment - """ - return input_words, input_words.copy(), get_trivial_alignment(N=len(input_words), i_shift=i_shift, o_shift=o_shift) diff --git a/nemo/collections/asr/inference/utils/lcs_merge.py b/nemo/collections/asr/inference/utils/lcs_merge.py deleted file mode 100644 index 5f5a0e733b2df56622d3c853507bb98712f2d8a5..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/utils/lcs_merge.py +++ /dev/null @@ -1,113 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.asr.inference.utils.enums import MergingStrategy -from nemo.collections.asr.parts.utils.streaming_utils import longest_common_subsequence_merge - - -def longest_common_substring(buffer: list[int], data: list[int]) -> tuple[int, int, int]: - """ - Find the longest common substring between two lists of integers. - If there are multiple LCSs, return the rightmost one in the buffer. - Args: - buffer: (list[int]) The buffer of tokens. - data: (list[int]) The new tokens to merge with the buffer. - Returns: - A tuple containing - (tuple[int, int, int]): - - Start index of the longest common substring in the buffer. - - Start index of the longest common substring in the data. - - Length of the longest common substring. - """ - n, m = len(buffer), len(data) - dp = [[0] * (m + 1) for _ in range(n + 1)] - - max_len = 0 - end_i = end_j = -1 - - for i in range(1, n + 1): - for j in range(1, m + 1): - if buffer[i - 1] == data[j - 1]: - dp[i][j] = dp[i - 1][j - 1] + 1 - - # Logic: - # 1. If we find a strictly longer substring, take it. - # 2. If it's the same length, update if this occurrence - # ends further right in the buffer (larger i). - if dp[i][j] > max_len or (dp[i][j] == max_len and i >= end_i): - max_len = dp[i][j] - end_i = i - end_j = j - else: - dp[i][j] = 0 - - if max_len == 0: - return -1, -1, 0 - - return end_i - max_len, end_j - max_len, max_len - - -def lcs_merge( - buffer: list[int], - data: list[int], - search_size: int, - sep_id: list[int] | None = None, - min_lcs_length: int = 1, - merging_strategy: MergingStrategy = MergingStrategy.LCSUBSTR, -) -> list[int]: - """ - Merge the buffer and data using the LCS algorithm. - Args: - buffer: (list[int]) The buffer of tokens. - data: (list[int]) The new tokens to merge with the buffer. - search_size: (int) The size of the search window in the buffer. - sep_id: (list[int] | None) The separator token ids. If no LCS is found, separator token is used to merge the buffer and data. - min_lcs_length: (int) The minimum length of the LCS. - merging_strategy: (MergingStrategy) The merging strategy to use. - Returns: - (list[int]) The merged tokens. - """ - - if len(buffer) == 0: - buffer += data - return buffer - - if sep_id is None: - sep_id = [] - - if search_size < 1: - buffer += sep_id + data - return buffer - - buffer_slice = buffer[-search_size:] - - if merging_strategy == MergingStrategy.LCSUBSTR: - i_rel, j_rel, length = longest_common_substring(buffer_slice, data) - elif merging_strategy == MergingStrategy.LCS: - (i_rel, j_rel, length), _ = longest_common_subsequence_merge(buffer_slice, data) - else: - raise ValueError( - f"Invalid merging strategy: {merging_strategy!r}. Supported strategies: {[s.name for s in MergingStrategy]}" - ) - - if length < min_lcs_length: - buffer += sep_id + data - return buffer - - base = len(buffer) - len(buffer_slice) - i_abs_start = base + i_rel - i_abs_end = i_abs_start + length # end position (exclusive) in `buffer` - j_after = j_rel + length # first index after LCS in `data` - - merged = buffer[:i_abs_end] + data[j_after:] - return merged diff --git a/nemo/collections/asr/inference/utils/manifest_io.py b/nemo/collections/asr/inference/utils/manifest_io.py deleted file mode 100644 index 2aca89d1e7a2e0e16afbe896926b55d239b9bb6f..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/utils/manifest_io.py +++ /dev/null @@ -1,197 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import json -import os - -import librosa -from omegaconf import OmegaConf - -from nemo.collections.asr.inference.streaming.framing.request_options import ASRRequestOptions -from nemo.collections.asr.inference.utils.constants import DEFAULT_OUTPUT_DIR_NAME -from nemo.collections.asr.parts.context_biasing.biasing_multi_model import BiasingRequestItemConfig -from nemo.collections.asr.parts.utils.manifest_utils import read_manifest -from nemo.collections.common.parts.preprocessing.manifest import get_full_path - - -def make_abs_path(path: str) -> str: - """ - Make a path absolute - Args: - path: (str) Path to the file or folder - Returns: - (str) Absolute path - """ - path = path.strip() - if not path: - raise ValueError("Path cannot be empty") - if not os.path.isabs(path): - path = os.path.abspath(path) - return path - - -def prepare_audio_data( - audio_file: str, sort_by_duration: bool = True -) -> tuple[list[str], list[dict] | None, list[ASRRequestOptions] | None, dict[str, int]]: - """ - Get audio filepaths from a folder or a single audio file - Args: - audio_file: (str) Path to the audio file, folder or manifest file - sort_by_duration: (bool) If True, sort the audio files by duration from shortest to longest - Returns: - (list[str], list[dict] | None, list[ASRRequestOptions] | None, dict[str, int]) - List of audio filepaths, manifest, options and filepath order - """ - audio_file = audio_file.strip() - audio_file = make_abs_path(audio_file) - manifest = None - options = None - if os.path.isdir(audio_file): - filepaths = filter(lambda x: x.endswith(".wav"), os.listdir(audio_file)) - filepaths = [os.path.join(audio_file, x) for x in filepaths] - elif audio_file.endswith(".wav"): - filepaths = [audio_file] - elif audio_file.endswith((".json", ".jsonl")): - manifest = read_manifest(audio_file) - filepaths = [get_full_path(entry["audio_filepath"], audio_file) for entry in manifest] - for record, filepath in zip(manifest, filepaths): - record["audio_filepath"] = filepath - options = [ - ASRRequestOptions( - biasing_cfg=( - BiasingRequestItemConfig( - **OmegaConf.to_container( - OmegaConf.merge(OmegaConf.structured(BiasingRequestItemConfig), record["biasing_request"]) - ) - ) - if "biasing_request" in record - else None - ) - ) - for record in manifest - ] - else: - raise ValueError(f"audio_file `{audio_file}` need to be folder, audio file or manifest file") - - filepath_order = {filepath: i for i, filepath in enumerate(filepaths)} - if sort_by_duration: - indices = list(range(len(filepaths))) - durations = [librosa.get_duration(path=filepaths[i]) for i in indices] - indices_with_durations = list(zip(indices, durations)) - indices_with_durations.sort(key=lambda x: x[1]) - filepaths = [filepaths[i] for i, duration in indices_with_durations] - if manifest is not None: - # keep manifest in the same order as filepaths for consistency - manifest = [manifest[i] for i, duration in indices_with_durations] - options = [options[i] for i, duration in indices_with_durations] - - return filepaths, manifest, options, filepath_order - - -def get_stem(file_path: str) -> str: - """ - Get the stem of a file path - Args: - file_path: (str) Path to the file - Returns: - (str) Filename with extension - """ - return file_path.split('/')[-1] - - -def dump_output( - output: dict, - output_filename: str, - output_dir: str | None = None, - manifest: list[dict] | None = None, - filepath_order: dict[str, int] | None = None, -) -> None: - """ - Dump the transcriptions to a output file - Args: - output (dict): Pipeline output, structured as {stream_id: {"text": str, "segments": list}} - output_filename: (str) Path to the output file - output_dir: (str | None) Path to the output directory, if None, will write at the same level as the output file - manifest: (list[dict] | None) Original manifest to copy extra fields from - filepath_order: (dict[str, int] | None) Order of the audio filepaths in the output - """ - # Create default output directory, if not provided - if output_dir is None: - output_dir = os.path.dirname(output_filename) - output_dir = os.path.join(output_dir, DEFAULT_OUTPUT_DIR_NAME) - os.makedirs(output_dir, exist_ok=True) - - # Create a mapping of audio filepaths to their index in the manifest - manifest_index = None - if manifest is not None: - manifest_index = {entry["audio_filepath"]: i for i, entry in enumerate(manifest)} - - # Define an order of the audio filepaths - if filepath_order is not None: - # Sort based on the original filepath order - ordered_output = sorted(output.values(), key=lambda d: filepath_order[d["audio_filepath"]]) - else: - # Sort based on the stream id - ordered_output = [output[k] for k in sorted(output)] - - with open(output_filename, 'w') as fout: - for data in ordered_output: - audio_filepath = data["audio_filepath"] - text = data["text"] - translation = data["translation"] - segments = data["segments"] - stem = get_stem(audio_filepath) - stem = os.path.splitext(stem)[0] - json_filepath = os.path.join(output_dir, f"{stem}.json") - json_filepath = make_abs_path(json_filepath) - with open(json_filepath, 'w') as json_fout: - for segment in segments: - json_line = json.dumps(segment.to_dict(), ensure_ascii=False) - json_fout.write(f"{json_line}\n") - - item = { - "audio_filepath": audio_filepath, - "pred_text": text, - "pred_translation": translation, - "json_filepath": json_filepath, - } - - # Copy extra fields from manifest - if manifest_index is not None: - manifest_entry = manifest[manifest_index[audio_filepath]] - for key in manifest_entry: - if key not in item: - item[key] = manifest_entry[key] - - json.dump(item, fout, ensure_ascii=False) - fout.write('\n') - fout.flush() - - -def calculate_duration(audio_filepaths: list[str]) -> tuple[float, dict[str, float]]: - """ - Calculate the duration of the audio files - Args: - audio_filepaths: (list[str]) List of audio filepaths - Returns: - (float) Total duration of the audio files - (dict[str, float]) Dictionary containing the duration of each audio file - """ - total_duration = 0 - durations = {} - for audio_filepath in audio_filepaths: - duration = librosa.get_duration(path=audio_filepath) - total_duration += duration - durations[audio_filepath] = duration - return total_duration, durations diff --git a/nemo/collections/asr/inference/utils/pipeline_eval.py b/nemo/collections/asr/inference/utils/pipeline_eval.py deleted file mode 100644 index db94d854d9e6d8d7667deba7063f7b192f44b917..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/utils/pipeline_eval.py +++ /dev/null @@ -1,126 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from omegaconf import DictConfig - -from nemo.collections.asr.parts.utils.eval_utils import cal_write_text_metric, cal_write_wer, compute_laal -from nemo.utils import logging - - -def evaluate_pipeline(output_path: str, cfg: DictConfig) -> None: - """ - Evaluate pipeline output and overwrite the output file with the metrics. - Args: - output_path: Path to the output file. - cfg: Configuration object. - """ - - if cfg.calculate_wer: - try: - asr_metrics_cfg = cfg.metrics.asr - output_manifest_w_wer, total_res, _ = cal_write_wer( - pred_manifest=output_path, - gt_text_attr_name=asr_metrics_cfg.gt_text_attr_name, - pred_text_attr_name="pred_text", - output_filename=None, - clean_groundtruth_text=asr_metrics_cfg.clean_groundtruth_text, - langid=asr_metrics_cfg.langid, - use_cer=asr_metrics_cfg.use_cer, - ignore_capitalization=asr_metrics_cfg.ignore_capitalization, - ignore_punctuation=asr_metrics_cfg.ignore_punctuation, - ) - if output_manifest_w_wer: - logging.info(f"Writing prediction and error rate of each sample to {output_manifest_w_wer}!") - logging.info(f"{total_res}") - else: - logging.warning( - "WER calculation is skipped because the output manifest does not contain ground truth text." - ) - except Exception as e: - logging.error(f"Error calculating WER: {e}") - - if cfg.calculate_bleu: - if cfg.enable_nmt: - try: - nmt_metrics_cfg = cfg.metrics.nmt - output_manifest_w_bleu, total_res, _ = cal_write_text_metric( - pred_manifest=output_path, - pred_text_attr_name="pred_translation", - gt_text_attr_name=nmt_metrics_cfg.gt_text_attr_name, - output_filename=None, - ignore_capitalization=nmt_metrics_cfg.ignore_capitalization, - ignore_punctuation=nmt_metrics_cfg.ignore_punctuation, - strip_punc_space=nmt_metrics_cfg.strip_punc_space, - ) - if output_manifest_w_bleu: - logging.info(f"Writing prediction and BLEU score of each sample to {output_manifest_w_bleu}!") - logging.info(f"{total_res}") - else: - logging.warning( - "BLEU calculation is skipped because the output manifest does not contain ground truth translation." - ) - except Exception as e: - logging.error(f"Error calculating BLEU score: {e}") - else: - logging.warning("BLEU calculation is skipped because NMT is not enabled.") - - -def calculate_pipeline_laal( - output: dict, durations: dict[str, float], manifest: list[dict], cfg: DictConfig -) -> float | None: - """ - Calculate the LAAL of the pipeline output. - Args: - output: Dictionary containing the pipeline output. - durations: Dictionary containing the duration of each audio file. - manifest: List of dictionaries containing the ground truth translation for each audio file. - cfg: Configuration object. - Returns: - float | None: Length-Adaptive Average Lagging (LAAL) for Simultaneous Speech Translation in milliseconds - """ - - if not cfg.enable_nmt: - logging.warning("LAAL calculation is skipped because NMT is not enabled.") - return None - - if manifest is None: - logging.warning("LAAL calculation is skipped because manifest is not provided.") - return None - - gt_text_attr_name = cfg.metrics.nmt.gt_text_attr_name - ref_translations = {item["audio_filepath"]: item[gt_text_attr_name] for item in manifest} - - laal_list = [] - for stream_id, stream_output in output.items(): - audio_filepath = stream_output["audio_filepath"] - duration = durations[audio_filepath] * 1000 # ms - num_words_in_ref_translation = len(ref_translations[audio_filepath].split()) - translation_segments = stream_output["translation_segments"] - - lagging = [] - for translation, delay in translation_segments: - translation = translation.strip() - if not translation: - continue - cur_words = translation.split() - lag = min(delay * 1000, duration) - lagging.extend([lag] * len(cur_words)) - - if len(lagging) == 0: - lagging.append(0) - - laal = compute_laal(lagging, duration, num_words_in_ref_translation) - laal_list.append(laal) - - return sum(laal_list) / len(laal_list) diff --git a/nemo/collections/asr/inference/utils/pipeline_utils.py b/nemo/collections/asr/inference/utils/pipeline_utils.py deleted file mode 100644 index dcdcaf2f7ab674e49a5e703e68df56a3715d9926..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/utils/pipeline_utils.py +++ /dev/null @@ -1,312 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import re -from functools import partial, wraps -from typing import Iterable - -import torch -from omegaconf import DictConfig, open_dict -from torch import Tensor - -from nemo.collections.asr.inference.utils.constants import BIG_EPSILON, SENTENCEPIECE_UNDERSCORE, SMALL_EPSILON -from nemo.collections.asr.parts.preprocessing.features import normalize_batch -from nemo.collections.asr.parts.utils.asr_confidence_utils import ( - get_confidence_aggregation_bank, - get_confidence_measure_bank, -) -from nemo.collections.common.tokenizers.tokenizer_spec import TokenizerSpec - - -def check_existance_of_required_attributes(obj: object, required_args: list[str]) -> None: - """ - Check if the required attributes exist in the object - Args: - obj: (object) Object to check the attributes of - required_args: (list[str]) List of required attributes - """ - not_found_args = [] - for arg in required_args: - if not hasattr(obj, arg): - not_found_args.append(arg) - if not_found_args: - raise ValueError(f"Required attributes not found: {not_found_args}") - - -def normalize_features(features: Tensor, feature_lens: Tensor = None) -> Tensor: - """Normalize the features. - Args: - features: (Tensor) features. Shape is torch.Size([B, C, T]). - feature_lens: (Tensor) feature lengths. Shape is torch.Size([B]). - Returns: - (Tensor) normalized features. Shape is torch.Size([B, C, T]). - """ - return normalize_batch(features, feature_lens, "per_feature")[0] - - -def ids_to_text_without_stripping(tokens: list[int], tokenizer: TokenizerSpec, sep: str = ' ') -> str: - """ - Convert a list of token IDs to text without stripping. - Args: - tokens: (list[int]) List of token IDs. - tokenizer: (TokenizerSpec) Tokenizer. - sep: (str) Separator between words. Default is ' '. - Returns: - (str) Text. - """ - pieces = tokenizer.ids_to_tokens(tokens) - text = "".join( - [(p.replace(SENTENCEPIECE_UNDERSCORE, sep) if p.startswith(SENTENCEPIECE_UNDERSCORE) else p) for p in pieces] - ) - return text - - -def memoize_normalization_mode(): - """ - Decorator to memoize the normalization mode. - In the first call, the normalization mode is detected and cached. - In the subsequent calls, the cached normalization mode is used. - """ - - def decorator(func): - mode = None # Cache the detected format - - @wraps(func) - def wrapper(log_probs: torch.Tensor) -> torch.Tensor: - nonlocal mode - - if mode is None: - ONE = torch.tensor(1.0, dtype=log_probs.dtype) - if torch.allclose(log_probs[0][0].sum(), ONE, atol=BIG_EPSILON): - # assume that softmax is already applied - mode = 'prob' - else: - if not torch.allclose(log_probs[0][0].exp().sum(), ONE, atol=BIG_EPSILON): - # It's neither prob nor log-softmax, need to apply log_softmax - mode = "logits" - else: - # It's already in log-softmax form - mode = "log_softmax" - - # Fast-path execution - if mode == "prob": - return torch.log(log_probs + SMALL_EPSILON) - elif mode == 'logits': - return torch.log_softmax(log_probs, dim=-1) - else: - return log_probs - - return wrapper - - return decorator - - -@memoize_normalization_mode() -def normalize_log_probs(log_probs: torch.Tensor) -> torch.Tensor: - """ - log_probs: (B, T, vocab_size) log probabilities - Returns: - (Tensor) normalized log probabilities. Shape is torch.Size([B, T, vocab_size]). - """ - # Ensure log_probs are normalized - return log_probs - - -def drop_trailing_features(features: Tensor, expected_feature_buffer_len: int) -> Tensor: - """Drop the trailing features if the number of features is greater than the expected feature buffer length. - Args: - features: (Tensor) features. Shape is torch.Size([B, C, T1]). - expected_feature_buffer_len: (int) Expected feature buffer length. - Returns: - (Tensor) features. Shape is torch.Size([B, C, T2]). - """ - if features.shape[2] > expected_feature_buffer_len: - features = features[:, :, :expected_feature_buffer_len] - return features - - -def make_preprocessor_deterministic(asr_model_cfg: DictConfig, disable_normalization: bool = True) -> DictConfig: - """ - Make the preprocessor deterministic by disabling normalization, dither and padding - Args: - asr_model_cfg: (DictConfig) ASR model configuration. - disable_normalization: (bool) Whether to disable normalization. Default is True. - Returns: - (DictConfig) ASR model configuration with deterministic preprocessor. - """ - # Enable config overwriting - with open_dict(asr_model_cfg): - # Normalization will be done per buffer in frame_bufferer - # Do not normalize whatever the model's preprocessor setting is - asr_model_cfg.preprocessor.dither = 0.0 - asr_model_cfg.preprocessor.pad_to = 0 - - if disable_normalization: - asr_model_cfg.preprocessor.normalize = "None" - - return asr_model_cfg - - -def get_confidence_utils(confidence_cfg: DictConfig) -> tuple: - """ - Get the confidence function and the confidence aggregator - Args: - confidence_cfg: (DictConfig) Confidence configuration. - Returns: - (tuple) Confidence function and the confidence aggregator. - """ - if confidence_cfg.method_cfg.name == "max_prob": - conf_type = "max_prob" - conf_alpha = 1.0 - else: - conf_type = f"entropy_{confidence_cfg.method_cfg.entropy_type}_{confidence_cfg.method_cfg.entropy_norm}" - conf_alpha = confidence_cfg.method_cfg.alpha - - conf_func = get_confidence_measure_bank()[conf_type] - conf_func = partial(conf_func, t=conf_alpha) - confidence_aggregator = get_confidence_aggregation_bank()[confidence_cfg.aggregation] - return conf_func, confidence_aggregator - - -def get_leading_punctuation_regex_pattern(puncts: set[str]) -> str: - """ - Get the regex pattern for the punctuation marks. - Args: - puncts (set[str]): Set of punctuation marks. - Returns: - (str) Regex pattern for the punctuation marks. - """ - if not puncts: - return "" - escaped_puncts = '|'.join(re.escape(punct) for punct in puncts) - return r'\s+(' + escaped_puncts + ')' - - -def get_repeated_punctuation_regex_pattern(puncts: set[str]) -> str: - """ - Get the regex pattern for the repeated punctuation marks. - Args: - puncts (set[str]): Set of punctuation marks. - Returns: - (str) Regex pattern for the repeated punctuation marks. - """ - if not puncts: - return "" - escaped_puncts = ''.join(re.escape(p) for p in puncts) - return r'([' + escaped_puncts + r']){2,}' - - -def update_punctuation_and_language_tokens_timestamps( - tokens: Tensor, timestamp: Tensor, tokens_to_move: set[int], underscore_id: int -) -> Tensor: - """ - RNNT models predict punctuations and language tokens at the end of the sequence. - Due to this, it appears as if there's a silence between the last word and the punctuation. - This function moves the tokens close to preceding word in the list. - Args: - tokens: (Tensor) Tokens tensor. - timestamp: (Tensor) Timestamps tensor. - tokens_to_move: (set[int]) Set of tokens to move. - underscore_id: (int) ID of the underscore token. - Returns: - (Tensor) Updated timestamps tensor. - """ - - n_tokens = tokens.shape[0] - if n_tokens != timestamp.shape[0]: - raise ValueError("Tokens and timestamps must have the same length") - - tokens_to_move_with_underscore = tokens_to_move.union({underscore_id}) - # If all tokens need moving, don't change timestamps (no content words to attach to) - only_special_tokens = all(token.item() in tokens_to_move_with_underscore for token in tokens) - if only_special_tokens: - return timestamp - - groups = [] - i = 0 - while i < n_tokens: - if tokens[i].item() in tokens_to_move_with_underscore: - start_idx = i - end_idx = i - j = i + 1 - while j < n_tokens and (tokens[j].item() in tokens_to_move_with_underscore): - if tokens[j].item() != underscore_id: - end_idx = j - j += 1 - if j > start_idx and end_idx >= start_idx: - left_timestamp = int(timestamp[start_idx - 1]) if start_idx > 0 else 0 - if start_idx == end_idx: - if tokens[start_idx].item() in tokens_to_move: - groups.append((start_idx, end_idx + 1, left_timestamp)) - else: - groups.append((start_idx, end_idx + 1, left_timestamp)) - i = j - else: - i += 1 - - updated_timestamps = timestamp.clone() - for start_idx, end_idx, left_timestamp in groups: - for k in range(start_idx, end_idx): - # Give all tokens_to_move the same timestamp as the preceding word - updated_timestamps[k] = left_timestamp - - return updated_timestamps - - -def adjust_vad_segments(vad_segments: Tensor, left_padding_size: float) -> Tensor | None: - """ - Adjust VAD segments for stateful mode by subtracting left_padding and applying clipping rules. - Args: - vad_segments: (Tensor) VAD segments tensor with shape [num_segments, 2] (start_time, end_time) - left_padding_size: (float) Amount of left padding in seconds to subtract from segments - Returns: - (Tensor | None) Adjusted VAD segments tensor or None if no valid segments are left. - """ - if vad_segments is None or len(vad_segments) == 0: - return vad_segments - - # Vectorized operations on the entire tensor - adjusted_segments = vad_segments - left_padding_size - - # Filter out segments that end before or at 0 - valid_mask = adjusted_segments[:, 1] > 0 - - if not valid_mask.any(): - return None - - adjusted_segments = adjusted_segments[valid_mask] - - # Clip start times to 0 - adjusted_segments[:, 0] = torch.clamp(adjusted_segments[:, 0], min=0.0) - - return adjusted_segments - - -def seconds_to_frames(seconds: float | int | Iterable[float | int], model_stride_in_secs: float) -> int | list[int]: - """ - Convert seconds to frames. - Args: - seconds: (float | int | Iterable[float | int]) Time in seconds - model_stride_in_secs: (float) Stride of the model in seconds - Returns: - (int | list[int]) Number of frames - """ - if isinstance(seconds, (float, int)): - return int(seconds / model_stride_in_secs) - - if isinstance(seconds, Iterable): - return [int(s / model_stride_in_secs) for s in seconds] - - raise ValueError(f"Invalid type for seconds: {type(seconds)}") diff --git a/nemo/collections/asr/inference/utils/progressbar.py b/nemo/collections/asr/inference/utils/progressbar.py deleted file mode 100644 index ef6663bbdaa579b7c660454dedb0f815741f7efb..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/utils/progressbar.py +++ /dev/null @@ -1,100 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from tqdm import tqdm - - -class ProgressBar: - """ - Base class for progress bars. - """ - - def __init__(self, value: float = 0.0, total: float = 1.0): - """ - Initialize the ProgressBar. - Args: - value: (float) Initial value. - total: (float) Total value. Must be greater than zero. - """ - if total <= 0: - raise ValueError("Total must be greater than zero.") - if value < 0 or value > total: - raise ValueError("Initial value must be between 0 and total.") - - self.value = value - self.total = total - self.start_value = value - - def restart(self) -> None: - """Restart progress from the initial value.""" - self.value = self.start_value - - def increment(self, by: float) -> None: - """ - Increase progress but do not exceed total. - Args: - by: (float) Amount to increment. - """ - self.value = min(self.value + by, self.total) - - def update_bar(self, by: float) -> None: - """ - Update progress and call update. - Args: - by: (float) Amount to increment. - """ - self.increment(by) - self.update() - - def finish(self) -> None: - """Complete progress bar.""" - self.value = self.total - self.update(True) - - def update(self, is_end: bool = False) -> None: - """ - Abstract method for updating the progress bar. - Args: - is_end: (bool) Whether the progress bar is at the end. - """ - raise NotImplementedError("Subclasses must implement update method.") - - -class TQDMProgressBar(ProgressBar): - """TQDM progress bar wrapper.""" - - def __init__(self, value: float = 0.0, total: float = 1.0): - """ - Initialize the TQDMProgressBar. - Args: - value: (float) Initial value. - total: (float) Total value. - """ - super().__init__(value, total) - self.bar = tqdm(total=self.total, bar_format='{l_bar}{bar}') - self.prev_value = value - - def update(self, is_end: bool = False) -> None: - """ - Update tqdm progress bar. - Args: - is_end: (bool) Whether the progress bar is at the end. - """ - increment = self.value - self.prev_value - if increment > 0: - self.bar.update(increment) - self.prev_value = self.value - - if is_end: - self.bar.close() diff --git a/nemo/collections/asr/inference/utils/state_management_utils.py b/nemo/collections/asr/inference/utils/state_management_utils.py deleted file mode 100644 index cabec9a9a54dd629d4ab4e03e2dd13d7d7fd7afd..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/utils/state_management_utils.py +++ /dev/null @@ -1,193 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from typing import Callable - -from nemo.collections.asr.inference.utils.constants import POST_WORD_PUNCTUATION, PRE_WORD_PUNCTUATION -from nemo.collections.asr.inference.utils.text_segment import TextSegment, Word - - -def merge_timesteps(timesteps1: list, timesteps2: list) -> list: - """ - Merge two lists of timesteps by preserving the order and ensuring that the timesteps are in increasing order - Args: - timesteps1: (list) The first list of timesteps - timesteps2: (list) The second list of timesteps - Returns: - (list) The merged list of timesteps - """ - # If both lists are empty, return an empty list - if not timesteps1 and not timesteps2: - return [] - - # If timesteps1 is not empty and the first timestep is negative, - # shift all the timesteps by the absolute value of the first timestep - if timesteps1: - if (first := timesteps1[0]) < 0: # Assigns and checks in the same line - for i, t in enumerate(timesteps1): - timesteps1[i] = t - first - - # If timesteps2 is not empty and the first timestep is negative, - # shift all the timesteps by the absolute value of the first timestep - if timesteps2: - if (first := timesteps2[0]) < 0: - for i, t in enumerate(timesteps2): - timesteps2[i] = t - first - - # If the first list is empty, return the second list - if not timesteps1: - return timesteps2 - - # If the second list is empty, return the first list - if not timesteps2: - return timesteps1 - - # If the last timestep of the first list is greater than the first timestep of the second list, - # calculate the gap between the two timesteps and shift all the timesteps of the second list by the gap - if (gap := timesteps2[0] - timesteps1[-1]) <= 0: - return timesteps1 + [t + abs(gap) + 1 for t in timesteps2] - return timesteps1 + timesteps2 - - -def merge_segment_tail( - segment_head: TextSegment, - segment_tail: TextSegment, - conf_aggregator: Callable = None, -) -> TextSegment: - """ - Merge the segment_tail into the segment_head - Args: - segment_head: (TextSegment) The head segment - segment_tail: (TextSegment) The tail segment - conf_aggregator: (Callable) The function to aggregate the confidence - Returns: - (TextSegment) The merged segment - """ - head = segment_head.copy() - - # for models that have built-in punctuation, we need to rm the last punctuation before merging - if head.text and (last_char := head.text[-1]) and last_char in POST_WORD_PUNCTUATION: - head.text = head.text.rstrip(last_char) - - # merge the segment_tail text - head.text += segment_tail.text - - # update the end timestep - head.end = segment_tail.end - - # update the confidence - if conf_aggregator is not None: - head.conf = conf_aggregator([head.conf, segment_tail.conf]) - - return head - - -def merge_word_tail( - word_head: Word, word_tail: Word, pnc_word_head: Word = None, conf_aggregator: Callable = None -) -> tuple[Word, Word]: - """ - Merge the word_tail into the word_head - Args: - word_head: (Word) The head word - word_tail: (Word) The tail word - pnc_word_head: (Word) The head word with punctuation/capitalization - conf_aggregator: (Callable) The function to aggregate the confidence - Returns: - (tuple[Word, Word]) The merged word and the head word with punctuation/capitalization - """ - - head = word_head.copy() - head_text = head.text - - # for models that have built-in punctuation, we need to rm the last punctuation before merging - if head_text and (last_char := head_text[-1]) and last_char in POST_WORD_PUNCTUATION: - head.text = head_text.rstrip(last_char) - - # merge the word_tail text - head.text += word_tail.text - - # update the end timestep - head.end = word_tail.end - - # update the confidence - if conf_aggregator is not None: - head.conf = conf_aggregator([head.conf, word_tail.conf]) - - pnc_head = None - if pnc_word_head is not None: - - last_char = pnc_word_head.text[-1] if pnc_word_head.text else None - first_char = pnc_word_head.text[0] if pnc_word_head.text else None - - pnc_head = head.copy() - - if last_char in POST_WORD_PUNCTUATION: - if pnc_head.text and pnc_head.text[-1] not in POST_WORD_PUNCTUATION: - pnc_head.text = pnc_head.text + last_char - - if first_char in PRE_WORD_PUNCTUATION: - if pnc_head.text and pnc_head.text[0] not in PRE_WORD_PUNCTUATION: - pnc_head.text = first_char + pnc_head.text - - if first_char and first_char.isupper(): - pnc_head.capitalize() - - return head, pnc_head - - -def find_max_overlap(state_tokens: list, new_tokens: list, limit: int) -> int: - """ - Finds the maximum overlap between the state_tokens suffix and the new_tokens prefix - Args: - state_tokens: (list) The list of state tokens - new_tokens: (list) The list of new tokens - limit: (int) The limit on the overlap - Returns: - (int) The maximum overlap within the limit - """ - max_overlap = 0 - for k in range(1, min(len(state_tokens), len(new_tokens), limit) + 1): - if state_tokens[-k:] == new_tokens[:k]: - max_overlap = k - return max_overlap - - -def detect_overlap( - state_tokens: list[int], - state_timesteps: list[float], - new_tokens: list[int], - new_timesteps: list[float], - overlap_search_th: int = 3, - close_in_time_th: float = 2.0, -) -> int: - """ - Detect the overlap between state_tokens and new_tokens - Args: - state_tokens: (list[int]) The list of state tokens - state_timesteps: (list[float]) The list of state timesteps - new_tokens: (list[int]) The list of new tokens - new_timesteps: (list[float]) The list of new timesteps - overlap_search_th: (int) The threshold on the overlap - close_in_time_th: (float) The threshold on the close in time - Returns: - (int) The overlap between the state_tokens and the new_tokens - """ - overlap = 0 - if state_tokens: - overlap = find_max_overlap(state_tokens, new_tokens, overlap_search_th) - if overlap > 0: - close_in_time = (new_timesteps[overlap - 1] - state_timesteps[-overlap]) <= close_in_time_th - overlap = overlap if close_in_time else 0 - return overlap diff --git a/nemo/collections/asr/inference/utils/text_segment.py b/nemo/collections/asr/inference/utils/text_segment.py deleted file mode 100644 index 77bc1c50e5e802b0730c615f82c53c17d95f0cd2..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/inference/utils/text_segment.py +++ /dev/null @@ -1,319 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from functools import lru_cache - -from nemo.collections.asr.inference.utils.constants import DEFAULT_SEMIOTIC_CLASS, SEP_REPLACEABLE_PUNCTUATION - - -@lru_cache(maxsize=5) -def get_translation_table(punct_marks_frozen: frozenset[str], sep: str) -> dict: - """ - Create and cache translation table for text normalization. - - Args: - punct_marks_frozen (frozenset[str]): Frozen set of punctuation marks to process - sep (str): Separator to replace certain punctuation marks - - Returns: - (dict) Translation table for str.translate() - """ - replace_map = {mark: sep if mark in SEP_REPLACEABLE_PUNCTUATION else "" for mark in punct_marks_frozen} - return str.maketrans(replace_map) - - -def normalize_text(text: str, punct_marks: set[str], sep: str) -> str: - """ - Helper to normalize text by removing/replacing punctuation and lowercasing. - - Args: - text (str): Text to normalize - punct_marks (set[str]): Set of punctuation marks to process - sep (str): Separator to replace certain punctuation marks - - Returns: - (str) Normalized text - """ - trans_table = get_translation_table(frozenset(punct_marks), sep) - return text.translate(trans_table).lower() - - -def validate_init_params( - text: str, start: float, end: float, conf: float, semiotic_class: str = None, strict: bool = False -) -> None: - """ - Validate initialization parameters. - Args: - text: (str) Text to validate - start: (float) Start time - end: (float) End time - conf: (float) Confidence score - semiotic_class: (str) Semiotic class - strict: (bool) Whether to strict validation - """ - if not isinstance(text, str): - raise TypeError(f"text must be a string, got {type(text).__name__}") - if not isinstance(start, (int, float)): - raise TypeError(f"start must be numeric, got {type(start).__name__}") - if not isinstance(end, (int, float)): - raise TypeError(f"end must be numeric, got {type(end).__name__}") - if not isinstance(conf, (int, float)): - raise TypeError(f"conf must be numeric, got {type(conf).__name__}") - - if semiotic_class is not None and not isinstance(semiotic_class, str): - raise TypeError(f"semiotic_class must be a string, got {type(semiotic_class).__name__}") - - if strict: - if start >= end: - raise ValueError(f"start time ({start}) must be less than end time ({end})") - if conf < 0 or conf > 1: - raise ValueError(f"confidence ({conf}) must be between 0 and 1") - - -class TextSegment: - """ - Text segment class. - Represents a continuous text segment with a start time, end time, and confidence score. - """ - - __slots__ = ['_text', '_start', '_end', '_conf'] - - def __init__(self, text: str, start: float, end: float, conf: float) -> None: - """ - Initialize a TextSegment instance. - - Args: - text: The content of the text segment - start: Start time in seconds - end: End time in seconds - conf: Confidence score [0.0, 1.0] - Raises: - ValueError: If start >= end or if confidence is negative - TypeError: If text is not a string - """ - validate_init_params(text, start, end, conf, strict=True) - - self._text = text - self._start = start - self._end = end - self._conf = conf - - @property - def text(self) -> str: - """The content of the text segment.""" - return self._text - - @property - def start(self) -> float: - """Start time of the text segment in seconds.""" - return self._start - - @property - def end(self) -> float: - """End time of the text segment in seconds.""" - return self._end - - @property - def duration(self) -> float: - """Duration of the text segment in seconds.""" - return self._end - self._start - - @property - def conf(self) -> float: - """Confidence score of the text segment.""" - return self._conf - - @text.setter - def text(self, value: str) -> None: - """Set the content of the text segment.""" - if not isinstance(value, str): - raise TypeError(f"text must be a string, got {type(value).__name__}") - self._text = value - - @start.setter - def start(self, value: float) -> None: - """Set the start time.""" - if not isinstance(value, (int, float)): - raise TypeError(f"start time must be numeric, got {type(value).__name__}") - self._start = value - - @end.setter - def end(self, value: float) -> None: - """Set the end time.""" - if not isinstance(value, (int, float)): - raise TypeError(f"end must be numeric, got {type(value).__name__}") - self._end = value - - @conf.setter - def conf(self, value: float) -> None: - """Set the confidence score.""" - if not isinstance(value, (int, float)): - raise TypeError(f"conf must be numeric, got {type(value).__name__}") - if value < 0 or value > 1: - raise ValueError(f"confidence ({value}) must be between 0 and 1") - self._conf = value - - def copy(self) -> 'TextSegment': - """ - Create a deep copy of this TextSegment instance. - - Returns: - A new TextSegment instance with identical properties - """ - return TextSegment(text=self.text, start=self.start, end=self.end, conf=self.conf) - - def capitalize(self) -> None: - """Capitalize first letter of the text segment.""" - self._text = self._text.capitalize() - - def with_normalized_text(self, punct_marks: set[str], sep: str = "") -> 'TextSegment': - """ - Create a new TextSegment with normalized text (punctuation removed/replaced and lowercased). - - Args: - punct_marks (set[str]): Set of punctuation marks to process - sep: Separator to replace certain punctuation marks - - Returns: - New TextSegment instance with normalized text - """ - # Return new instance instead of modifying in place - obj_copy = self.copy() - obj_copy._text = normalize_text(self._text, punct_marks, sep) # Direct access - return obj_copy - - def normalize_text_inplace(self, punct_marks: set[str], sep: str = "") -> None: - """ - Normalize text in place (punctuation removed/replaced and lowercased). - - Args: - punct_marks (set[str]): Set of punctuation marks to process - sep (str): Separator to replace certain punctuation marks - - Note: - This method modifies the current instance. Consider using - with_normalized_text() for a functional approach. - """ - self._text = normalize_text(self._text, punct_marks, sep) # Direct access - - def to_dict(self) -> dict: - """ - Convert the TextSegment to a JSON-compatible dictionary. - """ - return { - "text": self.text, - "start": self.start, - "end": self.end, - "conf": self.conf, - } - - -class Word(TextSegment): - """ - Word class. - Represents a word with a text, start time, end time, confidence score, and semiotic class. - """ - - __slots__ = ['_semiotic_class'] - - def __init__( - self, text: str, start: float, end: float, conf: float, semiotic_class: str = DEFAULT_SEMIOTIC_CLASS - ) -> None: - """ - Initialize a Word instance. - - Args: - text: The text content of the word - start: Start time in seconds - end: End time in seconds - conf: Confidence score [0.0, 1.0] - semiotic_class: Semiotic class of the word - - Raises: - ValueError: If start >= end or if confidence is negative - TypeError: If text is not a string - """ - validate_init_params(text, start, end, conf, semiotic_class, strict=True) - super().__init__(text, start, end, conf) - self._semiotic_class = semiotic_class - - @property - def semiotic_class(self) -> str: - """Semiotic class of the word.""" - return self._semiotic_class - - @semiotic_class.setter - def semiotic_class(self, value: str) -> None: - """Set the semiotic class.""" - if not isinstance(value, str): - raise TypeError(f"semiotic_class must be a string, got {type(value).__name__}") - self._semiotic_class = value - - def copy(self) -> 'Word': - """ - Create a deep copy of this Word instance. - - Returns: - A new Word instance with identical properties - """ - return Word(text=self.text, start=self.start, end=self.end, conf=self.conf, semiotic_class=self.semiotic_class) - - def to_dict(self) -> dict: - """ - Convert the Word to a JSON-compatible dictionary. - """ - return super().to_dict() | {"semiotic_class": self.semiotic_class} - - -def join_segments(segments: list[list[TextSegment]], sep: str) -> list[str]: - """ - Join the text segments to form transcriptions. - - Args: - segments (list[list[TextSegment]]): List of text segment sequences to join - sep (str): Separator to use when joining text segments - - Returns: - List of transcriptions, one for each text segment sequence - """ - return [sep.join([s.text for s in items]) for items in segments] - - -def normalize_segments_inplace( - segments: list[TextSegment] | list[list[TextSegment]], punct_marks: set[str], sep: str = ' ' -) -> None: - """ - Normalize text in text segments by removing punctuation and converting to lowercase. - - This function modifies the text segments in-place by calling normalize_text_inplace - on each TextSegment object. It handles both flat lists of text segments and nested lists. - - Args: - segments (list[TextSegment] | list[list[TextSegment]]): List of TextSegment objects or list of lists of TextSegment objects - punct_marks (set[str]): Set of punctuation marks to be processed - sep (str): Separator to replace certain punctuation marks (default: ' ') - - Note: - This function modifies the input text segments in-place. The original text - content of the text segments will be permanently changed. - """ - for item in segments: - if isinstance(item, list): - for segment in item: - segment.normalize_text_inplace(punct_marks, sep) - elif isinstance(item, TextSegment): - item.normalize_text_inplace(punct_marks, sep) - else: - raise ValueError(f"Invalid item type: {type(item)}. Expected `TextSegment` or `List[TextSegment]`.") diff --git a/nemo/collections/asr/losses/__init__.py b/nemo/collections/asr/losses/__init__.py deleted file mode 100644 index d833ce5cd4848130b48e5329c5713e1bad15a887..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/losses/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.asr.losses.angularloss import AngularSoftmaxLoss -from nemo.collections.asr.losses.bce_loss import BCELoss -from nemo.collections.asr.losses.ctc import CTCLoss -from nemo.collections.asr.losses.ssl_losses.contrastive import ContrastiveLoss -from nemo.collections.asr.losses.ssl_losses.ctc import CTCLossForSSL -from nemo.collections.asr.losses.ssl_losses.mlm import MLMLoss, MultiMLMLoss -from nemo.collections.asr.losses.ssl_losses.rnnt import RNNTLossForSSL diff --git a/nemo/collections/asr/losses/angularloss.py b/nemo/collections/asr/losses/angularloss.py deleted file mode 100644 index e2aee9bba6eaa391573acb70be1bfcb53e2940bd..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/losses/angularloss.py +++ /dev/null @@ -1,68 +0,0 @@ -# ! /usr/bin/python -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import torch - -from nemo.core.classes import Loss, Typing, typecheck -from nemo.core.neural_types import LabelsType, LogitsType, LossType, NeuralType - -__all__ = ['AngularSoftmaxLoss'] - - -class AngularSoftmaxLoss(Loss, Typing): - """ - Computes ArcFace Angular softmax angle loss - reference: https://openaccess.thecvf.com/content_CVPR_2019/papers/Deng_ArcFace_Additive_Angular_Margin_Loss_for_Deep_Face_Recognition_CVPR_2019_paper.pdf - args: - scale: scale value for cosine angle - margin: margin value added to cosine angle - """ - - @property - def input_types(self): - """Input types definitions for AnguarLoss. - """ - return { - "logits": NeuralType(('B', 'D'), LogitsType()), - "labels": NeuralType(('B',), LabelsType()), - } - - @property - def output_types(self): - """Output types definitions for AngularLoss. - loss: - NeuralType(None) - """ - return {"loss": NeuralType(elements_type=LossType())} - - def __init__(self, scale=20.0, margin=1.35): - super().__init__() - - self.eps = 1e-7 - self.scale = scale - self.margin = margin - - @typecheck() - def forward(self, logits, labels): - numerator = self.scale * torch.cos( - torch.acos(torch.clamp(torch.diagonal(logits.transpose(0, 1)[labels]), -1.0 + self.eps, 1 - self.eps)) - + self.margin - ) - excl = torch.cat( - [torch.cat((logits[i, :y], logits[i, y + 1 :])).unsqueeze(0) for i, y in enumerate(labels)], dim=0 - ) - denominator = torch.exp(numerator) + torch.sum(torch.exp(self.scale * excl), dim=1) - L = numerator - torch.log(denominator) - return -torch.mean(L) diff --git a/nemo/collections/asr/losses/bce_loss.py b/nemo/collections/asr/losses/bce_loss.py deleted file mode 100644 index 61a7b3b2946bc02979e40d473298395a1912b8d6..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/losses/bce_loss.py +++ /dev/null @@ -1,136 +0,0 @@ -# ! /usr/bin/python -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import torch - -from nemo.core.classes import Loss, Typing, typecheck -from nemo.core.neural_types import LabelsType, LengthsType, LossType, NeuralType, ProbsType - -__all__ = ['BCELoss'] - - -class BCELoss(Loss, Typing): - """ - Computes Binary Cross Entropy (BCE) loss. The BCELoss class expects output from Sigmoid function. - """ - - @property - def input_types(self): - """Input types definitions for AnguarLoss.""" - return { - "probs": NeuralType(('B', 'T', 'C'), ProbsType()), - 'labels': NeuralType(('B', 'T', 'C'), LabelsType()), - "target_lens": NeuralType(('B'), LengthsType()), - } - - @property - def output_types(self): - """ - Output types definitions for binary cross entropy loss. Weights for labels can be set using weight variables. - """ - return {"loss": NeuralType(elements_type=LossType())} - - def __init__( - self, - reduction: str = 'mean', - alpha: float = 1.0, - weight: torch.Tensor = torch.tensor([0.1, 0.9]), - sorted_preds: bool = False, - sorted_loss: bool = False, - class_normalization: bool = False, - ): - """ - A custom loss function that supports class normalization, - weighted binary cross-entropy, and optional sorting. - - Args: - reduction (str): Specifies the reduction to apply to the output, - options are 'mean', 'sum', or 'none'. Default is 'mean'. - alpha (float): Scaling factor for loss (unused in this implementation). Default is 1.0. - weight (torch.Tensor): Class weights for the binary cross-entropy loss. Default is [0.1, 0.9]. - sorted_preds (bool): If True, assumes predictions are sorted. Default is False. - sorted_loss (bool): If True, sorts the loss before reduction. Default is False. - class_normalization (bool): If True, uses 'none' reduction for per-class loss. Default is False. - """ - super().__init__() - self.class_normalization = class_normalization - if class_normalization: - self.reduction = 'none' - else: - self.reduction = 'mean' - self.loss_weight = weight - self.loss_f = torch.nn.BCELoss(reduction=self.reduction) - self.sorted_preds = sorted_preds - self.sorted_loss = sorted_loss - self.eps = 1e-6 - - @typecheck() - def forward(self, probs, labels, target_lens, enable_autocast=False): - """ - Calculate binary cross entropy loss based on probs, labels and target_lens variables. - - Args: - probs (torch.tensor) - Predicted probability value which ranges from 0 to 1. Sigmoid output is expected. - labels (torch.tensor) - Groundtruth label for the predicted samples. - target_lens (torch.tensor): - The actual length of the sequence without zero-padding. - - Returns: - loss (NeuralType) - Binary cross entropy loss value. - """ - probs_list = [probs[k, : target_lens[k], :] for k in range(probs.shape[0])] - targets_list = [labels[k, : target_lens[k], :] for k in range(labels.shape[0])] - probs = torch.cat(probs_list, dim=0) - labels = torch.cat(targets_list, dim=0) - norm_weight = torch.zeros_like(labels).detach().clone() - loss = torch.tensor(0.0).to(labels.device) - - if self.class_normalization in ['class', 'class_binary', 'binary']: - if self.class_normalization in ['class', 'class_binary']: - # Normalize loss by number of classes - norm_weight = 1 / (labels.sum(dim=0) + self.eps) - norm_weight_norm = norm_weight / norm_weight.sum() - norm_weight_norm = torch.clamp(norm_weight_norm, min=0.05, max=1.0) - norm_weight_norm = norm_weight_norm / norm_weight_norm.max() - norm_weight = norm_weight_norm[None, :].expand_as(labels).detach().clone() - else: - norm_weight = torch.ones_like(labels).detach().clone() - - if self.class_normalization in ['binary', 'class_binary']: - binary_weight = torch.ones_like(labels).detach().clone() - one_weight = (labels.sum() / (labels.shape[0] * labels.shape[1])).to(labels.device) - binary_weight[labels == 0] = one_weight - binary_weight[labels == 1] = 1 - one_weight - else: - binary_weight = torch.ones_like(labels).detach().clone() - - elif self.class_normalization == 'none' or not self.class_normalization: - binary_weight = torch.ones_like(labels).detach().clone() - norm_weight = torch.ones_like(labels).detach().clone() - - with torch.cuda.amp.autocast(enabled=enable_autocast): - if self.reduction == 'sum': - loss = self.loss_f(probs, labels) - elif self.reduction == 'mean': - loss = self.loss_f(probs, labels).mean() - elif self.reduction == 'none': - if self.class_normalization in ['class', 'class_binary', 'binary']: - loss = (binary_weight * norm_weight * self.loss_f(probs, labels)).sum() - else: - loss = self.loss_f(probs, labels) - return loss diff --git a/nemo/collections/asr/losses/ctc.py b/nemo/collections/asr/losses/ctc.py deleted file mode 100644 index 8a1f72448893fba9eda61d29b9decf2392d688b0..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/losses/ctc.py +++ /dev/null @@ -1,82 +0,0 @@ -# ! /usr/bin/python -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import torch -from torch import nn - -from nemo.core.classes import Serialization, Typing, typecheck -from nemo.core.neural_types import LabelsType, LengthsType, LogprobsType, LossType, NeuralType - -__all__ = ['CTCLoss'] - - -class CTCLoss(nn.CTCLoss, Serialization, Typing): - @property - def input_types(self): - """Input types definitions for CTCLoss. - """ - return { - "log_probs": NeuralType(('B', 'T', 'D'), LogprobsType()), - "targets": NeuralType(('B', 'T'), LabelsType()), - "input_lengths": NeuralType(tuple('B'), LengthsType()), - "target_lengths": NeuralType(tuple('B'), LengthsType()), - } - - @property - def output_types(self): - """Output types definitions for CTCLoss. - loss: - NeuralType(None) - """ - return {"loss": NeuralType(elements_type=LossType())} - - def __init__(self, num_classes, zero_infinity=False, reduction='mean_batch'): - self._blank = num_classes - # Don't forget to properly call base constructor - if reduction not in ['none', 'mean', 'sum', 'mean_batch', 'mean_volume']: - raise ValueError('`reduction` must be one of [mean, sum, mean_batch, mean_volume]') - - self.config_reduction = reduction - if reduction == 'mean_batch' or reduction == 'mean_volume': - ctc_reduction = 'none' - self._apply_reduction = True - elif reduction in ['sum', 'mean', 'none']: - ctc_reduction = reduction - self._apply_reduction = False - super().__init__(blank=self._blank, reduction=ctc_reduction, zero_infinity=zero_infinity) - - def reduce(self, losses, target_lengths): - if self.config_reduction == 'mean_batch': - losses = losses.mean() # global batch size average - elif self.config_reduction == 'mean_volume': - losses = losses.sum() / target_lengths.sum() # same as above but longer samples weigh more - - return losses - - @typecheck() - def forward(self, log_probs, targets, input_lengths, target_lengths): - # override forward implementation - # custom logic, if necessary - input_lengths = input_lengths.long() - target_lengths = target_lengths.long() - targets = targets.long() - # here we transpose because we expect [B, T, D] while PyTorch assumes [T, B, D] - log_probs = log_probs.transpose(1, 0) - loss = super().forward( - log_probs=log_probs, targets=targets, input_lengths=input_lengths, target_lengths=target_lengths - ) - if self._apply_reduction: - loss = self.reduce(loss, target_lengths) - return loss diff --git a/nemo/collections/asr/losses/rnnt.py b/nemo/collections/asr/losses/rnnt.py deleted file mode 100644 index 894be6319c99f82bd564fa765a50dde312eb3a19..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/losses/rnnt.py +++ /dev/null @@ -1,508 +0,0 @@ -# ! /usr/bin/python -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Copyright 2018-2019, Mingkun Huang -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import inspect -import operator -from dataclasses import dataclass -from typing import Any, Callable, Dict, List, Optional, Set - -import torch -from omegaconf import DictConfig, OmegaConf - -from nemo.collections.asr.losses.rnnt_pytorch import MultiblankRNNTLossPytorch, RNNTLossPytorch, TDTLossPytorch -from nemo.core.classes import Loss, typecheck -from nemo.core.neural_types import LabelsType, LengthsType, LogprobsType, LossType, NeuralType -from nemo.core.utils import numba_utils -from nemo.core.utils.k2_utils import K2_INSTALLATION_MESSAGE -from nemo.core.utils.numba_utils import NUMBA_INSTALLATION_MESSAGE -from nemo.utils import logging, logging_mode, model_utils - -try: - import warprnnt_pytorch as warprnnt - - WARP_RNNT_AVAILABLE = True -except (ImportError, ModuleNotFoundError): - WARP_RNNT_AVAILABLE = False - -try: - from nemo.collections.asr.parts.numba.rnnt_loss import MultiblankRNNTLossNumba, RNNTLossNumba, TDTLossNumba - - NUMBA_RNNT_AVAILABLE = True -except (ImportError, ModuleNotFoundError): - NUMBA_RNNT_AVAILABLE = False - -try: - from nemo.collections.asr.parts.k2.graph_transducer import GraphRnntLoss - from nemo.collections.asr.parts.k2.w_transducer import GraphWTransducerLoss - - K2_AVAILABLE = True -except (ImportError, ModuleNotFoundError): - K2_AVAILABLE = False - -WARP_RNNT_INSTALLATION_MESSAGE = ( - "Could not import `warprnnt_pytorch`.\n" - "Please visit https://github.com/HawkAaron/warp-transducer " - "and follow the steps in the readme to build and install the " - "pytorch bindings for RNNT Loss, or use the provided docker " - "container that supports RNN-T loss." -) - - -@dataclass -class RNNTLossConfig: - loss_name: str - lib_name: str - is_available: bool = False - installation_msg: str = "" - min_version: Optional[str] = None - force_float32: bool = True # default True for now for all losses except graph-based - - -# Resolved list of available RNNT losses -RNNT_LOSS_RESOLVER = { - "warprnnt": RNNTLossConfig( - loss_name="warprnnt", - lib_name="warprnnt_pytorch", - is_available=WARP_RNNT_AVAILABLE, - installation_msg=WARP_RNNT_INSTALLATION_MESSAGE, - force_float32=True, - ), - "warprnnt_numba": RNNTLossConfig( - loss_name="warprnnt_numba", - lib_name="numba", - min_version='0.53.0', - is_available=NUMBA_RNNT_AVAILABLE, - installation_msg=NUMBA_INSTALLATION_MESSAGE, - force_float32=False, # This is only temporarily false, will be dynamically updated during resolution - ), - "pytorch": RNNTLossConfig( - loss_name="pytorch", - lib_name="torch", - min_version='0.0', - is_available=True, - installation_msg="Pure Pytorch implementation of RNN-T loss. Slow and for debugging purposes only.", - force_float32=True, - ), - "multiblank_rnnt": RNNTLossConfig( - loss_name="multiblank_rnnt", - lib_name="numba", - min_version='0.53.0', - is_available=NUMBA_RNNT_AVAILABLE, - installation_msg=NUMBA_INSTALLATION_MESSAGE, - force_float32=True, - ), - "multiblank_rnnt_pytorch": RNNTLossConfig( - loss_name="pytorch", - lib_name="torch", - min_version='0.0', - is_available=True, - installation_msg="Pure Pytorch implementation of Multiblank RNN-T loss. Slow and for debugging purposes only.", - force_float32=True, - ), - "graph_w_transducer": RNNTLossConfig( - loss_name="graph_w_transducer", - lib_name="k2", - is_available=K2_AVAILABLE, - installation_msg=K2_INSTALLATION_MESSAGE, - force_float32=False, - ), - "graph_rnnt": RNNTLossConfig( - loss_name="graph_rnnt", - lib_name="k2", - is_available=K2_AVAILABLE, - installation_msg=K2_INSTALLATION_MESSAGE, - force_float32=False, - ), - "tdt": RNNTLossConfig( - loss_name="tdt", - lib_name="numba", - min_version='0.53.0', - is_available=NUMBA_RNNT_AVAILABLE, - installation_msg=NUMBA_INSTALLATION_MESSAGE, - ), - "tdt_pytorch": RNNTLossConfig( - loss_name="tdt_pytorch", - lib_name="torch", - min_version='0.0', - is_available=True, - installation_msg="Pure Pytorch implementation of TDT loss. Slow and for debugging purposes only.", - ), -} - -RNNT_LOSS_RESOLVER['default'] = RNNT_LOSS_RESOLVER['warprnnt_numba'] - - -def _warn_unused_additional_kwargs(loss_name, kwargs): - if len(kwargs) > 0: - logging.warning( - f"Loss function `{loss_name}` was provided with following additional kwargs,\n" - f"however they were ignored as it is unused.\n" - f"{kwargs}" - ) - - -def _clean_kwargs( - loss_name: str, kwargs: Optional[Dict[str, Any]], init_method: Callable, ignore_params: Optional[Set[str]] = None -) -> Dict[str, Any]: - """ - Cleans kwargs for the given loss function. Warn if there are unused kwargs. - - Args: - loss_name: name of the loss function - kwargs: kwargs to clean - init_method: LossClass.__init__ method - ignore_params: set of argument names for init_method to ignore - - Returns: - only used kwargs for the given `init_method` - """ - if not kwargs: - return {} - init_params = set(inspect.signature(init_method).parameters.keys()) - {"self"} - if ignore_params is not None: - init_params -= ignore_params - unused_kwargs = dict() - used_kwargs = dict() - for key, value in kwargs.items(): - if key not in init_params: - unused_kwargs[key] = value - else: - used_kwargs[key] = value - if len(unused_kwargs) > 0: - _warn_unused_additional_kwargs(loss_name, unused_kwargs) - return used_kwargs - - -def resolve_rnnt_default_loss_name() -> str: - return RNNT_LOSS_RESOLVER['default'].loss_name - - -def resolve_rnnt_loss(loss_name: str, blank_idx: int, loss_kwargs: dict = None) -> torch.nn.Module: - loss_function_names = list(RNNT_LOSS_RESOLVER.keys()) - - if loss_name not in loss_function_names: - raise ValueError( - f"Provided `loss_name` {loss_name} not in list of available RNNT losses \n" f"{loss_function_names}" - ) - - all_available_losses = {name: config for name, config in RNNT_LOSS_RESOLVER.items() if config.is_available} - - loss_config = RNNT_LOSS_RESOLVER[loss_name] # type: RNNTLossConfig - - # Re-raise import error with installation message - if not loss_config.is_available: - msg = ( - f"Installed RNNT losses are : {list(all_available_losses.keys())}.\n" - f"****************************************************************\n" - f"To install the selected loss function, please follow the steps below:\n" - f"{loss_config.installation_msg}" - ) - raise ImportError(msg) - - # Library version check - if loss_config.min_version is not None: - ver_matched, msg = model_utils.check_lib_version( - loss_config.lib_name, checked_version=loss_config.min_version, operator=operator.ge - ) - - if ver_matched is False: - msg = ( - f"{msg}\n" - f"****************************************************************\n" - f"To update the selected loss function, please follow the steps below:\n" - f"{loss_config.installation_msg}" - ) - raise RuntimeError(msg) - - # Resolve loss functions sequentially - loss_kwargs = {} if loss_kwargs is None else loss_kwargs - - if isinstance(loss_kwargs, DictConfig): - loss_kwargs = OmegaConf.to_container(loss_kwargs, resolve=True) - - # Get actual loss name for `default` - if loss_name == 'default': - loss_name = loss_config.loss_name - - """ - Resolve RNNT loss functions - """ - if loss_name == 'warprnnt': - loss_func = warprnnt.RNNTLoss(blank=blank_idx, reduction='none') - _warn_unused_additional_kwargs(loss_name, loss_kwargs) - - elif loss_name == 'warprnnt_numba': - # Update loss config's forced float32 flag if set to None - loss_config.force_float32 = not numba_utils.is_numba_cuda_fp16_supported() - - fastemit_lambda = loss_kwargs.pop('fastemit_lambda', 0.0) - clamp = loss_kwargs.pop('clamp', -1.0) - loss_func = RNNTLossNumba(blank=blank_idx, reduction='none', fastemit_lambda=fastemit_lambda, clamp=clamp) - _warn_unused_additional_kwargs(loss_name, loss_kwargs) - - elif loss_name == 'pytorch': - loss_func = RNNTLossPytorch(blank=blank_idx, reduction='none') - _warn_unused_additional_kwargs(loss_name, loss_kwargs) - - elif loss_name == 'multiblank_rnnt': - fastemit_lambda = loss_kwargs.pop('fastemit_lambda', 0.0) - clamp = loss_kwargs.pop('clamp', -1.0) - big_blank_durations = loss_kwargs.pop('big_blank_durations', None) - sigma = loss_kwargs.pop('sigma', 0.0) - loss_func = MultiblankRNNTLossNumba( - blank=blank_idx, - big_blank_durations=big_blank_durations, - reduction='none', - fastemit_lambda=fastemit_lambda, - clamp=clamp, - sigma=sigma, - ) - _warn_unused_additional_kwargs(loss_name, loss_kwargs) - - elif loss_name == 'multiblank_rnnt_pytorch': - big_blank_durations = loss_kwargs.pop('big_blank_durations', None) - sigma = loss_kwargs.pop('sigma', 0.0) - loss_func = MultiblankRNNTLossPytorch( - blank=blank_idx, big_blank_durations=big_blank_durations, reduction='none', sigma=sigma - ) - _warn_unused_additional_kwargs(loss_name, loss_kwargs) - - elif loss_name == 'tdt': - fastemit_lambda = loss_kwargs.pop('fastemit_lambda', 0.0) - clamp = loss_kwargs.pop('clamp', -1.0) - durations = loss_kwargs.pop('durations', None) - sigma = loss_kwargs.pop('sigma', 0.0) - omega = loss_kwargs.pop('omega', 0.0) - loss_func = TDTLossNumba( - blank=blank_idx, - durations=durations, - reduction='none', - fastemit_lambda=fastemit_lambda, - clamp=clamp, - sigma=sigma, - omega=omega, - ) - _warn_unused_additional_kwargs(loss_name, loss_kwargs) - - elif loss_name == 'tdt_pytorch': - durations = loss_kwargs.pop('durations', None) - sigma = loss_kwargs.pop('sigma', 0.0) - loss_func = TDTLossPytorch(blank=blank_idx, durations=durations, reduction='none', sigma=sigma) - _warn_unused_additional_kwargs(loss_name, loss_kwargs) - - elif loss_name == "graph_rnnt": - loss_kwargs = _clean_kwargs(loss_name, loss_kwargs, GraphRnntLoss.__init__, ignore_params={"blank"}) - loss_func = GraphRnntLoss(blank=blank_idx, **loss_kwargs) - elif loss_name == "graph_w_transducer": - loss_kwargs = _clean_kwargs(loss_name, loss_kwargs, GraphWTransducerLoss.__init__, ignore_params={"blank"}) - loss_func = GraphWTransducerLoss(blank=blank_idx, **loss_kwargs) - else: - raise ValueError( - f"Invalid value of `loss_name`: {loss_name}. Allowed loss names are :" f"{loss_function_names}" - ) - - return loss_func - - -class RNNTLoss(Loss): - @property - def input_types(self): - """Input types definitions for CTCLoss. - """ - return { - "log_probs": NeuralType(('B', 'T', 'T', 'D'), LogprobsType()), - "targets": NeuralType(('B', 'T'), LabelsType()), - "input_lengths": NeuralType(tuple('B'), LengthsType()), - "target_lengths": NeuralType(tuple('B'), LengthsType()), - } - - @property - def output_types(self): - """Output types definitions for CTCLoss. - loss: - NeuralType(None) - """ - return {"loss": NeuralType(elements_type=LossType())} - - def __init__(self, num_classes, reduction: str = 'mean_batch', loss_name: str = "default", loss_kwargs=None): - """ - RNN-T Loss function based on https://github.com/HawkAaron/warp-transducer. - Optionally, can utilize a numba implementation of the same loss without having to compile the loss, - albiet there is a small speed penalty for JIT numba compile. - - Note: - Requires Numba 0.53.0 or later to be installed to use this loss function. - - Losses can be selected via the config, and optionally be passed keyword arguments as follows. - - Examples: - .. code-block:: yaml - - model: # RNNT Model config - ... - loss: - loss_name: "warprnnt_numba" - warprnnt_numba_kwargs: - fastemit_lambda: 0.0 - - Warning: - In the case that GPU memory is exhausted in order to compute RNNTLoss, it might cause - a core dump at the cuda level with the following error message. - - ``` - ... - costs = costs.to(acts.device) - RuntimeError: CUDA error: an illegal memory access was encountered - terminate called after throwing an instance of 'c10::Error' - ``` - - Please kill all remaining python processes after this point, and use a smaller batch size - for train, validation and test sets so that CUDA memory is not exhausted. - - Args: - num_classes: Number of target classes for the joint network to predict. - In all cases (conventional RNNT, multi-blank RNNT, and TDT model), this equals the token-id - for the standard "blank" symbol. In particular, say V is the number of non-blank tokens in - the vocabulary, then in the case of, - standard RNNT: num_classes = V - multiblank RNNT: num_classes = V + number-big-blanks (since we store big-blanks before - standard blank, and the standard blank is the last symbol in the vocab) - TDT: num_classes = V. Note, V here does not include any of the "duration outputs". - - reduction: Type of reduction to perform on loss. Possible values are - `mean_batch`, 'mean_volume`, `mean`, `sum` or None. - `None` will return a torch vector comprising the individual loss values of the batch. - `mean_batch` will average the losses in the batch - `mean` will divide each loss by the target length and then average - `mean_volume` will add up all the losses and divide by sum of target lengths - - loss_name: String that is resolved into an RNNT loss function. Available list of losses - is ininitialized in `RNNT_LOSS_RESOLVER` dictionary. - - loss_kwargs: Optional Dict of (str, value) pairs that are passed to the instantiated loss - function. - """ - super(RNNTLoss, self).__init__() - - if reduction not in [None, 'mean', 'sum', 'mean_batch', 'mean_volume']: - raise ValueError('`reduction` must be one of [mean, sum, mean_batch, mean_volume]') - - self._blank = num_classes - self.reduction = reduction - self._loss = resolve_rnnt_loss(loss_name, blank_idx=self._blank, loss_kwargs=loss_kwargs) - self._force_float32 = RNNT_LOSS_RESOLVER[loss_name].force_float32 - self._fp16_compat_checked = False - - def reduce(self, losses, target_lengths): - - if isinstance(losses, List): - losses = torch.cat(losses, 0) - target_lengths = torch.cat(target_lengths, 0) - - if self.reduction == 'mean_batch': - losses = losses.mean() # global batch size average - elif self.reduction == 'mean': - losses = torch.div(losses, target_lengths).mean() - elif self.reduction == 'sum': - losses = losses.sum() - elif self.reduction == 'mean_volume': - losses = losses.sum() / target_lengths.sum() # same as above but longer samples weigh more - - return losses - - @typecheck() - def forward(self, log_probs, targets, input_lengths, target_lengths): - # Cast to int 64 - targets = targets.long() - input_lengths = input_lengths.long() - target_lengths = target_lengths.long() - - max_logit_len = input_lengths.max() - max_targets_len = target_lengths.max() - - # Force cast joint to float32 - if not self._force_float32 and numba_utils.is_numba_cuda_fp16_supported(): - # Execute the kernel in fp16 - pass - elif self._force_float32 and log_probs.dtype != torch.float32: - # Log just once if fp16 tensor was passed and fp16 Numba CUDA loss could not be used. - if log_probs.dtype == torch.float16 and not self._fp16_compat_checked: - _, reason = numba_utils.is_numba_cuda_fp16_supported(return_reason=True) - logging.warning( - f"Provided RNNT Joint tensor is of dtype {log_probs.dtype}, but RNNT loss could not be calculated " - f"in fp16 due to following reason stated below. Loss will be calculated in fp32. \n\n" - f"{reason}", - mode=logging_mode.ONCE, - ) - self._fp16_compat_checked = True - - # Upcast the activation tensor and compute loss and grads in fp32 - logits_orig = log_probs - log_probs = log_probs.float() - del logits_orig # save memory *before* computing the loss - - # Ensure that shape mismatch does not occur due to padding - # Due to padding and subsequent downsampling, it may be possible that - # max sequence length computed does not match the actual max sequence length - # of the log_probs tensor, therefore we increment the input_lengths by the difference. - # This difference is generally small. - if log_probs.shape[1] != max_logit_len: - log_probs = log_probs.narrow(dim=1, start=0, length=max_logit_len).contiguous() - - # Reduce transcript length to correct alignment if additional padding was applied. - # Transcript: [B, L] -> [B, L']; If L' < L - if not targets.is_contiguous(): - targets = targets.contiguous() - - if targets.shape[1] != max_targets_len: - targets = targets.narrow(dim=1, start=0, length=max_targets_len).contiguous() - - # Temporarily override loss reduction - loss_reduction = self._loss.reduction - self._loss.reduction = None - - # Compute RNNT loss - loss = self._loss(acts=log_probs, labels=targets, act_lens=input_lengths, label_lens=target_lengths) - - # Loss reduction can be dynamic, so reset it after call - self._loss.reduction = loss_reduction - - # reduce here using our own reduction function - if self.reduction is not None: - loss = self.reduce(loss, target_lengths) - - # del new variables that may have been created - del ( - log_probs, - targets, - input_lengths, - target_lengths, - ) - - return loss diff --git a/nemo/collections/asr/losses/rnnt_pytorch.py b/nemo/collections/asr/losses/rnnt_pytorch.py deleted file mode 100644 index c8eee90a2eb5ca571d82ded1ccf02a1585edc0ed..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/losses/rnnt_pytorch.py +++ /dev/null @@ -1,374 +0,0 @@ -# ! /usr/bin/python -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import List - -import torch - -from nemo.core.classes import Loss -from nemo.core.neural_types import LabelsType, LengthsType, LogprobsType, LossType, NeuralType - - -class RNNTLossPytorch(Loss): - @property - def input_types(self): - """Input types definitions for CTCLoss. - """ - return { - "acts": NeuralType(('B', 'T', 'T', 'D'), LogprobsType()), - "labels": NeuralType(('B', 'T'), LabelsType()), - "act_lens": NeuralType(tuple('B'), LengthsType()), - "label_lens": NeuralType(tuple('B'), LengthsType()), - } - - @property - def output_types(self): - """Output types definitions for CTCLoss. - loss: - NeuralType(None) - """ - return {"loss": NeuralType(elements_type=LossType())} - - def __init__(self, blank, reduction): - super().__init__() - self.blank = blank - self.reduction = reduction - - def forward(self, acts, labels, act_lens, label_lens): - # CPU patch for FP16 - if not acts.is_cuda and acts.dtype == torch.float16: - acts = acts.float() - - acts = torch.log_softmax(acts, -1) - - forward_logprob = self.compute_forward_prob(acts, labels, act_lens, label_lens) - losses = -forward_logprob - if self.reduction == 'mean_batch': - losses = losses.mean() # global batch size average - elif self.reduction == 'mean': - losses = torch.div(losses, label_lens).mean() - elif self.reduction == 'sum': - losses = losses.sum() - elif self.reduction == 'mean_volume': - losses = losses.sum() / label_lens.sum() # same as above but longer samples weigh more - - return losses - - def compute_forward_prob(self, acts, labels, act_lens, label_lens): - B, T, U, _ = acts.shape - - log_alpha = torch.zeros(B, T, U) - log_alpha = log_alpha.to(acts.device) - - for t in range(T): - for u in range(U): - if u == 0: - if t == 0: - # this is the base case: (t=0, u=0) with log-alpha = 0. - log_alpha[:, t, u] = 0.0 - else: - # this is case for (t = 0, u > 0), reached by (t, u - 1) - # emitting a blank symbol. - log_alpha[:, t, u] = log_alpha[:, t - 1, u] + acts[:, t - 1, 0, self.blank] - else: - if t == 0: - # in case of (u > 0, t = 0), this is only reached from - # (t, u - 1) with a label emission. - gathered = torch.gather( - acts[:, t, u - 1], dim=1, index=labels[:, u - 1].view(-1, 1).type(torch.int64) - ).reshape(-1) - log_alpha[:, t, u] = log_alpha[:, t, u - 1] + gathered.to(log_alpha.device) - else: - # here both t and u are > 0, this state is reachable - # with two possibilities: (t - 1, u) with a blank emission - # or (t, u - 1) with a label emission. - log_alpha[:, t, u] = torch.logsumexp( - torch.stack( - [ - log_alpha[:, t - 1, u] + acts[:, t - 1, u, self.blank], - log_alpha[:, t, u - 1] - + torch.gather( - acts[:, t, u - 1], dim=1, index=labels[:, u - 1].view(-1, 1).type(torch.int64) - ).reshape(-1), - ] - ), - dim=0, - ) - - log_probs = [] - for b in range(B): - # here we need to add the final blank emission weights. - to_append = ( - log_alpha[b, act_lens[b] - 1, label_lens[b]] + acts[b, act_lens[b] - 1, label_lens[b], self.blank] - ) - log_probs.append(to_append) - log_prob = torch.stack(log_probs) - - return log_prob - - -class TDTLossPytorch(Loss): - """ - Pure Python implementation of TDT loss (https://arxiv.org/pdf/2304.06795.pdf) - """ - - @property - def input_types(self): - """Input types definitions for CTCLoss. - """ - return { - "acts": NeuralType(('B', 'T', 'T', 'D'), LogprobsType()), - "labels": NeuralType(('B', 'T'), LabelsType()), - "act_lens": NeuralType(tuple('B'), LengthsType()), - "label_lens": NeuralType(tuple('B'), LengthsType()), - } - - @property - def output_types(self): - """Output types definitions for CTCLoss. - loss: - NeuralType(None) - """ - return {"loss": NeuralType(elements_type=LossType())} - - def __init__(self, blank: int, durations: List[int] = [], reduction: str = 'sum', sigma: float = 0.0): - super().__init__() - self.blank = blank - self.durations = durations - self.n_durations = len(durations) - self.reduction = reduction - self.sigma = sigma - - def forward(self, acts, labels, act_lens, label_lens): - label_acts = acts[:, :, :, : -self.n_durations] - duration_acts = acts[:, :, :, -self.n_durations :] - - # the - self.sigma here is for logit-undernormalization. Check the paper for details. - label_acts = torch.log_softmax(label_acts, -1) - self.sigma - - duration_acts = torch.log_softmax(duration_acts, -1) - - forward_logprob, _ = self.compute_forward_prob(label_acts, duration_acts, labels, act_lens, label_lens) - losses = -forward_logprob - if self.reduction == 'mean_batch': - losses = losses.mean() # global batch size average - elif self.reduction == 'mean': - losses = torch.div(losses, label_lens).mean() - elif self.reduction == 'sum': - losses = losses.sum() - elif self.reduction == 'mean_volume': - losses = losses.sum() / label_lens.sum() # same as above but longer samples weigh more - - return losses - - def logsumexp(self, a, b): - ret = torch.logsumexp(torch.stack([a, b]), dim=0) - return ret - - def compute_forward_prob(self, acts, duration_acts, labels, act_lens, label_lens): - """This function implements Equation 7 in the TDT paper https://arxiv.org/pdf/2304.06795.pdf, - Simply put, for each alpha(t, u), it sums over the contribution from all incoming blank arcs and non-blank arcs. - """ - B, T, U, _ = acts.shape - - log_alpha = torch.zeros(B, T, U) - log_alpha = log_alpha.cuda() - for b in range(B): - for t in range(T): - for u in range(U): - if u == 0: - if t == 0: - # both t and u are 0, this is the base case for alphas. - log_alpha[b, t, u] = 0.0 - else: - # u = 0 and t != 0: only considers blank emissions. - log_alpha[b, t, u] = -1000.0 - for n, l in enumerate(self.durations): - if ( - t - l >= 0 and l > 0 - ): # checking conditions for blank emission, l has to be at least 1 - tmp = ( - log_alpha[b, t - l, u] - + acts[b, t - l, u, self.blank] - + duration_acts[b, t - l, u, n] - ) - log_alpha[b, t, u] = self.logsumexp(tmp, 1.0 * log_alpha[b, t, u]) - - else: - # u != 0 here, need to consider both blanks and non-blanks. - log_alpha[b, t, u] = -1000.0 - for n, l in enumerate(self.durations): - if t - l >= 0: - if l > 0: # for blank emissions. Need to ensure index is not out-of-bound. - tmp = ( - log_alpha[b, t - l, u] - + acts[b, t - l, u, self.blank] - + duration_acts[b, t - l, u, n] - ) - log_alpha[b, t, u] = self.logsumexp(tmp, 1.0 * log_alpha[b, t, u]) - - # non-blank emissions. - tmp = ( - log_alpha[b, t - l, u - 1] - + acts[b, t - l, u - 1, labels[b, u - 1]] - + duration_acts[b, t - l, u - 1, n] - ) - log_alpha[b, t, u] = self.logsumexp(tmp, 1.0 * log_alpha[b, t, u]) - - log_probs = [] - for b in range(B): - tt = torch.Tensor([-1000.0]).cuda()[0] - - # need to loop over all possible ways that blank with different durations contributes to the final loss. - for n, l in enumerate(self.durations): - if act_lens[b] - l >= 0 and l > 0: - bb = ( - log_alpha[b, act_lens[b] - l, label_lens[b]] - + acts[b, act_lens[b] - l, label_lens[b], self.blank] - + duration_acts[b, act_lens[b] - l, label_lens[b], n] - ) - - tt = self.logsumexp(bb, 1.0 * tt) - - log_probs.append(tt) - - log_prob = torch.stack(log_probs) - - return log_prob, log_alpha - - -class MultiblankRNNTLossPytorch(Loss): - """ - Pure Python implementation of multi-blank transducer loss (https://arxiv.org/pdf/2211.03541.pdf) - """ - - @property - def input_types(self): - """Input types definitions for CTCLoss. - """ - return { - "acts": NeuralType(('B', 'T', 'T', 'D'), LogprobsType()), - "labels": NeuralType(('B', 'T'), LabelsType()), - "act_lens": NeuralType(tuple('B'), LengthsType()), - "label_lens": NeuralType(tuple('B'), LengthsType()), - } - - @property - def output_types(self): - """Output types definitions for CTCLoss. - loss: - NeuralType(None) - """ - return {"loss": NeuralType(elements_type=LossType())} - - def __init__(self, blank, big_blank_durations, reduction: str = "sum", sigma: float = 0.0): - super().__init__() - self.blank = blank - self.big_blank_durations = big_blank_durations - self.reduction = reduction - self.sigma = sigma - - def forward(self, acts, labels, act_lens, label_lens): - acts = torch.log_softmax(acts, -1) - self.sigma - forward_logprob, _ = self.compute_forward_prob(acts, labels, act_lens, label_lens) - - losses = -forward_logprob - if self.reduction == 'mean_batch': - losses = losses.mean() # global batch size average - elif self.reduction == 'mean': - losses = torch.div(losses, label_lens).mean() - elif self.reduction == 'sum': - losses = losses.sum() - elif self.reduction == 'mean_volume': - losses = losses.sum() / label_lens.sum() # same as above but longer samples weigh more - - return losses - - def compute_forward_prob(self, acts, labels, act_lens, label_lens): - B, T, U, _ = acts.shape - - log_alpha = torch.zeros(B, T, U, device=acts.device) - for t in range(T): - for u in range(U): - if u == 0: - if t == 0: - # this is the base case: (t=0, u=0) with log-alpha = 0. - log_alpha[:, t, u] = 0.0 - else: - # this is case for (t = 0, u > 0), reached by (t, u - d) - # emitting a blank symbol of duration d. - log_alpha[:, t, u] = log_alpha[:, t - 1, u] + acts[:, t - 1, 0, self.blank] - for i, d in enumerate(self.big_blank_durations): - if t >= d: - tt = log_alpha[:, t - d, u] + acts[:, t - d, 0, self.blank - 1 - i] - log_alpha[:, t, u] = torch.logsumexp( - torch.stack([1.0 * log_alpha[:, t, u], tt]), dim=0 - ) - - else: - if t == 0: - # in case of (u > 0, t = 0), this is only reached from - # (t, u - 1) with a label emission. - gathered = torch.gather( - acts[:, t, u - 1], dim=1, index=labels[:, u - 1].view(-1, 1).type(torch.int64) - ).reshape(-1) - log_alpha[:, t, u] = log_alpha[:, t, u - 1] + gathered - else: - # here both t and u are > 0, this state is reachable - # with two possibilities: (t - d, u) with emission of - # blank with duration d, or (t, u - 1) with a label emission. - - # first we take care of the standard blank. - log_alpha[:, t, u] = torch.logsumexp( - torch.stack( - [ - log_alpha[:, t - 1, u] + acts[:, t - 1, u, self.blank], - log_alpha[:, t, u - 1] - + torch.gather( - acts[:, t, u - 1], dim=1, index=labels[:, u - 1].view(-1, 1).type(torch.int64) - ).reshape(-1), - ] - ), - dim=0, - ) - - # now we go over all big blanks. They need to be considered if current t >= blank duration d. - for i, d in enumerate(self.big_blank_durations): - if t >= d: - tt = log_alpha[:, t - d, u] + acts[:, t - d, u, self.blank - 1 - i] - log_alpha[:, t, u] = torch.logsumexp( - torch.stack([1.0 * log_alpha[:, t, u], tt]), dim=0 - ) - - log_probs = [] - for b in range(B): - # here we need to add the final blank emission weights, which needs - # to consider all possible blank durations. - to_append = ( - log_alpha[b, act_lens[b] - 1, label_lens[b]] + acts[b, act_lens[b] - 1, label_lens[b], self.blank] - ) - - for i, d in enumerate(self.big_blank_durations): - if act_lens[b] >= d: - tt = ( - log_alpha[b, act_lens[b] - d, label_lens[b]] - + acts[b, act_lens[b] - d, label_lens[b], self.blank - 1 - i] - ) - to_append = torch.logsumexp(torch.stack([1.0 * to_append, tt]), dim=0) - - log_probs.append(to_append) - log_prob = torch.stack(log_probs) - - return log_prob, log_alpha diff --git a/nemo/collections/asr/losses/ssl_losses/__init__.py b/nemo/collections/asr/losses/ssl_losses/__init__.py deleted file mode 100644 index 2497903efb6d87cc21b9f7bdcfe2f68ca7c1043e..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/losses/ssl_losses/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.asr.losses.ssl_losses.contrastive import ContrastiveLoss diff --git a/nemo/collections/asr/losses/ssl_losses/contrastive.py b/nemo/collections/asr/losses/ssl_losses/contrastive.py deleted file mode 100644 index 16a70925ac9b0311901926e2310bb3ba1f7a2dff..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/losses/ssl_losses/contrastive.py +++ /dev/null @@ -1,304 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from math import ceil - -import torch -import torch.nn.functional as F -from torch import nn - -from nemo.core import Loss, typecheck -from nemo.core.neural_types import AcousticEncodedRepresentation, LengthsType, LossType, NeuralType, SpectrogramType - -__all__ = ["ContrastiveLoss"] - - -class ContrastiveLoss(Loss): - @property - def input_types(self): - """Input types definitions for Contrastive.""" - return { - "spectrograms": NeuralType(("B", "D", "T"), SpectrogramType()), - "spec_masks": NeuralType(("B", "D", "T"), SpectrogramType()), - "decoder_outputs": NeuralType(("B", "T", "D"), AcousticEncodedRepresentation()), - "decoder_lengths": NeuralType(tuple('B'), LengthsType(), optional=True), - } - - @property - def output_types(self): - """Output types definitions for Contrastive. - loss: - NeuralType(None) - """ - return {"loss": NeuralType(elements_type=LossType())} - - @property - def needs_labels(self): - return False - - def __init__( - self, - in_dim: int, - proj_dim: int = 128, - combine_time_steps: int = 1, - num_negatives: int = 100, - quantized_targets: bool = False, - codebook_size: int = 320, - prob_ppl_weight: float = 0.1, - logit_temp: float = 0.1, - reduce: str = "sum", - sample_from_same_utterance_only: bool = True, - sample_from_non_masked: bool = False, - sample_from_codebook: bool = False, - group_loss: bool = False, - num_groups: int = 2, - quantizer_temp_start: float = 2, - quantizer_temp_min: float = 0.5, - quantizer_temp_decay: float = 0.999995, - mask_threshold: float = 0.8, - store_ids: bool = True, - reduce_ids: bool = False, - multiplier: float = 16.0, - ): - """ - Loss function representing the contrastive task of identifying the true latent speech representation of - the masked spectrogram steps from a set of sampled distractors. - - Args: - in_dim: Number of spectrogram channels. - proj_dim: Number of channels in the model outputs. - combine_time_steps: How many time steps should be combined into a single representation. - num_negatives: Number of sampled negatives for each target. - quantized_targets: Bool that determines if the targets should be quantized. - codebook_size: Number of vectors in the codebook per group. - prob_ppl_weight: Float multiplier on the perplexity loss for target quantization. - logit_temp: Float temperature for normalizing logits. - reduce: String representing the type of reduction used for cross entropy. - sample_from_same_utterance_only: Bool that determines if negatives should be sampled only from same utterance. - sample_from_non_masked: Bool that determines if negatives should be sampled from non-masked steps of the spectrogram. - sample_from_codebook: Bool that determines if negatives should be sampled from entire codebook. - group_loss: Bool that determines if loss should be computed separately for each group in the quantizer codebook. - num_groups: Number of groups in the quantizer codebook. - quantizer_temp_start: Starting temperature in quantizer. - quantizer_temp_min: Minimum temperature in quantizer. - quantizer_temp_decay: Decay rate of quantizer temperature per global step. - mask_threshold: Float threshold for determining if a time step of the spectrogram is masked based on percent of masked channels. - store_ids: Bool that determines if the quantizer ids will be stored to be potentially used by other losses. - reduce_ids: Bool that determines if we convert any sequence of consecutive equivalent ids to a single occurence of that id. - multiplier: Float multipler on final loss - """ - - super().__init__() - quantizer_temp = (quantizer_temp_start, quantizer_temp_min, quantizer_temp_decay) - self.quantized_targets = quantized_targets - self.num_negatives = num_negatives - self.prob_ppl_weight = prob_ppl_weight - if self.quantized_targets: - quantizer_cfg = { - "_target_": "nemo.collections.asr.parts.submodules.ssl_quantizers.GumbelVectorQuantizer", - "dim": in_dim * combine_time_steps, - "vq_dim": proj_dim, - "num_vars": codebook_size, - "groups": num_groups, - "temp": quantizer_temp, - "combine_groups": True, - "time_first": True, - } - self.quantizer = ContrastiveLoss.from_config_dict(quantizer_cfg) - self.prob_ppl_weight = prob_ppl_weight - self.logit_temp = logit_temp - self.reduce = reduce - self.combine_time_steps = combine_time_steps - self.sample_from_same_utterance_only = sample_from_same_utterance_only - self.sample_from_non_masked = sample_from_non_masked - self.sample_from_codebook = sample_from_codebook - self.group_loss = group_loss - self.mask_threshold = mask_threshold - self.multiplier = multiplier - - self.store_ids = store_ids - self.reduce_ids = reduce_ids - - if not self.quantized_targets: - self.target_proj = nn.Linear(in_dim * combine_time_steps, proj_dim) - - def sample_negatives(self, y, num): - # y - T'xBxC or T'xC - - high = y.shape[0] - neg_idxs = torch.multinomial(torch.ones((num, high), device=y.device), self.num_negatives) - - negs = y[neg_idxs.view(-1)] - negs = negs.view((num, self.num_negatives) + y.shape[1:]) - negs = negs.transpose(0, 1) - # negs - NxT'xBxC or NxT'xC - - return negs, neg_idxs - - @typecheck() - def forward(self, spectrograms, spec_masks, decoder_outputs, decoder_lengths=None): - targets = spectrograms.transpose(-2, -1) - masks = spec_masks.transpose(-2, -1) - # BxTxC - diff = int(ceil(targets.shape[1] / decoder_outputs.shape[1]) * decoder_outputs.shape[1]) - targets.shape[1] - - if diff > 0: - targets = F.pad(targets, (0, 0, 0, diff)) - masks = F.pad(masks, (0, 0, 0, diff)) - - targets = targets.reshape(targets.shape[0], decoder_outputs.shape[1], -1) - masks = masks.reshape(targets.shape[0], decoder_outputs.shape[1], -1) - - if self.quantized_targets: - if self.store_ids: - # store ids for use by other losses - targets, prob_ppl_loss, cur_codebook_temp, self.target_ids = self.quantizer(targets, return_ids=True) - - if self.reduce_ids: - # reduce consecutive equivalent ids to a single occurence - _, indices = torch.unique_consecutive(self.target_ids, return_inverse=True) - indices -= indices.min(dim=1, keepdims=True)[0] - reduced_ids = torch.zeros_like(self.target_ids) - reduced_ids = reduced_ids.scatter_(1, indices, self.target_ids) - reduced_lens = indices.max(dim=-1)[0] + 1 - - self.target_ids = reduced_ids.narrow(1, 0, reduced_lens.max()) - self.target_lengths = reduced_lens - - else: - self.target_lengths = None - - else: - targets, prob_ppl_loss, cur_codebook_temp = self.quantizer(targets) - else: - targets = self.target_proj(targets) - - if self.sample_from_same_utterance_only: - bs = decoder_outputs.shape[0] - masks = masks.mean(-1) > self.mask_threshold - out_masked_only = decoder_outputs[masks] - targets_masked_only = targets[masks] - out_masked_only = out_masked_only.reshape(bs, -1, out_masked_only.shape[-1]) - targets_masked_only = targets_masked_only.reshape(bs, -1, targets_masked_only.shape[-1]) - - # BxT'xC - # number of masked time steps to predict (T') - # -> T'xBxC - - out_masked_only = out_masked_only.transpose(0, 1) - targets_masked_only = targets_masked_only.transpose(0, 1) - # -> T'xBxC - - if self.sample_from_non_masked: - # sample from all steps in utterance - negatives, _ = self.sample_negatives( - targets.transpose(0, 1), - targets_masked_only.size(0), # TxBxC # T' - ) - else: - # only sample from masked steps in utterance - negatives, _ = self.sample_negatives(targets_masked_only, targets_masked_only.size(0)) # T'xBxC # T' - # NxT'xBxC - - out_masked_only = out_masked_only.reshape(-1, out_masked_only.shape[-1]) - targets_masked_only = targets_masked_only.reshape(-1, targets_masked_only.shape[-1]) - negatives = negatives.reshape(self.num_negatives, -1, negatives.shape[-1]) - - # T'BxC and NxT'BxC - - else: - masks = masks.mean(-1) > self.mask_threshold - out_masked_only = decoder_outputs[masks] - targets_masked_only = targets[masks] - - # T'xC - # number of masked time steps to predict (T') - - if self.group_loss: - num_groups = self.quantizer.groups - negatives = self.quantizer.vars.reshape(num_groups, self.quantizer.num_vars, -1) - # GxNx(C//G) - negatives = negatives.transpose(0, 1) - # NxGx(C//G) - negatives = negatives.unsqueeze(1).expand(-1, out_masked_only.shape[0], -1, -1) - # NxT'xGx(C//G) - negatives = negatives.reshape(negatives.shape[0], -1, negatives.shape[-1]) - # NxT'Gx(C//G) - - out_masked_only = out_masked_only.reshape(-1, out_masked_only.shape[-1] // num_groups) - targets_masked_only = targets_masked_only.reshape(-1, targets_masked_only.shape[-1] // num_groups) - # T'Gx(C//G) - elif self.sample_from_codebook: - # sample from the full codebook - negatives = self.quantizer.sample_from_codebook(self.num_negatives, targets_masked_only.size(0)) - elif self.sample_from_non_masked: - # sample from all steps in batch - negatives, _ = self.sample_negatives( - targets.reshape(targets.shape[0] * targets.shape[1], -1), - targets_masked_only.size(0), # BTxC - ) # T' - else: - # only sample from masked steps - negatives, _ = self.sample_negatives(targets_masked_only, targets_masked_only.size(0)) # T'xC # T' - # NxT'xC - - # Calculate similarity between outputs and all targets - similarity_scores = self._calculate_similarity(out_masked_only, negatives, targets_masked_only) - # (1+N)xT' - # cosine similarity of outs with targets + N negatives - - # Create targets of size T - similarity_targets = decoder_outputs.new_zeros(similarity_scores.size(1), dtype=torch.long) - # T' - # targets are 0, since it's the first, followed by N sampled negatives - - # Transpose similarity scores to TxF for loss - similarity_scores = similarity_scores.transpose(0, 1) - # T'x(1+N) - - loss = F.cross_entropy(similarity_scores, similarity_targets, reduction=self.reduce) - - sample_size = similarity_targets.numel() - - if self.prob_ppl_weight != 0 and self.quantized_targets: - prob_ppl_loss = self.prob_ppl_weight * prob_ppl_loss * sample_size - loss += prob_ppl_loss - - if not isinstance(loss, torch.Tensor): - loss = torch.Tensor([0]).to(device=decoder_outputs.device) - - batch_size = spectrograms.shape[0] - loss *= self.multiplier / batch_size - - return loss - - def _calculate_similarity(self, logits, negatives, targets): - neg_is_pos = (targets == negatives).all(-1) - # NxT' - true where the negative is actually the positive - targets = targets.unsqueeze(0) - # 1xT'xC - targets = torch.cat([targets, negatives], dim=0) - # (1+N)xT'XC - logits = torch.cosine_similarity( - logits.float().unsqueeze(0).expand(targets.shape[0], -1, -1), targets.float(), dim=-1 - ).type_as(logits) - # (1+N)xT' - logits /= self.logit_temp - if neg_is_pos.any(): - logits[1:][neg_is_pos] = float("-inf") - return logits - - def set_num_updates(self, num_updates): - if self.quantized_targets: - self.quantizer.set_num_updates(num_updates) diff --git a/nemo/collections/asr/losses/ssl_losses/ctc.py b/nemo/collections/asr/losses/ssl_losses/ctc.py deleted file mode 100644 index e71d60ac4956ecc9a4983dc44d0481963358287d..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/losses/ssl_losses/ctc.py +++ /dev/null @@ -1,57 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.asr.losses import CTCLoss -from nemo.core import Loss, typecheck -from nemo.core.neural_types import LabelsType, LengthsType, LossType, NeuralType, SpectrogramType, VoidType - -__all__ = ["CTCLossForSSL"] - - -class CTCLossForSSL(Loss): - @property - def input_types(self): - """Input types definitions for Contrastive. - """ - return { - "spec_masks": NeuralType(("B", "D", "T"), SpectrogramType()), - "decoder_outputs": NeuralType(("B", "T", "D"), VoidType()), - "targets": NeuralType(('B', 'T'), LabelsType()), - "decoder_lengths": NeuralType(tuple('B'), LengthsType(), optional=True), - "target_lengths": NeuralType(tuple('B'), LengthsType(), optional=True), - } - - @property - def output_types(self): - """Output types definitions for Contrastive. - loss: - NeuralType(None) - """ - return {"loss": NeuralType(elements_type=LossType())} - - @property - def needs_labels(self): - return True - - def __init__(self, num_classes, zero_infinity=True, reduction='mean_batch'): - super().__init__() - self.loss = CTCLoss(num_classes=num_classes, reduction=reduction, zero_infinity=zero_infinity) - - @typecheck() - def forward(self, spec_masks, decoder_outputs, targets, decoder_lengths=None, target_lengths=None): - loss = self.loss( - log_probs=decoder_outputs, targets=targets, input_lengths=decoder_lengths, target_lengths=target_lengths - ) - - return loss diff --git a/nemo/collections/asr/losses/ssl_losses/mlm.py b/nemo/collections/asr/losses/ssl_losses/mlm.py deleted file mode 100644 index 4ed6f580bbb28df80511f998f4943d7fe13047fa..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/losses/ssl_losses/mlm.py +++ /dev/null @@ -1,141 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import torch -import torch.nn.functional as F -from torch import nn - -from nemo.core import Loss, typecheck -from nemo.core.neural_types import LabelsType, LengthsType, LogprobsType, LossType, NeuralType, SpectrogramType - -__all__ = ["MLMLoss"] - - -class MLMLoss(Loss): - @property - def input_types(self): - """Input types definitions for Contrastive.""" - return { - "spec_masks": NeuralType(("B", "D", "T"), SpectrogramType(), optional=True), - "decoder_outputs": NeuralType(("B", "T", "D"), LogprobsType()), - "targets": NeuralType(('B', 'T'), LabelsType()), - "decoder_lengths": NeuralType(tuple('B'), LengthsType(), optional=True), - "target_lengths": NeuralType(tuple('B'), LengthsType(), optional=True), - "masks": NeuralType(("B", "D", "T"), SpectrogramType(), optional=True), - } - - @property - def output_types(self): - """Output types definitions for Contrastive. - loss: - NeuralType(None) - """ - return {"loss": NeuralType(elements_type=LossType())} - - @property - def needs_labels(self): - return True - - def __init__( - self, - combine_time_steps: int = 1, - mask_threshold: float = 0.8, - ): - super().__init__() - self.nll_loss = nn.NLLLoss() - self.combine_time_steps = combine_time_steps - self.mask_threshold = mask_threshold - - @typecheck() - def forward( - self, decoder_outputs, targets, decoder_lengths=None, target_lengths=None, spec_masks=None, masks=None - ): - - if masks is None: - masks = spec_masks - - if masks is None: - masks = torch.ones_like(decoder_outputs, dtype=torch.bool) - else: - # B,D,T -> B,T,D - masks = masks.transpose(1, 2) - - masks = masks.reshape(masks.shape[0], masks.shape[1] // self.combine_time_steps, -1) - masks = masks.mean(-1) > self.mask_threshold - - out_masked_only = decoder_outputs[masks] - targets = F.pad(targets, (0, masks.shape[-1] - targets.shape[-1])) - targets_masked_only = targets[masks] - - loss = self.nll_loss(out_masked_only, targets_masked_only) - loss = torch.mean(loss) - - return loss - - -class MultiMLMLoss(Loss): - """ - Masked language model loss for multiple decoders, where cross-entropy loss is applied separately on each decoder. - This loss can be used with `nemo.collections.asr.modules.ssl_modules.MultiSoftmaxDecoder` to train a model with multiple targets per frame. - Reference: https://arxiv.org/abs/2202.01855 - """ - - @property - def input_types(self): - if self.squeeze_single and self.num_decoders == 1: - decoder_outputs = NeuralType(("B", "T", "C"), LogprobsType()) - targets = NeuralType(('B', 'T'), LabelsType()) - else: - decoder_outputs = NeuralType(("B", "T", "C", "H"), LogprobsType()) - targets = NeuralType(("B", "T", "H"), LabelsType()) - return { - "masks": NeuralType(("B", "D", "T"), SpectrogramType()), - "decoder_outputs": decoder_outputs, - "targets": targets, - "decoder_lengths": NeuralType(tuple('B'), LengthsType(), optional=True), - "target_lengths": NeuralType(tuple('B'), LengthsType(), optional=True), - } - - def __init__( - self, - combine_time_steps: int = 1, - mask_threshold: float = 0.8, - num_decoders: int = 1, - squeeze_single: bool = False, - ): - super().__init__() - self.num_decoders = num_decoders - self.squeeze_single = squeeze_single - self.mlm_loss = MLMLoss(combine_time_steps, mask_threshold) - - @typecheck() - def forward(self, masks, decoder_outputs, targets, decoder_lengths=None, target_lengths=None): - if self.squeeze_single and self.num_decoders == 1: - return self.mlm_loss( - spec_masks=masks, - decoder_outputs=decoder_outputs, - targets=targets, - decoder_lengths=decoder_lengths, - target_lengths=target_lengths, - ) - loss = 0.0 - for i in range(self.num_decoders): - loss += self.mlm_loss( - spec_masks=masks, - decoder_outputs=decoder_outputs[:, :, :, i], - targets=targets[:, :, i], - decoder_lengths=decoder_lengths, - target_lengths=target_lengths, - ) - return loss / self.num_decoders diff --git a/nemo/collections/asr/losses/ssl_losses/rnnt.py b/nemo/collections/asr/losses/ssl_losses/rnnt.py deleted file mode 100644 index 0336063638f747bdc83613c0625a95731d4316aa..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/losses/ssl_losses/rnnt.py +++ /dev/null @@ -1,58 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.asr.losses.rnnt import RNNTLoss -from nemo.core import Loss, typecheck -from nemo.core.neural_types import LabelsType, LengthsType, LogprobsType, LossType, NeuralType, SpectrogramType - -__all__ = ["RNNTLossForSSL"] - - -class RNNTLossForSSL(Loss): - @property - def input_types(self): - """Input types definitions for Contrastive. - """ - return { - "spec_masks": NeuralType(("B", "D", "T"), SpectrogramType()), - "decoder_outputs": NeuralType(('B', 'T', 'T', 'D'), LogprobsType()), - "targets": NeuralType(('B', 'T'), LabelsType()), - "decoder_lengths": NeuralType(tuple('B'), LengthsType(), optional=True), - "target_lengths": NeuralType(tuple('B'), LengthsType(), optional=True), - } - - @property - def output_types(self): - """Output types definitions for Contrastive. - loss: - NeuralType(None) - """ - return {"loss": NeuralType(elements_type=LossType())} - - @property - def needs_labels(self): - return True - - def __init__(self, num_classes): - super().__init__() - self.loss = RNNTLoss(num_classes=num_classes) - - @typecheck() - def forward(self, spec_masks, decoder_outputs, targets, decoder_lengths=None, target_lengths=None): - - loss = self.loss( - log_probs=decoder_outputs, targets=targets, input_lengths=decoder_lengths, target_lengths=target_lengths - ) - - return loss diff --git a/nemo/collections/asr/metrics/__init__.py b/nemo/collections/asr/metrics/__init__.py deleted file mode 100644 index d116dbae5977d469d1883dc943bac772fdca0f43..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/metrics/__init__.py +++ /dev/null @@ -1,23 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.asr.metrics.bleu import BLEU -from nemo.collections.asr.metrics.multitask import MultiTaskMetric -from nemo.collections.asr.metrics.wer import WER - -__all__ = [ - "MultiTaskMetric", - "WER", - "BLEU", -] diff --git a/nemo/collections/asr/metrics/bleu.py b/nemo/collections/asr/metrics/bleu.py deleted file mode 100644 index c99664160eafe68a981dd29bd625e6e8899f9265..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/metrics/bleu.py +++ /dev/null @@ -1,278 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import Literal, Optional, Sequence, TypeAlias, Union - -import torch -from lhotse import CutSet -from lhotse.cut import MixedCut -from torchmetrics.functional.text.bleu import _bleu_score_compute, _bleu_score_update -from torchmetrics.text import SacreBLEUScore - -from nemo.collections.asr.parts.submodules.ctc_decoding import AbstractCTCDecoding -from nemo.collections.asr.parts.submodules.multitask_decoding import AbstractMultiTaskDecoding -from nemo.collections.asr.parts.submodules.rnnt_decoding import AbstractRNNTDecoding -from nemo.utils import logging - -__all__ = ['BLEU'] - -# Keyword to avoid mispelling issues. -BLEU_TOKENIZER = "bleu_tokenizer" - - -def _get_bleu_tokenizers_from_cuts(cuts): - """ - Helper function for multi tokenizer BLEU evaluation. - Looks for `bleu_tokenizer` property to pass to BLEU metric. - """ - - def _get_lang(c): - return c.custom.get(BLEU_TOKENIZER) - - # Dataloader passes multiple types of cuts. Need to diambiguate to access custom. - # TODO: resolve in lhotse backend. - return [_get_lang(c.first_non_padding_cut) if isinstance(c, MixedCut) else _get_lang(c) for c in cuts] - - -def _move_dimension_to_the_front(tensor, dim_index): - all_dims = list(range(tensor.ndim)) - return tensor.permute(*([dim_index] + all_dims[:dim_index] + all_dims[dim_index + 1 :])) - - -class BLEU(SacreBLEUScore): - """ - This metric computes numerator, denominator, hypotheses lengths, and target lengths for Overall Bilingual Evaluation Understudy (BLEU) - between prediction and reference texts. When doing distributed training/evaluation the result of - ``res=BLEU.(predictions, predictions_lengths, targets, target_lengths)`` - calls will be all-reduced between all workers using SUM operations. - - If used with PytorchLightning LightningModule, include bleu_num bleur_den, bleu_pred_len, and bleu_target_len values inside - validation_step results. Then aggregate (sum) then at the end of validation epoch to correctly compute validation BLEUR. - - Example: - def validation_step(self, batch, batch_idx): - ... - bleu_values = self.bleu(predictions, predictions_len, transcript, transcript_len) - self.val_outputs = {'val_loss': loss_value, **bleu_values} - return self.val_outputs - - def on_validation_epoch_end(self): - ... - bleu_num = torch.stack([x['val_bleu_num'] for x in self.val_outputs]).sum() - bleu_denom = torch.stack([x['val_bleu_denom'] for x in self.val_outputs]).sum() - bleu_pred_len = torch.stack([x['val_bleu_pred_len'] for x in self.val_outputs]).sum() - bleu_target_len = torch.stack([x['val_bleu_target_len'] for x in self.val_outputs]).sum() - val_bleu = {"val_bleu": self.bleu._compute_bleu(bleu_pred_len, bleu_target_len, bleu_num, bleu_denom)} - tensorboard_logs.update(val_bleu) - self.val_outputs.clear() # free memory - return {'val_loss': val_loss_mean, 'log': tensorboard_logs} - - Args: - decoding: Decoder instance (CTCDecoding, RNNTDecoding, or MultiTaskDecoding) for converting model outputs to text. - tokenize: Tokenizer name for BLEU evaluation (affects BLEU score based on language/tokenization). - n_gram: Maximum n-gram order for BLEU calculation (default: 4). - lowercase: If True, lowercases all input texts before evaluation. - weights: Optional sequence of float weights for each n-gram order. - smooth: If True, applies smoothing to BLEU calculation. - check_cuts_for_tokenizers: If True, will inspect cuts for a `BLEU_TOKENIZERS` attribute for 'on the fly' changes to tokenizer (see `cuts` argument in `update`). - log_prediction: If True, logs the first reference and prediction in each batch. - batch_dim_index: Index of the batch dimension in input tensors. - dist_sync_on_step: If True, synchronizes metric state across distributed workers on each step. - - Returns: - Dictionary containing BLEU score and component statistics (numerator, denominator, prediction_lengths, target_lengths). - """ - - full_state_update: bool = True - SacreBLEUToken: TypeAlias = Literal[ - "none", "13a", "zh", "intl", "char", "ja-mecab", "ko-mecab", "flores101", "flores200" - ] - - def __init__( - self, - decoding: Union[AbstractCTCDecoding, AbstractRNNTDecoding, AbstractMultiTaskDecoding], - bleu_tokenizer: SacreBLEUToken = "13a", - n_gram: int = 4, - lowercase: bool = False, - weights: Optional[Sequence[float]] = None, - smooth: bool = False, - check_cuts_for_bleu_tokenizers: bool = False, - log_prediction=False, - fold_consecutive=True, - batch_dim_index=0, - dist_sync_on_step=False, - sync_on_compute=True, - **kwargs, - ): - self.log_prediction = log_prediction - self.fold_consecutive = fold_consecutive - self.batch_dim_index = batch_dim_index - - self.decoding = decoding - self._init_decode() - - self.check_cuts = check_cuts_for_bleu_tokenizers - super().__init__( - tokenize=bleu_tokenizer, - n_gram=n_gram, - lowercase=lowercase, - weights=weights, - smooth=smooth, - dist_sync_on_step=dist_sync_on_step, - sync_on_compute=sync_on_compute, - ) - - def update( - self, - predictions: torch.Tensor, - predictions_lengths: torch.Tensor, - targets: torch.Tensor, - targets_lengths: torch.Tensor, - predictions_mask: Optional[torch.Tensor] = None, - input_ids: Optional[torch.Tensor] = None, - cuts: Optional[CutSet] = None, - **kwargs, # To allow easy swapping of metrics without worrying about var alignment. - ): - """ - Updates metric state. - Args: - predictions: an integer torch.Tensor of shape ``[Batch, Time, {Vocabulary}]`` (if ``batch_dim_index == 0``) or - ``[Time, Batch]`` (if ``batch_dim_index == 1``) - predictions_lengths: an integer torch.Tensor of shape ``[Batch]`` - targets: an integer torch.Tensor of shape ``[Batch, Time]`` (if ``batch_dim_index == 0``) or - ``[Time, Batch]`` (if ``batch_dim_index == 1``) - target_lengths: an integer torch.Tensor of shape ``[Batch]`` - predictions_mask: a bool torch.Tensor of shape ``[Batch, Time]`` (if ``batch_dim_index == 0``) or - ``[Time, Batch]`` (if ``batch_dim_index == 1``). Required for MultiTaskDecoding. - input_ids: an int torch.Tensor of shape ``[Batch, Time]`` (if ``batch_dim_index == 0``) or - ``[Time, Batch]`` (if ``batch_dim_index == 1``). Required for MultiTaskDecoding. - cuts: a CutSet of ``length == batch size``. If `self.check_cuts`, inspects each element - for SacreBLEU tokenizer type for corresponding element in batch. If a sequence element is ``None``, - the initial tokenizer type from ``BLEU.__init__`` is used. If ``cuts == None`` then all elements - in batch are tokenized with initial tokenizer type. - """ - tokenizers = None - if self.check_cuts: - assert ( - len(cuts) == targets_lengths.shape[0] - ), f"BLEU metrics configured for multiple tokenizers, but got only '{len(cuts)}' samples for '{targets_lengths.shape[0]}' predictions." - tokenizers = _get_bleu_tokenizers_from_cuts(cuts) - - with torch.no_grad(): - # get predictions - hypotheses = ( - self.decode(predictions, predictions_lengths, predictions_mask, input_ids) - if predictions.numel() > 0 - else [] - ) - - # Get references - if self.batch_dim_index != 0: - targets = _move_dimension_to_the_front(targets, self.batch_dim_index) - targets_cpu_tensor = targets.long().cpu() - tgt_lenths_cpu_tensor = targets_lengths.long().cpu() - for idx, tgt_len in enumerate(tgt_lenths_cpu_tensor): - target = targets_cpu_tensor[idx][:tgt_len].tolist() - reference = self.decoding.decode_ids_to_str(target) - tok = tokenizers[idx] if tokenizers else None # `None` arg uses default tokenizer - - # TODO: the backend implementation of this has a lot of cpu to gpu operations. Should reimplement - # for speedup. - self.preds_len, self.target_len = _bleu_score_update( - [hypotheses[idx].text], - [[reference]], # Nested list as BLEU permits multiple references per prediction. - self.numerator, - self.denominator, - self.preds_len, - self.target_len, - self.n_gram, - self._get_tokenizer(tok), - ) - if hypotheses and self.log_prediction and idx == 0: - logging.info("\n") - logging.info(f"BLEU reference:{reference}") - logging.info(f"BLEU predicted:{hypotheses[idx].text}") - - def compute(self, return_all_metrics=True, prefix=""): - """ - Returns BLEU values and component metrics. - - Args: - return_all_metrics: bool flag. On True, BLEU and composite metrics returned. If False, returns - only BLEU. Default: True. - prefix: str to prepend to metric value keys. - - Returns: - Dict: key-value pairs of BLEU metrics and values. Keys are prepended with prefix flag. - """ - bleu = super().compute() - if return_all_metrics: - return { - f"{prefix}bleu": bleu, - f"{prefix}bleu_pred_len": self.preds_len.detach().float(), - f"{prefix}bleu_target_len": self.target_len.detach().float(), - f"{prefix}bleu_num": self.numerator.detach().float(), - f"{prefix}bleu_denom": self.denominator.detach().float(), - } - return { - f"{prefix}bleu": bleu, - } - - # Adding wrapper to avoid imports and extra variables over the namespace - def _compute_bleu( - self, - predictions_lengths, - targets_lengths, - numerator, - denominator, - ): - return _bleu_score_compute( - predictions_lengths, targets_lengths, numerator, denominator, self.n_gram, self.weights, self.smooth - ) - - # Wrapper for tokenizer access. Uses default if None. - def _get_tokenizer(self, tokenize=None): - if not self.check_cuts or tokenize is None: - return self.tokenizer - elif tokenize not in self.tokenizer._TOKENIZE_FN: - raise KeyError( - f"Sample passed BLEU tokenizer key '{tokenize}' but BLEU config only support '{self.tokenizer._TOKENIZE_FN.keys()}'" - ) - # Lower level function of torchmetric SacreBLEU call. See: - # https://github.com/Lightning-AI/torchmetrics/blob/5b8b757c71d1b0f0f056c0df63e3fd772974e8b0/src/torchmetrics/functional/text/sacre_bleu.py#L166-L168 - tokenizer_fn = getattr(self.tokenizer, self.tokenizer._TOKENIZE_FN[tokenize]) - return lambda line: self.tokenizer._lower(tokenizer_fn(line), self.tokenizer.lowercase).split() - - def _init_decode(self): - self.decode = None - if isinstance(self.decoding, AbstractRNNTDecoding): - # Just preload all potential SacreBLEU tokenizers. - self.decode = lambda predictions, predictions_lengths, predictions_mask, input_ids: self.decoding.rnnt_decoder_predictions_tensor( - encoder_output=predictions, encoded_lengths=predictions_lengths - ) - elif isinstance(self.decoding, AbstractCTCDecoding): - self.decode = lambda predictions, predictions_lengths, predictions_mask, input_ids: self.decoding.ctc_decoder_predictions_tensor( - decoder_outputs=predictions, - decoder_lengths=predictions_lengths, - fold_consecutive=self.fold_consecutive, - ) - elif isinstance(self.decoding, AbstractMultiTaskDecoding): - self.decode = lambda predictions, prediction_lengths, predictions_mask, input_ids: self.decoding.decode_predictions_tensor( - encoder_hidden_states=predictions, - encoder_input_mask=predictions_mask, - decoder_input_ids=input_ids, - return_hypotheses=False, - ) - else: - raise TypeError(f"BLEU metric does not support decoding of type {type(self.decoding)}") diff --git a/nemo/collections/asr/metrics/der.py b/nemo/collections/asr/metrics/der.py deleted file mode 100644 index 1ef968f1b185a0d5b989df65802be82d278aa9ca..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/metrics/der.py +++ /dev/null @@ -1,464 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import itertools -from itertools import permutations -from typing import Dict, List, Optional, Tuple - -import numpy as np -import pandas as pd -import torch -from pyannote.core import Segment, Timeline -from pyannote.metrics.diarization import DiarizationErrorRate - -from nemo.collections.asr.metrics.wer import word_error_rate -from nemo.collections.asr.parts.utils.optimization_utils import linear_sum_assignment -from nemo.utils import logging - -__all__ = [ - 'score_labels', - 'calculate_session_cpWER', - 'calculate_session_cpWER_bruteforce', - 'concat_perm_word_error_rate', -] - - -def get_partial_ref_labels(pred_labels: List[str], ref_labels: List[str]) -> List[str]: - """ - For evaluation of online diarization performance, generate partial reference labels - from the last prediction time. - - Args: - pred_labels (list[str]): list of partial prediction labels - ref_labels (list[str]): list of full reference labels - - Returns: - ref_labels_out (list[str]): list of partial reference labels - """ - # If there is no reference, return empty list - if len(ref_labels) == 0: - return [] - - # If there is no prediction, set the last prediction time to 0 - if len(pred_labels) == 0: - last_pred_time = 0 - else: - # The lastest prediction time in the prediction labels - last_pred_time = max([float(labels.split()[1]) for labels in pred_labels]) - ref_labels_out = [] - for label in ref_labels: - start, end, speaker = label.split() - start, end = float(start), float(end) - # If the current [start, end] interval extends beyond the end of hypothesis time stamps - if start < last_pred_time: - end_time = min(end, last_pred_time) - label = f"{start} {end_time} {speaker}" - ref_labels_out.append(label) - # Other cases where the current [start, end] interval is before the last prediction time - elif end < last_pred_time: - ref_labels_out.append(label) - return ref_labels_out - - -def get_online_DER_stats( - DER: float, - CER: float, - FA: float, - MISS: float, - diar_eval_count: int, - der_stat_dict: Dict[str, float], - deci: int = 3, -) -> Tuple[Dict[str, float], Dict[str, float]]: - """ - For evaluation of online diarization performance, add cumulative, average, and maximum DER/CER. - - Args: - DER (float): Diarization Error Rate from the start to the current point - CER (float): Confusion Error Rate from the start to the current point - FA (float): False Alarm from the start to the current point - MISS (float): Miss rate from the start to the current point - diar_eval_count (int): Number of evaluation sessions - der_stat_dict (dict): Dictionary containing cumulative, average, and maximum DER/CER - deci (int): Number of decimal places to round - - Returns: - der_dict (dict): Dictionary containing DER, CER, FA, and MISS - der_stat_dict (dict): Dictionary containing cumulative, average, and maximum DER/CER - """ - der_dict = { - "DER": round(100 * DER, deci), - "CER": round(100 * CER, deci), - "FA": round(100 * FA, deci), - "MISS": round(100 * MISS, deci), - } - der_stat_dict['cum_DER'] += DER - der_stat_dict['cum_CER'] += CER - der_stat_dict['avg_DER'] = round(100 * der_stat_dict['cum_DER'] / diar_eval_count, deci) - der_stat_dict['avg_CER'] = round(100 * der_stat_dict['cum_CER'] / diar_eval_count, deci) - der_stat_dict['max_DER'] = round(max(der_dict['DER'], der_stat_dict['max_DER']), deci) - der_stat_dict['max_CER'] = round(max(der_dict['CER'], der_stat_dict['max_CER']), deci) - return der_dict, der_stat_dict - - -def uem_timeline_from_file(uem_file, uniq_name=''): - """ - Generate pyannote timeline segments for uem file - - file format - UNIQ_SPEAKER_ID CHANNEL START_TIME END_TIME - """ - timeline = Timeline(uri=uniq_name) - with open(uem_file, 'r') as f: - lines = f.readlines() - for line in lines: - line = line.strip() - _, _, start_time, end_time = line.split() - timeline.add(Segment(float(start_time), float(end_time))) - - return timeline - - -def score_labels( - AUDIO_RTTM_MAP, - all_reference: list, - all_hypothesis: list, - all_uem: List[List[float]] = None, - collar: float = 0.25, - ignore_overlap: bool = True, - verbose: bool = True, -) -> Optional[Tuple[DiarizationErrorRate, Dict]]: - """ - Calculate DER, CER, FA and MISS rate from hypotheses and references. Hypothesis results are - coming from Pyannote-formatted speaker diarization results and References are coming from - Pyannote-formatted RTTM data. - - Args: - AUDIO_RTTM_MAP (dict): Dictionary containing information provided from manifestpath - all_reference (list[uniq_name,Annotation]): reference annotations for score calculation - all_hypothesis (list[uniq_name,Annotation]): hypothesis annotations for score calculation - all_uem (list[list[float]]): List of UEM segments for each audio file. If UEM file is not provided, - it will be read from manifestpath - collar (float): Length of collar (in seconds) for diarization error rate calculation - ignore_overlap (bool): If True, overlapping segments in reference and hypothesis will be ignored - verbose (bool): If True, warning messages will be printed - - Returns: - metric (pyannote.DiarizationErrorRate): Pyannote Diarization Error Rate metric object. - This object contains detailed scores of each audiofile. - mapping (dict): Mapping dict containing the mapping speaker label for each audio input - itemized_errors (tuple): Tuple containing (DER, CER, FA, MISS) for each audio file. - - DER: Diarization Error Rate, which is sum of all three errors, CER + FA + MISS. - - CER: Confusion Error Rate, which is sum of all errors - - FA: False Alarm Rate, which is the number of false alarm segments - - MISS: Missed Detection Rate, which is the number of missed detection segments - - < Caveat > - Unlike md-eval.pl, "no score" collar in pyannote.metrics is the maximum length of - "no score" collar from left to right. Therefore, if 0.25s is applied for "no score" - collar in md-eval.pl, 0.5s should be applied for pyannote.metrics. - """ - metric = None - if len(all_reference) == len(all_hypothesis): - metric = DiarizationErrorRate(collar=2 * collar, skip_overlap=ignore_overlap) - - mapping_dict, correct_spk_count = {}, 0 - for idx, (reference, hypothesis) in enumerate(zip(all_reference, all_hypothesis)): - ref_key, ref_labels = reference - _, hyp_labels = hypothesis - if len(ref_labels.labels()) == len(hyp_labels.labels()): - correct_spk_count += 1 - if verbose and len(ref_labels.labels()) != len(hyp_labels.labels()): - logging.info( - f"Wrong Spk. Count with uniq_id:...{ref_key[-10:]}, " - f"Ref: {len(ref_labels.labels())}, Hyp: {len(hyp_labels.labels())}" - ) - uem_obj = None - if all_uem is not None: - metric(ref_labels, hyp_labels, uem=all_uem[idx], detailed=True) - elif AUDIO_RTTM_MAP[ref_key].get('uem_filepath', None) is not None: - uem_file = AUDIO_RTTM_MAP[ref_key].get('uem_filepath', None) - uem_obj = uem_timeline_from_file(uem_file=uem_file, uniq_name=ref_key) - metric(ref_labels, hyp_labels, uem=uem_obj, detailed=True) - else: - metric(ref_labels, hyp_labels, detailed=True) - mapping_dict[ref_key] = metric.optimal_mapping(ref_labels, hyp_labels) - - spk_count_acc = correct_spk_count / len(all_reference) - DER = abs(metric) - if metric['total'] == 0: - raise ValueError("Total evaluation time is 0. Abort.") - CER = metric['confusion'] / metric['total'] - FA = metric['false alarm'] / metric['total'] - MISS = metric['missed detection'] / metric['total'] - - itemized_errors = (DER, CER, FA, MISS) - - if verbose: - pd.set_option('display.max_rows', None) # Show all rows - pd.set_option('display.max_columns', None) # Show all columns - pd.set_option('display.width', None) # Adjust width to avoid line wrapping - pd.set_option('display.max_colwidth', None) # Show full content of each cell - logging.info(f"\n{metric.report()}") - logging.info( - f"Cumulative Results for collar {collar} sec and ignore_overlap {ignore_overlap}: \n" - f"| FA: {FA:.4f} | MISS: {MISS:.4f} | CER: {CER:.4f} | DER: {DER:.4f} | " - f"Spk. Count Acc. {spk_count_acc:.4f}\n" - ) - - return metric, mapping_dict, itemized_errors - elif verbose: - logging.warning( - "Check if each ground truth RTTMs were present in the provided manifest file. " - "Skipping calculation of Diariazation Error Rate" - ) - return None - - -def evaluate_der(audio_rttm_map_dict, all_reference, all_hypothesis, diar_eval_mode='all'): - """ - Evaluate with a selected diarization evaluation scheme - - AUDIO_RTTM_MAP (dict): - Dictionary containing information provided from manifestpath - all_reference (list[uniq_name,annotation]): - reference annotations for score calculation - all_hypothesis (list[uniq_name,annotation]): - hypothesis annotations for score calculation - diar_eval_mode (str): - Diarization evaluation modes - - diar_eval_mode == "full": - DIHARD challenge style evaluation, the most strict way of evaluating diarization - (collar, ignore_overlap) = (0.0, False) - diar_eval_mode == "fair": - Evaluation setup used in VoxSRC challenge - (collar, ignore_overlap) = (0.25, False) - diar_eval_mode == "forgiving": - Traditional evaluation setup - (collar, ignore_overlap) = (0.25, True) - diar_eval_mode == "all": - Compute all three modes (default) - """ - eval_settings = [] - if diar_eval_mode == "full": - eval_settings = [(0.0, False)] - elif diar_eval_mode == "fair": - eval_settings = [(0.25, False)] - elif diar_eval_mode == "forgiving": - eval_settings = [(0.25, True)] - elif diar_eval_mode == "all": - eval_settings = [(0.0, False), (0.25, False), (0.25, True)] - else: - raise ValueError("`diar_eval_mode` variable contains an unsupported value") - - for collar, ignore_overlap in eval_settings: - diar_score = score_labels( - AUDIO_RTTM_MAP=audio_rttm_map_dict, - all_reference=all_reference, - all_hypothesis=all_hypothesis, - collar=collar, - ignore_overlap=ignore_overlap, - ) - return diar_score - - -def calculate_session_cpWER_bruteforce(spk_hypothesis: List[str], spk_reference: List[str]) -> Tuple[float, str, str]: - """ - Calculate cpWER with actual permutations in brute-force way when LSA algorithm cannot deliver the correct result. - - Args: - spk_hypothesis (list): - List containing the hypothesis transcript for each speaker. A list containing the sequence - of words is assigned for each speaker. - - Example: - >>> spk_hypothesis = ["hey how are you we that's nice", "i'm good yes hi is your sister"] - - spk_reference (list): - List containing the reference transcript for each speaker. A list containing the sequence - of words is assigned for each speaker. - - Example: - >>> spk_reference = ["hi how are you well that's nice", "i'm good yeah how is your sister"] - - Returns: - cpWER (float): - cpWER value for the given session. - min_perm_hyp_trans (str): - Hypothesis transcript containing the permutation that minimizes WER. Words are separated by spaces. - ref_trans (str): - Reference transcript in an arbitrary permutation. Words are separated by spaces. - """ - p_wer_list, permed_hyp_lists = [], [] - ref_word_list = [] - - # Concatenate the hypothesis transcripts into a list - for spk_id, word_list in enumerate(spk_reference): - ref_word_list.append(word_list) - ref_trans = " ".join(ref_word_list) - - # Calculate WER for every permutation - for hyp_word_list in permutations(spk_hypothesis): - hyp_trans = " ".join(hyp_word_list) - permed_hyp_lists.append(hyp_trans) - - # Calculate a WER value of the permuted and concatenated transcripts - p_wer = word_error_rate(hypotheses=[hyp_trans], references=[ref_trans]) - p_wer_list.append(p_wer) - - # Find the lowest WER and its hypothesis transcript - argmin_idx = np.argmin(p_wer_list) - min_perm_hyp_trans = permed_hyp_lists[argmin_idx] - cpWER = p_wer_list[argmin_idx] - return cpWER, min_perm_hyp_trans, ref_trans - - -def calculate_session_cpWER( - spk_hypothesis: List[str], spk_reference: List[str], use_lsa_only: bool = False -) -> Tuple[float, str, str]: - """ - Calculate a session-level concatenated minimum-permutation word error rate (cpWER) value. cpWER is - a scoring method that can evaluate speaker diarization and speech recognition performance at the same time. - cpWER is calculated by going through the following steps. - - 1. Concatenate all utterances of each speaker for both reference and hypothesis files. - 2. Compute the WER between the reference and all possible speaker permutations of the hypothesis. - 3. Pick the lowest WER among them (this is assumed to be the best permutation: `min_perm_hyp_trans`). - - cpWER was proposed in the following article: - CHiME-6 Challenge: Tackling Multispeaker Speech Recognition for Unsegmented Recordings - https://arxiv.org/pdf/2004.09249.pdf - - Implementation: - - Brute force permutation method for calculating cpWER has a time complexity of `O(n!)`. - - To reduce the computational burden, linear sum assignment (LSA) algorithm is applied - (also known as Hungarian algorithm) to find the permutation that leads to the lowest WER. - - In this implementation, instead of calculating all WER values for all permutation of hypotheses, - we only calculate WER values of (estimated number of speakers) x (reference number of speakers) - combinations with `O(n^2)`) time complexity and then select the permutation that yields the lowest - WER based on LSA algorithm. - - LSA algorithm has `O(n^3)` time complexity in the worst case. - - We cannot use LSA algorithm to find the best permutation when there are more hypothesis speakers - than reference speakers. In this case, we use the brute-force permutation method instead. - - Example: - >>> transcript_A = ['a', 'b', 'c', 'd', 'e', 'f'] # 6 speakers - >>> transcript_B = ['a c b d', 'e f'] # 2 speakers - - [case1] hypothesis is transcript_A, reference is transcript_B - [case2] hypothesis is transcript_B, reference is transcript_A - - LSA algorithm based cpWER is: - [case1] 4/6 (4 deletion) - [case2] 2/6 (2 substitution) - brute force permutation based cpWER is: - [case1] 0 - [case2] 2/6 (2 substitution) - - Args: - spk_hypothesis (list): - List containing the hypothesis transcript for each speaker. A list containing the sequence - of words is assigned for each speaker. - - Example: - >>> spk_hypothesis = ["hey how are you we that's nice", "i'm good yes hi is your sister"] - - spk_reference (list): - List containing the reference transcript for each speaker. A list containing the sequence - of words is assigned for each speaker. - - Example: - >>> spk_reference = ["hi how are you well that's nice", "i'm good yeah how is your sister"] - - Returns: - cpWER (float): - cpWER value for the given session. - min_perm_hyp_trans (str): - Hypothesis transcript containing the permutation that minimizes WER. Words are separated by spaces. - ref_trans (str): - Reference transcript in an arbitrary permutation. Words are separated by spaces. - """ - # Get all pairs of (estimated num of spks) x (reference num of spks) combinations - hyp_ref_pair = [spk_hypothesis, spk_reference] - all_pairs = list(itertools.product(*hyp_ref_pair)) - - num_hyp_spks, num_ref_spks = len(spk_hypothesis), len(spk_reference) - - if not use_lsa_only and num_ref_spks < num_hyp_spks: - # Brute force algorithm when there are more speakers in the hypothesis - cpWER, min_perm_hyp_trans, ref_trans = calculate_session_cpWER_bruteforce(spk_hypothesis, spk_reference) - else: - # Calculate WER for each speaker in hypothesis with reference - # There are (number of hyp speakers) x (number of ref speakers) combinations - lsa_wer_list = [] - for spk_hyp_trans, spk_ref_trans in all_pairs: - spk_wer = word_error_rate(hypotheses=[spk_hyp_trans], references=[spk_ref_trans]) - lsa_wer_list.append(spk_wer) - - # Make a cost matrix and calculate a linear sum assignment on the cost matrix. - # Row is hypothesis index and column is reference index - cost_wer = torch.tensor(lsa_wer_list).reshape([len(spk_hypothesis), len(spk_reference)]) - row_hyp_ind, col_ref_ind = linear_sum_assignment(cost_wer) - - # In case where hypothesis has more speakers, add words from residual speakers - hyp_permed = [spk_hypothesis[k] for k in np.argsort(col_ref_ind)] - min_perm_hyp_trans = " ".join(hyp_permed) - - # Concatenate the reference transcripts into a string variable - ref_trans = " ".join(spk_reference) - - # Calculate a WER value from the permutation that yields the lowest WER. - cpWER = word_error_rate(hypotheses=[min_perm_hyp_trans], references=[ref_trans]) - - return cpWER, min_perm_hyp_trans, ref_trans - - -def concat_perm_word_error_rate( - spk_hypotheses: List[List[str]], spk_references: List[List[str]] -) -> Tuple[List[float], List[str], List[str]]: - """ - Launcher function for `calculate_session_cpWER`. Calculate session-level cpWER and average cpWER. - For detailed information about cpWER, see docstrings of `calculate_session_cpWER` function. - - As opposed to `cpWER`, `WER` is the regular WER value where the hypothesis transcript contains - words in temporal order regardless of the speakers. `WER` value can be different from cpWER value, - depending on the speaker diarization results. - - Args: - spk_hypotheses (list): - List containing the lists of speaker-separated hypothesis transcripts. - spk_references (list): - List containing the lists of speaker-separated reference transcripts. - - Returns: - cpWER (float): - List containing cpWER values for each session - min_perm_hyp_trans (list): - List containing transcripts that lead to the minimum WER in string format - ref_trans (list): - List containing concatenated reference transcripts - """ - if len(spk_hypotheses) != len(spk_references): - raise ValueError( - "In concatenated-minimum permutation word error rate calculation, " - "hypotheses and reference lists must have the same number of elements. But got arguments:" - f"{len(spk_hypotheses)} and {len(spk_references)} correspondingly" - ) - cpWER_values, hyps_spk, refs_spk = [], [], [] - for spk_hypothesis, spk_reference in zip(spk_hypotheses, spk_references): - cpWER, min_hypothesis, concat_reference = calculate_session_cpWER(spk_hypothesis, spk_reference) - cpWER_values.append(cpWER) - hyps_spk.append(min_hypothesis) - refs_spk.append(concat_reference) - return cpWER_values, hyps_spk, refs_spk diff --git a/nemo/collections/asr/metrics/multi_binary_acc.py b/nemo/collections/asr/metrics/multi_binary_acc.py deleted file mode 100644 index f134bdbd89a1647e26f2e3b939fa521930b69bbc..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/metrics/multi_binary_acc.py +++ /dev/null @@ -1,138 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import logging - -import torch -from torchmetrics import Metric - -__all__ = ['MultiBinaryAccuracy'] - - -class MultiBinaryAccuracy(Metric): - """ - This metric computes accuracies that are needed to evaluate multiple binary outputs. - For example, if a model returns a set of multiple sigmoid outputs per each sample or at each time step, - F1 score can be calculated to monitor Type 1 error and Type 2 error together. - - Example: - def validation_step(self, batch, batch_idx): - ... - signals, signal_lengths, targets = batch - preds, _ = self.forward(input_signal=signals, - signal_lengths=signal_lengths, - targets=targets) - loss = self.loss(logits=preds, labels=targets) - self._accuracy_valid(preds, targets, signal_lengths) - f1_acc = self._accuracy.compute() - self.val_outputs = {'val_loss': loss, 'val_f1_acc': f1_acc} - return self.val_outputs - - def on_validation_epoch_end(self): - ... - val_loss_mean = torch.stack([x['val_loss'] for x in self.val_outputs]).mean() - correct_counts = torch.stack([x['val_correct_counts'] for x in self.val_outputs]).sum(axis=0) - total_counts = torch.stack([x['val_total_counts'] for x in self.val_outputs]).sum(axis=0) - - self._accuracy_valid.correct_counts_k = correct_counts - self._accuracy_valid.total_counts_k = total_counts - f1_acc = self._accuracy_valid.compute() - self._accuracy_valid.reset() - - self.log('val_loss', val_loss_mean) - self.log('val_f1_acc', f1_acc) - self.val_outputs.clear() # free memory - return {'val_loss': val_loss_mean, 'val_f1_acc': f1_acc} - - Args: - preds (torch.Tensor): - Predicted values which should be in range of [0, 1]. - targets (torch.Tensor): - Target values which should be in range of [0, 1]. - signal_lengths (torch.Tensor): - Length of each sequence in the batch input. signal_lengths values are used to - filter out zero-padded parts in each sequence. - - Returns: - f1_score (torch.Tensor): - F1 score calculated from the predicted value and binarized target values. - """ - - full_state_update = False - - def __init__(self, dist_sync_on_step=False): - super().__init__(dist_sync_on_step=dist_sync_on_step) - self.add_state("total_correct_counts", default=torch.tensor(0), dist_reduce_fx='sum', persistent=False) - self.add_state("total_sample_counts", default=torch.tensor(0), dist_reduce_fx='sum', persistent=False) - self.add_state("true_positive_count", default=torch.tensor(0), dist_reduce_fx='sum', persistent=False) - self.add_state("false_positive_count", default=torch.tensor(0), dist_reduce_fx='sum', persistent=False) - self.add_state("false_negative_count", default=torch.tensor(0), dist_reduce_fx='sum', persistent=False) - self.add_state("positive_count", default=torch.tensor(0), dist_reduce_fx='sum', persistent=False) - self.eps = 1e-6 - - @torch.inference_mode() - def update( - self, preds: torch.Tensor, targets: torch.Tensor, signal_lengths: torch.Tensor, cumulative=False, **kwargs - ) -> torch.Tensor: - """ - Update the metric with the given predictions, targets, and signal lengths to the metric instance. - - Args: - preds (torch.Tensor): Predicted values. - targets (torch.Tensor): Target values. - signal_lengths (torch.Tensor): Length of each sequence in the batch input. - cumulative (bool): Whether to accumulate the values over time. - """ - preds_list = [preds[k, : signal_lengths[k], :] for k in range(preds.shape[0])] - targets_list = [targets[k, : signal_lengths[k], :] for k in range(targets.shape[0])] - self.preds = torch.cat(preds_list, dim=0) - self.targets = torch.cat(targets_list, dim=0) - - self.true = self.preds.round().bool() == self.targets.round().bool() - self.false = self.preds.round().bool() != self.targets.round().bool() - self.positive = self.preds.round().bool() == 1 - self.negative = self.preds.round().bool() == 0 - - if cumulative: - self.positive_count += torch.sum(self.preds.round().bool() == True) - self.true_positive_count += torch.sum(torch.logical_and(self.true, self.positive)) - self.false_positive_count += torch.sum(torch.logical_and(self.false, self.positive)) - self.false_negative_count += torch.sum(torch.logical_and(self.false, self.negative)) - self.total_correct_counts += torch.sum(self.preds.round().bool() == self.targets.round().bool()) - self.total_sample_counts += torch.prod(torch.tensor(self.targets.shape)) - else: - self.positive_count = torch.sum(self.preds.round().bool() == True) - self.true_positive_count = torch.sum(torch.logical_and(self.true, self.positive)) - self.false_positive_count = torch.sum(torch.logical_and(self.false, self.positive)) - self.false_negative_count = torch.sum(torch.logical_and(self.false, self.negative)) - self.total_correct_counts = torch.sum(self.preds.round().bool() == self.targets.round().bool()) - self.total_sample_counts = torch.prod(torch.tensor(self.targets.shape)) - - def compute(self): - """ - Compute F1 score from the accumulated values. Return -1 if the F1 score is NaN. - - Returns: - f1_score (torch.Tensor): F1 score calculated from the accumulated values. - precision (torch.Tensor): Precision calculated from the accumulated values. - recall (torch.Tensor): Recall calculated from the accumulated values. - """ - precision = self.true_positive_count / (self.true_positive_count + self.false_positive_count + self.eps) - recall = self.true_positive_count / (self.true_positive_count + self.false_negative_count + self.eps) - f1_score = (2 * precision * recall / (precision + recall + self.eps)).detach().clone() - - if torch.isnan(f1_score): - logging.warning("self.f1_score contains NaN value. Returning -1 instead of NaN value.") - f1_score = -1 - return f1_score.float(), precision.float(), recall.float() diff --git a/nemo/collections/asr/metrics/multitask.py b/nemo/collections/asr/metrics/multitask.py deleted file mode 100644 index 1c10e26de90d21434a4937481b1194e29617e7de..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/metrics/multitask.py +++ /dev/null @@ -1,423 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import operator -from collections import defaultdict -from functools import partial -from typing import List, Optional - -import regex as re -import torch -from lhotse import CutSet -from lhotse.cut import MixedCut -from omegaconf import DictConfig, OmegaConf -from torch import nn - -from nemo.collections.asr.data.audio_to_text_lhotse_prompted import PromptedAudioToTextMiniBatch -from nemo.collections.asr.metrics.wer import WER -from nemo.core.classes import Serialization - -__all__ = ['MultiTaskMetric'] - - -# Helper functions for managing constraint criteria on metrics. -class ConstraintParser: - """Boolean Parser class for constraint passing in config""" - - _primitives = None - _booleans = None - - def parse_constraint(self, constraint: str): - array = re.sub(r"([()])", r" \1 ", constraint).strip().split() # Add space only for keywords. - if not array: - return self._no_constraint - - self._resolve_primitives(array) - if len(array) == 1: - return array[0] - - # Basic nested list parser. Starts from tail to aid readibility in subfunction. - stack = [] - array = ["("] + array + [")"] - while array: - if (c := array.pop()) == "(": - expr = [] - while stack: - if (e := stack.pop()) == ")": - if not (fnc := self._resolve_bools(expr)): - raise SyntaxError(f"Malformed subexpression find in constraint parsing: {fnc}") - stack.append(fnc) - break - expr.append(e) - else: - stack.append(c) - if not (fnc := self._resolve_bools(stack)): - raise SyntaxError(f"Parser cannot resolve constraint: {constraint}") - return fnc - - @property - def primitives(self): - if self._primitives is None: - self._primitives = { - "==": operator.eq, - "!=": operator.ne, - } - return self._primitives - - @property - def booleans(self): - if self._booleans is None: - self._booleans = { - "and": self._logical_and, - "or": self._logical_or, - "xor": self._logical_xor, - } - return self._booleans - - @staticmethod - def _logical_not(expr, properties): - if not expr: - raise ValueError(f"Malformed subexpression find in 'not' constraint parsing: {expr}") - return not expr(properties) - - @staticmethod - def _logical_and(l_expr, r_expr, properties): - if not (l_expr and r_expr): - raise ValueError(f"Malformed subexpression find in 'and' constraint parsing: {l_expr} and {r_expr}") - return l_expr(properties) and r_expr(properties) - - @staticmethod - def _logical_or(l_expr, r_expr, properties): - if not (l_expr and r_expr): - raise ValueError(f"Malformed subexpression find in 'or' constraint parsing: {l_expr} or {r_expr}") - return l_expr(properties) or r_expr(properties) - - @staticmethod - def _logical_xor(l_expr, r_expr, properties): - if not (l_expr and r_expr): - raise ValueError(f"Malformed subexpression find in 'xor' constraint parsing: {l_expr} xor {r_expr}") - return l_expr(properties) ^ r_expr(properties) - - @staticmethod - def _no_constraint(properties): - return True - - @staticmethod - def _static_constraint(fnc, key, val, properties): - return fnc(val, properties.get(key)) - - @staticmethod - def _compare_constraint(fnc, key1, key2, properties): - return ( - (prop_val1 := properties.get(key1)) is not None - and (prop_val2 := properties.get(key2)) is not None - and fnc(prop_val1, prop_val2) - ) - - def _resolve_primitives(self, constraint): - for idx, c in enumerate(constraint): - for n, o in self.primitives.items(): - # Check if string is for value assertion or equivalency of values. - entail, equal = fr'\.(\S+)\s*{n}\s*(\S+)', fr'\.(\S+)\s*{n}\s*\.(\S+)' - match_entail, match_equal = re.match(entail, c), re.match(equal, c) - if match_equal: - key1, key2 = match_equal.groups() - constraint[idx] = partial(self._compare_constraint, o, key1, key2) - elif match_entail: - key1, val = match_entail.groups() - constraint[idx] = partial(self._static_constraint, o, key1, val) - else: - pass - - def _resolve_bools(self, constraint: List[str]): - idx = 0 - stack = [] - while idx < len(constraint): - c = constraint[idx] - if c == "not": - c = partial(self._logical_not, constraint[idx + 1]) - idx += 1 # Skip so don't see the character again. - stack.append(c) - idx += 1 - - constraint = stack - for n, o in self.booleans.items(): - idx = 0 - stack = [] - while idx < len(constraint): - c = constraint[idx] - if c == n: - c = partial(o, stack.pop(), constraint[idx + 1]) - idx += 1 - stack.append(c) - idx += 1 - constraint = stack - if len(constraint) > 1: # More than one constraint, something went wrong. - return None - - return constraint[0] - - -class MultiTaskMetric(Serialization): - """ - Wrapper class for managing multiple metrics in multitask ASR/NLP models. - - This class enables conditional metric computation based on sample properties stored in Lhotse cuts. - It's primarily designed for `EncDecMultiTaskModel` but can support any model with a prompt schema. - - Key Features: - 1. **Automatic Model Integration**: Instantiated metrics are automatically added as attributes - to the parent model, enabling seamless integration with existing logging infrastructure. - - 2. **Conditional Metric Updates**: Only samples meeting specific constraints are passed to - each metric, avoiding inappropriate metric calculations (e.g., WER for translation tasks). - - 3. **Flexible Constraint System**: Supports complex logical expressions for determining - when metrics should be applied to samples. - - 4. **Configuration Inheritance**: Global configuration parameters are automatically - inherited by all metrics unless explicitly overridden. - - Args: - model (nn.Module): Parent model that will receive metric instances as attributes. - Must have a `decoding` attribute for metrics that require decoding. - cfg (DictConfig): Configuration dictionary containing metric definitions and constraints. - - Configuration Format: - The configuration should follow this structure: - - ``' - # Global parameters (inherited by all metrics unless overridden) - log_predictions: true - batch_dim_index: 0 - - # Metric definitions - metrics: - wer: - _target_: nemo.collections.asr.metrics.WER # Metric class to instantiate - constraint: ".task == transcribe" # When to apply this metric - use_cer: false # Metric-specific parameters - bleu: - _target_: nemo.collections.asr.metrics.BLEU - constraint: ".task == translate" - bleu_tokenizer: "13a" - n_gram: 4 - - ``` - - Constraint Syntax: - Constraints are evaluated against the `custom` dictionary of Lhotse cuts: - - - **Custom attribute Access**: `.task`, `.lang`, `.domain` - - **Comparisons**: `==`, `!=` - - **Logical Operations**: `and`, `or`, `not`, `xor` - - **Property Comparisons**: `.source_lang == .target_lang` - - Examples: - - `".task == transcribe"` - Apply to transcription tasks - - `".task == translate and .source_lang != .target_lang"` - Cross-lingual translation - - `"not .task == other"` - Apply to all tasks except 'other' - - `".domain == medical or .domain == legal"` - Specific domains - - Usage Example: - ```python - # In model initialization - if hasattr(cfg, 'multitask_metrics'): - self.multitask_metrics = MultiTaskMetric(self, cfg.multitask_metrics) - - # During training/validation - if hasattr(self, 'multitask_metrics'): - metrics = self.multitask_metrics.eval( - batch=batch, - predictions=predictions, - predictions_lengths=pred_lengths, - predictions_mask=pred_mask, - prefix="val", - return_all_metrics=True - ) - self.log_dict(metrics) - ``` - - Note: - - Each metric receives the model's `decoding` instance for text decoding operations - - Metrics are automatically instantiated for the parent model as attributes (e.g., `model.wer`, `model.bleu`) - - Global configuration parameters are inherited unless explicitly overridden per metric - - Metrics defined without 'constraint' keyword are called on every prediction sample - - Empty batches (no samples matching constraints) are handled by child metrics. - """ - - def __init__(self, model: nn.Module, cfg: DictConfig): - """ - Initialize MultiTaskMetric with model and configuration. - - Args: - model (nn.Module): Parent model that will contain metric instances - cfg (DictConfig): Configuration containing metric definitions - """ - super().__init__() - - # Setup tracking dictionaries - self._metric_dict, self._constr_dict = {}, {} - cfg = OmegaConf.to_container(cfg) - - # Process each metric instance. - parser = ConstraintParser() - seen_types = set() - for name, metric_cfg in cfg.pop("metrics").items(): - constraint = metric_cfg.pop( - "constraint", "" - ) # Empty string for no constraint value. Metric always calculated. - - # Inherit global configuration parameters - for k, v in cfg.items(): - if k not in metric_cfg: # do not override explicit metric values - metric_cfg[k] = v - - # Instantiates as instance of `model`. Avoids breaking behavior when other modules call specific metrics. (See `asr_model` for example.) - metric_cfg["decoding"] = model.decoding # For decoding reliant metrics like 'WER' or 'BLEU' - metric = MultiTaskMetric.from_config_dict(metric_cfg) - setattr(model, name, metric) - - # TODO: This is a from `asr_model` aggregation. To fix, update metric classes to support custom naming - # and update `asr_model` `multi_{validation,test}_epoch_end` to support metric aggregation with custom names. - metric_type = type(metric) - if metric_type in seen_types: - raise TypeError( - "MultiTaskMetric currently only supports one instance of each metric class. Please check your configs for duplicates values of `_target_` entry." - ) - seen_types.add(metric_type) - - # Store metric and its constraint function - self._metric_dict[name] = metric - self._constr_dict[name] = parser.parse_constraint(constraint) - - # Performs full PyMetrics validation loop for all metrics. - def eval( - self, - batch: PromptedAudioToTextMiniBatch, - predictions: torch.Tensor, - predictions_lengths: torch.Tensor, - predictions_mask: torch.Tensor, - return_all_metrics: Optional[bool] = False, - prefix: Optional[str] = None, - ): - metric_dict = {} - self.update( - predictions=predictions, - predictions_lengths=predictions_lengths, - targets=batch.transcript, - targets_lengths=batch.transcript_lens, - predictions_mask=predictions_mask, - input_ids=getattr(batch, "prompt", None), # Allows for CTC and RNN-T support. - cuts=batch.cuts, - ) - metric_dict.update( - self.compute( - prefix=f"{prefix}_" if prefix else "", - return_all_metrics=return_all_metrics, - ) - ) - self.reset() - return metric_dict - - def update( - self, - predictions: torch.Tensor, - predictions_lengths: torch.Tensor, - predictions_mask: torch.Tensor, - targets: torch.Tensor, - targets_lengths: torch.Tensor, - input_ids: torch.Tensor, - cuts: CutSet, - ): - - # Update each metric with its filtered data - cuts_split, idx_split = self._split_cuts(cuts) - for name, metric in self._metric_dict.items(): - cuts_subset, indices = cuts_split[name], idx_split[name] - # Update metric with filtered tensors - metric.update( - predictions=predictions[indices], - predictions_lengths=predictions_lengths[indices], - predictions_mask=predictions_mask[indices], - targets=targets[indices], - targets_lengths=targets_lengths[indices], - input_ids=input_ids[indices], - cuts=cuts_subset, - ) - - def compute(self, return_all_metrics=False, prefix=""): - output_dict = {} - - for name, metric in self._metric_dict.items(): - # Handle WER metric's special return format - # Custom name of metric used as suffix to allow custom naming. - # TODO: Standardize WER to return dict like other metrics - if type(metric) is WER: - wer, wer_num, wer_denom = metric.compute() - if return_all_metrics: - output_dict.update( - { - f"{prefix}wer": wer, - f"{prefix}wer_num": wer_num, - f"{prefix}wer_denom": wer_denom, - } - ) - else: - output_dict.update( - { - f"{prefix}wer": wer, - } - ) - else: - # Standard metric compute (returns dict) - output_dict.update( - metric.compute( - return_all_metrics=return_all_metrics, - prefix=prefix, - ) - ) - return output_dict - - def reset(self): - {metric.reset() for name, metric in self._metric_dict.items()} - - def _split_cuts(self, cuts): - """ - Split cuts based on metric constraints and return filtered subsets. - - This method evaluates each cut against all metric constraints and creates - separate lists of cuts and indices for each metric. - - Args: - cuts (CutSet): Input cuts containing sample metadata - - Returns: - tuple: (cuts_splits, idx_splits) where: - - cuts_splits (dict): Maps metric names to lists of matching cuts - - idx_splits (dict): Maps metric names to lists of matching indices - - Note: - - Handles both regular cuts and MixedCuts (uses first_non_padding_cut) - - A single cut may match multiple metrics - - Cuts not matching any constraints are ignored - """ - cuts_splits, idx_splits = defaultdict(list), defaultdict(list) - for idx, c in enumerate(cuts): - c = c.first_non_padding_cut if isinstance(c, MixedCut) else c - for metric, constr in self._constr_dict.items(): - if constr(c.custom): - cuts_splits[metric].append(c) - idx_splits[metric].append(idx) - return cuts_splits, idx_splits diff --git a/nemo/collections/asr/metrics/wer.py b/nemo/collections/asr/metrics/wer.py deleted file mode 100644 index 0011de8adc698ad7c41b75ad16daef23dd56546e..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/metrics/wer.py +++ /dev/null @@ -1,379 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from copy import deepcopy -from typing import List, Optional, Tuple, Union - -import editdistance -import jiwer -import torch -from torchmetrics import Metric - -from nemo.collections.asr.parts.submodules.ctc_decoding import AbstractCTCDecoding -from nemo.collections.asr.parts.submodules.multitask_decoding import AbstractMultiTaskDecoding -from nemo.collections.asr.parts.submodules.rnnt_decoding import AbstractRNNTDecoding -from nemo.utils import logging - -__all__ = ['word_error_rate', 'word_error_rate_detail', 'WER'] - - -def move_dimension_to_the_front(tensor, dim_index): - all_dims = list(range(tensor.ndim)) - return tensor.permute(*([dim_index] + all_dims[:dim_index] + all_dims[dim_index + 1 :])) - - -def word_error_rate(hypotheses: List[str], references: List[str], use_cer=False) -> float: - """ - Computes Average Word Error rate between two texts represented as - corresponding lists of string. - - Hypotheses and references must have same length. - - Args: - hypotheses (list): list of hypotheses - references(list) : list of references - use_cer (bool): set True to enable cer - - Returns: - wer (float): average word error rate - """ - scores = 0 - words = 0 - if len(hypotheses) != len(references): - raise ValueError( - "In word error rate calculation, hypotheses and reference" - " lists must have the same number of elements. But I got:" - "{0} and {1} correspondingly".format(len(hypotheses), len(references)) - ) - for h, r in zip(hypotheses, references): - if use_cer: - h_list = list(h) - r_list = list(r) - else: - h_list = h.split() - r_list = r.split() - words += len(r_list) - # May deprecate using editdistance in future release for here and rest of codebase - # once we confirm jiwer is reliable. - scores += editdistance.eval(h_list, r_list) - if words != 0: - wer = 1.0 * scores / words - else: - wer = float('inf') - return wer - - -def word_error_rate_detail( - hypotheses: List[str], references: List[str], use_cer=False -) -> Tuple[float, int, float, float, float]: - """ - Computes Average Word Error Rate with details (insertion rate, deletion rate, substitution rate) - between two texts represented as corresponding lists of string. - - Hypotheses and references must have same length. - - Args: - hypotheses (list): list of hypotheses - references(list) : list of references - use_cer (bool): set True to enable cer - - Returns: - wer (float): average word error rate - words (int): Total number of words/charactors of given reference texts - ins_rate (float): average insertion error rate - del_rate (float): average deletion error rate - sub_rate (float): average substitution error rate - """ - scores = 0 - words = 0 - ops_count = {'substitutions': 0, 'insertions': 0, 'deletions': 0} - - if len(hypotheses) != len(references): - raise ValueError( - "In word error rate calculation, hypotheses and reference" - " lists must have the same number of elements. But I got:" - "{0} and {1} correspondingly".format(len(hypotheses), len(references)) - ) - - for h, r in zip(hypotheses, references): - if use_cer: - h_list = list(h) - r_list = list(r) - else: - h_list = h.split() - r_list = r.split() - - # To get rid of the issue that jiwer does not allow empty string - if len(r_list) == 0: - if len(h_list) != 0: - errors = len(h_list) - ops_count['insertions'] += errors - else: - errors = 0 - else: - if use_cer: - measures = jiwer.cer(r, h, return_dict=True) - else: - measures = jiwer.compute_measures(r, h) - - errors = measures['insertions'] + measures['deletions'] + measures['substitutions'] - ops_count['insertions'] += measures['insertions'] - ops_count['deletions'] += measures['deletions'] - ops_count['substitutions'] += measures['substitutions'] - - scores += errors - words += len(r_list) - - if words != 0: - wer = 1.0 * scores / words - ins_rate = 1.0 * ops_count['insertions'] / words - del_rate = 1.0 * ops_count['deletions'] / words - sub_rate = 1.0 * ops_count['substitutions'] / words - else: - wer, ins_rate, del_rate, sub_rate = float('inf'), float('inf'), float('inf'), float('inf') - - return wer, words, ins_rate, del_rate, sub_rate - - -def word_error_rate_per_utt(hypotheses: List[str], references: List[str], use_cer=False) -> Tuple[List[float], float]: - """ - Computes Word Error Rate per utterance and the average WER - between two texts represented as corresponding lists of string. - - Hypotheses and references must have same length. - - Args: - hypotheses (list): list of hypotheses - references(list) : list of references - use_cer (bool): set True to enable cer - - Returns: - wer_per_utt (List[float]): word error rate per utterance - avg_wer (float): average word error rate - """ - scores = 0 - words = 0 - wer_per_utt = [] - - if len(hypotheses) != len(references): - raise ValueError( - "In word error rate calculation, hypotheses and reference" - " lists must have the same number of elements. But I got:" - "{0} and {1} correspondingly".format(len(hypotheses), len(references)) - ) - - for h, r in zip(hypotheses, references): - if use_cer: - h_list = list(h) - r_list = list(r) - else: - h_list = h.split() - r_list = r.split() - - # To get rid of the issue that jiwer does not allow empty string - if len(r_list) == 0: - if len(h_list) != 0: - errors = len(h_list) - wer_per_utt.append(float('inf')) - else: - if use_cer: - measures = jiwer.cer(r, h, return_dict=True) - er = measures['cer'] - else: - measures = jiwer.compute_measures(r, h) - er = measures['wer'] - - errors = measures['insertions'] + measures['deletions'] + measures['substitutions'] - wer_per_utt.append(er) - - scores += errors - words += len(r_list) - - if words != 0: - avg_wer = 1.0 * scores / words - else: - avg_wer = float('inf') - - return wer_per_utt, avg_wer - - -class WER(Metric): - """ - This metric computes numerator and denominator for Overall Word Error Rate (WER) between prediction and reference - texts. When doing distributed training/evaluation the result of ``res=WER(predictions, predictions_lengths, targets, target_lengths)`` - calls will be all-reduced between all workers using SUM operations. Here ``res`` contains three numbers - ``res=[wer, total_levenstein_distance, total_number_of_words]``. - - If used with PytorchLightning LightningModule, include wer_numerator and wer_denominators inside validation_step - results. Then aggregate (sum) then at the end of validation epoch to correctly compute validation WER. - - Example: - def validation_step(self, batch, batch_idx): - ... - wer_num, wer_denom = self.__wer(predictions, predictions_len, transcript, transcript_len) - self.val_outputs = {'val_loss': loss_value, 'val_wer_num': wer_num, 'val_wer_denom': wer_denom} - return self.val_outputs - - def on_validation_epoch_end(self): - ... - wer_num = torch.stack([x['val_wer_num'] for x in self.val_outputs]).sum() - wer_denom = torch.stack([x['val_wer_denom'] for x in self.val_outputs]).sum() - tensorboard_logs = {'validation_loss': val_loss_mean, 'validation_avg_wer': wer_num / wer_denom} - self.val_outputs.clear() # free memory - return {'val_loss': val_loss_mean, 'log': tensorboard_logs} - - Args: - decoding: An instance of CTCDecoding or RNNTDecoding. - use_cer: Whether to use Character Error Rate instead of Word Error Rate. - log_prediction: Whether to log a single decoded sample per call. - batch_dim_index: Index corresponding to batch dimension. (For RNNT.) - dist_dync_on_step: Whether to perform reduction on forward pass of metric. - return_hypotheses: Whether to return the hypotheses. - - Returns: - res: a tuple of 3 zero dimensional float32 ``torch.Tensor` objects: a WER score, a sum of Levenstein's - distances for all prediction - reference pairs, total number of words in all references. - """ - - full_state_update: bool = True - - def __init__( - self, - decoding: Union[AbstractCTCDecoding, AbstractRNNTDecoding, AbstractMultiTaskDecoding], - use_cer=False, - log_prediction=True, - fold_consecutive=True, - batch_dim_index=0, - dist_sync_on_step=False, - sync_on_compute=True, - return_hypotheses=False, - **kwargs, - ): - super().__init__(dist_sync_on_step=dist_sync_on_step, sync_on_compute=sync_on_compute) - - self.decoding = decoding - self.use_cer = use_cer - self.log_prediction = log_prediction - self.fold_consecutive = fold_consecutive - self.batch_dim_index = batch_dim_index - self.return_hypotheses = return_hypotheses - - self.decode = None - if isinstance(self.decoding, AbstractRNNTDecoding): - self.decode = lambda predictions, predictions_lengths, predictions_mask, input_ids: self.decoding.rnnt_decoder_predictions_tensor( - encoder_output=predictions, encoded_lengths=predictions_lengths, return_hypotheses=return_hypotheses - ) - elif isinstance(self.decoding, AbstractCTCDecoding): - self.decode = lambda predictions, predictions_lengths, predictions_mask, input_ids: self.decoding.ctc_decoder_predictions_tensor( - decoder_outputs=predictions, - decoder_lengths=predictions_lengths, - fold_consecutive=self.fold_consecutive, - return_hypotheses=return_hypotheses, - ) - elif isinstance(self.decoding, AbstractMultiTaskDecoding): - self.decode = lambda predictions, prediction_lengths, predictions_mask, input_ids: self.decoding.decode_predictions_tensor( - encoder_hidden_states=predictions, - encoder_input_mask=predictions_mask, - decoder_input_ids=input_ids, - return_hypotheses=return_hypotheses, - ) - else: - raise TypeError(f"WER metric does not support decoding of type {type(self.decoding)}") - - self.add_state("scores", default=torch.tensor(0), dist_reduce_fx='sum', persistent=False) - self.add_state("words", default=torch.tensor(0), dist_reduce_fx='sum', persistent=False) - self.hypotheses = None - - def update( - self, - predictions: torch.Tensor, - predictions_lengths: torch.Tensor, - targets: torch.Tensor, - targets_lengths: torch.Tensor, - predictions_mask: Optional[torch.Tensor] = None, - input_ids: Optional[torch.Tensor] = None, - **kwargs, # To allow easy swapping of metrics without worrying about var alignment. - ): - """ - Updates metric state. - Args: - predictions: an integer torch.Tensor of shape ``[Batch, Time, {Vocabulary}]`` (if ``batch_dim_index == 0``) or - ``[Time, Batch]`` (if ``batch_dim_index == 1``) - prediction_lengths: an integer torch.Tensor of shape ``[Batch]`` - targets: an integer torch.Tensor of shape ``[Batch, Time]`` (if ``batch_dim_index == 0``) or - ``[Time, Batch]`` (if ``batch_dim_index == 1``) - target_lengths: an integer torch.Tensor of shape ``[Batch]`` - predictions_lengths: an integer torch.Tensor of shape ``[Batch]`` - """ - words = 0 - scores = 0 - references = [] - - with torch.no_grad(): - tgt_lenths_cpu_tensor = targets_lengths.long().cpu() - targets_cpu_tensor = targets.long().cpu() - # check batch_dim_index is first dim - if self.batch_dim_index != 0: - targets_cpu_tensor = move_dimension_to_the_front(targets_cpu_tensor, self.batch_dim_index) - # iterate over batch - for ind in range(targets_cpu_tensor.shape[0]): - tgt_len = tgt_lenths_cpu_tensor[ind].item() - target = targets_cpu_tensor[ind][:tgt_len].numpy().tolist() - reference = self.decoding.decode_ids_to_str(target) - references.append(reference) - hypotheses = ( - self.decode(predictions, predictions_lengths, predictions_mask, input_ids) - if predictions.numel() > 0 - else [] - ) - - if hypotheses and self.log_prediction: - logging.info("\n") - logging.info(f"WER reference:{references[0]}") - logging.info(f"WER predicted:{hypotheses[0].text}") - - for h, r in zip(hypotheses, references): - if isinstance(h, list): - h = h[0] - if self.use_cer: - h_list = list(h.text) - r_list = list(r) - else: - h_list = h.text.split() - r_list = r.split() - words += len(r_list) - # Compute Levenstein's distance - scores += editdistance.eval(h_list, r_list) - - self.scores = torch.tensor(scores, device=self.scores.device, dtype=self.scores.dtype) - self.words = torch.tensor(words, device=self.words.device, dtype=self.words.dtype) - self.hypotheses = hypotheses - return None - - def compute(self): - scores = self.scores.detach().float() - words = self.words.detach().float() - return scores / words, scores, words - - def reset(self): - super().reset() - self.hypotheses = None - - def get_hypotheses(self): - """ - Returns the hypotheses generated during the last call to update. - """ - if self.hypotheses is None: - raise ValueError("No hypotheses available. Please call update() first.") - return deepcopy(self.hypotheses) diff --git a/nemo/collections/asr/models/__init__.py b/nemo/collections/asr/models/__init__.py deleted file mode 100644 index cc9b3a74e1ea504719aea6224465b58fc0e3d439..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/__init__.py +++ /dev/null @@ -1,63 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.asr.models.aed_multitask_models import EncDecMultiTaskModel # noqa: F401 -from nemo.collections.asr.models.asr_model import ASRModel # noqa: F401 -from nemo.collections.asr.models.classification_models import ( # noqa: F401 - ClassificationInferConfig, - EncDecClassificationModel, - EncDecFrameClassificationModel, -) -from nemo.collections.asr.models.clustering_diarizer import ClusteringDiarizer # noqa: F401 -from nemo.collections.asr.models.ctc_bpe_models import EncDecCTCModelBPE # noqa: F401 -from nemo.collections.asr.models.ctc_models import EncDecCTCModel # noqa: F401 -from nemo.collections.asr.models.hybrid_rnnt_ctc_bpe_models import EncDecHybridRNNTCTCBPEModel # noqa: F401 -from nemo.collections.asr.models.hybrid_rnnt_ctc_bpe_models_prompt import ( # noqa: F401 - EncDecHybridRNNTCTCBPEModelWithPrompt, -) -from nemo.collections.asr.models.hybrid_rnnt_ctc_models import EncDecHybridRNNTCTCModel # noqa: F401 -from nemo.collections.asr.models.label_models import EncDecSpeakerLabelModel # noqa: F401 -from nemo.collections.asr.models.multitalker_asr_models import EncDecMultiTalkerRNNTBPEModel # noqa: F401 -from nemo.collections.asr.models.rnnt_bpe_models import EncDecRNNTBPEModel # noqa: F401 -from nemo.collections.asr.models.rnnt_models import EncDecRNNTModel # noqa: F401 -from nemo.collections.asr.models.sortformer_diar_models import SortformerEncLabelModel # noqa: F401 -from nemo.collections.asr.models.ssl_models import ( # noqa: F401 - EncDecDenoiseMaskedTokenPredModel, - EncDecMaskedTokenPredModel, - SpeechEncDecSelfSupervisedModel, -) -from nemo.collections.asr.models.transformer_bpe_models import EncDecTransfModelBPE # noqa: F401 - -__all__ = [ - 'ASRModel', - 'ClassificationInferConfig', - 'ClusteringDiarizer', - 'EncDecCTCModel', - 'EncDecCTCModelBPE', - 'EncDecClassificationModel', - 'EncDecDenoiseMaskedTokenPredModel', - 'EncDecFrameClassificationModel', - 'EncDecHybridRNNTCTCBPEModel', - 'EncDecHybridRNNTCTCBPEModelWithPrompt', - 'EncDecHybridRNNTCTCModel', - 'EncDecMaskedTokenPredModel', - 'EncDecMultiTaskModel', - 'EncDecMultiTalkerRNNTBPEModel', - 'EncDecRNNTBPEModel', - 'EncDecRNNTModel', - 'EncDecSpeakerLabelModel', - 'EncDecTransfModelBPE', - 'SortformerEncLabelModel', - 'SpeechEncDecSelfSupervisedModel', -] diff --git a/nemo/collections/asr/models/aed_multitask_models.py b/nemo/collections/asr/models/aed_multitask_models.py deleted file mode 100644 index b5101db1380b27a6e082c2805d5056eb2b0c677c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/aed_multitask_models.py +++ /dev/null @@ -1,1462 +0,0 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os -import warnings -from collections.abc import Mapping, Sequence -from dataclasses import dataclass, field -from math import ceil -from typing import Any, Dict, List, Optional, Union - -import numpy as np -import torch -from lightning.pytorch import Trainer -from omegaconf import DictConfig, ListConfig, OmegaConf, open_dict -from torch.utils.data import DataLoader - -from nemo.collections.asr.data.audio_to_text_lhotse_prompted import ( - PromptedAudioToTextLhotseDataset, - PromptedAudioToTextMiniBatch, -) -from nemo.collections.asr.metrics import MultiTaskMetric -from nemo.collections.asr.models.asr_model import ASRModel, ExportableEncDecModel -from nemo.collections.asr.parts.mixins import ASRBPEMixin, ASRModuleMixin, ASRTranscriptionMixin -from nemo.collections.asr.parts.mixins.transcription import ( - GenericTranscriptionType, - InternalTranscribeConfig, - TranscribeConfig, -) -from nemo.collections.asr.parts.preprocessing.segment import ChannelSelectorType -from nemo.collections.asr.parts.submodules.multitask_decoding import MultiTaskDecoding, MultiTaskDecodingConfig -from nemo.collections.asr.parts.submodules.token_classifier import TokenClassifier -from nemo.collections.asr.parts.utils.chunking_utils import merge_all_hypotheses, merge_parallel_chunks -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis -from nemo.collections.asr.parts.utils.timestamp_utils import ( - get_forced_aligned_timestamps_with_external_model, - process_aed_timestamp_outputs, -) -from nemo.collections.common import tokenizers -from nemo.collections.common.data.lhotse.dataloader import get_lhotse_dataloader_from_config -from nemo.collections.common.metrics import GlobalAverageLossMetric -from nemo.collections.common.parts import transformer_weights_init -from nemo.collections.common.parts.preprocessing.manifest import get_full_path -from nemo.collections.common.prompts.formatter import PromptFormatter -from nemo.core.classes.common import typecheck -from nemo.core.connectors.save_restore_connector import SaveRestoreConnector -from nemo.core.neural_types import ( - AudioSignal, - ChannelType, - LabelsType, - LengthsType, - LogprobsType, - MaskType, - NeuralType, - SpectrogramType, -) -from nemo.utils import logging, model_utils -from nemo.utils.app_state import AppState - -__all__ = ['EncDecMultiTaskModel'] - - -def lens_to_mask(lens, max_length): - """ - Create a mask from a tensor of lengths. - """ - batch_size = lens.shape[0] - arange = torch.arange(max_length, device=lens.device) - mask = arange.expand(batch_size, max_length) < lens.unsqueeze(1) - return mask - - -def _config_check(cfg): - if 'tokenizer' not in cfg: - raise ValueError("`cfg` must have `tokenizer` config to create a tokenizer !") - # Assert config has "prompt_format" - if "prompt_format" not in cfg: - raise ValueError("`cfg` must have `prompt_format` config to create a multi task model !") - # Assert config has `model_defaults` - if 'model_defaults' not in cfg: - raise ValueError("`cfg` must have `model_defaults` config to create a model !") - if "asr_enc_hidden" not in cfg.model_defaults: - raise ValueError("`cfg.model_defaults` must have `asr_enc_hidden` key !") - if "lm_enc_hidden" not in cfg.model_defaults: - raise ValueError("`cfg.model_defaults` must have `lm_enc_hidden` key !") - if "lm_dec_hidden" not in cfg.model_defaults: - raise ValueError("`cfg.model_defaults` must have `lm_dec_hidden` key !") - - -@dataclass -class MultiTaskTranscriptionInternalConfig(InternalTranscribeConfig): - """ - Configuration for Multi Task Transcription - """ - - manifest_filepath: Optional[str] = None - primary_language: Optional[str] = None - - -@dataclass -class MultiTaskTranscriptionConfig(TranscribeConfig): - """ - Configuration for Multi Task Transcription - - enable_chunking: bool = True - Whether to enable parallel processing of audio chunks for long-form audio. - If enabled, batch_size should be set to 1 or single audio be passed. - """ - - prompt: list[dict[str, dict[str, str]]] | None = None - text_field: str = "answer" - lang_field: str = "target_lang" - - _internal: Optional[MultiTaskTranscriptionInternalConfig] = field( - default_factory=lambda: MultiTaskTranscriptionInternalConfig() - ) - enable_chunking: bool = True - - def __post_init__(self): - self.prompt = parse_multitask_prompt(self.prompt) - - -class EncDecMultiTaskModel(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRModuleMixin, ASRTranscriptionMixin): - """Base class for AED multi-task models""" - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - - # Convert to Hydra 1.0 compatible DictConfig - cfg = model_utils.convert_model_config_to_dict_config(cfg) - cfg = model_utils.maybe_update_config_version(cfg, make_copy=False) - _config_check(cfg) - - self.prompt_format = cfg.prompt_format - self.sample_rate = cfg.sample_rate - self._setup_tokenizer(cfg.tokenizer) - prompt_cls = PromptFormatter.resolve(self.prompt_format) - self.prompt = prompt_cls( - tokenizer=self.tokenizer, - defaults=OmegaConf.to_container(pd) if (pd := cfg.get("prompt_defaults")) is not None else None, - ) - - super().__init__(cfg=cfg, trainer=trainer) - - # Setup audio preprocessor - self.preprocessor = EncDecMultiTaskModel.from_config_dict(self.cfg.preprocessor) - # Setup audio encoder - self.encoder = EncDecMultiTaskModel.from_config_dict(self.cfg.encoder) - - # Add projection layer if encoder and decoder differ in hidden size - asr_enc_hidden_size = self.cfg.model_defaults.asr_enc_hidden - decoder_hidden_size = self.cfg.model_defaults.lm_dec_hidden - if asr_enc_hidden_size != decoder_hidden_size: - self.encoder_decoder_proj = torch.nn.Linear(asr_enc_hidden_size, decoder_hidden_size) - else: - self.encoder_decoder_proj = torch.nn.Identity() - - transf_encoder_cfg_dict = self.cfg.get('transf_encoder', None) - - # Whether to add Transformer Encoder block between Conformer and Transformer Decoder - self.use_transf_encoder = False - if transf_encoder_cfg_dict is not None and transf_encoder_cfg_dict['num_layers'] > 0: - self.use_transf_encoder = True - - self.transf_encoder = EncDecMultiTaskModel.from_config_dict(transf_encoder_cfg_dict) - - # Initialize weights - std_init_range = 1 / self.cfg.model_defaults.lm_enc_hidden**0.5 - self.transf_encoder.apply(lambda module: transformer_weights_init(module, std_init_range)) - - transf_decoder_cfg_dict = cfg.transf_decoder - - # Transformer decoder - vocab_size = 8 * ceil(self.tokenizer.vocab_size / 8) - - # Auto inject vocab size for `get_transformer` - with open_dict(transf_decoder_cfg_dict): - if 'config_dict' in transf_decoder_cfg_dict: - transf_decoder_cfg_dict['config_dict']['vocab_size'] = vocab_size - - self.transf_decoder = EncDecMultiTaskModel.from_config_dict(transf_decoder_cfg_dict) - - # Setup token classifier - with open_dict(self.cfg.head): - self.cfg.head.num_classes = vocab_size - - self.log_softmax = EncDecMultiTaskModel.from_config_dict(self.cfg.head) - - # Weight tying - if using TokenClassifier only - if isinstance(self.log_softmax, TokenClassifier): - self.log_softmax.mlp.layer0.weight = self.transf_decoder.embedding.token_embedding.weight - - # Initialize weights - std_init_range = 1 / self.cfg.model_defaults.lm_dec_hidden**0.5 - self.transf_decoder.apply(lambda module: transformer_weights_init(module, std_init_range)) - self.log_softmax.apply(lambda module: transformer_weights_init(module, std_init_range)) - - # Setup decoding objects - decoding_cfg = self.cfg.get('decoding', None) - - # In case decoding config not found, use default config - if decoding_cfg is None: - decoding_cfg = OmegaConf.structured(MultiTaskDecodingConfig) - with open_dict(self.cfg): - self.cfg.decoding = decoding_cfg - - self.decoding = MultiTaskDecoding( - decoding_cfg=self.cfg.decoding, - transformer_decoder=self.transf_decoder, - log_softmax_module=self.log_softmax, - tokenizer=self.tokenizer, - ) - - # Define autoregressive CE loss - with open_dict(self.cfg.loss): - self.cfg.loss.pad_id = self.tokenizer.pad_id - - self.loss = EncDecMultiTaskModel.from_config_dict(self.cfg.loss) - - if hasattr(self.cfg, 'spec_augment') and self.cfg.spec_augment is not None: - self.spec_augmentation = EncDecMultiTaskModel.from_config_dict(self.cfg.spec_augment) - else: - self.spec_augmentation = None - - self.val_loss = GlobalAverageLossMetric(dist_sync_on_step=False, take_avg_loss=True) - - # Setup metric logger. Use `get` for backcompatibility with aed checkpointing. - if (metric_cfg := cfg.get("multitask_metrics_cfg")) is None: - metric_cfg = DictConfig( - { - "metrics": { - "wer": { - "_target_": "nemo.collections.asr.metrics.WER", - }, - "bleu": { - "_target_": "nemo.collections.asr.metrics.BLEU", - }, - } - } - ) - self.metric_cfg = metric_cfg - self.metric = MultiTaskMetric(model=self, cfg=metric_cfg) - - # Setup encoder adapters (from ASRAdapterModelMixin) - self.setup_adapters() - - if self.cfg.get("restore_timestamps_model", True): - timestamps_asr_model = self.__restore_timestamps_asr_model() - else: - timestamps_asr_model = None - # Using object.__setattr__ to bypass PyTorch's module registration - object.__setattr__(self, 'timestamps_asr_model', timestamps_asr_model) - - def change_decoding_strategy(self, decoding_cfg: DictConfig): - """ - Changes decoding strategy used during Multi Task decoding process. - - Args: - decoding_cfg: A config for the decoder, which is optional. If the decoding type - needs to be changed (from say Greedy to Beam decoding etc), the config can be passed here. - """ - if decoding_cfg is None: - # Assume same decoding config as before - logging.info("No `decoding_cfg` passed when changing decoding strategy, using internal config") - decoding_cfg = self.cfg.decoding - - # Assert the decoding config with all hyper parameters - decoding_cls = OmegaConf.structured(MultiTaskDecodingConfig) - decoding_cls = OmegaConf.create(OmegaConf.to_container(decoding_cls)) - decoding_cfg = OmegaConf.merge(decoding_cls, decoding_cfg) - - self.decoding = MultiTaskDecoding( - decoding_cfg=decoding_cfg, - transformer_decoder=self.transf_decoder, - log_softmax_module=self.log_softmax, - tokenizer=self.tokenizer, - ) - - # Update metric logger - self.metric = MultiTaskMetric(model=self, cfg=self.metric_cfg) - - # Update config - with open_dict(self.cfg.decoding): - self.cfg.decoding = decoding_cfg - - logging.info(f"Changed decoding strategy to \n{OmegaConf.to_yaml(self.cfg.decoding)}") - - def change_vocabulary( - self, - new_tokenizer_dir: Union[str, DictConfig], - new_tokenizer_type: str, - decoding_cfg: Optional[DictConfig] = None, - prompt_format: Optional[str] = None, - ): - """ - Changes vocabulary used during AED decoding process. Use this method when fine-tuning on - from pre-trained model. This method changes only decoder and leaves encoder and pre-processing - modules unchanged. For example, you would use it if you want to use pretrained encoder when - fine-tuning on data in another language, or when you'd need model to learn capitalization, - punctuation and/or special characters. - - Args: - new_tokenizer_dir: Directory path to tokenizer or a config for a new tokenizer - (if the tokenizer type is `agg`) - new_tokenizer_type: Type of tokenizer. Can be either `agg`, `bpe` or `wpe`. - decoding_cfg: A config for the decoding, which is optional. If the decoding type - needs to be changed (from say Greedy to Beam decoding etc), the config can be passed here. - prompt_format: A string alias of the object that represents the prompt structure. - If not None, it will be used to update the prompt format. - """ - if isinstance(new_tokenizer_dir, (dict, DictConfig)): - if new_tokenizer_type == 'agg': - if not isinstance(new_tokenizer_dir, DictConfig): - new_tokenizer_dir = OmegaConf.create(new_tokenizer_dir) - - new_tokenizer_cfg = new_tokenizer_dir - else: - raise ValueError( - f'New tokenizer dir should be a string unless the tokenizer is `agg`, but this\ - tokenizer type is: {new_tokenizer_type}' - ) - else: - new_tokenizer_cfg = None - - if new_tokenizer_cfg is not None: - tokenizer_cfg = new_tokenizer_cfg - else: - if not os.path.isdir(new_tokenizer_dir): - raise NotADirectoryError( - f'New tokenizer dir must be non-empty path to a directory. But instead got: {new_tokenizer_dir}' - ) - - if new_tokenizer_type.lower() not in ('bpe', 'wpe'): - raise ValueError('New tokenizer type must be either `bpe` or `wpe`') - - tokenizer_cfg = OmegaConf.create({'dir': new_tokenizer_dir, 'type': new_tokenizer_type}) - - if prompt_format is None: - prompt_format = self.cfg.prompt_format - - # Setup the tokenizer - self._setup_tokenizer(tokenizer_cfg) - - # Initialize a dummy vocabulary - vocabulary = self.tokenizer.tokenizer.get_vocab() - - # Setup Decoder - transf_decoder_cfg_dict = self.transf_decoder.to_config_dict() - - vocab_size = 8 * ceil(self.tokenizer.vocab_size / 8) - - # Auto inject vocab size for `get_transformer` - with open_dict(transf_decoder_cfg_dict): - if 'config_dict' in transf_decoder_cfg_dict: - transf_decoder_cfg_dict['config_dict']['vocab_size'] = vocab_size - - original_decoder_state_dict = self.transf_decoder.state_dict() - self.transf_decoder = EncDecMultiTaskModel.from_config_dict(transf_decoder_cfg_dict) - - # Partially load the original state dict into the new decoder - decoder_state_dict = self.transf_decoder.state_dict() - for og_key, og_value in original_decoder_state_dict.items(): - if og_key in decoder_state_dict and og_value.shape == decoder_state_dict[og_key].shape: - decoder_state_dict[og_key] = og_value - else: - logging.warning( - f"Skipping key `{og_key}` in the `transf_decoder` module from original state dict due " - f"to shape mismatch after change in vocabulary.\n" - f"Original shape: {og_value.shape}, New shape: {decoder_state_dict[og_key].shape}" - ) - - self.transf_decoder.load_state_dict(decoder_state_dict) - - # Setup token classifier - with open_dict(self.cfg.head): - self.cfg.head.num_classes = vocab_size - - del self.log_softmax - self.log_softmax = EncDecMultiTaskModel.from_config_dict(self.cfg.head) - - # Weight tying - if using TokenClassifier only - if isinstance(self.log_softmax, TokenClassifier): - self.log_softmax.mlp.layer0.weight = self.transf_decoder.embedding.token_embedding.weight - - # Initialize weights of token classifier - std_init_range = 1 / self.cfg.model_defaults.lm_dec_hidden**0.5 - self.log_softmax.apply(lambda module: transformer_weights_init(module, std_init_range)) - - # Setup Decoding class - if decoding_cfg is None: - # Assume same decoding config as before - decoding_cfg = self.cfg.decoding - - # Assert the decoding config with all hyper parameters - decoding_cls = OmegaConf.structured(MultiTaskDecodingConfig) - decoding_cls = OmegaConf.create(OmegaConf.to_container(decoding_cls)) - decoding_cfg = OmegaConf.merge(decoding_cls, decoding_cfg) - - del self.decoding - self.decoding = MultiTaskDecoding( - decoding_cfg=decoding_cfg, - transformer_decoder=self.transf_decoder, - log_softmax_module=self.log_softmax, - tokenizer=self.tokenizer, - ) - - # Update metric logger - self.metric = MultiTaskMetric(model=self, cfg=self.metric_cfg) - - with open_dict(self.cfg.decoding): - self.cfg.decoding = decoding_cfg - - # Setup loss - with open_dict(self.cfg.loss): - self.cfg.loss.pad_id = self.tokenizer.pad_id - - del self.loss - self.loss = EncDecMultiTaskModel.from_config_dict(self.cfg.loss) - - # Update config - with open_dict(self.cfg): - self.cfg.prompt_format = prompt_format - - logging.info(f"Changed decoder to output to {vocabulary} vocabulary.") - - def change_prompt( - self, prompt_format: Optional[str] = None, prompt_defaults: Optional[List[Dict[str, Any]]] = None - ): - """ - Changes the prompt format used during Multi Task decoding process. - - Args: - prompt_format: A string alias of the object that represents the prompt structure. - If not None, it will be used to update the prompt format. - prompt_defaults: A dictionary of default values for the prompt format. - """ - if prompt_format is not None: - self.prompt_format = prompt_format - - if prompt_defaults is not None: - # Perform some assertions on the prompt defaults contents - # Must be a list-like object - if not isinstance(prompt_defaults, Sequence): - raise ValueError("`prompt_defaults` must be a list of dictionaries") - - # Must contain dict-like objects - for item in prompt_defaults: - if not isinstance(item, Mapping): - raise ValueError("`prompt_defaults` must be a list of dictionaries") - - # Each dict item must have a `role` key - if 'role' not in item: - raise ValueError( - "`prompt_defaults` must have a `role` key for each item in the list of dictionaries" - ) - - if 'slots' not in item: - raise ValueError( - "`prompt_defaults` must have a `slots` key for each item in the list of dictionaries" - ) - - # Cast to OmegaConf if not already - if not isinstance(prompt_defaults, ListConfig): - prompt_defaults = OmegaConf.create(prompt_defaults) - - prompt_cls = PromptFormatter.resolve(self.prompt_format) - self.prompt = prompt_cls( - tokenizer=self.tokenizer, - defaults=OmegaConf.to_container(pd) if (pd := self.cfg.get('prompt_defaults')) is not None else None, - ) - - # Update metric logger - self.metric = MultiTaskMetric(model=self, cfg=self.metric_cfg) - - # Update config - with open_dict(self.cfg): - self.cfg.prompt_format = self.prompt_format - self.cfg.prompt_defaults = prompt_defaults - - logging.info(f"Changed prompt format to `{self.prompt_format}`") - - @torch.no_grad() - def transcribe( - self, - audio: Union[str, List[str], np.ndarray, DataLoader], - batch_size: int = 4, - return_hypotheses: bool = False, - num_workers: int = 0, - channel_selector: Optional[ChannelSelectorType] = None, - augmentor: DictConfig = None, - verbose: bool = True, - timestamps: Optional[bool] = None, - override_config: Optional[MultiTaskTranscriptionConfig] = None, - **prompt, - ) -> Union[List[str], List[Hypothesis]]: - """ - Uses greedy decoding to transcribe audio files. Use this method for debugging and prototyping. - This allows the model to process long audio in manageable chunks and merge the results. - Args: - audio: (a single or list) of paths to audio files or a np.ndarray/tensor audio array or path - to a manifest file. - Can also be a dataloader object that provides values that can be consumed by the model. - Recommended length per file is between 5 and 25 seconds. \ - But it is possible to pass a few hours long file if enough GPU memory is available. - batch_size: (int) batch size to use during inference. - Bigger will result in better throughput performance but would use more memory. - return_hypotheses: (bool) Either return hypotheses or text - With hypotheses can do some postprocessing like getting timestamp or rescoring - num_workers: (int) number of workers for DataLoader - 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`. - augmentor: (DictConfig): Augment audio samples during transcription if augmentor is applied. - timestamps: Optional(Bool): timestamps will be returned if set to True as part of hypothesis - object (output.timestep['segment']/output.timestep['word']). Refer to `Hypothesis` class - for more details. Default is None and would retain the previous state set by using - self.change_decoding_strategy(). - Note: Currently its not supported for AED models. - verbose: (bool) whether to display tqdm progress bar - override_config: (Optional[MultiTaskTranscriptionConfig]) A config to override the - default config. - **prompt: Optional input to construct the prompts for the model. Accepted formats are: - 1) legacy Canary-1B API source_lang=, target_lang=, etc. - 2) explicit single-turn role=, slots={: , ...} - 3) explicit multi-turn: turns=[{"role": , "slots": {: , ...}}] - - Returns: - A list of transcriptions (or raw log probabilities if logprobs is True) in the same order - as paths2audio_files - """ - if timestamps is not None: - if self.timestamps_asr_model is None: - # TODO: Handle this key gracefully later - if timestamps is True: - timestamps = 'yes' - elif timestamps is False: - timestamps = 'no' - else: - timestamps = str(timestamps) - if timestamps not in ('yes', 'no', 'timestamp', 'notimestamp', '1', '0'): - raise ValueError( - f"Unsupported timestamps value '{timestamps}'. " - f"Must be one of: 'yes', 'no', 'timestamp', 'notimestamp', '1', '0'." - ) - prompt['timestamp'] = timestamps - else: - prompt['timestamp'] = 'no' - - if override_config is None: - trcfg = MultiTaskTranscriptionConfig( - batch_size=batch_size, - return_hypotheses=return_hypotheses, - num_workers=num_workers, - channel_selector=channel_selector, - augmentor=augmentor, - verbose=verbose, - prompt=prompt, - timestamps=timestamps, - ) - else: - if not isinstance(override_config, MultiTaskTranscriptionConfig): - raise ValueError( - f"override_config must be of type {MultiTaskTranscriptionConfig}, " - f"but got {type(override_config)}" - ) - trcfg = override_config - trcfg.timestamps = timestamps - - if trcfg.enable_chunking: - # Check if only one audio is provided with string - is_manifest = isinstance(audio, str) and audio.endswith(("json", "jsonl")) - if is_manifest: - try: - with open(audio, "r", encoding="utf-8") as manifest_f: - non_empty = 0 - for line in manifest_f: - if line.strip(): - non_empty += 1 - if non_empty > 1: - break - is_one_audio = non_empty == 1 - except OSError as e: - logging.warning(f"Failed to inspect manifest '{audio}' for chunking: {e}") - is_one_audio = False - else: - is_one_audio = isinstance(audio, str) or (isinstance(audio, list) and len(audio) == 1) - # Check if chunking will be enabled - trcfg.enable_chunking = (is_one_audio or trcfg.batch_size == 1) and self.timestamps_asr_model is not None - - if trcfg.enable_chunking: - if self.decoding.cfg.get('return_xattn_scores', False): - logging.warning( - "When chunking is enabled, cross-attention scores will not be returned even though " - "`return_xattn_scores` is set to True. If you want to return the cross-attention scores " - "set `enable_chunking` to False in the MultiTaskTranscriptionConfig in override_config." - ) - else: - logging.warning("Chunking is disabled. Please pass a single audio file or set batch_size to 1") - - results = super().transcribe(audio=audio, override_config=trcfg) - - if trcfg.enable_chunking: - results = merge_all_hypotheses(results, trcfg.timestamps, self.encoder.subsampling_factor) - - return results - - def _setup_dataloader_from_config(self, config: Optional[Dict]): - - if not config.get("use_lhotse", False): - raise ValueError( - "Multi-task model only supports dataloading with Lhotse. " - "Please set config.{train,validation,test}_ds.use_lhotse=True" - ) - global_rank = config.get("global_rank", self.global_rank) - world_size = config.get("world_size", self.world_size) - enable_chunking = config.get("enable_chunking", False) - # Adding a check for availability of timestamps_asr_model for differentating between Canary versions. - enable_chunking = enable_chunking and self.timestamps_asr_model is not None - - if enable_chunking: - # Adding this to support processing audio files of arbitrary length by chunking them into hour-long segments. - config.cut_into_windows_duration = 3600 - config.cut_into_windows_hop = 3600 - return get_lhotse_dataloader_from_config( - config, - global_rank=global_rank, - world_size=world_size, - dataset=PromptedAudioToTextLhotseDataset( - tokenizer=self.tokenizer, - prompt=self.prompt, - enable_chunking=enable_chunking, # <-- enables chunking - ), - tokenizer=self.tokenizer, - ) - - def setup_training_data(self, train_data_config: Optional[DictConfig]): - - # create audio-only data loader - self._update_dataset_config(dataset_name='train', config=train_data_config) - self._train_dl = self._setup_dataloader_from_config(config=train_data_config) - - # Need to set this because if using an IterableDataset, the length of the - # dataloader is the total number of samples rather than the number of batches, - # and this messes up the tqdm progress bar. So we set the number of steps manually - # (to the correct number) to fix this. - if 'is_tarred' in train_data_config and train_data_config['is_tarred']: - # We also need to check if limit_train_batches is already set. - # If it's an int, we assume that the user has set it to something sane, - # i.e. <= # training batches, and don't change it. Otherwise, adjust - # batches accordingly if it's a float (including 1.0). - if self._trainer is not None and isinstance(self._trainer.limit_train_batches, float): - self._trainer.limit_train_batches = int( - self._trainer.limit_train_batches - * ceil((len(self._train_dl.dataset) / self.world_size) / train_data_config['batch_size']) - ) - elif self._trainer is None: - logging.warning( - "Model Trainer was not set before constructing the dataset, incorrect number of " - "training batches will be used. Please set the trainer and rebuild the dataset." - ) - - def setup_validation_data(self, val_data_config: Optional[Union[DictConfig, Dict]]): - """ - Sets up the validation data loader via a Dict-like object. - Args: - val_data_config: A config that contains the information regarding construction - of an ASR Training dataset. - Supported Datasets: - - :class:`~nemo.collections.asr.data.audio_to_text_lhotse_prompted.PromptedAudioToTextLhotseDataset` - """ - if 'shuffle' not in val_data_config: - val_data_config['shuffle'] = False - - # preserve config - self._update_dataset_config(dataset_name='validation', config=val_data_config) - self._validation_dl = self._setup_dataloader_from_config(config=val_data_config) - - def setup_test_data(self, test_data_config: Optional[Union[DictConfig, Dict]]): - """ - Sets up the test data loader via a Dict-like object. - Args: - test_data_config: A config that contains the information regarding construction - of an ASR Training dataset. - Supported Datasets: - - :class:`~nemo.collections.asr.data.audio_to_text_lhotse_prompted.PromptedAudioToTextLhotseDataset` - """ - if 'shuffle' not in test_data_config: - test_data_config['shuffle'] = False - - # preserve config - self._update_dataset_config(dataset_name='test', config=test_data_config) - self._test_dl = self._setup_dataloader_from_config(config=test_data_config) - - @property - def input_types(self) -> Optional[Dict[str, NeuralType]]: - if hasattr(self.preprocessor, '_sample_rate'): - input_signal_eltype = AudioSignal(freq=self.preprocessor._sample_rate) - else: - input_signal_eltype = AudioSignal() - return { - "input_signal": NeuralType(('B', 'T'), input_signal_eltype, optional=True), - "input_signal_length": NeuralType(tuple('B'), LengthsType(), optional=True), - "processed_signal": NeuralType(('B', 'D', 'T'), SpectrogramType(), optional=True), - "processed_signal_length": NeuralType(tuple('B'), LengthsType(), optional=True), - "transcript": NeuralType(('B', 'T'), LabelsType(), optional=True), - "transcript_length": NeuralType(tuple('B'), LengthsType(), optional=True), - "prompt": NeuralType(('B', 'T'), LabelsType(), optional=True), - "prompt_length": NeuralType(tuple('B'), LengthsType(), optional=True), - "sample_id": NeuralType(tuple('B'), LengthsType(), optional=True), - } - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - return { - "transf_log_probs": NeuralType(('B', 'T', 'D'), LogprobsType()), - "encoded_lengths": NeuralType(tuple('B'), LengthsType()), - "encoder_states": NeuralType(('B', 'T', 'D'), ChannelType()), - "encoder_mask": NeuralType(('B', 'T'), MaskType()), - } - - @typecheck() - def forward( - self, - input_signal=None, - input_signal_length=None, - processed_signal=None, - processed_signal_length=None, - transcript=None, - transcript_length=None, - ): - """ - Forward pass of the model. - Args: - input_signal: Tensor that represents a batch of raw audio signals, - of shape [B, T]. T here represents timesteps, with 1 second of audio represented as - `self.sample_rate` number of floating point values. - input_signal_length: Vector of length B, that contains the individual lengths of the audio - sequences. - processed_signal: Tensor that represents a batch of processed audio signals, - of shape (B, D, T). - processed_signal_length: Vector of length B, that contains the individual lengths of the - processed audio sequences. - transcript: Tensor that represents a batch of target transcriptions, - of shape [B, T]. Used as decoder input during teacher-forced training. - transcript_length: Vector of length B, that contains the individual lengths of the - target transcription sequences. - - Returns: - A tuple of 3 elements - - 1) The log probabilities tensor of shape [B, T, D]. - 2) The lengths of the acoustic sequence after propagation through the encoder, of shape [B]. - 3) The greedy token predictions of the model of shape [B, T] (via argmax) - """ - has_input_signal = input_signal is not None and input_signal_length is not None - has_processed_signal = processed_signal is not None and processed_signal_length is not None - if (has_input_signal ^ has_processed_signal) == False: - raise ValueError( - f"{self} Arguments ``input_signal`` and ``input_signal_length`` are mutually exclusive " - " with ``processed_signal`` and ``processed_signal_len`` arguments." - ) - - if not has_processed_signal: - processed_signal, processed_signal_length = self.preprocessor( - input_signal=input_signal, length=input_signal_length - ) - - if self.spec_augmentation is not None and self.training: - processed_signal = self.spec_augmentation(input_spec=processed_signal, length=processed_signal_length) - - encoded, encoded_len = self.encoder(audio_signal=processed_signal, length=processed_signal_length) - - enc_states = encoded.permute(0, 2, 1) - enc_states = self.encoder_decoder_proj(enc_states) - enc_mask = lens_to_mask(encoded_len, enc_states.shape[1]).to(enc_states.dtype) - if self.use_transf_encoder: - enc_states = self.transf_encoder(encoder_states=enc_states, encoder_mask=enc_mask) - - transf_log_probs = None - if transcript is not None: - dec_mask = lens_to_mask(transcript_length, transcript.shape[1]).to(transcript.dtype) - dec_states = self.transf_decoder( - input_ids=transcript, decoder_mask=dec_mask, encoder_embeddings=enc_states, encoder_mask=enc_mask - ) - transf_log_probs = self.log_softmax(hidden_states=dec_states) - - return transf_log_probs, encoded_len, enc_states, enc_mask - - # PTL-specific methods - def training_step(self, batch: PromptedAudioToTextMiniBatch, batch_nb): - if batch is None: - return torch.tensor([0.0]) - - input_ids, labels = batch.get_decoder_inputs_outputs() - input_ids_lens = batch.prompted_transcript_lens - 1 - - num_frames = batch.audio_lens.sum().float() - num_tokens = batch.prompted_transcript_lens.sum().float() - tot_frames = torch.as_tensor(batch.audio.numel(), device=num_frames.device, dtype=torch.float) - tot_tokens = torch.as_tensor(batch.prompted_transcript.numel(), device=num_frames.device, dtype=torch.float) - - transf_log_probs, encoded_len, enc_states, enc_mask = self.forward( - input_signal=batch.audio, - input_signal_length=batch.audio_lens, - transcript=input_ids, - transcript_length=input_ids_lens, - ) - - # Mask components: 1) discard padding & 2) discard prompt (notice the negation) - # For a full decoder sequence O with len M, the loss mask skips the first element, - # covering the remaining M-1 elements - hence we subtract 1 from prompt lens to account BOS. - if self.cfg.get("use_loss_mask_for_prompt", False): - maxlen = batch.prompted_transcript.shape[1] - 1 - loss_mask = lens_to_mask(input_ids_lens, maxlen) & ~lens_to_mask(batch.prompt_lens - 1, maxlen) - else: - loss_mask = None - transf_loss = self.loss(log_probs=transf_log_probs, labels=labels, output_mask=loss_mask) - - # Train step evaluation. From other asr models. - if hasattr(self, '_trainer') and self._trainer is not None: - log_every_n_steps = self._trainer.log_every_n_steps - else: - log_every_n_steps = 1 - metric_dict = ( - self.metric.eval( - batch=batch, - predictions=enc_states, - predictions_lengths=encoded_len, - predictions_mask=enc_mask, - prefix="training_batch", - ) - if (batch_nb + 1) % log_every_n_steps == 0 - else {} - ) - - metric_dict.update( - { - 'train_loss': transf_loss, - 'learning_rate': torch.as_tensor(self._optimizer.param_groups[0]['lr']), - 'batch_size': torch.as_tensor(batch.audio.shape[0]), - 'num_frames': num_frames, - 'num_tokens': num_tokens, - 'input_to_padding_ratio': num_frames / tot_frames, - 'output_to_padding_ratio': num_tokens / tot_tokens, - } - ) - return {"loss": transf_loss, "log": metric_dict} - - def validation_pass(self, batch: PromptedAudioToTextMiniBatch, batch_idx, dataloader_idx=0, eval_mode="val"): - input_ids, labels = batch.get_decoder_inputs_outputs() - input_ids_lens = batch.prompted_transcript_lens - 1 - - transf_log_probs, encoded_len, enc_states, enc_mask = self.forward( - input_signal=batch.audio, - input_signal_length=batch.audio_lens, - transcript=input_ids, - transcript_length=batch.prompted_transcript_lens, - ) - - # Mask components: 1) discard padding & 2) discard prompt (notice the negation) - # For a full decoder sequence O with len M, the loss mask skips the first element, - # covering the remaining M-1 elements - hence we subtract 1 from prompt lens to account BOS. - if self.cfg.get("use_loss_mask_for_prompt", False): - maxlen = batch.prompted_transcript.shape[1] - 1 - loss_mask = lens_to_mask(input_ids_lens, maxlen) & ~lens_to_mask(batch.prompt_lens - 1, maxlen) - num_measurements = loss_mask.long().sum() - else: - loss_mask = None - num_measurements = transf_log_probs.shape[0] * transf_log_probs.shape[1] - - transf_loss = self.loss(log_probs=transf_log_probs, labels=labels, output_mask=loss_mask) - self.val_loss(loss=transf_loss, num_measurements=num_measurements) - - metric_dict = self.metric.eval( - batch=batch, - predictions=enc_states, - predictions_lengths=encoded_len, - predictions_mask=enc_mask, - prefix=eval_mode, - return_all_metrics=True, # Need all metrics for computation at end of cycle. - ) - metric_dict[f"{eval_mode}_loss"] = transf_loss - return metric_dict - - def validation_step(self, batch, batch_idx, dataloader_idx=0): - metrics = self.validation_pass(batch, batch_idx, dataloader_idx, eval_mode="val") - if type(self.trainer.val_dataloaders) == list and len(self.trainer.val_dataloaders) > 1: - self.validation_step_outputs[dataloader_idx].append(metrics) - else: - self.validation_step_outputs.append(metrics) - return metrics - - def test_step(self, batch, batch_idx, dataloader_idx=0): - metrics = self.validation_pass(batch, batch_idx, dataloader_idx, eval_mode="test") - if type(self.trainer.test_dataloaders) == list and len(self.trainer.test_dataloaders) > 1: - self.test_step_outputs[dataloader_idx].append(metrics) - else: - self.test_step_outputs.append(metrics) - return metrics - - def test_dataloader(self): - if self._test_dl is not None: - return self._test_dl - - """ Transcription methods """ - - def _transcribe_on_begin(self, audio, trcfg: MultiTaskTranscriptionConfig): - """ - Transcription setup method. - Args: - audio: A list of paths to audio files or a path to a manifest file. - trcfg: A config for the transcription, which is optional. If the decoding type - needs to be changed (from say Greedy to Beam decoding etc), the config can be passed here. - """ - super()._transcribe_on_begin(audio, trcfg) - - # Switch model to evaluation mode - self.transf_decoder.freeze() - - if isinstance(audio, list): - logging.debug(f"Found 'audio' to be a list of {len(audio)} items.") - logging.debug("Assuming each item in 'audio' is a path to audio file.") - - if isinstance(self.tokenizer, tokenizers.AggregateTokenizer): - if hasattr(trcfg, '_internal') and hasattr(trcfg._internal, 'primary_language'): - trcfg._internal.primary_language = self.tokenizer.langs[0] - logging.debug(f"Transcribing with default setting of {trcfg._internal.primary_language}.") - - if trcfg.timestamps and self.timestamps_asr_model is not None: - self.timestamps_asr_model.to(trcfg._internal.device) - - def _transcribe_input_manifest_processing( - self, audio_files: List[str], temp_dir: str, trcfg: MultiTaskTranscriptionConfig - ) -> Dict[str, Any]: - """ - Internal function to process the input audio filepaths and return a config dict for the dataloader. - This implementation adds support for dictionaries as manifest items. - - Args: - audio_files: A list of string filepaths for audio files, or a single string filepath for a manifest file. - temp_dir: A temporary directory to store intermediate files. - trcfg: The transcription config dataclass. Subclasses can change this to a different dataclass if needed. - - Returns: - A config dict that is used to setup the dataloader for transcription. - """ - manifest_filepath = trcfg._internal.manifest_filepath - audio_files = self._may_be_make_dict_and_fix_paths(audio_files, manifest_filepath, trcfg) - - ds_config = super()._transcribe_input_manifest_processing(audio_files, temp_dir, trcfg) - if trcfg.enable_chunking and self.timestamps_asr_model is not None: - ds_config['enable_chunking'] = True - return ds_config - - def _transcribe_forward( - self, batch: PromptedAudioToTextMiniBatch | tuple[torch.Tensor, ...], trcfg: MultiTaskTranscriptionConfig - ) -> dict: - """ - Internal function to perform the model's custom forward pass to return outputs that are processed by - `_transcribe_output_processing()`. - This function is called by `transcribe()` and `transcribe_generator()` to perform the model's forward pass. - - Args: - batch: A batch of input data from the data loader that is used to perform the model's forward pass. - trcfg: The transcription config dataclass. Subclasses can change this to a different dataclass if needed. - - Returns: - The model's outputs that are processed by `_transcribe_output_processing()`. - """ - if isinstance(batch, PromptedAudioToTextMiniBatch): - # Handling regular Canary DataLoader - audio = batch.audio - audio_lens = batch.audio_lens - decoder_input_ids = batch.prompt - else: - # Handling TensorDataset / external DataLoader - audio, audio_lens = batch[0], batch[1] - if len(batch) == 6: - # Prompt provided by the user. - decoder_input_ids = batch[4] - else: - # Prompt to be built dynamically. - decoder_input_ids = None - batch_size = audio.shape[0] - - log_probs, encoded_len, enc_states, enc_mask = self.forward(input_signal=audio, input_signal_length=audio_lens) - - if decoder_input_ids is None: - # The dataloader provided only audio + audio_lens, so we - # are constructing the prompt dynamically using TranscribeConfig. - - # Now ask the prompt formatter about which slots are required. - # It will return a default prompt structure with default slot values (if available, None otherwise). - # We iterate over that structure and update slot values based on ``trcfg.prompt``. - default_turns = self.prompt.get_default_dialog_slots() - if not trcfg.prompt: - # No turns were provided, use defaults. - turns = default_turns - else: - # Turns were provided, iterate over them and fill missing slot values using defaults.. - turns = trcfg.prompt.copy() # shallow copy #1: don't override the config - for turn in turns: - role = turn["role"] - # Check if we have defaults for this role. - # There shouldn't be more than a single turn for a given role, but if there are, - # we'll emit a warning. - if default_turns_for_role := [t for t in default_turns if t["role"] == role]: - if len(default_turns_for_role) > 1: - warnings.warn( - f"More than one default turn detected for {role=}. " - f"We'll be using default slot values for the first turn of {role=} only." - ) - default_slots = default_turns_for_role[0]["slots"] - turn["slots"] = turn["slots"].copy() # shallow copy #1: don't override the config - # fill missing slots using defaults - for slot, val in default_slots.items(): - if turn["slots"].get(slot) is None: - turn["slots"][slot] = val - - decoder_input_ids = ( - self.prompt.encode_dialog(turns=turns)["context_ids"] - .unsqueeze(0) - .repeat(batch_size, 1) - .to(trcfg._internal.device) - ) - - return dict( - log_probs=log_probs, - encoded_lengths=encoded_len, - encoder_states=enc_states, - encoder_mask=enc_mask, - decoder_input_ids=decoder_input_ids, - batch=batch, - ) - - def _transcribe_output_processing(self, outputs, trcfg: MultiTaskTranscriptionConfig) -> GenericTranscriptionType: - """ - Internal function to process the model's outputs to return the results to the user. This function is called by - `transcribe()` and `transcribe_generator()` to process the model's outputs. - If parallel chunking was used (enable_chunking=True), merges the hypotheses from each chunk - into a single hypothesis, joining text, token sequences, and timestamps. - - Args: - outputs: The model's outputs that are processed by `_transcribe_forward()`. - trcfg: The transcription config dataclass. Subclasses can change this to a different dataclass if needed. - - Returns: - The output can be a list of - objects, list of list of objects. - Its type is defined in `TranscriptionReturnType`. - - """ - log_probs = outputs.pop('log_probs') - encoded_len = outputs.pop('encoded_lengths') - enc_states = outputs.pop('encoder_states') - enc_mask = outputs.pop('encoder_mask') - decoder_input_ids = outputs.pop('decoder_input_ids') - batch = outputs.pop('batch') - - del log_probs - num_chunks = enc_states.shape[0] - # Repear decoder_input_ids to match number of chunks - if trcfg.enable_chunking and num_chunks > decoder_input_ids.shape[0]: - decoder_input_ids = decoder_input_ids.repeat(num_chunks, 1) - hypotheses = self.decoding.decode_predictions_tensor( - encoder_hidden_states=enc_states, - encoder_input_mask=enc_mask, - decoder_input_ids=decoder_input_ids, - return_hypotheses=trcfg.return_hypotheses, - ) - merge_to_be_done = trcfg.enable_chunking and len(hypotheses) > 1 - - del enc_states, enc_mask, decoder_input_ids - - # Determine the cut id to inject into hypotheses for chunking - if trcfg.enable_chunking or trcfg.timestamps: - if isinstance(batch, PromptedAudioToTextMiniBatch): - cut_id = batch.cuts[0].id - audio = batch.audio - audio_lens = batch.audio_lens - else: # TensorDataset / external DataLoader tuple type batch - cut_id = 'audio_0' - audio = batch[0] - audio_lens = batch[1] - - if trcfg.timestamps and self.timestamps_asr_model is not None: - hypotheses = get_forced_aligned_timestamps_with_external_model( - audio=[audio.squeeze()[:audio_len] for audio, audio_len in zip(audio, audio_lens)], - batch_size=len(audio), - external_ctc_model=self.timestamps_asr_model, - main_model_predictions=hypotheses, - timestamp_type='char' if merge_to_be_done else ['word', 'segment'], - viterbi_device=trcfg._internal.device, - verbose=trcfg.verbose, - ) - elif trcfg.timestamps: - hypotheses = process_aed_timestamp_outputs( - hypotheses, self.encoder.subsampling_factor, self.cfg['preprocessor']['window_stride'] - ) - - if merge_to_be_done and self.timestamps_asr_model is not None: - merged_hypotheses = merge_parallel_chunks( - hypotheses=hypotheses, - encoded_len=encoded_len, - model=self, - timestamps=trcfg.timestamps, - subsampling_factor=self.encoder.subsampling_factor, - window_stride=self.cfg['preprocessor']['window_stride'], - decoding=self.decoding, - ) - # Inject the id of the cut to hypothese to later be used for separate batches - setattr(merged_hypotheses, 'id', cut_id) - return [merged_hypotheses] - - if trcfg.enable_chunking: - for hyp in hypotheses: - setattr(hyp, 'id', cut_id) - return hypotheses - - def _setup_transcribe_dataloader(self, config: Dict) -> 'torch.utils.data.DataLoader': - """ - Setup function for a temporary data loader which wraps the provided audio file. - Args: - config: A python dictionary which contains keys such as: - paths2audio_files: (a list) of paths to audio files. The files should be relatively short fragments. \ - Recommended length per file is between 5 and 25 seconds. - batch_size: (int) batch size to use during inference. \ - Bigger will result in better throughput performance but would use more memory. - temp_dir: (str) A temporary directory where the audio manifest is temporarily - stored. - Returns: - A pytorch DataLoader for the given audio file(s). - - """ - if 'manifest_filepath' in config: - manifest_filepath = config['manifest_filepath'] - batch_size = config['batch_size'] - else: - # when using a list of audio files instead of a manifest (added from TranscrptionMixin) - manifest_filepath = os.path.join(config['temp_dir'], 'manifest.json') - batch_size = min(config['batch_size'], len(config['paths2audio_files'])) - enable_chunking = config.get('enable_chunking', False) and self.timestamps_asr_model is not None - dl_config = { - 'manifest_filepath': manifest_filepath, - 'sample_rate': self.preprocessor._sample_rate, - 'batch_size': batch_size, - 'trim_silence': False, - 'shuffle': False, - 'num_workers': config.get('num_workers', min(batch_size, os.cpu_count() - 1)), - 'pin_memory': True, - 'use_lhotse': config.get('use_lhotse', True), - 'use_bucketing': False, - 'drop_last': False, - 'text_field': config.get('text_field', 'answer'), - 'lang_field': config.get('lang_field', 'target_lang'), - 'channel_selector': config.get('channel_selector', None), - 'pad_min_duration': config.get('pad_min_duration', 1.0), - 'pad_direction': config.get('pad_direction', 'both'), - 'enable_chunking': enable_chunking, - } - - temporary_datalayer = self._setup_dataloader_from_config(config=DictConfig(dl_config)) - return temporary_datalayer - - def _transcribe_on_end(self, trcfg: MultiTaskTranscriptionConfig): - """ - Internal function to teardown the model after transcription. Perform all teardown and post-checks here. - - Args: - trcfg: The transcription config dataclass. Subclasses can change this to a different dataclass if needed. - """ - super()._transcribe_on_end(trcfg) - - self.transf_decoder.unfreeze(partial=True) - - def _may_be_make_dict_and_fix_paths(self, json_items, manifest_path, trcfg: MultiTaskTranscriptionConfig): - """ - Utility method to convert a list of strings to a list of dictionaries. - - Args: - json_items: A list of strings or dictionaries. - manifest_path: A path to a manifest file. - trcfg: The transcription config dataclass. Subclasses can change this to a different dataclass if needed. - - Returns: - A list of dictionaries with the audio file paths fixed. - """ - # This method is a legacy helper for Canary that checks whether prompt slot values were provided - # in the input manifest and if not, it injects the defaults. - out_json_items = [] - timestamps_required = False - for item in json_items: - if isinstance(item, str): - # assume it is a path to audio file - entry = { - 'audio_filepath': item, - 'duration': 100000, - } - elif isinstance(item, dict): - entry = item - entry['audio_filepath'] = get_full_path(entry['audio_filepath'], manifest_file=manifest_path) - else: - raise ValueError(f"Expected str or dict, got {type(item)}") - default_turn = [t for t in trcfg.prompt if t["role"] == "user"] - default_turn = default_turn[0]["slots"] if default_turn else {} - - # check for prompt format - if self.prompt_format == 'canary': - if 'timestamp' in default_turn and default_turn['timestamp']: - raise ValueError( - "Timestamp feature is not supported in Canary prompt format. Please use latest canary-1b-flash or canary-180m-flash" - ) - if 'context' in default_turn and default_turn['context']: - raise ValueError( - "Context feature is not supported in Canary prompt format. Please use latest canary-1b-flash or canary-180m-flash" - ) - - for k, dv in ( - ("source_lang", "en"), - ("target_lang", "en"), - ("taskname", "asr"), - ("pnc", "yes"), - ("context", ""), - ("timestamp", 'notimestamp'), - ): - if k not in entry: - # last-chance fallback injecting legacy Canary defaults if none were provided. - entry[k] = default_turn.get(k, dv) - if k == "timestamp": - if ( - str(entry[k]).lower() not in ['notimestamp', "no", "false", "0"] - and self.timestamps_asr_model is not None - ): - timestamps_required = True - entry[k] = 'notimestamp' - out_json_items.append(entry) - - if timestamps_required: - trcfg.timestamps = True - logging.warning( - "Timestamps are enabled for at least one of the input items. " - "Setting timestamps to True for all the input items, as the current model is using external ASR model for alignment." - ) - return out_json_items - - @classmethod - def get_transcribe_config(cls) -> MultiTaskTranscriptionConfig: - """ - Utility method that returns the default config for transcribe() function. - - Returns: - A dataclass - """ - return MultiTaskTranscriptionConfig() - - def predict_step( - self, - batch: PromptedAudioToTextMiniBatch, - batch_idx=0, - dataloader_idx=0, - has_processed_signal=False, - timestamps=False, - ): - if has_processed_signal: - processed_signal = batch.audio - processed_signal_length = batch.audio_lens - signal = None - signal_len = None - else: - processed_signal = None - processed_signal_length = None - signal = batch.audio - signal_len = batch.audio_lens - - _, _, enc_states, enc_mask = self.forward( - input_signal=signal, - input_signal_length=signal_len, - processed_signal=processed_signal, - processed_signal_length=processed_signal_length, - ) - - hypotheses = self.decoding.decode_predictions_tensor( - encoder_hidden_states=enc_states, - encoder_input_mask=enc_mask, - decoder_input_ids=batch.prompt, - return_hypotheses=False, - ) - - if timestamps and self.timestamps_asr_model is None: - hypotheses = process_aed_timestamp_outputs( - hypotheses, self.encoder.subsampling_factor, self.cfg['preprocessor']['window_stride'] - ) - - if batch.cuts: - return list(zip(batch.cuts, hypotheses)) - else: - return hypotheses - - @property - def adapter_module_names(self) -> List[str]: - return ['', 'encoder', 'transf_encoder', 'transf_decoder'] - - @property - def oomptimizer_schema(self) -> dict: - """ - Return a typing schema for optimal batch size calibration for various - sequence lengths using OOMptimizer. - """ - return { - "cls": PromptedAudioToTextMiniBatch, - "inputs": [ - {"name": "audio", "type": NeuralType(("B", "T"), AudioSignal()), "seq_length": "input"}, - {"name": "audio_lens", "type": NeuralType(("B",), LengthsType()), "seq_length": "input"}, - { - "name": "prompted_transcript", - "type": NeuralType(("B", "T"), LabelsType()), - "seq_length": "output", - "vocab_size": self.tokenizer.vocab_size, - }, - { - "name": "prompted_transcript_lens", - "type": NeuralType(("B",), LengthsType()), - "seq_length": "output", - }, - {"name": "transcript", "type": "dummy"}, - {"name": "transcript_lens", "type": "dummy"}, - {"name": "prompt", "type": "dummy"}, - {"name": "prompt_lens", "type": "dummy"}, - ], - } - - def __restore_timestamps_asr_model(self): - """ - This method is used to restore the external timestamp ASR model that will be used for forced alignment in `.transcribe()`. - The config and weights are expected to be in the main .nemo file and be named `timestamps_asr_model_config.yaml` and `timestamps_asr_model_weights.ckpt` respectively. - """ - app_state = AppState() - nemo_file_folder = app_state.nemo_file_folder # Already-extracted temp directory - model_restore_path = app_state.model_restore_path - - if not model_restore_path: - return None - - save_restore_connector = SaveRestoreConnector() - save_restore_connector.model_config_yaml = os.path.join(nemo_file_folder, "timestamps_asr_model_config.yaml") - save_restore_connector.model_weights_ckpt = os.path.join(nemo_file_folder, "timestamps_asr_model_weights.ckpt") - - # Check if the model_restore_path is already an extracted directory (which happens during restore_from) - # If so, use it directly to avoid double extraction - if app_state.nemo_file_folder and os.path.isdir(app_state.nemo_file_folder): - # Verify that the timestamp model components exist in the extracted folder - config_exists = os.path.exists(save_restore_connector.model_config_yaml) - weights_exists = os.path.exists(save_restore_connector.model_weights_ckpt) - - if not (config_exists and weights_exists): - return None - - save_restore_connector.model_extracted_dir = app_state.nemo_file_folder - - else: - filter_fn = lambda name: "timestamps_asr_model" in name - members = save_restore_connector._filtered_tar_info(model_restore_path, filter_fn=filter_fn) - - if not members: - return None - - try: - save_restore_connector.model_config_yaml = "timestamps_asr_model_config.yaml" - save_restore_connector.model_weights_ckpt = "timestamps_asr_model_weights.ckpt" - external_timestamps_model = ASRModel.restore_from( - model_restore_path, save_restore_connector=save_restore_connector - ) - external_timestamps_model.eval() - - except Exception as e: - raise RuntimeError( - f"Error restoring external timestamps ASR model with timestamps_asr_model_config.yaml and timestamps_asr_model_weights.ckpt: {e}" - ) - - return external_timestamps_model - - -def parse_multitask_prompt(prompt: dict | None) -> list[dict]: - if prompt is None or not prompt: - return [] - - # Case 1. - # Multi-turn prompting format. This format conforms to PromptFormatter API and needs no further modification. - # This format allows to condition the model on chat history, system+user prompts, etc. - # Example: - # model.transcribe( - # audio, - # turns=[ - # dict( - # role="user", - # slots=dict( - # source_lang='en', target_lang='de', task='asr', pnc=True, context='translate this text' - # ), - # ), - # dict( - # role="assistant", - # slots=dict(message="Calculating the translation of given text. Do you want to proceed?"), - # ), - # dict( - # role="user", - # slots=dict( - # source_lang='en', target_lang='de', task='asr', pnc=True, context='Yes, please proceed.' - # ), - # ), - # ], - # ) - if 'turns' in prompt: - if not ( - len(prompt) == 1 - and isinstance(prompt["turns"], list) - and all(isinstance(t, dict) and "role" in t and "slots" in t for t in prompt["turns"]) - ): - raise ValueError( - f"When providing a multi-turn prompt through 'turns', no other keys are allowed " - f"and the value under prompt['turns'] must be a list of dicts with roles and slot values " - f"(we received {prompt=})" - ) - return prompt["turns"] - - values_are_dicts = any(isinstance(v, dict) for k, v in prompt.items() if k != "slots") - if values_are_dicts: - raise ValueError(f"We don't support dict values for prompt keys other than 'slots'. " f"We received {prompt=}") - - # Case 2. - # Single-turn prompting format with explicitly provided role and slot names and values. - # We create a 1-item multi-turn prompt from this input. - # Example: - # model.transcribe( - # audio, - # role="user", - # slots=dict(source_lang='en', target_lang='de', task='asr', pnc=True, context='translate this text'), - # ) - if "role" in prompt and "slots" in prompt: - if not isinstance(prompt["slots"], dict): - raise ValueError( - f"When providing a single-turn prompt through 'role', 'slots' must also be provided " - f"as a dict (we received {prompt=})." - ) - return [prompt] - - # Case 3. - # Legacy prompting format for Canary-1B preserved for backward compatibility. - # Extra fields are converted to a single-turn prompt with role "user" (unless overridden with 'role'). - # Example: - # model.transcribe( - # audio, pnc=True, source_lang='en', target_lang='de', task='asr', context='translate this text' - # ) - role = prompt.pop("role", "user") - return [dict(role=role, slots=prompt)] diff --git a/nemo/collections/asr/models/asr_eou_models.py b/nemo/collections/asr/models/asr_eou_models.py deleted file mode 100644 index 4cb0b8f6076cdad52e8db1195e7316d5cf77c1d6..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/asr_eou_models.py +++ /dev/null @@ -1,967 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from dataclasses import dataclass -from pathlib import Path -from typing import Any, Dict, List, Optional, Tuple - -import numpy as np -import torch -from lightning.pytorch import Trainer -from lightning.pytorch.utilities import rank_zero_only -from omegaconf import DictConfig, OmegaConf, open_dict - -from nemo.collections.asr.data.audio_to_eou_label_lhotse import ( - EOB_LABEL, - EOB_STRING, - EOU_LABEL, - EOU_STRING, - AudioToTextEOUBatch, - LhotseSpeechToTextBpeEOUDataset, -) -from nemo.collections.asr.metrics.wer import WER -from nemo.collections.asr.models import EncDecHybridRNNTCTCBPEModel, EncDecRNNTBPEModel -from nemo.collections.asr.parts.mixins import TranscribeConfig -from nemo.collections.asr.parts.utils.eou_utils import ( - EOUResult, - cal_eou_metrics_from_frame_labels, - flatten_nested_list, -) -from nemo.collections.asr.parts.utils.manifest_utils import write_manifest -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis -from nemo.collections.common.data.lhotse import get_lhotse_dataloader_from_config -from nemo.collections.common.data.utils import move_data_to_device -from nemo.core.classes.mixins import AccessMixin -from nemo.core.neural_types import AudioSignal, LabelsType, LengthsType, NeuralType -from nemo.utils import logging - -__all__ = ['EncDecRNNTBPEEOUModel', 'EncDecHybridRNNTCTCBPEEOUModel'] - - -@dataclass -class EOUPrediction: - eou_probs: Optional[List[float]] = None - eob_probs: Optional[List[float]] = None - eou_preds: Optional[List[bool]] = None - eob_preds: Optional[List[bool]] = None - - -class ASREOUModelMixin: - def __init__(self): - if not hasattr(self, 'tokenizer'): - self.tokenizer = None - if not hasattr(self, 'eou_token'): - self.eou_token = None - if not hasattr(self, 'eob_token'): - self.eob_token = None - if not hasattr(self, 'frame_len_in_secs'): - self.frame_len_in_secs = None - - def setup_eou_mixin(self, eou_token: int, eob_token: int, frame_len_in_secs: float, tokenizer): - if getattr(self, 'eou_token', None) is None: - self.eou_token = eou_token - if getattr(self, 'eob_token', None) is None: - self.eob_token = eob_token - if getattr(self, 'frame_len_in_secs', None) is None: - self.frame_len_in_secs = frame_len_in_secs - if getattr(self, 'tokenizer', None) is None: - self.tokenizer = tokenizer - - def _patch_decoding_cfg(self, cfg: DictConfig): - """ - Patch the decoding config as needed for EOU computation - """ - with open_dict(cfg): - cfg.decoding.preserve_alignments = True - cfg.decoding.compute_timestamps = True - - def transfer_batch_to_device(self, batch: Any, device: torch.device, dataloader_idx: int) -> Any: - """ - PTL hook: https://pytorch-lightning.readthedocs.io/en/latest/common/lightning_module.html#transfer-batch-to-device - """ - batch = move_data_to_device(batch, device) - return batch - - def _get_text_from_tokens(self, tokens: torch.Tensor, tokens_len: Optional[torch.Tensor] = None) -> List[str]: - """ - Convert tokens to text. - Args: - tokens: tensor of tokens - Returns: - text: list of text - """ - text_list = [] - for i in range(len(tokens)): - tokens_i = tokens[i] - if tokens_len is not None: - tokens_i = tokens[i][: tokens_len[i]] - tokens_i = [int(x) for x in tokens_i if x < self.tokenizer.vocab_size] - text = self.tokenizer.ids_to_text(tokens_i) - text_list.append(text) - return text_list - - def _get_eou_predictions_from_hypotheses( - self, hypotheses: List[Hypothesis], batch: AudioToTextEOUBatch - ) -> List[EOUPrediction]: - """ - Get EOU predictions from the hypotheses. - Args: - hypotheses: batch of hypotheses - Returns: - eou_predictions: list of EOU predictions - """ - eou_predictions = [] - - for hyp in hypotheses: - # Process one hypothesis at a time - eou_probs = [] - eob_probs = [] - eou_preds = [] - eob_preds = [] - if isinstance(hyp.alignments, tuple): - # CTC - probs = torch.softmax(hyp.alignments[0], dim=-1) # [time, num_classes] - tokens = hyp.alignments[1] - eou_probs = probs[:, self.eou_token].tolist() - eob_probs = probs[:, self.eob_token].tolist() - eou_preds = [int(x) == self.eou_token for x in tokens] - eob_preds = [int(x) == self.eob_token for x in tokens] - else: - # RNNT, each timestamp has a list of (prob, token) tuples - for alignment in hyp.alignments: - # Process for each timestamp - probs = torch.softmax(torch.stack([a[0] for a in alignment], dim=0), dim=-1) # unfold RNNT preds - tokens = torch.stack([a[1] for a in alignment], dim=0) # unfold RNNT preds - - # Get the max prob for eou and eob - # and check if eou and eob are predicted - max_eou_prob = probs[:, self.eou_token].max().item() - max_eob_prob = probs[:, self.eob_token].max().item() - eou_pred = torch.any(tokens == self.eou_token).item() - eob_pred = torch.any(tokens == self.eob_token).item() - - eou_probs.append(max_eou_prob) - eob_probs.append(max_eob_prob) - eou_preds.append(eou_pred) - eob_preds.append(eob_pred) - - eou_predictions.append( - EOUPrediction( - eou_probs=eou_probs, - eob_probs=eob_probs, - eou_preds=eou_preds, - eob_preds=eob_preds, - ) - ) - - return eou_predictions - - def _pad_to_same_length(self, eou_labels: List[float], eou_preds: List[float]) -> Tuple[List[float], List[float]]: - """ - Pad the EOU labels and predictions to the same length. - Args: - eou_labels: list of EOU labels - eou_preds: list of EOU predictions - Returns: - eou_labels: list of EOU labels, padded to the same length - eou_preds: list of EOU predictions, padded to the same length - """ - if len(eou_labels) < len(eou_preds): - eou_labels = eou_labels + [0] * (len(eou_preds) - len(eou_labels)) - elif len(eou_labels) > len(eou_preds): - eou_preds = eou_preds + [0] * (len(eou_labels) - len(eou_preds)) - return eou_labels, eou_preds - - def _calculate_eou_metrics( - self, eou_predictions: List[EOUPrediction], batch: AudioToTextEOUBatch - ) -> Tuple[List[EOUResult], List[EOUResult]]: - """ - Calculate EOU metrics. - Args: - eou_predictions: list of EOU predictions - batch: batch of data - Returns: - eou_metrics_list: list of EOU metrics, each is of type EOUResult - eob_metrics_list: list of EOB metrics, each is of type EOUResult - """ - # Get the ground truth EOU labels - eou_labels = batch.eou_targets - eou_labels_len = batch.eou_target_lengths - - # Calculate EOU metrics - eou_metrics_list = [] - eob_metrics_list = [] - for i, eou_prediction in enumerate(eou_predictions): - eou_preds_i = [float(x) for x in eou_prediction.eou_preds] - eob_preds_i = [float(x) for x in eou_prediction.eob_preds] - - eou_labels_i = (eou_labels[i][: eou_labels_len[i]] == EOU_LABEL).float().tolist() - eob_labels_i = (eou_labels[i][: eou_labels_len[i]] == EOB_LABEL).float().tolist() - - # Pad the EOU labels and predictions to the same length with zeros - eou_labels_i, eou_preds_i = self._pad_to_same_length(eou_labels_i, eou_preds_i) - eob_labels_i, eob_preds_i = self._pad_to_same_length(eob_labels_i, eob_preds_i) - - # Calculate EOU metrics - eou_metrics: EOUResult = cal_eou_metrics_from_frame_labels( - prediction=eou_preds_i, - reference=eou_labels_i, - threshold=0.0, - collar=0.0, - frame_len_in_secs=self.frame_len_in_secs, - ) - - eob_metrics = cal_eou_metrics_from_frame_labels( - prediction=eob_preds_i, - reference=eob_labels_i, - threshold=0.0, - collar=0.0, - frame_len_in_secs=self.frame_len_in_secs, - ) - - eou_metrics_list.append(eou_metrics) - eob_metrics_list.append(eob_metrics) - - return eou_metrics_list, eob_metrics_list - - def _get_percentiles(self, values: List[float], percentiles: List[float], tag: str = "") -> Dict[str, float]: - """ - Get the percentiles of a list of values. - Args: - values: list of values - percentiles: list of percentiles - Returns: - metrics: Dict of percentiles - """ - if len(values) == 0: - return [0.0] * len(percentiles) - results = np.percentile(values, percentiles).tolist() - metrics = {} - if tag: - tag += "_" - for i, p in enumerate(percentiles): - metrics[f'{tag}p{int(p)}'] = float(results[i]) - return metrics - - def _aggregate_eou_metrics(self, outputs: List[dict], mode: str, is_ctc: bool = False): - if f'{mode}_eou_metrics' not in outputs[0] and not is_ctc: - return {} - if f'{mode}_eou_metrics_ctc' not in outputs[0] and is_ctc: - return {} - - # Aggregate EOU/EOB metrics - eou_metrics: List[EOUResult] = [] - eob_metrics: List[EOUResult] = [] - for x in outputs: - if is_ctc: - eou_metrics.extend(x[f'{mode}_eou_metrics_ctc']) - eob_metrics.extend(x[f'{mode}_eob_metrics_ctc']) - else: - eou_metrics.extend(x[f'{mode}_eou_metrics']) - eob_metrics.extend(x[f'{mode}_eob_metrics']) - num_eou_utterances = sum([x.num_utterances for x in eou_metrics]) - eou_latency = flatten_nested_list([x.latency for x in eou_metrics]) - eou_early_cutoff = flatten_nested_list([x.early_cutoff for x in eou_metrics]) - - num_eob_utterances = sum([x.num_utterances for x in eob_metrics]) - eob_latency = flatten_nested_list([x.latency for x in eob_metrics]) - eob_early_cutoff = flatten_nested_list([x.early_cutoff for x in eob_metrics]) - - eou_avg_num_early_cutoff = len(eou_early_cutoff) / num_eou_utterances if num_eou_utterances > 0 else 0.0 - eob_avg_num_early_cutoff = len(eob_early_cutoff) / num_eob_utterances if num_eob_utterances > 0 else 0.0 - if len(eou_latency) == 0: - eou_latency = [0.0] - if len(eou_early_cutoff) == 0: - eou_early_cutoff = [0.0] - if len(eob_latency) == 0: - eob_latency = [0.0] - if len(eob_early_cutoff) == 0: - eob_early_cutoff = [0.0] - - eou_missing = [x.missing for x in eou_metrics] - eob_missing = [x.missing for x in eob_metrics] - - tensorboard_logs = {} - target_percentiles = [50, 90, 95] - eou_latency_metrics = self._get_percentiles(eou_latency, target_percentiles, tag=f'{mode}_eou_latency') - eou_early_cutoff_metrics = self._get_percentiles( - eou_early_cutoff, target_percentiles, tag=f'{mode}_eou_early_cutoff' - ) - eob_latency_metrics = self._get_percentiles(eob_latency, target_percentiles, tag=f'{mode}_eob_latency') - eob_early_cutoff_metrics = self._get_percentiles( - eob_early_cutoff, target_percentiles, tag=f'{mode}_eob_early_cutoff' - ) - - tensorboard_logs.update(eou_latency_metrics) - tensorboard_logs.update(eou_early_cutoff_metrics) - tensorboard_logs.update(eob_latency_metrics) - tensorboard_logs.update(eob_early_cutoff_metrics) - - tensorboard_logs[f'{mode}_eou_early_cutoff_avg_num'] = eou_avg_num_early_cutoff - tensorboard_logs[f'{mode}_eob_early_cutoff_avg_num'] = eob_avg_num_early_cutoff - - tensorboard_logs[f'{mode}_eou_missing'] = ( - sum(eou_missing) / num_eou_utterances if num_eou_utterances > 0 else 0.0 - ) - tensorboard_logs[f'{mode}_eob_missing'] = ( - sum(eob_missing) / num_eob_utterances if num_eob_utterances > 0 else 0.0 - ) - - return tensorboard_logs - - @rank_zero_only - def _maybe_save_predictions( - self, outputs: List[Dict], mode: str = "val", dataloader_idx: int = 0 - ) -> Optional[Path]: - """ - Save predictions to disk. - Args: - outputs: list of outputs - mode: mode of the model, either 'val' or 'test' - Returns: - Path object if predictions are saved, None otherwise. - """ - - if not self.cfg.get('save_pred_to_file', None): - return None - - output_file = Path(self.cfg.save_pred_to_file) - output_file.parent.mkdir(parents=True, exist_ok=True) - - if getattr(self, '_validation_names', None): - output_file = output_file.with_name(f"{self._validation_names[dataloader_idx]}_{output_file.name}") - else: - output_file = output_file.with_suffix(f'.{dataloader_idx}.json') - - manifest = [] - for output in outputs: - for i in range(len(output[f'{mode}_sample_id'])): - item = { - "sample_id": output[f'{mode}_sample_id'][i], - "audio_filepath": output[f'{mode}_audio_filepath'][i], - "eou_text": output[f'{mode}_text_gt'][i], - "eou_pred_text": output[f'{mode}_text_pred'][i], - "is_backchannel": bool(str(output[f'{mode}_text_gt'][i]).endswith(EOB_STRING)), - } - if f"{mode}_text_pred_ctc" in output: - item["eou_pred_text_ctc"] = output[f"{mode}_text_pred_ctc"][i] - - eou_metrics = {f"eou_{k}": v for k, v in output[f"{mode}_eou_metrics"][i].to_dict().items()} - eob_metrics = {f"eob_{k}": v for k, v in output[f"{mode}_eob_metrics"][i].to_dict().items()} - item.update(eou_metrics) - item.update(eob_metrics) - manifest.append(item) - write_manifest(output_file, manifest) - logging.info(f"Predictions saved to {output_file}") - return output_file - - -class EncDecRNNTBPEEOUModel(EncDecRNNTBPEModel, ASREOUModelMixin): - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - - self._patch_decoding_cfg(cfg) - super().__init__(cfg=cfg, trainer=trainer) - - self.eou_token = self.tokenizer.token_to_id(EOU_STRING) - self.eob_token = self.tokenizer.token_to_id(EOB_STRING) - self.frame_len_in_secs = self.cfg.preprocessor.window_stride * self.cfg.encoder.subsampling_factor - - self.setup_eou_mixin(self.eou_token, self.eob_token, self.frame_len_in_secs, self.tokenizer) - - self.wer = WER( - decoding=self.decoding, - batch_dim_index=0, - use_cer=self._cfg.get('use_cer', False), - log_prediction=self._cfg.get('log_prediction', True), - dist_sync_on_step=True, - return_hypotheses=True, - ) - - # Setup fused Joint step if flag is set - if self.joint.fuse_loss_wer: - self.joint.set_loss(self.loss) - self.joint.set_wer(self.wer) - - def _setup_dataloader_from_config(self, config: Optional[Dict]): - cfg = OmegaConf.create(config) if not isinstance(config, DictConfig) else config - dataset = LhotseSpeechToTextBpeEOUDataset( - cfg=cfg, tokenizer=self.tokenizer, return_cuts=config.get("do_transcribe", False) - ) - return get_lhotse_dataloader_from_config( - config, - # During transcription, the model is initially loaded on the CPU. - # To ensure the correct global_rank and world_size are set, - # these values must be passed from the configuration. - global_rank=self.global_rank if not config.get("do_transcribe", False) else config.get("global_rank"), - world_size=self.world_size if not config.get("do_transcribe", False) else config.get("world_size"), - dataset=dataset, - tokenizer=self.tokenizer, - ) - - def _transcribe_forward(self, batch: Any, trcfg: TranscribeConfig): - if isinstance(batch, AudioToTextEOUBatch): - signal = batch.audio_signal - signal_len = batch.audio_lengths - else: - signal = batch[0] - signal_len = batch[1] - encoded, encoded_len = self.forward(input_signal=signal, input_signal_length=signal_len) - output = dict(encoded=encoded, encoded_len=encoded_len) - return output - - def training_step(self, batch: AudioToTextEOUBatch, batch_nb): - # Reset access registry - if AccessMixin.is_access_enabled(self.model_guid): - AccessMixin.reset_registry(self) - - signal = batch.audio_signal - signal_len = batch.audio_lengths - transcript = batch.text_tokens - transcript_len = batch.text_token_lengths - - # forward() only performs encoder forward - encoded, encoded_len = self.forward(input_signal=signal, input_signal_length=signal_len) - del signal - - # During training, loss must be computed, so decoder forward is necessary - decoder, target_length, states = self.decoder(targets=transcript, target_length=transcript_len) - - if hasattr(self, '_trainer') and self._trainer is not None: - log_every_n_steps = self._trainer.log_every_n_steps - sample_id = self._trainer.global_step - else: - log_every_n_steps = 1 - sample_id = batch_nb - - # If experimental fused Joint-Loss-WER is not used - if not self.joint.fuse_loss_wer: - # Compute full joint and loss - joint = self.joint(encoder_outputs=encoded, decoder_outputs=decoder) - loss_value = self.loss( - log_probs=joint, targets=transcript, input_lengths=encoded_len, target_lengths=target_length - ) - - # Add auxiliary losses, if registered - loss_value = self.add_auxiliary_losses(loss_value) - - # Reset access registry - if AccessMixin.is_access_enabled(self.model_guid): - AccessMixin.reset_registry(self) - - tensorboard_logs = { - 'train_loss': loss_value, - 'learning_rate': self._optimizer.param_groups[0]['lr'], - 'global_step': torch.tensor(self.trainer.global_step, dtype=torch.float32), - } - - if (sample_id + 1) % log_every_n_steps == 0: - self.wer.update( - predictions=encoded, - predictions_lengths=encoded_len, - targets=transcript, - targets_lengths=transcript_len, - ) - _, scores, words = self.wer.compute() - self.wer.reset() - tensorboard_logs.update({'training_batch_wer': scores.float() / words}) - - else: - # If experimental fused Joint-Loss-WER is used - if (sample_id + 1) % log_every_n_steps == 0: - compute_wer = True - else: - compute_wer = False - - # Fused joint step - loss_value, wer, _, _ = self.joint( - encoder_outputs=encoded, - decoder_outputs=decoder, - encoder_lengths=encoded_len, - transcripts=transcript, - transcript_lengths=transcript_len, - compute_wer=compute_wer, - ) - - # Add auxiliary losses, if registered - loss_value = self.add_auxiliary_losses(loss_value) - - # Reset access registry - if AccessMixin.is_access_enabled(self.model_guid): - AccessMixin.reset_registry(self) - - tensorboard_logs = { - 'train_loss': loss_value, - 'learning_rate': self._optimizer.param_groups[0]['lr'], - 'global_step': torch.tensor(self.trainer.global_step, dtype=torch.float32), - } - - if compute_wer: - tensorboard_logs.update({'training_batch_wer': wer}) - - # Log items - self.log_dict(tensorboard_logs) - - # Preserve batch acoustic model T and language model U parameters if normalizing - if self._optim_normalize_joint_txu: - self._optim_normalize_txu = [encoded_len.max(), transcript_len.max()] - - return {'loss': loss_value} - - def predict_step(self, batch: AudioToTextEOUBatch, batch_idx, dataloader_idx=0): - signal = batch.audio_signal - signal_len = batch.audio_lengths - - # forward() only performs encoder forward - encoded, encoded_len = self.forward(input_signal=signal, input_signal_length=signal_len) - del signal - - best_hyp_text = self.decoding.rnnt_decoder_predictions_tensor( - encoder_output=encoded, encoded_lengths=encoded_len, return_hypotheses=False - ) - - return list(best_hyp_text) - - def validation_pass(self, batch: AudioToTextEOUBatch, batch_idx: int, dataloader_idx: int = 0): - signal = batch.audio_signal - signal_len = batch.audio_lengths - transcript = batch.text_tokens - transcript_len = batch.text_token_lengths - - # forward() only performs encoder forward - encoded, encoded_len = self.forward(input_signal=signal, input_signal_length=signal_len) - del signal - - tensorboard_logs = {} - - if self.cfg.get('save_pred_to_file', None): - text_gt = self._get_text_from_tokens(transcript, transcript_len) - tensorboard_logs['val_sample_id'] = batch.sample_ids - tensorboard_logs['val_audio_filepath'] = batch.audio_filepaths - tensorboard_logs['val_text_gt'] = text_gt - # If experimental fused Joint-Loss-WER is not used - if not self.joint.fuse_loss_wer: - if self.compute_eval_loss: - decoder, target_length, states = self.decoder(targets=transcript, target_length=transcript_len) - joint = self.joint(encoder_outputs=encoded, decoder_outputs=decoder) - - loss_value = self.loss( - log_probs=joint, targets=transcript, input_lengths=encoded_len, target_lengths=target_length - ) - - tensorboard_logs['val_loss'] = loss_value - - self.wer.update( - predictions=encoded, - predictions_lengths=encoded_len, - targets=transcript, - targets_lengths=transcript_len, - ) - hypotheses = self.wer.get_hypotheses() - - if self.cfg.get('save_pred_to_file', None): - text_pred = self._get_text_from_tokens([x.y_sequence for x in hypotheses]) - tensorboard_logs['val_text_pred'] = text_pred - - if self.cfg.get('calculate_eou_metrics', True): - eou_predictions = self._get_eou_predictions_from_hypotheses(hypotheses, batch) - eou_metrics_list, eob_metrics_list = self._calculate_eou_metrics(eou_predictions, batch) - else: - eou_metrics_list = [] - eob_metrics_list = [] - - wer, wer_num, wer_denom = self.wer.compute() - self.wer.reset() - - tensorboard_logs['val_wer_num'] = wer_num - tensorboard_logs['val_wer_denom'] = wer_denom - tensorboard_logs['val_wer'] = wer - tensorboard_logs['val_eou_metrics'] = eou_metrics_list - tensorboard_logs['val_eob_metrics'] = eob_metrics_list - - else: - # If experimental fused Joint-Loss-WER is used - compute_wer = True - - if self.compute_eval_loss: - decoded, target_len, states = self.decoder(targets=transcript, target_length=transcript_len) - else: - decoded = None - target_len = transcript_len - - # Fused joint step - loss_value, wer, wer_num, wer_denom = self.joint( - encoder_outputs=encoded, - decoder_outputs=decoded, - encoder_lengths=encoded_len, - transcripts=transcript, - transcript_lengths=target_len, - compute_wer=compute_wer, - keep_hypotheses=True, - ) - - hypotheses = self.joint.get_hypotheses() - - if self.cfg.get('save_pred_to_file', None): - text_pred = self._get_text_from_tokens([x.y_sequence for x in hypotheses]) - tensorboard_logs['val_text_pred'] = text_pred - - if self.cfg.get('calculate_eou_metrics', True): - eou_predictions = self._get_eou_predictions_from_hypotheses(hypotheses, batch) - eou_metrics_list, eob_metrics_list = self._calculate_eou_metrics(eou_predictions, batch) - else: - eou_metrics_list = [] - eob_metrics_list = [] - - if loss_value is not None: - tensorboard_logs['val_loss'] = loss_value - - tensorboard_logs['val_wer_num'] = wer_num - tensorboard_logs['val_wer_denom'] = wer_denom - tensorboard_logs['val_wer'] = wer - tensorboard_logs['val_eou_metrics'] = eou_metrics_list - tensorboard_logs['val_eob_metrics'] = eob_metrics_list - - self.log('global_step', torch.tensor(self.trainer.global_step, dtype=torch.float32)) - - return tensorboard_logs - - def multi_inference_epoch_end(self, outputs, dataloader_idx: int = 0, mode: str = "val"): - assert mode in ['val', 'test'], f"Invalid mode: {mode}. Must be 'val' or 'test'." - - if not outputs: - logging.warning( - f"No outputs received for {mode} dataloader {dataloader_idx}. Skipping epoch end processing." - ) - return {} - - self._maybe_save_predictions(outputs, mode=mode, dataloader_idx=dataloader_idx) - - # Aggregate WER metrics - if self.compute_eval_loss: - loss_mean = torch.stack([x[f'{mode}_loss'] for x in outputs]).mean() - loss_log = {f'{mode}_loss': loss_mean} - else: - loss_log = {} - wer_num = torch.stack([x[f'{mode}_wer_num'] for x in outputs]).sum() - wer_denom = torch.stack([x[f'{mode}_wer_denom'] for x in outputs]).sum() - tensorboard_logs = {**loss_log, f'{mode}_wer': wer_num.float() / wer_denom} - - eou_metrics = {} - if self.cfg.get('calculate_eou_metrics', True): - eou_metrics = self._aggregate_eou_metrics(outputs, mode=mode) - tensorboard_logs.update(eou_metrics) - - return {**loss_log, 'log': tensorboard_logs} - - def multi_validation_epoch_end(self, outputs, dataloader_idx: int = 0): - return self.multi_inference_epoch_end(outputs, dataloader_idx, mode='val') - - def multi_test_epoch_end(self, outputs, dataloader_idx: int = 0): - return self.multi_inference_epoch_end(outputs, dataloader_idx, mode='test') - - @property - def oomptimizer_schema(self) -> dict: - """ - Return a typing schema for optimal batch size calibration for various - sequence lengths using OOMptimizer. - """ - return { - "cls": AudioToTextEOUBatch, - "inputs": [ - {"type": NeuralType(("B", "T"), AudioSignal()), "seq_length": "input", "name": "audio_signal"}, - {"type": NeuralType(("B",), LengthsType()), "seq_length": "input", "name": "audio_lengths"}, - { - "type": NeuralType(("B", "T"), LabelsType()), - "seq_length": "output", - "name": "text_tokens", - "vocab_size": self.tokenizer.vocab_size, - }, - {"type": NeuralType(("B",), LengthsType()), "seq_length": "output", "name": "text_token_lengths"}, - { - "type": NeuralType(("B", "T"), LabelsType()), - "seq_length": "output", - "name": "eou_targets", - "vocab_size": 4, - }, - {"type": NeuralType(("B",), LengthsType()), "seq_length": "output", "name": "eou_target_lengths"}, - ], - } - - -class EncDecHybridRNNTCTCBPEEOUModel(EncDecHybridRNNTCTCBPEModel, ASREOUModelMixin): - def __init__(self, cfg: DictConfig, trainer): - self._patch_decoding_cfg(cfg) - if cfg.aux_ctc.get('decoding', None) is not None: - with open_dict(cfg): - cfg.aux_ctc.decoding.preserve_alignments = True - cfg.aux_ctc.decoding.compute_timestamps = True - - super().__init__(cfg=cfg, trainer=trainer) - - self.eou_token = self.tokenizer.token_to_id(EOU_STRING) - self.eob_token = self.tokenizer.token_to_id(EOB_STRING) - self.frame_len_in_secs = self.cfg.preprocessor.window_stride * self.cfg.encoder.subsampling_factor - self.setup_eou_mixin(self.eou_token, self.eob_token, self.frame_len_in_secs, self.tokenizer) - - self.wer = WER( - decoding=self.decoding, - batch_dim_index=0, - use_cer=self._cfg.get('use_cer', False), - log_prediction=self._cfg.get('log_prediction', True), - dist_sync_on_step=True, - return_hypotheses=True, - ) - - self.ctc_wer = WER( - decoding=self.ctc_decoding, - use_cer=self.cfg.aux_ctc.get('use_cer', False), - dist_sync_on_step=True, - log_prediction=self.cfg.get("log_prediction", False), - return_hypotheses=True, - ) - - # Setup fused Joint step if flag is set - if self.joint.fuse_loss_wer: - self.joint.set_loss(self.loss) - self.joint.set_wer(self.wer) - - def _setup_dataloader_from_config(self, config: Optional[Dict]): - cfg = OmegaConf.create(config) if not isinstance(config, DictConfig) else config - dataset = LhotseSpeechToTextBpeEOUDataset( - cfg=cfg, tokenizer=self.tokenizer, return_cuts=config.get("do_transcribe", False) - ) - return get_lhotse_dataloader_from_config( - config, - # During transcription, the model is initially loaded on the CPU. - # To ensure the correct global_rank and world_size are set, - # these values must be passed from the configuration. - global_rank=self.global_rank if not config.get("do_transcribe", False) else config.get("global_rank"), - world_size=self.world_size if not config.get("do_transcribe", False) else config.get("world_size"), - dataset=dataset, - tokenizer=self.tokenizer, - ) - - def _transcribe_forward(self, batch: Any, trcfg: TranscribeConfig): - if isinstance(batch, AudioToTextEOUBatch): - signal = batch.audio_signal - signal_len = batch.audio_lengths - else: - signal = batch[0] - signal_len = batch[1] - encoded, encoded_len = self.forward(input_signal=signal, input_signal_length=signal_len) - output = dict(encoded=encoded, encoded_len=encoded_len) - return output - - def training_step(self, batch: AudioToTextEOUBatch, batch_nb): - signal = batch.audio_signal - signal_len = batch.audio_lengths - transcript = batch.text_tokens - transcript_len = batch.text_token_lengths - - new_batch = (signal, signal_len, transcript, transcript_len) - return super().training_step(new_batch, batch_nb) - - def predict_step(self, batch: AudioToTextEOUBatch, batch_idx, dataloader_idx=0): - signal = batch.audio_signal - signal_len = batch.audio_lengths - transcript = batch.text_tokens - transcript_len = batch.text_token_lengths - sample_ids = batch.sample_ids - new_batch = (signal, signal_len, transcript, transcript_len, sample_ids) - return super().predict_step(new_batch, batch_idx, dataloader_idx) - - def validation_pass(self, batch: AudioToTextEOUBatch, batch_idx: int, dataloader_idx: int = 0): - signal = batch.audio_signal - signal_len = batch.audio_lengths - transcript = batch.text_tokens - transcript_len = batch.text_token_lengths - - encoded, encoded_len = self.forward(input_signal=signal, input_signal_length=signal_len) - del signal - - tensorboard_logs = {} - - if self.cfg.get('save_pred_to_file', None): - text_gt = self._get_text_from_tokens(transcript, transcript_len) - tensorboard_logs['val_sample_id'] = batch.sample_ids - tensorboard_logs['val_audio_filepath'] = batch.audio_filepaths - tensorboard_logs['val_text_gt'] = text_gt - - loss_value = None - - # If experimental fused Joint-Loss-WER is not used - if not self.joint.fuse_loss_wer: - if self.compute_eval_loss: - decoder, target_length, states = self.decoder(targets=transcript, target_length=transcript_len) - joint = self.joint(encoder_outputs=encoded, decoder_outputs=decoder) - - loss_value = self.loss( - log_probs=joint, targets=transcript, input_lengths=encoded_len, target_lengths=target_length - ) - tensorboard_logs['val_loss'] = loss_value - - self.wer.update( - predictions=encoded, - predictions_lengths=encoded_len, - targets=transcript, - targets_lengths=transcript_len, - ) - - hypotheses = self.wer.get_hypotheses() - - if self.cfg.get('save_pred_to_file', None): - text_pred = self._get_text_from_tokens([x.y_sequence for x in hypotheses]) - tensorboard_logs['val_text_pred'] = text_pred - - eou_predictions = self._get_eou_predictions_from_hypotheses(hypotheses, batch) - eou_metrics_list, eob_metrics_list = self._calculate_eou_metrics(eou_predictions, batch) - - wer, wer_num, wer_denom = self.wer.compute() - self.wer.reset() - - tensorboard_logs['val_wer_num'] = wer_num - tensorboard_logs['val_wer_denom'] = wer_denom - tensorboard_logs['val_wer'] = wer - tensorboard_logs['val_eou_metrics'] = eou_metrics_list - tensorboard_logs['val_eob_metrics'] = eob_metrics_list - tensorboard_logs['val_text_pred'] = text_pred - - else: - # If experimental fused Joint-Loss-WER is used - compute_wer = True - - if self.compute_eval_loss: - decoded, target_len, states = self.decoder(targets=transcript, target_length=transcript_len) - else: - decoded = None - target_len = transcript_len - - # Fused joint step - loss_value, wer, wer_num, wer_denom = self.joint( - encoder_outputs=encoded, - decoder_outputs=decoded, - encoder_lengths=encoded_len, - transcripts=transcript, - transcript_lengths=target_len, - compute_wer=compute_wer, - keep_hypotheses=True, - ) - hypotheses = self.joint.get_hypotheses() - - if self.cfg.get('save_pred_to_file', None): - text_pred = self._get_text_from_tokens([x.y_sequence for x in hypotheses]) - tensorboard_logs['val_text_pred'] = text_pred - - eou_predictions = self._get_eou_predictions_from_hypotheses(hypotheses, batch) - - eou_metrics_list, eob_metrics_list = self._calculate_eou_metrics(eou_predictions, batch) - - if loss_value is not None: - tensorboard_logs['val_loss'] = loss_value - - tensorboard_logs['val_wer_num'] = wer_num - tensorboard_logs['val_wer_denom'] = wer_denom - tensorboard_logs['val_wer'] = wer - tensorboard_logs['val_eou_metrics'] = eou_metrics_list - tensorboard_logs['val_eob_metrics'] = eob_metrics_list - - log_probs = self.ctc_decoder(encoder_output=encoded) - if self.compute_eval_loss: - ctc_loss = self.ctc_loss( - log_probs=log_probs, targets=transcript, input_lengths=encoded_len, target_lengths=transcript_len - ) - tensorboard_logs['val_ctc_loss'] = ctc_loss - tensorboard_logs['val_rnnt_loss'] = loss_value - loss_value = (1 - self.ctc_loss_weight) * loss_value + self.ctc_loss_weight * ctc_loss - tensorboard_logs['val_loss'] = loss_value - - self.ctc_wer.update( - predictions=log_probs, - targets=transcript, - targets_lengths=transcript_len, - predictions_lengths=encoded_len, - ) - hypotheses_ctc = self.ctc_wer.get_hypotheses() - - if self.cfg.get('save_pred_to_file', None): - text_pred_ctc = self._get_text_from_tokens([x.y_sequence for x in hypotheses_ctc]) - tensorboard_logs['val_text_pred_ctc'] = text_pred_ctc - - eou_predictions_ctc = self._get_eou_predictions_from_hypotheses(hypotheses_ctc, batch) - eou_metrics_list_ctc, eob_metrics_list_ctc = self._calculate_eou_metrics(eou_predictions_ctc, batch) - - ctc_wer, ctc_wer_num, ctc_wer_denom = self.ctc_wer.compute() - self.ctc_wer.reset() - - tensorboard_logs['val_wer_num_ctc'] = ctc_wer_num - tensorboard_logs['val_wer_denom_ctc'] = ctc_wer_denom - tensorboard_logs['val_wer_ctc'] = ctc_wer - tensorboard_logs['val_eou_metrics_ctc'] = eou_metrics_list_ctc - tensorboard_logs['val_eob_metrics_ctc'] = eob_metrics_list_ctc - - self.log('global_step', torch.tensor(self.trainer.global_step, dtype=torch.float32)) - - loss_value, additional_logs = self.add_interctc_losses( - loss_value, - transcript, - transcript_len, - compute_wer=True, - compute_loss=self.compute_eval_loss, - log_wer_num_denom=True, - log_prefix="val_", - ) - if self.compute_eval_loss: - # overriding total loss value. Note that the previous - # rnnt + ctc loss is available in metrics as "val_final_loss" now - tensorboard_logs['val_loss'] = loss_value - tensorboard_logs.update(additional_logs) - # Reset access registry - if AccessMixin.is_access_enabled(self.model_guid): - AccessMixin.reset_registry(self) - - return tensorboard_logs - - def multi_inference_epoch_end(self, outputs, dataloader_idx: int = 0, mode: str = "val"): - assert mode in ['val', 'test'], f"Invalid mode: {mode}. Must be 'val' or 'test'." - self._maybe_save_predictions(outputs, mode=mode, dataloader_idx=dataloader_idx) - - # Aggregate WER metrics - if self.compute_eval_loss: - loss_mean = torch.stack([x[f'{mode}_loss'] for x in outputs]).mean() - loss_log = {f'{mode}_loss': loss_mean} - else: - loss_log = {} - wer_num = torch.stack([x[f'{mode}_wer_num'] for x in outputs]).sum() - wer_denom = torch.stack([x[f'{mode}_wer_denom'] for x in outputs]).sum() - tensorboard_logs = {**loss_log, f'{mode}_wer': wer_num.float() / wer_denom} - - if self.ctc_loss_weight > 0: - ctc_wer_num = torch.stack([x['val_wer_num_ctc'] for x in outputs]).sum() - ctc_wer_denom = torch.stack([x['val_wer_denom_ctc'] for x in outputs]).sum() - tensorboard_logs['val_wer_ctc'] = ctc_wer_num.float() / ctc_wer_denom - - eou_metrics = self._aggregate_eou_metrics(outputs, mode) - tensorboard_logs.update(eou_metrics) - - eou_metrics_ctc = self._aggregate_eou_metrics(outputs, mode, is_ctc=True) - for key, value in eou_metrics_ctc.items(): - tensorboard_logs[f'{key}_ctc'] = value - - return {**loss_log, 'log': tensorboard_logs} - - def multi_validation_epoch_end(self, outputs, dataloader_idx: int = 0): - return self.multi_inference_epoch_end(outputs, dataloader_idx, mode='val') - - def multi_test_epoch_end(self, outputs, dataloader_idx: int = 0): - return self.multi_inference_epoch_end(outputs, dataloader_idx, mode='test') diff --git a/nemo/collections/asr/models/asr_model.py b/nemo/collections/asr/models/asr_model.py deleted file mode 100644 index 3412595b53dee616b1c2883211b32e12c795d56c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/asr_model.py +++ /dev/null @@ -1,353 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import logging -from abc import ABC -from typing import List, Optional - -import torch - -from nemo.collections.common.parts.optional_cuda_graphs import WithOptionalCudaGraphs -from nemo.core.classes import ModelPT -from nemo.core.classes.common import PretrainedModelInfo -from nemo.core.classes.exportable import Exportable -from nemo.core.classes.mixins import AccessMixin -from nemo.core.neural_types import AudioSignal, LabelsType, LengthsType, NeuralType -from nemo.core.utils.neural_type_utils import get_io_names -from nemo.utils import logging, model_utils -from nemo.utils.cast_utils import cast_all - -__all__ = ['ASRModel'] - - -class ASRModel(ModelPT, WithOptionalCudaGraphs, ABC): - def multi_validation_epoch_end(self, outputs, dataloader_idx: int = 0): - val_loss = {} - tensorboard_logs = {} - - if 'val_loss' in outputs[0]: - val_loss_mean = torch.stack([x['val_loss'] for x in outputs]).mean() - val_loss = {'val_loss': val_loss_mean} - - tensorboard_logs.update(val_loss) - - if "val_wer_num" in outputs[0]: - wer_num = torch.stack([x['val_wer_num'] for x in outputs]).sum() - wer_denom = torch.stack([x['val_wer_denom'] for x in outputs]).sum() - val_wer = {'val_wer': wer_num / wer_denom} - - tensorboard_logs.update(val_wer) - - if "val_bleu_num" in outputs[0]: - bleu_pred_len = torch.stack([x["val_bleu_pred_len"] for x in outputs]).sum() - bleu_target_len = torch.stack([x["val_bleu_target_len"] for x in outputs]).sum() - bleu_num = torch.stack([x["val_bleu_num"] for x in outputs]).sum(dim=0) - bleu_denom = torch.stack([x["val_bleu_denom"] for x in outputs]).sum(dim=0) - val_bleu = {"val_bleu": self.bleu._compute_bleu(bleu_pred_len, bleu_target_len, bleu_num, bleu_denom)} - - tensorboard_logs.update(val_bleu) - - return {**val_loss, 'log': tensorboard_logs} - - def multi_test_epoch_end(self, outputs, dataloader_idx: int = 0): - val_loss = {} - tensorboard_logs = {} - - if 'test_loss' in outputs[0]: - val_loss_mean = torch.stack([x['test_loss'] for x in outputs]).mean() - val_loss = {'test_loss': val_loss_mean} - - tensorboard_logs.update(val_loss) - - if "test_wer_num" in outputs[0]: - wer_num = torch.stack([x['test_wer_num'] for x in outputs]).sum() - wer_denom = torch.stack([x['test_wer_denom'] for x in outputs]).sum() - val_wer = {'test_wer': wer_num / wer_denom} - - tensorboard_logs.update(val_wer) - - if "test_bleu_num" in outputs[0]: - bleu_pred_len = torch.stack([x["test_bleu_pred_len"] for x in outputs]).sum() - bleu_target_len = torch.stack([x["test_bleu_target_len"] for x in outputs]).sum() - bleu_num = torch.stack([x["test_bleu_num"] for x in outputs]).sum(dim=0) - bleu_denom = torch.stack([x["test_bleu_denom"] for x in outputs]).sum(dim=0) - val_bleu = {"test_bleu": self.bleu._compute_bleu(bleu_pred_len, bleu_target_len, bleu_num, bleu_denom)} - - tensorboard_logs.update(val_bleu) - - return {**val_loss, 'log': tensorboard_logs} - - @classmethod - def list_available_models(cls) -> 'List[PretrainedModelInfo]': - """ - This method returns a list of pre-trained model which can be instantiated directly from NVIDIA's NGC cloud. - Returns: - List of available pre-trained models. - """ - # recursively walk the subclasses to generate pretrained model info - list_of_models = model_utils.resolve_subclass_pretrained_model_info(cls) - return list_of_models - - def add_auxiliary_losses(self, loss: torch.Tensor, reset_registry: bool = False) -> torch.Tensor: - """ - Utility method to enable calculation of auxiliary losses for ASR training. - - Args: - loss: The output loss value prior to addition with auxiliary losses. - reset_registry: Bool, whether to reset the AccessMixin registry after adding auxiliary losses. - - Returns: - Loss tensor used for back propagation. - """ - # Add adapter auxiliary losses, if registered - if AccessMixin.is_access_enabled(self.model_guid): - registry = AccessMixin.get_module_registry(self) - log_dict = {} - - for loss_key, loss_registry in registry.items(): - # Add auxiliary loss to total loss - if 'adapter_loss' in loss_registry: - loss_list = loss_registry['adapter_loss'] - loss_value = sum(loss_list) - loss += loss_value - - # Log current loss name and value - keys = loss_key.split(".") - key = "/".join(keys) - key = "adapter_loss/" + key - log_dict[key] = loss_value.detach() - - if len(log_dict) > 0: - self.log_dict(log_dict) - - if reset_registry: - AccessMixin.reset_registry(self) - - # return total loss - return loss - - def setup_optimization_flags(self): - """ - Utility method that must be explicitly called by the subclass in order to support optional optimization flags. - This method is the only valid place to access self.cfg prior to DDP training occurs. - - The subclass may chose not to support this method, therefore all variables here must be checked via hasattr() - """ - # Skip update if nan/inf grads appear on any rank. - self._skip_nan_grad = False - if "skip_nan_grad" in self._cfg and self._cfg["skip_nan_grad"]: - self._skip_nan_grad = self._cfg["skip_nan_grad"] - - def on_after_backward(self): - """ - zero-out the gradients which any of them is NAN or INF - """ - super().on_after_backward() - - if hasattr(self, '_skip_nan_grad') and self._skip_nan_grad: - device = next(self.parameters()).device - valid_gradients = torch.tensor([1], device=device, dtype=torch.float32) - - # valid_gradients = True - for param_name, param in self.named_parameters(): - if param.grad is not None: - is_not_nan_or_inf = not (torch.isnan(param.grad).any() or torch.isinf(param.grad).any()) - if not is_not_nan_or_inf: - valid_gradients = valid_gradients * 0 - break - - if torch.distributed.is_initialized(): - torch.distributed.all_reduce(valid_gradients, op=torch.distributed.ReduceOp.MIN) - - if valid_gradients < 1: - logging.warning('detected inf or nan values in gradients! Setting gradients to zero.') - self.zero_grad() - - def maybe_enable_cuda_graphs(self, force_reinit=False) -> bool: - """Enable CUDA graphs if all conditions met, return True if state changed""" - state_changed = False - if force_reinit: - state_changed = self.disable_cuda_graphs() - # check that self.decoding.decoding exists and is instance of WithOptionalCudaGraphs - if isinstance(getattr(getattr(self, "decoding", None), "decoding", None), WithOptionalCudaGraphs): - state_changed |= self.decoding.decoding.maybe_enable_cuda_graphs() - if state_changed: - logging.info( - f"CUDA graphs enabled for {type(self).__name__}::{type(self.decoding).__name__}::" - f"{type(self.decoding.decoding).__name__}" - ) - return state_changed - - def disable_cuda_graphs(self) -> bool: - """Disable (maybe temporary) CUDA graphs, return True if state changed""" - state_changed = False - # check that self.decoding.decoding exists and is instance of WithOptionalCudaGraphs - if isinstance(getattr(getattr(self, "decoding", None), "decoding", None), WithOptionalCudaGraphs): - state_changed = self.decoding.decoding.disable_cuda_graphs() - if state_changed: - logging.info( - f"CUDA graphs disabled for {type(self).__name__}::{type(self.decoding).__name__}::" - f"{type(self.decoding.decoding).__name__}" - ) - return state_changed - - def on_train_epoch_start(self) -> None: - """ - Decoder with CUDA graphs does not release memory, thus we disable it for training epoch. - EncDecRNNTModel.decoding.decoding is the inference class with CUDA graphs - """ - self.disable_cuda_graphs() - - def on_train_epoch_end(self) -> None: - """ - After training, we can enable the decoder with CUDA graphs. - EncDecRNNTModel.decoding.decoding is the inference class with CUDA graphs - """ - self.maybe_enable_cuda_graphs() - - def on_validation_epoch_start(self) -> None: - """ - For validation, we enable CUDA graphs to speedup validation. - Force re-enabling required due to issues with trainer and mixed precision. - EncDecRNNTModel.decoding.decoding is the inference class with CUDA graphs. - """ - self.maybe_enable_cuda_graphs(force_reinit=True) - - def on_validation_epoch_end(self) -> Optional[dict[str, dict[str, torch.Tensor]]]: - """ - After validation, we disable CUDA graphs, since `validation` can be called in training loop, and - training will continue after validation - EncDecRNNTModel.decoding.decoding is the inference class with CUDA graphs. - """ - self.disable_cuda_graphs() - return super().on_validation_epoch_end(sync_metrics=True) - - def on_test_epoch_start(self) -> None: - """ - For testing, we enable CUDA graphs to speedup validation. - Force re-enabling required due to issues with trainer and mixed precision. - We do not need to disable CUDA graphs after testing, since `test` cannot be called in training loop. - EncDecRNNTModel.decoding.decoding is the inference class with CUDA graphs. - """ - self.maybe_enable_cuda_graphs(force_reinit=True) - - def on_predict_epoch_start(self) -> None: - """ - For predicting, we enable CUDA graphs to speedup validation. - Force re-enabling required due to issues with trainer and mixed precision. - We do not need to disable CUDA graphs after predicting, since `predict` cannot be called in training loop. - EncDecRNNTModel.decoding.decoding is the inference class with CUDA graphs - """ - self.maybe_enable_cuda_graphs(force_reinit=True) - - @property - def oomptimizer_schema(self) -> dict: - """ - Return a typing schema for optimal batch size calibration for various - sequence lengths using OOMptimizer. - """ - return { - "cls": tuple, - "inputs": [ - {"type": NeuralType(("B", "T"), AudioSignal()), "seq_length": "input"}, - {"type": NeuralType(("B",), LengthsType()), "seq_length": "input"}, - { - "type": NeuralType(("B", "T"), LabelsType()), - "seq_length": "output", - "vocab_size": self.tokenizer.vocab_size, - }, - {"type": NeuralType(("B",), LengthsType()), "seq_length": "output"}, - ], - } - - -class ExportableEncDecModel(Exportable): - """ - Simple utiliy mix-in to export models that consist of encoder/decoder pair - plus pre/post processor, but have to be exported as encoder/decoder pair only - (covers most ASR classes) - """ - - @property - def input_module(self): - return self.encoder - - @property - def output_module(self): - return self.decoder - - @property - def output_names(self): - otypes = self.output_module.output_types - if getattr(self.input_module, 'export_cache_support', False): - in_types = self.input_module.output_types - otypes = {n: t for (n, t) in list(otypes.items())[:1]} - for n, t in list(in_types.items())[1:]: - otypes[n] = t - return get_io_names(otypes, self.disabled_deployment_output_names) - - def forward_for_export( - self, audio_signal, length=None, cache_last_channel=None, cache_last_time=None, cache_last_channel_len=None - ): - """ - This forward is used when we need to export the model to ONNX format. - Inputs cache_last_channel and cache_last_time are needed to be passed for exporting streaming models. - - Args: - input: Tensor that represents a batch of raw audio signals of shape [B, T]. T here represents timesteps. - length: Vector of length B, that contains the individual lengths of the audio sequences. - cache_last_channel: Tensor of shape [N, B, T, H] which contains the cache for last channel layers - cache_last_time: Tensor of shape [N, B, H, T] which contains the cache for last time layers - N is the number of such layers which need caching, B is batch size, H is the hidden size of activations, - and T is the length of the cache - - Returns: - the output of the model - """ - enc_fun = getattr(self.input_module, 'forward_for_export', self.input_module.forward) - if cache_last_channel is None: - encoder_output = enc_fun(audio_signal=audio_signal, length=length) - if isinstance(encoder_output, tuple): - encoder_output = encoder_output[0] - else: - encoder_output, length, cache_last_channel, cache_last_time, cache_last_channel_len = enc_fun( - audio_signal=audio_signal, - length=length, - cache_last_channel=cache_last_channel, - cache_last_time=cache_last_time, - cache_last_channel_len=cache_last_channel_len, - ) - - dec_fun = getattr(self.output_module, 'forward_for_export', self.output_module.forward) - ret = dec_fun(encoder_output=encoder_output) - if isinstance(ret, tuple): - ret = ret[0] - if cache_last_channel is not None: - ret = (ret, length, cache_last_channel, cache_last_time, cache_last_channel_len) - return cast_all(ret, from_dtype=torch.float16, to_dtype=torch.float32) - - @property - def disabled_deployment_input_names(self): - return self.encoder.disabled_deployment_input_names - - @property - def disabled_deployment_output_names(self): - return self.encoder.disabled_deployment_output_names - - def set_export_config(self, args): - if 'cache_support' in args: - enable = bool(args['cache_support']) - self.encoder.export_cache_support = enable - logging.info(f"Caching support enabled: {enable}") - self.encoder.setup_streaming_params() - super().set_export_config(args) diff --git a/nemo/collections/asr/models/classification_models.py b/nemo/collections/asr/models/classification_models.py deleted file mode 100644 index f15665fa20cb08c9406fba7346039a2cb1a3116c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/classification_models.py +++ /dev/null @@ -1,1445 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import copy -import json -import os -from abc import abstractmethod -from dataclasses import dataclass, field -from math import ceil, floor -from typing import Any, Dict, List, Optional, Union - -import torch -from lightning.pytorch import Trainer -from omegaconf import DictConfig, ListConfig, OmegaConf -from torch.utils.data import DataLoader -from torchmetrics import Accuracy -from torchmetrics.regression import MeanAbsoluteError, MeanSquaredError - -from nemo.collections.asr.data import audio_to_label_dataset, feature_to_label_dataset -from nemo.collections.asr.models.asr_model import ASRModel, ExportableEncDecModel -from nemo.collections.asr.models.label_models import EncDecSpeakerLabelModel -from nemo.collections.asr.parts.mixins import TranscriptionMixin, TranscriptionReturnType -from nemo.collections.asr.parts.mixins.transcription import InternalTranscribeConfig -from nemo.collections.asr.parts.preprocessing.features import WaveformFeaturizer -from nemo.collections.asr.parts.preprocessing.perturb import process_augmentations -from nemo.collections.common.losses import CrossEntropyLoss, MSELoss -from nemo.collections.common.metrics import TopKClassificationAccuracy -from nemo.core.classes.common import PretrainedModelInfo, typecheck -from nemo.core.neural_types import * -from nemo.utils import logging, model_utils -from nemo.utils.cast_utils import cast_all - - -__all__ = ['EncDecClassificationModel', 'EncDecRegressionModel'] - - -@dataclass -class ClassificationInferConfig: - batch_size: int = 4 - logprobs: bool = False - - _internal: InternalTranscribeConfig = field(default_factory=lambda: InternalTranscribeConfig()) - - -@dataclass -class RegressionInferConfig: - batch_size: int = 4 - logprobs: bool = True - - _internal: InternalTranscribeConfig = field(default_factory=lambda: InternalTranscribeConfig()) - - -class _EncDecBaseModel(ASRModel, ExportableEncDecModel, TranscriptionMixin): - """Encoder decoder Classification models.""" - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - # Get global rank and total number of GPU workers for IterableDataset partitioning, if applicable - # Global_rank and local_rank is set by LightningModule in Lightning 1.2.0 - self.world_size = 1 - if trainer is not None: - self.world_size = trainer.num_nodes * trainer.num_devices - - # Convert config to a DictConfig - cfg = model_utils.convert_model_config_to_dict_config(cfg) - - # Convert config to support Hydra 1.0+ instantiation - cfg = model_utils.maybe_update_config_version(cfg) - - self.is_regression_task = cfg.get('is_regression_task', False) - # Change labels if needed - self._update_decoder_config(cfg.labels, cfg.decoder) - super().__init__(cfg=cfg, trainer=trainer) - - if hasattr(self._cfg, 'spec_augment') and self._cfg.spec_augment is not None: - self.spec_augmentation = ASRModel.from_config_dict(self._cfg.spec_augment) - else: - self.spec_augmentation = None - if hasattr(self._cfg, 'crop_or_pad_augment') and self._cfg.crop_or_pad_augment is not None: - self.crop_or_pad = ASRModel.from_config_dict(self._cfg.crop_or_pad_augment) - else: - self.crop_or_pad = None - - self.preprocessor = self._setup_preprocessor() - self.encoder = self._setup_encoder() - self.decoder = self._setup_decoder() - self.loss = self._setup_loss() - self._setup_metrics() - - @abstractmethod - def _setup_preprocessor(self): - """ - Setup preprocessor for audio data - Returns: Preprocessor - - """ - pass - - @abstractmethod - def _setup_encoder(self): - """ - Setup encoder for the Encoder-Decoder network - Returns: Encoder - """ - pass - - @abstractmethod - def _setup_decoder(self): - """ - Setup decoder for the Encoder-Decoder network - Returns: Decoder - """ - pass - - @abstractmethod - def _setup_loss(self): - """ - Setup loss function for training - Returns: Loss function - - """ - pass - - @abstractmethod - def _setup_metrics(self): - """ - Setup metrics to be tracked in addition to loss - Returns: void - - """ - pass - - @property - def input_types(self) -> Optional[Dict[str, NeuralType]]: - if hasattr(self.preprocessor, '_sample_rate'): - audio_eltype = AudioSignal(freq=self.preprocessor._sample_rate) - else: - audio_eltype = AudioSignal() - return { - "input_signal": NeuralType(('B', 'T'), audio_eltype, optional=True), - "input_signal_length": NeuralType(tuple('B'), LengthsType(), optional=True), - "processed_signal": NeuralType(('B', 'D', 'T'), SpectrogramType(), optional=True), - "processed_signal_length": NeuralType(tuple('B'), LengthsType(), optional=True), - } - - @property - @abstractmethod - def output_types(self) -> Optional[Dict[str, NeuralType]]: - pass - - def forward( - self, input_signal=None, input_signal_length=None, processed_signal=None, processed_signal_length=None - ): - has_input_signal = input_signal is not None and input_signal_length is not None - has_processed_signal = processed_signal is not None and processed_signal_length is not None - if (has_input_signal ^ has_processed_signal) == False: - raise ValueError( - f"{self} Arguments ``input_signal`` and ``input_signal_length`` are mutually exclusive " - " with ``processed_signal`` and ``processed_signal_length`` arguments." - ) - - if not has_processed_signal: - processed_signal, processed_signal_length = self.preprocessor( - input_signal=input_signal, - length=input_signal_length, - ) - # Crop or pad is always applied - if self.crop_or_pad is not None: - processed_signal, processed_signal_length = self.crop_or_pad( - input_signal=processed_signal, length=processed_signal_length - ) - # Spec augment is not applied during evaluation/testing - if self.spec_augmentation is not None and self.training: - processed_signal = self.spec_augmentation(input_spec=processed_signal, length=processed_signal_length) - encoded, encoded_len = self.encoder(audio_signal=processed_signal, length=processed_signal_length) - logits = self.decoder(encoder_output=encoded) - return logits - - def setup_training_data(self, train_data_config: Optional[Union[DictConfig, Dict]]): - if 'shuffle' not in train_data_config: - train_data_config['shuffle'] = True - # preserve config - self._update_dataset_config(dataset_name='train', config=train_data_config) - - self._train_dl = self._setup_dataloader_from_config(config=DictConfig(train_data_config)) - - # Need to set this because if using an IterableDataset, the length of the dataloader is the total number - # of samples rather than the number of batches, and this messes up the tqdm progress bar. - # So we set the number of steps manually (to the correct number) to fix this. - if ( - self._train_dl is not None - and hasattr(self._train_dl, 'dataset') - and isinstance(self._train_dl.dataset, torch.utils.data.IterableDataset) - ): - # We also need to check if limit_train_batches is already set. - # If it's an int, we assume that the user has set it to something sane, i.e. <= # training batches, - # and don't change it. Otherwise, adjust batches accordingly if it's a float (including 1.0). - if isinstance(self._trainer.limit_train_batches, float): - self._trainer.limit_train_batches = int( - self._trainer.limit_train_batches - * ceil((len(self._train_dl.dataset) / self.world_size) / train_data_config['batch_size']) - ) - - def setup_validation_data(self, val_data_config: Optional[Union[DictConfig, Dict]]): - if 'shuffle' not in val_data_config: - val_data_config['shuffle'] = False - - # preserve config - self._update_dataset_config(dataset_name='validation', config=val_data_config) - - self._validation_dl = self._setup_dataloader_from_config(config=DictConfig(val_data_config)) - - def setup_test_data(self, test_data_config: Optional[Union[DictConfig, Dict]], use_feat: bool = False): - if 'shuffle' not in test_data_config: - test_data_config['shuffle'] = False - - # preserve config - self._update_dataset_config(dataset_name='test', config=test_data_config) - - if use_feat and hasattr(self, '_setup_feature_label_dataloader'): - self._test_dl = self._setup_feature_label_dataloader(config=DictConfig(test_data_config)) - else: - self._test_dl = self._setup_dataloader_from_config(config=DictConfig(test_data_config)) - - def test_dataloader(self): - if self._test_dl is not None: - return self._test_dl - - def _setup_dataloader_from_config(self, config: DictConfig): - - OmegaConf.set_struct(config, False) - config.is_regression_task = self.is_regression_task - OmegaConf.set_struct(config, True) - - if 'augmentor' in config: - augmentor = process_augmentations(config['augmentor']) - else: - augmentor = None - - featurizer = WaveformFeaturizer( - sample_rate=config['sample_rate'], int_values=config.get('int_values', False), augmentor=augmentor - ) - shuffle = config['shuffle'] - - # Instantiate tarred dataset loader or normal dataset loader - if config.get('is_tarred', False): - if ('tarred_audio_filepaths' in config and config['tarred_audio_filepaths'] is None) or ( - 'manifest_filepath' in config and config['manifest_filepath'] is None - ): - logging.warning( - "Could not load dataset as `manifest_filepath` is None or " - f"`tarred_audio_filepaths` is None. Provided config : {config}" - ) - return None - - if 'vad_stream' in config and config['vad_stream']: - logging.warning("VAD inference does not support tarred dataset now") - return None - - shuffle_n = config.get('shuffle_n', 4 * config['batch_size']) if shuffle else 0 - dataset = audio_to_label_dataset.get_tarred_classification_label_dataset( - featurizer=featurizer, - config=config, - shuffle_n=shuffle_n, - global_rank=self.global_rank, - world_size=self.world_size, - ) - shuffle = False - batch_size = config['batch_size'] - if hasattr(dataset, 'collate_fn'): - collate_fn = dataset.collate_fn - elif hasattr(dataset.datasets[0], 'collate_fn'): - # support datasets that are lists of entries - collate_fn = dataset.datasets[0].collate_fn - else: - # support datasets that are lists of lists - collate_fn = dataset.datasets[0].datasets[0].collate_fn - - else: - if 'manifest_filepath' in config and config['manifest_filepath'] is None: - logging.warning(f"Could not load dataset as `manifest_filepath` is None. Provided config : {config}") - return None - - if 'vad_stream' in config and config['vad_stream']: - logging.info("Perform streaming frame-level VAD") - dataset = audio_to_label_dataset.get_speech_label_dataset(featurizer=featurizer, config=config) - batch_size = 1 - collate_fn = dataset.vad_frame_seq_collate_fn - else: - dataset = audio_to_label_dataset.get_classification_label_dataset(featurizer=featurizer, config=config) - batch_size = config['batch_size'] - if hasattr(dataset, 'collate_fn'): - collate_fn = dataset.collate_fn - elif hasattr(dataset.datasets[0], 'collate_fn'): - # support datasets that are lists of entries - collate_fn = dataset.datasets[0].collate_fn - else: - # support datasets that are lists of lists - collate_fn = dataset.datasets[0].datasets[0].collate_fn - - return torch.utils.data.DataLoader( - dataset=dataset, - batch_size=batch_size, - collate_fn=collate_fn, - drop_last=config.get('drop_last', False), - shuffle=shuffle, - num_workers=config.get('num_workers', 0), - pin_memory=config.get('pin_memory', False), - ) - - def _setup_feature_label_dataloader(self, config: DictConfig) -> torch.utils.data.DataLoader: - """ - setup dataloader for VAD inference with audio features as input - """ - - OmegaConf.set_struct(config, False) - config.is_regression_task = self.is_regression_task - OmegaConf.set_struct(config, True) - - if 'augmentor' in config: - augmentor = process_augmentations(config['augmentor']) - else: - augmentor = None - if 'manifest_filepath' in config and config['manifest_filepath'] is None: - logging.warning(f"Could not load dataset as `manifest_filepath` is None. Provided config : {config}") - return None - - dataset = feature_to_label_dataset.get_feature_label_dataset(config=config, augmentor=augmentor) - if 'vad_stream' in config and config['vad_stream']: - collate_func = dataset._vad_segment_collate_fn - batch_size = 1 - shuffle = False - else: - collate_func = dataset._collate_fn - batch_size = config['batch_size'] - shuffle = config['shuffle'] - - return torch.utils.data.DataLoader( - dataset=dataset, - batch_size=batch_size, - collate_fn=collate_func, - drop_last=config.get('drop_last', False), - shuffle=shuffle, - num_workers=config.get('num_workers', 0), - pin_memory=config.get('pin_memory', False), - ) - - @torch.no_grad() - def transcribe( - self, - audio: Union[List[str], DataLoader], - batch_size: int = 4, - logprobs=None, - override_config: Optional[ClassificationInferConfig] | Optional[RegressionInferConfig] = None, - ) -> TranscriptionReturnType: - """ - Generate class labels for provided audio files. Use this method for debugging and prototyping. - - Args: - audio: (a single or list) of paths to audio files or a np.ndarray audio array. - Can also be a dataloader object that provides values that can be consumed by the model. - Recommended length per file is approximately 1 second. - batch_size: (int) batch size to use during inference. \ - Bigger will result in better throughput performance but would use more memory. - logprobs: (bool) pass True to get log probabilities instead of class labels. - override_config: (Optional) ClassificationInferConfig to use for this inference call. - If None, will use the default config. - - Returns: - - A list of transcriptions (or raw log probabilities if logprobs is True) in the same order as paths2audio_files - """ - if logprobs is None: - logprobs = self.is_regression_task - - if override_config is None: - if not self.is_regression_task: - trcfg = ClassificationInferConfig(batch_size=batch_size, logprobs=logprobs) - else: - trcfg = RegressionInferConfig(batch_size=batch_size, logprobs=logprobs) - else: - if not isinstance(override_config, ClassificationInferConfig) and not isinstance( - override_config, RegressionInferConfig - ): - raise ValueError( - f"override_config must be of type {ClassificationInferConfig}, " f"but got {type(override_config)}" - ) - trcfg = override_config - - return super().transcribe(audio=audio, override_config=trcfg) - - """ Transcription related methods """ - - def _transcribe_input_manifest_processing( - self, audio_files: List[str], temp_dir: str, trcfg: ClassificationInferConfig - ): - with open(os.path.join(temp_dir, 'manifest.json'), 'w', encoding='utf-8') as fp: - for audio_file in audio_files: - label = 0.0 if self.is_regression_task else self.cfg.labels[0] - entry = {'audio_filepath': audio_file, 'duration': 100000.0, 'label': label} - fp.write(json.dumps(entry) + '\n') - - config = {'paths2audio_files': audio_files, 'batch_size': trcfg.batch_size, 'temp_dir': temp_dir} - return config - - def _transcribe_forward(self, batch: Any, trcfg: ClassificationInferConfig): - logits = self.forward(input_signal=batch[0], input_signal_length=batch[1]) - output = dict(logits=logits) - return output - - def _transcribe_output_processing( - self, outputs, trcfg: ClassificationInferConfig - ) -> Union[List[str], List[torch.Tensor]]: - logits = outputs.pop('logits') - labels = [] - - if trcfg.logprobs: - # dump log probs per file - for idx in range(logits.shape[0]): - lg = logits[idx] - labels.append(lg.cpu().numpy()) - else: - labels_k = [] - top_ks = self._accuracy.top_k - for top_k_i in top_ks: - # replace top k value with current top k - self._accuracy.top_k = top_k_i - labels_k_i = self._accuracy.top_k_predicted_labels(logits) - labels_k_i = labels_k_i.cpu() - labels_k.append(labels_k_i) - - # convenience: if only one top_k, pop out the nested list - if len(top_ks) == 1: - labels_k = labels_k[0] - - labels += labels_k - # reset top k to orignal value - self._accuracy.top_k = top_ks - - return labels - - def _setup_transcribe_dataloader(self, config: Dict) -> 'torch.utils.data.DataLoader': - """ - Setup function for a temporary data loader which wraps the provided audio file. - - Args: - config: A python dictionary which contains the following keys: - - Returns: - A pytorch DataLoader for the given audio file(s). - """ - dl_config = { - 'manifest_filepath': os.path.join(config['temp_dir'], 'manifest.json'), - 'sample_rate': self.preprocessor._sample_rate, - 'labels': self.cfg.labels, - 'batch_size': min(config['batch_size'], len(config['paths2audio_files'])), - 'trim_silence': False, - 'shuffle': False, - } - - temporary_datalayer = self._setup_dataloader_from_config(config=DictConfig(dl_config)) - return temporary_datalayer - - @abstractmethod - def _update_decoder_config(self, labels, cfg): - pass - - @classmethod - def get_transcribe_config(cls) -> ClassificationInferConfig: - """ - Utility method that returns the default config for transcribe() function. - Returns: - A dataclass - """ - return ClassificationInferConfig() - - -class EncDecClassificationModel(EncDecSpeakerLabelModel, TranscriptionMixin): - - def setup_test_data(self, test_data_config: Optional[Union[DictConfig, Dict]], use_feat: bool = False): - if 'shuffle' not in test_data_config: - test_data_config['shuffle'] = False - - # preserve config - self._update_dataset_config(dataset_name='test', config=test_data_config) - - if use_feat and hasattr(self, '_setup_feature_label_dataloader'): - self._test_dl = self._setup_feature_label_dataloader(config=DictConfig(test_data_config)) - else: - self._test_dl = self._setup_dataloader_from_config(config=DictConfig(test_data_config)) - - def _setup_feature_label_dataloader(self, config: DictConfig) -> torch.utils.data.DataLoader: - """ - setup dataloader for VAD inference with audio features as input - """ - - OmegaConf.set_struct(config, False) - config.is_regression_task = self.is_regression_task - OmegaConf.set_struct(config, True) - - if 'augmentor' in config: - augmentor = process_augmentations(config['augmentor']) - else: - augmentor = None - if 'manifest_filepath' in config and config['manifest_filepath'] is None: - logging.warning(f"Could not load dataset as `manifest_filepath` is None. Provided config : {config}") - return None - - dataset = feature_to_label_dataset.get_feature_label_dataset(config=config, augmentor=augmentor) - if 'vad_stream' in config and config['vad_stream']: - collate_func = dataset._vad_segment_collate_fn - batch_size = 1 - shuffle = False - else: - collate_func = dataset._collate_fn - batch_size = config['batch_size'] - shuffle = config['shuffle'] - - return torch.utils.data.DataLoader( - dataset=dataset, - batch_size=batch_size, - collate_fn=collate_func, - drop_last=config.get('drop_last', False), - shuffle=shuffle, - num_workers=config.get('num_workers', 0), - pin_memory=config.get('pin_memory', False), - ) - - def _setup_dataloader_from_config(self, config: DictConfig): - OmegaConf.set_struct(config, False) - config.is_regression_task = self.is_regression_task - OmegaConf.set_struct(config, True) - - if 'augmentor' in config: - augmentor = process_augmentations(config['augmentor']) - else: - augmentor = None - - featurizer = WaveformFeaturizer( - sample_rate=config['sample_rate'], int_values=config.get('int_values', False), augmentor=augmentor - ) - shuffle = config['shuffle'] - - # Instantiate tarred dataset loader or normal dataset loader - if config.get('is_tarred', False): - if ('tarred_audio_filepaths' in config and config['tarred_audio_filepaths'] is None) or ( - 'manifest_filepath' in config and config['manifest_filepath'] is None - ): - logging.warning( - "Could not load dataset as `manifest_filepath` is None or " - f"`tarred_audio_filepaths` is None. Provided config : {config}" - ) - return None - - if 'vad_stream' in config and config['vad_stream']: - logging.warning("VAD inference does not support tarred dataset now") - return None - - shuffle_n = config.get('shuffle_n', 4 * config['batch_size']) if shuffle else 0 - dataset = audio_to_label_dataset.get_tarred_classification_label_dataset( - featurizer=featurizer, - config=config, - shuffle_n=shuffle_n, - global_rank=self.global_rank, - world_size=self.world_size, - ) - shuffle = False - batch_size = config['batch_size'] - if hasattr(dataset, 'collate_fn'): - collate_fn = dataset.collate_fn - elif hasattr(dataset.datasets[0], 'collate_fn'): - # support datasets that are lists of entries - collate_fn = dataset.datasets[0].collate_fn - else: - # support datasets that are lists of lists - collate_fn = dataset.datasets[0].datasets[0].collate_fn - - else: - if 'manifest_filepath' in config and config['manifest_filepath'] is None: - logging.warning(f"Could not load dataset as `manifest_filepath` is None. Provided config : {config}") - return None - - if 'vad_stream' in config and config['vad_stream']: - logging.info("Perform streaming frame-level VAD") - dataset = audio_to_label_dataset.get_speech_label_dataset(featurizer=featurizer, config=config) - batch_size = 1 - collate_fn = dataset.vad_frame_seq_collate_fn - else: - dataset = audio_to_label_dataset.get_classification_label_dataset(featurizer=featurizer, config=config) - batch_size = config['batch_size'] - if hasattr(dataset, 'collate_fn'): - collate_fn = dataset.collate_fn - elif hasattr(dataset.datasets[0], 'collate_fn'): - # support datasets that are lists of entries - collate_fn = dataset.datasets[0].collate_fn - else: - # support datasets that are lists of lists - collate_fn = dataset.datasets[0].datasets[0].collate_fn - - return torch.utils.data.DataLoader( - dataset=dataset, - batch_size=batch_size, - collate_fn=collate_fn, - drop_last=config.get('drop_last', False), - shuffle=shuffle, - num_workers=config.get('num_workers', 0), - pin_memory=config.get('pin_memory', False), - ) - - def forward_for_export(self, audio_signal, length): - encoded, length = self.encoder(audio_signal=audio_signal, length=length) - logits = self.decoder(encoder_output=encoded, length=length) - return logits - - def _update_decoder_config(self, labels, cfg): - """ - Update the number of classes in the decoder based on labels provided. - - Args: - labels: The current labels of the model - cfg: The config of the decoder which will be updated. - """ - OmegaConf.set_struct(cfg, False) - if 'params' in cfg: - cfg.params.num_classes = len(labels) - cfg.num_classes = len(labels) - - OmegaConf.set_struct(cfg, True) - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - logging.warning( - "Please use the EncDecSpeakerLabelModel instead of this model. EncDecClassificationModel model is kept for backward compatibility with older models." - ) - self._update_decoder_config(cfg.labels, cfg.decoder) - if hasattr(cfg, 'is_regression_task') and cfg.is_regression_task is not None: - self.is_regression_task = cfg.is_regression_task - else: - self.is_regression_task = False - super().__init__(cfg, trainer) - if hasattr(cfg, 'crop_or_pad_augment') and cfg.crop_or_pad_augment is not None: - self.crop_or_pad = ASRModel.from_config_dict(cfg.crop_or_pad_augment) - else: - self.crop_or_pad = None - - def change_labels(self, new_labels: List[str]): - """ - Changes labels used by the decoder model. Use this method when fine-tuning on from pre-trained model. - This method changes only decoder and leaves encoder and pre-processing modules unchanged. For example, you would - use it if you want to use pretrained encoder when fine-tuning on a data in another dataset. - - If new_labels == self.decoder.vocabulary then nothing will be changed. - - Args: - - new_labels: list with new labels. Must contain at least 2 elements. Typically, \ - this is set of labels for the dataset. - - Returns: None - - """ - if new_labels is not None and not isinstance(new_labels, ListConfig): - new_labels = ListConfig(new_labels) - - if self._cfg.labels == new_labels: - logging.warning( - f"Old labels ({self._cfg.labels}) and new labels ({new_labels}) match. Not changing anything" - ) - else: - if new_labels is None or len(new_labels) == 0: - raise ValueError(f'New labels must be non-empty list of labels. But I got: {new_labels}') - - # Update config - self._cfg.labels = new_labels - - decoder_config = self.decoder.to_config_dict() - new_decoder_config = copy.deepcopy(decoder_config) - self._update_decoder_config(new_labels, new_decoder_config) - del self.decoder - self.decoder = EncDecClassificationModel.from_config_dict(new_decoder_config) - - OmegaConf.set_struct(self._cfg.decoder, False) - self._cfg.decoder = new_decoder_config - OmegaConf.set_struct(self._cfg.decoder, True) - - if 'train_ds' in self._cfg and self._cfg.train_ds is not None: - self._cfg.train_ds.labels = new_labels - - if 'validation_ds' in self._cfg and self._cfg.validation_ds is not None: - self._cfg.validation_ds.labels = new_labels - - if 'test_ds' in self._cfg and self._cfg.test_ds is not None: - self._cfg.test_ds.labels = new_labels - - self._macro_accuracy = Accuracy( - num_classes=self.decoder.num_classes, top_k=1, average='macro', task='multiclass' - ) - logging.info(f"Changed decoder output to {self.decoder.num_classes} labels.") - - @classmethod - def list_available_models(cls) -> Optional[List[PretrainedModelInfo]]: - """ - This method returns a list of pre-trained model which can be instantiated directly from NVIDIA's NGC cloud. - - Returns: - List of available pre-trained models. - """ - results = [] - - model = PretrainedModelInfo( - pretrained_model_name="vad_multilingual_marblenet", - description="For details about this model, please visit https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/vad_multilingual_marblenet", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/vad_multilingual_marblenet/versions/1.10.0/files/vad_multilingual_marblenet.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="vad_telephony_marblenet", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:vad_telephony_marblenet", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/vad_telephony_marblenet/versions/1.0.0rc1/files/vad_telephony_marblenet.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="vad_marblenet", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:vad_marblenet", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/vad_marblenet/versions/1.0.0rc1/files/vad_marblenet.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="commandrecognition_en_matchboxnet3x1x64_v1", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:commandrecognition_en_matchboxnet3x1x64_v1", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/commandrecognition_en_matchboxnet3x1x64_v1/versions/1.0.0rc1/files/commandrecognition_en_matchboxnet3x1x64_v1.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="commandrecognition_en_matchboxnet3x2x64_v1", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:commandrecognition_en_matchboxnet3x2x64_v1", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/commandrecognition_en_matchboxnet3x2x64_v1/versions/1.0.0rc1/files/commandrecognition_en_matchboxnet3x2x64_v1.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="commandrecognition_en_matchboxnet3x1x64_v2", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:commandrecognition_en_matchboxnet3x1x64_v2", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/commandrecognition_en_matchboxnet3x1x64_v2/versions/1.0.0rc1/files/commandrecognition_en_matchboxnet3x1x64_v2.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="commandrecognition_en_matchboxnet3x2x64_v2", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:commandrecognition_en_matchboxnet3x2x64_v2", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/commandrecognition_en_matchboxnet3x2x64_v2/versions/1.0.0rc1/files/commandrecognition_en_matchboxnet3x2x64_v2.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="commandrecognition_en_matchboxnet3x1x64_v2_subset_task", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:commandrecognition_en_matchboxnet3x1x64_v2_subset_task", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/commandrecognition_en_matchboxnet3x1x64_v2_subset_task/versions/1.0.0rc1/files/commandrecognition_en_matchboxnet3x1x64_v2_subset_task.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="commandrecognition_en_matchboxnet3x2x64_v2_subset_task", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:commandrecognition_en_matchboxnet3x2x64_v2_subset_task", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/commandrecognition_en_matchboxnet3x2x64_v2_subset_task/versions/1.0.0rc1/files/commandrecognition_en_matchboxnet3x2x64_v2_subset_task.nemo", - ) - results.append(model) - return results - - def _setup_transcribe_dataloader(self, config: Dict) -> 'torch.utils.data.DataLoader': - """ - Setup function for a temporary data loader which wraps the provided audio file. - - Args: - config: A python dictionary which contains the following keys: - - Returns: - A pytorch DataLoader for the given audio file(s). - """ - dl_config = { - 'manifest_filepath': os.path.join(config['temp_dir'], 'manifest.json'), - 'sample_rate': self.preprocessor._sample_rate, - 'labels': self.cfg.labels, - 'batch_size': min(config['batch_size'], len(config['paths2audio_files'])), - 'trim_silence': False, - 'shuffle': False, - } - - temporary_datalayer = self._setup_dataloader_from_config(config=DictConfig(dl_config)) - return temporary_datalayer - - @torch.no_grad() - def transcribe( - self, - audio: Union[List[str], DataLoader], - batch_size: int = 4, - logprobs=None, - override_config: Optional[ClassificationInferConfig] | Optional[RegressionInferConfig] = None, - ) -> TranscriptionReturnType: - """ - Generate class labels for provided audio files. Use this method for debugging and prototyping. - - Args: - audio: (a single or list) of paths to audio files or a np.ndarray audio array. - Can also be a dataloader object that provides values that can be consumed by the model. - Recommended length per file is approximately 1 second. - batch_size: (int) batch size to use during inference. \ - Bigger will result in better throughput performance but would use more memory. - logprobs: (bool) pass True to get log probabilities instead of class labels. - override_config: (Optional) ClassificationInferConfig to use for this inference call. - If None, will use the default config. - - Returns: - - A list of transcriptions (or raw log probabilities if logprobs is True) in the same order as paths2audio_files - """ - if logprobs is None: - logprobs = self.is_regression_task - - if override_config is None: - if not self.is_regression_task: - trcfg = ClassificationInferConfig(batch_size=batch_size, logprobs=logprobs) - else: - trcfg = RegressionInferConfig(batch_size=batch_size, logprobs=logprobs) - else: - if not isinstance(override_config, ClassificationInferConfig) and not isinstance( - override_config, RegressionInferConfig - ): - raise ValueError( - f"override_config must be of type {ClassificationInferConfig}, " f"but got {type(override_config)}" - ) - trcfg = override_config - - return super().transcribe(audio=audio, override_config=trcfg) - - """ Transcription related methods """ - - def _transcribe_input_manifest_processing( - self, audio_files: List[str], temp_dir: str, trcfg: ClassificationInferConfig - ): - with open(os.path.join(temp_dir, 'manifest.json'), 'w', encoding='utf-8') as fp: - for audio_file in audio_files: - label = 0.0 if self.is_regression_task else self.cfg.labels[0] - entry = {'audio_filepath': audio_file, 'duration': 100000.0, 'label': label} - fp.write(json.dumps(entry) + '\n') - - config = {'paths2audio_files': audio_files, 'batch_size': trcfg.batch_size, 'temp_dir': temp_dir} - return config - - def _transcribe_forward(self, batch: Any, trcfg: ClassificationInferConfig): - logits = self.forward(input_signal=batch[0], input_signal_length=batch[1]) - output = dict(logits=logits) - return output - - def _transcribe_output_processing( - self, outputs, trcfg: ClassificationInferConfig - ) -> Union[List[str], List[torch.Tensor]]: - logits = outputs.pop('logits') - labels = [] - - if trcfg.logprobs: - # dump log probs per file - for idx in range(logits.shape[0]): - lg = logits[idx] - labels.append(lg.cpu().numpy()) - else: - labels_k = [] - top_ks = self._accuracy.top_k - for top_k_i in top_ks: - # replace top k value with current top k - self._accuracy.top_k = top_k_i - labels_k_i = self._accuracy.top_k_predicted_labels(logits) - labels_k_i = labels_k_i.cpu() - labels_k.append(labels_k_i) - - # convenience: if only one top_k, pop out the nested list - if len(top_ks) == 1: - labels_k = labels_k[0] - - labels += labels_k - # reset top k to orignal value - self._accuracy.top_k = top_ks - - return labels - - def forward(self, input_signal, input_signal_length): - logits, _ = super().forward(input_signal, input_signal_length) - return logits - - -class EncDecRegressionModel(_EncDecBaseModel): - """Encoder decoder class for speech regression models. - Model class creates training, validation methods for setting up data - performing model forward pass. - """ - - @classmethod - def list_available_models(cls) -> List[PretrainedModelInfo]: - """ - This method returns a list of pre-trained model which can be instantiated directly from NVIDIA's NGC cloud. - Returns: - List of available pre-trained models. - """ - result = [] - - return result - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - if not cfg.get('is_regression_task', False): - raise ValueError("EndDecRegressionModel requires the flag is_regression_task to be set as true") - super().__init__(cfg=cfg, trainer=trainer) - - def _setup_preprocessor(self): - return EncDecRegressionModel.from_config_dict(self._cfg.preprocessor) - - def _setup_encoder(self): - return EncDecRegressionModel.from_config_dict(self._cfg.encoder) - - def _setup_decoder(self): - return EncDecRegressionModel.from_config_dict(self._cfg.decoder) - - def _setup_loss(self): - return MSELoss() - - def _setup_metrics(self): - self._mse = MeanSquaredError() - self._mae = MeanAbsoluteError() - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - return {"preds": NeuralType(tuple('B'), RegressionValuesType())} - - @typecheck() - def forward(self, input_signal, input_signal_length): - logits = super().forward(input_signal=input_signal, input_signal_length=input_signal_length) - return logits.view(-1) - - # PTL-specific methods - def training_step(self, batch, batch_idx): - audio_signal, audio_signal_len, targets, targets_len = batch - logits = self.forward(input_signal=audio_signal, input_signal_length=audio_signal_len) - loss = self.loss(preds=logits, labels=targets) - train_mse = self._mse(preds=logits, target=targets) - train_mae = self._mae(preds=logits, target=targets) - - self.log_dict( - { - 'train_loss': loss, - 'train_mse': train_mse, - 'train_mae': train_mae, - 'learning_rate': self._optimizer.param_groups[0]['lr'], - }, - ) - - return {'loss': loss} - - def validation_step(self, batch, batch_idx, dataloader_idx: int = 0): - audio_signal, audio_signal_len, targets, targets_len = batch - logits = self.forward(input_signal=audio_signal, input_signal_length=audio_signal_len) - loss_value = self.loss(preds=logits, labels=targets) - val_mse = self._mse(preds=logits, target=targets) - val_mae = self._mae(preds=logits, target=targets) - - return {'val_loss': loss_value, 'val_mse': val_mse, 'val_mae': val_mae} - - def test_step(self, batch, batch_idx, dataloader_idx: int = 0): - logs = self.validation_step(batch, batch_idx, dataloader_idx) - - return {'test_loss': logs['val_loss'], 'test_mse': logs['test_mse'], 'test_mae': logs['val_mae']} - - def multi_validation_epoch_end(self, outputs, dataloader_idx: int = 0): - val_loss_mean = torch.stack([x['val_loss'] for x in outputs]).mean() - val_mse = self._mse.compute() - self._mse.reset() - val_mae = self._mae.compute() - self._mae.reset() - - tensorboard_logs = {'val_loss': val_loss_mean, 'val_mse': val_mse, 'val_mae': val_mae} - - return {'val_loss': val_loss_mean, 'val_mse': val_mse, 'val_mae': val_mae, 'log': tensorboard_logs} - - def multi_test_epoch_end(self, outputs, dataloader_idx: int = 0): - test_loss_mean = torch.stack([x['test_loss'] for x in outputs]).mean() - test_mse = self._mse.compute() - self._mse.reset() - test_mae = self._mae.compute() - self._mae.reset() - - tensorboard_logs = {'test_loss': test_loss_mean, 'test_mse': test_mse, 'test_mae': test_mae} - - return {'test_loss': test_loss_mean, 'test_mse': test_mse, 'test_mae': test_mae, 'log': tensorboard_logs} - - @torch.no_grad() - def transcribe( - self, audio: List[str], batch_size: int = 4, override_config: Optional[RegressionInferConfig] = None - ) -> List[float]: - """ - Generate class labels for provided audio files. Use this method for debugging and prototyping. - - Args: - paths2audio_files: (a list) of paths to audio files. \ - Recommended length per file is approximately 1 second. - batch_size: (int) batch size to use during inference. \ - Bigger will result in better throughput performance but would use more memory. - - Returns: - - A list of predictions in the same order as paths2audio_files - """ - if override_config is None: - trcfg = RegressionInferConfig(batch_size=batch_size, logprobs=True) - else: - if not isinstance(override_config, RegressionInferConfig): - raise ValueError( - f"override_config must be of type {RegressionInferConfig}, " f"but got {type(override_config)}" - ) - trcfg = override_config - - predictions = super().transcribe(audio, override_config=trcfg) - return [float(pred) for pred in predictions] - - def _update_decoder_config(self, labels, cfg): - - OmegaConf.set_struct(cfg, False) - - if 'params' in cfg: - cfg.params.num_classes = 1 - else: - cfg.num_classes = 1 - - OmegaConf.set_struct(cfg, True) - - -class EncDecFrameClassificationModel(_EncDecBaseModel): - """ - EncDecFrameClassificationModel is a model that performs classification on each frame of the input audio. - The default config (i.e., marblenet_3x2x64_20ms.yaml) outputs 20ms frames. - """ - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - self.num_classes = len(cfg.labels) - self.eval_loop_cnt = 0 - self.ratio_threshold = cfg.get('ratio_threshold', 0.2) - if cfg.get("is_regression_task", False): - raise ValueError("EndDecClassificationModel requires the flag is_regression_task to be set as false") - - super().__init__(cfg=cfg, trainer=trainer) - self.decoder.output_types = self.output_types - self.decoder.output_types_for_export = self.output_types - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - return {"outputs": NeuralType(('B', 'T', 'C'), LogitsType())} - - @classmethod - def list_available_models(cls) -> Optional[List[PretrainedModelInfo]]: - results = [] - model = PretrainedModelInfo( - pretrained_model_name="vad_multilingual_frame_marblenet", - description="For details about this model, please visit https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/vad_multilingual_frame_marblenet", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/vad_multilingual_frame_marblenet/versions/1.20.0/files/vad_multilingual_frame_marblenet.nemo", - ) - results.append(model) - return results - - def _setup_preprocessor(self): - return EncDecClassificationModel.from_config_dict(self._cfg.preprocessor) - - def _setup_encoder(self): - return EncDecClassificationModel.from_config_dict(self._cfg.encoder) - - def _setup_decoder(self): - return EncDecClassificationModel.from_config_dict(self._cfg.decoder) - - def _update_decoder_config(self, labels, cfg): - """ - Update the number of classes in the decoder based on labels provided. - - Args: - labels: The current labels of the model - cfg: The config of the decoder which will be updated. - """ - OmegaConf.set_struct(cfg, False) - - if 'params' in cfg: - cfg.params.num_classes = len(labels) - else: - cfg.num_classes = len(labels) - - OmegaConf.set_struct(cfg, True) - - def _setup_metrics(self): - self._accuracy = TopKClassificationAccuracy(dist_sync_on_step=True) - self._macro_accuracy = Accuracy(num_classes=self.num_classes, average='macro', task="multiclass") - - def _setup_loss(self): - if "loss" in self.cfg: - weight = self.cfg.loss.get("weight", None) - if weight in [None, "none", "None"]: - weight = [1.0] * self.num_classes - logging.info(f"Using cross-entropy with weights: {weight}") - else: - weight = [1.0] * self.num_classes - return CrossEntropyLoss(logits_ndim=3, weight=weight) - - def _setup_dataloader_from_config(self, config: DictConfig): - OmegaConf.set_struct(config, False) - config.is_regression_task = self.is_regression_task - OmegaConf.set_struct(config, True) - shuffle = config.get('shuffle', False) - - if config.get('is_tarred', False): - if ('tarred_audio_filepaths' in config and config['tarred_audio_filepaths'] is None) or ( - 'manifest_filepath' in config and config['manifest_filepath'] is None - ): - raise ValueError( - "Could not load dataset as `manifest_filepath` is None or " - f"`tarred_audio_filepaths` is None. Provided cfg : {config}" - ) - - shuffle_n = config.get('shuffle_n', 4 * config['batch_size']) if shuffle else 0 - dataset = audio_to_label_dataset.get_tarred_audio_multi_label_dataset( - cfg=config, - shuffle_n=shuffle_n, - global_rank=self.global_rank, - world_size=self.world_size, - ) - shuffle = False - if hasattr(dataset, 'collate_fn'): - collate_func = dataset.collate_fn - else: - collate_func = dataset.datasets[0].collate_fn - else: - if 'manifest_filepath' in config and config['manifest_filepath'] is None: - raise ValueError(f"Could not load dataset as `manifest_filepath` is None. Provided cfg : {config}") - dataset = audio_to_label_dataset.get_audio_multi_label_dataset(config) - collate_func = dataset.collate_fn - - return torch.utils.data.DataLoader( - dataset=dataset, - batch_size=config.get("batch_size", 1), - collate_fn=collate_func, - drop_last=config.get('drop_last', False), - shuffle=shuffle, - num_workers=config.get('num_workers', 0), - pin_memory=config.get('pin_memory', False), - ) - - def _setup_feature_label_dataloader(self, config: DictConfig) -> torch.utils.data.DataLoader: - """ - setup dataloader for VAD inference with audio features as input - """ - - OmegaConf.set_struct(config, False) - config.is_regression_task = self.is_regression_task - OmegaConf.set_struct(config, True) - - if 'augmentor' in config: - augmentor = process_augmentations(config['augmentor']) - else: - augmentor = None - if 'manifest_filepath' in config and config['manifest_filepath'] is None: - logging.warning(f"Could not load dataset as `manifest_filepath` is None. Provided config : {config}") - return None - - dataset = feature_to_label_dataset.get_feature_multi_label_dataset(config=config, augmentor=augmentor) - - return torch.utils.data.DataLoader( - dataset=dataset, - batch_size=config.get("batch_size", 1), - collate_fn=dataset.collate_fn, - drop_last=config.get('drop_last', False), - shuffle=config.get('shuffle', False), - num_workers=config.get('num_workers', 0), - pin_memory=config.get('pin_memory', False), - ) - - def get_label_masks(self, labels, labels_len): - mask = torch.arange(labels.size(1))[None, :].to(labels.device) < labels_len[:, None] - return mask.to(labels.device, dtype=bool) - - @typecheck() - def forward( - self, input_signal=None, input_signal_length=None, processed_signal=None, processed_signal_length=None - ): - has_input_signal = input_signal is not None and input_signal_length is not None - has_processed_signal = processed_signal is not None and processed_signal_length is not None - if (has_input_signal ^ has_processed_signal) == False: - raise ValueError( - f"{self} Arguments ``input_signal`` and ``input_signal_length`` are mutually exclusive " - " with ``processed_signal`` and ``processed_signal_length`` arguments." - ) - - if not has_processed_signal: - processed_signal, processed_signal_length = self.preprocessor( - input_signal=input_signal, - length=input_signal_length, - ) - - # Crop or pad is always applied - if self.crop_or_pad is not None: - processed_signal, processed_signal_length = self.crop_or_pad( - input_signal=processed_signal, length=processed_signal_length - ) - # Spec augment is not applied during evaluation/testing - if self.spec_augmentation is not None and self.training: - processed_signal = self.spec_augmentation(input_spec=processed_signal, length=processed_signal_length) - encoded, encoded_len = self.encoder(audio_signal=processed_signal, length=processed_signal_length) - logits = self.decoder(encoded.transpose(1, 2)) - return logits - - # PTL-specific methods - def training_step(self, batch, batch_idx): - audio_signal, audio_signal_len, labels, labels_len = batch - logits = self.forward(input_signal=audio_signal, input_signal_length=audio_signal_len) - labels, labels_len = self.reshape_labels(logits, labels, audio_signal_len, labels_len) - masks = self.get_label_masks(labels, labels_len) - - loss_value = self.loss(logits=logits, labels=labels, loss_mask=masks) - - tensorboard_logs = { - 'train_loss': loss_value, - 'learning_rate': self._optimizer.param_groups[0]['lr'], - 'global_step': torch.tensor(self.trainer.global_step, dtype=torch.float32), - } - - metric_logits, metric_labels = self.get_metric_logits_labels(logits, labels, masks) - self._accuracy(logits=metric_logits, labels=metric_labels) - topk_scores = self._accuracy.compute() - self._accuracy.reset() - - for top_k, score in zip(self._accuracy.top_k, topk_scores): - tensorboard_logs[f'training_batch_accuracy_top@{top_k}'] = score - - return {'loss': loss_value, 'log': tensorboard_logs} - - def validation_step(self, batch, batch_idx, dataloader_idx: int = 0, tag: str = 'val'): - audio_signal, audio_signal_len, labels, labels_len = batch - logits = self.forward(input_signal=audio_signal, input_signal_length=audio_signal_len) - labels, labels_len = self.reshape_labels(logits, labels, audio_signal_len, labels_len) - masks = self.get_label_masks(labels, labels_len) - - loss_value = self.loss(logits=logits, labels=labels, loss_mask=masks) - - metric_logits, metric_labels = self.get_metric_logits_labels(logits, labels, masks) - - acc = self._accuracy(logits=metric_logits, labels=metric_labels) - correct_counts, total_counts = self._accuracy.correct_counts_k, self._accuracy.total_counts_k - - self._macro_accuracy.update(preds=metric_logits, target=metric_labels) - stats = self._macro_accuracy._final_state() - - output = { - f'{tag}_loss': loss_value, - f'{tag}_correct_counts': correct_counts, - f'{tag}_total_counts': total_counts, - f'{tag}_acc_micro': acc, - f'{tag}_acc_stats': stats, - } - - if tag == 'val': - if isinstance(self.trainer.val_dataloaders, (list, tuple)) and len(self.trainer.val_dataloaders) > 1: - self.validation_step_outputs[dataloader_idx].append(output) - else: - self.validation_step_outputs.append(output) - else: - if isinstance(self.trainer.test_dataloaders, (list, tuple)) and len(self.trainer.test_dataloaders) > 1: - self.test_step_outputs[dataloader_idx].append(output) - else: - self.test_step_outputs.append(output) - return output - - def multi_validation_epoch_end(self, outputs, dataloader_idx: int = 0, tag: str = 'val'): - val_loss_mean = torch.stack([x[f'{tag}_loss'] for x in outputs]).mean() - correct_counts = torch.stack([x[f'{tag}_correct_counts'] for x in outputs]).sum(axis=0) - total_counts = torch.stack([x[f'{tag}_total_counts'] for x in outputs]).sum(axis=0) - - self._accuracy.correct_counts_k = correct_counts - self._accuracy.total_counts_k = total_counts - topk_scores = self._accuracy.compute() - - self._macro_accuracy.tp = torch.stack([x[f'{tag}_acc_stats'][0] for x in outputs]).sum(axis=0) - self._macro_accuracy.fp = torch.stack([x[f'{tag}_acc_stats'][1] for x in outputs]).sum(axis=0) - self._macro_accuracy.tn = torch.stack([x[f'{tag}_acc_stats'][2] for x in outputs]).sum(axis=0) - self._macro_accuracy.fn = torch.stack([x[f'{tag}_acc_stats'][3] for x in outputs]).sum(axis=0) - macro_accuracy_score = self._macro_accuracy.compute() - - self._accuracy.reset() - self._macro_accuracy.reset() - - tensorboard_log = { - f'{tag}_loss': val_loss_mean, - f'{tag}_acc_macro': macro_accuracy_score, - } - - for top_k, score in zip(self._accuracy.top_k, topk_scores): - tensorboard_log[f'{tag}_acc_micro_top@{top_k}'] = score - - self.log_dict(tensorboard_log, sync_dist=True) - return tensorboard_log - - def test_step(self, batch, batch_idx, dataloader_idx=0): - return self.validation_step(batch, batch_idx, dataloader_idx, tag='test') - - def multi_test_epoch_end(self, outputs, dataloader_idx: int = 0): - return self.multi_validation_epoch_end(outputs, dataloader_idx, tag='test') - - def reshape_labels(self, logits, labels, logits_len, labels_len): - """ - Reshape labels to match logits shape. For example, each label is expected to cover a 40ms frame, while each frme prediction from the - model covers 20ms. If labels are shorter than logits, labels are repeated, otherwise labels are folded and argmax is applied to obtain - the label of each frame. When lengths of labels and logits are not factors of each other, labels are truncated or padded with zeros. - The ratio_threshold=0.2 is used to determine whether to pad or truncate labels, where the value 0.2 is not important as in real cases the ratio - is very close to either ceil(ratio) or floor(ratio). We use 0.2 here for easier unit-testing. This implementation does not allow frame length - and label length that are not multiples of each other. - Args: - logits: logits tensor with shape [B, T1, C] - labels: labels tensor with shape [B, T2] - logits_len: logits length tensor with shape [B] - labels_len: labels length tensor with shape [B] - Returns: - labels: labels tensor with shape [B, T1] - labels_len: labels length tensor with shape [B] - """ - logits_max_len = logits.size(1) - labels_max_len = labels.size(1) - batch_size = logits.size(0) - if logits_max_len < labels_max_len: - ratio = labels_max_len // logits_max_len - res = labels_max_len % logits_max_len - if ceil(ratio) - ratio < self.ratio_threshold: # e.g., ratio is 1.99 - # pad labels with zeros until labels_max_len is a multiple of logits_max_len - labels = labels.cpu().tolist() - if len(labels) % ceil(ratio) != 0: - labels += [0] * (ceil(ratio) - len(labels) % ceil(ratio)) - labels = torch.tensor(labels).long().to(logits.device) - labels = labels.view(-1, ceil(ratio)).amax(1) - return self.reshape_labels(logits, labels, logits_len, labels_len) - else: - # truncate additional labels until labels_max_len is a multiple of logits_max_len - if res > 0: - labels = labels[:, :-res] - mask = labels_len > (labels_max_len - res) - labels_len = labels_len - mask * (labels_len - (labels_max_len - res)) - labels = labels.view(batch_size, ratio, -1).amax(1) - labels_len = torch.div(labels_len, ratio, rounding_mode="floor") - labels_len = torch.min(torch.cat([logits_len[:, None], labels_len[:, None]], dim=1), dim=1)[0] - return labels.contiguous(), labels_len.contiguous() - elif logits_max_len > labels_max_len: - ratio = logits_max_len / labels_max_len - res = logits_max_len % labels_max_len - if ceil(ratio) - ratio < self.ratio_threshold: # e.g., ratio is 1.99 - # repeat labels for ceil(ratio) times, and DROP additional labels based on logits_max_len - labels = labels.repeat_interleave(ceil(ratio), dim=1).long() - labels = labels[:, :logits_max_len] - labels_len = labels_len * ceil(ratio) - mask = labels_len > logits_max_len - labels_len = labels_len - mask * (labels_len - logits_max_len) - else: # e.g., ratio is 2.01 - # repeat labels for floor(ratio) times, and ADD padding labels based on logits_max_len - labels = labels.repeat_interleave(floor(ratio), dim=1).long() - labels_len = labels_len * floor(ratio) - if res > 0: - labels = torch.cat([labels, labels[:, -res:]], dim=1) - # no need to update `labels_len` since we ignore additional "res" padded labels - labels_len = torch.min(torch.cat([logits_len[:, None], labels_len[:, None]], dim=1), dim=1)[0] - return labels.contiguous(), labels_len.contiguous() - else: - labels_len = torch.min(torch.cat([logits_len[:, None], labels_len[:, None]], dim=1), dim=1)[0] - return labels, labels_len - - def get_metric_logits_labels(self, logits, labels, masks): - """ - Computes valid logits and labels for metric computation. - Args: - logits: tensor of shape [B, T, C] - labels: tensor of shape [B, T] - masks: tensor of shape [B, T] - Returns: - logits of shape [N, C] - labels of shape [N,] - """ - C = logits.size(2) - logits = logits.view(-1, C) # [BxT, C] - labels = labels.view(-1).contiguous() # [BxT,] - masks = masks.view(-1) # [BxT,] - idx = masks.nonzero() # [BxT, 1] - - logits = logits.gather(dim=0, index=idx.repeat(1, 2)) - labels = labels.gather(dim=0, index=idx.view(-1)) - - return logits, labels - - def forward_for_export( - self, input, length=None, cache_last_channel=None, cache_last_time=None, cache_last_channel_len=None - ): - """ - This forward is used when we need to export the model to ONNX format. - Inputs cache_last_channel and cache_last_time are needed to be passed for exporting streaming models. - Args: - input: Tensor that represents a batch of raw audio signals, - of shape [B, T]. T here represents timesteps. - length: Vector of length B, that contains the individual lengths of the audio sequences. - cache_last_channel: Tensor of shape [N, B, T, H] which contains the cache for last channel layers - cache_last_time: Tensor of shape [N, B, H, T] which contains the cache for last time layers - N is the number of such layers which need caching, B is batch size, H is the hidden size of activations, - and T is the length of the cache - - Returns: - the output of the model - """ - enc_fun = getattr(self.input_module, 'forward_for_export', self.input_module.forward) - if cache_last_channel is None: - encoder_output = enc_fun(audio_signal=input, length=length) - if isinstance(encoder_output, tuple): - encoder_output = encoder_output[0] - else: - encoder_output, length, cache_last_channel, cache_last_time, cache_last_channel_len = enc_fun( - audio_signal=input, - length=length, - cache_last_channel=cache_last_channel, - cache_last_time=cache_last_time, - cache_last_channel_len=cache_last_channel_len, - ) - - dec_fun = getattr(self.output_module, 'forward_for_export', self.output_module.forward) - ret = dec_fun(hidden_states=encoder_output.transpose(1, 2)) - if isinstance(ret, tuple): - ret = ret[0] - if cache_last_channel is not None: - ret = (ret, length, cache_last_channel, cache_last_time, cache_last_channel_len) - return cast_all(ret, from_dtype=torch.float16, to_dtype=torch.float32) diff --git a/nemo/collections/asr/models/clustering_diarizer.py b/nemo/collections/asr/models/clustering_diarizer.py deleted file mode 100644 index 59f043f745554d757861221d71f70352af051ef1..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/clustering_diarizer.py +++ /dev/null @@ -1,531 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import json -import os -import pickle as pkl -import shutil -import tempfile -from copy import deepcopy -from typing import Any, List, Optional, Union - -import torch -from lightning.pytorch.utilities import rank_zero_only -from omegaconf import DictConfig, OmegaConf -from tqdm import tqdm - -from nemo.collections.asr.metrics.der import score_labels -from nemo.collections.asr.models.classification_models import EncDecClassificationModel -from nemo.collections.asr.models.label_models import EncDecSpeakerLabelModel -from nemo.collections.asr.parts.mixins.mixins import DiarizationMixin -from nemo.collections.asr.parts.utils.speaker_utils import ( - audio_rttm_map, - get_embs_and_timestamps, - get_uniqname_from_filepath, - parse_scale_configs, - perform_clustering, - segments_manifest_to_subsegments_manifest, - validate_vad_manifest, - write_rttm2manifest, -) -from nemo.collections.asr.parts.utils.vad_utils import ( - generate_overlap_vad_seq, - generate_vad_segment_table, - get_vad_stream_status, - prepare_manifest, -) -from nemo.core.classes import Model -from nemo.core.connectors.save_restore_connector import SaveRestoreConnector -from nemo.utils import logging, model_utils - -__all__ = ['ClusteringDiarizer'] - -_MODEL_CONFIG_YAML = "model_config.yaml" -_VAD_MODEL = "vad_model.nemo" -_SPEAKER_MODEL = "speaker_model.nemo" - - -def get_available_model_names(class_name): - "lists available pretrained model names from NGC" - available_models = class_name.list_available_models() - return list(map(lambda x: x.pretrained_model_name, available_models)) - - -class ClusteringDiarizer(torch.nn.Module, Model, DiarizationMixin): - """ - Inference model Class for offline speaker diarization. - This class handles required functionality for diarization : Speech Activity Detection, Segmentation, - Extract Embeddings, Clustering, Resegmentation and Scoring. - All the parameters are passed through config file - """ - - def __init__(self, cfg: Union[DictConfig, Any], speaker_model=None): - super().__init__() - if isinstance(cfg, DictConfig): - cfg = model_utils.convert_model_config_to_dict_config(cfg) - # Convert config to support Hydra 1.0+ instantiation - cfg = model_utils.maybe_update_config_version(cfg) - self._cfg = cfg - - # Diarizer set up - self._diarizer_params = self._cfg.diarizer - - # init vad model - self.has_vad_model = False - if not self._diarizer_params.oracle_vad: - if self._cfg.diarizer.vad.model_path is not None: - self._vad_params = self._cfg.diarizer.vad.parameters - self._init_vad_model() - - # init speaker model - self.multiscale_embeddings_and_timestamps = {} - self._init_speaker_model(speaker_model) - self._speaker_params = self._cfg.diarizer.speaker_embeddings.parameters - - # Clustering params - self._cluster_params = self._diarizer_params.clustering.parameters - - @classmethod - def list_available_models(cls): - pass - - def _init_vad_model(self): - """ - Initialize VAD model with model name or path passed through config - """ - model_path = self._cfg.diarizer.vad.model_path - if model_path.endswith('.nemo'): - self._vad_model = EncDecClassificationModel.restore_from(model_path, map_location=self._cfg.device) - logging.info("VAD model loaded locally from {}".format(model_path)) - else: - if model_path not in get_available_model_names(EncDecClassificationModel): - logging.warning( - "requested {} model name not available in pretrained models, instead".format(model_path) - ) - model_path = "vad_telephony_marblenet" - logging.info("Loading pretrained {} model from NGC".format(model_path)) - self._vad_model = EncDecClassificationModel.from_pretrained( - model_name=model_path, map_location=self._cfg.device - ) - self._vad_window_length_in_sec = self._vad_params.window_length_in_sec - self._vad_shift_length_in_sec = self._vad_params.shift_length_in_sec - self.has_vad_model = True - - def _init_speaker_model(self, speaker_model=None): - """ - Initialize speaker embedding model with model name or path passed through config - """ - if speaker_model is not None: - if self._cfg.device is None and torch.cuda.is_available(): - self._speaker_model = speaker_model.to(torch.device('cuda')) - else: - self._speaker_model = speaker_model - else: - model_path = self._cfg.diarizer.speaker_embeddings.model_path - if model_path is not None and model_path.endswith('.nemo'): - self._speaker_model = EncDecSpeakerLabelModel.restore_from(model_path, map_location=self._cfg.device) - logging.info("Speaker Model restored locally from {}".format(model_path)) - elif model_path.endswith('.ckpt'): - self._speaker_model = EncDecSpeakerLabelModel.load_from_checkpoint( - model_path, map_location=self._cfg.device - ) - logging.info("Speaker Model restored locally from {}".format(model_path)) - else: - if model_path not in get_available_model_names(EncDecSpeakerLabelModel): - logging.warning( - "requested {} model name not available in pretrained models, instead".format(model_path) - ) - model_path = "ecapa_tdnn" - logging.info("Loading pretrained {} model from NGC".format(model_path)) - self._speaker_model = EncDecSpeakerLabelModel.from_pretrained( - model_name=model_path, map_location=self._cfg.device - ) - self.multiscale_args_dict = parse_scale_configs( - self._diarizer_params.speaker_embeddings.parameters.window_length_in_sec, - self._diarizer_params.speaker_embeddings.parameters.shift_length_in_sec, - self._diarizer_params.speaker_embeddings.parameters.multiscale_weights, - ) - - def _setup_vad_test_data(self, manifest_vad_input): - vad_dl_config = { - 'manifest_filepath': manifest_vad_input, - 'sample_rate': self._cfg.sample_rate, - 'batch_size': self._cfg.get('batch_size'), - 'vad_stream': True, - 'labels': [ - 'infer', - ], - 'window_length_in_sec': self._vad_window_length_in_sec, - 'shift_length_in_sec': self._vad_shift_length_in_sec, - 'trim_silence': False, - 'num_workers': self._cfg.num_workers, - } - self._vad_model.setup_test_data(test_data_config=vad_dl_config) - - def _setup_spkr_test_data(self, manifest_file): - spk_dl_config = { - 'manifest_filepath': manifest_file, - 'sample_rate': self._cfg.sample_rate, - 'batch_size': self._cfg.get('batch_size'), - 'trim_silence': False, - 'labels': None, - 'num_workers': self._cfg.num_workers, - } - self._speaker_model.setup_test_data(spk_dl_config) - - def _run_vad(self, manifest_file): - """ - Run voice activity detection. - Get log probability of voice activity detection and smoothes using the post processing parameters. - Using generated frame level predictions generated manifest file for later speaker embedding extraction. - input: - manifest_file (str) : Manifest file containing path to audio file and label as infer - - """ - - shutil.rmtree(self._vad_dir, ignore_errors=True) - os.makedirs(self._vad_dir) - - self._vad_model.eval() - - time_unit = int(self._vad_window_length_in_sec / self._vad_shift_length_in_sec) - trunc = int(time_unit / 2) - trunc_l = time_unit - trunc - all_len = 0 - data = [] - for line in open(manifest_file, 'r', encoding='utf-8'): - file = json.loads(line)['audio_filepath'] - data.append(get_uniqname_from_filepath(file)) - - status = get_vad_stream_status(data) - for i, test_batch in enumerate( - tqdm(self._vad_model.test_dataloader(), desc='vad', leave=True, disable=not self.verbose) - ): - test_batch = [x.to(self._vad_model.device) for x in test_batch] - with torch.amp.autocast(self._vad_model.device.type): - log_probs = self._vad_model(input_signal=test_batch[0], input_signal_length=test_batch[1]) - probs = torch.softmax(log_probs, dim=-1) - pred = probs[:, 1] - if status[i] == 'start': - to_save = pred[:-trunc] - elif status[i] == 'next': - to_save = pred[trunc:-trunc_l] - elif status[i] == 'end': - to_save = pred[trunc_l:] - else: - to_save = pred - all_len += len(to_save) - outpath = os.path.join(self._vad_dir, data[i] + ".frame") - with open(outpath, "a", encoding='utf-8') as fout: - for f in range(len(to_save)): - fout.write('{0:0.4f}\n'.format(to_save[f])) - del test_batch - if status[i] == 'end' or status[i] == 'single': - all_len = 0 - - if not self._vad_params.smoothing: - # Shift the window by 10ms to generate the frame and use the prediction of the window to represent the label for the frame; - self.vad_pred_dir = self._vad_dir - frame_length_in_sec = self._vad_shift_length_in_sec - else: - # Generate predictions with overlapping input segments. Then a smoothing filter is applied to decide the label for a frame spanned by multiple segments. - # smoothing_method would be either in majority vote (median) or average (mean) - logging.info("Generating predictions with overlapping input segments") - smoothing_pred_dir = generate_overlap_vad_seq( - frame_pred_dir=self._vad_dir, - smoothing_method=self._vad_params.smoothing, - overlap=self._vad_params.overlap, - window_length_in_sec=self._vad_window_length_in_sec, - shift_length_in_sec=self._vad_shift_length_in_sec, - num_workers=self._cfg.num_workers, - ) - self.vad_pred_dir = smoothing_pred_dir - frame_length_in_sec = 0.01 - - logging.info("Converting frame level prediction to speech/no-speech segment in start and end times format.") - - vad_params = self._vad_params if isinstance(self._vad_params, (DictConfig, dict)) else self._vad_params.dict() - table_out_dir = generate_vad_segment_table( - vad_pred_dir=self.vad_pred_dir, - postprocessing_params=vad_params, - frame_length_in_sec=frame_length_in_sec, - num_workers=self._cfg.num_workers, - out_dir=self._vad_dir, - ) - - AUDIO_VAD_RTTM_MAP = {} - for key in self.AUDIO_RTTM_MAP: - if os.path.exists(os.path.join(table_out_dir, key + ".txt")): - AUDIO_VAD_RTTM_MAP[key] = deepcopy(self.AUDIO_RTTM_MAP[key]) - AUDIO_VAD_RTTM_MAP[key]['rttm_filepath'] = os.path.join(table_out_dir, key + ".txt") - else: - logging.warning(f"no vad file found for {key} due to zero or negative duration") - - write_rttm2manifest(AUDIO_VAD_RTTM_MAP, self._vad_out_file) - self._speaker_manifest_path = self._vad_out_file - - def _run_segmentation(self, window: float, shift: float, scale_tag: str = ''): - - self.subsegments_manifest_path = os.path.join(self._speaker_dir, f'subsegments{scale_tag}.json') - logging.info( - f"Subsegmentation for embedding extraction:{scale_tag.replace('_',' ')}, {self.subsegments_manifest_path}" - ) - self.subsegments_manifest_path = segments_manifest_to_subsegments_manifest( - segments_manifest_file=self._speaker_manifest_path, - subsegments_manifest_file=self.subsegments_manifest_path, - window=window, - shift=shift, - ) - return None - - def _perform_speech_activity_detection(self): - """ - Checks for type of speech activity detection from config. Choices are NeMo VAD, - external vad manifest and oracle VAD (generates speech activity labels from provided RTTM files) - """ - if self.has_vad_model: - self._auto_split = True - self._split_duration = 50 - manifest_vad_input = self._diarizer_params.manifest_filepath - - if self._auto_split: - logging.info("Split long audio file to avoid CUDA memory issue") - logging.debug("Try smaller split_duration if you still have CUDA memory issue") - config = { - 'input': manifest_vad_input, - 'window_length_in_sec': self._vad_window_length_in_sec, - 'split_duration': self._split_duration, - 'num_workers': self._cfg.num_workers, - 'out_dir': self._diarizer_params.out_dir, - } - manifest_vad_input = prepare_manifest(config) - else: - logging.warning( - "If you encounter CUDA memory issue, try splitting manifest entry by split_duration to avoid it." - ) - - self._setup_vad_test_data(manifest_vad_input) - self._run_vad(manifest_vad_input) - - elif self._diarizer_params.vad.external_vad_manifest is not None: - self._speaker_manifest_path = self._diarizer_params.vad.external_vad_manifest - elif self._diarizer_params.oracle_vad: - self._speaker_manifest_path = os.path.join(self._speaker_dir, 'oracle_vad_manifest.json') - self._speaker_manifest_path = write_rttm2manifest(self.AUDIO_RTTM_MAP, self._speaker_manifest_path) - else: - raise ValueError( - "Only one of diarizer.oracle_vad, vad.model_path or vad.external_vad_manifest must be passed from config" - ) - validate_vad_manifest(self.AUDIO_RTTM_MAP, vad_manifest=self._speaker_manifest_path) - - def _extract_embeddings(self, manifest_file: str, scale_idx: int, num_scales: int): - """ - This method extracts speaker embeddings from segments passed through manifest_file - Optionally you may save the intermediate speaker embeddings for debugging or any use. - """ - logging.info("Extracting embeddings for Diarization") - self._setup_spkr_test_data(manifest_file) - self.embeddings = {} - self._speaker_model.eval() - self.time_stamps = {} - - all_embs = torch.empty([0]) - for test_batch in tqdm( - self._speaker_model.test_dataloader(), - desc=f'[{scale_idx+1}/{num_scales}] extract embeddings', - leave=True, - disable=not self.verbose, - ): - test_batch = [x.to(self._speaker_model.device) for x in test_batch] - audio_signal, audio_signal_len, labels, slices = test_batch - with torch.amp.autocast(self._speaker_model.device.type): - _, embs = self._speaker_model.forward(input_signal=audio_signal, input_signal_length=audio_signal_len) - emb_shape = embs.shape[-1] - embs = embs.view(-1, emb_shape) - all_embs = torch.cat((all_embs, embs.cpu().detach()), dim=0) - del test_batch - - with open(manifest_file, 'r', encoding='utf-8') as manifest: - for i, line in enumerate(manifest.readlines()): - line = line.strip() - dic = json.loads(line) - uniq_name = get_uniqname_from_filepath(dic['audio_filepath']) - if uniq_name in self.embeddings: - self.embeddings[uniq_name] = torch.cat((self.embeddings[uniq_name], all_embs[i].view(1, -1))) - else: - self.embeddings[uniq_name] = all_embs[i].view(1, -1) - if uniq_name not in self.time_stamps: - self.time_stamps[uniq_name] = [] - start = dic['offset'] - end = start + dic['duration'] - self.time_stamps[uniq_name].append([start, end]) - - if self._speaker_params.save_embeddings: - embedding_dir = os.path.join(self._speaker_dir, 'embeddings') - if not os.path.exists(embedding_dir): - os.makedirs(embedding_dir, exist_ok=True) - - prefix = get_uniqname_from_filepath(manifest_file) - name = os.path.join(embedding_dir, prefix) - self._embeddings_file = name + '_embeddings.pkl' - pkl.dump(self.embeddings, open(self._embeddings_file, 'wb')) - logging.info("Saved embedding files to {}".format(embedding_dir)) - - def diarize(self, paths2audio_files: List[str] = None, batch_size: int = 0): - """ - Diarize files provided through paths2audio_files or manifest file - input: - paths2audio_files (List[str]): list of paths to file containing audio file - batch_size (int): batch_size considered for extraction of speaker embeddings and VAD computation - """ - - self._out_dir = self._diarizer_params.out_dir - - self._speaker_dir = os.path.join(self._diarizer_params.out_dir, 'speaker_outputs') - - if os.path.exists(self._speaker_dir): - logging.warning("Deleting previous clustering diarizer outputs.") - shutil.rmtree(self._speaker_dir, ignore_errors=True) - os.makedirs(self._speaker_dir) - - if not os.path.exists(self._out_dir): - os.mkdir(self._out_dir) - - self._vad_dir = os.path.join(self._out_dir, 'vad_outputs') - self._vad_out_file = os.path.join(self._vad_dir, "vad_out.json") - - if batch_size: - self._cfg.batch_size = batch_size - - if paths2audio_files: - if type(paths2audio_files) is list: - self._diarizer_params.manifest_filepath = os.path.join(self._out_dir, 'paths2audio_filepath.json') - self.path2audio_files_to_manifest(paths2audio_files, self._diarizer_params.manifest_filepath) - else: - raise ValueError("paths2audio_files must be of type list of paths to file containing audio file") - - self.AUDIO_RTTM_MAP = audio_rttm_map(self._diarizer_params.manifest_filepath) - - out_rttm_dir = os.path.join(self._out_dir, 'pred_rttms') - os.makedirs(out_rttm_dir, exist_ok=True) - - # Speech Activity Detection - self._perform_speech_activity_detection() - - # Segmentation - scales = self.multiscale_args_dict['scale_dict'].items() - for scale_idx, (window, shift) in scales: - - # Segmentation for the current scale (scale_idx) - self._run_segmentation(window, shift, scale_tag=f'_scale{scale_idx}') - - # Embedding Extraction for the current scale (scale_idx) - self._extract_embeddings(self.subsegments_manifest_path, scale_idx, len(scales)) - - self.multiscale_embeddings_and_timestamps[scale_idx] = [self.embeddings, self.time_stamps] - - embs_and_timestamps = get_embs_and_timestamps( - self.multiscale_embeddings_and_timestamps, self.multiscale_args_dict - ) - - # Clustering - all_reference, all_hypothesis = perform_clustering( - embs_and_timestamps=embs_and_timestamps, - AUDIO_RTTM_MAP=self.AUDIO_RTTM_MAP, - out_rttm_dir=out_rttm_dir, - clustering_params=self._cluster_params, - device=self._speaker_model.device, - verbose=self.verbose, - ) - logging.info("Outputs are saved in {} directory".format(os.path.abspath(self._diarizer_params.out_dir))) - - # Scoring - return score_labels( - self.AUDIO_RTTM_MAP, - all_reference, - all_hypothesis, - collar=self._diarizer_params.collar, - ignore_overlap=self._diarizer_params.ignore_overlap, - verbose=self.verbose, - ) - - @rank_zero_only - def save_to(self, save_path: str): - """ - Saves model instance (weights and configuration) into EFF archive or . - You can use "restore_from" method to fully restore instance from .nemo file. - - .nemo file is an archive (tar.gz) with the following: - model_config.yaml - model configuration in .yaml format. You can deserialize this into cfg argument for model's constructor - model_wights.chpt - model checkpoint - - Args: - save_path: Path to .nemo file where model instance should be saved - """ - - # TODO: Why does this override the main save_to? - - with tempfile.TemporaryDirectory() as tmpdir: - config_yaml = os.path.join(tmpdir, _MODEL_CONFIG_YAML) - spkr_model = os.path.join(tmpdir, _SPEAKER_MODEL) - - self.to_config_file(path2yaml_file=config_yaml) - if self.has_vad_model: - vad_model = os.path.join(tmpdir, _VAD_MODEL) - self._vad_model.save_to(vad_model) - self._speaker_model.save_to(spkr_model) - SaveRestoreConnector._make_nemo_file_from_folder(filename=save_path, source_dir=tmpdir) - - @classmethod - def restore_from( - cls, - restore_path: str, - override_config_path: Optional[str] = None, - map_location: Optional[torch.device] = None, - ): - # Get path where the command is executed - the artifacts will be "retrieved" there - # (original .nemo behavior) - cwd = os.getcwd() - - with tempfile.TemporaryDirectory() as tmpdir: - try: - SaveRestoreConnector._unpack_nemo_file(path2file=restore_path, out_folder=tmpdir) - os.chdir(tmpdir) - if override_config_path is None: - config_yaml = os.path.join(tmpdir, _MODEL_CONFIG_YAML) - else: - config_yaml = override_config_path - conf = OmegaConf.load(config_yaml) - if os.path.exists(os.path.join(tmpdir, _VAD_MODEL)): - conf.diarizer.vad.model_path = os.path.join(tmpdir, _VAD_MODEL) - else: - logging.info( - f'Model {cls.__name__} does not contain a VAD model. A VAD model or manifest file with' - f'speech segments need for diarization with this model' - ) - - conf.diarizer.speaker_embeddings.model_path = os.path.join(tmpdir, _SPEAKER_MODEL) - conf.restore_map_location = map_location - OmegaConf.set_struct(conf, True) - instance = cls(cfg=conf) - - logging.info(f'Model {cls.__name__} was successfully restored from {restore_path}.') - finally: - os.chdir(cwd) - - return instance - - @property - def verbose(self) -> bool: - return self._cfg.verbose diff --git a/nemo/collections/asr/models/confidence_ensemble.py b/nemo/collections/asr/models/confidence_ensemble.py deleted file mode 100644 index 7f0b262ae420432a0f0b29b07ccd8e8ad844d87b..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/confidence_ensemble.py +++ /dev/null @@ -1,233 +0,0 @@ -# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os.path - -import pickle -import warnings -from dataclasses import dataclass - -try: - from joblib.numpy_pickle_utils import _read_fileobject as _validate_joblib_file -except ImportError: - from joblib.numpy_pickle_utils import _validate_fileobject_and_memmap as _validate_joblib_file -import torch -from sklearn.linear_model import LogisticRegression -from sklearn.pipeline import Pipeline -from sklearn.preprocessing import StandardScaler - -from nemo.collections.asr.parts.utils.asr_confidence_utils import ( - ConfidenceConfig, - ConfidenceMethodConfig, - get_confidence_aggregation_bank, - get_confidence_measure_bank, -) -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis - - -# frozen is required to allow hashing of this class and use it -# as a dictionary key when running confidence tuning -@dataclass(frozen=True) -class ConfidenceSpec: - exclude_blank: bool - aggregation: str - confidence_type: str - alpha: float - - def to_confidence_config(self) -> ConfidenceConfig: - """Converts confidence spec to the confidence config. - - Internally, the tuning procedure uses this "spec" objects as they - are more aligned with how things are implemented. But when it's time - to save the models or call transcribe, we need to use the proper - object of type ``ConfidenceConfig``. - """ - if self.confidence_type == 'max_prob': - name = 'max_prob' - entropy_type = 'tsallis' # can be any - entropy_norm = 'lin' # can be any - else: - name, entropy_type, entropy_norm = self.confidence_type.split("_") - return ConfidenceConfig( - exclude_blank=self.exclude_blank, - aggregation=self.aggregation, - method_cfg=ConfidenceMethodConfig( - name=name, - entropy_type=entropy_type, - alpha=self.alpha, - entropy_norm=entropy_norm, - ), - ) - - -def get_filtered_logprobs(hypothesis: Hypothesis, exclude_blank: bool) -> torch.Tensor: - """Returns logprobs from the hypothesis object with optional blanks filter. - - This function supports both CTC and Transducer hypotheses. Will place the - logprobs on GPU if it's available. - - Args: - hypothesis: generated hypothesis as returned from the transcribe - method of the ASR model. - exclude_blank: whether to filter out all ```` tokens. - - Returns: - torch.Tensor: of shape [S, V], where S is (filtered) sequence length and - V is the vocabulary size. - """ - if isinstance(hypothesis.alignments, list): # Transducer - filtered_logprobs = [] - for alignment in hypothesis.alignments: - for align_elem in alignment: - if not exclude_blank: - filtered_logprobs.append(align_elem[0]) - elif align_elem[1].item() != align_elem[0].shape[-1] - 1: - filtered_logprobs.append(align_elem[0]) - if not filtered_logprobs: # for the edge-case of all blanks - filtered_logprobs.append(align_elem[0]) - filtered_logprobs = torch.stack(filtered_logprobs) - if torch.cuda.is_available(): # by default logprobs are placed on cpu in nemo - filtered_logprobs = filtered_logprobs.cuda() - else: # CTC - logprobs = hypothesis.y_sequence - if torch.cuda.is_available(): # by default logprobs are placed on cpu in nemo - logprobs = logprobs.cuda() - if exclude_blank: # filtering blanks - labels = logprobs.argmax(dim=-1) - filtered_logprobs = logprobs[labels != logprobs.shape[1] - 1] - if filtered_logprobs.shape[0] == 0: # for the edge-case of all blanks - filtered_logprobs = logprobs[:1] - else: - filtered_logprobs = logprobs - - # need to make sure logprobs are always normalized, so checking if they sum up to 1 - if not torch.allclose(filtered_logprobs[0].exp().sum(), torch.tensor(1.0)): - filtered_logprobs = torch.log_softmax(filtered_logprobs, dim=1) - - return filtered_logprobs - - -def compute_confidence(hypothesis: Hypothesis, confidence_cfg: ConfidenceConfig) -> float: - """Computes confidence score of the full utterance from a given hypothesis. - - This is essentially a re-implementation of the built-in confidence - computation in NeMo. The difference is that we aggregate full-utterance - scores, while core functionality only supports word and token level - aggregations. - - Args: - hypothesis: generated hypothesis as returned from the transcribe - method of the ASR model. - confidence_cfg: confidence config specifying what kind of - method/aggregation should be used. - - Returns: - float: confidence score. - - """ - filtered_logprobs = get_filtered_logprobs(hypothesis, confidence_cfg.exclude_blank) - vocab_size = filtered_logprobs.shape[1] - aggr_func = get_confidence_aggregation_bank()[confidence_cfg.aggregation] - if confidence_cfg.method_cfg.name == "max_prob": - conf_type = "max_prob" - alpha = 1.0 - else: - conf_type = f"entropy_{confidence_cfg.method_cfg.entropy_type}_{confidence_cfg.method_cfg.entropy_norm}" - alpha = confidence_cfg.method_cfg.alpha - conf_func = get_confidence_measure_bank()[conf_type] - - conf_value = aggr_func(conf_func(filtered_logprobs, v=vocab_size, t=alpha)).cpu().item() - - return conf_value - - -def safe_joblib_load(file_path: str) -> Pipeline: - """ - Safely load a joblib file containing a scikit-learn pipeline. - - Args: - file_path: Path to the joblib file - - Returns: - Pipeline: A scikit-learn pipeline object - - Raises: - ValueError: If the file doesn't exist or contains unauthorized content - SecurityError: If the file contains potentially malicious content - """ - if not os.path.exists(file_path): - raise ValueError(f"Model file not found: {file_path}") - - # Define whitelist of allowed classes for deserialization - ALLOWED_CLASSES = { - 'sklearn.pipeline.Pipeline', - 'sklearn.preprocessing._data.StandardScaler', - 'sklearn.linear_model._logistic.LogisticRegression', - 'numpy.ndarray', - 'numpy.dtype', - 'numpy._pickle', - } - - class RestrictedUnpickler(pickle.Unpickler): - def find_class(self, module, name): - # Only allow specific classes to be loaded - class_path = f"{module}.{name}" - if class_path in ALLOWED_CLASSES: - if module == "numpy._pickle": - import numpy as np - - return getattr(np, name) - return super().find_class(module, name) - # Log and raise exception for unauthorized classes - raise SecurityError(f"Unauthorized class {class_path} in joblib file") - - try: - # Use joblib's load function with our custom unpickler - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - # First try to load with our custom unpickler - try: - with open(file_path, 'rb') as rawf: - with _validate_joblib_file(rawf, file_path, mmap_mode=None) as stream: - if isinstance(stream, tuple): - stream = stream[0] - - if isinstance(stream, str): - with open(stream, "rb") as f: - model = RestrictedUnpickler(f).load() - else: - model = RestrictedUnpickler(stream).load() - - # Validate the loaded object is a sklearn Pipeline - if not isinstance(model, Pipeline): - raise ValueError("Loaded model must be a scikit-learn Pipeline") - - # Validate pipeline steps - for step_name, step_obj in model.named_steps.items(): - if not (isinstance(step_obj, (StandardScaler, LogisticRegression))): - raise ValueError(f"Unauthorized pipeline step: {type(step_obj)}") - - except (pickle.UnpicklingError, AttributeError) as e: - raise SecurityError(f"Failed to safely load model: {e}") - - return model - - except Exception as e: - raise SecurityError(f"Failed to safely load model: {str(e)}") - - -class SecurityError(Exception): - """Custom exception for security-related errors.""" - - pass diff --git a/nemo/collections/asr/models/configs/__init__.py b/nemo/collections/asr/models/configs/__init__.py deleted file mode 100644 index 8a18906a7ec30a17a51bdc936c832fd55cb25fab..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/configs/__init__.py +++ /dev/null @@ -1,42 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.asr.models.configs.asr_models_config import ( # noqa: F401 - ASRDatasetConfig, - CacheAwareStreamingConfig, - EncDecCTCConfig, - EncDecCTCModelConfig, -) -from nemo.collections.asr.models.configs.classification_models_config import ( # noqa: F401 - EncDecClassificationConfig, - EncDecClassificationDatasetConfig, - EncDecClassificationModelConfig, -) -from nemo.collections.asr.models.configs.matchboxnet_config import ( # noqa: F401 - EncDecClassificationModelConfigBuilder, - MatchboxNetModelConfig, - MatchboxNetVADModelConfig, -) -from nemo.collections.asr.modules.audio_preprocessing import ( # noqa: F401 - AudioToMelSpectrogramPreprocessorConfig, - AudioToMFCCPreprocessorConfig, - CropOrPadSpectrogramAugmentationConfig, - SpectrogramAugmentationConfig, -) -from nemo.collections.asr.modules.conv_asr import ( # noqa: F401 - ConvASRDecoderClassificationConfig, - ConvASRDecoderConfig, - ConvASREncoderConfig, - JasperEncoderConfig, -) diff --git a/nemo/collections/asr/models/configs/asr_models_config.py b/nemo/collections/asr/models/configs/asr_models_config.py deleted file mode 100644 index 081233da5d32ff46dcc4a790481584620eaff05b..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/configs/asr_models_config.py +++ /dev/null @@ -1,141 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from dataclasses import dataclass, field -from typing import Any, Dict, List, Optional - -from omegaconf import MISSING - -import nemo.core.classes.dataset -from nemo.collections.asr.modules.audio_preprocessing import ( - AudioToMelSpectrogramPreprocessorConfig, - SpectrogramAugmentationConfig, -) -from nemo.collections.asr.modules.conv_asr import ConvASRDecoderConfig, ConvASREncoderConfig -from nemo.collections.asr.parts.submodules.ctc_decoding import CTCDecodingConfig -from nemo.core.config import modelPT as model_cfg - - -@dataclass -class ASRDatasetConfig(nemo.core.classes.dataset.DatasetConfig): - manifest_filepath: Optional[Any] = None - sample_rate: int = MISSING - labels: List[str] = MISSING - trim_silence: bool = False - - # Tarred dataset support - is_tarred: bool = False - tarred_audio_filepaths: Optional[Any] = None - tarred_shard_strategy: str = "scatter" - shard_manifests: bool = False - shuffle_n: int = 0 - - # lhotse support - use_lhotse: bool = False - tarred_random_access: bool = False - use_bucketing: bool = False - batch_duration: Optional[int] = None - quadratic_duration: Optional[int] = None - bucket_batch_size: Optional[int] = None - bucket_duration_bins: Optional[list] = None - num_buckets: Optional[int] = 0 - pin_memory: bool = False - - # Optional - int_values: Optional[int] = None - augmentor: Optional[Dict[str, Any]] = None - max_duration: Optional[float] = None - min_duration: Optional[float] = None - max_utts: int = 0 - blank_index: int = -1 - unk_index: int = -1 - normalize: bool = False - trim: bool = True - parser: Optional[str] = 'en' - eos_id: Optional[int] = None - bos_id: Optional[int] = None - pad_id: int = 0 - use_start_end_token: bool = False - return_sample_id: Optional[bool] = False - - # bucketing params - bucketing_strategy: str = "synced_randomized" - bucketing_batch_size: Optional[Any] = None - bucketing_weights: Optional[List[int]] = None - - # Optional callable function to parse manifest file - manifest_parse_func: Optional[Any] = (None,) - - -@dataclass -class EncDecCTCConfig(model_cfg.ModelConfig): - # Model global arguments - sample_rate: int = 16000 - repeat: int = 1 - dropout: float = 0.0 - separable: bool = False - labels: List[str] = MISSING - - # Dataset configs - train_ds: ASRDatasetConfig = field(default_factory=lambda: ASRDatasetConfig(manifest_filepath=None, shuffle=True)) - validation_ds: ASRDatasetConfig = field( - default_factory=lambda: ASRDatasetConfig(manifest_filepath=None, shuffle=False) - ) - test_ds: ASRDatasetConfig = field(default_factory=lambda: ASRDatasetConfig(manifest_filepath=None, shuffle=False)) - - # Optimizer / Scheduler config - optim: Optional[model_cfg.OptimConfig] = field( - default_factory=lambda: model_cfg.OptimConfig(sched=model_cfg.SchedConfig()) - ) - - # Model component configs - preprocessor: AudioToMelSpectrogramPreprocessorConfig = field( - default_factory=lambda: AudioToMelSpectrogramPreprocessorConfig() - ) - spec_augment: Optional[SpectrogramAugmentationConfig] = field( - default_factory=lambda: SpectrogramAugmentationConfig() - ) - encoder: ConvASREncoderConfig = field(default_factory=lambda: ConvASREncoderConfig()) - decoder: ConvASRDecoderConfig = field(default_factory=lambda: ConvASRDecoderConfig()) - decoding: CTCDecodingConfig = field(default_factory=lambda: CTCDecodingConfig()) - - -@dataclass -class EncDecCTCModelConfig(model_cfg.NemoConfig): - model: EncDecCTCConfig = field(default_factory=lambda: EncDecCTCConfig()) - - -@dataclass -class CacheAwareStreamingConfig: - chunk_size: int = ( - 0 # the size of each chunk at each step, it can be a list of two integers to specify different chunk sizes for the first step and others - ) - shift_size: int = ( - 0 # the size of the shift in each step, it can be a list of two integers to specify different shift sizes for the first step and others - ) - - cache_drop_size: int = 0 # the number of steps to drop from the cache - last_channel_cache_size: int = 0 # the size of the needed cache for last channel layers - - valid_out_len: int = ( - 0 # the number of the steps in the final output which are valid (have the same value as in the offline mode) - ) - - pre_encode_cache_size: int = ( - 0 # the size of the needed cache for the pre-encoding part of the model to avoid caching inside the pre-encoding layers - ) - drop_extra_pre_encoded: int = 0 # the number of steps to get dropped after the pre-encoding layer - - last_channel_num: int = 0 # number of the last channel layers (like MHA layers) which need caching in the model - last_time_num: int = 0 # number of the last time layers (like convolutions) which need caching in the model diff --git a/nemo/collections/asr/models/configs/classification_models_config.py b/nemo/collections/asr/models/configs/classification_models_config.py deleted file mode 100644 index 76c6022e22e2dc0ea13b7cda5778d5370c38161c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/configs/classification_models_config.py +++ /dev/null @@ -1,112 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from dataclasses import dataclass, field -from typing import Any, Dict, List, Optional, Union - -from omegaconf import MISSING - -import nemo.core.classes.dataset -from nemo.collections.asr.modules.audio_preprocessing import ( - AudioToMFCCPreprocessorConfig, - CropOrPadSpectrogramAugmentationConfig, - SpectrogramAugmentationConfig, -) -from nemo.collections.asr.modules.conv_asr import ConvASRDecoderClassificationConfig, ConvASREncoderConfig -from nemo.core.config import modelPT as model_cfg - - -@dataclass -class EncDecClassificationDatasetConfig(nemo.core.classes.dataset.DatasetConfig): - manifest_filepath: Optional[str] = None - sample_rate: int = MISSING - labels: List[str] = MISSING - trim_silence: bool = False - - # Tarred dataset support - is_tarred: bool = False - tarred_audio_filepaths: Optional[str] = None - tarred_shard_strategy: str = "scatter" - shuffle_n: int = 0 - - # Optional - int_values: Optional[int] = None - augmentor: Optional[Dict[str, Any]] = None - max_duration: Optional[float] = None - min_duration: Optional[float] = None - cal_labels_occurrence: Optional[bool] = False - channel_selector: Optional[Union[str, int, List[int]]] = None - - # VAD Optional - vad_stream: Optional[bool] = None - window_length_in_sec: float = 0.31 - shift_length_in_sec: float = 0.01 - normalize_audio: bool = False - is_regression_task: bool = False - - # bucketing params - bucketing_strategy: str = "synced_randomized" - bucketing_batch_size: Optional[Any] = None - bucketing_weights: Optional[List[int]] = None - - -@dataclass -class EncDecClassificationConfig(model_cfg.ModelConfig): - # Model global arguments - sample_rate: int = 16000 - repeat: int = 1 - dropout: float = 0.0 - separable: bool = True - kernel_size_factor: float = 1.0 - labels: List[str] = MISSING - timesteps: int = MISSING - - # Dataset configs - train_ds: EncDecClassificationDatasetConfig = field( - default_factory=lambda: EncDecClassificationDatasetConfig( - manifest_filepath=None, shuffle=True, trim_silence=False - ) - ) - validation_ds: EncDecClassificationDatasetConfig = field( - default_factory=lambda: EncDecClassificationDatasetConfig(manifest_filepath=None, shuffle=False) - ) - test_ds: EncDecClassificationDatasetConfig = field( - default_factory=lambda: EncDecClassificationDatasetConfig(manifest_filepath=None, shuffle=False) - ) - - # Optimizer / Scheduler config - optim: Optional[model_cfg.OptimConfig] = field( - default_factory=lambda: model_cfg.OptimConfig(sched=model_cfg.SchedConfig()) - ) - - # Model component configs - preprocessor: AudioToMFCCPreprocessorConfig = field(default_factory=lambda: AudioToMFCCPreprocessorConfig()) - spec_augment: Optional[SpectrogramAugmentationConfig] = field( - default_factory=lambda: SpectrogramAugmentationConfig() - ) - crop_or_pad_augment: Optional[CropOrPadSpectrogramAugmentationConfig] = field( - default_factory=lambda: CropOrPadSpectrogramAugmentationConfig(audio_length=-1) - ) - - encoder: ConvASREncoderConfig = field(default_factory=lambda: ConvASREncoderConfig()) - decoder: ConvASRDecoderClassificationConfig = field(default_factory=lambda: ConvASRDecoderClassificationConfig()) - - def __post_init__(self): - if self.crop_or_pad_augment is not None: - self.crop_or_pad_augment.audio_length = self.timesteps - - -@dataclass -class EncDecClassificationModelConfig(model_cfg.NemoConfig): - model: EncDecClassificationConfig = field(default_factory=lambda: EncDecClassificationConfig()) diff --git a/nemo/collections/asr/models/configs/diarizer_config.py b/nemo/collections/asr/models/configs/diarizer_config.py deleted file mode 100644 index 63f220b5f494efef0d3081021c8408f8faee3b07..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/configs/diarizer_config.py +++ /dev/null @@ -1,158 +0,0 @@ -# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from dataclasses import asdict, dataclass, field -from typing import Any, Dict, Optional, Tuple, Union - - -@dataclass -class DiarizerComponentConfig: - """Dataclass to imitate HydraConfig dict when accessing parameters.""" - - def get(self, name: str, default: Optional[Any] = None): - return getattr(self, name, default) - - def __iter__(self): - for key in asdict(self): - yield key - - def dict(self) -> Dict: - return asdict(self) - - -@dataclass -class ASRDiarizerCTCDecoderParams: - pretrained_language_model: Optional[str] = None # KenLM model file: .arpa model file or .bin binary file. - beam_width: int = 32 - alpha: float = 0.5 - beta: float = 2.5 - - -@dataclass -class ASRRealigningLMParams: - # Provide a KenLM language model in .arpa format. - arpa_language_model: Optional[str] = None - # Min number of words for the left context. - min_number_of_words: int = 3 - # Max number of words for the right context. - max_number_of_words: int = 10 - # The threshold for the difference between two log probability values from two hypotheses. - logprob_diff_threshold: float = 1.2 - - -@dataclass -class ASRDiarizerParams(DiarizerComponentConfig): - # if True, speech segmentation for diarization is based on word-timestamps from ASR inference. - asr_based_vad: bool = False - # Threshold (in sec) that caps the gap between two words when generating VAD timestamps using ASR based VAD. - asr_based_vad_threshold: float = 1.0 - # Batch size can be dependent on each ASR model. Default batch sizes are applied if set to null. - asr_batch_size: Optional[int] = None - # Native decoder delay. null is recommended to use the default values for each ASR model. - decoder_delay_in_sec: Optional[float] = None - # Offset to set a reference point from the start of the word. Recommended range of values is [-0.05 0.2]. - word_ts_anchor_offset: Optional[float] = None - # Select which part of the word timestamp we want to use. The options are: 'start', 'end', 'mid'. - word_ts_anchor_pos: str = "start" - # Fix the word timestamp using VAD output. You must provide a VAD model to use this feature. - fix_word_ts_with_VAD: bool = False - # If True, use colored text to distinguish speakers in the output transcript. - colored_text: bool = False - # If True, the start and end time of each speaker turn is printed in the output transcript. - print_time: bool = True - # If True, the output transcript breaks the line to fix the line width (default is 90 chars) - break_lines: bool = False - - -@dataclass -class ASRDiarizerConfig(DiarizerComponentConfig): - model_path: Optional[str] = "stt_en_conformer_ctc_large" - parameters: ASRDiarizerParams = field(default_factory=lambda: ASRDiarizerParams()) - ctc_decoder_parameters: ASRDiarizerCTCDecoderParams = field(default_factory=lambda: ASRDiarizerCTCDecoderParams()) - realigning_lm_parameters: ASRRealigningLMParams = field(default_factory=lambda: ASRRealigningLMParams()) - - -@dataclass -class VADParams(DiarizerComponentConfig): - window_length_in_sec: float = 0.15 # Window length in sec for VAD context input - shift_length_in_sec: float = 0.01 # Shift length in sec for generate frame level VAD prediction - smoothing: Union[str, bool] = "median" # False or type of smoothing method (eg: median) - overlap: float = 0.5 # Overlap ratio for overlapped mean/median smoothing filter - onset: float = 0.1 # Onset threshold for detecting the beginning and end of a speech - offset: float = 0.1 # Offset threshold for detecting the end of a speech - pad_onset: float = 0.1 # Adding durations before each speech segment - pad_offset: float = 0 # Adding durations after each speech segment - min_duration_on: float = 0 # Threshold for short speech segment deletion - min_duration_off: float = 0.2 # Threshold for small non_speech deletion - filter_speech_first: bool = True - - -@dataclass -class VADConfig(DiarizerComponentConfig): - model_path: str = "vad_multilingual_marblenet" # .nemo local model path or pretrained VAD model name - external_vad_manifest: Optional[str] = None - parameters: VADParams = field(default_factory=lambda: VADParams()) - - -@dataclass -class SpeakerEmbeddingsParams(DiarizerComponentConfig): - # Window length(s) in sec (floating-point number). either a number or a list. ex) 1.5 or [1.5,1.0,0.5] - window_length_in_sec: Tuple[float] = (1.5, 1.25, 1.0, 0.75, 0.5) - # Shift length(s) in sec (floating-point number). either a number or a list. ex) 0.75 or [0.75,0.5,0.25] - shift_length_in_sec: Tuple[float] = (0.75, 0.625, 0.5, 0.375, 0.25) - # Weight for each scale. None (for single scale) or list with window/shift scale count. ex) [0.33,0.33,0.33] - multiscale_weights: Tuple[float] = (1, 1, 1, 1, 1) - # save speaker embeddings in pickle format. - save_embeddings: bool = True - - -@dataclass -class SpeakerEmbeddingsConfig(DiarizerComponentConfig): - # .nemo local model path or pretrained model name (titanet_large, ecapa_tdnn or speakerverification_speakernet) - model_path: Optional[str] = None - parameters: SpeakerEmbeddingsParams = field(default_factory=lambda: SpeakerEmbeddingsParams()) - - -@dataclass -class ClusteringParams(DiarizerComponentConfig): - # If True, use num of speakers value provided in manifest file. - oracle_num_speakers: bool = False - # Max number of speakers for each recording. If an oracle number of speakers is passed, this value is ignored. - max_num_speakers: int = 8 - # If the number of segments is lower than this number, enhanced speaker counting is activated. - enhanced_count_thres: int = 80 - # Determines the range of p-value search: 0 < p <= max_rp_threshold. - max_rp_threshold: float = 0.25 - # The higher the number, the more values will be examined with more time. - sparse_search_volume: int = 30 - # If True, take a majority vote on multiple p-values to estimate the number of speakers. - maj_vote_spk_count: bool = False - - -@dataclass -class ClusteringConfig(DiarizerComponentConfig): - parameters: ClusteringParams = field(default_factory=lambda: ClusteringParams()) - - -@dataclass -class DiarizerConfig(DiarizerComponentConfig): - manifest_filepath: Optional[str] = None - out_dir: Optional[str] = None - oracle_vad: bool = False # If True, uses RTTM files provided in the manifest file to get VAD timestamps - collar: float = 0.25 # Collar value for scoring - ignore_overlap: bool = True # Consider or ignore overlap segments while scoring - vad: VADConfig = field(default_factory=lambda: VADConfig()) - speaker_embeddings: SpeakerEmbeddingsConfig = field(default_factory=lambda: SpeakerEmbeddingsConfig()) - clustering: ClusteringConfig = field(default_factory=lambda: ClusteringConfig()) - asr: ASRDiarizerConfig = field(default_factory=lambda: ASRDiarizerConfig()) diff --git a/nemo/collections/asr/models/configs/matchboxnet_config.py b/nemo/collections/asr/models/configs/matchboxnet_config.py deleted file mode 100644 index 52ec4c35d9e853fac6143d89158400c45fd1aceb..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/configs/matchboxnet_config.py +++ /dev/null @@ -1,261 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from dataclasses import dataclass, field -from typing import Any, Callable, List, Optional - -from omegaconf import MISSING - -from nemo.collections.asr.models.configs import classification_models_config as clf_cfg -from nemo.collections.asr.modules.audio_preprocessing import ( - AudioToMFCCPreprocessorConfig, - CropOrPadSpectrogramAugmentationConfig, - SpectrogramAugmentationConfig, -) -from nemo.collections.asr.modules.conv_asr import ( - ConvASRDecoderClassificationConfig, - ConvASREncoderConfig, - JasperEncoderConfig, -) -from nemo.core.config import modelPT as model_cfg - - -# fmt: off -def matchboxnet_3x1x64(): - config = [ - JasperEncoderConfig(filters=128, repeat=1, kernel=[11], stride=[1], dilation=[1], dropout=0.0, - residual=False, groups=1, separable=True, heads=-1, residual_mode='add', - residual_dense=False, se=False, se_reduction_ratio=8, se_context_size=-1, - se_interpolation_mode='nearest', kernel_size_factor=1.0, stride_last=False), - JasperEncoderConfig(filters=64, repeat=1, kernel=[13], stride=[1], dilation=[1], dropout=0.0, - residual=True, groups=1, separable=True, heads=-1, residual_mode='add', - residual_dense=False, se=False, se_reduction_ratio=8, se_context_size=-1, - se_interpolation_mode='nearest', kernel_size_factor=1.0, stride_last=False), - JasperEncoderConfig(filters=64, repeat=1, kernel=[15], stride=[1], dilation=[1], dropout=0.0, - residual=True, groups=1, separable=True, heads=-1, residual_mode='add', - residual_dense=False, se=False, se_reduction_ratio=8, se_context_size=-1, - se_interpolation_mode='nearest', kernel_size_factor=1.0, stride_last=False), - JasperEncoderConfig(filters=64, repeat=1, kernel=[17], stride=[1], dilation=[1], dropout=0.0, - residual=True, groups=1, separable=True, heads=-1, residual_mode='add', - residual_dense=False, se=False, se_reduction_ratio=8, se_context_size=-1, - se_interpolation_mode='nearest', kernel_size_factor=1.0, stride_last=False), - JasperEncoderConfig(filters=128, repeat=1, kernel=[29], stride=[1], dilation=[2], dropout=0.0, - residual=False, groups=1, separable=True, heads=-1, residual_mode='add', - residual_dense=False, se=False, se_reduction_ratio=8, se_context_size=-1, - se_interpolation_mode='nearest', kernel_size_factor=1.0, stride_last=False), - JasperEncoderConfig(filters=128, repeat=1, kernel=[1], stride=[1], dilation=[1], dropout=0.0, - residual=False, groups=1, separable=False, heads=-1, residual_mode='add', - residual_dense=False, se=False, se_reduction_ratio=8, se_context_size=-1, - se_interpolation_mode='nearest', kernel_size_factor=1.0, stride_last=False) - ] - return config - - -def matchboxnet_3x1x64_vad(): - config = [ - JasperEncoderConfig(filters=128, repeat=1, kernel=[11], stride=[1], dilation=[1], dropout=0.0, - residual=False, groups=1, separable=True, heads=-1, residual_mode='add', - residual_dense=False, se=False, se_reduction_ratio=8, se_context_size=-1, - se_interpolation_mode='nearest', kernel_size_factor=1.0, stride_last=False), - JasperEncoderConfig(filters=64, repeat=1, kernel=[13], stride=[1], dilation=[1], dropout=0.0, - residual=True, groups=1, separable=True, heads=-1, residual_mode='add', - residual_dense=False, se=False, se_reduction_ratio=8, se_context_size=-1, - se_interpolation_mode='nearest', kernel_size_factor=1.0, stride_last=False), - JasperEncoderConfig(filters=64, repeat=1, kernel=[15], stride=[1], dilation=[1], dropout=0.0, - residual=True, groups=1, separable=True, heads=-1, residual_mode='add', - residual_dense=False, se=False, se_reduction_ratio=8, se_context_size=-1, - se_interpolation_mode='nearest', kernel_size_factor=1.0, stride_last=False), - JasperEncoderConfig(filters=64, repeat=1, kernel=[17], stride=[1], dilation=[1], dropout=0.0, - residual=True, groups=1, separable=True, heads=-1, residual_mode='add', - residual_dense=False, se=False, se_reduction_ratio=8, se_context_size=-1, - se_interpolation_mode='nearest', kernel_size_factor=1.0, stride_last=False), - JasperEncoderConfig(filters=128, repeat=1, kernel=[29], stride=[1], dilation=[2], dropout=0.0, - residual=False, groups=1, separable=True, heads=-1, residual_mode='add', - residual_dense=False, se=False, se_reduction_ratio=8, se_context_size=-1, - se_interpolation_mode='nearest', kernel_size_factor=1.0, stride_last=False), - JasperEncoderConfig(filters=128, repeat=1, kernel=[1], stride=[1], dilation=[1], dropout=0.0, - residual=False, groups=1, separable=False, heads=-1, residual_mode='add', - residual_dense=False, se=False, se_reduction_ratio=8, se_context_size=-1, - se_interpolation_mode='nearest', kernel_size_factor=1.0, stride_last=False) - ] - return config - - -# fmt: on - - -@dataclass -class MatchboxNetModelConfig(clf_cfg.EncDecClassificationConfig): - # Model global arguments - sample_rate: int = 16000 - repeat: int = 1 - dropout: float = 0.0 - separable: bool = True - kernel_size_factor: float = 1.0 - timesteps: int = 128 - labels: List[str] = MISSING - - # Dataset configs - train_ds: clf_cfg.EncDecClassificationDatasetConfig = field( - default_factory=lambda: clf_cfg.EncDecClassificationDatasetConfig( - manifest_filepath=None, shuffle=True, trim_silence=False - ) - ) - validation_ds: clf_cfg.EncDecClassificationDatasetConfig = field( - default_factory=lambda: clf_cfg.EncDecClassificationDatasetConfig(manifest_filepath=None, shuffle=False) - ) - test_ds: clf_cfg.EncDecClassificationDatasetConfig = field( - default_factory=lambda: clf_cfg.EncDecClassificationDatasetConfig(manifest_filepath=None, shuffle=False) - ) - - # Optimizer / Scheduler config - optim: Optional[model_cfg.OptimConfig] = field( - default_factory=lambda: model_cfg.OptimConfig(sched=model_cfg.SchedConfig()) - ) - - # Model general component configs - preprocessor: AudioToMFCCPreprocessorConfig = field( - default_factory=lambda: AudioToMFCCPreprocessorConfig(window_size=0.025) - ) - spec_augment: Optional[SpectrogramAugmentationConfig] = field( - default_factory=lambda: SpectrogramAugmentationConfig( - freq_masks=2, time_masks=2, freq_width=15, time_width=25, rect_masks=5, rect_time=25, rect_freq=15 - ) - ) - crop_or_pad_augment: Optional[CropOrPadSpectrogramAugmentationConfig] = field( - default_factory=lambda: CropOrPadSpectrogramAugmentationConfig(audio_length=128) - ) - - encoder: ConvASREncoderConfig = field(default_factory=lambda: ConvASREncoderConfig(activation="relu")) - decoder: ConvASRDecoderClassificationConfig = field(default_factory=lambda: ConvASRDecoderClassificationConfig()) - - -@dataclass -class MatchboxNetVADModelConfig(MatchboxNetModelConfig): - timesteps: int = 64 - labels: List[str] = field(default_factory=lambda: ['background', 'speech']) - - crop_or_pad_augment: Optional[CropOrPadSpectrogramAugmentationConfig] = None - - -class EncDecClassificationModelConfigBuilder(model_cfg.ModelConfigBuilder): - VALID_CONFIGS = ['matchboxnet_3x1x64', 'matchboxnet_3x1x64_vad'] - - def __init__(self, name: str = 'matchboxnet_3x1x64', encoder_cfg_func: Optional[Callable[[], List[Any]]] = None): - if name not in EncDecClassificationModelConfigBuilder.VALID_CONFIGS: - raise ValueError("`name` must be one of : \n" f"{EncDecClassificationModelConfigBuilder.VALID_CONFIGS}") - - self.name = name - - if 'matchboxnet_3x1x64_vad' in name: - if encoder_cfg_func is None: - encoder_cfg_func = matchboxnet_3x1x64_vad - - model_cfg = MatchboxNetVADModelConfig( - repeat=1, - separable=True, - encoder=ConvASREncoderConfig(jasper=encoder_cfg_func(), activation="relu"), - decoder=ConvASRDecoderClassificationConfig(), - ) - - elif 'matchboxnet_3x1x64' in name: - if encoder_cfg_func is None: - encoder_cfg_func = matchboxnet_3x1x64 - - model_cfg = MatchboxNetModelConfig( - repeat=1, - separable=False, - spec_augment=SpectrogramAugmentationConfig(rect_masks=5, rect_freq=50, rect_time=120), - encoder=ConvASREncoderConfig(jasper=encoder_cfg_func(), activation="relu"), - decoder=ConvASRDecoderClassificationConfig(), - ) - - else: - raise ValueError(f"Invalid config name submitted to {self.__class__.__name__}") - - super(EncDecClassificationModelConfigBuilder, self).__init__(model_cfg) - self.model_cfg: clf_cfg.EncDecClassificationConfig = model_cfg # enable type hinting - - def set_labels(self, labels: List[str]): - self.model_cfg.labels = labels - - def set_separable(self, separable: bool): - self.model_cfg.separable = separable - - def set_repeat(self, repeat: int): - self.model_cfg.repeat = repeat - - def set_sample_rate(self, sample_rate: int): - self.model_cfg.sample_rate = sample_rate - - def set_dropout(self, dropout: float = 0.0): - self.model_cfg.dropout = dropout - - def set_timesteps(self, timesteps: int): - self.model_cfg.timesteps = timesteps - - def set_is_regression_task(self, is_regression_task: bool): - self.model_cfg.is_regression_task = is_regression_task - - # Note: Autocomplete for users wont work without these overrides - # But practically it is not needed since python will infer at runtime - - # def set_train_ds(self, cfg: Optional[clf_cfg.EncDecClassificationDatasetConfig] = None): - # super().set_train_ds(cfg) - # - # def set_validation_ds(self, cfg: Optional[clf_cfg.EncDecClassificationDatasetConfig] = None): - # super().set_validation_ds(cfg) - # - # def set_test_ds(self, cfg: Optional[clf_cfg.EncDecClassificationDatasetConfig] = None): - # super().set_test_ds(cfg) - - def _finalize_cfg(self): - # propagate labels - self.model_cfg.train_ds.labels = self.model_cfg.labels - self.model_cfg.validation_ds.labels = self.model_cfg.labels - self.model_cfg.test_ds.labels = self.model_cfg.labels - self.model_cfg.decoder.vocabulary = self.model_cfg.labels - - # propagate num classes - self.model_cfg.decoder.num_classes = len(self.model_cfg.labels) - - # propagate sample rate - self.model_cfg.sample_rate = self.model_cfg.sample_rate - self.model_cfg.preprocessor.sample_rate = self.model_cfg.sample_rate - self.model_cfg.train_ds.sample_rate = self.model_cfg.sample_rate - self.model_cfg.validation_ds.sample_rate = self.model_cfg.sample_rate - self.model_cfg.test_ds.sample_rate = self.model_cfg.sample_rate - - # propagate filters - self.model_cfg.encoder.feat_in = self.model_cfg.preprocessor.features - self.model_cfg.decoder.feat_in = self.model_cfg.encoder.jasper[-1].filters - - # propagate timeteps - if self.model_cfg.crop_or_pad_augment is not None: - self.model_cfg.crop_or_pad_augment.audio_length = self.model_cfg.timesteps - - # propagate separable - for layer in self.model_cfg.encoder.jasper[:-1]: # type: JasperEncoderConfig - layer.separable = self.model_cfg.separable - - # propagate repeat - for layer in self.model_cfg.encoder.jasper[1:-2]: # type: JasperEncoderConfig - layer.repeat = self.model_cfg.repeat - - # propagate dropout - for layer in self.model_cfg.encoder.jasper: # type: JasperEncoderConfig - layer.dropout = self.model_cfg.dropout - - def build(self) -> clf_cfg.EncDecClassificationConfig: - return super().build() diff --git a/nemo/collections/asr/models/ctc_bpe_models.py b/nemo/collections/asr/models/ctc_bpe_models.py deleted file mode 100644 index abd6cba0fb20c2b3b61aa34156d71267b0bb5f3a..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/ctc_bpe_models.py +++ /dev/null @@ -1,631 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import copy -import os -from typing import Dict, List, Optional, Union - -import torch -from omegaconf import DictConfig, ListConfig, OmegaConf, open_dict - -from nemo.collections.asr.data import audio_to_text_dataset -from nemo.collections.asr.data.audio_to_text import _AudioTextDataset -from nemo.collections.asr.data.audio_to_text_dali import AudioToBPEDALIDataset -from nemo.collections.asr.data.audio_to_text_lhotse import LhotseSpeechToTextBpeDataset -from nemo.collections.asr.losses.ctc import CTCLoss -from nemo.collections.asr.metrics.wer import WER -from nemo.collections.asr.models.ctc_models import EncDecCTCModel -from nemo.collections.asr.parts.mixins import ASRBPEMixin -from nemo.collections.asr.parts.submodules.ctc_decoding import CTCBPEDecoding, CTCBPEDecodingConfig -from nemo.collections.asr.parts.utils.asr_batching import get_semi_sorted_batch_sampler -from nemo.collections.common.data.lhotse import get_lhotse_dataloader_from_config -from nemo.core.classes.common import PretrainedModelInfo -from nemo.utils import logging, model_utils - -__all__ = ['EncDecCTCModelBPE'] - - -class EncDecCTCModelBPE(EncDecCTCModel, ASRBPEMixin): - """Encoder decoder CTC-based models with Byte Pair Encoding.""" - - def __init__(self, cfg: DictConfig, trainer=None): - # Convert to Hydra 1.0 compatible DictConfig - cfg = model_utils.convert_model_config_to_dict_config(cfg) - cfg = model_utils.maybe_update_config_version(cfg, make_copy=False) - - if 'tokenizer' not in cfg: - raise ValueError("`cfg` must have `tokenizer` config to create a tokenizer !") - - # Setup the tokenizer - self._setup_tokenizer(cfg.tokenizer) - - # Initialize a dummy vocabulary - vocabulary = self.tokenizer.tokenizer.get_vocab() - - # Set the new vocabulary - with open_dict(cfg): - # sidestepping the potential overlapping tokens issue in aggregate tokenizers - if self.tokenizer_type == "agg": - cfg.decoder.vocabulary = ListConfig(vocabulary) - else: - cfg.decoder.vocabulary = ListConfig(list(vocabulary.keys())) - - # Override number of classes if placeholder provided - num_classes = cfg.decoder["num_classes"] - - if num_classes < 1: - logging.info( - "\nReplacing placeholder number of classes ({}) with actual number of classes - {}".format( - num_classes, len(vocabulary) - ) - ) - cfg.decoder["num_classes"] = len(vocabulary) - - super().__init__(cfg=cfg, trainer=trainer) - - # Setup decoding objects - decoding_cfg = self.cfg.get('decoding', None) - - # In case decoding config not found, use default config - if decoding_cfg is None: - decoding_cfg = OmegaConf.structured(CTCBPEDecodingConfig) - with open_dict(self.cfg): - self.cfg.decoding = decoding_cfg - - self.decoding = CTCBPEDecoding(self.cfg.decoding, tokenizer=self.tokenizer) - - # Setup metric with decoding strategy - self.wer = WER( - decoding=self.decoding, - use_cer=self._cfg.get('use_cer', False), - dist_sync_on_step=True, - log_prediction=self._cfg.get("log_prediction", False), - ) - - def _setup_dataloader_from_config(self, config: Optional[Dict]): - if config.get("use_lhotse"): - return get_lhotse_dataloader_from_config( - config, - # During transcription, the model is initially loaded on the CPU. - # To ensure the correct global_rank and world_size are set, - # these values must be passed from the configuration. - global_rank=self.global_rank if not config.get("do_transcribe", False) else config.get("global_rank"), - world_size=self.world_size if not config.get("do_transcribe", False) else config.get("world_size"), - dataset=LhotseSpeechToTextBpeDataset( - tokenizer=self.tokenizer, - return_cuts=config.get("do_transcribe", False), - ), - tokenizer=self.tokenizer, - ) - - dataset = audio_to_text_dataset.get_audio_to_text_bpe_dataset_from_config( - config=config, - local_rank=self.local_rank, - global_rank=self.global_rank, - world_size=self.world_size, - tokenizer=self.tokenizer, - preprocessor_cfg=self.cfg.get("preprocessor", None), - ) - - if dataset is None: - return None - - if isinstance(dataset, AudioToBPEDALIDataset): - # DALI Dataset implements dataloader interface - return dataset - - shuffle = config['shuffle'] - if isinstance(dataset, torch.utils.data.IterableDataset): - shuffle = False - - if hasattr(dataset, 'collate_fn'): - collate_fn = dataset.collate_fn - elif hasattr(dataset.datasets[0], 'collate_fn'): - # support datasets that are lists of entries - collate_fn = dataset.datasets[0].collate_fn - else: - # support datasets that are lists of lists - collate_fn = dataset.datasets[0].datasets[0].collate_fn - - batch_sampler = None - if config.get('use_semi_sorted_batching', False): - if not isinstance(dataset, _AudioTextDataset): - raise RuntimeError( - "Semi Sorted Batch sampler can be used with AudioToCharDataset or AudioToBPEDataset " - f"but found dataset of type {type(dataset)}" - ) - # set batch_size and batch_sampler to None to disable automatic batching - batch_sampler = get_semi_sorted_batch_sampler(self, dataset, config) - config['batch_size'] = None - config['drop_last'] = False - shuffle = False - - return torch.utils.data.DataLoader( - dataset=dataset, - batch_size=config['batch_size'], - sampler=batch_sampler, - batch_sampler=None, - collate_fn=collate_fn, - drop_last=config.get('drop_last', False), - shuffle=shuffle, - num_workers=config.get('num_workers', 0), - pin_memory=config.get('pin_memory', False), - ) - - def _setup_transcribe_dataloader(self, config: Dict) -> 'torch.utils.data.DataLoader': - """ - Setup function for a temporary data loader which wraps the provided audio file. - - Args: - config: A python dictionary which contains the following keys: - paths2audio_files: (a list) of paths to audio files. The files should be relatively short fragments. \ - Recommended length per file is between 5 and 25 seconds. - batch_size: (int) batch size to use during inference. \ - Bigger will result in better throughput performance but would use more memory. - temp_dir: (str) A temporary directory where the audio manifest is temporarily - stored. - num_workers: (int) number of workers. Depends of the batch_size and machine. \ - 0 - only the main process will load batches, 1 - one worker (not main process) - - Returns: - A pytorch DataLoader for the given audio file(s). - """ - - if 'manifest_filepath' in config: - manifest_filepath = config['manifest_filepath'] - batch_size = config['batch_size'] - else: - manifest_filepath = os.path.join(config['temp_dir'], 'manifest.json') - batch_size = min(config['batch_size'], len(config['paths2audio_files'])) - - dl_config = { - 'use_lhotse': config.get('use_lhotse', True), - 'manifest_filepath': manifest_filepath, - 'sample_rate': self.preprocessor._sample_rate, - 'batch_size': batch_size, - 'shuffle': False, - 'num_workers': config.get('num_workers', min(batch_size, os.cpu_count() - 1)), - 'pin_memory': True, - 'channel_selector': config.get('channel_selector', None), - 'use_start_end_token': self.cfg.validation_ds.get('use_start_end_token', False), - } - - if config.get("augmentor"): - dl_config['augmentor'] = config.get("augmentor") - - temporary_datalayer = self._setup_dataloader_from_config(config=DictConfig(dl_config)) - return temporary_datalayer - - def change_vocabulary( - self, - new_tokenizer_dir: Union[str, DictConfig], - new_tokenizer_type: str, - decoding_cfg: Optional[DictConfig] = None, - ): - """ - Changes vocabulary of the tokenizer used during CTC decoding process. - Use this method when fine-tuning on from pre-trained model. - This method changes only decoder and leaves encoder and pre-processing modules unchanged. - For example, you would use it if you want to use pretrained encoder when fine-tuning on a - data in another language, or when you'd need model to learn capitalization, punctuation - and/or special characters. - - Args: - new_tokenizer_dir: Directory path to tokenizer or a config for a new tokenizer - (if the tokenizer type is `agg`) - new_tokenizer_type: Either `agg`, `bpe` or `wpe`. `bpe` is used for SentencePiece tokenizers, - whereas `wpe` is used for `BertTokenizer`. - new_tokenizer_cfg: A config for the new tokenizer. if provided, pre-empts the dir and type - - Returns: None - - """ - if isinstance(new_tokenizer_dir, DictConfig): - if new_tokenizer_type == 'agg': - new_tokenizer_cfg = new_tokenizer_dir - else: - raise ValueError( - f'New tokenizer dir should be a string unless the tokenizer is `agg`, but this tokenizer \ - type is: {new_tokenizer_type}' - ) - else: - new_tokenizer_cfg = None - - if new_tokenizer_cfg is not None: - tokenizer_cfg = new_tokenizer_cfg - else: - if not os.path.isdir(new_tokenizer_dir): - raise NotADirectoryError( - f'New tokenizer dir must be non-empty path to a directory. But I got: {new_tokenizer_dir}' - ) - - if new_tokenizer_type.lower() not in ('bpe', 'wpe'): - raise ValueError(f'New tokenizer type must be either `bpe` or `wpe`, got {new_tokenizer_type}') - - tokenizer_cfg = OmegaConf.create({'dir': new_tokenizer_dir, 'type': new_tokenizer_type}) - - # Setup the tokenizer - self._setup_tokenizer(tokenizer_cfg) - - # Initialize a dummy vocabulary - vocabulary = self.tokenizer.tokenizer.get_vocab() - - # Set the new vocabulary - decoder_config = copy.deepcopy(self.decoder.to_config_dict()) - # sidestepping the potential overlapping tokens issue in aggregate tokenizers - if self.tokenizer_type == "agg": - decoder_config.vocabulary = ListConfig(vocabulary) - else: - decoder_config.vocabulary = ListConfig(list(vocabulary.keys())) - - decoder_num_classes = decoder_config['num_classes'] - - # Override number of classes if placeholder provided - logging.info( - "\nReplacing old number of classes ({}) with new number of classes - {}".format( - decoder_num_classes, len(vocabulary) - ) - ) - - decoder_config['num_classes'] = len(vocabulary) - - del self.decoder - self.decoder = EncDecCTCModelBPE.from_config_dict(decoder_config) - del self.loss - self.loss = CTCLoss( - num_classes=self.decoder.num_classes_with_blank - 1, - zero_infinity=True, - reduction=self._cfg.get("ctc_reduction", "mean_batch"), - ) - - if decoding_cfg is None: - # Assume same decoding config as before - decoding_cfg = self.cfg.decoding - - # Assert the decoding config with all hyper parameters - decoding_cls = OmegaConf.structured(CTCBPEDecodingConfig) - decoding_cls = OmegaConf.create(OmegaConf.to_container(decoding_cls)) - decoding_cfg = OmegaConf.merge(decoding_cls, decoding_cfg) - - self.decoding = CTCBPEDecoding(decoding_cfg=decoding_cfg, tokenizer=self.tokenizer) - - self.wer = WER( - decoding=self.decoding, - use_cer=self._cfg.get('use_cer', False), - log_prediction=self._cfg.get("log_prediction", False), - dist_sync_on_step=True, - ) - - # Update config - with open_dict(self.cfg.decoder): - self._cfg.decoder = decoder_config - - with open_dict(self.cfg.decoding): - self._cfg.decoding = decoding_cfg - - logging.info(f"Changed tokenizer to {self.decoder.vocabulary} vocabulary.") - - def change_decoding_strategy(self, decoding_cfg: DictConfig, verbose: bool = True): - """ - Changes decoding strategy used during CTC decoding process. - - Args: - decoding_cfg: A config for the decoder, which is optional. If the decoding type - needs to be changed (from say Greedy to Beam decoding etc), the config can be passed here. - verbose: Whether to print the new config or not. - """ - if decoding_cfg is None: - # Assume same decoding config as before - logging.info("No `decoding_cfg` passed when changing decoding strategy, using internal config") - decoding_cfg = self.cfg.decoding - - # Assert the decoding config with all hyper parameters - decoding_cls = OmegaConf.structured(CTCBPEDecodingConfig) - decoding_cls = OmegaConf.create(OmegaConf.to_container(decoding_cls)) - decoding_cfg = OmegaConf.merge(decoding_cls, decoding_cfg) - - self.decoding = CTCBPEDecoding( - decoding_cfg=decoding_cfg, - tokenizer=self.tokenizer, - ) - - self.wer = WER( - decoding=self.decoding, - use_cer=self.wer.use_cer, - log_prediction=self.wer.log_prediction, - dist_sync_on_step=True, - ) - - self.decoder.temperature = decoding_cfg.get('temperature', 1.0) - - # Update config - with open_dict(self.cfg.decoding): - self.cfg.decoding = decoding_cfg - - if verbose: - logging.info(f"Changed decoding strategy to \n{OmegaConf.to_yaml(self.cfg.decoding)}") - - @classmethod - def list_available_models(cls) -> List[PretrainedModelInfo]: - """ - This method returns a list of pre-trained model which can be instantiated directly from NVIDIA's NGC cloud. - - Returns: - List of available pre-trained models. - """ - results = [] - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_citrinet_256", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_citrinet_256", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_citrinet_256/versions/1.0.0rc1/files/stt_en_citrinet_256.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_citrinet_512", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_citrinet_512", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_citrinet_512/versions/1.0.0rc1/files/stt_en_citrinet_512.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_citrinet_1024", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_citrinet_1024", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_citrinet_1024/versions/1.0.0rc1/files/stt_en_citrinet_1024.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_citrinet_256_gamma_0_25", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:\nemo:stt_en_citrinet_256_gamma_0_25", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_citrinet_256_gamma_0_25/versions/1.0.0/files/stt_en_citrinet_256_gamma_0_25.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_citrinet_512_gamma_0_25", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_citrinet_512_gamma_0_25", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_citrinet_512_gamma_0_25/versions/1.0.0/files/stt_en_citrinet_512_gamma_0_25.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_citrinet_1024_gamma_0_25", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_citrinet_1024_gamma_0_25", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_citrinet_1024_gamma_0_25/versions/1.0.0/files/stt_en_citrinet_1024_gamma_0_25.nemo", - ) - - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_es_citrinet_512", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_es_citrinet_512", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_es_citrinet_512/versions/1.0.0/files/stt_es_citrinet_512.nemo", - ) - - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_de_citrinet_1024", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_de_citrinet_1024", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_de_citrinet_1024/versions/1.5.0/files/stt_de_citrinet_1024.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_fr_citrinet_1024_gamma_0_25", - description="For details about this model, please visit https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/stt_fr_citrinet_1024_gamma_0_25", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_fr_citrinet_1024_gamma_0_25/versions/1.5/files/stt_fr_citrinet_1024_gamma_0_25.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_fr_no_hyphen_citrinet_1024_gamma_0_25", - description="For details about this model, please visit https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/stt_fr_citrinet_1024_gamma_0_25", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_fr_citrinet_1024_gamma_0_25/versions/1.5/files/stt_fr_no_hyphen_citrinet_1024_gamma_0_25.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_es_citrinet_1024_gamma_0_25", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_es_citrinet_1024_gamma_0_25", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_es_citrinet_1024_gamma_0_25/versions/1.8.0/files/stt_es_citrinet_1024_gamma_0_25.nemo", - ) - - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_conformer_ctc_small", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_conformer_ctc_small", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_conformer_ctc_small/versions/1.6.0/files/stt_en_conformer_ctc_small.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_conformer_ctc_medium", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_conformer_ctc_medium", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_conformer_ctc_medium/versions/1.6.0/files/stt_en_conformer_ctc_medium.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_conformer_ctc_large", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_conformer_ctc_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_conformer_ctc_large/versions/1.10.0/files/stt_en_conformer_ctc_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_conformer_ctc_xlarge", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_conformer_ctc_xlarge", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_conformer_ctc_xlarge/versions/1.10.0/files/stt_en_conformer_ctc_xlarge.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_conformer_ctc_small_ls", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_conformer_ctc_small_ls", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_conformer_ctc_small_ls/versions/1.0.0/files/stt_en_conformer_ctc_small_ls.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_conformer_ctc_medium_ls", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_conformer_ctc_medium_ls", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_conformer_ctc_medium_ls/versions/1.0.0/files/stt_en_conformer_ctc_medium_ls.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_conformer_ctc_large_ls", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_conformer_ctc_large_ls", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_conformer_ctc_large_ls/versions/1.0.0/files/stt_en_conformer_ctc_large_ls.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_fr_conformer_ctc_large", - description="For details about this model, please visit https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/stt_fr_conformer_ctc_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_fr_conformer_ctc_large/versions/1.5.1/files/stt_fr_conformer_ctc_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_fr_no_hyphen_conformer_ctc_large", - description="For details about this model, please visit https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/stt_fr_conformer_ctc_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_fr_conformer_ctc_large/versions/1.5.1/files/stt_fr_no_hyphen_conformer_ctc_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_de_conformer_ctc_large", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_de_conformer_ctc_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_de_conformer_ctc_large/versions/1.5.0/files/stt_de_conformer_ctc_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_es_conformer_ctc_large", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_es_conformer_ctc_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_es_conformer_ctc_large/versions/1.8.0/files/stt_es_conformer_ctc_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_hi_conformer_ctc_medium", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_hi_conformer_ctc_medium", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_hi_conformer_ctc_medium/versions/1.6.0/files/stt_hi_conformer_ctc_medium.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_mr_conformer_ctc_medium", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_mr_conformer_ctc_medium", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_mr_conformer_ctc_medium/versions/1.6.0/files/stt_mr_conformer_ctc_medium.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_enes_conformer_ctc_large", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_enes_conformer_ctc_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_enes_conformer_ctc_large/versions/1.0.0/files/stt_enes_conformer_ctc_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_ca_conformer_ctc_large", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_ca_conformer_ctc_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_ca_conformer_ctc_large/versions/1.11.0/files/stt_ca_conformer_ctc_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_rw_conformer_ctc_large", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_rw_conformer_ctc_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_rw_conformer_ctc_large/versions/1.11.0/files/stt_rw_conformer_ctc_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_enes_conformer_ctc_large_codesw", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_enes_conformer_ctc_large_codesw", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_enes_conformer_ctc_large_codesw/versions/1.0.0/files/stt_enes_conformer_ctc_large_codesw.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_be_conformer_ctc_large", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_be_conformer_ctc_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_be_conformer_ctc_large/versions/1.12.0/files/stt_be_conformer_ctc_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_hr_conformer_ctc_large", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_hr_conformer_ctc_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_hr_conformer_ctc_large/versions/1.11.0/files/stt_hr_conformer_ctc_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_it_conformer_ctc_large", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_it_conformer_ctc_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_it_conformer_ctc_large/versions/1.13.0/files/stt_it_conformer_ctc_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_ru_conformer_ctc_large", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_ru_conformer_ctc_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_ru_conformer_ctc_large/versions/1.13.0/files/stt_ru_conformer_ctc_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_eo_conformer_ctc_large", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_eo_conformer_ctc_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_eo_conformer_ctc_large/versions/1.14.0/files/stt_eo_conformer_ctc_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_fastconformer_ctc_large", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_fastconformer_ctc_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_fastconformer_ctc_large/versions/1.0.0/files/stt_en_fastconformer_ctc_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_fastconformer_ctc_large_ls", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_fastconformer_ctc_large_ls", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_fastconformer_ctc_large_ls/versions/1.0.0/files/stt_en_fastconformer_ctc_large_ls.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_fastconformer_ctc_xlarge", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_fastconformer_ctc_xlarge", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_fastconformer_ctc_xlarge/versions/1.20.0/files/stt_en_fastconformer_ctc_xlarge.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_fastconformer_ctc_xxlarge", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_fastconformer_ctc_xxlarge", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_fastconformer_ctc_xxlarge/versions/1.20.1/files/stt_en_fastconformer_ctc_xxlarge.nemo", - ) - results.append(model) - - return results diff --git a/nemo/collections/asr/models/ctc_models.py b/nemo/collections/asr/models/ctc_models.py deleted file mode 100644 index 00477092dff3fcaea89d1e61e254115ffef76af2..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/ctc_models.py +++ /dev/null @@ -1,826 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import copy -import os -from math import ceil -from typing import Any, Dict, List, Optional, Union - -import numpy as np -import torch -from lightning.pytorch import Trainer -from omegaconf import DictConfig, OmegaConf, open_dict -from torch.utils.data import DataLoader - -from nemo.collections.asr.data import audio_to_text_dataset -from nemo.collections.asr.data.audio_to_text import _AudioTextDataset -from nemo.collections.asr.data.audio_to_text_dali import AudioToCharDALIDataset, DALIOutputs -from nemo.collections.asr.data.audio_to_text_lhotse import LhotseSpeechToTextBpeDataset -from nemo.collections.asr.losses.ctc import CTCLoss -from nemo.collections.asr.metrics.wer import WER -from nemo.collections.asr.models.asr_model import ASRModel, ExportableEncDecModel -from nemo.collections.asr.parts.mixins import ASRModuleMixin, ASRTranscriptionMixin, InterCTCMixin, TranscribeConfig -from nemo.collections.asr.parts.mixins.transcription import GenericTranscriptionType, TranscriptionReturnType -from nemo.collections.asr.parts.preprocessing.segment import ChannelSelectorType -from nemo.collections.asr.parts.submodules.ctc_decoding import CTCDecoding, CTCDecodingConfig -from nemo.collections.asr.parts.utils.asr_batching import get_semi_sorted_batch_sampler -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis -from nemo.collections.asr.parts.utils.timestamp_utils import process_timestamp_outputs -from nemo.collections.common.data.lhotse import get_lhotse_dataloader_from_config -from nemo.collections.common.parts.preprocessing.parsers import make_parser -from nemo.core.classes.common import PretrainedModelInfo, typecheck -from nemo.core.classes.mixins import AccessMixin -from nemo.core.neural_types import AudioSignal, LabelsType, LengthsType, LogprobsType, NeuralType, SpectrogramType -from nemo.utils import logging - -__all__ = ['EncDecCTCModel'] - - -class EncDecCTCModel(ASRModel, ExportableEncDecModel, ASRModuleMixin, InterCTCMixin, ASRTranscriptionMixin): - """Base class for encoder decoder CTC-based models.""" - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - # Get global rank and total number of GPU workers for IterableDataset partitioning, if applicable - # Global_rank and local_rank is set by LightningModule in Lightning 1.2.0 - self.world_size = 1 - if trainer is not None: - self.world_size = trainer.world_size - - super().__init__(cfg=cfg, trainer=trainer) - self.preprocessor = EncDecCTCModel.from_config_dict(self._cfg.preprocessor) - self.encoder = EncDecCTCModel.from_config_dict(self._cfg.encoder) - - with open_dict(self._cfg): - if "feat_in" not in self._cfg.decoder or ( - not self._cfg.decoder.feat_in and hasattr(self.encoder, '_feat_out') - ): - self._cfg.decoder.feat_in = self.encoder._feat_out - if "feat_in" not in self._cfg.decoder or not self._cfg.decoder.feat_in: - raise ValueError("param feat_in of the decoder's config is not set!") - - if self.cfg.decoder.num_classes < 1 and self.cfg.decoder.vocabulary is not None: - logging.info( - "\nReplacing placeholder number of classes ({}) with actual number of classes - {}".format( - self.cfg.decoder.num_classes, len(self.cfg.decoder.vocabulary) - ) - ) - cfg.decoder["num_classes"] = len(self.cfg.decoder.vocabulary) - - self.decoder = EncDecCTCModel.from_config_dict(self._cfg.decoder) - - self.loss = CTCLoss( - num_classes=self.decoder.num_classes_with_blank - 1, - zero_infinity=True, - reduction=self._cfg.get("ctc_reduction", "mean_batch"), - ) - - if hasattr(self._cfg, 'spec_augment') and self._cfg.spec_augment is not None: - self.spec_augmentation = EncDecCTCModel.from_config_dict(self._cfg.spec_augment) - else: - self.spec_augmentation = None - - # Setup decoding objects - decoding_cfg = self.cfg.get('decoding', None) - - # In case decoding config not found, use default config - if decoding_cfg is None: - decoding_cfg = OmegaConf.structured(CTCDecodingConfig) - with open_dict(self.cfg): - self.cfg.decoding = decoding_cfg - - self.decoding = CTCDecoding(self.cfg.decoding, vocabulary=OmegaConf.to_container(self.decoder.vocabulary)) - - # Setup metric with decoding strategy - self.wer = WER( - decoding=self.decoding, - use_cer=self._cfg.get('use_cer', False), - dist_sync_on_step=True, - log_prediction=self._cfg.get("log_prediction", False), - ) - - # Setup optional Optimization flags - self.setup_optimization_flags() - - # setting up interCTC loss (from InterCTCMixin) - self.setup_interctc(decoder_name='decoder', loss_name='loss', wer_name='wer') - - # Adapter modules setup (from ASRAdapterModelMixin) - self.setup_adapters() - - def transcribe( - self, - audio: Union[str, List[str], torch.Tensor, np.ndarray, DataLoader], - batch_size: int = 4, - return_hypotheses: bool = False, - num_workers: int = 0, - channel_selector: Optional[ChannelSelectorType] = None, - augmentor: DictConfig = None, - verbose: bool = True, - timestamps: Optional[bool] = None, - override_config: Optional[TranscribeConfig] = None, - ) -> TranscriptionReturnType: - """ - Uses greedy decoding to transcribe audio files. Use this method for debugging and prototyping. - - Args: - audio: (a single or list) of paths to audio files or a np.ndarray/tensor audio array or - path to a manifest file. - Can also be a dataloader object that provides values that can be consumed by the model. - Recommended length per file is between 5 and 25 seconds. \ - But it is possible to pass a few hours long file if enough GPU memory is available. - batch_size: (int) batch size to use during inference. - Bigger will result in better throughput performance but would use more memory. - return_hypotheses: (bool) Either return hypotheses or text - With hypotheses can do some postprocessing like getting timestamp or rescoring - num_workers: (int) number of workers for DataLoader - 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`. - augmentor: (DictConfig): Augment audio samples during transcription if augmentor is applied. - timestamps: Optional(Bool): timestamps will be returned if set to True as part of hypothesis - object (output.timestep['segment']/output.timestep['word']). Refer to `Hypothesis` class - for more details. Default is None and would retain the previous state set by - using self.change_decoding_strategy(). - verbose: (bool) whether to display tqdm progress bar - override_config: (Optional[TranscribeConfig]) override transcription config pre-defined by the user. - **Note**: All other arguments in the function will be ignored if override_config is passed. - You should call this argument as `model.transcribe(audio, override_config=TranscribeConfig(...))`. - - Returns: - A list of transcriptions (or raw log probabilities if logprobs is True) in the same order as - paths2audio_files - """ - timestamps = timestamps or (override_config.timestamps if override_config is not None else None) - if timestamps is not None: - # else retain the decoder state (users can set it using change_decoding_strategy) - if timestamps or (override_config is not None and override_config.timestamps): - logging.info( - "Timestamps requested, setting decoding timestamps to True. Capture them in Hypothesis object, \ - with output[idx].timestep['word'/'segment'/'char']" - ) - return_hypotheses = True - with open_dict(self.cfg.decoding): - self.cfg.decoding.compute_timestamps = True - self.change_decoding_strategy(self.cfg.decoding, verbose=False) - else: # This is done to ensure the state is preserved when decoding_strategy is set outside - with open_dict(self.cfg.decoding): - self.cfg.decoding.compute_timestamps = self.cfg.decoding.get('compute_timestamps', False) - self.cfg.decoding.preserve_alignments = self.cfg.decoding.get('preserve_alignments', False) - self.change_decoding_strategy(self.cfg.decoding, verbose=False) - - return super().transcribe( - audio=audio, - batch_size=batch_size, - return_hypotheses=return_hypotheses, - num_workers=num_workers, - channel_selector=channel_selector, - augmentor=augmentor, - verbose=verbose, - timestamps=timestamps, - override_config=override_config, - ) - - def change_vocabulary(self, new_vocabulary: List[str], decoding_cfg: Optional[DictConfig] = None): - """ - Changes vocabulary used during CTC decoding process. Use this method when fine-tuning on from pre-trained model. - This method changes only decoder and leaves encoder and pre-processing modules unchanged. For example, you would - use it if you want to use pretrained encoder when fine-tuning on a data in another language, or when you'd need - model to learn capitalization, punctuation and/or special characters. - - If new_vocabulary == self.decoder.vocabulary then nothing will be changed. - - Args: - - new_vocabulary: list with new vocabulary. Must contain at least 2 elements. Typically, \ - this is target alphabet. - - Returns: None - - """ - if self.decoder.vocabulary == new_vocabulary: - logging.warning(f"Old {self.decoder.vocabulary} and new {new_vocabulary} match. Not changing anything.") - else: - if new_vocabulary is None or len(new_vocabulary) == 0: - raise ValueError(f'New vocabulary must be non-empty list of chars. But I got: {new_vocabulary}') - decoder_config = self.decoder.to_config_dict() - new_decoder_config = copy.deepcopy(decoder_config) - new_decoder_config['vocabulary'] = new_vocabulary - new_decoder_config['num_classes'] = len(new_vocabulary) - - del self.decoder - self.decoder = EncDecCTCModel.from_config_dict(new_decoder_config) - del self.loss - self.loss = CTCLoss( - num_classes=self.decoder.num_classes_with_blank - 1, - zero_infinity=True, - reduction=self._cfg.get("ctc_reduction", "mean_batch"), - ) - - if decoding_cfg is None: - # Assume same decoding config as before - decoding_cfg = self.cfg.decoding - - # Assert the decoding config with all hyper parameters - decoding_cls = OmegaConf.structured(CTCDecodingConfig) - decoding_cls = OmegaConf.create(OmegaConf.to_container(decoding_cls)) - decoding_cfg = OmegaConf.merge(decoding_cls, decoding_cfg) - - self.decoding = CTCDecoding( - decoding_cfg=decoding_cfg, vocabulary=OmegaConf.to_container(self.decoder.vocabulary) - ) - - self.wer = WER( - decoding=self.decoding, - use_cer=self._cfg.get('use_cer', False), - dist_sync_on_step=True, - log_prediction=self._cfg.get("log_prediction", False), - ) - - # Update config - with open_dict(self.cfg.decoder): - self._cfg.decoder = new_decoder_config - - with open_dict(self.cfg.decoding): - self.cfg.decoding = decoding_cfg - - ds_keys = ['train_ds', 'validation_ds', 'test_ds'] - for key in ds_keys: - if key in self.cfg: - with open_dict(self.cfg[key]): - self.cfg[key]['labels'] = OmegaConf.create(new_vocabulary) - - logging.info(f"Changed decoder to output to {self.decoder.vocabulary} vocabulary.") - - def change_decoding_strategy(self, decoding_cfg: DictConfig, verbose: bool = True): - """ - Changes decoding strategy used during CTC decoding process. - - Args: - decoding_cfg: A config for the decoder, which is optional. If the decoding type - needs to be changed (from say Greedy to Beam decoding etc), the config can be passed here. - verbose: (bool) whether to display logging information - """ - if decoding_cfg is None: - # Assume same decoding config as before - logging.info("No `decoding_cfg` passed when changing decoding strategy, using internal config") - decoding_cfg = self.cfg.decoding - - # Assert the decoding config with all hyper parameters - decoding_cls = OmegaConf.structured(CTCDecodingConfig) - decoding_cls = OmegaConf.create(OmegaConf.to_container(decoding_cls)) - decoding_cfg = OmegaConf.merge(decoding_cls, decoding_cfg) - - self.decoding = CTCDecoding( - decoding_cfg=decoding_cfg, vocabulary=OmegaConf.to_container(self.decoder.vocabulary) - ) - - self.wer = WER( - decoding=self.decoding, - use_cer=self.wer.use_cer, - log_prediction=self.wer.log_prediction, - dist_sync_on_step=True, - ) - - self.decoder.temperature = decoding_cfg.get('temperature', 1.0) - - # Update config - with open_dict(self.cfg.decoding): - self.cfg.decoding = decoding_cfg - - if verbose: - logging.info(f"Changed decoding strategy to \n{OmegaConf.to_yaml(self.cfg.decoding)}") - - def _setup_dataloader_from_config(self, config: Optional[Dict]): - # Automatically inject args from model config to dataloader config - audio_to_text_dataset.inject_dataloader_value_from_model_config(self.cfg, config, key='sample_rate') - audio_to_text_dataset.inject_dataloader_value_from_model_config(self.cfg, config, key='labels') - - if config.get("use_lhotse"): - return get_lhotse_dataloader_from_config( - config, - # During transcription, the model is initially loaded on the CPU. - # To ensure the correct global_rank and world_size are set, - # these values must be passed from the configuration. - global_rank=self.global_rank if not config.get("do_transcribe", False) else config.get("global_rank"), - world_size=self.world_size if not config.get("do_transcribe", False) else config.get("world_size"), - dataset=LhotseSpeechToTextBpeDataset( - tokenizer=make_parser( - labels=config.get('labels', None), - name=config.get('parser', 'en'), - unk_id=config.get('unk_index', -1), - blank_id=config.get('blank_index', -1), - do_normalize=config.get('normalize_transcripts', False), - ), - return_cuts=config.get("do_transcribe", False), - ), - ) - - dataset = audio_to_text_dataset.get_audio_to_text_char_dataset_from_config( - config=config, - local_rank=self.local_rank, - global_rank=self.global_rank, - world_size=self.world_size, - preprocessor_cfg=self._cfg.get("preprocessor", None), - ) - - if dataset is None: - return None - - if isinstance(dataset, AudioToCharDALIDataset): - # DALI Dataset implements dataloader interface - return dataset - - shuffle = config['shuffle'] - if isinstance(dataset, torch.utils.data.IterableDataset): - shuffle = False - - if hasattr(dataset, 'collate_fn'): - collate_fn = dataset.collate_fn - elif hasattr(dataset.datasets[0], 'collate_fn'): - # support datasets that are lists of entries - collate_fn = dataset.datasets[0].collate_fn - else: - # support datasets that are lists of lists - collate_fn = dataset.datasets[0].datasets[0].collate_fn - - batch_sampler = None - if config.get('use_semi_sorted_batching', False): - if not isinstance(dataset, _AudioTextDataset): - raise RuntimeError( - "Semi Sorted Batch sampler can be used with AudioToCharDataset or AudioToBPEDataset " - f"but found dataset of type {type(dataset)}" - ) - # set batch_size and batch_sampler to None to disable automatic batching - batch_sampler = get_semi_sorted_batch_sampler(self, dataset, config) - config['batch_size'] = None - config['drop_last'] = False - shuffle = False - - return torch.utils.data.DataLoader( - dataset=dataset, - batch_size=config['batch_size'], - sampler=batch_sampler, - batch_sampler=None, - collate_fn=collate_fn, - drop_last=config.get('drop_last', False), - shuffle=shuffle, - num_workers=config.get('num_workers', 0), - pin_memory=config.get('pin_memory', False), - ) - - def setup_training_data(self, train_data_config: Optional[Union[DictConfig, Dict]]): - """ - Sets up the training data loader via a Dict-like object. - - Args: - train_data_config: A config that contains the information regarding construction - of an ASR Training dataset. - - Supported Datasets: - - :class:`~nemo.collections.asr.data.audio_to_text.AudioToCharDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.AudioToBPEDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.TarredAudioToCharDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.TarredAudioToBPEDataset` - - :class:`~nemo.collections.asr.data.audio_to_text_dali.AudioToCharDALIDataset` - """ - if 'shuffle' not in train_data_config: - train_data_config['shuffle'] = True - - # preserve config - self._update_dataset_config(dataset_name='train', config=train_data_config) - - self._train_dl = self._setup_dataloader_from_config(config=train_data_config) - - # Need to set this because if using an IterableDataset, the length of the dataloader is the total number - # of samples rather than the number of batches, and this messes up the tqdm progress bar. - # So we set the number of steps manually (to the correct number) to fix this. - if ( - self._train_dl is not None - and hasattr(self._train_dl, 'dataset') - and isinstance(self._train_dl.dataset, torch.utils.data.IterableDataset) - ): - # We also need to check if limit_train_batches is already set. - # If it's an int, we assume that the user has set it to something sane, i.e. <= # training batches, - # and don't change it. Otherwise, adjust batches accordingly if it's a float (including 1.0). - if self._trainer is not None and isinstance(self._trainer.limit_train_batches, float): - self._trainer.limit_train_batches = int( - self._trainer.limit_train_batches - * ceil((len(self._train_dl.dataset) / self.world_size) / train_data_config['batch_size']) - ) - elif self._trainer is None: - logging.warning( - "Model Trainer was not set before constructing the dataset, incorrect number of " - "training batches will be used. Please set the trainer and rebuild the dataset." - ) - - def setup_validation_data(self, val_data_config: Optional[Union[DictConfig, Dict]]): - """ - Sets up the validation data loader via a Dict-like object. - - Args: - val_data_config: A config that contains the information regarding construction - of an ASR Training dataset. - - Supported Datasets: - - :class:`~nemo.collections.asr.data.audio_to_text.AudioToCharDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.AudioToBPEDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.TarredAudioToCharDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.TarredAudioToBPEDataset` - - :class:`~nemo.collections.asr.data.audio_to_text_dali.AudioToCharDALIDataset` - """ - if 'shuffle' not in val_data_config: - val_data_config['shuffle'] = False - - # preserve config - self._update_dataset_config(dataset_name='validation', config=val_data_config) - - self._validation_dl = self._setup_dataloader_from_config(config=val_data_config) - - def setup_test_data(self, test_data_config: Optional[Union[DictConfig, Dict]]): - """ - Sets up the test data loader via a Dict-like object. - - Args: - test_data_config: A config that contains the information regarding construction - of an ASR Training dataset. - - Supported Datasets: - - :class:`~nemo.collections.asr.data.audio_to_text.AudioToCharDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.AudioToBPEDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.TarredAudioToCharDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.TarredAudioToBPEDataset` - - :class:`~nemo.collections.asr.data.audio_to_text_dali.AudioToCharDALIDataset` - """ - if 'shuffle' not in test_data_config: - test_data_config['shuffle'] = False - - # preserve config - self._update_dataset_config(dataset_name='test', config=test_data_config) - - self._test_dl = self._setup_dataloader_from_config(config=test_data_config) - - @property - def input_types(self) -> Optional[Dict[str, NeuralType]]: - if hasattr(self.preprocessor, '_sample_rate'): - input_signal_eltype = AudioSignal(freq=self.preprocessor._sample_rate) - else: - input_signal_eltype = AudioSignal() - return { - "input_signal": NeuralType(('B', 'T'), input_signal_eltype, optional=True), - "input_signal_length": NeuralType(tuple('B'), LengthsType(), optional=True), - "processed_signal": NeuralType(('B', 'D', 'T'), SpectrogramType(), optional=True), - "processed_signal_length": NeuralType(tuple('B'), LengthsType(), optional=True), - "sample_id": NeuralType(tuple('B'), LengthsType(), optional=True), - } - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - return { - "outputs": NeuralType(('B', 'T', 'D'), LogprobsType()), - "encoded_lengths": NeuralType(tuple('B'), LengthsType()), - "greedy_predictions": NeuralType(('B', 'T'), LabelsType()), - } - - @typecheck() - def forward( - self, input_signal=None, input_signal_length=None, processed_signal=None, processed_signal_length=None - ): - """ - Forward pass of the model. - - Args: - input_signal: Tensor that represents a batch of raw audio signals, - of shape [B, T]. T here represents timesteps, with 1 second of audio represented as - `self.sample_rate` number of floating point values. - input_signal_length: Vector of length B, that contains the individual lengths of the audio - sequences. - processed_signal: Tensor that represents a batch of processed audio signals, - of shape (B, D, T) that has undergone processing via some DALI preprocessor. - processed_signal_length: Vector of length B, that contains the individual lengths of the - processed audio sequences. - - Returns: - A tuple of 3 elements - - 1) The log probabilities tensor of shape [B, T, D]. - 2) The lengths of the acoustic sequence after propagation through the encoder, of shape [B]. - 3) The greedy token predictions of the model of shape [B, T] (via argmax) - """ - has_input_signal = input_signal is not None and input_signal_length is not None - has_processed_signal = processed_signal is not None and processed_signal_length is not None - if (has_input_signal ^ has_processed_signal) == False: - raise ValueError( - f"{self} Arguments ``input_signal`` and ``input_signal_length`` are mutually exclusive " - " with ``processed_signal`` and ``processed_signal_len`` arguments." - ) - - if not has_processed_signal: - processed_signal, processed_signal_length = self.preprocessor( - input_signal=input_signal, - length=input_signal_length, - ) - - if self.spec_augmentation is not None and self.training: - processed_signal = self.spec_augmentation(input_spec=processed_signal, length=processed_signal_length) - - encoder_output = self.encoder(audio_signal=processed_signal, length=processed_signal_length) - encoded = encoder_output[0] - encoded_len = encoder_output[1] - log_probs = self.decoder(encoder_output=encoded) - greedy_predictions = log_probs.argmax(dim=-1, keepdim=False) - - return ( - log_probs, - encoded_len, - greedy_predictions, - ) - - # PTL-specific methods - def training_step(self, batch, batch_nb): - # Reset access registry - if AccessMixin.is_access_enabled(self.model_guid): - AccessMixin.reset_registry(self) - - if self.is_interctc_enabled(): - AccessMixin.set_access_enabled(access_enabled=True, guid=self.model_guid) - - signal, signal_len, transcript, transcript_len = batch - if isinstance(batch, DALIOutputs) and batch.has_processed_signal: - log_probs, encoded_len, predictions = self.forward( - processed_signal=signal, processed_signal_length=signal_len - ) - else: - log_probs, encoded_len, predictions = self.forward(input_signal=signal, input_signal_length=signal_len) - - if hasattr(self, '_trainer') and self._trainer is not None: - log_every_n_steps = self._trainer.log_every_n_steps - else: - log_every_n_steps = 1 - - loss_value = self.loss( - log_probs=log_probs, targets=transcript, input_lengths=encoded_len, target_lengths=transcript_len - ) - - # Add auxiliary losses, if registered - loss_value = self.add_auxiliary_losses(loss_value) - # only computing WER when requested in the logs (same as done for final-layer WER below) - loss_value, tensorboard_logs = self.add_interctc_losses( - loss_value, transcript, transcript_len, compute_wer=((batch_nb + 1) % log_every_n_steps == 0) - ) - - # Reset access registry - if AccessMixin.is_access_enabled(self.model_guid): - AccessMixin.reset_registry(self) - - tensorboard_logs.update( - { - 'train_loss': loss_value, - 'learning_rate': self._optimizer.param_groups[0]['lr'], - 'global_step': torch.tensor(self.trainer.global_step, dtype=torch.float32), - } - ) - - if (batch_nb + 1) % log_every_n_steps == 0: - self.wer.update( - predictions=log_probs, - targets=transcript, - targets_lengths=transcript_len, - predictions_lengths=encoded_len, - ) - wer, _, _ = self.wer.compute() - self.wer.reset() - tensorboard_logs.update({'training_batch_wer': wer}) - - return {'loss': loss_value, 'log': tensorboard_logs} - - def predict_step(self, batch, batch_idx, dataloader_idx=0): - signal, signal_len, transcript, transcript_len, sample_id = batch - if isinstance(batch, DALIOutputs) and batch.has_processed_signal: - log_probs, encoded_len, predictions = self.forward( - processed_signal=signal, processed_signal_length=signal_len - ) - else: - log_probs, encoded_len, predictions = self.forward(input_signal=signal, input_signal_length=signal_len) - - transcribed_texts = self.wer.decoding.ctc_decoder_predictions_tensor( - decoder_outputs=log_probs, - decoder_lengths=encoded_len, - return_hypotheses=False, - ) - - if isinstance(sample_id, torch.Tensor): - sample_id = sample_id.cpu().detach().numpy() - return list(zip(sample_id, transcribed_texts)) - - def validation_pass(self, batch, batch_idx, dataloader_idx=0): - if self.is_interctc_enabled(): - AccessMixin.set_access_enabled(access_enabled=True, guid=self.model_guid) - - signal, signal_len, transcript, transcript_len = batch - if isinstance(batch, DALIOutputs) and batch.has_processed_signal: - log_probs, encoded_len, predictions = self.forward( - processed_signal=signal, processed_signal_length=signal_len - ) - else: - log_probs, encoded_len, predictions = self.forward(input_signal=signal, input_signal_length=signal_len) - - loss_value = self.loss( - log_probs=log_probs, targets=transcript, input_lengths=encoded_len, target_lengths=transcript_len - ) - loss_value, metrics = self.add_interctc_losses( - loss_value, - transcript, - transcript_len, - compute_wer=True, - log_wer_num_denom=True, - log_prefix="val_", - ) - - self.wer.update( - predictions=log_probs, - targets=transcript, - targets_lengths=transcript_len, - predictions_lengths=encoded_len, - ) - wer, wer_num, wer_denom = self.wer.compute() - self.wer.reset() - metrics.update({'val_loss': loss_value, 'val_wer_num': wer_num, 'val_wer_denom': wer_denom, 'val_wer': wer}) - - self.log('global_step', torch.tensor(self.trainer.global_step, dtype=torch.float32)) - - # Reset access registry - if AccessMixin.is_access_enabled(self.model_guid): - AccessMixin.reset_registry(self) - - return metrics - - def validation_step(self, batch, batch_idx, dataloader_idx=0): - metrics = self.validation_pass(batch, batch_idx, dataloader_idx) - if type(self.trainer.val_dataloaders) == list and len(self.trainer.val_dataloaders) > 1: - self.validation_step_outputs[dataloader_idx].append(metrics) - else: - self.validation_step_outputs.append(metrics) - return metrics - - def multi_validation_epoch_end(self, outputs, dataloader_idx: int = 0): - metrics = super().multi_validation_epoch_end(outputs, dataloader_idx) - self.finalize_interctc_metrics(metrics, outputs, prefix="val_") - return metrics - - def multi_test_epoch_end(self, outputs, dataloader_idx: int = 0): - metrics = super().multi_test_epoch_end(outputs, dataloader_idx) - self.finalize_interctc_metrics(metrics, outputs, prefix="test_") - return metrics - - def test_step(self, batch, batch_idx, dataloader_idx=0): - logs = self.validation_pass(batch, batch_idx, dataloader_idx=dataloader_idx) - test_logs = {name.replace("val_", "test_"): value for name, value in logs.items()} - if type(self.trainer.test_dataloaders) == list and len(self.trainer.test_dataloaders) > 1: - self.test_step_outputs[dataloader_idx].append(test_logs) - else: - self.test_step_outputs.append(test_logs) - return test_logs - - def test_dataloader(self): - if self._test_dl is not None: - return self._test_dl - - """ Transcription related methods """ - - def _transcribe_forward(self, batch: Any, trcfg: TranscribeConfig): - logits, logits_len, greedy_predictions = self.forward(input_signal=batch[0], input_signal_length=batch[1]) - output = dict(logits=logits, logits_len=logits_len) - del greedy_predictions - return output - - def _transcribe_output_processing(self, outputs, trcfg: TranscribeConfig) -> GenericTranscriptionType: - logits = outputs.pop('logits') - logits_len = outputs.pop('logits_len') - - hypotheses = self.decoding.ctc_decoder_predictions_tensor( - logits, - decoder_lengths=logits_len, - return_hypotheses=trcfg.return_hypotheses, - ) - if trcfg.return_hypotheses: - if logits.is_cuda: - # See comment in - # ctc_greedy_decoding.py::GreedyCTCInfer::forward() to - # understand this idiom. - logits_cpu = torch.empty(logits.shape, dtype=logits.dtype, device=torch.device("cpu"), pin_memory=True) - logits_cpu.copy_(logits, non_blocking=True) - else: - logits_cpu = logits - logits_len = logits_len.cpu() - # dump log probs per file - for idx in range(logits_cpu.shape[0]): - # We clone because we don't want references to the - # cudaMallocHost()-allocated tensor to be floating - # around. Were that to be the case, then the pinned - # memory cache would always miss. - hypotheses[idx].y_sequence = logits_cpu[idx, : logits_len[idx]].clone() - if hypotheses[idx].alignments is None: - hypotheses[idx].alignments = hypotheses[idx].y_sequence - del logits_cpu - - # cleanup memory - del logits, logits_len - - if trcfg.timestamps: - hypotheses = process_timestamp_outputs( - hypotheses, self.encoder.subsampling_factor, self.cfg['preprocessor']['window_stride'] - ) - - return hypotheses - - def get_best_hyptheses(self, all_hypothesis: list[list[Hypothesis]]): - return [hyp[0] for hyp in all_hypothesis] - - def _setup_transcribe_dataloader(self, config: Dict) -> 'torch.utils.data.DataLoader': - """ - Setup function for a temporary data loader which wraps the provided audio file. - - Args: - config: A python dictionary which contains the following keys: - paths2audio_files: (a list) of paths to audio files. The files should be relatively short fragments. \ - Recommended length per file is between 5 and 25 seconds. - batch_size: (int) batch size to use during inference. \ - Bigger will result in better throughput performance but would use more memory. - temp_dir: (str) A temporary directory where the audio manifest is temporarily - stored. - num_workers: (int) number of workers. Depends of the batch_size and machine. \ - 0 - only the main process will load batches, 1 - one worker (not main process) - - Returns: - A pytorch DataLoader for the given audio file(s). - """ - if 'manifest_filepath' in config: - manifest_filepath = config['manifest_filepath'] - batch_size = config['batch_size'] - else: - manifest_filepath = os.path.join(config['temp_dir'], 'manifest.json') - batch_size = min(config['batch_size'], len(config['paths2audio_files'])) - - dl_config = { - 'manifest_filepath': manifest_filepath, - 'sample_rate': self.preprocessor._sample_rate, - 'labels': OmegaConf.to_container(self.decoder.vocabulary), - 'batch_size': batch_size, - 'trim_silence': False, - 'shuffle': False, - 'num_workers': config.get('num_workers', min(batch_size, os.cpu_count() - 1)), - 'pin_memory': True, - 'channel_selector': config.get('channel_selector', None), - } - if config.get("augmentor"): - dl_config['augmentor'] = config.get("augmentor") - - temporary_datalayer = self._setup_dataloader_from_config(config=DictConfig(dl_config)) - return temporary_datalayer - - @classmethod - def list_available_models(cls) -> List[PretrainedModelInfo]: - """ - This method returns a list of pre-trained model which can be instantiated directly from NVIDIA's NGC cloud. - - Returns: - List of available pre-trained models. - """ - results = [] - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_jasper10x5dr", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_jasper10x5dr", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_jasper10x5dr/versions/1.0.0rc1/files/stt_en_jasper10x5dr.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="asr_talknet_aligner", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:asr_talknet_aligner", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/asr_talknet_aligner/versions/1.0.0rc1/files/qn5x5_libri_tts_phonemes.nemo", - ) - results.append(model) - - return results - - @property - def adapter_module_names(self) -> List[str]: - return ['', 'encoder', 'decoder'] - - @property - def wer(self): - return self._wer - - @wer.setter - def wer(self, wer): - self._wer = wer diff --git a/nemo/collections/asr/models/hybrid_rnnt_ctc_bpe_models.py b/nemo/collections/asr/models/hybrid_rnnt_ctc_bpe_models.py deleted file mode 100644 index 0b41587971019c8b161598b6cea61c99fd0a6294..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/hybrid_rnnt_ctc_bpe_models.py +++ /dev/null @@ -1,641 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import copy -import os -from typing import Dict, List, Optional, Union - -import torch -from lightning.pytorch import Trainer -from omegaconf import DictConfig, ListConfig, OmegaConf, open_dict - -from nemo.collections.asr.data import audio_to_text_dataset -from nemo.collections.asr.data.audio_to_text import _AudioTextDataset -from nemo.collections.asr.data.audio_to_text_dali import AudioToBPEDALIDataset -from nemo.collections.asr.data.audio_to_text_lhotse import LhotseSpeechToTextBpeDataset -from nemo.collections.asr.losses.ctc import CTCLoss -from nemo.collections.asr.losses.rnnt import RNNTLoss -from nemo.collections.asr.metrics.wer import WER -from nemo.collections.asr.models.hybrid_rnnt_ctc_models import EncDecHybridRNNTCTCModel -from nemo.collections.asr.parts.mixins import ASRBPEMixin -from nemo.collections.asr.parts.submodules.ctc_decoding import CTCBPEDecoding, CTCBPEDecodingConfig -from nemo.collections.asr.parts.submodules.rnnt_decoding import RNNTBPEDecoding, RNNTBPEDecodingConfig -from nemo.collections.asr.parts.utils.asr_batching import get_semi_sorted_batch_sampler -from nemo.collections.common.data.lhotse import get_lhotse_dataloader_from_config -from nemo.core.classes.common import PretrainedModelInfo -from nemo.utils import logging, model_utils - - -class EncDecHybridRNNTCTCBPEModel(EncDecHybridRNNTCTCModel, ASRBPEMixin): - """Base class for encoder decoder RNNT-based models with auxiliary CTC decoder/loss and subword tokenization.""" - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - # Convert to Hydra 1.0 compatible DictConfig - cfg = model_utils.convert_model_config_to_dict_config(cfg) - cfg = model_utils.maybe_update_config_version(cfg, make_copy=False) - - # Tokenizer is necessary for this model - if 'tokenizer' not in cfg: - raise ValueError("`cfg` must have `tokenizer` config to create a tokenizer !") - - if not isinstance(cfg, DictConfig): - cfg = OmegaConf.create(cfg) - - # Setup the tokenizer - self._setup_tokenizer(cfg.tokenizer) - - # Initialize a dummy vocabulary - vocabulary = self.tokenizer.tokenizer.get_vocab() - - # Set the new vocabulary - with open_dict(cfg): - cfg.labels = ListConfig(list(vocabulary)) - - with open_dict(cfg.decoder): - cfg.decoder.vocab_size = len(vocabulary) - - with open_dict(cfg.joint): - cfg.joint.num_classes = len(vocabulary) - cfg.joint.vocabulary = ListConfig(list(vocabulary)) - cfg.joint.jointnet.encoder_hidden = cfg.model_defaults.enc_hidden - cfg.joint.jointnet.pred_hidden = cfg.model_defaults.pred_hidden - - # setup auxiliary CTC decoder - if 'aux_ctc' not in cfg: - raise ValueError( - "The config need to have a section for the CTC decoder named as aux_ctc for Hybrid models." - ) - - with open_dict(cfg): - if self.tokenizer_type == "agg": - cfg.aux_ctc.decoder.vocabulary = ListConfig(vocabulary) - else: - cfg.aux_ctc.decoder.vocabulary = ListConfig(list(vocabulary.keys())) - - if cfg.aux_ctc.decoder["num_classes"] < 1: - logging.info( - "\nReplacing placholder number of classes ({}) with actual number of classes - {}".format( - cfg.aux_ctc.decoder["num_classes"], len(vocabulary) - ) - ) - cfg.aux_ctc.decoder["num_classes"] = len(vocabulary) - - super().__init__(cfg=cfg, trainer=trainer) - - self.cfg.decoding = self.set_decoding_type_according_to_loss(self.cfg.decoding) - # Setup decoding object - self.decoding = RNNTBPEDecoding( - decoding_cfg=self.cfg.decoding, - decoder=self.decoder, - joint=self.joint, - tokenizer=self.tokenizer, - ) - - # Setup wer object - self.wer = WER( - decoding=self.decoding, - batch_dim_index=0, - use_cer=self.cfg.get('use_cer', False), - log_prediction=self.cfg.get('log_prediction', True), - dist_sync_on_step=True, - ) - - # Setup fused Joint step if flag is set - if self.joint.fuse_loss_wer: - self.joint.set_loss(self.loss) - self.joint.set_wer(self.wer) - - # Setup CTC decoding - ctc_decoding_cfg = self.cfg.aux_ctc.get('decoding', None) - if ctc_decoding_cfg is None: - ctc_decoding_cfg = OmegaConf.structured(CTCBPEDecodingConfig) - with open_dict(self.cfg.aux_ctc): - self.cfg.aux_ctc.decoding = ctc_decoding_cfg - self.ctc_decoding = CTCBPEDecoding(self.cfg.aux_ctc.decoding, tokenizer=self.tokenizer) - - # Setup CTC WER - self.ctc_wer = WER( - decoding=self.ctc_decoding, - use_cer=self.cfg.aux_ctc.get('use_cer', False), - dist_sync_on_step=True, - log_prediction=self.cfg.get("log_prediction", False), - ) - - # setting the RNNT decoder as the default one - self.cur_decoder = "rnnt" - - def _setup_dataloader_from_config(self, config: Optional[Dict]): - - if config.get("use_lhotse"): - return get_lhotse_dataloader_from_config( - config, - # During transcription, the model is initially loaded on the CPU. - # To ensure the correct global_rank and world_size are set, - # these values must be passed from the configuration. - global_rank=self.global_rank if not config.get("do_transcribe", False) else config.get("global_rank"), - world_size=self.world_size if not config.get("do_transcribe", False) else config.get("world_size"), - dataset=LhotseSpeechToTextBpeDataset( - tokenizer=self.tokenizer, - return_cuts=config.get("do_transcribe", False), - ), - tokenizer=self.tokenizer, - ) - - dataset = audio_to_text_dataset.get_audio_to_text_bpe_dataset_from_config( - config=config, - local_rank=self.local_rank, - global_rank=self.global_rank, - world_size=self.world_size, - tokenizer=self.tokenizer, - preprocessor_cfg=self.cfg.get("preprocessor", None), - ) - - if dataset is None: - return None - - if isinstance(dataset, AudioToBPEDALIDataset): - # DALI Dataset implements dataloader interface - return dataset - - shuffle = config['shuffle'] - if isinstance(dataset, torch.utils.data.IterableDataset): - shuffle = False - - if hasattr(dataset, 'collate_fn'): - collate_fn = dataset.collate_fn - elif hasattr(dataset.datasets[0], 'collate_fn'): - # support datasets that are lists of entries - collate_fn = dataset.datasets[0].collate_fn - else: - # support datasets that are lists of lists - collate_fn = dataset.datasets[0].datasets[0].collate_fn - - batch_sampler = None - if config.get('use_semi_sorted_batching', False): - if not isinstance(dataset, _AudioTextDataset): - raise RuntimeError( - "Semi Sorted Batch sampler can be used with AudioToCharDataset or AudioToBPEDataset " - f"but found dataset of type {type(dataset)}" - ) - # set batch_size and batch_sampler to None to disable automatic batching - batch_sampler = get_semi_sorted_batch_sampler(self, dataset, config) - config['batch_size'] = None - config['drop_last'] = False - shuffle = False - - return torch.utils.data.DataLoader( - dataset=dataset, - batch_size=config['batch_size'], - sampler=batch_sampler, - batch_sampler=None, - collate_fn=collate_fn, - drop_last=config.get('drop_last', False), - shuffle=shuffle, - num_workers=config.get('num_workers', 0), - pin_memory=config.get('pin_memory', False), - ) - - def _setup_transcribe_dataloader(self, config: Dict) -> 'torch.utils.data.DataLoader': - """ - Setup function for a temporary data loader which wraps the provided audio file. - - Args: - config: A python dictionary which contains the following keys: - paths2audio_files: (a list) of paths to audio files. The files should be relatively short fragments. \ - Recommended length per file is between 5 and 25 seconds. - batch_size: (int) batch size to use during inference. \ - Bigger will result in better throughput performance but would use more memory. - temp_dir: (str) A temporary directory where the audio manifest is temporarily - stored. - num_workers: (int) number of workers. Depends of the batch_size and machine. \ - 0 - only the main process will load batches, 1 - one worker (not main process) - - Returns: - A pytorch DataLoader for the given audio file(s). - """ - - if 'manifest_filepath' in config: - manifest_filepath = config['manifest_filepath'] - batch_size = config['batch_size'] - else: - manifest_filepath = os.path.join(config['temp_dir'], 'manifest.json') - batch_size = min(config['batch_size'], len(config['paths2audio_files'])) - - dl_config = { - 'use_lhotse': config.get('use_lhotse', True), - 'manifest_filepath': manifest_filepath, - 'sample_rate': self.preprocessor._sample_rate, - 'batch_size': batch_size, - 'shuffle': False, - 'num_workers': config.get('num_workers', min(batch_size, os.cpu_count() - 1)), - 'pin_memory': True, - 'channel_selector': config.get('channel_selector', None), - 'use_start_end_token': self.cfg.validation_ds.get('use_start_end_token', False), - } - - if config.get("augmentor"): - dl_config['augmentor'] = config.get("augmentor") - - temporary_datalayer = self._setup_dataloader_from_config(config=DictConfig(dl_config)) - return temporary_datalayer - - def change_vocabulary( - self, - new_tokenizer_dir: Union[str, DictConfig], - new_tokenizer_type: str, - decoding_cfg: Optional[DictConfig] = None, - ctc_decoding_cfg: Optional[DictConfig] = None, - ): - """ - Changes vocabulary used during RNNT decoding process. Use this method when fine-tuning on - from pre-trained model. This method changes only decoder and leaves encoder and pre-processing - modules unchanged. For example, you would use it if you want to use pretrained encoder when - fine-tuning on data in another language, or when you'd need model to learn capitalization, - punctuation and/or special characters. - - Args: - new_tokenizer_dir: Directory path to tokenizer or a config for a new tokenizer (if the tokenizer type is `agg`) - new_tokenizer_type: Type of tokenizer. Can be either `agg`, `bpe` or `wpe`. - decoding_cfg: A config for the decoder, which is optional. If the decoding type - needs to be changed (from say Greedy to Beam decoding etc), the config can be passed here. - ctc_decoding_cfg: A config for auxiliary CTC decoding, which is optional and can be used to change the decoding type. - - Returns: None - - """ - if isinstance(new_tokenizer_dir, DictConfig): - if new_tokenizer_type == 'agg': - new_tokenizer_cfg = new_tokenizer_dir - else: - raise ValueError( - f'New tokenizer dir should be a string unless the tokenizer is `agg`, but this tokenizer type is: {new_tokenizer_type}' - ) - else: - new_tokenizer_cfg = None - - if new_tokenizer_cfg is not None: - tokenizer_cfg = new_tokenizer_cfg - else: - if not os.path.isdir(new_tokenizer_dir): - raise NotADirectoryError( - f'New tokenizer dir must be non-empty path to a directory. But I got: {new_tokenizer_dir}' - ) - - if new_tokenizer_type.lower() not in ('bpe', 'wpe'): - raise ValueError(f'New tokenizer type must be either `bpe` or `wpe`, got {new_tokenizer_type}') - - tokenizer_cfg = OmegaConf.create({'dir': new_tokenizer_dir, 'type': new_tokenizer_type}) - - # Setup the tokenizer - self._setup_tokenizer(tokenizer_cfg) - - # Initialize a dummy vocabulary - vocabulary = self.tokenizer.tokenizer.get_vocab() - - joint_config = self.joint.to_config_dict() - new_joint_config = copy.deepcopy(joint_config) - if self.tokenizer_type == "agg": - new_joint_config["vocabulary"] = ListConfig(vocabulary) - else: - new_joint_config["vocabulary"] = ListConfig(list(vocabulary.keys())) - - new_joint_config['num_classes'] = len(vocabulary) - del self.joint - self.joint = EncDecHybridRNNTCTCBPEModel.from_config_dict(new_joint_config) - - decoder_config = self.decoder.to_config_dict() - new_decoder_config = copy.deepcopy(decoder_config) - new_decoder_config.vocab_size = len(vocabulary) - del self.decoder - self.decoder = EncDecHybridRNNTCTCBPEModel.from_config_dict(new_decoder_config) - - del self.loss - self.loss = RNNTLoss(num_classes=self.joint.num_classes_with_blank - 1) - - if decoding_cfg is None: - # Assume same decoding config as before - decoding_cfg = self.cfg.decoding - - # Assert the decoding config with all hyper parameters - decoding_cls = OmegaConf.structured(RNNTBPEDecodingConfig) - decoding_cls = OmegaConf.create(OmegaConf.to_container(decoding_cls)) - decoding_cfg = OmegaConf.merge(decoding_cls, decoding_cfg) - decoding_cfg = self.set_decoding_type_according_to_loss(decoding_cfg) - - self.decoding = RNNTBPEDecoding( - decoding_cfg=decoding_cfg, - decoder=self.decoder, - joint=self.joint, - tokenizer=self.tokenizer, - ) - - self.wer = WER( - decoding=self.decoding, - batch_dim_index=self.wer.batch_dim_index, - use_cer=self.wer.use_cer, - log_prediction=self.wer.log_prediction, - dist_sync_on_step=True, - ) - - # Setup fused Joint step - if self.joint.fuse_loss_wer or ( - self.decoding.joint_fused_batch_size is not None and self.decoding.joint_fused_batch_size > 0 - ): - self.joint.set_loss(self.loss) - self.joint.set_wer(self.wer) - - # Update config - with open_dict(self.cfg.joint): - self.cfg.joint = new_joint_config - - with open_dict(self.cfg.decoder): - self.cfg.decoder = new_decoder_config - - with open_dict(self.cfg.decoding): - self.cfg.decoding = decoding_cfg - - logging.info(f"Changed tokenizer of the RNNT decoder to {self.joint.vocabulary} vocabulary.") - - # set up the new tokenizer for the CTC decoder - if hasattr(self, 'ctc_decoder'): - ctc_decoder_config = copy.deepcopy(self.ctc_decoder.to_config_dict()) - # sidestepping the potential overlapping tokens issue in aggregate tokenizers - if self.tokenizer_type == "agg": - ctc_decoder_config.vocabulary = ListConfig(vocabulary) - else: - ctc_decoder_config.vocabulary = ListConfig(list(vocabulary.keys())) - - decoder_num_classes = ctc_decoder_config['num_classes'] - # Override number of classes if placeholder provided - logging.info( - "\nReplacing old number of classes ({}) with new number of classes - {}".format( - decoder_num_classes, len(vocabulary) - ) - ) - ctc_decoder_config['num_classes'] = len(vocabulary) - - del self.ctc_decoder - self.ctc_decoder = EncDecHybridRNNTCTCBPEModel.from_config_dict(ctc_decoder_config) - del self.ctc_loss - self.ctc_loss = CTCLoss( - num_classes=self.ctc_decoder.num_classes_with_blank - 1, - zero_infinity=True, - reduction=self.cfg.aux_ctc.get("ctc_reduction", "mean_batch"), - ) - - if ctc_decoding_cfg is None: - # Assume same decoding config as before - ctc_decoding_cfg = self.cfg.aux_ctc.decoding - - # Assert the decoding config with all hyper parameters - ctc_decoding_cls = OmegaConf.structured(CTCBPEDecodingConfig) - ctc_decoding_cls = OmegaConf.create(OmegaConf.to_container(ctc_decoding_cls)) - ctc_decoding_cfg = OmegaConf.merge(ctc_decoding_cls, ctc_decoding_cfg) - - self.ctc_decoding = CTCBPEDecoding(decoding_cfg=ctc_decoding_cfg, tokenizer=self.tokenizer) - - self.ctc_wer = WER( - decoding=self.ctc_decoding, - use_cer=self.cfg.aux_ctc.get('use_cer', False), - log_prediction=self.cfg.get("log_prediction", False), - dist_sync_on_step=True, - ) - - # Update config - with open_dict(self.cfg.aux_ctc): - self.cfg.aux_ctc.decoder = ctc_decoder_config - - with open_dict(self.cfg.aux_ctc): - self.cfg.aux_ctc.decoding = ctc_decoding_cfg - - logging.info(f"Changed tokenizer of the CTC decoder to {self.ctc_decoder.vocabulary} vocabulary.") - - def change_decoding_strategy( - self, decoding_cfg: DictConfig = None, decoder_type: str = None, verbose: bool = True - ): - """ - Changes decoding strategy used during RNNT decoding process. - Args: - decoding_cfg: A config for the decoder, which is optional. If the decoding type - needs to be changed (from say Greedy to Beam decoding etc), the config can be passed here. - decoder_type: (str) Can be set to 'rnnt' or 'ctc' to switch between appropriate decoder in a - model having both RNN-T and CTC decoders. Defaults to None, in which case RNN-T decoder is - used. If set to 'ctc', it raises error if 'ctc_decoder' is not an attribute of the model. - verbose: bool whether to display change of decoder config or not. - """ - if decoder_type is None or decoder_type == 'rnnt': - if decoding_cfg is None: - # Assume same decoding config as before - logging.info("No `decoding_cfg` passed when changing decoding strategy, using internal config") - decoding_cfg = self.cfg.decoding - - # Assert the decoding config with all hyper parameters - decoding_cls = OmegaConf.structured(RNNTBPEDecodingConfig) - decoding_cls = OmegaConf.create(OmegaConf.to_container(decoding_cls)) - decoding_cfg = OmegaConf.merge(decoding_cls, decoding_cfg) - decoding_cfg = self.set_decoding_type_according_to_loss(decoding_cfg) - - self.decoding = RNNTBPEDecoding( - decoding_cfg=decoding_cfg, - decoder=self.decoder, - joint=self.joint, - tokenizer=self.tokenizer, - ) - - self.wer = WER( - decoding=self.decoding, - batch_dim_index=self.wer.batch_dim_index, - use_cer=self.wer.use_cer, - log_prediction=self.wer.log_prediction, - dist_sync_on_step=True, - ) - - # Setup fused Joint step - if self.joint.fuse_loss_wer or ( - self.decoding.joint_fused_batch_size is not None and self.decoding.joint_fused_batch_size > 0 - ): - self.joint.set_loss(self.loss) - self.joint.set_wer(self.wer) - - self.joint.temperature = decoding_cfg.get('temperature', 1.0) - - # Update config - with open_dict(self.cfg.decoding): - self.cfg.decoding = decoding_cfg - - self.cur_decoder = "rnnt" - if verbose: - logging.info( - f"Changed decoding strategy of the RNNT decoder to \n{OmegaConf.to_yaml(self.cfg.decoding)}" - ) - - elif decoder_type == 'ctc': - if not hasattr(self, 'ctc_decoding'): - raise ValueError("The model does not have the ctc_decoding module and does not support ctc decoding.") - if decoding_cfg is None: - # Assume same decoding config as before - logging.info("No `decoding_cfg` passed when changing decoding strategy, using internal config") - decoding_cfg = self.cfg.aux_ctc.decoding - - # Assert the decoding config with all hyper parameters - decoding_cls = OmegaConf.structured(CTCBPEDecodingConfig) - decoding_cls = OmegaConf.create(OmegaConf.to_container(decoding_cls)) - decoding_cfg = OmegaConf.merge(decoding_cls, decoding_cfg) - - self.ctc_decoding = CTCBPEDecoding(decoding_cfg=decoding_cfg, tokenizer=self.tokenizer) - - self.ctc_wer = WER( - decoding=self.ctc_decoding, - use_cer=self.ctc_wer.use_cer, - log_prediction=self.ctc_wer.log_prediction, - dist_sync_on_step=True, - ) - - self.ctc_decoder.temperature = decoding_cfg.get('temperature', 1.0) - - # Update config - with open_dict(self.cfg.aux_ctc.decoding): - self.cfg.aux_ctc.decoding = decoding_cfg - - self.cur_decoder = "ctc" - if verbose: - logging.info( - f"Changed decoding strategy of the CTC decoder to \n{OmegaConf.to_yaml(self.cfg.aux_ctc.decoding)}" - ) - else: - raise ValueError(f"decoder_type={decoder_type} is not supported. Supported values: [ctc,rnnt]") - - @classmethod - def list_available_models(cls) -> List[PretrainedModelInfo]: - """ - This method returns a list of pre-trained model which can be instantiated directly from NVIDIA's NGC cloud. - - Returns: - List of available pre-trained models. - """ - results = [] - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_fastconformer_hybrid_large_pc", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_fastconformer_hybrid_large_pc", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_fastconformer_hybrid_large_pc/versions/1.21.0/files/stt_en_fastconformer_hybrid_large_pc.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_de_fastconformer_hybrid_large_pc", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_de_fastconformer_hybrid_large_pc", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_de_fastconformer_hybrid_large_pc/versions/1.21.0/files/stt_de_fastconformer_hybrid_large_pc.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_it_fastconformer_hybrid_large_pc", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_it_fastconformer_hybrid_large_pc", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_it_fastconformer_hybrid_large_pc/versions/1.20.0/files/stt_it_fastconformer_hybrid_large_pc.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_es_fastconformer_hybrid_large_pc", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_es_fastconformer_hybrid_large_pc", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_es_fastconformer_hybrid_large_pc/versions/1.21.0/files/stt_es_fastconformer_hybrid_large_pc.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_hr_fastconformer_hybrid_large_pc", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_hr_fastconformer_hybrid_large_pc", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_hr_fastconformer_hybrid_large_pc/versions/1.21.0/files/FastConformer-Hybrid-Transducer-CTC-BPE-v256-averaged.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_ua_fastconformer_hybrid_large_pc", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_ua_fastconformer_hybrid_large_pc", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_ua_fastconformer_hybrid_large_pc/versions/1.21.0/files/stt_ua_fastconformer_hybrid_large_pc.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_pl_fastconformer_hybrid_large_pc", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_pl_fastconformer_hybrid_large_pc", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_pl_fastconformer_hybrid_large_pc/versions/1.21.0/files/stt_pl_fastconformer_hybrid_large_pc.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_by_fastconformer_hybrid_large_pc", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_by_fastconformer_hybrid_large_pc", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_by_fastconformer_hybrid_large_pc/versions/1.21.0/files/stt_by_fastconformer_hybrid_large_pc.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_ru_fastconformer_hybrid_large_pc", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_ru_fastconformer_hybrid_large_pc", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_ru_fastconformer_hybrid_large_pc/versions/1.21.0/files/stt_ru_fastconformer_hybrid_large_pc.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_fr_fastconformer_hybrid_large_pc", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_fr_fastconformer_hybrid_large_pc", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_fr_fastconformer_hybrid_large_pc/versions/1.21.0/files/stt_fr_fastconformer_hybrid_large_pc.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_multilingual_fastconformer_hybrid_large_pc_blend_eu", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_multilingual_fastconformer_hybrid_large_pc_blend_eu", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_multilingual_fastconformer_hybrid_large_pc_blend_eu/versions/1.21.0/files/stt_multilingual_fastconformer_hybrid_large_pc_blend_eu.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_multilingual_fastconformer_hybrid_large_pc", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_multilingual_fastconformer_hybrid_large_pc", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_multilingual_fastconformer_hybrid_large_pc/versions/1.21.0/files/stt_multilingual_fastconformer_hybrid_large_pc.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_fastconformer_hybrid_large_streaming_80ms", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_fastconformer_hybrid_large_streaming_80ms", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_fastconformer_hybrid_large_streaming_80ms/versions/1.20.0/files/stt_en_fastconformer_hybrid_large_streaming_80ms.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_fastconformer_hybrid_large_streaming_480ms", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_fastconformer_hybrid_large_streaming_480ms", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_fastconformer_hybrid_large_streaming_480ms/versions/1.20.0/files/stt_en_fastconformer_hybrid_large_streaming_480ms.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_fastconformer_hybrid_large_streaming_1040ms", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_fastconformer_hybrid_large_streaming_1040ms", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_fastconformer_hybrid_large_streaming_1040ms/versions/1.20.0/files/stt_en_fastconformer_hybrid_large_streaming_1040ms.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_fastconformer_hybrid_large_streaming_multi", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_fastconformer_hybrid_large_streaming_multi", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_fastconformer_hybrid_large_streaming_multi/versions/1.20.0/files/stt_en_fastconformer_hybrid_large_streaming_multi.nemo", - ) - results.append(model) - - return results diff --git a/nemo/collections/asr/models/hybrid_rnnt_ctc_bpe_models_prompt.py b/nemo/collections/asr/models/hybrid_rnnt_ctc_bpe_models_prompt.py deleted file mode 100644 index 992de84fc7a8e75f9c4076c4b1b5a3e8a85aee6b..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/hybrid_rnnt_ctc_bpe_models_prompt.py +++ /dev/null @@ -1,1012 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import math -import os -from dataclasses import dataclass -from math import ceil -from typing import Dict, List, Optional, Union - -import torch -from omegaconf import DictConfig, ListConfig, OmegaConf, open_dict -from pytorch_lightning import Trainer - -from nemo.collections.asr.data import audio_to_text_dataset -from nemo.collections.asr.data.audio_to_text_dali import AudioToBPEDALIDataset, DALIOutputs -from nemo.collections.asr.data.audio_to_text_lhotse import LhotseSpeechToTextBpeDataset -from nemo.collections.asr.data.audio_to_text_lhotse_prompt import LhotseSpeechToTextBpeDatasetWithPrompt -from nemo.collections.asr.metrics.bleu import BLEU -from nemo.collections.asr.metrics.wer import WER -from nemo.collections.asr.models.hybrid_rnnt_ctc_bpe_models import EncDecHybridRNNTCTCBPEModel -from nemo.collections.asr.parts.mixins import ASRTranscriptionMixin, TranscribeConfig -from nemo.collections.asr.parts.mixins.transcription import TranscriptionReturnType -from nemo.collections.asr.parts.preprocessing.segment import ChannelSelectorType -from nemo.collections.asr.parts.submodules.ctc_decoding import CTCBPEDecoding, CTCBPEDecodingConfig -from nemo.collections.asr.parts.submodules.rnnt_decoding import RNNTBPEDecoding -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis -from nemo.collections.common.data.lhotse import get_lhotse_dataloader_from_config -from nemo.core.classes.common import PretrainedModelInfo, typecheck -from nemo.core.classes.mixins import AccessMixin -from nemo.core.neural_types import ( - AcousticEncodedRepresentation, - AudioSignal, - LabelsType, - LengthsType, - NeuralType, - SpectrogramType, -) -from nemo.utils import logging, model_utils - - -@dataclass -class HybridRNNTCTCPromptTranscribeConfig(TranscribeConfig): - """ - Configuration for Hybrid RNNT-CTC BPE Model with Prompt Transcription - """ - - target_lang: str = "en-US" - prompt_field: str = "lang" - - -class EncDecHybridRNNTCTCBPEModelWithPrompt(EncDecHybridRNNTCTCBPEModel, ASRTranscriptionMixin): - """Base class for encoder decoder RNNT-based models with auxiliary CTC decoder/loss, subword tokenization, and prompt conditioning.""" - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - # Convert to Hydra 1.0 compatible DictConfig - cfg = model_utils.convert_model_config_to_dict_config(cfg) - cfg = model_utils.maybe_update_config_version(cfg) - - # Tokenizer is necessary for this model - if 'tokenizer' not in cfg: - raise ValueError("`cfg` must have `tokenizer` config to create a tokenizer !") - - if not isinstance(cfg, DictConfig): - cfg = OmegaConf.create(cfg) - - # Setup the tokenizer - self._setup_tokenizer(cfg.tokenizer) - - # Initialize a dummy vocabulary - vocabulary = self.tokenizer.tokenizer.get_vocab() - - # Set the new vocabulary - with open_dict(cfg): - cfg.labels = ListConfig(list(vocabulary)) - - with open_dict(cfg.decoder): - cfg.decoder.vocab_size = len(vocabulary) - - with open_dict(cfg.joint): - cfg.joint.num_classes = len(vocabulary) - cfg.joint.vocabulary = ListConfig(list(vocabulary)) - cfg.joint.jointnet.encoder_hidden = cfg.model_defaults.enc_hidden - cfg.joint.jointnet.pred_hidden = cfg.model_defaults.pred_hidden - - # setup auxiliary CTC decoder - if 'aux_ctc' not in cfg: - raise ValueError( - "The config need to have a section for the CTC decoder named as aux_ctc for Hybrid models." - ) - - with open_dict(cfg): - if self.tokenizer_type == "agg": - cfg.aux_ctc.decoder.vocabulary = ListConfig(vocabulary) - else: - cfg.aux_ctc.decoder.vocabulary = ListConfig(list(vocabulary.keys())) - - # Setup prompt settings - default to 128 prompts if not specified - cfg.num_prompts = cfg.model_defaults.get('num_prompts', 128) - - # Make sure prompt_dictionary exists - if 'prompt_dictionary' not in cfg.model_defaults: - raise ValueError("No prompt_dictionary found in config.") - - # Set subsampling_factor in a place accessible to the class - self.subsampling_factor = cfg.get('subsampling_factor', 8) - - if cfg.aux_ctc.decoder["num_classes"] < 1: - logging.info( - "\nReplacing placholder number of classes ({}) with actual number of classes - {}".format( - cfg.aux_ctc.decoder["num_classes"], len(vocabulary) - ) - ) - cfg.aux_ctc.decoder["num_classes"] = len(vocabulary) - - super().__init__(cfg=cfg, trainer=trainer) - - # Initialize concat flag - self.concat = False - - if self.cfg.model_defaults.get('initialize_prompt_feature', False): - self.initialize_prompt_feature() - - def initialize_prompt_feature(self): - """Initialize model components for prompt feature via concatenation.""" - logging.info("Model with prompt feature has been initialized") - - # Enable concatenation mode - self.concat = True - self.num_prompts = self.cfg.get('num_prompts', 128) - - # Setup projection layers - proj_in_size = self.num_prompts + self._cfg.model_defaults.enc_hidden - proj_out_size = self._cfg.model_defaults.enc_hidden - - self.prompt_kernel = torch.nn.Sequential( - torch.nn.Linear(proj_in_size, proj_out_size * 2), - torch.nn.ReLU(), - torch.nn.Linear(proj_out_size * 2, proj_out_size), - ) - - # Setup decoding object - self.decoding = RNNTBPEDecoding( - decoding_cfg=self.cfg.decoding, - decoder=self.decoder, - joint=self.joint, - tokenizer=self.tokenizer, - ) - - # Setup wer object - self.wer = WER( - decoding=self.decoding, - batch_dim_index=0, - use_cer=self.cfg.get('use_cer', False), - log_prediction=self.cfg.get('log_prediction', True), - dist_sync_on_step=True, - ) - - # Setup bleu object - self._bleu = BLEU(decoding=self.decoding, tokenize=self.cfg.get('bleu_tokenizer', "13a"), log_prediction=True) - - # Setup fused Joint step if flag is set - if self.joint.fuse_loss_wer: - self.joint.set_loss(self.loss) - self.joint.set_wer(self.wer) - - # Setup CTC decoding - ctc_decoding_cfg = self.cfg.aux_ctc.get('decoding', None) - if ctc_decoding_cfg is None: - ctc_decoding_cfg = OmegaConf.structured(CTCBPEDecodingConfig) - with open_dict(self.cfg.aux_ctc): - self.cfg.aux_ctc.decoding = ctc_decoding_cfg - self.ctc_decoding = CTCBPEDecoding(self.cfg.aux_ctc.decoding, tokenizer=self.tokenizer) - - # Setup CTC WER - self.ctc_wer = WER( - decoding=self.ctc_decoding, - use_cer=self.cfg.aux_ctc.get('use_cer', False), - dist_sync_on_step=True, - log_prediction=self.cfg.get("log_prediction", False), - ) - - # setting the RNNT decoder as the default one - self.cur_decoder = "rnnt" - - def _setup_dataloader_from_config(self, config: Optional[Dict]): - if config.get("use_lhotse"): - if config.get('initialize_prompt_feature', True): - dataset = LhotseSpeechToTextBpeDatasetWithPrompt(tokenizer=self.tokenizer, cfg=config) - logging.info("Setting up Lhotse dataset with prompt support") - else: - dataset = LhotseSpeechToTextBpeDataset(tokenizer=self.tokenizer) - logging.info("Setting up Lhotse dataset without prompt support") - return get_lhotse_dataloader_from_config( - config, - global_rank=self.global_rank, - world_size=self.world_size, - dataset=dataset, - tokenizer=self.tokenizer, - ) - - dataset = audio_to_text_dataset.get_audio_to_text_bpe_dataset_from_config( - config=config, - local_rank=self.local_rank, - global_rank=self.global_rank, - world_size=self.world_size, - tokenizer=self.tokenizer, - preprocessor_cfg=self.cfg.get("preprocessor", None), - ) - - if dataset is None: - return None - - if isinstance(dataset, AudioToBPEDALIDataset): - # DALI Dataset implements dataloader interface - return dataset - - shuffle = config['shuffle'] - if isinstance(dataset, torch.utils.data.IterableDataset): - shuffle = False - - if hasattr(dataset, 'collate_fn'): - collate_fn = dataset.collate_fn - elif hasattr(dataset.datasets[0], 'collate_fn'): - # support datasets that are lists of entries - collate_fn = dataset.datasets[0].collate_fn - else: - # support datasets that are lists of lists - collate_fn = dataset.datasets[0].datasets[0].collate_fn - - return torch.utils.data.DataLoader( - dataset=dataset, - batch_size=config['batch_size'], - collate_fn=collate_fn, - drop_last=config.get('drop_last', False), - shuffle=shuffle, - num_workers=config.get('num_workers', 0), - pin_memory=config.get('pin_memory', False), - ) - - def _setup_transcribe_dataloader(self, config: Dict) -> 'torch.utils.data.DataLoader': - """ - Setup function for a temporary data loader which wraps the provided audio file. - - Args: - config: A python dictionary which contains the following keys: - paths2audio_files: (a list) of paths to audio files. The files should be relatively short fragments. \ - Recommended length per file is between 5 and 25 seconds. - batch_size: (int) batch size to use during inference. \ - Bigger will result in better throughput performance but would use more memory. - temp_dir: (str) A temporary directory where the audio manifest is temporarily - stored. - target_lang: (str) target language ID for transcription - - Returns: - A pytorch DataLoader for the given audio file(s). - """ - if 'manifest_filepath' in config: - manifest_filepath = config['manifest_filepath'] - batch_size = config['batch_size'] - else: - manifest_filepath = os.path.join(config['temp_dir'], 'manifest.json') - batch_size = min(config['batch_size'], len(config['paths2audio_files'])) - - # Get target language from config - target_lang = config.get('target_lang', 'en-US') - - dl_config = { - 'manifest_filepath': manifest_filepath, - 'sample_rate': self.preprocessor._sample_rate, - 'labels': self.joint.vocabulary, - 'batch_size': batch_size, - 'trim_silence': False, - 'shuffle': False, - 'num_workers': config.get('num_workers', min(batch_size, os.cpu_count() - 1)), - 'pin_memory': True, - 'use_lhotse': config.get('use_lhotse', True), - 'use_bucketing': False, - 'drop_last': False, - 'prompt_field': config.get('prompt_field', 'target_lang'), - 'initialize_prompt_feature': True, - 'prompt_dictionary': self.cfg.model_defaults.get('prompt_dictionary'), - 'num_prompts': self.cfg.model_defaults.get('num_prompts', 128), - 'subsampling_factor': self.cfg.get('subsampling_factor', 8), - 'default_lang': target_lang, - 'window_stride': self.cfg.preprocessor.get('window_stride', 0.01), - } - - if config.get("augmentor"): - dl_config['augmentor'] = config.get("augmentor") - - temporary_datalayer = self._setup_dataloader_from_config(config=DictConfig(dl_config)) - return temporary_datalayer - - def _transcribe_forward(self, batch: tuple[torch.Tensor, ...], trcfg: HybridRNNTCTCPromptTranscribeConfig) -> dict: - """ - Internal function to perform the model's custom forward pass to return outputs that are processed by - `_transcribe_output_processing()`. - This function is called by `transcribe()` and `transcribe_generator()` to perform the model's forward pass. - - Args: - batch: A batch of input data from the data loader that is used to perform the model's forward pass. - Expected structure: (audio, audio_lens, tokens, token_lens, prompt_targets) - For transcription, we may only have (audio, audio_lens) or (audio, audio_lens, ..., prompt_targets) - trcfg: The transcription config dataclass. Subclasses can change this to a different dataclass if needed. - - Returns: - The model's outputs that are processed by `_transcribe_output_processing()`. - """ - # Handling DataLoader batch - should be a tuple of tensors - # Expected structure: (audio, audio_lens, tokens, token_lens, prompt_targets) - # For transcription, we may only have (audio, audio_lens) or (audio, audio_lens, ..., prompt_targets) - audio, audio_lens = batch[0], batch[1] - if len(batch) >= 5: - # Prompt provided by the dataloader (one-hot vectors) - prompt = batch[4] # This should be the prompt_targets from dataset - else: - # Prompt to be built dynamically. - prompt = None - - batch_size = audio.shape[0] - - if prompt is None: - # The dataloader provided only audio + audio_lens, so we need to construct - # the prompt as one-hot vectors dynamically using TranscribeConfig. - target_lang = trcfg.target_lang - - # Get prompt dictionary and num_prompts from model config - prompt_dict = self.cfg.model_defaults.get('prompt_dictionary') - num_prompts = self.cfg.model_defaults.get('num_prompts', 128) - - if not prompt_dict: - raise ValueError("Prompt dictionary is empty. Cannot create dynamic prompts.") - - # Get the prompt index for the target language - if target_lang not in prompt_dict: - available_keys = list(prompt_dict.keys()) - raise ValueError( - f"Unknown target language: '{target_lang}'. Available languages: {available_keys[:10]}{'...' if len(available_keys) > 10 else ''}" - ) - - prompt_id = prompt_dict[target_lang] - - # Preprocess audio to get the actual feature dimensions (like streaming does) - processed_signal, processed_signal_length = self.preprocessor(input_signal=audio, length=audio_lens) - - # Calculate exact hidden length using the same approach as streaming - time_length = processed_signal.shape[2] # Feature time dimension - subsampling_factor = self.cfg.get('subsampling_factor', 8) - hidden_length = math.ceil(time_length / subsampling_factor) - - # Create one-hot prompt tensor: (batch_size, time_steps, num_prompts) - prompt = torch.zeros(batch_size, hidden_length, num_prompts, dtype=torch.float32, device=audio.device) - prompt[:, :, prompt_id] = 1.0 # Set the target language prompt to 1 - - # Now call forward with preprocessed signal and prompt - encoded, encoded_len = self.forward( - processed_signal=processed_signal, processed_signal_length=processed_signal_length, prompt=prompt - ) - else: - # Prompt was provided, use normal forward path - encoded, encoded_len = self.forward(input_signal=audio, input_signal_length=audio_lens, prompt=prompt) - - # Prepare output dictionary based on decoder type - if self.cur_decoder == "rnnt": - # RNNT Path - just use encoded outputs directly - output = dict(encoded=encoded, encoded_len=encoded_len) - else: - # CTC Path - compute logits from encoder output - logits = self.ctc_decoder(encoder_output=encoded) - output = dict(logits=logits, encoded_len=encoded_len) - del encoded - - return output - - @torch.no_grad() - def transcribe( - self, - audio: List[str], - batch_size: int = 4, - return_hypotheses: bool = False, - partial_hypothesis: Optional[List['Hypothesis']] = None, - num_workers: int = 0, - channel_selector: Optional[ChannelSelectorType] = None, - augmentor: DictConfig = None, - verbose: bool = True, - timestamps: Optional[bool] = None, - override_config: Optional[HybridRNNTCTCPromptTranscribeConfig] = None, - **prompt, - ) -> TranscriptionReturnType: - """ - Uses greedy decoding to transcribe audio files. Use this method for debugging and prototyping. - - Args: - audio: (a single or list) of paths to audio files or a np.ndarray audio array. - Can also be a dataloader object that provides values that can be consumed by the model. - Recommended length per file is between 5 and 25 seconds. \ - But it is possible to pass a few hours long file if enough GPU memory is available. - batch_size: (int) batch size to use during inference. \ - Bigger will result in better throughput performance but would use more memory. - return_hypotheses: (bool) Either return hypotheses or text - With hypotheses can do some postprocessing like getting timestamp or rescoring - partial_hypothesis: (Optional[List['Hypothesis']]) partial hypotheses for streaming - num_workers: (int) number of workers for DataLoader - channel_selector: (Optional[ChannelSelectorType]) 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. - augmentor: (DictConfig): Augment audio samples during transcription if augmentor is applied. - verbose: (bool) whether to display tqdm progress bar - timestamps: (Optional[bool]) timestamps will be returned if set to True as part of hypothesis object - override_config: (Optional[HybridRNNTCTCPromptTranscribeConfig]) override transcription config pre-defined by the user. - **prompt: Optional input to construct the prompts for the model. Accepted formats include: - target_lang: (str) target language ID for transcription (e.g., "en-US", "de-DE") - prompt_field: (str) field name to use for prompt extraction from manifest - Additional prompt parameters can be passed and will be forwarded to the transcription config. - - Returns: - Returns a tuple of 2 items - - * A list of greedy transcript texts / Hypothesis - * An optional list of beam search transcript texts / Hypothesis / NBestHypothesis. - """ - if self.cur_decoder not in ["ctc", "rnnt"]: - raise ValueError( - f"{self.cur_decoder} is not supported for cur_decoder. Supported values are ['ctc', 'rnnt']" - ) - - if timestamps is not None: - if self.cur_decoder not in ["ctc", "rnnt"]: - raise ValueError( - f"{self.cur_decoder} is not supported for cur_decoder. Supported values are ['ctc', 'rnnt']" - ) - decoding_cfg = self.cfg.aux_ctc.decoding if self.cur_decoder == "ctc" else self.cfg.decoding - if timestamps or (override_config is not None and override_config.timestamps): - logging.info( - "Timestamps requested, setting decoding timestamps to True. Capture them in Hypothesis object, \ - with output[idx].timestep['word'/'segment'/'char']" - ) - return_hypotheses = True - with open_dict(decoding_cfg): - decoding_cfg.compute_timestamps = True - decoding_cfg.preserve_alignments = True - else: - with open_dict(decoding_cfg): - decoding_cfg.compute_timestamps = False - decoding_cfg.preserve_alignments = False - self.change_decoding_strategy(decoding_cfg, decoder_type=self.cur_decoder, verbose=False) - - # Create transcription config if not provided - if override_config is None: - # Extract target_lang from prompt or use default - target_lang = prompt.get('target_lang', 'en-US') - prompt_field = prompt.get('prompt_field', 'target_lang') - - trcfg = HybridRNNTCTCPromptTranscribeConfig( - batch_size=batch_size, - return_hypotheses=return_hypotheses, - num_workers=num_workers, - channel_selector=channel_selector, - augmentor=augmentor, - verbose=verbose, - timestamps=timestamps, - target_lang=target_lang, - prompt_field=prompt_field, - ) - - else: - if not isinstance(override_config, HybridRNNTCTCPromptTranscribeConfig): - raise ValueError( - f"override_config must be of type {HybridRNNTCTCPromptTranscribeConfig}, " - f"but got {type(override_config)}" - ) - trcfg = override_config - - # Call parent class transcribe method with proper parameters - return super().transcribe( - audio=audio, - batch_size=batch_size, - return_hypotheses=return_hypotheses, - partial_hypothesis=partial_hypothesis, - num_workers=num_workers, - channel_selector=channel_selector, - augmentor=augmentor, - verbose=verbose, - timestamps=timestamps, - override_config=trcfg, - ) - - @property - def input_types(self) -> Optional[Dict[str, NeuralType]]: - if hasattr(self.preprocessor, '_sample_rate'): - input_signal_eltype = AudioSignal(freq=self.preprocessor._sample_rate) - else: - input_signal_eltype = AudioSignal() - - return { - "input_signal": NeuralType(('B', 'T'), input_signal_eltype, optional=True), - "input_signal_length": NeuralType(tuple('B'), LengthsType(), optional=True), - "processed_signal": NeuralType(('B', 'D', 'T'), SpectrogramType(), optional=True), - "processed_signal_length": NeuralType(tuple('B'), LengthsType(), optional=True), - "prompt": NeuralType(('B', 'T', 'D'), LabelsType()), - } - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - return { - "outputs": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), - "encoded_lengths": NeuralType(tuple('B'), LengthsType()), - } - - @typecheck() - def forward( - self, - input_signal=None, - input_signal_length=None, - processed_signal=None, - processed_signal_length=None, - prompt=None, - ): - """ - Forward pass of the model. Note that for RNNT Models, the forward pass of the model is a 3 step process, - and this method only performs the first step - forward of the acoustic model. - - Please refer to the `training_step` in order to see the full `forward` step for training - which - performs the forward of the acoustic model, the prediction network and then the joint network. - Finally, it computes the loss and possibly compute the detokenized text via the `decoding` step. - - Please refer to the `validation_step` in order to see the full `forward` step for inference - which - performs the forward of the acoustic model, the prediction network and then the joint network. - Finally, it computes the decoded tokens via the `decoding` step and possibly compute the batch metrics. - - Args: - input_signal: Tensor that represents a batch of raw audio signals, - of shape [B, T]. T here represents timesteps, with 1 second of audio represented as - `self.sample_rate` number of floating point values. - input_signal_length: Vector of length B, that contains the individual lengths of the audio - sequences. - processed_signal: Tensor that represents a batch of processed audio signals, - of shape (B, D, T) that has undergone processing via some DALI preprocessor. - processed_signal_length: Vector of length B, that contains the individual lengths of the - processed audio sequences. - prompt: Tensor that represents the prompt embeddings, - of shape (B, T, D) where D is the number of supported prompts. - Used for prompt-conditioned encoding via concatenation with acoustic features. - - Returns: - A tuple of 2 elements - - 1) The log probabilities tensor of shape [B, T, D]. - 2) The lengths of the acoustic sequence after propagation through the encoder, of shape [B]. - """ - has_input_signal = input_signal is not None and input_signal_length is not None - has_processed_signal = processed_signal is not None and processed_signal_length is not None - if (has_input_signal ^ has_processed_signal) is False: - raise ValueError( - f"{self} Arguments ``input_signal`` and ``input_signal_length`` are mutually exclusive " - " with ``processed_signal`` and ``processed_signal_len`` arguments." - ) - - if not has_processed_signal: - processed_signal, processed_signal_length = self.preprocessor( - input_signal=input_signal, - length=input_signal_length, - ) - - # Spec augment is not applied during evaluation/testing - if self.spec_augmentation is not None and self.training: - processed_signal = self.spec_augmentation(input_spec=processed_signal, length=processed_signal_length) - - encoded, encoded_len = self.encoder(audio_signal=processed_signal, length=processed_signal_length) - encoded = torch.transpose(encoded, 1, 2) # B * D * T -> B * T * D - - if self.concat: - if prompt.shape[1] > encoded.shape[1]: - prompt = prompt[:, : encoded.shape[1], :] - out_dtype = encoded.dtype # this is dtype, which the decoder previously got from encoder - - # Concatenate encoded states with prompt - concat_enc_states = torch.cat([encoded, prompt], dim=-1) - - # Apply joint projection - encoded = self.prompt_kernel(concat_enc_states).to( - out_dtype - ) # cast: unexpectedly without cast dtype is different from out_dtype - - encoded = torch.transpose(encoded, 1, 2) # B * T * D -> B * D * T - return encoded, encoded_len - - def training_step(self, batch, batch_nb): - # Reset access registry - if AccessMixin.is_access_enabled(): - AccessMixin.reset_registry(self) - - if self.is_interctc_enabled(): - AccessMixin.set_access_enabled(access_enabled=True) - - signal, signal_len, transcript, transcript_len, prompt = batch - - # forward() only performs encoder forward - if isinstance(batch, DALIOutputs) and batch.has_processed_signal: - encoded, encoded_len = self.forward(processed_signal=signal, processed_signal_length=signal_len) - else: - encoded, encoded_len = self.forward(input_signal=signal, input_signal_length=signal_len, prompt=prompt) - del signal - - # During training, loss must be computed, so decoder forward is necessary - decoder, target_length, states = self.decoder(targets=transcript, target_length=transcript_len) - - if hasattr(self, '_trainer') and self._trainer is not None: - log_every_n_steps = self._trainer.log_every_n_steps - sample_id = self._trainer.global_step - else: - log_every_n_steps = 1 - sample_id = batch_nb - - if (sample_id + 1) % log_every_n_steps == 0: - compute_wer = True - else: - compute_wer = False - - # If fused Joint-Loss-WER is not used - if not self.joint.fuse_loss_wer: - # Compute full joint and loss - joint = self.joint(encoder_outputs=encoded, decoder_outputs=decoder) - loss_value = self.loss( - log_probs=joint, targets=transcript, input_lengths=encoded_len, target_lengths=target_length - ) - - # Add auxiliary losses, if registered - loss_value = self.add_auxiliary_losses(loss_value) - - tensorboard_logs = { - 'learning_rate': self._optimizer.param_groups[0]['lr'], - 'global_step': torch.tensor(self.trainer.global_step, dtype=torch.float32), - } - - if compute_wer: - self.wer.update( - predictions=encoded, - predictions_lengths=encoded_len, - targets=transcript, - targets_lengths=transcript_len, - ) - _, scores, words = self.wer.compute() - self.wer.reset() - tensorboard_logs.update({'training_batch_wer': scores.float() / words}) - - else: # If fused Joint-Loss-WER is used - # Fused joint step - loss_value, wer, _, _ = self.joint( - encoder_outputs=encoded, - decoder_outputs=decoder, - encoder_lengths=encoded_len, - transcripts=transcript, - transcript_lengths=transcript_len, - compute_wer=compute_wer, - ) - - # Add auxiliary losses, if registered - loss_value = self.add_auxiliary_losses(loss_value) - - tensorboard_logs = { - 'learning_rate': self._optimizer.param_groups[0]['lr'], - 'global_step': torch.tensor(self.trainer.global_step, dtype=torch.float32), - } - - if compute_wer: - tensorboard_logs.update({'training_batch_wer': wer}) - - if self.ctc_loss_weight > 0: - log_probs = self.ctc_decoder(encoder_output=encoded) - ctc_loss = self.ctc_loss( - log_probs=log_probs, targets=transcript, input_lengths=encoded_len, target_lengths=transcript_len - ) - tensorboard_logs['train_rnnt_loss'] = loss_value - tensorboard_logs['train_ctc_loss'] = ctc_loss - loss_value = (1 - self.ctc_loss_weight) * loss_value + self.ctc_loss_weight * ctc_loss - if compute_wer: - self.ctc_wer.update( - predictions=log_probs, - targets=transcript, - targets_lengths=transcript_len, - predictions_lengths=encoded_len, - ) - ctc_wer, _, _ = self.ctc_wer.compute() - self.ctc_wer.reset() - tensorboard_logs.update({'training_batch_wer_ctc': ctc_wer}) - - # note that we want to apply interctc independent of whether main ctc - # loss is used or not (to allow rnnt + interctc training). - # assuming ``ctc_loss_weight=0.3`` and interctc is applied to a single - # layer with weight of ``0.1``, the total loss will be - # ``loss = 0.9 * (0.3 * ctc_loss + 0.7 * rnnt_loss) + 0.1 * interctc_loss`` - loss_value, additional_logs = self.add_interctc_losses( - loss_value, transcript, transcript_len, compute_wer=compute_wer - ) - tensorboard_logs.update(additional_logs) - tensorboard_logs['train_loss'] = loss_value - # Reset access registry - if AccessMixin.is_access_enabled(): - AccessMixin.reset_registry(self) - - # Log items - self.log_dict(tensorboard_logs) - - return {'loss': loss_value} - - def predict_step(self, batch, batch_idx, dataloader_idx=0): - signal, signal_len, transcript, transcript_len, prompt = batch - - # forward() only performs encoder forward - if isinstance(batch, DALIOutputs) and batch.has_processed_signal: - encoded, encoded_len = self.forward(processed_signal=signal, processed_signal_length=signal_len) - else: - encoded, encoded_len = self.forward(input_signal=signal, input_signal_length=signal_len, prompt=prompt) - del signal - - if self.cur_decoder == 'rnnt': - best_hyp = self.decoding.rnnt_decoder_predictions_tensor( - encoder_output=encoded, encoded_lengths=encoded_len, return_hypotheses=False - ) - else: - logits = self.ctc_decoder(encoder_output=encoded) - best_hyp = self.ctc_decoding.ctc_decoder_predictions_tensor( - decoder_outputs=logits, - decoder_lengths=encoded_len, - return_hypotheses=False, - ) - - batch_size = signal_len.shape[0] - sample_id = torch.arange(batch_idx * batch_size, (batch_idx + 1) * batch_size).cpu().detach().numpy() - - return list(zip(sample_id, best_hyp)) - - def validation_pass(self, batch, batch_idx, dataloader_idx): - if self.is_interctc_enabled(): - AccessMixin.set_access_enabled(access_enabled=True) - - signal, signal_len, transcript, transcript_len, prompt = batch - - # forward() only performs encoder forward - if isinstance(batch, DALIOutputs) and batch.has_processed_signal: - encoded, encoded_len = self.forward(processed_signal=signal, processed_signal_length=signal_len) - else: - encoded, encoded_len = self.forward(input_signal=signal, input_signal_length=signal_len, prompt=prompt) - del signal - - tensorboard_logs = {} - loss_value = None - - # If experimental fused Joint-Loss-WER is not used - if not self.joint.fuse_loss_wer: - if self.compute_eval_loss: - decoder, target_length, states = self.decoder(targets=transcript, target_length=transcript_len) - joint = self.joint(encoder_outputs=encoded, decoder_outputs=decoder) - - loss_value = self.loss( - log_probs=joint, targets=transcript, input_lengths=encoded_len, target_lengths=target_length - ) - tensorboard_logs['val_loss'] = loss_value - - self.wer.update( - predictions=encoded, - predictions_lengths=encoded_len, - targets=transcript, - targets_lengths=transcript_len, - ) - wer, wer_num, wer_denom = self.wer.compute() - self.wer.reset() - - tensorboard_logs['val_wer_num'] = wer_num - tensorboard_logs['val_wer_denom'] = wer_denom - tensorboard_logs['val_wer'] = wer - - else: - # If experimental fused Joint-Loss-WER is used - compute_wer = True - - if self.compute_eval_loss: - decoded, target_len, states = self.decoder(targets=transcript, target_length=transcript_len) - else: - decoded = None - target_len = transcript_len - - # Fused joint step - loss_value, wer, wer_num, wer_denom = self.joint( - encoder_outputs=encoded, - decoder_outputs=decoded, - encoder_lengths=encoded_len, - transcripts=transcript, - transcript_lengths=target_len, - compute_wer=compute_wer, - ) - if loss_value is not None: - tensorboard_logs['val_loss'] = loss_value - - tensorboard_logs['val_wer_num'] = wer_num - tensorboard_logs['val_wer_denom'] = wer_denom - tensorboard_logs['val_wer'] = wer - - log_probs = self.ctc_decoder(encoder_output=encoded) - if self.compute_eval_loss: - ctc_loss = self.ctc_loss( - log_probs=log_probs, targets=transcript, input_lengths=encoded_len, target_lengths=transcript_len - ) - tensorboard_logs['val_ctc_loss'] = ctc_loss - tensorboard_logs['val_rnnt_loss'] = loss_value - loss_value = (1 - self.ctc_loss_weight) * loss_value + self.ctc_loss_weight * ctc_loss - tensorboard_logs['val_loss'] = loss_value - - # CTC WER calculation - self.ctc_wer.update( - predictions=log_probs, - targets=transcript, - targets_lengths=transcript_len, - predictions_lengths=encoded_len, - ) - ctc_wer, ctc_wer_num, ctc_wer_denom = self.ctc_wer.compute() - self.ctc_wer.reset() - tensorboard_logs['val_wer_num_ctc'] = ctc_wer_num - tensorboard_logs['val_wer_denom_ctc'] = ctc_wer_denom - tensorboard_logs['val_wer_ctc'] = ctc_wer - - # BLEU score calculation - self.bleu.update( - predictions=encoded, predictions_lengths=encoded_len, targets=transcript, targets_lengths=transcript_len - ) - bleu_metrics = self.bleu.compute(return_all_metrics=True, prefix="val_") - tensorboard_logs.update( - { - 'val_bleu_num': bleu_metrics['val_bleu_num'], - 'val_bleu_denom': bleu_metrics['val_bleu_denom'], - 'val_bleu_pred_len': bleu_metrics['val_bleu_pred_len'], - 'val_bleu_target_len': bleu_metrics['val_bleu_target_len'], - 'val_bleu': bleu_metrics['val_bleu'], - } - ) - self.bleu.reset() - - self.log('global_step', torch.tensor(self.trainer.global_step, dtype=torch.float32)) - - # Inter-CTC losses and additional logging - loss_value, additional_logs = self.add_interctc_losses( - loss_value, - transcript, - transcript_len, - compute_wer=True, - compute_loss=self.compute_eval_loss, - log_wer_num_denom=True, - log_prefix="val_", - ) - if self.compute_eval_loss: - # overriding total loss value. Note that the previous - # rnnt + ctc loss is available in metrics as "val_final_loss" now - tensorboard_logs['val_loss'] = loss_value - tensorboard_logs.update(additional_logs) - - # Reset access registry - if AccessMixin.is_access_enabled(): - AccessMixin.reset_registry(self) - - return tensorboard_logs - - def validation_step(self, batch, batch_idx, dataloader_idx=0): - tensorboard_logs = self.validation_pass(batch, batch_idx, dataloader_idx) - if type(self.trainer.val_dataloaders) == list and len(self.trainer.val_dataloaders) > 1: - self.validation_step_outputs[dataloader_idx].append(tensorboard_logs) - else: - self.validation_step_outputs.append(tensorboard_logs) - - return tensorboard_logs - - def test_step(self, batch, batch_idx, dataloader_idx=0): - logs = self.validation_pass(batch, batch_idx, dataloader_idx=dataloader_idx) - test_logs = {name.replace("val_", "test_"): value for name, value in logs.items()} - if type(self.trainer.test_dataloaders) == list and len(self.trainer.test_dataloaders) > 1: - self.test_step_outputs[dataloader_idx].append(test_logs) - else: - self.test_step_outputs.append(test_logs) - return test_logs - - def multi_validation_epoch_end(self, outputs, dataloader_idx: int = 0): - # Calculate validation loss if required - if self.compute_eval_loss: - val_loss_mean = torch.stack([x['val_loss'] for x in outputs]).mean() - val_loss_log = {'val_loss': val_loss_mean} - else: - val_loss_log = {} - - # Calculate WER - wer_num = torch.stack([x['val_wer_num'] for x in outputs]).sum() - wer_denom = torch.stack([x['val_wer_denom'] for x in outputs]).sum() - tensorboard_logs = {**val_loss_log, 'val_wer': wer_num.float() / wer_denom} - - # Calculate CTC WER if applicable - if self.ctc_loss_weight > 0: - ctc_wer_num = torch.stack([x['val_wer_num_ctc'] for x in outputs]).sum() - ctc_wer_denom = torch.stack([x['val_wer_denom_ctc'] for x in outputs]).sum() - tensorboard_logs['val_wer_ctc'] = ctc_wer_num.float() / ctc_wer_denom - - # Calculate BLEU score - bleu_num = torch.stack([x['val_bleu_num'] for x in outputs]).sum(dim=0) - bleu_denom = torch.stack([x['val_bleu_denom'] for x in outputs]).sum(dim=0) - bleu_pred_len = torch.stack([x['val_bleu_pred_len'] for x in outputs]).sum(dim=0) - bleu_target_len = torch.stack([x['val_bleu_target_len'] for x in outputs]).sum(dim=0) - - val_bleu = self.bleu._compute_bleu(bleu_pred_len, bleu_target_len, bleu_num, bleu_denom) - tensorboard_logs['val_bleu'] = val_bleu - - # Finalize and log metrics - metrics = {**val_loss_log, 'log': tensorboard_logs} - self.finalize_interctc_metrics(metrics, outputs, prefix="val_") - - return metrics - - @property - def bleu(self): - return self._bleu - - @bleu.setter - def bleu(self, bleu): - self._bleu = bleu - - @classmethod - def get_transcribe_config(cls) -> HybridRNNTCTCPromptTranscribeConfig: - """ - Get the default transcribe config for this model. - """ - return HybridRNNTCTCPromptTranscribeConfig() - - def setup_training_data(self, train_data_config: Optional[DictConfig]): - """ - Sets up the training data loader via a Dict-like object. - Args: - train_data_config: A config that contains the information regarding construction - of an ASR Training dataset. - Supported Datasets: - - :class:`~nemo.collections.asr.data.audio_to_text_lhotse_prompt.LhotseSpeechToTextBpeDatasetWithPrompt` - """ - # create audio-only data loader - self._update_dataset_config(dataset_name='train', config=train_data_config) - self._train_dl = self._setup_dataloader_from_config(config=train_data_config) - - # Need to set this because if using an IterableDataset, the length of the - # dataloader is the total number of samples rather than the number of batches, - # and this messes up the tqdm progress bar. So we set the number of steps manually - # (to the correct number) to fix this. - if 'is_tarred' in train_data_config and train_data_config['is_tarred']: - # We also need to check if limit_train_batches is already set. - # If it's an int, we assume that the user has set it to something sane, - # i.e. <= # training batches, and don't change it. Otherwise, adjust - # batches accordingly if it's a float (including 1.0). - if self._trainer is not None and isinstance(self._trainer.limit_train_batches, float): - self._trainer.limit_train_batches = int( - self._trainer.limit_train_batches - * ceil((len(self._train_dl.dataset) / self.world_size) / train_data_config['batch_size']) - ) - elif self._trainer is None: - logging.warning( - "Model Trainer was not set before constructing the dataset, incorrect number of " - "training batches will be used. Please set the trainer and rebuild the dataset." - ) - - def setup_validation_data(self, val_data_config: Optional[Union[DictConfig, Dict]]): - """ - Sets up the validation data loader via a Dict-like object. - Args: - val_data_config: A config that contains the information regarding construction - of an ASR Training dataset. - Supported Datasets: - - :class:`~nemo.collections.asr.data.audio_to_text_lhotse_prompt.LhotseSpeechToTextBpeDatasetWithPrompt` - """ - if 'shuffle' not in val_data_config: - val_data_config['shuffle'] = False - - # preserve config - self._update_dataset_config(dataset_name='validation', config=val_data_config) - self._validation_dl = self._setup_dataloader_from_config(config=val_data_config) - - def setup_test_data(self, test_data_config: Optional[Union[DictConfig, Dict]]): - """ - Sets up the test data loader via a Dict-like object. - Args: - test_data_config: A config that contains the information regarding construction - of an ASR Training dataset. - Supported Datasets: - - :class:`~nemo.collections.asr.data.audio_to_text_lhotse_prompt.LhotseSpeechToTextBpeDatasetWithPrompt` - """ - if 'shuffle' not in test_data_config: - test_data_config['shuffle'] = False - - # preserve config - self._update_dataset_config(dataset_name='test', config=test_data_config) - self._test_dl = self._setup_dataloader_from_config(config=test_data_config) - - @classmethod - def list_available_models(cls) -> List[PretrainedModelInfo]: - """ - This method returns a list of pre-trained model which can be instantiated directly from NVIDIA's NGC cloud. - - Returns: - List of available pre-trained models. - """ - return None diff --git a/nemo/collections/asr/models/hybrid_rnnt_ctc_models.py b/nemo/collections/asr/models/hybrid_rnnt_ctc_models.py deleted file mode 100644 index 5b0d1a98743a81d9d1e5c2e4f23f27810dc834e7..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/hybrid_rnnt_ctc_models.py +++ /dev/null @@ -1,719 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import copy -from typing import Any, List, Optional, Union - -import torch -from lightning.pytorch import Trainer -from omegaconf import DictConfig, OmegaConf, open_dict - -from nemo.collections.asr.data.audio_to_text_dali import DALIOutputs -from nemo.collections.asr.losses.ctc import CTCLoss -from nemo.collections.asr.metrics.wer import WER -from nemo.collections.asr.models.rnnt_models import EncDecRNNTModel -from nemo.collections.asr.parts.mixins import ASRBPEMixin, ASRTranscriptionMixin, InterCTCMixin, TranscribeConfig -from nemo.collections.asr.parts.mixins.transcription import TranscriptionReturnType -from nemo.collections.asr.parts.preprocessing.segment import ChannelSelectorType -from nemo.collections.asr.parts.submodules.ctc_decoding import CTCDecoding, CTCDecodingConfig -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis -from nemo.collections.asr.parts.utils.timestamp_utils import process_timestamp_outputs -from nemo.core.classes.common import PretrainedModelInfo -from nemo.core.classes.mixins import AccessMixin -from nemo.utils import logging, model_utils - - -class EncDecHybridRNNTCTCModel(EncDecRNNTModel, ASRBPEMixin, InterCTCMixin, ASRTranscriptionMixin): - """Base class for hybrid RNNT/CTC models.""" - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - cfg = model_utils.convert_model_config_to_dict_config(cfg) - cfg = model_utils.maybe_update_config_version(cfg) - super().__init__(cfg=cfg, trainer=trainer) - - if 'aux_ctc' not in self.cfg: - raise ValueError( - "The config need to have a section for the CTC decoder named as aux_ctc for Hybrid models." - ) - with open_dict(self.cfg.aux_ctc): - if "feat_in" not in self.cfg.aux_ctc.decoder or ( - not self.cfg.aux_ctc.decoder.feat_in and hasattr(self.encoder, '_feat_out') - ): - self.cfg.aux_ctc.decoder.feat_in = self.encoder._feat_out - if "feat_in" not in self.cfg.aux_ctc.decoder or not self.cfg.aux_ctc.decoder.feat_in: - raise ValueError("param feat_in of the decoder's config is not set!") - - if self.cfg.aux_ctc.decoder.num_classes < 1 and self.cfg.aux_ctc.decoder.vocabulary is not None: - logging.info( - "\nReplacing placeholder number of classes ({}) with actual number of classes - {}".format( - self.cfg.aux_ctc.decoder.num_classes, len(self.cfg.aux_ctc.decoder.vocabulary) - ) - ) - self.cfg.aux_ctc.decoder["num_classes"] = len(self.cfg.aux_ctc.decoder.vocabulary) - - self.ctc_decoder = EncDecRNNTModel.from_config_dict(self.cfg.aux_ctc.decoder) - self.ctc_loss_weight = self.cfg.aux_ctc.get("ctc_loss_weight", 0.5) - - self.ctc_loss = CTCLoss( - num_classes=self.ctc_decoder.num_classes_with_blank - 1, - zero_infinity=True, - reduction=self.cfg.aux_ctc.get("ctc_reduction", "mean_batch"), - ) - - ctc_decoding_cfg = self.cfg.aux_ctc.get('decoding', None) - if ctc_decoding_cfg is None: - ctc_decoding_cfg = OmegaConf.structured(CTCDecodingConfig) - with open_dict(self.cfg.aux_ctc): - self.cfg.aux_ctc.decoding = ctc_decoding_cfg - - self.ctc_decoding = CTCDecoding(self.cfg.aux_ctc.decoding, vocabulary=self.ctc_decoder.vocabulary) - self.ctc_wer = WER( - decoding=self.ctc_decoding, - use_cer=self.cfg.aux_ctc.get('use_cer', False), - dist_sync_on_step=True, - log_prediction=self.cfg.get("log_prediction", False), - ) - - # setting the RNNT decoder as the default one - self.cur_decoder = "rnnt" - - # setting up interCTC loss (from InterCTCMixin) - self.setup_interctc(decoder_name='ctc_decoder', loss_name='ctc_loss', wer_name='ctc_wer') - - @torch.no_grad() - def transcribe( - self, - audio: List[str], - batch_size: int = 4, - return_hypotheses: bool = False, - partial_hypothesis: Optional[List['Hypothesis']] = None, - num_workers: int = 0, - channel_selector: Optional[ChannelSelectorType] = None, - augmentor: DictConfig = None, - verbose: bool = True, - timestamps: bool = None, - override_config: Optional[TranscribeConfig] = None, - ) -> TranscriptionReturnType: - """ - Uses greedy decoding to transcribe audio files. Use this method for debugging and prototyping. - - Args: - - audio: (a single or list) of paths to audio files or a np.ndarray audio array. - Can also be a dataloader object that provides values that can be consumed by the model. - Recommended length per file is between 5 and 25 seconds. \ - But it is possible to pass a few hours long file if enough GPU memory is available. - batch_size: (int) batch size to use during inference. \ - Bigger will result in better throughput performance but would use more memory. - return_hypotheses: (bool) Either return hypotheses or text - With hypotheses can do some postprocessing like getting timestamp or rescoring - num_workers: (int) number of workers for DataLoader - 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. - augmentor: (DictConfig): Augment audio samples during transcription if augmentor is applied. - timestamps: Optional(Bool): timestamps will be returned if set to True as part of hypothesis object - (output.timestep['segment']/output.timestep['word']). Refer to `Hypothesis` class for more details. - Default is None and would retain the previous state set by using self.change_decoding_strategy(). - verbose: (bool) whether to display tqdm progress bar - logprobs: (bool) whether to return ctc logits insted of hypotheses - - Returns: - Returns a tuple of 2 items - - * A list of greedy transcript texts / Hypothesis - * An optional list of beam search transcript texts / Hypothesis / NBestHypothesis. - """ - - if timestamps is not None: - if self.cur_decoder not in ["ctc", "rnnt"]: - raise ValueError( - f"{self.cur_decoder} is not supported for cur_decoder. Supported values are ['ctc', 'rnnt']" - ) - decoding_cfg = self.cfg.aux_ctc.decoding if self.cur_decoder == "ctc" else self.cfg.decoding - need_change_decoding = False - if timestamps or (override_config is not None and override_config.timestamps): - logging.info( - "Timestamps requested, setting decoding timestamps to True. Capture them in Hypothesis object, \ - with output[idx].timestep['word'/'segment'/'char']" - ) - return_hypotheses = True - if decoding_cfg.get("compute_timestamps", None) is not True: - # compute_timestamps None, False or non-existent -> change to True - need_change_decoding = True - with open_dict(decoding_cfg): - decoding_cfg.compute_timestamps = True - else: - if decoding_cfg.get("compute_timestamps", None) is not False: - # compute_timestamps None, True or non-existent -> change to False - need_change_decoding = True - with open_dict(decoding_cfg): - decoding_cfg.compute_timestamps = False - if need_change_decoding: - self.change_decoding_strategy(decoding_cfg, decoder_type=self.cur_decoder, verbose=False) - - return ASRTranscriptionMixin.transcribe( - self, - audio=audio, - batch_size=batch_size, - return_hypotheses=return_hypotheses, - partial_hypothesis=partial_hypothesis, - num_workers=num_workers, - channel_selector=channel_selector, - augmentor=augmentor, - verbose=verbose, - timestamps=timestamps, - override_config=override_config, - ) - - def _transcribe_on_begin(self, audio, trcfg: TranscribeConfig): - super()._transcribe_on_begin(audio, trcfg) - - if hasattr(self, 'ctc_decoder'): - self.ctc_decoder.freeze() - - def _transcribe_on_end(self, trcfg: TranscribeConfig): - super()._transcribe_on_end(trcfg) - - if hasattr(self, 'ctc_decoder'): - self.ctc_decoder.unfreeze(partial=True) - - def _transcribe_forward(self, batch: Any, trcfg: TranscribeConfig): - if self.cur_decoder == "rnnt": - return super()._transcribe_forward(batch, trcfg) - - # CTC Path - encoded, encoded_len = self.forward(input_signal=batch[0], input_signal_length=batch[1]) - - logits = self.ctc_decoder(encoder_output=encoded) - output = dict(logits=logits, encoded_len=encoded_len) - - del encoded - return output - - def _transcribe_output_processing( - self, outputs, trcfg: TranscribeConfig - ) -> Union[List['Hypothesis'], List[List['Hypothesis']]]: - if self.cur_decoder == "rnnt": - return super()._transcribe_output_processing(outputs, trcfg) - - # CTC Path - logits = outputs.pop('logits') - encoded_len = outputs.pop('encoded_len') - - hypotheses = self.ctc_decoding.ctc_decoder_predictions_tensor( - logits, - encoded_len, - return_hypotheses=trcfg.return_hypotheses, - ) - logits = logits.cpu() - - if trcfg.return_hypotheses: - # dump log probs per file - for idx in range(logits.shape[0]): - hypotheses[idx].y_sequence = logits[idx][: encoded_len[idx]] - if hypotheses[idx].alignments is None: - hypotheses[idx].alignments = hypotheses[idx].y_sequence - - # DEPRECATED? - # if logprobs: - # for logit, elen in zip(logits, encoded_len): - # logits_list.append(logit[:elen]) - - if trcfg.timestamps: - hypotheses = process_timestamp_outputs( - hypotheses, self.encoder.subsampling_factor, self.cfg['preprocessor']['window_stride'] - ) - - del logits, encoded_len - - return hypotheses - - def change_vocabulary( - self, - new_vocabulary: List[str], - decoding_cfg: Optional[DictConfig] = None, - ctc_decoding_cfg: Optional[DictConfig] = None, - ): - """ - Changes vocabulary used during RNNT decoding process. Use this method when fine-tuning a - pre-trained model. This method changes only decoder and leaves encoder and pre-processing - modules unchanged. For example, you would use it if you want to use pretrained encoder - when fine-tuning on data in another language, or when you'd need model to learn capitalization, - punctuation and/or special characters. - - Args: - new_vocabulary: list with new vocabulary. Must contain at least 2 elements. Typically, \ - this is target alphabet. - decoding_cfg: A config for the decoder, which is optional. If the decoding type - needs to be changed (from say Greedy to Beam decoding etc), the config can be passed here. - ctc_decoding_cfg: A config for CTC decoding, which is optional and can be used to change decoding type. - - Returns: None - - """ - super().change_vocabulary(new_vocabulary=new_vocabulary, decoding_cfg=decoding_cfg) - - # set up the new tokenizer for the CTC decoder - if hasattr(self, 'ctc_decoder'): - if self.ctc_decoder.vocabulary == new_vocabulary: - logging.warning( - f"Old {self.ctc_decoder.vocabulary} and new {new_vocabulary} match. Not changing anything." - ) - else: - if new_vocabulary is None or len(new_vocabulary) == 0: - raise ValueError(f'New vocabulary must be non-empty list of chars. But I got: {new_vocabulary}') - decoder_config = self.ctc_decoder.to_config_dict() - new_decoder_config = copy.deepcopy(decoder_config) - new_decoder_config['vocabulary'] = new_vocabulary - new_decoder_config['num_classes'] = len(new_vocabulary) - - del self.ctc_decoder - self.ctc_decoder = EncDecHybridRNNTCTCModel.from_config_dict(new_decoder_config) - del self.ctc_loss - self.ctc_loss = CTCLoss( - num_classes=self.ctc_decoder.num_classes_with_blank - 1, - zero_infinity=True, - reduction=self.cfg.aux_ctc.get("ctc_reduction", "mean_batch"), - ) - - if ctc_decoding_cfg is None: - # Assume same decoding config as before - logging.info("No `ctc_decoding_cfg` passed when changing decoding strategy, using internal config") - ctc_decoding_cfg = self.cfg.aux_ctc.decoding - - # Assert the decoding config with all hyper parameters - ctc_decoding_cls = OmegaConf.structured(CTCDecodingConfig) - ctc_decoding_cls = OmegaConf.create(OmegaConf.to_container(ctc_decoding_cls)) - ctc_decoding_cfg = OmegaConf.merge(ctc_decoding_cls, ctc_decoding_cfg) - - self.ctc_decoding = CTCDecoding(decoding_cfg=ctc_decoding_cfg, vocabulary=self.ctc_decoder.vocabulary) - - self.ctc_wer = WER( - decoding=self.ctc_decoding, - use_cer=self.ctc_wer.use_cer, - log_prediction=self.ctc_wer.log_prediction, - dist_sync_on_step=True, - ) - - # Update config - with open_dict(self.cfg.aux_ctc): - self.cfg.aux_ctc.decoding = ctc_decoding_cfg - - with open_dict(self.cfg.aux_ctc): - self.cfg.aux_ctc.decoder = new_decoder_config - - ds_keys = ['train_ds', 'validation_ds', 'test_ds'] - for key in ds_keys: - if key in self.cfg: - with open_dict(self.cfg[key]): - self.cfg[key]['labels'] = OmegaConf.create(new_vocabulary) - - logging.info(f"Changed the tokenizer of the CTC decoder to {self.ctc_decoder.vocabulary} vocabulary.") - - def change_decoding_strategy( - self, decoding_cfg: DictConfig = None, decoder_type: str = None, verbose: bool = True - ): - """ - Changes decoding strategy used during RNNT decoding process. - - Args: - decoding_cfg: A config for the decoder, which is optional. If the decoding type - needs to be changed (from say Greedy to Beam decoding etc), the config can be passed here. - decoder_type: (str) Can be set to 'rnnt' or 'ctc' to switch between appropriate decoder in a - model having RNN-T and CTC decoders. Defaults to None, in which case RNN-T decoder is - used. If set to 'ctc', it raises error if 'ctc_decoder' is not an attribute of the model. - verbose: (bool) whether to display logging information - """ - if decoder_type is None or decoder_type == 'rnnt': - self.cur_decoder = "rnnt" - return super().change_decoding_strategy(decoding_cfg=decoding_cfg, verbose=verbose) - - assert decoder_type == 'ctc' and hasattr(self, 'ctc_decoder') - if decoding_cfg is None: - # Assume same decoding config as before - logging.info("No `decoding_cfg` passed when changing decoding strategy, using internal config") - decoding_cfg = self.cfg.aux_ctc.decoding - - # Assert the decoding config with all hyper parameters - decoding_cls = OmegaConf.structured(CTCDecodingConfig) - decoding_cls = OmegaConf.create(OmegaConf.to_container(decoding_cls)) - decoding_cfg = OmegaConf.merge(decoding_cls, decoding_cfg) - - self.ctc_decoding = CTCDecoding(decoding_cfg=decoding_cfg, vocabulary=self.ctc_decoder.vocabulary) - - self.ctc_wer = WER( - decoding=self.ctc_decoding, - use_cer=self.ctc_wer.use_cer, - log_prediction=self.ctc_wer.log_prediction, - dist_sync_on_step=True, - ) - - self.ctc_decoder.temperature = decoding_cfg.get('temperature', 1.0) - - # Update config - with open_dict(self.cfg.aux_ctc): - self.cfg.aux_ctc.decoding = decoding_cfg - - self.cur_decoder = "ctc" - if verbose: - logging.info(f"Changed decoding strategy to \n{OmegaConf.to_yaml(self.cfg.aux_ctc.decoding)}") - - return None - - # PTL-specific methods - def training_step(self, batch, batch_nb): - # Reset access registry - if AccessMixin.is_access_enabled(self.model_guid): - AccessMixin.reset_registry(self) - - if self.is_interctc_enabled(): - AccessMixin.set_access_enabled(access_enabled=True, guid=self.model_guid) - - signal, signal_len, transcript, transcript_len = batch - - # forward() only performs encoder forward - if isinstance(batch, DALIOutputs) and batch.has_processed_signal: - encoded, encoded_len = self.forward(processed_signal=signal, processed_signal_length=signal_len) - else: - encoded, encoded_len = self.forward(input_signal=signal, input_signal_length=signal_len) - del signal - - # During training, loss must be computed, so decoder forward is necessary - decoder, target_length, states = self.decoder(targets=transcript, target_length=transcript_len) - - if hasattr(self, '_trainer') and self._trainer is not None: - log_every_n_steps = self._trainer.log_every_n_steps - sample_id = self._trainer.global_step - else: - log_every_n_steps = 1 - sample_id = batch_nb - - if (sample_id + 1) % log_every_n_steps == 0: - compute_wer = True - else: - compute_wer = False - - # If fused Joint-Loss-WER is not used - if not self.joint.fuse_loss_wer: - # Compute full joint and loss - joint = self.joint(encoder_outputs=encoded, decoder_outputs=decoder) - loss_value = self.loss( - log_probs=joint, targets=transcript, input_lengths=encoded_len, target_lengths=target_length - ) - - # Add auxiliary losses, if registered - loss_value = self.add_auxiliary_losses(loss_value) - - tensorboard_logs = { - 'learning_rate': self._optimizer.param_groups[0]['lr'], - 'global_step': torch.tensor(self.trainer.global_step, dtype=torch.float32), - } - - if compute_wer: - self.wer.update( - predictions=encoded, - predictions_lengths=encoded_len, - targets=transcript, - targets_lengths=transcript_len, - ) - _, scores, words = self.wer.compute() - self.wer.reset() - tensorboard_logs.update({'training_batch_wer': scores.float() / words}) - - else: # If fused Joint-Loss-WER is used - # Fused joint step - loss_value, wer, _, _ = self.joint( - encoder_outputs=encoded, - decoder_outputs=decoder, - encoder_lengths=encoded_len, - transcripts=transcript, - transcript_lengths=transcript_len, - compute_wer=compute_wer, - ) - - # Add auxiliary losses, if registered - loss_value = self.add_auxiliary_losses(loss_value) - - tensorboard_logs = { - 'learning_rate': self._optimizer.param_groups[0]['lr'], - 'global_step': torch.tensor(self.trainer.global_step, dtype=torch.float32), - } - - if compute_wer: - tensorboard_logs.update({'training_batch_wer': wer}) - - if self.ctc_loss_weight > 0: - log_probs = self.ctc_decoder(encoder_output=encoded) - ctc_loss = self.ctc_loss( - log_probs=log_probs, targets=transcript, input_lengths=encoded_len, target_lengths=transcript_len - ) - tensorboard_logs['train_rnnt_loss'] = loss_value - tensorboard_logs['train_ctc_loss'] = ctc_loss - loss_value = (1 - self.ctc_loss_weight) * loss_value + self.ctc_loss_weight * ctc_loss - if compute_wer: - self.ctc_wer.update( - predictions=log_probs, - targets=transcript, - targets_lengths=transcript_len, - predictions_lengths=encoded_len, - ) - ctc_wer, _, _ = self.ctc_wer.compute() - self.ctc_wer.reset() - tensorboard_logs.update({'training_batch_wer_ctc': ctc_wer}) - - # note that we want to apply interctc independent of whether main ctc - # loss is used or not (to allow rnnt + interctc training). - # assuming ``ctc_loss_weight=0.3`` and interctc is applied to a single - # layer with weight of ``0.1``, the total loss will be - # ``loss = 0.9 * (0.3 * ctc_loss + 0.7 * rnnt_loss) + 0.1 * interctc_loss`` - loss_value, additional_logs = self.add_interctc_losses( - loss_value, transcript, transcript_len, compute_wer=compute_wer - ) - tensorboard_logs.update(additional_logs) - tensorboard_logs['train_loss'] = loss_value - # Reset access registry - if AccessMixin.is_access_enabled(self.model_guid): - AccessMixin.reset_registry(self) - - # Log items - self.log_dict(tensorboard_logs) - - # Preserve batch acoustic model T and language model U parameters if normalizing - if self._optim_normalize_joint_txu: - self._optim_normalize_txu = [encoded_len.max(), transcript_len.max()] - - return {'loss': loss_value} - - def predict_step(self, batch, batch_idx, dataloader_idx=0): - signal, signal_len, transcript, transcript_len, sample_id = batch - - # forward() only performs encoder forward - if isinstance(batch, DALIOutputs) and batch.has_processed_signal: - encoded, encoded_len = self.forward(processed_signal=signal, processed_signal_length=signal_len) - else: - encoded, encoded_len = self.forward(input_signal=signal, input_signal_length=signal_len) - del signal - - if self.cur_decoder == 'rnnt': - best_hyp = self.decoding.rnnt_decoder_predictions_tensor( - encoder_output=encoded, encoded_lengths=encoded_len, return_hypotheses=True - ) - else: - logits = self.ctc_decoder(encoder_output=encoded) - best_hyp = self.ctc_decoding.ctc_decoder_predictions_tensor( - decoder_outputs=logits, - decoder_lengths=encoded_len, - return_hypotheses=True, - ) - - if isinstance(sample_id, torch.Tensor): - sample_id = sample_id.cpu().detach().numpy() - return list(zip(sample_id, best_hyp)) - - def validation_pass(self, batch, batch_idx, dataloader_idx): - if self.is_interctc_enabled(): - AccessMixin.set_access_enabled(access_enabled=True, guid=self.model_guid) - - signal, signal_len, transcript, transcript_len = batch - - # forward() only performs encoder forward - if isinstance(batch, DALIOutputs) and batch.has_processed_signal: - encoded, encoded_len = self.forward(processed_signal=signal, processed_signal_length=signal_len) - else: - encoded, encoded_len = self.forward(input_signal=signal, input_signal_length=signal_len) - del signal - - tensorboard_logs = {} - loss_value = None - - # If experimental fused Joint-Loss-WER is not used - if not self.joint.fuse_loss_wer: - if self.compute_eval_loss: - decoder, target_length, states = self.decoder(targets=transcript, target_length=transcript_len) - joint = self.joint(encoder_outputs=encoded, decoder_outputs=decoder) - - loss_value = self.loss( - log_probs=joint, targets=transcript, input_lengths=encoded_len, target_lengths=target_length - ) - tensorboard_logs['val_loss'] = loss_value - - self.wer.update( - predictions=encoded, - predictions_lengths=encoded_len, - targets=transcript, - targets_lengths=transcript_len, - ) - wer, wer_num, wer_denom = self.wer.compute() - self.wer.reset() - - tensorboard_logs['val_wer_num'] = wer_num - tensorboard_logs['val_wer_denom'] = wer_denom - tensorboard_logs['val_wer'] = wer - - else: - # If experimental fused Joint-Loss-WER is used - compute_wer = True - - if self.compute_eval_loss: - decoded, target_len, states = self.decoder(targets=transcript, target_length=transcript_len) - else: - decoded = None - target_len = transcript_len - - # Fused joint step - loss_value, wer, wer_num, wer_denom = self.joint( - encoder_outputs=encoded, - decoder_outputs=decoded, - encoder_lengths=encoded_len, - transcripts=transcript, - transcript_lengths=target_len, - compute_wer=compute_wer, - ) - if loss_value is not None: - tensorboard_logs['val_loss'] = loss_value - - tensorboard_logs['val_wer_num'] = wer_num - tensorboard_logs['val_wer_denom'] = wer_denom - tensorboard_logs['val_wer'] = wer - - log_probs = self.ctc_decoder(encoder_output=encoded) - if self.compute_eval_loss: - ctc_loss = self.ctc_loss( - log_probs=log_probs, targets=transcript, input_lengths=encoded_len, target_lengths=transcript_len - ) - tensorboard_logs['val_ctc_loss'] = ctc_loss - tensorboard_logs['val_rnnt_loss'] = loss_value - loss_value = (1 - self.ctc_loss_weight) * loss_value + self.ctc_loss_weight * ctc_loss - tensorboard_logs['val_loss'] = loss_value - self.ctc_wer.update( - predictions=log_probs, - targets=transcript, - targets_lengths=transcript_len, - predictions_lengths=encoded_len, - ) - ctc_wer, ctc_wer_num, ctc_wer_denom = self.ctc_wer.compute() - self.ctc_wer.reset() - tensorboard_logs['val_wer_num_ctc'] = ctc_wer_num - tensorboard_logs['val_wer_denom_ctc'] = ctc_wer_denom - tensorboard_logs['val_wer_ctc'] = ctc_wer - - self.log('global_step', torch.tensor(self.trainer.global_step, dtype=torch.float32)) - - loss_value, additional_logs = self.add_interctc_losses( - loss_value, - transcript, - transcript_len, - compute_wer=True, - compute_loss=self.compute_eval_loss, - log_wer_num_denom=True, - log_prefix="val_", - ) - if self.compute_eval_loss: - # overriding total loss value. Note that the previous - # rnnt + ctc loss is available in metrics as "val_final_loss" now - tensorboard_logs['val_loss'] = loss_value - tensorboard_logs.update(additional_logs) - # Reset access registry - if AccessMixin.is_access_enabled(self.model_guid): - AccessMixin.reset_registry(self) - - return tensorboard_logs - - def validation_step(self, batch, batch_idx, dataloader_idx=0): - tensorboard_logs = self.validation_pass(batch, batch_idx, dataloader_idx) - if type(self.trainer.val_dataloaders) == list and len(self.trainer.val_dataloaders) > 1: - self.validation_step_outputs[dataloader_idx].append(tensorboard_logs) - else: - self.validation_step_outputs.append(tensorboard_logs) - - return tensorboard_logs - - def test_step(self, batch, batch_idx, dataloader_idx=0): - logs = self.validation_pass(batch, batch_idx, dataloader_idx=dataloader_idx) - test_logs = {name.replace("val_", "test_"): value for name, value in logs.items()} - if type(self.trainer.test_dataloaders) == list and len(self.trainer.test_dataloaders) > 1: - self.test_step_outputs[dataloader_idx].append(test_logs) - else: - self.test_step_outputs.append(test_logs) - return test_logs - - def multi_validation_epoch_end(self, outputs, dataloader_idx: int = 0): - if not outputs or not all([isinstance(x, dict) for x in outputs]): - logging.warning("No outputs to process for validation_epoch_end") - return {} - if self.compute_eval_loss: - val_loss_mean = torch.stack([x['val_loss'] for x in outputs]).mean() - val_loss_log = {'val_loss': val_loss_mean} - else: - val_loss_log = {} - wer_num = torch.stack([x['val_wer_num'] for x in outputs]).sum() - wer_denom = torch.stack([x['val_wer_denom'] for x in outputs]).sum() - tensorboard_logs = {**val_loss_log, 'val_wer': wer_num.float() / wer_denom} - if self.ctc_loss_weight > 0: - ctc_wer_num = torch.stack([x['val_wer_num_ctc'] for x in outputs]).sum() - ctc_wer_denom = torch.stack([x['val_wer_denom_ctc'] for x in outputs]).sum() - tensorboard_logs['val_wer_ctc'] = ctc_wer_num.float() / ctc_wer_denom - metrics = {**val_loss_log, 'log': tensorboard_logs} - self.finalize_interctc_metrics(metrics, outputs, prefix="val_") - return metrics - - def multi_test_epoch_end(self, outputs, dataloader_idx: int = 0): - if self.compute_eval_loss: - test_loss_mean = torch.stack([x['test_loss'] for x in outputs]).mean() - test_loss_log = {'test_loss': test_loss_mean} - else: - test_loss_log = {} - wer_num = torch.stack([x['test_wer_num'] for x in outputs]).sum() - wer_denom = torch.stack([x['test_wer_denom'] for x in outputs]).sum() - tensorboard_logs = {**test_loss_log, 'test_wer': wer_num.float() / wer_denom} - - if self.ctc_loss_weight > 0: - ctc_wer_num = torch.stack([x['test_wer_num_ctc'] for x in outputs]).sum() - ctc_wer_denom = torch.stack([x['test_wer_denom_ctc'] for x in outputs]).sum() - tensorboard_logs['test_wer_ctc'] = ctc_wer_num.float() / ctc_wer_denom - - metrics = {**test_loss_log, 'log': tensorboard_logs} - self.finalize_interctc_metrics(metrics, outputs, prefix="test_") - return metrics - - # EncDecRNNTModel is exported in 2 parts - def list_export_subnets(self): - if self.cur_decoder == 'rnnt': - return ['encoder', 'decoder_joint'] - else: - return ['self'] - - @property - def output_module(self): - if self.cur_decoder == 'rnnt': - return self.decoder - else: - return self.ctc_decoder - - @classmethod - def list_available_models(cls) -> Optional[PretrainedModelInfo]: - """ - This method returns a list of pre-trained model which can be instantiated directly from NVIDIA's NGC cloud. - - Returns: - List of available pre-trained models. - """ - results = [] - model = PretrainedModelInfo( - pretrained_model_name="parakeet-tdt_ctc-110m", - description="For details on this model, please refer to https://ngc.nvidia.com/catalog/models/nvidia:nemo:parakeet-tdt_ctc-110m", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/parakeet-tdt_ctc-110m/versions/v1/files/parakeet-tdt_ctc-110m.nemo", - ) - results.append(model) - return results diff --git a/nemo/collections/asr/models/label_models.py b/nemo/collections/asr/models/label_models.py deleted file mode 100644 index 9300f7cfc897e946072508fbd05ec21c395633d6..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/label_models.py +++ /dev/null @@ -1,844 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import copy -import itertools -import os -import tempfile -from collections import Counter -from math import ceil -from typing import Dict, List, Optional, Union - -import librosa -import numpy as np -import soundfile as sf -import torch -from hydra.utils import instantiate -from lightning.pytorch import Trainer -from omegaconf import DictConfig, OmegaConf, open_dict -from sklearn.metrics import roc_curve -from torchmetrics import Accuracy -from tqdm import tqdm - -from nemo.collections.asr.data.audio_to_label import ( - AudioPairToLabelDataset, - AudioToSpeechLabelDataset, - cache_datastore_manifests, -) -from nemo.collections.asr.data.audio_to_label_dataset import ( - get_concat_tarred_speech_label_dataset, - get_tarred_speech_label_dataset, -) -from nemo.collections.asr.data.audio_to_text_dataset import convert_to_config_list -from nemo.collections.asr.models.asr_model import ExportableEncDecModel -from nemo.collections.asr.parts.mixins.mixins import VerificationMixin -from nemo.collections.asr.parts.preprocessing.features import WaveformFeaturizer -from nemo.collections.asr.parts.preprocessing.perturb import process_augmentations -from nemo.collections.common.metrics import TopKClassificationAccuracy -from nemo.collections.common.parts.preprocessing.collections import ASRSpeechLabel -from nemo.core.classes import ModelPT -from nemo.core.classes.common import PretrainedModelInfo -from nemo.core.neural_types import * -from nemo.utils import logging - -__all__ = ['EncDecSpeakerLabelModel'] - - -class EncDecSpeakerLabelModel(ModelPT, ExportableEncDecModel, VerificationMixin): - """ - Encoder decoder class for speaker label models. - Model class creates training, validation methods for setting up data - performing model forward pass. - Expects config dict for - - * preprocessor - - * Jasper/Quartznet Encoder - - * Speaker Decoder - """ - - @classmethod - def list_available_models(cls) -> List[PretrainedModelInfo]: - """ - This method returns a list of pre-trained model which can be instantiated directly from NVIDIA's NGC cloud. - Returns: - List of available pre-trained models. - """ - result = [] - - model = PretrainedModelInfo( - pretrained_model_name="speakerverification_speakernet", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/speakerverification_speakernet/versions/1.16.0/files/speakerverification_speakernet.nemo", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:speakerverification_speakernet", - ) - result.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="ecapa_tdnn", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/ecapa_tdnn/versions/1.16.0/files/ecapa_tdnn.nemo", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:ecapa_tdnn", - ) - result.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="titanet_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/titanet_large/versions/v1/files/titanet-l.nemo", - description="For details about this model, please visit https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/titanet_large", - ) - result.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="langid_ambernet", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/langid_ambernet/versions/1.12.0/files/ambernet.nemo", - description="For details about this model, please visit https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/langid_ambernet", - ) - result.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="titanet_small", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:titanet_small", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/titanet_small/versions/1.19.0/files/titanet-s.nemo", - ) - result.append(model) - - return result - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - self.world_size = 1 - self.cal_labels_occurrence_train = False - self.labels_occurrence = None - self.labels = None - - num_classes = cfg.decoder.num_classes - - if 'loss' in cfg: - if 'weight' in cfg.loss: - if cfg.loss.weight == 'auto': - weight = num_classes * [1] - self.cal_labels_occurrence_train = True - else: - weight = cfg.loss.weight - else: - weight = None # weight is None for angular loss and CE loss if it's not specified. - - if trainer is not None: - self.world_size = trainer.num_nodes * trainer.num_devices - - super().__init__(cfg=cfg, trainer=trainer) - - if self.labels_occurrence: - # Goal is to give more weight to the classes with less samples so as to match the ones with the higher frequencies - weight = [sum(self.labels_occurrence) / (len(self.labels_occurrence) * i) for i in self.labels_occurrence] - - if 'loss' in cfg: - cfg_eval_loss = copy.deepcopy(cfg.loss) - - if 'angular' in cfg.loss.get('_target_', {}): - OmegaConf.set_struct(cfg, True) - with open_dict(cfg): - cfg.decoder.angular = True - - if 'weight' in cfg.loss: - cfg.loss.weight = weight - cfg_eval_loss.weight = None - - # May need a general check for arguments of loss - self.loss = instantiate(cfg.loss) - self.eval_loss = instantiate(cfg_eval_loss) - - else: - tmp_loss_cfg = OmegaConf.create( - {"_target_": "nemo.collections.common.losses.cross_entropy.CrossEntropyLoss"} - ) - - self.loss = instantiate(tmp_loss_cfg) - self.eval_loss = instantiate(tmp_loss_cfg) - - self._accuracy = TopKClassificationAccuracy(top_k=[1]) - - self.preprocessor = EncDecSpeakerLabelModel.from_config_dict(cfg.preprocessor) - self.encoder = EncDecSpeakerLabelModel.from_config_dict(cfg.encoder) - self.decoder = EncDecSpeakerLabelModel.from_config_dict(cfg.decoder) - - self._macro_accuracy = Accuracy(num_classes=num_classes, top_k=1, average='macro', task='multiclass') - self._pair_macro_accuracy = Accuracy(num_classes=2, top_k=1, average='macro', task='multiclass') - - if hasattr(self._cfg, 'spec_augment') and self._cfg.spec_augment is not None: - self.spec_augmentation = EncDecSpeakerLabelModel.from_config_dict(self._cfg.spec_augment) - else: - self.spec_augmentation = None - - @staticmethod - def extract_labels(data_layer_config): - labels = set() - manifest_filepath = data_layer_config.get('manifest_filepath', None) - if manifest_filepath is None: - logging.warning("No manifest_filepath was provided, no labels got extracted!") - return None - manifest_filepaths = convert_to_config_list(data_layer_config['manifest_filepath']) - - for manifest_filepath in itertools.chain.from_iterable(manifest_filepaths): - cache_datastore_manifests(manifest_filepaths=manifest_filepath) - collection = ASRSpeechLabel( - manifests_files=manifest_filepath, - min_duration=data_layer_config.get("min_duration", None), - max_duration=data_layer_config.get("max_duration", None), - index_by_file_id=True, - ) - labels.update(collection.uniq_labels) - labels = list(sorted(labels)) - logging.warning(f"Total number of {len(labels)} labels found in all the manifest files.") - return labels - - def __setup_dataloader_from_config(self, config: Optional[Dict]): - if 'augmentor' in config: - augmentor = process_augmentations(config['augmentor']) - else: - augmentor = None - - featurizer = WaveformFeaturizer( - sample_rate=config['sample_rate'], int_values=config.get('int_values', False), augmentor=augmentor - ) - shuffle = config.get('shuffle', False) - if config.get('is_tarred', False): - if ('tarred_audio_filepaths' in config and config['tarred_audio_filepaths'] is None) or ( - 'manifest_filepath' in config and config['manifest_filepath'] is None - ): - logging.warning( - "Could not load dataset as `manifest_filepath` was None or " - f"`tarred_audio_filepaths` is None. Provided config : {config}" - ) - return None - - shuffle_n = config.get('shuffle_n', 4 * config['batch_size']) if shuffle else 0 - if config.get("is_concat", False): - dataset = get_concat_tarred_speech_label_dataset( - featurizer=featurizer, - config=config, - shuffle_n=shuffle_n, - global_rank=self.global_rank, - world_size=self.world_size, - ) - else: - dataset = get_tarred_speech_label_dataset( - featurizer=featurizer, - config=config, - shuffle_n=shuffle_n, - global_rank=self.global_rank, - world_size=self.world_size, - ) - shuffle = False - else: - if 'manifest_filepath' in config and config['manifest_filepath'] is None: - logging.warning(f"Could not load dataset as `manifest_filepath` was None. Provided config : {config}") - return None - - if config.get("is_audio_pair", False): - data_cls = AudioPairToLabelDataset - logging.warning("Using AudioPairToLabelDataset, where Angular loss will not be computed.") - else: - data_cls = AudioToSpeechLabelDataset - - dataset = data_cls( - manifest_filepath=config['manifest_filepath'], - labels=config['labels'], - featurizer=featurizer, - max_duration=config.get('max_duration', None), - min_duration=config.get('min_duration', None), - trim=config.get('trim_silence', False), - channel_selector=config.get('channel_selector', None), - normalize_audio=config.get('normalize_audio', False), - cal_labels_occurrence=config.get('cal_labels_occurrence', False), - ) - if dataset.labels_occurrence: - self.labels_occurrence = dataset.labels_occurrence - - if hasattr(dataset, 'fixed_seq_collate_fn'): - collate_fn = dataset.fixed_seq_collate_fn - else: - collate_fn = dataset.datasets[0].fixed_seq_collate_fn - - batch_size = config['batch_size'] - return torch.utils.data.DataLoader( - dataset=dataset, - batch_size=batch_size, - collate_fn=collate_fn, - drop_last=config.get('drop_last', False), - shuffle=shuffle, - num_workers=config.get('num_workers', 0), - pin_memory=config.get('pin_memory', False), - ) - - def setup_training_data(self, train_data_layer_config: Optional[Union[DictConfig, Dict]]): - if self.cal_labels_occurrence_train: - # Calculate labels occurence for weighed CE loss for train set if weight equals 'auto' - # Note in this case, the cal_labels_occurrence in val_data_layer_config and test_data_layer_params need to be stay as False - OmegaConf.set_struct(train_data_layer_config, True) - with open_dict(train_data_layer_config): - train_data_layer_config['cal_labels_occurrence'] = True - - self.labels = self.extract_labels(train_data_layer_config) - train_data_layer_config['labels'] = self.labels - if 'shuffle' not in train_data_layer_config: - train_data_layer_config['shuffle'] = True - self._train_dl = self.__setup_dataloader_from_config(config=train_data_layer_config) - # Need to set this because if using an IterableDataset, the length of the dataloader is the total number - # of samples rather than the number of batches, and this messes up the tqdm progress bar. - # So we set the number of steps manually (to the correct number) to fix this. - if ( - self._train_dl is not None - and hasattr(self._train_dl, 'dataset') - and isinstance(self._train_dl.dataset, torch.utils.data.IterableDataset) - ): - # We also need to check if limit_train_batches is already set. - # If it's an int, we assume that the user has set it to something sane, i.e. <= # training batches, - # and don't change it. Otherwise, adjust batches accordingly if it's a float (including 1.0). - if self._trainer is not None and isinstance(self._trainer.limit_train_batches, float): - self._trainer.limit_train_batches = int( - self._trainer.limit_train_batches - * ceil((len(self._train_dl.dataset) / self.world_size) / train_data_layer_config['batch_size']) - ) - elif self._trainer is None: - logging.warning( - "Model Trainer was not set before constructing the dataset, incorrect number of " - "training batches will be used. Please set the trainer and rebuild the dataset." - ) - - def setup_validation_data(self, val_data_layer_config: Optional[Union[DictConfig, Dict]]): - if val_data_layer_config.get("is_audio_pair", False): - val_data_layer_config['labels'] = ["0", "1"] - else: - val_data_layer_config['labels'] = self.labels - self._validation_dl = self.__setup_dataloader_from_config(config=val_data_layer_config) - - def setup_test_data(self, test_data_layer_params: Optional[Union[DictConfig, Dict]]): - if hasattr(self, 'dataset'): - if test_data_layer_params.get("is_audio_pair", False): - test_data_layer_params['labels'] = ["0", "1"] - else: - test_data_layer_params['labels'] = self.labels - - self.embedding_dir = test_data_layer_params.get('embedding_dir', './') - self._test_dl = self.__setup_dataloader_from_config(config=test_data_layer_params) - self.test_manifest = test_data_layer_params.get('manifest_filepath', None) - - def test_dataloader(self): - if self._test_dl is not None: - return self._test_dl - - @property - def input_types(self) -> Optional[Dict[str, NeuralType]]: - if hasattr(self.preprocessor, '_sample_rate'): - audio_eltype = AudioSignal(freq=self.preprocessor._sample_rate) - else: - audio_eltype = AudioSignal() - return { - "input_signal": NeuralType(('B', 'T'), audio_eltype), - "input_signal_length": NeuralType(tuple('B'), LengthsType()), - } - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - return { - "logits": NeuralType(('B', 'D'), LogitsType()), - "embs": NeuralType(('B', 'D'), AcousticEncodedRepresentation()), - } - - def forward_for_export(self, audio_signal, length): - encoded, length = self.encoder(audio_signal=audio_signal, length=length) - output = self.decoder(encoder_output=encoded, length=length) - return output - - def forward(self, input_signal, input_signal_length): - processed_signal, processed_signal_len = self.preprocessor( - input_signal=input_signal, - length=input_signal_length, - ) - - if self.spec_augmentation is not None and self.training: - processed_signal = self.spec_augmentation(input_spec=processed_signal, length=processed_signal_len) - - encoder_outputs = self.encoder(audio_signal=processed_signal, length=processed_signal_len) - if isinstance(encoder_outputs, tuple): - encoded, length = encoder_outputs - else: - encoded, length = encoder_outputs, None - decoder_outputs = self.decoder(encoder_output=encoded, length=length) - if isinstance(decoder_outputs, tuple): - logits, embs = decoder_outputs - else: - logits, embs = decoder_outputs, None - - return logits, embs - - # PTL-specific methods - def training_step(self, batch, batch_idx): - if len(batch) > 4: - audio_signal_1, audio_signal_len_1, audio_signal_2, audio_signal_len_2, labels, _ = batch - _, audio_emb1 = self.forward(input_signal=audio_signal_1, input_signal_length=audio_signal_len_1) - _, audio_emb2 = self.forward(input_signal=audio_signal_2, input_signal_length=audio_signal_len_2) - - # convert binary labels to -1, 1 - loss_labels = (labels.float() - 0.5) * 2 - cosine_sim = torch.cosine_similarity(audio_emb1, audio_emb2) - loss = torch.nn.functional.mse_loss(cosine_sim, loss_labels) - else: - audio_signal, audio_signal_len, labels, _ = batch - output = self.forward(input_signal=audio_signal, input_signal_length=audio_signal_len) - if isinstance(output, tuple): - logits, _ = output - else: - logits = output - loss = self.loss(logits=logits, labels=labels) - - self.log('loss', loss) - self.log('learning_rate', self._optimizer.param_groups[0]['lr']) - self.log('global_step', self.trainer.global_step) - - self._accuracy(logits=logits, labels=labels) - top_k = self._accuracy.compute() - self._accuracy.reset() - for i, top_i in enumerate(top_k): - self.log(f'training_batch_accuracy_top_{i}', top_i) - - return {'loss': loss} - - def evaluation_step(self, batch, batch_idx, dataloader_idx: int = 0, tag: str = 'val'): - if len(batch) > 4: - return self.pair_evaluation_step(batch, batch_idx, dataloader_idx, tag) - - audio_signal, audio_signal_len, labels, _ = batch - output = self.forward(input_signal=audio_signal, input_signal_length=audio_signal_len) - if isinstance(output, tuple): - logits, _ = output - else: - logits = output - loss_value = self.eval_loss(logits=logits, labels=labels) - - acc_top_k = self._accuracy(logits=logits, labels=labels) - correct_counts, total_counts = self._accuracy.correct_counts_k, self._accuracy.total_counts_k - self._macro_accuracy.update(preds=logits, target=labels) - stats = self._macro_accuracy._final_state() - - output = { - f'{tag}_loss': loss_value, - f'{tag}_correct_counts': correct_counts, - f'{tag}_total_counts': total_counts, - f'{tag}_acc_micro_top_k': acc_top_k, - f'{tag}_acc_macro_stats': stats, - } - if tag == 'val': - if isinstance(self.trainer.val_dataloaders, (list, tuple)) and len(self.trainer.val_dataloaders) > 1: - self.validation_step_outputs[dataloader_idx].append(output) - else: - self.validation_step_outputs.append(output) - else: - if isinstance(self.trainer.test_dataloaders, (list, tuple)) and len(self.trainer.test_dataloaders) > 1: - self.test_step_outputs[dataloader_idx].append(output) - else: - self.test_step_outputs.append(output) - - return output - - def pair_evaluation_step(self, batch, batch_idx, dataloader_idx: int = 0, tag: str = 'val'): - audio_signal_1, audio_signal_len_1, audio_signal_2, audio_signal_len_2, labels, _ = batch - _, audio_emb1 = self.forward(input_signal=audio_signal_1, input_signal_length=audio_signal_len_1) - _, audio_emb2 = self.forward(input_signal=audio_signal_2, input_signal_length=audio_signal_len_2) - - # convert binary labels to -1, 1 - loss_labels = (labels.float() - 0.5) * 2 - cosine_sim = torch.cosine_similarity(audio_emb1, audio_emb2) - loss_value = torch.nn.functional.mse_loss(cosine_sim, loss_labels) - - logits = torch.stack([1 - cosine_sim, cosine_sim], dim=-1) - acc_top_k = self._accuracy(logits=logits, labels=labels) - correct_counts, total_counts = self._accuracy.correct_counts_k, self._accuracy.total_counts_k - self._pair_macro_accuracy.update(preds=logits, target=labels) - stats = self._pair_macro_accuracy._final_state() - - output = { - f'{tag}_loss': loss_value, - f'{tag}_correct_counts': correct_counts, - f'{tag}_total_counts': total_counts, - f'{tag}_acc_micro_top_k': acc_top_k, - f'{tag}_acc_macro_stats': stats, - f"{tag}_scores": cosine_sim, - f"{tag}_labels": labels, - } - - if tag == 'val': - if isinstance(self.trainer.val_dataloaders, (list, tuple)) and len(self.trainer.val_dataloaders) > 1: - self.validation_step_outputs[dataloader_idx].append(output) - else: - self.validation_step_outputs.append(output) - else: - if isinstance(self.trainer.test_dataloaders, (list, tuple)) and len(self.trainer.test_dataloaders) > 1: - self.test_step_outputs[dataloader_idx].append(output) - else: - self.test_step_outputs.append(output) - - return output - - def pair_multi_eval_epoch_end(self, outputs, dataloader_idx: int = 0, tag: str = 'val'): - loss_mean = torch.stack([x[f'{tag}_loss'] for x in outputs]).mean() - scores = torch.cat([x[f'{tag}_scores'] for x in outputs]).cpu().numpy() - labels = torch.cat([x[f'{tag}_labels'] for x in outputs]).long().cpu().numpy() - fpr, tpr, thresholds = roc_curve(y_true=labels, y_score=scores, pos_label=1) - fnr = 1 - tpr - try: - eer = fpr[np.nanargmin(np.absolute((fnr - fpr)))] * 100 - except ValueError as e: - logging.warning(f"Got ValueError while calculating EER: {e}") - eer = 100.0 - - correct_counts = torch.stack([x[f'{tag}_correct_counts'] for x in outputs]).sum(axis=0) - total_counts = torch.stack([x[f'{tag}_total_counts'] for x in outputs]).sum(axis=0) - - self._accuracy.correct_counts_k = correct_counts - self._accuracy.total_counts_k = total_counts - topk_scores = self._accuracy.compute() - - self._pair_macro_accuracy.tp = torch.stack([x[f'{tag}_acc_macro_stats'][0] for x in outputs]).sum(axis=0) - self._pair_macro_accuracy.fp = torch.stack([x[f'{tag}_acc_macro_stats'][1] for x in outputs]).sum(axis=0) - self._pair_macro_accuracy.tn = torch.stack([x[f'{tag}_acc_macro_stats'][2] for x in outputs]).sum(axis=0) - self._pair_macro_accuracy.fn = torch.stack([x[f'{tag}_acc_macro_stats'][3] for x in outputs]).sum(axis=0) - macro_accuracy_score = self._pair_macro_accuracy.compute() - - self._accuracy.reset() - self._pair_macro_accuracy.reset() - - tensorboard_logs = {f'{tag}_loss': loss_mean, f"{tag}_eer": eer} - for top_k, score in zip(self._accuracy.top_k, topk_scores): - tensorboard_logs[f'{tag}_acc_micro_top_{top_k}'] = score - tensorboard_logs[f'{tag}_acc_macro'] = macro_accuracy_score - - return {f'{tag}_loss': loss_mean, 'log': tensorboard_logs} - - def multi_evaluation_epoch_end(self, outputs, dataloader_idx: int = 0, tag: str = 'val'): - # Check if all outputs are non-empty - if not outputs or not all([bool(x) for x in outputs]): - logging.warning( - f"Not all outputs are dictionaries. Cannot aggregate results for {tag} dataset in dataloader {dataloader_idx}. Outputs: {outputs}" - ) - return {} - - if f"{tag}_scores" in outputs[0]: - return self.pair_multi_eval_epoch_end(outputs, dataloader_idx, tag) - - loss_mean = torch.stack([x[f'{tag}_loss'] for x in outputs]).mean() - - correct_counts = torch.stack([x[f'{tag}_correct_counts'] for x in outputs]).sum(axis=0) - total_counts = torch.stack([x[f'{tag}_total_counts'] for x in outputs]).sum(axis=0) - - self._accuracy.correct_counts_k = correct_counts - self._accuracy.total_counts_k = total_counts - topk_scores = self._accuracy.compute() - - self._macro_accuracy.tp = torch.stack([x[f'{tag}_acc_macro_stats'][0] for x in outputs]).sum(axis=0) - self._macro_accuracy.fp = torch.stack([x[f'{tag}_acc_macro_stats'][1] for x in outputs]).sum(axis=0) - self._macro_accuracy.tn = torch.stack([x[f'{tag}_acc_macro_stats'][2] for x in outputs]).sum(axis=0) - self._macro_accuracy.fn = torch.stack([x[f'{tag}_acc_macro_stats'][3] for x in outputs]).sum(axis=0) - macro_accuracy_score = self._macro_accuracy.compute() - - self._accuracy.reset() - self._macro_accuracy.reset() - - tensorboard_logs = {f'{tag}_loss': loss_mean} - for top_k, score in zip(self._accuracy.top_k, topk_scores): - tensorboard_logs[f'{tag}_acc_micro_top_{top_k}'] = score - tensorboard_logs[f'{tag}_acc_macro'] = macro_accuracy_score - - return {f'{tag}_loss': loss_mean, 'log': tensorboard_logs} - - def validation_step(self, batch, batch_idx, dataloader_idx: int = 0): - return self.evaluation_step(batch, batch_idx, dataloader_idx, 'val') - - def multi_validation_epoch_end(self, outputs, dataloader_idx: int = 0): - return self.multi_evaluation_epoch_end(outputs, dataloader_idx, 'val') - - def test_step(self, batch, batch_idx, dataloader_idx: int = 0): - return self.evaluation_step(batch, batch_idx, dataloader_idx, 'test') - - def multi_test_epoch_end(self, outputs, dataloader_idx: int = 0): - return self.multi_evaluation_epoch_end(outputs, dataloader_idx, 'test') - - @torch.no_grad() - def infer_file(self, path2audio_file): - """ - Args: - path2audio_file: path to an audio wav file - - Returns: - emb: speaker embeddings (Audio representations) - logits: logits corresponding of final layer - """ - audio, sr = sf.read(path2audio_file) - target_sr = self._cfg.train_ds.get('sample_rate', 16000) - if sr != target_sr: - audio = librosa.core.resample(audio, orig_sr=sr, target_sr=target_sr) - audio_length = audio.shape[0] - device = self.device - audio = np.array([audio]) - audio_signal, audio_signal_len = ( - torch.tensor(audio, device=device, dtype=torch.float32), - torch.tensor([audio_length], device=device), - ) - mode = self.training - self.freeze() - - logits, emb = self.forward(input_signal=audio_signal, input_signal_length=audio_signal_len) - - self.train(mode=mode) - if mode is True: - self.unfreeze() - del audio_signal, audio_signal_len - return emb, logits - - @torch.no_grad() - def infer_segment(self, segment): - """ - Args: - segment: segment of audio file - - Returns: - emb: speaker embeddings (Audio representations) - logits: logits corresponding of final layer - """ - segment_length = segment.shape[0] - - device = self.device - audio = np.array([segment]) - audio_signal, audio_signal_len = ( - torch.tensor(audio, device=device, dtype=torch.float32), - torch.tensor([segment_length], device=device), - ) - mode = self.training - self.freeze() - - logits, emb = self.forward(input_signal=audio_signal, input_signal_length=audio_signal_len) - - self.train(mode=mode) - if mode is True: - self.unfreeze() - del audio_signal, audio_signal_len - return emb, logits - - def get_label( - self, path2audio_file: str, segment_duration: float = np.inf, num_segments: int = 1, random_seed: int = None - ): - """ - Returns label of path2audio_file from classes the model was trained on. - Args: - path2audio_file (str): Path to audio wav file. - segment_duration (float): Random sample duration in seconds. - num_segments (int): Number of segments of file to use for majority vote. - random_seed (int): Seed for generating the starting position of the segment. - - Returns: - label: label corresponding to the trained model - """ - audio, sr = sf.read(path2audio_file) - target_sr = self._cfg.train_ds.get('sample_rate', 16000) - if sr != target_sr: - audio = librosa.core.resample(audio, orig_sr=sr, target_sr=target_sr) - audio_length = audio.shape[0] - - duration = target_sr * segment_duration - if duration > audio_length: - duration = audio_length - - label_id_list = [] - np.random.seed(random_seed) - starts = np.random.randint(0, audio_length - duration + 1, size=num_segments) - for start in starts: - audio = audio[start : start + duration] - - _, logits = self.infer_segment(audio) - label_id = logits.argmax(axis=1) - label_id_list.append(int(label_id[0])) - - m_label_id = Counter(label_id_list).most_common(1)[0][0] - - trained_labels = self._cfg['train_ds'].get('labels', None) - if trained_labels is not None: - trained_labels = list(trained_labels) - label = trained_labels[m_label_id] - else: - logging.info("labels are not saved to model, hence only outputting the label id index") - label = m_label_id - - return label - - def get_embedding(self, path2audio_file): - """ - Returns the speaker embeddings for a provided audio file. - - Args: - path2audio_file: path to an audio wav file - - Returns: - emb: speaker embeddings (Audio representations) - """ - - emb, _ = self.infer_file(path2audio_file=path2audio_file) - - return emb - - @torch.no_grad() - def verify_speakers(self, path2audio_file1, path2audio_file2, threshold=0.7): - """ - Verify if two audio files are from the same speaker or not. - - Args: - path2audio_file1: path to audio wav file of speaker 1 - path2audio_file2: path to audio wav file of speaker 2 - threshold: cosine similarity score used as a threshold to distinguish two embeddings (default = 0.7) - - Returns: - True if both audio files are from same speaker, False otherwise - """ - embs1 = self.get_embedding(path2audio_file1).squeeze() - embs2 = self.get_embedding(path2audio_file2).squeeze() - # Length Normalize - X = embs1 / torch.linalg.norm(embs1) - Y = embs2 / torch.linalg.norm(embs2) - # Score - similarity_score = torch.dot(X, Y) / ((torch.dot(X, X) * torch.dot(Y, Y)) ** 0.5) - similarity_score = (similarity_score + 1) / 2 - - # Decision - if similarity_score >= threshold: - logging.info(" two audio files are from same speaker") - return True - else: - logging.info(" two audio files are from different speakers") - return False - - @torch.no_grad() - def verify_speakers_batch(self, audio_files_pairs, threshold=0.7, batch_size=32, sample_rate=16000, device='cuda'): - """ - Verify if audio files from the first and second manifests are from the same speaker or not. - - Args: - audio_files_pairs: list of tuples with audio_files pairs to be verified - threshold: cosine similarity score used as a threshold to distinguish two embeddings (default = 0.7) - batch_size: batch size to perform batch inference - sample_rate: sample rate of audio files in manifest file - device: compute device to perform operations. - - Returns: - True if both audio pair is from same speaker, False otherwise - """ - - if type(audio_files_pairs) is list: - tmp_dir = tempfile.TemporaryDirectory() - manifest_filepath1 = os.path.join(tmp_dir.name, 'tmp_manifest1.json') - manifest_filepath2 = os.path.join(tmp_dir.name, 'tmp_manifest2.json') - self.path2audio_files_to_manifest([p[0] for p in audio_files_pairs], manifest_filepath1) - self.path2audio_files_to_manifest([p[1] for p in audio_files_pairs], manifest_filepath2) - else: - raise ValueError("audio_files_pairs must be of type list of tuples containing a pair of audio files") - - embs1, _, _, _ = self.batch_inference( - manifest_filepath1, batch_size=batch_size, sample_rate=sample_rate, device=device - ) - embs2, _, _, _ = self.batch_inference( - manifest_filepath2, batch_size=batch_size, sample_rate=sample_rate, device=device - ) - - embs1 = torch.Tensor(embs1).to(device) - embs2 = torch.Tensor(embs2).to(device) - # Length Normalize - embs1 = torch.div(embs1, torch.linalg.norm(embs1, dim=1).unsqueeze(dim=1)) - embs2 = torch.div(embs2, torch.linalg.norm(embs2, dim=1).unsqueeze(dim=1)) - - X = embs1.unsqueeze(dim=1) - Y = embs2.unsqueeze(dim=2) - # Score - similarity_scores = torch.matmul(X, Y).squeeze() / ( - (torch.matmul(X, X.permute(0, 2, 1)).squeeze() * torch.matmul(Y.permute(0, 2, 1), Y).squeeze()) ** 0.5 - ) - similarity_scores = (similarity_scores + 1) / 2 - - # Decision - decision = similarity_scores >= threshold - - tmp_dir.cleanup() - return decision.cpu().numpy() - - @torch.no_grad() - def batch_inference(self, manifest_filepath, batch_size=32, sample_rate=16000, device='cuda'): - """ - Perform batch inference on EncDecSpeakerLabelModel. - To perform inference on single audio file, once can use infer_model, get_label or get_embedding - - To map predicted labels, one can do - `arg_values = logits.argmax(axis=1)` - `pred_labels = list(map(lambda t : trained_labels[t], arg_values))` - - Args: - manifest_filepath: Path to manifest file - batch_size: batch size to perform batch inference - sample_rate: sample rate of audio files in manifest file - device: compute device to perform operations. - - Returns: - The variables below all follow the audio file order in the manifest file. - embs: embeddings of files provided in manifest file - logits: logits of final layer of EncDecSpeakerLabel Model - gt_labels: labels from manifest file (needed for speaker enrollment and testing) - trained_labels: Classification labels sorted in the order that they are mapped by the trained model - - """ - mode = self.training - self.freeze() - self.eval() - self.to(device) - trained_labels = self._cfg['train_ds']['labels'] - if trained_labels is not None: - trained_labels = list(trained_labels) - - dl_config = { - 'manifest_filepath': manifest_filepath, - 'sample_rate': sample_rate, - 'channel_selector': 0, - 'batch_size': batch_size, - } - self.labels = self.extract_labels(dl_config) - dl_config['labels'] = self.labels - dataloader = self.__setup_dataloader_from_config(config=dl_config) - - logits = [] - embs = [] - gt_labels = [] - - for test_batch in tqdm(dataloader): - if device == 'cuda': - test_batch = [x.to(device) for x in test_batch] - audio_signal, audio_signal_len, labels, _ = test_batch - logit, emb = self.forward(input_signal=audio_signal, input_signal_length=audio_signal_len) - - logits.extend(logit.cpu().numpy()) - gt_labels.extend(labels.cpu().numpy()) - embs.extend(emb.cpu().numpy()) - - gt_labels = list(map(lambda t: dataloader.dataset.id2label[t], gt_labels)) - - self.train(mode=mode) - if mode is True: - self.unfreeze() - - logits, embs, gt_labels = np.asarray(logits), np.asarray(embs), np.asarray(gt_labels) - - return embs, logits, gt_labels, trained_labels diff --git a/nemo/collections/asr/models/multitalker_asr_models.py b/nemo/collections/asr/models/multitalker_asr_models.py deleted file mode 100644 index 66261fa2c561cdad64f4af3acf3bd53a681bb167..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/multitalker_asr_models.py +++ /dev/null @@ -1,142 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -from typing import Any, Dict, List, Optional - -import torch -from omegaconf import DictConfig, open_dict -from pytorch_lightning import Trainer - -from nemo.collections.asr.data.audio_to_text_lhotse_speaker import LhotseSpeechToTextSpkBpeDataset -from nemo.collections.asr.models.rnnt_bpe_models import EncDecRNNTBPEModel -from nemo.collections.asr.parts.mixins import TranscribeConfig -from nemo.collections.asr.parts.mixins.multitalker_asr_mixins import SpeakerKernelMixin -from nemo.collections.common.data.lhotse import get_lhotse_dataloader_from_config -from nemo.core.classes.common import PretrainedModelInfo - - -class EncDecMultiTalkerRNNTBPEModel(EncDecRNNTBPEModel, SpeakerKernelMixin): - """Base class for encoder decoder RNNT-based models with subword tokenization.""" - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - super().__init__(cfg=cfg, trainer=trainer) - # Initialize speaker kernel functionality from mixin - self._init_speaker_kernel_config(cfg) - - @classmethod - def list_available_models(cls) -> List[PretrainedModelInfo]: - """ - This method returns a list of pre-trained model which can be instantiated directly from NVIDIA's NGC cloud. - - Returns: - List of available pre-trained models. - """ - results = [] - - return results - - def _setup_dataloader_from_config(self, config: Optional[Dict]): - if config.get("use_lhotse"): - # Use open_dict to allow dynamic key addition - with open_dict(config): - config.global_rank = self.global_rank - config.world_size = self.world_size - - return get_lhotse_dataloader_from_config( - config, - global_rank=self.global_rank, - world_size=self.world_size, - dataset=LhotseSpeechToTextSpkBpeDataset( - cfg=config, - tokenizer=self.tokenizer, - ), - ) - - def training_step(self, batch, batch_nb): - """Training step with speaker targets.""" - signal, signal_len, transcript, transcript_len, *additional_args = batch - spk_targets, bg_spk_targets = additional_args - - self.set_speaker_targets(spk_targets, bg_spk_targets) - - batch = (signal, signal_len, transcript, transcript_len) - - return super().training_step(batch, batch_nb) - - def validation_pass(self, batch, batch_idx, dataloader_idx=0): - """Validation pass with speaker targets.""" - signal, signal_len, transcript, transcript_len, *additional_args = batch - spk_targets, bg_spk_targets = additional_args - - self.set_speaker_targets(spk_targets, bg_spk_targets) - - batch = (signal, signal_len, transcript, transcript_len) - - return super().validation_pass(batch, batch_idx, dataloader_idx) - - def _transcribe_forward(self, batch: Any, trcfg: TranscribeConfig): - """Transcribe forward with speaker targets.""" - signal, signal_len, transcript, transcript_len, *additional_args = batch - spk_targets, bg_spk_targets = additional_args - - self.set_speaker_targets(spk_targets, bg_spk_targets) - - batch = (signal, signal_len, transcript, transcript_len) - - return super()._transcribe_forward(batch, trcfg) - - def _setup_transcribe_dataloader(self, config: Dict) -> 'torch.utils.data.DataLoader': - """ - Setup function for a temporary data loader which wraps the provided audio file. - - Args: - config: A python dictionary which contains the following keys: - paths2audio_files: (a list) of paths to audio files. The files should be relatively short fragments. \ - Recommended length per file is between 5 and 25 seconds. - batch_size: (int) batch size to use during inference. \ - Bigger will result in better throughput performance but would use more memory. - temp_dir: (str) A temporary directory where the audio manifest is temporarily - stored. - - Returns: - A pytorch DataLoader for the given audio file(s). - """ - if 'dataset_manifest' in config: - manifest_filepath = config['dataset_manifest'] - batch_size = config['batch_size'] - else: - manifest_filepath = os.path.join(config['temp_dir'], 'manifest.json') - batch_size = min(config['batch_size'], len(config['paths2audio_files'])) - - dl_config = { - 'manifest_filepath': manifest_filepath, - 'sample_rate': self.preprocessor._sample_rate, - 'batch_size': batch_size, - 'shuffle': False, - 'num_workers': config.get('num_workers', min(batch_size, os.cpu_count() - 1)), - 'pin_memory': True, - 'use_lhotse': config.get('use_lhotse', True), - 'use_bucketing': False, - 'channel_selector': config.get('channel_selector', None), - 'inference_mode': self.cfg.test_ds.get('inference_mode', True), - 'fixed_spk_id': config.get('fixed_spk_id', None), - } - - if config.get("augmentor"): - dl_config['augmentor'] = config.get("augmentor") - - temporary_datalayer = self._setup_dataloader_from_config(config=DictConfig(dl_config)) - - return temporary_datalayer diff --git a/nemo/collections/asr/models/online_diarizer.py b/nemo/collections/asr/models/online_diarizer.py deleted file mode 100644 index 7074b92f4c041b486419024302398280314bfacf..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/online_diarizer.py +++ /dev/null @@ -1,579 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os -import time -from copy import deepcopy -from typing import Dict - -import torch -from omegaconf import DictConfig - -from nemo.collections.asr.models import ClusteringDiarizer -from nemo.collections.asr.parts.utils.offline_clustering import get_scale_interpolated_embs, split_input_data -from nemo.collections.asr.parts.utils.online_clustering import OnlineSpeakerClustering -from nemo.collections.asr.parts.utils.speaker_utils import ( - OnlineSegmentor, - audio_rttm_map, - generate_cluster_labels, - get_embs_and_timestamps, -) -from nemo.utils import logging, model_utils - -__all__ = ['OnlineClusteringDiarizer'] - - -def timeit(method): - """ - Monitor elapsed time of the corresponding function displaying the method name. - - Args: - method: function that is being measured - - Return: - `timed` function for measuring the elapsed time - """ - - def timed(*args, **kwargs): - ts = time.time() - result = method(*args, **kwargs) - te = time.time() - if 'log_time' in kwargs: - name = kwargs.get('log_name', method.__name__.upper()) - kwargs['log_time'][name] = int((te - ts) * 1000) - else: - logging.info('%2.2fms %r' % ((te - ts) * 1000, method.__name__)) - return result - - return timed - - -class OnlineClusteringDiarizer(ClusteringDiarizer): - """ - A class that enables online (streaming) clustering based diarization. - - - The instance created from `OnlineClusteringDiarizer` sets aside a certain amount of memory - to provide the upcoming inference with history information - - - There are two major modules involved: `OnlineSegmentor` and `OnlineSpeakerClustering`. - OnlineSegmentor: Take the VAD-timestamps and generate segments for each scale - OnlineSpeakerClustering: Update the entire speaker labels of the given online session - while updating the speaker labels of the streaming inputs. - - - The overall diarization process is done by calling `diarize_step` function. - `diarize_step` function goes through the following steps: - (1) Segmentation (`OnlineSegmentor` class) - (2) Embedding extraction (`_extract_online_embeddings` function call) - (3) Online speaker counting and speaker clustering (`OnlineClusteringDiarizer` class) - (4) Label generation (`generate_cluster_labels` function call) - """ - - def __init__(self, cfg: DictConfig): - super().__init__(cfg) - self.cfg = model_utils.convert_model_config_to_dict_config(cfg) - self._cfg_diarizer = self.cfg.diarizer - self.base_scale_index = max(self.multiscale_args_dict['scale_dict'].keys()) - - self.uniq_id = self._cfg_diarizer.get('uniq_id', None) - self.decimals = self._cfg_diarizer.get('decimals', 2) - self.AUDIO_RTTM_MAP = audio_rttm_map(self.cfg.diarizer.manifest_filepath) - self.sample_rate = self.cfg.sample_rate - torch.manual_seed(0) - - self._out_dir = self._cfg_diarizer.out_dir - if not os.path.exists(self._out_dir): - os.mkdir(self._out_dir) - - if torch.cuda.is_available(): - self.cuda = True - self.device = torch.device("cuda") - else: - self.cuda = False - self.device = torch.device("cpu") - - self.reset() - - # Set speaker embedding model in eval mode - self._speaker_model.eval() - - def _init_online_clustering_module(self, clustering_params): - """ - Initialize online speaker clustering module - - Attributes: - online_clus (OnlineSpeakerClustering): - Online clustering diarizer class instance - history_n (int): - History buffer size for saving history of speaker label inference - Total number of embedding vectors saved in the buffer that is kept till the end of the session - current_n (int): - Current buffer (FIFO queue) size for calculating the speaker label inference - Total number of embedding vectors saved in the FIFO queue for clustering inference - """ - self.online_clus = OnlineSpeakerClustering( - max_num_speakers=clustering_params.max_num_speakers, - max_rp_threshold=clustering_params.max_rp_threshold, - sparse_search_volume=clustering_params.sparse_search_volume, - history_buffer_size=clustering_params.history_buffer_size, - current_buffer_size=clustering_params.current_buffer_size, - cuda=self.cuda, - ) - self.history_n = clustering_params.history_buffer_size - self.current_n = clustering_params.current_buffer_size - - self.max_num_speakers = self.online_clus.max_num_speakers - - def _init_online_segmentor_module(self, sample_rate): - """ - Initialize an online segmentor module - - Attributes: - online_segmentor (OnlineSegmentor): - online segmentation module that generates short speech segments from the VAD input - """ - self.online_segmentor = OnlineSegmentor(sample_rate) - - def _init_memory_buffer(self): - """ - Variables are kept in memory for future updates - - Attributes: - memory_margin (int): - The number of embeddings saved in the memory buffer. - This memory margin is dependent on the base scale length: margin = (buffer_length)/(base scale shift) - memory margin is automatically calculated to have minimal memory usage - memory_segment_ranges (dict): - The segment range information kept in the memory buffer - memory_segment_indexes (dict): - The segment indexes kept in the memory buffer - memory_cluster_labels (Tensor): - The cluster labels inferred in the previous diarization steps - """ - self.memory_margin = 0 - self.memory_segment_ranges = {key: [] for key in self.multiscale_args_dict['scale_dict'].keys()} - self.memory_segment_indexes = {key: [] for key in self.multiscale_args_dict['scale_dict'].keys()} - self.memory_cluster_labels = torch.tensor([]) - - def _init_temporal_major_voting_module(self, clustering_params): - """ - Variables needed for taking majority votes for speaker labels - - Attributes: - use_temporal_label_major_vote (bool): - Boolean for whether to use temporal majority voting - temporal_label_major_vote_buffer_size (int): - buffer size for majority voting - base_scale_label_dict (dict): - Dictionary containing multiple speaker labels for major voting - Speaker labels from multiple steps are saved for each segment index. - """ - self.use_temporal_label_major_vote = clustering_params.get('use_temporal_label_major_vote', False) - self.temporal_label_major_vote_buffer_size = clustering_params.get('temporal_label_major_vote_buffer_size', 1) - self.base_scale_label_dict = {} - - def _init_segment_variables(self): - """ - Initialize segment variables for each scale. - Note that we have `uniq_id` variable in case where multiple sessions are handled. - """ - self.emb_vectors = {} - self.time_stamps = {} - self.segment_range_ts = {} - self.segment_raw_audio = {} - self.segment_indexes = {} - - for scale_idx in self.multiscale_args_dict['scale_dict'].keys(): - self.multiscale_embeddings_and_timestamps[scale_idx] = [None, None] - self.emb_vectors[scale_idx] = torch.tensor([]) - self.time_stamps[scale_idx] = [] - self.segment_range_ts[scale_idx] = [] - self.segment_raw_audio[scale_idx] = [] - self.segment_indexes[scale_idx] = [] - - def _init_buffer_frame_timestamps(self): - """ - Timing variables transferred from OnlineDiarWithASR class. - Buffer is window region where input signal is kept for ASR. - Frame is window region where the actual inference ASR decoded results are updated - - Example: - buffer_len = 5.0 - frame_len = 1.0 - - |___Buffer___[___________]____________| - |____________[ Frame ]____________| - - | <- buffer_start - |____________| <- frame_start - |_____________________________________| <- buffer_end - - buffer_start = 12.0 - buffer_end = 17.0 - frame_start = 14.0 - - These timestamps and index variables are updated by OnlineDiarWithASR. - - Attributes: - frame_index (int): - Integer index of frame window - frame_start (float): - The start of the frame window - buffer_start (float): - The start of the buffer window - buffer_end (float): - The end of the buffer - """ - self.frame_index = 0 - self.frame_start = 0.0 - self.buffer_start = 0.0 - self.buffer_end = 0.0 - - def _transfer_timestamps_to_segmentor(self): - """ - Pass the timing information from streaming ASR buffers. - """ - self.online_segmentor.frame_start = self.frame_start - self.online_segmentor.buffer_start = self.buffer_start - self.online_segmentor.buffer_end = self.buffer_end - - def reset(self): - """ - Reset all the necessary variables and initialize classes. - - Attributes: - n_embed_seg_len (int): - Number of segments needed for 1 second of input time-series signal - """ - self.n_embed_seg_len = int( - self.sample_rate * self.multiscale_args_dict['scale_dict'][self.base_scale_index][0] - ) - self._init_segment_variables() - self._init_online_clustering_module(self._cfg_diarizer.clustering.parameters) - self._init_online_segmentor_module(self.cfg.sample_rate) - self._init_memory_buffer() - self._init_temporal_major_voting_module(self._cfg_diarizer.clustering.parameters) - self._init_buffer_frame_timestamps() - - def _clear_memory(self, scale_idx: int): - """ - Calculate how many segments should be removed from memory (`memory_margin`) and - save the necessary information. - `keep_range` determines how many segments and their corresponding embedding, raw audio, - timestamps in the memory of the online diarizer instance. - - Args: - scale_idx (int): - Scale index in integer type - """ - base_scale_shift = self.multiscale_args_dict['scale_dict'][self.base_scale_index][1] - self.memory_margin = int((self.buffer_end - self.buffer_start) / base_scale_shift) - - scale_buffer_size = int( - len(set(self.scale_mapping_dict[scale_idx].tolist())) - / len(set(self.scale_mapping_dict[self.base_scale_index].tolist())) - * (self.history_n + self.current_n) - ) - keep_range = scale_buffer_size + self.memory_margin - self.emb_vectors[scale_idx] = self.emb_vectors[scale_idx][-keep_range:] - self.segment_raw_audio[scale_idx] = self.segment_raw_audio[scale_idx][-keep_range:] - self.segment_range_ts[scale_idx] = self.segment_range_ts[scale_idx][-keep_range:] - self.segment_indexes[scale_idx] = self.segment_indexes[scale_idx][-keep_range:] - - @timeit - def _temporal_label_major_vote(self) -> torch.Tensor: - """ - Take a majority voting for every segment on temporal steps. This feature significantly reduces the error coming - from unstable speaker counting in the beginning of sessions. - - Returns: - maj_vote_labels (list): - List containing the major-voted speaker labels on temporal domain - """ - maj_vote_labels = [] - for seg_idx in self.memory_segment_indexes[self.base_scale_index]: - if seg_idx not in self.base_scale_label_dict: - self.base_scale_label_dict[seg_idx] = [self.memory_cluster_labels[seg_idx]] - else: - while len(self.base_scale_label_dict[seg_idx]) > self.temporal_label_major_vote_buffer_size: - self.base_scale_label_dict[seg_idx].pop(0) - self.base_scale_label_dict[seg_idx].append(self.memory_cluster_labels[seg_idx]) - - maj_vote_labels.append(torch.mode(torch.tensor(self.base_scale_label_dict[seg_idx]))[0].item()) - return maj_vote_labels - - def save_history_data(self, scale_idx: int, total_cluster_labels: torch.Tensor, is_online: bool) -> torch.Tensor: - """ - Save the temporary input to the class memory buffer. - - - Clustering is done for (hist_N + curr_N) number of embeddings. - - Thus, we need to remove the clustering results on the embedding memory. - - If self.diar.history_buffer_seg_end is not None, that indicates streaming diarization system - is starting to save embeddings to its memory. Thus, the new incoming clustering label should be separated. - - If `is_online = True`, old embeddings outside the window are removed to save GPU memory. - - Args: - scale_idx (int): - Scale index in integer - total_cluster_labels (Tensor): - The speaker labels from the beginning of the session to the current position - is_online (bool) - Boolean variable that indicates whether the system is currently in online mode or not - - Returns: - cluster_label_hyp (Tensor): - Majority voted speaker labels over multiple inferences - """ - total_cluster_labels = total_cluster_labels.tolist() - - if not is_online: - self.memory_segment_ranges[scale_idx] = deepcopy(self.segment_range_ts[scale_idx]) - self.memory_segment_indexes[scale_idx] = deepcopy(self.segment_indexes[scale_idx]) - if scale_idx == self.base_scale_index: - self.memory_cluster_labels = deepcopy(total_cluster_labels) - - # Only if there are newly obtained embeddings, update ranges and embeddings. - elif self.segment_indexes[scale_idx][-1] > self.memory_segment_indexes[scale_idx][-1]: - # Get the global index of the first segment we want to keep in the buffer - global_stt_idx = max(max(self.memory_segment_indexes[scale_idx]) - self.memory_margin, 0) - - # Convert global index global_stt_idx to buffer index buffer_stt_idx - segment_indexes_mat = torch.tensor(self.segment_indexes[scale_idx]) - buffer_stt_idx = torch.where(segment_indexes_mat == global_stt_idx)[0][0] - self.memory_segment_ranges[scale_idx][global_stt_idx:] = deepcopy( - self.segment_range_ts[scale_idx][buffer_stt_idx:] - ) - self.memory_segment_indexes[scale_idx][global_stt_idx:] = deepcopy( - self.segment_indexes[scale_idx][buffer_stt_idx:] - ) - if scale_idx == self.base_scale_index: - self.memory_cluster_labels[global_stt_idx:] = deepcopy(total_cluster_labels[global_stt_idx:]) - if len(self.memory_cluster_labels) != len(self.memory_segment_ranges[scale_idx]): - raise ValueError( - "self.memory_cluster_labels and self.memory_segment_ranges should always have the same length, " - f"but they have {len(self.memory_cluster_labels)} and {len(self.memory_segment_ranges[scale_idx])}." - ) - - # Remove unnecessary old values - self._clear_memory(scale_idx) - - if not ( - len(self.emb_vectors[scale_idx]) - == len(self.segment_raw_audio[scale_idx]) - == len(self.segment_indexes[scale_idx]) - == len(self.segment_range_ts[scale_idx]) - ): - raise ValueError( - "self.emb_vectors, self.segment_raw_audio, self.segment_indexes, and self.segment_range_ts " - "should always have the same length, " - f"but they have {len(self.emb_vectors[scale_idx])}, {len(self.segment_raw_audio[scale_idx])}, " - f"{len(self.segment_indexes[scale_idx])}, and {len(self.segment_range_ts[scale_idx])}, respectively." - ) - - if self.use_temporal_label_major_vote: - cluster_label_hyp = self._temporal_label_major_vote() - else: - cluster_label_hyp = self.memory_cluster_labels - return cluster_label_hyp - - @timeit - @torch.no_grad() - def _run_embedding_extractor(self, audio_signal: torch.Tensor) -> torch.Tensor: - """ - Call `forward` function of the speaker embedding model. - - Args: - audio_signal (Tensor): - Torch tensor containing time-series signal - - Returns: - Speaker embedding vectors for the given time-series input `audio_signal`. - """ - audio_signal = torch.stack(audio_signal).float().to(self.device) - audio_signal_lens = torch.tensor([self.n_embed_seg_len for k in range(audio_signal.shape[0])]).to(self.device) - _, torch_embs = self._speaker_model.forward(input_signal=audio_signal, input_signal_length=audio_signal_lens) - return torch_embs - - @timeit - def _extract_online_embeddings( - self, audio_signal: torch.Tensor, segment_ranges: torch.Tensor, embeddings - ) -> torch.Tensor: - """ - Incrementally extract speaker embeddings based on `audio_signal` and `segment_ranges` variables. - Unlike offline speaker diarization, speaker embedding and subsegment ranges are not saved to disk. - Measures the mismatch between `segment_ranges` and `embeddings` then extract the necessary amount of - speaker embeddings. - - Args: - audio_signal (Tensor): - Torch tensor containing time-series audio signal - embeddings (Tensor): - Previously existing Torch tensor containing speaker embedding vector - segment_ranges(Tensor): - Torch tensor containing the start and end of each segment - - Returns: - embeddings (Tensor): - Concatenated speaker embedding vectors that match segment range information in `segment_ranges`. - """ - stt_idx = 0 if embeddings is None else embeddings.shape[0] - end_idx = len(segment_ranges) - - if end_idx > stt_idx: - torch_embs = self._run_embedding_extractor(audio_signal[stt_idx:end_idx]) - if embeddings is None or embeddings.shape[0] == 0: - embeddings = torch_embs - else: - embeddings = torch.vstack((embeddings[:stt_idx, :], torch_embs)) - - elif end_idx < stt_idx: - embeddings = embeddings[: len(segment_ranges)] - - if len(segment_ranges) != embeddings.shape[0]: - raise ValueError("Segment ranges and embeddings shapes do not match.") - return embeddings - - @timeit - def _perform_online_clustering( - self, uniq_embs_and_timestamps: Dict[str, torch.Tensor], cuda=False, - ) -> torch.Tensor: - """ - Launch online clustering for `uniq_embs_and_timestamps` input variable. - - Args: - uniq_embs_and_timestamps (dict): - Dictionary containing embeddings, timestamps and multiscale weights. - If uniq_embs_and_timestamps contains only one scale, single scale diarization - is performed. - cuda (bool): - Boolean indicator for cuda usages - """ - device = torch.device("cuda") if cuda else torch.device("cpu") - - # Get base-scale (the highest index) information from uniq_embs_and_timestamps. - embeddings_in_scales, timestamps_in_scales = split_input_data( - embeddings_in_scales=uniq_embs_and_timestamps['embeddings'], - timestamps_in_scales=uniq_embs_and_timestamps['timestamps'], - multiscale_segment_counts=uniq_embs_and_timestamps['multiscale_segment_counts'], - ) - - curr_emb, self.scale_mapping_dict = get_scale_interpolated_embs( - multiscale_weights=uniq_embs_and_timestamps['multiscale_weights'], - embeddings_in_scales=embeddings_in_scales, - timestamps_in_scales=timestamps_in_scales, - device=device, - ) - - base_segment_indexes = torch.tensor(self.segment_indexes[self.base_scale_index]).to(curr_emb.device) - merged_clus_labels = self.online_clus.forward_infer( - curr_emb=curr_emb, base_segment_indexes=base_segment_indexes, frame_index=self.frame_index, cuda=cuda, - ) - # Update history data - for scale_idx, (window, shift) in self.multiscale_args_dict['scale_dict'].items(): - cluster_label_hyp = self.save_history_data(scale_idx, merged_clus_labels, self.online_clus.is_online) - - return cluster_label_hyp - - def _get_interim_output(self) -> torch.Tensor: - """ - In case buffer is not filled or there is no speech activity in the input, generate temporary output. - - Returns: - diar_hyp (Tensor): Speaker labels based on the previously saved segments and speaker labels - """ - if len(self.memory_cluster_labels) == 0 or self.buffer_start < 0: - diar_hyp, _ = generate_cluster_labels([[0.0, self.total_buffer_in_secs]], [0]) - else: - diar_hyp, _ = generate_cluster_labels( - self.memory_segment_ranges[self.base_scale_index], self.memory_cluster_labels - ) - return diar_hyp - - @timeit - def diarize_step(self, audio_buffer: torch.Tensor, vad_timestamps: torch.Tensor) -> torch.Tensor: - """ - A function for a unit diarization step. Each diarization step goes through the following steps: - - 1. Segmentation: - Using `OnlineSegmentor` class, call `run_online_segmentation` method to get the segments. - 2. Embedding Extraction: - Extract multiscale embeddings from the extracted speech segments. - 3. Online Clustering & Counting - Perform online speaker clustering by using `OnlineSpeakerClustering` class. - 4. Generate speaker labels: - Generate start and end timestamps of speaker labels based on the diarization results. - - c.f.) Also see method `diarize` in `ClusteringDiarizer` class. - - Args: - audio_buffer (Tensor): - Tensor variable containing the time series signal at the current frame - Dimensions: (Number of audio time-series samples) x 1 - vad_timestamps (Tensor): - List containing VAD timestamps. - Dimensions: (Number of segments) x 2 - Example: - >>> vad_timestamps = torch.Tensor([[0.05, 2.52], [3.12, 6.85]]) - - Returns: - diar_hyp (Tensor): - Speaker label hypothesis from the start of the session to the current position - """ - self._transfer_timestamps_to_segmentor() - - # In case buffer is not filled or there is no speech activity in the input - if self.buffer_start < 0 or len(vad_timestamps) == 0: - return self._get_interim_output() - - # Segmentation: (c.f. see `diarize` function in ClusteringDiarizer class) - for scale_idx, (window, shift) in self.multiscale_args_dict['scale_dict'].items(): - - # Step 1: Get subsegments for embedding extraction. - audio_sigs, segment_ranges, range_inds = self.online_segmentor.run_online_segmentation( - audio_buffer=audio_buffer, - vad_timestamps=vad_timestamps, - segment_raw_audio=self.segment_raw_audio[scale_idx], - segment_range_ts=self.segment_range_ts[scale_idx], - segment_indexes=self.segment_indexes[scale_idx], - window=window, - shift=shift, - ) - self.segment_raw_audio[scale_idx] = audio_sigs - self.segment_range_ts[scale_idx] = segment_ranges - self.segment_indexes[scale_idx] = range_inds - - # Step 2-1: Extract speaker embeddings from the extracted subsegment timestamps. - embeddings = self._extract_online_embeddings( - audio_signal=self.segment_raw_audio[scale_idx], - segment_ranges=self.segment_range_ts[scale_idx], - embeddings=self.emb_vectors[scale_idx], - ) - - # Step 2-2:Save the embeddings and segmentation timestamps in memory - self.emb_vectors[scale_idx] = embeddings - - self.multiscale_embeddings_and_timestamps[scale_idx] = [ - {self.uniq_id: embeddings}, - {self.uniq_id: segment_ranges}, - ] - - embs_and_timestamps = get_embs_and_timestamps( - self.multiscale_embeddings_and_timestamps, self.multiscale_args_dict - ) - - # Step 3 - Clustering: Perform an online version of clustering algorithm - cluster_label_hyp = self._perform_online_clustering(embs_and_timestamps[self.uniq_id], cuda=self.cuda,) - - # Step 4: Generate RTTM style diarization labels from segment ranges and cluster labels - diar_hyp, _ = generate_cluster_labels(self.memory_segment_ranges[self.base_scale_index], cluster_label_hyp) - return diar_hyp diff --git a/nemo/collections/asr/models/rnnt_bpe_models.py b/nemo/collections/asr/models/rnnt_bpe_models.py deleted file mode 100644 index 779f03e3719de5c84b41c73a92beb217ab92bb6d..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/rnnt_bpe_models.py +++ /dev/null @@ -1,547 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import copy -import os -from typing import Dict, List, Optional, Union - -import torch -from lightning.pytorch import Trainer -from omegaconf import DictConfig, ListConfig, OmegaConf, open_dict - -from nemo.collections.asr.data import audio_to_text_dataset -from nemo.collections.asr.data.audio_to_text import _AudioTextDataset -from nemo.collections.asr.data.audio_to_text_dali import AudioToBPEDALIDataset -from nemo.collections.asr.data.audio_to_text_lhotse import LhotseSpeechToTextBpeDataset -from nemo.collections.asr.losses.rnnt import RNNTLoss -from nemo.collections.asr.metrics.wer import WER -from nemo.collections.asr.models.rnnt_models import EncDecRNNTModel -from nemo.collections.asr.parts.mixins import ASRBPEMixin -from nemo.collections.asr.parts.submodules.rnnt_decoding import RNNTBPEDecoding, RNNTBPEDecodingConfig -from nemo.collections.asr.parts.utils.asr_batching import get_semi_sorted_batch_sampler -from nemo.collections.common.data.lhotse import get_lhotse_dataloader_from_config -from nemo.core.classes.common import PretrainedModelInfo -from nemo.utils import logging, model_utils - - -class EncDecRNNTBPEModel(EncDecRNNTModel, ASRBPEMixin): - """Base class for encoder decoder RNNT-based models with subword tokenization.""" - - @classmethod - def list_available_models(cls) -> List[PretrainedModelInfo]: - """ - This method returns a list of pre-trained model which can be instantiated directly from NVIDIA's NGC cloud. - - Returns: - List of available pre-trained models. - """ - results = [] - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_conformer_transducer_small", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_conformer_transducer_small", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_conformer_transducer_small/versions/1.6.0/files/stt_en_conformer_transducer_small.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_conformer_transducer_medium", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_conformer_transducer_medium", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_conformer_transducer_medium/versions/1.6.0/files/stt_en_conformer_transducer_medium.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_conformer_transducer_large", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_conformer_transducer_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_conformer_transducer_large/versions/1.10.0/files/stt_en_conformer_transducer_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_conformer_transducer_large_ls", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_conformer_transducer_large_ls", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_conformer_transducer_large_ls/versions/1.8.0/files/stt_en_conformer_transducer_large_ls.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_conformer_transducer_xlarge", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_conformer_transducer_xlarge", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_conformer_transducer_xlarge/versions/1.10.0/files/stt_en_conformer_transducer_xlarge.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_conformer_transducer_xxlarge", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_conformer_transducer_xxlarge", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_conformer_transducer_xxlarge/versions/1.8.0/files/stt_en_conformer_transducer_xxlarge.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_de_conformer_transducer_large", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_de_conformer_transducer_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_de_conformer_transducer_large/versions/1.5.0/files/stt_de_conformer_transducer_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_fr_conformer_transducer_large", - description="For details about this model, please visit https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/stt_fr_conformer_transducer_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_fr_conformer_transducer_large/versions/1.5/files/stt_fr_conformer_transducer_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_es_conformer_transducer_large", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_es_conformer_transducer_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_es_conformer_transducer_large/versions/1.8.0/files/stt_es_conformer_transducer_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_enes_conformer_transducer_large", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_enes_conformer_transducer_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_enes_conformer_transducer_large/versions/1.0.0/files/stt_enes_conformer_transducer_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_ca_conformer_transducer_large", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_ca_conformer_transducer_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_ca_conformer_transducer_large/versions/1.11.0/files/stt_ca_conformer_transducer_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_rw_conformer_transducer_large", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_rw_conformer_transducer_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_rw_conformer_transducer_large/versions/1.11.0/files/stt_rw_conformer_transducer_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_enes_conformer_transducer_large_codesw", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_enes_conformer_transducer_large_codesw", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_enes_conformer_transducer_large_codesw/versions/1.0.0/files/stt_enes_conformer_transducer_large_codesw.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_kab_conformer_transducer_large", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_kab_conformer_transducer_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_kab_conformer_transducer_large/versions/1.12.0/files/stt_kab_conformer_transducer_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_be_conformer_transducer_large", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_be_conformer_transducer_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_be_conformer_transducer_large/versions/1.12.0/files/stt_be_conformer_transducer_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_hr_conformer_transducer_large", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_hr_conformer_transducer_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_hr_conformer_transducer_large/versions/1.11.0/files/stt_hr_conformer_transducer_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_it_conformer_transducer_large", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_it_conformer_transducer_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_it_conformer_transducer_large/versions/1.13.0/files/stt_it_conformer_transducer_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_ru_conformer_transducer_large", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_ru_conformer_transducer_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_ru_conformer_transducer_large/versions/1.13.0/files/stt_ru_conformer_transducer_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_eo_conformer_transducer_large", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_eo_conformer_transducer_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_eo_conformer_transducer_large/versions/1.14.0/files/stt_eo_conformer_transducer_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_fastconformer_transducer_large", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_fastconformer_transducer_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_fastconformer_transducer_large/versions/1.0.0/files/stt_en_fastconformer_transducer_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_fastconformer_transducer_large_ls", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_fastconformer_transducer_large_ls", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_fastconformer_transducer_large_ls/versions/1.0.0/files/stt_en_fastconformer_transducer_large_ls.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_fastconformer_transducer_xlarge", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_fastconformer_transducer_xlarge", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_fastconformer_transducer_xlarge/versions/1.20.1/files/stt_en_fastconformer_transducer_xlarge.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_fastconformer_transducer_xxlarge", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_fastconformer_transducer_xxlarge", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_fastconformer_transducer_xxlarge/versions/1.20.1/files/stt_en_fastconformer_transducer_xxlarge.nemo", - ) - results.append(model) - - return results - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - # Convert to Hydra 1.0 compatible DictConfig - cfg = model_utils.convert_model_config_to_dict_config(cfg) - cfg = model_utils.maybe_update_config_version(cfg) - - # Tokenizer is necessary for this model - if 'tokenizer' not in cfg: - raise ValueError("`cfg` must have `tokenizer` config to create a tokenizer !") - - if not isinstance(cfg, DictConfig): - cfg = OmegaConf.create(cfg) - - # Setup the tokenizer - self._setup_tokenizer(cfg.tokenizer) - - # Initialize a dummy vocabulary - vocabulary = self.tokenizer.tokenizer.get_vocab() - - # Set the new vocabulary - with open_dict(cfg): - cfg.labels = ListConfig(list(vocabulary)) - - with open_dict(cfg.decoder): - cfg.decoder.vocab_size = len(vocabulary) - - with open_dict(cfg.joint): - cfg.joint.num_classes = len(vocabulary) - cfg.joint.vocabulary = ListConfig(list(vocabulary)) - cfg.joint.jointnet.encoder_hidden = cfg.model_defaults.enc_hidden - cfg.joint.jointnet.pred_hidden = cfg.model_defaults.pred_hidden - - super().__init__(cfg=cfg, trainer=trainer) - - self.cfg.decoding = self.set_decoding_type_according_to_loss(self.cfg.decoding) - # Setup decoding object - self.decoding = RNNTBPEDecoding( - decoding_cfg=self.cfg.decoding, - decoder=self.decoder, - joint=self.joint, - tokenizer=self.tokenizer, - ) - - # Setup wer object - self.wer = WER( - decoding=self.decoding, - batch_dim_index=0, - use_cer=self._cfg.get('use_cer', False), - log_prediction=self._cfg.get('log_prediction', True), - dist_sync_on_step=True, - ) - - # Setup fused Joint step if flag is set - if self.joint.fuse_loss_wer: - self.joint.set_loss(self.loss) - self.joint.set_wer(self.wer) - - def change_vocabulary( - self, - new_tokenizer_dir: Union[str, DictConfig], - new_tokenizer_type: str, - decoding_cfg: Optional[DictConfig] = None, - ): - """ - Changes vocabulary used during RNNT decoding process. Use this method when fine-tuning - on from pre-trained model. This method changes only decoder and leaves encoder and pre-processing - modules unchanged. For example, you would use it if you want to use pretrained encoder when fine-tuning - on data in another language, or when you'd need model to learn capitalization, punctuation - and/or special characters. - - Args: - new_tokenizer_dir: Directory path to tokenizer or a config for a new tokenizer - (if the tokenizer type is `agg`) - new_tokenizer_type: Type of tokenizer. Can be either `agg`, `bpe` or `wpe`. - decoding_cfg: A config for the decoder, which is optional. If the decoding type - needs to be changed (from say Greedy to Beam decoding etc), the config can be passed here. - - Returns: None - - """ - if isinstance(new_tokenizer_dir, DictConfig): - if new_tokenizer_type == 'agg': - new_tokenizer_cfg = new_tokenizer_dir - else: - raise ValueError( - f'New tokenizer dir should be a string unless the tokenizer is `agg`, but this tokenizer \ - type is: {new_tokenizer_type}' - ) - else: - new_tokenizer_cfg = None - - if new_tokenizer_cfg is not None: - tokenizer_cfg = new_tokenizer_cfg - else: - if not os.path.isdir(new_tokenizer_dir): - raise NotADirectoryError( - f'New tokenizer dir must be non-empty path to a directory. But I got: {new_tokenizer_dir}' - ) - - if new_tokenizer_type.lower() not in ('bpe', 'wpe'): - raise ValueError(f'New tokenizer type must be either `bpe` or `wpe`, got {new_tokenizer_type}') - - tokenizer_cfg = OmegaConf.create({'dir': new_tokenizer_dir, 'type': new_tokenizer_type}) - - # Setup the tokenizer - self._setup_tokenizer(tokenizer_cfg) - - # Initialize a dummy vocabulary - vocabulary = self.tokenizer.tokenizer.get_vocab() - - joint_config = self.joint.to_config_dict() - new_joint_config = copy.deepcopy(joint_config) - if self.tokenizer_type == "agg": - new_joint_config["vocabulary"] = ListConfig(vocabulary) - else: - new_joint_config["vocabulary"] = ListConfig(list(vocabulary.keys())) - - new_joint_config['num_classes'] = len(vocabulary) - del self.joint - self.joint = EncDecRNNTBPEModel.from_config_dict(new_joint_config) - - decoder_config = self.decoder.to_config_dict() - new_decoder_config = copy.deepcopy(decoder_config) - new_decoder_config.vocab_size = len(vocabulary) - del self.decoder - self.decoder = EncDecRNNTBPEModel.from_config_dict(new_decoder_config) - - del self.loss - self.loss = RNNTLoss(num_classes=self.joint.num_classes_with_blank - 1) - - if decoding_cfg is None: - # Assume same decoding config as before - decoding_cfg = self.cfg.decoding - - # Assert the decoding config with all hyper parameters - decoding_cls = OmegaConf.structured(RNNTBPEDecodingConfig) - decoding_cls = OmegaConf.create(OmegaConf.to_container(decoding_cls)) - decoding_cfg = OmegaConf.merge(decoding_cls, decoding_cfg) - decoding_cfg = self.set_decoding_type_according_to_loss(decoding_cfg) - - self.decoding = RNNTBPEDecoding( - decoding_cfg=decoding_cfg, - decoder=self.decoder, - joint=self.joint, - tokenizer=self.tokenizer, - ) - - self.wer = WER( - decoding=self.decoding, - batch_dim_index=self.wer.batch_dim_index, - use_cer=self.wer.use_cer, - log_prediction=self.wer.log_prediction, - dist_sync_on_step=True, - ) - - # Setup fused Joint step - if self.joint.fuse_loss_wer or ( - self.decoding.joint_fused_batch_size is not None and self.decoding.joint_fused_batch_size > 0 - ): - self.joint.set_loss(self.loss) - self.joint.set_wer(self.wer) - - # Update config - with open_dict(self.cfg.joint): - self.cfg.joint = new_joint_config - - with open_dict(self.cfg.decoder): - self.cfg.decoder = new_decoder_config - - with open_dict(self.cfg.decoding): - self.cfg.decoding = decoding_cfg - - logging.info(f"Changed decoder to output to {self.joint.vocabulary} vocabulary.") - - def change_decoding_strategy(self, decoding_cfg: DictConfig, verbose: bool = True): - """ - Changes decoding strategy used during RNNT decoding process. - - Args: - decoding_cfg: A config for the decoder, which is optional. If the decoding type - needs to be changed (from say Greedy to Beam decoding etc), the config can be passed here. - verbose: A flag to enable/disable logging. - """ - if decoding_cfg is None: - # Assume same decoding config as before - logging.info("No `decoding_cfg` passed when changing decoding strategy, using internal config") - decoding_cfg = self.cfg.decoding - - # Assert the decoding config with all hyper parameters - decoding_cls = OmegaConf.structured(RNNTBPEDecodingConfig) - decoding_cls = OmegaConf.create(OmegaConf.to_container(decoding_cls)) - decoding_cfg = OmegaConf.merge(decoding_cls, decoding_cfg) - decoding_cfg = self.set_decoding_type_according_to_loss(decoding_cfg) - - self.decoding = RNNTBPEDecoding( - decoding_cfg=decoding_cfg, - decoder=self.decoder, - joint=self.joint, - tokenizer=self.tokenizer, - ) - - self.wer = WER( - decoding=self.decoding, - batch_dim_index=self.wer.batch_dim_index, - use_cer=self.wer.use_cer, - log_prediction=self.wer.log_prediction, - dist_sync_on_step=True, - ) - - # Setup fused Joint step - if self.joint.fuse_loss_wer or ( - self.decoding.joint_fused_batch_size is not None and self.decoding.joint_fused_batch_size > 0 - ): - self.joint.set_loss(self.loss) - self.joint.set_wer(self.wer) - - self.joint.temperature = decoding_cfg.get('temperature', 1.0) - - # Update config - with open_dict(self.cfg.decoding): - self.cfg.decoding = decoding_cfg - - if verbose: - logging.info(f"Changed decoding strategy to \n{OmegaConf.to_yaml(self.cfg.decoding)}") - - def _setup_dataloader_from_config(self, config: Optional[Dict]): - if config.get("use_lhotse"): - return get_lhotse_dataloader_from_config( - config, - # During transcription, the model is initially loaded on the CPU. - # To ensure the correct global_rank and world_size are set, - # these values must be passed from the configuration. - global_rank=self.global_rank if not config.get("do_transcribe", False) else config.get("global_rank"), - world_size=self.world_size if not config.get("do_transcribe", False) else config.get("world_size"), - dataset=LhotseSpeechToTextBpeDataset( - tokenizer=self.tokenizer, - return_cuts=config.get("do_transcribe", False), - ), - tokenizer=self.tokenizer, - ) - - dataset = audio_to_text_dataset.get_audio_to_text_bpe_dataset_from_config( - config=config, - local_rank=self.local_rank, - global_rank=self.global_rank, - world_size=self.world_size, - tokenizer=self.tokenizer, - preprocessor_cfg=self.cfg.get("preprocessor", None), - ) - - if dataset is None: - return None - - if isinstance(dataset, AudioToBPEDALIDataset): - # DALI Dataset implements dataloader interface - return dataset - - shuffle = config['shuffle'] - if isinstance(dataset, torch.utils.data.IterableDataset): - shuffle = False - - if hasattr(dataset, 'collate_fn'): - collate_fn = dataset.collate_fn - elif hasattr(dataset.datasets[0], 'collate_fn'): - # support datasets that are lists of entries - collate_fn = dataset.datasets[0].collate_fn - else: - # support datasets that are lists of lists - collate_fn = dataset.datasets[0].datasets[0].collate_fn - - batch_sampler = None - if config.get('use_semi_sorted_batching', False): - if not isinstance(dataset, _AudioTextDataset): - raise RuntimeError( - "Semi Sorted Batch sampler can be used with AudioToCharDataset or AudioToBPEDataset " - f"but found dataset of type {type(dataset)}" - ) - # set batch_size and batch_sampler to None to disable automatic batching - batch_sampler = get_semi_sorted_batch_sampler(self, dataset, config) - config['batch_size'] = None - config['drop_last'] = False - shuffle = False - - return torch.utils.data.DataLoader( - dataset=dataset, - batch_size=config['batch_size'], - sampler=batch_sampler, - batch_sampler=None, - collate_fn=collate_fn, - drop_last=config.get('drop_last', False), - shuffle=shuffle, - num_workers=config.get('num_workers', 0), - pin_memory=config.get('pin_memory', False), - ) - - def _setup_transcribe_dataloader(self, config: Dict) -> 'torch.utils.data.DataLoader': - """ - Setup function for a temporary data loader which wraps the provided audio file. - - Args: - config: A python dictionary which contains the following keys: - paths2audio_files: (a list) of paths to audio files. The files should be relatively short fragments. \ - Recommended length per file is between 5 and 25 seconds. - batch_size: (int) batch size to use during inference. \ - Bigger will result in better throughput performance but would use more memory. - temp_dir: (str) A temporary directory where the audio manifest is temporarily - stored. - - Returns: - A pytorch DataLoader for the given audio file(s). - """ - if 'manifest_filepath' in config: - manifest_filepath = config['manifest_filepath'] - batch_size = config['batch_size'] - else: - manifest_filepath = os.path.join(config['temp_dir'], 'manifest.json') - batch_size = min(config['batch_size'], len(config['paths2audio_files'])) - - dl_config = { - 'use_lhotse': config.get('use_lhotse', True), - 'manifest_filepath': manifest_filepath, - 'sample_rate': self.preprocessor._sample_rate, - 'batch_size': batch_size, - 'shuffle': False, - 'num_workers': config.get('num_workers', min(batch_size, os.cpu_count() - 1)), - 'pin_memory': True, - 'channel_selector': config.get('channel_selector', None), - 'use_start_end_token': self.cfg.validation_ds.get('use_start_end_token', False), - } - - if config.get("augmentor"): - dl_config['augmentor'] = config.get("augmentor") - - temporary_datalayer = self._setup_dataloader_from_config(config=DictConfig(dl_config)) - return temporary_datalayer diff --git a/nemo/collections/asr/models/rnnt_models.py b/nemo/collections/asr/models/rnnt_models.py deleted file mode 100644 index ef116cf2d6b5408fb92bd36faf3f80f2b953010f..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/rnnt_models.py +++ /dev/null @@ -1,1136 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import copy -import os -from math import ceil -from typing import Any, Dict, List, Optional, Union - -import numpy as np -import torch -from lightning.pytorch import Trainer -from omegaconf import DictConfig, OmegaConf, open_dict -from torch.utils.data import DataLoader - -from nemo.collections.asr.data import audio_to_text_dataset -from nemo.collections.asr.data.audio_to_text import _AudioTextDataset -from nemo.collections.asr.data.audio_to_text_dali import AudioToCharDALIDataset, DALIOutputs -from nemo.collections.asr.data.audio_to_text_lhotse import LhotseSpeechToTextBpeDataset -from nemo.collections.asr.losses.rnnt import RNNTLoss, resolve_rnnt_default_loss_name -from nemo.collections.asr.metrics.wer import WER -from nemo.collections.asr.models.asr_model import ASRModel, ExportableEncDecModel -from nemo.collections.asr.modules.rnnt import RNNTDecoderJoint -from nemo.collections.asr.parts.mixins import ( - ASRModuleMixin, - ASRTranscriptionMixin, - TranscribeConfig, - TranscriptionReturnType, -) -from nemo.collections.asr.parts.preprocessing.segment import ChannelSelectorType -from nemo.collections.asr.parts.submodules.rnnt_decoding import RNNTDecoding, RNNTDecodingConfig -from nemo.collections.asr.parts.utils.asr_batching import get_semi_sorted_batch_sampler -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis -from nemo.collections.asr.parts.utils.timestamp_utils import process_timestamp_outputs -from nemo.collections.common.data.lhotse import get_lhotse_dataloader_from_config -from nemo.collections.common.parts.preprocessing.parsers import make_parser -from nemo.core.classes.common import PretrainedModelInfo, typecheck -from nemo.core.classes.mixins import AccessMixin -from nemo.core.neural_types import AcousticEncodedRepresentation, AudioSignal, LengthsType, NeuralType, SpectrogramType -from nemo.utils import logging - - -class EncDecRNNTModel(ASRModel, ASRModuleMixin, ExportableEncDecModel, ASRTranscriptionMixin): - """Base class for encoder decoder RNNT-based models.""" - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - # Get global rank and total number of GPU workers for IterableDataset partitioning, if applicable - # Global_rank and local_rank is set by LightningModule in Lightning 1.2.0 - self.world_size = 1 - if trainer is not None: - self.world_size = trainer.world_size - - super().__init__(cfg=cfg, trainer=trainer) - - # Initialize components - self.preprocessor = EncDecRNNTModel.from_config_dict(self.cfg.preprocessor) - self.encoder = EncDecRNNTModel.from_config_dict(self.cfg.encoder) - - # Update config values required by components dynamically - with open_dict(self.cfg.decoder): - self.cfg.decoder.vocab_size = len(self.cfg.labels) - - with open_dict(self.cfg.joint): - self.cfg.joint.num_classes = len(self.cfg.labels) - self.cfg.joint.vocabulary = self.cfg.labels - self.cfg.joint.jointnet.encoder_hidden = self.cfg.model_defaults.enc_hidden - self.cfg.joint.jointnet.pred_hidden = self.cfg.model_defaults.pred_hidden - - self.decoder = EncDecRNNTModel.from_config_dict(self.cfg.decoder) - self.joint = EncDecRNNTModel.from_config_dict(self.cfg.joint) - - # Setup RNNT Loss - loss_name, loss_kwargs = self.extract_rnnt_loss_cfg(self.cfg.get("loss", None)) - - num_classes = self.joint.num_classes_with_blank - 1 # for standard RNNT and multi-blank - - if loss_name == 'tdt': - num_classes = num_classes - self.joint.num_extra_outputs - - self.loss = RNNTLoss( - num_classes=num_classes, - loss_name=loss_name, - loss_kwargs=loss_kwargs, - reduction=self.cfg.get("rnnt_reduction", "mean_batch"), - ) - - if hasattr(self.cfg, 'spec_augment') and self._cfg.spec_augment is not None: - self.spec_augmentation = EncDecRNNTModel.from_config_dict(self.cfg.spec_augment) - else: - self.spec_augmentation = None - - self.cfg.decoding = self.set_decoding_type_according_to_loss(self.cfg.decoding) - # Setup decoding objects - self.decoding = RNNTDecoding( - decoding_cfg=self.cfg.decoding, - decoder=self.decoder, - joint=self.joint, - vocabulary=self.joint.vocabulary, - ) - # Setup WER calculation - self.wer = WER( - decoding=self.decoding, - batch_dim_index=0, - use_cer=self._cfg.get('use_cer', False), - log_prediction=self._cfg.get('log_prediction', True), - dist_sync_on_step=True, - ) - - # Whether to compute loss during evaluation - if 'compute_eval_loss' in self.cfg: - self.compute_eval_loss = self.cfg.compute_eval_loss - else: - self.compute_eval_loss = True - - # Setup fused Joint step if flag is set - if self.joint.fuse_loss_wer or ( - self.decoding.joint_fused_batch_size is not None and self.decoding.joint_fused_batch_size > 0 - ): - self.joint.set_loss(self.loss) - self.joint.set_wer(self.wer) - - # Setup optimization normalization (if provided in config) - self.setup_optim_normalization() - - # Setup optional Optimization flags - self.setup_optimization_flags() - - # Setup encoder adapters (from ASRAdapterModelMixin) - self.setup_adapters() - - def setup_optim_normalization(self): - """ - Helper method to setup normalization of certain parts of the model prior to the optimization step. - - Supported pre-optimization normalizations are as follows: - - .. code-block:: yaml - - # Variation Noise injection - model: - variational_noise: - std: 0.0 - start_step: 0 - - # Joint - Length normalization - model: - normalize_joint_txu: false - - # Encoder Network - gradient normalization - model: - normalize_encoder_norm: false - - # Decoder / Prediction Network - gradient normalization - model: - normalize_decoder_norm: false - - # Joint - gradient normalization - model: - normalize_joint_norm: false - """ - # setting up the variational noise for the decoder - if hasattr(self.cfg, 'variational_noise'): - self._optim_variational_noise_std = self.cfg['variational_noise'].get('std', 0) - self._optim_variational_noise_start = self.cfg['variational_noise'].get('start_step', 0) - else: - self._optim_variational_noise_std = 0 - self._optim_variational_noise_start = 0 - - # Setup normalized gradients for model joint by T x U scaling factor (joint length normalization) - self._optim_normalize_joint_txu = self.cfg.get('normalize_joint_txu', False) - self._optim_normalize_txu = None - - # Setup normalized encoder norm for model - self._optim_normalize_encoder_norm = self.cfg.get('normalize_encoder_norm', False) - - # Setup normalized decoder norm for model - self._optim_normalize_decoder_norm = self.cfg.get('normalize_decoder_norm', False) - - # Setup normalized joint norm for model - self._optim_normalize_joint_norm = self.cfg.get('normalize_joint_norm', False) - - def extract_rnnt_loss_cfg(self, cfg: Optional[DictConfig]): - """ - Helper method to extract the rnnt loss name, and potentially its kwargs - to be passed. - - Args: - cfg: Should contain `loss_name` as a string which is resolved to a RNNT loss name. - If the default should be used, then `default` can be used. - Optionally, one can pass additional kwargs to the loss function. The subdict - should have a keyname as follows : `{loss_name}_kwargs`. - - Note that whichever loss_name is selected, that corresponding kwargs will be - selected. For the "default" case, the "{resolved_default}_kwargs" will be used. - - Examples: - .. code-block:: yaml - - loss_name: "default" - warprnnt_numba_kwargs: - kwargs2: some_other_val - - Returns: - A tuple, the resolved loss name as well as its kwargs (if found). - """ - if cfg is None: - cfg = DictConfig({}) - - loss_name = cfg.get("loss_name", "default") - - if loss_name == "default": - loss_name = resolve_rnnt_default_loss_name() - - loss_kwargs = cfg.get(f"{loss_name}_kwargs", None) - - logging.info(f"Using RNNT Loss : {loss_name}\n" f"Loss {loss_name}_kwargs: {loss_kwargs}") - - return loss_name, loss_kwargs - - def set_decoding_type_according_to_loss(self, decoding_cfg): - loss_name, loss_kwargs = self.extract_rnnt_loss_cfg(self.cfg.get("loss", None)) - - if loss_name == 'tdt': - decoding_cfg.durations = loss_kwargs.durations - elif loss_name == 'multiblank_rnnt': - decoding_cfg.big_blank_durations = loss_kwargs.big_blank_durations - - return decoding_cfg - - @torch.no_grad() - def transcribe( - self, - audio: Union[str, List[str], np.ndarray, DataLoader], - use_lhotse: bool = True, - batch_size: int = 4, - return_hypotheses: bool = False, - partial_hypothesis: Optional[List['Hypothesis']] = None, - num_workers: int = 0, - channel_selector: Optional[ChannelSelectorType] = None, - augmentor: DictConfig = None, - verbose: bool = True, - timestamps: Optional[bool] = None, - override_config: Optional[TranscribeConfig] = None, - ) -> TranscriptionReturnType: - """ - Uses greedy decoding to transcribe audio files. Use this method for debugging and prototyping. - - Args: - audio: (a single or list) of paths to audio files or a np.ndarray/tensor audio array or path - to a manifest file. - Can also be a dataloader object that provides values that can be consumed by the model. - Recommended length per file is between 5 and 25 seconds. \ - But it is possible to pass a few hours long file if enough GPU memory is available. - use_lhotse: (bool) If audio is not a dataloder, defines whether to create a lhotse dataloader or a - non-lhotse dataloader. - batch_size: (int) batch size to use during inference. \ - Bigger will result in better throughput performance but would use more memory. - return_hypotheses: (bool) Either return hypotheses or text - With hypotheses can do some postprocessing like getting timestamp or rescoring - partial_hypothesis: Optional[List['Hypothesis']] - A list of partial hypotheses to be used during rnnt - decoding. This is useful for streaming rnnt decoding. If this is not None, then the length of this - list should be equal to the length of the audio list. - num_workers: (int) number of workers for DataLoader - 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. - augmentor: (DictConfig): Augment audio samples during transcription if augmentor is applied. - verbose: (bool) whether to display tqdm progress bar - timestamps: Optional(Bool): timestamps will be returned if set to True as part of hypothesis object - (output.timestep['segment']/output.timestep['word']). Refer to `Hypothesis` class for more details. - Default is None and would retain the previous state set by using self.change_decoding_strategy(). - override_config: (Optional[TranscribeConfig]) override transcription config pre-defined by the user. - **Note**: All other arguments in the function will be ignored if override_config is passed. - You should call this argument as `model.transcribe(audio, override_config=TranscribeConfig(...))`. - - Returns: - Returns a tuple of 2 items - - * A list of greedy transcript texts / Hypothesis - * An optional list of beam search transcript texts / Hypothesis / NBestHypothesis. - """ - - timestamps = timestamps or (override_config.timestamps if override_config is not None else None) - if timestamps is not None: - need_change_decoding = False - if timestamps or (override_config is not None and override_config.timestamps): - logging.info( - "Timestamps requested, setting decoding timestamps to True. Capture them in Hypothesis object, \ - with output[0][idx].timestep['word'/'segment'/'char']" - ) - return_hypotheses = True - if self.cfg.decoding.get("compute_timestamps", None) is not True: - # compute_timestamps None, False or non-existent -> change to True - need_change_decoding = True - with open_dict(self.cfg.decoding): - self.cfg.decoding.compute_timestamps = True - else: - return_hypotheses = False - if self.cfg.decoding.get("compute_timestamps", None) is not False: - # compute_timestamps None, True or non-existent -> change to False - need_change_decoding = True - with open_dict(self.cfg.decoding): - self.cfg.decoding.compute_timestamps = False - - if need_change_decoding: - self.change_decoding_strategy(self.cfg.decoding, verbose=False) - - return super().transcribe( - audio=audio, - use_lhotse=use_lhotse, - batch_size=batch_size, - return_hypotheses=return_hypotheses, - num_workers=num_workers, - channel_selector=channel_selector, - augmentor=augmentor, - verbose=verbose, - timestamps=timestamps, - override_config=override_config, - # Additional arguments - partial_hypothesis=partial_hypothesis, - ) - - def change_vocabulary(self, new_vocabulary: List[str], decoding_cfg: Optional[DictConfig] = None): - """ - Changes vocabulary used during RNNT decoding process. Use this method when fine-tuning a - pre-trained model. This method changes only decoder and leaves encoder and pre-processing - modules unchanged. For example, you would use it if you want to use pretrained encoder when - fine-tuning on data in another language, or when you'd need model to learn capitalization, - punctuation and/or special characters. - - Args: - new_vocabulary: list with new vocabulary. Must contain at least 2 elements. Typically, \ - this is target alphabet. - decoding_cfg: A config for the decoder, which is optional. If the decoding type - needs to be changed (from say Greedy to Beam decoding etc), the config can be passed here. - - Returns: None - - """ - if self.joint.vocabulary == new_vocabulary: - logging.warning(f"Old {self.joint.vocabulary} and new {new_vocabulary} match. Not changing anything.") - else: - if new_vocabulary is None or len(new_vocabulary) == 0: - raise ValueError(f'New vocabulary must be non-empty list of chars. But I got: {new_vocabulary}') - - joint_config = self.joint.to_config_dict() - new_joint_config = copy.deepcopy(joint_config) - new_joint_config['vocabulary'] = new_vocabulary - new_joint_config['num_classes'] = len(new_vocabulary) - del self.joint - self.joint = EncDecRNNTModel.from_config_dict(new_joint_config) - - decoder_config = self.decoder.to_config_dict() - new_decoder_config = copy.deepcopy(decoder_config) - new_decoder_config.vocab_size = len(new_vocabulary) - del self.decoder - self.decoder = EncDecRNNTModel.from_config_dict(new_decoder_config) - - del self.loss - loss_name, loss_kwargs = self.extract_rnnt_loss_cfg(self.cfg.get('loss', None)) - self.loss = RNNTLoss( - num_classes=self.joint.num_classes_with_blank - 1, loss_name=loss_name, loss_kwargs=loss_kwargs - ) - - if decoding_cfg is None: - # Assume same decoding config as before - decoding_cfg = self.cfg.decoding - - # Assert the decoding config with all hyper parameters - decoding_cls = OmegaConf.structured(RNNTDecodingConfig) - decoding_cls = OmegaConf.create(OmegaConf.to_container(decoding_cls)) - decoding_cfg = OmegaConf.merge(decoding_cls, decoding_cfg) - decoding_cfg = self.set_decoding_type_according_to_loss(decoding_cfg) - - self.decoding = RNNTDecoding( - decoding_cfg=decoding_cfg, - decoder=self.decoder, - joint=self.joint, - vocabulary=self.joint.vocabulary, - ) - - self.wer = WER( - decoding=self.decoding, - batch_dim_index=self.wer.batch_dim_index, - use_cer=self.wer.use_cer, - log_prediction=self.wer.log_prediction, - dist_sync_on_step=True, - ) - - # Setup fused Joint step - if self.joint.fuse_loss_wer or ( - self.decoding.joint_fused_batch_size is not None and self.decoding.joint_fused_batch_size > 0 - ): - self.joint.set_loss(self.loss) - self.joint.set_wer(self.wer) - - # Update config - with open_dict(self.cfg.joint): - self.cfg.joint = new_joint_config - - with open_dict(self.cfg.decoder): - self.cfg.decoder = new_decoder_config - - with open_dict(self.cfg.decoding): - self.cfg.decoding = decoding_cfg - - ds_keys = ['train_ds', 'validation_ds', 'test_ds'] - for key in ds_keys: - if key in self.cfg: - with open_dict(self.cfg[key]): - self.cfg[key]['labels'] = OmegaConf.create(new_vocabulary) - - logging.info(f"Changed decoder to output to {self.joint.vocabulary} vocabulary.") - - def change_decoding_strategy(self, decoding_cfg: DictConfig, verbose=True): - """ - Changes decoding strategy used during RNNT decoding process. - - Args: - decoding_cfg: A config for the decoder, which is optional. If the decoding type - needs to be changed (from say Greedy to Beam decoding etc), the config can be passed here. - verbose: (bool) whether to display logging information - """ - if decoding_cfg is None: - # Assume same decoding config as before - logging.info("No `decoding_cfg` passed when changing decoding strategy, using internal config") - decoding_cfg = self.cfg.decoding - - # Assert the decoding config with all hyper parameters - decoding_cls = OmegaConf.structured(RNNTDecodingConfig) - decoding_cls = OmegaConf.create(OmegaConf.to_container(decoding_cls)) - decoding_cfg = OmegaConf.merge(decoding_cls, decoding_cfg) - decoding_cfg = self.set_decoding_type_according_to_loss(decoding_cfg) - - self.decoding = RNNTDecoding( - decoding_cfg=decoding_cfg, - decoder=self.decoder, - joint=self.joint, - vocabulary=self.joint.vocabulary, - ) - - self.wer = WER( - decoding=self.decoding, - batch_dim_index=self.wer.batch_dim_index, - use_cer=self.wer.use_cer, - log_prediction=self.wer.log_prediction, - dist_sync_on_step=True, - ) - - # Setup fused Joint step - if self.joint.fuse_loss_wer or ( - self.decoding.joint_fused_batch_size is not None and self.decoding.joint_fused_batch_size > 0 - ): - self.joint.set_loss(self.loss) - self.joint.set_wer(self.wer) - - self.joint.temperature = decoding_cfg.get('temperature', 1.0) - - # Update config - with open_dict(self.cfg.decoding): - self.cfg.decoding = decoding_cfg - - if verbose: - logging.info(f"Changed decoding strategy to \n{OmegaConf.to_yaml(self.cfg.decoding)}") - - def _setup_dataloader_from_config(self, config: Optional[Dict]): - # Automatically inject args from model config to dataloader config - audio_to_text_dataset.inject_dataloader_value_from_model_config(self.cfg, config, key='sample_rate') - audio_to_text_dataset.inject_dataloader_value_from_model_config(self.cfg, config, key='labels') - - if config.get("use_lhotse"): - return get_lhotse_dataloader_from_config( - config, - # During transcription, the model is initially loaded on the CPU. - # To ensure the correct global_rank and world_size are set, - # these values must be passed from the configuration. - global_rank=self.global_rank if not config.get("do_transcribe", False) else config.get("global_rank"), - world_size=self.world_size if not config.get("do_transcribe", False) else config.get("world_size"), - dataset=LhotseSpeechToTextBpeDataset( - tokenizer=make_parser( - labels=config.get('labels', None), - name=config.get('parser', 'en'), - unk_id=config.get('unk_index', -1), - blank_id=config.get('blank_index', -1), - do_normalize=config.get('normalize_transcripts', False), - ), - return_cuts=config.get("do_transcribe", False), - ), - ) - - dataset = audio_to_text_dataset.get_audio_to_text_char_dataset_from_config( - config=config, - local_rank=self.local_rank, - global_rank=self.global_rank, - world_size=self.world_size, - preprocessor_cfg=self._cfg.get("preprocessor", None), - ) - - if dataset is None: - return None - - if isinstance(dataset, AudioToCharDALIDataset): - # DALI Dataset implements dataloader interface - return dataset - - shuffle = config['shuffle'] - if isinstance(dataset, torch.utils.data.IterableDataset): - shuffle = False - - if hasattr(dataset, 'collate_fn'): - collate_fn = dataset.collate_fn - elif hasattr(dataset.datasets[0], 'collate_fn'): - # support datasets that are lists of entries - collate_fn = dataset.datasets[0].collate_fn - else: - # support datasets that are lists of lists - collate_fn = dataset.datasets[0].datasets[0].collate_fn - - batch_sampler = None - if config.get('use_semi_sorted_batching', False): - if not isinstance(dataset, _AudioTextDataset): - raise RuntimeError( - "Semi Sorted Batch sampler can be used with AudioToCharDataset or AudioToBPEDataset " - f"but found dataset of type {type(dataset)}" - ) - # set batch_size and batch_sampler to None to disable automatic batching - batch_sampler = get_semi_sorted_batch_sampler(self, dataset, config) - config['batch_size'] = None - config['drop_last'] = False - shuffle = False - - return torch.utils.data.DataLoader( - dataset=dataset, - batch_size=config['batch_size'], - sampler=batch_sampler, - batch_sampler=None, - collate_fn=collate_fn, - drop_last=config.get('drop_last', False), - shuffle=shuffle, - num_workers=config.get('num_workers', 0), - pin_memory=config.get('pin_memory', False), - ) - - def setup_training_data(self, train_data_config: Optional[Union[DictConfig, Dict]]): - """ - Sets up the training data loader via a Dict-like object. - - Args: - train_data_config: A config that contains the information regarding construction - of an ASR Training dataset. - - Supported Datasets: - - :class:`~nemo.collections.asr.data.audio_to_text.AudioToCharDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.AudioToBPEDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.TarredAudioToCharDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.TarredAudioToBPEDataset` - - :class:`~nemo.collections.asr.data.audio_to_text_dali.AudioToCharDALIDataset` - """ - if 'shuffle' not in train_data_config: - train_data_config['shuffle'] = True - - # preserve config - self._update_dataset_config(dataset_name='train', config=train_data_config) - - self._train_dl = self._setup_dataloader_from_config(config=train_data_config) - - # Need to set this because if using an IterableDataset, the length of the dataloader is the total number - # of samples rather than the number of batches, and this messes up the tqdm progress bar. - # So we set the number of steps manually (to the correct number) to fix this. - - if ( - self._train_dl is not None - and hasattr(self._train_dl, 'dataset') - and isinstance(self._train_dl.dataset, torch.utils.data.IterableDataset) - ): - # We also need to check if limit_train_batches is already set. - # If it's an int, we assume that the user has set it to something sane, i.e. <= # training batches, - # and don't change it. Otherwise, adjust batches accordingly if it's a float (including 1.0). - if self._trainer is not None and isinstance(self._trainer.limit_train_batches, float): - self._trainer.limit_train_batches = int( - self._trainer.limit_train_batches - * ceil((len(self._train_dl.dataset) / self.world_size) / train_data_config['batch_size']) - ) - elif self._trainer is None: - logging.warning( - "Model Trainer was not set before constructing the dataset, incorrect number of " - "training batches will be used. Please set the trainer and rebuild the dataset." - ) - - def setup_validation_data(self, val_data_config: Optional[Union[DictConfig, Dict]]): - """ - Sets up the validation data loader via a Dict-like object. - - Args: - val_data_config: A config that contains the information regarding construction - of an ASR Training dataset. - - Supported Datasets: - - :class:`~nemo.collections.asr.data.audio_to_text.AudioToCharDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.AudioToBPEDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.TarredAudioToCharDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.TarredAudioToBPEDataset` - - :class:`~nemo.collections.asr.data.audio_to_text_dali.AudioToCharDALIDataset` - """ - if 'shuffle' not in val_data_config: - val_data_config['shuffle'] = False - - # preserve config - self._update_dataset_config(dataset_name='validation', config=val_data_config) - - self._validation_dl = self._setup_dataloader_from_config(config=val_data_config) - - def setup_test_data(self, test_data_config: Optional[Union[DictConfig, Dict]]): - """ - Sets up the test data loader via a Dict-like object. - - Args: - test_data_config: A config that contains the information regarding construction - of an ASR Training dataset. - - Supported Datasets: - - :class:`~nemo.collections.asr.data.audio_to_text.AudioToCharDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.AudioToBPEDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.TarredAudioToCharDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.TarredAudioToBPEDataset` - - :class:`~nemo.collections.asr.data.audio_to_text_dali.AudioToCharDALIDataset` - """ - if 'shuffle' not in test_data_config: - test_data_config['shuffle'] = False - - # preserve config - self._update_dataset_config(dataset_name='test', config=test_data_config) - - self._test_dl = self._setup_dataloader_from_config(config=test_data_config) - - @property - def input_types(self) -> Optional[Dict[str, NeuralType]]: - if hasattr(self.preprocessor, '_sample_rate'): - input_signal_eltype = AudioSignal(freq=self.preprocessor._sample_rate) - else: - input_signal_eltype = AudioSignal() - - return { - "input_signal": NeuralType(('B', 'T'), input_signal_eltype, optional=True), - "input_signal_length": NeuralType(tuple('B'), LengthsType(), optional=True), - "processed_signal": NeuralType(('B', 'D', 'T'), SpectrogramType(), optional=True), - "processed_signal_length": NeuralType(tuple('B'), LengthsType(), optional=True), - } - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - return { - "outputs": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), - "encoded_lengths": NeuralType(tuple('B'), LengthsType()), - } - - @typecheck() - def forward( - self, input_signal=None, input_signal_length=None, processed_signal=None, processed_signal_length=None - ): - """ - Forward pass of the model. Note that for RNNT Models, the forward pass of the model is a 3 step process, - and this method only performs the first step - forward of the acoustic model. - - Please refer to the `training_step` in order to see the full `forward` step for training - which - performs the forward of the acoustic model, the prediction network and then the joint network. - Finally, it computes the loss and possibly compute the detokenized text via the `decoding` step. - - Please refer to the `validation_step` in order to see the full `forward` step for inference - which - performs the forward of the acoustic model, the prediction network and then the joint network. - Finally, it computes the decoded tokens via the `decoding` step and possibly compute the batch metrics. - - Args: - input_signal: Tensor that represents a batch of raw audio signals, - of shape [B, T]. T here represents timesteps, with 1 second of audio represented as - `self.sample_rate` number of floating point values. - input_signal_length: Vector of length B, that contains the individual lengths of the audio - sequences. - processed_signal: Tensor that represents a batch of processed audio signals, - of shape (B, D, T) that has undergone processing via some DALI preprocessor. - processed_signal_length: Vector of length B, that contains the individual lengths of the - processed audio sequences. - - Returns: - A tuple of 2 elements - - 1) The log probabilities tensor of shape [B, T, D]. - 2) The lengths of the acoustic sequence after propagation through the encoder, of shape [B]. - """ - has_input_signal = input_signal is not None and input_signal_length is not None - has_processed_signal = processed_signal is not None and processed_signal_length is not None - if (has_input_signal ^ has_processed_signal) is False: - raise ValueError( - f"{self} Arguments ``input_signal`` and ``input_signal_length`` are mutually exclusive " - " with ``processed_signal`` and ``processed_signal_len`` arguments." - ) - - if not has_processed_signal: - processed_signal, processed_signal_length = self.preprocessor( - input_signal=input_signal, - length=input_signal_length, - ) - - # Spec augment is not applied during evaluation/testing - if self.spec_augmentation is not None and self.training: - processed_signal = self.spec_augmentation(input_spec=processed_signal, length=processed_signal_length) - - encoded, encoded_len = self.encoder(audio_signal=processed_signal, length=processed_signal_length) - return encoded, encoded_len - - # PTL-specific methods - def training_step(self, batch, batch_nb): - # Reset access registry - if AccessMixin.is_access_enabled(self.model_guid): - AccessMixin.reset_registry(self) - - signal, signal_len, transcript, transcript_len = batch - - # forward() only performs encoder forward - if isinstance(batch, DALIOutputs) and batch.has_processed_signal: - encoded, encoded_len = self.forward(processed_signal=signal, processed_signal_length=signal_len) - else: - encoded, encoded_len = self.forward(input_signal=signal, input_signal_length=signal_len) - del signal - - # During training, loss must be computed, so decoder forward is necessary - decoder, target_length, states = self.decoder(targets=transcript, target_length=transcript_len) - - if hasattr(self, '_trainer') and self._trainer is not None: - log_every_n_steps = self._trainer.log_every_n_steps - sample_id = self._trainer.global_step - else: - log_every_n_steps = 1 - sample_id = batch_nb - - # If experimental fused Joint-Loss-WER is not used - if not self.joint.fuse_loss_wer: - # Compute full joint and loss - joint = self.joint(encoder_outputs=encoded, decoder_outputs=decoder) - loss_value = self.loss( - log_probs=joint, targets=transcript, input_lengths=encoded_len, target_lengths=target_length - ) - - # Add auxiliary losses, if registered - loss_value = self.add_auxiliary_losses(loss_value) - - # Reset access registry - if AccessMixin.is_access_enabled(self.model_guid): - AccessMixin.reset_registry(self) - - tensorboard_logs = { - 'train_loss': loss_value, - 'learning_rate': self._optimizer.param_groups[0]['lr'], - 'global_step': torch.tensor(self.trainer.global_step, dtype=torch.float32), - } - - if (sample_id + 1) % log_every_n_steps == 0: - self.wer.update( - predictions=encoded, - predictions_lengths=encoded_len, - targets=transcript, - targets_lengths=transcript_len, - ) - _, scores, words = self.wer.compute() - self.wer.reset() - tensorboard_logs.update({'training_batch_wer': scores.float() / words}) - - else: - # If experimental fused Joint-Loss-WER is used - if (sample_id + 1) % log_every_n_steps == 0: - compute_wer = True - else: - compute_wer = False - - # Fused joint step - loss_value, wer, _, _ = self.joint( - encoder_outputs=encoded, - decoder_outputs=decoder, - encoder_lengths=encoded_len, - transcripts=transcript, - transcript_lengths=transcript_len, - compute_wer=compute_wer, - ) - - # Add auxiliary losses, if registered - loss_value = self.add_auxiliary_losses(loss_value) - - # Reset access registry - if AccessMixin.is_access_enabled(self.model_guid): - AccessMixin.reset_registry(self) - - tensorboard_logs = { - 'train_loss': loss_value, - 'learning_rate': self._optimizer.param_groups[0]['lr'], - 'global_step': torch.tensor(self.trainer.global_step, dtype=torch.float32), - } - - if compute_wer: - tensorboard_logs.update({'training_batch_wer': wer}) - - # Log items - self.log_dict(tensorboard_logs) - - # Preserve batch acoustic model T and language model U parameters if normalizing - if self._optim_normalize_joint_txu: - self._optim_normalize_txu = [encoded_len.max(), transcript_len.max()] - - return {'loss': loss_value} - - def predict_step(self, batch, batch_idx, dataloader_idx=0): - signal, signal_len, transcript, transcript_len, sample_id = batch - - # forward() only performs encoder forward - if isinstance(batch, DALIOutputs) and batch.has_processed_signal: - encoded, encoded_len = self.forward(processed_signal=signal, processed_signal_length=signal_len) - else: - encoded, encoded_len = self.forward(input_signal=signal, input_signal_length=signal_len) - del signal - - best_hyp_text = self.decoding.rnnt_decoder_predictions_tensor( - encoder_output=encoded, encoded_lengths=encoded_len, return_hypotheses=True - ) - - if isinstance(sample_id, torch.Tensor): - sample_id = sample_id.cpu().detach().numpy() - return list(zip(sample_id, best_hyp_text)) - - def validation_pass(self, batch, batch_idx, dataloader_idx=0): - signal, signal_len, transcript, transcript_len = batch - - # forward() only performs encoder forward - if isinstance(batch, DALIOutputs) and batch.has_processed_signal: - encoded, encoded_len = self.forward(processed_signal=signal, processed_signal_length=signal_len) - else: - encoded, encoded_len = self.forward(input_signal=signal, input_signal_length=signal_len) - del signal - - tensorboard_logs = {} - - # If experimental fused Joint-Loss-WER is not used - if not self.joint.fuse_loss_wer: - if self.compute_eval_loss: - decoder, target_length, states = self.decoder(targets=transcript, target_length=transcript_len) - joint = self.joint(encoder_outputs=encoded, decoder_outputs=decoder) - - loss_value = self.loss( - log_probs=joint, targets=transcript, input_lengths=encoded_len, target_lengths=target_length - ) - - tensorboard_logs['val_loss'] = loss_value - - self.wer.update( - predictions=encoded, - predictions_lengths=encoded_len, - targets=transcript, - targets_lengths=transcript_len, - ) - wer, wer_num, wer_denom = self.wer.compute() - self.wer.reset() - - tensorboard_logs['val_wer_num'] = wer_num - tensorboard_logs['val_wer_denom'] = wer_denom - tensorboard_logs['val_wer'] = wer - - else: - # If experimental fused Joint-Loss-WER is used - compute_wer = True - - if self.compute_eval_loss: - decoded, target_len, states = self.decoder(targets=transcript, target_length=transcript_len) - else: - decoded = None - target_len = transcript_len - - # Fused joint step - loss_value, wer, wer_num, wer_denom = self.joint( - encoder_outputs=encoded, - decoder_outputs=decoded, - encoder_lengths=encoded_len, - transcripts=transcript, - transcript_lengths=target_len, - compute_wer=compute_wer, - ) - - if loss_value is not None: - tensorboard_logs['val_loss'] = loss_value - - tensorboard_logs['val_wer_num'] = wer_num - tensorboard_logs['val_wer_denom'] = wer_denom - tensorboard_logs['val_wer'] = wer - - self.log('global_step', torch.tensor(self.trainer.global_step, dtype=torch.float32)) - - return tensorboard_logs - - def validation_step(self, batch, batch_idx, dataloader_idx=0): - metrics = self.validation_pass(batch, batch_idx, dataloader_idx) - if type(self.trainer.val_dataloaders) == list and len(self.trainer.val_dataloaders) > 1: - self.validation_step_outputs[dataloader_idx].append(metrics) - else: - self.validation_step_outputs.append(metrics) - return metrics - - def test_step(self, batch, batch_idx, dataloader_idx=0): - logs = self.validation_pass(batch, batch_idx, dataloader_idx=dataloader_idx) - test_logs = {name.replace("val_", "test_"): value for name, value in logs.items()} - if type(self.trainer.test_dataloaders) == list and len(self.trainer.test_dataloaders) > 1: - self.test_step_outputs[dataloader_idx].append(test_logs) - else: - self.test_step_outputs.append(test_logs) - return test_logs - - def multi_validation_epoch_end(self, outputs, dataloader_idx: int = 0): - if self.compute_eval_loss: - val_loss_mean = torch.stack([x['val_loss'] for x in outputs]).mean() - val_loss_log = {'val_loss': val_loss_mean} - else: - val_loss_log = {} - wer_num = torch.stack([x['val_wer_num'] for x in outputs]).sum() - wer_denom = torch.stack([x['val_wer_denom'] for x in outputs]).sum() - tensorboard_logs = {**val_loss_log, 'val_wer': wer_num.float() / wer_denom} - return {**val_loss_log, 'log': tensorboard_logs} - - def multi_test_epoch_end(self, outputs, dataloader_idx: int = 0): - if self.compute_eval_loss: - test_loss_mean = torch.stack([x['test_loss'] for x in outputs]).mean() - test_loss_log = {'test_loss': test_loss_mean} - else: - test_loss_log = {} - wer_num = torch.stack([x['test_wer_num'] for x in outputs]).sum() - wer_denom = torch.stack([x['test_wer_denom'] for x in outputs]).sum() - tensorboard_logs = {**test_loss_log, 'test_wer': wer_num.float() / wer_denom} - return {**test_loss_log, 'log': tensorboard_logs} - - """ Transcription related methods """ - - def _transcribe_forward(self, batch: Any, trcfg: TranscribeConfig): - encoded, encoded_len = self.forward(input_signal=batch[0], input_signal_length=batch[1]) - output = dict(encoded=encoded, encoded_len=encoded_len) - return output - - def _transcribe_output_processing( - self, outputs, trcfg: TranscribeConfig - ) -> Union[List['Hypothesis'], List[List['Hypothesis']]]: - encoded = outputs.pop('encoded') - encoded_len = outputs.pop('encoded_len') - - hyp = self.decoding.rnnt_decoder_predictions_tensor( - encoded, - encoded_len, - return_hypotheses=trcfg.return_hypotheses, - partial_hypotheses=trcfg.partial_hypothesis, - ) - # cleanup memory - del encoded, encoded_len - - if trcfg.timestamps: - hyp = process_timestamp_outputs( - hyp, self.encoder.subsampling_factor, self.cfg['preprocessor']['window_stride'] - ) - - return hyp - - def _setup_transcribe_dataloader(self, config: Dict) -> 'torch.utils.data.DataLoader': - """ - Setup function for a temporary data loader which wraps the provided audio file. - - Args: - config: A python dictionary which contains the following keys: - paths2audio_files: (a list) of paths to audio files. The files should be relatively short fragments. \ - Recommended length per file is between 5 and 25 seconds. - batch_size: (int) batch size to use during inference. \ - Bigger will result in better throughput performance but would use more memory. - temp_dir: (str) A temporary directory where the audio manifest is temporarily - stored. - - Returns: - A pytorch DataLoader for the given audio file(s). - """ - if 'manifest_filepath' in config: - manifest_filepath = config['manifest_filepath'] - batch_size = config['batch_size'] - else: - manifest_filepath = os.path.join(config['temp_dir'], 'manifest.json') - batch_size = min(config['batch_size'], len(config['paths2audio_files'])) - - dl_config = { - 'manifest_filepath': manifest_filepath, - 'sample_rate': self.preprocessor._sample_rate, - 'labels': self.joint.vocabulary, - 'batch_size': batch_size, - 'trim_silence': False, - 'shuffle': False, - 'num_workers': config.get('num_workers', min(batch_size, os.cpu_count() - 1)), - 'pin_memory': True, - } - - if config.get("augmentor"): - dl_config['augmentor'] = config.get("augmentor") - - temporary_datalayer = self._setup_dataloader_from_config(config=DictConfig(dl_config)) - return temporary_datalayer - - def _transcribe_on_begin(self, audio, trcfg: TranscribeConfig): - super()._transcribe_on_begin(audio=audio, trcfg=trcfg) - # add biasing requests to the decoding computer - try: - biasing_multi_model = self.decoding.decoding.decoding_computer.biasing_multi_model - except AttributeError: - biasing_multi_model = None - if trcfg.partial_hypothesis: - for partial_hyp in trcfg.partial_hypothesis: - if ( - isinstance(partial_hyp, Hypothesis) - and partial_hyp.has_biasing_request() - and partial_hyp.biasing_cfg.auto_manage_multi_model - and partial_hyp.biasing_cfg.multi_model_id is None - ): - if biasing_multi_model is not None: - partial_hyp.biasing_cfg.add_to_multi_model( - tokenizer=self.tokenizer, biasing_multi_model=biasing_multi_model - ) - else: - logging.warning("Requested biasing for hypothesis, but multi-model is not found, skipping.") - - def _transcribe_on_end(self, trcfg: TranscribeConfig): - super()._transcribe_on_end(trcfg=trcfg) - try: - biasing_multi_model = self.decoding.decoding.decoding_computer.biasing_multi_model - except AttributeError: - biasing_multi_model = None - - # remove biasing requests from the decoding computer - if biasing_multi_model is not None and trcfg.partial_hypothesis: - for partial_hyp in trcfg.partial_hypothesis: - if ( - isinstance(partial_hyp, Hypothesis) - and partial_hyp.has_biasing_request() - and partial_hyp.biasing_cfg.auto_manage_multi_model - ): - partial_hyp.biasing_cfg.remove_from_multi_model(biasing_multi_model=biasing_multi_model) - - def on_after_backward(self): - super().on_after_backward() - if self._optim_variational_noise_std > 0 and self.global_step >= self._optim_variational_noise_start: - for param_name, param in self.decoder.named_parameters(): - if param.grad is not None: - noise = torch.normal( - mean=0.0, - std=self._optim_variational_noise_std, - size=param.size(), - device=param.device, - dtype=param.dtype, - ) - param.grad.data.add_(noise) - - if self._optim_normalize_joint_txu: - T, U = self._optim_normalize_txu - if T is not None and U is not None: - for param_name, param in self.encoder.named_parameters(): - if param.grad is not None: - param.grad.data.div_(U) - - for param_name, param in self.decoder.named_parameters(): - if param.grad is not None: - param.grad.data.div_(T) - - if self._optim_normalize_encoder_norm: - for param_name, param in self.encoder.named_parameters(): - if param.grad is not None: - norm = param.grad.norm() - param.grad.data.div_(norm) - - if self._optim_normalize_decoder_norm: - for param_name, param in self.decoder.named_parameters(): - if param.grad is not None: - norm = param.grad.norm() - param.grad.data.div_(norm) - - if self._optim_normalize_joint_norm: - for param_name, param in self.joint.named_parameters(): - if param.grad is not None: - norm = param.grad.norm() - param.grad.data.div_(norm) - - # EncDecRNNTModel is exported in 2 parts - def list_export_subnets(self): - return ['encoder', 'decoder_joint'] - - # for export - @property - def decoder_joint(self): - return RNNTDecoderJoint(self.decoder, self.joint) - - def set_export_config(self, args): - if 'decoder_type' in args: - if hasattr(self, 'change_decoding_strategy'): - self.change_decoding_strategy(decoder_type=args['decoder_type']) - else: - raise Exception("Model does not have decoder type option") - super().set_export_config(args) - - @classmethod - def list_available_models(cls) -> List[PretrainedModelInfo]: - """ - This method returns a list of pre-trained model which can be instantiated directly from NVIDIA's NGC cloud. - - Returns: - List of available pre-trained models. - """ - results = [] - - model = PretrainedModelInfo( - pretrained_model_name="stt_zh_conformer_transducer_large", - description="For details about this model, please visit https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/stt_zh_conformer_transducer_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_zh_conformer_transducer_large/versions/1.8.0/files/stt_zh_conformer_transducer_large.nemo", - ) - results.append(model) - - return results - - @property - def wer(self): - return self._wer - - @wer.setter - def wer(self, wer): - self._wer = wer diff --git a/nemo/collections/asr/models/sortformer_diar_models.py b/nemo/collections/asr/models/sortformer_diar_models.py deleted file mode 100644 index 0f9d2c0a32f6f5d86fdfef6a083be488385b8bbc..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/sortformer_diar_models.py +++ /dev/null @@ -1,1173 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# pylint: disable=E1101 -import itertools -import math -import os -import random -from collections import OrderedDict -from typing import Any, Dict, List, Optional, Tuple, Union - -import numpy as np -import torch -import torch.distributed as dist -from hydra.utils import instantiate -from omegaconf import DictConfig -from pytorch_lightning import Trainer -from torch.utils.data import DataLoader -from tqdm import tqdm - -from nemo.collections.asr.data.audio_to_diar_label import AudioToSpeechE2ESpkDiarDataset -from nemo.collections.asr.data.audio_to_diar_label_lhotse import LhotseAudioToSpeechE2ESpkDiarDataset -from nemo.collections.asr.metrics.multi_binary_acc import MultiBinaryAccuracy -from nemo.collections.asr.models.asr_model import ExportableEncDecModel -from nemo.collections.asr.parts.mixins.diarization import DiarizeConfig, SpkDiarizationMixin -from nemo.collections.asr.parts.preprocessing.features import FilterbankFeatures, WaveformFeaturizer -from nemo.collections.asr.parts.preprocessing.perturb import process_augmentations -from nemo.collections.asr.parts.utils.asr_multispeaker_utils import get_ats_targets, get_pil_targets -from nemo.collections.asr.parts.utils.speaker_utils import generate_diarization_output_lines -from nemo.collections.asr.parts.utils.vad_utils import ts_vad_post_processing -from nemo.collections.common.data.lhotse import get_lhotse_dataloader_from_config -from nemo.core.classes import ModelPT -from nemo.core.classes.common import PretrainedModelInfo -from nemo.core.neural_types import AudioSignal, LengthsType, NeuralType -from nemo.core.neural_types.elements import ProbsType -from nemo.utils import logging - -__all__ = ['SortformerEncLabelModel'] - - -class SortformerEncLabelModel(ModelPT, ExportableEncDecModel, SpkDiarizationMixin): - """ - Encoder class for Sortformer diarization model. - Model class creates training, validation methods for setting up data performing model forward pass. - - This model class expects config dict for: - * preprocessor - * Transformer Encoder - * FastConformer Encoder - * Sortformer Modules - """ - - @classmethod - def list_available_models(cls) -> List[PretrainedModelInfo]: - """ - This method returns a list of pre-trained model which can be instantiated directly - from NVIDIA's NGC cloud. - - Returns: - List of available pre-trained models. - """ - result = [] - - model = PretrainedModelInfo( - pretrained_model_name="diar_sortformer_4spk-v1", - description="For details about this model, please visit https://huggingface.co/nvidia/diar_sortformer_4spk-v1", - location="https://huggingface.co/nvidia/diar_sortformer_4spk-v1", - ) - result.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="diar_streaming_sortformer_4spk-v2", - description="For details about this model, please visit https://huggingface.co/nvidia/diar_streaming_sortformer_4spk-v2", - location="https://huggingface.co/nvidia/diar_streaming_sortformer_4spk-v2", - ) - result.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="diar_streaming_sortformer_4spk-v2.1", - description="For details about this model, please visit https://huggingface.co/nvidia/diar_streaming_sortformer_4spk-v2.1", - location="https://huggingface.co/nvidia/diar_streaming_sortformer_4spk-v2.1", - ) - result.append(model) - - return result - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - """ - Initialize an Sortformer Diarizer model and a pretrained NEST encoder. - In this init function, training and validation datasets are prepared. - """ - random.seed(42) - self._trainer = trainer if trainer else None - self._cfg = cfg - - if self._trainer: - self.world_size = trainer.num_nodes * trainer.num_devices - else: - self.world_size = 1 - - if self._trainer is not None and self._cfg.get('augmentor', None) is not None: - self.augmentor = process_augmentations(self._cfg.augmentor) - else: - self.augmentor = None - super().__init__(cfg=self._cfg, trainer=trainer) - self.preprocessor = SortformerEncLabelModel.from_config_dict(self._cfg.preprocessor) - - if hasattr(self._cfg, 'spec_augment') and self._cfg.spec_augment is not None: - self.spec_augmentation = SortformerEncLabelModel.from_config_dict(self._cfg.spec_augment) - else: - self.spec_augmentation = None - - self.encoder = SortformerEncLabelModel.from_config_dict(self._cfg.encoder).to(self.device) - self.sortformer_modules = SortformerEncLabelModel.from_config_dict(self._cfg.sortformer_modules).to( - self.device - ) - self.transformer_encoder = SortformerEncLabelModel.from_config_dict(self._cfg.transformer_encoder).to( - self.device - ) - if self._cfg.encoder.d_model != self._cfg.model_defaults.tf_d_model: - self.sortformer_modules.encoder_proj = self.sortformer_modules.encoder_proj.to(self.device) - else: - self.sortformer_modules.encoder_proj = None - self._init_loss_weights() - - self.eps = self._cfg.get("eps", 1e-3) - self.negative_init_val = self._cfg.get("negative_init_val", -99) - self.loss = instantiate(self._cfg.loss) - - self.async_streaming = self._cfg.get("async_streaming", False) - self.streaming_mode = self._cfg.get("streaming_mode", False) - if self.streaming_mode: - # Validate streaming parameters once at initialization for streaming models - self.sortformer_modules._check_streaming_parameters() - self.save_hyperparameters("cfg") - self._init_eval_metrics() - speaker_inds = list(range(self._cfg.max_num_of_spks)) - self.speaker_permutations = torch.tensor(list(itertools.permutations(speaker_inds))) # Get all permutations - - self.max_batch_dur = self._cfg.get("max_batch_dur", 20000) - self.concat_and_pad_script = torch.jit.script(self.sortformer_modules.concat_and_pad) - self.rttms_mask_mats: List[torch.Tensor] = None # Used when GT diarization needs to be tested. - - def add_rttms_mask_mats(self, rttms_mask_mats, device: torch.device): - """ - Check if the rttms_mask_mats is empty then add it to the list - - Args: - rttms_mask_mats (List[torch.Tensor]): List of PyTorch tensors containing the rttms mask matrices. - """ - if self.rttms_mask_mats is None: - self.rttms_mask_mats = rttms_mask_mats.to(device) - else: - raise ValueError( - f"{self.rttms_mask_mats.shape}: rttms_mask_mats already exist but new one is being added." - ) - - def _init_loss_weights(self): - pil_weight = self._cfg.get("pil_weight", 0.0) - ats_weight = self._cfg.get("ats_weight", 1.0) - if pil_weight + ats_weight == 0: - raise ValueError(f"weights for PIL {pil_weight} and ATS {ats_weight} cannot sum to 0") - self.pil_weight = pil_weight / (pil_weight + ats_weight) - self.ats_weight = ats_weight / (pil_weight + ats_weight) - - def _init_eval_metrics(self): - """ - If there is no label, then the evaluation metrics will be based on Permutation Invariant Loss (PIL). - """ - self._accuracy_test = MultiBinaryAccuracy() - self._accuracy_train = MultiBinaryAccuracy() - self._accuracy_valid = MultiBinaryAccuracy() - - self._accuracy_test_ats = MultiBinaryAccuracy() - self._accuracy_train_ats = MultiBinaryAccuracy() - self._accuracy_valid_ats = MultiBinaryAccuracy() - - def _reset_train_metrics(self): - self._accuracy_train.reset() - self._accuracy_train_ats.reset() - - def _reset_valid_metrics(self): - self._accuracy_valid.reset() - self._accuracy_valid_ats.reset() - - def __setup_dataloader_from_config(self, config): - # Switch to lhotse dataloader if specified in the config - if config.get("use_lhotse"): - return get_lhotse_dataloader_from_config( - config, - global_rank=self.global_rank, - world_size=self.world_size, - dataset=LhotseAudioToSpeechE2ESpkDiarDataset(cfg=config), - ) - - featurizer = WaveformFeaturizer( - sample_rate=config['sample_rate'], int_values=config.get('int_values', False), augmentor=self.augmentor - ) - fb_featurizer = FilterbankFeatures( - sample_rate=self._cfg.preprocessor.sample_rate, - normalize=self._cfg.preprocessor.normalize, - n_window_size=int(self._cfg.preprocessor.window_size * config['sample_rate']), - n_window_stride=int(self._cfg.preprocessor.window_stride * config['sample_rate']), - window=self._cfg.preprocessor.window, - nfilt=self._cfg.preprocessor.features, - n_fft=self._cfg.preprocessor.n_fft, - frame_splicing=self._cfg.preprocessor.frame_splicing, - dither=self._cfg.preprocessor.dither, - ) - - if 'manifest_filepath' in config and config['manifest_filepath'] is None: - logging.warning(f"Could not load dataset as `manifest_filepath` was None. Provided config : {config}") - return None - - logging.info(f"Loading dataset from {config.manifest_filepath}") - - if self._trainer is not None: - global_rank = self._trainer.global_rank - else: - global_rank = 0 - - dataset = AudioToSpeechE2ESpkDiarDataset( - manifest_filepath=config.manifest_filepath, - soft_label_thres=config.soft_label_thres, - session_len_sec=config.session_len_sec, - num_spks=config.num_spks, - featurizer=featurizer, - fb_featurizer=fb_featurizer, - window_stride=self._cfg.preprocessor.window_stride, - global_rank=global_rank, - soft_targets=config.soft_targets if 'soft_targets' in config else False, - device=self.device, - ) - - self.data_collection = dataset.collection - self.collate_ds = dataset - - dataloader_instance = torch.utils.data.DataLoader( - dataset=dataset, - batch_size=config.batch_size, - collate_fn=self.collate_ds.eesd_train_collate_fn, - drop_last=config.get('drop_last', False), - shuffle=False, - num_workers=config.get('num_workers', 1), - pin_memory=config.get('pin_memory', False), - ) - return dataloader_instance - - def setup_training_data(self, train_data_config: Optional[Union[DictConfig, Dict]]): - self._train_dl = self.__setup_dataloader_from_config( - config=train_data_config, - ) - - def setup_validation_data(self, val_data_layer_config: Optional[Union[DictConfig, Dict]]): - self._validation_dl = self.__setup_dataloader_from_config( - config=val_data_layer_config, - ) - - def setup_test_data(self, test_data_config: Optional[Union[DictConfig, Dict]]): - self._test_dl = self.__setup_dataloader_from_config( - config=test_data_config, - ) - - def test_dataloader(self): - if self._test_dl is not None: - return self._test_dl - return None - - @property - def input_types(self) -> Optional[Dict[str, NeuralType]]: - if hasattr(self.preprocessor, '_sample_rate'): - audio_eltype = AudioSignal(freq=self.preprocessor._sample_rate) - else: - audio_eltype = AudioSignal() - return { - "audio_signal": NeuralType(('B', 'T'), audio_eltype), - "audio_signal_length": NeuralType(('B',), LengthsType()), - } - - @property - def output_types(self) -> Dict[str, NeuralType]: - return OrderedDict( - { - "preds": NeuralType(('B', 'T', 'C'), ProbsType()), - } - ) - - def frontend_encoder(self, processed_signal, processed_signal_length, bypass_pre_encode: bool = False): - """ - Generate encoder outputs from frontend encoder. - - Args: - processed_signal (torch.Tensor): tensor containing audio-feature - (mel spectrogram, mfcc, etc.). - processed_signal_length (torch.Tensor): tensor containing lengths - of audio signal in integers. - - Returns: - emb_seq (torch.Tensor): tensor containing encoder outputs. - emb_seq_length (torch.Tensor): tensor containing lengths of encoder outputs. - """ - # Spec augment is not applied during evaluation/testing - if self.spec_augmentation is not None and self.training: - processed_signal = self.spec_augmentation(input_spec=processed_signal, length=processed_signal_length) - emb_seq, emb_seq_length = self.encoder( - audio_signal=processed_signal, - length=processed_signal_length, - bypass_pre_encode=bypass_pre_encode, - ) - emb_seq = emb_seq.transpose(1, 2) - if self.sortformer_modules.encoder_proj is not None: - emb_seq = self.sortformer_modules.encoder_proj(emb_seq) - return emb_seq, emb_seq_length - - def forward_infer(self, emb_seq, emb_seq_length): - """ - The main forward pass for diarization for offline diarization inference. - - Args: - emb_seq (torch.Tensor): Tensor containing FastConformer encoder states (embedding vectors). - Shape: (batch_size, diar_frame_count, emb_dim) - emb_seq_length (torch.Tensor): Tensor containing lengths of FastConformer encoder states. - Shape: (batch_size,) - - Returns: - preds (torch.Tensor): Sorted tensor containing Sigmoid values for predicted speaker labels. - Shape: (batch_size, diar_frame_count, num_speakers) - """ - encoder_mask = self.sortformer_modules.length_to_mask(emb_seq_length, emb_seq.shape[1]) - trans_emb_seq = self.transformer_encoder(encoder_states=emb_seq, encoder_mask=encoder_mask) - _preds = self.sortformer_modules.forward_speaker_sigmoids(trans_emb_seq) - preds = _preds * encoder_mask.unsqueeze(-1) - return preds - - def _diarize_forward(self, batch: Any): - """ - A counterpart of `_transcribe_forward` function in ASR. - This function is a wrapper for forward pass functions for compataibility - with the existing classes. - - Args: - batch (Any): The input batch containing audio signal and audio signal length. - - Returns: - preds (torch.Tensor): Sorted tensor containing Sigmoid values for predicted speaker labels. - Shape: (batch_size, diar_frame_count, num_speakers) - """ - with torch.no_grad(): - preds = self.forward(audio_signal=batch[0], audio_signal_length=batch[1]) - preds = preds.to('cpu') - torch.cuda.empty_cache() - return preds - - def _diarize_output_processing( - self, outputs, uniq_ids, diarcfg: DiarizeConfig - ) -> Union[List[List[str]], Tuple[List[List[str]], List[torch.Tensor]]]: - """ - Processes the diarization outputs and generates RTTM (Real-time Text Markup) files. - TODO: Currently, this function is not included in mixin test because of - `ts_vad_post_processing` function. - (1) Implement a test-compatible function - (2) `vad_utils.py` has `predlist_to_timestamps` function that is close to this function. - Needs to consolute differences and implement the test-compatible function. - - Args: - outputs (torch.Tensor): Sorted tensor containing Sigmoid values for predicted speaker labels. - Shape: (batch_size, diar_frame_count, num_speakers) - uniq_ids (List[str]): List of unique identifiers for each audio file. - diarcfg (DiarizeConfig): Configuration object for diarization. - - Returns: - diar_output_lines_list (List[List[str]]): A list of lists, where each inner list contains - the RTTM lines for a single audio file. - preds_list (List[torch.Tensor]): A list of tensors containing the diarization outputs - for each audio file. - """ - preds_list, diar_output_lines_list = [], [] - if outputs.shape[0] == 1: # batch size = 1 - preds_list.append(outputs) - else: - preds_list.extend(torch.split(outputs, [1] * outputs.shape[0])) - - for sample_idx, uniq_id in enumerate(uniq_ids): - offset = self._diarize_audio_rttm_map[uniq_id]['offset'] - speaker_assign_mat = preds_list[sample_idx].squeeze(dim=0) - speaker_timestamps = [[] for _ in range(speaker_assign_mat.shape[-1])] - for spk_id in range(speaker_assign_mat.shape[-1]): - ts_mat = ts_vad_post_processing( - speaker_assign_mat[:, spk_id], - cfg_vad_params=diarcfg.postprocessing_params, - unit_10ms_frame_count=int(self._cfg.encoder.subsampling_factor), - bypass_postprocessing=False, - ) - ts_mat = ts_mat + offset - ts_seg_raw_list = ts_mat.tolist() - ts_seg_list = [[round(stt, 2), round(end, 2)] for (stt, end) in ts_seg_raw_list] - speaker_timestamps[spk_id].extend(ts_seg_list) - - diar_output_lines = generate_diarization_output_lines( - speaker_timestamps=speaker_timestamps, model_spk_num=len(speaker_timestamps) - ) - diar_output_lines_list.append(diar_output_lines) - if diarcfg.include_tensor_outputs: - return (diar_output_lines_list, preds_list) - else: - return diar_output_lines_list - - def _setup_diarize_dataloader(self, config: Dict) -> 'torch.utils.data.DataLoader': - """ - Setup function for a temporary data loader which wraps the provided audio file. - - Args: - config: A python dictionary which contains the following keys: - - manifest_filepath: Path to the manifest file containing audio file paths - and corresponding speaker labels. - - Returns: - A pytorch DataLoader for the given audio file(s). - """ - if 'manifest_filepath' in config: - manifest_filepath = config['manifest_filepath'] - batch_size = config['batch_size'] - else: - manifest_filepath = os.path.join(config['temp_dir'], 'manifest.json') - batch_size = min(config['batch_size'], len(config['paths2audio_files'])) - - dl_config = { - 'manifest_filepath': manifest_filepath, - 'sample_rate': self.preprocessor._sample_rate, - 'num_spks': config.get('num_spks', self._cfg.max_num_of_spks), - 'batch_size': batch_size, - 'shuffle': False, - 'soft_label_thres': 0.5, - 'session_len_sec': config['session_len_sec'], - 'num_workers': config.get('num_workers', min(batch_size, os.cpu_count() - 1)), - 'pin_memory': True, - 'use_lhotse': config.get('use_lhotse', False), - } - temporary_datalayer = self.__setup_dataloader_from_config(config=DictConfig(dl_config)) - return temporary_datalayer - - def oom_safe_feature_extraction(self, input_signal, input_signal_length): - """ - This function divides the input signal into smaller sub-batches and processes them sequentially - to prevent out-of-memory errors during feature extraction. - - Args: - input_signal (torch.Tensor): The input audio signal. - input_signal_length (torch.Tensor): The lengths of the input audio signals. - - Returns: - A tuple of ``(processed_signal, processed_signal_length)`` where - ``processed_signal`` is the aggregated audio signal tensor - (length matches original batch size) and - ``processed_signal_length`` contains the lengths of the processed signals. - """ - input_signal = input_signal.cpu() - processed_signal_list, processed_signal_length_list = [], [] - max_batch_sec = input_signal.shape[1] / self.preprocessor._cfg.sample_rate - org_batch_size = input_signal.shape[0] - div_batch_count = min(int(max_batch_sec * org_batch_size // self.max_batch_dur + 1), org_batch_size) - div_size = math.ceil(org_batch_size / div_batch_count) - - for div_count in range(div_batch_count): - start_idx = int(div_count * div_size) - end_idx = int((div_count + 1) * div_size) - if start_idx >= org_batch_size: - break - input_signal_div = input_signal[start_idx:end_idx, :].to(self.device) - input_signal_length_div = input_signal_length[start_idx:end_idx] - processed_signal_div, processed_signal_length_div = self.preprocessor( - input_signal=input_signal_div, length=input_signal_length_div - ) - processed_signal_div = processed_signal_div.detach().cpu() - processed_signal_length_div = processed_signal_length_div.detach().cpu() - processed_signal_list.append(processed_signal_div) - processed_signal_length_list.append(processed_signal_length_div) - - processed_signal = torch.cat(processed_signal_list, 0) - processed_signal_length = torch.cat(processed_signal_length_list, 0) - assert processed_signal.shape[0] == org_batch_size, ( - f"The resulting batch size of processed signal - {processed_signal.shape[0]} " - f"is not equal to original batch size: {org_batch_size}" - ) - processed_signal = processed_signal.to(self.device) - processed_signal_length = processed_signal_length.to(self.device) - return processed_signal, processed_signal_length - - def process_signal(self, audio_signal, audio_signal_length): - """ - Extract audio features from time-series signal for further processing in the model. - - This function performs the following steps: - 1. Moves the audio signal to the correct device. - 2. Normalizes the time-series audio signal. - 3. Extrac audio feature from from the time-series audio signal using the model's preprocessor. - - Args: - audio_signal (torch.Tensor): The input audio signal. - Shape: (batch_size, num_samples) - audio_signal_length (torch.Tensor): The length of each audio signal in the batch. - Shape: (batch_size,) - - Returns: - processed_signal (torch.Tensor): The preprocessed audio signal. - Shape: (batch_size, num_features, num_frames) - processed_signal_length (torch.Tensor): The length of each processed signal. - Shape: (batch_size,) - """ - audio_signal, audio_signal_length = audio_signal.to(self.device), audio_signal_length.to(self.device) - if not self.streaming_mode: - audio_signal = (1 / (audio_signal.max() + self.eps)) * audio_signal - - batch_total_dur = audio_signal.shape[0] * audio_signal.shape[1] / self.preprocessor._cfg.sample_rate - if self.max_batch_dur > 0 and self.max_batch_dur < batch_total_dur: - processed_signal, processed_signal_length = self.oom_safe_feature_extraction( - input_signal=audio_signal, input_signal_length=audio_signal_length - ) - else: - processed_signal, processed_signal_length = self.preprocessor( - input_signal=audio_signal, length=audio_signal_length - ) - # This cache clearning can significantly slow down the training speed. - # Only perform `empty_cache()` when the input file is extremely large for streaming mode. - if not self.training and self.streaming_mode: - del audio_signal, audio_signal_length - torch.cuda.empty_cache() - return processed_signal, processed_signal_length - - def forward( - self, - audio_signal, - audio_signal_length, - ): - """ - Forward pass for training and inference. - - Args: - audio_signal (torch.Tensor): Tensor containing audio waveform - Shape: (batch_size, num_samples) - audio_signal_length (torch.Tensor): Tensor containing lengths of audio waveforms - Shape: (batch_size,) - - Returns: - preds (torch.Tensor): Sorted tensor containing predicted speaker labels - Shape: (batch_size, max. diar frame count, num_speakers) - """ - processed_signal, processed_signal_length = self.process_signal( - audio_signal=audio_signal, audio_signal_length=audio_signal_length - ) - processed_signal = processed_signal[:, :, : processed_signal_length.max()] - if self.streaming_mode: - preds = self.forward_streaming(processed_signal, processed_signal_length) - else: - emb_seq, emb_seq_length = self.frontend_encoder( - processed_signal=processed_signal, processed_signal_length=processed_signal_length - ) - preds = self.forward_infer(emb_seq, emb_seq_length) - return preds - - @property - def input_names(self): - return ["chunk", "chunk_lengths", "spkcache", "spkcache_lengths", "fifo", "fifo_lengths"] - - @property - def output_names(self): - return ["spkcache_fifo_chunk_preds", "chunk_pre_encode_embs", "chunk_pre_encode_lengths"] - - def streaming_input_examples(self): - """Input tensor examples for exporting streaming version of model""" - batch_size = 4 - chunk = torch.rand([batch_size, 120, 80]).to(self.device) - chunk_lengths = torch.tensor([120] * batch_size).to(self.device) - spkcache = torch.randn([batch_size, 188, 512]).to(self.device) - spkcache_lengths = torch.tensor([40, 188, 0, 68]).to(self.device) - fifo = torch.randn([batch_size, 188, 512]).to(self.device) - fifo_lengths = torch.tensor([50, 88, 0, 90]).to(self.device) - return chunk, chunk_lengths, spkcache, spkcache_lengths, fifo, fifo_lengths - - def streaming_export(self, output: str): - """Exports the model for streaming inference.""" - input_example = self.streaming_input_examples() - export_out = self.export(output, input_example=input_example) - return export_out - - def forward_for_export(self, chunk, chunk_lengths, spkcache, spkcache_lengths, fifo, fifo_lengths): - """ - This forward pass is for ONNX model export. - - Args: - chunk (torch.Tensor): Tensor containing audio waveform. - The term "chunk" refers to the "input buffer" in the speech processing pipeline. - The size of chunk (input buffer) determines the latency introduced by buffering. - Shape: (batch_size, feature frame count, dimension) - chunk_lengths (torch.Tensor): Tensor containing lengths of audio waveforms - Shape: (batch_size,) - spkcache (torch.Tensor): Tensor containing speaker cache embeddings from start - Shape: (batch_size, spkcache_len, emb_dim) - spkcache_lengths (torch.Tensor): Tensor containing lengths of speaker cache - Shape: (batch_size,) - fifo (torch.Tensor): Tensor containing embeddings from latest chunks - Shape: (batch_size, fifo_len, emb_dim) - fifo_lengths (torch.Tensor): Tensor containing lengths of FIFO queue embeddings - Shape: (batch_size,) - - Returns: - spkcache_fifo_chunk_preds (torch.Tensor): Sorted tensor containing predicted speaker labels - Shape: (batch_size, max. diar frame count, num_speakers) - chunk_pre_encode_embs (torch.Tensor): Tensor containing pre-encoded embeddings from the chunk - Shape: (batch_size, num_frames, emb_dim) - chunk_pre_encode_lengths (torch.Tensor): Tensor containing lengths of pre-encoded embeddings - from the chunk (=input buffer). - Shape: (batch_size,) - """ - # pre-encode the chunk - chunk_pre_encode_embs, chunk_pre_encode_lengths = self.encoder.pre_encode(x=chunk, lengths=chunk_lengths) - chunk_pre_encode_lengths = chunk_pre_encode_lengths.to(torch.int64) - - # concat the embeddings from speaker cache, FIFO queue and the chunk - spkcache_fifo_chunk_pre_encode_embs, spkcache_fifo_chunk_pre_encode_lengths = self.concat_and_pad_script( - [spkcache, fifo, chunk_pre_encode_embs], [spkcache_lengths, fifo_lengths, chunk_pre_encode_lengths] - ) - - # encode the concatenated embeddings - spkcache_fifo_chunk_fc_encoder_embs, spkcache_fifo_chunk_fc_encoder_lengths = self.frontend_encoder( - processed_signal=spkcache_fifo_chunk_pre_encode_embs, - processed_signal_length=spkcache_fifo_chunk_pre_encode_lengths, - bypass_pre_encode=True, - ) - - # forward pass for inference - spkcache_fifo_chunk_preds = self.forward_infer( - spkcache_fifo_chunk_fc_encoder_embs, spkcache_fifo_chunk_fc_encoder_lengths - ) - return spkcache_fifo_chunk_preds, chunk_pre_encode_embs, chunk_pre_encode_lengths - - def forward_streaming( - self, - processed_signal, - processed_signal_length, - ): - """ - The main forward pass for diarization inference in streaming mode. - - Args: - processed_signal (torch.Tensor): Tensor containing audio waveform - Shape: (batch_size, num_samples) - processed_signal_length (torch.Tensor): Tensor containing lengths of audio waveforms - Shape: (batch_size,) - - Returns: - total_preds (torch.Tensor): Tensor containing predicted speaker labels for the current chunk - and all previous chunks - Shape: (batch_size, pred_len, num_speakers) - """ - streaming_state = self.sortformer_modules.init_streaming_state( - batch_size=processed_signal.shape[0], async_streaming=self.async_streaming, device=self.device - ) - - batch_size, ch, sig_length = processed_signal.shape - processed_signal_offset = torch.zeros((batch_size,), dtype=torch.long, device=self.device) - - if dist.is_available() and dist.is_initialized(): - local_tensor = torch.tensor([sig_length], device=processed_signal.device) - dist.all_reduce( - local_tensor, op=dist.ReduceOp.MAX, async_op=False - ) # get max feature length across all GPUs - max_n_frames = local_tensor.item() - if dist.get_rank() == 0: - logging.info(f"Maximum feature length across all GPUs: {max_n_frames}") - else: - max_n_frames = sig_length - - if sig_length < max_n_frames: # need padding to have the same feature length for all GPUs - pad_tensor = torch.full( - (batch_size, ch, max_n_frames - sig_length), - self.negative_init_val, - dtype=processed_signal.dtype, - device=processed_signal.device, - ) - processed_signal = torch.cat([processed_signal, pad_tensor], dim=2) - - att_mod = False - if self.training: - rand_num = random.random() - if rand_num < self.sortformer_modules.causal_attn_rate: - self.encoder.att_context_size = [-1, self.sortformer_modules.causal_attn_rc] - self.transformer_encoder.diag = self.sortformer_modules.causal_attn_rc - att_mod = True - - total_preds = torch.zeros((batch_size, 0, self.sortformer_modules.n_spk), device=self.device) - - feat_len = processed_signal.shape[2] - num_chunks = math.ceil( - feat_len / (self.sortformer_modules.chunk_len * self.sortformer_modules.subsampling_factor) - ) - streaming_loader = self.sortformer_modules.streaming_feat_loader( - feat_seq=processed_signal, - feat_seq_length=processed_signal_length, - feat_seq_offset=processed_signal_offset, - ) - for _, chunk_feat_seq_t, feat_lengths, left_offset, right_offset in tqdm( - streaming_loader, - total=num_chunks, - desc="Streaming Steps", - disable=self.training, - ): - streaming_state, total_preds = self.forward_streaming_step( - processed_signal=chunk_feat_seq_t, - processed_signal_length=feat_lengths, - streaming_state=streaming_state, - total_preds=total_preds, - left_offset=left_offset, - right_offset=right_offset, - ) - - if att_mod: - self.encoder.att_context_size = [-1, -1] - self.transformer_encoder.diag = None - - del processed_signal, processed_signal_length - - if sig_length < max_n_frames: # Discard preds corresponding to padding - n_frames = math.ceil(sig_length / self.encoder.subsampling_factor) - total_preds = total_preds[:, :n_frames, :] - return total_preds - - def forward_streaming_step( - self, - processed_signal, - processed_signal_length, - streaming_state, - total_preds, - drop_extra_pre_encoded=0, - left_offset=0, - right_offset=0, - ): - """ - One-step forward pass for diarization inference in streaming mode. - - Args: - processed_signal (torch.Tensor): Tensor containing audio waveform - Shape: (batch_size, num_samples) - processed_signal_length (torch.Tensor): Tensor containing lengths of audio waveforms - Shape: (batch_size,) - streaming_state (SortformerStreamingState): - Tensor variables that contain the streaming state of the model. - Find more details in the `SortformerStreamingState` class in `sortformer_modules.py`. - - Attributes: - spkcache (torch.Tensor): Speaker cache to store embeddings from start - spkcache_lengths (torch.Tensor): Lengths of the speaker cache - spkcache_preds (torch.Tensor): The speaker predictions for the speaker cache parts - fifo (torch.Tensor): FIFO queue to save the embedding from the latest chunks - fifo_lengths (torch.Tensor): Lengths of the FIFO queue - fifo_preds (torch.Tensor): The speaker predictions for the FIFO queue parts - spk_perm (torch.Tensor): Speaker permutation information for the speaker cache - - total_preds (torch.Tensor): Tensor containing total predicted speaker activity probabilities - Shape: (batch_size, cumulative pred length, num_speakers) - left_offset (int): left offset for the current chunk - right_offset (int): right offset for the current chunk - - Returns: - streaming_state (SortformerStreamingState): - Tensor variables that contain the updated streaming state of the model from - this function call. - total_preds (torch.Tensor): - Tensor containing the updated total predicted speaker activity probabilities. - Shape: (batch_size, cumulative pred length, num_speakers) - """ - chunk_pre_encode_embs, chunk_pre_encode_lengths = self.encoder.pre_encode( - x=processed_signal, lengths=processed_signal_length - ) - # To match the output of the ASR model, we need to drop the extra pre-encoded embeddings - if drop_extra_pre_encoded > 0: - chunk_pre_encode_embs = chunk_pre_encode_embs[:, drop_extra_pre_encoded:, :] - chunk_pre_encode_lengths = chunk_pre_encode_lengths - drop_extra_pre_encoded - - if self.async_streaming: - spkcache_fifo_chunk_pre_encode_embs, spkcache_fifo_chunk_pre_encode_lengths = ( - self.sortformer_modules.concat_and_pad( - [streaming_state.spkcache, streaming_state.fifo, chunk_pre_encode_embs], - [streaming_state.spkcache_lengths, streaming_state.fifo_lengths, chunk_pre_encode_lengths], - ) - ) - else: - spkcache_fifo_chunk_pre_encode_embs = self.sortformer_modules.concat_embs( - [streaming_state.spkcache, streaming_state.fifo, chunk_pre_encode_embs], dim=1, device=self.device - ) - spkcache_fifo_chunk_pre_encode_lengths = ( - streaming_state.spkcache.shape[1] + streaming_state.fifo.shape[1] + chunk_pre_encode_lengths - ) - spkcache_fifo_chunk_fc_encoder_embs, spkcache_fifo_chunk_fc_encoder_lengths = self.frontend_encoder( - processed_signal=spkcache_fifo_chunk_pre_encode_embs, - processed_signal_length=spkcache_fifo_chunk_pre_encode_lengths, - bypass_pre_encode=True, - ) - spkcache_fifo_chunk_preds = self.forward_infer( - emb_seq=spkcache_fifo_chunk_fc_encoder_embs, emb_seq_length=spkcache_fifo_chunk_fc_encoder_lengths - ) - - spkcache_fifo_chunk_preds = self.sortformer_modules.apply_mask_to_preds( - spkcache_fifo_chunk_preds, spkcache_fifo_chunk_fc_encoder_lengths - ) - if self.async_streaming: - streaming_state, chunk_preds = self.sortformer_modules.streaming_update_async( - streaming_state=streaming_state, - chunk=chunk_pre_encode_embs, - chunk_lengths=chunk_pre_encode_lengths, - preds=spkcache_fifo_chunk_preds, - lc=round(left_offset / self.encoder.subsampling_factor), - rc=math.ceil(right_offset / self.encoder.subsampling_factor), - ) - else: - streaming_state, chunk_preds = self.sortformer_modules.streaming_update( - streaming_state=streaming_state, - chunk=chunk_pre_encode_embs, - preds=spkcache_fifo_chunk_preds, - lc=round(left_offset / self.encoder.subsampling_factor), - rc=math.ceil(right_offset / self.encoder.subsampling_factor), - ) - total_preds = torch.cat([total_preds, chunk_preds], dim=1) - - return streaming_state, total_preds - - def _get_aux_train_evaluations(self, preds, targets, target_lens) -> dict: - """ - Compute auxiliary training evaluations including losses and metrics. - - This function calculates various losses and metrics for the training process, - including Arrival Time Sort (ATS) Loss and Permutation Invariant Loss (PIL) - based evaluations. - - Args: - preds (torch.Tensor): Predicted speaker labels. - Shape: (batch_size, diar_frame_count, num_speakers) - targets (torch.Tensor): Ground truth speaker labels. - Shape: (batch_size, diar_frame_count, num_speakers) - target_lens (torch.Tensor): Lengths of target sequences. - Shape: (batch_size,) - - Returns: - (dict): A dictionary containing the following training metrics. - """ - targets = targets.to(preds.dtype) - if preds.shape[1] < targets.shape[1]: - logging.info( - f"WARNING! preds has less frames than targets ({preds.shape[1]} < {targets.shape[1]}). " - "Truncating targets and clamping target_lens." - ) - targets = targets[:, : preds.shape[1], :] - target_lens = target_lens.clamp(max=preds.shape[1]) - targets_ats = get_ats_targets(targets.clone(), preds, speaker_permutations=self.speaker_permutations) - targets_pil = get_pil_targets(targets.clone(), preds, speaker_permutations=self.speaker_permutations) - ats_loss = self.loss(probs=preds, labels=targets_ats, target_lens=target_lens) - pil_loss = self.loss(probs=preds, labels=targets_pil, target_lens=target_lens) - loss = self.ats_weight * ats_loss + self.pil_weight * pil_loss - - self._accuracy_train(preds, targets_pil, target_lens) - train_f1_acc, train_precision, train_recall = self._accuracy_train.compute() - - self._accuracy_train_ats(preds, targets_ats, target_lens) - train_f1_acc_ats, _, _ = self._accuracy_train_ats.compute() - - train_metrics = { - 'loss': loss, - 'ats_loss': ats_loss, - 'pil_loss': pil_loss, - 'learning_rate': self._optimizer.param_groups[0]['lr'], - 'train_f1_acc': train_f1_acc, - 'train_precision': train_precision, - 'train_recall': train_recall, - 'train_f1_acc_ats': train_f1_acc_ats, - } - return train_metrics - - def training_step(self, batch: list, batch_idx: int) -> dict: - """ - Performs a single training step. - - Args: - batch (list): A list containing the following elements: - - audio_signal (torch.Tensor): The input audio signal in time-series format. - - audio_signal_length (torch.Tensor): The length of each audio signal in the batch. - - targets (torch.Tensor): The target labels for the batch. - - target_lens (torch.Tensor): The length of each target sequence in the batch. - batch_idx (int): The index of the current batch. - - Returns: - (dict): A dictionary containing the 'loss' key with the calculated loss value. - """ - audio_signal, audio_signal_length, targets, target_lens = batch - preds = self.forward(audio_signal=audio_signal, audio_signal_length=audio_signal_length) - train_metrics = self._get_aux_train_evaluations(preds, targets, target_lens) - self._reset_train_metrics() - self.log_dict(train_metrics, sync_dist=True, on_step=True, on_epoch=False, logger=True) - return {'loss': train_metrics['loss']} - - def _get_aux_validation_evaluations(self, preds, targets, target_lens) -> dict: - """ - Compute auxiliary validation evaluations including losses and metrics. - - This function calculates various losses and metrics for the training process, - including Arrival Time Sort (ATS) Loss and Permutation Invariant Loss (PIL) - based evaluations. - - Args: - preds (torch.Tensor): Predicted speaker labels. - Shape: (batch_size, diar_frame_count, num_speakers) - targets (torch.Tensor): Ground truth speaker labels. - Shape: (batch_size, diar_frame_count, num_speakers) - target_lens (torch.Tensor): Lengths of target sequences. - Shape: (batch_size,) - - Returns: - val_metrics (dict): A dictionary containing the following validation metrics - """ - targets = targets.to(preds.dtype) - if preds.shape[1] < targets.shape[1]: - logging.info( - f"WARNING! preds has less frames than targets ({preds.shape[1]} < {targets.shape[1]}). " - "Truncating targets and clamping target_lens." - ) - targets = targets[:, : preds.shape[1], :] - target_lens = target_lens.clamp(max=preds.shape[1]) - targets_ats = get_ats_targets(targets.clone(), preds, speaker_permutations=self.speaker_permutations) - targets_pil = get_pil_targets(targets.clone(), preds, speaker_permutations=self.speaker_permutations) - - val_ats_loss = self.loss(probs=preds, labels=targets_ats, target_lens=target_lens) - val_pil_loss = self.loss(probs=preds, labels=targets_pil, target_lens=target_lens) - val_loss = self.ats_weight * val_ats_loss + self.pil_weight * val_pil_loss - - self._accuracy_valid(preds, targets_pil, target_lens) - val_f1_acc, val_precision, val_recall = self._accuracy_valid.compute() - - self._accuracy_valid_ats(preds, targets_ats, target_lens) - valid_f1_acc_ats, _, _ = self._accuracy_valid_ats.compute() - - self._accuracy_valid.reset() - self._accuracy_valid_ats.reset() - - val_metrics = { - 'val_loss': val_loss, - 'val_ats_loss': val_ats_loss, - 'val_pil_loss': val_pil_loss, - 'val_f1_acc': val_f1_acc, - 'val_precision': val_precision, - 'val_recall': val_recall, - 'val_f1_acc_ats': valid_f1_acc_ats, - } - return val_metrics - - def validation_step(self, batch: list, batch_idx: int, dataloader_idx: int = 0): - """ - Performs a single validation step. - - This method processes a batch of data during the validation phase. It forward passes - the audio signal through the model, computes various validation metrics, and stores - these metrics for later aggregation. - - Args: - batch (list): A list containing the following elements: - - audio_signal (torch.Tensor): The input audio signal. - - audio_signal_length (torch.Tensor): The length of each audio signal in the batch. - - targets (torch.Tensor): The target labels for the batch. - - target_lens (torch.Tensor): The length of each target sequence in the batch. - batch_idx (int): The index of the current batch. - dataloader_idx (int, optional): The index of the dataloader in case of multiple - validation dataloaders. Defaults to 0. - - Returns: - dict: A dictionary containing various validation metrics for this batch. - """ - audio_signal, audio_signal_length, targets, target_lens = batch - preds = self.forward( - audio_signal=audio_signal, - audio_signal_length=audio_signal_length, - ) - val_metrics = self._get_aux_validation_evaluations(preds, targets, target_lens) - if isinstance(self.trainer.val_dataloaders, list) and len(self.trainer.val_dataloaders) > 1: - self.validation_step_outputs[dataloader_idx].append(val_metrics) - else: - self.validation_step_outputs.append(val_metrics) - return val_metrics - - def test_step(self, batch: list, batch_idx: int, dataloader_idx: int = 0): - """ - Performs a single validation step. - - This method processes a batch of data during the validation phase. It forward passes - the audio signal through the model, computes various validation metrics, and stores - these metrics for later aggregation. - - Args: - batch (list): A list containing the following elements: - - audio_signal (torch.Tensor): The input audio signal. - - audio_signal_length (torch.Tensor): The length of each audio signal in the batch. - - targets (torch.Tensor): The target labels for the batch. - - target_lens (torch.Tensor): The length of each target sequence in the batch. - batch_idx (int): The index of the current batch. - dataloader_idx (int, optional): The index of the dataloader in case of multiple - validation dataloaders. Defaults to 0. - - Returns: - dict: A dictionary containing various validation metrics for this batch. - """ - return self.validation_step(batch, batch_idx, dataloader_idx) - - def multi_validation_epoch_end(self, outputs: list, dataloader_idx: int = 0): - if not outputs: - logging.warning(f"`outputs` is None; empty outputs for dataloader={dataloader_idx}") - return None - val_loss_mean = torch.stack([x['val_loss'] for x in outputs]).mean() - val_ats_loss_mean = torch.stack([x['val_ats_loss'] for x in outputs]).mean() - val_pil_loss_mean = torch.stack([x['val_pil_loss'] for x in outputs]).mean() - val_f1_acc_mean = torch.stack([x['val_f1_acc'] for x in outputs]).mean() - val_precision_mean = torch.stack([x['val_precision'] for x in outputs]).mean() - val_recall_mean = torch.stack([x['val_recall'] for x in outputs]).mean() - val_f1_acc_ats_mean = torch.stack([x['val_f1_acc_ats'] for x in outputs]).mean() - - self._reset_valid_metrics() - - multi_val_metrics = { - 'val_loss': val_loss_mean, - 'val_ats_loss': val_ats_loss_mean, - 'val_pil_loss': val_pil_loss_mean, - 'val_f1_acc': val_f1_acc_mean, - 'val_precision': val_precision_mean, - 'val_recall': val_recall_mean, - 'val_f1_acc_ats': val_f1_acc_ats_mean, - } - return {'log': multi_val_metrics} - - def _get_aux_test_batch_evaluations(self, batch_idx: int, preds, targets, target_lens): - """ - Compute auxiliary validation evaluations including losses and metrics. - - This function calculates various losses and metrics for the training process, - including Arrival Time Sort (ATS) Loss and Permutation Invariant Loss (PIL) - based evaluations. - - Args: - preds (torch.Tensor): Predicted speaker labels. - Shape: (batch_size, diar_frame_count, num_speakers) - targets (torch.Tensor): Ground truth speaker labels. - Shape: (batch_size, diar_frame_count, num_speakers) - target_lens (torch.Tensor): Lengths of target sequences. - Shape: (batch_size,) - """ - targets = targets.to(preds.dtype) - if preds.shape[1] < targets.shape[1]: - logging.info( - f"WARNING! preds has less frames than targets ({preds.shape[1]} < {targets.shape[1]}). " - "Truncating targets and clamping target_lens." - ) - targets = targets[:, : preds.shape[1], :] - target_lens = target_lens.clamp(max=preds.shape[1]) - targets_ats = get_ats_targets(targets.clone(), preds, speaker_permutations=self.speaker_permutations) - targets_pil = get_pil_targets(targets.clone(), preds, speaker_permutations=self.speaker_permutations) - self._accuracy_test(preds, targets_pil, target_lens) - f1_acc, precision, recall = self._accuracy_test.compute() - self.batch_f1_accs_list.append(f1_acc) - self.batch_precision_list.append(precision) - self.batch_recall_list.append(recall) - logging.info(f"batch {batch_idx}: f1_acc={f1_acc}, precision={precision}, recall={recall}") - - self._accuracy_test_ats(preds, targets_ats, target_lens) - f1_acc_ats, precision_ats, recall_ats = self._accuracy_test_ats.compute() - self.batch_f1_accs_ats_list.append(f1_acc_ats) - logging.info( - f"batch {batch_idx}: f1_acc_ats={f1_acc_ats}, precision_ats={precision_ats}, recall_ats={recall_ats}" - ) - - self._accuracy_test.reset() - self._accuracy_test_ats.reset() - - def test_batch( - self, - ): - """ - Perform batch testing on the model. - - This method iterates through the test data loader, making predictions for each batch, - and calculates various evaluation metrics. It handles both single and multi-sample batches. - """ - ( - self.preds_total_list, - self.batch_f1_accs_list, - self.batch_precision_list, - self.batch_recall_list, - self.batch_f1_accs_ats_list, - ) = ([], [], [], [], []) - - with torch.no_grad(): - for batch_idx, batch in enumerate(tqdm(self._test_dl)): - audio_signal, audio_signal_length, targets, target_lens = batch - audio_signal = audio_signal.to(self.device) - audio_signal_length = audio_signal_length.to(self.device) - targets = targets.to(self.device) - preds = self.forward( - audio_signal=audio_signal, - audio_signal_length=audio_signal_length, - ) - self._get_aux_test_batch_evaluations(batch_idx, preds, targets, target_lens) - preds = preds.detach().to('cpu') - if preds.shape[0] == 1: # batch size = 1 - self.preds_total_list.append(preds) - else: - self.preds_total_list.extend(torch.split(preds, [1] * preds.shape[0])) - torch.cuda.empty_cache() - - logging.info(f"Batch F1Acc. MEAN: {torch.mean(torch.tensor(self.batch_f1_accs_list))}") - logging.info(f"Batch Precision MEAN: {torch.mean(torch.tensor(self.batch_precision_list))}") - logging.info(f"Batch Recall MEAN: {torch.mean(torch.tensor(self.batch_recall_list))}") - logging.info(f"Batch ATS F1Acc. MEAN: {torch.mean(torch.tensor(self.batch_f1_accs_ats_list))}") - - def on_validation_epoch_end(self) -> Optional[dict[str, dict[str, torch.Tensor]]]: - """Run validation with sync_dist=True.""" - return super().on_validation_epoch_end(sync_metrics=True) - - @torch.no_grad() - def diarize( - self, - audio: Union[str, List[str], np.ndarray, DataLoader], - sample_rate: Optional[int] = None, - batch_size: int = 1, - include_tensor_outputs: bool = False, - postprocessing_yaml: Optional[str] = None, - num_workers: int = 0, - verbose: bool = True, - override_config: Optional[DiarizeConfig] = None, - ) -> Union[List[List[str]], Tuple[List[List[str]], List[torch.Tensor]]]: - """One-click runner function for diarization. - - Args: - audio: (a single or list) of paths to audio files or path to a manifest file. - batch_size: (int) Batch size to use during inference. - Bigger will result in better throughput performance but would use more memory. - include_tensor_outputs: (bool) Include raw speaker activity probabilities to the output. - See Returns: for more details. - postprocessing_yaml: Optional(str) Path to .yaml file with postprocessing parameters. - num_workers: (int) Number of workers for DataLoader. - verbose: (bool) Whether to display tqdm progress bar. - override_config: (Optional[DiarizeConfig]) A config to override the default config. - - Returns: - If include_tensor_outputs is False: A list of lists of speech segments with a corresponding speaker index, - in format "[begin_seconds, end_seconds, speaker_index]". - If include_tensor_outputs is True: A tuple of the above list - and list of tensors of raw speaker activity probabilities. - """ - return super().diarize( - audio=audio, - sample_rate=sample_rate, - batch_size=batch_size, - include_tensor_outputs=include_tensor_outputs, - postprocessing_yaml=postprocessing_yaml, - num_workers=num_workers, - verbose=verbose, - override_config=override_config, - ) diff --git a/nemo/collections/asr/models/ssl_models.py b/nemo/collections/asr/models/ssl_models.py deleted file mode 100644 index 6e149c3c17b82d19ed781864262b805c0e99e0ae..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/ssl_models.py +++ /dev/null @@ -1,1058 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from math import ceil -from typing import Any, Dict, List, Optional, Union - -import torch -import torch.nn as nn -from lightning.pytorch import Trainer -from omegaconf import DictConfig - -from nemo.collections.asr.data import audio_to_text_dataset, ssl_dataset -from nemo.collections.asr.data.audio_to_text_dali import DALIOutputs -from nemo.collections.asr.data.audio_to_text_lhotse import LhotseSpeechToTextBpeDataset -from nemo.collections.asr.modules.ssl_modules.masking import ConvFeatureMaksingWrapper -from nemo.collections.asr.parts.mixins import ASRModuleMixin -from nemo.collections.asr.parts.preprocessing.perturb import process_augmentations -from nemo.collections.common.data.lhotse import get_lhotse_dataloader_from_config -from nemo.collections.common.data.utils import move_data_to_device -from nemo.collections.common.parts.preprocessing.parsers import make_parser -from nemo.core.classes import ModelPT -from nemo.core.classes.common import PretrainedModelInfo, typecheck -from nemo.core.classes.mixins import AccessMixin, set_access_cfg -from nemo.core.neural_types import ( - AcousticEncodedRepresentation, - AudioSignal, - LabelsType, - LengthsType, - LogprobsType, - NeuralType, - SpectrogramType, -) -from nemo.utils import logging - -__all__ = ['SpeechEncDecSelfSupervisedModel', 'EncDecMaskedTokenPredModel', 'EncDecDenoiseMaskedTokenPredModel'] - - -class SpeechEncDecSelfSupervisedModel(ModelPT, ASRModuleMixin, AccessMixin): - """Base class for encoder-decoder models used for self-supervised encoder pre-training""" - - @classmethod - def list_available_models(cls) -> List[PretrainedModelInfo]: - """ - This method returns a list of pre-trained model which can be instantiated directly from NVIDIA's NGC cloud. - - Returns: - List of available pre-trained models. - """ - results = [] - - model = PretrainedModelInfo( - pretrained_model_name="ssl_en_conformer_large", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:ssl_en_conformer_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/ssl_en_conformer_large/versions/1.10.1/files/ssl_en_conformer_large.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="ssl_en_conformer_xlarge", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:ssl_en_conformer_xlarge", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/ssl_en_conformer_xlarge/versions/1.10.0/files/ssl_en_conformer_xlarge.nemo", - ) - results.append(model) - - return results - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - # Get global rank and total number of GPU workers for IterableDataset partitioning, if applicable - # Global_rank and local_rank is set by LightningModule in Lightning 1.2.0 - self.world_size = 1 - if trainer is not None: - self.world_size = trainer.world_size - - super().__init__(cfg=cfg, trainer=trainer) - self.preprocessor = SpeechEncDecSelfSupervisedModel.from_config_dict(self._cfg.preprocessor) - self.encoder = SpeechEncDecSelfSupervisedModel.from_config_dict(self._cfg.encoder) - - self.decoder_losses = None - - if "loss_list" in self._cfg: - - self.decoder_losses = {} - self.loss_alphas = {} - self.start_step = {} - self.output_from_layer = {} - self.transpose_encoded = {} - self.targets_from_loss = {} - self.decoder_losses_active = {} - # need to be separate for moduledict - - for decoder_loss_name, decoder_loss_cfg in self._cfg.loss_list.items(): - if not decoder_loss_cfg.get("is_active", True): # active by default - continue - - new_decoder_loss = { - 'decoder': SpeechEncDecSelfSupervisedModel.from_config_dict(decoder_loss_cfg.decoder), - 'loss': SpeechEncDecSelfSupervisedModel.from_config_dict(decoder_loss_cfg.loss), - } - new_decoder_loss = nn.ModuleDict(new_decoder_loss) - self.decoder_losses[decoder_loss_name] = new_decoder_loss - self.loss_alphas[decoder_loss_name] = decoder_loss_cfg.get("loss_alpha", 1.0) - self.output_from_layer[decoder_loss_name] = decoder_loss_cfg.get("output_from_layer", None) - self.targets_from_loss[decoder_loss_name] = decoder_loss_cfg.get("targets_from_loss", None) - self.start_step[decoder_loss_name] = decoder_loss_cfg.get("start_step", 0) - self.transpose_encoded[decoder_loss_name] = decoder_loss_cfg.get("transpose_encoded", False) - self.decoder_losses_active[decoder_loss_name] = True - - self.decoder_losses = nn.ModuleDict(self.decoder_losses) - - else: - self.decoder_ssl = SpeechEncDecSelfSupervisedModel.from_config_dict(self._cfg.decoder) - self.loss = SpeechEncDecSelfSupervisedModel.from_config_dict(self._cfg.loss) - - self.spec_augmentation = SpeechEncDecSelfSupervisedModel.from_config_dict(self._cfg.spec_augment) - - # dropout for features/spectrograms (applied before masking) - self.dropout_features = ( - torch.nn.Dropout(self._cfg.dropout_features) if "dropout_features" in self._cfg else None - ) - - # dropout for targets (applied before quantization) - self.dropout_features_q = ( - torch.nn.Dropout(self._cfg.dropout_features_q) if "dropout_features_q" in self._cfg else None - ) - - # Feature penalty for preprocessor encodings (for Wav2Vec training) - if "feature_penalty" in self._cfg: - self.feat_pen, self.pen_factor = 0.0, self._cfg.feature_penalty - else: - self.feat_pen, self.pen_factor = None, None - - if "access" in self._cfg: - set_access_cfg(self._cfg.access, self.model_guid) - - self.apply_masking = True - - def _setup_dataloader_from_config(self, config: Optional[Dict]): - if 'augmentor' in config: - augmentor = process_augmentations(config['augmentor']) - else: - augmentor = None - - # Automatically inject args from model config to dataloader config - audio_to_text_dataset.inject_dataloader_value_from_model_config(self.cfg, config, key='sample_rate') - - if config.get("use_lhotse"): - return get_lhotse_dataloader_from_config( - config, - global_rank=self.global_rank, - world_size=self.world_size, - dataset=LhotseSpeechToTextBpeDataset( - tokenizer=make_parser( - labels=config.get('labels', None), - name=config.get('parser', 'en'), - unk_id=config.get('unk_index', -1), - blank_id=config.get('blank_index', -1), - do_normalize=config.get('normalize_transcripts', False), - ), - ), - ) - - shuffle = config['shuffle'] - device = 'gpu' if torch.cuda.is_available() else 'cpu' - if config.get('use_dali', False): - device_id = self.local_rank if device == 'gpu' else None - dataset = audio_to_text_dataset.get_dali_char_dataset( - config=config, - shuffle=shuffle, - device_id=device_id, - global_rank=self.global_rank, - world_size=self.world_size, - preprocessor_cfg=self._cfg.preprocessor, - ) - return dataset - - # Instantiate tarred dataset loader or normal dataset loader - if config.get('is_tarred', False): - if ('tarred_audio_filepaths' in config and config['tarred_audio_filepaths'] is None) or ( - 'manifest_filepath' in config and config['manifest_filepath'] is None - ): - logging.warning( - "Could not load dataset as `manifest_filepath` was None or " - f"`tarred_audio_filepaths` is None. Provided config : {config}" - ) - return None - - shuffle_n = config.get('shuffle_n', 4 * config['batch_size']) if shuffle else 0 - dataset = audio_to_text_dataset.get_tarred_dataset( - config=config, - shuffle_n=shuffle_n, - global_rank=self.global_rank, - world_size=self.world_size, - augmentor=augmentor, - ) - shuffle = False - else: - if 'manifest_filepath' in config and config['manifest_filepath'] is None: - logging.warning(f"Could not load dataset as `manifest_filepath` was None. Provided config : {config}") - return None - - dataset = audio_to_text_dataset.get_char_dataset(config=config, augmentor=augmentor) - - if hasattr(dataset, 'collate_fn'): - collate_fn = dataset.collate_fn - elif hasattr(dataset.datasets[0], 'collate_fn'): - # support datasets that are lists of entries - collate_fn = dataset.datasets[0].collate_fn - else: - # support datasets that are lists of lists - collate_fn = dataset.datasets[0].datasets[0].collate_fn - - return torch.utils.data.DataLoader( - dataset=dataset, - batch_size=config['batch_size'], - collate_fn=collate_fn, - drop_last=config.get('drop_last', False), - shuffle=shuffle, - num_workers=config.get('num_workers', 0), - pin_memory=config.get('pin_memory', False), - ) - - def setup_training_data(self, train_data_config: Optional[Union[DictConfig, Dict]]): - """ - Sets up the training data loader via a Dict-like object. - - Args: - train_data_config: A config that contains the information regarding construction - of an ASR Training dataset. - - Supported Datasets: - - :class:`~nemo.collections.asr.data.audio_to_text.AudioToCharDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.AudioToBPEDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.TarredAudioToCharDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.TarredAudioToBPEDataset` - - :class:`~nemo.collections.asr.data.audio_to_text_dali.AudioToCharDALIDataset` - """ - if 'shuffle' not in train_data_config: - train_data_config['shuffle'] = True - - # preserve config - self._update_dataset_config(dataset_name='train', config=train_data_config) - - self._train_dl = self._setup_dataloader_from_config(config=train_data_config) - - # Need to set this because if using an IterableDataset, the length of the dataloader is the total number - # of samples rather than the number of batches, and this messes up the tqdm progress bar. - # So we set the number of steps manually (to the correct number) to fix this. - if ( - self._train_dl is not None - and hasattr(self._train_dl, 'dataset') - and isinstance(self._train_dl.dataset, torch.utils.data.IterableDataset) - ): - # We also need to check if limit_train_batches is already set. - # If it's an int, we assume that the user has set it to something sane, i.e. <= # training batches, - # and don't change it. Otherwise, adjust batches accordingly if it's a float (including 1.0). - if self._trainer is not None and isinstance(self._trainer.limit_train_batches, float): - self._trainer.limit_train_batches = int( - self._trainer.limit_train_batches - * ceil((len(self._train_dl.dataset) / self.world_size) / train_data_config['batch_size']) - ) - elif self._trainer is None: - logging.warning( - "Model Trainer was not set before constructing the dataset, incorrect number of " - "training batches will be used. Please set the trainer and rebuild the dataset." - ) - - def setup_validation_data(self, val_data_config: Optional[Union[DictConfig, Dict]]): - """ - Sets up the validation data loader via a Dict-like object. - - Args: - val_data_config: A config that contains the information regarding construction - of an ASR Training dataset. - - Supported Datasets: - - :class:`~nemo.collections.asr.data.audio_to_text.AudioToCharDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.AudioToBPEDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.TarredAudioToCharDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.TarredAudioToBPEDataset` - - :class:`~nemo.collections.asr.data.audio_to_text_dali.AudioToCharDALIDataset` - """ - if 'shuffle' not in val_data_config: - val_data_config['shuffle'] = False - - # preserve config - self._update_dataset_config(dataset_name='validation', config=val_data_config) - - self._validation_dl = self._setup_dataloader_from_config(config=val_data_config) - - # Need to set this because if using an IterableDataset, the length of the dataloader is the total number - # of samples rather than the number of batches, and this messes up the tqdm progress bar. - # So we set the number of steps manually (to the correct number) to fix this. - if ( - self._validation_dl is not None - and hasattr(self._validation_dl, 'dataset') - and isinstance(self._validation_dl.dataset, torch.utils.data.IterableDataset) - ): - # We also need to check if limit_train_batches is already set. - # If it's an int, we assume that the user has set it to something sane, i.e. <= # training batches, - # and don't change it. Otherwise, adjust batches accordingly if it's a float (including 1.0). - if isinstance(self._trainer.limit_val_batches, float): - self._trainer.limit_val_batches = int( - self._trainer.limit_val_batches - * ceil((len(self._validation_dl.dataset) / self.world_size) / val_data_config['batch_size']) - ) - - @property - def input_types(self) -> Optional[Dict[str, NeuralType]]: - if hasattr(self.preprocessor, '_sample_rate'): - input_signal_eltype = AudioSignal(freq=self.preprocessor._sample_rate) - else: - input_signal_eltype = AudioSignal() - return { - "input_signal": NeuralType(('B', 'T'), input_signal_eltype, optional=True), - "input_signal_length": NeuralType(tuple('B'), LengthsType(), optional=True), - "processed_signal": NeuralType(('B', 'D', 'T'), SpectrogramType(), optional=True), - "processed_signal_length": NeuralType(tuple('B'), LengthsType(), optional=True), - "targets": NeuralType(('B', 'T'), LabelsType(), optional=True), - "target_lengths": NeuralType(tuple('B'), LengthsType(), optional=True), - } - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - return { - "spectrograms": NeuralType(('B', 'D', 'T'), SpectrogramType()), - "spec_masks": NeuralType(('B', 'D', 'T'), SpectrogramType()), - "encoded": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), - "encoded_len": NeuralType(tuple('B'), LengthsType()), - } - - @typecheck() - def forward( - self, - input_signal=None, - input_signal_length=None, - processed_signal=None, - processed_signal_length=None, - ): - """ - Forward pass of the model. - - Args: - input_signal: Tensor that represents a batch of raw audio signals, - of shape [B, T]. T here represents timesteps, with 1 second of audio represented as - `self.sample_rate` number of floating point values. - input_signal_length: Vector of length B, that contains the individual lengths of the audio - sequences. - processed_signal: Tensor that represents a batch of processed audio signals, - of shape (B, D, T) that has undergone processing via some DALI preprocessor. - processed_signal_length: Vector of length B, that contains the individual lengths of the - processed audio sequences. - - Returns: - A tuple of 4 elements - - 1) Processed spectrograms of shape [B, D, T]. - 2) Masks applied to spectrograms of shape [B, D, T]. - 3) The encoded features tensor of shape [B, D, T]. - 2) The lengths of the acoustic sequence after propagation through the encoder, of shape [B]. - """ - # Reset access registry - if self.is_access_enabled(self.model_guid): - self.reset_registry() - - # Check for special flag for validation step - if hasattr(self, '_in_validation_step'): - in_validation_step = self._in_validation_step - else: - in_validation_step = False - - # reset module registry from AccessMixin - if ( - (self.training or in_validation_step) - and self.decoder_losses is not None - and self.output_from_layer is not None - and len(self.output_from_layer) > 0 - ): - layer_names = list(self.output_from_layer.values()) - register_layer = any([name is not None for name in layer_names]) - - if register_layer: - self.access_cfg['save_encoder_tensors'] = True - self.set_access_enabled(access_enabled=True, guid=self.model_guid) - - has_input_signal = input_signal is not None and input_signal_length is not None - has_processed_signal = processed_signal is not None and processed_signal_length is not None - if (has_input_signal ^ has_processed_signal) == False: - raise ValueError( - f"{self} Arguments ``input_signal`` and ``input_signal_length`` are mutually exclusive " - " with ``processed_signal`` and ``processed_signal_len`` arguments." - ) - - if not has_processed_signal: - processed_signal, processed_signal_length = self.preprocessor( - input_signal=input_signal, - length=input_signal_length, - ) - - if self.pen_factor: - self.feat_pen = processed_signal.float().pow(2).mean() * self.pen_factor - spectrograms = processed_signal.detach().clone() - - if self.dropout_features: - processed_signal = self.dropout_features(processed_signal) - if self.dropout_features_q: - spectrograms = self.dropout_features_q(spectrograms) - - if self.apply_masking: - processed_signal = self.spec_augmentation(input_spec=processed_signal, length=processed_signal_length) - - masked_spectrograms = processed_signal.detach() - spec_masks = torch.logical_and(masked_spectrograms < 1e-5, masked_spectrograms > -1e-5).float() - for idx, proc_len in enumerate(processed_signal_length): - spec_masks[idx, :, proc_len:] = 0.0 - - encoded, encoded_len = self.encoder(audio_signal=processed_signal, length=processed_signal_length) - - return spectrograms, spec_masks, encoded, encoded_len - - def decoder_loss_step(self, spectrograms, spec_masks, encoded, encoded_len, targets=None, target_lengths=None): - """ - Forward pass through all decoders and calculate corresponding losses. - Args: - spectrograms: Processed spectrograms of shape [B, D, T]. - spec_masks: Masks applied to spectrograms of shape [B, D, T]. - encoded: The encoded features tensor of shape [B, D, T]. - encoded_len: The lengths of the acoustic sequence after propagation through the encoder, of shape [B]. - targets: Optional target labels of shape [B, T] - target_lengths: Optional target label lengths of shape [B] - - Returns: - A tuple of 2 elements - - 1) Total sum of losses weighted by corresponding loss_alphas - 2) Dictionary of unweighted losses - """ - loss_val_dict = {} - - if self.decoder_losses is None: - if hasattr(self.decoder_ssl, "needs_labels") and self.decoder_ssl.needs_labels: - outputs = self.decoder_ssl(encoder_output=encoded, targets=targets, target_lengths=target_lengths) - else: - outputs = self.decoder_ssl(encoder_output=encoded) - if self.loss.needs_labels: - loss_value = self.loss( - spec_masks=spec_masks, - decoder_outputs=outputs, - targets=targets, - decoder_lengths=encoded_len, - target_lengths=target_lengths, - ) - else: - loss_value = self.loss(spectrograms=spectrograms, spec_masks=spec_masks, decoder_outputs=outputs) - else: - - loss_value = encoded.new_zeros(1) - outputs = {} - registry = self.get_module_registry(self.encoder) - - for dec_loss_name, dec_loss in self.decoder_losses.items(): - # loop through decoders and corresponding losses - if not self.decoder_losses_active[dec_loss_name]: - continue - - if self.output_from_layer[dec_loss_name] is None: - dec_input = encoded - else: - # extract output from specified layer using AccessMixin registry - dec_input = registry[self.output_from_layer[dec_loss_name]]['encoder'][-1] - if self.transpose_encoded[dec_loss_name]: - dec_input = dec_input.transpose(-2, -1) - - if self.targets_from_loss[dec_loss_name] is not None: - # extract targets from specified loss - target_loss = self.targets_from_loss[dec_loss_name] - targets = self.decoder_losses[target_loss]['loss'].target_ids - target_lengths = self.decoder_losses[target_loss]['loss'].target_lengths - if target_lengths is None: - target_lengths = encoded_len - - if hasattr(dec_loss['decoder'], "needs_labels") and dec_loss['decoder'].needs_labels: - # if we are using a decoder which needs labels, provide them - outputs[dec_loss_name] = dec_loss['decoder']( - encoder_output=dec_input, targets=targets, target_lengths=target_lengths - ) - else: - outputs[dec_loss_name] = dec_loss['decoder'](encoder_output=dec_input) - - current_loss = dec_loss['loss'] - if current_loss.needs_labels: - # if we are using a loss which needs labels, provide them - current_loss_value = current_loss( - spec_masks=spec_masks, - decoder_outputs=outputs[dec_loss_name], - targets=targets, - decoder_lengths=encoded_len, - target_lengths=target_lengths, - ) - else: - current_loss_value = current_loss( - spectrograms=spectrograms, - spec_masks=spec_masks, - decoder_outputs=outputs[dec_loss_name], - decoder_lengths=encoded_len, - ) - loss_value = loss_value + current_loss_value * self.loss_alphas[dec_loss_name] - loss_val_dict[dec_loss_name] = current_loss_value - - return loss_value, loss_val_dict - - # PTL-specific methods - def training_step(self, batch, batch_nb): - signal, signal_len, targets, target_lengths = batch - if isinstance(batch, DALIOutputs) and batch.has_processed_signal: - spectrograms, spec_masks, encoded, encoded_len = self.forward( - processed_signal=signal, - processed_signal_length=signal_len, - ) - else: - spectrograms, spec_masks, encoded, encoded_len = self.forward( - input_signal=signal, - input_signal_length=signal_len, - ) - - if self.decoder_losses is not None: - for dec_loss_name, dec_loss in self.decoder_losses.items(): - self.decoder_losses_active[dec_loss_name] = self.trainer.global_step >= self.start_step[dec_loss_name] - loss = dec_loss['loss'] - if hasattr(loss, "set_num_updates"): - loss.set_num_updates(self.trainer.global_step) - else: - if hasattr(self.loss, "set_num_updates"): - self.loss.set_num_updates(self.trainer.global_step) - - loss_value, loss_val_dict = self.decoder_loss_step( - spectrograms, spec_masks, encoded, encoded_len, targets, target_lengths - ) - - tensorboard_logs = { - 'learning_rate': self._optimizer.param_groups[0]['lr'], - 'global_step': self.trainer.global_step, - } - - for loss_name, loss_val in loss_val_dict.items(): - tensorboard_logs['train_' + loss_name] = loss_val - - if self.feat_pen: - loss_value += self.feat_pen - - # Reset access registry - self.reset_registry() - - return {'loss': loss_value, 'log': tensorboard_logs} - - def validation_pass(self, batch, batch_idx, dataloader_idx=0): - # Set flag to register tensors - self._in_validation_step = True - - signal, signal_len, targets, target_lengths = batch - if isinstance(batch, DALIOutputs) and batch.has_processed_signal: - spectrograms, spec_masks, encoded, encoded_len = self.forward( - processed_signal=signal, - processed_signal_length=signal_len, - ) - else: - spectrograms, spec_masks, encoded, encoded_len = self.forward( - input_signal=signal, - input_signal_length=signal_len, - ) - - if self.decoder_losses is not None: - for dec_loss_name, dec_loss in self.decoder_losses.items(): - self.decoder_losses_active[dec_loss_name] = self.trainer.global_step >= self.start_step[dec_loss_name] - - loss_value, _ = self.decoder_loss_step(spectrograms, spec_masks, encoded, encoded_len, targets, target_lengths) - - if self.feat_pen: - loss_value += self.feat_pen - - # reset access registry - self.reset_registry() - del self._in_validation_step - - metrics = {'val_loss': loss_value} - - return metrics - - def validation_step(self, batch, batch_idx, dataloader_idx=0): - metrics = self.validation_pass(batch, batch_idx, dataloader_idx) - if type(self.trainer.val_dataloaders) == list and len(self.trainer.val_dataloaders) > 1: - self.validation_step_outputs[dataloader_idx].append(metrics) - else: - self.validation_step_outputs.append(metrics) - return metrics - - def multi_validation_epoch_end(self, outputs, dataloader_idx: int = 0): - val_loss_mean = torch.stack([x['val_loss'] for x in outputs]).mean() - tensorboard_logs = {'val_loss': val_loss_mean} - return {'val_loss': val_loss_mean, 'log': tensorboard_logs} - - -class EncDecMaskedTokenPredModel(SpeechEncDecSelfSupervisedModel): - """ - Speech self-supervised model that performs masked token prediction on the encoder output. - """ - - def transfer_batch_to_device(self, batch: Any, device: torch.device, dataloader_idx: int) -> Any: - """ - PTL hook: https://pytorch-lightning.readthedocs.io/en/latest/common/lightning_module.html#transfer-batch-to-device - """ - batch = move_data_to_device(batch, device) - return batch - - @classmethod - def list_available_models(cls) -> List[PretrainedModelInfo]: - """ - This method returns a list of pre-trained model which can be instantiated directly from NVIDIA's NGC cloud. - - Returns: - List of available pre-trained models. - """ - results = [] - return results - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - super().__init__(cfg, trainer) - del self.decoder_ssl # delete unused decoder from parent class - - if self.cfg.get("mask_position", "pre_conv") == "post_conv": - # adjust config for post-convolution masking - self.cfg.quantizer.feat_in = self.cfg.encoder.d_model - self.cfg.masking.feat_in = self.cfg.encoder.d_model - self.cfg.masking.block_size = self.cfg.masking.block_size // self.cfg.encoder.subsampling_factor - self.cfg.loss.combine_time_steps = 1 - - self.quantizer = self.from_config_dict(self.cfg.quantizer) - self.mask_processor = self.from_config_dict(self.cfg.masking) - self.encoder = self.from_config_dict(self.cfg.encoder) - self.decoder = self.from_config_dict(self.cfg.decoder) - self.loss = self.from_config_dict(self.cfg.loss) - - self.pre_encoder = None - if self.cfg.get("mask_position", "pre_conv") == "post_conv": - # hacked to mask features after convolutional sub-sampling - self.pre_encoder = ConvFeatureMaksingWrapper(self.encoder.pre_encode, self.mask_processor) - self.encoder.pre_encode = self.pre_encoder - - @property - def oomptimizer_schema(self) -> dict: - """ - Return a typing schema for optimal batch size calibration for various - sequence lengths using OOMptimizer. - """ - return { - "cls": tuple, - "inputs": [ - {"type": NeuralType(("B", "T"), AudioSignal()), "seq_length": "input"}, - {"type": NeuralType(("B",), LengthsType()), "seq_length": "input"}, - ], - } - - @property - def input_types(self) -> Optional[Dict[str, NeuralType]]: - if hasattr(self.preprocessor, '_sample_rate'): - input_signal_eltype = AudioSignal(freq=self.preprocessor._sample_rate) - else: - input_signal_eltype = AudioSignal() - return { - "input_signal": NeuralType(('B', 'T'), input_signal_eltype, optional=True), - "input_signal_length": NeuralType(tuple('B'), LengthsType(), optional=True), - "processed_signal": NeuralType(('B', 'D', 'T'), SpectrogramType(), optional=True), - "processed_signal_length": NeuralType(tuple('B'), LengthsType(), optional=True), - "apply_mask": NeuralType(optional=True), - } - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - if self.cfg.num_books == 1 and self.cfg.squeeze_single: - logprobs = NeuralType(('B', 'T', 'C'), LogprobsType()) - tokens = NeuralType(('B', 'T'), LabelsType()) - else: - logprobs = NeuralType(('B', 'T', 'C', 'H'), LogprobsType()) - tokens = NeuralType(('B', 'T', 'H'), LabelsType()) - return { - "logprobs": logprobs, - "encoded_len": NeuralType(tuple('B'), LengthsType()), - "masks": NeuralType(('B', 'D', 'T'), SpectrogramType()), - "tokens": tokens, - } - - @typecheck() - def forward( - self, - input_signal=None, - input_signal_length=None, - processed_signal=None, - processed_signal_length=None, - apply_mask=False, - ): - has_input_signal = input_signal is not None and input_signal_length is not None - has_processed_signal = processed_signal is not None and processed_signal_length is not None - if (has_input_signal ^ has_processed_signal) == False: - raise ValueError( - f"{self} Arguments ``input_signal`` and ``input_signal_length`` are mutually exclusive " - " with ``processed_signal`` and ``processed_signal_len`` arguments." - ) - - if not has_processed_signal: - processed_signal, processed_signal_length = self.preprocessor( - input_signal=input_signal, - length=input_signal_length, - ) - - if self.pre_encoder is not None: - # mask after convolutional sub-sampling - self.pre_encoder.set_masking_enabled(apply_mask=apply_mask) - encoded, encoded_len = self.encoder(audio_signal=processed_signal, length=processed_signal_length) - masks = self.pre_encoder.get_current_mask() - feats = self.pre_encoder.get_current_feat() - _, tokens = self.quantizer(input_signal=feats.transpose(1, 2)) - else: - _, tokens = self.quantizer(input_signal=processed_signal) - if apply_mask: - masked_signal, masks = self.mask_processor( - input_feats=processed_signal, input_lengths=processed_signal_length - ) - else: - masked_signal = processed_signal - masks = torch.zeros_like(processed_signal) - encoded, encoded_len = self.encoder(audio_signal=masked_signal, length=processed_signal_length) - - log_probs = self.decoder(encoder_output=encoded) - - return log_probs, encoded_len, masks, tokens - - def training_step(self, batch, batch_idx=0): - input_signal, input_signal_length = batch[0], batch[1] - if isinstance(batch, DALIOutputs) and batch.has_processed_signal: - log_probs, encoded_len, masks, tokens = self.forward( - processed_signal=input_signal, processed_signal_length=input_signal_length, apply_mask=True - ) - else: - log_probs, encoded_len, masks, tokens = self.forward( - input_signal=input_signal, input_signal_length=input_signal_length, apply_mask=True - ) - - loss_value = self.loss(masks=masks, decoder_outputs=log_probs, targets=tokens, decoder_lengths=encoded_len) - - tensorboard_logs = { - 'learning_rate': self._optimizer.param_groups[0]['lr'], - 'global_step': self.trainer.global_step, - 'train_loss': loss_value, - } - - return {'loss': loss_value, 'log': tensorboard_logs} - - def inference_pass(self, batch, batch_idx=0, dataloader_idx=0, mode='val', apply_mask=False): - input_signal, input_signal_length = batch[0], batch[1] - if isinstance(batch, DALIOutputs) and batch.has_processed_signal: - log_probs, encoded_len, masks, tokens = self.forward( - processed_signal=input_signal, processed_signal_length=input_signal_length, apply_mask=apply_mask - ) - else: - log_probs, encoded_len, masks, tokens = self.forward( - input_signal=input_signal, input_signal_length=input_signal_length, apply_mask=apply_mask - ) - - loss_value = self.loss(masks=masks, decoder_outputs=log_probs, targets=tokens, decoder_lengths=encoded_len) - - return {f'{mode}_loss': loss_value} - - def validation_step(self, batch, batch_idx=0, dataloader_idx=0): - metrics = self.inference_pass(batch, batch_idx, dataloader_idx, apply_mask=True) - if type(self.trainer.val_dataloaders) == list and len(self.trainer.val_dataloaders) > 1: - self.validation_step_outputs[dataloader_idx].append(metrics) - else: - self.validation_step_outputs.append(metrics) - return metrics - - def test_step(self, batch, batch_idx=0, dataloader_idx=0): - metrics = self.inference_pass(batch, batch_idx, dataloader_idx, mode="test", apply_mask=True) - if type(self.trainer.val_dataloaders) == list and len(self.trainer.val_dataloaders) > 1: - self.validation_step_outputs[dataloader_idx].append(metrics) - else: - self.validation_step_outputs.append(metrics) - return metrics - - def multi_validation_epoch_end(self, outputs: list, dataloader_idx: int = 0): - loss_list = [] - for i, x in enumerate(outputs): - if not isinstance(x, dict): - logging.warning(f'Batch {i} output in validation dataloader {dataloader_idx} is not a dictionary: {x}') - if 'val_loss' in x: - loss_list.append(x['val_loss']) - else: - logging.warning( - f'Batch {i} output in validation dataloader {dataloader_idx} does not have key `val_loss`: {x}' - ) - - if len(loss_list) == 0: - logging.warning( - f'Epoch {self.current_epoch} received no batches for validation dataloader {dataloader_idx}.' - ) - return {} - - val_loss_mean = torch.stack(loss_list).mean() - tensorboard_logs = {'val_loss': val_loss_mean} - return {'val_loss': val_loss_mean, 'log': tensorboard_logs} - - def multi_test_epoch_end(self, outputs, dataloader_idx: int = 0): - test_loss_mean = torch.stack([x['test_loss'] for x in outputs]).mean() - tensorboard_logs = {'test_loss': test_loss_mean} - return {'test_loss': test_loss_mean, 'log': tensorboard_logs} - - -class EncDecDenoiseMaskedTokenPredModel(EncDecMaskedTokenPredModel): - """ - Model class that performs denoising and masked token prediction for speech self-supervised learning. - Please refer to the NEST paper for more details: https://arxiv.org/abs/2408.13106 - """ - - @property - def oomptimizer_schema(self) -> dict: - """ - Return a typing schema for optimal batch size calibration for various - sequence lengths using OOMptimizer. - """ - return { - "cls": ssl_dataset.AudioNoiseBatch, - "inputs": [ - {"type": NeuralType(("B", "T"), AudioSignal()), "seq_length": "input", "name": "audio"}, - {"type": NeuralType(("B",), LengthsType()), "seq_length": "input", "name": "audio_len"}, - {"type": NeuralType(("B", "T"), AudioSignal()), "seq_length": "input", "name": "noise"}, - {"type": NeuralType(("B",), LengthsType()), "seq_length": "input", "name": "noise_len"}, - {"type": NeuralType(("B", "T"), AudioSignal()), "seq_length": "input", "name": "noisy_audio"}, - {"type": NeuralType(("B",), LengthsType()), "seq_length": "input", "name": "noisy_audio_len"}, - ], - } - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - super().__init__(cfg, trainer) - - def _setup_dataloader_from_config(self, config: Optional[Dict]): - audio_to_text_dataset.inject_dataloader_value_from_model_config(self.cfg, config, key='sample_rate') - - if config.get("use_lhotse"): - return get_lhotse_dataloader_from_config( - config, - global_rank=self.global_rank, - world_size=self.world_size, - dataset=ssl_dataset.LhotseAudioNoiseDataset( - noise_manifest=config.get('noise_manifest', None), - batch_augmentor_cfg=config.get('batch_augmentor', None), - ), - ) - - dataset = ssl_dataset.get_audio_noise_dataset_from_config( - config, - global_rank=self.global_rank, - world_size=self.world_size, - ) - - shuffle = config['shuffle'] - if isinstance(dataset, torch.utils.data.IterableDataset): - shuffle = False - - if hasattr(dataset, 'collate_fn'): - collate_fn = dataset.collate_fn - elif hasattr(dataset.datasets[0], 'collate_fn'): - # support datasets that are lists of entries - collate_fn = dataset.datasets[0].collate_fn - else: - # support datasets that are lists of lists - collate_fn = dataset.datasets[0].datasets[0].collate_fn - - return torch.utils.data.DataLoader( - dataset=dataset, - batch_size=config['batch_size'], - collate_fn=collate_fn, - drop_last=config.get('drop_last', False), - shuffle=shuffle, - num_workers=config.get('num_workers', 0), - pin_memory=config.get('pin_memory', False), - ) - - @property - def input_types(self) -> Optional[Dict[str, NeuralType]]: - if hasattr(self.preprocessor, '_sample_rate'): - input_signal_eltype = AudioSignal(freq=self.preprocessor._sample_rate) - else: - input_signal_eltype = AudioSignal() - return { - "input_signal": NeuralType(('B', 'T'), input_signal_eltype, optional=True), - "input_signal_length": NeuralType(tuple('B'), LengthsType(), optional=True), - "processed_signal": NeuralType(('B', 'D', 'T'), SpectrogramType(), optional=True), - "processed_signal_length": NeuralType(tuple('B'), LengthsType(), optional=True), - "noise_signal": NeuralType(('B', 'T'), input_signal_eltype, optional=True), - "noise_signal_length": NeuralType(tuple('B'), LengthsType(), optional=True), - "processed_noise_signal": NeuralType(('B', 'D', 'T'), SpectrogramType(), optional=True), - "processed_noise_length": NeuralType(tuple('B'), LengthsType(), optional=True), - "noisy_input_signal": NeuralType(('B', 'T'), input_signal_eltype, optional=True), - "noisy_input_signal_length": NeuralType(tuple('B'), LengthsType(), optional=True), - "processed_noisy_signal": NeuralType(('B', 'D', 'T'), SpectrogramType(), optional=True), - "processed_noisy_signal_length": NeuralType(tuple('B'), LengthsType(), optional=True), - "apply_mask": NeuralType(optional=True), - } - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - if self.cfg.num_books == 1 and self.cfg.squeeze_single: - logprobs = NeuralType(('B', 'T', 'C'), LogprobsType()) - tokens = NeuralType(('B', 'T'), LabelsType()) - else: - logprobs = NeuralType(('B', 'T', 'C', 'H'), LogprobsType()) - tokens = NeuralType(('B', 'T', 'H'), LabelsType()) - return { - "logprobs": logprobs, - "encoded_len": NeuralType(tuple('B'), LengthsType()), - "masks": NeuralType(('B', 'D', 'T'), SpectrogramType()), - "tokens": tokens, - } - - @typecheck() - def forward( - self, - input_signal=None, - input_signal_length=None, - processed_signal=None, - processed_signal_length=None, - noise_signal=None, # noqa - noise_signal_length=None, # noqa - processed_noise_signal=None, # noqa - processed_noise_signal_length=None, # noqa - noisy_input_signal=None, - noisy_input_signal_length=None, - processed_noisy_input_signal=None, - processed_noisy_input_signal_length=None, - apply_mask=False, - ): - has_input_signal = input_signal is not None and input_signal_length is not None - has_processed_signal = processed_signal is not None and processed_signal_length is not None - if (has_input_signal ^ has_processed_signal) == False: - raise ValueError( - f"{self} Arguments ``input_signal`` and ``input_signal_length`` are mutually exclusive " - " with ``processed_signal`` and ``processed_signal_len`` arguments." - ) - if not has_processed_signal: - processed_signal, processed_signal_length = self.preprocessor( - input_signal=input_signal, - length=input_signal_length, - ) - - ### Following code snipet is not used but kept for future reference - # - # has_noise_signal = noise_signal is not None and noise_signal_length is not None - # has_processed_noise_signal = processed_noise_signal is not None and processed_noise_signal_length is not None - # if (has_noise_signal ^ has_processed_noise_signal) == False: - # raise ValueError( - # f"{self} Arguments ``noise_signal`` and ``noise_signal_length`` are mutually exclusive " - # " with ``processed_noise_signal`` and ``processed_noise_signal_len`` arguments." - # ) - # if not has_processed_noise_signal: - # processed_noise_signal, processed_noise_signal_length = self.preprocessor( - # input_signal=noise_signal, - # length=noise_signal_length, - # ) - - has_noisy_input_signal = noisy_input_signal is not None and noisy_input_signal_length is not None - has_processed_noisy_input_signal = ( - processed_noisy_input_signal is not None and processed_noisy_input_signal_length is not None - ) - if (has_noisy_input_signal ^ has_processed_noisy_input_signal) == False: - raise ValueError( - f"{self} Arguments ``noisy_input_signal`` and ``noisy_input_signal_length`` are mutually exclusive " - " with ``processed_noisy_input_signal`` and ``processed_noisy_input_signal_len`` arguments." - ) - if not has_processed_noisy_input_signal: - processed_noisy_input_signal, processed_noisy_input_signal_length = self.preprocessor( - input_signal=noisy_input_signal, - length=noisy_input_signal_length, - ) - - if self.pre_encoder is not None: - # mask after convolutional sub-sampling - feats, _ = self.pre_encoder.pre_encode(x=processed_signal, lengths=processed_signal_length) - _, tokens = self.quantizer(input_signal=feats.transpose(1, 2)) - - self.pre_encoder.set_masking_enabled(apply_mask=apply_mask) - encoded, encoded_len = self.encoder( - audio_signal=processed_noisy_input_signal, length=processed_noisy_input_signal_length - ) - masks = self.pre_encoder.get_current_mask() - else: - _, tokens = self.quantizer(input_signal=processed_signal) - if apply_mask: - masked_signal, masks = self.mask_processor( - input_feats=processed_noisy_input_signal, input_lengths=processed_noisy_input_signal_length - ) - else: - masked_signal = processed_noisy_input_signal - masks = torch.zeros_like(processed_noisy_input_signal) - encoded, encoded_len = self.encoder(audio_signal=masked_signal, length=processed_noisy_input_signal_length) - - log_probs = self.decoder(encoder_output=encoded) - - return log_probs, encoded_len, masks, tokens - - def training_step(self, batch: ssl_dataset.AudioNoiseBatch, batch_idx: int): - log_probs, encoded_len, masks, tokens = self.forward( - input_signal=batch.audio, - input_signal_length=batch.audio_len, - noise_signal=batch.noise, - noise_signal_length=batch.noise_len, - noisy_input_signal=batch.noisy_audio, - noisy_input_signal_length=batch.noisy_audio_len, - apply_mask=True, - ) - - loss_value = self.loss(masks=masks, decoder_outputs=log_probs, targets=tokens, decoder_lengths=encoded_len) - - tensorboard_logs = { - 'learning_rate': self._optimizer.param_groups[0]['lr'], - 'global_step': self.trainer.global_step, - 'train_loss': loss_value, - } - - return {'loss': loss_value, 'log': tensorboard_logs} - - def inference_pass( - self, - batch: ssl_dataset.AudioNoiseBatch, - batch_idx: int, - dataloader_idx: int = 0, - mode: str = 'val', - apply_mask: bool = True, - ): - log_probs, encoded_len, masks, tokens = self.forward( - input_signal=batch.audio, - input_signal_length=batch.audio_len, - noise_signal=batch.noise, - noise_signal_length=batch.noise_len, - noisy_input_signal=batch.noisy_audio, - noisy_input_signal_length=batch.noisy_audio_len, - apply_mask=apply_mask, - ) - - loss_value = self.loss(masks=masks, decoder_outputs=log_probs, targets=tokens, decoder_lengths=encoded_len) - - return {f'{mode}_loss': loss_value} diff --git a/nemo/collections/asr/models/transformer_bpe_models.py b/nemo/collections/asr/models/transformer_bpe_models.py deleted file mode 100644 index 4692cb662b4b9be12b205139b83c77a8259b27b4..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/transformer_bpe_models.py +++ /dev/null @@ -1,641 +0,0 @@ -# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import itertools -import json -import os -import tempfile -from math import ceil -from typing import Any, Dict, List, Optional, Union - -import editdistance -import torch -import torch.distributed as dist -from lightning.pytorch import Trainer -from omegaconf import DictConfig, OmegaConf, open_dict -from torch.utils.data import DataLoader -from torchmetrics.text import SacreBLEUScore -from tqdm.auto import tqdm - -from nemo.collections.asr.data import audio_to_text_dataset -from nemo.collections.asr.data.audio_to_text_dali import DALIOutputs -from nemo.collections.asr.data.audio_to_text_lhotse import LhotseSpeechToTextBpeDataset -from nemo.collections.asr.models.asr_model import ASRModel, ExportableEncDecModel -from nemo.collections.asr.modules.transformer import ( - BeamSearchSequenceGenerator, - TransformerEncoder, - get_nemo_transformer, -) -from nemo.collections.asr.parts.mixins import ASRBPEMixin, ASRTranscriptionMixin, TranscribeConfig -from nemo.collections.asr.parts.preprocessing.segment import ChannelSelectorType -from nemo.collections.asr.parts.submodules.token_classifier import TokenClassifier -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis -from nemo.collections.common.data.lhotse import get_lhotse_dataloader_from_config -from nemo.collections.common.losses import SmoothedCrossEntropyLoss -from nemo.collections.common.metrics import GlobalAverageLossMetric -from nemo.collections.common.parts import transformer_weights_init -from nemo.core.classes.common import typecheck -from nemo.core.neural_types import ( - AudioSignal, - ChannelType, - LabelsType, - LengthsType, - LogprobsType, - MaskType, - NeuralType, - SpectrogramType, -) -from nemo.utils import logging - -__all__ = ['EncDecTransfModelBPE'] - - -def lens_to_mask(lens, max_length): - batch_size = lens.shape[0] - mask = torch.arange(max_length).repeat(batch_size, 1).to(lens.device) < lens[:, None] - return mask - - -class EncDecTransfModelBPE(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRTranscriptionMixin): - """Base class for encoder decoder CTC-based models.""" - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - - if 'tokenizer' not in cfg: - raise ValueError("`cfg` must have `tokenizer` config to create a tokenizer !") - - # Setup the tokenizer - self._setup_tokenizer(cfg.tokenizer) - - super().__init__(cfg=cfg, trainer=trainer) - - # Setup audio preprocessor - self.preprocessor = EncDecTransfModelBPE.from_config_dict(self.cfg.preprocessor) - - # Setup audio encoder - self.encoder = EncDecTransfModelBPE.from_config_dict(self.cfg.encoder) - - # Add projection layer if encoder and decoder differ in hidden size - if self.cfg.encoder['d_model'] != self.cfg.transf_decoder['hidden_size']: - self.adapter = torch.nn.Linear(self.cfg.encoder['d_model'], self.cfg.transf_decoder['hidden_size']) - else: - self.adapter = torch.nn.Identity() - - transf_encoder_cfg_dict = OmegaConf.to_container(cfg.get('transf_encoder')) - - # Whether to add Transformer Encoder block between Conformer and Transformer Decoder - self.use_transf_encoder = False - if transf_encoder_cfg_dict['num_layers'] > 0: - self.use_transf_encoder = True - - self.transf_encoder = TransformerEncoder( - num_layers=transf_encoder_cfg_dict['num_layers'], - hidden_size=transf_encoder_cfg_dict['hidden_size'], - inner_size=transf_encoder_cfg_dict['inner_size'], - mask_future=False, - num_attention_heads=transf_encoder_cfg_dict['num_attention_heads'], - attn_score_dropout=transf_encoder_cfg_dict['attn_score_dropout'], - attn_layer_dropout=transf_encoder_cfg_dict['attn_layer_dropout'], - ffn_dropout=transf_encoder_cfg_dict['ffn_dropout'], - pre_ln=transf_encoder_cfg_dict.get('pre_ln', True), - pre_ln_final_layer_norm=transf_encoder_cfg_dict.get('pre_ln_final_layer_norm', True), - ) - std_init_range = 1 / transf_encoder_cfg_dict['hidden_size'] ** 0.5 - self.transf_encoder.apply(lambda module: transformer_weights_init(module, std_init_range)) - - transf_decoder_cfg_dict = OmegaConf.to_container(cfg.get('transf_decoder')) - - # Transformer decoder - vocab_size = 8 * ceil(self.tokenizer.vocab_size / 8) - transf_decoder_cfg_dict['vocab_size'] = vocab_size - library = transf_decoder_cfg_dict.pop('library', 'nemo') - if library != 'nemo': - raise ValueError(f"Currently only 'nemo' library is supported for Transformer decoder. Got {library}") - model_name = transf_decoder_cfg_dict.pop('model_name', None) - pretrained = transf_decoder_cfg_dict.pop('pretrained', False) - self.transf_decoder = get_nemo_transformer( - model_name=model_name, - pretrained=pretrained, - config_dict=transf_decoder_cfg_dict, - encoder=False, - pre_ln_final_layer_norm=transf_decoder_cfg_dict.get("pre_ln_final_layer_norm", False), - ) - - self.log_softmax = TokenClassifier( - hidden_size=self.transf_decoder.hidden_size, - num_classes=vocab_size, - activation=self.cfg.head.activation, - log_softmax=self.cfg.head.log_softmax, - dropout=self.cfg.head.dropout, - use_transformer_init=self.cfg.head.use_transformer_init, - num_layers=self.cfg.head.num_layers, - ) - self.log_softmax.mlp.layer0.weight = self.transf_decoder.embedding.token_embedding.weight - std_init_range = 1 / self.transf_decoder.hidden_size**0.5 - self.transf_decoder.apply(lambda module: transformer_weights_init(module, std_init_range)) - self.log_softmax.apply(lambda module: transformer_weights_init(module, std_init_range)) - - # Beam Search decoding - self.beam_search = BeamSearchSequenceGenerator( - embedding=self.transf_decoder.embedding, - decoder=self.transf_decoder.decoder, - log_softmax=self.log_softmax, - max_sequence_length=self.transf_decoder.max_sequence_length, - beam_size=self.cfg.beam_search.beam_size, - bos=self.tokenizer.bos_id, - pad=self.tokenizer.pad_id, - eos=self.tokenizer.eos_id, - len_pen=self.cfg.beam_search.len_pen, - max_delta_length=self.cfg.beam_search.max_generation_delta, - ) - - # Define autoregressive CE loss - self.transf_loss = SmoothedCrossEntropyLoss( - pad_id=self.tokenizer.pad_id, label_smoothing=self.cfg.label_smoothing - ) - - if hasattr(self.cfg, 'spec_augment') and self.cfg.spec_augment is not None: - self.spec_augmentation = EncDecTransfModelBPE.from_config_dict(self.cfg.spec_augment) - else: - self.spec_augmentation = None - - self.val_loss = GlobalAverageLossMetric(dist_sync_on_step=False, take_avg_loss=True) - - @torch.no_grad() - def transcribe( - self, - audio: Union[List[str], DataLoader], - batch_size: int = 4, - return_hypotheses: bool = False, - num_workers: int = 0, - channel_selector: Optional[ChannelSelectorType] = None, - augmentor: DictConfig = None, - verbose: bool = True, - ) -> Union[List[str], List[Hypothesis]]: - """ - Uses greedy decoding to transcribe audio files. Use this method for debugging and prototyping. - Args: - audio: (a list) of paths to audio files. - Can also be a dataloader object that provides values that can be consumed by the model. - Recommended length per file is between 5 and 25 seconds. \ - But it is possible to pass a few hours long file if enough GPU memory is available. - batch_size: (int) batch size to use during inference. - Bigger will result in better throughput performance but would use more memory. - return_hypotheses: (bool) Either return hypotheses or text - With hypotheses can do some postprocessing like getting timestamp or rescoring - num_workers: (int) number of workers for DataLoader - 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`. - augmentor: (DictConfig): Augment audio samples during transcription if augmentor is applied. - verbose: (bool) whether to display tqdm progress bar - Returns: - A list of transcriptions (or raw log probabilities if logprobs is True) in the same order as paths2audio_files - """ - return super().transcribe( - audio=audio, - batch_size=batch_size, - return_hypotheses=return_hypotheses, - num_workers=num_workers, - channel_selector=channel_selector, - augmentor=augmentor, - verbose=verbose, - ) - - def _update_default_values(self, config: DictConfig): - if self.training: # don't do anything for training - return config - with open_dict(config): - for k, v in self.cfg.train_ds.items(): - if k not in config: - config[k] = v - return config - - def _setup_dataloader_from_config(self, config: Optional[Dict]): - if config.get("use_lhotse"): - config = self._update_default_values(config) - return get_lhotse_dataloader_from_config( - config, - # During transcription, the model is initially loaded on the CPU. - # To ensure the correct global_rank and world_size are set, - # these values must be passed from the configuration. - global_rank=self.global_rank if not config.get("do_transcribe", False) else config.get("global_rank"), - world_size=self.world_size if not config.get("do_transcribe", False) else config.get("world_size"), - dataset=LhotseSpeechToTextBpeDataset( - tokenizer=self.tokenizer, - return_cuts=config.get("do_transcribe", False), - ), - tokenizer=self.tokenizer, - ) - - dataset = audio_to_text_dataset.get_audio_to_text_bpe_dataset_from_config( - config=config, - local_rank=self.local_rank, - global_rank=self.global_rank, - world_size=self.world_size, - tokenizer=self.tokenizer, - preprocessor_cfg=self.cfg.get("preprocessor", None), - ) - - if dataset is None: - return None - - shuffle = config['shuffle'] - if config.get('is_tarred', False): - shuffle = False - - if hasattr(dataset, 'collate_fn'): - collate_fn = dataset.collate_fn - else: - collate_fn = dataset.datasets[0].collate_fn - - return torch.utils.data.DataLoader( - dataset=dataset, - batch_size=config['batch_size'], - collate_fn=collate_fn, - drop_last=config.get('drop_last', False), - shuffle=shuffle, - num_workers=config.get('num_workers', 0), - pin_memory=config.get('pin_memory', False), - ) - - def setup_training_data(self, train_data_config: Optional[DictConfig]): - - # create audio-only data loader - self._update_dataset_config(dataset_name='train', config=train_data_config) - self._train_dl = self._setup_dataloader_from_config(config=train_data_config) - - # Need to set this because if using an IterableDataset, the length of the - # dataloader is the total number of samples rather than the number of batches, - # and this messes up the tqdm progress bar. So we set the number of steps manually - # (to the correct number) to fix this. - if 'is_tarred' in train_data_config and train_data_config['is_tarred']: - # We also need to check if limit_train_batches is already set. - # If it's an int, we assume that the user has set it to something sane, - # i.e. <= # training batches, and don't change it. Otherwise, adjust - # batches accordingly if it's a float (including 1.0). - if self._trainer is not None and isinstance(self._trainer.limit_train_batches, float): - self._trainer.limit_train_batches = int( - self._trainer.limit_train_batches - * ceil((len(self._train_dl.dataset) / self.world_size) / train_data_config['batch_size']) - ) - elif self._trainer is None: - logging.warning( - "Model Trainer was not set before constructing the dataset, incorrect number of " - "training batches will be used. Please set the trainer and rebuild the dataset." - ) - - def setup_validation_data(self, val_data_config: Optional[Union[DictConfig, Dict]]): - """ - Sets up the validation data loader via a Dict-like object. - Args: - val_data_config: A config that contains the information regarding construction - of an ASR Training dataset. - Supported Datasets: - - :class:`~nemo.collections.asr.data.audio_to_text.AudioToCharDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.AudioToBPEDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.TarredAudioToCharDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.TarredAudioToBPEDataset` - - :class:`~nemo.collections.asr.data.audio_to_text_dali.AudioToCharDALIDataset` - """ - if 'shuffle' not in val_data_config: - val_data_config['shuffle'] = False - - # preserve config - self._update_dataset_config(dataset_name='validation', config=val_data_config) - self._validation_dl = self._setup_dataloader_from_config(config=val_data_config) - - def setup_test_data(self, test_data_config: Optional[Union[DictConfig, Dict]]): - """ - Sets up the test data loader via a Dict-like object. - Args: - test_data_config: A config that contains the information regarding construction - of an ASR Training dataset. - Supported Datasets: - - :class:`~nemo.collections.asr.data.audio_to_text.AudioToCharDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.AudioToBPEDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.TarredAudioToCharDataset` - - :class:`~nemo.collections.asr.data.audio_to_text.TarredAudioToBPEDataset` - - :class:`~nemo.collections.asr.data.audio_to_text_dali.AudioToCharDALIDataset` - """ - if 'shuffle' not in test_data_config: - test_data_config['shuffle'] = False - - # preserve config - self._update_dataset_config(dataset_name='test', config=test_data_config) - self._test_dl = self._setup_dataloader_from_config(config=test_data_config) - - @property - def input_types(self) -> Optional[Dict[str, NeuralType]]: - if hasattr(self.preprocessor, '_sample_rate'): - input_signal_eltype = AudioSignal(freq=self.preprocessor._sample_rate) - else: - input_signal_eltype = AudioSignal() - return { - "input_signal": NeuralType(('B', 'T'), input_signal_eltype, optional=True), - "input_signal_length": NeuralType(tuple('B'), LengthsType(), optional=True), - "processed_signal": NeuralType(('B', 'D', 'T'), SpectrogramType(), optional=True), - "processed_signal_length": NeuralType(tuple('B'), LengthsType(), optional=True), - "transcript": NeuralType(('B', 'T'), LabelsType(), optional=True), - "transcript_length": NeuralType(tuple('B'), LengthsType(), optional=True), - "sample_id": NeuralType(tuple('B'), LengthsType(), optional=True), - } - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - return { - "transf_log_probs": NeuralType(('B', 'T', 'D'), LogprobsType()), - "encoded_lengths": NeuralType(tuple('B'), LengthsType()), - "encoder_states": NeuralType(('B', 'T', 'D'), ChannelType()), - "encoder_mask": NeuralType(('B', 'T'), MaskType()), - } - - @typecheck() - def forward( - self, - input_signal=None, - input_signal_length=None, - processed_signal=None, - processed_signal_length=None, - transcript=None, - transcript_length=None, - ): - """ - Forward pass of the model. - Args: - input_signal: Tensor that represents a batch of raw audio signals, - of shape [B, T]. T here represents timesteps, with 1 second of audio represented as - `self.sample_rate` number of floating point values. - input_signal_length: Vector of length B, that contains the individual lengths of the audio - sequences. - processed_signal: Tensor that represents a batch of processed audio signals, - of shape (B, D, T) that has undergone processing via some DALI preprocessor. - processed_signal_length: Vector of length B, that contains the individual lengths of the - processed audio sequences. - Returns: - A tuple of 3 elements - - 1) The log probabilities tensor of shape [B, T, D]. - 2) The lengths of the acoustic sequence after propagation through the encoder, of shape [B]. - 3) The greedy token predictions of the model of shape [B, T] (via argmax) - """ - has_input_signal = input_signal is not None and input_signal_length is not None - has_processed_signal = processed_signal is not None and processed_signal_length is not None - if (has_input_signal ^ has_processed_signal) == False: - raise ValueError( - f"{self} Arguments ``input_signal`` and ``input_signal_length`` are mutually exclusive " - " with ``processed_signal`` and ``processed_signal_len`` arguments." - ) - - if not has_processed_signal: - processed_signal, processed_signal_length = self.preprocessor( - input_signal=input_signal, length=input_signal_length - ) - - if self.spec_augmentation is not None and self.training: - processed_signal = self.spec_augmentation(input_spec=processed_signal, length=processed_signal_length) - - encoded, encoded_len = self.encoder(audio_signal=processed_signal, length=processed_signal_length) - - enc_states = encoded.permute(0, 2, 1) - enc_states = self.adapter(enc_states) - enc_mask = lens_to_mask(encoded_len, enc_states.shape[1]).to(enc_states.dtype) - if self.use_transf_encoder: - enc_states = self.transf_encoder(encoder_states=enc_states, encoder_mask=enc_mask) - - transf_log_probs = None - if transcript is not None: - dec_mask = lens_to_mask(transcript_length, transcript.shape[1]).to(transcript.dtype) - dec_states = self.transf_decoder( - input_ids=transcript, decoder_mask=dec_mask, encoder_embeddings=enc_states, encoder_mask=enc_mask - ) - transf_log_probs = self.log_softmax(hidden_states=dec_states) - - return transf_log_probs, encoded_len, enc_states, enc_mask - - def compute_audio_loss(self, batch): - - if batch is None: - return 0 - - signal, signal_len, transcript, transcript_len = batch - input_ids, labels = transcript[:, :-1], transcript[:, 1:] - - transf_log_probs, encoded_len, enc_states, enc_mask = self.forward( - input_signal=signal, - input_signal_length=signal_len, - transcript=input_ids, - transcript_length=transcript_len, - ) - - transf_loss = self.transf_loss(log_probs=transf_log_probs, labels=labels) - - return transf_loss - - # PTL-specific methods - def training_step(self, batch, batch_nb): - - audio_loss = self.compute_audio_loss(batch) - - tensorboard_logs = { - 'train_loss': audio_loss, - 'learning_rate': self._optimizer.param_groups[0]['lr'], - } - - return {'loss': audio_loss, 'log': tensorboard_logs} - - def validation_step(self, batch, batch_idx, dataloader_idx=0, eval_mode="val"): - signal, signal_len, transcript, transcript_len = batch - input_ids, labels = transcript[:, :-1], transcript[:, 1:] - - if isinstance(batch, DALIOutputs) and batch.has_processed_signal: - transf_log_probs, encoded_len, enc_states, enc_mask = self.forward( - processed_signal=signal, - processed_signal_length=signal_len, - transcript=input_ids, - transcript_length=transcript_len, - ) - else: - transf_log_probs, encoded_len, enc_states, enc_mask = self.forward( - input_signal=signal, - input_signal_length=signal_len, - transcript=input_ids, - transcript_length=transcript_len, - ) - - beam_hypotheses = self.beam_search( - encoder_hidden_states=enc_states, encoder_input_mask=enc_mask, return_beam_scores=False - ) - transf_loss = self.transf_loss(log_probs=transf_log_probs, labels=labels) - - ground_truths = [self.tokenizer.ids_to_text(sent) for sent in transcript.detach().cpu().tolist()] - translations = [self.tokenizer.ids_to_text(sent) for sent in beam_hypotheses.detach().cpu().tolist()] - - self.val_loss(loss=transf_loss, num_measurements=transf_log_probs.shape[0] * transf_log_probs.shape[1]) - - output_dict = {f'{eval_mode}_loss': transf_loss, 'translations': translations, 'ground_truths': ground_truths} - - self.validation_step_outputs.append(output_dict) - - return output_dict - - def test_step(self, batch, batch_idx, dataloader_idx=0): - return self.validation_step(batch, batch_idx, dataloader_idx, eval_mode="test") - - def multi_validation_epoch_end(self, outputs, dataloader_idx: int = 0, eval_mode: str = "val"): - """ - Called at the end of validation to aggregate outputs. - :param outputs: list of individual outputs of each validation step. - """ - if not outputs: - return - - if isinstance(outputs[0], dict): - outputs = [outputs] - - for output in outputs: - eval_loss = getattr(self, 'val_loss').compute() - translations = list(itertools.chain(*[x['translations'] for x in output])) - ground_truths = list(itertools.chain(*[x['ground_truths'] for x in output])) - - # Gather translations and ground truths from all workers - tr_and_gt = [None for _ in range(self.world_size)] - # we also need to drop pairs where ground truth is an empty string - if self.world_size > 1: - dist.all_gather_object( - tr_and_gt, [(t, g) for (t, g) in zip(translations, ground_truths) if g.strip() != ''] - ) - else: - tr_and_gt[0] = [(t, g) for (t, g) in zip(translations, ground_truths) if g.strip() != ''] - - if self.global_rank == 0: - _translations = [] - _ground_truths = [] - for rank in range(0, self.world_size): - _translations += [t for (t, g) in tr_and_gt[rank]] - _ground_truths += [g for (t, g) in tr_and_gt[rank]] - - sacre_bleu = SacreBLEUScore()(_translations, [[x] for x in _ground_truths]).item() - sb_score = sacre_bleu * self.world_size - - wer_scores, wer_words = 0, 0 - for h, r in zip(_translations, _ground_truths): - wer_words += len(r.split()) - wer_scores += editdistance.eval(h.split(), r.split()) - wer_score = 1.0 * wer_scores * self.world_size / wer_words - - else: - sb_score = 0.0 - wer_score = 0.0 - - self.log(f"{eval_mode}_loss", eval_loss, sync_dist=True) - self.log(f"{eval_mode}_sacreBLEU", sb_score, sync_dist=True) - self.log(f"{eval_mode}_WER", wer_score, sync_dist=True) - self.val_loss.reset() - - def multi_test_epoch_end(self, outputs, dataloader_idx: int = 0): - return self.multi_validation_epoch_end(outputs, dataloader_idx, eval_mode="test") - - def test_dataloader(self): - if self._test_dl is not None: - return self._test_dl - - def _setup_transcribe_dataloader(self, config: Dict) -> 'torch.utils.data.DataLoader': - """ - Setup function for a temporary data loader which wraps the provided audio file. - Args: - config: A python dictionary which contains the following keys: - paths2audio_files: (a list) of paths to audio files. The files should be relatively short fragments. \ - Recommended length per file is between 5 and 25 seconds. - batch_size: (int) batch size to use during inference. \ - Bigger will result in better throughput performance but would use more memory. - temp_dir: (str) A temporary directory where the audio manifest is temporarily - stored. - Returns: - A pytorch DataLoader for the given audio file(s). - """ - batch_size = min(config['batch_size'], len(config['paths2audio_files'])) - dl_config = { - 'manifest_filepath': os.path.join(config['temp_dir'], 'manifest.json'), - 'sample_rate': self.preprocessor._sample_rate, - 'batch_size': batch_size, - 'trim_silence': False, - 'shuffle': False, - 'num_workers': min(batch_size, os.cpu_count() - 1), - 'pin_memory': True, - } - - temporary_datalayer = self._setup_dataloader_from_config(config=DictConfig(dl_config)) - return temporary_datalayer - - """ Transcription related methods """ - - def _transcribe_on_begin(self, audio, trcfg: TranscribeConfig): - super()._transcribe_on_begin(audio, trcfg) - - # Freeze the encoder and decoder modules - self.transf_decoder.freeze() - - def _transcribe_forward(self, batch: Any, trcfg: TranscribeConfig): - log_probs, encoded_len, enc_states, enc_mask = self.forward( - input_signal=batch[0], input_signal_length=batch[1] - ) - output = dict(log_probs=log_probs, encoded_len=encoded_len, enc_states=enc_states, enc_mask=enc_mask) - return output - - def _transcribe_output_processing(self, outputs, trcfg: TranscribeConfig) -> List[str]: - log_probs = outputs.pop('log_probs') - encoded_len = outputs.pop('encoded_len') - enc_states = outputs.pop('enc_states') - enc_mask = outputs.pop('enc_mask') - - # TODO(@AlexGrinch): add support for returning logprobs from return_hypotheses=True - del log_probs - - beam_hypotheses = ( - # TODO(@titu1994): maybe set return_beam_scores to True if theres no perf difference - self.beam_search(encoder_hidden_states=enc_states, encoder_input_mask=enc_mask, return_beam_scores=False) - .detach() - .cpu() - .numpy() - ) - - beam_hypotheses_out = [self.tokenizer.ids_to_text(hyp) for hyp in beam_hypotheses] - del enc_states, enc_mask, encoded_len - - if trcfg.return_hypotheses: - # TODO: add support for returning logprobs from return_hypotheses=True @AlexGrinch - # dump log probs per file - # for idx in range(logits.shape[0]): - # current_hypotheses[idx].y_sequence = logits[idx][: logits_len[idx]] - hypotheses = [] - for idx, hyp in enumerate(beam_hypotheses): - hypotheses.append( - Hypothesis( - score=0.0, - y_sequence=beam_hypotheses[idx], - text=beam_hypotheses_out[idx], - length=len(beam_hypotheses[idx]), - ) - ) - - # Replace output with Hypothesis list - beam_hypotheses_out = hypotheses - - del beam_hypotheses - - return beam_hypotheses_out - - def _transcribe_on_end(self, trcfg: TranscribeConfig): - super()._transcribe_on_end(trcfg) - - # Unfreeze the encoder and decoder modules - self.transf_decoder.unfreeze(partial=True) diff --git a/nemo/collections/asr/modules/__init__.py b/nemo/collections/asr/modules/__init__.py deleted file mode 100644 index 7259d077809eb2fb4841cbae5c732080e5a102fb..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/__init__.py +++ /dev/null @@ -1,86 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.asr.modules.audio_preprocessing import ( # noqa: F401 - AudioToMelSpectrogramPreprocessor, - AudioToMFCCPreprocessor, - CropOrPadSpectrogramAugmentation, - MaskedPatchAugmentation, - SpectrogramAugmentation, -) -from nemo.collections.asr.modules.beam_search_decoder import BeamSearchDecoderWithLM # noqa: F401 -from nemo.collections.asr.modules.conformer_encoder import ( # noqa: F401 - ConformerEncoder, - ConformerEncoderAdapter, - ConformerMultiLayerFeatureExtractor, -) -from nemo.collections.asr.modules.conv_asr import ( # noqa: F401 - ConvASRDecoder, - ConvASRDecoderClassification, - ConvASRDecoderReconstruction, - ConvASREncoder, - ConvASREncoderAdapter, - ECAPAEncoder, - ParallelConvASREncoder, - SpeakerDecoder, -) -from nemo.collections.asr.modules.hybrid_autoregressive_transducer import HATJoint # noqa: F401 -from nemo.collections.asr.modules.lstm_decoder import LSTMDecoder # noqa: F401 -from nemo.collections.asr.modules.rnn_encoder import RNNEncoder # noqa: F401 -from nemo.collections.asr.modules.rnnt import ( # noqa: F401 - RNNTDecoder, - RNNTDecoderJointSSL, - RNNTJoint, - SampledRNNTJoint, - StatelessTransducerDecoder, -) -from nemo.collections.asr.modules.ssl_modules import ( - ConformerMultiLayerFeaturePreprocessor, - ConvFeatureMaksingWrapper, - MultiSoftmaxDecoder, - RandomBlockMasking, - RandomProjectionVectorQuantizer, -) - -__all__ = [ - 'AudioToMelSpectrogramPreprocessor', - 'AudioToMFCCPreprocessor', - 'CropOrPadSpectrogramAugmentation', - 'MaskedPatchAugmentation', - 'SpectrogramAugmentation', - 'BeamSearchDecoderWithLM', - 'ConformerEncoder', - 'ConformerEncoderAdapter', - 'ConformerMultiLayerFeatureExtractor', - 'ConvASRDecoder', - 'ConvASRDecoderClassification', - 'ConvASRDecoderReconstruction', - 'ConvASREncoder', - 'ConvASREncoderAdapter', - 'ECAPAEncoder', - 'ParallelConvASREncoder', - 'SpeakerDecoder', - 'HATJoint', - 'LSTMDecoder', - 'RNNTDecoder', - 'RNNTDecoderJointSSL', - 'RNNTJoint', - 'SampledRNNTJoint', - 'StatelessTransducerDecoder', - 'ConformerMultiLayerFeaturePreprocessor', - 'ConvFeatureMaksingWrapper', - 'MultiSoftmaxDecoder', - 'RandomBlockMasking', - 'RandomProjectionVectorQuantizer', -] diff --git a/nemo/collections/asr/modules/audio_preprocessing.py b/nemo/collections/asr/modules/audio_preprocessing.py deleted file mode 100644 index a621c8db83c7634fbd83e078ac62f05b10010959..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/audio_preprocessing.py +++ /dev/null @@ -1,777 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import math -import random -from abc import ABC, abstractmethod -from dataclasses import dataclass -from typing import Any, Optional - -import torch - -from nemo.collections.asr.parts.preprocessing.features import FilterbankFeatures -from nemo.collections.asr.parts.submodules.spectr_augment import SpecAugment, SpecCutout -from nemo.collections.audio.parts.utils.transforms import MFCC -from nemo.core.classes import Exportable, NeuralModule, typecheck -from nemo.core.neural_types import ( - AudioSignal, - LengthsType, - MelSpectrogramType, - MFCCSpectrogramType, - NeuralType, - SpectrogramType, -) -from nemo.core.utils.optional_libs import NUMBA_CUDA_AVAILABLE -from nemo.utils import logging, logging_mode - -if NUMBA_CUDA_AVAILABLE: - from nemo.collections.asr.parts.numba.spec_augment import SpecAugmentNumba, spec_augment_launch_heuristics - -__all__ = [ - 'AudioToMelSpectrogramPreprocessor', - 'AudioToMFCCPreprocessor', - 'SpectrogramAugmentation', - 'MaskedPatchAugmentation', - 'CropOrPadSpectrogramAugmentation', -] - - -class AudioPreprocessor(NeuralModule, ABC): - """ - An interface for Neural Modules that performs audio pre-processing, - transforming the wav files to features. - """ - - def __init__(self, win_length, hop_length): - super().__init__() - - self.win_length = win_length - self.hop_length = hop_length - - self.torch_windows = { - 'hann': torch.hann_window, - 'hamming': torch.hamming_window, - 'blackman': torch.blackman_window, - 'bartlett': torch.bartlett_window, - 'ones': torch.ones, - None: torch.ones, - } - - # Normally, when you call to(dtype) on a torch.nn.Module, all - # floating point parameters and buffers will change to that - # dtype, rather than being float32. The AudioPreprocessor - # classes, uniquely, don't actually have any parameters or - # buffers from what I see. In addition, we want the input to - # the preprocessor to be float32, but need to create the - # output in appropriate precision. We have this empty tensor - # here just to detect which dtype tensor this module should - # output at the end of execution. - self.register_buffer("dtype_sentinel_tensor", torch.tensor((), dtype=torch.float32), persistent=False) - - @typecheck() - @torch.no_grad() - def forward(self, input_signal, length): - if input_signal.dtype != torch.float32: - logging.warning( - f"AudioPreprocessor received an input signal of dtype {input_signal.dtype}, rather than torch.float32. In sweeps across multiple datasets, we have found that the preprocessor is not robust to low precision mathematics. As such, it runs in float32. Your input will be cast to float32, but this is not necessarily enough to recovery full accuracy. For example, simply casting input_signal from torch.float32 to torch.bfloat16, then back to torch.float32 before running AudioPreprocessor causes drops in absolute WER of up to 0.1%. torch.bfloat16 simply does not have enough mantissa bits to represent enough values in the range [-1.0,+1.0] correctly.", - mode=logging_mode.ONCE, - ) - processed_signal, processed_length = self.get_features(input_signal.to(torch.float32), length) - processed_signal = processed_signal.to(self.dtype_sentinel_tensor.dtype) - return processed_signal, processed_length - - @abstractmethod - def get_features(self, input_signal, length): - # Called by forward(). Subclasses should implement this. - pass - - -class AudioToMelSpectrogramPreprocessor(AudioPreprocessor, Exportable): - """Featurizer module that converts wavs to mel spectrograms. - - Args: - sample_rate (int): Sample rate of the input audio data. - Defaults to 16000 - window_size (float): Size of window for fft in seconds - Defaults to 0.02 - window_stride (float): Stride of window for fft in seconds - Defaults to 0.01 - n_window_size (int): Size of window for fft in samples - Defaults to None. Use one of window_size or n_window_size. - n_window_stride (int): Stride of window for fft in samples - Defaults to None. Use one of window_stride or n_window_stride. - window (str): Windowing function for fft. can be one of ['hann', - 'hamming', 'blackman', 'bartlett'] - Defaults to "hann" - normalize (str): Can be one of ['per_feature', 'all_features']; all - other options disable feature normalization. 'all_features' - normalizes the entire spectrogram to be mean 0 with std 1. - 'pre_features' normalizes per channel / freq instead. - Defaults to "per_feature" - n_fft (int): Length of FT window. If None, it uses the smallest power - of 2 that is larger than n_window_size. - Defaults to None - preemph (float): Amount of pre emphasis to add to audio. Can be - disabled by passing None. - Defaults to 0.97 - features (int): Number of mel spectrogram freq bins to output. - Defaults to 64 - lowfreq (int): Lower bound on mel basis in Hz. - Defaults to 0 - highfreq (int): Lower bound on mel basis in Hz. - Defaults to None - log (bool): Log features. - Defaults to True - log_zero_guard_type(str): Need to avoid taking the log of zero. There - are two options: "add" or "clamp". - Defaults to "add". - log_zero_guard_value(float, or str): Add or clamp requires the number - to add with or clamp to. log_zero_guard_value can either be a float - or "tiny" or "eps". torch.finfo is used if "tiny" or "eps" is - passed. - Defaults to 2**-24. - dither (float): Amount of white-noise dithering. - Defaults to 1e-5 - pad_to (int): Ensures that the output size of the time dimension is - a multiple of pad_to. - Defaults to 16 - frame_splicing (int): Defaults to 1 - exact_pad (bool): If True, sets stft center to False and adds padding, such that num_frames = audio_length - // hop_length. Defaults to False. - pad_value (float): The value that shorter mels are padded with. - Defaults to 0 - mag_power (float): The power that the linear spectrogram is raised to - prior to multiplication with mel basis. - Defaults to 2 for a power spec - rng : Random number generator - nb_augmentation_prob (float) : Probability with which narrowband augmentation would be applied to - samples in the batch. - Defaults to 0.0 - nb_max_freq (int) : Frequency above which all frequencies will be masked for narrowband augmentation. - Defaults to 4000 - mel_norm: Normalization used for mel filterbank weights. - Defaults to 'slaney' (area normalization) - stft_exact_pad: Deprecated argument, kept for compatibility with older checkpoints. - stft_conv: Deprecated argument, kept for compatibility with older checkpoints. - """ - - def save_to(self, save_path: str): - pass - - @classmethod - def restore_from(cls, restore_path: str): - pass - - @property - def input_types(self): - """Returns definitions of module input ports.""" - return { - "input_signal": NeuralType(('B', 'T'), AudioSignal(freq=self._sample_rate)), - "length": NeuralType( - tuple('B'), LengthsType() - ), # Please note that length should be in samples not seconds. - } - - @property - def output_types(self): - """Returns definitions of module output ports. - - processed_signal: - 0: AxisType(BatchTag) - 1: AxisType(MelSpectrogramSignalTag) - 2: AxisType(ProcessedTimeTag) - processed_length: - 0: AxisType(BatchTag) - """ - return { - "processed_signal": NeuralType(('B', 'D', 'T'), MelSpectrogramType()), - "processed_length": NeuralType(tuple('B'), LengthsType()), - } - - def __init__( - self, - sample_rate=16000, - window_size=0.02, - window_stride=0.01, - n_window_size=None, - n_window_stride=None, - window="hann", - normalize="per_feature", - n_fft=None, - preemph=0.97, - features=64, - lowfreq=0, - highfreq=None, - log=True, - log_zero_guard_type="add", - log_zero_guard_value=2**-24, - dither=1e-5, - pad_to=16, - frame_splicing=1, - exact_pad=False, - pad_value=0, - mag_power=2.0, - rng=None, - nb_augmentation_prob=0.0, - nb_max_freq=4000, - mel_norm="slaney", - use_torchaudio: bool = False, # Deprecated arguments; kept for config compatibility - stft_exact_pad=False, # Deprecated arguments; kept for config compatibility - stft_conv=False, # Deprecated arguments; kept for config compatibility - ): - self._sample_rate = sample_rate - if window_size and n_window_size: - raise ValueError(f"{self} received both window_size and " f"n_window_size. Only one should be specified.") - if window_stride and n_window_stride: - raise ValueError( - f"{self} received both window_stride and " f"n_window_stride. Only one should be specified." - ) - if window_size: - n_window_size = int(window_size * self._sample_rate) - if window_stride: - n_window_stride = int(window_stride * self._sample_rate) - super().__init__(n_window_size, n_window_stride) - - # Given the long and similar argument list, point to the class and instantiate it by reference - self.featurizer = FilterbankFeatures( - sample_rate=self._sample_rate, - n_window_size=n_window_size, - n_window_stride=n_window_stride, - window=window, - normalize=normalize, - n_fft=n_fft, - preemph=preemph, - nfilt=features, - lowfreq=lowfreq, - highfreq=highfreq, - log=log, - log_zero_guard_type=log_zero_guard_type, - log_zero_guard_value=log_zero_guard_value, - dither=dither, - pad_to=pad_to, - frame_splicing=frame_splicing, - exact_pad=exact_pad, - pad_value=pad_value, - mag_power=mag_power, - rng=rng, - nb_augmentation_prob=nb_augmentation_prob, - nb_max_freq=nb_max_freq, - mel_norm=mel_norm, - stft_exact_pad=stft_exact_pad, # Deprecated arguments; kept for config compatibility - stft_conv=stft_conv, # Deprecated arguments; kept for config compatibility - ) - - def input_example(self, max_batch: int = 8, max_dim: int = 32000, min_length: int = 200): - dev = self.filter_banks.device - - signals = torch.randn(size=[max_batch, max_dim], device=dev) - lengths = torch.randint(low=min_length, high=max_dim, size=[max_batch], device=dev) - lengths[0] = max_dim - return signals, lengths - - def get_features(self, input_signal, length): - return self.featurizer(input_signal, length) - - @property - def filter_banks(self): - return self.featurizer.filter_banks - - -class AudioToMFCCPreprocessor(AudioPreprocessor): - """Preprocessor that converts wavs to MFCCs. - - Args: - sample_rate: The sample rate of the audio. - Defaults to 16000. - window_size: Size of window for fft in seconds. Used to calculate the - win_length arg for mel spectrogram. - Defaults to 0.02 - window_stride: Stride of window for fft in seconds. Used to caculate - the hop_length arg for mel spect. - Defaults to 0.01 - n_window_size: Size of window for fft in samples - Defaults to None. Use one of window_size or n_window_size. - n_window_stride: Stride of window for fft in samples - Defaults to None. Use one of window_stride or n_window_stride. - window: Windowing function for fft. can be one of ['hann', - 'hamming', 'blackman', 'bartlett', 'none', 'null']. - Defaults to 'hann' - n_fft: Length of FT window. If None, it uses the smallest power of 2 - that is larger than n_window_size. - Defaults to None - lowfreq (int): Lower bound on mel basis in Hz. - Defaults to 0 - highfreq (int): Lower bound on mel basis in Hz. - Defaults to None - n_mels: Number of mel filterbanks. - Defaults to 64 - n_mfcc: Number of coefficients to retain - Defaults to 64 - dct_type: Type of discrete cosine transform to use - norm: Type of norm to use - log: Whether to use log-mel spectrograms instead of db-scaled. - Defaults to True. - """ - - @property - def input_types(self): - """Returns definitions of module input ports.""" - return { - "input_signal": NeuralType(('B', 'T'), AudioSignal(freq=self._sample_rate)), - "length": NeuralType(tuple('B'), LengthsType()), - } - - @property - def output_types(self): - """Returns definitions of module output ports.""" - return { - "processed_signal": NeuralType(('B', 'D', 'T'), MFCCSpectrogramType()), - "processed_length": NeuralType(tuple('B'), LengthsType()), - } - - def save_to(self, save_path: str): - pass - - @classmethod - def restore_from(cls, restore_path: str): - pass - - def __init__( - self, - sample_rate=16000, - window_size=0.02, - window_stride=0.01, - n_window_size=None, - n_window_stride=None, - window='hann', - n_fft=None, - lowfreq=0.0, - highfreq=None, - n_mels=64, - n_mfcc=64, - dct_type=2, - norm='ortho', - log=True, - ): - self._sample_rate = sample_rate - if window_size and n_window_size: - raise ValueError(f"{self} received both window_size and " f"n_window_size. Only one should be specified.") - if window_stride and n_window_stride: - raise ValueError( - f"{self} received both window_stride and " f"n_window_stride. Only one should be specified." - ) - # Get win_length (n_window_size) and hop_length (n_window_stride) - if window_size: - n_window_size = int(window_size * self._sample_rate) - if window_stride: - n_window_stride = int(window_stride * self._sample_rate) - - super().__init__(n_window_size, n_window_stride) - - mel_kwargs = {} - - mel_kwargs['f_min'] = lowfreq - mel_kwargs['f_max'] = highfreq - mel_kwargs['n_mels'] = n_mels - - mel_kwargs['n_fft'] = n_fft or 2 ** math.ceil(math.log2(n_window_size)) - - mel_kwargs['win_length'] = n_window_size - mel_kwargs['hop_length'] = n_window_stride - - # Set window_fn. None defaults to torch.ones. - window_fn = self.torch_windows.get(window, None) - if window_fn is None: - raise ValueError( - f"Window argument for AudioProcessor is invalid: {window}." - f"For no window function, use 'ones' or None." - ) - mel_kwargs['window_fn'] = window_fn - - # Use torchaudio's implementation of MFCCs as featurizer - self.featurizer = MFCC( - sample_rate=self._sample_rate, - n_mfcc=n_mfcc, - dct_type=dct_type, - norm=norm, - log_mels=log, - melkwargs=mel_kwargs, - ) - - def get_features(self, input_signal, length): - features = self.featurizer(input_signal) - seq_len = torch.ceil(length.to(torch.float32) / self.hop_length).to(dtype=torch.long) - return features, seq_len - - -class SpectrogramAugmentation(NeuralModule): - """ - Performs time and freq cuts in one of two ways. - SpecAugment zeroes out vertical and horizontal sections as described in - SpecAugment (https://arxiv.org/abs/1904.08779). Arguments for use with - SpecAugment are `freq_masks`, `time_masks`, `freq_width`, and `time_width`. - SpecCutout zeroes out rectangulars as described in Cutout - (https://arxiv.org/abs/1708.04552). Arguments for use with Cutout are - `rect_masks`, `rect_freq`, and `rect_time`. - - Args: - freq_masks (int): how many frequency segments should be cut. - Defaults to 0. - time_masks (int): how many time segments should be cut - Defaults to 0. - freq_width (int): maximum number of frequencies to be cut in one - segment. - Defaults to 10. - time_width (int): maximum number of time steps to be cut in one - segment - Defaults to 10. - rect_masks (int): how many rectangular masks should be cut - Defaults to 0. - rect_freq (int): maximum size of cut rectangles along the frequency - dimension - Defaults to 5. - rect_time (int): maximum size of cut rectangles along the time - dimension - Defaults to 25. - use_numba_spec_augment: use numba code for Spectrogram augmentation - use_vectorized_spec_augment: use vectorized code for Spectrogram augmentation - - """ - - @property - def input_types(self): - """Returns definitions of module input types""" - return { - "input_spec": NeuralType(('B', 'D', 'T'), SpectrogramType()), - "length": NeuralType(tuple('B'), LengthsType()), - } - - @property - def output_types(self): - """Returns definitions of module output types""" - return {"augmented_spec": NeuralType(('B', 'D', 'T'), SpectrogramType())} - - def __init__( - self, - freq_masks=0, - time_masks=0, - freq_width=10, - time_width=10, - rect_masks=0, - rect_time=5, - rect_freq=20, - rng=None, - mask_value=0.0, - use_vectorized_spec_augment: bool = True, - use_numba_spec_augment: bool = False, - ): - super().__init__() - - if rect_masks > 0: - self.spec_cutout = SpecCutout( - rect_masks=rect_masks, - rect_time=rect_time, - rect_freq=rect_freq, - rng=rng, - ) - # self.spec_cutout.to(self._device) - else: - self.spec_cutout = lambda input_spec: input_spec - if freq_masks + time_masks > 0: - self.spec_augment = SpecAugment( - freq_masks=freq_masks, - time_masks=time_masks, - freq_width=freq_width, - time_width=time_width, - rng=rng, - mask_value=mask_value, - use_vectorized_code=use_vectorized_spec_augment, - ) - else: - self.spec_augment = lambda input_spec, length: input_spec - - # Check if numba is supported, and use a Numba kernel if it is - if use_numba_spec_augment and NUMBA_CUDA_AVAILABLE: - logging.info('Numba CUDA SpecAugment kernel is being used') - self.spec_augment_numba = SpecAugmentNumba( - freq_masks=freq_masks, - time_masks=time_masks, - freq_width=freq_width, - time_width=time_width, - rng=rng, - mask_value=mask_value, - ) - else: - self.spec_augment_numba = None - - @typecheck() - def forward(self, input_spec, length): - augmented_spec = self.spec_cutout(input_spec=input_spec) - - # To run the Numba kernel, correct numba version is required as well as - # tensor must be on GPU and length must be provided - if self.spec_augment_numba is not None and spec_augment_launch_heuristics(augmented_spec, length): - augmented_spec = self.spec_augment_numba(input_spec=augmented_spec, length=length) - else: - augmented_spec = self.spec_augment(input_spec=augmented_spec, length=length) - return augmented_spec - - -class MaskedPatchAugmentation(NeuralModule): - """ - Zeroes out fixed size time patches of the spectrogram. - All samples in batch are guaranteed to have the same amount of masked time steps. - Optionally also performs frequency masking in the same way as SpecAugment. - Args: - patch_size (int): up to how many time steps does one patch consist of. - Defaults to 48. - mask_patches (float): how many patches should be masked in each sample. - if >= 1., interpreted as number of patches (after converting to int) - if <1., interpreted as fraction of total tokens to be masked (number of patches is rounded up) - Defaults to 10. - freq_masks (int): how many frequency segments should be cut. - Defaults to 0. - freq_width (int): maximum number of frequencies to be cut in a segment. - Defaults to 0. - """ - - @property - def input_types(self): - """Returns definitions of module input types""" - return { - "input_spec": NeuralType(('B', 'D', 'T'), SpectrogramType()), - "length": NeuralType(tuple('B'), LengthsType()), - } - - @property - def output_types(self): - """Returns definitions of module output types""" - return {"augmented_spec": NeuralType(('B', 'D', 'T'), SpectrogramType())} - - def __init__( - self, - patch_size: int = 48, - mask_patches: float = 10.0, - freq_masks: int = 0, - freq_width: int = 0, - ): - super().__init__() - self.patch_size = patch_size - if mask_patches >= 1: - self.mask_patches = int(mask_patches) - elif mask_patches >= 0: - self._mask_fraction = mask_patches - self.mask_patches = None - else: - raise ValueError('mask_patches cannot be negative') - - if freq_masks > 0: - self.spec_augment = SpecAugment( - freq_masks=freq_masks, - time_masks=0, - freq_width=freq_width, - time_width=0, - ) - else: - self.spec_augment = None - - @typecheck() - def forward(self, input_spec, length): - augmented_spec = input_spec - - min_len = torch.min(length) - - if self.mask_patches is None: - # masking specified as fraction - len_fraction = int(min_len * self._mask_fraction) - mask_patches = len_fraction // self.patch_size + int(len_fraction % self.patch_size != 0) - else: - mask_patches = self.mask_patches - - if min_len < self.patch_size * mask_patches: - mask_patches = min_len // self.patch_size - - for idx in range(input_spec.shape[0]): - cur_len = length[idx] - patches = range(cur_len // self.patch_size) - masked_patches = random.sample(patches, mask_patches) - - for mp in masked_patches: - augmented_spec[idx, :, mp * self.patch_size : (mp + 1) * self.patch_size] = 0.0 - - if self.spec_augment is not None: - augmented_spec = self.spec_augment(input_spec=augmented_spec, length=length) - - return augmented_spec - - -class CropOrPadSpectrogramAugmentation(NeuralModule): - """ - Pad or Crop the incoming Spectrogram to a certain shape. - - Args: - audio_length (int): the final number of timesteps that is required. - The signal will be either padded or cropped temporally to this - size. - """ - - def __init__(self, audio_length): - super(CropOrPadSpectrogramAugmentation, self).__init__() - self.audio_length = audio_length - - if self.audio_length < 0: - raise ValueError( - 'audio_length must be non-negative. If using a dataclass with OmegaConf, ' - 'please call OmegaConf.to_object(cfg) to call appropriate __post_init__ methods.' - ) - - @typecheck() - @torch.no_grad() - def forward(self, input_signal, length): - image = input_signal - num_images = image.shape[0] - - audio_length = self.audio_length - image_len = image.shape[-1] - - # Crop long signal - if image_len > audio_length: # randomly slice - cutout_images = [] - offset = torch.randint(low=0, high=image_len - audio_length + 1, size=[num_images]) - - for idx, offset in enumerate(offset): - cutout_images.append(image[idx : idx + 1, :, offset : offset + audio_length]) - - image = torch.cat(cutout_images, dim=0) - del cutout_images - - else: # symmetrically pad short signal with zeros - pad_left = (audio_length - image_len) // 2 - pad_right = (audio_length - image_len) // 2 - - if (audio_length - image_len) % 2 == 1: - pad_right += 1 - - image = torch.nn.functional.pad(image, [pad_left, pad_right], mode="constant", value=0) - - # Replace dynamic length sequences with static number of timesteps - length = (length * 0) + audio_length - - return image, length - - @property - def input_types(self): - """Returns definitions of module output ports.""" - return { - "input_signal": NeuralType(('B', 'D', 'T'), SpectrogramType()), - "length": NeuralType(tuple('B'), LengthsType()), - } - - @property - def output_types(self): - """Returns definitions of module output ports.""" - return { - "processed_signal": NeuralType(('B', 'D', 'T'), SpectrogramType()), - "processed_length": NeuralType(tuple('B'), LengthsType()), - } - - def save_to(self, save_path: str): - pass - - @classmethod - def restore_from(cls, restore_path: str): - pass - - -@dataclass -class AudioToMelSpectrogramPreprocessorConfig: - _target_: str = "nemo.collections.asr.modules.AudioToMelSpectrogramPreprocessor" - sample_rate: int = 16000 - window_size: float = 0.02 - window_stride: float = 0.01 - n_window_size: Optional[int] = None - n_window_stride: Optional[int] = None - window: str = "hann" - normalize: str = "per_feature" - n_fft: Optional[int] = None - preemph: float = 0.97 - features: int = 64 - lowfreq: int = 0 - highfreq: Optional[int] = None - log: bool = True - log_zero_guard_type: str = "add" - log_zero_guard_value: float = 2**-24 - dither: float = 1e-5 - pad_to: int = 16 - frame_splicing: int = 1 - exact_pad: bool = False - pad_value: int = 0 - mag_power: float = 2.0 - rng: Optional[str] = None - nb_augmentation_prob: float = 0.0 - nb_max_freq: int = 4000 - mel_norm: str = "slaney" - use_torchaudio: bool = False # Deprecated argument, kept for compatibility with older checkpoints. - stft_exact_pad: bool = False # Deprecated argument, kept for compatibility with older checkpoints. - stft_conv: bool = False # Deprecated argument, kept for compatibility with older checkpoints. - - -@dataclass -class AudioToMFCCPreprocessorConfig: - _target_: str = 'nemo.collections.asr.modules.AudioToMFCCPreprocessor' - sample_rate: int = 16000 - window_size: float = 0.02 - window_stride: float = 0.01 - n_window_size: Optional[int] = None - n_window_stride: Optional[int] = None - window: str = 'hann' - n_fft: Optional[int] = None - lowfreq: Optional[float] = 0.0 - highfreq: Optional[float] = None - n_mels: int = 64 - n_mfcc: int = 64 - dct_type: int = 2 - norm: str = 'ortho' - log: bool = True - - -@dataclass -class SpectrogramAugmentationConfig: - _target_: str = "nemo.collections.asr.modules.SpectrogramAugmentation" - freq_masks: int = 0 - time_masks: int = 0 - freq_width: int = 0 - time_width: Optional[Any] = 0 - rect_masks: int = 0 - rect_time: int = 0 - rect_freq: int = 0 - mask_value: float = 0 - rng: Optional[Any] = None # random.Random() type - use_numba_spec_augment: bool = False - use_vectorized_spec_augment: bool = True - - -@dataclass -class CropOrPadSpectrogramAugmentationConfig: - audio_length: int - _target_: str = "nemo.collections.asr.modules.CropOrPadSpectrogramAugmentation" - - -@dataclass -class MaskedPatchAugmentationConfig: - patch_size: int = 48 - mask_patches: float = 10.0 - freq_masks: int = 0 - freq_width: int = 0 - _target_: str = "nemo.collections.asr.modules.MaskedPatchAugmentation" diff --git a/nemo/collections/asr/modules/beam_search_decoder.py b/nemo/collections/asr/modules/beam_search_decoder.py deleted file mode 100644 index b39804ae8e658eccb77c41e12bf1ab8ef63a51f9..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/beam_search_decoder.py +++ /dev/null @@ -1,103 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import torch - -from nemo.core.classes import NeuralModule, typecheck -from nemo.core.neural_types import LengthsType, LogprobsType, NeuralType, PredictionsType - - -class BeamSearchDecoderWithLM(NeuralModule): - """Neural Module that does CTC beam search with a N-gram language model. - It takes a batch of log_probabilities. Note the bigger the batch, the - better as processing is parallelized. Outputs a list of size batch_size. - Each element in the list is a list of size beam_search, and each element - in that list is a tuple of (final_log_prob, hyp_string). - Args: - vocab (list): List of characters that can be output by the ASR model. For English, this is the 28 character set - {a-z '}. The CTC blank symbol is automatically added. - beam_width (int): Size of beams to keep and expand upon. Larger beams result in more accurate but slower - predictions - alpha (float): The amount of importance to place on the N-gram language model. Larger alpha means more - importance on the LM and less importance on the acoustic model. - beta (float): A penalty term given to longer word sequences. Larger beta will result in shorter sequences. - lm_path (str): Path to N-gram language model - num_cpus (int): Number of CPUs to use - cutoff_prob (float): Cutoff probability in vocabulary pruning, default 1.0, no pruning - cutoff_top_n (int): Cutoff number in pruning, only top cutoff_top_n characters with highest probs in - vocabulary will be used in beam search, default 40. - input_tensor (bool): Set to True if you intend to pass PyTorch Tensors, set to False if you intend to pass - NumPy arrays. - """ - - @property - def input_types(self): - """Returns definitions of module input ports. - """ - return { - "log_probs": NeuralType(('B', 'T', 'D'), LogprobsType()), - "log_probs_length": NeuralType(tuple('B'), LengthsType()), - } - - @property - def output_types(self): - """Returns definitions of module output ports. - """ - return {"predictions": NeuralType(('B', 'T'), PredictionsType())} - - def __init__( - self, vocab, beam_width, alpha, beta, lm_path, num_cpus, cutoff_prob=1.0, cutoff_top_n=40, input_tensor=False - ): - - try: - from ctc_decoders import Scorer, ctc_beam_search_decoder_batch - except ModuleNotFoundError: - raise ModuleNotFoundError( - "BeamSearchDecoderWithLM requires the installation of ctc_decoders " - "from scripts/asr_language_modeling/ngram_lm/install_beamsearch_decoders.sh" - ) - - super().__init__() - - if lm_path is not None: - self.scorer = Scorer(alpha, beta, model_path=lm_path, vocabulary=vocab) - else: - self.scorer = None - self.beam_search_func = ctc_beam_search_decoder_batch - self.vocab = vocab - self.beam_width = beam_width - self.num_cpus = num_cpus - self.cutoff_prob = cutoff_prob - self.cutoff_top_n = cutoff_top_n - self.input_tensor = input_tensor - - @typecheck(ignore_collections=True) - @torch.no_grad() - def forward(self, log_probs, log_probs_length): - probs_list = log_probs - if self.input_tensor: - probs = torch.exp(log_probs) - probs_list = [] - for i, prob in enumerate(probs): - probs_list.append(prob[: log_probs_length[i], :]) - res = self.beam_search_func( - probs_list, - self.vocab, - beam_size=self.beam_width, - num_processes=self.num_cpus, - ext_scoring_func=self.scorer, - cutoff_prob=self.cutoff_prob, - cutoff_top_n=self.cutoff_top_n, - ) - return res diff --git a/nemo/collections/asr/modules/conformer_encoder.py b/nemo/collections/asr/modules/conformer_encoder.py deleted file mode 100644 index aa63f588cd63660a259885a3484c9ec0f4456cdf..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/conformer_encoder.py +++ /dev/null @@ -1,1392 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import math -import random -from collections import OrderedDict -from dataclasses import dataclass -from typing import List, Optional, Set, Tuple - -import torch -import torch.distributed -from omegaconf import DictConfig, ListConfig, open_dict -from torch import nn - -from nemo.collections.asr.models.configs import CacheAwareStreamingConfig -from nemo.collections.asr.parts.mixins.streaming import StreamingEncoder -from nemo.collections.asr.parts.submodules.causal_convs import CausalConv1D -from nemo.collections.asr.parts.submodules.conformer_modules import ConformerLayer -from nemo.collections.asr.parts.submodules.multi_head_attention import ( - LocalAttRelPositionalEncoding, - MultiHeadAttention, - PositionalEncoding, - RelPositionalEncoding, - RelPositionMultiHeadAttention, - RelPositionMultiHeadAttentionLongformer, -) -from nemo.collections.asr.parts.submodules.subsampling import ( - ConvSubsampling, - StackingSubsampling, - SubsamplingReductionModule, -) -from nemo.collections.asr.parts.utils import adapter_utils -from nemo.collections.asr.parts.utils.regularization_utils import compute_stochastic_depth_drop_probs -from nemo.core.classes.common import typecheck -from nemo.core.classes.exportable import Exportable -from nemo.core.classes.mixins import AccessMixin, adapter_mixins -from nemo.core.classes.module import NeuralModule -from nemo.core.neural_types import ( - AcousticEncodedRepresentation, - BoolType, - ChannelType, - LengthsType, - NeuralType, - SpectrogramType, -) -from nemo.utils import logging - -__all__ = ['ConformerEncoder', 'ConformerMultiLayerFeatureExtractor'] - - -class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): - """ - The encoder for ASR model of Conformer. - Based on this paper: - 'Conformer: Convolution-augmented Transformer for Speech Recognition' by Anmol Gulati et al. - https://arxiv.org/abs/2005.08100 - - Args: - feat_in (int): the size of feature channels - n_layers (int): number of layers of ConformerBlock - d_model (int): the hidden size of the model - feat_out (int): the size of the output features - Defaults to -1 (means feat_out is d_model) - subsampling (str): the method of subsampling: - choices = ['vggnet', 'striding', 'dw-striding', 'stacking', 'stacking_norm'] - Defaults to striding. - subsampling_factor (int): the subsampling factor which should be power of 2 - Defaults to 4. - subsampling_conv_chunking_factor(int): optionally, force chunk inputs (helpful for large inputs) - Should be power of 2, 1 (auto-chunking, default), or -1 (no chunking) - subsampling_conv_channels (int): the size of the convolutions in the subsampling module - Defaults to -1 which would set it to d_model. - reduction (str, Optional): the method of reduction, choices=['pooling', 'striding']. If no value - is passed, then no reduction is performed and the models runs with the original 4x subsampling. - reduction_position (int, Optional): the index of the layer to apply reduction. If -1, apply reduction - at the end. - reduction_factor (int): the reduction factor which should be either 1 or a power of 2 - Defaults to 1. - ff_expansion_factor (int): the expansion factor in feed forward layers - Defaults to 4. - self_attention_model (str): the type of the attention layer and positional encoding. - - 'rel_pos': - relative positional embedding and Transformer-XL - 'rel_pos_local_attn': - relative positional embedding and Transformer-XL with local attention using - overlapping chunks. Attention context is determined by att_context_size parameter. - 'abs_pos': - absolute positional embedding and Transformer - - Default is rel_pos. - pos_emb_max_len (int): the maximum length of positional embeddings - Defaults to 5000 - n_heads (int): number of heads in multi-headed attention layers - Defaults to 4. - att_context_size (List[Union[List[int],int]]): specifies the context sizes on each side. - Each context size should be a list of two integers like `[100, 100]`. - A list of context sizes like `[[100,100]`, `[100,50]]` can also be passed. -1 means unlimited context. - Defaults to `[-1, -1]` - att_context_probs (List[float]): a list of probabilities of each one of the att_context_size - when a list of them is passed. If not specified, uniform distribution is being used. - Defaults to None - att_context_style (str): 'regular' or 'chunked_limited'. - Defaults to 'regular' - xscaling (bool): enables scaling the inputs to the multi-headed attention layers by `sqrt(d_model)`. - Defaults to True. - untie_biases (bool): whether to not share (untie) the bias weights between layers of Transformer-XL - Defaults to True. - conv_kernel_size (int): the size of the convolutions in the convolutional modules - Defaults to 31. - conv_norm_type (str): the type of the normalization in the convolutional modules - Defaults to 'batch_norm'. - conv_context_size (list): it can be"causal" or a list of two integers - while `conv_context_size[0]+conv_context_size[1]+1==conv_kernel_size`. - `None` means `[(conv_kernel_size-1)//2`, `(conv_kernel_size-1)//2]`, and 'causal' means - `[(conv_kernel_size-1), 0]`. - Defaults to None. - conv_dual_mode (bool): specifies if convolution should be dual mode when dual_offline mode is being used. - When enables, the left half of the convolution kernel would get masked in streaming cases. - Defaults to False. - use_bias (bool): Use bias in all Linear and Conv1d layers from each ConformerLayer to improve - activation flow and stabilize training of huge models. - Defaults to True. - dropout (float): the dropout rate used in all layers except the attention layers - Defaults to 0.1. - dropout_pre_encoder (float): the dropout rate used before the encoder - Defaults to 0.1. - dropout_emb (float): the dropout rate used for the positional embeddings - Defaults to 0.1. - dropout_att (float): the dropout rate used for the attention layer - Defaults to 0.0. - stochastic_depth_drop_prob (float): if non-zero, will randomly drop - layers during training. The higher this value, the more often layers - are dropped. Defaults to 0.0. - stochastic_depth_mode (str): can be either "linear" or "uniform". If - set to "uniform", all layers have the same probability of drop. If - set to "linear", the drop probability grows linearly from 0 for the - first layer to the desired value for the final layer. Defaults to - "linear". - stochastic_depth_start_layer (int): starting layer for stochastic depth. - All layers before this will never be dropped. Note that drop - probability will be adjusted accordingly if mode is "linear" when - start layer is > 1. Defaults to 1. - global_tokens (int): number of tokens to be used for global attention. - Only relevant if self_attention_model is 'rel_pos_local_attn'. - Defaults to 0. - global_tokens_spacing (int): how far apart the global tokens are - Defaults to 1. - global_attn_separate (bool): whether the q, k, v layers used for global tokens should be separate. - Defaults to False. - use_pytorch_sdpa (bool): use torch sdpa instead of manual attention. - Defaults to False. - use_pytorch_sdpa_backends (list[str]): list of backend names to use in sdpa. - None or empty list means all backends. e.g. ["MATH"] - Defaults to None. - bypass_pre_encode: if True, skip the pre-encoder module and the `audio_signal` should be pre-encoded - embeddings. The `audio_signal` input supports two formats depending on the `bypass_pre_encode` - boolean flag. This determines the required format of the input variable `audio_signal`. - Defaults to `bypass_pre_encode=False`. `bypass_pre_encode=True` is used for the cases - where frame-level, context-independent embeddings are needed to be saved or reused. - (e.g., speaker cache in streaming speaker diarization) - sync_max_audio_length (bool): when true, performs NCCL all_reduce to allocate the same amount of memory for - positional encoding buffers on all GPUs. Disabling this setting may help with deadlocks in certain - scenarios such as model parallelism, or generally when this module is not being ran on some GPUs - as a part of the training step. - """ - - def input_example(self, max_batch=1, max_dim=256): - """ - Generates input examples for tracing etc. - Returns: - A tuple of input examples. - """ - dev = next(self.parameters()).device - if self.export_cache_support: - window_size = max_dim - if self.streaming_cfg is not None: - if isinstance(self.streaming_cfg.chunk_size, list): - chunk_size = self.streaming_cfg.chunk_size[1] - else: - chunk_size = self.streaming_cfg.chunk_size - if isinstance(self.streaming_cfg.pre_encode_cache_size, list): - pre_encode_cache_size = self.streaming_cfg.pre_encode_cache_size[1] - else: - pre_encode_cache_size = self.streaming_cfg.pre_encode_cache_size - window_size = chunk_size + pre_encode_cache_size - input_example = torch.randn(max_batch, self._feat_in, window_size, device=dev) - input_example_length = torch.randint( - window_size // 4, window_size, (max_batch,), device=dev, dtype=torch.int64 - ) - cache_last_channel, cache_last_time, cache_last_channel_len = self.get_initial_cache_state( - batch_size=max_batch, device=dev, max_dim=max_dim - ) - all_input_example = tuple( - [ - input_example, - input_example_length, - cache_last_channel.transpose(0, 1), - cache_last_time.transpose(0, 1), - cache_last_channel_len, - ] - ) - else: - input_example = torch.randn(max_batch, self._feat_in, max_dim, device=dev) - input_example_length = torch.randint(max_dim // 4, max_dim, (max_batch,), device=dev, dtype=torch.int64) - all_input_example = tuple([input_example, input_example_length]) - - return all_input_example - - @property - def input_types(self): - """Returns definitions of module input ports.""" - return OrderedDict( - { - "audio_signal": NeuralType(('B', 'D', 'T'), SpectrogramType()), - "length": NeuralType(tuple('B'), LengthsType()), - "cache_last_channel": NeuralType(('D', 'B', 'T', 'D'), ChannelType(), optional=True), - "cache_last_time": NeuralType(('D', 'B', 'D', 'T'), ChannelType(), optional=True), - "cache_last_channel_len": NeuralType(tuple('B'), LengthsType(), optional=True), - "bypass_pre_encode": NeuralType(tuple(), BoolType(), optional=True), - } - ) - - @property - def input_types_for_export(self): - """Returns definitions of module input ports.""" - return OrderedDict( - { - "audio_signal": NeuralType(('B', 'D', 'T'), SpectrogramType()), - "length": NeuralType(tuple('B'), LengthsType()), - "cache_last_channel": NeuralType(('B', 'D', 'T', 'D'), ChannelType(), optional=True), - "cache_last_time": NeuralType(('B', 'D', 'D', 'T'), ChannelType(), optional=True), - "cache_last_channel_len": NeuralType(tuple('B'), LengthsType(), optional=True), - "bypass_pre_encode": NeuralType(tuple(), BoolType(), optional=True), - } - ) - - @property - def output_types(self): - """Returns definitions of module output ports.""" - return OrderedDict( - { - "outputs": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), - "encoded_lengths": NeuralType(tuple('B'), LengthsType()), - "cache_last_channel_next": NeuralType(('D', 'B', 'T', 'D'), ChannelType(), optional=True), - "cache_last_time_next": NeuralType(('D', 'B', 'D', 'T'), ChannelType(), optional=True), - "cache_last_channel_next_len": NeuralType(tuple('B'), LengthsType(), optional=True), - } - ) - - @property - def output_types_for_export(self): - """Returns definitions of module output ports.""" - return OrderedDict( - { - "outputs": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), - "encoded_lengths": NeuralType(tuple('B'), LengthsType()), - "cache_last_channel_next": NeuralType(('B', 'D', 'T', 'D'), ChannelType(), optional=True), - "cache_last_time_next": NeuralType(('B', 'D', 'D', 'T'), ChannelType(), optional=True), - "cache_last_channel_next_len": NeuralType(tuple('B'), LengthsType(), optional=True), - } - ) - - @property - def disabled_deployment_input_names(self): - if not self.export_cache_support: - return set(["cache_last_channel", "cache_last_time", "cache_last_channel_len"]) - else: - return set() - - @property - def disabled_deployment_output_names(self): - if not self.export_cache_support: - return set(["cache_last_channel_next", "cache_last_time_next", "cache_last_channel_next_len"]) - else: - return set() - - def __init__( - self, - feat_in, - n_layers, - d_model, - feat_out=-1, - causal_downsampling=False, - subsampling='striding', - subsampling_factor=4, - subsampling_conv_chunking_factor=1, - subsampling_conv_channels=-1, - reduction=None, - reduction_position=None, - reduction_factor=1, - ff_expansion_factor=4, - self_attention_model='rel_pos', - n_heads=4, - att_context_size=None, - att_context_probs=None, - att_context_style='regular', - xscaling=True, - untie_biases=True, - pos_emb_max_len=5000, - conv_kernel_size=31, - conv_norm_type='batch_norm', - conv_context_size=None, - use_bias=True, - dropout=0.1, - dropout_pre_encoder=0.1, - dropout_emb=0.1, - dropout_att=0.0, - stochastic_depth_drop_prob: float = 0.0, - stochastic_depth_mode: str = "linear", - stochastic_depth_start_layer: int = 1, - global_tokens: int = 0, - global_tokens_spacing: int = 1, - global_attn_separate: bool = False, - use_pytorch_sdpa: bool = False, - use_pytorch_sdpa_backends=None, - sync_max_audio_length: bool = True, - ): - super().__init__() - d_ff = d_model * ff_expansion_factor - self.d_model = d_model - self.n_layers = n_layers - self._feat_in = feat_in - self.att_context_style = att_context_style - self.subsampling_factor = subsampling_factor - self.subsampling_conv_chunking_factor = subsampling_conv_chunking_factor - - self.self_attention_model = self_attention_model - self.global_tokens = global_tokens - self.global_attn_separate = global_attn_separate - self.global_tokens_spacing = global_tokens_spacing - self.use_pytorch_sdpa = use_pytorch_sdpa - if use_pytorch_sdpa_backends is None: - use_pytorch_sdpa_backends = [] - self.use_pytorch_sdpa_backends = use_pytorch_sdpa_backends - self.sync_max_audio_length = sync_max_audio_length - - # Setting up the att_context_size - ( - self.att_context_size_all, - self.att_context_size, - self.att_context_probs, - self.conv_context_size, - ) = self._calc_context_sizes( - att_context_style=att_context_style, - att_context_size=att_context_size, - att_context_probs=att_context_probs, - conv_context_size=conv_context_size, - conv_kernel_size=conv_kernel_size, - ) - - if xscaling: - self.xscale = math.sqrt(d_model) - else: - self.xscale = None - - # Subsampling - if subsampling_conv_channels == -1: - subsampling_conv_channels = d_model - if subsampling and subsampling_factor > 1: - if subsampling in ['stacking', 'stacking_norm']: - # stacking_norm has an extra layer norm after stacking comparing to stacking - self.pre_encode = StackingSubsampling( - subsampling_factor=subsampling_factor, - feat_in=feat_in, - feat_out=d_model, - norm=True if subsampling == 'stacking_norm' else False, - ) - else: - self.pre_encode = ConvSubsampling( - subsampling=subsampling, - subsampling_factor=subsampling_factor, - feat_in=feat_in, - feat_out=d_model, - conv_channels=subsampling_conv_channels, - subsampling_conv_chunking_factor=subsampling_conv_chunking_factor, - activation=nn.ReLU(True), - is_causal=causal_downsampling, - ) - else: - self.pre_encode = nn.Linear(feat_in, d_model) - - # Reduction - if reduction and reduction_factor > 1: - assert reduction_position >= -1 and reduction_position < n_layers - self.reduction_subsampling = SubsamplingReductionModule( - reduction=reduction, - d_model=d_model, - reduction_factor=reduction_factor, - ) - self.reduction_position = reduction_position - else: - self.reduction_subsampling = None - self.reduction_position = None - - self._feat_out = d_model - - # Biases for relative positional encoding - if not untie_biases and self_attention_model == "rel_pos": - d_head = d_model // n_heads - pos_bias_u = nn.Parameter(torch.Tensor(n_heads, d_head)) - pos_bias_v = nn.Parameter(torch.Tensor(n_heads, d_head)) - nn.init.zeros_(pos_bias_u) - nn.init.zeros_(pos_bias_v) - else: - pos_bias_u = None - pos_bias_v = None - - # Positional encodings - self.pos_emb_max_len = pos_emb_max_len - if self_attention_model == "rel_pos": - self.pos_enc = RelPositionalEncoding( - d_model=d_model, - dropout_rate=dropout_pre_encoder, - max_len=pos_emb_max_len, - xscale=self.xscale, - dropout_rate_emb=dropout_emb, - ) - elif self_attention_model == 'rel_pos_local_attn': - if max(att_context_size) <= 0: - raise ValueError("When using local attention, context size must be set > 0") - self.pos_enc = LocalAttRelPositionalEncoding( - att_context_size=att_context_size, - d_model=d_model, - dropout_rate=dropout, - max_len=pos_emb_max_len, - xscale=self.xscale, - dropout_rate_emb=dropout_emb, - ) - elif self_attention_model == "abs_pos": - pos_bias_u = None - pos_bias_v = None - self.pos_enc = PositionalEncoding( - d_model=d_model, dropout_rate=dropout_pre_encoder, max_len=pos_emb_max_len, xscale=self.xscale - ) - else: - raise ValueError(f"Not valid self_attention_model: '{self_attention_model}'!") - - self.layers = nn.ModuleList() - for i in range(n_layers): - layer = ConformerLayer( - d_model=d_model, - d_ff=d_ff, - self_attention_model=self_attention_model, - global_tokens=global_tokens, - global_tokens_spacing=global_tokens_spacing, - global_attn_separate=global_attn_separate, - n_heads=n_heads, - conv_kernel_size=conv_kernel_size, - conv_norm_type=conv_norm_type, - conv_context_size=self.conv_context_size, - dropout=dropout, - dropout_att=dropout_att, - pos_bias_u=pos_bias_u, - pos_bias_v=pos_bias_v, - att_context_size=self.att_context_size, - use_bias=use_bias, - use_pytorch_sdpa=self.use_pytorch_sdpa, - use_pytorch_sdpa_backends=self.use_pytorch_sdpa_backends, - ) - self.layers.append(layer) - - if feat_out > 0 and feat_out != self._feat_out: - self.out_proj = nn.Linear(self._feat_out, feat_out) - self._feat_out = feat_out - else: - self.out_proj = None - self._feat_out = d_model - self.set_max_audio_length(self.pos_emb_max_len) - self.use_pad_mask = True - - self.setup_streaming_params() - self.export_cache_support = False - - self.layer_drop_probs = compute_stochastic_depth_drop_probs( - len(self.layers), stochastic_depth_drop_prob, stochastic_depth_mode, stochastic_depth_start_layer - ) - # will be set in self.forward() if defined in AccessMixin config - self.interctc_capture_at_layers = None - - def forward_for_export( - self, audio_signal, length, cache_last_channel=None, cache_last_time=None, cache_last_channel_len=None - ): - """ - Forward function for model export. Please see `forward()` for more details. - """ - if cache_last_channel is not None: - cache_last_channel = cache_last_channel.transpose(0, 1) - cache_last_time = cache_last_time.transpose(0, 1) - - rets = self.forward_internal( - audio_signal, - length, - cache_last_channel=cache_last_channel, - cache_last_time=cache_last_time, - cache_last_channel_len=cache_last_channel_len, - ) - rets = self.streaming_post_process(rets, keep_all_outputs=False) - if len(rets) == 2: - return rets - elif rets[2] is None and rets[3] is None and rets[4] is None: - return (rets[0], rets[1]) - else: - return ( - rets[0], - rets[1], - rets[2].transpose(0, 1), - rets[3].transpose(0, 1), - rets[4], - ) - - def streaming_post_process(self, rets, keep_all_outputs=True): - """ - Post-process the output of the forward function for streaming. - - Args: - rets: The output of the forward function. - keep_all_outputs: Whether to keep all outputs. - """ - if len(rets) == 2: - return rets[0], rets[1], None, None, None - - (encoded, encoded_len, cache_last_channel_next, cache_last_time_next, cache_last_channel_next_len) = rets - - if cache_last_channel_next is not None and self.streaming_cfg.last_channel_cache_size >= 0: - if self.streaming_cfg.last_channel_cache_size > 0: - cache_last_channel_next = cache_last_channel_next[ - :, :, -self.streaming_cfg.last_channel_cache_size :, : - ] - - if self.streaming_cfg.valid_out_len > 0 and (not keep_all_outputs or self.att_context_style == "regular"): - encoded = encoded[:, :, : self.streaming_cfg.valid_out_len] - encoded_len = torch.clamp(encoded_len, max=self.streaming_cfg.valid_out_len) - - return (encoded, encoded_len, cache_last_channel_next, cache_last_time_next, cache_last_channel_next_len) - - @typecheck() - def forward( - self, - audio_signal, - length, - cache_last_channel=None, - cache_last_time=None, - cache_last_channel_len=None, - bypass_pre_encode=False, - ): - """ - Forward function for the ConformerEncoder accepting an audio signal and its corresponding length. - The ``audio_signal`` input supports two formats depending on ``bypass_pre_encode``: - - - ``bypass_pre_encode=False`` (default): ``audio_signal`` must be a tensor - containing audio features. Shape: ``(batch, feat_in, n_frames)``. - - ``bypass_pre_encode=True``: ``audio_signal`` must be a tensor containing - pre-encoded embeddings. Shape: ``(batch, n_frame, d_model)``. - """ - if not bypass_pre_encode and audio_signal.shape[-2] != self._feat_in: - raise ValueError( - f"If bypass_pre_encode is False, audio_signal should have shape " - f"(batch, {self._feat_in}, n_frame) but got last dimension {audio_signal.shape[-2]}." - ) - if bypass_pre_encode and audio_signal.shape[-1] != self.d_model: - raise ValueError( - f"If bypass_pre_encode is True, audio_signal should have shape " - f"(batch, n_frame, {self.d_model}) but got last dimension {audio_signal.shape[-1]}." - ) - - if bypass_pre_encode: - self.update_max_seq_length(seq_length=audio_signal.size(1), device=audio_signal.device) - else: - self.update_max_seq_length(seq_length=audio_signal.size(2), device=audio_signal.device) - return self.forward_internal( - audio_signal, - length, - cache_last_channel=cache_last_channel, - cache_last_time=cache_last_time, - cache_last_channel_len=cache_last_channel_len, - bypass_pre_encode=bypass_pre_encode, - ) - - def forward_internal( - self, - audio_signal, - length, - cache_last_channel=None, - cache_last_time=None, - cache_last_channel_len=None, - bypass_pre_encode=False, - ): - """ - The ``audio_signal`` input supports two formats depending on ``bypass_pre_encode``: - - - ``bypass_pre_encode=False`` (default): ``audio_signal`` must be a tensor - containing audio features. Shape: ``(batch, feat_in, n_frames)``. - - ``bypass_pre_encode=True``: ``audio_signal`` must be a tensor containing - pre-encoded embeddings. Shape: ``(batch, n_frame, d_model)``. - - ``bypass_pre_encode=True`` is used in cases where frame-level, context-independent embeddings are - needed to be saved or reused (e.g., speaker cache in streaming speaker diarization). - """ - if length is None: - length = audio_signal.new_full( - (audio_signal.size(0),), audio_signal.size(-1), dtype=torch.int64, device=audio_signal.device - ) - - # select a random att_context_size with the distribution specified by att_context_probs during training - # for non-validation cases like test, validation or inference, it uses the first mode in self.att_context_size - if self.training and len(self.att_context_size_all) > 1: - cur_att_context_size = random.choices(self.att_context_size_all, weights=self.att_context_probs)[0] - else: - cur_att_context_size = self.att_context_size - - if not bypass_pre_encode: - audio_signal = torch.transpose(audio_signal, 1, 2) - - if isinstance(self.pre_encode, nn.Linear): - audio_signal = self.pre_encode(audio_signal) - else: - audio_signal, length = self.pre_encode(x=audio_signal, lengths=length) - length = length.to(torch.int64) - # `self.streaming_cfg` is set by setup_streaming_cfg(), called in the init - if self.streaming_cfg.drop_extra_pre_encoded > 0 and cache_last_channel is not None: - audio_signal = audio_signal[:, self.streaming_cfg.drop_extra_pre_encoded :, :] - length = (length - self.streaming_cfg.drop_extra_pre_encoded).clamp(min=0) - - if self.reduction_position is not None and cache_last_channel is not None: - raise ValueError("Caching with reduction feature is not supported yet!") - - max_audio_length = audio_signal.size(1) - if cache_last_channel is not None: - cache_len = self.streaming_cfg.last_channel_cache_size - cache_keep_size = max_audio_length - self.streaming_cfg.cache_drop_size - max_audio_length = max_audio_length + cache_len - padding_length = length + cache_len - offset = torch.neg(cache_last_channel_len) + cache_len - else: - padding_length = length - cache_last_channel_next = None - cache_len = 0 - offset = None - - audio_signal, pos_emb = self.pos_enc(x=audio_signal, cache_len=cache_len) - - # Create the self-attention and padding masks - pad_mask, att_mask = self._create_masks( - att_context_size=cur_att_context_size, - padding_length=padding_length, - max_audio_length=max_audio_length, - offset=offset, - device=audio_signal.device, - ) - - if cache_last_channel is not None: - pad_mask = pad_mask[:, cache_len:] - if att_mask is not None: - att_mask = att_mask[:, cache_len:] - # Convert caches from the tensor to list - cache_last_time_next = [] - cache_last_channel_next = [] - - for lth, (drop_prob, layer) in enumerate(zip(self.layer_drop_probs, self.layers)): - original_signal = audio_signal - if cache_last_channel is not None: - cache_last_channel_cur = cache_last_channel[lth] - cache_last_time_cur = cache_last_time[lth] - else: - cache_last_channel_cur = None - cache_last_time_cur = None - audio_signal = layer( - x=audio_signal, - att_mask=att_mask, - pos_emb=pos_emb, - pad_mask=pad_mask, - cache_last_channel=cache_last_channel_cur, - cache_last_time=cache_last_time_cur, - ) - - if cache_last_channel_cur is not None: - (audio_signal, cache_last_channel_cur, cache_last_time_cur) = audio_signal - cache_last_channel_next.append(cache_last_channel_cur) - cache_last_time_next.append(cache_last_time_cur) - - # applying stochastic depth logic from https://arxiv.org/abs/2102.03216 - if self.training and drop_prob > 0.0: - should_drop = torch.rand(1) < drop_prob - # adjusting to match expectation - if should_drop: - # that's not efficient, but it's hard to implement distributed - # version of dropping layers without deadlock or random seed meddling - # so multiplying the signal by 0 to ensure all weights get gradients - audio_signal = audio_signal * 0.0 + original_signal - else: - # not doing this operation if drop prob is 0 as it's identity in that case - audio_signal = (audio_signal - original_signal) / (1.0 - drop_prob) + original_signal - - if self.reduction_position == lth: - audio_signal, length = self.reduction_subsampling(x=audio_signal, lengths=length) - max_audio_length = audio_signal.size(1) - # Don't update the audio_signal here because then it will again scale the audio_signal - # and cause an increase in the WER - _, pos_emb = self.pos_enc(x=audio_signal, cache_len=cache_len) - pad_mask, att_mask = self._create_masks( - att_context_size=cur_att_context_size, - padding_length=length, - max_audio_length=max_audio_length, - offset=offset, - device=audio_signal.device, - ) - - # saving tensors if required for interctc loss - if self.is_access_enabled(getattr(self, "model_guid", None)): - if self.interctc_capture_at_layers is None: - self.interctc_capture_at_layers = self.access_cfg.get('interctc', {}).get('capture_layers', []) - if lth in self.interctc_capture_at_layers: - lth_audio_signal = audio_signal - if self.out_proj is not None: - lth_audio_signal = self.out_proj(audio_signal) - # shape is the same as the shape of audio_signal output, i.e. [B, D, T] - self.register_accessible_tensor( - name=f'interctc/layer_output_{lth}', tensor=torch.transpose(lth_audio_signal, 1, 2) - ) - self.register_accessible_tensor(name=f'interctc/layer_length_{lth}', tensor=length) - - if self.out_proj is not None: - audio_signal = self.out_proj(audio_signal) - - # Reduction - if self.reduction_position == -1: - audio_signal, length = self.reduction_subsampling(x=audio_signal, lengths=length) - - audio_signal = torch.transpose(audio_signal, 1, 2) - length = length.to(dtype=torch.int64) - - if cache_last_channel is not None: - cache_last_channel_next = torch.stack(cache_last_channel_next, dim=0) - cache_last_time_next = torch.stack(cache_last_time_next, dim=0) - return ( - audio_signal, - length, - cache_last_channel_next, - cache_last_time_next, - torch.clamp(cache_last_channel_len + cache_keep_size, max=cache_len), - ) - else: - return audio_signal, length - - def update_max_seq_length(self, seq_length: int, device): - """ - Updates the maximum sequence length for the model. - - Args: - seq_length (int): New maximum sequence length. - device (torch.device): Device to use for computations. - """ - # Find global max audio length across all nodes - if self.sync_max_audio_length and torch.distributed.is_initialized(): - global_max_len = torch.tensor([seq_length], dtype=torch.float32, device=device) - - # Update across all ranks in the distributed system - torch.distributed.all_reduce(global_max_len, op=torch.distributed.ReduceOp.MAX) - - seq_length = global_max_len.int().item() - - if seq_length > self.max_audio_length: - self.set_max_audio_length(seq_length) - - def set_max_audio_length(self, max_audio_length): - """ - Sets maximum input length. - Pre-calculates internal seq_range mask. - - Args: - max_audio_length (int): New maximum sequence length. - """ - self.max_audio_length = max_audio_length - device = next(self.parameters()).device - dtype = next(self.parameters()).dtype - self.pos_enc.extend_pe(max_audio_length, device, dtype) - - def _create_masks(self, att_context_size, padding_length, max_audio_length, offset, device): - if self.self_attention_model != "rel_pos_local_attn": - att_mask = torch.ones(1, max_audio_length, max_audio_length, dtype=torch.bool, device=device) - - if self.att_context_style == "regular": - if att_context_size[0] >= 0: - att_mask = att_mask.triu(diagonal=-att_context_size[0]) - if att_context_size[1] >= 0: - att_mask = att_mask.tril(diagonal=att_context_size[1]) - elif self.att_context_style == "chunked_limited": - # When right context is unlimited, just the left side of the masking need to get updated - if att_context_size[1] == -1: - if att_context_size[0] >= 0: - att_mask = att_mask.triu(diagonal=-att_context_size[0]) - else: - chunk_size = att_context_size[1] + 1 - # left_chunks_num specifies the number of chunks to be visible by each chunk on the left side - if att_context_size[0] >= 0: - left_chunks_num = att_context_size[0] // chunk_size - else: - left_chunks_num = 10000 - - chunk_idx = torch.arange(0, max_audio_length, dtype=torch.int, device=att_mask.device) - chunk_idx = torch.div(chunk_idx, chunk_size, rounding_mode="trunc") - diff_chunks = chunk_idx.unsqueeze(1) - chunk_idx.unsqueeze(0) - chunked_limited_mask = torch.logical_and( - torch.le(diff_chunks, left_chunks_num), torch.ge(diff_chunks, 0) - ) - att_mask = torch.logical_and(att_mask, chunked_limited_mask.unsqueeze(0)) - else: - att_mask = None - - # pad_mask is the masking to be used to ignore paddings - pad_mask = torch.arange(0, max_audio_length, device=device).expand( - padding_length.size(0), -1 - ) < padding_length.unsqueeze(-1) - - if offset is not None: - pad_mask_off = torch.arange(0, max_audio_length, device=device).expand( - padding_length.size(0), -1 - ) >= offset.unsqueeze(-1) - pad_mask = pad_mask_off.logical_and(pad_mask) - - if att_mask is not None: - # pad_mask_for_att_mask is the mask which helps to ignore paddings - pad_mask_for_att_mask = pad_mask.unsqueeze(1).repeat([1, max_audio_length, 1]) - pad_mask_for_att_mask = torch.logical_and(pad_mask_for_att_mask, pad_mask_for_att_mask.transpose(1, 2)) - # att_mask is the masking to be used by the MHA layers to ignore the tokens not supposed to be visible - att_mask = att_mask[:, :max_audio_length, :max_audio_length] - # paddings should also get ignored, so pad_mask_for_att_mask is used to ignore their corresponding scores - att_mask = torch.logical_and(pad_mask_for_att_mask, att_mask.to(pad_mask_for_att_mask.device)) - att_mask = ~att_mask - - pad_mask = ~pad_mask - return pad_mask, att_mask - - def enable_pad_mask(self, on=True): - """ - Enables or disables the pad mask and assign the boolean state `on`. - - Returns: - mask (bool): The current state of the pad mask. - """ - # On inference, user may choose to disable pad mask - mask = self.use_pad_mask - self.use_pad_mask = on - return mask - - def _calc_context_sizes( - self, att_context_size, att_context_probs, att_context_style, conv_context_size, conv_kernel_size - ): - # convert att_context_size to a standard list of lists - if att_context_size: - att_context_size_all = list(att_context_size) - if isinstance(att_context_size_all[0], int): - att_context_size_all = [att_context_size_all] - for i, att_cs in enumerate(att_context_size_all): - if isinstance(att_cs, ListConfig): - att_context_size_all[i] = list(att_cs) - if att_context_style == "chunked_limited": - if att_cs[0] > 0 and att_cs[0] % (att_cs[1] + 1) > 0: - raise ValueError(f"att_context_size[{i}][0] % (att_context_size[{i}][1] + 1) should be zero!") - if att_cs[1] < 0 and len(att_context_size_all) <= 1: - raise ValueError( - f"Right context (att_context_size[{i}][1]) can not be unlimited for chunked_limited style!" - ) - else: - att_context_size_all = [[-1, -1]] - - if att_context_probs: - if len(att_context_probs) != len(att_context_size_all): - raise ValueError("The size of the att_context_probs should be the same as att_context_size.") - att_context_probs = list(att_context_probs) - if sum(att_context_probs) != 1: - raise ValueError( - "The sum of numbers in att_context_probs should be equal to one to be a distribution." - ) - else: - att_context_probs = [1.0 / len(att_context_size_all)] * len(att_context_size_all) - - if conv_context_size is not None: - if isinstance(conv_context_size, ListConfig): - conv_context_size = list(conv_context_size) - if not isinstance(conv_context_size, list) and not isinstance(conv_context_size, str): - raise ValueError( - "Invalid conv_context_size! It should be the string 'causal' or a list of two integers." - ) - if conv_context_size == "causal": - conv_context_size = [conv_kernel_size - 1, 0] - else: - if conv_context_size[0] + conv_context_size[1] + 1 != conv_kernel_size: - raise ValueError(f"Invalid conv_context_size: {self.conv_context_size}!") - else: - conv_context_size = [(conv_kernel_size - 1) // 2, (conv_kernel_size - 1) // 2] - return att_context_size_all, att_context_size_all[0], att_context_probs, conv_context_size - - def set_default_att_context_size(self, att_context_size): - """ - Sets the default attention context size from `att_context_size` argument. - - Args: - att_context_size (list): The attention context size to be set. - """ - if att_context_size not in self.att_context_size_all: - logging.warning( - f"att_context_size={att_context_size} is not among the list of the supported " - f"look-aheads: {self.att_context_size_all}" - ) - if att_context_size is not None: - self.att_context_size = att_context_size - - self.setup_streaming_params() - - def setup_streaming_params( - self, - chunk_size: int = None, - shift_size: int = None, - left_chunks: int = None, - att_context_size: list = None, - max_context: int = 10000, - ): - """ - This function sets the needed values and parameters to perform streaming. - The configuration would be stored in self.streaming_cfg. - The streaming configuration is needed to simulate streaming inference. - - Args: - chunk_size (int): overrides the chunk size - shift_size (int): overrides the shift size for chunks - left_chunks (int): overrides the number of left chunks visible to each chunk - max_context (int): the value used for the cache size of last_channel layers - if left context is set to infinity (-1) - Defaults to -1 (means feat_out is d_model) - """ - streaming_cfg = CacheAwareStreamingConfig() - - # When att_context_size is not specified, it uses the default_att_context_size - if att_context_size is None: - att_context_size = self.att_context_size - - if chunk_size is not None: - if chunk_size < 1: - raise ValueError("chunk_size needs to be a number larger or equal to one.") - lookahead_steps = chunk_size - 1 - streaming_cfg.cache_drop_size = chunk_size - shift_size - elif self.att_context_style == "chunked_limited": - lookahead_steps = att_context_size[1] - streaming_cfg.cache_drop_size = 0 - elif self.att_context_style == "regular": - lookahead_steps = att_context_size[1] * self.n_layers + self.conv_context_size[1] * self.n_layers - streaming_cfg.cache_drop_size = lookahead_steps - else: - streaming_cfg.cache_drop_size = 0 - lookahead_steps = None - - if chunk_size is None: - streaming_cfg.last_channel_cache_size = att_context_size[0] if att_context_size[0] >= 0 else max_context - else: - if left_chunks is None: - streaming_cfg.last_channel_cache_size = ( - att_context_size[0] if att_context_size[0] >= 0 else max_context - ) - logging.warning( - f"left_chunks is not set. Setting it to default: {streaming_cfg.last_channel_cache_size}." - ) - else: - streaming_cfg.last_channel_cache_size = left_chunks * chunk_size - - if hasattr(self.pre_encode, "get_sampling_frames"): - sampling_frames = self.pre_encode.get_sampling_frames() - else: - sampling_frames = 0 - - if isinstance(sampling_frames, list): - streaming_cfg.chunk_size = [ - sampling_frames[0] + self.subsampling_factor * lookahead_steps, - sampling_frames[1] + self.subsampling_factor * lookahead_steps, - ] - else: - streaming_cfg.chunk_size = sampling_frames * (1 + lookahead_steps) - - if isinstance(sampling_frames, list): - streaming_cfg.shift_size = [ - sampling_frames[0] + sampling_frames[1] * (lookahead_steps - streaming_cfg.cache_drop_size), - sampling_frames[1] + sampling_frames[1] * (lookahead_steps - streaming_cfg.cache_drop_size), - ] - else: - streaming_cfg.shift_size = sampling_frames * (1 + lookahead_steps - streaming_cfg.cache_drop_size) - - if isinstance(streaming_cfg.shift_size, list): - streaming_cfg.valid_out_len = ( - streaming_cfg.shift_size[1] - sampling_frames[1] - ) // self.subsampling_factor + 1 - else: - streaming_cfg.valid_out_len = streaming_cfg.shift_size // self.subsampling_factor - - if hasattr(self.pre_encode, "get_streaming_cache_size"): - streaming_cfg.pre_encode_cache_size = self.pre_encode.get_streaming_cache_size() - else: - streaming_cfg.pre_encode_cache_size = 0 - - if isinstance(streaming_cfg.pre_encode_cache_size, list): - if streaming_cfg.pre_encode_cache_size[1] >= 1: - streaming_cfg.drop_extra_pre_encoded = ( - 1 + (streaming_cfg.pre_encode_cache_size[1] - 1) // self.subsampling_factor - ) - else: - streaming_cfg.drop_extra_pre_encoded = 0 - else: - streaming_cfg.drop_extra_pre_encoded = streaming_cfg.pre_encode_cache_size // self.subsampling_factor - - for m in self.layers.modules(): - if hasattr(m, "_max_cache_len"): - if isinstance(m, MultiHeadAttention): - m.cache_drop_size = streaming_cfg.cache_drop_size - if isinstance(m, CausalConv1D): - m.cache_drop_size = streaming_cfg.cache_drop_size - - self.streaming_cfg = streaming_cfg - - def get_initial_cache_state(self, batch_size=1, dtype=torch.float32, device=None, max_dim=0): - if device is None: - device = next(self.parameters()).device - if max_dim > 0: - create_tensor = torch.randn - else: - create_tensor = torch.zeros - last_time_cache_size = self.conv_context_size[0] - cache_last_channel = create_tensor( - ( - len(self.layers), - batch_size, - self.streaming_cfg.last_channel_cache_size, - self.d_model, - ), - device=device, - dtype=dtype, - ) - cache_last_time = create_tensor( - (len(self.layers), batch_size, self.d_model, last_time_cache_size), - device=device, - dtype=dtype, - ) - if max_dim > 0: - cache_last_channel_len = torch.randint( - 0, - min(max_dim, self.streaming_cfg.last_channel_cache_size), - (batch_size,), - device=device, - dtype=torch.int64, - ) - for i in range(batch_size): - cache_last_channel[:, i, cache_last_channel_len[i] :, :] = 0 - # what is the right rule to zero out cache_last_time? - if cache_last_channel_len[i] == 0: - cache_last_time[:, i, :, :] = 0 - else: - cache_last_channel_len = torch.zeros(batch_size, device=device, dtype=torch.int64) - return cache_last_channel, cache_last_time, cache_last_channel_len - - def change_attention_model( - self, - self_attention_model: str = None, - att_context_size: List[int] = None, - update_config: bool = True, - device: torch.device = None, - ): - """ - Update the self_attention_model which changes the positional encoding and attention layers. - - Args: - self_attention_model (str): type of the attention layer and positional encoding - - 'rel_pos': - relative positional embedding and Transformer-XL - - 'rel_pos_local_attn': - relative positional embedding and Transformer-XL with local attention using - overlapping windows. Attention context is determined by att_context_size parameter. - - 'abs_pos': - absolute positional embedding and Transformer - - If None is provided, the self_attention_model isn't changed. Defaults to None. - att_context_size (List[int]): List of 2 ints corresponding to left and right attention context sizes, - or None to keep as it is. Defaults to None. - update_config (bool): Whether to update the config or not with the new attention model. - Defaults to True. - device (torch.device): If provided, new layers will be moved to the device. - Defaults to None. - """ - - if att_context_size: - att_context_size = list(att_context_size) - else: - att_context_size = self.att_context_size - - if self_attention_model is None: - self_attention_model = self.self_attention_model - - if self_attention_model == 'rel_pos_local_attn' and max(att_context_size) <= 0: - raise ValueError("When using local attention, context size must be set > 0") - - if self_attention_model == "rel_pos": - new_pos_enc = RelPositionalEncoding( - d_model=self._cfg.d_model, - dropout_rate=self._cfg.dropout, - max_len=self._cfg.pos_emb_max_len, - xscale=self.xscale, - dropout_rate_emb=self._cfg.dropout_emb, - ) - elif self_attention_model == 'rel_pos_local_attn': - new_pos_enc = LocalAttRelPositionalEncoding( - att_context_size=att_context_size, - d_model=self._cfg.d_model, - dropout_rate=self._cfg.dropout, - max_len=self._cfg.pos_emb_max_len, - xscale=self.xscale, - dropout_rate_emb=self._cfg.dropout_emb, - ) - elif self_attention_model == "abs_pos": - new_pos_enc = PositionalEncoding( - d_model=self._cfg.d_model, - dropout_rate=self._cfg.dropout, - max_len=self._cfg.pos_emb_max_len, - xscale=self.xscale, - ) - else: - raise ValueError(f"Not valid self_attention_model: '{self_attention_model}'!") - - if device is not None: - new_pos_enc = new_pos_enc.to(device=device) - del self.pos_enc - self.pos_enc = new_pos_enc - self.self_attention_model = self_attention_model - self.att_context_size = att_context_size - self.set_max_audio_length(self.pos_emb_max_len) - - for _, m in self.named_modules(): - if type(m) == ConformerLayer: - if self_attention_model == 'rel_pos': - new_attn = RelPositionMultiHeadAttention( - n_head=self._cfg.n_heads, - n_feat=self._cfg.d_model, - dropout_rate=self._cfg.dropout_att, - max_cache_len=att_context_size[0], - pos_bias_u=None, - pos_bias_v=None, - use_pytorch_sdpa=self.use_pytorch_sdpa, - use_pytorch_sdpa_backends=self.use_pytorch_sdpa_backends, - ) - elif self_attention_model == 'rel_pos_local_attn': - new_attn = RelPositionMultiHeadAttentionLongformer( - n_head=self._cfg.n_heads, - n_feat=self._cfg.d_model, - dropout_rate=self._cfg.dropout_att, - max_cache_len=att_context_size[0], - att_context_size=att_context_size, - pos_bias_u=None, - pos_bias_v=None, - use_pytorch_sdpa=self.use_pytorch_sdpa, - use_pytorch_sdpa_backends=self.use_pytorch_sdpa_backends, - ) - elif self_attention_model == 'abs_pos': - new_attn = MultiHeadAttention( - n_head=self._cfg.n_heads, - n_feat=self._cfg.d_model, - dropout_rate=self._cfg.dropout_att, - max_cache_len=att_context_size[0], - use_pytorch_sdpa=self.use_pytorch_sdpa, - use_pytorch_sdpa_backends=self.use_pytorch_sdpa_backends, - ) - else: - raise ValueError( - f"'{self_attention_model}' is not not a valid value for 'self_attention_model', " - f"valid values can be from ['rel_pos', 'rel_pos_local_attn', 'abs_pos']" - ) - if device is not None: - new_attn = new_attn.to(device=device) - new_attn.load_state_dict(m.self_attn.state_dict(), strict=False) - del m.self_attn - m.self_attn = new_attn - m.self_attention_model = self_attention_model - - if update_config: - with open_dict(self._cfg): - self._cfg.self_attention_model = self_attention_model - self._cfg.att_context_size = att_context_size - - def change_subsampling_conv_chunking_factor(self, subsampling_conv_chunking_factor: int): - """ - Update the conv_chunking_factor (int) - Default is 1 (auto) - Set it to -1 (disabled) or to a specific value (power of 2) if you OOM in the conv subsampling layers - - - Args: - subsampling_conv_chunking_factor (int) - """ - - if not hasattr(self.pre_encode, "change_subsampling_conv_chunking_factor"): - logging.info("Model pre_encoder doesn't have a change_subsampling_conv_chunking_factor method ") - return - - self.pre_encode.change_subsampling_conv_chunking_factor( - subsampling_conv_chunking_factor=subsampling_conv_chunking_factor - ) - - -class ConformerEncoderAdapter(ConformerEncoder, adapter_mixins.AdapterModuleMixin): - """This class inherits from ConformerEncoder and wraps the adapter mixin class.""" - - # Higher level forwarding - def add_adapter(self, name: str, cfg: dict): - cfg = self._update_adapter_cfg_input_dim(cfg) - for conformer_layer in self.layers: # type: adapter_mixins.AdapterModuleMixin - conformer_layer.add_adapter(name, cfg) - - def is_adapter_available(self) -> bool: - return any([conformer_layer.is_adapter_available() for conformer_layer in self.layers]) - - def set_enabled_adapters(self, name: Optional[str] = None, enabled: bool = True): - for conformer_layer in self.layers: # type: adapter_mixins.AdapterModuleMixin - conformer_layer.set_enabled_adapters(name=name, enabled=enabled) - - def get_enabled_adapters(self) -> List[str]: - names = set([]) - for conformer_layer in self.layers: # type: adapter_mixins.AdapterModuleMixin - names.update(conformer_layer.get_enabled_adapters()) - - names = sorted(list(names)) - return names - - def _update_adapter_cfg_input_dim(self, cfg: DictConfig): - cfg = adapter_utils.update_adapter_cfg_input_dim(self, cfg, module_dim=self.d_model) - return cfg - - def get_accepted_adapter_types( - self, - ) -> Set[type]: - types = super().get_accepted_adapter_types() - - if len(types) == 0: - self.set_accepted_adapter_types( - [ - adapter_utils.LINEAR_ADAPTER_CLASSPATH, - adapter_utils.MHA_ADAPTER_CLASSPATH, - adapter_utils.RELMHA_ADAPTER_CLASSPATH, - ] - ) - types = self.get_accepted_adapter_types() - return types - - -class ConformerMultiLayerFeatureExtractor(NeuralModule, Exportable, AccessMixin): - """ - A wrapper module that extracts features from multiple layers of a ConformerEncoder, - by reusing existing mechanisim for interctc loss. - To use it, set `layer_idx_list` to specify the indices of layers to extract from. - Also, you can specify an `aggretator` module to aggregate the features from different layers, - default not aggregating. - """ - - def __init__( - self, - encoder: ConformerEncoder, - layer_idx_list: Optional[List[int]] = None, - aggregator: Optional[NeuralModule] = None, - detach: bool = False, - convert_to_cpu: bool = False, - ): - """ - This class is used to extract features from different layers of the ConformerEncoder. - Args: - encoder: ConformerEncoder instance. - layer_idx_list: List of layer indices to extract features from. If None, all layers are extracted. - aggregator: Aggregator instance. If None, the features are returned as a list. - detach: If True, the features are detached from the graph. - convert_to_cpu: If True, the features are converted to CPU. - """ - super().__init__() - self.encoder = encoder - self.num_layers = len(encoder.layers) - self.layer_idx_list = [] - if not layer_idx_list: - layer_idx_list = list(range(self.num_layers)) - for lid in layer_idx_list: - if lid < -self.num_layers or lid >= self.num_layers: - raise ValueError(f"Invalid layer index {lid} for ConformerEncoder with {self.num_layers} layers.") - if lid < 0: - lid = self.num_layers + lid - self.layer_idx_list.append(lid) - self.layer_idx_list.sort() - logging.info(f"Extracting ConformerEncoder features from layers: {self.layer_idx_list}") - self.enc_access_cfg = { - "interctc": { - "capture_layers": self.layer_idx_list, - }, - "detach": detach, - "convert_to_cpu": convert_to_cpu, - } - self.aggregator = aggregator - - def forward( - self, audio_signal, length, cache_last_channel=None, cache_last_time=None, cache_last_channel_len=None - ) -> Tuple[torch.Tensor, torch.Tensor]: - """ - Args: - same interface as ConformerEncoder.forward() - Returns: - - Tuple[List[Tensor[B,D,T]], List[Tensor[B]]] if aggregator is None - - Tuple[Tensor[B,H,T], Tensor[B]] if aggregator is not None, where H is the hidden size of the aggregator - """ - old_access_flag = self.is_access_enabled(guid=getattr(self, "model_guid", None)) - self.update_access_cfg(self.enc_access_cfg, guid=getattr(self, "model_guid", None)) - self.set_access_enabled(access_enabled=True, guid=getattr(self, "model_guid", None)) - - _ = self.encoder( - audio_signal=audio_signal, - length=length, - cache_last_channel=cache_last_channel, - cache_last_time=cache_last_time, - cache_last_channel_len=cache_last_channel_len, - ) - - # Chunk of code adapted from ConformerEncoder.forward_internal() - total_registry = {} - for module_registry in self.get_module_registry(self.encoder).values(): - for key in module_registry: - if key.startswith("interctc/") and key in total_registry: - raise RuntimeError(f"layer {key} has been logged multiple times!") - total_registry.update(module_registry) - - encoded_list = [] - encoded_len_list = [] - for layer_idx in self.layer_idx_list: - try: - layer_outputs = total_registry[f"interctc/layer_output_{layer_idx}"] - layer_lengths = total_registry[f"interctc/layer_length_{layer_idx}"] - except KeyError: - raise RuntimeError( - f"Intermediate layer {layer_idx} was not captured! " - "Check the layer index and the number of ConformerEncoder layers." - ) - if len(layer_outputs) > 1 or len(layer_lengths) > 1: - raise RuntimeError("Make sure encoder.forward is called exactly one time") - encoded_list.append(layer_outputs[0]) # [B, D, T] - encoded_len_list.append(layer_lengths[0]) # [B] - - self.encoder.reset_registry() - self.set_access_enabled(access_enabled=old_access_flag, guid=getattr(self, "model_guid", None)) - # End of the adapted chunk - - if self.aggregator is not None: - return self.aggregator(encoded_list, encoded_len_list) # Tensor[B,H,T], Tensor[B] - else: - return encoded_list, encoded_len_list # List[Tensor[B,D,T]], List[Tensor[B]] - - -# Register any additional information -if adapter_mixins.get_registered_adapter(ConformerEncoder) is None: - adapter_mixins.register_adapter(base_class=ConformerEncoder, adapter_class=ConformerEncoderAdapter) - - -@dataclass -class ConformerChangeConfig: - """ - Change self_attention_model for Conformer. - - Options: - 'rel_pos': relative positional embedding and Transformer-XL - 'rel_pos_local_attn': relative positional embedding and Transformer-XL with local attention using - overlapping chunks. Attention context is determined by att_context_size parameter. - 'abs_pos': absolute positional embedding and Transformer - """ - - # If None is provided, self_attention_model is not changed. - self_attention_model: Optional[str] = None - - # Change the attention context size by providing 2 integers, - # corresponding to left and right context, or -1 for full context. - # If None is provided, the attention context size isn't changed. - att_context_size: Optional[List[int]] = None diff --git a/nemo/collections/asr/modules/conv_asr.py b/nemo/collections/asr/modules/conv_asr.py deleted file mode 100644 index b5fdac06b07d3af099958511e59d89c4d339902e..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/conv_asr.py +++ /dev/null @@ -1,1003 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -from collections import OrderedDict -from dataclasses import dataclass, field -from typing import List, Optional, Set, Union - -import torch -import torch.distributed -import torch.nn as nn -import torch.nn.functional as F -from omegaconf import MISSING, DictConfig, ListConfig, OmegaConf - -from nemo.collections.asr.parts.submodules.jasper import ( - JasperBlock, - MaskedConv1d, - ParallelBlock, - SqueezeExcite, - init_weights, - jasper_activations, -) -from nemo.collections.asr.parts.submodules.tdnn_attention import ( - AttentivePoolLayer, - StatsPoolLayer, - TDNNModule, - TDNNSEModule, -) -from nemo.collections.asr.parts.utils import adapter_utils -from nemo.core.classes.common import typecheck -from nemo.core.classes.exportable import Exportable -from nemo.core.classes.mixins import AccessMixin, adapter_mixins -from nemo.core.classes.module import NeuralModule -from nemo.core.neural_types import ( - AcousticEncodedRepresentation, - LengthsType, - LogitsType, - LogprobsType, - NeuralType, - SpectrogramType, -) -from nemo.utils import logging - -__all__ = ['ConvASRDecoder', 'ConvASREncoder', 'ConvASRDecoderClassification'] - - -class ConvASREncoder(NeuralModule, Exportable, AccessMixin): - """ - Convolutional encoder for ASR models. With this class you can implement JasperNet and QuartzNet models. - - Based on these papers: - https://arxiv.org/pdf/1904.03288.pdf - https://arxiv.org/pdf/1910.10261.pdf - """ - - def _prepare_for_export(self, **kwargs): - m_count = 0 - for name, m in self.named_modules(): - if isinstance(m, MaskedConv1d): - m.use_mask = False - m_count += 1 - - Exportable._prepare_for_export(self, **kwargs) - logging.warning(f"Turned off {m_count} masked convolutions") - - def input_example(self, max_batch=1, max_dim=8192): - """ - Generates input examples for tracing etc. - Returns: - A tuple of input examples. - """ - device = next(self.parameters()).device - input_example = torch.randn(max_batch, self._feat_in, max_dim, device=device) - lens = torch.full(size=(input_example.shape[0],), fill_value=max_dim, device=device) - return tuple([input_example, lens]) - - @property - def input_types(self): - """Returns definitions of module input ports.""" - return OrderedDict( - { - "audio_signal": NeuralType(('B', 'D', 'T'), SpectrogramType()), - "length": NeuralType(tuple('B'), LengthsType()), - } - ) - - @property - def output_types(self): - """Returns definitions of module output ports.""" - return OrderedDict( - { - "outputs": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), - "encoded_lengths": NeuralType(tuple('B'), LengthsType()), - } - ) - - def __init__( - self, - jasper, - activation: str, - feat_in: int, - normalization_mode: str = "batch", - residual_mode: str = "add", - norm_groups: int = -1, - conv_mask: bool = True, - frame_splicing: int = 1, - init_mode: Optional[str] = 'xavier_uniform', - quantize: bool = False, - ): - super().__init__() - if isinstance(jasper, ListConfig): - jasper = OmegaConf.to_container(jasper) - - activation = jasper_activations[activation]() - - # If the activation can be executed in place, do so. - if hasattr(activation, 'inplace'): - activation.inplace = True - - feat_in = feat_in * frame_splicing - - self._feat_in = feat_in - - residual_panes = [] - encoder_layers = [] - self.dense_residual = False - self._subsampling_factor = 1 - for layer_idx, lcfg in enumerate(jasper): - dense_res = [] - if lcfg.get('residual_dense', False): - residual_panes.append(feat_in) - dense_res = residual_panes - self.dense_residual = True - groups = lcfg.get('groups', 1) - separable = lcfg.get('separable', False) - heads = lcfg.get('heads', -1) - residual_mode = lcfg.get('residual_mode', residual_mode) - se = lcfg.get('se', False) - se_reduction_ratio = lcfg.get('se_reduction_ratio', 8) - se_context_window = lcfg.get('se_context_size', -1) - se_interpolation_mode = lcfg.get('se_interpolation_mode', 'nearest') - kernel_size_factor = lcfg.get('kernel_size_factor', 1.0) - stride_last = lcfg.get('stride_last', False) - future_context = lcfg.get('future_context', -1) - encoder_layers.append( - JasperBlock( - feat_in, - lcfg['filters'], - repeat=lcfg['repeat'], - kernel_size=lcfg['kernel'], - stride=lcfg['stride'], - dilation=lcfg['dilation'], - dropout=lcfg['dropout'], - residual=lcfg['residual'], - groups=groups, - separable=separable, - heads=heads, - residual_mode=residual_mode, - normalization=normalization_mode, - norm_groups=norm_groups, - activation=activation, - residual_panes=dense_res, - conv_mask=conv_mask, - se=se, - se_reduction_ratio=se_reduction_ratio, - se_context_window=se_context_window, - se_interpolation_mode=se_interpolation_mode, - kernel_size_factor=kernel_size_factor, - stride_last=stride_last, - future_context=future_context, - quantize=quantize, - layer_idx=layer_idx, - ) - ) - feat_in = lcfg['filters'] - self._subsampling_factor *= ( - int(lcfg['stride'][0]) if isinstance(lcfg['stride'], List) else int(lcfg['stride']) - ) - - self._feat_out = feat_in - - self.encoder = torch.nn.Sequential(*encoder_layers) - self.apply(lambda x: init_weights(x, mode=init_mode)) - - self.max_audio_length = 0 - - @typecheck() - def forward(self, audio_signal, length): - self.update_max_sequence_length(seq_length=audio_signal.size(2), device=audio_signal.device) - s_input, length = self.encoder(([audio_signal], length)) - if length is None: - return s_input[-1] - - return s_input[-1], length - - def update_max_sequence_length(self, seq_length: int, device): - """ - Find global max audio length across all nodes in distributed training and update the max_audio_length - """ - if torch.distributed.is_initialized(): - global_max_len = torch.tensor([seq_length], dtype=torch.float32, device=device) - - # Update across all ranks in the distributed system - torch.distributed.all_reduce(global_max_len, op=torch.distributed.ReduceOp.MAX) - - seq_length = global_max_len.int().item() - - if seq_length > self.max_audio_length: - if seq_length < 5000: - seq_length = seq_length * 2 - elif seq_length < 10000: - seq_length = seq_length * 1.5 - self.max_audio_length = seq_length - - device = next(self.parameters()).device - seq_range = torch.arange(0, self.max_audio_length, device=device) - if hasattr(self, 'seq_range'): - self.seq_range = seq_range - else: - self.register_buffer('seq_range', seq_range, persistent=False) - - # Update all submodules - for name, m in self.named_modules(): - if isinstance(m, MaskedConv1d): - m.update_masked_length(self.max_audio_length, seq_range=self.seq_range) - elif isinstance(m, SqueezeExcite): - m.set_max_len(self.max_audio_length, seq_range=self.seq_range) - - @property - def subsampling_factor(self) -> int: - return self._subsampling_factor - - -class ParallelConvASREncoder(NeuralModule, Exportable): - """ - Convolutional encoder for ASR models with parallel blocks. - """ - - def _prepare_for_export(self): - m_count = 0 - for m in self.modules(): - if isinstance(m, MaskedConv1d): - m.use_mask = False - m_count += 1 - logging.warning(f"Turned off {m_count} masked convolutions") - - def input_example(self, max_batch=1, max_dim=256): - """ - Generates input examples for tracing etc. - Returns: - A tuple of input examples. - """ - input_example = torch.randn(max_batch, self._feat_in, max_dim).to(next(self.parameters()).device) - return tuple([input_example]) - - @property - def disabled_deployment_input_names(self): - """Implement this method to return a set of input names disabled for export""" - return set(["length"]) - - @property - def disabled_deployment_output_names(self): - """Implement this method to return a set of output names disabled for export""" - return set(["encoded_lengths"]) - - def save_to(self, save_path: str): - pass - - @classmethod - def restore_from(cls, restore_path: str): - pass - - @property - def input_types(self): - """Returns definitions of module input ports.""" - return OrderedDict( - { - "audio_signal": NeuralType(('B', 'D', 'T'), SpectrogramType()), - "length": NeuralType(tuple('B'), LengthsType()), - } - ) - - @property - def output_types(self): - """Returns definitions of module output ports.""" - return OrderedDict( - { - "outputs": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), - "encoded_lengths": NeuralType(tuple('B'), LengthsType()), - } - ) - - def __init__( - self, - jasper, - activation: str, - feat_in: int, - normalization_mode: str = "batch", - residual_mode: str = "add", - norm_groups: int = -1, - conv_mask: bool = True, - frame_splicing: int = 1, - init_mode: Optional[str] = 'xavier_uniform', - aggregation_mode: Optional[str] = None, - quantize: bool = False, - ): - super().__init__() - if isinstance(jasper, ListConfig): - jasper = OmegaConf.to_container(jasper) - - activation = jasper_activations[activation]() - feat_in = feat_in * frame_splicing - - self._feat_in = feat_in - - residual_panes = [] - encoder_layers = [] - self.dense_residual = False - for lcfg in jasper: - dense_res = [] - if lcfg.get('residual_dense', False): - residual_panes.append(feat_in) - dense_res = residual_panes - self.dense_residual = True - groups = lcfg.get('groups', 1) - separable = lcfg.get('separable', False) - heads = lcfg.get('heads', -1) - residual_mode = lcfg.get('residual_mode', residual_mode) - se = lcfg.get('se', False) - se_reduction_ratio = lcfg.get('se_reduction_ratio', 8) - se_context_window = lcfg.get('se_context_size', -1) - se_interpolation_mode = lcfg.get('se_interpolation_mode', 'nearest') - kernel_size_factor = lcfg.get('kernel_size_factor', 1.0) - stride_last = lcfg.get('stride_last', False) - aggregation_mode = lcfg.get('aggregation_mode', 'sum') - block_dropout = lcfg.get('block_dropout', 0.0) - parallel_residual_mode = lcfg.get('parallel_residual_mode', 'sum') - - parallel_blocks = [] - for kernel_size in lcfg['kernel']: - parallel_blocks.append( - JasperBlock( - feat_in, - lcfg['filters'], - repeat=lcfg['repeat'], - kernel_size=[kernel_size], - stride=lcfg['stride'], - dilation=lcfg['dilation'], - dropout=lcfg['dropout'], - residual=lcfg['residual'], - groups=groups, - separable=separable, - heads=heads, - residual_mode=residual_mode, - normalization=normalization_mode, - norm_groups=norm_groups, - activation=activation, - residual_panes=dense_res, - conv_mask=conv_mask, - se=se, - se_reduction_ratio=se_reduction_ratio, - se_context_window=se_context_window, - se_interpolation_mode=se_interpolation_mode, - kernel_size_factor=kernel_size_factor, - stride_last=stride_last, - quantize=quantize, - ) - ) - if len(parallel_blocks) == 1: - encoder_layers.append(parallel_blocks[0]) - else: - encoder_layers.append( - ParallelBlock( - parallel_blocks, - aggregation_mode=aggregation_mode, - block_dropout_prob=block_dropout, - residual_mode=parallel_residual_mode, - in_filters=feat_in, - out_filters=lcfg['filters'], - ) - ) - feat_in = lcfg['filters'] - - self._feat_out = feat_in - - self.encoder = torch.nn.Sequential(*encoder_layers) - self.apply(lambda x: init_weights(x, mode=init_mode)) - - @typecheck() - def forward(self, audio_signal, length=None): - s_input, length = self.encoder(([audio_signal], length)) - if length is None: - return s_input[-1] - - return s_input[-1], length - - -class ConvASRDecoder(NeuralModule, Exportable, adapter_mixins.AdapterModuleMixin): - """Simple ASR Decoder for use with CTC-based models such as JasperNet and QuartzNet - - Based on these papers: - https://arxiv.org/pdf/1904.03288.pdf - https://arxiv.org/pdf/1910.10261.pdf - https://arxiv.org/pdf/2005.04290.pdf - """ - - @property - def input_types(self): - return OrderedDict({"encoder_output": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation())}) - - @property - def output_types(self): - return OrderedDict({"logprobs": NeuralType(('B', 'T', 'D'), LogprobsType())}) - - def __init__(self, feat_in, num_classes, init_mode="xavier_uniform", vocabulary=None, add_blank=True): - super().__init__() - - if vocabulary is None and num_classes < 0: - raise ValueError("Neither of the vocabulary and num_classes are set! At least one of them need to be set.") - - if num_classes <= 0: - num_classes = len(vocabulary) - logging.info(f"num_classes of ConvASRDecoder is set to the size of the vocabulary: {num_classes}.") - - if vocabulary is not None: - if num_classes != len(vocabulary): - raise ValueError( - f"If vocabulary is specified, it's length should be equal to the num_classes. \ - Instead got: num_classes={num_classes} and len(vocabulary)={len(vocabulary)}" - ) - self.__vocabulary = vocabulary - self._feat_in = feat_in - # Add 1 for blank char - self._num_classes = num_classes + 1 if add_blank else num_classes - - self.decoder_layers = torch.nn.Sequential( - torch.nn.Conv1d(self._feat_in, self._num_classes, kernel_size=1, bias=True) - ) - self.apply(lambda x: init_weights(x, mode=init_mode)) - - accepted_adapters = [adapter_utils.LINEAR_ADAPTER_CLASSPATH] - self.set_accepted_adapter_types(accepted_adapters) - - # to change, requires running ``model.temperature = T`` explicitly - self.temperature = 1.0 - - @typecheck() - def forward(self, encoder_output): - # Adapter module forward step - if self.is_adapter_available(): - encoder_output = encoder_output.transpose(1, 2) # [B, T, C] - encoder_output = self.forward_enabled_adapters(encoder_output) - encoder_output = encoder_output.transpose(1, 2) # [B, C, T] - - if self.temperature != 1.0: - return torch.nn.functional.log_softmax( - self.decoder_layers(encoder_output).transpose(1, 2) / self.temperature, dim=-1 - ) - return torch.nn.functional.log_softmax(self.decoder_layers(encoder_output).transpose(1, 2), dim=-1) - - def input_example(self, max_batch=1, max_dim=256): - """ - Generates input examples for tracing etc. - Returns: - A tuple of input examples. - """ - input_example = torch.randn(max_batch, self._feat_in, max_dim).to(next(self.parameters()).device) - return tuple([input_example]) - - def _prepare_for_export(self, **kwargs): - m_count = 0 - for m in self.modules(): - if type(m).__name__ == "MaskedConv1d": - m.use_mask = False - m_count += 1 - if m_count > 0: - logging.warning(f"Turned off {m_count} masked convolutions") - Exportable._prepare_for_export(self, **kwargs) - - # Adapter method overrides - def add_adapter(self, name: str, cfg: DictConfig): - # Update the config with correct input dim - cfg = self._update_adapter_cfg_input_dim(cfg) - # Add the adapter - super().add_adapter(name=name, cfg=cfg) - - def _update_adapter_cfg_input_dim(self, cfg: DictConfig): - cfg = adapter_utils.update_adapter_cfg_input_dim(self, cfg, module_dim=self._feat_in) - return cfg - - @property - def vocabulary(self): - return self.__vocabulary - - @property - def num_classes_with_blank(self): - return self._num_classes - - -class ConvASRDecoderReconstruction(NeuralModule, Exportable): - """ASR Decoder for reconstructing masked regions of spectrogram""" - - @property - def input_types(self): - return OrderedDict({"encoder_output": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation())}) - - @property - def output_types(self): - if self.apply_softmax: - return OrderedDict({"out": NeuralType(('B', 'T', 'D'), LogprobsType())}) - else: - return OrderedDict({"out": NeuralType(('B', 'T', 'D'), AcousticEncodedRepresentation())}) - - def __init__( - self, - feat_in, - feat_out, - feat_hidden, - stride_layers=0, - non_stride_layers=0, - kernel_size=11, - init_mode="xavier_uniform", - activation="relu", - stride_transpose=True, - apply_softmax=False, - ): - super().__init__() - - if ((stride_layers + non_stride_layers) > 0) and (kernel_size < 3 or kernel_size % 2 == 0): - raise ValueError("Kernel size in this decoder needs to be >= 3 and odd when using at least 1 conv layer.") - - activation = jasper_activations[activation]() - - self.feat_in = feat_in - self.feat_out = feat_out - self.feat_hidden = feat_hidden - - self.decoder_layers = [nn.Conv1d(self.feat_in, self.feat_hidden, kernel_size=1, bias=True)] - for i in range(stride_layers): - self.decoder_layers.append(activation) - if stride_transpose: - self.decoder_layers.append( - nn.ConvTranspose1d( - self.feat_hidden, - self.feat_hidden, - kernel_size, - stride=2, - padding=(kernel_size - 3) // 2 + 1, - output_padding=1, - bias=True, - groups=self.feat_hidden, - ) - ) - else: - self.decoder_layers.append( - nn.Conv1d( - self.feat_hidden, - self.feat_hidden, - kernel_size, - stride=2, - padding=(kernel_size - 1) // 2, - bias=True, - groups=self.feat_hidden, - ) - ) - self.decoder_layers.append(nn.Conv1d(self.feat_hidden, self.feat_hidden, kernel_size=1, bias=True)) - self.decoder_layers.append(nn.BatchNorm1d(self.feat_hidden, eps=1e-3, momentum=0.1)) - for i in range(non_stride_layers): - self.decoder_layers.append(activation) - self.decoder_layers.append( - nn.Conv1d( - self.feat_hidden, - self.feat_hidden, - kernel_size, - bias=True, - groups=self.feat_hidden, - padding=kernel_size // 2, - ) - ) - self.decoder_layers.append(nn.Conv1d(self.feat_hidden, self.feat_hidden, kernel_size=1, bias=True)) - self.decoder_layers.append(nn.BatchNorm1d(self.feat_hidden, eps=1e-3, momentum=0.1)) - - self.decoder_layers.append(activation) - self.decoder_layers.append(nn.Conv1d(self.feat_hidden, self.feat_out, kernel_size=1, bias=True)) - - self.decoder_layers = nn.Sequential(*self.decoder_layers) - self.apply_softmax = apply_softmax - - self.apply(lambda x: init_weights(x, mode=init_mode)) - - @typecheck() - def forward(self, encoder_output): - out = self.decoder_layers(encoder_output).transpose(-2, -1) - if self.apply_softmax: - out = torch.nn.functional.log_softmax(out, dim=-1) - return out - - def input_example(self, max_batch=1, max_dim=256): - """ - Generates input examples for tracing etc. - Returns: - A tuple of input examples. - """ - input_example = torch.randn(max_batch, self._feat_in, max_dim).to(next(self.parameters()).device) - return tuple([input_example]) - - def _prepare_for_export(self, **kwargs): - m_count = 0 - for m in self.modules(): - if type(m).__name__ == "MaskedConv1d": - m.use_mask = False - m_count += 1 - if m_count > 0: - logging.warning(f"Turned off {m_count} masked convolutions") - Exportable._prepare_for_export(self, **kwargs) - - -class ConvASRDecoderClassification(NeuralModule, Exportable): - """Simple ASR Decoder for use with classification models such as JasperNet and QuartzNet - - Based on these papers: - https://arxiv.org/pdf/2005.04290.pdf - """ - - def input_example(self, max_batch=1, max_dim=256): - """ - Generates input examples for tracing etc. - Returns: - A tuple of input examples. - """ - input_example = torch.randn(max_batch, self._feat_in, max_dim).to(next(self.parameters()).device) - return tuple([input_example]) - - @property - def input_types(self): - return OrderedDict({"encoder_output": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation())}) - - @property - def output_types(self): - return OrderedDict({"logits": NeuralType(('B', 'D'), LogitsType())}) - - def __init__( - self, - feat_in: int, - num_classes: int, - init_mode: Optional[str] = "xavier_uniform", - return_logits: bool = True, - pooling_type='avg', - ): - super().__init__() - - self._feat_in = feat_in - self._return_logits = return_logits - self._num_classes = num_classes - - if pooling_type == 'avg': - self.pooling = torch.nn.AdaptiveAvgPool1d(1) - elif pooling_type == 'max': - self.pooling = torch.nn.AdaptiveMaxPool1d(1) - else: - raise ValueError('Pooling type chosen is not valid. Must be either `avg` or `max`') - - self.decoder_layers = torch.nn.Sequential(torch.nn.Linear(self._feat_in, self._num_classes, bias=True)) - self.apply(lambda x: init_weights(x, mode=init_mode)) - - def forward(self, encoder_output, **kwargs): - batch, in_channels, timesteps = encoder_output.size() - - encoder_output = self.pooling(encoder_output).view(batch, in_channels) # [B, C] - logits = self.decoder_layers(encoder_output) # [B, num_classes] - - if self._return_logits: - return logits - - return torch.nn.functional.softmax(logits, dim=-1) - - @property - def num_classes(self): - return self._num_classes - - -class ECAPAEncoder(NeuralModule, Exportable): - """ - Modified ECAPA Encoder layer without Res2Net module for faster training and inference which achieves - better numbers on speaker diarization tasks - Reference: ECAPA-TDNN Embeddings for Speaker Diarization (https://arxiv.org/pdf/2104.01466.pdf) - - input: - feat_in: input feature shape (mel spec feature shape) - filters: list of filter shapes for SE_TDNN modules - kernel_sizes: list of kernel shapes for SE_TDNN modules - dilations: list of dilations for group conv se layer - scale: scale value to group wider conv channels (deafult:8) - - output: - outputs : encoded output - output_length: masked output lengths - """ - - @property - def input_types(self): - """Returns definitions of module input ports.""" - return OrderedDict( - { - "audio_signal": NeuralType(('B', 'D', 'T'), SpectrogramType()), - "length": NeuralType(tuple('B'), LengthsType()), - } - ) - - @property - def output_types(self): - """Returns definitions of module output ports.""" - return OrderedDict( - { - "outputs": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), - "encoded_lengths": NeuralType(tuple('B'), LengthsType()), - } - ) - - def __init__( - self, - feat_in: int, - filters: list, - kernel_sizes: list, - dilations: list, - scale: int = 8, - init_mode: str = 'xavier_uniform', - ): - super().__init__() - self.layers = nn.ModuleList() - self.layers.append(TDNNModule(feat_in, filters[0], kernel_size=kernel_sizes[0], dilation=dilations[0])) - - for i in range(len(filters) - 2): - self.layers.append( - TDNNSEModule( - filters[i], - filters[i + 1], - group_scale=scale, - se_channels=128, - kernel_size=kernel_sizes[i + 1], - dilation=dilations[i + 1], - ) - ) - self.feature_agg = TDNNModule(filters[-1], filters[-1], kernel_sizes[-1], dilations[-1]) - self.apply(lambda x: init_weights(x, mode=init_mode)) - - def forward(self, audio_signal, length=None): - x = audio_signal - outputs = [] - - for layer in self.layers: - x = layer(x, length=length) - outputs.append(x) - - x = torch.cat(outputs[1:], dim=1) - x = self.feature_agg(x) - return x, length - - -class SpeakerDecoder(NeuralModule, Exportable): - """ - Speaker Decoder creates the final neural layers that maps from the outputs - of Jasper Encoder to the embedding layer followed by speaker based softmax loss. - - Args: - feat_in (int): Number of channels being input to this module - num_classes (int): Number of unique speakers in dataset - emb_sizes (list) : shapes of intermediate embedding layers (we consider speaker embbeddings - from 1st of this layers). Defaults to [1024,1024] - pool_mode (str) : Pooling strategy type. options are 'xvector','tap', 'attention' - Defaults to 'xvector (mean and variance)' - tap (temporal average pooling: just mean) - attention (attention based pooling) - init_mode (str): Describes how neural network parameters are - initialized. Options are ['xavier_uniform', 'xavier_normal', - 'kaiming_uniform','kaiming_normal']. - Defaults to "xavier_uniform". - """ - - def input_example(self, max_batch=1, max_dim=256): - """ - Generates input examples for tracing etc. - Returns: - A tuple of input examples. - """ - input_example = torch.randn(max_batch, self.input_feat_in, max_dim).to(next(self.parameters()).device) - return tuple([input_example]) - - @property - def input_types(self): - return OrderedDict( - { - "encoder_output": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), - "length": NeuralType(('B',), LengthsType(), optional=True), - } - ) - - @property - def output_types(self): - return OrderedDict( - { - "logits": NeuralType(('B', 'D'), LogitsType()), - "embs": NeuralType(('B', 'D'), AcousticEncodedRepresentation()), - } - ) - - def __init__( - self, - feat_in: int, - num_classes: int, - emb_sizes: Optional[Union[int, list]] = 256, - pool_mode: str = 'xvector', - angular: bool = False, - attention_channels: int = 128, - init_mode: str = "xavier_uniform", - ): - super().__init__() - self.angular = angular - self.emb_id = 2 - bias = False if self.angular else True - emb_sizes = [emb_sizes] if type(emb_sizes) is int else emb_sizes - - self._num_classes = num_classes - self.pool_mode = pool_mode.lower() - if self.pool_mode == 'xvector' or self.pool_mode == 'tap': - self._pooling = StatsPoolLayer(feat_in=feat_in, pool_mode=self.pool_mode) - affine_type = 'linear' - elif self.pool_mode == 'attention': - self._pooling = AttentivePoolLayer(inp_filters=feat_in, attention_channels=attention_channels) - affine_type = 'conv' - - shapes = [self._pooling.feat_in] - for size in emb_sizes: - shapes.append(int(size)) - - emb_layers = [] - for shape_in, shape_out in zip(shapes[:-1], shapes[1:]): - layer = self.affine_layer(shape_in, shape_out, learn_mean=False, affine_type=affine_type) - emb_layers.append(layer) - - self.emb_layers = nn.ModuleList(emb_layers) - - self.final = nn.Linear(shapes[-1], self._num_classes, bias=bias) - - self.apply(lambda x: init_weights(x, mode=init_mode)) - - def affine_layer( - self, - inp_shape, - out_shape, - learn_mean=True, - affine_type='conv', - ): - if affine_type == 'conv': - layer = nn.Sequential( - nn.BatchNorm1d(inp_shape, affine=True, track_running_stats=True), - nn.Conv1d(inp_shape, out_shape, kernel_size=1), - ) - - else: - layer = nn.Sequential( - nn.Linear(inp_shape, out_shape), - nn.BatchNorm1d(out_shape, affine=learn_mean, track_running_stats=True), - nn.ReLU(), - ) - - return layer - - @typecheck() - def forward(self, encoder_output, length=None): - pool = self._pooling(encoder_output, length) - - for layer in self.emb_layers: - last_pool = pool - pool = layer(pool) - emb = layer[: self.emb_id](last_pool) - - pool = pool.squeeze(-1) - if self.angular: - for W in self.final.parameters(): - W = F.normalize(W, p=2, dim=1) - pool = F.normalize(pool, p=2, dim=1) - - out = self.final(pool) - - return out, emb.squeeze(-1) - - -class ConvASREncoderAdapter(ConvASREncoder, adapter_mixins.AdapterModuleMixin): - - # Higher level forwarding - def add_adapter(self, name: str, cfg: dict): - for jasper_block in self.encoder: # type: adapter_mixins.AdapterModuleMixin - cfg = self._update_adapter_cfg_input_dim(jasper_block, cfg) - - jasper_block.set_accepted_adapter_types(self.get_accepted_adapter_types()) - jasper_block.add_adapter(name, cfg) - - def is_adapter_available(self) -> bool: - return any([jasper_block.is_adapter_available() for jasper_block in self.encoder]) - - def set_enabled_adapters(self, name: Optional[str] = None, enabled: bool = True): - for jasper_block in self.encoder: # type: adapter_mixins.AdapterModuleMixin - jasper_block.set_enabled_adapters(name=name, enabled=enabled) - - def get_enabled_adapters(self) -> List[str]: - names = set([]) - for jasper_block in self.encoder: # type: adapter_mixins.AdapterModuleMixin - names.update(jasper_block.get_enabled_adapters()) - - names = sorted(list(names)) - return names - - def _update_adapter_cfg_input_dim(self, block: JasperBlock, cfg): - cfg = adapter_utils.update_adapter_cfg_input_dim(self, cfg, module_dim=block.planes) - return cfg - - def get_accepted_adapter_types( - self, - ) -> Set[type]: - types = super().get_accepted_adapter_types() - - if len(types) == 0: - self.set_accepted_adapter_types( - [ - adapter_utils.LINEAR_ADAPTER_CLASSPATH, - ] - ) - types = self.get_accepted_adapter_types() - return types - - -@dataclass -class JasperEncoderConfig: - filters: int = MISSING - repeat: int = MISSING - kernel: List[int] = MISSING - stride: List[int] = MISSING - dilation: List[int] = MISSING - dropout: float = MISSING - residual: bool = MISSING - - # Optional arguments - groups: int = 1 - separable: bool = False - heads: int = -1 - residual_mode: str = "add" - residual_dense: bool = False - se: bool = False - se_reduction_ratio: int = 8 - se_context_size: int = -1 - se_interpolation_mode: str = 'nearest' - kernel_size_factor: float = 1.0 - stride_last: bool = False - - -@dataclass -class ConvASREncoderConfig: - _target_: str = 'nemo.collections.asr.modules.ConvASREncoder' - jasper: Optional[List[JasperEncoderConfig]] = field(default_factory=list) - activation: str = MISSING - feat_in: int = MISSING - normalization_mode: str = "batch" - residual_mode: str = "add" - norm_groups: int = -1 - conv_mask: bool = True - frame_splicing: int = 1 - init_mode: Optional[str] = "xavier_uniform" - - -@dataclass -class ConvASRDecoderConfig: - _target_: str = 'nemo.collections.asr.modules.ConvASRDecoder' - feat_in: int = MISSING - num_classes: int = MISSING - init_mode: Optional[str] = "xavier_uniform" - vocabulary: Optional[List[str]] = field(default_factory=list) - - -@dataclass -class ConvASRDecoderClassificationConfig: - _target_: str = 'nemo.collections.asr.modules.ConvASRDecoderClassification' - feat_in: int = MISSING - num_classes: int = MISSING - init_mode: Optional[str] = "xavier_uniform" - return_logits: bool = True - pooling_type: str = 'avg' - - -""" -Register any additional information -""" -if adapter_mixins.get_registered_adapter(ConvASREncoder) is None: - adapter_mixins.register_adapter(base_class=ConvASREncoder, adapter_class=ConvASREncoderAdapter) diff --git a/nemo/collections/asr/modules/flashlight_decoder.py b/nemo/collections/asr/modules/flashlight_decoder.py deleted file mode 100644 index 05a111ebb7e76516fb1c3a3ae84d0998c53d5f22..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/flashlight_decoder.py +++ /dev/null @@ -1,290 +0,0 @@ -# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import itertools -import math -from typing import Iterable, List, Optional, Tuple, Union - -import numpy as np -import torch - -from nemo.collections.common.tokenizers.tokenizer_spec import TokenizerSpec -from nemo.core.classes import NeuralModule, typecheck -from nemo.core.neural_types import LengthsType, LogprobsType, NeuralType, PredictionsType - - -class _TokensWrapper: - def __init__(self, vocabulary: List[str], tokenizer: TokenizerSpec): - self.vocabulary = vocabulary - self.tokenizer = tokenizer - - if tokenizer is None: - self.reverse_map = {self.vocabulary[i]: i for i in range(len(self.vocabulary))} - - self.vocab_len = len(self.vocabulary) - - if (self.tokenizer is not None) and hasattr(self.tokenizer, 'unk_id') and self.tokenizer.unk_id is not None: - self.unknown_id = self.tokenizer.unk_id - elif ' ' in self.vocabulary: - self.unknown_id = self.token_to_id(' ') - elif '' in self.vocabulary: - self.unknown_id = self.token_to_id('') - else: - self.unknown_id = -1 - - @property - def blank(self): - return self.vocab_len - - @property - def unk_id(self): - return self.unknown_id - - @property - def vocab(self): - return self.vocabulary - - @property - def vocab_size(self): - # the +1 is because we add the blank id - return self.vocab_len + 1 - - def token_to_id(self, token: str): - if token == self.blank: - return -1 - - if self.tokenizer is not None: - return self.tokenizer.token_to_id(token) - else: - return self.reverse_map[token] - - def text_to_tokens(self, text: str): - if self.tokenizer is not None: - return self.tokenizer.text_to_tokens(text) - else: - return list(text) - - -class FlashLightKenLMBeamSearchDecoder(NeuralModule): - ''' - @property - def input_types(self): - """Returns definitions of module input ports. - """ - return { - "log_probs": NeuralType(('B', 'T', 'D'), LogprobsType()), - } - - @property - def output_types(self): - """Returns definitions of module output ports. - """ - return {"hypos": NeuralType(('B'), PredictionsType())} - ''' - - def __init__( - self, - lm_path: str, - vocabulary: List[str], - tokenizer: Optional[TokenizerSpec] = None, - lexicon_path: Optional[str] = None, - boost_path: Optional[str] = None, - beam_size: int = 32, - beam_size_token: int = 32, - beam_threshold: float = 25.0, - lm_weight: float = 2.0, - word_score: float = -1.0, - unk_weight: float = -math.inf, - sil_weight: float = 0.0, - ): - - try: - from flashlight.lib.text.decoder import ( - LM, - CriterionType, - KenLM, - LexiconDecoder, - LexiconDecoderOptions, - SmearingMode, - Trie, - ) - from flashlight.lib.text.dictionary import create_word_dict, load_words - except ModuleNotFoundError: - raise ModuleNotFoundError( - "FlashLightKenLMBeamSearchDecoder requires the installation of flashlight python bindings " - "from https://github.com/flashlight/text. Please follow the build instructions there." - ) - - super().__init__() - - self.criterion_type = CriterionType.CTC - self.tokenizer_wrapper = _TokensWrapper(vocabulary, tokenizer) - self.vocab_size = self.tokenizer_wrapper.vocab_size - self.blank = self.tokenizer_wrapper.blank - self.silence = self.tokenizer_wrapper.unk_id - - if lexicon_path is not None: - self.lexicon = load_words(lexicon_path) - self.word_dict = create_word_dict(self.lexicon) - self.unk_word = self.word_dict.get_index("") - - # loads in the boosted words if given via a file - if boost_path is not None: - with open(boost_path, 'r', encoding='utf_8') as fr: - boost_words = [line.strip().split('\t') for line in fr] - boost_words = {w[0]: w[1] for w in boost_words} - else: - boost_words = {} - - # add OOV boosted words to word_dict so it gets picked up in LM obj creation - for word in boost_words.keys(): - if word not in self.lexicon: - self.word_dict.add_entry(word) - - # loads in the kenlm binary and combines in with the dictionary object from the lexicon - # this gives a mapping between each entry in the kenlm binary and its mapping to whatever - # numeraire is used by the AM, which is explicitly mapped via the lexicon - # this information is ued to build a vocabulary trie for decoding - self.lm = KenLM(lm_path, self.word_dict) - self.trie = Trie(self.vocab_size, self.silence) - - start_state = self.lm.start(False) - for i, (word, spellings) in enumerate(self.lexicon.items()): - word_idx = self.word_dict.get_index(word) - _, score = self.lm.score(start_state, word_idx) - for spelling in spellings: - spelling_idxs = [self.tokenizer_wrapper.token_to_id(token) for token in spelling] - if self.tokenizer_wrapper.unk_id in spelling_idxs: - print(f'tokenizer has unknown id for word[ {word} ] {spelling} {spelling_idxs}', flush=True) - continue - self.trie.insert( - spelling_idxs, word_idx, score if word not in boost_words else float(boost_words[word]) - ) - # handle OOV boosted words - for word, boost in boost_words.items(): - if word not in self.lexicon: - word_idx = self.word_dict.get_index(word) - spelling = self.tokenizer_wrapper.text_to_tokens(word) - spelling_idxs = [self.tokenizer_wrapper.token_to_id(token) for token in spelling] - if self.tokenizer_wrapper.unk_id in spelling_idxs: - print(f'tokenizer has unknown id for word[ {word} ] {spelling} {spelling_idxs}', flush=True) - continue - self.trie.insert(spelling_idxs, word_idx, float(boost)) - self.trie.smear(SmearingMode.MAX) - - self.decoder_opts = LexiconDecoderOptions( - beam_size=beam_size, - beam_size_token=int(beam_size_token), - beam_threshold=beam_threshold, - lm_weight=lm_weight, - word_score=word_score, - unk_score=unk_weight, - sil_score=sil_weight, - log_add=False, - criterion_type=self.criterion_type, - ) - - self.decoder = LexiconDecoder( - self.decoder_opts, self.trie, self.lm, self.silence, self.blank, self.unk_word, [], False, - ) - else: - from flashlight.lib.text.decoder import LexiconFreeDecoder, LexiconFreeDecoderOptions - - d = { - w: [[w]] - for w in self.tokenizer_wrapper.vocab + ([] if '' in self.tokenizer_wrapper.vocab else ['']) - } - self.word_dict = create_word_dict(d) - self.lm = KenLM(lm_path, self.word_dict) - self.decoder_opts = LexiconFreeDecoderOptions( - beam_size=beam_size, - beam_size_token=int(beam_size_token), - beam_threshold=beam_threshold, - lm_weight=lm_weight, - sil_score=sil_weight, - log_add=False, - criterion_type=self.criterion_type, - ) - self.decoder = LexiconFreeDecoder(self.decoder_opts, self.lm, self.silence, self.blank, []) - - def _get_tokens(self, idxs: List[int]): - """Normalize tokens by handling CTC blank, ASG replabels, etc.""" - - idxs = (g[0] for g in itertools.groupby(idxs)) - if self.silence < 0: - idxs = filter(lambda x: x != self.blank and x != self.silence, idxs) - else: - idxs = filter(lambda x: x != self.blank, idxs) - idxs = list(idxs) - if idxs[0] == self.silence: - idxs = idxs[1:] - if idxs[-1] == self.silence: - idxs = idxs[:-1] - - return torch.LongTensor(idxs) - - def _get_timesteps(self, token_idxs: List[int]): - """Returns frame numbers corresponding to every non-blank token. - Parameters - ---------- - token_idxs : List[int] - IDs of decoded tokens. - Returns - ------- - List[int] - Frame numbers corresponding to every non-blank token. - """ - - timesteps = [] - for i, token_idx in enumerate(token_idxs): - if token_idx == self.blank: - continue - if i == 0 or token_idx != token_idxs[i - 1]: - timesteps.append(i) - - return timesteps - - # @typecheck(ignore_collections=True) - @torch.no_grad() - def forward(self, log_probs: Union[np.ndarray, torch.Tensor]): - if isinstance(log_probs, np.ndarray): - log_probs = torch.from_numpy(log_probs).float() - if log_probs.dim() == 2: - log_probs = log_probs.unsqueeze(0) - - emissions = log_probs.cpu().contiguous() - - B, T, N = emissions.size() - hypos = [] - # we iterate over the batch dimension of our input tensor log probabilities - for b in range(B): - # the flashlight C++ expects a C style pointer, so the memory address - # which is what we obtain here. Then we pass it to pybinding method which - # is bound to the underlying C++ code - emissions_ptr = emissions.data_ptr() + 4 * b * emissions.stride(0) - results = self.decoder.decode(emissions_ptr, T, N) - - hypos.append( - [ - { - "tokens": self._get_tokens(result.tokens), - "score": result.score, - "timesteps": self._get_timesteps(result.tokens), - "words": [self.word_dict.get_entry(x) for x in result.words if x >= 0], - } - for result in results - ] - ) - - return hypos diff --git a/nemo/collections/asr/modules/hybrid_autoregressive_transducer.py b/nemo/collections/asr/modules/hybrid_autoregressive_transducer.py deleted file mode 100644 index 8fac6a00e9b660db84258193ceb8f0c1cf46125a..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/hybrid_autoregressive_transducer.py +++ /dev/null @@ -1,239 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Copyright 2017 Johns Hopkins University (Shinji Watanabe) -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import Any, Dict, List, Optional, Tuple, Union - -import torch - -from nemo.collections.asr.modules import rnnt -from nemo.collections.asr.parts.utils.rnnt_utils import HATJointOutput - -from nemo.utils import logging - - -class HATJoint(rnnt.RNNTJoint): - """A Hybrid Autoregressive Transducer Joint Network (HAT Joint Network). - A HAT Joint network, comprised of a feedforward model. - - Args: - jointnet: A dict-like object which contains the following key-value pairs. - encoder_hidden: int specifying the hidden dimension of the encoder net. - pred_hidden: int specifying the hidden dimension of the prediction net. - joint_hidden: int specifying the hidden dimension of the joint net - activation: Activation function used in the joint step. Can be one of - ['relu', 'tanh', 'sigmoid']. - - Optionally, it may also contain the following: - dropout: float, set to 0.0 by default. Optional dropout applied at the end of the joint net. - - num_classes: int, specifying the vocabulary size that the joint network must predict, - excluding the HAT blank token. - - vocabulary: Optional list of strings/tokens that comprise the vocabulary of the joint network. - Unused and kept only for easy access for character based encoding HAT models. - - log_softmax: Optional bool, set to None by default. If set as None, will compute the log_softmax() - based on the value provided. - - preserve_memory: Optional bool, set to False by default. If the model crashes due to the memory - intensive joint step, one might try this flag to empty the tensor cache in pytorch. - - Warning: This will make the forward-backward pass much slower than normal. - It also might not fix the OOM if the GPU simply does not have enough memory to compute the joint. - - fuse_loss_wer: Optional bool, set to False by default. - - Fuses the joint forward, loss forward and - wer forward steps. In doing so, it trades of speed for memory conservation by creating sub-batches - of the provided batch of inputs, and performs Joint forward, loss forward and wer forward (optional), - all on sub-batches, then collates results to be exactly equal to results from the entire batch. - - When this flag is set, prior to calling forward, the fields `loss` and `wer` (either one) *must* - be set using the `HATJoint.set_loss()` or `HATJoint.set_wer()` methods. - - Further, when this flag is set, the following argument `fused_batch_size` *must* be provided - as a non negative integer. This value refers to the size of the sub-batch. - - When the flag is set, the input and output signature of `forward()` of this method changes. - Input - in addition to `encoder_outputs` (mandatory argument), the following arguments can be provided. - - decoder_outputs (optional). Required if loss computation is required. - - encoder_lengths (required) - - transcripts (optional). Required for wer calculation. - - transcript_lengths (optional). Required for wer calculation. - - compute_wer (bool, default false). Whether to compute WER or not for the fused batch. - - Output - instead of the usual `joint` log prob tensor, the following results can be returned. - - loss (optional). Returned if decoder_outputs, transcripts and transript_lengths are not None. - - wer_numerator + wer_denominator (optional). Returned if transcripts, transcripts_lengths are provided - and compute_wer is set. - - fused_batch_size: Optional int, required if `fuse_loss_wer` flag is set. Determines the size of the - sub-batches. Should be any value below the actual batch size per GPU. - """ - - def __init__( - self, - jointnet: Dict[str, Any], - num_classes: int, - num_extra_outputs: int = 0, - vocabulary: Optional[List] = None, - log_softmax: Optional[bool] = None, - preserve_memory: bool = False, - fuse_loss_wer: bool = False, - fused_batch_size: Optional[int] = None, - experimental_fuse_loss_wer: Any = None, - ): - super().__init__( - jointnet=jointnet, - num_classes=num_classes, - num_extra_outputs=num_extra_outputs, - vocabulary=vocabulary, - log_softmax=log_softmax, - preserve_memory=preserve_memory, - fuse_loss_wer=fuse_loss_wer, - fused_batch_size=fused_batch_size, - experimental_fuse_loss_wer=experimental_fuse_loss_wer, - ) - - self.pred, self.enc, self.joint_net, self.blank_pred = self._joint_hat_net_modules( - num_classes=self._vocab_size, # non blank symbol - pred_n_hidden=self.pred_hidden, - enc_n_hidden=self.encoder_hidden, - joint_n_hidden=self.joint_hidden, - activation=self.activation, - dropout=jointnet.get('dropout', 0.0), - ) - self._return_hat_ilm = False - - @property - def return_hat_ilm(self): - return self._return_hat_ilm - - @return_hat_ilm.setter - def return_hat_ilm(self, hat_subtract_ilm): - self._return_hat_ilm = hat_subtract_ilm - - def joint_after_projection(self, f: torch.Tensor, g: torch.Tensor) -> Union[torch.Tensor, HATJointOutput]: - """ - Compute the joint step of the network after Encoder/Decoder projection. - - Here, - B = Batch size - T = Acoustic model timesteps - U = Target sequence length - H1, H2 = Hidden dimensions of the Encoder / Decoder respectively - H = Hidden dimension of the Joint hidden step. - V = Vocabulary size of the Decoder (excluding the HAT blank token). - - NOTE: - The implementation of this model is slightly modified from the original paper. - The original paper proposes the following steps : - (enc, dec) -> Expand + Concat + Sum [B, T, U, H1+H2] -> Forward through joint hidden [B, T, U, H] -- *1 - *1 -> Forward through joint final [B, T, U, V + 1]. - - We instead split the joint hidden into joint_hidden_enc and joint_hidden_dec and act as follows: - enc -> Forward through joint_hidden_enc -> Expand [B, T, 1, H] -- *1 - dec -> Forward through joint_hidden_dec -> Expand [B, 1, U, H] -- *2 - (*1, *2) -> Sum [B, T, U, H] -> Forward through joint final [B, T, U, V + 1]. - - Args: - f: Output of the Encoder model. A torch.Tensor of shape [B, T, H1] - g: Output of the Decoder model. A torch.Tensor of shape [B, U, H2] - - Returns: - Log softmaxed tensor of shape (B, T, U, V + 1). - Internal LM probability (B, 1, U, V) -- in case of return_ilm==True. - """ - f = f.unsqueeze(dim=2) # (B, T, 1, H) - g = g.unsqueeze(dim=1) # (B, 1, U, H) - inp = f + g # [B, T, U, H] - - del f - - # Forward adapter modules on joint hidden - if self.is_adapter_available(): - inp = self.forward_enabled_adapters(inp) - - blank_logprob = self.blank_pred(inp) # [B, T, U, 1] - label_logit = self.joint_net(inp) # [B, T, U, V] - - del inp - - label_logprob = label_logit.log_softmax(dim=-1) - scale_prob = torch.clamp(1 - torch.exp(blank_logprob), min=1e-6) - label_logprob_scaled = torch.log(scale_prob) + label_logprob # [B, T, U, V] - - res = torch.cat((label_logprob_scaled, blank_logprob), dim=-1).contiguous() # [B, T, U, V+1] - - if self.return_hat_ilm: - ilm_logprobs = self.joint_net(g).log_softmax(dim=-1) # [B, 1, U, V] - res = HATJointOutput(hat_logprobs=res, ilm_logprobs=ilm_logprobs) - - del g, blank_logprob, label_logprob, label_logit, scale_prob, label_logprob_scaled - - if self.preserve_memory: - torch.cuda.empty_cache() - - return res - - def _joint_hat_net_modules(self, num_classes, pred_n_hidden, enc_n_hidden, joint_n_hidden, activation, dropout): - """ - Prepare the trainable modules of the Joint Network - - Args: - num_classes: Number of output classes (vocab size) excluding the HAT blank token. - pred_n_hidden: Hidden size of the prediction network. - enc_n_hidden: Hidden size of the encoder network. - joint_n_hidden: Hidden size of the joint network. - activation: Activation of the joint. Can be one of [relu, tanh, sigmoid] - dropout: Dropout value to apply to joint. - """ - pred = torch.nn.Linear(pred_n_hidden, joint_n_hidden) - enc = torch.nn.Linear(enc_n_hidden, joint_n_hidden) - blank_pred = torch.nn.Sequential( - torch.nn.Tanh(), torch.nn.Dropout(p=dropout), torch.nn.Linear(joint_n_hidden, 1), torch.nn.LogSigmoid() - ) - - if activation not in ['relu', 'sigmoid', 'tanh']: - raise ValueError("Unsupported activation for joint step - please pass one of " "[relu, sigmoid, tanh]") - - activation = activation.lower() - - if activation == 'relu': - activation = torch.nn.ReLU(inplace=True) - elif activation == 'sigmoid': - activation = torch.nn.Sigmoid() - elif activation == 'tanh': - activation = torch.nn.Tanh() - - layers = ( - [activation] - + ([torch.nn.Dropout(p=dropout)] if dropout else []) - + [torch.nn.Linear(joint_n_hidden, num_classes)] - ) - return pred, enc, torch.nn.Sequential(*layers), blank_pred diff --git a/nemo/collections/asr/modules/lstm_decoder.py b/nemo/collections/asr/modules/lstm_decoder.py deleted file mode 100644 index 03f6cf6aa87579335595f1b1a9376ad89bd7957f..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/lstm_decoder.py +++ /dev/null @@ -1,104 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from collections import OrderedDict - -import torch -import torch.nn as nn - -from nemo.core.classes.common import typecheck -from nemo.core.classes.exportable import Exportable -from nemo.core.classes.module import NeuralModule -from nemo.core.neural_types import AcousticEncodedRepresentation, LogprobsType, NeuralType - -__all__ = ['LSTMDecoder'] - - -class LSTMDecoder(NeuralModule, Exportable): - """ - Simple LSTM Decoder for ASR models - Args: - feat_in (int): size of the input features - num_classes (int): the size of the vocabulary - lstm_hidden_size (int): hidden size of the LSTM layers - vocabulary (vocab): The vocabulary - bidirectional (bool): default is False. Whether LSTMs are bidirectional or not - num_layers (int): default is 1. Number of LSTM layers stacked - add_blank (bool): default is True. Whether to add a blank token to the vocabulary. - """ - - @property - def input_types(self): - return OrderedDict({"encoder_output": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation())}) - - @property - def output_types(self): - return OrderedDict({"logprobs": NeuralType(('B', 'T', 'D'), LogprobsType())}) - - def __init__( - self, - feat_in, - num_classes, - lstm_hidden_size, - vocabulary=None, - bidirectional=False, - num_layers=1, - add_blank=True, - ): - super().__init__() - - if vocabulary is not None: - if num_classes != len(vocabulary): - raise ValueError( - f"If vocabulary is specified, it's length should be equal to the num_classes. " - f"Instead got: num_classes={num_classes} and len(vocabulary)={len(vocabulary)}" - ) - self.__vocabulary = vocabulary - self._feat_in = feat_in - # Add 1 for blank char - self._num_classes = num_classes + 1 if add_blank else num_classes - - self.lstm_layer = nn.LSTM( - input_size=feat_in, - hidden_size=lstm_hidden_size, - num_layers=num_layers, - batch_first=True, - bidirectional=bidirectional, - ) - lstm_hidden_size = 2 * lstm_hidden_size if bidirectional else lstm_hidden_size - self.linear_layer = torch.nn.Linear(in_features=lstm_hidden_size, out_features=self._num_classes) - - @typecheck() - def forward(self, encoder_output): - output = encoder_output.transpose(1, 2) - output, _ = self.lstm_layer(output) - output = self.linear_layer(output) - return torch.nn.functional.log_softmax(output, dim=-1) - - def input_example(self, max_batch=1, max_dim=256): - """ - Generates input examples for tracing etc. - Returns: - A tuple of input examples. - """ - input_example = torch.randn(max_batch, self._feat_in, max_dim).to(next(self.parameters()).device) - return tuple([input_example]) - - @property - def vocabulary(self): - return self.__vocabulary - - @property - def num_classes_with_blank(self): - return self._num_classes diff --git a/nemo/collections/asr/modules/rnn_encoder.py b/nemo/collections/asr/modules/rnn_encoder.py deleted file mode 100644 index 0ebb89f545e27cf8309a78bb218efdf90e116e5c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/rnn_encoder.py +++ /dev/null @@ -1,178 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from collections import OrderedDict - -import torch -import torch.distributed -import torch.nn as nn - -from nemo.collections.asr.parts.submodules.subsampling import ConvSubsampling, StackingSubsampling -from nemo.core.classes.common import typecheck -from nemo.core.classes.exportable import Exportable -from nemo.core.classes.module import NeuralModule -from nemo.core.neural_types import AcousticEncodedRepresentation, LengthsType, NeuralType, SpectrogramType - -__all__ = ['RNNEncoder'] - - -class RNNEncoder(NeuralModule, Exportable): - """ - The RNN-based encoder for ASR models. - Followed the architecture suggested in the following paper: - 'STREAMING END-TO-END SPEECH RECOGNITION FOR MOBILE DEVICES' by Yanzhang He et al. - https://arxiv.org/pdf/1811.06621.pdf - - - Args: - feat_in (int): the size of feature channels - n_layers (int): number of layers of RNN - d_model (int): the hidden size of the model - proj_size (int): the size of the output projection after each RNN layer - rnn_type (str): the type of the RNN layers, choices=['lstm, 'gru', 'rnn'] - bidirectional (float): specifies whether RNN layers should be bidirectional or not - Defaults to True. - feat_out (int): the size of the output features - Defaults to -1 (means feat_out is d_model) - subsampling (str): the method of subsampling, choices=['stacking, 'vggnet', 'striding'] - Defaults to stacking. - subsampling_factor (int): the subsampling factor - Defaults to 4. - subsampling_conv_channels (int): the size of the convolutions in the subsampling module for vggnet and striding - Defaults to -1 which would set it to d_model. - dropout (float): the dropout rate used between all layers - Defaults to 0.2. - """ - - def input_example(self): - """ - Generates input examples for tracing etc. - Returns: - A tuple of input examples. - """ - input_example = torch.randn(16, self._feat_in, 256).to(next(self.parameters()).device) - input_example_length = torch.randint(0, 256, (16,)).to(next(self.parameters()).device) - return tuple([input_example, input_example_length]) - - @property - def input_types(self): - """Returns definitions of module input ports. - """ - return OrderedDict( - { - "audio_signal": NeuralType(('B', 'D', 'T'), SpectrogramType()), - "length": NeuralType(tuple('B'), LengthsType()), - } - ) - - @property - def output_types(self): - """Returns definitions of module output ports. - """ - return OrderedDict( - { - "outputs": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), - "encoded_lengths": NeuralType(tuple('B'), LengthsType()), - } - ) - - def __init__( - self, - feat_in: int, - n_layers: int, - d_model: int, - proj_size: int = -1, - rnn_type: str = 'lstm', - bidirectional: bool = True, - subsampling: str = 'striding', - subsampling_factor: int = 4, - subsampling_conv_channels: int = -1, - dropout: float = 0.2, - ): - super().__init__() - - self.d_model = d_model - self._feat_in = feat_in - - if subsampling_conv_channels == -1: - subsampling_conv_channels = proj_size - if subsampling and subsampling_factor > 1: - if subsampling in ['stacking', 'stacking_norm']: - self.pre_encode = StackingSubsampling( - subsampling_factor=subsampling_factor, - feat_in=feat_in, - feat_out=proj_size, - norm=True if 'norm' in subsampling else False, - ) - else: - self.pre_encode = ConvSubsampling( - subsampling=subsampling, - subsampling_factor=subsampling_factor, - feat_in=feat_in, - feat_out=proj_size, - conv_channels=subsampling_conv_channels, - activation=nn.ReLU(), - ) - else: - self.pre_encode = nn.Linear(feat_in, proj_size) - - self._feat_out = proj_size - - self.layers = nn.ModuleList() - - SUPPORTED_RNN = {"lstm": nn.LSTM, "gru": nn.GRU, "rnn": nn.RNN} - if rnn_type not in SUPPORTED_RNN: - raise ValueError(f"rnn_type can be one from the following:{SUPPORTED_RNN.keys()}") - else: - rnn_module = SUPPORTED_RNN[rnn_type] - - for i in range(n_layers): - rnn_proj_size = proj_size // 2 if bidirectional else proj_size - if rnn_type == "lstm": - layer = rnn_module( - input_size=self._feat_out, - hidden_size=d_model, - num_layers=1, - batch_first=True, - bidirectional=bidirectional, - proj_size=rnn_proj_size, - ) - self.layers.append(layer) - self.layers.append(nn.LayerNorm(proj_size)) - self.layers.append(nn.Dropout(p=dropout)) - self._feat_out = proj_size - - @typecheck() - def forward(self, audio_signal, length=None): - max_audio_length: int = audio_signal.size(-1) - - if length is None: - length = audio_signal.new_full( - audio_signal.size(0), max_audio_length, dtype=torch.int32, device=self.seq_range.device - ) - - audio_signal = torch.transpose(audio_signal, 1, 2) - - if isinstance(self.pre_encode, nn.Linear): - audio_signal = self.pre_encode(audio_signal) - else: - audio_signal, length = self.pre_encode(audio_signal, length) - - for lth, layer in enumerate(self.layers): - audio_signal = layer(audio_signal) - if isinstance(audio_signal, tuple): - audio_signal, _ = audio_signal - - audio_signal = torch.transpose(audio_signal, 1, 2) - return audio_signal, length diff --git a/nemo/collections/asr/modules/rnnt.py b/nemo/collections/asr/modules/rnnt.py deleted file mode 100644 index feaf0edfca927085b85c103d042605697f9bbf30..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/rnnt.py +++ /dev/null @@ -1,2373 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Copyright 2017 Johns Hopkins University (Shinji Watanabe) -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import Any, Dict, List, Optional, Tuple, Union - -import torch -from omegaconf import DictConfig - -from nemo.collections.asr.modules import rnnt_abstract -from nemo.collections.asr.parts.submodules import stateless_net -from nemo.collections.asr.parts.utils import adapter_utils, rnnt_utils -from nemo.collections.common.parts import rnn -from nemo.core.classes import adapter_mixins, typecheck -from nemo.core.classes.exportable import Exportable -from nemo.core.classes.mixins import AdapterModuleMixin -from nemo.core.neural_types import ( - AcousticEncodedRepresentation, - ElementType, - EmbeddedTextType, - LabelsType, - LengthsType, - LogprobsType, - LossType, - NeuralType, - SpectrogramType, -) -from nemo.utils import logging - - -class StatelessTransducerDecoder(rnnt_abstract.AbstractRNNTDecoder, Exportable): - """A Stateless Neural Network Transducer Decoder / Prediction Network. - An RNN-T Decoder/Prediction stateless network that simply takes concatenation of embeddings of the history tokens as the output. - - Args: - prednet: A dict-like object which contains the following key-value pairs. - pred_hidden: int specifying the hidden dimension of the prediction net. - - dropout: float, set to 0.0 by default. Optional dropout applied at the end of the final LSTM RNN layer. - - vocab_size: int, specifying the vocabulary size of the embedding layer of the Prediction network, - excluding the RNNT blank token. - - context_size: int, specifying the size of the history context used for this decoder. - - normalization_mode: Can be either None, 'layer'. By default, is set to None. - Defines the type of normalization applied to the RNN layer. - - """ - - @property - def input_types(self): - """Returns definitions of module input ports.""" - return { - "targets": NeuralType(('B', 'T'), LabelsType()), - "target_length": NeuralType(tuple('B'), LengthsType()), - "states": [NeuralType(('B', 'T'), LabelsType(), optional=True)], - } - - @property - def output_types(self): - """Returns definitions of module output ports.""" - return { - "outputs": NeuralType(('B', 'D', 'T'), EmbeddedTextType()), - "prednet_lengths": NeuralType(tuple('B'), LengthsType()), - "states": [NeuralType(('B', 'T'), LabelsType(), optional=True)], - } - - def input_example(self, max_batch=1, max_dim=1): - """ - Generates input examples for tracing etc. - Returns: - A tuple of input examples. - """ - length = max_dim - targets = torch.full(fill_value=self.blank_idx, size=(max_batch, length), dtype=torch.int32).to( - next(self.parameters()).device - ) - target_length = torch.randint(0, length, size=(max_batch,), dtype=torch.int32).to( - next(self.parameters()).device - ) - states = tuple(self.initialize_state(targets.float())) - return (targets, target_length, states) - - def _prepare_for_export(self, **kwargs): - self._rnnt_export = True - super()._prepare_for_export(**kwargs) - - def __init__( - self, - prednet: Dict[str, Any], - vocab_size: int, - context_size: int = 1, - normalization_mode: Optional[str] = None, - ): - # Required arguments - self.pred_hidden = prednet['pred_hidden'] - self.blank_idx = vocab_size - self.context_size = context_size - - # Initialize the model (blank token increases vocab size by 1) - super().__init__(vocab_size=vocab_size, blank_idx=self.blank_idx, blank_as_pad=True) - - # Optional arguments - dropout = prednet.get('dropout', 0.0) - - self.prediction = self._predict_modules( - **{ - "context_size": context_size, - "vocab_size": vocab_size, - "emb_dim": self.pred_hidden, - "blank_idx": self.blank_idx, - "normalization_mode": normalization_mode, - "dropout": dropout, - } - ) - self._rnnt_export = False - - @typecheck() - def forward(self, targets, target_length, states=None): - # y: (B, U) - y = rnn.label_collate(targets) - - # state maintenance is unnecessary during training forward call - # to get state, use .predict() method. - if self._rnnt_export: - add_sos = False - else: - add_sos = True - - g, state = self.predict(y, state=states, add_sos=add_sos) # (B, U, D) - g = g.transpose(1, 2) # (B, D, U) - - return g, target_length, state - - def predict( - self, - y: Optional[torch.Tensor] = None, - state: Optional[torch.Tensor] = None, - add_sos: bool = True, - batch_size: Optional[int] = None, - ) -> Tuple[torch.Tensor, List[torch.Tensor]]: - """ - Stateful prediction of scores and state for a tokenset. - - Here: - B - batch size - U - label length - C - context size for stateless decoder - D - total embedding size - - Args: - y: Optional torch tensor of shape [B, U] of dtype long which will be passed to the Embedding. - If None, creates a zero tensor of shape [B, 1, D] which mimics output of pad-token on Embedding. - - state: An optional one-element list of one tensor. The tensor is used to store previous context labels. - The tensor uses type long and is of shape [B, C]. - - add_sos: bool flag, whether a zero vector describing a "start of signal" token should be - prepended to the above "y" tensor. When set, output size is (B, U + 1, D). - - batch_size: An optional int, specifying the batch size of the `y` tensor. - Can be infered if `y` and `state` is None. But if both are None, then batch_size cannot be None. - - Returns: - A tuple (g, state) such that - - - If add_sos is False: - - g: - (B, U, D) - - state: - [(B, C)] storing the history context including the new words in y. - - If add_sos is True: - - g: - (B, U + 1, D) - - state: - [(B, C)] storing the history context including the new words in y. - - """ - # Get device and dtype of current module - _p = next(self.parameters()) - device = _p.device - dtype = _p.dtype - - # If y is not None, it is of shape [B, U] with dtype long. - if y is not None: - if y.device != device: - y = y.to(device) - - y, state = self.prediction(y, state) - - else: - # Y is not provided, assume zero tensor with shape [B, 1, D] is required - # Emulates output of embedding of pad token. - if batch_size is None: - B = 1 if state is None else state[0].size(1) - else: - B = batch_size - - y = torch.zeros((B, 1, self.pred_hidden), device=device, dtype=dtype) - - # Prepend blank "start of sequence" symbol (zero tensor) - if add_sos: - B, U, D = y.shape - start = torch.zeros((B, 1, D), device=y.device, dtype=y.dtype) - y = torch.cat([start, y], dim=1).contiguous() # (B, U + 1, D) - else: - start = None # makes del call later easier - - del start - return y, state - - def _predict_modules(self, **kwargs): - """ - Prepare the trainable parameters of the Prediction Network. - - Args: - vocab_size: Vocab size (excluding the blank token). - pred_n_hidden: Hidden size of the RNNs. - norm: Type of normalization to perform in RNN. - dropout: Whether to apply dropout to RNN. - """ - - net = stateless_net.StatelessNet(**kwargs) - return net - - def score_hypothesis( - self, hypothesis: rnnt_utils.Hypothesis, cache: Dict[Tuple[int], Any] - ) -> Tuple[torch.Tensor, List[torch.Tensor], torch.Tensor]: - """ - Similar to the predict() method, instead this method scores a Hypothesis during beam search. - Hypothesis is a dataclass representing one hypothesis in a Beam Search. - - Args: - hypothesis: Refer to rnnt_utils.Hypothesis. - cache: Dict which contains a cache to avoid duplicate computations. - - Returns: - Returns a tuple (y, states, lm_token) such that: - y is a torch.Tensor of shape [1, 1, H] representing the score of the last token in the Hypothesis. - state is a list of RNN states, each of shape [L, 1, H]. - lm_token is the final integer token of the hypothesis. - """ - if hypothesis.dec_state is not None: - device = hypothesis.dec_state[0].device - else: - _p = next(self.parameters()) - device = _p.device - - # parse "blank" tokens in hypothesis - if len(hypothesis.y_sequence) > 0 and hypothesis.y_sequence[-1] == self.blank_idx: - blank_state = True - else: - blank_state = False - - # Convert last token of hypothesis to torch.Tensor - target = torch.full([1, 1], fill_value=hypothesis.y_sequence[-1], device=device, dtype=torch.long) - lm_token = target[:, -1] # [1] - - # Convert current hypothesis into a tuple to preserve in cache - sequence = tuple(hypothesis.y_sequence) - - if sequence in cache: - y, new_state = cache[sequence] - else: - # Obtain score for target token and new states - if blank_state: - y, new_state = self.predict(None, state=None, add_sos=False, batch_size=1) # [1, 1, H] - - else: - y, new_state = self.predict( - target, state=hypothesis.dec_state, add_sos=False, batch_size=1 - ) # [1, 1, H] - - y = y[:, -1:, :] # Extract just last state : [1, 1, H] - cache[sequence] = (y, new_state) - - return y, new_state, lm_token - - def initialize_state(self, y: torch.Tensor) -> List[torch.Tensor]: - batch = y.size(0) - # state contains context_size - 1 elements for each utterance in batch, - # consistent with the state returned from StatelessNet.forward - state = [ - torch.full([batch, self.context_size - 1], fill_value=self.blank_idx, dtype=torch.long, device=y.device) - ] - return state - - def batch_initialize_states(self, decoder_states: List[List[torch.Tensor]]): - """ - Creates a stacked decoder states to be passed to prediction network. - - Args: - decoder_states (list of list of torch.Tensor): list of decoder states - of shape ``[B, 1, C]`` where B is batch size and C is hidden state dim. - - Returns: - batch_states (list of torch.Tensor): batch of decoder states ``[[B x C]]``. - """ - new_state = torch.stack([s[0] for s in decoder_states]) - - return [new_state] - - def batch_select_state(self, batch_states: List[torch.Tensor], idx: int) -> List[List[torch.Tensor]]: - """Get decoder state from batch of states, for given id. - - Args: - batch_states (list): batch of decoder states - [(B, C)] - - idx (int): index to extract state from batch of states - - Returns: - (tuple): decoder states for given id - [(C)] - """ - if batch_states is not None: - states = batch_states[0][idx] - states = ( - states.long() - ) # beam search code assumes the batch_states tensor is always of float type, so need conversion - return [states] - else: - return None - - def batch_concat_states(self, batch_states: List[List[torch.Tensor]]) -> List[torch.Tensor]: - """Concatenate a batch of decoder state to a packed state. - - Args: - batch_states (list): batch of decoder states - B x ([(C)] - - Returns: - (tuple): decoder states - [(B x C)] - """ - state_list = [] - batch_list = [] - for sample_id in range(len(batch_states)): - tensor = torch.stack(batch_states[sample_id]) # [1, H] - batch_list.append(tensor) - - state_tensor = torch.cat(batch_list, 0) # [B, H] - state_list.append(state_tensor) - - return state_list - - @classmethod - def batch_replace_states_mask( - cls, - src_states: tuple[torch.Tensor, torch.Tensor] | list[torch.Tensor], - dst_states: tuple[torch.Tensor, torch.Tensor] | list[torch.Tensor], - mask: torch.Tensor, - other_src_states: Optional[tuple[torch.Tensor, torch.Tensor] | list[torch.Tensor]] = None, - ): - """ - Replaces states in `dst_states` with states from `src_states` based on the given `mask`. - - Args: - mask (torch.Tensor): When True, selects values from `src_states`, otherwise `out` or `other_src_states` (if provided). - src_states (tuple[torch.Tensor, torch.Tensor]): Values selected at indices where `mask` is True. - dst_states (tuple[torch.Tensor, torch.Tensor], optional): The output states. - other_src_states (tuple[torch.Tensor, torch.Tensor], optional): Values selected at indices where `mask` is False. - - Note: - This operation is performed without CPU-GPU synchronization by using `torch.where`. - """ - other = other_src_states if other_src_states is not None else dst_states - # same as `dst_states[0][mask] = src_states[0][mask]`, but non-blocking - torch.where(mask.unsqueeze(-1), src_states[0], other[0], out=dst_states[0]) - - @classmethod - def batch_replace_states_all( - cls, - src_states: list[torch.Tensor], - dst_states: list[torch.Tensor], - batch_size: int | None = None, - ): - """Replace states in dst_states with states from src_states""" - if batch_size is None: - dst_states[0].copy_(src_states[0]) - else: - dst_states[0][:batch_size].copy_(src_states[0][:batch_size]) - - @classmethod - def clone_state(cls, state: list[torch.Tensor]) -> list[torch.Tensor]: - """Return copy of the states""" - return [sub_state.clone() for sub_state in state] - - @classmethod - def batch_split_states(cls, batch_states: list[torch.Tensor]) -> list[list[torch.Tensor]]: - """ - Split states into a list of states. - Useful for splitting the final state for converting results of the decoding algorithm to Hypothesis class. - """ - return [sub_state.split(1, dim=0) for sub_state in batch_states] - - @classmethod - def batch_unsplit_states( - cls, batch_states: list[list[torch.Tensor]], device=None, dtype=None - ) -> list[torch.Tensor]: - """ - Concatenate a batch of decoder state to a packed state. Inverse of `batch_split_states`. - """ - return [ - torch.stack([state[0] for state in batch_states], dim=0).to(device=device, dtype=dtype), - ] - - def batch_copy_states( - self, - old_states: List[torch.Tensor], - new_states: List[torch.Tensor], - ids: List[int], - value: Optional[float] = None, - ) -> List[torch.Tensor]: - """Copy states from new state to old state at certain indices. - - Args: - old_states: packed decoder states - single element list of (B x C) - - new_states: packed decoder states - single element list of (B x C) - - ids (list): List of indices to copy states at. - - value (optional float): If a value should be copied instead of a state slice, a float should be provided - - Returns: - batch of decoder states with partial copy at ids (or a specific value). - (B x C) - """ - - if value is None: - old_states[0][ids, :] = new_states[0][ids, :] - - return old_states - - def mask_select_states( - self, states: Optional[List[torch.Tensor]], mask: torch.Tensor - ) -> Optional[List[torch.Tensor]]: - """ - Return states by mask selection - Args: - states: states for the batch - mask: boolean mask for selecting states; batch dimension should be the same as for states - - Returns: - states filtered by mask - """ - if states is None: - return None - return [states[0][mask]] - - def batch_score_hypothesis( - self, - hypotheses: List[rnnt_utils.Hypothesis], - cache: Dict[Tuple[int], Any], - ) -> Tuple[List[torch.Tensor], List[List[torch.Tensor]]]: - """ - Used for batched beam search algorithms. Similar to score_hypothesis method. - - Args: - hypothesis: List of Hypotheses. Refer to rnnt_utils.Hypothesis. - cache: Dict which contains a cache to avoid duplicate computations. - - Returns: - Returns a tuple (batch_dec_out, batch_dec_states) such that: - batch_dec_out: a list of torch.Tensor [1, H] representing the prediction network outputs for the last tokens in the Hypotheses. - batch_dec_states: a list of list of RNN states, each of shape [L, B, H]. Represented as B x List[states]. - """ - final_batch = len(hypotheses) - - if final_batch == 0: - raise ValueError("No hypotheses was provided for the batch!") - - _p = next(self.parameters()) - device = _p.device - - tokens = [] - to_process = [] - final = [None for _ in range(final_batch)] - - # For each hypothesis, cache the last token of the sequence and the current states - for final_idx, hyp in enumerate(hypotheses): - sequence = tuple(hyp.y_sequence) - - if sequence in cache: - final[final_idx] = cache[sequence] - else: - tokens.append(hyp.y_sequence[-1]) - to_process.append((sequence, hyp.dec_state)) - - if to_process: - batch = len(to_process) - - # convert list of tokens to torch.Tensor, then reshape. - tokens = torch.tensor(tokens, device=device, dtype=torch.long).view(batch, -1) - dec_states = self.batch_initialize_states([d_state for _, d_state in to_process]) - - dec_outputs, dec_states = self.predict( - tokens, state=dec_states, add_sos=False, batch_size=batch - ) # [B, 1, H], B x List([L, 1, H]) - - # Update final states and cache shared by entire batch. - processed_idx = 0 - for final_idx in range(final_batch): - if to_process and final[final_idx] is None: - # Select sample's state from the batch state list - new_state = self.batch_select_state(dec_states, processed_idx) - - # Cache [1, H] scores of the current y_j, and its corresponding state - final[final_idx] = (dec_outputs[processed_idx], new_state) - cache[to_process[processed_idx][0]] = (dec_outputs[processed_idx], new_state) - - processed_idx += 1 - - return [dec_out for dec_out, _ in final], [dec_states for _, dec_states in final] - - -class RNNTDecoder(rnnt_abstract.AbstractRNNTDecoder, Exportable, AdapterModuleMixin): - """A Recurrent Neural Network Transducer Decoder / Prediction Network (RNN-T Prediction Network). - An RNN-T Decoder/Prediction network, comprised of a stateful LSTM model. - - Args: - prednet: A dict-like object which contains the following key-value pairs. - - pred_hidden: - int specifying the hidden dimension of the prediction net. - - pred_rnn_layers: - int specifying the number of rnn layers. - - Optionally, it may also contain the following: - - forget_gate_bias: - float, set by default to 1.0, which constructs a forget gate - initialized to 1.0. - Reference: - [An Empirical Exploration of Recurrent Network Architectures](http://proceedings.mlr.press/v37/jozefowicz15.pdf) - - t_max: - int value, set to None by default. If an int is specified, performs Chrono Initialization - of the LSTM network, based on the maximum number of timesteps `t_max` expected during the course - of training. - Reference: - [Can recurrent neural networks warp time?](https://openreview.net/forum?id=SJcKhk-Ab) - - weights_init_scale: - Float scale of the weights after initialization. Setting to lower than one - sometimes helps reduce variance between runs. - - hidden_hidden_bias_scale: - Float scale for the hidden-to-hidden bias scale. Set to 0.0 for - the default behaviour. - - dropout: - float, set to 0.0 by default. Optional dropout applied at the end of the final LSTM RNN layer. - - vocab_size: int, specifying the vocabulary size of the embedding layer of the Prediction network, - excluding the RNNT blank token. - - normalization_mode: Can be either None, 'batch' or 'layer'. By default, is set to None. - Defines the type of normalization applied to the RNN layer. - - random_state_sampling: bool, set to False by default. When set, provides normal-distribution - sampled state tensors instead of zero tensors during training. - Reference: - [Recognizing long-form speech using streaming end-to-end models](https://arxiv.org/abs/1910.11455) - - blank_as_pad: bool, set to True by default. When set, will add a token to the Embedding layer of this - prediction network, and will treat this token as a pad token. In essence, the RNNT pad token will - be treated as a pad token, and the embedding layer will return a zero tensor for this token. - - It is set by default as it enables various batch optimizations required for batched beam search. - Therefore, it is not recommended to disable this flag. - """ - - @property - def input_types(self): - """Returns definitions of module input ports.""" - return { - "targets": NeuralType(('B', 'T'), LabelsType()), - "target_length": NeuralType(tuple('B'), LengthsType()), - "states": [NeuralType(('D', 'B', 'D'), ElementType(), optional=True)], # must always be last - } - - @property - def output_types(self): - """Returns definitions of module output ports.""" - return { - "outputs": NeuralType(('B', 'D', 'T'), EmbeddedTextType()), - "prednet_lengths": NeuralType(tuple('B'), LengthsType()), - "states": [NeuralType((('D', 'B', 'D')), ElementType(), optional=True)], # must always be last - } - - def input_example(self, max_batch=1, max_dim=1): - """ - Generates input examples for tracing etc. - Returns: - A tuple of input examples. - """ - length = max_dim - targets = torch.full(fill_value=self.blank_idx, size=(max_batch, length), dtype=torch.int32).to( - next(self.parameters()).device - ) - target_length = torch.randint(0, length, size=(max_batch,), dtype=torch.int32).to( - next(self.parameters()).device - ) - states = tuple(self.initialize_state(targets.float())) - return (targets, target_length, states) - - def _prepare_for_export(self, **kwargs): - self._rnnt_export = True - super()._prepare_for_export(**kwargs) - - def __init__( - self, - prednet: Dict[str, Any], - vocab_size: int, - normalization_mode: Optional[str] = None, - random_state_sampling: bool = False, - blank_as_pad: bool = True, - ): - # Required arguments - self.pred_hidden = prednet['pred_hidden'] - self.pred_rnn_layers = prednet["pred_rnn_layers"] - self.blank_idx = vocab_size - - # Initialize the model (blank token increases vocab size by 1) - super().__init__(vocab_size=vocab_size, blank_idx=self.blank_idx, blank_as_pad=blank_as_pad) - - # Optional arguments - forget_gate_bias = prednet.get('forget_gate_bias', 1.0) - t_max = prednet.get('t_max', None) - weights_init_scale = prednet.get('weights_init_scale', 1.0) - hidden_hidden_bias_scale = prednet.get('hidden_hidden_bias_scale', 0.0) - dropout = prednet.get('dropout', 0.0) - self.random_state_sampling = random_state_sampling - - self.prediction = self._predict_modules( - vocab_size=vocab_size, # add 1 for blank symbol - pred_n_hidden=self.pred_hidden, - pred_rnn_layers=self.pred_rnn_layers, - forget_gate_bias=forget_gate_bias, - t_max=t_max, - norm=normalization_mode, - weights_init_scale=weights_init_scale, - hidden_hidden_bias_scale=hidden_hidden_bias_scale, - dropout=dropout, - rnn_hidden_size=prednet.get("rnn_hidden_size", -1), - ) - self._rnnt_export = False - - @typecheck() - def forward(self, targets, target_length, states=None): - # y: (B, U) - y = rnn.label_collate(targets) - - # state maintenance is unnecessary during training forward call - # to get state, use .predict() method. - if self._rnnt_export: - add_sos = False - else: - add_sos = True - - g, states = self.predict(y, state=states, add_sos=add_sos) # (B, U, D) - g = g.transpose(1, 2) # (B, D, U) - - return g, target_length, states - - def predict( - self, - y: Optional[torch.Tensor] = None, - state: Optional[List[torch.Tensor]] = None, - add_sos: bool = True, - batch_size: Optional[int] = None, - ) -> Tuple[torch.Tensor, List[torch.Tensor]]: - """ - Stateful prediction of scores and state for a (possibly null) tokenset. - This method takes various cases into consideration : - - No token, no state - used for priming the RNN - - No token, state provided - used for blank token scoring - - Given token, states - used for scores + new states - - Here: - B - batch size - U - label length - H - Hidden dimension size of RNN - L - Number of RNN layers - - Args: - y: Optional torch tensor of shape [B, U] of dtype long which will be passed to the Embedding. - If None, creates a zero tensor of shape [B, 1, H] which mimics output of pad-token on EmbeddiNg. - - state: An optional list of states for the RNN. Eg: For LSTM, it is the state list length is 2. - Each state must be a tensor of shape [L, B, H]. - If None, and during training mode and `random_state_sampling` is set, will sample a - normal distribution tensor of the above shape. Otherwise, None will be passed to the RNN. - - add_sos: bool flag, whether a zero vector describing a "start of signal" token should be - prepended to the above "y" tensor. When set, output size is (B, U + 1, H). - - batch_size: An optional int, specifying the batch size of the `y` tensor. - Can be infered if `y` and `state` is None. But if both are None, then batch_size cannot be None. - - Returns: - A tuple (g, hid) such that - - - If add_sos is False: - - g: - (B, U, H) - - hid: - (h, c) where h is the final sequence hidden state and c is the final cell state: - - h (tensor), shape (L, B, H) - - c (tensor), shape (L, B, H) - - If add_sos is True: - g: - (B, U + 1, H) - - hid: - (h, c) where h is the final sequence hidden state and c is the final cell state: - - h (tensor), shape (L, B, H) - - c (tensor), shape (L, B, H) - - """ - # Get device and dtype of current module - _p = next(self.parameters()) - device = _p.device - dtype = _p.dtype - - # If y is not None, it is of shape [B, U] with dtype long. - if y is not None: - if y.device != device: - y = y.to(device) - - # (B, U) -> (B, U, H) - y = self.prediction["embed"](y) - else: - # Y is not provided, assume zero tensor with shape [B, 1, H] is required - # Emulates output of embedding of pad token. - if batch_size is None: - B = 1 if state is None else state[0].size(1) - else: - B = batch_size - - y = torch.zeros((B, 1, self.pred_hidden), device=device, dtype=dtype) - - # Prepend blank "start of sequence" symbol (zero tensor) - if add_sos: - B, U, H = y.shape - start = torch.zeros((B, 1, H), device=y.device, dtype=y.dtype) - y = torch.cat([start, y], dim=1).contiguous() # (B, U + 1, H) - else: - start = None # makes del call later easier - - # If in training mode, and random_state_sampling is set, - # initialize state to random normal distribution tensor. - if state is None: - if self.random_state_sampling and self.training: - state = self.initialize_state(y) - - # Forward step through RNN - y = y.transpose(0, 1) # (U + 1, B, H) - g, hid = self.prediction["dec_rnn"](y, state) - g = g.transpose(0, 1) # (B, U + 1, H) - - del y, start, state - - # Adapter module forward step - if self.is_adapter_available(): - g = self.forward_enabled_adapters(g) - - return g, hid - - def _predict_modules( - self, - vocab_size, - pred_n_hidden, - pred_rnn_layers, - forget_gate_bias, - t_max, - norm, - weights_init_scale, - hidden_hidden_bias_scale, - dropout, - rnn_hidden_size, - ): - """ - Prepare the trainable parameters of the Prediction Network. - - Args: - vocab_size: Vocab size (excluding the blank token). - pred_n_hidden: Hidden size of the RNNs. - pred_rnn_layers: Number of RNN layers. - forget_gate_bias: Whether to perform unit forget gate bias. - t_max: Whether to perform Chrono LSTM init. - norm: Type of normalization to perform in RNN. - weights_init_scale: Float scale of the weights after initialization. Setting to lower than one - sometimes helps reduce variance between runs. - hidden_hidden_bias_scale: Float scale for the hidden-to-hidden bias scale. Set to 0.0 for - the default behaviour. - dropout: Whether to apply dropout to RNN. - rnn_hidden_size: the hidden size of the RNN, if not specified, pred_n_hidden would be used - """ - if self.blank_as_pad: - embed = torch.nn.Embedding(vocab_size + 1, pred_n_hidden, padding_idx=self.blank_idx) - else: - embed = torch.nn.Embedding(vocab_size, pred_n_hidden) - - layers = torch.nn.ModuleDict( - { - "embed": embed, - "dec_rnn": rnn.rnn( - input_size=pred_n_hidden, - hidden_size=rnn_hidden_size if rnn_hidden_size > 0 else pred_n_hidden, - num_layers=pred_rnn_layers, - norm=norm, - forget_gate_bias=forget_gate_bias, - t_max=t_max, - dropout=dropout, - weights_init_scale=weights_init_scale, - hidden_hidden_bias_scale=hidden_hidden_bias_scale, - proj_size=pred_n_hidden if pred_n_hidden < rnn_hidden_size else 0, - ), - } - ) - return layers - - def initialize_state(self, y: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: - """ - Initialize the state of the LSTM layers, with same dtype and device as input `y`. - LSTM accepts a tuple of 2 tensors as a state. - - Args: - y: A torch.Tensor whose device the generated states will be placed on. - - Returns: - Tuple of 2 tensors, each of shape [L, B, H], where - - L = Number of RNN layers - - B = Batch size - - H = Hidden size of RNN. - """ - batch = y.size(0) - if self.random_state_sampling and self.training: - state = ( - torch.randn(self.pred_rnn_layers, batch, self.pred_hidden, dtype=y.dtype, device=y.device), - torch.randn(self.pred_rnn_layers, batch, self.pred_hidden, dtype=y.dtype, device=y.device), - ) - - else: - state = ( - torch.zeros(self.pred_rnn_layers, batch, self.pred_hidden, dtype=y.dtype, device=y.device), - torch.zeros(self.pred_rnn_layers, batch, self.pred_hidden, dtype=y.dtype, device=y.device), - ) - return state - - def score_hypothesis( - self, hypothesis: rnnt_utils.Hypothesis, cache: Dict[Tuple[int], Any] - ) -> Tuple[torch.Tensor, List[torch.Tensor], torch.Tensor]: - """ - Similar to the predict() method, instead this method scores a Hypothesis during beam search. - Hypothesis is a dataclass representing one hypothesis in a Beam Search. - - Args: - hypothesis: Refer to rnnt_utils.Hypothesis. - cache: Dict which contains a cache to avoid duplicate computations. - - Returns: - Returns a tuple (y, states, lm_token) such that: - y is a torch.Tensor of shape [1, 1, H] representing the score of the last token in the Hypothesis. - state is a list of RNN states, each of shape [L, 1, H]. - lm_token is the final integer token of the hypothesis. - """ - if hypothesis.dec_state is not None: - device = hypothesis.dec_state[0].device - else: - _p = next(self.parameters()) - device = _p.device - - # parse "blank" tokens in hypothesis - if len(hypothesis.y_sequence) > 0 and hypothesis.y_sequence[-1] == self.blank_idx: - blank_state = True - else: - blank_state = False - - # Convert last token of hypothesis to torch.Tensor - target = torch.full([1, 1], fill_value=hypothesis.y_sequence[-1], device=device, dtype=torch.long) - lm_token = target[:, -1] # [1] - - # Convert current hypothesis into a tuple to preserve in cache - sequence = tuple(hypothesis.y_sequence) - - if sequence in cache: - y, new_state = cache[sequence] - else: - # Obtain score for target token and new states - if blank_state: - y, new_state = self.predict(None, state=None, add_sos=False, batch_size=1) # [1, 1, H] - - else: - y, new_state = self.predict( - target, state=hypothesis.dec_state, add_sos=False, batch_size=1 - ) # [1, 1, H] - - y = y[:, -1:, :] # Extract just last state : [1, 1, H] - cache[sequence] = (y, new_state) - - return y, new_state, lm_token - - def batch_score_hypothesis( - self, - hypotheses: List[rnnt_utils.Hypothesis], - cache: Dict[Tuple[int], Any], - ) -> Tuple[List[torch.Tensor], List[List[torch.Tensor]]]: - """ - Used for batched beam search algorithms. Similar to score_hypothesis method. - - Args: - hypothesis: List of Hypotheses. Refer to rnnt_utils.Hypothesis. - cache: Dict which contains a cache to avoid duplicate computations. - - Returns: - Returns a tuple (batch_dec_out, batch_dec_states) such that: - batch_dec_out: a list of torch.Tensor [1, H] representing the prediction network outputs for the last tokens in the Hypotheses. - batch_dec_states: a list of list of RNN states, each of shape [L, B, H]. Represented as B x List[states]. - """ - final_batch = len(hypotheses) - - if final_batch == 0: - raise ValueError("No hypotheses was provided for the batch!") - - _p = next(self.parameters()) - device = _p.device - - tokens = [] - to_process = [] - final = [None for _ in range(final_batch)] - - # For each hypothesis, cache the last token of the sequence and the current states - for final_idx, hyp in enumerate(hypotheses): - sequence = tuple(hyp.y_sequence) - - if sequence in cache: - final[final_idx] = cache[sequence] - else: - tokens.append(hyp.y_sequence[-1]) - to_process.append((sequence, hyp.dec_state)) - - if to_process: - batch = len(to_process) - - # convert list of tokens to torch.Tensor, then reshape. - tokens = torch.tensor(tokens, device=device, dtype=torch.long).view(batch, -1) - dec_states = self.batch_initialize_states([d_state for _, d_state in to_process]) - - dec_out, dec_states = self.predict( - tokens, state=dec_states, add_sos=False, batch_size=batch - ) # [B, 1, H], B x List([L, 1, H]) - - # Update final states and cache shared by entire batch. - processed_idx = 0 - for final_idx in range(final_batch): - if final[final_idx] is None: - # Select sample's state from the batch state list - new_state = self.batch_select_state(dec_states, processed_idx) - - # Cache [1, H] scores of the current y_j, and its corresponding state - final[final_idx] = (dec_out[processed_idx], new_state) - cache[to_process[processed_idx][0]] = (dec_out[processed_idx], new_state) - - processed_idx += 1 - - return [dec_out for dec_out, _ in final], [dec_states for _, dec_states in final] - - def batch_initialize_states(self, decoder_states: List[List[torch.Tensor]]) -> List[torch.Tensor]: - """ - Creates a stacked decoder states to be passed to prediction network. - - Args: - decoder_states (list of list of list of torch.Tensor): list of decoder states - of shape ``[B, C, L, H]`` where B is batch size, C is the number of state - types (e.g., 2 for LSTM: hidden and cell), L is number of layers, and - H is the hidden state dimensionality. - - Returns: - batch_states (list of torch.Tensor): batch of decoder states - ``[C x torch.Tensor[L x B x H]]``. - """ - # stack decoder states into tensor of shape [B x layers x L x H] - # permute to the target shape [layers x L x B x H] - stacked_states = torch.stack([torch.stack(decoder_state) for decoder_state in decoder_states]) - permuted_states = stacked_states.permute(1, 2, 0, 3) - - return list(permuted_states.contiguous()) - - def batch_select_state(self, batch_states: List[torch.Tensor], idx: int) -> List[List[torch.Tensor]]: - """Get decoder state from batch of states, for given id. - - Args: - batch_states (list): batch of decoder states - ([L x (B, H)], [L x (B, H)]) - - idx (int): index to extract state from batch of states - - Returns: - (tuple): decoder states for given id - ([L x (1, H)], [L x (1, H)]) - """ - if batch_states is not None: - return [state[:, idx] for state in batch_states] - - return None - - @classmethod - def batch_aggregate_states_beam( - cls, - src_states: tuple[torch.Tensor, torch.Tensor], - batch_size: int, - beam_size: int, - indices: torch.Tensor, - dst_states: Optional[tuple[torch.Tensor, torch.Tensor]] = None, - ) -> tuple[torch.Tensor, torch.Tensor]: - """ - Aggregates decoder states based on the given indices. - - Args: - src_states (Tuple[torch.Tensor, torch.Tensor]): source states of - shape `([L x (batch_size * beam_size, H)], [L x (batch_size * beam_size, H)])` - batch_size (int): The size of the batch. - beam_size (int): The size of the beam. - indices (torch.Tensor): A tensor of shape `(batch_size, beam_size)` containing - the indices in beam that map the source states to the destination states. - dst_states (Optional[Tuple[torch.Tensor, torch.Tensor]]): If provided, the method - updates these tensors in-place. - - Returns: - Tuple[torch.Tensor, torch.Tensor]: The aggregated states. - - Note: - The `indices` tensor is expanded to match the shape of the source states - during the gathering operation. - """ - layers_num = src_states[0].shape[0] - layers_dim = src_states[0].shape[-1] - - beam_shape = torch.Size((layers_num, batch_size, beam_size, layers_dim)) - flat_shape = torch.Size((layers_num, batch_size * beam_size, layers_dim)) - - # Expand indices to match the source states' shape - indices_expanded = indices[None, :, :, None].expand(beam_shape) - - if dst_states is not None: - # Perform in-place gathering into dst_states - torch.gather( - src_states[0].view(beam_shape), dim=2, index=indices_expanded, out=dst_states[0].view(beam_shape) - ) - torch.gather( - src_states[1].view(beam_shape), dim=2, index=indices_expanded, out=dst_states[1].view(beam_shape) - ) - return dst_states - - # Gather and reshape into the output format - return ( - torch.gather(src_states[0].view(beam_shape), dim=2, index=indices_expanded).view(flat_shape), - torch.gather(src_states[1].view(beam_shape), dim=2, index=indices_expanded).view(flat_shape), - ) - - def batch_concat_states(self, batch_states: List[List[torch.Tensor]]) -> List[torch.Tensor]: - """Concatenate a batch of decoder state to a packed state. - - Args: - batch_states (list): batch of decoder states - B x ([L x (H)], [L x (H)]) - - Returns: - (tuple): decoder states - (L x B x H, L x B x H) - """ - state_list = [] - - for state_id in range(len(batch_states[0])): - batch_list = [] - for sample_id in range(len(batch_states)): - tensor = ( - torch.stack(batch_states[sample_id][state_id]) - if not isinstance(batch_states[sample_id][state_id], torch.Tensor) - else batch_states[sample_id][state_id] - ) # [L, H] - tensor = tensor.unsqueeze(0) # [1, L, H] - batch_list.append(tensor) - - state_tensor = torch.cat(batch_list, 0) # [B, L, H] - state_tensor = state_tensor.transpose(1, 0) # [L, B, H] - state_list.append(state_tensor) - - return state_list - - @classmethod - def batch_replace_states_mask( - cls, - src_states: Tuple[torch.Tensor, torch.Tensor], - dst_states: Tuple[torch.Tensor, torch.Tensor], - mask: torch.Tensor, - other_src_states: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, - ): - """ - Replaces states in `dst_states` with states from `src_states` based on the given `mask`. - - Args: - mask (torch.Tensor): When True, selects values from `src_states`, otherwise `out` or `other_src_states` (if provided). - src_states (Tuple[torch.Tensor, torch.Tensor]): Values selected at indices where `mask` is True. - dst_states (Tuple[torch.Tensor, torch.Tensor])): The output states. - other_src_states (Tuple[torch.Tensor, torch.Tensor], optional): Values selected at indices where `mask` is False. - - Note: - This operation is performed without CPU-GPU synchronization by using `torch.where`. - """ - # same as `dst_states[i][mask] = src_states[i][mask]`, but non-blocking - # we need to cast, since LSTM is calculated in fp16 even if autocast to bfloat16 is enabled - - other = other_src_states if other_src_states is not None else dst_states - dtype = dst_states[0].dtype - torch.where(mask.unsqueeze(0).unsqueeze(-1), src_states[0].to(dtype), other[0].to(dtype), out=dst_states[0]) - torch.where(mask.unsqueeze(0).unsqueeze(-1), src_states[1].to(dtype), other[1].to(dtype), out=dst_states[1]) - - @classmethod - def batch_replace_states_all( - cls, - src_states: Tuple[torch.Tensor, torch.Tensor], - dst_states: Tuple[torch.Tensor, torch.Tensor], - batch_size: int | None = None, - ): - """Replace states in dst_states with states from src_states""" - if batch_size is None: - dst_states[0].copy_(src_states[0]) - dst_states[1].copy_(src_states[1]) - else: - dst_states[0][:, :batch_size].copy_(src_states[0][:, :batch_size]) - dst_states[1][:, :batch_size].copy_(src_states[1][:, :batch_size]) - - @classmethod - def clone_state(cls, state: tuple[torch.Tensor, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]: - """Return copy of the states""" - return state[0].clone(), state[1].clone() - - @classmethod - def batch_split_states( - cls, batch_states: tuple[torch.Tensor, torch.Tensor] - ) -> list[tuple[torch.Tensor, torch.Tensor]]: - """ - Split states into a list of states. - Useful for splitting the final state for converting results of the decoding algorithm to Hypothesis class. - """ - return [ - (sub_state_1.squeeze(1), sub_state_2.squeeze(1)) - for sub_state_1, sub_state_2 in zip(batch_states[0].split(1, dim=1), batch_states[1].split(1, dim=1)) - ] - - @classmethod - def batch_unsplit_states( - cls, batch_states: list[tuple[torch.Tensor, torch.Tensor]], device=None, dtype=None - ) -> tuple[torch.Tensor, torch.Tensor]: - """ - Concatenate a batch of decoder state to a packed state. Inverse of `batch_split_states`. - - Args: - batch_states (list): batch of decoder states - B x ([L x (H)], [L x (H)]) - - Returns: - (tuple): decoder states - (L x B x H, L x B x H) - """ - return ( - torch.stack([state[0] for state in batch_states], dim=1).to(device=device, dtype=dtype), - torch.stack([state[1] for state in batch_states], dim=1).to(device=device, dtype=dtype), - ) - - def batch_copy_states( - self, - old_states: List[torch.Tensor], - new_states: List[torch.Tensor], - ids: List[int], - value: Optional[float] = None, - ) -> List[torch.Tensor]: - """Copy states from new state to old state at certain indices. - - Args: - old_states(list): packed decoder states - (L x B x H, L x B x H) - - new_states: packed decoder states - (L x B x H, L x B x H) - - ids (list): List of indices to copy states at. - - value (optional float): If a value should be copied instead of a state slice, a float should be provided - - Returns: - batch of decoder states with partial copy at ids (or a specific value). - (L x B x H, L x B x H) - """ - for state_id in range(len(old_states)): - if value is None: - old_states[state_id][:, ids, :] = new_states[state_id][:, ids, :] - else: - old_states[state_id][:, ids, :] *= 0.0 - old_states[state_id][:, ids, :] += value - - return old_states - - def mask_select_states( - self, states: Tuple[torch.Tensor, torch.Tensor], mask: torch.Tensor - ) -> Tuple[torch.Tensor, torch.Tensor]: - """ - Return states by mask selection - Args: - states: states for the batch - mask: boolean mask for selecting states; batch dimension should be the same as for states - - Returns: - states filtered by mask - """ - # LSTM in PyTorch returns a tuple of 2 tensors as a state - return states[0][:, mask], states[1][:, mask] - - # Adapter method overrides - def add_adapter(self, name: str, cfg: DictConfig): - # Update the config with correct input dim - cfg = self._update_adapter_cfg_input_dim(cfg) - # Add the adapter - super().add_adapter(name=name, cfg=cfg) - - def _update_adapter_cfg_input_dim(self, cfg: DictConfig): - cfg = adapter_utils.update_adapter_cfg_input_dim(self, cfg, module_dim=self.pred_hidden) - return cfg - - -class RNNTJoint(rnnt_abstract.AbstractRNNTJoint, Exportable, AdapterModuleMixin): - """A Recurrent Neural Network Transducer Joint Network (RNN-T Joint Network). - An RNN-T Joint network, comprised of a feedforward model. - - Args: - jointnet: A dict-like object which contains the following key-value pairs. - encoder_hidden: int specifying the hidden dimension of the encoder net. - pred_hidden: int specifying the hidden dimension of the prediction net. - joint_hidden: int specifying the hidden dimension of the joint net - activation: Activation function used in the joint step. Can be one of - ['relu', 'tanh', 'sigmoid']. - - Optionally, it may also contain the following: - dropout: float, set to 0.0 by default. Optional dropout applied at the end of the joint net. - - num_classes: int, specifying the vocabulary size that the joint network must predict, - excluding the RNNT blank token. - - vocabulary: Optional list of strings/tokens that comprise the vocabulary of the joint network. - Unused and kept only for easy access for character based encoding RNNT models. - - log_softmax: Optional bool, set to None by default. If set as None, will compute the log_softmax() - based on the value provided. - - preserve_memory: Optional bool, set to False by default. If the model crashes due to the memory - intensive joint step, one might try this flag to empty the tensor cache in pytorch. - - Warning: This will make the forward-backward pass much slower than normal. - It also might not fix the OOM if the GPU simply does not have enough memory to compute the joint. - - fuse_loss_wer: Optional bool, set to False by default. - - Fuses the joint forward, loss forward and - wer forward steps. In doing so, it trades of speed for memory conservation by creating sub-batches - of the provided batch of inputs, and performs Joint forward, loss forward and wer forward (optional), - all on sub-batches, then collates results to be exactly equal to results from the entire batch. - - When this flag is set, prior to calling forward, the fields `loss` and `wer` (either one) *must* - be set using the `RNNTJoint.set_loss()` or `RNNTJoint.set_wer()` methods. - - Further, when this flag is set, the following argument `fused_batch_size` *must* be provided - as a non negative integer. This value refers to the size of the sub-batch. - - When the flag is set, the input and output signature of `forward()` of this method changes. - Input - in addition to `encoder_outputs` (mandatory argument), the following arguments can be provided. - - - decoder_outputs (optional). Required if loss computation is required. - - - encoder_lengths (required) - - - transcripts (optional). Required for wer calculation. - - - transcript_lengths (optional). Required for wer calculation. - - - compute_wer (bool, default false). Whether to compute WER or not for the fused batch. - - - keep_hypotheses (bool, default false). Whether to keep the hypotheses of the decoded outputs. - - Output - instead of the usual `joint` log prob tensor, the following results can be returned. - - - loss (optional). Returned if decoder_outputs, transcripts and transript_lengths are not None. - - - wer_numerator + wer_denominator (optional). Returned if transcripts, transcripts_lengths are provided - and compute_wer is set. - - fused_batch_size: Optional int, required if `fuse_loss_wer` flag is set. Determines the size of the - sub-batches. Should be any value below the actual batch size per GPU. - masking_prob: Optional float, indicating the probability of masking out decoder output in HAINAN - (Hybrid Autoregressive Inference Transducer) model, described in https://arxiv.org/pdf/2410.02597 - Default to -1.0, which runs standard Joint network computation; if > 0, then masking out decoder output - with the specified probability. - """ - - @property - def input_types(self): - """Returns definitions of module input ports.""" - return { - "encoder_outputs": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), - "decoder_outputs": NeuralType(('B', 'D', 'T'), EmbeddedTextType()), - "encoder_lengths": NeuralType(tuple('B'), LengthsType(), optional=True), - "transcripts": NeuralType(('B', 'T'), LabelsType(), optional=True), - "transcript_lengths": NeuralType(tuple('B'), LengthsType(), optional=True), - "compute_wer": NeuralType(optional=True), - "keep_hypotheses": NeuralType(optional=True), - } - - @property - def output_types(self): - """Returns definitions of module output ports.""" - if not self._fuse_loss_wer: - return { - "outputs": NeuralType(('B', 'T', 'T', 'D'), LogprobsType()), - } - - else: - return { - "loss": NeuralType(elements_type=LossType(), optional=True), - "wer": NeuralType(elements_type=ElementType(), optional=True), - "wer_numer": NeuralType(elements_type=ElementType(), optional=True), - "wer_denom": NeuralType(elements_type=ElementType(), optional=True), - } - - def _prepare_for_export(self, **kwargs): - self._fuse_loss_wer = False - self.log_softmax = False - super()._prepare_for_export(**kwargs) - - def input_example(self, max_batch=1, max_dim=8192): - """ - Generates input examples for tracing etc. - Returns: - A tuple of input examples. - """ - B, T, U = max_batch, max_dim, max_batch - encoder_outputs = torch.randn(B, self.encoder_hidden, T).to(next(self.parameters()).device) - decoder_outputs = torch.randn(B, self.pred_hidden, U).to(next(self.parameters()).device) - return (encoder_outputs, decoder_outputs) - - @property - def disabled_deployment_input_names(self): - """Implement this method to return a set of input names disabled for export""" - return set(["encoder_lengths", "transcripts", "transcript_lengths", "compute_wer"]) - - def __init__( - self, - jointnet: Dict[str, Any], - num_classes: int, - num_extra_outputs: int = 0, - vocabulary: Optional[List] = None, - log_softmax: Optional[bool] = None, - preserve_memory: bool = False, - fuse_loss_wer: bool = False, - fused_batch_size: Optional[int] = None, - experimental_fuse_loss_wer: Any = None, - masking_prob: float = -1.0, - ): - super().__init__() - - self.vocabulary = vocabulary - - self._vocab_size = num_classes - self._num_extra_outputs = num_extra_outputs - self._num_classes = num_classes + 1 + num_extra_outputs # 1 is for blank - - self.masking_prob = masking_prob - if self.masking_prob > 0.0: - assert self.masking_prob < 1.0, "masking_prob must be between 0 and 1" - - if experimental_fuse_loss_wer is not None: - # Override fuse_loss_wer from deprecated argument - fuse_loss_wer = experimental_fuse_loss_wer - - self._fuse_loss_wer = fuse_loss_wer - self._fused_batch_size = fused_batch_size - - if fuse_loss_wer and (fused_batch_size is None): - raise ValueError("If `fuse_loss_wer` is set, then `fused_batch_size` cannot be None!") - - self._loss = None - self._wer = None - - # Log softmax should be applied explicitly only for CPU - self.log_softmax = log_softmax - self.preserve_memory = preserve_memory - - if preserve_memory: - logging.warning( - "`preserve_memory` was set for the Joint Model. Please be aware this will severely impact " - "the forward-backward step time. It also might not solve OOM issues if the GPU simply " - "does not have enough memory to compute the joint." - ) - - # Required arguments - self.encoder_hidden = jointnet['encoder_hidden'] - self.pred_hidden = jointnet['pred_hidden'] - self.joint_hidden = jointnet['joint_hidden'] - self.activation = jointnet['activation'] - - # Optional arguments - dropout = jointnet.get('dropout', 0.0) - - self.pred, self.enc, self.joint_net = self._joint_net_modules( - num_classes=self._num_classes, # add 1 for blank symbol - pred_n_hidden=self.pred_hidden, - enc_n_hidden=self.encoder_hidden, - joint_n_hidden=self.joint_hidden, - activation=self.activation, - dropout=dropout, - ) - - # Flag needed for RNNT export support - self._rnnt_export = False - - # to change, requires running ``model.temperature = T`` explicitly - self.temperature = 1.0 - - self.hypotheses = None - - @typecheck() - def forward( - self, - encoder_outputs: torch.Tensor, - decoder_outputs: Optional[torch.Tensor], - encoder_lengths: Optional[torch.Tensor] = None, - transcripts: Optional[torch.Tensor] = None, - transcript_lengths: Optional[torch.Tensor] = None, - compute_wer: bool = False, - keep_hypotheses: bool = False, - ) -> Union[torch.Tensor, List[Optional[torch.Tensor]]]: - # encoder = (B, D, T) - # decoder = (B, D, U) if passed, else None - encoder_outputs = encoder_outputs.transpose(1, 2) # (B, T, D) - - if decoder_outputs is not None: - decoder_outputs = decoder_outputs.transpose(1, 2) # (B, U, D) - - if not self._fuse_loss_wer: - if decoder_outputs is None: - raise ValueError( - "decoder_outputs passed is None, and `fuse_loss_wer` is not set. " - "decoder_outputs can only be None for fused step!" - ) - - out = self.joint(encoder_outputs, decoder_outputs) # [B, T, U, V + 1] - return out - - else: - # At least the loss module must be supplied during fused joint - if self._loss is None or self._wer is None: - raise ValueError("`fuse_loss_wer` flag is set, but `loss` and `wer` modules were not provided! ") - - # If fused joint step is required, fused batch size is required as well - if self._fused_batch_size is None: - raise ValueError("If `fuse_loss_wer` is set, then `fused_batch_size` cannot be None!") - - # When using fused joint step, both encoder and transcript lengths must be provided - if (encoder_lengths is None) or (transcript_lengths is None): - raise ValueError( - "`fuse_loss_wer` is set, therefore encoder and target lengths " "must be provided as well!" - ) - - losses = [] - wers, wer_nums, wer_denoms = [], [], [] - target_lengths = [] - batch_size = int(encoder_outputs.size(0)) # actual batch size - hypotheses = [] - - # Iterate over batch using fused_batch_size steps - for batch_idx in range(0, batch_size, self._fused_batch_size): - begin = batch_idx - end = min(begin + self._fused_batch_size, batch_size) - - # Extract the sub batch inputs - # sub_enc = encoder_outputs[begin:end, ...] - # sub_transcripts = transcripts[begin:end, ...] - sub_enc = encoder_outputs.narrow(dim=0, start=begin, length=int(end - begin)) - sub_transcripts = transcripts.narrow(dim=0, start=begin, length=int(end - begin)) - - sub_enc_lens = encoder_lengths[begin:end] - sub_transcript_lens = transcript_lengths[begin:end] - - # Sub transcripts does not need the full padding of the entire batch - # Therefore reduce the decoder time steps to match - max_sub_enc_length = sub_enc_lens.max() - max_sub_transcript_length = sub_transcript_lens.max() - - if decoder_outputs is not None: - # Reduce encoder length to preserve computation - # Encoder: [sub-batch, T, D] -> [sub-batch, T', D]; T' < T - if sub_enc.shape[1] != max_sub_enc_length: - sub_enc = sub_enc.narrow(dim=1, start=0, length=int(max_sub_enc_length)) - - # sub_dec = decoder_outputs[begin:end, ...] # [sub-batch, U, D] - sub_dec = decoder_outputs.narrow(dim=0, start=begin, length=int(end - begin)) # [sub-batch, U, D] - - # Reduce decoder length to preserve computation - # Decoder: [sub-batch, U, D] -> [sub-batch, U', D]; U' < U - if sub_dec.shape[1] != max_sub_transcript_length + 1: - sub_dec = sub_dec.narrow(dim=1, start=0, length=int(max_sub_transcript_length + 1)) - - # Perform joint => [sub-batch, T', U', V + 1] - sub_joint = self.joint(sub_enc, sub_dec) - - del sub_dec - - # Reduce transcript length to correct alignment - # Transcript: [sub-batch, L] -> [sub-batch, L']; L' <= L - if sub_transcripts.shape[1] != max_sub_transcript_length: - sub_transcripts = sub_transcripts.narrow(dim=1, start=0, length=int(max_sub_transcript_length)) - - # Compute sub batch loss - # preserve loss reduction type - loss_reduction = self.loss.reduction - - # override loss reduction to sum - self.loss.reduction = None - - # compute and preserve loss - loss_batch = self.loss( - log_probs=sub_joint, - targets=sub_transcripts, - input_lengths=sub_enc_lens, - target_lengths=sub_transcript_lens, - ) - losses.append(loss_batch) - target_lengths.append(sub_transcript_lens) - - # reset loss reduction type - self.loss.reduction = loss_reduction - - else: - losses = None - - # Update WER for sub batch - if compute_wer: - sub_enc = sub_enc.transpose(1, 2) # [B, T, D] -> [B, D, T] - sub_enc = sub_enc.detach() - sub_transcripts = sub_transcripts.detach() - - # Update WER on each process without syncing - if self.training: - original_sync = self.wer._to_sync - self.wer._to_sync = False - - self.wer.update( - predictions=sub_enc, - predictions_lengths=sub_enc_lens, - targets=sub_transcripts, - targets_lengths=sub_transcript_lens, - ) - - hyp = self.wer.get_hypotheses() if keep_hypotheses else [] - - # Sync and all_reduce on all processes, compute global WER - wer, wer_num, wer_denom = self.wer.compute() - self.wer.reset() - - if self.training: - self.wer._to_sync = original_sync - - wers.append(wer) - wer_nums.append(wer_num) - wer_denoms.append(wer_denom) - hypotheses.extend(hyp) - - del sub_enc, sub_transcripts, sub_enc_lens, sub_transcript_lens - - # Reduce over sub batches - if losses is not None: - losses = self.loss.reduce(losses, target_lengths) - - # Collect sub batch wer results - if compute_wer: - wer = sum(wers) / len(wers) - wer_num = sum(wer_nums) - wer_denom = sum(wer_denoms) - else: - wer = None - wer_num = None - wer_denom = None - - self.hypotheses = hypotheses if keep_hypotheses else None - return losses, wer, wer_num, wer_denom - - def get_hypotheses(self): - """ - Returns the hypotheses generated during the last forward pass. - """ - if self.hypotheses is None: - raise ValueError( - "No hypotheses were generated during the last forward pass. Did you set keep_hypotheses=True in forward()?" - ) - return self.hypotheses - - def project_encoder(self, encoder_output: torch.Tensor) -> torch.Tensor: - """ - Project the encoder output to the joint hidden dimension. - - Args: - encoder_output: A torch.Tensor of shape [B, T, D] - - Returns: - A torch.Tensor of shape [B, T, H] - """ - return self.enc(encoder_output) - - def project_prednet(self, prednet_output: torch.Tensor) -> torch.Tensor: - """ - Project the Prediction Network (Decoder) output to the joint hidden dimension. - - Args: - prednet_output: A torch.Tensor of shape [B, U, D] - - Returns: - A torch.Tensor of shape [B, U, H] - """ - return self.pred(prednet_output) - - def joint_after_projection(self, f: torch.Tensor, g: torch.Tensor) -> torch.Tensor: - r""" - Compute the joint step of the network after projection. - - Here, - B = Batch size - T = Acoustic model timesteps - U = Target sequence length - H1, H2 = Hidden dimensions of the Encoder / Decoder respectively - H = Hidden dimension of the Joint hidden step. - V = Vocabulary size of the Decoder (excluding the RNNT blank token). - - NOTE: - The implementation of this model is slightly modified from the original paper. - The original paper proposes the following steps : - (enc, dec) -> Expand + Concat + Sum [B, T, U, H1+H2] -> Forward through joint hidden [B, T, U, H] -- \*1 - \*1 -> Forward through joint final [B, T, U, V + 1]. - - We instead split the joint hidden into joint_hidden_enc and joint_hidden_dec and act as follows: - enc -> Forward through joint_hidden_enc -> Expand [B, T, 1, H] -- \*1 - dec -> Forward through joint_hidden_dec -> Expand [B, 1, U, H] -- \*2 - (\*1, \*2) -> Sum [B, T, U, H] -> Forward through joint final [B, T, U, V + 1]. - - Args: - f: Output of the Encoder model. A torch.Tensor of shape [B, T, H1] - g: Output of the Decoder model. A torch.Tensor of shape [B, U, H2] - - Returns: - Logits / log softmaxed tensor of shape (B, T, U, V + 1). - """ - f = f.unsqueeze(dim=2) # (B, T, 1, H) - g = g.unsqueeze(dim=1) # (B, 1, U, H) - - if self.training and self.masking_prob > 0: - [B, _, U, _] = g.shape - rand = torch.rand([B, 1, U, 1]).to(g.device) - rand = torch.gt(rand, self.masking_prob) - g = g * rand - - inp = f + g # [B, T, U, H] - - del f, g - - # Forward adapter modules on joint hidden - if self.is_adapter_available(): - inp = self.forward_enabled_adapters(inp) - - res = self.joint_net(inp) # [B, T, U, V + 1] - - del inp - - if self.preserve_memory: - torch.cuda.empty_cache() - - # If log_softmax is automatic - if self.log_softmax is None: - if not res.is_cuda: # Use log softmax only if on CPU - if self.temperature != 1.0: - res = (res / self.temperature).log_softmax(dim=-1) - else: - res = res.log_softmax(dim=-1) - else: - if self.log_softmax: - if self.temperature != 1.0: - res = (res / self.temperature).log_softmax(dim=-1) - else: - res = res.log_softmax(dim=-1) - - return res - - def _joint_net_modules(self, num_classes, pred_n_hidden, enc_n_hidden, joint_n_hidden, activation, dropout): - """ - Prepare the trainable modules of the Joint Network - - Args: - num_classes: Number of output classes (vocab size) excluding the RNNT blank token. - pred_n_hidden: Hidden size of the prediction network. - enc_n_hidden: Hidden size of the encoder network. - joint_n_hidden: Hidden size of the joint network. - activation: Activation of the joint. Can be one of [relu, tanh, sigmoid] - dropout: Dropout value to apply to joint. - """ - pred = torch.nn.Linear(pred_n_hidden, joint_n_hidden) - enc = torch.nn.Linear(enc_n_hidden, joint_n_hidden) - - if activation not in ['relu', 'sigmoid', 'tanh']: - raise ValueError("Unsupported activation for joint step - please pass one of " "[relu, sigmoid, tanh]") - - activation = activation.lower() - - if activation == 'relu': - activation = torch.nn.ReLU(inplace=True) - elif activation == 'sigmoid': - activation = torch.nn.Sigmoid() - elif activation == 'tanh': - activation = torch.nn.Tanh() - - layers = ( - [activation] - + ([torch.nn.Dropout(p=dropout)] if dropout else []) - + [torch.nn.Linear(joint_n_hidden, num_classes)] - ) - return pred, enc, torch.nn.Sequential(*layers) - - # Adapter method overrides - def add_adapter(self, name: str, cfg: DictConfig): - # Update the config with correct input dim - cfg = self._update_adapter_cfg_input_dim(cfg) - # Add the adapter - super().add_adapter(name=name, cfg=cfg) - - def _update_adapter_cfg_input_dim(self, cfg: DictConfig): - cfg = adapter_utils.update_adapter_cfg_input_dim(self, cfg, module_dim=self.joint_hidden) - return cfg - - @property - def num_classes_with_blank(self): - return self._num_classes - - @property - def num_extra_outputs(self): - return self._num_extra_outputs - - @property - def loss(self): - return self._loss - - def set_loss(self, loss): - if not self._fuse_loss_wer: - raise ValueError("Attempting to set loss module even though `fuse_loss_wer` is not set!") - - self._loss = loss - - @property - def wer(self): - return self._wer - - def set_wer(self, wer): - if not self._fuse_loss_wer: - raise ValueError("Attempting to set WER module even though `fuse_loss_wer` is not set!") - - self._wer = wer - - @property - def fuse_loss_wer(self): - return self._fuse_loss_wer - - def set_fuse_loss_wer(self, fuse_loss_wer, loss=None, metric=None): - self._fuse_loss_wer = fuse_loss_wer - - self._loss = loss - self._wer = metric - - @property - def fused_batch_size(self): - return self._fused_batch_size - - def set_fused_batch_size(self, fused_batch_size): - self._fused_batch_size = fused_batch_size - - -class RNNTDecoderJoint(torch.nn.Module, Exportable): - """ - Utility class to export Decoder+Joint as a single module - """ - - def __init__(self, decoder, joint): - super().__init__() - self.decoder = decoder - self.joint = joint - - @property - def input_types(self): - state_type = NeuralType(('D', 'B', 'D'), ElementType()) - mytypes = { - 'encoder_outputs': NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), - "targets": NeuralType(('B', 'T'), LabelsType()), - "target_length": NeuralType(tuple('B'), LengthsType()), - 'input_states_1': state_type, - 'input_states_2': state_type, - } - - return mytypes - - def input_example(self, max_batch=1, max_dim=1): - decoder_example = self.decoder.input_example(max_batch=max_batch, max_dim=max_dim) - state1, state2 = decoder_example[-1] - return tuple([self.joint.input_example()[0]]) + decoder_example[:2] + (state1, state2) - - @property - def output_types(self): - return { - "outputs": NeuralType(('B', 'T', 'T', 'D'), LogprobsType()), - "prednet_lengths": NeuralType(tuple('B'), LengthsType()), - "output_states_1": NeuralType((('D', 'B', 'D')), ElementType()), - "output_states_2": NeuralType((('D', 'B', 'D')), ElementType()), - } - - def forward(self, encoder_outputs, targets, target_length, input_states_1, input_states_2): - decoder_outputs = self.decoder(targets, target_length, (input_states_1, input_states_2)) - decoder_output = decoder_outputs[0] - decoder_length = decoder_outputs[1] - input_states_1, input_states_2 = decoder_outputs[2][0], decoder_outputs[2][1] - joint_output = self.joint(encoder_outputs, decoder_output) - return (joint_output, decoder_length, input_states_1, input_states_2) - - -class RNNTDecoderJointSSL(torch.nn.Module): - def __init__(self, decoder, joint): - super().__init__() - self.decoder = decoder - self.joint = joint - - @property - def needs_labels(self): - return True - - @property - def input_types(self): - return { - "encoder_output": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), - "targets": NeuralType(('B', 'T'), LabelsType()), - "target_lengths": NeuralType(tuple('B'), LengthsType()), - } - - @property - def output_types(self): - return {"log_probs": NeuralType(('B', 'T', 'D'), SpectrogramType())} - - def forward(self, encoder_output, targets, target_lengths): - - decoder, target_length, states = self.decoder(targets=targets, target_length=target_lengths) - log_probs = self.joint(encoder_outputs=encoder_output, decoder_outputs=decoder) - - return log_probs - - -class SampledRNNTJoint(RNNTJoint): - """A Sampled Recurrent Neural Network Transducer Joint Network (RNN-T Joint Network). - An RNN-T Joint network, comprised of a feedforward model, where the vocab size will be sampled instead - of computing the full vocabulary joint. - - Args: - jointnet: A dict-like object which contains the following key-value pairs. - encoder_hidden: int specifying the hidden dimension of the encoder net. - pred_hidden: int specifying the hidden dimension of the prediction net. - joint_hidden: int specifying the hidden dimension of the joint net - activation: Activation function used in the joint step. Can be one of - ['relu', 'tanh', 'sigmoid']. - - Optionally, it may also contain the following: - dropout: float, set to 0.0 by default. Optional dropout applied at the end of the joint net. - - num_classes: int, specifying the vocabulary size that the joint network must predict, - excluding the RNNT blank token. - - n_samples: int, specifies the number of tokens to sample from the vocabulary space, - excluding the RNNT blank token. If a given value is larger than the entire vocabulary size, - then the full vocabulary will be used. - - vocabulary: Optional list of strings/tokens that comprise the vocabulary of the joint network. - Unused and kept only for easy access for character based encoding RNNT models. - - log_softmax: Optional bool, set to None by default. If set as None, will compute the log_softmax() - based on the value provided. - - preserve_memory: Optional bool, set to False by default. If the model crashes due to the memory - intensive joint step, one might try this flag to empty the tensor cache in pytorch. - - Warning: This will make the forward-backward pass much slower than normal. - It also might not fix the OOM if the GPU simply does not have enough memory to compute the joint. - - fuse_loss_wer: Optional bool, set to False by default. - - Fuses the joint forward, loss forward and - wer forward steps. In doing so, it trades of speed for memory conservation by creating sub-batches - of the provided batch of inputs, and performs Joint forward, loss forward and wer forward (optional), - all on sub-batches, then collates results to be exactly equal to results from the entire batch. - - When this flag is set, prior to calling forward, the fields `loss` and `wer` (either one) *must* - be set using the `RNNTJoint.set_loss()` or `RNNTJoint.set_wer()` methods. - - Further, when this flag is set, the following argument `fused_batch_size` *must* be provided - as a non negative integer. This value refers to the size of the sub-batch. - - When the flag is set, the input and output signature of `forward()` of this method changes. - Input - in addition to `encoder_outputs` (mandatory argument), the following arguments can be provided. - - - decoder_outputs (optional). Required if loss computation is required. - - - encoder_lengths (required) - - - transcripts (optional). Required for wer calculation. - - - transcript_lengths (optional). Required for wer calculation. - - - compute_wer (bool, default false). Whether to compute WER or not for the fused batch. - - Output - instead of the usual `joint` log prob tensor, the following results can be returned. - - - loss (optional). Returned if decoder_outputs, transcripts and transript_lengths are not None. - - - wer_numerator + wer_denominator (optional). Returned if transcripts, transcripts_lengths are provided - and compute_wer is set. - - fused_batch_size: Optional int, required if `fuse_loss_wer` flag is set. Determines the size of the - sub-batches. Should be any value below the actual batch size per GPU. - """ - - def __init__( - self, - jointnet: Dict[str, Any], - num_classes: int, - n_samples: int, - vocabulary: Optional[List] = None, - log_softmax: Optional[bool] = None, - preserve_memory: bool = False, - fuse_loss_wer: bool = False, - fused_batch_size: Optional[int] = None, - ): - super().__init__( - jointnet=jointnet, - num_classes=num_classes, - vocabulary=vocabulary, - log_softmax=log_softmax, - preserve_memory=preserve_memory, - fuse_loss_wer=fuse_loss_wer, - fused_batch_size=fused_batch_size, - ) - self.n_samples = n_samples - self.register_buffer('blank_id', torch.tensor([self.num_classes_with_blank - 1]), persistent=False) - - @typecheck() - def forward( - self, - encoder_outputs: torch.Tensor, - decoder_outputs: Optional[torch.Tensor], - encoder_lengths: Optional[torch.Tensor] = None, - transcripts: Optional[torch.Tensor] = None, - transcript_lengths: Optional[torch.Tensor] = None, - compute_wer: bool = False, - ) -> Union[torch.Tensor, List[Optional[torch.Tensor]]]: - # If in inference mode, revert to basic RNNT Joint behaviour. - # Sampled RNNT is only used for training. - if not torch.is_grad_enabled() or torch.is_inference_mode_enabled(): - # Simply call full tensor joint - return super().forward( - encoder_outputs=encoder_outputs, - decoder_outputs=decoder_outputs, - encoder_lengths=encoder_lengths, - transcripts=transcripts, - transcript_lengths=transcript_lengths, - compute_wer=compute_wer, - ) - - if transcripts is None or transcript_lengths is None: - logging.warning( - "Sampled RNNT Joint currently only works with `fuse_loss_wer` set to True, " - "and when `fused_batch_size` is a positive integer." - ) - raise ValueError( - "Sampled RNNT loss only works when the transcripts are provided during training." - "Please ensure that you correctly pass the `transcripts` and `transcript_lengths`." - ) - - # encoder = (B, D, T) - # decoder = (B, D, U) if passed, else None - encoder_outputs = encoder_outputs.transpose(1, 2) # (B, T, D) - - if decoder_outputs is not None: - decoder_outputs = decoder_outputs.transpose(1, 2) # (B, U, D) - - # At least the loss module must be supplied during fused joint - if self._loss is None or self._wer is None: - raise ValueError("`fuse_loss_wer` flag is set, but `loss` and `wer` modules were not provided! ") - - # If fused joint step is required, fused batch size is required as well - if self._fused_batch_size is None: - raise ValueError("If `fuse_loss_wer` is set, then `fused_batch_size` cannot be None!") - - # When using fused joint step, both encoder and transcript lengths must be provided - if (encoder_lengths is None) or (transcript_lengths is None): - raise ValueError( - "`fuse_loss_wer` is set, therefore encoder and target lengths " "must be provided as well!" - ) - - losses = [] - wers, wer_nums, wer_denoms = [], [], [] - target_lengths = [] - batch_size = int(encoder_outputs.size(0)) # actual batch size - - # Iterate over batch using fused_batch_size steps - for batch_idx in range(0, batch_size, self._fused_batch_size): - begin = batch_idx - end = min(begin + self._fused_batch_size, batch_size) - - # Extract the sub batch inputs - # sub_enc = encoder_outputs[begin:end, ...] - # sub_transcripts = transcripts[begin:end, ...] - sub_enc = encoder_outputs.narrow(dim=0, start=begin, length=int(end - begin)) - sub_transcripts = transcripts.narrow(dim=0, start=begin, length=int(end - begin)) - - sub_enc_lens = encoder_lengths[begin:end] - sub_transcript_lens = transcript_lengths[begin:end] - - # Sub transcripts does not need the full padding of the entire batch - # Therefore reduce the decoder time steps to match - max_sub_enc_length = sub_enc_lens.max() - max_sub_transcript_length = sub_transcript_lens.max() - - if decoder_outputs is not None: - # Reduce encoder length to preserve computation - # Encoder: [sub-batch, T, D] -> [sub-batch, T', D]; T' < T - if sub_enc.shape[1] != max_sub_enc_length: - sub_enc = sub_enc.narrow(dim=1, start=0, length=int(max_sub_enc_length)) - - # sub_dec = decoder_outputs[begin:end, ...] # [sub-batch, U, D] - sub_dec = decoder_outputs.narrow(dim=0, start=begin, length=int(end - begin)) # [sub-batch, U, D] - - # Reduce decoder length to preserve computation - # Decoder: [sub-batch, U, D] -> [sub-batch, U', D]; U' < U - if sub_dec.shape[1] != max_sub_transcript_length + 1: - sub_dec = sub_dec.narrow(dim=1, start=0, length=int(max_sub_transcript_length + 1)) - - # Reduce transcript length to correct alignment - # Transcript: [sub-batch, L] -> [sub-batch, L']; L' <= L - if sub_transcripts.shape[1] != max_sub_transcript_length: - sub_transcripts = sub_transcripts.narrow(dim=1, start=0, length=int(max_sub_transcript_length)) - - # Perform sampled joint => [sub-batch, T', U', {V' < V} + 1}] - sub_joint, sub_transcripts_remapped = self.sampled_joint( - sub_enc, sub_dec, transcript=sub_transcripts, transcript_lengths=sub_transcript_lens - ) - - del sub_dec - - # Compute sub batch loss - # preserve loss reduction type - loss_reduction = self.loss.reduction - - # override loss reduction to sum - self.loss.reduction = None - - # override blank idx in order to map to new vocabulary space - # in the new vocabulary space, we set the mapping of the RNNT Blank from index V+1 to 0 - # So the loss here needs to be updated accordingly. - # TODO: See if we can have some formal API for rnnt loss to update inner blank index. - cached_blank_id = self.loss._loss.blank - self.loss._loss.blank = 0 - - # compute and preserve loss - loss_batch = self.loss( - log_probs=sub_joint, - targets=sub_transcripts_remapped, # Note: We have to use remapped transcripts here ! - input_lengths=sub_enc_lens, - target_lengths=sub_transcript_lens, # Note: Even after remap, the transcript lengths remain intact. - ) - losses.append(loss_batch) - target_lengths.append(sub_transcript_lens) - - # reset loss reduction type and blank id - self.loss.reduction = loss_reduction - self.loss._loss.blank = cached_blank_id - - else: - losses = None - - # Update WER for sub batch - if compute_wer: - sub_enc = sub_enc.transpose(1, 2) # [B, T, D] -> [B, D, T] - sub_enc = sub_enc.detach() - sub_transcripts = sub_transcripts.detach() - - # Update WER on each process without syncing - self.wer.update( - predictions=sub_enc, - predictions_lengths=sub_enc_lens, - targets=sub_transcripts, - targets_lengths=sub_transcript_lens, - ) - - # Sync and all_reduce on all processes, compute global WER - wer, wer_num, wer_denom = self.wer.compute() - self.wer.reset() - - wers.append(wer) - wer_nums.append(wer_num) - wer_denoms.append(wer_denom) - - del sub_enc, sub_transcripts, sub_enc_lens, sub_transcript_lens - - # Reduce over sub batches - if losses is not None: - losses = self.loss.reduce(losses, target_lengths) - - # Collect sub batch wer results - if compute_wer: - wer = sum(wers) / len(wers) - wer_num = sum(wer_nums) - wer_denom = sum(wer_denoms) - else: - wer = None - wer_num = None - wer_denom = None - - return losses, wer, wer_num, wer_denom - - def sampled_joint( - self, - f: torch.Tensor, - g: torch.Tensor, - transcript: torch.Tensor, - transcript_lengths: torch.Tensor, - ) -> torch.Tensor: - r""" - Compute the sampled joint step of the network. - - Reference: `Memory-Efficient Training of RNN-Transducer with Sampled Softmax `__. - - Here, - B = Batch size - T = Acoustic model timesteps - U = Target sequence length - H1, H2 = Hidden dimensions of the Encoder / Decoder respectively - H = Hidden dimension of the Joint hidden step. - V = Vocabulary size of the Decoder (excluding the RNNT blank token). - S = Sample size of vocabulary. - - NOTE: - The implementation of this joint model is slightly modified from the original paper. - The original paper proposes the following steps : - (enc, dec) -> Expand + Concat + Sum [B, T, U, H1+H2] -> Forward through joint hidden [B, T, U, H] -- \*1 - \*1 -> Forward through joint final [B, T, U, V + 1]. - - We instead split the joint hidden into joint_hidden_enc and joint_hidden_dec and act as follows: - enc -> Forward through joint_hidden_enc -> Expand [B, T, 1, H] -- \*1 - dec -> Forward through joint_hidden_dec -> Expand [B, 1, U, H] -- \*2 - (\*1, \*2) -> Sum [B, T, U, H] -> Sample Vocab V_Pos (for target tokens) and V_Neg -> - (V_Neg is sampled not uniformly by as a rand permutation of all vocab tokens, then eliminate - all Intersection(V_Pos, V_Neg) common tokens to avoid duplication of loss) -> - Concat new Vocab V_Sampled = Union(V_Pos, V_Neg) - -> Forward partially through the joint final to create [B, T, U, V_Sampled] - - Args: - f: Output of the Encoder model. A torch.Tensor of shape [B, T, H1] - g: Output of the Decoder model. A torch.Tensor of shape [B, U, H2] - transcript: Batch of transcripts. A torch.Tensor of shape [B, U] - transcript_lengths: Batch of lengths of the transcripts. A torch.Tensor of shape [B] - - Returns: - Logits / log softmaxed tensor of shape (B, T, U, V + 1). - """ - # If under inference mode, ignore sampled joint and compute full joint. - if self.training is False or torch.is_grad_enabled() is False or torch.is_inference_mode_enabled(): - # Simply call full tensor joint - return super().joint(f=f, g=g) - - # Compute sampled softmax - # f = [B, T, H1] - f = self.enc(f) - f.unsqueeze_(dim=2) # (B, T, 1, H) - - # g = [B, U, H2] - g = self.pred(g) - g.unsqueeze_(dim=1) # (B, 1, U, H) - - inp = f + g # [B, T, U, H] - - del f, g - - # Forward adapter modules on joint hidden - if self.is_adapter_available(): - inp = self.forward_enabled_adapters(inp) - - # Do partial forward of joint net (skipping the final linear) - for module in self.joint_net[:-1]: - inp = module(inp) # [B, T, U, H] - - # Begin compute of sampled RNNT joint - with torch.no_grad(): - # gather true labels - transcript_vocab_ids = torch.unique(transcript) - - # augment with blank token id - transcript_vocab_ids = torch.cat([self.blank_id, transcript_vocab_ids]) - - # Remap the transcript label ids to new positions of label ids (in the transcript_vocab_ids) - # This is necessary cause the RNNT loss doesnt care about the value, only the position of the ids - # of the transcript tokens. We can skip this step for noise samples cause those are only used for softmax - # estimation, not for computing actual label. - # From `https://stackoverflow.com/a/68969697` - bucketize algo. - t_ids = torch.arange(transcript_vocab_ids.size(0), device='cpu') - mapping = {k: v for k, v in zip(transcript_vocab_ids.to('cpu'), t_ids)} - - # From `https://stackoverflow.com/questions/13572448`. - palette, key = zip(*mapping.items()) - - t_device = transcript.device - key = torch.tensor(key, device=t_device) - palette = torch.tensor(palette, device=t_device) - - # This step maps old token id to new token id in broadcasted manner. - # For example, if original transcript tokens were [2, 1, 4, 5, 4, 1] - # But after computing the unique token set of above we get - # transcript_vocab_ids = [1, 2, 4, 5] # note: pytorch returns sorted unique values thankfully - # Then we get the index map of the new vocab ids as: - # {0: 1, 1: 2, 2: 4, 3: 5} - # Now we need to map the original transcript tokens to new vocab id space - # So we construct the inverted map as follow : - # {1: 0, 2: 1, 4: 2, 5: 3} - # Then remap the original transcript tokens to new token ids - # new_transcript = [1, 0, 2, 3, 2, 0] - index = torch.bucketize(transcript.ravel(), palette) - transcript = key[index].reshape(transcript.shape) - transcript = transcript.to(t_device) - - # Extract out partial weight tensor and bias tensor of just the V_Pos vocabulary from the full joint. - true_weights = self.joint_net[-1].weight[transcript_vocab_ids, :] - true_bias = self.joint_net[-1].bias[transcript_vocab_ids] - - # Compute the transcript joint scores (only of vocab V_Pos) - transcript_scores = torch.matmul(inp, true_weights.transpose(0, 1)) + true_bias - - # Construct acceptance criteria in vocab space, reject all tokens in Intersection(V_Pos, V_Neg) - with torch.no_grad(): - # Instead of uniform sample, first we create arange V (ignoring blank), then randomly shuffle - # this range of ids, then subset `n_samples` amount of vocab tokens out of the permuted tensor. - # This is good because it guarentees that no token will ever be repeated in V_Neg; - # which dramatically complicates loss calculation. - # Further more, with this strategy, given a `n_samples` > V + 1; we are guarenteed to get the - # V_Samples = V (i.e., full vocabulary will be used in such a case). - # Useful to debug cases where you expect sampled vocab to get exact same training curve as - # full vocab. - sample_ids = torch.randperm(n=self.num_classes_with_blank - 1, device=transcript_scores.device)[ - : self.n_samples - ] - - # We need to compute the intersection(V_Pos, V_Neg), then eliminate the intersection arguments - # from inside V_Neg. - - # First, compute the pairwise commonality to find index inside `sample_ids` which match the token id - # inside transcript_vocab_ids. - # Note: It is important to ignore the hardcoded RNNT Blank token injected at id 0 of the transcript - # vocab ids, otherwise the blank may occur twice, once for RNNT blank and once as negative sample, - # doubling the gradient of the RNNT blank token. - reject_samples = torch.where(transcript_vocab_ids[1:, None] == sample_ids[None, :]) - - # Let accept samples be a set of ids which is a subset of sample_ids - # such that intersection(V_Pos, accept_samples) is a null set. - accept_samples = sample_ids.clone() - - # In order to construct such an accept_samples tensor, first we construct a bool map - # and fill all the indices where there is a match inside of sample_ids. - # reject_samples is a tuple (transcript_vocab_position, sample_position) which gives a - # many to many map between N values of transript and M values of sample_ids. - # We dont care about transcript side matches, only the ids inside of sample_ids that matched. - sample_mask = torch.ones_like(accept_samples, dtype=torch.bool) - sample_mask[reject_samples[1]] = False - - # Finally, compute the subset of tokens by selecting only those sample_ids which had no matches - accept_samples = accept_samples[sample_mask] - - # Extract out partial weight tensor and bias tensor of just the V_Neg vocabulary from the full joint. - sample_weights = self.joint_net[-1].weight[accept_samples, :] - sample_bias = self.joint_net[-1].bias[accept_samples] - - # Compute the noise joint scores (only of vocab V_Neg) to be used for softmax - # The quality of this sample determines the quality of the softmax gradient. - # We use naive algo broadcasted over batch, but it is more efficient than sample level computation. - # One can increase `n_samples` for better estimation of rejection samples and its gradient. - noise_scores = torch.matmul(inp, sample_weights.transpose(0, 1)) + sample_bias - - # Finally, construct the sampled joint as the V_Sampled = Union(V_Pos, V_Neg) - # Here, we simply concatenate the two tensors to construct the joint with V_Sampled vocab - # because before we have properly asserted that Intersection(V_Pos, V_Neg) is a null set. - res = torch.cat([transcript_scores, noise_scores], dim=-1) - - del inp - - if self.preserve_memory: - torch.cuda.empty_cache() - - # If log_softmax is automatic - if self.log_softmax is None: - if not res.is_cuda: # Use log softmax only if on CPU - res = res.log_softmax(dim=-1) - else: - if self.log_softmax: - res = res.log_softmax(dim=-1) - - return res, transcript - - -# Add the adapter compatible modules to the registry -for cls in [RNNTDecoder, RNNTJoint, SampledRNNTJoint]: - if adapter_mixins.get_registered_adapter(cls) is None: - adapter_mixins.register_adapter(cls, cls) # base class is adapter compatible itself diff --git a/nemo/collections/asr/modules/rnnt_abstract.py b/nemo/collections/asr/modules/rnnt_abstract.py deleted file mode 100644 index e83ccc76501e0a29969095fd60b3f43f5e0e4282..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/rnnt_abstract.py +++ /dev/null @@ -1,409 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -from abc import ABC, abstractmethod -from typing import Any, Dict, List, Optional, Tuple - -import torch - -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis -from nemo.core import NeuralModule - - -class AbstractRNNTJoint(NeuralModule, ABC): - """ - An abstract RNNT Joint framework, which can possibly integrate with GreedyRNNTInfer and BeamRNNTInfer classes. - Represents the abstract RNNT Joint network, which accepts the acoustic model and prediction network - embeddings in order to compute the joint of the two prior to decoding the output sequence. - """ - - @abstractmethod - def joint_after_projection(self, f: torch.Tensor, g: torch.Tensor) -> Any: - """ - Compute the joint step of the network after the projection step. - Args: - f: Output of the Encoder model after projection. A torch.Tensor of shape [B, T, H] - g: Output of the Decoder model (Prediction Network) after projection. A torch.Tensor of shape [B, U, H] - - Returns: - Logits / log softmaxed tensor of shape (B, T, U, V + 1). - Arbitrary return type, preferably torch.Tensor, but not limited to (e.g., see HatJoint) - """ - raise NotImplementedError() - - @abstractmethod - def project_encoder(self, encoder_output: torch.Tensor) -> torch.Tensor: - """ - Project the encoder output to the joint hidden dimension. - - Args: - encoder_output: A torch.Tensor of shape [B, T, D] - - Returns: - A torch.Tensor of shape [B, T, H] - """ - raise NotImplementedError() - - @abstractmethod - def project_prednet(self, prednet_output: torch.Tensor) -> torch.Tensor: - """ - Project the Prediction Network (Decoder) output to the joint hidden dimension. - - Args: - prednet_output: A torch.Tensor of shape [B, U, D] - - Returns: - A torch.Tensor of shape [B, U, H] - """ - raise NotImplementedError() - - def joint(self, f: torch.Tensor, g: torch.Tensor) -> torch.Tensor: - """ - Compute the joint step of the network. - - Here, - B = Batch size - T = Acoustic model timesteps - U = Target sequence length - H1, H2 = Hidden dimensions of the Encoder / Decoder respectively - H = Hidden dimension of the Joint hidden step. - V = Vocabulary size of the Decoder (excluding the RNNT blank token). - - NOTE: - The implementation of this model is slightly modified from the original paper. - The original paper proposes the following steps : - (enc, dec) -> Expand + Concat + Sum [B, T, U, H1+H2] -> Forward through joint hidden [B, T, U, H] -- *1 - *1 -> Forward through joint final [B, T, U, V + 1]. - - We instead split the joint hidden into joint_hidden_enc and joint_hidden_dec and act as follows: - enc -> Forward through joint_hidden_enc -> Expand [B, T, 1, H] -- *1 - dec -> Forward through joint_hidden_dec -> Expand [B, 1, U, H] -- *2 - (*1, *2) -> Sum [B, T, U, H] -> Forward through joint final [B, T, U, V + 1]. - - Args: - f: Output of the Encoder model. A torch.Tensor of shape [B, T, H1] - g: Output of the Decoder model. A torch.Tensor of shape [B, U, H2] - - Returns: - Logits / log softmaxed tensor of shape (B, T, U, V + 1). - """ - return self.joint_after_projection(self.project_encoder(f), self.project_prednet(g)) - - @property - def num_classes_with_blank(self): - raise NotImplementedError() - - @property - def num_extra_outputs(self): - raise NotImplementedError() - - -class AbstractRNNTDecoder(NeuralModule, ABC): - """ - An abstract RNNT Decoder framework, which can possibly integrate with GreedyRNNTInfer and BeamRNNTInfer classes. - Represents the abstract RNNT Prediction/Decoder stateful network, which performs autoregressive decoding - in order to construct the output sequence. - - Args: - vocab_size: Size of the vocabulary, excluding the RNNT blank token. - blank_idx: Index of the blank token. Can be 0 or size(vocabulary). - blank_as_pad: Bool flag, whether to allocate an additional token in the Embedding layer - of this module in order to treat all RNNT `blank` tokens as pad tokens, thereby letting - the Embedding layer batch tokens more efficiently. - - It is mandatory to use this for certain Beam RNNT Infer methods - such as TSD, ALSD. - It is also more efficient to use greedy batch decoding with this flag. - """ - - def __init__(self, vocab_size, blank_idx, blank_as_pad): - super().__init__() - - self.vocab_size = vocab_size - self.blank_idx = blank_idx # first or last index of vocabulary - self.blank_as_pad = blank_as_pad - - if blank_idx not in [0, vocab_size]: - raise ValueError("`blank_idx` must be either 0 or the final token of the vocabulary") - - @abstractmethod - def predict( - self, - y: Optional[torch.Tensor] = None, - state: Optional[torch.Tensor] = None, - add_sos: bool = False, - batch_size: Optional[int] = None, - ) -> Tuple[torch.Tensor, List[torch.Tensor]]: - """ - Stateful prediction of scores and state for a (possibly null) tokenset. - This method takes various cases into consideration : - - No token, no state - used for priming the RNN - - No token, state provided - used for blank token scoring - - Given token, states - used for scores + new states - - Here: - B - batch size - U - label length - H - Hidden dimension size of RNN - L - Number of RNN layers - - Args: - y: Optional torch tensor of shape [B, U] of dtype long which will be passed to the Embedding. - If None, creates a zero tensor of shape [B, 1, H] which mimics output of pad-token on Embedding. - - state: An optional list of states for the RNN. Eg: For LSTM, it is the state list length is 2. - Each state must be a tensor of shape [L, B, H]. - If None, and during training mode and `random_state_sampling` is set, will sample a - normal distribution tensor of the above shape. Otherwise, None will be passed to the RNN. - - add_sos: bool flag, whether a zero vector describing a "start of signal" token should be - prepended to the above "y" tensor. When set, output size is (B, U + 1, H). - - batch_size: An optional int, specifying the batch size of the `y` tensor. - Can be infered if `y` and `state` is None. But if both are None, then batch_size cannot be None. - - Returns: - A tuple (g, hid) such that - - - If add_sos is False: - g: (B, U, H) - hid: (h, c) where h is the final sequence hidden state and c is the final cell state: - h (tensor), shape (L, B, H) - c (tensor), shape (L, B, H) - - If add_sos is True: - g: (B, U + 1, H) - hid: (h, c) where h is the final sequence hidden state and c is the final cell state: - h (tensor), shape (L, B, H) - c (tensor), shape (L, B, H) - - """ - raise NotImplementedError() - - @abstractmethod - def initialize_state(self, y: torch.Tensor) -> List[torch.Tensor]: - """ - Initialize the state of the RNN layers, with same dtype and device as input `y`. - - Args: - y: A torch.Tensor whose device the generated states will be placed on. - - Returns: - List of torch.Tensor, each of shape [L, B, H], where - L = Number of RNN layers - B = Batch size - H = Hidden size of RNN. - """ - raise NotImplementedError() - - @abstractmethod - def score_hypothesis( - self, hypothesis: Hypothesis, cache: Dict[Tuple[int], Any] - ) -> Tuple[torch.Tensor, List[torch.Tensor], torch.Tensor]: - """ - Similar to the predict() method, instead this method scores a Hypothesis during beam search. - Hypothesis is a dataclass representing one hypothesis in a Beam Search. - - Args: - hypothesis: Refer to rnnt_utils.Hypothesis. - cache: Dict which contains a cache to avoid duplicate computations. - - Returns: - Returns a tuple (y, states, lm_token) such that: - y is a torch.Tensor of shape [1, 1, H] representing the score of the last token in the Hypothesis. - state is a list of RNN states, each of shape [L, 1, H]. - lm_token is the final integer token of the hypothesis. - """ - raise NotImplementedError() - - def batch_score_hypothesis( - self, hypotheses: List[Hypothesis], cache: Dict[Tuple[int], Any] - ) -> Tuple[torch.Tensor, List[torch.Tensor], torch.Tensor]: - """ - Used for batched beam search algorithms. Similar to score_hypothesis method. - - Args: - hypothesis: List of Hypotheses. Refer to rnnt_utils.Hypothesis. - cache: Dict which contains a cache to avoid duplicate computations. - - Returns: - Returns a tuple (batch_dec_out, batch_dec_states) such that: - batch_dec_out: a list of torch.Tensor [1, H] representing the prediction network outputs for the last tokens in the Hypotheses. - batch_dec_states: a list of list of RNN states, each of shape [L, B, H]. Represented as B x List[states]. - """ - raise NotImplementedError() - - def batch_initialize_states(self, decoder_states: List[List[torch.Tensor]]): - """ - Creates a stacked decoder states to be passed to prediction network - - Args: - decoder_states (list of list of list of torch.Tensor): list of decoder states - [B, C, L, H] - - B: Batch size. - - C: e.g., for LSTM, this is 2: hidden and cell states - - L: Number of layers in prediction RNN. - - H: Dimensionality of the hidden state. - - Returns: - batch_states (list of torch.Tensor): batch of decoder states - [C x torch.Tensor[L x B x H] - """ - raise NotImplementedError() - - def batch_select_state(self, batch_states: List[torch.Tensor], idx: int) -> List[List[torch.Tensor]]: - """Get decoder state from batch of states, for given id. - - Args: - batch_states (list): batch of decoder states - ([L x (B, H)], [L x (B, H)]) - - idx (int): index to extract state from batch of states - - Returns: - (tuple): decoder states for given id - ([L x (1, H)], [L x (1, H)]) - """ - raise NotImplementedError() - - @classmethod - def batch_aggregate_states_beam( - cls, - src_states: tuple[torch.Tensor, torch.Tensor] | list[torch.Tensor], - batch_size: int, - beam_size: int, - indices: torch.Tensor, - dst_states: Optional[tuple[torch.Tensor, torch.Tensor] | list[torch.Tensor]] = None, - ) -> tuple[torch.Tensor, torch.Tensor] | list[torch.Tensor]: - """ - Aggregates decoder states based on the given indices. - Args: - src_states (tuple[torch.Tensor, torch.Tensor] | list[torch.Tensor]): source states of - shape `([L x (batch_size * beam_size, H)], [L x (batch_size * beam_size, H)])` - batch_size (int): The size of the batch. - beam_size (int): The size of the beam. - indices (torch.Tensor): A tensor of shape `(batch_size, beam_size)` containing - the indices in beam that map the source states to the destination states. - dst_states (tuple[torch.Tensor, torch.Tensor] | list[torch.Tensor], optional): If provided, the method - updates these tensors in-place. - Returns: - tuple[torch.Tensor, torch.Tensor] | list[torch.Tensor]: aggregated states - """ - - raise NotImplementedError() - - @classmethod - def batch_replace_states_mask( - cls, - src_states: tuple[torch.Tensor, torch.Tensor] | list[torch.Tensor], - dst_states: tuple[torch.Tensor, torch.Tensor] | list[torch.Tensor], - mask: torch.Tensor, - other_src_states: Optional[tuple[torch.Tensor, torch.Tensor] | list[torch.Tensor]] = None, - ): - """ - Replaces states in `dst_states` with states from `src_states` based on the given `mask`. - - Args: - mask (torch.Tensor): When True, selects values from `src_states`, otherwise `out` or `other_src_states`(if provided). - src_states (tuple[torch.Tensor, torch.Tensor] | list[torch.Tensor]): Values selected at indices where `mask` is True. - dst_states (tuple[torch.Tensor, torch.Tensor] | list[torch.Tensor], optional): The output states. - other_src_states (tuple[torch.Tensor, torch.Tensor] | list[torch.Tensor], optional): Values selected at indices where `mask` is False. - - Note: - This operation is performed without CPU-GPU synchronization by using `torch.where`. - """ - raise NotImplementedError() - - @classmethod - def batch_replace_states_all( - cls, - src_states: list[torch.Tensor], - dst_states: list[torch.Tensor], - batch_size: int | None = None, - ): - """Replace states in dst_states with states from src_states""" - raise NotImplementedError() - - @classmethod - def clone_state( - cls, states: tuple[torch.Tensor, torch.Tensor] | list[torch.Tensor] - ) -> tuple[torch.Tensor, torch.Tensor] | list[torch.Tensor]: - """Return copy of the states""" - raise NotImplementedError() - - @classmethod - def batch_split_states(cls, batch_states: list[torch.Tensor]) -> list[list[torch.Tensor]]: - """ - Split states into a list of states. - Useful for splitting the final state for converting results of the decoding algorithm to Hypothesis class. - """ - raise NotImplementedError() - - @classmethod - def batch_unsplit_states( - cls, batch_states: list[tuple[torch.Tensor, torch.Tensor] | list[torch.Tensor]], device=None, dtype=None - ) -> tuple[torch.Tensor, torch.Tensor] | list[torch.Tensor]: - """ - Concatenate a batch of decoder state to a packed state. Inverse of `batch_split_states`. - """ - raise NotImplementedError() - - def batch_concat_states(self, batch_states: List[List[torch.Tensor]]) -> List[torch.Tensor]: - """Concatenate a batch of decoder state to a packed state. - - Args: - batch_states (list): batch of decoder states - B x ([L x (H)], [L x (H)]) - - Returns: - (tuple): decoder states - (L x B x H, L x B x H) - """ - raise NotImplementedError() - - def batch_copy_states( - self, - old_states: List[torch.Tensor], - new_states: List[torch.Tensor], - ids: List[int], - value: Optional[float] = None, - ) -> List[torch.Tensor]: - """Copy states from new state to old state at certain indices. - - Args: - old_states(list): packed decoder states - (L x B x H, L x B x H) - - new_states: packed decoder states - (L x B x H, L x B x H) - - ids (list): List of indices to copy states at. - - value (optional float): If a value should be copied instead of a state slice, a float should be provided - - Returns: - batch of decoder states with partial copy at ids (or a specific value). - (L x B x H, L x B x H) - """ - raise NotImplementedError() - - def mask_select_states(self, states: Any, mask: torch.Tensor) -> Any: - """ - Return states by mask selection - Args: - states: states for the batch (preferably a list of tensors, but not limited to) - mask: boolean mask for selecting states; batch dimension should be the same as for states - - Returns: - states filtered by mask (same type as `states`) - """ - raise NotImplementedError() diff --git a/nemo/collections/asr/modules/sortformer_modules.py b/nemo/collections/asr/modules/sortformer_modules.py deleted file mode 100644 index 4b06c0e2978d28d3003fc75e74708754ab207644..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/sortformer_modules.py +++ /dev/null @@ -1,896 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import math -from dataclasses import dataclass -from typing import List, Tuple - -import torch -import torch.nn as nn -import torch.nn.functional as F - -from nemo.core.classes.exportable import Exportable -from nemo.core.classes.module import NeuralModule -from nemo.utils import logging - -__all__ = ['SortformerModules'] - - -@dataclass -class StreamingSortformerState: - """ - This class creates a class instance that will be used to store the state of the - streaming Sortformer model. - - Attributes: - spkcache (torch.Tensor): Speaker cache to store embeddings from start - spkcache_lengths (torch.Tensor): Lengths of the speaker cache - spkcache_preds (torch.Tensor): The speaker predictions for the speaker cache parts - fifo (torch.Tensor): FIFO queue to save the embedding from the latest chunks - fifo_lengths (torch.Tensor): Lengths of the FIFO queue - fifo_preds (torch.Tensor): The speaker predictions for the FIFO queue parts - spk_perm (torch.Tensor): Speaker permutation information for the speaker cache - mean_sil_emb (torch.Tensor): Mean silence embedding - n_sil_frames (torch.Tensor): Number of silence frames - """ - - spkcache = None # Speaker cache to store embeddings from start - spkcache_lengths = None # - spkcache_preds = None # speaker cache predictions - fifo = None # to save the embedding from the latest chunks - fifo_lengths = None - fifo_preds = None - spk_perm = None - mean_sil_emb = None - n_sil_frames = None - - def to(self, device): - if self.spkcache is not None: - self.spkcache = self.spkcache.to(device) - if self.spkcache_lengths is not None: - self.spkcache_lengths = self.spkcache_lengths.to(device) - if self.spkcache_preds is not None: - self.spkcache_preds = self.spkcache_preds.to(device) - if self.fifo is not None: - self.fifo = self.fifo.to(device) - if self.fifo_lengths is not None: - self.fifo_lengths = self.fifo_lengths.to(device) - if self.fifo_preds is not None: - self.fifo_preds = self.fifo_preds.to(device) - if self.spk_perm is not None: - self.spk_perm = self.spk_perm.to(device) - if self.mean_sil_emb is not None: - self.mean_sil_emb = self.mean_sil_emb.to(device) - if self.n_sil_frames is not None: - self.n_sil_frames = self.n_sil_frames.to(device) - - -class SortformerModules(NeuralModule, Exportable): - """ - A class including auxiliary functions for Sortformer models. - This class contains and will contain the following functions that performs streaming features, - and any neural layers that are not included in the NeMo neural modules - (e.g. Transformer, Fast-Conformer). - """ - - def init_weights(self, m): - """Init weights for linear layers.""" - if isinstance(m, nn.Linear): - torch.nn.init.xavier_uniform_(m.weight) - m.bias.data.fill_(0.01) - - def __init__( - self, - num_spks: int = 4, - dropout_rate: float = 0.5, - fc_d_model: int = 512, - tf_d_model: int = 192, - subsampling_factor: int = 8, - spkcache_len: int = 188, - fifo_len: int = 0, - chunk_len: int = 188, - spkcache_update_period: int = 188, - chunk_left_context: int = 1, - chunk_right_context: int = 1, - spkcache_sil_frames_per_spk: int = 3, - causal_attn_rate: float = 0, - causal_attn_rc: int = 7, - scores_add_rnd: float = 0, - pred_score_threshold: float = 0.25, - max_index: int = 99999, - scores_boost_latest: float = 0.05, - sil_threshold: float = 0.2, - strong_boost_rate: float = 0.75, - weak_boost_rate: float = 1.5, - min_pos_scores_rate: float = 0.5, - ): - super().__init__() - # General params - self.subsampling_factor = subsampling_factor - self.fc_d_model = fc_d_model - self.tf_d_model = tf_d_model - self.hidden_size = tf_d_model - self.n_spk: int = num_spks - self.hidden_to_spks = nn.Linear(2 * self.hidden_size, self.n_spk) - self.first_hidden_to_hidden = nn.Linear(self.hidden_size, self.hidden_size) - self.single_hidden_to_spks = nn.Linear(self.hidden_size, self.n_spk) - self.dropout = nn.Dropout(dropout_rate) - self.encoder_proj = nn.Linear(self.fc_d_model, self.tf_d_model) - self.log = False - - # Streaming-related params - self.spkcache_len = spkcache_len - self.fifo_len = fifo_len - self.chunk_len = chunk_len - self.chunk_left_context = chunk_left_context - self.chunk_right_context = chunk_right_context - self.spkcache_sil_frames_per_spk = spkcache_sil_frames_per_spk - self.spkcache_update_period = spkcache_update_period - self.causal_attn_rate = causal_attn_rate - self.causal_attn_rc = causal_attn_rc - self.scores_add_rnd = scores_add_rnd - self.max_index = max_index - self.pred_score_threshold = pred_score_threshold - self.scores_boost_latest = scores_boost_latest - self.sil_threshold = sil_threshold - self.strong_boost_rate = strong_boost_rate - self.weak_boost_rate = weak_boost_rate - self.min_pos_scores_rate = min_pos_scores_rate - - def _check_streaming_parameters(self): - """ - Check if there are any illegal parameter combinations. - - Restrictions: - - All streaming parameters should be non-negative integers. - - Chunk length and speaker cache update period should be greater than 0. - - Speaker cache length should be greater than or equal to `(1 + spkcache_sil_frames_per_spk ) * n_spk`. - - The effective range of self.spkcache_update_period is: chunk_len <= spkcache_update_period <= fifo_len + chunk_len - """ - param_constraints = { - 'spkcache_len': (1 + self.spkcache_sil_frames_per_spk) * self.n_spk, - 'fifo_len': 0, - 'chunk_len': 1, - 'spkcache_update_period': 1, - 'chunk_left_context': 0, - 'chunk_right_context': 0, - 'spkcache_sil_frames_per_spk': 0, - } - - for param, min_val in param_constraints.items(): - val = getattr(self, param) - if not isinstance(val, int): - raise TypeError(f"Parameter '{param}' must be an integer, but got {param}: {val}") - if val < min_val: - raise ValueError(f"Parameter '{param}' must be at least {min_val}, but got {val}.") - - if self.spkcache_update_period < self.chunk_len: - logging.warning( - f"spkcache_update_period ({self.spkcache_update_period}) is less than chunk_len ({self.chunk_len}). " - f"The effective update period will be {self.chunk_len}." - ) - if self.spkcache_update_period > self.fifo_len + self.chunk_len: - logging.warning( - f"spkcache_update_period ({self.spkcache_update_period}) is greater than " - f"fifo_len + chunk_len ({self.fifo_len + self.chunk_len}). " - f"The effective update period will be {self.fifo_len + self.chunk_len}." - ) - - @staticmethod - def length_to_mask(lengths, max_length: int): - """ - Convert length values to encoder mask input tensor - - Args: - lengths (torch.Tensor): Tensor containing lengths of sequences - max_length (int): maximum sequence length - - Returns: - mask (torch.Tensor): Tensor of shape (batch_size, max_len) containing 0's - in the padded region and 1's elsewhere - """ - batch_size = lengths.shape[0] - arange = torch.arange(max_length, device=lengths.device) - mask = arange.expand(batch_size, max_length) < lengths.unsqueeze(1) - return mask - - def streaming_feat_loader( - self, feat_seq, feat_seq_length, feat_seq_offset - ) -> Tuple[int, torch.Tensor, torch.Tensor, int, int]: - """ - Load a chunk of feature sequence for streaming inference. - - Args: - feat_seq (torch.Tensor): Tensor containing feature sequence - Shape: (batch_size, feat_dim, feat frame count) - feat_seq_length (torch.Tensor): Tensor containing feature sequence lengths - Shape: (batch_size,) - feat_seq_offset (torch.Tensor): Tensor containing feature sequence offsets - Shape: (batch_size,) - - Returns: - chunk_idx (int): Index of the current chunk - chunk_feat_seq (torch.Tensor): Tensor containing the chunk of feature sequence - Shape: (batch_size, diar frame count, feat_dim) - feat_lengths (torch.Tensor): Tensor containing lengths of the chunk of feature sequence - Shape: (batch_size,) - """ - feat_len = feat_seq.shape[2] - num_chunks = math.ceil(feat_len / (self.chunk_len * self.subsampling_factor)) - if self.log: - logging.info( - f"feat_len={feat_len}, num_chunks={num_chunks}, " - f"feat_seq_length={feat_seq_length}, feat_seq_offset={feat_seq_offset}" - ) - - stt_feat, end_feat, chunk_idx = 0, 0, 0 - while end_feat < feat_len: - left_offset = min(self.chunk_left_context * self.subsampling_factor, stt_feat) - end_feat = min(stt_feat + self.chunk_len * self.subsampling_factor, feat_len) - right_offset = min(self.chunk_right_context * self.subsampling_factor, feat_len - end_feat) - chunk_feat_seq = feat_seq[:, :, stt_feat - left_offset : end_feat + right_offset] - feat_lengths = (feat_seq_length + feat_seq_offset - stt_feat + left_offset).clamp( - 0, chunk_feat_seq.shape[2] - ) - feat_lengths = feat_lengths * (feat_seq_offset < end_feat) - stt_feat = end_feat - chunk_feat_seq_t = torch.transpose(chunk_feat_seq, 1, 2) - if self.log: - logging.info( - f"chunk_idx: {chunk_idx}, " - f"chunk_feat_seq_t shape: {chunk_feat_seq_t.shape}, " - f"chunk_feat_lengths: {feat_lengths}" - ) - yield chunk_idx, chunk_feat_seq_t, feat_lengths, left_offset, right_offset - chunk_idx += 1 - - def forward_speaker_sigmoids(self, hidden_out): - """ - The final layer that outputs speaker probabilities using the Sigmoid activation function. - - Args: - hidden_out (torch.Tensor): Tensor containing hidden states from the encoder - Shape: (batch_size, n_frames, hidden_dim) - - Returns: - preds (torch.Tensor): Tensor containing speaker probabilities computed using - the Sigmoid activation function - Shape: (batch_size, n_frames, n_spk) - """ - hidden_out = self.dropout(F.relu(hidden_out)) - hidden_out = self.first_hidden_to_hidden(hidden_out) - hidden_out = self.dropout(F.relu(hidden_out)) - spk_preds = self.single_hidden_to_spks(hidden_out) - preds = F.sigmoid(spk_preds) - return preds - - @staticmethod - def concat_embs( - list_of_tensors=List[torch.Tensor], - return_lengths: bool = False, - dim: int = 1, - device: torch.device = None, - ): - """ - Concatenate a list of tensors along the specified dimension. - - Args: - list_of_tensors (List[torch.Tensor]): List of tensors to concatenate - return_lengths (bool): Whether to return lengths of the concatenated tensors - dim (int): Concatenation axis - device (torch.device): device to use for tensor operations - - Returns: - embs (torch.Tensor): concatenated tensor - """ - embs = torch.cat(list_of_tensors, dim=dim).to(device) - lengths = torch.tensor(embs.shape[1]).repeat(embs.shape[0]).to(device) - if return_lengths: - return embs, lengths - else: - return embs - - @staticmethod - def concat_and_pad(embs: List[torch.Tensor], lengths: List[torch.Tensor]): - """ - Concatenates lengths[i] first embeddings of embs[i], and pads the rest elements with zeros. - - Args: - embs: List of embeddings Tensors of (batch_size, n_frames, emb_dim) shape - lengths: List of lengths Tensors of (batch_size,) shape - - Returns: - output: concatenated embeddings Tensor of (batch_size, n_frames, emb_dim) shape - total_lengths: output lengths Tensor of (batch_size,) shape - """ - # Error handling for mismatched list lengths - if len(embs) != len(lengths): - raise ValueError( - f"Length lists must have the same length, but got len(embs) - {len(embs)} " - f"and len(lengths) - {len(lengths)}." - ) - # Handle empty lists - if len(embs) == 0 or len(lengths) == 0: - raise ValueError( - f"Cannot concatenate empty lists of embeddings or lengths: embs - {len(embs)}, lengths - {len(lengths)}" - ) - - device, dtype = embs[0].device, embs[0].dtype - batch_size, emb_dim = embs[0].shape[0], embs[0].shape[2] - - total_lengths = torch.sum(torch.stack(lengths), dim=0) - sig_length = total_lengths.max().item() - - output = torch.zeros(batch_size, sig_length, emb_dim, device=device, dtype=dtype) - start_indices = torch.zeros(batch_size, dtype=torch.int64, device=device) - - for emb, length in zip(embs, lengths): - end_indices = start_indices + length - for batch_idx in range(batch_size): - output[batch_idx, start_indices[batch_idx] : end_indices[batch_idx]] = emb[ - batch_idx, : length[batch_idx] - ] - start_indices = end_indices - - return output, total_lengths - - def init_streaming_state(self, batch_size: int = 1, async_streaming: bool = False, device: torch.device = None): - """ - Initializes StreamingSortformerState with empty tensors or zero-valued tensors. - - Args: - batch_size (int): Batch size for tensors in streaming state - async_streaming (bool): True for asynchronous update, False for synchronous update - device (torch.device): Device for tensors in streaming state - - Returns: - streaming_state (SortformerStreamingState): initialized streaming state - """ - streaming_state = StreamingSortformerState() - if async_streaming: - streaming_state.spkcache = torch.zeros((batch_size, self.spkcache_len, self.fc_d_model), device=device) - streaming_state.spkcache_preds = torch.zeros((batch_size, self.spkcache_len, self.n_spk), device=device) - streaming_state.spkcache_lengths = torch.zeros((batch_size,), dtype=torch.long, device=device) - streaming_state.fifo = torch.zeros((batch_size, self.fifo_len, self.fc_d_model), device=device) - streaming_state.fifo_lengths = torch.zeros((batch_size,), dtype=torch.long, device=device) - else: - streaming_state.spkcache = torch.zeros((batch_size, 0, self.fc_d_model), device=device) - streaming_state.fifo = torch.zeros((batch_size, 0, self.fc_d_model), device=device) - streaming_state.mean_sil_emb = torch.zeros((batch_size, self.fc_d_model), device=device) - streaming_state.n_sil_frames = torch.zeros((batch_size,), dtype=torch.long, device=device) - return streaming_state - - @staticmethod - def apply_mask_to_preds(spkcache_fifo_chunk_preds, spkcache_fifo_chunk_fc_encoder_lengths): - """ - Applies mask to speaker cache and FIFO queue to ensure that only valid frames are - considered for predictions from the model. - - Args: - spkcache_fifo_chunk_preds (torch.Tensor): Speaker predictions of the chunk - spkcache_fifo_chunk_fc_encoder_lengths (torch.Tensor): Lengths of current chunk in - the Fast-Conformer encoder - - Returns: - spkcache_fifo_chunk_preds (torch.Tensor): Speaker predictions of the chunk with valid frames only - """ - batch_size, n_frames, n_spk = spkcache_fifo_chunk_preds.shape - preds_mask = torch.arange(n_frames, device=spkcache_fifo_chunk_preds.device).view(1, -1, 1) - preds_mask = preds_mask.expand(batch_size, -1, n_spk) < spkcache_fifo_chunk_fc_encoder_lengths.view(-1, 1, 1) - preds_mask = preds_mask.expand(-1, n_frames, n_spk) - spkcache_fifo_chunk_preds = torch.where(preds_mask, spkcache_fifo_chunk_preds, torch.tensor(0.0)) - return spkcache_fifo_chunk_preds - - def streaming_update_async(self, streaming_state, chunk, chunk_lengths, preds, lc: int = 0, rc: int = 0): - """ - Update the speaker cache and FIFO queue with the chunk of embeddings and speaker predictions. - Asynchronous version, which means speaker cache, FIFO and chunk may have different lengths within a batch. - Should be used for real streaming applications. - - Args: - streaming_state (SortformerStreamingState): Previous streaming state including speaker cache and FIFO - chunk (torch.Tensor): chunk of embeddings to be predicted - Shape: (batch_size, lc+chunk_len+rc, emb_dim) - chunk_lengths (torch.Tensor): Lengths of current chunk - Shape: (batch_size,) - preds (torch.Tensor): Speaker predictions of the [spkcache + fifo + chunk] embeddings - Shape: (batch_size, spkcache_len + fifo_len + lc+chunk_len+rc, num_spks) - lc and rc (int): The left & right offset of the chunk, - only the chunk[:, lc:chunk_len+lc] is used for update of speaker cache and FIFO queue - - Returns: - streaming_state (SortformerStreamingState): Current streaming state including speaker cache and FIFO - chunk_preds (torch.Tensor): Speaker predictions of the chunk embeddings - Shape: (batch_size, chunk_len, num_spks) - """ - batch_size, _, emb_dim = chunk.shape - n_spk = preds.shape[2] - - max_spkcache_len, max_fifo_len, max_chunk_len = ( - streaming_state.spkcache.shape[1], - streaming_state.fifo.shape[1], - chunk.shape[1] - lc - rc, - ) - - max_pop_out_len = max(self.spkcache_update_period, max_chunk_len) - max_pop_out_len = min(max_pop_out_len, max_chunk_len + max_fifo_len) - - streaming_state.fifo_preds = torch.zeros((batch_size, max_fifo_len, n_spk), device=preds.device) - chunk_preds = torch.zeros((batch_size, max_chunk_len, n_spk), device=preds.device) - chunk_lengths = (chunk_lengths - lc).clamp(min=0, max=max_chunk_len) - updated_fifo = torch.zeros((batch_size, max_fifo_len + max_chunk_len, emb_dim), device=preds.device) - updated_fifo_preds = torch.zeros((batch_size, max_fifo_len + max_chunk_len, n_spk), device=preds.device) - updated_spkcache = torch.zeros((batch_size, max_spkcache_len + max_pop_out_len, emb_dim), device=preds.device) - updated_spkcache_preds = torch.full( - (batch_size, max_spkcache_len + max_pop_out_len, n_spk), 0.0, device=preds.device - ) - - for batch_index in range(batch_size): - spkcache_len = streaming_state.spkcache_lengths[batch_index].item() - fifo_len = streaming_state.fifo_lengths[batch_index].item() - chunk_len = chunk_lengths[batch_index].item() - streaming_state.fifo_preds[batch_index, :fifo_len, :] = preds[ - batch_index, spkcache_len : spkcache_len + fifo_len, : - ] - chunk_preds[batch_index, :chunk_len, :] = preds[ - batch_index, spkcache_len + fifo_len + lc : spkcache_len + fifo_len + lc + chunk_len - ] - updated_spkcache[batch_index, :spkcache_len, :] = streaming_state.spkcache[batch_index, :spkcache_len, :] - updated_spkcache_preds[batch_index, :spkcache_len, :] = streaming_state.spkcache_preds[ - batch_index, :spkcache_len, : - ] - updated_fifo[batch_index, :fifo_len, :] = streaming_state.fifo[batch_index, :fifo_len, :] - updated_fifo_preds[batch_index, :fifo_len, :] = streaming_state.fifo_preds[batch_index, :fifo_len, :] - - # append chunk to fifo - streaming_state.fifo_lengths[batch_index] += chunk_len - updated_fifo[batch_index, fifo_len : fifo_len + chunk_len, :] = chunk[batch_index, lc : lc + chunk_len, :] - updated_fifo_preds[batch_index, fifo_len : fifo_len + chunk_len, :] = chunk_preds[ - batch_index, :chunk_len, : - ] - if fifo_len + chunk_len > max_fifo_len: - # move pop_out_len first frames of FIFO queue to speaker cache - pop_out_len = self.spkcache_update_period - pop_out_len = max(pop_out_len, max_chunk_len - max_fifo_len + fifo_len) - pop_out_len = min(pop_out_len, fifo_len + chunk_len) - streaming_state.spkcache_lengths[batch_index] += pop_out_len - pop_out_embs = updated_fifo[batch_index, :pop_out_len, :] - pop_out_preds = updated_fifo_preds[batch_index, :pop_out_len, :] - ( - streaming_state.mean_sil_emb[batch_index : batch_index + 1], - streaming_state.n_sil_frames[batch_index : batch_index + 1], - ) = self._get_silence_profile( - streaming_state.mean_sil_emb[batch_index : batch_index + 1], - streaming_state.n_sil_frames[batch_index : batch_index + 1], - pop_out_embs.unsqueeze(0), - pop_out_preds.unsqueeze(0), - ) - updated_spkcache[batch_index, spkcache_len : spkcache_len + pop_out_len, :] = pop_out_embs - if updated_spkcache_preds[batch_index, 0, 0] >= 0: - # speaker cache already compressed at least once - updated_spkcache_preds[batch_index, spkcache_len : spkcache_len + pop_out_len, :] = pop_out_preds - elif spkcache_len + pop_out_len > self.spkcache_len: - # will compress speaker cache for the first time - updated_spkcache_preds[batch_index, :spkcache_len, :] = preds[batch_index, :spkcache_len, :] - updated_spkcache_preds[batch_index, spkcache_len : spkcache_len + pop_out_len, :] = pop_out_preds - streaming_state.fifo_lengths[batch_index] -= pop_out_len - new_fifo_len = streaming_state.fifo_lengths[batch_index].item() - updated_fifo[batch_index, :new_fifo_len, :] = updated_fifo[ - batch_index, pop_out_len : pop_out_len + new_fifo_len, : - ].clone() - updated_fifo_preds[batch_index, :new_fifo_len, :] = updated_fifo_preds[ - batch_index, pop_out_len : pop_out_len + new_fifo_len, : - ].clone() - updated_fifo[batch_index, new_fifo_len:, :] = 0 - updated_fifo_preds[batch_index, new_fifo_len:, :] = 0 - - streaming_state.fifo = updated_fifo[:, :max_fifo_len, :] - streaming_state.fifo_preds = updated_fifo_preds[:, :max_fifo_len, :] - - # update speaker cache - need_compress = streaming_state.spkcache_lengths > self.spkcache_len - streaming_state.spkcache = updated_spkcache[:, : self.spkcache_len, :] - streaming_state.spkcache_preds = updated_spkcache_preds[:, : self.spkcache_len, :] - - idx = torch.where(need_compress)[0] - if len(idx) > 0: - streaming_state.spkcache[idx], streaming_state.spkcache_preds[idx], _ = self._compress_spkcache( - emb_seq=updated_spkcache[idx], - preds=updated_spkcache_preds[idx], - mean_sil_emb=streaming_state.mean_sil_emb[idx], - permute_spk=False, - ) - streaming_state.spkcache_lengths[idx] = streaming_state.spkcache_lengths[idx].clamp(max=self.spkcache_len) - - if self.log: - logging.info( - f"spkcache: {streaming_state.spkcache.shape}, spkcache_lengths: {streaming_state.spkcache_lengths}, " - f"fifo: {streaming_state.fifo.shape}, fifo_lengths: {streaming_state.fifo_lengths}, " - f"chunk: {chunk.shape}, chunk_lengths: {chunk_lengths}, " - f"chunk_preds: {chunk_preds.shape}" - ) - - return streaming_state, chunk_preds - - def streaming_update(self, streaming_state, chunk, preds, lc: int = 0, rc: int = 0): - """ - Update the speaker cache and FIFO queue with the chunk of embeddings and speaker predictions. - Synchronous version, which means speaker cahce, FIFO queue and chunk have same lengths within a batch. - Should be used for training and evaluation, not for real streaming applications. - - Args: - streaming_state (SortformerStreamingState): previous streaming state including speaker cache and FIFO - chunk (torch.Tensor): chunk of embeddings to be predicted - Shape: (batch_size, lc+chunk_len+rc, emb_dim) - preds (torch.Tensor): speaker predictions of the [spkcache + fifo + chunk] embeddings - Shape: (batch_size, spkcache_len + fifo_len + lc+chunk_len+rc, num_spks) - lc and rc (int): left & right offset of the chunk, - only the chunk[:, lc:chunk_len+lc] is used for update of speaker cache and FIFO queue - - Returns: - streaming_state (SortformerStreamingState): current streaming state including speaker cache and FIFO - chunk_preds (torch.Tensor): speaker predictions of the chunk embeddings - Shape: (batch_size, chunk_len, num_spks) - """ - - batch_size, _, emb_dim = chunk.shape - - spkcache_len, fifo_len, chunk_len = ( - streaming_state.spkcache.shape[1], - streaming_state.fifo.shape[1], - chunk.shape[1] - lc - rc, - ) - if streaming_state.spk_perm is not None: - inv_spk_perm = torch.stack( - [torch.argsort(streaming_state.spk_perm[batch_index]) for batch_index in range(batch_size)] - ) - preds = torch.stack( - [preds[batch_index, :, inv_spk_perm[batch_index]] for batch_index in range(batch_size)] - ) - - streaming_state.fifo_preds = preds[:, spkcache_len : spkcache_len + fifo_len] - chunk = chunk[:, lc : chunk_len + lc] - chunk_preds = preds[:, spkcache_len + fifo_len + lc : spkcache_len + fifo_len + chunk_len + lc] - - # append chunk to fifo - streaming_state.fifo = torch.cat([streaming_state.fifo, chunk], dim=1) - streaming_state.fifo_preds = torch.cat([streaming_state.fifo_preds, chunk_preds], dim=1) - - if fifo_len + chunk_len > self.fifo_len: - # extract pop_out_len first frames from FIFO queue - pop_out_len = self.spkcache_update_period - pop_out_len = max(pop_out_len, chunk_len - self.fifo_len + fifo_len) - pop_out_len = min(pop_out_len, fifo_len + chunk_len) - - pop_out_embs = streaming_state.fifo[:, :pop_out_len] - pop_out_preds = streaming_state.fifo_preds[:, :pop_out_len] - streaming_state.mean_sil_emb, streaming_state.n_sil_frames = self._get_silence_profile( - streaming_state.mean_sil_emb, - streaming_state.n_sil_frames, - pop_out_embs, - pop_out_preds, - ) - streaming_state.fifo = streaming_state.fifo[:, pop_out_len:] - streaming_state.fifo_preds = streaming_state.fifo_preds[:, pop_out_len:] - - # append pop_out_embs to spkcache - streaming_state.spkcache = torch.cat([streaming_state.spkcache, pop_out_embs], dim=1) - if streaming_state.spkcache_preds is not None: # if speaker cache has been already updated at least once - streaming_state.spkcache_preds = torch.cat([streaming_state.spkcache_preds, pop_out_preds], dim=1) - if streaming_state.spkcache.shape[1] > self.spkcache_len: - if streaming_state.spkcache_preds is None: # if this is a first update of speaker cache - streaming_state.spkcache_preds = torch.cat([preds[:, :spkcache_len], pop_out_preds], dim=1) - streaming_state.spkcache, streaming_state.spkcache_preds, streaming_state.spk_perm = ( - self._compress_spkcache( - emb_seq=streaming_state.spkcache, - preds=streaming_state.spkcache_preds, - mean_sil_emb=streaming_state.mean_sil_emb, - permute_spk=self.training, - ) - ) - - if self.log: - logging.info( - f"spkcache: {streaming_state.spkcache.shape}, fifo: {streaming_state.fifo.shape}, " - f"chunk: {chunk.shape}, chunk_preds: {chunk_preds.shape}" - ) - - return streaming_state, chunk_preds - - def _boost_topk_scores( - self, scores, n_boost_per_spk: int, scale_factor: float = 1.0, offset: float = 0.5 - ) -> torch.Tensor: - """ - Increase `n_boost_per_spk` highest scores for each speaker. - - Args: - scores (torch.Tensor): Tensor containing scores for each frame and speaker - Shape: (batch_size, n_frames, n_spk) - n_boost_per_spk (int): Number of frames to boost per speaker - scale_factor (float): Scaling factor for boosting scores. Defaults to 1.0. - offset (float): Offset for score adjustment. Defaults to 0.5. - - Returns: - scores (torch.Tensor): Tensor containing scores for each frame and speaker after boosting. - Shape: (batch_size, n_frames, n_spk) - """ - batch_size, _, n_spk = scores.shape - _, topk_indices = torch.topk(scores, n_boost_per_spk, dim=1, largest=True, sorted=False) - batch_indices = torch.arange(batch_size).unsqueeze(1).unsqueeze(2) # Shape: (batch_size, 1, 1) - speaker_indices = torch.arange(n_spk).unsqueeze(0).unsqueeze(0) # Shape: (1, 1, n_spk) - # Boost scores corresponding to topk_indices; but scores for disabled frames will remain '-inf' - scores[batch_indices, topk_indices, speaker_indices] -= scale_factor * math.log(offset) - return scores - - def _get_silence_profile(self, mean_sil_emb, n_sil_frames, emb_seq, preds): - """ - Get updated mean silence embedding and number of silence frames from emb_seq sequence. - Embeddings are considered as silence if sum of corresponding preds is lower than self.sil_threshold. - - Args: - mean_sil_emb (torch.Tensor): Previous mean silence embedding tensor - Shape: (batch_size, emb_dim) - n_sil_frames (torch.Tensor): Previous number of silence frames - Shape: (batch_size) - emb_seq (torch.Tensor): Tensor containing sequence of embeddings - Shape: (batch_size, n_frames, emb_dim) - preds (torch.Tensor): Tensor containing speaker activity probabilities - Shape: (batch_size, n_frames, n_spk) - - Returns: - mean_sil_emb (torch.Tensor): Updated mean silence embedding tensor - Shape: (batch_size, emb_dim) - n_sil_frames (torch.Tensor): Updated number of silence frames - Shape: (batch_size) - """ - is_sil = preds.sum(dim=2) < self.sil_threshold - sil_count = is_sil.sum(dim=1) - has_new_sil = sil_count > 0 - if not has_new_sil.any(): - return mean_sil_emb, n_sil_frames - sil_emb_sum = torch.sum(emb_seq * is_sil.unsqueeze(-1), dim=1) - upd_n_sil_frames = n_sil_frames + sil_count - old_sil_emb_sum = mean_sil_emb * n_sil_frames.unsqueeze(1) - total_sil_sum = old_sil_emb_sum + sil_emb_sum - upd_mean_sil_emb = total_sil_sum / torch.clamp(upd_n_sil_frames.unsqueeze(1), min=1) - return upd_mean_sil_emb, upd_n_sil_frames - - def _get_log_pred_scores(self, preds): - """ - Get per-frame scores for speakers based on their activity probabilities. - Scores are log-based and designed to be high for confident prediction of non-overlapped speech. - - Args: - preds (torch.Tensor): Tensor containing speaker activity probabilities - Shape: (batch_size, n_frames, n_spk) - - Returns: - scores (torch.Tensor): Tensor containing speaker scores - Shape: (batch_size, n_frames, n_spk) - """ - log_probs = torch.log(torch.clamp(preds, min=self.pred_score_threshold)) - log_1_probs = torch.log(torch.clamp(1.0 - preds, min=self.pred_score_threshold)) - log_1_probs_sum = log_1_probs.sum(dim=2).unsqueeze(-1).expand(-1, -1, self.n_spk) - scores = log_probs - log_1_probs + log_1_probs_sum - math.log(0.5) - return scores - - def _get_topk_indices(self, scores): - """ - Get indices corresponding to spkcache_len highest scores, and binary mask for frames in topk to be disabled. - Disabled frames correspond to either '-inf' score or spkcache_sil_frames_per_spk frames of extra silence - Mean silence embedding will be used for these frames. - - Args: - scores (torch.Tensor): Tensor containing speaker scores, including for extra silence frames - Shape: (batch_size, n_frames, n_spk) - - Returns: - topk_indices_sorted (torch.Tensor): Tensor containing frame indices of spkcache_len highest scores - Shape: (batch_size, spkcache_len) - is_disabled (torch.Tensor): Tensor containing binary mask for frames in topk to be disabled - Shape: (batch_size, spkcache_len) - """ - batch_size, n_frames, _ = scores.shape - n_frames_no_sil = n_frames - self.spkcache_sil_frames_per_spk - # Concatenate scores for all speakers and get spkcache_len frames with highest scores. - # Replace topk_indices corresponding to '-inf' score with a placeholder index self.max_index. - scores_flatten = scores.permute(0, 2, 1).reshape(batch_size, -1) - topk_values, topk_indices = torch.topk(scores_flatten, self.spkcache_len, dim=1, sorted=False) - valid_topk_mask = topk_values != float('-inf') - topk_indices = torch.where(valid_topk_mask, topk_indices, torch.tensor(self.max_index)) - # Sort topk_indices to preserve the original order of the frames. - # Get correct indices corresponding to the original frames - topk_indices_sorted, _ = torch.sort(topk_indices, dim=1) # Shape: (batch_size, spkcache_len) - is_disabled = topk_indices_sorted == self.max_index - topk_indices_sorted = torch.remainder(topk_indices_sorted, n_frames) - is_disabled += topk_indices_sorted >= n_frames_no_sil - topk_indices_sorted[is_disabled] = 0 # Set a placeholder index to make gather work - return topk_indices_sorted, is_disabled - - def _gather_spkcache_and_preds(self, emb_seq, preds, topk_indices, is_disabled, mean_sil_emb): - """ - Gather embeddings from emb_seq and speaker activities from preds corresponding to topk_indices. - For disabled frames, use mean silence embedding and zero probability instead. - - Args: - emb_seq (torch.Tensor): Tensor containing sequence of embeddings. - Shape: (batch_size, n_frames, emb_dim) - preds (torch.Tensor): Tensor containing speaker activity probabilities - Shape: (batch_size, n_frames, n_spk) - topk_indices (torch.Tensor): Tensor containing indices of frames to gather - Shape: (batch_size, spkcache_len) - is_disabled (torch.Tensor): Tensor containing binary mask for disabled frames - Shape: (batch_size, spkcache_len) - mean_sil_emb (torch.Tensor): Tensor containing mean silence embedding - Shape: (batch_size, emb_dim) - - Returns: - emb_seq_gathered (torch.Tensor): Tensor containing gathered embeddings. - Shape: (batch_size, spkcache_len, emb_dim) - preds_gathered (torch.Tensor): Tensor containing gathered speaker activities. - Shape: (batch_size, spkcache_len, n_spk) - """ - # To use `torch.gather`, expand `topk_indices` along the last dimension to match `emb_dim`. - # Gather the speaker cache embeddings, including the placeholder embeddings for silence frames. - # Finally, replace the placeholder embeddings with actual mean silence embedding. - emb_dim, n_spk = emb_seq.shape[2], preds.shape[2] - indices_expanded_emb = topk_indices.unsqueeze(-1).expand(-1, -1, emb_dim) - emb_seq_gathered = torch.gather(emb_seq, 1, indices_expanded_emb) # (batch_size, spkcache_len, emb_dim) - mean_sil_emb_expanded = mean_sil_emb.unsqueeze(1).expand(-1, self.spkcache_len, -1) - emb_seq_gathered = torch.where(is_disabled.unsqueeze(-1), mean_sil_emb_expanded, emb_seq_gathered) - - # To use `torch.gather`, expand `topk_indices` along the last dimension to match `n_spk`. - # Gather speaker cache predictions `preds`, including the placeholder `preds` for silence frames. - # Finally, replace the placeholder `preds` with zeros. - indices_expanded_spk = topk_indices.unsqueeze(-1).expand(-1, -1, n_spk) - preds_gathered = torch.gather(preds, 1, indices_expanded_spk) # (batch_size, spkcache_len, n_spk) - preds_gathered = torch.where(is_disabled.unsqueeze(-1), torch.tensor(0.0), preds_gathered) - return emb_seq_gathered, preds_gathered - - def _get_max_perm_index(self, scores): - """ - Get number of first speakers having at least one positive score. - These speakers will be randomly permuted during _compress_spkcache (training only). - - Args: - scores (torch.Tensor): Tensor containing speaker scores - Shape: (batch_size, n_frames, n_spk) - - Returns: - max_perm_index (torch.Tensor): Tensor with number of first speakers to permute - Shape: (batch_size) - """ - - batch_size, _, n_spk = scores.shape - is_pos = scores > 0 # positive score usually means that only current speaker is speaking - zero_indices = torch.where(is_pos.sum(dim=1) == 0) - max_perm_index = torch.full((batch_size,), n_spk, dtype=torch.long, device=scores.device) - max_perm_index.scatter_reduce_(0, zero_indices[0], zero_indices[1], reduce="amin", include_self=False) - return max_perm_index - - def _disable_low_scores(self, preds, scores, min_pos_scores_per_spk: int): - """ - Sets scores for non-speech to '-inf'. - Also sets non-positive scores to '-inf', if there are at least min_pos_scores_per_spk positive scores. - - Args: - preds (torch.Tensor): Tensor containing speaker activity probabilities - Shape: (batch_size, n_frames, n_spk) - scores (torch.Tensor): Tensor containing speaker importance scores - Shape: (batch_size, n_frames, n_spk) - min_pos_scores_per_spk (int): if number of positive scores for a speaker is greater than this, - then all non-positive scores for this speaker will be disabled, i.e. set to '-inf'. - - Returns: - scores (torch.Tensor): Tensor containing speaker scores. - Shape: (batch_size, n_frames, n_spk) - """ - # Replace scores for non-speech with '-inf'. - is_speech = preds > 0.5 - scores = torch.where(is_speech, scores, torch.tensor(float('-inf'))) - - # Replace non-positive scores (usually overlapped speech) with '-inf' - # This will be applied only if a speaker has at least min_pos_scores_per_spk positive-scored frames - is_pos = scores > 0 # positive score usually means that only current speaker is speaking - is_nonpos_replace = (~is_pos) * is_speech * (is_pos.sum(dim=1).unsqueeze(1) >= min_pos_scores_per_spk) - scores = torch.where(is_nonpos_replace, torch.tensor(float('-inf')), scores) - return scores - - def _permute_speakers(self, scores, max_perm_index): - """ - Create a random permutation of scores max_perm_index first speakers. - - Args: - scores (torch.Tensor): Tensor containing speaker scores - Shape: (batch_size, n_frames, n_spk) - max_perm_index (torch.Tensor): Tensor with number of first speakers to permute - Shape: (batch_size) - - Returns: - scores (torch.Tensor): Tensor with permuted scores. - Shape: (batch_size, n_frames, n_spk) - spk_perm (torch.Tensor): Tensor containing speaker permutation applied to scores - Shape: (batch_size, n_spk) - """ - spk_perm_list, scores_list = [], [] - batch_size, _, n_spk = scores.shape - for batch_index in range(batch_size): - rand_perm_inds = torch.randperm(max_perm_index[batch_index].item()) - linear_inds = torch.arange(max_perm_index[batch_index].item(), n_spk) - permutation = torch.cat([rand_perm_inds, linear_inds]) - spk_perm_list.append(permutation) - scores_list.append(scores[batch_index, :, permutation]) - spk_perm = torch.stack(spk_perm_list).to(scores.device) - scores = torch.stack(scores_list).to(scores.device) - return scores, spk_perm - - def _compress_spkcache(self, emb_seq, preds, mean_sil_emb, permute_spk: bool = False): - """ - Compress speaker cache for streaming inference. - Keep spkcache_len most important frames out of input n_frames, based on preds. - - Args: - emb_seq (torch.Tensor): Tensor containing n_frames > spkcache_len embeddings - Shape: (batch_size, n_frames, emb_dim) - preds (torch.Tensor): Tensor containing n_frames > spkcache_len speaker activity probabilities - Shape: (batch_size, n_frames, n_spk) - mean_sil_emb (torch.Tensor): Tensor containing mean silence embedding - Shape: (batch_size, emb_dim) - permute_spk (bool): If true, will generate a random permutation of existing speakers - - Returns: - spkcache (torch.Tensor): Tensor containing spkcache_len most important embeddings from emb_seq. - Embeddings are ordered by speakers. Within each speaker, original order of frames is kept. - Shape: (batch_size, spkcache_len, emb_dim) - spkcache_preds (torch.Tensor): predictions corresponding to speaker cache - Shape: (batch_size, spkcache_len, n_spk) - spk_perm (torch.Tensor): random speaker permutation tensor if permute_spk=True, otherwise None - Shape: (batch_size, n_spk) - """ - batch_size, n_frames, n_spk = preds.shape - spkcache_len_per_spk = self.spkcache_len // n_spk - self.spkcache_sil_frames_per_spk - strong_boost_per_spk = math.floor(spkcache_len_per_spk * self.strong_boost_rate) - weak_boost_per_spk = math.floor(spkcache_len_per_spk * self.weak_boost_rate) - min_pos_scores_per_spk = math.floor(spkcache_len_per_spk * self.min_pos_scores_rate) - - scores = self._get_log_pred_scores(preds) - scores = self._disable_low_scores(preds, scores, min_pos_scores_per_spk) - - if permute_spk: # Generate a random permutation of speakers - max_perm_index = self._get_max_perm_index(scores) - scores, spk_perm = self._permute_speakers(scores, max_perm_index) - else: - spk_perm = None - - if self.scores_boost_latest > 0: # Boost newly added frames - scores[:, self.spkcache_len :, :] += self.scores_boost_latest - - if self.training: - if self.scores_add_rnd > 0: # Add random noise to scores - scores += torch.rand(batch_size, n_frames, n_spk, device=scores.device) * self.scores_add_rnd - - # Strong boosting to ensure each speaker has at least K frames in speaker cache - scores = self._boost_topk_scores(scores, strong_boost_per_spk, scale_factor=2) - # Weak boosting to prevent dominance of one speaker in speaker cache - scores = self._boost_topk_scores(scores, weak_boost_per_spk, scale_factor=1) - - if self.spkcache_sil_frames_per_spk > 0: # Add number of silence frames in the end of each block - pad = torch.full((batch_size, self.spkcache_sil_frames_per_spk, n_spk), float('inf'), device=scores.device) - scores = torch.cat([scores, pad], dim=1) # (batch_size, n_frames + spkcache_sil_frames_per_spk, n_spk) - - topk_indices, is_disabled = self._get_topk_indices(scores) - spkcache, spkcache_preds = self._gather_spkcache_and_preds( - emb_seq, preds, topk_indices, is_disabled, mean_sil_emb - ) - return spkcache, spkcache_preds, spk_perm diff --git a/nemo/collections/asr/modules/ssl_modules/__init__.py b/nemo/collections/asr/modules/ssl_modules/__init__.py deleted file mode 100644 index f33127bd7d853b3ddec9d52df4a1db1d476f5285..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/ssl_modules/__init__.py +++ /dev/null @@ -1,32 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.asr.modules.ssl_modules.augmentation import ( - MultiSpeakerNoiseAugmentation, - SpeakerNoiseAugmentation, -) -from nemo.collections.asr.modules.ssl_modules.masking import ConvFeatureMaksingWrapper, RandomBlockMasking -from nemo.collections.asr.modules.ssl_modules.multi_layer_feat import ConformerMultiLayerFeaturePreprocessor -from nemo.collections.asr.modules.ssl_modules.multi_softmax_decoder import MultiSoftmaxDecoder -from nemo.collections.asr.modules.ssl_modules.quantizers import RandomProjectionVectorQuantizer - -__all__ = [ - 'MultiSpeakerNoiseAugmentation', - 'SpeakerNoiseAugmentation', - 'ConvFeatureMaksingWrapper', - 'RandomBlockMasking', - 'ConformerMultiLayerFeaturePreprocessor', - 'MultiSoftmaxDecoder', - 'RandomProjectionVectorQuantizer', -] diff --git a/nemo/collections/asr/modules/ssl_modules/augmentation.py b/nemo/collections/asr/modules/ssl_modules/augmentation.py deleted file mode 100644 index cd665634f841352b67b3cf9e9a9dc7c57b36ba8a..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/ssl_modules/augmentation.py +++ /dev/null @@ -1,280 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import math -import random -from collections import Counter - -import torch - -from nemo.collections.asr.data.ssl_dataset import AudioNoiseBatch - - -class SpeakerNoiseAugmentation(object): - def __init__( - self, - prob: float = 0.0, - noise_ratio: float = 0.0, - min_r_speech: float = -5.0, - max_r_speech: float = 5.0, - min_r_noise: float = -5.0, - max_r_noise: float = 20.0, - min_mix_rate: float = 0.0, - max_mix_rate: float = 1.0, - ): - super().__init__() - self.prob = prob - self.noise_ratio = noise_ratio - self.min_r_speech = min_r_speech - self.max_r_speech = max_r_speech - self.min_r_noise = min_r_noise - self.max_r_noise = max_r_noise - self.min_mix_rate = min_mix_rate - self.max_mix_rate = max_mix_rate - - if not (0 <= self.prob <= 1): - raise ValueError(f"prob must be in [0, 1], got: {self.prob}") - if not (0 <= self.noise_ratio <= 1): - raise ValueError(f"noise_ratio must be in [0, 1], got: {self.noise_ratio}") - if not (self.min_r_speech <= self.max_r_speech): - raise ValueError( - f"min_r_speech must be no greater than max_r_speech, got: min={self.min_r_speech} and max={self.max_r_speech}" - ) - if not (self.min_r_noise <= self.max_r_noise): - raise ValueError( - f"min_r_noise must be no greater than max_r_noise, got: min={self.min_r_noise} and max={self.max_r_noise}" - ) - if not (0 <= self.min_mix_rate <= self.max_mix_rate <= 1): - raise ValueError( - f"min_mix_rate must be no greater than max_mix_rate, and both must be in [0, 1], got: {self.min_mix_rate} and {self.max_mix_rate}" - ) - - def repeat_noise(self, noise: torch.Tensor, noise_len: int, max_audio_len: int) -> torch.Tensor: - noise = noise[:noise_len] - if noise_len < max_audio_len: - noise = noise.repeat(max_audio_len // noise_len + 1) - noise = noise[:max_audio_len] - return noise - - def pad_or_trim_noise(self, noise: torch.Tensor, max_audio_len: int, value=0) -> torch.Tensor: - noise_len = noise.size(0) - if noise_len < max_audio_len: - pad = (0, max_audio_len - noise_len) - noise = torch.nn.functional.pad(noise, pad, value=value) - else: - noise = noise[:max_audio_len] - return noise - - def __call__(self, batch: AudioNoiseBatch) -> AudioNoiseBatch: - audio_signal = batch.audio - audio_lengths = batch.audio_len - batch_size = audio_signal.size(0) - max_audio_len = audio_signal.size(1) - - noise = batch.noise - noise_len = batch.noise_len - for i in range(batch_size): - if random.random() > self.prob: - continue - - # randomly select the length of mixing segment - if 0 <= self.min_mix_rate < self.max_mix_rate <= 1: - mix_len = random.randint( - int(audio_lengths[i] * self.min_mix_rate), int(audio_lengths[i] * self.max_mix_rate) - 1 - ) - else: - mix_len = max(1, int(audio_lengths[i] * self.min_mix_rate)) - - # randomly select position to start the mixing - mix_start_idx = random.randint(0, audio_lengths[i] - mix_len - 1) - - # randomly select the energy ratio between speech and noise - if random.random() < self.noise_ratio or batch_size == 1: - energy_ratio = random.uniform(self.min_r_noise, self.max_r_noise) - else: - energy_ratio = random.uniform(self.min_r_speech, self.max_r_speech) - j = random.choice([x for x in range(batch_size) if x != i]) - noise[i] = audio_signal[j].clone() - noise_len[i] = audio_lengths[j] - - # repeat noise to match the length of audio mix length if necessary - if noise_len[i] <= mix_len: - # repeat noise to match the length of audio mix length - noise_start_idx = 0 - noise[i] = self.pad_or_trim_noise(self.repeat_noise(noise[i], noise_len[i], mix_len), max_audio_len) - noise_len[i] = mix_len - else: - # randomly select a segment of noise - noise_start_idx = random.randint(0, noise_len[i] - mix_len - 1) - - # calculate the scale factor for noise - audio_energy = torch.sum(audio_signal[i, : audio_lengths[i]] ** 2) / audio_lengths[i] - noise_energy = torch.sum(noise[i, : noise_len[i]] ** 2) / noise_len[i] if noise_len[i] > 0 else 0 - mix_scale = math.sqrt(audio_energy / (10 ** (energy_ratio / 10) * noise_energy)) if noise_energy > 0 else 0 - - # get the residual signal to be added to original audio - noise_clip = noise[i, noise_start_idx : noise_start_idx + mix_len] - noise_signal = torch.zeros_like(audio_signal[i]) - noise_signal[mix_start_idx : mix_start_idx + mix_len] = mix_scale * noise_clip - - noise[i] = noise_signal - noise_len[i] = audio_lengths[i] - - return AudioNoiseBatch( - sample_id=batch.sample_id, - audio=batch.audio, - audio_len=batch.audio_len, - noise=noise, - noise_len=noise_len, - noisy_audio=batch.audio + noise, - noisy_audio_len=noise_len, - ) - - -class MultiSpeakerNoiseAugmentation(SpeakerNoiseAugmentation): - def __init__( - self, - prob: float = 0.0, - noise_ratio: float = 0.0, - min_r_speech: float = -5.0, - max_r_speech: float = 5.0, - min_r_noise: float = -5.0, - max_r_noise: float = 20.0, - min_mix_rate: float = 0.0, - max_mix_rate: float = 1.0, - min_num_segments: int = 1, - max_num_segments: int = 5, - min_num_speakers: int = 1, - max_num_speakers: int = 4, - ): - super().__init__( - prob=prob, - noise_ratio=noise_ratio, - min_r_speech=min_r_speech, - max_r_speech=max_r_speech, - min_r_noise=min_r_noise, - max_r_noise=max_r_noise, - min_mix_rate=min_mix_rate, - max_mix_rate=max_mix_rate, - ) - self.min_num_segments = min_num_segments - self.max_num_segments = max_num_segments - self.min_num_speakers = min_num_speakers - self.max_num_speakers = max_num_speakers - - def __call__(self, batch: AudioNoiseBatch) -> AudioNoiseBatch: - audio_signal = batch.audio - audio_lengths = batch.audio_len - batch_size = audio_signal.size(0) - - noise = batch.noise - noise_len = batch.noise_len - for i in range(batch_size): - if random.random() > self.prob: - continue - - # randomly select the length of mixing segment - if 0 <= self.min_mix_rate < self.max_mix_rate <= 1: - mix_rate = random.uniform(self.min_mix_rate, self.max_mix_rate) - else: - mix_rate = self.min_mix_rate - mix_len = max(1, int(audio_lengths[i] * mix_rate)) - - # randomly select the number of segments - num_segments = random.randint(self.min_num_segments, self.max_num_segments) - num_speakers = random.randint(self.min_num_speakers, self.max_num_speakers) - num_speakers = min(num_speakers, batch_size) - - # randomly chunk mix_len into num_segments - segment_lens = list(Counter(random.choices(range(num_segments), k=mix_len)).values()) - - # randomly select the energy ratio between speech and noise - if random.random() < self.noise_ratio or batch_size == 1: - mode = "noise" - energy_ratio = random.uniform(self.min_r_noise, self.max_r_noise) - else: - mode = "speech" - energy_ratio = random.uniform(self.min_r_speech, self.max_r_speech) - - noise_segments = self.get_noise_segments(i, batch, segment_lens, num_speakers, mode) - noise_signal = torch.zeros_like(audio_signal[i]) - min_start_idx = 0 - max_start_idx = audio_lengths[i] - mix_len - for j in range(num_segments): - start_idx = min_start_idx - if min_start_idx < max_start_idx: - start_idx = random.randint(min_start_idx, max_start_idx - 1) - noise_signal[start_idx : start_idx + segment_lens[j]] = noise_segments[j] - min_start_idx = start_idx + segment_lens[j] - max_start_idx += segment_lens[j] - - # calculate the scale factor for noise - audio_energy = torch.sum(audio_signal[i, : audio_lengths[i]] ** 2) / audio_lengths[i] - noise_energy = torch.sum(noise_signal[: audio_lengths[i]] ** 2) / audio_lengths[i] - mix_scale = math.sqrt(audio_energy / (10 ** (energy_ratio / 10) * noise_energy)) if noise_energy > 0 else 0 - - # get the residual signal to be added to original audio - noise_signal = mix_scale * noise_signal - noise[i] = noise_signal - noise_len[i] = audio_lengths[i] - - return AudioNoiseBatch( - sample_id=batch.sample_id, - audio=batch.audio, - audio_len=batch.audio_len, - noise=noise, - noise_len=noise_len, - noisy_audio=batch.audio + noise, - noisy_audio_len=noise_len, - ) - - def get_noise_segments(self, batch_idx, batch, segment_lens, num_speakers, mode): - audio_signal = batch.audio - audio_lengths = batch.audio_len - noise = batch.noise - noise_len = batch.noise_len - batch_size = noise.size(0) - max_audio_len = audio_signal.size(1) - noise_segments = [] - if mode == "noise": - noise_padded = self.pad_or_trim_noise( - self.repeat_noise(noise[batch_idx], noise_len[batch_idx], max_audio_len), max_audio_len - ) - start_idx = 0 - for segment_len in segment_lens: - noise_segments.append(noise_padded[start_idx : start_idx + segment_len]) - start_idx += segment_len - return noise_segments - - if mode != "speech": - raise ValueError(f"mode must be either 'noise' or 'speech', got: {mode}") - - speaker_candidates = [x for x in range(batch_size) if x != batch_idx] - speaker_candidates = random.sample(speaker_candidates, k=min(num_speakers, batch_size - 1)) - sid = 0 - for seg_len in segment_lens: - bid = speaker_candidates[sid] - if seg_len > audio_lengths[bid]: - audio_segment = self.pad_or_trim_noise( - self.repeat_noise(audio_signal[bid], audio_lengths[bid], seg_len), seg_len - ) - else: - start_idx = random.randint(0, audio_lengths[bid] - seg_len - 1) if audio_lengths[bid] > seg_len else 0 - audio_segment = audio_signal[bid][start_idx : start_idx + seg_len].clone() - noise_segments.append(audio_segment) - sid += 1 - if sid >= len(speaker_candidates): - sid = random.randint(0, len(speaker_candidates) - 1) - - return noise_segments diff --git a/nemo/collections/asr/modules/ssl_modules/masking.py b/nemo/collections/asr/modules/ssl_modules/masking.py deleted file mode 100644 index c491c56fa82922dd26fe0210c18e3524bcf30159..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/ssl_modules/masking.py +++ /dev/null @@ -1,223 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from typing import Optional, Union - -import torch -import torch.nn as nn - -from nemo.core.classes import NeuralModule -from nemo.core.neural_types import AcousticEncodedRepresentation, LengthsType, NeuralType - - -class RandomBlockMasking(NeuralModule): - """ - Performs random block masking on sequence of features. - Args: - mask_prob (float): percentage of sequence to mask - block_size (int): size of each block to mask - mask_value (Optional[float]): value to use for masking, if None, use random values - feat_in (Optional[int]): size of input features, required if mask_value is None - freeze (bool): if True, mask embedding is not trainable - allow_overlap (bool): if True, masked blocks can overlap - """ - - def __init__( - self, - feat_in: int, - mask_prob: float = 0.5, - block_size: int = 48, - mask_value: Optional[float] = None, - freeze: bool = True, - allow_overlap: bool = False, - max_mask_ratio: float = 0.8, - ): - super().__init__() - self.block_size = block_size - self.mask_prob = mask_prob - self.allow_overlap = allow_overlap - self.max_mask_ratio = max_mask_ratio - - if mask_value is None: - self.mask_embedding = nn.Parameter(torch.FloatTensor(feat_in)) - nn.init.normal_(self.mask_embedding, mean=0.0, std=0.1) - else: - self.mask_embedding = nn.Parameter(torch.ones(feat_in) * mask_value, requires_grad=False) - if freeze: - self.freeze() - - @property - def input_types(self): - """Returns definitions of module input types""" - return { - "input_feats": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), - "input_lengths": NeuralType(tuple('B'), LengthsType()), - } - - @property - def output_types(self): - """Returns definitions of module output types""" - return { - "maksed_feats": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), - "masks": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), - } - - def forward(self, input_feats: torch.Tensor, input_lengths: torch.Tensor): - """ - Args: - input_feats (Tensor): input sequence features, shape=(batch, features, time) - input_length (Tensor): length of each sequence in the batch, shape=(batch) - Returns: - masked_feats (Tensor): masked features, shape=(batch, features, time) - masks (Tensor): the generated masks, shape=(batch, features, time) - """ - if self.allow_overlap: - return self.forward_with_overlap(input_feats, input_lengths) - else: - return self.forward_without_overlap(input_feats, input_lengths) - - def forward_without_overlap(self, input_feats: torch.Tensor, input_lengths: torch.Tensor): - """ - Args: - input_feats (Tensor): input sequence features, shape=(batch, features, time) - input_length (Tensor): length of each sequence in the batch, shape=(batch) - Returns: - masked_feats (Tensor): masked features, shape=(batch, features, time) - masks (Tensor): the generated masks, shape=(batch, features, time) - """ - batch_size = input_feats.size(0) - masks = torch.zeros_like(input_feats) - masked_feats = input_feats - indices = [] - for i in range(batch_size): - if self.block_size >= input_lengths[i] * self.max_mask_ratio: - # handle case where audio is too short - block_size = 8 - num_patches = 1 - patch_indices = torch.tensor([0]) - offset = 0 - else: - num_patches = torch.ceil(input_lengths[i] * self.mask_prob / self.block_size).int() - offset = torch.randint(0, self.block_size, (1,))[0] - block_size = self.block_size - if (num_patches + 1) * self.block_size > input_lengths[i]: - block_size = torch.div(input_lengths[i], (num_patches + 1), rounding_mode='trunc') - max_num_patches = torch.div(input_lengths[i], block_size, rounding_mode='trunc') - patch_indices = torch.randperm(max_num_patches - 1)[:num_patches] - - if num_patches: - starts = patch_indices * block_size + offset - ends = starts + block_size - positions = torch.cat([torch.arange(s, e) for s, e in zip(starts, ends)]).reshape(-1, 1) - batch_index = torch.full((positions.shape[0], 1), i, dtype=positions.dtype) - positions = torch.cat([batch_index, positions], dim=1) - indices.append(positions.unique(dim=0)) - - if indices: - indices = torch.cat(indices, dim=0).unbind(1) - masks = masks.permute(0, 2, 1) - masked_feats = masked_feats.permute(0, 2, 1) - - masks = masks.index_put(indices, values=torch.tensor(1.0)).permute(0, 2, 1) - masked_feats = masked_feats.index_put(indices, values=self.mask_embedding).permute(0, 2, 1) - - return masked_feats, masks - - def forward_with_overlap(self, input_feats: torch.Tensor, input_lengths: torch.Tensor): - """ - Args: - input_feats (Tensor): input sequence features, shape=(batch, features, time) - input_length (Tensor): length of each sequence in the batch, shape=(batch) - Returns: - masked_feats (Tensor): masked features, shape=(batch, features, time) - masks (Tensor): the generated masks, shape=(batch, features, time) - """ - batch_size = input_feats.size(0) - masks = torch.zeros_like(input_feats) - masked_feats = input_feats - mask_prob = torch.tensor(self.mask_prob) - indices = [] - for i in range(batch_size): - input_length = input_lengths[i].item() - if self.block_size >= input_length * self.max_mask_ratio: - # handle case where audio is too short - block_size = 8 - num_patches = 1 - patch_indices = torch.tensor([0]) - else: - block_size = self.block_size - count = max(0, input_length - self.block_size) - num_patches = torch.binomial(torch.tensor(count).float(), mask_prob).long() - patch_indices = torch.randperm(count) - patch_indices = patch_indices[:num_patches] - if num_patches: - ends = torch.clamp(patch_indices + block_size, max=input_length) - positions = torch.cat([torch.arange(s, e) for s, e in zip(patch_indices, ends)]).reshape(-1, 1) - batch_index = torch.full((positions.shape[0], 1), i, dtype=positions.dtype) - positions = torch.cat([batch_index, positions], dim=1) - indices.append(positions.unique(dim=0)) - - if indices: - indices = torch.cat(indices, dim=0).unbind(1) - masks = masks.permute(0, 2, 1) - masked_feats = masked_feats.permute(0, 2, 1) - - masks = masks.index_put(indices, values=torch.tensor(1.0)).permute(0, 2, 1) - masked_feats = masked_feats.index_put(indices, values=self.mask_embedding).permute(0, 2, 1) - - return masked_feats, masks - - -class ConvFeatureMaksingWrapper(NeuralModule): - """ - A wrapper module that applies masking to the features after subsampling layer of ConformerEncoder. - """ - - def __init__(self, pre_encode_module: nn.Module, masking_module: Union[nn.Module, NeuralModule]) -> None: - """ - Args: - pre_encode_module: the pre_encode module of the ConformerEncoder instance - masking_module: the module that performs masking on the extracted features - """ - super().__init__() - self.pre_encode = pre_encode_module - self.masking = masking_module - self.curr_mask = None - self.curr_feat = None - self.apply_mask = False - - def forward(self, x, lengths): - """ - Same interface as ConformerEncoder.pre_encode - """ - feats, lengths = self.pre_encode(x=x, lengths=lengths) - self.curr_feat = feats.detach() - if self.apply_mask: - feats = feats.transpose(1, 2) - masked_feats, self.curr_mask = self.masking(input_feats=feats, input_lengths=lengths) - masked_feats = masked_feats.transpose(1, 2).detach() - else: - masked_feats = feats - self.curr_mask = torch.zeros_like(feats) - return masked_feats, lengths - - def set_masking_enabled(self, apply_mask: bool): - self.apply_mask = apply_mask - - def get_current_mask(self): - return self.curr_mask - - def get_current_feat(self): - return self.curr_feat diff --git a/nemo/collections/asr/modules/ssl_modules/multi_layer_feat.py b/nemo/collections/asr/modules/ssl_modules/multi_layer_feat.py deleted file mode 100644 index 73ca41438437dcff3b92ea63429a9ab59c475ff4..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/ssl_modules/multi_layer_feat.py +++ /dev/null @@ -1,138 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import List, Optional, Tuple - -import torch -import torch.distributed -import torch.nn as nn - -from nemo.collections.asr.modules import ( - AudioToMelSpectrogramPreprocessor, - ConformerEncoder, - ConformerMultiLayerFeatureExtractor, -) -from nemo.core.classes import Exportable, NeuralModule -from nemo.core.classes.mixins import AccessMixin - - -class Aggregator(nn.Module): - AVAILABLE_POOLING = ["cat", "sum", "mean", "avg", "max", "min", "none", "weighted_sum"] - - def __init__(self, mode, weights, layer_idx_list, channel_idx: int = 1): - """ - Args: - mode: Aggregation mode. One of ["cat", "sum", "mean", "avg", "max", "min", "none", "weighted_sum"] - weights: Weights for weighted sum aggregation. If None, weights are initialized to 1/num_layers. - layer_idx_list: List of layer indices to aggregate. - channel_idx: Channel dimension index of the input tensors. - """ - super().__init__() - self.mode = mode - self.channel_idx = channel_idx - self.weights = weights - if self.mode not in self.AVAILABLE_POOLING: - raise ValueError(f"Unknown mode `{self.mode}`, available modes are {self.AVAILABLE_POOLING}") - if self.mode == "weighted_sum" and self.weights is None: - self.weights = nn.Parameter(torch.ones(len(layer_idx_list)) / len(layer_idx_list)) - - def _forward_for_weighted_sum( - self, encoded: List[torch.Tensor], encoded_len: List[torch.Tensor] - ) -> Tuple[torch.Tensor, torch.Tensor]: - encoded_weighted = [encoded[i] * self.weights[i] for i in range(len(encoded))] - encoded_weighted = torch.sum(torch.stack(encoded_weighted, dim=-1), dim=-1) - return encoded_weighted, encoded_len[0] - - def forward( - self, encoded: List[torch.Tensor], encoded_len: List[torch.Tensor] - ) -> Tuple[torch.Tensor, torch.Tensor]: - """ - Args: - encoded: List of tensors of shape [B, D, T] representing the encoded features from different layers. - encoded_len: List of tensors of shape [B] representing the lengths of the encoded features. - Returns: - aggregated: Aggregated tensor of shape [B, D, T] representing the aggregated features. - aggregated_len: Tensor of shape [B] representing the lengths of the aggregated features. - """ - - if self.mode == "cat": - return torch.cat(encoded, dim=self.channel_idx), encoded_len[0] - elif self.mode == "sum": - return torch.cat([x.unsqueeze(-1) for x in encoded], dim=-1).sum(dim=-1), encoded_len[0] - elif self.mode == "mean" or self.mode == "avg": - return torch.cat([x.unsqueeze(-1) for x in encoded], dim=-1).mean(dim=-1), encoded_len[0] - elif self.mode == "max": - return torch.cat([x.unsqueeze(-1) for x in encoded], dim=-1).max(dim=-1), encoded_len[0] - elif self.mode == "min": - return torch.cat([x.unsqueeze(-1) for x in encoded], dim=-1).min(dim=-1), encoded_len[0] - elif self.mode == "none": - return encoded, encoded_len - elif self.mode == "weighted_sum": - return self._forward_for_weighted_sum(encoded, encoded_len) - else: - raise ValueError(f"Unknown mode {self.mode}") - - -class ConformerMultiLayerFeaturePreprocessor(NeuralModule, Exportable, AccessMixin): - """ - This class is used to replace the AudioToMelSpectrogramPreprocessor such that - the input to the actual model encoder is the multi-layer features from a pre-trained ConformerEncoder. - """ - - def __init__( - self, - aggregator: nn.Module, - preprocessor: AudioToMelSpectrogramPreprocessor, - encoder: ConformerEncoder, - spec_augment=None, - layer_idx_list: Optional[List[int]] = None, - freeze_encoder: bool = True, - ): - super().__init__() - self.preprocessor = preprocessor - self.spec_augmentation = spec_augment - self.feature_extractor = ConformerMultiLayerFeatureExtractor( - encoder=encoder, aggregator=aggregator, layer_idx_list=layer_idx_list - ) - self.freeze_encoder = freeze_encoder - if freeze_encoder: - self.freeze() - - def forward(self, input_signal, length): - """ - Forward pass of the model. - - Args: - input_signal: Tensor that represents a batch of raw audio signals, - of shape [B, T]. T here represents timesteps, with 1 second of audio represented as - `self.sample_rate` number of floating point values. - length: Vector of length B, that contains the individual lengths of the audio - sequences. - Returns: - encoded: A tensor of shape [B, D, T], where D represents the number of - feature dimensions extracted from the audio signal, and T represents the - number of timesteps in the processed audio signal. - encoded_len: A tensor of shape [B], that contains the lengths of the audio sequences. - """ - - processed_signal, processed_signal_length = self.preprocessor( - input_signal=input_signal, - length=length, - ) - - if self.spec_augmentation is not None and self.training: - processed_signal = self.spec_augmentation(input_spec=processed_signal, length=processed_signal_length) - - encoded, encoded_len = self.feature_extractor(audio_signal=processed_signal, length=processed_signal_length) - return encoded, encoded_len diff --git a/nemo/collections/asr/modules/ssl_modules/multi_softmax_decoder.py b/nemo/collections/asr/modules/ssl_modules/multi_softmax_decoder.py deleted file mode 100644 index 67c76e342c38fd0b321f9a394059bd167850d09d..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/ssl_modules/multi_softmax_decoder.py +++ /dev/null @@ -1,84 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from collections import OrderedDict - -import torch - -from nemo.collections.asr.parts.submodules.jasper import init_weights -from nemo.core.classes import NeuralModule, typecheck -from nemo.core.neural_types import AcousticEncodedRepresentation, LogprobsType, NeuralType - - -class MultiSoftmaxDecoder(NeuralModule): - """ - A linear decoder that takes encoder output and produces log probabilities, which also handles the - case where each frame has multiple output targets. This can be used together with - `nemo.collections.asr.losses.ssl_losses.MultiMLMLoss` to train a model with multiple targets per frame. - """ - - @property - def input_types(self): - return OrderedDict({"encoder_output": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation())}) - - @property - def output_types(self): - if self.squeeze_single and self.num_decoders == 1: - return OrderedDict({"logprobs": NeuralType(('B', 'T', 'C'), LogprobsType())}) - return OrderedDict({"logprobs": NeuralType(('B', 'T', 'C', 'H'), LogprobsType())}) - - def __init__( - self, - feat_in: int, - num_classes: int, - num_decoders: int = 1, - init_mode: str = "xavier_uniform", - use_bias: bool = False, - squeeze_single: bool = False, - ) -> None: - """ - Args: - feat_in: input feature dimension - num_classes: number of classes - num_decoders: number of decoders - init_mode: initialization mode - use_bias: whether to use bias - squeeze_single: if True, squeeze codebook dimension if num_books is 1 - """ - super().__init__() - self.feat_in = feat_in - self.num_classes = num_classes - self.num_decoders = num_decoders - self.squeeze_single = squeeze_single - - self.decoder_layers = torch.nn.Sequential( - torch.nn.Conv1d(self.feat_in, self.num_classes * self.num_decoders, kernel_size=1, bias=use_bias) - ) - self.apply(lambda x: init_weights(x, mode=init_mode)) - - @typecheck() - def forward(self, encoder_output): - """ - Args: - encoder_output: output from the encoder of shape (B, D, T) - Returns: - logprobs: log probabilities of shape (B, T, C, H), or (B, T, C) if squeeze_single is True - """ - logits = self.decoder_layers(encoder_output).transpose(1, 2) - logits = logits.reshape(logits.shape[0], logits.shape[1], self.num_classes, self.num_decoders) - if self.squeeze_single and self.num_decoders == 1: - logits = logits.squeeze(-1) - - return torch.nn.functional.log_softmax(logits, dim=2) diff --git a/nemo/collections/asr/modules/ssl_modules/quantizers.py b/nemo/collections/asr/modules/ssl_modules/quantizers.py deleted file mode 100644 index 8a53a7c000987e8fe81735137a9c3aca429d89a1..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/ssl_modules/quantizers.py +++ /dev/null @@ -1,166 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import torch -import torch.nn.functional as F -from torch import nn - -from nemo.core import NeuralModule -from nemo.core.classes import Exportable, NeuralModule, typecheck -from nemo.core.neural_types import LabelsType, NeuralType, SpectrogramType - - -class RandomProjectionVectorQuantizer(NeuralModule, Exportable): - DIST_FN_LIST = ["l2", "cosine"] - - def __init__( - self, - feat_in: int, - code_dim: int, - num_classes: int, - num_books: int, - dist_fn: str = "cosine", - time_ahead: bool = False, - freeze: bool = True, - squeeze_single: bool = False, - combine_time_steps: int = 1, - ): - """Vector quantization using random projection proposed in BEST-RQ paper: - 'Self-Supervised Learning with Random-Projection Quantizer for Speech Recognition' - - Args: - feat_in: input feature dimension - code_dim: dimension of the codebook features - num_classes: number of classes - num_books: number of codebooks - dist_fn: distance function to use, one of "l2" or "cosine" - time_ahead: if Ture, the input is of shape (B, T, D), otherwise (B, D, T) - freeze: whether to freeze the projection matrix - squeeze_single: if True, squeeze codebook dimension if num_books is 1 - """ - super().__init__() - - if dist_fn not in self.DIST_FN_LIST: - raise ValueError(f"Unknown distance function {dist_fn}, must be one of {self.DIST_FN_LIST}") - - self.feat_in = feat_in - self.code_dim = code_dim - self.num_classes = num_classes - self.num_books = num_books - self.dist_fn = dist_fn - self.time_ahead = time_ahead - self.squeeze_single = squeeze_single - self.combine_time_steps = combine_time_steps - - # (B, T, D) -> (B, T, num_books, code_dim) - self.proj = nn.Linear(self.feat_in * combine_time_steps, self.num_books * self.code_dim, bias=False) - torch.nn.init.xavier_normal_(self.proj.weight) - - # (num_books, num_classes, hid_dim) - codebooks = torch.randn(self.num_books, self.num_classes, self.code_dim).double() - torch.nn.init.normal_(codebooks, mean=0, std=1) - codebooks = F.normalize(codebooks, dim=-1) - self.codebooks = nn.Parameter(codebooks) - if freeze: - self.freeze() - - @property - def input_types(self): - """Returns definitions of module input ports.""" - if self.time_ahead: - return {"input_signal": NeuralType(('B', 'T', 'D'), SpectrogramType())} - return {"input_signal": NeuralType(('B', 'D', 'T'), SpectrogramType())} - - @property - def output_types(self): - """Returns definitions of module output ports.""" - if self.time_ahead: - if self.num_books == 1 and self.squeeze_single: - return { - "xq": NeuralType(('B', 'T', 'D'), SpectrogramType()), - "xid": NeuralType(('B', 'T'), LabelsType()), - } - return { - "xq": NeuralType(('B', 'T', 'D', 'H'), SpectrogramType()), - "xid": NeuralType(('B', 'T', 'H'), LabelsType()), - } - if self.num_books == 1 and self.squeeze_single: - return { - "xq": NeuralType(('B', 'D', 'T'), SpectrogramType()), - "xid": NeuralType(('B', 'T'), LabelsType()), - } - return { - "xq": NeuralType(('B', 'D', 'T', 'H'), SpectrogramType()), - "xid": NeuralType(('B', 'T', 'H'), LabelsType()), - } - - @typecheck() - def forward(self, input_signal): - """ - Args: - input_signal: input features of shape (B, T, D) or (B, D, T) - Returns: - xq: quantized features of shape (B, T, D, N) or (B, D, T, N) - xid: quantized tokens of shape (B, T, N) - """ - if not self.time_ahead: - # (B, D, T) -> (B, T, D) - input_signal = input_signal.transpose(1, 2) - - B, T, _ = input_signal.size() - - if self.combine_time_steps > 1: - input_signal = input_signal.contiguous().reshape(B, T // self.combine_time_steps, -1) - T = T // self.combine_time_steps - - # (B, T, D) -> (B, T, num_books*code_dim) - x = self.proj(input_signal) - - # normalize each feature vector - # (B, T, num_books*code_dim) -> (B, T, num_books, code_dim) - x = F.normalize(x.view(B, T, self.num_books, self.code_dim), dim=-1) - - # get tokens (xid) of shape (B, T, num_books) - if self.dist_fn == "cosine": - # (B, T, num_books, code_dim) -> (B, T, num_books, num_classes) - xid = torch.einsum('btdh,dch->btdc', x, self.codebooks) - # (B, T, num_books, num_classes) -> (B, T, num_books) - xid = xid.max(dim=-1)[1] - elif self.dist_fn == "l2": - # (B, T, num_books, code_dim) -> (B, T, num_books, code_dim, num_classes) - xid = x.unsqueeze(-1) - self.codebooks.transpose(1, 2).unsqueeze(0).unsqueeze(0) - xid = xid.norm(dim=-2).argmin(dim=-1) - else: - raise ValueError(f"Unknown distance function {self.dist_fn}, must be one of {self.DIST_FN_LIST}") - - # xid2: (B, T, num_books) -> (B, T, num_books) - xid2 = xid + self.num_classes * torch.arange(self.num_books, device=xid.device).unsqueeze(0).unsqueeze(0) - # xid2: (B, T, num_books) -> (B*num_books, T) - xid2 = xid2.transpose(1, 2).contiguous().view(-1, T) - - # get quantized vector (xq) of shape (B, T, code_dim, num_books) - # codebook: (num_books, num_classes, code_dim) -> (num_books*num_classes, code_dim) - xq = F.embedding(xid2.view(-1), self.codebooks.view(-1, self.code_dim)).view( - B, T, self.code_dim, self.num_books - ) - - if not self.time_ahead: - # (B, T, D) -> (B, D, T) - xq = xq.transpose(1, 2) - - if self.num_books == 1 and self.squeeze_single: - xq = xq.squeeze(-1) - xid = xid.squeeze(-1) - - return xq, xid diff --git a/nemo/collections/asr/modules/transformer/__init__.py b/nemo/collections/asr/modules/transformer/__init__.py deleted file mode 100644 index f3cea616f00ffe5a34559a331a1ab6061f6e0bef..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/transformer/__init__.py +++ /dev/null @@ -1,54 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.asr.modules.transformer.bridge_encoders import BridgeEncoder -from nemo.collections.asr.modules.transformer.perceiver_encoders import PerceiverEncoder -from nemo.collections.asr.modules.transformer.transformer_bottleneck import ( - NeMoTransformerBottleneckConfig, - NeMoTransformerBottleneckDecoderConfig, - NeMoTransformerBottleneckEncoderConfig, - TransformerBottleneckEncoderNM, -) -from nemo.collections.asr.modules.transformer.transformer_decoders import TransformerDecoder -from nemo.collections.asr.modules.transformer.transformer_encoders import TransformerEncoder -from nemo.collections.asr.modules.transformer.transformer_generators import ( - BeamSearchSequenceGenerator, - BeamSearchSequenceGeneratorWithFusionModels, - BeamSearchSequenceGeneratorWithLanguageModel, - EnsembleBeamSearchSequenceGenerator, - GreedySequenceGenerator, - TopKSequenceGenerator, -) -from nemo.collections.asr.modules.transformer.transformer_modules import AttentionBridge, TransformerEmbedding -from nemo.collections.asr.modules.transformer.transformer_utils import get_nemo_transformer - -__all__ = [ - "BridgeEncoder", - "PerceiverEncoder", - "NeMoTransformerBottleneckConfig", - "NeMoTransformerBottleneckDecoderConfig", - "NeMoTransformerBottleneckEncoderConfig", - "TransformerBottleneckEncoderNM", - "TransformerDecoder", - "TransformerEncoder", - "BeamSearchSequenceGenerator", - "BeamSearchSequenceGeneratorWithLanguageModel", - "BeamSearchSequenceGeneratorWithFusionModels", - "EnsembleBeamSearchSequenceGenerator", - "GreedySequenceGenerator", - "TopKSequenceGenerator", - "AttentionBridge", - "TransformerEmbedding", - "get_nemo_transformer", -] diff --git a/nemo/collections/asr/modules/transformer/bridge_encoders.py b/nemo/collections/asr/modules/transformer/bridge_encoders.py deleted file mode 100644 index 5c72d27b9ebf9a618c93346cf6b6371c58df6b45..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/transformer/bridge_encoders.py +++ /dev/null @@ -1,141 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import torch - -from nemo.collections.asr.modules.transformer.transformer_encoders import TransformerEncoder -from nemo.collections.asr.modules.transformer.transformer_modules import AttentionBridge - -__all__ = ["BridgeEncoder"] - - -class BridgeEncoder(torch.nn.Module): - def __init__( - self, - num_layers: int, - hidden_size: int, - inner_size: int, - mask_future: bool = False, - num_attention_heads: int = 1, - attn_score_dropout: float = 0.0, - attn_layer_dropout: float = 0.0, - ffn_dropout: float = 0.0, - hidden_act: str = "relu", - pre_ln: bool = False, - pre_ln_final_layer_norm: bool = True, - hidden_steps: int = 32, - hidden_init_method: str = "default", - hidden_blocks: int = 0, - ): - super().__init__() - - self._hidden_steps = hidden_steps - self._hidden_init_method = hidden_init_method - self._hidden_blocks = hidden_blocks - - if self._hidden_init_method == "default": - self._hidden_init_method = "enc_shared" - - if self.hidden_init_method not in self.supported_init_methods: - raise ValueError( - "Unknown hidden_init_method = {hidden_init_method}, supported methods are {supported_init_methods}".format( - hidden_init_method=self.hidden_init_method, supported_init_methods=self.supported_init_methods, - ) - ) - - # attention bridge - self.att_bridge = AttentionBridge(hidden_size=hidden_size, k=hidden_steps, bridge_size=inner_size,) - - if self.hidden_init_method == "enc": - self.init_hidden_enc = TransformerEncoder( - num_layers=num_layers, - hidden_size=hidden_size, - inner_size=inner_size, - mask_future=mask_future, - num_attention_heads=num_attention_heads, - attn_score_dropout=attn_score_dropout, - attn_layer_dropout=attn_layer_dropout, - ffn_dropout=ffn_dropout, - hidden_act=hidden_act, - pre_ln=pre_ln, - pre_ln_final_layer_norm=pre_ln_final_layer_norm, - ) - - # self attention - self.hidden_enc = TransformerEncoder( - num_layers=num_layers, - hidden_size=hidden_size, - inner_size=inner_size, - mask_future=mask_future, - num_attention_heads=num_attention_heads, - attn_score_dropout=attn_score_dropout, - attn_layer_dropout=attn_layer_dropout, - ffn_dropout=ffn_dropout, - hidden_act=hidden_act, - pre_ln=pre_ln, - pre_ln_final_layer_norm=pre_ln_final_layer_norm, - ) - - @property - def supported_init_methods(self): - return ["enc_shared", "identity", "enc"] - - @property - def hidden_steps(self): - return self._hidden_steps - - @property - def hidden_blocks(self): - return self._hidden_blocks - - @property - def hidden_init_method(self): - return self._hidden_init_method - - def forward(self, encoder_states, encoder_mask): - """ - Args: - encoder_states: output of the encoder (B x L_enc x H) - encoder_mask: encoder inputs mask (B x L_enc) - """ - # self-attention over input - if self.hidden_init_method == "enc_shared": - residual = encoder_states - hidden_states = self.hidden_enc(encoder_states=encoder_states, encoder_mask=encoder_mask) - # residual connection - hidden_states += residual - elif self.hidden_init_method == "identity": - hidden_states = encoder_states - elif self.hidden_init_method == "enc": - residual = encoder_states - hidden_states = self.init_hidden_enc(encoder_states=encoder_states, encoder_mask=encoder_mask) - # residual connection - hidden_states += residual - - # project encoder states to a fixed steps hidden using k attention heads - hidden_states = self.att_bridge(hidden=hidden_states, hidden_mask=encoder_mask) - - # all hidden values are active - hidden_mask = torch.ones( - encoder_states.shape[0], self._hidden_steps, dtype=encoder_mask.dtype, device=encoder_mask.device - ) - - # apply self-attention over fixed-size hidden_states - for block in range(self._hidden_blocks): - residual = hidden_states - hidden_states = self.hidden_enc(encoder_states=hidden_states, encoder_mask=hidden_mask) - # residual connection - hidden_states += residual - - return hidden_states, hidden_mask diff --git a/nemo/collections/asr/modules/transformer/decoder_module.py b/nemo/collections/asr/modules/transformer/decoder_module.py deleted file mode 100644 index d1cb8ac9b1f049c93f3b679ae0a56962012f6e06..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/transformer/decoder_module.py +++ /dev/null @@ -1,59 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from abc import ABC -from typing import Any, Dict, Optional - -from nemo.core.classes import NeuralModule -from nemo.core.neural_types import ChannelType, EncodedRepresentation, MaskType, NeuralType - -__all__ = ['DecoderModule'] - - -class DecoderModule(NeuralModule, ABC): - """ Base class for decoder neural module to be used in NLP models. """ - - @property - def input_types(self) -> Optional[Dict[str, NeuralType]]: - return { - "input_ids": NeuralType(('B', 'T'), ChannelType()), - "decoder_mask": NeuralType(('B', 'T'), MaskType(), optional=True), - "encoder_embeddings": NeuralType(('B', 'T', 'D'), ChannelType(), optional=True), - "encoder_mask": NeuralType(('B', 'T'), MaskType(), optional=True), - "decoder_mems": NeuralType(('B', 'D', 'T', 'D'), EncodedRepresentation(), optional=True), - } - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - return {"last_hidden_states": NeuralType(('B', 'T', 'D'), ChannelType())} - - @property - def hidden_size(self) -> Optional[int]: - raise NotImplementedError - - @property - def vocab_size(self) -> Optional[int]: - raise NotImplementedError - - @property - def embedding(self) -> Optional[Any]: - raise NotImplementedError - - @property - def decoder(self) -> Optional[Any]: - raise NotImplementedError - - @property - def max_sequence_length(self) -> Optional[int]: - raise NotImplementedError diff --git a/nemo/collections/asr/modules/transformer/encoder_module.py b/nemo/collections/asr/modules/transformer/encoder_module.py deleted file mode 100644 index bd3912e0e693e1e3f5f32e7702bf894445a77485..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/transformer/encoder_module.py +++ /dev/null @@ -1,40 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from abc import ABC -from typing import Dict, Optional - -from nemo.core.classes import NeuralModule -from nemo.core.neural_types import ChannelType, MaskType, NeuralType - -__all__ = ['EncoderModule'] - - -class EncoderModule(NeuralModule, ABC): - """ Base class for encoder neural module to be used in NLP models. """ - - @property - def input_types(self) -> Optional[Dict[str, NeuralType]]: - return { - "input_ids": NeuralType(('B', 'T'), ChannelType()), - "encoder_mask": NeuralType(('B', 'T'), MaskType()), - } - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - return {"last_hidden_states": NeuralType(('B', 'T', 'D'), ChannelType())} - - @property - def hidden_size(self) -> Optional[int]: - raise NotImplementedError diff --git a/nemo/collections/asr/modules/transformer/perceiver_encoders.py b/nemo/collections/asr/modules/transformer/perceiver_encoders.py deleted file mode 100644 index e836e20be7bc6222b1612ec769069cd7c9e9023a..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/transformer/perceiver_encoders.py +++ /dev/null @@ -1,174 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import copy - -import torch - -from nemo.collections.asr.modules.transformer.transformer_decoders import TransformerDecoder -from nemo.collections.asr.modules.transformer.transformer_encoders import TransformerEncoder -from nemo.collections.asr.modules.transformer.transformer_modules import AttentionBridge - -__all__ = ["PerceiverEncoder"] - - -class PerceiverEncoder(torch.nn.Module): - def __init__( - self, - num_layers: int, - hidden_size: int, - inner_size: int, - mask_future: bool = False, - num_attention_heads: int = 1, - attn_score_dropout: float = 0.0, - attn_layer_dropout: float = 0.0, - ffn_dropout: float = 0.0, - hidden_act: str = "relu", - pre_ln: bool = False, - pre_ln_final_layer_norm: bool = True, - hidden_steps: int = 32, - hidden_init_method: str = "default", - hidden_blocks: int = 2, - ): - super().__init__() - - self._hidden_steps = hidden_steps - self._hidden_init_method = hidden_init_method - self._hidden_blocks = hidden_blocks - - if self._hidden_init_method == "default": - self._hidden_init_method = "params" - - if self.hidden_init_method not in self.supported_init_methods: - raise ValueError( - "Unknown hidden_init_method = {hidden_init_method}, supported methods are {supported_init_methods}".format( - hidden_init_method=self.hidden_init_method, supported_init_methods=self.supported_init_methods, - ) - ) - - diagonal = 0 if mask_future else None - - if self.hidden_init_method == "params": - # learnable initial hidden values - self.init_hidden = torch.nn.Parameter(torch.nn.init.xavier_normal_(torch.empty(hidden_steps, hidden_size))) - self.init_cross_att = TransformerDecoder( - num_layers=1, - hidden_size=hidden_size, - inner_size=inner_size, - num_attention_heads=num_attention_heads, - attn_score_dropout=attn_score_dropout, - attn_layer_dropout=attn_layer_dropout, - ffn_dropout=ffn_dropout, - hidden_act=hidden_act, - pre_ln=pre_ln, - pre_ln_final_layer_norm=pre_ln_final_layer_norm, - ) - self.init_cross_att.diagonal = diagonal - elif self.hidden_init_method == "bridge": - # initialize latent with attention bridge - self.att_bridge = AttentionBridge(hidden_size=hidden_size, k=hidden_steps, bridge_size=inner_size,) - - # cross-attention encoder - layer = TransformerDecoder( - num_layers=1, - hidden_size=hidden_size, - inner_size=inner_size, - num_attention_heads=num_attention_heads, - attn_score_dropout=attn_score_dropout, - attn_layer_dropout=attn_layer_dropout, - ffn_dropout=ffn_dropout, - hidden_act=hidden_act, - pre_ln=pre_ln, - pre_ln_final_layer_norm=pre_ln_final_layer_norm, - ) - layer.diagonal = diagonal - self.cross_att_layers = torch.nn.ModuleList([copy.deepcopy(layer) for _ in range(hidden_blocks)]) - - # self-attention encoder - layer = TransformerEncoder( - num_layers=num_layers, - hidden_size=hidden_size, - inner_size=inner_size, - mask_future=mask_future, - num_attention_heads=num_attention_heads, - attn_score_dropout=attn_score_dropout, - attn_layer_dropout=attn_layer_dropout, - ffn_dropout=ffn_dropout, - hidden_act=hidden_act, - pre_ln=pre_ln, - pre_ln_final_layer_norm=pre_ln_final_layer_norm, - ) - self.self_att_layers = torch.nn.ModuleList([copy.deepcopy(layer) for _ in range(hidden_blocks)]) - - @property - def supported_init_methods(self): - return ["params", "bridge"] - - @property - def hidden_steps(self): - return self._hidden_steps - - @property - def hidden_blocks(self): - return self._hidden_blocks - - @property - def hidden_init_method(self): - return self._hidden_init_method - - def forward(self, encoder_states, encoder_mask): - """ - Args: - encoder_states: output of the encoder (B x L_enc x H) - encoder_mask: encoder inputs mask (B x L_enc) - """ - # all hidden values are active - hidden_mask = torch.ones( - encoder_states.shape[0], self._hidden_steps, dtype=encoder_mask.dtype, device=encoder_mask.device - ) - - # initialize hidden state - if self._hidden_init_method == "params": - # initialize latent with learned parameters - hidden_states = self.init_hidden.unsqueeze(0).expand(encoder_states.shape[0], -1, -1) - hidden_states = self.init_cross_att( - decoder_states=hidden_states, - decoder_mask=hidden_mask, - encoder_states=encoder_states, - encoder_mask=encoder_mask, - ) - elif self._hidden_init_method == "bridge": - # initialize latent with attention bridge - hidden_states = self.att_bridge(hidden=encoder_states, hidden_mask=encoder_mask,) - - # apply block (cross-attention, self-attention) multiple times - # for block in range(self._hidden_blocks): - for self_att, cross_att in zip(self.self_att_layers, self.cross_att_layers): - residual = hidden_states - - # cross attention of hidden over encoder states - hidden_states = cross_att( - decoder_states=hidden_states, - decoder_mask=hidden_mask, - encoder_states=encoder_states, - encoder_mask=encoder_mask, - ) - - # self-attention over hidden - hidden_states = self_att(encoder_states=hidden_states, encoder_mask=hidden_mask,) - - # residual connection - hidden_states += residual - - return hidden_states, hidden_mask diff --git a/nemo/collections/asr/modules/transformer/reduction_encoders.py b/nemo/collections/asr/modules/transformer/reduction_encoders.py deleted file mode 100644 index 0c3355b0949f54c220814131509a209956245d9c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/transformer/reduction_encoders.py +++ /dev/null @@ -1,148 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import copy - -import torch - -from nemo.collections.asr.modules.transformer.transformer_encoders import TransformerEncoder - -__all__ = ["PoolingEncoder"] - - -class PoolingEncoder(torch.nn.Module): - - _SUPPORTED_ARCH = ["max", "avg"] - - def __init__( - self, - num_layers: int, - hidden_size: int, - inner_size: int, - mask_future: bool = False, - num_attention_heads: int = 1, - attn_score_dropout: float = 0.0, - attn_layer_dropout: float = 0.0, - ffn_dropout: float = 0.0, - hidden_act: str = "relu", - pre_ln: bool = False, - pre_ln_final_layer_norm: bool = True, - hidden_steps: int = 4, - hidden_init_method: str = "default", - hidden_blocks: int = 2, - pooling_type: str = "max", - ): - super().__init__() - - # minimal steps to allow reduction - self._hidden_steps = hidden_steps - self._hidden_init_method = hidden_init_method - self._hidden_blocks = hidden_blocks - self._pooling_type = pooling_type - - if self._hidden_steps < 2: - raise ValueError("Expected hidden_steps >= 2 but received hidden_steps = {self._hidden_steps}") - - if self.hidden_init_method not in self.supported_init_methods: - raise ValueError( - "Unknown hidden_init_method = {hidden_init_method}, supported methods are {supported_init_methods}".format( - hidden_init_method=self.hidden_init_method, supported_init_methods=self.supported_init_methods, - ) - ) - - if self._pooling_type not in self.supported_arch: - raise ValueError(f"Unknown pooling_type = {pooling_type}. Available values = {self.supported_arch}") - - # self-attention encoder - layer = TransformerEncoder( - num_layers=num_layers, - hidden_size=hidden_size, - inner_size=inner_size, - mask_future=mask_future, - num_attention_heads=num_attention_heads, - attn_score_dropout=attn_score_dropout, - attn_layer_dropout=attn_layer_dropout, - ffn_dropout=ffn_dropout, - hidden_act=hidden_act, - pre_ln=pre_ln, - pre_ln_final_layer_norm=pre_ln_final_layer_norm, - ) - self.self_att_layers = torch.nn.ModuleList([copy.deepcopy(layer) for _ in range(hidden_blocks)]) - - self.pooling = self._build_pooling_module() - - def _build_pooling_module(self): - """ - Returns pooling module. - Allows to override for child classes. - """ - if self._pooling_type == "max": - pooling = torch.nn.MaxPool1d(kernel_size=2, stride=2) - elif self._pooling_type == "avg": - pooling = torch.nn.AvgPool1d(kernel_size=2, stride=2) - - return pooling - - @property - def supported_arch(self): - return self._SUPPORTED_ARCH - - @property - def supported_init_methods(self): - return ["default"] - - @property - def hidden_steps(self): - return self._hidden_steps - - @property - def hidden_blocks(self): - return self._hidden_blocks - - @property - def hidden_init_method(self): - return self._hidden_init_method - - def forward(self, encoder_states, encoder_mask): - """ - Args: - encoder_states: output of the encoder (B x L_enc x H) - encoder_mask: encoder inputs mask (B x L_enc) - """ - # initialize hidden state - hidden_mask = encoder_mask - hidden_states = encoder_states - - # apply block (self-attention, max-pool) multiple times - for self_att in self.self_att_layers: - residual = hidden_states - - # self-attention over hidden - hidden_states = self_att(encoder_states=hidden_states, encoder_mask=hidden_mask) - - hidden_states += residual - - # max pool reduction if possible - if hidden_states.shape[1] >= self.hidden_steps: - # max pool hidden states - hidden_states = hidden_states.permute(0, 2, 1) - hidden_states = self.pooling(hidden_states) - hidden_states = hidden_states.permute(0, 2, 1) - - # max pool mask - hidden_mask = ( - self.pooling(hidden_mask.unsqueeze(0).type_as(hidden_states)).squeeze(0).type_as(hidden_mask) - ) - - return hidden_states, hidden_mask diff --git a/nemo/collections/asr/modules/transformer/text_generation.py b/nemo/collections/asr/modules/transformer/text_generation.py deleted file mode 100644 index a261e925691f291f72c16ba7d5b0d8f5ee0896f1..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/transformer/text_generation.py +++ /dev/null @@ -1,101 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import sys -from typing import List, Tuple, Union - -from torch import Tensor - -if sys.version_info >= (3, 8): - from typing import TypedDict -else: - from typing_extensions import TypedDict - - -class LengthParam(TypedDict): - max_length: int # The maximum length of the sequence to be generated. - min_length: int # The minimum length of the sequence to be generated. - - -class SamplingParam(TypedDict): - use_greedy: bool # Whether or not to use sampling ; use greedy decoding otherwise - temperature: float # sampling temperature - top_k: int # The number of highest probability vocabulary tokens to keep for top-k-filtering. - top_p: float # If set to float < 1, only the most probable tokens with probabilities that add up to top_p or higher are kept for generation. - repetition_penalty: float # The parameter for repetition penalty. 1.0 means no penalty. - add_BOS: bool # add the bos token at the begining of the prompt - all_probs: bool # whether return the log prob for all the tokens in vocab - compute_logprob: bool # a flag used to compute logprob of all the input text, a very special case of running inference, default False - - -class OutputType(TypedDict): - sentences: List[str] # output sentences - tokens: List[List[str]] # output sentences borken into tokens - logprob: List[List[float]] # log prob of generated tokens - full_logprob: List[List[float]] # log prob of all the tokens in the vocab - token_ids: List[List[int]] # output sentence token ids - offsets: List[List[int]] # list of tokens start positions in text - - -class TextGeneration: - """ - Interface for all text generation models. - """ - - def generate( - self, - inputs: Union[List[str], Tuple[Tensor, Tensor], List[dict]], - length_params: LengthParam, - sampling_params: SamplingParam = None, - ) -> OutputType: - """ - Public method to generate text. - - Args: - inputs (Union[List[str], Tensor, List[dict]]): - Can be one of the 3 types: - 1. List of strings. Each element of the list provides input prompt. The model will apply tokenizer on it. - E.g [‘sentence’, ‘sentence2’ … ] - 2. Tuple of Pytorch Tensors (context_tokens, context_lengths). The `context_tokens` has shape (batch_size, seq_length), it's the batched sequences of tokens used as a prompst for the generation or as model inputs to the encoder. - The generative model will skip the tokenization and padding step. The `context_lengths` has shape (batch_size,), it indicates the length of the context tokens for each of the input sequences. - E.g. ( torch.tensor([[23,5234,23,35,…], [223,323,23,23232,232,...] …]), torch.tensor([20, 30, …])) - 3. List of python dict objects. Used for prompt/p-tuning inputs where a set of key-value pairs are converted into input token embeddings for the model. - E.g. [{"prompt-tag": "sentiment", "sentence": "this is a good movie"}, - {"prompt-tag": "qa", "context": "some context text", "question": "a simple question"} ... ] - where 'prompt-tag' is used to identify the type of NLP task to solve. - length_params (LengthParam): - a dictionary type which controls the sampling length. - max_length: int, The maximum length of the sequence to be generated. - min_length: int, The minimum length of the sequence to be generated. - If None, max_length is set to 30, and min_length is set to None - sampling_params (SamplingParam): - a dictionary type which contains the parameters for text sampling. It has the following keys - use_greedy: bool, Whether or not to use sampling ; use greedy decoding otherwise - top_k: int, The number of highest probability vocabulary tokens to keep for top-k-filtering. - top_p: float, If set to float < 1, only the most probable tokens with probabilities that add up to top_p or higher are kept for generation. - repetition_penalty: float, The parameter for repetition penalty. 1.0 means no penalty. - add_BOS: bool, Whether add the bos token at the begining of the prompt - all_probs: bool # whether return the log prob for all the tokens in vocab - compute_logprob: bool # a flag used to compute logprob of all the input text, a very special case of running inference, default False - Default None, If it is None, use_greedy will be "True". - Returns: - OutputType: It generates the output in a dictionary type. It has the following keys: - sentences: List[str], output sentences - tokens: List[List[str]], output sentences borken into tokens - logprob: List[List[float]], log prob of generated tokens - full_logprob: List[List[float]], log prob of all the tokens in the vocab - token_ids: List[List[int]], output sentence token ids - offsets: List[List[int]] # list of tokens start positions in text - """ - raise NotImplementedError("please implement this method") diff --git a/nemo/collections/asr/modules/transformer/transformer.py b/nemo/collections/asr/modules/transformer/transformer.py deleted file mode 100644 index b96c481f837fc52d29b570fa783b8f4786a8c323..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/transformer/transformer.py +++ /dev/null @@ -1,318 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from dataclasses import dataclass -from typing import Dict, List, Optional - -import torch -from omegaconf.omegaconf import MISSING, DictConfig - -from nemo.collections.asr.modules.transformer.decoder_module import DecoderModule -from nemo.collections.asr.modules.transformer.encoder_module import EncoderModule -from nemo.collections.asr.modules.transformer.transformer_decoders import TransformerDecoder, TransformerDecoderAdapter -from nemo.collections.asr.modules.transformer.transformer_encoders import TransformerEncoder -from nemo.collections.asr.modules.transformer.transformer_modules import TransformerEmbedding -from nemo.collections.asr.parts.utils import adapter_utils -from nemo.core.classes.common import typecheck -from nemo.core.classes.exportable import Exportable -from nemo.core.classes.mixins import adapter_mixins -from nemo.core.neural_types import ChannelType, NeuralType - - -@dataclass -class NeMoTransformerConfig: - # must be configured by the user - hidden_size: int = MISSING - num_layers: int = MISSING - inner_size: int = MISSING - num_attention_heads: int = MISSING - - # embedding - max_sequence_length: int = 512 - num_token_types: int = 2 - embedding_dropout: float = 0.0 - learn_positional_encodings: bool = False - - # transformer - ffn_dropout: float = 0.0 - attn_score_dropout: float = 0.0 - attn_layer_dropout: float = 0.0 - hidden_act: str = 'relu' - pre_ln: bool = False - pre_ln_final_layer_norm: bool = True - - # named model arguments - library: str = 'nemo' - model_name: Optional[str] = None - pretrained: bool = False - - -@dataclass -class NeMoTransformerEncoderConfig(NeMoTransformerConfig): - mask_future: bool = False - - -@dataclass -class NeMoTransformerDecoderConfig(NeMoTransformerConfig): - r2l: bool = False - - -class TransformerEncoderNM(EncoderModule, Exportable): - def __init__( - self, - vocab_size: int, - hidden_size: int, - num_layers: int, - inner_size: int, - num_attention_heads: int, - max_sequence_length: int = 512, - num_token_types: int = 2, - embedding_dropout: float = 0.0, - learn_positional_encodings: bool = False, - ffn_dropout: float = 0.0, - attn_score_dropout: float = 0.0, - attn_layer_dropout: float = 0.0, - hidden_act: str = 'relu', - mask_future: bool = False, - pre_ln: bool = False, - pre_ln_final_layer_norm: bool = True, - ): - super().__init__() - - self._vocab_size = vocab_size - self._hidden_size = hidden_size - self._max_sequence_length = max_sequence_length - - self._embedding = TransformerEmbedding( - vocab_size=self._vocab_size, - hidden_size=self._hidden_size, - max_sequence_length=max_sequence_length, - num_token_types=num_token_types, - embedding_dropout=embedding_dropout, - learn_positional_encodings=learn_positional_encodings, - ) - - self._encoder = TransformerEncoder( - hidden_size=self._hidden_size, - num_layers=num_layers, - inner_size=inner_size, - num_attention_heads=num_attention_heads, - ffn_dropout=ffn_dropout, - attn_score_dropout=attn_score_dropout, - attn_layer_dropout=attn_layer_dropout, - hidden_act=hidden_act, - mask_future=mask_future, - pre_ln=pre_ln, - pre_ln_final_layer_norm=pre_ln_final_layer_norm, - ) - - @typecheck() - def forward(self, input_ids, encoder_mask): - embeddings = self._embedding(input_ids=input_ids) - encoder_hidden_states = self._encoder(encoder_states=embeddings, encoder_mask=encoder_mask) - return encoder_hidden_states - - @property - def hidden_size(self): - return self._hidden_size - - @property - def vocab_size(self): - return self._vocab_size - - @property - def max_sequence_length(self): - return self._max_sequence_length - - @property - def embedding(self): - return self._embedding - - @property - def encoder(self): - return self._encoder - - def input_example(self, max_batch=1, max_dim=256): - """ - Generates input examples for tracing etc. - Returns: - A tuple of input examples. - """ - sample = next(self.parameters()) - sz = (max_batch, max_dim) - input_ids = torch.randint(low=0, high=2048, size=sz, device=sample.device) - encoder_mask = torch.randint(low=0, high=1, size=sz, device=sample.device) - return tuple([input_ids, encoder_mask]) - - -class TransformerDecoderNM(DecoderModule, Exportable): - DECODER_TYPE: type = TransformerDecoder - - def __init__( - self, - vocab_size: int, - hidden_size: int, - num_layers: int, - inner_size: int, - num_attention_heads: int, - max_sequence_length: int = 512, - num_token_types: int = 2, - embedding_dropout: float = 0.0, - learn_positional_encodings: bool = False, - ffn_dropout: float = 0.0, - attn_score_dropout: float = 0.0, - attn_layer_dropout: float = 0.0, - hidden_act: str = 'relu', - pre_ln: bool = False, - pre_ln_final_layer_norm: bool = True, - ): - super().__init__() - - self._vocab_size = vocab_size - self._hidden_size = hidden_size - self._max_sequence_length = max_sequence_length - self.num_states = num_layers + 1 - self.return_mems = False - if pre_ln_final_layer_norm: - self.num_states += 1 - - self._embedding = TransformerEmbedding( - vocab_size=self.vocab_size, - hidden_size=self.hidden_size, - max_sequence_length=max_sequence_length, - num_token_types=num_token_types, - embedding_dropout=embedding_dropout, - learn_positional_encodings=learn_positional_encodings, - ) - - self._decoder = self.DECODER_TYPE( - hidden_size=self.hidden_size, - num_layers=num_layers, - inner_size=inner_size, - num_attention_heads=num_attention_heads, - ffn_dropout=ffn_dropout, - attn_score_dropout=attn_score_dropout, - attn_layer_dropout=attn_layer_dropout, - hidden_act=hidden_act, - pre_ln=pre_ln, - pre_ln_final_layer_norm=pre_ln_final_layer_norm, - ) - - @typecheck() - def forward( - self, - input_ids, - decoder_mask, - encoder_embeddings, - encoder_mask, - decoder_mems=None, - ): - start_pos = 0 - if decoder_mems is not None: - start_pos = input_ids.shape[1] - 1 - input_ids = input_ids[:, -1:] - decoder_mask = decoder_mask[:, -1:] - decoder_mems = torch.transpose(decoder_mems, 0, 1) - decoder_embeddings = self._embedding(input_ids=input_ids, start_pos=start_pos) - decoder_hidden_states, xatt_scores_list = self._decoder( - decoder_states=decoder_embeddings, - decoder_mask=decoder_mask, - encoder_states=encoder_embeddings, - encoder_mask=encoder_mask, - decoder_mems_list=decoder_mems, - return_mems=self.return_mems, - return_mems_as_list=False, - ) - if self.return_mems: - decoder_hidden_states = torch.transpose(decoder_hidden_states, 0, 1) - return decoder_hidden_states - - @property - def hidden_size(self): - return self._hidden_size - - @property - def vocab_size(self): - return self._vocab_size - - @property - def max_sequence_length(self): - return self._max_sequence_length - - @property - def embedding(self): - return self._embedding - - @property - def decoder(self): - return self._decoder - - def input_example(self, max_batch=1, max_dim=256): - """ - Generates input examples for tracing etc. - Returns: - A tuple of input examples. - """ - sample = next(self.parameters()) - sz = (max_batch, max_dim) - input_ids = torch.randint(low=0, high=2048, size=sz, device=sample.device) - encoder_mask = torch.randint(low=0, high=1, size=sz, device=sample.device) - mem_size = [max_batch, self.num_states, max_dim - 1, self._hidden_size] - decoder_mems = torch.rand(mem_size, device=sample.device) - return tuple([input_ids, encoder_mask, self._embedding(input_ids), encoder_mask, decoder_mems]) - - def _prepare_for_export(self, **kwargs): - self._decoder.diagonal = None - self.return_mems = True - super()._prepare_for_export(**kwargs) - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - if self.return_mems: - return {"last_hidden_states": NeuralType(('B', 'D', 'T', 'D'), ChannelType())} - else: - return {"last_hidden_states": NeuralType(('B', 'T', 'D'), ChannelType())} - - -class TransformerDecoderNMAdapter(TransformerDecoderNM, adapter_mixins.AdapterModuleMixin): - DECODER_TYPE: type = TransformerDecoderAdapter - - # Higher level forwarding - def add_adapter(self, name: str, cfg: dict): - cfg = self._update_adapter_cfg_input_dim(cfg) - self._decoder.add_adapter(name, cfg) # type: adapter_mixins.AdapterModuleMixin - - def is_adapter_available(self) -> bool: - return self._decoder.is_adapter_available() # type: adapter_mixins.AdapterModuleMixin - - def set_enabled_adapters(self, name: Optional[str] = None, enabled: bool = True): - self._decoder.set_enabled_adapters(name=name, enabled=enabled) # # type: adapter_mixins.AdapterModuleMixin - - def get_enabled_adapters(self) -> List[str]: - names = set([]) - names.update(self._decoder.get_enabled_adapters()) # type: adapter_mixins.AdapterModuleMixin - - names = sorted(list(names)) - return names - - def _update_adapter_cfg_input_dim(self, cfg: DictConfig): - cfg = adapter_utils.update_adapter_cfg_input_dim(self, cfg, module_dim=self._hidden_size) - return cfg - - -""" -Register any additional information -""" -if adapter_mixins.get_registered_adapter(TransformerDecoderNM) is None: - adapter_mixins.register_adapter(base_class=TransformerDecoderNM, adapter_class=TransformerDecoderNMAdapter) diff --git a/nemo/collections/asr/modules/transformer/transformer_bottleneck.py b/nemo/collections/asr/modules/transformer/transformer_bottleneck.py deleted file mode 100644 index c463b4de1c70418c01bd944bb2d22d366f1e2df0..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/transformer/transformer_bottleneck.py +++ /dev/null @@ -1,336 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from dataclasses import dataclass -from typing import Dict, Optional - -from nemo.collections.asr.modules.transformer.bridge_encoders import BridgeEncoder -from nemo.collections.asr.modules.transformer.perceiver_encoders import PerceiverEncoder -from nemo.collections.asr.modules.transformer.reduction_encoders import PoolingEncoder -from nemo.collections.asr.modules.transformer.transformer import ( - NeMoTransformerConfig, - TransformerDecoderNM, - TransformerEncoderNM, -) -from nemo.core.classes.common import typecheck -from nemo.core.neural_types import MaskType, NeuralType -from nemo.core.neural_types.elements import BoolType - -__all__ = [ - "NeMoTransformerBottleneckConfig", - "NeMoTransformerBottleneckEncoderConfig", - "NeMoTransformerBottleneckDecoderConfig", - "TransformerBottleneckEncoderNM", -] - - -@dataclass -class NeMoTransformerBottleneckConfig(NeMoTransformerConfig): - # architecture details (default is no bottleneck) - arch: str = '' - hidden_steps: int = -1 - hidden_blocks: int = 1 - hidden_init_method: str = "params" - - -@dataclass -class NeMoTransformerBottleneckEncoderConfig(NeMoTransformerBottleneckConfig): - mask_future: bool = False - # change return_mask to False to return hidden states only (default for non-bottleneck encoder) - return_mask: bool = True - - -@dataclass -class NeMoTransformerBottleneckDecoderConfig(NeMoTransformerBottleneckConfig): - r2l: bool = False - - -class TransformerBottleneckEncoderNM(TransformerEncoderNM): - - _SUPPORTED_ARCH = ["seq2seq", "bridge", "perceiver", "max_pool", "avg_pool"] - - def __init__( - self, - vocab_size: int, - hidden_size: int, - num_layers: int, - inner_size: int, - num_attention_heads: int, - max_sequence_length: int = 512, - num_token_types: int = 2, - embedding_dropout: float = 0.0, - learn_positional_encodings: bool = False, - ffn_dropout: float = 0.0, - attn_score_dropout: float = 0.0, - attn_layer_dropout: float = 0.0, - hidden_act: str = 'relu', - mask_future: bool = False, - pre_ln: bool = False, - pre_ln_final_layer_norm: bool = True, - arch: str = '', - hidden_steps: int = -1, - hidden_blocks: int = 1, - hidden_init_method: str = "default", - # default whether forward() method returns hidden or (hidden, mask) - return_mask=True, - ): - super().__init__( - vocab_size=vocab_size, - hidden_size=hidden_size, - num_layers=num_layers, - inner_size=inner_size, - num_attention_heads=num_attention_heads, - max_sequence_length=max_sequence_length, - num_token_types=num_token_types, - embedding_dropout=embedding_dropout, - learn_positional_encodings=learn_positional_encodings, - ffn_dropout=ffn_dropout, - attn_score_dropout=attn_score_dropout, - attn_layer_dropout=attn_layer_dropout, - hidden_act=hidden_act, - mask_future=mask_future, - pre_ln=pre_ln, - pre_ln_final_layer_norm=pre_ln_final_layer_norm, - ) - - self._arch = arch - self._return_mask = return_mask - - # replace encoder - self._encoder = self._build_encoder( - arch=arch, - hidden_steps=hidden_steps, - hidden_blocks=hidden_blocks, - hidden_init_method=hidden_init_method, - hidden_size=hidden_size, - num_layers=num_layers, - inner_size=inner_size, - num_attention_heads=num_attention_heads, - ffn_dropout=ffn_dropout, - attn_score_dropout=attn_score_dropout, - attn_layer_dropout=attn_layer_dropout, - hidden_act=hidden_act, - mask_future=mask_future, - pre_ln=pre_ln, - pre_ln_final_layer_norm=pre_ln_final_layer_norm, - ) - - def _build_encoder(self, arch, **kwargs): - """ - Returns a decoder based on architecture arch and kwargs - """ - # default non-bottleneck transformer encoder - if (not arch) or (arch == "seq2seq"): - encoder = self.encoder - elif arch == "bridge": - encoder = BridgeEncoder( - num_layers=kwargs["num_layers"], - hidden_size=kwargs["hidden_size"], - inner_size=kwargs["inner_size"], - num_attention_heads=kwargs["num_attention_heads"], - attn_score_dropout=kwargs["attn_score_dropout"], - attn_layer_dropout=kwargs["attn_layer_dropout"], - ffn_dropout=kwargs["ffn_dropout"], - hidden_act=kwargs["hidden_act"], - mask_future=kwargs["mask_future"], - pre_ln=kwargs["pre_ln"], - pre_ln_final_layer_norm=kwargs["pre_ln_final_layer_norm"], - hidden_steps=kwargs["hidden_steps"], - hidden_blocks=kwargs["hidden_blocks"], - hidden_init_method=kwargs["hidden_init_method"], - ) - elif arch == "perceiver": - encoder = PerceiverEncoder( - num_layers=kwargs["num_layers"], - hidden_size=kwargs["hidden_size"], - inner_size=kwargs["inner_size"], - num_attention_heads=kwargs["num_attention_heads"], - attn_score_dropout=kwargs["attn_score_dropout"], - attn_layer_dropout=kwargs["attn_layer_dropout"], - ffn_dropout=kwargs["ffn_dropout"], - hidden_act=kwargs["hidden_act"], - mask_future=kwargs["mask_future"], - pre_ln=kwargs["pre_ln"], - pre_ln_final_layer_norm=kwargs["pre_ln_final_layer_norm"], - hidden_steps=kwargs["hidden_steps"], - hidden_blocks=kwargs["hidden_blocks"], - hidden_init_method=kwargs["hidden_init_method"], - ) - elif arch == "max_pool": - encoder = PoolingEncoder( - num_layers=kwargs["num_layers"], - hidden_size=kwargs["hidden_size"], - inner_size=kwargs["inner_size"], - num_attention_heads=kwargs["num_attention_heads"], - attn_score_dropout=kwargs["attn_score_dropout"], - attn_layer_dropout=kwargs["attn_layer_dropout"], - ffn_dropout=kwargs["ffn_dropout"], - hidden_act=kwargs["hidden_act"], - mask_future=kwargs["mask_future"], - pre_ln=kwargs["pre_ln"], - pre_ln_final_layer_norm=kwargs["pre_ln_final_layer_norm"], - hidden_steps=kwargs["hidden_steps"], - hidden_blocks=kwargs["hidden_blocks"], - hidden_init_method=kwargs["hidden_init_method"], - pooling_type="max", - ) - elif arch == "avg_pool": - encoder = PoolingEncoder( - num_layers=kwargs["num_layers"], - hidden_size=kwargs["hidden_size"], - inner_size=kwargs["inner_size"], - num_attention_heads=kwargs["num_attention_heads"], - attn_score_dropout=kwargs["attn_score_dropout"], - attn_layer_dropout=kwargs["attn_layer_dropout"], - ffn_dropout=kwargs["ffn_dropout"], - hidden_act=kwargs["hidden_act"], - mask_future=kwargs["mask_future"], - pre_ln=kwargs["pre_ln"], - pre_ln_final_layer_norm=kwargs["pre_ln_final_layer_norm"], - hidden_steps=kwargs["hidden_steps"], - hidden_blocks=kwargs["hidden_blocks"], - hidden_init_method=kwargs["hidden_init_method"], - pooling_type="avg", - ) - else: - raise ValueError(f"Unknown arch = {self.arch}, supported arch = {self.supported_arch}") - - return encoder - - @property - def input_types(self) -> Optional[Dict[str, NeuralType]]: - input_types = super().input_types - input_types.update( - {"return_mask": NeuralType((), BoolType(), True),} - ) - - return input_types - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - output_types = super().output_types - output_types.update( - {"hidden_mask": NeuralType(('B', 'T'), MaskType(), True),} - ) - return output_types - - @property - def supported_arch(self): - return self._SUPPORTED_ARCH - - @property - def arch(self): - return self._arch - - @typecheck() - def forward(self, input_ids, encoder_mask, return_mask=None): - if return_mask is None: - return_mask = self._return_mask - - embeddings = self._embedding(input_ids=input_ids) - - if (not self.arch) or (self.arch == "seq2seq"): - encoder_hidden_states = self._encoder(encoder_states=embeddings, encoder_mask=encoder_mask) - encoder_hidden_mask = encoder_mask - else: - encoder_hidden_states, encoder_hidden_mask = self._encoder( - encoder_states=embeddings, encoder_mask=encoder_mask, - ) - - if return_mask: - return encoder_hidden_states, encoder_hidden_mask - else: - return encoder_hidden_states - - -class TransformerBottleneckDecoderNM(TransformerDecoderNM): - _SUPPORTED_ARCH = ["seq2seq"] - - def __init__( - self, - vocab_size: int, - hidden_size: int, - num_layers: int, - inner_size: int, - num_attention_heads: int, - max_sequence_length: int = 512, - num_token_types: int = 2, - embedding_dropout: float = 0.0, - learn_positional_encodings: bool = False, - ffn_dropout: float = 0.0, - attn_score_dropout: float = 0.0, - attn_layer_dropout: float = 0.0, - hidden_act: str = 'relu', - pre_ln: bool = False, - pre_ln_final_layer_norm: bool = True, - arch='', - ): - super().__init__( - vocab_size=vocab_size, - hidden_size=hidden_size, - num_layers=num_layers, - inner_size=inner_size, - num_attention_heads=num_attention_heads, - max_sequence_length=max_sequence_length, - num_token_types=num_token_types, - embedding_dropout=embedding_dropout, - learn_positional_encodings=learn_positional_encodings, - ffn_dropout=ffn_dropout, - attn_score_dropout=attn_score_dropout, - attn_layer_dropout=attn_layer_dropout, - hidden_act=hidden_act, - pre_ln=pre_ln, - pre_ln_final_layer_norm=pre_ln_final_layer_norm, - ) - - self._arch = arch - - # replace decoder - self._decoder = self._build_decoder( - arch=arch, - hidden_size=hidden_size, - num_layers=num_layers, - inner_size=inner_size, - num_attention_heads=num_attention_heads, - max_sequence_length=max_sequence_length, - num_token_types=num_token_types, - embedding_dropout=embedding_dropout, - learn_positional_encodings=learn_positional_encodings, - ffn_dropout=ffn_dropout, - attn_score_dropout=attn_score_dropout, - attn_layer_dropout=attn_layer_dropout, - hidden_act=hidden_act, - pre_ln=pre_ln, - pre_ln_final_layer_norm=pre_ln_final_layer_norm, - ) - - def _build_decoder(self, arch, **kwargs): - """ - Returns a decoder based on architecture arch and kwargs - """ - # usual non-bottleneck transformer decoder - if (not arch) or (arch == "seq2seq"): - decoder = self.decoder - else: - raise ValueError(f"Unknown arch = {self.arch}, supported arch = {self.supported_arch}") - - return decoder - - @property - def supported_arch(self): - return self._SUPPORTED_ARCH - - @property - def arch(self): - return self._arch diff --git a/nemo/collections/asr/modules/transformer/transformer_decoders.py b/nemo/collections/asr/modules/transformer/transformer_decoders.py deleted file mode 100644 index b8b7e820b1b6a5334b592c4612ad3ce082b9c932..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/transformer/transformer_decoders.py +++ /dev/null @@ -1,334 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import copy -from typing import List, Optional, Set - -import torch -import torch.nn as nn -from omegaconf import DictConfig - -from nemo.collections.asr.modules.transformer.transformer_modules import MultiHeadAttention, PositionWiseFF -from nemo.collections.asr.parts.submodules.adapters.attention_adapter_mixin import AttentionAdapterModuleMixin -from nemo.collections.asr.parts.utils import adapter_utils -from nemo.collections.common.parts import form_attention_mask -from nemo.core.classes.mixins import adapter_mixins - -__all__ = ["TransformerDecoder"] - - -class TransformerDecoderBlock(nn.Module, AttentionAdapterModuleMixin): - """ - Building block of Transformer decoder. - - Args: - hidden_size: size of the embeddings in the model, also known as d_model - inner_size: number of neurons in the intermediate part of feed-forward - net, usually is (4-8 x hidden_size) in the papers - num_attention_heads: number of heads in multi-head attention - attn_score_dropout: probability of dropout applied to attention scores - attn_layer_dropout: probability of dropout applied to the output of the - attention layers, but before layer normalization - ffn_dropout: probability of dropout applied to FFN output - hidden_act: activation function used between two linear layers in FFN - """ - - def __init__( - self, - hidden_size: int, - inner_size: int, - num_attention_heads: int = 1, - attn_score_dropout: float = 0.0, - attn_layer_dropout: float = 0.0, - ffn_dropout: float = 0.0, - hidden_act: str = "relu", - pre_ln: bool = False, - ): - super().__init__() - self.pre_ln = pre_ln - self.layer_norm_1 = nn.LayerNorm(hidden_size, eps=1e-5) - self.first_sub_layer = MultiHeadAttention( - hidden_size, num_attention_heads, attn_score_dropout, attn_layer_dropout - ) - self.layer_norm_2 = nn.LayerNorm(hidden_size, eps=1e-5) - self.second_sub_layer = MultiHeadAttention( - hidden_size, - num_attention_heads, - attn_score_dropout, - attn_layer_dropout, - return_xatt_scores=True, - ) - self.layer_norm_3 = nn.LayerNorm(hidden_size, eps=1e-5) - self.third_sub_layer = PositionWiseFF(hidden_size, inner_size, ffn_dropout, hidden_act) - - # Information for the adapter module mixin - self.self_attention_model = "transf_abs" - - def forward_preln(self, decoder_query, decoder_mask, decoder_keys, encoder_states, encoder_mask): - """ - Pre-LayerNorm block - Order of operations: LN -> Self-Attn -> Residual -> LN -> Cross-Attn -> Residual -> LN -> FFN - """ - residual = decoder_query - decoder_query = self.layer_norm_1(decoder_query) - decoder_keys = self.layer_norm_1(decoder_keys) - self_attn_output, _ = self.first_sub_layer(decoder_query, decoder_keys, decoder_keys, decoder_mask) - self_attn_output += residual - - if self.is_adapter_available(): - # Call the MHA adapters - pack_input = { - 'x': self_attn_output, - 'loc': 'mha', - 'att_mask': decoder_mask, - 'pos_emb': None, - } - pack_input = self.forward_enabled_adapters(pack_input) - self_attn_output = pack_input['x'] - - residual = self_attn_output - self_attn_output = self.layer_norm_2(self_attn_output) - enc_dec_attn_output, extra_output = self.second_sub_layer( - self_attn_output, encoder_states, encoder_states, encoder_mask - ) - enc_dec_attn_output += residual - - residual = enc_dec_attn_output - enc_dec_attn_output = self.layer_norm_3(enc_dec_attn_output) - output_states = self.third_sub_layer(enc_dec_attn_output) - output_states += residual - - if self.is_adapter_available(): - # Call the Linear adapters - pack_input = { - 'x': output_states, - 'loc': 'post', - } - pack_input = self.forward_enabled_adapters(pack_input) - output_states = pack_input['x'] - - return output_states, extra_output - - def forward_postln(self, decoder_query, decoder_mask, decoder_keys, encoder_states, encoder_mask): - """ - Post-LayerNorm block - Order of operations: Self-Attn -> Residual -> LN -> Cross-Attn -> Residual -> LN -> FFN -> Residual -> LN - """ - self_attn_output, _ = self.first_sub_layer(decoder_query, decoder_keys, decoder_keys, decoder_mask) - self_attn_output += decoder_query - - if self.is_adapter_available(): - # Call the MHA adapters - pack_ip = { - 'x': self_attn_output, - 'loc': 'mha', - 'att_mask': decoder_mask, - 'pos_emb': None, - } - pack_ip = self.forward_enabled_adapters(pack_ip) - self_attn_output = pack_ip['x'] - - self_attn_output = self.layer_norm_1(self_attn_output) - - enc_dec_attn_output, extra_output = self.second_sub_layer( - self_attn_output, encoder_states, encoder_states, encoder_mask - ) - enc_dec_attn_output += self_attn_output - enc_dec_attn_output = self.layer_norm_2(enc_dec_attn_output) - - output_states = self.third_sub_layer(enc_dec_attn_output) - output_states += enc_dec_attn_output - - if self.is_adapter_available(): - # Call the linear adapters - pack_ip = { - 'x': output_states, - 'loc': 'post', - } - pack_ip = self.forward_enabled_adapters(pack_ip) - output_states = pack_ip['x'] - - return self.layer_norm_3(output_states), extra_output - - def forward(self, decoder_query, decoder_mask, decoder_keys, encoder_states, encoder_mask): - if self.pre_ln: - return self.forward_preln(decoder_query, decoder_mask, decoder_keys, encoder_states, encoder_mask) - else: - return self.forward_postln(decoder_query, decoder_mask, decoder_keys, encoder_states, encoder_mask) - - def get_accepted_adapter_types(self) -> Set[type]: - types = super().get_accepted_adapter_types() - - if len(types) == 0: - self.set_accepted_adapter_types( - [ - adapter_utils.LINEAR_ADAPTER_CLASSPATH, - adapter_utils.TRANSFORMER_MHA_ADAPTER_CLASSPATH, - ] - ) - types = self.get_accepted_adapter_types() - return types - - -class TransformerDecoder(nn.Module): - def __init__( - self, - num_layers: int, - hidden_size: int, - inner_size: int, - num_attention_heads: int = 1, - attn_score_dropout: float = 0.0, - attn_layer_dropout: float = 0.0, - ffn_dropout: float = 0.0, - hidden_act: str = "relu", - pre_ln: bool = False, - pre_ln_final_layer_norm: bool = True, - ): - super().__init__() - - if pre_ln and pre_ln_final_layer_norm: - self.final_layer_norm = nn.LayerNorm(hidden_size, eps=1e-5) - else: - self.final_layer_norm = None - - self.d_model = hidden_size - - layer = TransformerDecoderBlock( - hidden_size, - inner_size, - num_attention_heads, - attn_score_dropout, - attn_layer_dropout, - ffn_dropout, - hidden_act, - pre_ln, - ) - self.layers = nn.ModuleList([copy.deepcopy(layer) for _ in range(num_layers)]) - self.diagonal = 0 - - def _get_memory_states(self, decoder_states, decoder_mems_list=None, i=0): - if decoder_mems_list is not None: - inp1 = torch.transpose(decoder_mems_list[i], 1, 2) # Putting seq_len to last dim to handle export cases - inp2 = torch.transpose(decoder_states, 1, 2) - memory_states = torch.cat((inp1, inp2), dim=2) - memory_states = torch.transpose(memory_states, 1, 2) # Transposing back - else: - memory_states = decoder_states - return memory_states - - def forward( - self, - decoder_states, - decoder_mask, - encoder_states, - encoder_mask, - decoder_mems_list=None, - return_mems=False, - return_mems_as_list=True, - ): - """ - Args: - decoder_states: output of the embedding layer (B x L_dec x H) - decoder_mask: decoder inputs mask (B x L_dec) - encoder_states: output of the encoder (B x L_enc x H) - encoder_mask: encoder inputs mask (B x L_enc) - decoder_mems_list: list of the cached decoder hidden states - for fast autoregressive generation which will be used instead - of decoder_states as keys and values if not None - return_mems: bool, whether to return outputs of all decoder layers - or the last layer only - return_mems_as_list: bool, when True, mems returned are as a list; otherwise mems are Tensor - """ - decoder_attn_mask = form_attention_mask(decoder_mask, diagonal=self.diagonal) - encoder_attn_mask = form_attention_mask(encoder_mask) - memory_states = self._get_memory_states(decoder_states, decoder_mems_list, 0) - if return_mems: - if return_mems_as_list: - cached_mems_list = [memory_states] - else: - cached_mems_list = memory_states.unsqueeze(0) - - xatt_scores_list = [] - - for i, layer in enumerate(self.layers): - decoder_states, extra_output = layer( - decoder_states, decoder_attn_mask, memory_states, encoder_states, encoder_attn_mask - ) - memory_states = self._get_memory_states(decoder_states, decoder_mems_list, i + 1) - xatt_scores_list.append(extra_output['xatt_scores']) - if return_mems: - if return_mems_as_list: - cached_mems_list.append(memory_states) - else: - cached_mems_list = torch.cat((cached_mems_list, memory_states.unsqueeze(0)), dim=0) - - if self.final_layer_norm is not None: - decoder_states = self.final_layer_norm(decoder_states) - memory_states = self._get_memory_states(decoder_states, decoder_mems_list, i + 2) - if return_mems: - if return_mems_as_list: - cached_mems_list.append(memory_states) - else: - cached_mems_list = torch.cat((cached_mems_list, memory_states.unsqueeze(0)), dim=0) - - if return_mems: - return cached_mems_list, xatt_scores_list - else: - return memory_states, xatt_scores_list - - def input_example(self, max_batch=1, max_dim=256): - """ - Generates input examples for tracing etc. - Returns: - A tuple of input examples. - """ - sample = next(self.parameters()) - input_ids = torch.randint(low=0, high=2048, size=(max_batch, max_dim, 1024), device=sample.device) - encoder_mask = torch.randint(low=0, high=1, size=(max_batch, max_dim), device=sample.device) - return tuple([input_ids, encoder_mask, input_ids, encoder_mask]) - - -class TransformerDecoderAdapter(TransformerDecoder, adapter_mixins.AdapterModuleMixin): - - # Higher level forwarding - def add_adapter(self, name: str, cfg: dict): - cfg = self._update_adapter_cfg_input_dim(cfg) - for transformer_layer in self.layers: # type: adapter_mixins.AdapterModuleMixin - transformer_layer.add_adapter(name, cfg) - - def is_adapter_available(self) -> bool: - return any([transformer_layer.is_adapter_available() for transformer_layer in self.layers]) - - def set_enabled_adapters(self, name: Optional[str] = None, enabled: bool = True): - for transformer_layer in self.layers: # type: adapter_mixins.AdapterModuleMixin - transformer_layer.set_enabled_adapters(name=name, enabled=enabled) - - def get_enabled_adapters(self) -> List[str]: - names = set([]) - for transformer_layer in self.layers: # type: adapter_mixins.AdapterModuleMixin - names.update(transformer_layer.get_enabled_adapters()) - - names = sorted(list(names)) - return names - - def _update_adapter_cfg_input_dim(self, cfg: DictConfig): - cfg = adapter_utils.update_adapter_cfg_input_dim(self, cfg, module_dim=self.d_model) - return cfg - - -""" -Register any additional information -""" -if adapter_mixins.get_registered_adapter(TransformerDecoder) is None: - adapter_mixins.register_adapter(base_class=TransformerDecoder, adapter_class=TransformerDecoderAdapter) diff --git a/nemo/collections/asr/modules/transformer/transformer_encoders.py b/nemo/collections/asr/modules/transformer/transformer_encoders.py deleted file mode 100644 index 3f3236b3a794f46ba6514593cf118e84be7b78e1..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/transformer/transformer_encoders.py +++ /dev/null @@ -1,274 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import copy -from typing import List, Optional, Set - -import torch -import torch.nn as nn -from omegaconf import DictConfig - -from nemo.collections.asr.modules.transformer.transformer_modules import MultiHeadAttention, PositionWiseFF -from nemo.collections.asr.parts.submodules.adapters.attention_adapter_mixin import AttentionAdapterModuleMixin -from nemo.collections.asr.parts.utils import adapter_utils -from nemo.collections.common.parts import form_attention_mask -from nemo.core.classes.mixins import adapter_mixins - -__all__ = ["TransformerEncoder"] - - -class TransformerEncoderBlock(nn.Module, AttentionAdapterModuleMixin): - """ - Building block of Transformer encoder. - - Args: - hidden_size: size of the embeddings in the model, also known as d_model - inner_size: number of neurons in the intermediate part of feed-forward - net, usually is (4-8 x hidden_size) in the papers - num_attention_heads: number of heads in multi-head attention - attn_score_dropout: probability of dropout applied to attention scores - attn_layer_dropout: probability of dropout applied to the output of the - attention layers, but before layer normalization - ffn_dropout: probability of dropout applied to FFN output - hidden_act: activation function used between two linear layers in FFN - """ - - def __init__( - self, - hidden_size: int, - inner_size: int, - num_attention_heads: int = 1, - attn_score_dropout: float = 0.0, - attn_layer_dropout: float = 0.0, - ffn_dropout: float = 0.0, - hidden_act: str = "relu", - pre_ln: bool = False, - ): - super().__init__() - self.pre_ln = pre_ln - self.layer_norm_1 = nn.LayerNorm(hidden_size, eps=1e-5) - self.first_sub_layer = MultiHeadAttention( - hidden_size, num_attention_heads, attn_score_dropout, attn_layer_dropout - ) - self.layer_norm_2 = nn.LayerNorm(hidden_size, eps=1e-5) - self.second_sub_layer = PositionWiseFF(hidden_size, inner_size, ffn_dropout, hidden_act) - - # Information for the adapter module mixin - self.self_attention_model = "transf_abs" - - def forward_preln(self, encoder_query, encoder_mask, encoder_keys): - """ - Pre-LayerNorm block - Order of operations: LN -> Self-Attn -> Residual -> LN -> Cross-Attn -> Residual -> LN -> FFN - """ - residual = encoder_query - encoder_query = self.layer_norm_1(encoder_query) - encoder_keys = self.layer_norm_1(encoder_keys) - self_attn_output, _ = self.first_sub_layer(encoder_query, encoder_keys, encoder_keys, encoder_mask) - self_attn_output += residual - - if self.is_adapter_available(): - # Call the MHA adapters - pack_input = { - 'x': self_attn_output, - 'loc': 'mha', - 'att_mask': encoder_mask, - 'pos_emb': None, - } - pack_input = self.forward_enabled_adapters(pack_input) - self_attn_output = pack_input['x'] - - residual = self_attn_output - self_attn_output = self.layer_norm_2(self_attn_output) - output_states = self.second_sub_layer(self_attn_output) - output_states += residual - - if self.is_adapter_available(): - # Call the Linear adapters - pack_input = { - 'x': output_states, - 'loc': 'post', - } - pack_input = self.forward_enabled_adapters(pack_input) - output_states = pack_input['x'] - - return output_states - - def forward_postln(self, encoder_query, encoder_mask, encoder_keys): - """ - Post-LayerNorm block - Order of operations: Self-Attn -> Residual -> LN -> Cross-Attn -> Residual -> LN -> FFN -> Residual -> LN - """ - self_attn_output, _ = self.first_sub_layer(encoder_query, encoder_keys, encoder_keys, encoder_mask) - self_attn_output += encoder_query - - if self.is_adapter_available(): - # Call the MHA adapters - pack_ip = { - 'x': self_attn_output, - 'loc': 'mha', - 'att_mask': encoder_mask, - 'pos_emb': None, - } - pack_ip = self.forward_enabled_adapters(pack_ip) - self_attn_output = pack_ip['x'] - - self_attn_output = self.layer_norm_1(self_attn_output) - - output_states = self.second_sub_layer(self_attn_output) - output_states += self_attn_output - - if self.is_adapter_available(): - # Call the linear adapters - pack_ip = { - 'x': output_states, - 'loc': 'post', - } - pack_ip = self.forward_enabled_adapters(pack_ip) - output_states = pack_ip['x'] - - output_states = self.layer_norm_2(output_states) - - return output_states - - def forward(self, encoder_query, encoder_mask, encoder_keys): - if self.pre_ln: - return self.forward_preln(encoder_query, encoder_mask, encoder_keys) - else: - return self.forward_postln(encoder_query, encoder_mask, encoder_keys) - - def get_accepted_adapter_types(self) -> Set[type]: - types = super().get_accepted_adapter_types() - - if len(types) == 0: - self.set_accepted_adapter_types( - [ - adapter_utils.LINEAR_ADAPTER_CLASSPATH, - adapter_utils.TRANSFORMER_MHA_ADAPTER_CLASSPATH, - ] - ) - types = self.get_accepted_adapter_types() - return types - - -class TransformerEncoder(nn.Module): - def __init__( - self, - num_layers: int, - hidden_size: int, - inner_size: int, - mask_future: bool = False, - num_attention_heads: int = 1, - attn_score_dropout: float = 0.0, - attn_layer_dropout: float = 0.0, - ffn_dropout: float = 0.0, - hidden_act: str = "relu", - pre_ln: bool = False, - pre_ln_final_layer_norm: bool = True, - ): - super().__init__() - - if pre_ln and pre_ln_final_layer_norm: - self.final_layer_norm = nn.LayerNorm(hidden_size, eps=1e-5) - else: - self.final_layer_norm = None - - self.d_model = hidden_size - - layer = TransformerEncoderBlock( - hidden_size, - inner_size, - num_attention_heads, - attn_score_dropout, - attn_layer_dropout, - ffn_dropout, - hidden_act, - pre_ln, - ) - self.layers = nn.ModuleList([copy.deepcopy(layer) for _ in range(num_layers)]) - self.diag = 0 if mask_future else None - - def _get_memory_states(self, encoder_states, encoder_mems_list=None, i=0): - if encoder_mems_list is not None: - memory_states = torch.cat((encoder_mems_list[i], encoder_states), dim=1) - else: - memory_states = encoder_states - return memory_states - - def forward(self, encoder_states, encoder_mask, encoder_mems_list=None, return_mems=False): - """ - Args: - encoder_states: output of the embedding_layer (B x L_enc x H) - encoder_mask: encoder inputs mask (B x L_enc) - encoder_mems_list: list of the cached encoder hidden states - for fast autoregressive generation which will be used instead - of encoder_states as keys and values if not None - return_mems: bool, whether to return outputs of all encoder layers - or the last layer only - """ - - encoder_attn_mask = form_attention_mask(encoder_mask, self.diag) - - memory_states = self._get_memory_states(encoder_states, encoder_mems_list, 0) - cached_mems_list = [memory_states] - - for i, layer in enumerate(self.layers): - encoder_states = layer(encoder_states, encoder_attn_mask, memory_states) - memory_states = self._get_memory_states(encoder_states, encoder_mems_list, i + 1) - cached_mems_list.append(memory_states) - - if self.final_layer_norm is not None: - encoder_states = self.final_layer_norm(encoder_states) - memory_states = self._get_memory_states(encoder_states, encoder_mems_list, i + 1) - cached_mems_list.append(memory_states) - - if return_mems: - return cached_mems_list - else: - return cached_mems_list[-1] - - -class TransformerEncoderAdapter(TransformerEncoder, adapter_mixins.AdapterModuleMixin): - - # Higher level forwarding - def add_adapter(self, name: str, cfg: dict): - cfg = self._update_adapter_cfg_input_dim(cfg) - for transformer_layer in self.layers: # type: adapter_mixins.AdapterModuleMixin - transformer_layer.add_adapter(name, cfg) - - def is_adapter_available(self) -> bool: - return any([transformer_layer.is_adapter_available() for transformer_layer in self.layers]) - - def set_enabled_adapters(self, name: Optional[str] = None, enabled: bool = True): - for transformer_layer in self.layers: # type: adapter_mixins.AdapterModuleMixin - transformer_layer.set_enabled_adapters(name=name, enabled=enabled) - - def get_enabled_adapters(self) -> List[str]: - names = set([]) - for transformer_layer in self.layers: # type: adapter_mixins.AdapterModuleMixin - names.update(transformer_layer.get_enabled_adapters()) - - names = sorted(list(names)) - return names - - def _update_adapter_cfg_input_dim(self, cfg: DictConfig): - cfg = adapter_utils.update_adapter_cfg_input_dim(self, cfg, module_dim=self.d_model) - return cfg - - -""" -Register any additional information -""" -if adapter_mixins.get_registered_adapter(TransformerEncoder) is None: - adapter_mixins.register_adapter(base_class=TransformerEncoder, adapter_class=TransformerEncoderAdapter) diff --git a/nemo/collections/asr/modules/transformer/transformer_encoders_nlp.py b/nemo/collections/asr/modules/transformer/transformer_encoders_nlp.py deleted file mode 100644 index ea6de7cb1848d7a9a8c56466ba5cc1060be09176..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/transformer/transformer_encoders_nlp.py +++ /dev/null @@ -1,174 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import copy - -import torch -import torch.nn as nn - -from nemo.collections.common.parts import form_attention_mask -from nemo.collections.nlp.modules.common.transformer.transformer_modules import MultiHeadAttention, PositionWiseFF - -__all__ = ["TransformerEncoder"] - - -class TransformerEncoderBlock(nn.Module): - """ - Building block of Transformer encoder. - - Args: - hidden_size: size of the embeddings in the model, also known as d_model - inner_size: number of neurons in the intermediate part of feed-forward - net, usually is (4-8 x hidden_size) in the papers - num_attention_heads: number of heads in multi-head attention - attn_score_dropout: probability of dropout applied to attention scores - attn_layer_dropout: probability of dropout applied to the output of the - attention layers, but before layer normalization - ffn_dropout: probability of dropout applied to FFN output - hidden_act: activation function used between two linear layers in FFN - """ - - def __init__( - self, - hidden_size: int, - inner_size: int, - num_attention_heads: int = 1, - attn_score_dropout: float = 0.0, - attn_layer_dropout: float = 0.0, - ffn_dropout: float = 0.0, - hidden_act: str = "relu", - pre_ln: bool = False, - ): - super().__init__() - self.pre_ln = pre_ln - self.layer_norm_1 = nn.LayerNorm(hidden_size, eps=1e-5) - self.first_sub_layer = MultiHeadAttention( - hidden_size, num_attention_heads, attn_score_dropout, attn_layer_dropout - ) - self.layer_norm_2 = nn.LayerNorm(hidden_size, eps=1e-5) - self.second_sub_layer = PositionWiseFF(hidden_size, inner_size, ffn_dropout, hidden_act) - - def forward_preln(self, encoder_query, encoder_mask, encoder_keys): - """ - Pre-LayerNorm block - Order of operations: LN -> Self-Attn -> Residual -> LN -> Cross-Attn -> Residual -> LN -> FFN - """ - residual = encoder_query - encoder_query = self.layer_norm_1(encoder_query) - encoder_keys = self.layer_norm_1(encoder_keys) - self_attn_output = self.first_sub_layer(encoder_query, encoder_keys, encoder_keys, encoder_mask) - self_attn_output += residual - - residual = self_attn_output - self_attn_output = self.layer_norm_2(self_attn_output) - output_states = self.second_sub_layer(self_attn_output) - output_states += residual - - return output_states - - def forward_postln(self, encoder_query, encoder_mask, encoder_keys): - """ - Post-LayerNorm block - Order of operations: Self-Attn -> Residual -> LN -> Cross-Attn -> Residual -> LN -> FFN -> Residual -> LN - """ - self_attn_output = self.first_sub_layer(encoder_query, encoder_keys, encoder_keys, encoder_mask) - self_attn_output += encoder_query - self_attn_output = self.layer_norm_1(self_attn_output) - - output_states = self.second_sub_layer(self_attn_output) - output_states += self_attn_output - output_states = self.layer_norm_2(output_states) - - return output_states - - def forward(self, encoder_query, encoder_mask, encoder_keys): - if self.pre_ln: - return self.forward_preln(encoder_query, encoder_mask, encoder_keys) - else: - return self.forward_postln(encoder_query, encoder_mask, encoder_keys) - - -class TransformerEncoder(nn.Module): - def __init__( - self, - num_layers: int, - hidden_size: int, - inner_size: int, - mask_future: bool = False, - num_attention_heads: int = 1, - attn_score_dropout: float = 0.0, - attn_layer_dropout: float = 0.0, - ffn_dropout: float = 0.0, - hidden_act: str = "relu", - pre_ln: bool = False, - pre_ln_final_layer_norm: bool = True, - ): - super().__init__() - - if pre_ln and pre_ln_final_layer_norm: - self.final_layer_norm = nn.LayerNorm(hidden_size, eps=1e-5) - else: - self.final_layer_norm = None - - layer = TransformerEncoderBlock( - hidden_size, - inner_size, - num_attention_heads, - attn_score_dropout, - attn_layer_dropout, - ffn_dropout, - hidden_act, - pre_ln, - ) - self.layers = nn.ModuleList([copy.deepcopy(layer) for _ in range(num_layers)]) - self.diag = 0 if mask_future else None - - def _get_memory_states(self, encoder_states, encoder_mems_list=None, i=0): - if encoder_mems_list is not None: - memory_states = torch.cat((encoder_mems_list[i], encoder_states), dim=1) - else: - memory_states = encoder_states - return memory_states - - def forward(self, encoder_states, encoder_mask, encoder_mems_list=None, return_mems=False): - """ - Args: - encoder_states: output of the embedding_layer (B x L_enc x H) - encoder_mask: encoder inputs mask (B x L_enc) - encoder_mems_list: list of the cached encoder hidden states - for fast autoregressive generation which will be used instead - of encoder_states as keys and values if not None - return_mems: bool, whether to return outputs of all encoder layers - or the last layer only - """ - - encoder_attn_mask = form_attention_mask(encoder_mask, self.diag) - - memory_states = self._get_memory_states(encoder_states, encoder_mems_list, 0) - cached_mems_list = [memory_states] - - for i, layer in enumerate(self.layers): - encoder_states = layer(encoder_states, encoder_attn_mask, memory_states) - memory_states = self._get_memory_states(encoder_states, encoder_mems_list, i + 1) - cached_mems_list.append(memory_states) - - if self.final_layer_norm is not None: - encoder_states = self.final_layer_norm(encoder_states) - memory_states = self._get_memory_states(encoder_states, encoder_mems_list, i + 1) - cached_mems_list.append(memory_states) - - if return_mems: - return cached_mems_list - else: - return cached_mems_list[-1] diff --git a/nemo/collections/asr/modules/transformer/transformer_generators.py b/nemo/collections/asr/modules/transformer/transformer_generators.py deleted file mode 100644 index d78518a1fcd1b8d7d7cc83c3cd9e116034e67ef9..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/transformer/transformer_generators.py +++ /dev/null @@ -1,1284 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from contextlib import contextmanager -from typing import Optional - -import torch -from omegaconf import DictConfig -from torch.distributions import Categorical - -from nemo.collections.asr.parts.submodules.token_classifier import TokenClassifier -from nemo.collections.asr.parts.utils.asr_confidence_utils import ConfidenceMethodMixin -from nemo.collections.common.parts import NEG_INF, mask_padded_tokens - -__all__ = [ - "GreedySequenceGenerator", - "TopKSequenceGenerator", - "BeamSearchSequenceGenerator", - "BeamSearchSequenceGeneratorWithLanguageModel", - "BeamSearchSequenceGeneratorWithNGramLM", - "EnsembleBeamSearchSequenceGenerator", -] - - -class GreedySequenceGenerator(ConfidenceMethodMixin): - """ - Greedy sequence generator based on the decoder followed by log_softmax. - Optionally supports temperature sampling with ``n_samples`` and ``temperature`` options. - - Args: - embedding: nn.Module, transforms input_ids into vector embeddings - decoder: nn.Module, takes embeddings and produces hidden_states - classifier: nn.Module, takes hidden_states and produces - logits or log-probability distribution of tokens (ids) - pad: index of padding token in the vocabulary - bos: index of beginning of sequence token in the vocabulary - eos: index of end of sequence token in the vocabulary - max_sequence_length: maximum allowed length for generated sequences - max_delta_length: in case of encoder-decoder generation (e.g. NMT), - forbids generated sequences to be longer than the length of - source sequences plus max_delta_length - batch_size: size of the batch of generated sequences if neither - source nor target starting sequences are provided - n_samples: number of sequences to generate (requires ``temperature`` to be set) - temperature: temperature for temperature sampling. Even with ``n_samples`` set to 1, - enabling temperature will sample hypotheses instead of returning the best ones. - - preserve_step_confidence: Bool flag which preserves the history of per-step confidence scores generated - during greedy decoding. When set to true, the results will contain additional List of tensor floats. - return_xattn_scores: Bool flag which indicates whether to keep and return the cross-attention scores - during greedy/beam search decoding. When set to true, the results will contain additional List of tensors. - confidence_method_cfg: A dict-like object which contains the method name and settings to compute per-step - confidence scores. - name: The method name (str). - Supported values: - - 'max_prob' for using the maximum token probability as a confidence. - - 'entropy' for using a normalized entropy of a log-likelihood vector. - entropy_type: Which type of entropy to use (str). Used if confidence_method_cfg.name is set to `entropy`. - Supported values: - - 'gibbs' for the (standard) Gibbs entropy. If the alpha (α) is provided, - the formula is the following: H_α = -sum_i((p^α_i)*log(p^α_i)). - Note that for this entropy, the alpha should comply the following inequality: - (log(V)+2-sqrt(log^2(V)+4))/(2*log(V)) <= α <= (1+log(V-1))/log(V-1) - where V is the model vocabulary size. - - 'tsallis' for the Tsallis entropy with the Boltzmann constant one. - Tsallis entropy formula is the following: H_α = 1/(α-1)*(1-sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/Tsallis_entropy - - 'renyi' for the Rényi entropy. - Rényi entropy formula is the following: H_α = 1/(1-α)*log_2(sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/R%C3%A9nyi_entropy - alpha: Power scale for logsoftmax (α for entropies). Here we restrict it to be > 0. - When the alpha equals one, scaling is not applied to 'max_prob', - and any entropy type behaves like the Shannon entropy: H = -sum_i(p_i*log(p_i)) - entropy_norm: A mapping of the entropy value to the interval [0,1]. - Supported values: - - 'lin' for using the linear mapping. - - 'exp' for using exponential mapping with linear shift. - """ - - def __init__( - self, - embedding, - decoder, - classifier: TokenClassifier, - pad=0, - bos=1, - eos=2, - max_sequence_length=512, - max_delta_length=20, - batch_size=1, - n_samples=1, - temperature=None, - preserve_step_confidence=False, - return_xattn_scores=False, - confidence_method_cfg: Optional[DictConfig] = None, - ): - super().__init__() - self.embedding = embedding - self.decoder = decoder - self.classifier = classifier - self.pad, self.bos, self.eos = pad, bos, eos - self.max_seq_length = max_sequence_length - self.max_delta_len = max_delta_length - self.batch_size = batch_size - self.n_samples = n_samples - self.temperature = temperature - self.preserve_step_confidence = preserve_step_confidence - self.return_xattn_scores = return_xattn_scores - - # set confidence calculation method - self.num_tokens = getattr(self.classifier.mlp, f'layer{self.classifier.mlp.layers - 1}').out_features - self._init_confidence_method(confidence_method_cfg) - - def _one_step_forward( - self, - decoder_input_ids=None, - encoder_hidden_states=None, - encoder_input_mask=None, - decoder_mems_list=None, - pos=0, - return_scores: bool = True, - ): - """ - One step of autoregressive output generation. - - Args: - decoder_input_ids: starting sequence of tokens to generate from; - if None, generation will start from a batch of tokens - encoder_hidden_states: output of the encoder for conditional - sequence generation; if None, generator will use unconditional - mode (e.g., language modeling) - encoder_input_mask: input mask used in the encoder - decoder_mems_list: list of size num_layers with cached activations - of sequence (x[1], ..., x[k-1]) for fast generation of x[k] - pos: starting position in positional encoding (can be a tensor for asynchronius decoding) - """ - - decoder_hidden_states = self.embedding.forward(decoder_input_ids, start_pos=pos) - decoder_input_mask = mask_padded_tokens(decoder_input_ids, self.pad).float() - - if encoder_hidden_states is not None: - decoder_mems_list, xatt_scores_list = self.decoder.forward( - decoder_hidden_states, - decoder_input_mask, - encoder_hidden_states, - encoder_input_mask, - decoder_mems_list, - return_mems=True, - ) - else: - decoder_mems_list, _ = self.decoder.forward( - decoder_hidden_states, decoder_input_mask, decoder_mems_list, return_mems=True - ) - xatt_scores_list = None - with self.classifier.with_log_softmax_enabled(return_scores) as clf: - logits = clf.forward(hidden_states=decoder_mems_list[-1][:, -1:]) - - return logits, decoder_mems_list, xatt_scores_list - - def _prepare_for_search(self, decoder_input_ids=None, encoder_hidden_states=None): - """ - Helper function which defines starting sequence to begin generating - with and maximum allowed number of tokens to be generated. - """ - - decoder_parameter = next(self.decoder.parameters()) - batch_size = self.batch_size - - # for encoder-decoder generation, maximum length of generated sequence - # is min(max_sequence_length, src_len + max_delta_length) - if encoder_hidden_states is not None: - batch_size, src_len, _ = encoder_hidden_states.size() - if self.max_delta_len >= 0: - max_seq_length = min(self.max_seq_length, src_len + self.max_delta_len) - else: - max_seq_length = self.max_seq_length - else: - max_seq_length = self.max_seq_length - - # if no input is provided, start with the batch of tokens - if decoder_input_ids is not None: - tgt = decoder_input_ids - batch_size, tgt_len = decoder_input_ids.size() - else: - tgt = torch.zeros(batch_size, 1).long().fill_(self.bos).to(decoder_parameter.device) - tgt_len = 1 - max_generation_length = max_seq_length - tgt_len - - return tgt, batch_size, max_generation_length - - def _forward( - self, decoder_input_ids=None, encoder_hidden_states=None, encoder_input_mask=None, return_beam_scores=False - ): - assert not return_beam_scores - is_sampling = self.temperature is not None and self.n_samples > 1 - - tgt, batch_size, max_generation_length = self._prepare_for_search(decoder_input_ids, encoder_hidden_states) - tgt_len = tgt.size(-1) - if is_sampling: - tgt = torch.repeat_interleave(tgt, self.n_samples, dim=0) - encoder_hidden_states = torch.repeat_interleave(encoder_hidden_states, self.n_samples, dim=0) - encoder_input_mask = torch.repeat_interleave(encoder_input_mask, self.n_samples, dim=0) - orig_batch_size = batch_size - batch_size = batch_size * self.n_samples - - # pad profile tracks sequences ending with token to replace - # everything after with token - decoder_parameter = next(self.decoder.parameters()) - pad_profile = torch.zeros(batch_size).long().to(decoder_parameter.device) - - if self.preserve_step_confidence: - if encoder_hidden_states is None: - raise RuntimeError("`encoder_hidden_states` must be provided to compute confidence scores.") - # start with prompt confidence which is always 1 - step_confidence = [torch.full_like(tgt, 1, dtype=encoder_hidden_states.dtype)] - else: - step_confidence = None - - decoder_mems_list = None - xatt_scores_list = None - for i in range(max_generation_length): - - if i == 0: - input_ids = tgt - else: - i += tgt_len - 1 - input_ids = tgt[:, -1:] - - logits, decoder_mems_list, new_xatt_scores_list = self._one_step_forward( - input_ids, - encoder_hidden_states, - encoder_input_mask, - decoder_mems_list, - i, - return_scores=return_beam_scores, - ) - if self.return_xattn_scores: - if xatt_scores_list is not None: - for layer in range(len(xatt_scores_list)): - xatt_scores_list[layer] = torch.cat( - (xatt_scores_list[layer], new_xatt_scores_list[layer]), dim=2 - ) - else: - xatt_scores_list = new_xatt_scores_list - - if self.temperature is None: # Greedy decoding - next_tokens = torch.argmax(logits[:, -1], dim=-1) - else: # Temperature sampling - next_tokens = Categorical(logits=logits[:, -1] / self.temperature).sample() - - next_tokens = self.pad * pad_profile + next_tokens * (1 - pad_profile) - pad_profile = torch.max(pad_profile, (next_tokens == self.eos).long()) - tgt = torch.cat((tgt, next_tokens.unsqueeze(1)), dim=-1) - - if self.preserve_step_confidence: - step_confidence.append( - self._get_confidence_tensor( - torch.nn.functional.log_softmax(logits, dim=-1) if not return_beam_scores else logits - ) - ) - - # abort generation if all sequences end with - if pad_profile.sum() == batch_size: - break - - step_confidence_tensor = ( - torch.cat(step_confidence, dim=1) if self.preserve_step_confidence and len(step_confidence) > 0 else None - ) - - samples = None - if is_sampling: - samples = list(tgt.view(orig_batch_size, self.n_samples, -1)) - tgt = tgt[:: self.n_samples] - - return tgt, samples, step_confidence_tensor, xatt_scores_list - - def __call__( - self, decoder_input_ids=None, encoder_hidden_states=None, encoder_input_mask=None, return_beam_scores=False - ): - with torch.inference_mode(): - results = self._forward( - decoder_input_ids, encoder_hidden_states, encoder_input_mask, return_beam_scores=return_beam_scores - ) - if not return_beam_scores: - return results - else: - prefixes, scores, tgt, xatt_scores_list = results - prefixes = prefixes.view(-1, self.beam_size, tgt.size(1)).split(1, dim=0) - scores = scores.view(-1, self.beam_size).split(1, dim=0) - prefixes = [x.squeeze(0) for x in prefixes] # each item is [beam, seq_len] - scores = [x.squeeze(0) for x in scores] # each item is [beam,] - return prefixes, scores, tgt, xatt_scores_list - - def freeze(self) -> None: - """Freeze weights of embedding, decoder, and classification layers to prevent memory leak.""" - for param in self.embedding.parameters(): - param.requires_grad = False - self.embedding.eval() - for param in self.decoder.parameters(): - param.requires_grad = False - self.decoder.eval() - for param in self.classifier.parameters(): - param.requires_grad = False - self.classifier.eval() - - def unfreeze(self) -> None: - """Unfreeze weights of embedding, decoder, and classification layers.""" - for param in self.embedding.parameters(): - param.requires_grad = True - self.embedding.train() - for param in self.decoder.parameters(): - param.requires_grad = True - self.decoder.train() - for param in self.classifier.parameters(): - param.requires_grad = True - self.classifier.train() - - @contextmanager - def as_frozen(self): - """ - Context manager which temporarily freezes embedding, decoder, and classifier modules, - yields control and finally unfreezes the modules. - """ - self.freeze() - - try: - yield - finally: - self.unfreeze() - - -class TopKSequenceGenerator(GreedySequenceGenerator): - """ - Top-k sequence generator based on the decoder followed by log_softmax. - - Args: - *all args of GreedySequenceGenerator class - beam_size: size of the beam (parameter k in top-k) - temperature: temperature of top-k sampling, all logits are divided - by temperature before rescaling. High temperature leads to - uniform distribution, low leads to delta-like distribution. - Kwargs: - all remaining parameters of GreedySequenceGenerator class - """ - - def __init__(self, embedding, decoder, log_softmax, beam_size=1, temperature=1.0, **kwargs): - super().__init__(embedding, decoder, log_softmax, **kwargs) - self.beam_size = beam_size - self.temp = temperature - - # @torch.no_grad() - def _one_step_forward( - self, - decoder_input_ids=None, - encoder_hidden_states=None, - encoder_input_mask=None, - decoder_mems_list=None, - pos=0, - return_scores: bool = True, - ): - log_probs, decoder_mems_list, _ = super()._one_step_forward( - decoder_input_ids, - encoder_hidden_states, - encoder_input_mask, - decoder_mems_list, - pos, - return_scores=return_scores, - ) - - batch_size, seq_len, vocab_size = log_probs.size() - scores, indices = torch.topk(log_probs, self.beam_size, dim=-1) - - rescaled_logexp = torch.zeros_like(log_probs).scatter(-1, indices, scores.div(self.temp).exp()) - probs = rescaled_logexp / rescaled_logexp.norm(1, -1, keepdim=True) - - # We randomly sample next tokens from rescaled probability distribution - # over top-k candidates and return a binary tensor which indicates - # candidates that have been selected. We call this object - # `pseudo_log_probs` as genuine log_probs should have -infs instead of - # 0s and 0s instead of 1s. - ids = torch.multinomial(probs.view(-1, vocab_size), 1).view(-1, seq_len, 1) - pseudo_log_probs = torch.zeros_like(log_probs).scatter(-1, ids, 1.0) - - return pseudo_log_probs, decoder_mems_list - - -class BeamSearchSequenceGenerator(GreedySequenceGenerator): - def __init__(self, embedding, decoder, log_softmax, beam_size=1, len_pen=0, **kwargs): - """ - Beam Search sequence generator based on the decoder followed by - log_softmax. - - Args: - *all args of GreedySequenceGenerator class - beam_size: size of the beam - len_pen: length penalty parameter - Kwargs: - all remaining parameters of GreedySequenceGenerator class - """ - - super().__init__(embedding, decoder, log_softmax, **kwargs) - self.beam_size = beam_size - self.len_pen = len_pen - - @staticmethod - def compute_len_penalty(lengths, alpha): - """Returns length penalty according to https://arxiv.org/pdf/1609.08144.pdf""" - return ((5 + lengths) / 6).pow(alpha) - - def _forward( - self, decoder_input_ids=None, encoder_hidden_states=None, encoder_input_mask=None, return_beam_scores=False - ): - tgt, batch_size, max_generation_length = self._prepare_for_search(decoder_input_ids, encoder_hidden_states) - - # generate initial buffer of beam_size prefixes-hypotheses - log_probs, decoder_mems_list, xatt_scores_list = self._one_step_forward( - tgt, encoder_hidden_states, encoder_input_mask, None, 0 - ) - if not self.return_xattn_scores: - xatt_scores_list = None - scores, prefixes = torch.topk(log_probs.permute(0, 2, 1), self.beam_size, dim=1) - scores, prefixes = scores.view(-1, 1), prefixes.view(-1, 1) - - # repeat init target prefixes and cached memory states beam_size times - prefixes = torch.cat((tgt.repeat(1, self.beam_size).view(-1, tgt.shape[1]), prefixes), dim=1) - for j in range(len(decoder_mems_list)): - decoder_mems_list[j] = decoder_mems_list[j].repeat(self.beam_size, 1, 1) - - # repeat source sequence beam_size times for beam search - if encoder_hidden_states is not None: - _, src_length, hidden_size = encoder_hidden_states.size() - encoder_input_mask = encoder_input_mask.repeat(1, self.beam_size).view(-1, src_length) - encoder_hidden_states = encoder_hidden_states.repeat(1, self.beam_size, 1).view( - -1, src_length, hidden_size - ) - else: - hidden_size = decoder_mems_list[0].size(2) - - # repeat xattn scores - if xatt_scores_list is not None: - xatt_scores_list = [xatt_layer.repeat(self.beam_size, 1, 1, 1) for xatt_layer in xatt_scores_list] - - # pad_profile tracks finished hypotheses to generate only tokens - # if or has been generated - pad_profile = torch.zeros_like(scores).long() - - # prefixes_len tracks lengths of generated hypotheses to perform - # length penalty correction - prefixes_len = torch.zeros_like(scores).fill_(prefixes.size(1) + 1) - - tgt_len = tgt.size(-1) - for i in range(tgt_len, max_generation_length + tgt_len): - - # mask all finished hypotheses to exclude them from beam - pad_mask = pad_profile.repeat(1, self.beam_size) - - # generate and score candidates for prefixes continuation - log_probs, decoder_mems_list, next_xatt_scores_list = self._one_step_forward( - prefixes[:, -1:], encoder_hidden_states, encoder_input_mask, decoder_mems_list, i - ) - scores_i, prefixes_i = torch.topk(log_probs[:, -1, :], self.beam_size, dim=-1) - - # for all prefixes ending with or replace generated - # continuations with - prefixes_i = self.pad * pad_mask + prefixes_i * (1 - pad_mask) - - # force all hypotheses but one generated from already finished - # hypotheses to have extremely low score, so they will not be - # considered during beam re-ranking - pad_mask[:, 1:] = pad_mask[:, 1:] * NEG_INF - scores = scores + scores_i * (1 - pad_mask).to(scores.dtype) - - # choose top-k hypotheses with length penalty applied - len_penalties = self.compute_len_penalty(prefixes_len, self.len_pen) - scores = scores / len_penalties - scores, indices_i = torch.topk(scores.view(-1, self.beam_size**2), self.beam_size, dim=1) - scores = scores.view(-1, 1) * len_penalties - - # select prefixes which correspond to the chosen hypotheses - prefixes = prefixes.unsqueeze(1).repeat(1, self.beam_size, 1) - prefixes = torch.cat((prefixes, prefixes_i.unsqueeze(2)), dim=2) - prefixes = prefixes.view(batch_size, self.beam_size**2, -1) - p_len = prefixes.size(2) - prefixes_ids = indices_i.unsqueeze(2).repeat(1, 1, p_len) - prefixes = prefixes.gather(1, prefixes_ids).view(-1, p_len) - - # select xatt scores corresponding to chosen hypotheses - if self.return_xattn_scores and next_xatt_scores_list is not None: - num_heads = xatt_scores_list[0].shape[1] - xatt_indices_i = ( - indices_i.unsqueeze(2).unsqueeze(3).unsqueeze(4).repeat(1, 1, num_heads, p_len - 1, src_length) - // self.beam_size - ) - for layer in range(len(next_xatt_scores_list)): - xatt_layer_score_i = torch.cat((xatt_scores_list[layer], next_xatt_scores_list[layer]), dim=2) - xatt_scores_list[layer] = ( - xatt_layer_score_i.view(-1, self.beam_size, num_heads, p_len - 1, src_length) - .gather(1, xatt_indices_i) - .view(-1, num_heads, p_len - 1, src_length) - ) - - # reshuffle cached decoder memory states to restore the order - # of hypotheses broken after top-k selection - mems_ids = indices_i.unsqueeze(2).unsqueeze(3).repeat(1, 1, p_len - 1, hidden_size) // self.beam_size - for j in range(len(decoder_mems_list)): - decoder_mems_list[j] = ( - decoder_mems_list[j] - .view(-1, self.beam_size, p_len - 1, hidden_size) - .gather(1, mems_ids) - .view(-1, p_len - 1, hidden_size) - ) - - # update prefixes_len and pad_profile - not_eos_pad = prefixes.ne(self.eos) & prefixes.ne(self.pad) - prefixes_len = 1 + not_eos_pad.sum(dim=1, keepdim=True).to(scores.dtype) - pad_profile = (~not_eos_pad[:, -1:]).long() - - # if all hypotheses end with or , interrupt search - if pad_profile.sum() == batch_size * self.beam_size: - break - - # select best performing hypotheses in each element of the batch - len_penalties = self.compute_len_penalty(prefixes_len, self.len_pen) - scores = scores / len_penalties - best_guesses = torch.argmax(scores.view(-1, self.beam_size), dim=1, keepdim=True) - tgt_best_guesses = best_guesses.repeat(1, prefixes.size(1)).unsqueeze(1) - tgt = prefixes.view(batch_size, self.beam_size, -1).gather(1, tgt_best_guesses).squeeze(1) - - # select xatt scores for best hypotheses - if xatt_scores_list is not None: - _, num_heads, tgt_len, src_len = xatt_scores_list[0].shape - xatt_best_guesses = ( - best_guesses.unsqueeze(2).unsqueeze(3).unsqueeze(4).repeat(1, 1, num_heads, tgt_len, src_len) - ) - for layer in range(len(xatt_scores_list)): - xatt_scores_list[layer] = ( - xatt_scores_list[layer] - .view(-1, self.beam_size, num_heads, tgt_len, src_len) - .gather(1, xatt_best_guesses) - .squeeze(1) - ) - - if return_beam_scores: - return prefixes, scores * len_penalties, tgt, xatt_scores_list - else: - return tgt - - -class BeamSearchSequenceGeneratorWithFusionModels(BeamSearchSequenceGenerator): - def __init__( - self, embedding, decoder, log_softmax, fusion_models, fusion_models_alpha, beam_size=1, len_pen=0, **kwargs - ): - """ - Beam Search sequence generator based on the decoder followed by - log_softmax. - - Args: - *all args of BeamSearchSequenceGenerator class - ngram_lm_model: path to the n-gram language model; LM should use the same tokenizer as the current model - ngram_lm_alpha: n-gram LM weight - Kwargs: - all remaining parameters of BeamSearchSequenceGenerator class - """ - - super().__init__(embedding, decoder, log_softmax, beam_size=beam_size, len_pen=len_pen, **kwargs) - - self.fusion_models = fusion_models - self.fusion_models_alpha = fusion_models_alpha - - def _forward( - self, decoder_input_ids=None, encoder_hidden_states=None, encoder_input_mask=None, return_beam_scores=False - ): - device = encoder_hidden_states.device - # force fusion models to use the same device as encoder_hidden_states, since current class is not nn.Module instance - for fusion_model in self.fusion_models: - fusion_model.to(device) - - tgt, batch_size, max_generation_length = self._prepare_for_search(decoder_input_ids, encoder_hidden_states) - - batch_fusion_states_list = [ - fusion_model.get_init_states(batch_size=batch_size, bos=True) for fusion_model in self.fusion_models - ] - batch_fusion_states_candidates_list = [] - - # generate initial buffer of beam_size prefixes-hypotheses - log_probs, decoder_mems_list, xatt_scores_list = self._one_step_forward( - tgt, encoder_hidden_states, encoder_input_mask, None, 0 - ) - if not self.return_xattn_scores: - xatt_scores_list = None - # get fusion models scores - for fusion_model_idx, fusion_model in enumerate(self.fusion_models): - fusion_scores, batch_fusion_states_candidates = fusion_model.advance( - states=batch_fusion_states_list[fusion_model_idx], eos_id=self.eos - ) - batch_fusion_states_candidates_list.append(batch_fusion_states_candidates) - log_probs += self.fusion_models_alpha[fusion_model_idx] * fusion_scores[:, None, :] - - scores, prefixes = torch.topk(log_probs.permute(0, 2, 1), self.beam_size, dim=1) # [Batch, Beam, 1] - for fusion_model_idx, batch_fusion_states_candidates in enumerate(batch_fusion_states_candidates_list): - batch_fusion_states_list[fusion_model_idx] = batch_fusion_states_candidates.gather( - dim=1, index=prefixes.squeeze(-1) - ).view( - -1 - ) # [Batch, Beam] -> [Batch*Beam] - - scores, prefixes = scores.view(-1, 1), prefixes.view(-1, 1) # [Batch*Beam, 1] - - # repeat init target prefixes and cached memory states beam_size times - prefixes = torch.cat((tgt.repeat(1, self.beam_size).view(-1, tgt.shape[1]), prefixes), dim=1) - for j in range(len(decoder_mems_list)): - decoder_mems_list[j] = decoder_mems_list[j].repeat(self.beam_size, 1, 1) - - # repeat source sequence beam_size times for beam search - if encoder_hidden_states is not None: - _, src_length, hidden_size = encoder_hidden_states.size() - encoder_input_mask = encoder_input_mask.repeat(1, self.beam_size).view(-1, src_length) - encoder_hidden_states = encoder_hidden_states.repeat(1, self.beam_size, 1).view( - -1, src_length, hidden_size - ) - else: - hidden_size = decoder_mems_list[0].size(2) - - # repeat xattn scores - if xatt_scores_list is not None: - xatt_scores_list = [xatt_layer.repeat(self.beam_size, 1, 1, 1) for xatt_layer in xatt_scores_list] - - # pad_profile tracks finished hypotheses to generate only tokens - # if or has been generated - pad_profile = torch.zeros_like(scores).long() - - # prefixes_len tracks lengths of generated hypotheses to perform - # length penalty correction - prefixes_len = torch.zeros_like(scores).fill_(prefixes.size(1) + 1) - - tgt_len = tgt.size(-1) - for i in range(tgt_len, max_generation_length + tgt_len): - - # mask all finished hypotheses to exclude them from beam - pad_mask = pad_profile.repeat(1, self.beam_size) - - # generate and score candidates for prefixes continuation - log_probs, decoder_mems_list, next_xatt_scores_list = self._one_step_forward( - prefixes[:, -1:], encoder_hidden_states, encoder_input_mask, decoder_mems_list, i - ) - for fusion_model_idx, fusion_model in enumerate(self.fusion_models): - fusion_scores, batch_fusion_states_candidates = fusion_model.advance( - states=batch_fusion_states_list[fusion_model_idx], eos_id=self.eos - ) - log_probs += self.fusion_models_alpha[fusion_model_idx] * fusion_scores[:, None, :] - batch_fusion_states_candidates_list[fusion_model_idx] = batch_fusion_states_candidates - - scores_i, prefixes_i = torch.topk(log_probs[:, -1, :], self.beam_size, dim=-1) # [Batch*Beam, Beam] - - for fusion_model_idx, batch_fusion_states_candidates in enumerate(batch_fusion_states_candidates_list): - batch_fusion_states_list[fusion_model_idx] = batch_fusion_states_candidates.gather( - dim=1, index=prefixes_i - ) - - # for all prefixes ending with or replace generated - # continuations with - prefixes_i = self.pad * pad_mask + prefixes_i * (1 - pad_mask) - - # force all hypotheses but one generated from already finished - # hypotheses to have extremely low score, so they will not be - # considered during beam re-ranking - pad_mask[:, 1:] = pad_mask[:, 1:] * NEG_INF - scores = scores + scores_i * (1 - pad_mask).to(scores.dtype) - - # choose top-k hypotheses with length penalty applied - len_penalties = self.compute_len_penalty(prefixes_len, self.len_pen) - scores = scores / len_penalties - scores, indices_i = torch.topk(scores.view(-1, self.beam_size**2), self.beam_size, dim=1) # [Batch, Beam] - - for fusion_model_idx, batch_fusion_states in enumerate(batch_fusion_states_list): - batch_fusion_states_list[fusion_model_idx] = ( - batch_fusion_states.view(-1, self.beam_size**2).gather(dim=1, index=indices_i).view(-1) - ) - - scores = scores.view(-1, 1) * len_penalties # [Batch*Beam, 1] - - # select prefixes which correspond to the chosen hypotheses - prefixes = prefixes.unsqueeze(1).repeat(1, self.beam_size, 1) - prefixes = torch.cat((prefixes, prefixes_i.unsqueeze(2)), dim=2) - prefixes = prefixes.view(batch_size, self.beam_size**2, -1) - p_len = prefixes.size(2) - prefixes_ids = indices_i.unsqueeze(2).repeat(1, 1, p_len) - prefixes = prefixes.gather(1, prefixes_ids).view(-1, p_len) - - # select xatt scores corresponding to chosen hypotheses - if self.return_xattn_scores and next_xatt_scores_list is not None: - num_heads = xatt_scores_list[0].shape[1] - xatt_indices_i = ( - indices_i.unsqueeze(2).unsqueeze(3).unsqueeze(4).repeat(1, 1, num_heads, p_len - 1, src_length) - // self.beam_size - ) - for layer in range(len(next_xatt_scores_list)): - xatt_layer_score_i = torch.cat((xatt_scores_list[layer], next_xatt_scores_list[layer]), dim=2) - xatt_scores_list[layer] = ( - xatt_layer_score_i.view(-1, self.beam_size, num_heads, p_len - 1, src_length) - .gather(1, xatt_indices_i) - .view(-1, num_heads, p_len - 1, src_length) - ) - - # reshuffle cached decoder memory states to restore the order - # of hypotheses broken after top-k selection - mems_ids = indices_i.unsqueeze(2).unsqueeze(3).repeat(1, 1, p_len - 1, hidden_size) // self.beam_size - for j in range(len(decoder_mems_list)): - decoder_mems_list[j] = ( - decoder_mems_list[j] - .view(-1, self.beam_size, p_len - 1, hidden_size) - .gather(1, mems_ids) - .view(-1, p_len - 1, hidden_size) - ) - - # update prefixes_len and pad_profile - not_eos_pad = prefixes.ne(self.eos) & prefixes.ne(self.pad) - prefixes_len = 1 + not_eos_pad.sum(dim=1, keepdim=True).to(scores.dtype) - pad_profile = (~not_eos_pad[:, -1:]).long() - - # if all hypotheses end with or , interrupt search - if pad_profile.sum() == batch_size * self.beam_size: - break - - # select best performing hypotheses in each element of the batch - len_penalties = self.compute_len_penalty(prefixes_len, self.len_pen) - scores = scores / len_penalties - best_guesses = torch.argmax(scores.view(-1, self.beam_size), dim=1, keepdim=True) - tgt_best_guesses = best_guesses.repeat(1, prefixes.size(1)).unsqueeze(1) - tgt = prefixes.view(batch_size, self.beam_size, -1).gather(1, tgt_best_guesses).squeeze(1) - - # select xatt scores for best hypotheses - if xatt_scores_list is not None: - _, num_heads, tgt_len, src_len = xatt_scores_list[0].shape - xatt_best_guesses = ( - best_guesses.unsqueeze(2).unsqueeze(3).unsqueeze(4).repeat(1, 1, num_heads, tgt_len, src_len) - ) - for layer in range(len(xatt_scores_list)): - xatt_scores_list[layer] = ( - xatt_scores_list[layer] - .view(-1, self.beam_size, num_heads, tgt_len, src_len) - .gather(1, xatt_best_guesses) - .squeeze(1) - ) - - if return_beam_scores: - return prefixes, scores * len_penalties, tgt, xatt_scores_list - else: - return tgt - - -class EnsembleBeamSearchSequenceGenerator: - def __init__( - self, - encoders, - embeddings, - decoders, - log_softmaxes, - beam_size=1, - len_pen=0, - pad=0, - bos=1, - eos=2, - max_sequence_length=512, - max_delta_length=20, - batch_size=1, - language_model=None, - fusion_coef=None, - ): - """ - Ensemble Beam Search sequence generator based on the decoder followed by - log_softmax. Averages the probabilities of different models. - NOTE: All models must have been trained with the same BPE tokenizers. - - Args: - encoders: A list of encoders - embeddings: A list of decoder embedding layers - decoders: A list of decoders - log_softmaxes: A list of decoder output layers - beam_size: Beam size - len_pen: Length penalty to adjust logprob scores to favor longer sequences - pad: pad id - bos: beginning of sequence id - eos: end of sequence id - max_sequence_length: maximum sequence length - max_delta_length: maximum length difference between input and output - batch_size: batch size if not inferrable from input sequence - """ - self.encoders = encoders - self.embeddings = embeddings - self.decoders = decoders - self.log_softmaxes = log_softmaxes - self.beam_size = beam_size - self.len_pen = len_pen - self.pad, self.bos, self.eos = pad, bos, eos - self.max_seq_length = max_sequence_length - self.max_delta_len = max_delta_length - self.batch_size = batch_size - assert len(embeddings) == len(decoders) == len(log_softmaxes) == len(encoders) - self.num_models = len(encoders) - self.language_model = language_model - self.fusion_coef = fusion_coef - - @staticmethod - def compute_len_penalty(lengths, alpha): - """Returns length penalty according to https://arxiv.org/pdf/1609.08144.pdf""" - return ((5 + lengths) / 6).pow(alpha) - - def _one_step_forward_lm(self, decoder_input_ids=None, lm_mems_list=None, pos=0): - input_mask = mask_padded_tokens(decoder_input_ids, self.pad).float() - lm_hidden_states = self.language_model.encoder.embedding.forward(decoder_input_ids, start_pos=pos) - lm_mems_list = self.language_model.encoder.encoder.forward( - lm_hidden_states, - input_mask, - lm_mems_list, - return_mems=True, - ) - lm_log_probs = self.language_model.log_softmax.forward(hidden_states=lm_mems_list[-1][:, -1:]) - return lm_log_probs, lm_mems_list - - def _one_step_forward( - self, - ensemble_index, - decoder_input_ids=None, - encoder_hidden_states=None, - encoder_input_mask=None, - decoder_mems_list=None, - pos=0, - ): - """ - One step of autoregressive output generation for one particular model. - - Args: - decoder_input_ids: starting sequence of tokens to generate from; - if None, generation will start from a batch of tokens - encoder_hidden_states: output of the encoder for conditional - sequence generation; if None, generator will use unconditional - mode (e.g., language modeling) - encoder_input_mask: input mask used in the encoder - decoder_mems_list: list of size num_layers with cached activations - of sequence (x[1], ..., x[k-1]) for fast generation of x[k] - pos: starting position in positional encoding - """ - - decoder_hidden_states = self.embeddings[ensemble_index].forward(decoder_input_ids, start_pos=pos) - decoder_input_mask = mask_padded_tokens(decoder_input_ids, self.pad).float() - - if encoder_hidden_states is not None: - decoder_mems_list = self.decoders[ensemble_index].forward( - decoder_hidden_states, - decoder_input_mask, - encoder_hidden_states, - encoder_input_mask, - decoder_mems_list, - return_mems=True, - ) - else: - decoder_mems_list = self.decoders[ensemble_index].forward( - decoder_hidden_states, decoder_input_mask, decoder_mems_list, return_mems=True - ) - log_probs = self.log_softmaxes[ensemble_index].forward(hidden_states=decoder_mems_list[-1][:, -1:]) - return log_probs, decoder_mems_list - - def _prepare_for_search(self, decoder_input_ids=None, encoder_hidden_states=None): - """ - Helper function which defines starting sequence to begin generating - with and maximum allowed number of tokens to be generated. - """ - - decoder_parameter = next(self.decoders[0].parameters()) - batch_size = self.batch_size - - # for encoder-decoder generation, maximum length of generated sequence - # is min(max_sequence_length, src_len + max_delta_length) - if encoder_hidden_states is not None: - batch_size, src_len, _ = encoder_hidden_states.size() - if self.max_delta_len >= 0: - max_seq_length = min(self.max_seq_length, src_len + self.max_delta_len) - else: - max_seq_length = self.max_seq_length - else: - max_seq_length = self.max_seq_length - - # if no input is provided, start with the batch of tokens - if decoder_input_ids is not None: - tgt = decoder_input_ids - batch_size, tgt_len = decoder_input_ids.size() - else: - tgt = torch.zeros(batch_size, 1).long().fill_(self.bos).to(decoder_parameter.device) - tgt_len = 1 - max_generation_length = max_seq_length - tgt_len - - return tgt, batch_size, max_generation_length - - def _get_encoder_hidden_states(self, src_ids, encoder_input_mask, ensemble_index): - return self.encoders[ensemble_index](input_ids=src_ids, encoder_mask=encoder_input_mask) - - def _average_probs(self, probs_list): - probs_list = torch.stack(probs_list) - return torch.log(torch.exp(probs_list).mean(0)) - # probs = torch.stack(probs_list) # Ens x B x T x V - # return torch.log(probs.sum(0) / probs.sum(-1).sum(0).unsqueeze(-1)) - - def _forward(self, src_ids, encoder_input_mask, decoder_input_ids=None, return_beam_scores=False): - encoder_hidden_states = [ - self._get_encoder_hidden_states(src_ids, encoder_input_mask, i) for i in range(self.num_models) - ] - tgt, batch_size, max_generation_length = self._prepare_for_search(decoder_input_ids, encoder_hidden_states[0]) - - # generate initial buffer of beam_size prefixes-hypotheses - outputs = [ - self._one_step_forward(i, tgt, encoder_hidden_states[i], encoder_input_mask, None, 0) - for i in range(self.num_models) - ] - nmt_log_probs = self._average_probs([x[0] for x in outputs]) - decoder_mems_lists = [x[1] for x in outputs] - - if self.language_model is not None: - lm_log_probs, lm_mems_list = self._one_step_forward_lm(tgt, None, 0) - log_probs = nmt_log_probs + self.fusion_coef * lm_log_probs - else: - log_probs = nmt_log_probs - scores, prefixes = torch.topk(log_probs.permute(0, 2, 1), self.beam_size, dim=1) - scores, prefixes = scores.view(-1, 1), prefixes.view(-1, 1) - - # repeat init target prefixes and cached memory states beam_size times - prefixes = torch.cat((tgt.repeat(1, self.beam_size).view(-1, 1), prefixes), dim=1) - for i in range(self.num_models): - for j in range(len(decoder_mems_lists[i])): - decoder_mems_lists[i][j] = decoder_mems_lists[i][j].repeat(self.beam_size, 1, 1) - - if self.language_model is not None: - for j in range(len(lm_mems_list)): - lm_mems_list[j] = lm_mems_list[j].repeat(self.beam_size, 1, 1) - lm_hidden_size = lm_mems_list[0].size(2) - - encoder_input_mask = encoder_input_mask.repeat(1, self.beam_size).view(-1, encoder_input_mask.size(1)) - for i in range(self.num_models): - _, src_length, hidden_size = encoder_hidden_states[i].size() - encoder_hidden_states[i] = ( - encoder_hidden_states[i].repeat(1, self.beam_size, 1).view(-1, src_length, hidden_size) - ) - - # pad_profile tracks finished hypotheses to generate only tokens - # if or has been generated - pad_profile = torch.zeros_like(scores).long() - - # prefixes_len tracks lengths of generated hypotheses to perform - # length penalty correction - prefixes_len = torch.zeros_like(scores).fill_(prefixes.size(1) + 1) - - for i in range(max_generation_length): - - # mask all finished hypotheses to exclude them from beam - pad_mask = pad_profile.repeat(1, self.beam_size) - - # generate and score candidates for prefixes continuation - outputs = [ - self._one_step_forward( - model_num, - prefixes[:, -1:], - encoder_hidden_states[model_num], - encoder_input_mask, - decoder_mems_lists[model_num], - i + 1, - ) - for model_num in range(self.num_models) - ] - nmt_log_probs = self._average_probs([x[0] for x in outputs]) - decoder_mems_lists = [x[1] for x in outputs] - - if self.language_model is not None: - lm_log_probs, lm_mems_list = self._one_step_forward_lm(prefixes[:, -1:], lm_mems_list, i + 1) - log_probs = nmt_log_probs + self.fusion_coef * lm_log_probs - else: - log_probs = nmt_log_probs - scores_i, prefixes_i = torch.topk(log_probs[:, -1, :], self.beam_size, dim=-1) - - # for all prefixes ending with or replace generated - # continuations with - prefixes_i = self.pad * pad_mask + prefixes_i * (1 - pad_mask) - - # force all hypotheses but one generated from already finished - # hypotheses to have extremely low score, so they will not be - # considered during beam re-ranking - pad_mask[:, 1:] = pad_mask[:, 1:] * NEG_INF - scores = scores + scores_i * (1 - pad_mask).to(scores.dtype) - - # choose top-k hypotheses with length penalty applied - len_penalties = self.compute_len_penalty(prefixes_len, self.len_pen) - scores = scores / len_penalties - scores, indices_i = torch.topk(scores.view(-1, self.beam_size**2), self.beam_size, dim=1) - scores = scores.view(-1, 1) * len_penalties - - # select prefixes which correspond to the chosen hypotheses - prefixes = prefixes.unsqueeze(1).repeat(1, self.beam_size, 1) - prefixes = torch.cat((prefixes, prefixes_i.unsqueeze(2)), dim=2) - prefixes = prefixes.view(batch_size, self.beam_size**2, -1) - p_len = prefixes.size(2) - prefixes_ids = indices_i.unsqueeze(2).repeat(1, 1, p_len) - prefixes = prefixes.gather(1, prefixes_ids).view(-1, p_len) - - # reshuffle cached decoder memory states to restore the order - # of hypotheses broken after top-k selection - for model_num in range(self.num_models): - hidden_size = decoder_mems_lists[model_num][0].size(2) - mems_ids = indices_i.unsqueeze(2).unsqueeze(3).repeat(1, 1, p_len - 1, hidden_size) // self.beam_size - for j in range(len(decoder_mems_lists[model_num])): - decoder_mems_lists[model_num][j] = ( - decoder_mems_lists[model_num][j] - .view(-1, self.beam_size, p_len - 1, hidden_size) - .gather(1, mems_ids) - .view(-1, p_len - 1, hidden_size) - ) - if self.language_model is not None: - lm_mems_ids = ( - indices_i.unsqueeze(2).unsqueeze(3).repeat(1, 1, p_len - 1, lm_hidden_size) // self.beam_size - ) - for j in range(len(lm_mems_list)): - lm_mems_list[j] = ( - lm_mems_list[j] - .view(-1, self.beam_size, p_len - 1, lm_hidden_size) - .gather(1, lm_mems_ids) - .view(-1, p_len - 1, lm_hidden_size) - ) - - # update prefixes_len and pad_profile - not_eos_pad = prefixes.ne(self.eos) & prefixes.ne(self.pad) - prefixes_len = 1 + not_eos_pad.sum(dim=1, keepdim=True).to(scores.dtype) - pad_profile = (~not_eos_pad[:, -1:]).long() - - # if all hypotheses end with or , interrupt search - if pad_profile.sum() == batch_size * self.beam_size: - break - - # select best performing hypotheses in each element of the batch - len_penalties = self.compute_len_penalty(prefixes_len, self.len_pen) - scores = scores / len_penalties - best_guesses = ( - torch.argmax(scores.view(-1, self.beam_size), dim=1, keepdim=True).repeat(1, prefixes.size(1)).unsqueeze(1) - ) - tgt = prefixes.view(batch_size, self.beam_size, -1).gather(1, best_guesses).squeeze(1) - - if return_beam_scores: - return prefixes, scores * len_penalties, tgt - else: - return tgt - - def __call__(self, src_ids, encoder_input_mask, decoder_input_ids=None, return_beam_scores=False): - with torch.inference_mode(): - return self._forward(src_ids, encoder_input_mask, decoder_input_ids, return_beam_scores) - - def freeze(self) -> None: - """Freeze weights of embedding, decoder, and classification layers to prevent memory leak.""" - for model_num in range(self.num_models): - for param in self.embeddings[model_num].parameters(): - param.requires_grad = False - self.embeddings[model_num].eval() - for param in self.decoders[model_num].parameters(): - param.requires_grad = False - self.decoders[model_num].eval() - for param in self.log_softmaxes[model_num].parameters(): - param.requires_grad = False - self.log_softmaxes[model_num].eval() - for param in self.encoders[model_num].parameters(): - param.requires_grad = False - self.encoders[model_num].eval() - - def unfreeze(self) -> None: - """Unfreeze weights of embedding, decoder, and classification layers.""" - for model_num in range(self.num_models): - for param in self.embeddings[model_num].parameters(): - param.requires_grad = True - self.embeddings[model_num].train() - for param in self.decoders[model_num].parameters(): - param.requires_grad = True - self.decoders[model_num].train() - for param in self.log_softmaxes[model_num].parameters(): - param.requires_grad = True - self.log_softmaxes[model_num].train() - for param in self.encoders[model_num].parameters(): - param.requires_grad = True - self.encoders[model_num].train() - - @contextmanager - def as_frozen(self): - """ - Context manager which temporarily freezes embedding, decoder, and log_softmax modules, - yields control and finally unfreezes the modules. - """ - self.freeze() - - try: - yield - finally: - self.unfreeze() - - -class BeamSearchSequenceGeneratorWithLanguageModel(GreedySequenceGenerator): - def __init__( - self, embedding, decoder, log_softmax, language_model, beam_size=1, len_pen=0, fusion_coef=0.0, **kwargs - ): - """ - Beam Search sequence generator based on the decoder followed by log_softmax - with external language model fusion. - Args: - *all args of BeamSearchSequenceGenerator class - language_model: nemo TransformerLMModel - fusion_coef: coefficient before language model score, the resulting score is - score = log P_NMT(y|x) + fusion_coef * log P_LM(y) - Kwargs: - all remaining parameters of GreedySequenceGenerator class - """ - - super().__init__(embedding, decoder, log_softmax, **kwargs) - self.language_model = language_model - self.beam_size = beam_size - self.len_pen = len_pen - self.fusion_coef = fusion_coef - - def _one_step_forward( - self, - decoder_input_ids=None, - encoder_hidden_states=None, - encoder_input_mask=None, - decoder_mems_list=None, - lm_mems_list=None, - pos=0, - ): - - nmt_log_probs, decoder_mems_list, _ = super()._one_step_forward( - decoder_input_ids, - encoder_hidden_states, - encoder_input_mask, - decoder_mems_list, - pos, - ) - input_mask = mask_padded_tokens(decoder_input_ids, self.pad).float() - lm_hidden_states = self.language_model.encoder.embedding.forward(decoder_input_ids, start_pos=pos) - - lm_mems_list = self.language_model.encoder.encoder.forward( - lm_hidden_states, - input_mask, - lm_mems_list, - return_mems=True, - ) - lm_log_probs = self.language_model.log_softmax.forward(hidden_states=lm_mems_list[-1][:, -1:]) - - log_probs = nmt_log_probs + self.fusion_coef * lm_log_probs - - return log_probs, decoder_mems_list, lm_mems_list - - @staticmethod - def compute_len_penalty(lengths, alpha): - """Returns length penalty according to https://arxiv.org/pdf/1609.08144.pdf""" - return ((5 + lengths) / 6).pow(alpha) - - def _forward( - self, decoder_input_ids=None, encoder_hidden_states=None, encoder_input_mask=None, return_beam_scores=False - ): - - tgt, batch_size, max_generation_length = self._prepare_for_search(decoder_input_ids, encoder_hidden_states) - - # generate initial buffer of beam_size prefixes-hypotheses - log_probs, decoder_mems_list, lm_mems_list = self._one_step_forward( - tgt, encoder_hidden_states, encoder_input_mask, None, None, 0 - ) - scores, prefixes = torch.topk(log_probs.permute(0, 2, 1), self.beam_size, dim=1) - scores, prefixes = scores.view(-1, 1), prefixes.view(-1, 1) - - # repeat init target prefixes and cached memory states beam_size times - prefixes = torch.cat((tgt.repeat(1, self.beam_size).view(-1, 1), prefixes), dim=1) - for j in range(len(decoder_mems_list)): - decoder_mems_list[j] = decoder_mems_list[j].repeat(self.beam_size, 1, 1) - for j in range(len(lm_mems_list)): - lm_mems_list[j] = lm_mems_list[j].repeat(self.beam_size, 1, 1) - - # repeat source sequence beam_size times for beam search - if encoder_hidden_states is not None: - _, src_length, hidden_size = encoder_hidden_states.size() - encoder_input_mask = encoder_input_mask.repeat(1, self.beam_size).view(-1, src_length) - encoder_hidden_states = encoder_hidden_states.repeat(1, self.beam_size, 1).view( - -1, src_length, hidden_size - ) - else: - hidden_size = decoder_mems_list[0].size(2) - lm_hidden_size = lm_mems_list[0].size(2) - - # pad_profile tracks finished hypotheses to generate only tokens - # if or has been generated - pad_profile = torch.zeros_like(scores).long() - - # prefixes_len tracks lengths of generated hypotheses to perform - # length penalty correction - prefixes_len = torch.zeros_like(scores).fill_(prefixes.size(1) + 1) - - for i in range(max_generation_length): - - # mask all finished hypotheses to exclude them from beam - pad_mask = pad_profile.repeat(1, self.beam_size) - - # generate and score candidates for prefixes continuation - log_probs, decoder_mems_list, lm_mems_list = self._one_step_forward( - prefixes[:, -1:], encoder_hidden_states, encoder_input_mask, decoder_mems_list, lm_mems_list, i + 1 - ) - scores_i, prefixes_i = torch.topk(log_probs[:, -1, :], self.beam_size, dim=-1) - - # for all prefixes ending with or replace generated - # continuations with - prefixes_i = self.pad * pad_mask + prefixes_i * (1 - pad_mask) - - # force all hypotheses but one generated from already finished - # hypotheses to have extremely low score, so they will not be - # considered during beam re-ranking - pad_mask[:, 1:] = pad_mask[:, 1:] * NEG_INF - scores = scores + scores_i * (1 - pad_mask).to(scores.dtype) - - # choose top-k hypotheses with length penalty applied - len_penalties = self.compute_len_penalty(prefixes_len, self.len_pen) - scores = scores / len_penalties - scores, indices_i = torch.topk(scores.view(-1, self.beam_size**2), self.beam_size, dim=1) - scores = scores.view(-1, 1) * len_penalties - - # select prefixes which correspond to the chosen hypotheses - prefixes = prefixes.unsqueeze(1).repeat(1, self.beam_size, 1) - prefixes = torch.cat((prefixes, prefixes_i.unsqueeze(2)), dim=2) - prefixes = prefixes.view(batch_size, self.beam_size**2, -1) - p_len = prefixes.size(2) - prefixes_ids = indices_i.unsqueeze(2).repeat(1, 1, p_len) - prefixes = prefixes.gather(1, prefixes_ids).view(-1, p_len) - - # reshuffle cached decoder memory states to restore the order - # of hypotheses broken after top-k selection - mems_ids = indices_i.unsqueeze(2).unsqueeze(3).repeat(1, 1, p_len - 1, hidden_size) // self.beam_size - for j in range(len(decoder_mems_list)): - decoder_mems_list[j] = ( - decoder_mems_list[j] - .view(-1, self.beam_size, p_len - 1, hidden_size) - .gather(1, mems_ids) - .view(-1, p_len - 1, hidden_size) - ) - lm_mems_ids = indices_i.unsqueeze(2).unsqueeze(3).repeat(1, 1, p_len - 1, lm_hidden_size) // self.beam_size - for j in range(len(lm_mems_list)): - lm_mems_list[j] = ( - lm_mems_list[j] - .view(-1, self.beam_size, p_len - 1, lm_hidden_size) - .gather(1, lm_mems_ids) - .view(-1, p_len - 1, lm_hidden_size) - ) - - # update prefixes_len and pad_profile - not_eos_pad = prefixes.ne(self.eos) & prefixes.ne(self.pad) - prefixes_len = 1 + not_eos_pad.sum(dim=1, keepdim=True).to(scores.dtype) - pad_profile = (~not_eos_pad[:, -1:]).long() - - # if all hypotheses end with or , interrupt search - if pad_profile.sum() == batch_size * self.beam_size: - break - - # select best performing hypotheses in each element of the batch - len_penalties = self.compute_len_penalty(prefixes_len, self.len_pen) - scores = scores / len_penalties - best_guesses = ( - torch.argmax(scores.view(-1, self.beam_size), dim=1, keepdim=True).repeat(1, prefixes.size(1)).unsqueeze(1) - ) - tgt = prefixes.view(batch_size, self.beam_size, -1).gather(1, best_guesses).squeeze(1) - - if return_beam_scores: - return prefixes, scores * len_penalties, tgt - else: - return tgt diff --git a/nemo/collections/asr/modules/transformer/transformer_modules.py b/nemo/collections/asr/modules/transformer/transformer_modules.py deleted file mode 100644 index 5c45aca92237d87c701648747722cffdb4bd7a70..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/transformer/transformer_modules.py +++ /dev/null @@ -1,303 +0,0 @@ -# Copyright 2018 The Google AI Language Team Authors and -# The HuggingFace Inc. team. -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import math - -import numpy as np -import torch -from torch import nn -from torch.nn.functional import gelu - -from nemo.collections.common.parts import form_attention_mask - -__all__ = ["TransformerEmbedding", "AttentionBridge"] - - -class FixedPositionalEncoding(nn.Module): - """ - Fixed positional encoding (embedding layer) from sine and cosine functions - of different frequencies according to https://arxiv.org/abs/1706.03762 - - Args: - hidden_size: size of the embeddings in the model, also known as d_model - max_sequence_length: maximum allowed length of the input sequence - """ - - def __init__(self, hidden_size, max_sequence_length=512): - super().__init__() - - self._hidden_size = hidden_size - self._max_sequence_length = max_sequence_length - self._build_pos_enc(hidden_size=self._hidden_size, max_sequence_length=self._max_sequence_length) - - def _build_pos_enc(self, hidden_size, max_sequence_length, device=None): - """ - Builds/replaces pre-computed positional encoding. - """ - pos_enc = torch.zeros(max_sequence_length, hidden_size, device=device) - position = torch.arange(0.0, max_sequence_length).unsqueeze(1) - coef = -math.log(10000.0) / hidden_size - div_term = torch.exp(coef * torch.arange(0.0, hidden_size, 2)) - pos_enc[:, 0::2] = torch.sin(position * div_term) - pos_enc[:, 1::2] = torch.cos(position * div_term) - pos_enc.div_(math.sqrt(hidden_size)) - self.register_buffer('pos_enc', pos_enc) - - def forward(self, position_ids): - embeddings = torch.embedding(self.pos_enc, position_ids) - return embeddings - - -class TransformerEmbedding(nn.Module): - """ - Embedding from token and position embeddings. - Optionally add token_type embedding (e.g. type of the sentence in BERT). - - Args: - vocab_size: size of the vocabulary - hidden_size: size of the embeddings in the model, also known as d_model - max_sequence_length: maximum allowed length of the input sequence - num_token_types: number of different token types - (e.g. tokens of sentence A and tokens of sentence B in BERT) - embedding_dropout: probability of dropout applied to embeddings - learn_positional_encodings: whether to learn positional encodings or - use fixed (sine-cosine) ones - """ - - def __init__( - self, - vocab_size, - hidden_size, - max_sequence_length=512, - num_token_types=2, - embedding_dropout=0.0, - learn_positional_encodings=False, - ): - super().__init__() - - self.max_sequence_length = max_sequence_length - self.learn_positional_encodings = learn_positional_encodings - self.token_embedding = nn.Embedding(vocab_size, hidden_size, padding_idx=0) - if learn_positional_encodings: - self.position_embedding = nn.Embedding(max_sequence_length, hidden_size) - else: - self.position_embedding = FixedPositionalEncoding(hidden_size, max_sequence_length) - if num_token_types > 0: - self.token_type_embedding = nn.Embedding(num_token_types, hidden_size) - self.layer_norm = nn.LayerNorm(hidden_size, eps=1e-5) - self.dropout = nn.Dropout(embedding_dropout) - - def forward(self, input_ids, token_type_ids=None, start_pos=0): - seq_length = input_ids.size(1) - # we fail here only with parametric positional embedding. FixedPositionalEncoding automatically extends. - if self.learn_positional_encodings and (seq_length > self.max_sequence_length): - raise ValueError( - f"Input sequence is longer than maximum allowed sequence length for positional encoding. " - f"Got {seq_length} and {self.max_sequence_length}" - ) - - # prepare position embedding for asynchronius decoding (canary streaming) - if torch.is_tensor(start_pos): - shift_pos = start_pos.unsqueeze(-1) - start_pos = 0 - else: - shift_pos = None - - position_ids = torch.arange( - start=start_pos, end=start_pos + seq_length, dtype=torch.long, device=input_ids.device - ) - position_ids = position_ids.unsqueeze(0).repeat(input_ids.size(0), 1) - if torch.is_tensor(shift_pos): - # shift_pos is a tensor, so we need to add it to the position_ids - # and make sure that the resulting position_ids are within the - # range of the positional embedding - position_ids = position_ids + shift_pos - - token_embeddings = self.token_embedding(input_ids) - position_embeddings = self.position_embedding(position_ids) - embeddings = token_embeddings + position_embeddings - - if token_type_ids is not None: - token_type_embeddings = self.token_type_embedding(token_type_ids) - embeddings = embeddings + token_type_embeddings - - embeddings = self.layer_norm(embeddings) - embeddings = self.dropout(embeddings) - - return embeddings - - -class MultiHeadAttention(nn.Module): - """ - Multi-head scaled dot-product attention layer. - - Args: - hidden_size: size of the embeddings in the model, also known as d_model - num_attention_heads: number of heads in multi-head attention - attn_score_dropout: probability of dropout applied to attention scores - attn_layer_dropout: probability of dropout applied to the output of the - whole layer, but before layer normalization - """ - - def __init__( - self, - hidden_size, - num_attention_heads, - attn_score_dropout=0.0, - attn_layer_dropout=0.0, - return_xatt_scores=False, - ): - super().__init__() - if hidden_size % num_attention_heads != 0: - raise ValueError( - "The hidden size (%d) is not a multiple of the number " - "of attention heads (%d)" % (hidden_size, num_attention_heads) - ) - self.hidden_size = hidden_size - self.num_attention_heads = num_attention_heads - self.attn_head_size = int(hidden_size / num_attention_heads) - self.attn_scale = math.sqrt(math.sqrt(self.attn_head_size)) - - self.query_net = nn.Linear(hidden_size, hidden_size) - self.key_net = nn.Linear(hidden_size, hidden_size) - self.value_net = nn.Linear(hidden_size, hidden_size) - self.out_projection = nn.Linear(hidden_size, hidden_size) - - self.attn_dropout = nn.Dropout(attn_score_dropout) - self.layer_dropout = nn.Dropout(attn_layer_dropout) - self.return_xatt_scores = return_xatt_scores - - def transpose_for_scores(self, x): - new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attn_head_size) - x = x.view(*new_x_shape) - return x.permute(0, 2, 1, 3) - - def forward(self, queries, keys, values, attention_mask): - - # attention_mask is needed to hide the tokens which correspond to [PAD] - # in the case of BERT, or to hide the future tokens in the case of - # vanilla language modeling and translation - query = self.query_net(queries) - key = self.key_net(keys) - value = self.value_net(values) - query = self.transpose_for_scores(query) / self.attn_scale - key = self.transpose_for_scores(key) / self.attn_scale - value = self.transpose_for_scores(value) - - # for numerical stability we pre-divide query and key by sqrt(sqrt(d)) - attention_scores = torch.matmul(query, key.transpose(-1, -2)) - if attention_mask is not None: - attention_scores = attention_scores + attention_mask.to(attention_scores.dtype) - attention_probs = torch.softmax(attention_scores, dim=-1) - attention_probs = self.attn_dropout(attention_probs) - - context = torch.matmul(attention_probs, value) - context_hidden_size = context.size()[-1] * self.num_attention_heads - context = context.permute(0, 2, 1, 3).contiguous() - new_context_shape = context.size()[:-2] + (context_hidden_size,) - context = context.view(*new_context_shape) - - # output projection - output_states = self.out_projection(context) - output_states = self.layer_dropout(output_states) - - extra_output = {} - if self.return_xatt_scores: - extra_output['xatt_scores'] = attention_probs - - return output_states, extra_output - - -class PositionWiseFF(nn.Module): - """ - Position-wise feed-forward network of Transformer block. - - Args: - hidden_size: size of the embeddings in the model, also known as d_model - inner_size: number of neurons in the intermediate part of feed-forward - net, usually is (4-8 x hidden_size) in the papers - ffn_dropout: probability of dropout applied to net output - hidden_act: activation function used between two linear layers - """ - - def __init__(self, hidden_size, inner_size, ffn_dropout=0.0, hidden_act="relu"): - super().__init__() - self.dense_in = nn.Linear(hidden_size, inner_size) - self.dense_out = nn.Linear(inner_size, hidden_size) - self.layer_dropout = nn.Dropout(ffn_dropout) - ACT2FN = {"gelu": gelu, "relu": torch.relu} - self.act_fn = ACT2FN[hidden_act] - - def forward(self, hidden_states): - output_states = self.dense_in(hidden_states) - output_states = self.act_fn(output_states) - output_states = self.dense_out(output_states) - output_states = self.layer_dropout(output_states) - return output_states - - -class AttentionBridge(torch.nn.Module): - """ - A multi-head attention bridge to project a variable-size hidden states - to k hidden states (per attention head). - - Code is based on the paper https://arxiv.org/pdf/1703.03130.pdf - """ - - def __init__(self, hidden_size, k, bridge_size): - """ - hidden_size - size of input hidden state - k - number of attention heads - bridge_size - size of internal feed forward weights (i.e., attention head size) - """ - super().__init__() - - self.hidden_size = hidden_size - self.k = k - self.bridge_size = bridge_size - - self.attn_scale = np.sqrt(np.sqrt(self.bridge_size)) - - # build model - - self.W1 = torch.nn.Linear(hidden_size, bridge_size, bias=False) - self.W2 = torch.nn.Linear(bridge_size, k, bias=False) - self.act = torch.nn.ReLU() - - def forward(self, hidden, hidden_mask=None, return_ortho_loss=False): - """ - Project hidden [B x N x H] to fixed-size [B x k x H] - - return_ortho_loss - if True returns loss term to encourage - orthogonal attention vectors - """ - - attention_scores = self.W2(self.act(self.W1(hidden) / self.attn_scale) / self.attn_scale).transpose(-1, -2) - - attention_mask = form_attention_mask(hidden_mask) - if attention_mask is not None: - attention_mask.squeeze_(1) - attention_scores = attention_scores + attention_mask.to(attention_scores.dtype) - - A = torch.softmax(attention_scores, dim=-1) - M = A @ hidden - - if return_ortho_loss: - ortho_loss = ((A @ A.transpose(-1, -2)) - torch.eye(self.k).type_as(A)).pow(2).sum() - - return M, ortho_loss - else: - return M diff --git a/nemo/collections/asr/modules/transformer/transformer_utils.py b/nemo/collections/asr/modules/transformer/transformer_utils.py deleted file mode 100644 index 5de1652ee1b0fc9323102d37acaa6342126eb0aa..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/transformer/transformer_utils.py +++ /dev/null @@ -1,135 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from typing import Optional, Union - -from omegaconf.dictconfig import DictConfig - -from nemo.collections.asr.modules.transformer.transformer import TransformerDecoderNM, TransformerEncoderNM -from nemo.collections.asr.modules.transformer.transformer_bottleneck import TransformerBottleneckEncoderNM - -__all__ = ['get_nemo_transformer'] - - -def get_nemo_transformer( - model_name: Optional[str] = None, - pretrained: bool = False, - config_dict: Optional[Union[dict, DictConfig]] = None, - encoder: bool = True, - pre_ln_final_layer_norm: bool = True, -) -> Union[TransformerEncoderNM, TransformerDecoderNM]: - """Returns NeMo transformer. - The following configurations are mandatory: - vocab_size: int - hidden_size: int - num_layers: int - inner_size: int - and must be specified if using config_dict. - - Args: - model_name (Optional[str]): model name to download from NGC - pretrained: (bool): False will instantiate the named model architecture with random weights. - config_dict (Optional[dict], optional): model configuration parameters. Defaults to None. - config_file (Optional[str], optional): path to json file containing model configuration. Defaults to None. - checkpoint_file (Optional[str], optional): load weights from path to local checkpoint. Defaults to None. - encoder (bool, optional): True will use EncoderTransformerNM, False will use DecoderTransformerNM. Defaults to True. - """ - if model_name is not None: - raise ValueError(f'NeMo transformers cannot be loaded from NGC yet. model_name should be None') - - if pretrained: - raise ValueError(f'NeMo transformers cannot be loaded from NGC yet. pretrained should be False') - - cfg = None - - if not pretrained: - assert ( - config_dict.get('vocab_size') is not None - and config_dict.get('hidden_size') is not None - and config_dict.get('num_layers') is not None - and config_dict.get('inner_size') is not None - ), f'Using config_dict: {config_dict}. vocab_size, hidden_size, num_layers, and inner_size must are mandatory arguments' - - cfg = config_dict - - if encoder: - # if arch exists in cfg we return TransformerBottleneckEncoderNM - arch = cfg.get('arch', '') - if not arch: - model = TransformerEncoderNM( - vocab_size=cfg.get('vocab_size'), - hidden_size=cfg.get('hidden_size'), - num_layers=cfg.get('num_layers'), - inner_size=cfg.get('inner_size'), - max_sequence_length=cfg.get('max_sequence_length', 512), - embedding_dropout=cfg.get('embedding_dropout', 0.0), - learn_positional_encodings=cfg.get('learn_positional_encodings', False), - num_attention_heads=cfg.get('num_attention_heads'), - ffn_dropout=cfg.get('ffn_dropout', 0.0), - attn_score_dropout=cfg.get('attn_score_dropout', 0.0), - attn_layer_dropout=cfg.get('attn_layer_dropout', 0.0), - hidden_act=cfg.get('hidden_act', 'relu'), - mask_future=cfg.get('mask_future', True), - pre_ln=cfg.get('pre_ln', False), - pre_ln_final_layer_norm=pre_ln_final_layer_norm, - num_token_types=cfg.get('num_token_types', 2), - ) - elif arch in TransformerBottleneckEncoderNM._SUPPORTED_ARCH: - model = TransformerBottleneckEncoderNM( - vocab_size=cfg.get('vocab_size'), - hidden_size=cfg.get('hidden_size'), - num_layers=cfg.get('num_layers'), - inner_size=cfg.get('inner_size'), - max_sequence_length=cfg.get('max_sequence_length', 512), - embedding_dropout=cfg.get('embedding_dropout', 0.0), - learn_positional_encodings=cfg.get('learn_positional_encodings', False), - num_attention_heads=cfg.get('num_attention_heads'), - ffn_dropout=cfg.get('ffn_dropout', 0.0), - attn_score_dropout=cfg.get('attn_score_dropout', 0.0), - attn_layer_dropout=cfg.get('attn_layer_dropout', 0.0), - hidden_act=cfg.get('hidden_act', 'relu'), - mask_future=cfg.get('mask_future', False), - pre_ln=cfg.get('pre_ln', False), - pre_ln_final_layer_norm=pre_ln_final_layer_norm, - num_token_types=cfg.get('num_token_types', 2), - arch=cfg.get('arch', 'full'), - hidden_steps=cfg.get('hidden_steps', -1), - hidden_blocks=cfg.get('hidden_blocks', 1), - hidden_init_method=cfg.get('hidden_init_method', 'default'), - return_mask=cfg.get('return_mask', True), - ) - else: - raise ValueError(f"Unknown arch = {arch}") - else: - - model = TransformerDecoderNM( - vocab_size=cfg.get('vocab_size'), - hidden_size=cfg.get('hidden_size'), - num_layers=cfg.get('num_layers'), - inner_size=cfg.get('inner_size'), - max_sequence_length=cfg.get('max_sequence_length', 512), - embedding_dropout=cfg.get('embedding_dropout', 0.0), - learn_positional_encodings=cfg.get('learn_positional_encodings', False), - num_attention_heads=cfg.get('num_attention_heads'), - ffn_dropout=cfg.get('ffn_dropout', 0.0), - attn_score_dropout=cfg.get('attn_score_dropout', 0.0), - attn_layer_dropout=cfg.get('attn_layer_dropout', 0.0), - hidden_act=cfg.get('hidden_act', 'relu'), - pre_ln=cfg.get('pre_ln', False), - pre_ln_final_layer_norm=pre_ln_final_layer_norm, - num_token_types=cfg.get('num_token_types', 2), - ) - - return model diff --git a/nemo/collections/asr/modules/wav2vec_modules.py b/nemo/collections/asr/modules/wav2vec_modules.py deleted file mode 100644 index e823943de4e2650ea5e283b234fcb526c6d34b44..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/wav2vec_modules.py +++ /dev/null @@ -1,369 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import math -import random -from typing import Dict, List - -import torch -from omegaconf import DictConfig -from omegaconf.dictconfig import DictConfig -from torch import nn -from torch.nn import functional as F - -from nemo.collections.asr.modules.common.transformer.transformer_encoders_nlp import TransformerEncoder -from nemo.collections.common.parts import form_attention_mask, transformer_weights_init -from nemo.core.classes.module import NeuralModule -from nemo.core.neural_types import AcousticEncodedRepresentation, AudioSignal, LengthsType, NeuralType, SpectrogramType - - -class TransposeLast(torch.nn.Module): - """ - Transposes last dimension. Useful for adding to a sequential block. - """ - - def forward(self, x): - return x.transpose(-2, -1) - - -class SamePad(torch.nn.Module): - def __init__(self, kernel_size): - super().__init__() - self.remove = kernel_size % 2 == 0 - - def forward(self, x): - if self.remove: - x = x[:, :, :-1] - return x - - -class ConvFeatureEncoder(NeuralModule): - """ - Encoder used to isolate features in raw audio for Wav2Vec style training. - Treated as preprocessor module in NeMo ASR training. Defaults values are - for base model found in Baeski et al (https://arxiv.org/abs/2006.11477), - save for use of layer normalization as default schema. (Chosen for stability.) - """ - - @property - def input_types(self): - """Returns definitions of module input ports. - input_signal: - 0: AxisType(BatchTag) - 1: AxisType(TimeTag) - input_signal_length: - 0: AxisType(BatchTag) - Note: length is in number of samples, not seconds - """ - return { - "input_signal": NeuralType(('B', 'T'), AudioSignal(freq=self._sample_rate)), - "length": NeuralType(tuple('B'), LengthsType()), - } - - @property - def output_types(self): - """Returns definitions of module output ports. - For compatibility, processed features are treated as Spectrogram types - processed_signal: - 0: AxisType(BatchTag) - 1: AxisType(ChannelTag) - 2: AxisType(ProcessedTimeTag) - processed_signal_length: - 0: AxisType(BatchTag) - """ - return { - "processed_signal": NeuralType(('B', 'C', 'T'), SpectrogramType()), - "processed_signal_length": NeuralType(tuple('B'), LengthsType()), - } - - def __init__( - self, - conv_layers: List[Dict[str, int]], - extractor_mode: str = "layer_norm", - conv_bias: bool = False, - feature_grad_mult=1.0, - normalize_audio=True, - embedding_dim=768, - ): - super().__init__() - - self.grad_mult = feature_grad_mult - self.normalize_input = normalize_audio - - def block( - n_in, - n_out, - k, - stride, - is_layer_norm=False, - is_group_norm=False, - conv_bias=False, - ): - def make_conv(): - conv = nn.Conv1d(n_in, n_out, k, stride=stride, bias=conv_bias) - nn.init.kaiming_normal_(conv.weight) - return conv - - assert (is_layer_norm and is_group_norm) is False, "layer norm and group norm are exclusive" - - if is_layer_norm: - return nn.Sequential( - make_conv(), - nn.Sequential(TransposeLast(), nn.LayerNorm(dim, elementwise_affine=True), TransposeLast()), - nn.GELU(), - ) - elif is_group_norm: - return nn.Sequential( - make_conv(), - nn.GroupNorm(dim, dim, affine=True), - nn.GELU(), - ) - else: - return nn.Sequential(make_conv(), nn.GELU()) - - in_d = 1 - self.layer_cfg = conv_layers - self.conv_layers = nn.ModuleList() - self.mode = extractor_mode - for i, cl in enumerate(conv_layers): - assert len(cl) == 3, "invalid conv definition: " + str(cl) - dim, k, stride = cl["emb_dim"], cl["kernel_size"], cl["stride"] - - self.conv_layers.append( - block( - in_d, - dim, - k, - stride, - is_layer_norm=self.mode == "layer_norm", - is_group_norm=self.mode == "group_norm" and i == 0, # applied to first layer only - conv_bias=conv_bias, - ) - ) - in_d = dim - - # Model Layers - final_conv_dim = self.layer_cfg[-1]["emb_dim"] # Select last conv output layer dimension - self.post_extract_proj = ( # To project feature encodings to transformer - nn.Linear(final_conv_dim, embedding_dim) if final_conv_dim != embedding_dim else None - ) - self.layer_norm = nn.LayerNorm(embedding_dim) - - def apply_layers(self, x): - for conv in self.conv_layers: - x = conv(x) - return x - - def normalize(self, source, lengths): - with torch.no_grad(): # Normalizes audio source - for i in range(lengths.size(0)): - orig = source[i, : lengths[i]] - norm = F.layer_norm(orig, orig.shape) - source[i, : lengths[i]] = norm - return source - - def forward(self, input_signal, length): - if self.normalize_input: - input_signal = self.normalize(input_signal, length) - - # BxT -> BxCxT - processed_signal = input_signal.unsqueeze(1) - - # Applies grad mult scaling - if self.grad_mult > 0: - processed_signal = self.apply_layers(processed_signal) - if self.grad_mult != 1.0: - processed_signal = GradMultiply.apply(processed_signal, self.grad_mult) - else: - with torch.no_grad(): # 0 indicates frozen feature encoder - processed_signal = self.apply_layers(processed_signal) - - processed_signal = processed_signal.transpose(1, 2) # B,T,C - # Project to embedding - if self.post_extract_proj is not None: - processed_signal = self.post_extract_proj(processed_signal) - - # Adding normalization for output - if self.mode == "layer_norm": - processed_signal = self.layer_norm(processed_signal) - - processed_signal = processed_signal.transpose(1, 2) # B,C,T - - # Feature lengths will have been changed through convolutions - processed_signal_length = self.get_lengths(audio_lengths=length) - - return processed_signal, processed_signal_length - - def get_lengths(self, audio_lengths): - # converts audio lengths to timestep lengths - for conv in self.layer_cfg: - kernel = conv["kernel_size"] - stride = conv["stride"] - audio_lengths = ( - torch.div(audio_lengths - kernel, stride, rounding_mode='floor') + 1 - ) # from pytorch documentation - return audio_lengths - - -class Wav2VecTransformerEncoder(TransformerEncoder): - """ - Encoder module following Transformer encoder paradigm - as described in Vaswani et al. (https://arxiv.org/abs/1706.03762). Used for Wav2Vec - style encoding of context vectors as described by in Baeski et al (https://arxiv.org/abs/2006.11477). - Takes convolutional encodings of all time steps and adds to features before applying series - of self-attention layers. - - Example configs may be found at: https://github.com/NVIDIA/NeMo/tree/main/examples/asr/conf/wav2vec - - Args: - layer_drop: Floating point value specifying proportion of module for layer dropout (See Fan et al. https://arxiv.org/pdf/1909.11556.pdf). - If non-zero, each layer will draw from uniform probability to determine if applied in current forward call. - Occurs only during training step - pos_embed: Config specifying parameters for contextual embedding convolutions. Module configures convolutional padding - to maintain number of time steps - Must contain following: - embedding_dim: Depth/number of channels of each time step from feature encoding - conv_pos: Kernel size for convolution - conv_pos_groups: Number of groups for convolution - transformer: Config for transformer encoder. Uses self-attention layers found in: nemo.collections.nlp.modules.common.transformer - Must contain followign: - num_layers: Number of attention layers - hidden_size: Expected input depth (embedding size between model layers) - inner_size: Depth of embeddings within feed-forward sections of encoder layers - num_attention_heads: Number of attention heads - attn_score_dropout: Probability of dropout applied to attention scores - attn_layer_dropout: Probability of dropout applied to the output of the attention layers (prior to normalization) - ffn_dropout: Probability of dropout applied to feed-forward modules - hidden_act: Activation function for hidden layers - """ - - def __init__(self, pos_embed: DictConfig, transformer: DictConfig, layer_drop: float = 0.0): - super().__init__(**transformer) # see nlp.collections - - # positional convolutional embeddings - emb_dim = pos_embed.embedding_dim - self.pos_conv = nn.Conv1d( - emb_dim, - emb_dim, - kernel_size=pos_embed.conv_pos, - padding=pos_embed.conv_pos // 2, # Padding size preserves time step length - groups=pos_embed.conv_pos_groups, - ) - - self.layer_drop = layer_drop - - self.dropout = transformer.attn_layer_dropout # He initialization - std = math.sqrt((4 * (1.0 - self.dropout)) / (pos_embed.conv_pos * pos_embed.embedding_dim)) - nn.init.normal_(self.pos_conv.weight, mean=0, std=std) - nn.init.constant_(self.pos_conv.bias, 0) - - self.pos_conv = nn.utils.weight_norm(self.pos_conv, name="weight", dim=2) - self.pos_conv = nn.Sequential(self.pos_conv, SamePad(pos_embed.conv_pos), nn.GELU()) - - self.layer_norm = nn.LayerNorm(emb_dim) - self.apply(lambda x: transformer_weights_init(x, xavier=False)) - - @property - def input_types(self): - """Returns definitions of module output ports. - We treat features as SpectrogramType for Nemo compatibility - audio_signal: - 0: AxisType(BatchTag) - 1: AxisType(ChannelTag) - 2: AxisType(ProcessedTimeTag) - length: - 0: AxisType(BatchTag) - """ - return { - "audio_signal": NeuralType(('B', 'C', 'T'), SpectrogramType()), - "length": NeuralType(tuple('B'), LengthsType()), - } - - @property - def output_types(self): - """Returns definitions of module output ports. - We're using SpectrogramType for now to keep things Nemo safe - processed_signal: - 0: AxisType(BatchTag) - 1: AxisType(ChannelTag) - 2: AxisType(ProcessedTimeTag) - processed_length: - 0: AxisType(BatchTag) - """ - return { - "processed_signal": NeuralType(('B', 'C', 'T'), AcousticEncodedRepresentation()), - "processed_length": NeuralType(tuple('B'), LengthsType()), - } - - def forward(self, audio_signal, length): - - # Padding mask needed for transformer - padding_mask = self.create_padding_mask(length) - - # Applying padding before convolution - for idx, len in enumerate(length): - audio_signal[idx, :, len:] = 0.0 - - signal_conv = self.pos_conv(audio_signal) # B, C, T - audio_signal = audio_signal + signal_conv - - audio_signal = audio_signal.transpose(1, 2) # B, C, T -> B, T, C - audio_signal = self.layer_norm(audio_signal) - - context_emb = self.apply_transformer(audio_signal, padding_mask=padding_mask) - - context_emb = context_emb.transpose(1, 2) # B, T, C -> B, C, T - - return context_emb, length # Returning length for NeMo compatibility - - def apply_transformer(self, x, padding_mask=None): - encoder_attn_mask = form_attention_mask(padding_mask) - if ( - self.layer_drop and self.training - ): # Stochastic layer drop as in: Huang et al. https://arxiv.org/pdf/1603.09382.pdf - for _, layer in enumerate(self.layers): - p = random.random() - if p > self.layer_drop: - x = layer(x, encoder_attn_mask, x) - else: - for _, layer in enumerate(self.layers): - x = layer(x, encoder_attn_mask, x) - return x - - def create_padding_mask(self, length): - # Broadcast to vectorize creating the padding mask - max_len = max(length) - padding_mask = torch.arange(max_len, device=length.device) - - # Switch to binary for transformer, 1 for valid tokens, 0 for padding - padding_mask = (padding_mask.expand(len(length), max_len) < length.unsqueeze(1)).type(torch.uint8) - - return padding_mask - - -class GradMultiply(torch.autograd.Function): - @staticmethod - def forward(ctx, x, scale): - ctx.scale = scale - res = x.new(x) - return res - - @staticmethod - def backward(ctx, grad): - return grad * ctx.scale, None diff --git a/nemo/collections/asr/parts/__init__.py b/nemo/collections/asr/parts/__init__.py deleted file mode 100644 index 9e3250071955216f6abc505e6181fb59931baa8d..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/asr/parts/context_biasing/__init__.py b/nemo/collections/asr/parts/context_biasing/__init__.py deleted file mode 100644 index 93bd6116a8742b0248f9bd9e247e5a6aface355d..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/context_biasing/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.asr.parts.context_biasing.boosting_graph_batched import ( - BoostingTreeModelConfig, - GPUBoostingTreeModel, -) -from nemo.collections.asr.parts.context_biasing.context_biasing_utils import ( - compute_fscore, - merge_alignment_with_ws_hyps, -) -from nemo.collections.asr.parts.context_biasing.context_graph_ctc import ContextGraphCTC -from nemo.collections.asr.parts.context_biasing.ctc_based_word_spotter import run_word_spotter - -__all__ = [ - "GPUBoostingTreeModel", - "BoostingTreeModelConfig", - "compute_fscore", - "merge_alignment_with_ws_hyps", - "ContextGraphCTC", - "run_word_spotter", -] diff --git a/nemo/collections/asr/parts/context_biasing/biasing_multi_model.py b/nemo/collections/asr/parts/context_biasing/biasing_multi_model.py deleted file mode 100644 index c4032035f9927478ca5c1f0cec8c2aef6726dd17..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/context_biasing/biasing_multi_model.py +++ /dev/null @@ -1,719 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import abc -from abc import abstractmethod -from dataclasses import dataclass, field -from typing import Callable, cast - -import torch -import torch.nn as nn - -from nemo.collections.asr.parts.context_biasing.boosting_graph_batched import ( - BoostingTreeModelConfig, - GPUBoostingTreeModel, -) -from nemo.collections.asr.parts.submodules.ngram_lm import NGramGPULanguageModel -from nemo.collections.common.tokenizers import TokenizerSpec -from nemo.core.utils.optional_libs import TRITON_AVAILABLE, triton_required -from nemo.utils import logging - -if TRITON_AVAILABLE: - import triton - - from nemo.collections.asr.parts.submodules.ngram_lm.ngram_lm_triton import ngram_multi_advance_triton_kernel - -_BIASING_MODEL_CACHE = dict() - - -@dataclass -class BiasingRequestItemConfig: - boosting_model_cfg: BoostingTreeModelConfig = field(default_factory=BoostingTreeModelConfig) - boosting_model_alpha: float = 1.0 # boosting weight - cache_key: str | None = None # cache key for memory cache; NB: cache key should be unique for (tokenizer, phrases) - multi_model_id: int | None = None # compiled model id - auto_manage_multi_model: bool = True # if model should be added to the decoder and removed automatically - - def __post_init__(self): - # if BiasingRequestItemConfig initialized from dict, we need to fix boosting_model_cfg field - # see solution https://stackoverflow.com/a/60383031 - if isinstance(self.boosting_model_cfg, dict): - self.boosting_model_cfg = BoostingTreeModelConfig(**self.boosting_model_cfg) - - def is_empty(self) -> bool: - """Return True if biasing request (or model) is empty""" - if self.cache_key and self.cache_key in _BIASING_MODEL_CACHE: - return False - if self.multi_model_id is not None: - return False - if not BoostingTreeModelConfig.is_empty(self.boosting_model_cfg): - return False - return True - - def get_model(self, tokenizer: TokenizerSpec) -> NGramGPULanguageModel | GPUBoostingTreeModel | None: - """Create biasing model or get from cache, return the model. `None` is returned if biasing config is empty""" - if self.cache_key and self.cache_key in _BIASING_MODEL_CACHE: - return _BIASING_MODEL_CACHE[self.cache_key] - if self.boosting_model_cfg.is_empty(self.boosting_model_cfg): - return None - boosting_model = GPUBoostingTreeModel.from_config(self.boosting_model_cfg, tokenizer=tokenizer) - if self.cache_key: - _BIASING_MODEL_CACHE[self.cache_key] = boosting_model - return boosting_model - - def add_to_multi_model(self, tokenizer: TokenizerSpec, biasing_multi_model: "GPUBiasingMultiModelBase"): - """Add biasing model to biasing multi-model""" - boosting_model = self.get_model(tokenizer=tokenizer) - if boosting_model is None: - raise ValueError("Nothing to add, biasing model is empty") - self.multi_model_id = biasing_multi_model.add_model(model=boosting_model, alpha=self.boosting_model_alpha) - - def remove_from_cache(self): - """Remove model from cache (if cache entry exists)""" - if self.cache_key and self.cache_key in _BIASING_MODEL_CACHE: - del _BIASING_MODEL_CACHE[self.cache_key] - - def remove_from_multi_model(self, biasing_multi_model: "GPUBiasingMultiModelBase"): - """Remove biasing model from multi-model""" - if self.multi_model_id is None: - # nothing to remove - return - biasing_multi_model.remove_model(self.multi_model_id) - self.multi_model_id = None - - -class GPUBiasingMultiModelBase(abc.ABC, nn.Module): - """ - Base class for implementing biasing multi-model: - model that contains multiple biasing models and handles batched requests for them - """ - - START_STATE = 0 - - @abstractmethod - def add_model(self, model: NGramGPULanguageModel, alpha: float = 1.0) -> int: - pass - - @abstractmethod - def remove_model(self, model_id: int): - pass - - @abstractmethod - def has_models(self) -> bool: - """Return True if the multi-model has at least one model""" - pass - - def compatible_with_cuda_graphs(self) -> bool: - """True if model can be compiled as a part of CUDA graph, False otherwise""" - return False - - @abstractmethod - def advance( - self, states: torch.Tensor, model_ids: torch.Tensor, eos_id: int | None = None - ) -> tuple[torch.Tensor, torch.Tensor]: - """ - Advance `states` [B]: return scores [B, V] and next states [B, V] for full vocab - Args: - states: batch of states - model_ids: ids of models for each state - eos_id: if not None, for eos symbol use final state weight - - Returns: - tuple with next states and scores - """ - pass - - @abstractmethod - def get_init_states(self, batch_size: int, bos=True) -> torch.Tensor: - """ - Get batch of the initial states - - Args: - batch_size: batch size - bos: use begin-of-sentence state - - Returns: - tensor [B] of initial states - """ - pass - - -class GPUBiasingMultiModelReference(GPUBiasingMultiModelBase): - """Reference implementation (incompatible with CUDA graphs)""" - - def __init__(self, vocab_size: int, *args, **kwargs): - """ - - Args: - vocab_size: vocabulary size of the model - *args, **kwargs: added for easiness of switching between this model and efficient implementation - """ - super().__init__() - self.models = nn.ModuleList([]) - self.buffer_for_device_handling = nn.Buffer(torch.zeros([1], dtype=torch.long)) - self.alphas: list[float] = [] - self.vocab_size: int = vocab_size - self.float_dtype: torch.dtype | None = None - self.bos_state: int | None = None - self._params_defined = False - self.free_ids = set() - self.num_models = 0 - - def has_models(self) -> bool: - """Return True if the multi-model has at least one model""" - return self.num_models > 0 - - def _check_model_compatibility(self, model: NGramGPULanguageModel): - if self.vocab_size != model.vocab_size: - raise ValueError(f"Inconsistent vocab size: {model.vocab_size}") - if self.bos_state != model.bos_state: - raise ValueError(f"Inconsistent bos state: {self.bos_state} vs {model.bos_state}") - if self.START_STATE != model.START_STATE: - raise ValueError(f"Inconsistent start state: {self.START_STATE} vs {model.START_STATE}") - - def add_model(self, model: NGramGPULanguageModel, alpha: float = 1.0) -> int: - if not self._params_defined: - # there were no previous models - self.bos_state = model.bos_state - self.float_dtype = model.arcs_weights.dtype - self._params_defined = True - self._check_model_compatibility(model=model) - try: - model_id = self.free_ids.pop() - except KeyError: - model_id = None - if model_id is None: - model_id = len(self.models) - self.models.append(model) - self.alphas.append(alpha) - else: - self.models[model_id] = model - self.alphas[model_id] = alpha - self.num_models += 1 - return model_id - - def remove_model(self, model_id: int): - self.models[model_id] = nn.Identity() # dummy nn model - self.alphas[model_id] = 0.0 - self.free_ids.add(model_id) - self.num_models -= 1 - - def get_init_states(self, batch_size: int, bos=True) -> torch.Tensor: - """ - Get batch of the initial states - - Args: - batch_size: batch size - bos: use begin-of-sentence state - - Returns: - tensor [B] of initial states - """ - device = self.buffer_for_device_handling.device - if not self._params_defined: - return torch.zeros([batch_size], device=device, dtype=torch.long) - return torch.full( - [batch_size], fill_value=self.bos_state if bos else self.START_STATE, device=device, dtype=torch.long - ) - - def advance( - self, states: torch.Tensor, model_ids: torch.Tensor, eos_id: int | None = None - ) -> tuple[torch.Tensor, torch.Tensor]: - """ - Advance `states` [B]: return scores [B, V] and next states [B, V] for full vocab - Args: - states: batch of states - model_ids: ids of models for each state - eos_id: if not None, for eos symbol use final state weight - - Returns: - tuple with next states and scores - """ - batch_size = states.shape[0] - assert model_ids.shape[0] == batch_size - device = next(iter(self.parameters())).device - scores = torch.zeros([batch_size, self.vocab_size], device=device, dtype=self.float_dtype) - next_states = torch.full([batch_size, self.vocab_size], fill_value=-1, dtype=torch.long, device=device) - model_ids = model_ids.to("cpu").tolist() - for batch_i, model_id in enumerate(model_ids): - if model_id < 0: - continue - model = cast(NGramGPULanguageModel, self.models[model_id]) - scores_i, next_states_i = model.advance(states[batch_i : batch_i + 1], eos_id=eos_id) - scores[batch_i : batch_i + 1] = scores_i * self.alphas[model_id] - next_states[batch_i : batch_i + 1] = next_states_i - return scores, next_states - - -class GPUBiasingMultiModel(GPUBiasingMultiModelBase): - """Efficient multi-model implementation""" - - INIT_NUM_ARCS = 1_000_000 - INIT_NUM_STATES = 1_000_000 - INIT_NUM_MODELS = 128 - - def __init__( - self, vocab_size: int, reallocation_callback_fn: Callable | None = None, use_triton: bool | None = None - ): - """ - - Args: - vocab_size: vocabulary size of the model - reallocation_callback_fn: function to call when reallocation occurred (needed for decoders with CUDA graphs) - use_triton: allow using Triton, `None` means "auto" (used if available) - """ - super().__init__() - self.vocab_size: int = vocab_size - self.float_dtype: torch.dtype | None = None - self.bos_state: int | None = None - self._params_defined = False - self.free_ids = set() - - self.reallocation_callbacks = [] - if reallocation_callback_fn is not None: - self.reallocation_callbacks.append(reallocation_callback_fn) - - self.use_triton = use_triton if use_triton is not None else TRITON_AVAILABLE - - int_dtype = torch.int64 - - self.num_models = 0 - self.num_models_reserved = self.INIT_NUM_MODELS - - # store each model properties - self.model2alpha = nn.Buffer(torch.zeros([self.num_models_reserved])) - self.model2active = nn.Buffer(torch.zeros([self.num_models_reserved], dtype=torch.bool)) - self.model2num_states = nn.Buffer(torch.zeros([self.num_models_reserved], dtype=torch.int64)) - self.model2num_arcs = nn.Buffer(torch.zeros([self.num_models_reserved], dtype=torch.int64)) - self.model2num_arcs_extended = nn.Buffer(torch.zeros([self.num_models_reserved], dtype=torch.int64)) - self.model2states_offset = nn.Buffer(torch.zeros([self.num_models_reserved], dtype=torch.int64)) - self.model2arcs_offset = nn.Buffer(torch.zeros([self.num_models_reserved], dtype=torch.int64)) - - self.num_states_total = 0 - self.num_arcs_extended_total = 0 # + extra padding - self.num_states_reserved = self.INIT_NUM_STATES - self.num_arcs_extended_reserved = self.INIT_NUM_ARCS # + extra padding - - # arcs-related data - self.all_arcs_weights = nn.Parameter(torch.zeros([self.num_arcs_extended_reserved])) - self.all_from_states = nn.Buffer(torch.zeros([self.num_arcs_extended_reserved], dtype=int_dtype)) - self.all_to_states = nn.Buffer(torch.zeros([self.num_arcs_extended_reserved], dtype=int_dtype)) - self.all_ilabels = nn.Buffer(torch.zeros([self.num_arcs_extended_reserved], dtype=int_dtype)) - - # states-related data - self.all_start_end_arcs = nn.Buffer(torch.zeros([self.num_states_reserved, 2], dtype=int_dtype)) - self.all_state_order = nn.Buffer(torch.zeros([self.num_states_reserved], dtype=int_dtype)) - self.all_backoff_to_states = nn.Buffer(torch.zeros([self.num_states_reserved], dtype=int_dtype)) - self.all_backoff_weights = nn.Parameter(torch.zeros([self.num_states_reserved])) - self.all_final_weights = nn.Parameter(torch.zeros([self.num_states_reserved])) - - def compatible_with_cuda_graphs(self) -> bool: - """True if model can be compiled as a part of CUDA graph, False otherwise""" - return self.use_triton - - def has_models(self) -> bool: - """Return True if the multi-model has at least one model""" - return self.num_models > 0 - - def _check_model_compatibility(self, model: NGramGPULanguageModel): - """Check that the new model parameters are the same compared to already stored models""" - if self.vocab_size != model.vocab_size: - raise ValueError(f"Inconsistent vocab size: {model.vocab_size}") - if self.bos_state != model.bos_state: - raise ValueError(f"Inconsistent bos state: {self.bos_state} vs {model.bos_state}") - if self.START_STATE != model.START_STATE: - raise ValueError(f"Inconsistent start state: {self.START_STATE} vs {model.START_STATE}") - if not model._final_resolved: - model._resolve_final() - - @staticmethod - def _extend_buffer_or_param(buffer_or_param: nn.Buffer | nn.Parameter, add_len: int): - """Extend buffer or parameter""" - buffer_or_param.data = torch.cat( - ( - buffer_or_param.data, - torch.zeros( - [add_len] + list(buffer_or_param.shape)[1:], - dtype=buffer_or_param.dtype, - device=buffer_or_param.device, - ), - ) - ) - - def _maybe_extend_arcs_and_states(self, add_num_states: int, add_num_arcs_extended: int) -> bool: - """Extend memory allocated for arcs and states, return True if any tensor is reallocated""" - reallocated = False - - if self.num_arcs_extended_total + add_num_arcs_extended > self.num_arcs_extended_reserved: - # min allocation: 2x - add_num_arcs = max( - self.num_arcs_extended_reserved, - self.num_arcs_extended_total + add_num_arcs_extended - self.num_arcs_extended_reserved, - ) - self._extend_buffer_or_param(self.all_arcs_weights, add_len=add_num_arcs) - self._extend_buffer_or_param(self.all_from_states, add_len=add_num_arcs) - self._extend_buffer_or_param(self.all_to_states, add_len=add_num_arcs) - self._extend_buffer_or_param(self.all_ilabels, add_len=add_num_arcs) - self.num_arcs_extended_reserved += add_num_arcs - reallocated = True - - if self.num_states_total + add_num_states > self.num_states_reserved: - # min allocation: 2x - add_num_states = max( - self.num_states_reserved, self.num_states_total + add_num_states - self.num_states_reserved - ) - self._extend_buffer_or_param(self.all_start_end_arcs, add_len=add_num_states) - self._extend_buffer_or_param(self.all_state_order, add_len=add_num_states) - self._extend_buffer_or_param(self.all_backoff_to_states, add_len=add_num_states) - self._extend_buffer_or_param(self.all_backoff_weights, add_len=add_num_states) - self._extend_buffer_or_param(self.all_final_weights, add_len=add_num_states) - self.num_states_reserved += add_num_states - reallocated = True - - return reallocated - - @staticmethod - def _extend_buffer_2x(buffer: nn.Buffer): - buffer.data = torch.cat((buffer.data, torch.zeros_like(buffer.data)), dim=-1) - - def _extend_num_models(self): - """Extend memory allocated for models with properties""" - assert self.num_models_reserved > 0 - self.num_models_reserved *= 2 - - self._extend_buffer_2x(self.model2alpha) - self._extend_buffer_2x(self.model2active) - self._extend_buffer_2x(self.model2num_states) - self._extend_buffer_2x(self.model2num_arcs) - self._extend_buffer_2x(self.model2num_arcs_extended) - self._extend_buffer_2x(self.model2states_offset) - self._extend_buffer_2x(self.model2arcs_offset) - - @torch.no_grad() - def add_model(self, model: GPUBoostingTreeModel, alpha: float = 1.0) -> int: - """ - Add boosting model with `alpha` weight. Returns id for the added model - - Args: - model: boosting model - alpha: weight of the boosting model - - Returns: - model id (to use in queries) - """ - if not self._params_defined: - # there were no previous models - self.bos_state = model.bos_state - self.float_dtype = model.arcs_weights.dtype - self._params_defined = True - self._check_model_compatibility(model=model) - - reallocated = False - # select model id: either any free id, or num_models - if self.free_ids: - model_id = self.free_ids.pop() - else: - if self.num_models >= self.num_models_reserved: - self._extend_num_models() - reallocated = True - model_id = self.num_models - self.num_models += 1 - self.model2alpha[model_id] = alpha - self.model2active[model_id] = True - - reallocated |= self._maybe_extend_arcs_and_states( - add_num_states=model.num_states, - add_num_arcs_extended=model.num_arcs_extended, - ) - self.model2num_states[model_id] = model.num_states - self.model2num_arcs[model_id] = model.num_arcs - self.model2num_arcs_extended[model_id] = model.num_arcs_extended - self.model2states_offset[model_id] = self.num_states_total - self.model2arcs_offset[model_id] = self.num_arcs_extended_total - - # model is added always to the end of data storage - states_start = self.num_states_total - arcs_start = self.num_arcs_extended_total - - # arcs-related data - self.all_arcs_weights.data[arcs_start : arcs_start + model.num_arcs].copy_( - model.arcs_weights.data[: model.num_arcs] - ) - self.all_from_states.data[arcs_start : arcs_start + model.num_arcs].copy_( - model.from_states.data[: model.num_arcs] - ) - self.all_to_states.data[arcs_start : arcs_start + model.num_arcs].copy_(model.to_states.data[: model.num_arcs]) - self.all_ilabels.data[arcs_start : arcs_start + model.num_arcs].copy_(model.ilabels.data[: model.num_arcs]) - - # states-related data - self.all_start_end_arcs.data[states_start : states_start + model.num_states].copy_( - model.start_end_arcs.data[: model.num_states] - ) - self.all_state_order.data[states_start : states_start + model.num_states].copy_( - model.state_order.data[: model.num_states] - ) - self.all_backoff_to_states.data[states_start : states_start + model.num_states].copy_( - model.backoff_to_states.data[: model.num_states] - ) - self.all_backoff_weights.data[states_start : states_start + model.num_states].copy_( - model.backoff_weights.data[: model.num_states] - ) - self.all_final_weights.data[states_start : states_start + model.num_states].copy_( - model.final_weights.data[: model.num_states] - ) - - self.num_states_total += model.num_states - self.num_arcs_extended_total += model.num_arcs_extended - - if reallocated: - logging.info("Biasing multi-model reallocated memory. Executing reallocation callbacks") - for reallocation_callback_fn in self.reallocation_callbacks: - reallocation_callback_fn() - return model_id - - @staticmethod - def _clear_buffer_or_param_range( - buffer_or_param: nn.Buffer | nn.Parameter, start: int, end: int, buffer_len: int | None = None - ): - if buffer_len is None: - buffer_len = buffer_or_param.shape[0] - remove_len = end - start - buffer_or_param[start : buffer_len - remove_len].copy_(buffer_or_param[end:buffer_len].clone()) - buffer_or_param[buffer_len - remove_len : buffer_len].fill_(0) - - @torch.no_grad() - def remove_model(self, model_id: int): - """ - Remove boosting model. - - Args: - model_id: boosting model id provided by the `add_model` method - """ - logging.debug(f"Removing model: {model_id}") - if model_id in self.free_ids or model_id >= self.num_models: - raise ValueError( - f"Trying to remove already deleted or non-existing model {model_id}. Total models in reserve: {self.num_models}" - ) - - # set model as inactive (we do not decrease num_models, only set to inactive!) - self.model2active[model_id] = False - self.model2alpha[model_id] = 0.0 - self.free_ids.add(model_id) - - start_state = self.model2states_offset[model_id].item() - num_states = self.model2num_states[model_id].item() - end_state = start_state + num_states - - start_arc = self.model2arcs_offset[model_id].item() - num_arcs = self.model2num_arcs_extended[model_id].item() - end_arc = start_arc + num_arcs - - assert num_arcs > 0 and num_states > 0, "Unexpected zero-size model" - - # clean up arcs-related data: cut [start_arc, end_arc) from the buffer (shifting right part to the left) - self._clear_buffer_or_param_range(self.all_arcs_weights, start_arc, end_arc, self.num_arcs_extended_total) - self._clear_buffer_or_param_range(self.all_from_states, start_arc, end_arc, self.num_arcs_extended_total) - self._clear_buffer_or_param_range(self.all_to_states, start_arc, end_arc, self.num_arcs_extended_total) - self._clear_buffer_or_param_range(self.all_ilabels, start_arc, end_arc, self.num_arcs_extended_total) - - # clean up states-related data: cut [start_state, end_state) from the buffer (shifting right part to the left) - self._clear_buffer_or_param_range(self.all_start_end_arcs, start_state, end_state, self.num_states_total) - self._clear_buffer_or_param_range(self.all_state_order, start_state, end_state, self.num_states_total) - self._clear_buffer_or_param_range(self.all_backoff_to_states, start_state, end_state, self.num_states_total) - self._clear_buffer_or_param_range(self.all_backoff_weights, start_state, end_state, self.num_states_total) - self._clear_buffer_or_param_range(self.all_final_weights, start_state, end_state, self.num_states_total) - - # set num states/arcs to zero - self.num_states_total -= num_states - self.num_arcs_extended_total -= num_arcs - - self.model2num_states[model_id] = 0 - self.model2num_arcs[model_id] = 0 - self.model2num_arcs_extended[model_id] = 0 - # shift model offsets - self.model2states_offset[model_id] = 0 - self.model2arcs_offset[model_id] = 0 - # shift states and arcs offsets - torch.where( - self.model2states_offset < start_state, - self.model2states_offset, - self.model2states_offset - num_states, - out=self.model2states_offset, - ) - torch.where( - self.model2arcs_offset < start_arc, - self.model2arcs_offset, - self.model2arcs_offset - num_arcs, - out=self.model2arcs_offset, - ) - - def get_init_states(self, batch_size: int, bos=True) -> torch.Tensor: - """ - Get batch of the initial states - - Args: - batch_size: batch size - bos: use begin-of-sentence state - - Returns: - tensor [B] of initial states - """ - device = self.all_arcs_weights.device - if not self._params_defined: - return torch.full([batch_size], fill_value=self.START_STATE, device=device, dtype=torch.long) - return torch.full( - [batch_size], fill_value=self.bos_state if bos else self.START_STATE, device=device, dtype=torch.long - ) - - def advance( - self, states: torch.Tensor, model_ids: torch.Tensor, eos_id: int | None = None - ) -> tuple[torch.Tensor, torch.Tensor]: - """ - Advance `states` [B]: return scores [B, V] and next states [B, V] for full vocab - Args: - states: batch of states - model_ids: batch of ids of the models (`-1` to apply dummy model with zero weight) - eos_id: if not None, for eos symbol use final state weight - - Returns: - tuple with next states and scores - """ - assert model_ids.shape[0] == states.shape[0] - - if self.use_triton and states.device.type == "cuda": - scores, next_states = self._advance_triton(states=states, model_ids=model_ids) - else: - scores, next_states = self._advance_pytorch(states=states, model_ids=model_ids) - # NB: model_id can be -1, but we assume that there at least 1 element in self.alphas - scores *= self.model2alpha[model_ids][:, None] - - # replace eos_id score with maximum state weight to prevent from hallucinating in case of AED models (e.g. Canary) - if eos_id is not None: - raise NotImplementedError - - return scores, next_states - - @triton_required - def _advance_triton(self, states: torch.Tensor, model_ids: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: - """ - Advance `states` [B]: return scores [B, V] and next states [B, V] for full vocab. - Triton implementation. Currently not differentiable. - - Args: - states: batch of states - model_ids: ids of the models (`-1` to apply dummy model with zero weight) - - Returns: - tuple of scores and next states - """ - batch_size = states.shape[0] - device = states.device - scores = torch.zeros([batch_size, self.vocab_size], device=device, dtype=self.all_arcs_weights.dtype) - next_states = torch.full([batch_size, self.vocab_size], fill_value=-1, dtype=torch.long, device=device) - - ngram_multi_advance_triton_kernel[batch_size,]( - vocab_size=self.vocab_size, - states_ptr=states, - new_states_out_ptr=next_states, - scores_out_ptr=scores, - start_state=self.START_STATE, - model_ids_ptr=model_ids, - states_offsets_ptr=self.model2states_offset, - arcs_offsets_ptr=self.model2arcs_offset, - to_states_ptr=self.all_to_states, - ilabels_ptr=self.all_ilabels, - arcs_weights_ptr=self.all_arcs_weights, - start_end_arcs_ptr=self.all_start_end_arcs, - backoff_to_states_ptr=self.all_backoff_to_states, - backoff_weights_ptr=self.all_backoff_weights, - BLOCK_SIZE=triton.next_power_of_2(self.vocab_size), - ) - - return scores, next_states - - def _advance_pytorch(self, states: torch.Tensor, model_ids: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: - """ - Advance `states` [B]: return scores [B, V] and next states [B, V] for full vocab. - PyTorch implementation (slow, differentiable). - - Args: - states: batch of states - model_ids: ids of the models (`-1` to apply dummy model with zero weight) - - Returns: - tuple of scores and next states - """ - batch_size = states.shape[0] - device = states.device - current_states = states.clone() - states_dtype = current_states.dtype - - # init output tensors - out_scores = torch.zeros(batch_size, self.vocab_size, device=device) - out_states = torch.full([batch_size, self.vocab_size], fill_value=-1, dtype=states_dtype, device=device) - - # helper ranges - vocab_range = torch.arange(self.vocab_size, device=device) - batch_indices = torch.arange(batch_size, device=device) - - # backoff weight accumulator - accumulated_backoff = torch.zeros(batch_size, device=device) - # loop condition - start_state_not_processed = model_ids != -1 - - states_offsets = self.model2states_offset[model_ids] - arcs_offsets = self.model2arcs_offset[model_ids] - - num_iterations = 0 - while start_state_not_processed.any(): - num_iterations += 1 - # get arc boundaries - start, end = self.all_start_end_arcs[current_states + states_offsets].unbind(dim=1) - # number of arcs for each state cannot be larger than vocab size - start += arcs_offsets - end += arcs_offsets - arc_indices = start[:, None] + vocab_range[None, :] - mask = arc_indices < end[:, None] - mask &= start_state_not_processed[:, None] - mask_flat = mask.view(-1) - arc_indices_flat = arc_indices.view(-1) - # map indices outside the mask to vocab_size + 1 - scores_add = torch.zeros([batch_size, self.vocab_size + 1], device=device, dtype=out_scores.dtype) - out_states_add = torch.full( - [batch_size, self.vocab_size + 1], fill_value=-1, device=device, dtype=states_dtype - ) - ilabels = self.all_ilabels[arc_indices_flat] * mask_flat + ~mask_flat * self.vocab_size - scores_add[batch_indices.repeat_interleave(self.vocab_size), ilabels] = self.all_arcs_weights[ - arc_indices_flat - ] - out_states_add[batch_indices.repeat_interleave(self.vocab_size), ilabels] = self.all_to_states[ - arc_indices_flat - ].to(states_dtype) - # fill out_scores and out_states with new values where state is not found yet - state_found = out_states != -1 - out_scores = torch.where( - state_found, out_scores, accumulated_backoff.unsqueeze(-1) + scores_add[:, : self.vocab_size] - ) - out_states = torch.where(state_found, out_states, out_states_add[:, : self.vocab_size]) - # update loop condition; process backoffs - start_state_not_processed &= current_states != self.START_STATE - accumulated_backoff += ( - self.all_backoff_weights[current_states + states_offsets] * start_state_not_processed - ) - torch.where( - start_state_not_processed, - self.all_backoff_to_states[current_states + states_offsets], - current_states, - out=current_states, - ) - return out_scores, out_states diff --git a/nemo/collections/asr/parts/context_biasing/boosting_graph_batched.py b/nemo/collections/asr/parts/context_biasing/boosting_graph_batched.py deleted file mode 100644 index a7cd54714bd0ca49ae79e0a18b9615882fefaea7..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/context_biasing/boosting_graph_batched.py +++ /dev/null @@ -1,615 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os -from collections import deque -from dataclasses import InitVar, dataclass, field -from pathlib import Path -from typing import NamedTuple, Optional - -import numpy as np -import sentencepiece as spm -import torch -from lightning.pytorch import Trainer -from omegaconf import MISSING, DictConfig, OmegaConf - -from nemo.collections.asr.parts.context_biasing.context_graph_universal import ContextGraph, ContextState -from nemo.collections.asr.parts.submodules.ngram_lm import DEFAULT_TOKEN_OFFSET, NGramGPULanguageModel -from nemo.collections.common.tokenizers import AggregateTokenizer -from nemo.collections.common.tokenizers.tokenizer_spec import TokenizerSpec -from nemo.utils import logging -from nemo.utils.exceptions import NeMoBaseException - - -@dataclass -class PhraseItem: - phrase: str # phrase itself - lang: str # per-phrase language (for aggregate tokenizer) - # custom weight can be further added - - -@dataclass -class BoostingTreeModelConfig: - """ - Boosting tree model config - """ - - model_path: Optional[str] = None # The path to builded '.nemo' boosting tree model - key_phrases_file: Optional[str] = None # The path to the context-biasing list file (one phrase per line) - key_phrases_list: Optional[list[str]] = ( - None # The list of context-biasing phrases ['word1', 'word2', 'word3', ...] - ) - # The list of context-biasing phrases with custom options: - # [PhraseItem("word1", lang="en"), PhraseItem("frase dos", lang="es"), ...] - # in CLI: key_phrase_items_list='[{phrase:"word1",lang:en},{phrase:"frase dos",lang:es}]' - key_phrase_items_list: list[PhraseItem] | None = None - context_score: float = 1.0 # The score for each arc transition in the context graph - depth_scaling: float = ( - 2.0 # The scaling factor for the depth of the context graph (2.0 for CTC, RNN-T and TDT, 1.0 for Canary) - ) - unk_score: float = ( - 0.0 # The score for unknown tokens (tokens that are not presented in the beginning of context-biasing phrases) - ) - final_eos_score: float = ( - 1.0 # The score for eos token after detected end of context phrase to prevent hallucination for AED models - ) - score_per_phrase: float = 0.0 # Custom score for each phrase in the context graph - source_lang: str = "en" # The source language of the context-biasing phrases (for aggregate tokenizer) - use_triton: bool = True # Whether to use Triton for inference. - uniform_weights: bool = False # Whether to use uniform weights for the context-biasing tree as in Icefall - use_bpe_dropout: bool = False # Whether to use BPE dropout for generating alternative transcriptions - num_of_transcriptions: int = ( - 5 # The number of alternative transcriptions to generate for each context-biasing phrase - ) - bpe_alpha: float = 0.3 # The alpha parameter for BPE dropout - - @staticmethod - def is_empty(cfg: "BoostingTreeModelConfig") -> bool: - return ( - cfg.model_path is None - and cfg.key_phrases_file is None - and (not cfg.key_phrases_list) - and (not cfg.key_phrase_items_list) - ) - - -class TBranch(NamedTuple): - """Structure (tuple) to represent a branch in the boosting tree""" - - symbol: int # token id - start_node: ContextState # start node of the branch - next_node: ContextState # next node of the branch - - -@dataclass -class BoostingTreeStorage: - """ - NumPy-based storage for suffix tree (weighted acceptor) for phrase boosting - """ - - num_states_max: InitVar[int] - num_arcs_max: InitVar[int] - - vocab_size: int - max_order: int - - arcs: np.ndarray = field(init=False) - states: np.ndarray = field(init=False) - - _node_cache: dict[int, int] = field(default_factory=dict) - - unk_score: float = 0.0 - final_eos_score: float = 0.0 - num_states: int = 0 - num_arcs: int = 0 - start_state: int = 0 - bos_state: int = 0 - - def __post_init__(self, num_states_max: int, num_arcs_max: int): - if max(num_states_max, num_arcs_max) < np.iinfo(np.int32).max: - int_np_dtype = np.int32 - else: - int_np_dtype = np.int64 - self.arcs = np.zeros( - [num_arcs_max], - dtype=[("from", int_np_dtype), ("to", int_np_dtype), ("ilabel", int_np_dtype), ("weight", np.float32)], - ) - self.states = np.zeros( - [num_states_max], - dtype=[ - ("arcs_start", int_np_dtype), - ("arcs_end", int_np_dtype), - ("order", int_np_dtype), - ("backoff_to", int_np_dtype), - ("backoff_w", np.float32), - ("final", np.float32), - ], - ) - self.states["final"] = self.final_eos_score - self._node_cache[0] = 0 - self.separate_bos_state = False - - def _add_tbranches_first_order(self, tbranches: list): - """Add all first order tbranches to the model (similar with unigrams for N-Gram LM)""" - - tbranches = sorted(tbranches, key=lambda x: (x.start_node.id, x.symbol)) - - self.num_states = 1 - self.num_arcs = 0 - # state: start_arcs, end_arcs, order, backoff_to, backoff_weight - self.states[self.start_state] = (0, self.vocab_size, 1, self.start_state, 0.0, 0.0) - added_symbols = set() - num_vocab_labels = 0 - for tbranch in tbranches: - ilabel = tbranch.symbol - assert ilabel < self.vocab_size - arc_id = ilabel - added_symbols.add(ilabel) - next_state = self.num_states - self.num_states += 1 - self.arcs[arc_id] = (self.start_state, next_state, ilabel, tbranch.next_node.token_score) - self.num_arcs += 1 - - if tbranch.next_node.is_end: - # we do not penalize transitions from final nodes in case of non-uniform weights - backoff_weight = 0.0 - else: - backoff_weight = tbranch.next_node.fail.node_score - tbranch.next_node.node_score - - # state order - self.states[next_state] = ( - 0, - 0, - self.states[self.start_state]["order"] + 1, - self.start_state, - backoff_weight, - self.final_eos_score if tbranch.next_node.is_end else 0.0, - ) - num_vocab_labels += 1 - self._node_cache[tbranch.next_node.id] = next_state - - for ilabel in range(self.vocab_size): - if ilabel not in added_symbols: - self.arcs[ilabel] = (self.start_state, self.start_state, ilabel, self.unk_score) - self.num_arcs += 1 - - def _add_tbranches_next_order(self, tbranches: list): - """Add tbranches for the order > 1; should be called after adding first order tokens (unigrams), using increasing order""" - tbranches = sorted(tbranches, key=lambda x: (x.start_node.id, x.symbol)) - - for tbranch in tbranches: - ilabel = tbranch.symbol - from_state = self._node_cache[tbranch.start_node.id] - assert ilabel < self.vocab_size - backoff_state = self._node_cache[tbranch.next_node.fail.id] - - if tbranch.next_node.is_end and not self.uniform_weights: - # we do not penalize transitions from final nodes in case of non-uniform weights - backoff_weight = 0.0 - else: - backoff_weight = tbranch.next_node.fail.node_score - tbranch.next_node.node_score - - arc_id = self.num_arcs - next_state = self.num_states - self.num_arcs += 1 - self.num_states += 1 - token_score = tbranch.next_node.token_score - if self.uniform_weights and tbranch.next_node.is_end: - token_score += tbranch.next_node.node_score - - self.arcs[arc_id] = (from_state, next_state, ilabel, token_score) - - self.states[next_state] = ( - 0, - 0, - self.states[from_state]["order"] + 1, - backoff_state, - backoff_weight, - self.final_eos_score if tbranch.next_node.is_end else 0.0, - ) - - self._node_cache[tbranch.next_node.id] = next_state - - if self.states[from_state]["arcs_start"] == 0: - self.states[from_state]["arcs_start"] = arc_id - self.states[from_state]["arcs_end"] = arc_id + 1 - else: - assert self.states[from_state]["arcs_end"] == arc_id - self.states[from_state]["arcs_end"] = arc_id + 1 - - def _start_adding_tbranches_for_order(self, order: int): - """Prepare for adding tbranches for the given order: initialize temporary storage""" - self._start_arcs = self.num_arcs - self._cur_order = order - self._tbranches = [] - self._tbranches_cnt = 0 - - def _end_adding_tbranches_for_order(self, order: int): - """Finish adding tbranches for the given order""" - if order == 1: - assert len(self._tbranches) == self._tbranches_cnt - self._add_tbranches_first_order(tbranches=self._tbranches) - self._tbranches = None - self._tbranches_cnt = 0 - else: - assert len(self._tbranches) == self._tbranches_cnt - self._add_tbranches_next_order(tbranches=self._tbranches) - self._tbranches = None - self._tbranches_cnt = 0 - - def sanity_check(self): - """Sanity check for the model""" - assert (self.arcs["ilabel"][: self.num_arcs] < self.vocab_size).all() - assert (self.arcs["ilabel"][: self.num_arcs] >= 0).all() - - -@dataclass -class BoostingTreeConfig: - """ - N-Gram LM Config - """ - - num_states: int = MISSING - num_arcs: int = MISSING - max_order: int = MISSING - vocab_size: int = MISSING - separate_bos_state: bool = False - use_triton: bool | None = None - - -class GPUBoostingTreeModel(NGramGPULanguageModel): - """ - GPU-accelerated boosting tree supporting batched queries. - Fast implementation for parallel queries for full vocabulary. - Supports autograd (differentiable weights). - """ - - START_STATE = 0 - - def __init__( - self, - cfg: DictConfig, - trainer: Trainer = None, - ): - """ - Stubs for constructor that does not initialize the structure. - This constructor can be useful when storing/loading module using native torch serialization mechanism - instead of directly reading ARPA model -> converting to Torch, which can be slow for large N-Gram models - (of several GBs). - - Args: - cfg: - num_states: number of states in graph - num_arcs: number of arcs (transitions) in graph - max_order: maximum order of n-gram LM (maximum possible nubmer of transitions without backoffs) - vocab_size: vocabulary size (existing vocabulary units in LM; should not include blank etc.) - separate_bos_state: separate Begin-of-Sentence state (default: True - for n-gram LM) - use_triton: allow using Triton implementation; - None (default) means "auto" (used if available), True means forced mode - (will crash if Triton is unavailable) - trainer: Lightning trainer (optional) - """ - super().__init__(cfg=cfg, trainer=trainer) - self.bos_state = self.START_STATE # Always START_STATE for gpu boosting tree - - @classmethod - def _read_context_graph( - cls, - context_graph: ContextGraph, - ) -> tuple[dict[int, int], list[TBranch]]: - """ - Read context-biasing tree from python structure and return branches in TBranch format. - - Args: - context_graph: python context-biasing graph - """ - - seen = set() - queue = deque() - queue.append(context_graph.root) - seen.add(0) - order2cnt = {} - tbranches_list = [] - - # read context graph tree in breadth-first order to add branches for boosting tree generation - while len(queue): - current_node = queue.popleft() - for token, node in current_node.next.items(): - if node.id not in seen: - tbranches_list.append(TBranch(symbol=token, start_node=current_node, next_node=node)) - order2cnt[node.level] = order2cnt.get(node.level, 0) + 1 - queue.append(node) - - return order2cnt, tbranches_list - - @classmethod - def from_context_graph( - cls, - context_graph: ContextGraph, - vocab_size: int, - unk_score: float = 0.0, - final_eos_score: float = 0.0, - use_triton: bool | None = None, - uniform_weights: bool | None = None, - ) -> "GPUBoostingTreeModel": - """ - Constructor from Icefall context graph (dict-based tree). - - Args: - context_graph: context-biasing graph - vocab_size: vocabulary size (existing vocabulary units in LM; should not include blank etc.) - unk_score: score for unknown tokens - final_eos_score: score for eos token after detected end of context phrase - use_triton: allow using Triton implementation; - None (default) means "auto" (used if available), True means forced mode - (will crash if Triton is unavailable) - uniform_weights: whether to use uniform weights for the context-biasing tree as in Icefall - - Returns: - GPUBoostingTreeModel instance - """ - logging.info(f"{cls.__name__}: reading boosting tree from {context_graph}") - - order2cnt, tbranches_list = cls._read_context_graph(context_graph=context_graph) - - # init suffix tree storage - max_states = context_graph.num_nodes + 1 # + 1 for root state - boosting_tree_np = BoostingTreeStorage( - num_states_max=max_states, - num_states=0, - num_arcs=0, - num_arcs_max=max_states * 2 + vocab_size * 2 + 1, - unk_score=unk_score, - final_eos_score=final_eos_score, - vocab_size=vocab_size, - max_order=max(order2cnt) + 1, - ) - - boosting_tree_np.uniform_weights = uniform_weights - # convert context-biasing graph to np boosting tree - tbranch_cur_order_i = 0 - cur_order = 1 - - for tbranch in tbranches_list: - - if tbranch_cur_order_i == 0: - boosting_tree_np._start_adding_tbranches_for_order(order=cur_order) - tbranch_cur_order_i += 1 - - # add tbranch - boosting_tree_np._tbranches.append(tbranch) - boosting_tree_np._tbranches_cnt += 1 - - if tbranch_cur_order_i == order2cnt[cur_order]: - boosting_tree_np._end_adding_tbranches_for_order(order=cur_order) - logging.debug(f"Processed {order2cnt[cur_order]} n-grams of order {cur_order}") - cur_order += 1 - tbranch_cur_order_i = 0 - - assert tbranch_cur_order_i == 0 - boosting_tree_np.sanity_check() - logging.debug(f"Loaded boosting model with {len(tbranches_list)} arcs") - return GPUBoostingTreeModel.from_boosting_tree_np(boosting_tree_np=boosting_tree_np, use_triton=use_triton) - - @classmethod - def from_boosting_tree_np( - cls, boosting_tree_np: BoostingTreeStorage, use_triton: bool | None = None - ) -> "GPUBoostingTreeModel": - """ - Constructor from suffix tree storage. - - Args: - suffix_tree_np: suffix tree - use_triton: allow using Triton implementation; - None (default) means "auto" (used if available), True means forced mode - (will crash if Triton is unavailable) - - Returns: - GPUBoostingTreeModel instance - """ - model = GPUBoostingTreeModel( - OmegaConf.structured( - BoostingTreeConfig( - num_states=boosting_tree_np.num_states, - num_arcs=boosting_tree_np.num_arcs, - max_order=boosting_tree_np.max_order, - vocab_size=boosting_tree_np.vocab_size, - use_triton=use_triton, - ) - ) - ) - model._init_from_suffix_tree_np(suffix_tree_np=boosting_tree_np) - model._resolve_final() - return model - - def advance(self, states: torch.Tensor, eos_id: Optional[int] = None) -> tuple[torch.Tensor, torch.Tensor]: - """ - Advance `states` [B]: return scores [B, V] and next states [B, V] for full vocab - Args: - states: batch of states - eos_id: if not None, for eos symbol use final state weight - - Returns: - tuple with next states and scores - """ - if self.use_triton and states.device.type == "cuda": - scores, next_states = self._advance_triton(states=states) - else: - scores, next_states = self._advance_pytorch(states=states) - - # replace eos_id score with maximum state weight to prevent from hallucinating in case of AED models (e.g. Canary) - if eos_id is not None: - # 1. replace eos score with maximum boosting value at each step - scores[:, eos_id] = torch.clamp(torch.max(scores, dim=1).values, min=0.0) - - # 2. increase eos score after detected end of context phrase - scores[:, eos_id] += self.get_final(states) - - next_states[:, eos_id] = states - return scores, next_states - - def get_final(self, states: torch.Tensor) -> torch.Tensor: - """ - Get final weights for states - - Args: - states: batch of states - - Returns: - tensor [B] with final weights for each state - """ - - return self.final_weights[states] - - @classmethod - def dummy_boosting_tree( - cls, - vocab_size: int, - use_triton: bool | None = None, - ) -> "GPUBoostingTreeModel": - """ - Constructs a trivial boosting tree with only one context phrase without scores. - Useful for testing purposes (e.g., decoding). - - Returns: - GPUBoostingTreeModel instance - """ - - context_graph_trivial = ContextGraph(context_score=0.0, depth_scaling=0.0) - context_graph_trivial.build(token_ids=[[1]], phrases=["c"], scores=[0.0], uniform_weights=False) - - boosting_tree_trivial = GPUBoostingTreeModel.from_context_graph( - context_graph=context_graph_trivial, - vocab_size=vocab_size, - unk_score=0.0, - final_eos_score=0.0, - use_triton=use_triton, - uniform_weights=False, - ) - return boosting_tree_trivial - - @classmethod - def get_alternative_transcripts( - cls, cfg: BoostingTreeModelConfig, tokenizer: TokenizerSpec, phrase: str - ) -> list[list[int]]: - """ - Get alternative transcriptions for a key phrase using BPE dropout - """ - i = 1 - cur_step = 1 - transcripts_set = set() - transcripts_list = [tokenizer.text_to_ids(phrase)] - while i < cfg.num_of_transcriptions and cur_step < cfg.num_of_transcriptions * 5: - cur_step += 1 - transcript = tokenizer.tokenizer.encode(phrase, enable_sampling=True, alpha=cfg.bpe_alpha, nbest_size=-1) - transcript_text = tokenizer.ids_to_tokens(transcript) - if transcript_text[0] == "▁": # skip the case of empty first token - continue - transcript_text = " ".join(transcript_text) - if transcript_text not in transcripts_set: - transcripts_list.append(transcript) - transcripts_set.add(transcript_text) - i += 1 - return transcripts_list - - @classmethod - def from_arpa( - cls, - lm_path: Path | str, - vocab_size: int, - normalize_unk: bool = True, - use_triton: bool | None = None, - token_offset: int = DEFAULT_TOKEN_OFFSET, - ) -> "NGramGPULanguageModel": - raise NeMoBaseException("Boosting tree cannot be loaded from ARPA file") - - @classmethod - def from_config(cls, cfg: BoostingTreeModelConfig, tokenizer: TokenizerSpec) -> "GPUBoostingTreeModel": - """ - Constructor boosting tree model from config file - """ - # load boosting tree from already built model path - if cfg.model_path is not None and os.path.exists(cfg.model_path): - return cls.from_nemo(lm_path=cfg.model_path, vocab_size=tokenizer.vocab_size) - - # 1. read key phrases from file or list - phrase_items_list: list[PhraseItem] - if cfg.key_phrases_file is not None and bool(cfg.key_phrases_list or cfg.key_phrase_items_list): - raise ValueError("Both file and phrases specified, use only one") - elif cfg.key_phrases_file: - with open(cfg.key_phrases_file, "r", encoding="utf-8") as f: - phrase_items_list = [PhraseItem(line.strip(), cfg.source_lang) for line in f] - elif cfg.key_phrases_list or cfg.key_phrase_items_list: - phrase_items_list = [] - if cfg.key_phrases_list: - phrase_items_list = [PhraseItem(phrase, cfg.source_lang) for phrase in cfg.key_phrases_list] - if cfg.key_phrase_items_list: - phrase_items_list += cfg.key_phrase_items_list - else: - raise ValueError("No key phrases file or list specified") - - # 2. tokenize key phrases - phrases_dict = {} - is_aggregate_tokenizer = isinstance(tokenizer, AggregateTokenizer) - - use_bpe_dropout = cfg.use_bpe_dropout - if use_bpe_dropout: - if is_aggregate_tokenizer: - logging.warning( - "Aggregated tokenizer does not support BPE dropout, only one default transcription will be used..." - ) - use_bpe_dropout = False - spm.set_random_generator_seed(1234) # fix random seed for reproducibility of BPE dropout - - for phrase_item in phrase_items_list: - phrase = phrase_item.phrase - if use_bpe_dropout: - phrases_dict[phrase] = cls.get_alternative_transcripts(cfg, tokenizer, phrase) - else: - if is_aggregate_tokenizer: - phrases_dict[phrase] = tokenizer.text_to_ids(phrase, phrase_item.lang) - else: - phrases_dict[phrase] = tokenizer.text_to_ids(phrase) - - # 3. build pythoncontext graph - contexts, scores, phrases = [], [], [] - for phrase in phrases_dict: - if use_bpe_dropout: - for transcript in phrases_dict[phrase]: - contexts.append(transcript) - scores.append(round(cfg.score_per_phrase / len(phrase), 2)) - phrases.append(phrase) - else: - contexts.append(phrases_dict[phrase]) - scores.append(round(cfg.score_per_phrase / len(phrase), 2)) - phrases.append(phrase) - - context_graph = ContextGraph(context_score=cfg.context_score, depth_scaling=cfg.depth_scaling) - context_graph.build(token_ids=contexts, scores=scores, phrases=phrases, uniform_weights=cfg.uniform_weights) - - # 4. build GPU boosting tree model from python context graph - boosting_tree_model = GPUBoostingTreeModel.from_context_graph( - context_graph=context_graph, - vocab_size=tokenizer.vocab_size, - unk_score=cfg.unk_score, - final_eos_score=cfg.final_eos_score, - use_triton=cfg.use_triton, - uniform_weights=cfg.uniform_weights, - ) - - # 5. save model - if cfg.model_path is not None: - boosting_tree_model.save_to(cfg.model_path) - - return boosting_tree_model diff --git a/nemo/collections/asr/parts/context_biasing/context_biasing_utils.py b/nemo/collections/asr/parts/context_biasing/context_biasing_utils.py deleted file mode 100644 index 141ac0cdd4c39d9a64b0544ae7a39caf00134af6..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/context_biasing/context_biasing_utils.py +++ /dev/null @@ -1,275 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os -from typing import List, Union - -import numpy as np -from kaldialign import align - -from nemo.collections.asr.parts.context_biasing.ctc_based_word_spotter import WSHyp -from nemo.collections.asr.parts.utils import rnnt_utils -from nemo.collections.asr.parts.utils.manifest_utils import read_manifest -from nemo.utils import logging - - -def merge_alignment_with_ws_hyps( - candidate: Union[np.ndarray, rnnt_utils.Hypothesis], - asr_model, - cb_results: List[WSHyp], - decoder_type: str = "ctc", - intersection_threshold: float = 30.0, - blank_idx: int = 0, - print_stats: bool = False, - bow: str = "▁", -) -> tuple[str, str]: - """ - Merge context biasing predictions with ctc/rnnt word-level alignment. - Words from alignment will be replaced by spotted words if intersection between them is greater than threshold. - - Args: - candidate: argmax predictions per frame (for ctc) or rnnt hypothesis (for rnnt) - asr_model: ctc or hybrid transducer-ctc model - cb_results: list of context biasing predictions (spotted words) - decoder_type: ctc or rnnt - intersection_threshold: threshold for intersection between spotted word and word from alignment (in percentage) - blank_idx: blank index for ctc/rnnt decoding - print_stats: if True, print word alignment and spotted words - bow: symbol for begin of word (bow) in BPE tokenizer - Returns: - boosted_text: final text with context biasing predictions - """ - - # step 1: get token-level alignment [frame, token] - if decoder_type == "ctc": - alignment_tokens = [] - prev_token = None - for idx, token in enumerate(candidate): - if token != blank_idx: - if token == prev_token: - alignment_tokens[-1] = [idx, asr_model.tokenizer.ids_to_tokens([int(token)])[0]] - else: - alignment_tokens.append([idx, asr_model.tokenizer.ids_to_tokens([int(token)])[0]]) - prev_token = token - - elif decoder_type == "rnnt": - alignment_tokens = [] - if not isinstance(candidate.y_sequence, list): - candidate.y_sequence = candidate.y_sequence.tolist() - tokens = asr_model.tokenizer.ids_to_tokens(candidate.y_sequence) - for idx, token in enumerate(tokens): - # bow symbol may be predicted separately from token - if token == bow: - if idx + 1 < len(tokens) and not tokens[idx + 1].startswith(bow): - tokens[idx + 1] = bow + tokens[idx + 1] - continue - alignment_tokens.append([candidate.timestamp[idx].item(), token]) - else: - raise ValueError(f"decoder_type {decoder_type} is not supported") - - if not alignment_tokens: - # ctc/rnnt decoding results are empty, return context biasing results only - return " ".join([ws_hyp.word for ws_hyp in cb_results]), "" - - # step 2: get word-level alignment [word, start_frame, end_frame] - word_alignment = [] - word = "" - ( - L, - r, - ) = ( - None, - None, - ) - for item in alignment_tokens: - if not word: - word = item[1][1:] - L = r = item[0] - else: - if item[1].startswith(bow): - word_alignment.append((word, L, r)) - word = item[1][1:] - L = r = item[0] - else: - word += item[1] - r = item[0] - word_alignment.append((word, L, r)) - initial_text_transcript = " ".join([item[0] for item in word_alignment]) - if print_stats: - logging.info(f"Word alignment: {word_alignment}") - - # step 3: merge spotted words with word alignment - for ws_hyp in cb_results: - # extend ws_hyp start frame in case of rnnt (rnnt tends to predict labels one frame earlier sometimes) - if ws_hyp.start_frame > 0 and decoder_type == "rnnt": - ws_hyp.start_frame -= 1 - new_word_alignment = [] - already_inserted = False - # get interval of spotted word - ws_interval = set(range(ws_hyp.start_frame, ws_hyp.end_frame + 1)) - for item in word_alignment: - # get interval if word from alignment - li, ri = item[1], item[2] - item_interval = set(range(li, ri + 1)) - if ws_hyp.start_frame < li: - # spotted word starts before first word from alignment - if not already_inserted: - new_word_alignment.append((ws_hyp.word, ws_hyp.start_frame, ws_hyp.end_frame)) - already_inserted = True - # compute intersection between spotted word and word from alignment in percentage - intersection_part = 100 / len(item_interval) * len(ws_interval & item_interval) - if intersection_part <= intersection_threshold: - new_word_alignment.append(item) - elif not already_inserted: - # word from alignment will be replaced by spotted word - new_word_alignment.append((ws_hyp.word, ws_hyp.start_frame, ws_hyp.end_frame)) - already_inserted = True - # insert last spotted word if not yet - if not already_inserted: - new_word_alignment.append((ws_hyp.word, ws_hyp.start_frame, ws_hyp.end_frame)) - word_alignment = new_word_alignment - if print_stats: - logging.info(f"Spotted word: {ws_hyp.word} [{ws_hyp.start_frame}, {ws_hyp.end_frame}]") - - boosted_text_list = [item[0] for item in new_word_alignment] - boosted_text = " ".join(boosted_text_list) - - return boosted_text, initial_text_transcript - - -def compute_fscore( - recognition_results_manifest: str, - key_words_list: List, - eps: str = "", - print_stats: bool = False, -) -> tuple[float, float, float]: - """ - Compute fscore for list of context biasing words/phrases. - The idea is to get a word-level alignment for ground truth text and prediction results from manifest file. - Then compute f-score for each word/phrase from key_words_list according to obtained word alignment. - - Args: - recognition_results_manifest: path to nemo manifest file with recognition results in pred_text field. - key_words_list: list of context biasing words/phrases. - return_scores: if True, return precision, recall and fscore (not only print). - eps: epsilon symbol for alignment. - Returns: - Returns tuple of precision, recall and fscore. - """ - - assert key_words_list, "key_words_list is empty" - - # get data from manifest - assert os.path.isfile(recognition_results_manifest), f"manifest file {recognition_results_manifest} doesn't exist" - data = read_manifest(recognition_results_manifest) - assert len(data) > 0, "manifest file is empty" - assert data[0].get('text', None), "manifest file should contain text field" - assert data[0].get('pred_text', None), "manifest file should contain pred_text field" - - # compute max number of words in one context biasing phrase - max_ngram_order = max([len(item.split()) for item in key_words_list]) - key_words_stat = {} # a word here can be single word or phareses - for word in key_words_list: - key_words_stat[word] = [0, 0, 0] # [true positive (tp), groud truth (gt), false positive (fp)] - - for item in data: - # get alignment by texterrors - ref = item['text'].split() - hyp = item['pred_text'].split() - ali = align(ref, hyp, eps) - - # 1-grams - for idx in range(len(ali)): - word_ref = ali[idx][0] - word_hyp = ali[idx][1] - if word_ref in key_words_stat: - key_words_stat[word_ref][1] += 1 # add to gt - if word_ref == word_hyp: - key_words_stat[word_ref][0] += 1 # add to tp - elif word_hyp in key_words_stat: - key_words_stat[word_hyp][2] += 1 # add to fp - - # 2-grams and higher (takes into account epsilons in alignment) - for ngram_order in range(2, max_ngram_order + 1): - # for reference phrase - idx = 0 - item_ref = [] - while idx < len(ali): - if item_ref: - item_ref = [item_ref[1]] - idx = item_ref[0][1] + 1 # idex of second non eps word + 1 - while len(item_ref) != ngram_order and idx < len(ali): - word = ali[idx][0] - idx += 1 - if word == eps: - continue - else: - item_ref.append((word, idx - 1)) - if len(item_ref) == ngram_order: - phrase_ref = " ".join([item[0] for item in item_ref]) - phrase_hyp = " ".join([ali[item[1]][1] for item in item_ref]) - if phrase_ref in key_words_stat: - key_words_stat[phrase_ref][1] += 1 # add to gt - if phrase_ref == phrase_hyp: - key_words_stat[phrase_ref][0] += 1 # add to tp - # in case of false positive hypothesis phrase - idx = 0 - item_hyp = [] - while idx < len(ali): - if item_hyp: - item_hyp = [item_hyp[1]] - idx = item_hyp[0][1] + 1 # idex of first non eps word in previous ngram + 1 - while len(item_hyp) != ngram_order and idx < len(ali): - word = ali[idx][1] - idx += 1 - if word == eps: - continue - else: - item_hyp.append((word, idx - 1)) - if len(item_hyp) == ngram_order: - phrase_hyp = " ".join([item[0] for item in item_hyp]) - phrase_ref = " ".join([ali[item[1]][0] for item in item_hyp]) - if phrase_hyp in key_words_stat and phrase_hyp != phrase_ref: - key_words_stat[phrase_hyp][2] += 1 # add to fp - - tp = sum([key_words_stat[x][0] for x in key_words_stat]) - gt = sum([key_words_stat[x][1] for x in key_words_stat]) - fp = sum([key_words_stat[x][2] for x in key_words_stat]) - - precision = tp / (tp + fp + 1e-8) - recall = tp / (gt + 1e-8) - fscore = 2 * (precision * recall) / (precision + recall + 1e-8) - - if print_stats: - logging.info("=" * 60) - logging.info("Per words statistic (word: correct/totall | false positive):\n") - max_len = max([len(x) for x in key_words_stat if key_words_stat[x][1] > 0 or key_words_stat[x][2] > 0]) - for word in key_words_list: - if key_words_stat[word][1] > 0 or key_words_stat[word][2] > 0: - false_positive = "" - if key_words_stat[word][2] > 0: - false_positive = key_words_stat[word][2] - if print_stats: - logging.info( - f"{word:>{max_len}}: {key_words_stat[word][0]:3}/{key_words_stat[word][1]:<3} |{false_positive:>3}" - ) - if print_stats: - logging.info("=" * 60) - logging.info("=" * 60) - logging.info(f"Precision: {precision:.4f} ({tp}/{tp + fp}) fp:{fp}") - logging.info(f"Recall: {recall:.4f} ({tp}/{gt})") - logging.info(f"Fscore: {fscore:.4f}") - logging.info("=" * 60) - - return (precision, recall, fscore) diff --git a/nemo/collections/asr/parts/context_biasing/context_graph_ctc.py b/nemo/collections/asr/parts/context_biasing/context_graph_ctc.py deleted file mode 100644 index b0282efa4d4eea20c8bb99ccecdb5cc04e53b89c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/context_biasing/context_graph_ctc.py +++ /dev/null @@ -1,249 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Copyright 2023 Xiaomi Corp. (authors: Wei Kang) -# -# See ../LICENSE for clarification regarding multiple authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# The script was obtained and modified from Icefall repo: -# https://github.com/k2-fsa/icefall/blob/11d816d174076ec9485ab8b1d36af2592514e348/icefall/context_graph.py - -from collections import deque -from typing import Dict, List, Optional - - -try: - import graphviz - - _GRAPHVIZ_AVAILABLE = True -except (ImportError, ModuleNotFoundError): - _GRAPHVIZ_AVAILABLE = False - - -class ContextState: - """The state in ContextGraph""" - - def __init__( - self, - index: int, - is_end: bool = False, - word: Optional[str] = None, - ): - """Create a ContextState. - Args: - index: - The node index, only for visualization now. A node is in [0, graph.num_nodes). - The index of the root node is always 0. - is_end: - True if current node is the end of a context biasing word. - word: - The word of coresponding transcription (not None only for end states). - """ - self.index = index - self.is_end = is_end - self.word = word - # dict of next token transitions to next states (key: token, value: next state) - self.next = {} - # the best token on current state (needed for state pruning during word spotter work) - self.best_token = None - - -class ContextGraphCTC: - """ - Context-biasing graph (based on prefix tree) according to the CTC transition topology (with blank nodes). - A ContextGraph contains some words / phrases that we expect to boost their recognition accuracy. - """ - - def __init__(self, blank_id: int = 1024): - """ - Initialize the ContextGraphCTC based on given blank_id. - - Args: - blank_id: the id of blank token in ASR model - """ - - self.num_nodes = 0 - self.root = ContextState(index=self.num_nodes, is_end=False) - self.blank_token = blank_id - - def add_to_graph(self, word_items: List[tuple[str, List[List[int]]]]): - """ - Adding nodes to the context graph based on given word_items. - - Args: - word_items: a list of word items, each word item is a tuple of (word, tokenizations) - word: the word to be inserted into the context graph - tokenizations: a list of possible BPE word tokenizations - (each word can have several tokenizations to improve the recognition accuracy) - - """ - # process context biasing words with tokenizations - for word_item in word_items: - for tokens in word_item[1]: - prev_node = self.root - prev_token = None - for i, token in enumerate(tokens): - if token not in prev_node.next: - self.num_nodes += 1 - is_end = i == len(tokens) - 1 - word = word_item[0] if is_end else None - node = ContextState(index=self.num_nodes, is_end=is_end, word=word) - node.next[token] = node - prev_node.next[token] = node - - # add blank node: - if prev_node is not self.root: - if self.blank_token in prev_node.next: - # blank node already exists - prev_node.next[self.blank_token].next[token] = node - else: - # create new blank node - self.num_nodes += 1 - blank_node = ContextState(index=self.num_nodes, is_end=False) - blank_node.next[self.blank_token] = blank_node - blank_node.next[token] = node - prev_node.next[self.blank_token] = blank_node - - # in case of two consecutive equal tokens - if token == prev_token: - # if token already in prev_node.next[balnk_token].next - if self.blank_token in prev_node.next and token in prev_node.next[self.blank_token].next: - prev_node = prev_node.next[self.blank_token].next[token] - prev_token = token - continue - # create new token - self.num_nodes += 1 - is_end = i == len(tokens) - 1 - word = word_item[0] if is_end else None - node = ContextState(index=self.num_nodes, is_end=is_end, word=word) - # add blank - if self.blank_token in prev_node.next: - prev_node.next[self.blank_token].next[token] = node - node.next[token] = node - else: - # create new blank node - self.num_nodes += 1 - blank_node = ContextState(index=self.num_nodes, is_end=False) - blank_node.next[self.blank_token] = blank_node - blank_node.next[token] = node - prev_node.next[self.blank_token] = blank_node - # rewrite previous node - if prev_node.index != prev_node.next[token].index: - prev_node = prev_node.next[token] - else: - prev_node = prev_node.next[self.blank_token].next[token] - prev_token = token - - def draw( - self, - title: Optional[str] = None, - symbol_table: Optional[Dict[int, str]] = None, - ) -> "graphviz.Digraph": - """Visualize a ContextGraph via graphviz. - - Render ContextGraph as an image via graphviz, and return the Digraph object - - Note: - You need to install graphviz to use this function: - pip install graphviz - - Args: - title: - Title to be displayed in image, e.g. 'A simple FSA example' - symbol_table: - Map the token ids to symbols. - Returns: - A Diagraph from grahpviz. - """ - if _GRAPHVIZ_AVAILABLE is False: - raise ImportError("graphviz is not installed") - - graph_attr = { - "rankdir": "LR", - "size": "8.5,11", - "center": "1", - "orientation": "Portrait", - "ranksep": "0.30", - "nodesep": "0.25", - } - if title is not None: - graph_attr["label"] = title - - default_edge_attr = { - "fontsize": "12", - } - - default_node_attr = { - "shape": "circle", - "style": "bold", - "fontsize": "12", - } - - final_state_attr = { - "shape": "doublecircle", - "style": "bold", - "fontsize": "12", - } - - dot = graphviz.Digraph(name="Context Graph", graph_attr=graph_attr) - - seen = set() - queue = deque() - queue.append(self.root) - # root id is always 0 - dot.node("0", label="0", **default_node_attr) - seen.add(0) - printed_arcs = set() - - while len(queue): - current_node = queue.popleft() - for token, node in current_node.next.items(): - if node.index not in seen: - label = f"{node.index}" - if node.is_end: - dot.node(str(node.index), label=label, **final_state_attr) - else: - dot.node(str(node.index), label=label, **default_node_attr) - seen.add(node.index) - label = str(token) if symbol_table is None else symbol_table[token] - if node.index != current_node.index: - output, input, arc = str(current_node.index), str(node.index), f"{label}" - if (output, input, arc) not in printed_arcs: - if arc == self.blank_token: - dot.edge(output, input, label=self.blank_token, color="blue", **default_edge_attr) - else: - dot.edge(output, input, label=arc) - queue.append(node) - else: - output, input, arc = str(current_node.index), str(current_node.index), f"{label}" - if (output, input, arc) not in printed_arcs: - if arc == self.blank_token: - dot.edge(output, input, label=self.blank_token, color="blue", **default_edge_attr) - else: - dot.edge(output, input, label=arc, color="green") - printed_arcs.add((output, input, arc)) - - return dot diff --git a/nemo/collections/asr/parts/context_biasing/context_graph_universal.py b/nemo/collections/asr/parts/context_biasing/context_graph_universal.py deleted file mode 100644 index 5671f5bdd90afe31957b77428d6f60cdc431dd19..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/context_biasing/context_graph_universal.py +++ /dev/null @@ -1,389 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Copyright 2023 Xiaomi Corp. (authors: Wei Kang) -# -# See ../LICENSE for clarification regarding multiple authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# The script was obtained and modified from Icefall repo: -# https://github.com/k2-fsa/icefall/blob/aac7df064a6d1529f3bf4acccc6c550bd260b7b3/icefall/context_graph.py - - -import os -import shutil -from collections import deque -from typing import Dict, List, Optional -import numpy as np - - -class ContextState: - """The state in ContextGraph""" - - def __init__( - self, - id: int, - token: int, - token_score: float, - node_score: float, - output_score: float, - is_end: bool, - level: int, - phrase: str = "", - ac_threshold: float = 1.0, - ): - """Create a ContextState. - - Args: - id: - The node id, only for visualization now. A node is in [0, graph.num_nodes). - The id of the root node is always 0. - token: - The token id. - token_score: - The bonus for each token during decoding, which will hopefully - boost the token up to survive beam search. - node_score: - The accumulated bonus from root of graph to current node, it will be - used to calculate the score for fail arc. - output_score: - The total scores of matched phrases, sum of the node_score of all - the output node for current node. - is_end: - True if current token is the end of a context. - level: - The distance from current node to root. - phrase: - The context phrase of current state, the value is valid only when - current state is end state (is_end == True). - ac_threshold: - The acoustic threshold (probability) of current context phrase, the - value is valid only when current state is end state (is_end == True). - Note: ac_threshold only used in keywords spotting. - """ - self.id = id - self.token = token - self.token_score = token_score - self.node_score = node_score - self.output_score = output_score - self.is_end = is_end - self.level = level - self.next = {} - self.phrase = phrase - self.ac_threshold = ac_threshold - self.fail = None - self.output = None - - -class ContextGraph: - """The ContextGraph is modified from Aho-Corasick which is mainly - a Trie with a fail arc for each node. - See https://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_algorithm for more details - of Aho-Corasick algorithm. - - A ContextGraph contains some words / phrases that we expect to boost their - scores during decoding. If the substring of a decoded sequence matches the word / phrase - in the ContextGraph, we will give the decoded sequence a bonus to make it survive - beam search. - """ - - def __init__(self, context_score: float, depth_scaling: float = 1.0, ac_threshold: float = 1.0): - """Initialize a ContextGraph with the given ``context_score``. - - A root node will be created (**NOTE:** the token of root is hardcoded to -1). - - Args: - context_score: - The bonus score for each token(note: NOT for each word/phrase, it means longer - word/phrase will have larger bonus score, they have to be matched though). - Note: This is just the default score for each token, the users can manually - specify the context_score for each word/phrase (i.e. different phrase might - have different token score). - depth_scaling: - The depth scaling factor for each token [1, inf), it is used to give a larger score for all tokens after the first one. - ac_threshold: - The acoustic threshold (probability) to trigger the word/phrase, this argument - is used only when applying the graph to keywords spotting system. - """ - self.context_score = context_score - self.depth_scaling = depth_scaling - self.ac_threshold = ac_threshold - self.num_nodes = 0 - self.root = ContextState( - id=self.num_nodes, - token=-1, - token_score=0, - node_score=0, - output_score=0, - is_end=False, - level=0, - ) - self.root.fail = self.root - - def _fill_fail_output(self): - """This function fills the fail arc for each trie node, it can be computed - in linear time by performing a breadth-first search starting from the root. - See https://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_algorithm for the - details of the algorithm. - """ - queue = deque() - for token, node in self.root.next.items(): - node.fail = self.root - queue.append(node) - while queue: - current_node = queue.popleft() - for token, node in current_node.next.items(): - fail = current_node.fail - if token in fail.next: - fail = fail.next[token] - else: - fail = fail.fail - while token not in fail.next: - fail = fail.fail - if fail.token == -1: # root - break - if token in fail.next: - fail = fail.next[token] - node.fail = fail - # fill the output arc - output = node.fail - while not output.is_end: - output = output.fail - if output.token == -1: # root - output = None - break - node.output = output - node.output_score += 0 if output is None else output.output_score - queue.append(node) - - def build( - self, - token_ids: List[List[int]], - phrases: Optional[List[str]] = None, - scores: Optional[List[float]] = None, - ac_thresholds: Optional[List[float]] = None, - uniform_weights: Optional[bool] = False, - ): - """Build the ContextGraph from a list of token list. - It first build a trie from the given token lists, then fill the fail arc - for each trie node. - - See https://en.wikipedia.org/wiki/Trie for how to build a trie. - - Args: - token_ids: - The given token lists to build the ContextGraph, it is a list of - token list, the token list contains the token ids - for a word/phrase. The token id could be an id of a char - (modeling with single Chinese char) or an id of a BPE - (modeling with BPEs). - phrases: - The given phrases, they are the original text of the token_ids, the - length of `phrases` MUST be equal to the length of `token_ids`. - scores: - The customize boosting score(token level) for each word/phrase, - 0 means using the default value (i.e. self.context_score). - It is a list of floats, and the length of `scores` MUST be equal to - the length of `token_ids`. - ac_thresholds: - The customize trigger acoustic threshold (probability) for each phrase, - 0 means using the default value (i.e. self.ac_threshold). It is - used only when this graph applied for the keywords spotting system. - The length of `ac_threshold` MUST be equal to the length of `token_ids`. - uniform_weights: - If True, the weights will be distributed uniformly for all tokens as in Icefall. - - Note: The phrases would have shared states, the score of the shared states is - the MAXIMUM value among all the tokens sharing this state. - """ - num_phrases = len(token_ids) - if phrases is not None: - assert len(phrases) == num_phrases, (len(phrases), num_phrases) - if scores is not None: - assert len(scores) == num_phrases, (len(scores), num_phrases) - if ac_thresholds is not None: - assert len(ac_thresholds) == num_phrases, (len(ac_thresholds), num_phrases) - - for index, tokens in enumerate(token_ids): - phrase = "" if phrases is None else phrases[index] - score = 0.0 if scores is None else scores[index] - ac_threshold = 0.0 if ac_thresholds is None else ac_thresholds[index] - node = self.root - # If has customized score using the customized token score, otherwise - # using the default score - context_score = self.context_score if score == 0.0 else score - threshold = self.ac_threshold if ac_threshold == 0.0 else ac_threshold - for i, token in enumerate(tokens): - if token not in node.next: - if i > 0 and not uniform_weights: - token_score = context_score * self.depth_scaling + np.log( - i + 1 - ) # depth scaling is used to give a larger score for all tokens after the first one - else: - token_score = context_score - self.num_nodes += 1 - is_end = i == len(tokens) - 1 - node_score = node.node_score + token_score - node.next[token] = ContextState( - id=self.num_nodes, - token=token, - token_score=token_score, - node_score=node_score, - output_score=node_score if is_end else 0, - is_end=is_end, - level=i + 1, - phrase=phrase if is_end else "", - ac_threshold=threshold if is_end else 0.0, - ) - else: - # node exists, get the score of shared state. - token_score = max(context_score, node.next[token].token_score) - node.next[token].token_score = token_score - node_score = node.node_score + token_score - node.next[token].node_score = node_score - is_end = i == len(tokens) - 1 or node.next[token].is_end - node.next[token].output_score = node_score if is_end else 0 - node.next[token].is_end = is_end - if i == len(tokens) - 1: - node.next[token].phrase = phrase - node.next[token].ac_threshold = threshold - node = node.next[token] - self._fill_fail_output() - - def draw( - self, - title: Optional[str] = None, - filename: Optional[str] = "", - symbol_table: Optional[Dict[int, str]] = None, - ) -> "Digraph": # noqa - """Visualize a ContextGraph via graphviz. - - Render ContextGraph as an image via graphviz, and return the Digraph object; - and optionally save to file `filename`. - `filename` must have a suffix that graphviz understands, such as - `pdf`, `svg` or `png`. - - Note: - You need to install graphviz to use this function:: - - pip install graphviz - - Args: - title: - Title to be displayed in image, e.g. 'A simple FSA example' - filename: - Filename to (optionally) save to, e.g. 'foo.png', 'foo.svg', - 'foo.png' (must have a suffix that graphviz understands). - symbol_table: - Map the token ids to symbols. - Returns: - A Diagraph from grahpviz. - """ - - try: - import graphviz - except Exception: - print("You cannot use `to_dot` unless the graphviz package is installed.") - raise - - graph_attr = { - "rankdir": "LR", - "size": "8.5,11", - "center": "1", - "orientation": "Portrait", - "ranksep": "0.4", - "nodesep": "0.25", - } - if title is not None: - graph_attr["label"] = title - - default_node_attr = { - "shape": "circle", - "style": "bold", - "fontsize": "14", - } - - final_state_attr = { - "shape": "doublecircle", - "style": "bold", - "fontsize": "14", - } - - dot = graphviz.Digraph(name="Context Graph", graph_attr=graph_attr) - - seen = set() - queue = deque() - queue.append(self.root) - # root id is always 0 - dot.node("0", label="0", **default_node_attr) - dot.edge("0", "0", color="red") - seen.add(0) - - while len(queue): - current_node = queue.popleft() - for token, node in current_node.next.items(): - if node.id not in seen: - node_score = f"{node.node_score:.2f}".rstrip("0").rstrip(".") - output_score = f"{node.output_score:.2f}".rstrip("0").rstrip(".") - label = f"{node.id}/({node_score}, {output_score})" - if node.is_end: - dot.node(str(node.id), label=label, **final_state_attr) - else: - dot.node(str(node.id), label=label, **default_node_attr) - seen.add(node.id) - weight = f"{node.token_score:.2f}".rstrip("0").rstrip(".") - label = str(token) if symbol_table is None else symbol_table[token] - dot.edge(str(current_node.id), str(node.id), label=f"{label}/{weight}") - dot.edge( - str(node.id), - str(node.fail.id), - color="red", - ) - if node.output is not None: - dot.edge( - str(node.id), - str(node.output.id), - color="green", - ) - queue.append(node) - - if filename: - _, extension = os.path.splitext(filename) - if extension == "" or extension[0] != ".": - raise ValueError("Filename needs to have a suffix like .png, .pdf, .svg: {}".format(filename)) - - import tempfile - - with tempfile.TemporaryDirectory() as tmp_dir: - temp_fn = dot.render( - filename="temp", - directory=tmp_dir, - format=extension[1:], - cleanup=True, - ) - - shutil.move(temp_fn, filename) - - return dot diff --git a/nemo/collections/asr/parts/context_biasing/ctc_based_word_spotter.py b/nemo/collections/asr/parts/context_biasing/ctc_based_word_spotter.py deleted file mode 100644 index d9240eec8d8dc9b15603ead550cc43a2d8e08f8f..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/context_biasing/ctc_based_word_spotter.py +++ /dev/null @@ -1,365 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from dataclasses import dataclass -from typing import List, Optional - -import numpy as np - -from nemo.collections.asr.parts.context_biasing.context_graph_ctc import ContextGraphCTC, ContextState - - -@dataclass -class Token: - """ - Dataclass of alignment tracking according to the Token Passing Algoritm (TPA). - - Args: - state: state of Context-Biasing graph - score: accumulated token score in log space - start_frame: index of acoustic frame from which the token was created - alive: token status (alive or dead) - """ - - state: ContextState - score: float = 0.0 - start_frame: Optional[int] = None - alive: bool = True - - -@dataclass -class WSHyp: - """ - Hypothesis of Word Spotter prediction - - Args: - word: spotted word - score: accumulative score of best token - start_frame: index of acoustic frame from which the best token was created - end_frame: index of acoustic frame from which the final state of ContextGraph was reached - """ - - word: str - score: float - start_frame: int - end_frame: int - - -def beam_pruning(next_tokens: List[Token], beam_threshold: float) -> List[Token]: - """ - Prun all tokens whose score is worse than best_token.score - beam_threshold - - Args: - next_tokens: list of input tokens - beam_threshold: beam threshold - - Returns: - list of pruned tokens - """ - if not next_tokens: - return [] - best_token = next_tokens[np.argmax([token.score for token in next_tokens])] - next_tokens = [token for token in next_tokens if token.score > best_token.score - beam_threshold] - return next_tokens - - -def state_pruning(next_tokens: List[Token]) -> List[Token]: - """ - If there are several tokens on the same state, then leave only the best of them according to score - - Args: - next_tokens: list of input tokens - - Returns: - list of pruned tokens - """ - if not next_tokens: - return [] - # traverse all tokens and check each graph state for the best token - for token in next_tokens: - if not token.state.best_token: - token.state.best_token = token - else: - if token.score <= token.state.best_token.score: - token.alive = False - else: - token.state.best_token.alive = False - token.state.best_token = token - # save only alive tokens - next_tokens_pruned = [token for token in next_tokens if token.alive] - # clean all best_tokens in context_graph - for token in next_tokens: - token.state.best_token = None - return next_tokens_pruned - - -def find_best_hyps(spotted_words: List[WSHyp], intersection_threshold: int = 10) -> List[WSHyp]: - """ - Some spotted hypotheses may have overlap. - If hypotheses intersection is greater than intersection_threshold, - then the function leaves only the best hypothesis according to the score. - - Args: - spotted_words: list of spotter hypotheses WSHyp - intersection_threshold: minimal intersection threshold (in percentages) - - Returns: - list of best hyps without intersection - """ - - hyp_intervals_dict = {} - for hyp in spotted_words: - hyp_interval = set(range(hyp.start_frame, hyp.end_frame + 1)) - h_interval_name = f"{hyp.start_frame}_{hyp.end_frame}" - insert_new_hyp = True - - # check hyp intersection with all the elements in hyp_intervals_dict - for h_interval_key in hyp_intervals_dict: - # get left and right interval values - l, r = int(h_interval_key.split("_")[0]), int(h_interval_key.split("_")[1]) - current_dict_interval = set(range(l, r + 1)) - intersection_part = 100 / len(current_dict_interval) * len(hyp_interval & current_dict_interval) - # in case of intersection: - if intersection_part >= intersection_threshold: - if hyp.score > hyp_intervals_dict[h_interval_key].score: - hyp_intervals_dict.pop(h_interval_key) - insert_new_hyp = True - break - else: - insert_new_hyp = False - if insert_new_hyp: - hyp_intervals_dict[h_interval_name] = hyp - - best_hyp_list = [hyp_intervals_dict[h_interval_key] for h_interval_key in hyp_intervals_dict] - - return best_hyp_list - - -def get_ctc_word_alignment( - logprob: np.ndarray, asr_model, token_weight: float = 1.0, blank_idx: int = 0 -) -> List[tuple]: - """ - Get word level alignment (with start and end frames) based on argmax ctc predictions. - The word score is a sum of non-blank token logprobs with additional token_weight. - token_weight is used to prevent false accepts during filtering word spotting hypotheses. - - Args: - logprob: ctc logprobs - asr_model: asr model (ctc or hybrid transducer-ctc) - token_weight: additional token weight for word-level ctc alignment - - Returns: - list of word level alignment where each element is tuple (word, left_frame, rigth_frame, word_score) - """ - - alignment_ctc = np.argmax(logprob, axis=1) - - # get token level alignment - token_alignment = [] - prev_idx = None - for i, idx in enumerate(alignment_ctc): - token_logprob = 0 - if idx != blank_idx: - token = asr_model.tokenizer.ids_to_tokens([int(idx)])[0] - if idx == prev_idx: - prev_repited_token = token_alignment.pop() - token_logprob += prev_repited_token[2] - token_logprob += logprob[i, idx].item() - token_alignment.append((token, i, token_logprob)) - prev_idx = idx - - # get word level alignment - begin_of_word = "▁" - word_alignment = [] - word = "" - l, r, score = None, None, None - for item in token_alignment: - if not word: - if word.startswith(begin_of_word): - word = item[0][1:] - else: - word = item[0][:] - l = item[1] - r = item[1] - score = item[2] + token_weight - else: - if item[0].startswith(begin_of_word): - word_alignment.append((word, l, r, score)) - word = item[0][1:] - l = item[1] - r = item[1] - score = item[2] + token_weight - else: - word += item[0] - r = item[1] - score += item[2] + token_weight - if word: - word_alignment.append((word, l, r, score)) - - if len(word_alignment) == 1 and not word_alignment[0][0]: - word_alignment = [] - - return word_alignment - - -def filter_wb_hyps(best_hyp_list: List[WSHyp], word_alignment: List[tuple]) -> List[WSHyp]: - """ - Compare scores of spotted words with overlapping words from ctc alignment. - If score of spotted word is less than overalapping words from ctc alignment, - the spotted word will removed as false positive. - A spotted word may overlap with several words from ctc alignment ("gpu" -> "g p u"). - Here we use overall_spot_score variable to accumulate scores of several words. - - Args: - best_hyp_list: list of spotted hypotheses WSHyp - word_alignment: world level ctc alignment with word scores - - Returns: - filtered best_hyp_list - """ - - if not word_alignment: - return best_hyp_list - - best_hyp_list_filtered = [] - current_word_in_ali = 0 - for hyp in best_hyp_list: - overall_spot_score = 0 - hyp_intersects = False - hyp_interval = set(range(hyp.start_frame, hyp.end_frame + 1)) - # check if spotted word overlaps with words from ctc alignment - for i in range(current_word_in_ali, len(word_alignment)): - word_stats = word_alignment[i] - word_interval = set(range(word_stats[1], word_stats[2] + 1)) - intersection_part = 100 / len(word_interval) * len(hyp_interval & word_interval) - if intersection_part: - if not hyp_intersects: - overall_spot_score = word_stats[3] - else: - overall_spot_score += intersection_part / 100 * word_stats[3] - hyp_intersects = True - elif hyp_intersects: - # add hyp to the best list - if hyp.score >= overall_spot_score: - best_hyp_list_filtered.append(hyp) - current_word_in_ali = i - hyp_intersects = False - break - # if hyp has not yet been added (end of sentence case) - if hyp_intersects and hyp.score >= overall_spot_score: - best_hyp_list_filtered.append(hyp) - - return best_hyp_list_filtered - - -def run_word_spotter( - logprobs: np.ndarray, - context_graph: ContextGraphCTC, - asr_model, - blank_idx: int = 0, - beam_threshold: float = 5.0, - cb_weight: float = 3.0, - ctc_ali_token_weight: float = 0.5, - keyword_threshold: float = -5.0, - blank_threshold: float = 0.8, - non_blank_threshold: float = 0.001, -): - """ - CTC-based Word Spotter for recognition of words from context biasing graph (paper link) - The algorithm is based on the Token Passing Algorithm (TPA) and uses run, beam and state prunings. - Blank and non-blank thresholds are used for preliminary hypotheses pruning. - The algorithm is implemented in log semiring. - - Args: - logprobs: CTC logprobs for one file [Time, Vocab+blank] - context_graph: Context-Biasing graph - blank_idx: blank index in ASR model - asr_model: ASR model (ctc or hybrid-transducer-ctc) - beam_threshold: threshold for beam pruning - cb_weight: context biasing weight - ctc_ali_token_weight: additional token weight for word-level ctc alignment - keyword_threshold: auxiliary weight for pruning final hypotheses - blank_threshold: blank threshold (probability) for preliminary hypotheses pruning - non_blank_threshold: non-blank threshold (probability) for preliminary hypotheses pruning - - Returns: - final list of spotted hypotheses WSHyp - """ - - start_state = context_graph.root - active_tokens = [] - next_tokens = [] - spotted_words = [] - - # move threshold probabilities to log space - blank_threshold = np.log(blank_threshold) - non_blank_threshold = np.log(non_blank_threshold) - - for frame in range(logprobs.shape[0]): - # add an empty token (located in the graph root) at each new frame to start new word spotting - active_tokens.append(Token(start_state, start_frame=frame)) - best_score = None - for token in active_tokens: - # skip token by the blank_threshold if empty token - if token.state is context_graph.root and logprobs[frame][blank_idx] > blank_threshold: - continue - for transition_state in token.state.next: - # skip non-blank token by the non_blank_threshold if empty token - if token.state is context_graph.root and logprobs[frame][int(transition_state)] < non_blank_threshold: - continue - # running beam pruning (start) - skips current token by score before Token class creations - if transition_state != blank_idx: - # add cb_weight only for non-blank tokens - current_score = token.score + logprobs[frame][int(transition_state)].item() + cb_weight - else: - current_score = token.score + logprobs[frame][int(transition_state)].item() - if not best_score: - best_score = current_score - else: - if current_score < best_score - beam_threshold: - continue - elif current_score > best_score: - best_score = current_score - # running beam pruning (end) - - new_token = Token(token.state.next[transition_state], current_score, token.start_frame) - # add a word as spotted if token reached the end of word state in context graph: - if new_token.state.is_end and new_token.score > keyword_threshold: - word = new_token.state.word - spotted_words.append( - WSHyp(word=word, score=new_token.score, start_frame=new_token.start_frame, end_frame=frame) - ) - # check case when the current state is the last in the branch (only one self-loop transition) - if len(new_token.state.next) == 1: - if current_score is best_score: - best_score = None - continue - next_tokens.append(new_token) - # state and beam prunings: - next_tokens = beam_pruning(next_tokens, beam_threshold) - next_tokens = state_pruning(next_tokens) - - active_tokens = next_tokens - next_tokens = [] - - # find best hyps for spotted keywords (in case of hyps overlapping): - best_hyp_list = find_best_hyps(spotted_words) - - # filter hyps according to word-level ctc alignment to avoid a high false accept rate - ctc_word_alignment = get_ctc_word_alignment( - logprobs, asr_model, token_weight=ctc_ali_token_weight, blank_idx=blank_idx - ) - best_hyp_list = filter_wb_hyps(best_hyp_list, ctc_word_alignment) - - return best_hyp_list diff --git a/nemo/collections/asr/parts/features.py b/nemo/collections/asr/parts/features.py deleted file mode 100644 index 06665c413a45676e67b7950287cc5cd8636ed19d..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/features.py +++ /dev/null @@ -1,39 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Copyright (c) 2018 Ryan Leary -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in all -# copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. -# This file contains code artifacts adapted from https://github.com/ryanleary/patter - -""" -ALIAS FILE for backward compatibility -""" -from nemo.collections.asr.parts.preprocessing.features import * diff --git a/nemo/collections/asr/parts/k2/__init__.py b/nemo/collections/asr/parts/k2/__init__.py deleted file mode 100644 index 2db92b2574167fb3436c079fd7941450ae0c316b..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/k2/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/asr/parts/k2/graph_transducer.py b/nemo/collections/asr/parts/k2/graph_transducer.py deleted file mode 100644 index 874e6e6fd2b4e85d7093a13c248afa43cb295dec..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/k2/graph_transducer.py +++ /dev/null @@ -1,570 +0,0 @@ -# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import abc -from contextlib import nullcontext -from typing import ContextManager - -import torch -import torch.nn.functional as F - -from nemo.core.classes.loss import Loss -from nemo.core.utils.k2_guard import k2 -from nemo.core.utils.optional_libs import TRITON_AVAILABLE -from nemo.utils import logging - -if TRITON_AVAILABLE: - from nemo.collections.asr.parts.k2.rnnt_logprobs_triton import rnnt_logprobs_triton - - -def force_float32_context() -> ContextManager: - """Get context manager to force float32 precision in autocast mode.""" - if torch.is_autocast_enabled(): - return torch.amp.autocast('cuda', dtype=torch.float32) - return nullcontext() - - -class GraphTransducerLossBase(Loss): - """ - Base class for graph transducer losses. - Implementation of the approach described in "Powerful and Extensible WFST Framework for RNN-Transducer Losses" - https://ieeexplore.ieee.org/document/10096679 - - Compose-Transducer: compose the unit (target text) and temporal schemas (graphs) into lattice. - Subclass should implement `get_unit_schema` and `get_temporal_schema` methods. - Grid-Transducer: construct the RNN-T lattice (grid) directly in code. - Subclass should implement `get_grid` method. - """ - - def __init__( - self, use_grid_implementation: bool, connect_composed=False, double_scores=False, cast_to_float32=False - ): - """ - - Args: - use_grid_implementation: Whether to use the grid implementation (Grid-Transducer). - connect_composed: Connect graph after composing unit and temporal schemas (only for Compose-Transducer). - `connect` operation is slow, it is useful for visualization, but not necessary for loss computation. - double_scores: Use calculation of loss in double precision (float64) in the lattice. - Does not significantly affect memory usage since the lattice is ~V/2 times smaller - than the joint tensor. - cast_to_float32: Force cast joint tensor to float32 before log-softmax calculation. - """ - super().__init__() - self.use_grid_implementation = use_grid_implementation - self.connect_composed = connect_composed - self.double_scores = double_scores - self.cast_to_float32 = cast_to_float32 - - @abc.abstractmethod - def get_unit_schema(self, units_tensor: torch.Tensor, vocab_size: int) -> "k2.Fsa": - """ - Get unit schema (target text) graph for Compose-Transducer. - - Args: - units_tensor: tensor with target text - vocab_size: number of labels (including blank). Needed to construct additional eps-arcs (in some cases). - - Returns: - unit schema graph (k2.Fsa). - Labels: :: (k2.Fsa: labels, aux_labels, unit_positions) - """ - pass - - @abc.abstractmethod - def get_temporal_schema(self, num_frames: int, vocab_size: int, device: torch.device) -> "k2.Fsa": - """ - Get temporal schema graph for Compose-Transducer. - - Args: - num_frames: length of the sequence (in frames) - vocab_size: number of labels (including blank) - device: device for tensor to construct - - Returns: - temporal schema graph (k2.Fsa). - Labels: :. is a unit from vocab + special units (e.g., additional eps). - """ - pass - - @abc.abstractmethod - def get_grid(self, units_tensor: torch.Tensor, num_frames: int, vocab_size: int) -> "k2.Fsa": - """ - Construct the transducer lattice (grid) directly for Grid-Transducer. - - Args: - units_tensor: tensor with target text - num_frames: length of the sequence (in frames) - vocab_size: number of labels (including blank) - - Returns: - transducer lattice (k2.Fsa). - Labels: :: (k2.Fsa: labels, aux_labels, unit_positions) - """ - pass - - def get_composed_lattice(self, units_tensor: torch.Tensor, num_frames: int, vocab_size: int) -> "k2.Fsa": - """ - Get composed lattice (unit and temporal schemas) for Compose-Transducer. Useful for visualization. - Should be equivalent to the lattice from `get_grid` method. - - Args: - units_tensor: tensor with target text - num_frames: length of the sequence (in frames) - vocab_size: vocab size (including blank) - - Returns: - composed lattice (k2.Fsa) from unit and temporal schemas - """ - fsa_text = self.get_unit_schema(units_tensor, vocab_size) - fsa_temporal = self.get_temporal_schema(num_frames, vocab_size, units_tensor.device) - composed = k2.compose(fsa_text, fsa_temporal, treat_epsilons_specially=False) - if self.connect_composed: - composed = k2.connect(composed) - return composed - - def get_graphs_batched( - self, source_lengths: torch.Tensor, targets: torch.Tensor, target_lengths: torch.Tensor, vocab_size: int - ) -> "k2.Fsa": - """ - Get batched lattice (grid or composed) for the batch of sequences. - - Args: - source_lengths: tensor with lengths of logits - targets: tensor with target units - target_lengths: tensor with lengths of targets - vocab_size: vocab size (including blank) - - Returns: - batched lattice - FsaVec (k2.Fsa) - """ - batch_size = source_lengths.shape[0] - with torch.no_grad(): - if self.use_grid_implementation: - source_lengths_list = source_lengths.tolist() - target_lengths_list = target_lengths.tolist() - return k2.create_fsa_vec( - [ - self.get_grid( - units_tensor=targets[i, : target_lengths_list[i]], - num_frames=source_lengths_list[i], - vocab_size=vocab_size, - ) - for i in range(batch_size) - ] - ) - - # composed version - text_fsas = [ - self.get_unit_schema( - units_tensor=targets[i, : target_lengths[i].item()], - vocab_size=vocab_size, - ) - for i in range(batch_size) - ] - temporal_fsas = [ - self.get_temporal_schema( - num_frames=source_lengths[i].item(), vocab_size=vocab_size, device=targets.device - ) - for i in range(batch_size) - ] - target_fsas_vec = k2.compose( - k2.create_fsa_vec(text_fsas), k2.create_fsa_vec(temporal_fsas), treat_epsilons_specially=False - ) - if self.connect_composed: - target_fsas_vec = k2.connect(target_fsas_vec) - return target_fsas_vec - - def get_batch_indices(self, target_fsas_vec: k2.Fsa) -> torch.Tensor: - """ - Get batch indices (for logits) for each arc in the lattices. - - Args: - target_fsas_vec: batch of target FSAs with lattices - - Returns: - 1d tensor with indices - """ - batch_size = target_fsas_vec.shape[0] - device = target_fsas_vec.device - scores_to_batch_i = torch.repeat_interleave( - torch.arange(batch_size, device=device, dtype=torch.int64), - torch.tensor( - [target_fsas_vec.arcs.index(0, i)[0].values().shape[0] for i in range(batch_size)], - device=device, - ), - ) - return scores_to_batch_i - - def get_logits_indices(self, target_fsas_vec: k2.Fsa, logits_shape: torch.Size) -> torch.Tensor: - """ - Get indices of flatten logits for each arc in the lattices. - - Args: - target_fsas_vec: batch of target FSAs with lattices - logits_shape: shape of the logits tensor - - Returns: - 1d tensor with indices - """ - # logits_shape: B x Time x Text+1 x Labels - scores_to_batch_i = self.get_batch_indices(target_fsas_vec=target_fsas_vec) - indices = ( - scores_to_batch_i * logits_shape[1] * logits_shape[2] * logits_shape[3] # Batch - + target_fsas_vec.aux_labels.to(torch.int64) * logits_shape[2] * logits_shape[3] # Time indices - + target_fsas_vec.unit_positions.to(torch.int64) * logits_shape[3] # Units (text) indices - + target_fsas_vec.labels.to(torch.int64) # Labels - ) - return indices - - -class GraphRnntLoss(GraphTransducerLossBase): - """ - RNN-T loss implementation based on WFST according - to "Powerful and Extensible WFST Framework for RNN-Transducer Losses" - https://ieeexplore.ieee.org/document/10096679 - """ - - def __init__( - self, - blank: int, - use_grid_implementation=True, - connect_composed=False, - double_scores=False, - cast_to_float32=False, - return_graph=False, - use_triton=True, - ): - """ - Init method - - Args: - blank: blank label index - use_grid_implementation: Whether to use the grid implementation (Grid-Transducer). - connect_composed: Connect graph after composing unit and temporal schemas (only for Compose-Transducer). - `connect` operation is slow, it is useful for visualization, but not necessary for loss computation. - double_scores: Use calculation of loss in double precision (float64) in the lattice. - Does not significantly affect memory usage since the lattice is ~V/2 times smaller - than the joint tensor. - cast_to_float32: Force cast joint tensor to float32 before log-softmax calculation. - return_graph: Return graph (along with loss) from `forward` function - use_triton: use optimized log probs calculations with Triton (faster and more memory efficient) - """ - super().__init__( - use_grid_implementation=use_grid_implementation, - connect_composed=connect_composed, - double_scores=double_scores, - cast_to_float32=cast_to_float32, - ) - self.blank = blank - self.return_graph = return_graph - self.use_triton = use_triton and TRITON_AVAILABLE - if not self.use_triton: - logging.warning("Triton is disabled, memory usage can be larger") - - def get_unit_schema(self, units_tensor: torch.Tensor, vocab_size: int) -> "k2.Fsa": - """ - Get unit schema (target text) graph for RNN-T loss (Compose-Transducer). - Forward arcs represent text labels. - - Example graph: text [1, 2], blank=0. - - graph:: - - 0:0:0 0:0:1 0:0:2 - +-------+ +-------+ +-------+ - v | v | v | - +-----------+ 1:1:0 +-----------+ 2:2:1 +-----------+ -1:-1:-1 #===# - | 0 | -------> | 1 | -------> | 2 | ---------> H 3 H - +-----------+ +-----------+ +-----------+ #===# - - Args: - units_tensor: 1d tensor with text units - vocab_size: number of total labels (vocab size including blank) - - Returns: - unit schema graph (k2.Fsa). - Labels: :: (k2.Fsa: labels, aux_labels, unit_positions) - """ - - blank_id = self.blank - device = units_tensor.device - text_len = units_tensor.shape[0] - - # arcs - # text_len + 1 states, in every state - self-loops (blank) and forward (text label / last forward -1) - arcs = torch.zeros(((text_len + 1) * 2, 4), dtype=torch.int32, device=device) - text_indices = torch.arange(0, text_len + 1, dtype=torch.int32, device=device) - # blank labels - arcs[::2, 0] = text_indices # from state - arcs[::2, 1] = text_indices # to state - arcs[::2, 2] = blank_id - - # text labels - arcs[1::2, 0] = text_indices # from state - arcs[1::2, 1] = text_indices + 1 # to state - arcs[1:-1:2, 2] = units_tensor # labels: text - - arcs[-1, 2] = -1 # last transition to final state, ilabel=-1 (special for k2) - olabels = arcs[:, 2].detach().clone() # same as ilabels - - fsa_text = k2.Fsa(arcs, olabels) - fsa_text.unit_positions = text_indices.expand(2, -1).transpose(0, 1).flatten() - fsa_text.unit_positions[-1] = -1 # last transition to final state - return fsa_text - - def get_temporal_schema(self, num_frames: int, vocab_size: int, device: torch.device) -> "k2.Fsa": - """ - Get temporal schema graph for RNN-T loss (Compose-Transducer). - Forward arc - blank, self-loops - all labels excluding blank - - Example graph: blank=0, num_frames=3, vocab_size=3. - Labels: :. is a unit from vocab. - - graph:: - - 1:0 1:1 1:2 - +-----+ +-----+ +-----+ - v | v | v | - +---------+ 0:0 +---------+ 0:1 +---------+ 0:2 +---+ -1:-1 #===# - | 0 | -----> | 1 | -----> | 2 | -----> | 3 | -------> H 4 H - +---------+ +---------+ +---------+ +---+ #===# - ^ 2:0 | ^ 2:1 | ^ 2:2 | - +-----+ +-----+ +-----+ - - Args: - num_frames: length of the sequence (in frames) - vocab_size: number of labels (including blank) - device: device for tensor to construct - - Returns: - temporal schema graph (k2.Fsa). - Labels: :. is a unit from vocab. - """ - blank_id = self.blank - - fsa_temporal_arcs = torch.zeros((num_frames * vocab_size + 1, 4), dtype=torch.int32, device=device) - sequence_states = torch.arange(0, num_frames, dtype=torch.int32, device=device) - # for every state - vocab_size arcs, [0, 1, ..., vocab_size-1, 0, 1, ..., vocab_size-1, ...] - start_states = sequence_states.expand(vocab_size, num_frames).transpose(0, 1).flatten() - # first: make all arcs - self-loops - fsa_temporal_arcs[:-1, 0] = start_states # from - fsa_temporal_arcs[:-1, 1] = start_states # to - fsa_temporal_arcs[:-1, 2] = ( - torch.arange(0, vocab_size, dtype=torch.int32, device=device).expand(num_frames, vocab_size).flatten() - ) - - # blank-arcs: forward - fsa_temporal_arcs[blank_id:-1:vocab_size, 1] = sequence_states + 1 # blanks - - # transition to last final state - fsa_temporal_arcs[-1, :3] = torch.tensor((num_frames, num_frames + 1, -1), dtype=torch.int32, device=device) - - # output symbols: position in the sequence, same as start states for arcs - olabels = fsa_temporal_arcs[:, 0].detach().clone() - olabels[-1] = -1 # last arc to final state - - fsa_temporal = k2.Fsa(fsa_temporal_arcs, olabels) - fsa_temporal = k2.arc_sort(fsa_temporal) # need for compose - return fsa_temporal - - @staticmethod - def relabel_states(states: torch.Tensor, n: int, m: int) -> torch.Tensor: - """ - Relabel states to be in topological order: by diagonals - - Args: - states: tensor with states - n: number of rows - m: number of columns - - Returns: - tensor with relabeled states (same shape as `states`) - """ - i = states % n - j = torch.div(states, n, rounding_mode='floor') # states // n, torch.div to avoid pytorch warnings - min_mn = min(m, n) - max_mn = max(m, n) - diag = i + j - anti_diag = m + n - 1 - diag - max_idx = n * m - 1 - cur_diag_idx = i if m > n else m - j - 1 - new_states = ( - diag.lt(min_mn) * ((diag * (diag + 1) >> 1) + i) - + torch.logical_and(diag.ge(min_mn), diag.lt(max_mn)) - * ((min_mn * (min_mn + 1) >> 1) + (diag - min_mn) * min_mn + cur_diag_idx) - + diag.ge(max_mn) * (max_idx - (anti_diag * (anti_diag + 1) >> 1) + m - j) - ) - torch.where(states >= n * m, states, new_states, out=new_states) - return new_states - - def get_grid(self, units_tensor: torch.Tensor, num_frames: int, vocab_size: int) -> "k2.Fsa": - """ - Construct the RNN-T lattice directly (Grid-Transducer). - - Args: - units_tensor: 1d tensor with text units - num_frames: length of the sequence (number of frames) - vocab_size: number of total labels (vocab size including blank) - - Returns: - transducer lattice (k2.Fsa). - Labels: :: (k2.Fsa: labels, aux_labels, unit_positions) - """ - blank_id = self.blank - text_length = units_tensor.shape[0] - device = units_tensor.device - num_grid_states = num_frames * (text_length + 1) - num_forward_arcs = (num_frames - 1) * (text_length + 1) - num_text_arcs = text_length * num_frames - arcs = torch.zeros((num_forward_arcs + num_text_arcs + 2, 4), dtype=torch.int32, device=device) - # blank transitions - # i, i+, 0 , i / , i % - from_states = torch.arange(num_forward_arcs, device=device) - to_states = from_states + (text_length + 1) - arcs[:num_forward_arcs, 0] = from_states - arcs[:num_forward_arcs, 1] = to_states - arcs[:num_forward_arcs, 2] = blank_id - - # text arcs - from_states = ( - torch.arange(num_grid_states, dtype=torch.int32, device=device) - .reshape(num_frames, text_length + 1)[:, :-1] - .flatten() - ) - to_states = from_states + 1 - ilabels = units_tensor.expand(num_frames, -1).flatten() - arcs[num_forward_arcs:-2, 0] = from_states - arcs[num_forward_arcs:-2, 1] = to_states - arcs[num_forward_arcs:-2, 2] = ilabels - - # last 2 states - arcs[-2, :3] = torch.tensor((num_grid_states - 1, num_grid_states, blank_id), dtype=torch.int32, device=device) - arcs[-1, :3] = torch.tensor((num_grid_states, num_grid_states + 1, -1), dtype=torch.int32, device=device) - - # sequence indices, time indices - olabels = torch.div(arcs[:, 0], (text_length + 1), rounding_mode="floor") # arcs[:, 0] // (text_length + 1) - unit_positions = arcs[:, 0] % (text_length + 1) - # last state: final - olabels[-1] = -1 - unit_positions[-1] = -1 - - # relabel - # instead of using top sort (extremely expensive) k2.top_sort(rnnt_graph) - arcs[:-2, 0] = self.relabel_states(arcs[:-2, 0], text_length + 1, num_frames) - arcs[:-3, 1] = self.relabel_states(arcs[:-3, 1], text_length + 1, num_frames) - - # sort by start state - required in k2 - # TODO: maybe it is more optimal to avoid sort, construct arcs in ascending order - _, indices = torch.sort(arcs[:, 0], dim=0) - sorted_arcs = arcs[indices] - olabels = olabels[indices] - unit_positions = unit_positions[indices] - - rnnt_graph = k2.Fsa(sorted_arcs, olabels) - rnnt_graph.unit_positions = unit_positions - return rnnt_graph - - def get_weighted_graphs( - self, - logits: torch.Tensor, - targets: torch.Tensor, - source_lengths: torch.Tensor, - target_lengths: torch.Tensor, - use_graph_weight=False, - ) -> "k2.Fsa": - """ - Get batch of graphs (FsaVec) for RNN-T loss calculation. - - Args: - logits: activations (joint tensor). NB: raw logits, not after log-softmax - targets: target labels - source_lengths: lengths of source sequences - target_lengths: length of target sequences - use_graph_weight: uses weight from graphs (if `get_graphs_batched` returns graphs with weights) - - Returns: - FsaVec containing RNN-T graphs for all utterances. - """ - vocab_size = logits.shape[-1] - target_fsas_vec = self.get_graphs_batched(source_lengths, targets, target_lengths, vocab_size) - - with torch.no_grad(): - # last transitions in the graph are labeled with -1 label - last_transition_mask = target_fsas_vec.labels == -1 - batch_indices = self.get_batch_indices(target_fsas_vec=target_fsas_vec) - time_indices = target_fsas_vec.aux_labels.clone().to(torch.int64) - unit_indices = target_fsas_vec.unit_positions.clone().to(torch.int64) - text_units = target_fsas_vec.labels.clone().to(torch.int64) - # fill in the indices outside the logits with 0, replace later - text_units.masked_fill_(last_transition_mask, 0) - - cast_context = force_float32_context() if self.cast_to_float32 else nullcontext() - with cast_context: - # NB: do not assign scores -> modify, k2 will not update all scores correctly (modify -> assign) - if self.use_triton and logits.device.type == "cuda": - unit_scores, blank_scores = rnnt_logprobs_triton( - logits=logits, - targets=targets, - blank_id=self.blank, - source_lengths=source_lengths, - target_lengths=target_lengths, - ) - text_units_blank_mask = text_units == self.blank - scores = torch.where( - text_units_blank_mask, - blank_scores[batch_indices, time_indices, unit_indices], - unit_scores[batch_indices, time_indices, unit_indices], - ).to(torch.float32) - scores[last_transition_mask] = 0.0 # fix weights for the arcs to the last state - else: - log_probs = F.log_softmax(logits, dim=-1) - scores = log_probs[batch_indices, time_indices, unit_indices, text_units].to(torch.float32) - scores[last_transition_mask] = 0.0 - - if use_graph_weight: - target_fsas_vec.scores = target_fsas_vec.scores + scores - else: - target_fsas_vec.scores = scores - return target_fsas_vec - - def forward( - self, - acts: torch.Tensor, - labels: torch.Tensor, - act_lens: torch.Tensor, - label_lens: torch.Tensor, - ) -> torch.Tensor | tuple[torch.Tensor, "k2.Fsa"]: - """ - Compute forward method for RNN-T. - - Args: - acts: activations (joint tensor). NB: raw logits, not after log-softmax - labels: target labels - act_lens: lengths of activations - label_lens: length of labels sequences - - Returns: - batch of RNN-T scores (loss) - """ - # argument names are consistent with NeMo, see RNNTLoss.forward: - # self._loss(acts=log_probs, labels=targets, act_lens=input_lengths, label_lens=target_lengths) - target_fsas_vec = self.get_weighted_graphs( - logits=acts, targets=labels, source_lengths=act_lens, target_lengths=label_lens, use_graph_weight=False - ) - - scores = -1 * target_fsas_vec.get_tot_scores(use_double_scores=self.double_scores, log_semiring=True) - if self.return_graph: - return scores, target_fsas_vec - return scores diff --git a/nemo/collections/asr/parts/k2/rnnt_logprobs.py b/nemo/collections/asr/parts/k2/rnnt_logprobs.py deleted file mode 100644 index 599bd3555c61000c6fc7d10ef52a3e74f20f072a..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/k2/rnnt_logprobs.py +++ /dev/null @@ -1,44 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import torch -import torch.nn.functional as F - - -def rnnt_logprobs_torch( - logits: torch.Tensor, targets: torch.Tensor, blank_id: int -) -> tuple[torch.Tensor, torch.Tensor]: - """ - Given logits, calculate log probabilities for blank and target labels needed for transducer loss calculation. - Naive implementation in PyTorch, for testing and prototyping purposes. - - Args: - logits: Joint tensor of size [B, T, U+1, D] - targets: Targets of size [B, U] - blank_id: id of the blank output - - Returns: - Tuple of tensors with log probabilities for targets and blank labels, both of size [B, T, U+1]. - For the last non-existent target (U+1) output is zero. - """ - device = logits.device - batch_size = logits.shape[0] - log_probs = F.log_softmax(logits, dim=-1) - blank_scores = log_probs[..., blank_id] - targets = torch.cat((targets, torch.zeros([batch_size], dtype=targets.dtype, device=device).unsqueeze(1)), dim=-1) - target_scores = torch.gather( - log_probs, dim=-1, index=targets.unsqueeze(1).expand(log_probs.shape[:-1]).unsqueeze(-1) - ).squeeze(-1) - target_scores[:, :, -1] = 0.0 - return target_scores, blank_scores diff --git a/nemo/collections/asr/parts/k2/rnnt_logprobs_triton.py b/nemo/collections/asr/parts/k2/rnnt_logprobs_triton.py deleted file mode 100644 index a52bea49509351111b75668bdcb29470bb9e7b02..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/k2/rnnt_logprobs_triton.py +++ /dev/null @@ -1,250 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import torch -import triton -import triton.language as tl - - -@triton.jit -def _rnnt_logprobs_fwd_kernel( - logits_ptr, - targets_ptr, - source_lengths_ptr, - target_lengths_ptr, - max_source_len: int, - max_target_len_plus_1: int, - num_labels: int, # vocab size (with blank) - blank_id: int, - target_scores_ptr, - blank_scores_ptr, - BLOCK_SIZE: tl.constexpr, -): - """ - Forward kernel for RNN-T log probs. Stores result in `target_scores_ptr` and `blank_scores_ptr`. - Calculations are performed in float32 (but original tensors can use any precision). - """ - batch_i = tl.program_id(axis=0).to(tl.int64) - source_i = tl.program_id(axis=1).to(tl.int64) - target_i = tl.program_id(axis=2).to(tl.int64) - - # load lengths for source/target - source_len = tl.load(source_lengths_ptr + batch_i) - target_len = tl.load(target_lengths_ptr + batch_i) - - if source_i >= source_len or target_i > target_len: - # no calculations required - return - - # calculate offset in [B, T, U+1, V] tensor for the current vector with target logits - flat_index = ((batch_i * max_source_len + source_i) * max_target_len_plus_1 + target_i) * num_labels - logits_ptr += flat_index - col_offsets = tl.arange(0, BLOCK_SIZE) - mask = col_offsets < num_labels - logits = tl.load(logits_ptr + col_offsets, mask=mask, other=-float("inf")).to(tl.float32) - # stable log softmax calculation - logits_max = tl.max(logits, axis=0) - logits_minus_max = logits - logits_max - denominator = tl.log(tl.sum(tl.exp(logits_minus_max), axis=0)) - blank_logit = tl.load(logits_ptr + blank_id).to(tl.float32) - flat_index_output = (batch_i * max_source_len + source_i) * max_target_len_plus_1 + target_i - tl.store(blank_scores_ptr + flat_index_output, blank_logit - logits_max - denominator) - - # calculate log prob for target if needed - if target_i < target_len: - target_id = tl.load(targets_ptr + batch_i * (max_target_len_plus_1 - 1) + target_i) - target_logit = tl.load(logits_ptr + target_id).to(tl.float32) - tl.store(target_scores_ptr + flat_index_output, target_logit - logits_max - denominator) - - -@triton.jit -def _rnnt_logprobs_bwd_kernel( - logits_ptr, - grad_logits_ptr, - targets_ptr, - source_lengths_ptr, - target_lengths_ptr, - max_source_len: int, - max_target_len_plus_1: int, - num_labels: int, - blank_id: int, - grad_target_scores_ptr, - grad_blank_scores_ptr, - BLOCK_SIZE: tl.constexpr, -): - """ - Backward kernel for RNN-T log probs. Stores result in `grad_target_scores_ptr` and `grad_blank_scores_ptr`. - We recalculate part of the forward here to avoid using extra memory in forward. - Calculations are performed in float32 (but original tensors can use any precision). - """ - batch_i = tl.program_id(axis=0).to(tl.int64) - source_i = tl.program_id(axis=1).to(tl.int64) - target_i = tl.program_id(axis=2).to(tl.int64) - - # load lengths for source/target - source_len = tl.load(source_lengths_ptr + batch_i) - target_len = tl.load(target_lengths_ptr + batch_i) - if source_i >= source_len or target_i > target_len: - # no calculations required - return - - # calculate offset in [B, T, U+1, V] tensor for the current vector with target logits/grad_logits - flat_index = ((batch_i * max_source_len + source_i) * max_target_len_plus_1 + target_i) * num_labels - logits_ptr += flat_index - grad_logits_ptr += flat_index - - col_offsets = tl.arange(0, BLOCK_SIZE) - mask = col_offsets < num_labels - logits = tl.load(logits_ptr + col_offsets, mask=mask, other=-float("inf")).to(tl.float32) - # stable log softmax calculation - logits_max = tl.max(logits, axis=0) - logits_minus_max = logits - logits_max - denominator = tl.log(tl.sum(tl.exp(logits_minus_max), axis=0)) - log_softmax = logits_minus_max - denominator - # softmax for gradient - softmax = tl.exp(log_softmax) - - flat_index_grad = (batch_i * max_source_len + source_i) * max_target_len_plus_1 + target_i - blank_grad = tl.load(grad_blank_scores_ptr + flat_index_grad).to(tl.float32) - target_i_valid = target_i < target_len - target_grad = tl.load(grad_target_scores_ptr + flat_index_grad, mask=target_i_valid, other=0.0).to(tl.float32) - target_id = tl.load(targets_ptr + batch_i * (max_target_len_plus_1 - 1) + target_i, mask=target_i_valid, other=-1) - - grad_not_in_targets = (-softmax) * (blank_grad + target_grad) - grad = tl.where(col_offsets == blank_id, blank_grad + grad_not_in_targets, grad_not_in_targets) - grad = tl.where(col_offsets == target_id, target_grad + grad_not_in_targets, grad) - tl.store(grad_logits_ptr + col_offsets, grad, mask=mask) - - -class RnntLogProbs(torch.autograd.Function): - """ - Function to calculate log probabilities for target and blank labels for RNN-T, supporting torch.autograd. - """ - - @staticmethod - def forward( - ctx, - logits: torch.Tensor, - targets: torch.Tensor, - blank_id: int, - source_lengths: torch.Tensor | None, - target_lengths: torch.Tensor | None, - ): - """ - - Args: - ctx: ctx object for storing the context - logits: Joint tensor of size [B, T, U+1, D] - targets: Targets of size [B, U] - blank_id: id of the blank output - source_lengths: optional tensor with lengths for source utterances - target_lengths: optional tensor with lengths for targets - - Returns: - - """ - assert logits.is_contiguous() # logits are huge, so here we just check if logits are contiguous - targets = targets.contiguous() - device = logits.device - float_dtype = torch.float32 - - target_scores = torch.zeros(logits.shape[:-1], dtype=float_dtype, device=device) - blank_scores = torch.zeros_like(target_scores) - if source_lengths is None: - source_lengths = torch.full([logits.shape[0]], fill_value=logits.shape[1], dtype=torch.int, device=device) - else: - source_lengths = source_lengths.contiguous() - if target_lengths is None: - target_lengths = torch.full( - [logits.shape[0]], fill_value=logits.shape[2] - 1, dtype=torch.int, device=device - ) - else: - target_lengths = target_lengths.contiguous() - - # run Triton kernel - _rnnt_logprobs_fwd_kernel[(logits.shape[0], logits.shape[1], logits.shape[2])]( - logits_ptr=logits, - targets_ptr=targets, - source_lengths_ptr=source_lengths, - target_lengths_ptr=target_lengths, - max_source_len=logits.shape[1], - max_target_len_plus_1=logits.shape[2], - num_labels=logits.shape[3], - blank_id=blank_id, - target_scores_ptr=target_scores, - blank_scores_ptr=blank_scores, - BLOCK_SIZE=triton.next_power_of_2(logits.shape[-1]), - ) - - # saving for backward - ctx.save_for_backward(logits, targets, source_lengths, target_lengths) - ctx.blank_id = blank_id - return target_scores, blank_scores - - @staticmethod - def backward(ctx, grad_target_scores, grad_blank_scores): - """ - Backward calculation for RNN-T log-probs. - - Args: - ctx: ctx object for storing the context - grad_target_scores: upstream gradient for targets - grad_blank_scores: upstream gradient for blank scores - - Returns: - gradient for logits, None for all other arguments for `forward` - """ - (logits, targets, source_lengths, target_lengths) = ctx.saved_tensors - blank_id = ctx.blank_id - grad_logits = torch.zeros_like(logits) - _rnnt_logprobs_bwd_kernel[(logits.shape[0], logits.shape[1], logits.shape[2])]( - logits_ptr=logits, - grad_logits_ptr=grad_logits, - source_lengths_ptr=source_lengths, - target_lengths_ptr=target_lengths, - targets_ptr=targets, - max_source_len=logits.shape[1], - max_target_len_plus_1=logits.shape[2], - num_labels=logits.shape[3], - blank_id=blank_id, - grad_target_scores_ptr=grad_target_scores, - grad_blank_scores_ptr=grad_blank_scores, - BLOCK_SIZE=triton.next_power_of_2(logits.shape[-1]), - ) - return grad_logits, None, None, None, None - - -def rnnt_logprobs_triton( - logits: torch.Tensor, - targets: torch.Tensor, - blank_id: int, - source_lengths: torch.Tensor | None = None, - target_lengths: torch.Tensor | None = None, -) -> tuple[torch.Tensor, torch.Tensor]: - """ - Given logits, calculate log probabilities for blank and target labels needed for transducer loss calculation. - Optimized implementation in Triton. - - Args: - logits: Joint tensor of size [B, T, U+1, D] - targets: Targets of size [B, U] - blank_id: id of the blank output - source_lengths: optional tensor with lengths for source utterances - target_lengths: optional tensor with lengths for targets - - Returns: - Tuple of tensors with log probabilities for targets and blank labels, both of size [B, T, U+1]. - For the non-existent targets (U+1 or beyond target_lengths) output is zero. - """ - return RnntLogProbs.apply(logits, targets, blank_id, source_lengths, target_lengths) diff --git a/nemo/collections/asr/parts/k2/w_transducer.py b/nemo/collections/asr/parts/k2/w_transducer.py deleted file mode 100644 index b38a6c560fcdbec7000c5f628a0f839c9643b38e..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/k2/w_transducer.py +++ /dev/null @@ -1,340 +0,0 @@ -# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from contextlib import nullcontext -from typing import Union - -import torch -import torch.nn.functional as F - -from nemo.collections.asr.parts.k2.graph_transducer import GraphRnntLoss, force_float32_context -from nemo.core.utils.k2_guard import k2 -from nemo.utils.enum import PrettyStrEnum - - -class GraphWTransducerLoss(GraphRnntLoss): - """ - W-Transducer loss: RNN-T loss modification for training RNN-T model for the case - when some text at the beginning/end of the utterance is missing. - The resulting model behaves like the RNN-T model (no modification for decoding is required). - For details see "Powerful and Extensible WFST Framework for RNN-Transducer Losses" paper - https://ieeexplore.ieee.org/document/10096679 - """ - - class LastBlankMode(PrettyStrEnum): - ALLOW_IGNORE = "allow_ignore" - FORCE_FINAL = "force_final" - - def __init__( - self, - blank: int, - eps_weight: float = 0.0, - last_blank_mode: Union[LastBlankMode, str] = LastBlankMode.FORCE_FINAL, - use_grid_implementation=True, - connect_composed=False, - double_scores=False, - cast_to_float32=False, - ): - """ - Init method - - Args: - blank: blank label index - eps_weight: weight of epsilon transitions, 0 means no penalty (default) - last_blank_mode: allow to skip last blank in the prediction (default) or force it - use_grid_implementation: Whether to use the grid implementation (Grid-Transducer). - connect_composed: Connect graph after composing unit and temporal schemas - (only for Compose-Transducer). `connect` operation is slow, it is useful for visualization, - but not necessary for loss computation. - double_scores: Use calculation of loss in double precision (float64) in the lattice. - Does not significantly affect memory usage since the lattice is ~V/2 times smaller than the joint tensor. - cast_to_float32: Force cast joint tensor to float32 before log-softmax calculation. - """ - super().__init__( - blank=blank, - use_grid_implementation=use_grid_implementation, - connect_composed=connect_composed, - double_scores=double_scores, - cast_to_float32=cast_to_float32, - ) - self.eps_weight = eps_weight - self.last_blank_mode = self.LastBlankMode(last_blank_mode) - - def get_unit_schema(self, units_tensor: torch.Tensor, vocab_size: int) -> "k2.Fsa": - """ - Get unit schema (target text) graph for W-Transducer loss (Compose-Transducer). - Forward arcs represent text labels. - - Example graph: text [1, 2], blank=0. Eps ids: 3, 4. - - graph:: - - 3:3:0 0:0:1 0:0:2 - +-------+ +-------+ +-------+ - v | v | v | - +-----------+ 1:1:0 +-----------+ 2:2:1 +-----------+ -1:-1:-1 #===# - | 0 | -------> | 1 | -------> | 2 | ---------> H 3 H - +-----------+ +-----------+ +-----------+ #===# - ^ 0:0:0 | ^ 4:4:2 | - +-------+ +-------+ - - Args: - units_tensor: 1d tensor with text units - vocab_size: number of total labels (vocab size including blank) - - Returns: - unit schema graph (k2.Fsa). - Labels: :: (k2.Fsa: labels, aux_labels, unit_positions) - """ - - blank_id = self.blank - start_eps_id = vocab_size - end_eps_id = vocab_size + 1 - device = units_tensor.device - text_len = units_tensor.shape[0] - - # arcs: scr, dest, label, score - arcs = torch.zeros(((text_len + 1) * 2 + 2, 4), dtype=torch.int32, device=device) - text_indices = torch.arange(0, text_len + 1, dtype=torch.int32, device=device) - # eps - arcs[0, 2] = start_eps_id - # blank labels - arcs[1:-1:2, 0] = text_indices # from state - arcs[1:-1:2, 1] = text_indices # to state - arcs[1:-1:2, 2] = blank_id - - # text labels - arcs[2:-1:2, 0] = text_indices # from state - arcs[2:-1:2, 1] = text_indices + 1 # to state - arcs[2:-2:2, 2] = units_tensor # labels: text - - arcs[-1] = arcs[-2] - arcs[-2, 1] = text_len - arcs[-2, 2] = end_eps_id - arcs[-1, 2] = -1 # last transition to final state, ilabel=-1 (special for k2) - olabels = arcs[:, 2].detach().clone() # same as ilabels - - fsa_text = k2.Fsa(arcs, olabels) - fsa_text.unit_positions = torch.zeros_like(olabels) - fsa_text.unit_positions[1:-1] = text_indices.expand(2, -1).transpose(0, 1).flatten() - fsa_text.unit_positions[-1] = -1 - return fsa_text - - def get_temporal_schema(self, num_frames: int, vocab_size: int, device: torch.device) -> "k2.Fsa": - """ - Get temporal schema graph for W-Transducer loss (Compose-Transducer). - - Example graph: blank=0, num_frames=3, vocab_size=3, last_blank_mode="force_final". - Labels: :. is a unit from vocab + special eps ids `vocab_size`, `vocab_size+1`. - - graph for force_final:: - - 4:0 - +--------------------------------------------+ - | 4:1 | - | +--------------------+ | - 1:0 | 1:1 | 1:2 | | - +-----+ | +-----+ | +-----+ | | - v | | v | | v | v v - +--------------+ 0:0 +------------+ 0:1 +------------+ 0:2 +---+ -1:-1 #===# - | 0 | ----> | 1 | -----> | 2 | -----> | 3 | -------> H 4 H - +--------------+ +------------+ +------------+ +---+ #===# - ^ 2:0 | | | ^ 2:1 | ^ ^ 2:2 | ^ - +-----+ | | +-----+ | +-----+ | - | | 3:0 | | - | +------------------+ 3:0 | - +-------------------------------------------+ - - - Args: - num_frames: length of the sequence (in frames) - vocab_size: number of labels (including blank) - device: device for tensor to construct - - Returns: - temporal schema graph (k2.Fsa). - Labels: :. is a unit from vocab + special units (e.g., additional eps). - """ - blank_id = self.blank - start_eps_id = vocab_size - end_eps_id = vocab_size + 1 - num_eps = 2 - - num_sequence_arcs = num_frames * vocab_size + (num_frames - 1) * num_eps + 1 - fsa_temporal_arcs = torch.zeros((num_sequence_arcs, 4), dtype=torch.int32, device=device) - sequence_states = torch.arange(0, num_frames, dtype=torch.int32, device=device) - sequence_states_next = sequence_states + 1 - # for every state - vocab_size+1 arcs, [0, 1, ..., vocab_size-1, eps, 0, 1, ..., vocab_size-1, eps, ...] - start_states = sequence_states.expand(vocab_size + num_eps, num_frames).transpose(0, 1).flatten() - - # self-loops - all, make forward arcs later - fsa_temporal_arcs[:num_sequence_arcs, 0] = start_states[:-1] # from - fsa_temporal_arcs[:num_sequence_arcs, 1] = start_states[:-1] # to - fsa_temporal_arcs[:num_sequence_arcs, 2] = ( - torch.arange(0, vocab_size + num_eps, dtype=torch.int32, device=device) - .expand(num_frames, vocab_size + num_eps) - .flatten()[:-1] - ) - # forward arcs - fsa_temporal_arcs[blank_id : num_sequence_arcs : vocab_size + num_eps, 1] = sequence_states_next # blanks - # eps arcs - fsa_temporal_arcs[start_eps_id : num_sequence_arcs : vocab_size + num_eps, 0] = 0 - fsa_temporal_arcs[start_eps_id : num_sequence_arcs : vocab_size + num_eps, 1] = sequence_states + 1 - fsa_temporal_arcs[end_eps_id : num_sequence_arcs : vocab_size + num_eps, 0] = sequence_states[:-1] - fsa_temporal_arcs[end_eps_id : num_sequence_arcs : vocab_size + num_eps, 1] = ( - num_frames - 1 if self.last_blank_mode == self.LastBlankMode.FORCE_FINAL else num_frames - ) - - # transition to last final state - fsa_temporal_arcs[-1, :3] = torch.tensor((num_frames, num_frames + 1, -1), dtype=torch.int32, device=device) - - # need to sort arcs - _, indices = torch.sort(fsa_temporal_arcs[:, 0], dim=0) - fsa_temporal_arcs = fsa_temporal_arcs[indices] - - # output symbols: position in the sequence, same as start states for arcs - olabels = fsa_temporal_arcs[:, 0].detach().clone() - olabels[-1] = -1 # transition to the last final state - - fsa_temporal = k2.Fsa(fsa_temporal_arcs, olabels) - fsa_temporal = k2.arc_sort(fsa_temporal) # need for compose - return fsa_temporal - - def get_grid(self, units_tensor: torch.Tensor, num_frames: int, vocab_size: int) -> "k2.Fsa": - """ - Construct W-Transducer lattice directly (Grid-Transducer). - - Args: - units_tensor: 1d tensor with text units - num_frames: length of the sequence (number of frames) - vocab_size: number of total labels (vocab size including blank) - - Returns: - transducer lattice (k2.Fsa). - Labels: :: (k2.Fsa: labels, aux_labels, unit_positions) - """ - blank_id = self.blank - eps_id = vocab_size # beyond vocabulary - text_length = units_tensor.shape[0] - device = units_tensor.device - num_grid_states = num_frames * (text_length + 1) - num_forward_arcs_base = (num_frames - 1) * (text_length + 1) - num_forward_arcs_additional = (num_frames - 1) * 2 - num_forward_arcs = num_forward_arcs_base + num_forward_arcs_additional - num_text_arcs = text_length * num_frames - arcs = torch.zeros((num_forward_arcs + num_text_arcs + 2, 4), dtype=torch.int32, device=device) - # blank transitions - # i, i+, 0 , i / , i % - from_states = torch.arange(num_forward_arcs_base, device=device) - to_states = from_states + (text_length + 1) - arcs[:num_forward_arcs_base, 0] = from_states - arcs[:num_forward_arcs_base, 1] = to_states - arcs[:num_forward_arcs_base, 2] = blank_id - - from_states = torch.cat( - [ - torch.arange(num_frames - 1, device=device) * (text_length + 1), - text_length + torch.arange(num_frames - 1, device=device) * (text_length + 1), - ] - ) - to_states = from_states + (text_length + 1) - arcs[num_forward_arcs_base : num_forward_arcs_base + (num_frames - 1) * 2, 0] = from_states - arcs[num_forward_arcs_base : num_forward_arcs_base + (num_frames - 1) * 2, 1] = to_states - arcs[num_forward_arcs_base : num_forward_arcs_base + (num_frames - 1), 2] = eps_id - arcs[num_forward_arcs_base + (num_frames - 1) : num_forward_arcs_base + (num_frames - 1) * 2, 2] = eps_id + 1 - - arcs[num_forward_arcs_base : num_forward_arcs_base + (num_frames - 1), 0] = 0 - arcs[num_forward_arcs_base + (num_frames - 1) : num_forward_arcs_base + (num_frames - 1) * 2, 1] = ( - num_grid_states - 1 - ) # if other mode - fix later - # last eps ark - after relabel - - # text arcs - from_states = ( - torch.arange(num_grid_states, dtype=torch.int32, device=device) - .reshape(num_frames, text_length + 1)[:, :-1] - .flatten() - ) - to_states = from_states + 1 - ilabels = units_tensor.expand(num_frames, -1).flatten() - arcs[num_forward_arcs:-2, 0] = from_states - arcs[num_forward_arcs:-2, 1] = to_states - arcs[num_forward_arcs:-2, 2] = ilabels - - # last 2 states - arcs[-2, :3] = torch.tensor((num_grid_states - 1, num_grid_states, blank_id), dtype=torch.int32, device=device) - arcs[-1, :3] = torch.tensor((num_grid_states, num_grid_states + 1, -1), dtype=torch.int32, device=device) - - # sequence indices, time indices - olabels = torch.div(arcs[:, 0], (text_length + 1), rounding_mode="floor") # arcs[:, 0] // (text_length + 1) - unit_positions = arcs[:, 0] % (text_length + 1) - # last state: final - olabels[-1] = -1 - unit_positions[-1] = -1 - - # relabel - # instead of using top sort (extremely expensive) k2.top_sort(rnnt_graph) - arcs[:-2, 0] = self.relabel_states(arcs[:-2, 0], text_length + 1, num_frames) - arcs[:-3, 1] = self.relabel_states(arcs[:-3, 1], text_length + 1, num_frames) - - if self.last_blank_mode == self.LastBlankMode.ALLOW_IGNORE: - arcs[ - num_forward_arcs_base + (num_frames - 1) : num_forward_arcs_base + (num_frames - 1) * 2, 1 - ] = num_grid_states - - # sort by start state - required in k2 - # TODO: maybe it is more optimal to avoid sort, construct arcs in ascending order - _, indices = torch.sort(arcs[:, 0], dim=0) - arcs = arcs[indices] - olabels = olabels[indices] - unit_positions = unit_positions[indices] - - rnnt_graph = k2.Fsa(arcs, olabels) - rnnt_graph.unit_positions = unit_positions - return rnnt_graph - - def forward( - self, acts: torch.Tensor, labels: torch.Tensor, act_lens: torch.Tensor, label_lens: torch.Tensor, - ): - """ - Forward method is similar to RNN-T Graph-Transducer forward method, - but we need to assign eps weight to eps-transitions. - """ - # argument names are consistent with NeMo, see RNNTLoss.forward: - # self._loss(acts=log_probs, labels=targets, act_lens=input_lengths, label_lens=target_lengths) - logits, targets, logits_lengths, target_lengths = acts, labels, act_lens, label_lens - - # logits: B x Time x Text+1 x C - vocab_size = logits.shape[-1] - target_fsas_vec = self.get_graphs_batched(logits_lengths, targets, target_lengths, vocab_size) - - cast_context = force_float32_context() if self.cast_to_float32 else nullcontext() - with cast_context: - log_probs = F.log_softmax(logits, dim=-1) - with torch.no_grad(): - indices = self.get_logits_indices(target_fsas_vec, logits.shape) - # transition to the last state + eps-transitions - # use 0 index (for valid index_select) and manually assign score after index_select for this case - indices[target_fsas_vec.labels == -1] = 0 - indices[target_fsas_vec.labels >= vocab_size] = 0 # eps - - # NB: do not assign scores -> modify, k2 will not update all scores correctly (modify -> assign) - scores = log_probs.flatten().index_select(-1, indices) - # fix weights for the arcs to the last state + eps-transitions - scores[target_fsas_vec.labels == -1] = 0 - scores[target_fsas_vec.labels >= vocab_size] = self.eps_weight # eps - - target_fsas_vec.scores = scores - scores = -1 * target_fsas_vec.get_tot_scores(use_double_scores=self.double_scores, log_semiring=True) - return scores diff --git a/nemo/collections/asr/parts/mixins/__init__.py b/nemo/collections/asr/parts/mixins/__init__.py deleted file mode 100644 index c8bfd1503454ad82c98048ca53cec0503a811bef..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/mixins/__init__.py +++ /dev/null @@ -1,42 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.asr.parts.mixins.asr_adapter_mixins import ASRAdapterModelMixin -from nemo.collections.asr.parts.mixins.interctc_mixin import InterCTCMixin -from nemo.collections.asr.parts.mixins.mixins import ( - ASRAdapterModelMixin, - ASRBPEMixin, - ASRModuleMixin, - DiarizationMixin, -) -from nemo.collections.asr.parts.mixins.multitalker_asr_mixins import SpeakerKernelMixin -from nemo.collections.asr.parts.mixins.transcription import ( - ASRTranscriptionMixin, - TranscribeConfig, - TranscriptionMixin, - TranscriptionReturnType, -) - -__all__ = [ - 'ASRAdapterModelMixin', - 'ASRBPEMixin', - 'ASRModuleMixin', - 'ASRTranscriptionMixin', - 'DiarizationMixin', - 'InterCTCMixin', - 'SpeakerKernelMixin', - 'TranscribeConfig', - 'TranscriptionMixin', - 'TranscriptionReturnType', -] diff --git a/nemo/collections/asr/parts/mixins/asr_adapter_mixins.py b/nemo/collections/asr/parts/mixins/asr_adapter_mixins.py deleted file mode 100644 index bd0607f2c4f3547d441a2a47f42c370bd7a20c27..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/mixins/asr_adapter_mixins.py +++ /dev/null @@ -1,276 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import List, Optional, Tuple - -from omegaconf import DictConfig, open_dict - -from nemo.core.classes.mixins.adapter_mixins import AdapterModelPTMixin, AdapterModuleMixin -from nemo.utils import logging, logging_mode - - -class ASRAdapterModelMixin(AdapterModelPTMixin): - """ASR Adapter Mixin that can augment any Encoder module with Adapter module support. - - This mixin class should be used only with a top level ModelPT subclass, that includes an `encoder` submodule. - This mixin class adds several utility methods which are propagated to the `encoder`. - - An Adapter module is any Pytorch nn.Module that possess a few properties : - - - It's input and output dimension are the same, while the hidden dimension need not be the same. - - The final layer of the Adapter module is zero-initialized, so that the residual connection to the adapter - yields the original output. - - This mixin adds the following instance variables to the class this inherits it: - - - `adapter_layer`: A torch.nn.ModuleDict(), whose keys are the names of the adapter (globally unique), - and values are the Adapter nn.Module(). - - `adapter_cfg`: A OmegaConf DictConfig object that holds the config of the adapters that are initialized. - - `adapter_global_cfg_key`: A str representing a key in the model config that can be provided by the user. - The value resolves to `global_cfg`, and can be overridden via `model.cfg.adapters.global_cfg.*`. - - **Note**: This module **is** responsible for maintaining its config. At the ModelPT level, it will access and - write Adapter config information to `self.cfg.adapters`. - """ - - def setup_adapters(self): - """ - Utility method that is called in the ASR ModelPT-implementation constructor, so as to restore any - adapters that were previously added. - - This method should be called just once at constructor time. - """ - supports_adapters = False - - # At least the encoder must extend AdapterModuleMixin - valid_adapter_names = [x for x in self.adapter_module_names if x != ''] - for module_name in valid_adapter_names: - if hasattr(self, module_name) and isinstance(getattr(self, module_name), AdapterModuleMixin): - supports_adapters |= True - - # If adapters are supported, setup the adapter config + any modules (pre-existing adapter modules) - if supports_adapters: - super().setup_adapters() - - def add_adapter(self, name: str, cfg: DictConfig): - """ - Add an Adapter module to this model. - - Args: - name: A globally unique name for the adapter. Will be used to access, enable and disable adapters. - cfg: A DictConfig that contains at the bare minimum `__target__` to instantiate a new Adapter module. - """ - # setup the config for adapters - super().add_adapter(name=name, cfg=cfg) - - # Resolve module name and adapter name - module_name, _ = self.resolve_adapter_module_name_(name) - - # Use + as a splitter, in order to share one name across multiple modules - if '+' in module_name: - module_names = module_name.split('+') - else: - module_names = [module_name] - - valid_module_names = [x for x in self.adapter_module_names if x != ''] - default_module_name = self.default_adapter_module_name - - # Check if default module name is None or not - if default_module_name is None: - raise ValueError( - f"Default module name is None. Class {self.__class__.__name__} must implement " - f"`default_adapter_module_name`" - ) - - # Update the model.cfg with information about the new adapter from cfg - with open_dict(self.cfg): - for module_name in module_names: - # Check if encoder adapters should be added - if module_name == '': - if hasattr(self, default_module_name): - # Dispatch the call to the default model. - getattr(self, default_module_name).add_adapter(name=name, cfg=cfg) - - elif module_name in valid_module_names: - # Check if module exists - if hasattr(self, module_name): - # Dispatch the call to the module. - getattr(self, module_name).add_adapter(name=name, cfg=cfg) - - def is_adapter_available(self) -> bool: - """ - Checks if any Adapter module has been instantiated. - - Returns: - bool, determining if any Adapter module has been instantiated. Returns true even if the adapters are - enabled or disabled, false only if no adapters exist. - """ - config_contains_adapter = super().is_adapter_available() - - valid_module_names = [x for x in self.adapter_module_names if x != ''] - - # Forward the method call to the individual modules - for module_name in valid_module_names: - if hasattr(self, module_name) and isinstance(getattr(self, module_name), AdapterModuleMixin): - config_contains_adapter |= getattr(self, module_name).is_adapter_available() - - return config_contains_adapter - - def set_enabled_adapters(self, name: Optional[str] = None, enabled: bool = True): - """ - Updated the internal adapter config, determining if an adapter (or all adapters) are either - enabled or disabled. - - A common user pattern would be to disable all adapters (either after adding them, or restoring a model - with pre-existing adapters) and then simply enable one of the adapters. - - .. code:: - - model.set_enabled_adapters(enabled=False) - model.set_enabled_adapters(name=, enabled=True) - - Args: - name: Optional str. If a str name is given, the config will be updated to the value of `enabled`. - If no name is given, then all adapters will be enabled/disabled. - enabled: Bool, determines if the adapter(s) will be enabled/disabled. - """ - super().set_enabled_adapters(name=name, enabled=enabled) - - # Resolve the module name and adapter name - if name is not None: - module_name, _ = self.resolve_adapter_module_name_(name) - else: - module_name = None - - # Use + as a splitter, in order to share one name across multiple modules - if module_name is not None and '+' in module_name: - module_names = module_name.split('+') - else: - module_names = [module_name] - - valid_module_names = [x for x in self.adapter_module_names if x != ''] - default_module_name = self.default_adapter_module_name - - # Check if default module name is None or not - if default_module_name is None: - raise ValueError( - f"Default module name is None. Class {self.__class__.__name__} must implement " - f"`default_adapter_module_name`" - ) - - # Forward the method call to the individual modules if they exist - for module_name in module_names: - # Check if encoder adapters should be used - - if module_name == '': - if hasattr(self, default_module_name): - # Dispatch the call to the default model. - getattr(self, default_module_name).set_enabled_adapters(name=name, enabled=enabled) - - elif module_name in valid_module_names: - if hasattr(self, module_name): - # Dispatch the call to the module. - getattr(self, module_name).set_enabled_adapters(name=name, enabled=enabled) - - def get_enabled_adapters(self) -> List[str]: - """ - Returns a list of all enabled adapters. - - Returns: - A list of str names of each enabled adapter(s). - """ - enabled_adapters = super().get_enabled_adapters() - - valid_module_names = [x for x in self.adapter_module_names if x != ''] - - # Check if encoder adapters should be used or are enabled - for module_name in valid_module_names: - if hasattr(self, module_name) and isinstance(getattr(self, module_name), AdapterModuleMixin): - enabled_adapters.extend(getattr(self, module_name).get_enabled_adapters()) - - enabled_adapters = list(sorted(list(set(enabled_adapters)))) - - return enabled_adapters - - def check_valid_model_with_adapter_support_(self): - """ - Utility method to test if the subclass of this mixin is an appropriate subclass of ModelPT itself. - """ - # Obtain the global adapter config if possible, otherwise use sensible defaults. - global_cfg = self._get_global_cfg() - - valid_module_names = [x for x in self.adapter_module_names if x != ''] - - for module_name in valid_module_names: - check_adapter_support = global_cfg.get(f'check_{module_name}_adapter', True) - - if check_adapter_support: - # Test whether the module supports adapters - if hasattr(self, module_name) and not isinstance(getattr(self, module_name), AdapterModuleMixin): - logging.warning( - f'Module `{module_name}` exists, but {getattr(self, module_name).__class__.__name__} ' - f'does not implement `AdapterModuleMixin`', - mode=logging_mode.ONCE, - ) - - def resolve_adapter_module_name_(self, name: str) -> Tuple[str, str]: - """ - Utility method to resolve a given global/module adapter name to its components. - Always returns a tuple representing (module_name, adapter_name). ":" is used as the - delimiter for denoting the module name vs the adapter name. - - Will attempt to also resolve a given adapter_name alone back to (module_name, adapter_name) - if the metadata config exists for access. - - Args: - name: A global adapter, or a module adapter name (with structure module_name:adapter_name). - - Returns: - A tuple representing (module_name, adapter_name). If a global adapter is provided, - module_name is set to ''. - """ - module_name, adapter_name = super().resolve_adapter_module_name_(name) - - # Use + as a splitter, in order to share one name across multiple modules - if '+' in module_name: - module_names = module_name.split('+') - else: - module_names = [module_name] - - # resolve name and module only for valid modules - valid_module_names = self.adapter_module_names - - for mod_name in module_names: - if mod_name not in valid_module_names: - raise ValueError(f"Provided module name `{mod_name}` is not in valid list : {valid_module_names}") - - return (module_name, adapter_name) - - def _get_global_cfg(self): - """ - Utility method, to either extract or construct the global config inside adapters config. - """ - global_config = DictConfig({}) - if 'adapters' in self.cfg and self.adapter_global_cfg_key in self.cfg.adapters: - global_config = self.adapter_cfg[self.adapter_global_cfg_key] - return global_config - - @property - def adapter_module_names(self) -> List[str]: - valid_module_names = ['', 'encoder', 'decoder', 'joint'] - return valid_module_names - - @property - def default_adapter_module_name(self) -> str: - return 'encoder' diff --git a/nemo/collections/asr/parts/mixins/diarization.py b/nemo/collections/asr/parts/mixins/diarization.py deleted file mode 100644 index f59b5a3475f82838972a26a7e30d134e770c59ac..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/mixins/diarization.py +++ /dev/null @@ -1,651 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import json -import os -import tempfile -from abc import ABC, abstractmethod -from dataclasses import dataclass -from functools import partial -from typing import Any, Dict, List, Optional, Tuple, Union - -import librosa -import numpy as np -import torch -from torch.utils.data import DataLoader, Dataset -from tqdm import tqdm - -from nemo.collections.asr.parts.utils.speaker_utils import audio_rttm_map, get_uniqname_from_filepath -from nemo.collections.asr.parts.utils.vad_utils import PostProcessingParams, load_postprocessing_from_yaml -from nemo.collections.common.data.utils import move_data_to_device -from nemo.utils import logging - -GenericDiarizationType = Union[List[Any], List[List[Any]], Tuple[Any], Tuple[List[Any]]] - - -def resample_audio(samples: np.ndarray, orig_sr: int, target_sr: int) -> np.ndarray: - """ - Resample a mono 1D numpy signal to `target_sr`. - """ - orig_sr = int(orig_sr) - target_sr = int(target_sr) - if orig_sr <= 0 or target_sr <= 0: - raise ValueError(f"Invalid sample rates: orig_sr={orig_sr}, target_sr={target_sr}") - - if orig_sr == target_sr: - return samples.astype(np.float32, copy=False) - - if samples.size == 0: - return samples.astype(np.float32, copy=False) - - resampled_samples = samples.astype(np.float32, copy=False) - resampled_samples = librosa.core.resample(resampled_samples, orig_sr=orig_sr, target_sr=target_sr) - return resampled_samples.astype(np.float32, copy=False) - - -class NumpyAudioDataset(Dataset): - def __init__(self, waveforms: List[torch.Tensor], lengths: List[int]): - self._waveforms = waveforms - self._lengths = lengths - - def __len__(self) -> int: - return len(self._waveforms) - - def __getitem__(self, idx: int): - return self._waveforms[idx], self._lengths[idx] - - -@dataclass -class InternalDiarizeConfig: - """Internal diarization configuration parameters for diarization inference.""" - - # Internal values - device: Optional[torch.device] = None - dtype: Optional[torch.dtype] = None - training_mode: bool = False - logging_level: Optional[Any] = None - target_sample_rate: int = 16000 - - # Preprocessor values - dither_value: float = 0.0 - pad_to_value: int = 0 - - # Scratch space - temp_dir: Optional[str] = None - manifest_filepath: Optional[str] = None - max_num_of_spks: Optional[int] = 4 - - -@dataclass -class DiarizeConfig: - """Configuration parameters for diarization inference.""" - - session_len_sec: float = -1 # End-to-end diarization session length limit in seconds - batch_size: int = 1 - num_workers: int = 1 - sample_rate: Optional[int] = None - postprocessing_yaml: Optional[str] = None # Path to a yaml file for postprocessing configurations - verbose: bool = True - include_tensor_outputs: bool = False - postprocessing_params: PostProcessingParams = None - max_num_of_spks: Optional[int] = None - - # Utility - _internal: Optional[InternalDiarizeConfig] = None - - -def get_value_from_diarization_config(diarcfg, key, default): - """ - Utility function to get a value from the diarization config. - If the value is not present in the diarization config, the default value is returned. - - Args: - diarcfg: A dataclass that represents the diarization config. - key: The name of the arg to retrieve. - default: The default value to return if the key is not present in the diarization config. - - Returns: - The value of the key in the diarization config or the default value. - """ - if hasattr(diarcfg, key): - return getattr(diarcfg, key) - else: - logging.debug( - f"Using default value of {default} for {key} because it is not present \ - in the diarization config {diarcfg}." - ) - return default - - -class SpkDiarizationMixin(ABC): - """ - An abstract class for diarize-able models. - - Creates a template function `diarize()` that provides an interface to perform diarization of audio tensors or - filepaths. - """ - - def __init__(self): - self._diarize_audio_rttm_map = {} - - def _diarize_infer_model_device(self) -> torch.device: - """Best-effort resolution of the model device for diarize() runtime.""" - if hasattr(self, 'device'): - return self.device - return next(self.parameters()).device - - def _diarize_numpy_to_1d_float_tensor( - self, audio_samples: np.ndarray, sample_rate: int, target_sample_rate: int - ) -> torch.Tensor: - """Convert numpy audio (1D/2D) into a mono 1D float32 CPU torch tensor.""" - if not isinstance(audio_samples, np.ndarray): - raise TypeError(f"Expected np.ndarray, got {type(audio_samples)}") - if audio_samples.size == 0: - raise ValueError("Empty numpy audio array provided to diarize()") - - # Normalize shape to (T,) by converting multi-channel inputs to mono. - if audio_samples.ndim == 1: - mono_samples = audio_samples - elif audio_samples.ndim == 2: - # Accept (T, C) or (C, T); choose the one that looks like time-major. - if audio_samples.shape[0] <= 8 and audio_samples.shape[1] > audio_samples.shape[0]: - audio_samples = audio_samples.T - mono_samples = audio_samples.mean(axis=1) - else: - raise ValueError(f"Unsupported numpy audio shape {audio_samples.shape}. Expected 1D or 2D audio.") - - mono_samples = resample_audio(mono_samples, orig_sr=sample_rate, target_sr=target_sample_rate) - - waveform_tensor = torch.as_tensor(np.ascontiguousarray(mono_samples)) - return waveform_tensor.to(torch.float32) - - def _diarize_collate_pad_to_device(self, batch, model_device: torch.device): - """Collate `(wave_cpu_tensor, length)` items into `(padded_wave, lengths)` on `model_device`.""" - waveform_tensors_cpu, waveform_lengths = zip(*batch) - lengths_tensor = torch.tensor(waveform_lengths, dtype=torch.long, device=model_device) - max_length = int(max(waveform_lengths)) - padded_waveforms = torch.zeros( - (len(waveform_tensors_cpu), max_length), dtype=torch.float32, device=model_device - ) - for batch_index, waveform_tensor_cpu in enumerate(waveform_tensors_cpu): - waveform_tensor = waveform_tensor_cpu.to(device=model_device, dtype=torch.float32, non_blocking=True) - padded_waveforms[batch_index, : waveform_tensor.shape[0]] = waveform_tensor - return padded_waveforms, lengths_tensor - - @torch.inference_mode() - def diarize( - self, - audio: Union[str, List[str], np.ndarray, List[np.ndarray], DataLoader], - sample_rate: Optional[int] = None, - batch_size: int = 1, - include_tensor_outputs: bool = False, - postprocessing_yaml: Optional[str] = None, - num_workers: int = 1, - verbose: bool = False, - override_config: Optional[DiarizeConfig] = None, - **config_kwargs, - ) -> GenericDiarizationType: - """ - Takes paths to audio files and returns speaker labels - """ - - if override_config is None: - postprocessing_params = load_postprocessing_from_yaml(postprocessing_yaml) - diarize_cfg = DiarizeConfig( - batch_size=batch_size, - num_workers=num_workers, - verbose=verbose, - include_tensor_outputs=include_tensor_outputs, - postprocessing_yaml=postprocessing_yaml, - postprocessing_params=postprocessing_params, - sample_rate=sample_rate, - **config_kwargs, - ) - else: - if not hasattr(override_config, '_internal'): - raise ValueError( - "`diarize_cfg must have an `_internal` argument, which must be of an object of type " - "InternalDiarizeConfig or its subclass." - ) - - if override_config._internal is None: - override_config._internal = InternalDiarizeConfig() - - diarize_cfg = override_config - - # Ensure postprocessing params exist even when override_config is used. - # If the caller passed `postprocessing_yaml=...` but override_config didn't set it, honor the arg. - if getattr(diarize_cfg, 'postprocessing_yaml', None) is None and postprocessing_yaml is not None: - diarize_cfg.postprocessing_yaml = postprocessing_yaml - - if getattr(diarize_cfg, 'postprocessing_params', None) is None: - diarize_cfg.postprocessing_params = load_postprocessing_from_yaml( - getattr(diarize_cfg, 'postprocessing_yaml', None) - ) - - # Add new internal config - if diarize_cfg._internal is None: - diarize_cfg._internal = InternalDiarizeConfig() - else: - # Check if internal config is valid - if not isinstance(diarize_cfg._internal, InternalDiarizeConfig): - raise ValueError( - "`diarize_cfg._internal` must be of an object of type InternalDiarizeConfig or " "its subclass" - ) - - # Hold the results here - results = None - - try: - generator = self.diarize_generator(audio, override_config=diarize_cfg) - - for processed_outputs in generator: - # Store results - if isinstance(processed_outputs, list): - # Create a results of the same type as each element in processed_outputs - if results is None: - results = [] - - results.extend(processed_outputs) - - elif isinstance(processed_outputs, tuple): - # Create a results of the same type as each element in processed_outputs - if results is None: - results = tuple([[] for _ in processed_outputs]) - - # If nested list structure - if isinstance(processed_outputs[0], list): - for output_index, processed_output in enumerate(processed_outputs): - results[output_index].extend(processed_output) - else: - # If flat list structure - if len(processed_outputs) != len(results): - raise RuntimeError( - f"The number of elements in the result ({len(results)}) does not " - f"match the results of the current batch ({len(processed_outputs)})." - ) - - for output_index, processed_output in enumerate(processed_outputs): - results[output_index].append(processed_output) - - except StopIteration: - pass - - return results - - def diarize_generator( - self, - audio: Union[str, List[str], np.ndarray, List[np.ndarray], DataLoader], - override_config: Optional[DiarizeConfig], - ): - """ - A generator version of `diarize` function. - """ - if override_config is None: - override_config = DiarizeConfig() - - if not hasattr(override_config, '_internal'): - raise ValueError( - "`diarize_cfg must have an `_internal` argument, which must be of an object of type " - "InternalDiarizeConfig or its subclass." - ) - - # Add new internal config - if override_config._internal is None: - override_config._internal = InternalDiarizeConfig() - else: - # Check if internal config is valid - if not isinstance(override_config._internal, InternalDiarizeConfig): - raise ValueError( - "`diarize_cfg._internal` must be of an object of type InternalDiarizeConfig or " "its subclass" - ) - - diarize_cfg = override_config - - try: - # Initialize and assert the diarization environment - self._diarize_on_begin(audio, diarize_cfg) - - # Work in tmp directory - will store manifest file there - with tempfile.TemporaryDirectory() as tmpdir: - diarize_cfg._internal.temp_dir = tmpdir - - # Create a DataLoader if not already present - if not isinstance(audio, DataLoader): - dataloader = self._diarize_input_processing(audio, diarize_cfg) - else: - dataloader = audio - - if hasattr(diarize_cfg, 'verbose'): - verbose = diarize_cfg.verbose - else: - verbose = True - - for batch_idx, test_batch in enumerate(tqdm(dataloader, desc="Diarizing", disable=not verbose)): - # Move batch to device - test_batch = move_data_to_device(test_batch, diarize_cfg._internal.device) - uniq_ids = list(self._diarize_audio_rttm_map.keys())[ - batch_idx * diarize_cfg.batch_size : (batch_idx + 1) * diarize_cfg.batch_size - ] - - # Run forward pass - pred_outputs = self._diarize_forward(test_batch) - processed_outputs = self._diarize_output_processing(pred_outputs, uniq_ids, diarize_cfg) - - # Yield results if generator - yield processed_outputs - - # clear up memory - del test_batch, pred_outputs, processed_outputs - torch.cuda.empty_cache() - - finally: - # set mode back to its original value - self._diarize_on_end(diarize_cfg) - - def _input_audio_to_rttm_processing(self, audio_files: List[str]) -> List[Dict[str, Union[str, float]]]: - """ - Generate manifest style dict if `audio` is a list of paths to audio files. - - Args: - audio_files: A list of paths to audio files. - - Returns: - audio_rttm_map_dict A list of manifest style dicts. - """ - audio_rttm_map_dict = {} - for audio_file in audio_files: - uniq_id = get_uniqname_from_filepath(audio_file) - entry = { - 'uniq_id': uniq_id, - 'audio_filepath': audio_file, - 'offset': 0.0, - 'duration': None, - 'text': '-', - 'label': 'infer', - } - audio_rttm_map_dict[uniq_id] = entry - return audio_rttm_map_dict - - def _diarize_on_begin(self, audio: Union[str, List[str]], diarcfg: DiarizeConfig): - """ - Internal function to setup the model for diarization. Perform all setup and pre-checks here. - - Args: - audio (Union[str, List[str]]): Of type `GenericDiarizationType` - diarcfg (DiarizeConfig): An instance of `DiarizeConfig`. - """ - if audio is None: - return {} - - if isinstance(audio, str): - audio = [audio] - - if isinstance(audio, list) and len(audio) == 0: - return {} - - # Set num_workers - num_workers = get_value_from_diarization_config(diarcfg, 'num_workers', default=1) - - if num_workers is None: - _batch_size = get_value_from_diarization_config(diarcfg, 'batch_size', default=1) - num_workers = min(_batch_size, os.cpu_count() - 1) - - # Assign num_workers if available as key in diarcfg - if hasattr(diarcfg, 'num_workers'): - diarcfg.num_workers = num_workers - - # Model's mode and device - diarcfg._internal.training_mode = self.training - - # Save preprocessor settings before switching to evaluation mode - if hasattr(self, 'preprocessor'): - if hasattr(self.preprocessor, 'featurizer') and hasattr(self.preprocessor.featurizer, 'dither'): - diarcfg._internal.dither_value = self.preprocessor.featurizer.dither - self.preprocessor.featurizer.dither = 0.0 - - if hasattr(self.preprocessor, 'featurizer') and hasattr(self.preprocessor.featurizer, 'pad_to'): - diarcfg._internal.pad_to_value = self.preprocessor.featurizer.pad_to - self.preprocessor.featurizer.pad_to = 0 - - # Switch model to evaluation mode - self.eval() - - # Disable logging - diarcfg._internal.logging_level = logging.get_verbosity() - logging.set_verbosity(logging.WARNING) - - # Target sample rate for numpy inputs (resample to model preprocessor SR when available). - if hasattr(self, 'preprocessor') and hasattr(self.preprocessor, '_sample_rate'): - diarcfg._internal.target_sample_rate = int(self.preprocessor._sample_rate) - - def _diarize_input_processing(self, audio, diarcfg: DiarizeConfig): - """ - Internal function to process the input audio data and return a DataLoader. This function is called by - `diarize()` and `diarize_generator()` to setup the input data for diarization. - - Args: - audio: Of type `GenericDiarizationType` - diarcfg: The diarization config dataclass. Subclasses can change this to a different dataclass if needed. - - Returns: - A DataLoader object that is used to iterate over the input audio data. - """ - if isinstance(audio, (list, tuple)): - if len(audio) == 0: - raise ValueError("Input `audio` is empty") - else: - # Assume it is a single variable, so wrap it in a list - audio = [audio] - - # Check if audio is a list of strings (filepaths or manifests) - if isinstance(audio[0], str): - if len(audio) == 1 and (audio[0].endswith('.json') or audio[0].endswith('.jsonl')): - # Assume it is a path to a manifest file - self._diarize_audio_rttm_map = audio_rttm_map(audio[0]) - # Keep this config minimal and typed correctly; downstream datasets expect numeric session_len_sec. - manifest_item_count = len(self._diarize_audio_rttm_map) - requested_batch_size = int(get_value_from_diarization_config(diarcfg, 'batch_size', 1)) - ds_config = { - 'manifest_filepath': audio[0], - 'batch_size': min(requested_batch_size, manifest_item_count), - 'session_len_sec': get_value_from_diarization_config( - diarcfg, 'session_len_sec', diarcfg.session_len_sec - ), - 'num_workers': get_value_from_diarization_config(diarcfg, 'num_workers', 1), - 'use_lhotse': True, - } - else: - # Make `audio_files` a list of audio file paths - audio_files = list(audio) - self._diarize_audio_rttm_map = self._input_audio_to_rttm_processing(audio_files=audio_files) - tmp_dir = diarcfg._internal.temp_dir - ds_config = self._diarize_input_manifest_processing(audio_files, temp_dir=tmp_dir, diarcfg=diarcfg) - - temp_dataloader = self._setup_diarize_dataloader(ds_config) - return temp_dataloader - - # Numpy waveform input(s) - elif isinstance(audio[0], np.ndarray): - - sample_rate = get_value_from_diarization_config(diarcfg, 'sample_rate', None) - if sample_rate is None: - raise ValueError("Sample rate is not set. Numpy audio inputs require sample_rate to be set.") - - # Be robust to callers accidentally passing "an array of arrays" (dtype=object), - # which should be interpreted as a list of waveforms. - if ( - isinstance(audio[0], np.ndarray) - and getattr(audio[0], "dtype", None) == object - and audio[0].ndim == 1 - and len(audio) == 1 - ): - audio_list = list(audio[0]) - else: - audio_list = list(audio) - - # Infer the model's device for efficient numpy->tensor placement. - model_device = self._diarize_infer_model_device() - - # Creating CUDA tensors inside DataLoader workers is not supported. - if model_device.type == 'cuda' and getattr(diarcfg, 'num_workers', 0) not in (0, None): - logging.warning("For numpy inputs on CUDA, forcing `num_workers=0` to avoid CUDA tensors in workers.") - diarcfg.num_workers = 0 - - waveform_tensors_cpu: List[torch.Tensor] = [] - waveform_lengths: List[int] = [] - entries: List[Dict[str, Union[str, float]]] = [] - for array_index, numpy_array in enumerate(audio_list): - uniq_id = f"numpy_{array_index}" - waveform_tensor_cpu = self._diarize_numpy_to_1d_float_tensor( - numpy_array, - sample_rate=sample_rate, - target_sample_rate=diarcfg._internal.target_sample_rate, - ) - waveform_length = int(waveform_tensor_cpu.shape[0]) - waveform_tensors_cpu.append(waveform_tensor_cpu) - waveform_lengths.append(waveform_length) - entries.append( - { - 'uniq_id': uniq_id, - 'audio_filepath': f"", - 'offset': 0.0, - 'duration': float(waveform_length) / float(sample_rate), - 'text': '-', - 'label': 'infer', - } - ) - - self._diarize_audio_rttm_map = {entry['uniq_id']: entry for entry in entries} - - np_dataset = NumpyAudioDataset(waveform_tensors_cpu, waveform_lengths) - return DataLoader( - np_dataset, - batch_size=get_value_from_diarization_config(diarcfg, 'batch_size', 1), - shuffle=False, - num_workers=get_value_from_diarization_config(diarcfg, 'num_workers', 0) or 0, - pin_memory=False, - collate_fn=partial(self._diarize_collate_pad_to_device, model_device=model_device), - ) - - else: - raise ValueError( - f"Input `audio` is of type {type(audio[0])}. " - "Only `str` (path to audio file) or `np.ndarray` are supported as input." - ) - - def _diarize_input_manifest_processing( - self, audio_files: List[Union[str, Dict[str, Any]]], temp_dir: str, diarcfg: DiarizeConfig - ) -> Dict[str, Any]: - """ - Internal function to process the input audio filepaths and return a config dict for the dataloader. - - Args: - audio_files: A list of audio inputs (either filepaths or manifest-style dicts). - temp_dir: A temporary directory to store intermediate files. - diarcfg: The diarization config dataclass. Subclasses can change this to a different dataclass if needed. - - Returns: - A config dict that is used to setup the dataloader for diarization. - """ - with open(os.path.join(temp_dir, 'manifest.json'), 'w', encoding='utf-8') as fp: - for audio_file in audio_files: - if isinstance(audio_file, str): - entry = {'audio_filepath': audio_file, 'duration': 100000, 'text': ''} - fp.write(json.dumps(entry) + '\n') - elif isinstance(audio_file, dict): - fp.write(json.dumps(audio_file) + '\n') - else: - raise ValueError( - f"Input `audio` is of type {type(audio_file)}. " - "Only `str` (path to audio file) or `dict` are supported as input." - ) - - ds_config = { - 'paths2audio_files': audio_files, - 'batch_size': get_value_from_diarization_config(diarcfg, 'batch_size', 1), - 'temp_dir': temp_dir, - 'session_len_sec': get_value_from_diarization_config(diarcfg, 'session_len_sec', diarcfg.session_len_sec), - 'num_workers': get_value_from_diarization_config(diarcfg, 'num_workers', 1), - 'use_lhotse': True, - } - - return ds_config - - @abstractmethod - def _setup_diarize_dataloader(self, config: Dict) -> DataLoader: - """ - Internal function to setup the dataloader for diarization. This function is called by - `diarize()` and `diarize_generator()` to setup the input data for diarization. - - Args: - config: A config dict that is used to setup the dataloader for diarization. - It can be generated by `_diarize_input_manifest_processing()`. - - Returns: - A DataLoader object that is used to iterate over the input audio data. - """ - pass - - @abstractmethod - def _diarize_forward(self, batch: Any): - """ - Internal function to perform the model's custom forward pass to return outputs that are processed by - `_diarize_output_processing()`. - This function is called by `diarize()` and `diarize_generator()` to perform the model's forward pass. - - Args: - batch: A batch of input data from the data loader that is used to perform the model's forward pass. - - Returns: - The model's outputs that are processed by `_diarize_output_processing()`. - """ - pass - - @abstractmethod - def _diarize_output_processing(self, outputs, uniq_ids, diarcfg: DiarizeConfig) -> GenericDiarizationType: - """ - Internal function to process the model's outputs to return the results to the user. This function is called by - `diarize()` and `diarize_generator()` to process the model's outputs. - - Args: - outputs: The model's outputs that are processed by `_diarize_forward()`. - uniq_ids: List of unique recording identificators in batch - diarcfg: The diarization config dataclass. Subclasses can change this to a different dataclass if needed. - - Returns: - The output can be a list of - objects, list of list of objects, tuple of objects, tuple of list of objects. - Its type is defined in `GenericDiarizationType`. - """ - pass - - def _diarize_on_end(self, diarcfg: DiarizeConfig): - """ - Internal function to teardown the model after diarization. Perform all teardown and post-checks here. - - Args: - diarcfg: The diarization config dataclass. Subclasses can change this to a different dataclass if needed. - """ - # set mode back to its original value - self.train(mode=diarcfg._internal.training_mode) - - if hasattr(self, 'preprocessor'): - if hasattr(self.preprocessor, 'featurizer') and hasattr(self.preprocessor.featurizer, 'dither'): - self.preprocessor.featurizer.dither = diarcfg._internal.dither_value - - if hasattr(self.preprocessor, 'featurizer') and hasattr(self.preprocessor.featurizer, 'pad_to'): - self.preprocessor.featurizer.pad_to = diarcfg._internal.pad_to_value - - if diarcfg._internal.logging_level is not None: - logging.set_verbosity(diarcfg._internal.logging_level) diff --git a/nemo/collections/asr/parts/mixins/interctc_mixin.py b/nemo/collections/asr/parts/mixins/interctc_mixin.py deleted file mode 100644 index 3e1e9785d6226d12bbadf96adb4c2d5b46c3e97c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/mixins/interctc_mixin.py +++ /dev/null @@ -1,294 +0,0 @@ -# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -from typing import Dict, List, Optional, Tuple - -import torch - -from nemo.core.classes.mixins import AccessMixin -from nemo.utils import logging - - -class InterCTCMixin: - """Adds utilities for computing interCTC loss from https://arxiv.org/abs/2102.03216. - - To use, make sure encoder accesses ``interctc['capture_layers']`` - property in the AccessMixin and registers ``interctc/layer_output_X`` and - ``interctc/layer_length_X`` for all layers that we want to get loss from. - Additionally, specify the following config parameters to set up loss:: - - interctc: - # can use different values - loss_weights: [0.3] - apply_at_layers: [8] - - Then call - - * ``self.setup_interctc(ctc_decoder_name, ctc_loss_name, ctc_wer_name)`` - in the init method - * ``self.add_interctc_losses`` after computing regular loss. - * ``self.finalize_interctc_metrics(metrics, outputs, prefix="val_")`` - in the `multi_validation_epoch_end` method. - * ``self.finalize_interctc_metrics(metrics, outputs, prefix="test_")`` - in the `multi_test_epoch_end` method. - """ - - def _process_config_values(self, loss_weights: List[float], apply_at_layers: List[int]): - self.set_interctc_param('intermediate_loss_weights', loss_weights) - self.set_interctc_param('apply_at_layers', apply_at_layers) - self.set_interctc_param('main_loss_weight', 1.0 - sum(loss_weights)) - if self.get_interctc_param('main_loss_weight') <= 0.0: - raise ValueError( - "Make sure that sum of intermediate loss weights is < 1.0. " - "Note that we don't do any normalization and assign " - "remaining weight to the regular model loss. " - "E.g., if interctc.loss_weights = [0.1, 0.3], regular " - "loss will have weight of 0.6" - ) - self.set_interctc_param('enabled', len(loss_weights) > 0) - - if len(apply_at_layers) != len(loss_weights): - raise ValueError('Length of interctc.apply_at_layers has to match interctc.loss_weights') - - # setting up config for AccessMixin that will be checked in encoders to - # log the layers we need - AccessMixin.update_access_cfg( - {'interctc': {'capture_layers': apply_at_layers}}, guid=getattr(self, "model_guid", None) - ) - if hasattr(self, "propagate_model_guid"): - self.propagate_model_guid() - else: - logging.warning( - f"Not able to propagate model_guid to the submodules. Make sure to call self.propagate_model_guid() in ModelPT class." - ) - - def setup_interctc(self, decoder_name, loss_name, wer_name): - """Sets up all interctc-specific parameters and checks config consistency. - - Caller has to specify names of attributes to perform CTC-specific WER, - decoder and loss computation. They will be looked up in the class - state with ``getattr``. - - The reason we get the names and look up object later is because those - objects might change without re-calling the setup of this class. So - we always want to look up the most up-to-date object instead of - "caching" it here. - """ - # registering all parameters in a dictionary to avoid conflicts with - # main class's names - self._interctc_params = {} - interctc_config = self.cfg.get("interctc") - if interctc_config is not None: - # if interctc is in the config, we want to check that it indeed defines - # the required keys and nothing else - that's automatically done by - # matching with keyword arguments in self._process_config_values - self._process_config_values(**interctc_config) - self._interctc_params['decoder_name'] = decoder_name - self._interctc_params['loss_name'] = loss_name - self._interctc_params['wer_name'] = wer_name - else: - self.set_interctc_param('enabled', False) - - def get_interctc_param(self, param_name): - """Either directly get parameter from ``self._interctc_params`` or - call getattr with the corresponding name. - """ - if param_name in ['decoder', 'loss', 'wer']: - return getattr(self, self._interctc_params[param_name + "_name"]) - return self._interctc_params[param_name] - - def set_interctc_param(self, param_name, param_value): - """Setting the parameter to the ``self._interctc_params`` dictionary. - - Raises an error if trying to set decoder, loss or wer as those should - always come from the main class. - """ - if param_name in ['decoder', 'loss', 'wer']: - raise ValueError( - 'Cannot set "decoder", "loss" or "wer" as parameters. ' - 'They are always looked up in the main class state.' - ) - self._interctc_params[param_name] = param_value - - def _verify_setup_was_called(self): - """Can be used to verify if setup_interctc was called.""" - if not hasattr(self, '_interctc_params'): - raise RuntimeError( - 'self.setup_interctc(ctc_decoder_name, ctc_loss_name, ctc_wer_name) has to be ' - 'called before InterCTC loss can be used!' - ) - - def is_interctc_enabled(self) -> bool: - """Returns whether interCTC loss is enabled.""" - self._verify_setup_was_called() - return self.get_interctc_param('enabled') - - def set_interctc_enabled(self, enabled: bool): - """Can be used to enable/disable InterCTC manually.""" - self._verify_setup_was_called() - if enabled: # checking if proper config parameters were specified - if len(self.get_interctc_param('intermediate_loss_weights')) == 0: - raise RuntimeError( - 'InterCTC cannot be enabled since interctc.loss_weights was not specified in the config.' - ) - if len(self.get_interctc_param('apply_at_layers')) != len( - self.get_interctc_param('intermediate_loss_weights') - ): - raise RuntimeError( - 'InterCTC cannot be enabled, since length of "loss_weights" does not match "apply_at_layers".' - ) - self.set_interctc_param('enabled', enabled) - - def finalize_interctc_metrics(self, metrics: Dict, outputs: List[Dict], prefix: str): - """Finalizes InterCTC WER and loss metrics for logging purposes. - - Should be called inside ``multi_validation_epoch_end`` (with ``prefix="val_"``) or - ``multi_test_epoch_end`` (with ``prefix="test_"``). - - Note that ``metrics`` dictionary is going to be updated in-place. - """ - if self.is_interctc_enabled(): - for layer_idx in self.get_interctc_param('apply_at_layers'): - # assuming that if the first batch logged the metrics, then all batches did - if f"{prefix}inter_ctc_loss_l{layer_idx}" in outputs[0]: - loss = torch.stack([x[f"{prefix}inter_ctc_loss_l{layer_idx}"] for x in outputs]).mean() - metrics["log"][f"{prefix}inter_ctc_loss_l{layer_idx}"] = loss - - if f"{prefix}inter_wer_num_l{layer_idx}" in outputs[0]: - wer_num = torch.stack([x[f"{prefix}inter_wer_num_l{layer_idx}"] for x in outputs]).sum() - wer_denom = torch.stack([x[f"{prefix}inter_wer_denom_l{layer_idx}"] for x in outputs]).sum() - metrics["log"][f"{prefix}inter_wer_l{layer_idx}"] = wer_num / wer_denom - - if f"{prefix}final_loss" in outputs[0]: - metrics["log"][f"{prefix}final_loss"] = torch.stack([x[f"{prefix}final_loss"] for x in outputs]).mean() - - def get_captured_interctc_tensors(self) -> List[Tuple[torch.Tensor, torch.Tensor]]: - """Returns a list of captured tensors from encoder: tuples of (output, length). - - Will additionally apply ``ctc_decoder`` to the outputs. - """ - if not self.is_interctc_enabled(): - return [] - - # note that we have a loop here, because tensors can be defined from - # submodules of encoder (e.g., that's the case in Jasper) - total_registry = {} - for module_registry in AccessMixin.get_module_registry(self.encoder).values(): - for key in module_registry: - if key.startswith("interctc/") and key in total_registry: - raise RuntimeError(f"layer {key} has been logged multiple times!") - total_registry.update(module_registry) - # if intermediate_loss_weights was set, the encoder has to register - # interctc/layer_output_X and interctc/layer_length_X tensors. - # We need to apply decoder to each of them and compute CTC loss. - captured_tensors = [] - for layer_idx in self.get_interctc_param('apply_at_layers'): - try: - layer_outputs = total_registry[f"interctc/layer_output_{layer_idx}"] - layer_lengths = total_registry[f"interctc/layer_length_{layer_idx}"] - except KeyError: - raise RuntimeError( - f"Intermediate layer {layer_idx} was not captured! " - "Check if length of model.encoder.captured_layer_outputs matches " - "length of model.intermediate_loss_weights properties." - ) - if len(layer_outputs) > 1 or len(layer_lengths) > 1: - raise RuntimeError( - "Make sure encoder.forward is called exactly one time before interCTC loss is computed." - ) - captured_tensors.append( - (self.get_interctc_param('decoder')(encoder_output=layer_outputs[0]), layer_lengths[0]) - ) - return captured_tensors - - def add_interctc_losses( - self, - loss_value: torch.Tensor, - transcript: torch.Tensor, - transcript_len: torch.Tensor, - compute_wer: bool, - compute_loss: bool = True, - log_wer_num_denom: bool = False, - log_prefix: str = "", - ) -> Tuple[Optional[torch.Tensor], Dict]: - """Adding interCTC losses if required. - - Will also register loss/wer metrics in the returned dictionary. - - Args: - loss_value (torch.Tensor): regular loss tensor (will add interCTC loss to it). - transcript (torch.Tensor): current utterance transcript. - transcript_len (torch.Tensor): current utterance transcript length. - compute_wer (bool): whether to compute WER for the current utterance. - Should typically be True for validation/test and only True for - training if current batch WER should be logged. - compute_loss (bool): whether to compute loss for the current utterance. - Should always be True in training and almost always True in - validation, unless all other losses are disabled as well. - Defaults to True. - log_wer_num_denom (bool): if True, will additionally log WER num/denom - in the returned metrics dictionary. Should always be True for - validation/test to allow correct metrics aggregation. Should - always be False for training. Defaults to False. - log_prefix (str): prefix added to all log values. Should be ``""`` for - training and ``"val_"`` for validation. Defaults to "". - - Returns: - tuple[Optional[torch.Tensor], Dict]: tuple of new loss tensor and dictionary with logged metrics. - """ - if not self.is_interctc_enabled() or not AccessMixin.is_access_enabled(getattr(self, "model_guid", None)): - return loss_value, {} - metrics = {} - if compute_loss: - metrics[f"{log_prefix}final_loss"] = loss_value - else: - loss_value = None - captured_tensors = self.get_captured_interctc_tensors() - - if compute_loss: - loss_value *= self.get_interctc_param('main_loss_weight') - - for layer_idx, intermediate_result, loss_weight in zip( - self.get_interctc_param('apply_at_layers'), - captured_tensors, - self.get_interctc_param('intermediate_loss_weights'), - ): - if compute_loss: - inter_loss_value = self.get_interctc_param('loss')( - log_probs=intermediate_result[0], - targets=transcript, - target_lengths=transcript_len, - input_lengths=intermediate_result[1], - ) - metrics[f"{log_prefix}inter_ctc_loss_l{layer_idx}"] = inter_loss_value.detach() - loss_value += inter_loss_value * loss_weight - if compute_wer: - self.get_interctc_param('wer').update( - predictions=intermediate_result[0], - targets=transcript, - targets_lengths=transcript_len, - predictions_lengths=intermediate_result[1], - ) - wer, wer_num, wer_denom = self.get_interctc_param('wer').compute() - self.get_interctc_param('wer').reset() - metrics.update({f'{log_prefix}inter_wer_l{layer_idx}': wer}) - if log_wer_num_denom: - metrics.update( - { - f'{log_prefix}inter_wer_num_l{layer_idx}': wer_num, - f'{log_prefix}inter_wer_denom_l{layer_idx}': wer_denom, - } - ) - - # return total loss and dictionary of metrics - return loss_value, metrics diff --git a/nemo/collections/asr/parts/mixins/mixins.py b/nemo/collections/asr/parts/mixins/mixins.py deleted file mode 100644 index af973be3cc4c569c37e13ef86ca6d218134433f5..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/mixins/mixins.py +++ /dev/null @@ -1,899 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import json -import os -import tarfile -from abc import ABC, abstractmethod -from typing import List - -import torch -from omegaconf import DictConfig, OmegaConf, open_dict -from torch import Tensor - -import nemo.collections.asr.models as asr_models -from nemo.collections.asr.parts.mixins.asr_adapter_mixins import ASRAdapterModelMixin -from nemo.collections.asr.parts.mixins.streaming import StreamingEncoder -from nemo.collections.asr.parts.utils import asr_module_utils -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis -from nemo.collections.asr.parts.utils.tokenizer_utils import ( - extract_capitalized_tokens_from_vocab, - extract_punctuation_from_vocab, -) -from nemo.collections.common import tokenizers -from nemo.utils import app_state, logging -from nemo.utils.file_utils import robust_copy - - -class ASRBPEMixin(ABC): - """ASR BPE Mixin class that sets up a Tokenizer via a config - - This mixin class adds the method `_setup_tokenizer(...)`, which can be used by ASR models - which depend on subword tokenization. - - The setup_tokenizer method adds the following parameters to the class - - - tokenizer_cfg: The resolved config supplied to the tokenizer (with `dir` and `type` arguments). - - tokenizer_dir: The directory path to the tokenizer vocabulary + additional metadata. - - tokenizer_type: The type of the tokenizer. Currently supports `bpe` and `wpe`, as well as `agg`. - - vocab_path: Resolved path to the vocabulary text file. - - In addition to these variables, the method will also instantiate and preserve a tokenizer - (subclass of TokenizerSpec) if successful, and assign it to self.tokenizer. - - The mixin also supports aggregate tokenizers, which consist of ordinary, monolingual tokenizers. - If a conversion between a monolongual and an aggregate tokenizer (or vice versa) is detected, - all registered artifacts will be cleaned up. - """ - - # this will be used in configs and nemo artifacts - AGGREGATE_TOKENIZERS_DICT_PREFIX = 'langs' - - def _setup_tokenizer(self, tokenizer_cfg: DictConfig): - tokenizer_type = tokenizer_cfg.get('type') - if tokenizer_type is None: - raise ValueError("`tokenizer.type` cannot be None") - elif tokenizer_type.lower() == 'agg': - self._setup_aggregate_tokenizer(tokenizer_cfg) - else: - self._setup_monolingual_tokenizer(tokenizer_cfg) - - self._derive_tokenizer_properties() - - def _setup_monolingual_tokenizer(self, tokenizer_cfg: DictConfig): - # Prevent tokenizer parallelism (unless user has explicitly set it) - if 'TOKENIZERS_PARALLELISM' not in os.environ: - os.environ['TOKENIZERS_PARALLELISM'] = 'false' - - self.tokenizer_cfg = OmegaConf.to_container(tokenizer_cfg, resolve=True) # type: dict - self.tokenizer_dir = self.tokenizer_cfg.pop('dir') # Remove tokenizer directory - self.tokenizer_type = self.tokenizer_cfg.pop('type').lower() # Remove tokenizer_type - - self.hf_tokenizer_kwargs = self.tokenizer_cfg.pop("hf_kwargs", {}) # Remove HF tokenizer kwargs - - # just in case the previous tokenizer was an aggregate - self._cleanup_aggregate_config_and_artifacts_if_needed() - - # Preserve config - if hasattr(self, 'cfg') and 'tokenizer' in self.cfg: - self.cfg.tokenizer.dir = self.tokenizer_dir - self.cfg.tokenizer.type = self.tokenizer_type - - if 'hf_kwargs' in tokenizer_cfg: - with open_dict(self.cfg.tokenizer): - self.cfg.tokenizer.hf_kwargs = tokenizer_cfg.get('hf_kwargs') - - if self.tokenizer_type not in ['bpe', 'wpe']: - raise ValueError( - "`tokenizer.type` must be either `bpe` for SentencePiece tokenizer or " - "`wpe` for BERT based tokenizer" - ) - - if self.tokenizer_type == 'bpe': - # This is a BPE Tokenizer - if 'model_path' in self.tokenizer_cfg: - model_path = self.tokenizer_cfg.get('model_path') - else: - model_path = os.path.join(self.tokenizer_dir, 'tokenizer.model') - model_path = self.register_artifact('tokenizer.model_path', model_path) - self.model_path = model_path - - if 'special_tokens' in self.tokenizer_cfg: - special_tokens = self.tokenizer_cfg['special_tokens'] - - if special_tokens is not None: - raise ValueError("`special_tokens` are no longer supported for SentencePiece based tokenizers.") - - if "custom_tokenizer" in self.tokenizer_cfg: - self.tokenizer = self.from_config_dict( - {"_target_": tokenizer_cfg["custom_tokenizer"]["_target_"], "model_path": model_path} - ) - else: - self.tokenizer = tokenizers.SentencePieceTokenizer(model_path=model_path) - - if 'vocab_path' in self.tokenizer_cfg: - vocab_path = self.tokenizer_cfg.get('vocab_path') - else: - vocab_path = os.path.join(self.tokenizer_dir, 'vocab.txt') - vocab_path = self.register_artifact('tokenizer.vocab_path', vocab_path) - self.vocab_path = vocab_path - - try: - if 'spe_tokenizer_vocab' in self.tokenizer_cfg: - spe_vocab_path = self.tokenizer_cfg.get('spe_tokenizer_vocab') - else: - spe_vocab_path = os.path.join(self.tokenizer_dir, 'tokenizer.vocab') - spe_vocab_path = self.register_artifact('tokenizer.spe_tokenizer_vocab', spe_vocab_path) - self.spe_vocab_path = spe_vocab_path - except FileNotFoundError: - # fallback case for older checkpoints that did not preserve the tokenizer.vocab - self.spe_vocab_path = None - - vocabulary = {} - for i in range(self.tokenizer.vocab_size): - piece = self.tokenizer.ids_to_tokens([i]) - piece = piece[0] - vocabulary[piece] = i + 1 - - # wrapper method to get vocabulary conveniently - def get_vocab(): - return vocabulary - - # attach utility values to the tokenizer wrapper - self.tokenizer.tokenizer.vocab_size = len(vocabulary) - self.tokenizer.tokenizer.get_vocab = get_vocab - self.tokenizer.tokenizer.all_special_tokens = self.tokenizer.special_token_to_id - - else: - # This is a WPE Tokenizer - # If path from previous registration exists, remove it - if 'vocab_path' in self.tokenizer_cfg: - vocab_path = self.tokenizer_cfg.get('vocab_path') - else: - vocab_path = os.path.join(self.tokenizer_dir, 'vocab.txt') - vocab_path = self.register_artifact('tokenizer.vocab_path', vocab_path) - self.vocab_path = vocab_path - - # If path from previous registration exists, remove it - if 'vocab_path' in self.tokenizer_cfg: - self.tokenizer_cfg.pop('vocab_path') - - self.tokenizer = tokenizers.AutoTokenizer( - pretrained_model_name='bert-base-cased', - vocab_file=self.vocab_path, - mask_token=self.hf_tokenizer_kwargs.get('mask_token', None), - bos_token=self.hf_tokenizer_kwargs.get('bos_token', None), - eos_token=self.hf_tokenizer_kwargs.get('eos_token', None), - pad_token=self.hf_tokenizer_kwargs.get('pad_token', None), - sep_token=self.hf_tokenizer_kwargs.get('sep_token', None), - cls_token=self.hf_tokenizer_kwargs.get('cls_token', None), - unk_token=self.hf_tokenizer_kwargs.get('unk_token', None), - use_fast=self.hf_tokenizer_kwargs.get('use_fast', False), - ) - - logging.info( - "Tokenizer {} initialized with {} tokens".format( - self.tokenizer.__class__.__name__, self.tokenizer.vocab_size - ) - ) - - def _setup_aggregate_tokenizer(self, tokenizer_cfg: DictConfig): - # Prevent tokenizer parallelism (unless user has explicitly set it) - if 'TOKENIZERS_PARALLELISM' not in os.environ: - os.environ['TOKENIZERS_PARALLELISM'] = 'false' - - self.tokenizer_cfg = OmegaConf.to_container(tokenizer_cfg, resolve=True) # type: dict - - # the aggregate tokenizer does not have one tokenizer_dir but multiple ones - self.tokenizer_dir = None - - self.tokenizer_cfg.pop('dir', None) # Remove tokenizer directory, if any - # Remove tokenizer_type -- obviously if we are here, the type is 'agg' - self.tokenizer_type = self.tokenizer_cfg.pop('type').lower() - - # the aggregate tokenizer should not have these - self.hf_tokenizer_kwargs = {} - self.tokenizer_cfg.pop("hf_kwargs", {}) # Remove HF tokenizer kwargs, if any - - logging.info('_setup_tokenizer: detected an aggregate tokenizer') - # need to de-register any monolingual config items if they exist - self._cleanup_monolingual_and_aggregate_config_and_artifacts_if_needed() - - # overwrite tokenizer type - if hasattr(self, 'cfg') and 'tokenizer' in self.cfg: - self.cfg.tokenizer.type = self.tokenizer_type - - tokenizers_dict = {} - # init each of the monolingual tokenizers found in the config and assemble into AggregateTokenizer - for lang, tokenizer_config in self.tokenizer_cfg[self.AGGREGATE_TOKENIZERS_DICT_PREFIX].items(): - ( - tokenizer, - model_path, - vocab_path, - spe_vocab_path, - ) = self._make_tokenizer(tokenizer_config, lang) - - tokenizers_dict[lang] = tokenizer - if hasattr(self, 'cfg'): - with open_dict(self.cfg.tokenizer): - self.cfg.tokenizer[self.AGGREGATE_TOKENIZERS_DICT_PREFIX][lang]['dir'] = self.tokenizer_cfg[ - self.AGGREGATE_TOKENIZERS_DICT_PREFIX - ][lang]['dir'] - self.cfg.tokenizer[self.AGGREGATE_TOKENIZERS_DICT_PREFIX][lang]['type'] = self.tokenizer_cfg[ - self.AGGREGATE_TOKENIZERS_DICT_PREFIX - ][lang]['type'] - - if "custom_tokenizer" in tokenizer_cfg: - # Class which implements this is usually a ModelPT, has access to Serializable mixin by extension - self.tokenizer = self.from_config_dict( - {"_target_": tokenizer_cfg["custom_tokenizer"]["_target_"], "tokenizers": tokenizers_dict} - ) - else: - self.tokenizer = tokenizers.AggregateTokenizer(tokenizers_dict) - - def _make_tokenizer(self, tokenizer_cfg: DictConfig, lang=None): - - tokenizer_type = tokenizer_cfg.get('type').lower() - tokenizer_dir = tokenizer_cfg.get('dir') - - if tokenizer_type not in ['bpe', 'wpe']: - raise ValueError( - '`tokenizer.type` must be either `bpe` for SentencePiece tokenizer or' '`wpe` for BERT based tokenizer' - ) - - # defaults - model_path = None - vocab_path = None - spe_vocab_path = None - - if tokenizer_type == 'bpe': - # This is a BPE Tokenizer - if 'model_path' in tokenizer_cfg: - model_path = tokenizer_cfg.get('model_path') - else: - model_path = os.path.join(tokenizer_dir, 'tokenizer.model') - - model_path = self.register_artifact( - 'tokenizer.' + self.AGGREGATE_TOKENIZERS_DICT_PREFIX + '.' + lang + '.model_path', model_path - ) - - if 'special_tokens' in tokenizer_cfg: - special_tokens = tokenizer_cfg['special_tokens'] - if special_tokens is not None: - raise ValueError('`special_tokens` are no longer supported for SentencePiece based tokenizers.') - - # Update special tokens - tokenizer = tokenizers.SentencePieceTokenizer(model_path=model_path) - - if 'vocab_path' in tokenizer_cfg: - vocab_path = tokenizer_cfg.get('vocab_path') - else: - vocab_path = os.path.join(tokenizer_dir, 'vocab.txt') - - vocab_path = self.register_artifact( - 'tokenizer.' + self.AGGREGATE_TOKENIZERS_DICT_PREFIX + '.' + lang + '.vocab_path', vocab_path - ) - - try: - if 'spe_tokenizer_vocab' in tokenizer_cfg: - spe_vocab_path = tokenizer_cfg.get('spe_tokenizer_vocab') - else: - spe_vocab_path = os.path.join(tokenizer_dir, 'tokenizer.vocab') - - spe_vocab_path = self.register_artifact( - 'tokenizer.' + self.AGGREGATE_TOKENIZERS_DICT_PREFIX + '.' + lang + '.spe_tokenizer_vocab', - spe_vocab_path, - ) - - except FileNotFoundError: - # fallback case for older checkpoints that did not preserve the tokenizer.vocab - spe_vocab_path = None - - vocabulary = {} - for i in range(tokenizer.vocab_size): - piece = tokenizer.ids_to_tokens([i]) - piece = piece[0] - vocabulary[piece] = i + 1 - - # wrapper method to get vocabulary conveniently - def get_vocab(): - return vocabulary - - # attach utility values to the tokenizer wrapper - tokenizer.tokenizer.vocab_size = len(vocabulary) - tokenizer.tokenizer.get_vocab = get_vocab - tokenizer.tokenizer.all_special_tokens = tokenizer.special_token_to_id - - else: - # This is a WPE Tokenizer - # If path from previous registration exists, remove it - if 'vocab_path' in tokenizer_cfg: - vocab_path = tokenizer_cfg.get('vocab_path') - else: - vocab_path = os.path.join(tokenizer_dir, 'vocab.txt') - - vocab_path = self.register_artifact( - 'tokenizer.' + self.AGGREGATE_TOKENIZERS_DICT_PREFIX + '.' + lang + '.vocab_path', vocab_path - ) - - # If path from previous registration exists, remove it - if 'vocab_path' in tokenizer_cfg: - tokenizer_cfg.pop('vocab_path') - - hf_tokenizer_kwargs = tokenizer_cfg.get('hf_kwargs', {}) - tokenizer = tokenizers.AutoTokenizer( - pretrained_model_name=hf_tokenizer_kwargs.get('pretrained_model_name', 'bert-base-cased'), - vocab_file=vocab_path, - mask_token=hf_tokenizer_kwargs.get('mask_token', None), - bos_token=hf_tokenizer_kwargs.get('bos_token', None), - eos_token=hf_tokenizer_kwargs.get('eos_token', None), - pad_token=hf_tokenizer_kwargs.get('pad_token', None), - sep_token=hf_tokenizer_kwargs.get('sep_token', None), - cls_token=hf_tokenizer_kwargs.get('cls_token', None), - unk_token=hf_tokenizer_kwargs.get('unk_token', None), - use_fast=hf_tokenizer_kwargs.get('use_fast', False), - ) - - logging.info( - 'Tokenizer {} initialized with {} tokens'.format(tokenizer.__class__.__name__, tokenizer.vocab_size) - ) - - return tokenizer, model_path, vocab_path, spe_vocab_path - - def _cleanup_monolingual_and_aggregate_config_and_artifacts_if_needed(self): - """ - Clean ups any monolingual and some aggregate config items and artifacts. - We need to do this when we switch from a monolingual tokenizer to an aggregate one - or go between aggregate tokenizers which could have a different number of languages - """ - if hasattr(self, 'cfg'): - with open_dict(self.cfg.tokenizer): - self.cfg.tokenizer.pop('dir', None) - self.cfg.tokenizer.pop('model_path', None) - self.cfg.tokenizer.pop('vocab_path', None) - self.cfg.tokenizer.pop('spe_tokenizer_vocab', None) - self.cfg.tokenizer.pop('hf_kwargs', None) - - # need to de-register any monolingual artifacts if they exist - if hasattr(self, 'artifacts'): - self.artifacts.pop('tokenizer.model_path', None) - self.artifacts.pop('tokenizer.vocab_path', None) - self.artifacts.pop('tokenizer.spe_tokenizer_vocab', None) - - # just in case we are replacing one aggregate tokenizer with another one, we better - # clean up the old aggregate artifacts as well - for akey in list(self.artifacts.keys()): - if akey.startswith('tokenizer.' + self.AGGREGATE_TOKENIZERS_DICT_PREFIX + '.'): - self.artifacts.pop(akey) - - def _cleanup_aggregate_config_and_artifacts_if_needed(self): - """ - Clean ups any aggregate config items and artifacts. - We need to do this when we switch from an aggregate tokenizer to a monolingual one - """ - if hasattr(self, 'cfg'): - with open_dict(self.cfg.tokenizer): - self.cfg.tokenizer.pop(self.AGGREGATE_TOKENIZERS_DICT_PREFIX, None) - - # clean up the old aggregate artifacts as well - if hasattr(self, 'artifacts'): - for akey in list(self.artifacts.keys()): - if akey.startswith('tokenizer.' + self.AGGREGATE_TOKENIZERS_DICT_PREFIX + '.'): - self.artifacts.pop(akey) - - def save_tokenizers(self, directory: str): - """ - Save the model tokenizer(s) to the specified directory. - - Args: - directory: The directory to save the tokenizer(s) to. - """ - if not hasattr(self, 'cfg'): - raise RuntimeError( - "The model has not been initialized with a tokenizer yet. Please call the model's " - "__init__ and _setup_tokenizer methods first." - ) - - if self.tokenizer_type == 'agg': - for lang in self.tokenizer.langs: - subconfig = self.cfg.tokenizer.langs.get(lang) - new_dir = os.path.join(directory, lang) - self._extract_tokenizer_from_config(subconfig, new_dir) - else: - self._extract_tokenizer_from_config(self.cfg.tokenizer, directory) - - def _extract_tokenizer_from_config(self, tokenizer_cfg: DictConfig, dir: str): - """ - Extracts the tokenizer from the config and write the objects to dir. - The file may be from a local path (new model init) or from a .nemo file (restored model). - If its from a newly initialized model, the file is copied to dir. - If its from a restored model, the file is extracted from the .nemo file and copied to dir. - - Args: - tokenizer_cfg: The tokenizer config to extract the tokenizer from. - dir: The directory to write the tokenizer objects to. - """ - if not os.path.exists(dir): - os.makedirs(dir, exist_ok=True) - - nemo_file_objects = [] - - for k, v in tokenizer_cfg.items(): - # Check if the value is a filepath (new model init) or has `nemo:` in it (restored model) - if isinstance(v, str) and os.path.exists(v): - # local file from first instantiation - loc = robust_copy(v, dir) - logging.info(f"Saved {k} at {loc}") - - if isinstance(v, str) and v.startswith('nemo:'): - nemo_object_name = v[5:] - nemo_file_objects.append(nemo_object_name) - - if len(nemo_file_objects) > 0: - logging.debug(f"Copying the following nemo file objects to {dir}: {nemo_file_objects}") - - if not hasattr(self, 'model_guid'): - raise ValueError( - "The model does not have a model_guid attribute. " - "Please ensure that the model has been restored from a .nemo file." - ) - - appstate = app_state.AppState() - restore_path = appstate.get_model_metadata_from_guid(self.model_guid).restoration_path - if restore_path is None: - raise ValueError( - "The model has not been restored from a .nemo file. Cannot extract the tokenizer " - "as the nemo file cannot be located." - ) - - # Read the nemo file without fully extracting all contents - # we start with an assumption of uncompressed tar, - # which should be true for versions 1.7.0 and above - tar_header = "r:" - try: - tar_test = tarfile.open(restore_path, tar_header) - tar_test.close() - except tarfile.ReadError: - # can be older checkpoint => try compressed tar - tar_header = "r:gz" - tar = tarfile.open(restore_path, tar_header) - - for nemo_object_name in nemo_file_objects: - members = [x for x in tar.getmembers() if nemo_object_name in x.name] - for member in members: - tar.extract(member, dir) - - new_name = member.name.split("_")[1:] - if len(new_name) > 1: - new_name = "_".join(new_name) - else: - new_name = new_name[0] - os.rename(os.path.join(dir, member.name), os.path.join(dir, new_name)) - - logging.info(f"Saved {nemo_object_name} at {os.path.join(dir, new_name)}") - - def _derive_tokenizer_properties(self): - vocab = self.tokenizer.tokenizer.get_vocab() - - self.tokenizer.supports_capitalization = bool(extract_capitalized_tokens_from_vocab(vocab)) - self.tokenizer.supported_punctuation = extract_punctuation_from_vocab(vocab) - - -class ASRModuleMixin(ASRAdapterModelMixin): - """ - ASRModuleMixin is a mixin class added to ASR models in order to add methods that are specific - to a particular instantiation of a module inside of an ASRModel. - - Each method should first check that the module is present within the subclass, and support additional - functionality if the corresponding module is present. - """ - - def change_conv_asr_se_context_window(self, context_window: int, update_config: bool = True): - """ - Update the context window of the SqueezeExcitation module if the provided model contains an - `encoder` which is an instance of `ConvASREncoder`. - - Args: - context_window: An integer representing the number of input timeframes that will be used - to compute the context. Each timeframe corresponds to a single window stride of the - STFT features. - - Say the window_stride = 0.01s, then a context window of 128 represents 128 * 0.01 s - of context to compute the Squeeze step. - update_config: Whether to update the config or not with the new context window. - """ - asr_module_utils.change_conv_asr_se_context_window( - self, context_window=context_window, update_config=update_config - ) - - def change_attention_model( - self, self_attention_model: str = None, att_context_size: List[int] = None, update_config: bool = True - ): - """ - Update the self_attention_model if function is available in encoder. - - Args: - self_attention_model (str): type of the attention layer and positional encoding - - 'rel_pos': - relative positional embedding and Transformer-XL - - 'rel_pos_local_attn': - relative positional embedding and Transformer-XL with local attention using - overlapping windows. Attention context is determined by att_context_size parameter. - - 'abs_pos': - absolute positional embedding and Transformer - - If None is provided, the self_attention_model isn't changed. Defauts to None. - att_context_size (List[int]): List of 2 ints corresponding to left and right attention context sizes, - or None to keep as it is. Defauts to None. - update_config (bool): Whether to update the config or not with the new attention model. - Defaults to True. - """ - if self_attention_model is None and att_context_size is None: - return - - if not hasattr(self, 'encoder'): - logging.info( - "Could not change the self_attention_model in encoder " - "since the model provided does not contain an `encoder` module in its config." - ) - return - - if not hasattr(self.encoder, "change_attention_model"): - logging.info("Model encoder doesn't have a change_attention_model method ") - return - - self.encoder.change_attention_model(self_attention_model, att_context_size, update_config, self.device) - if update_config: - with open_dict(self.cfg): - self.cfg.encoder.self_attention_model = self_attention_model - self.cfg.encoder.att_context_size = att_context_size - - def change_subsampling_conv_chunking_factor( - self, subsampling_conv_chunking_factor: int, update_config: bool = True - ): - """ - Update the conv_chunking_factor (int) if function is available in encoder. - Default is 1 (auto) - Set it to -1 (disabled) or to a specific value (power of 2) if you OOM in the conv subsampling layers - - Args: - conv_chunking_factor (int) - """ - - if not hasattr(self, 'encoder'): - logging.info( - "Could not call the change_subsampling_conv_chunking_factor method in encoder " - "since the model provided does not contain an `encoder` module in its config." - ) - return - - if not hasattr(self.encoder, "change_subsampling_conv_chunking_factor"): - logging.info("Model encoder doesn't have a change_subsampling_conv_chunking_factor method ") - return - - self.encoder.change_subsampling_conv_chunking_factor(subsampling_conv_chunking_factor) - if update_config: - with open_dict(self.cfg): - self.cfg.encoder.subsampling_conv_chunking_factor = subsampling_conv_chunking_factor - - def conformer_stream_step( - self, - processed_signal: Tensor, - processed_signal_length: Tensor = None, - cache_last_channel: Tensor = None, - cache_last_time: Tensor = None, - cache_last_channel_len: Tensor = None, - keep_all_outputs: bool = True, - previous_hypotheses: List[Hypothesis] = None, - previous_pred_out: Tensor = None, - drop_extra_pre_encoded: int = None, - return_transcription: bool = True, - return_log_probs: bool = False, - bypass_pre_encode: bool = False, - ): - """ - It simulates a forward step with caching for streaming purposes. - It supports the ASR models where their encoder supports streaming like Conformer. - Args: - processed_signal: the input audio signals - processed_signal_length: the length of the audios - cache_last_channel: the cache tensor for last channel layers like MHA - cache_last_channel_len: lengths for cache_last_channel - cache_last_time: the cache tensor for last time layers like convolutions - keep_all_outputs: if set to True, would not drop the extra outputs specified by encoder.streaming_cfg.valid_out_len - previous_hypotheses: the hypotheses from the previous step for RNNT models - previous_pred_out: the predicted outputs from the previous step for CTC models - drop_extra_pre_encoded: number of steps to drop from the beginning of the outputs after the downsampling module. This can be used if extra paddings are added on the left side of the input. - return_transcription: whether to decode and return the transcriptions. It can not get disabled for Transducer models. - return_log_probs: whether to return the log probs, only valid for ctc model - - Returns: - greedy_predictions: the greedy predictions from the decoder - all_hyp_or_transcribed_texts: the decoder hypotheses for Transducer models and the transcriptions for CTC models - cache_last_channel_next: the updated tensor cache for last channel layers to be used for next streaming step - cache_last_time_next: the updated tensor cache for last time layers to be used for next streaming step - cache_last_channel_next_len: the updated lengths for cache_last_channel - best_hyp: the best hypotheses for the Transducer models - log_probs: the logits tensor of current streaming chunk, only returned when return_log_probs=True - encoded_len: the length of the output log_probs + history chunk log_probs, only returned when return_log_probs=True - """ - if not isinstance(self, asr_models.EncDecRNNTModel) and not isinstance(self, asr_models.EncDecCTCModel): - raise NotImplementedError(f"stream_step does not support {type(self)}!") - - if not isinstance(self.encoder, StreamingEncoder): - raise NotImplementedError("Encoder of this model does not support streaming!") - - if isinstance(self, asr_models.EncDecRNNTModel) and return_transcription is False: - logging.info( - "return_transcription can not be False for Transducer models as decoder returns the transcriptions too." - ) - - if not isinstance(self, asr_models.EncDecCTCModel) and return_log_probs is True: - logging.info("return_log_probs can only be True for CTC models.") - - ( - encoded, - encoded_len, - cache_last_channel_next, - cache_last_time_next, - cache_last_channel_next_len, - ) = self.encoder.cache_aware_stream_step( - processed_signal=processed_signal, - processed_signal_length=processed_signal_length, - cache_last_channel=cache_last_channel, - cache_last_time=cache_last_time, - cache_last_channel_len=cache_last_channel_len, - keep_all_outputs=keep_all_outputs, - drop_extra_pre_encoded=drop_extra_pre_encoded, - bypass_pre_encode=bypass_pre_encode, - ) - - if isinstance(self, asr_models.EncDecCTCModel) or ( - isinstance(self, asr_models.EncDecHybridRNNTCTCModel) and self.cur_decoder == "ctc" - ): - if hasattr(self, "ctc_decoder"): - decoding = self.ctc_decoding - decoder = self.ctc_decoder - else: - decoding = self.decoding - decoder = self.decoder - - log_probs = decoder(encoder_output=encoded) - predictions_tensor = log_probs.argmax(dim=-1, keepdim=False) - - # Concatenate the previous predictions with the current one to have the full predictions. - # We drop the extra predictions for each sample by using the lengths returned by the encoder (encoded_len) - # Then create a list of the predictions for the batch. The predictions can have different lengths because of the paddings. - greedy_predictions = [] - if return_transcription: - all_hyp_or_transcribed_texts = [] - else: - all_hyp_or_transcribed_texts = None - for preds_idx, preds in enumerate(predictions_tensor): - if encoded_len is None: - preds_cur = predictions_tensor[preds_idx] - else: - preds_cur = predictions_tensor[preds_idx, : encoded_len[preds_idx]] - if previous_pred_out is not None: - greedy_predictions_concat = torch.cat((previous_pred_out[preds_idx], preds_cur), dim=-1) - encoded_len[preds_idx] += len(previous_pred_out[preds_idx]) - else: - greedy_predictions_concat = preds_cur - greedy_predictions.append(greedy_predictions_concat) - - # TODO: make decoding more efficient by avoiding the decoding process from the beginning - if return_transcription: - decoded_out = decoding.ctc_decoder_predictions_tensor( - decoder_outputs=greedy_predictions_concat.unsqueeze(0), - decoder_lengths=encoded_len[preds_idx : preds_idx + 1], - return_hypotheses=False, - ) - all_hyp_or_transcribed_texts.append(decoded_out[0]) - best_hyp = None - else: - best_hyp = self.decoding.rnnt_decoder_predictions_tensor( - encoder_output=encoded, - encoded_lengths=encoded_len, - return_hypotheses=True, - partial_hypotheses=previous_hypotheses, - ) - greedy_predictions = [hyp.y_sequence for hyp in best_hyp] - - all_hyp_or_transcribed_texts = best_hyp - - result = [ - greedy_predictions, - all_hyp_or_transcribed_texts, - cache_last_channel_next, - cache_last_time_next, - cache_last_channel_next_len, - best_hyp, - ] - if return_log_probs: - result.append(log_probs) - result.append(encoded_len) - - return tuple(result) - - @torch.no_grad() - def transcribe_simulate_cache_aware_streaming( - self, - paths2audio_files: List[str], - batch_size: int = 4, - logprobs: bool = False, - return_hypotheses: bool = False, - online_normalization: bool = False, - ): - """ - Args: - paths2audio_files: (a list) of paths to audio files. - batch_size: (int) batch size to use during inference. - Bigger will result in better throughput performance but would use more memory. - logprobs: (bool) pass True to get log probabilities instead of transcripts. - return_hypotheses: (bool) Either return hypotheses or text - With hypotheses can do some postprocessing like getting timestamp or rescoring - online_normalization: (bool) Perform normalization on the run per chunk. - Returns: - A list of transcriptions (or raw log probabilities if logprobs is True) in the same order as paths2audio_files - """ - if paths2audio_files is None or len(paths2audio_files) == 0: - return {} - - if return_hypotheses and logprobs: - raise ValueError( - "Either `return_hypotheses` or `logprobs` can be True at any given time." - "Returned hypotheses will contain the logprobs." - ) - - if not isinstance(self, asr_models.EncDecCTCModel): - raise NotImplementedError(f"simulate streaming does not support {type(self)}!") - - if not isinstance(self.encoder, StreamingEncoder): - raise NotImplementedError("Encoder of this model does not support streaming!") - - data_loader = self._setup_streaming_transcribe_dataloader(paths2audio_files, batch_size, online_normalization) - - total_log_probs = [] - total_texts = [] - - for streaming_buffer in data_loader: - streaming_buffer_iter = iter(streaming_buffer) - batch_size = len(streaming_buffer.streams_length) - cache_last_channel, cache_last_time, cache_last_channel_len = self.encoder.get_initial_cache_state( - batch_size=batch_size - ) - previous_hypotheses = None - pred_out_stream = None - encoded_len = None - transcribed_texts = None - batch_log_probs = [] - - for step_num, (chunk_audio, chunk_lengths) in enumerate(streaming_buffer_iter): - drop_extra_pre_encoded = self.encoder.streaming_cfg.drop_extra_pre_encoded if step_num != 0 else 0 - with torch.inference_mode(): - result = self.conformer_stream_step( - processed_signal=chunk_audio, - processed_signal_length=chunk_lengths, - cache_last_channel=cache_last_channel, - cache_last_time=cache_last_time, - cache_last_channel_len=cache_last_channel_len, - keep_all_outputs=streaming_buffer.is_buffer_empty(), - previous_hypotheses=previous_hypotheses, - previous_pred_out=pred_out_stream, - drop_extra_pre_encoded=drop_extra_pre_encoded, - return_transcription=True, - return_log_probs=logprobs or return_hypotheses, - ) - if logprobs or return_hypotheses: - ( - pred_out_stream, - transcribed_texts, - cache_last_channel, - cache_last_time, - cache_last_channel_len, - previous_hypotheses, - cur_chunk_log_probs, - encoded_len, - ) = result - batch_log_probs.append(cur_chunk_log_probs.cpu()) - else: - ( - pred_out_stream, - transcribed_texts, - cache_last_channel, - cache_last_time, - cache_last_channel_len, - previous_hypotheses, - ) = result - - if logprobs or return_hypotheses: - # concatenate chunk log probs on T dim - batch_log_probs = torch.cat(batch_log_probs, axis=1) - for log_probs, log_prob_len in zip(batch_log_probs, encoded_len): - total_log_probs.append(log_probs[0:log_prob_len]) - - if transcribed_texts is None: - total_texts += [''] * batch_size - else: - total_texts += transcribed_texts - - if logprobs: - return total_log_probs - - if not return_hypotheses: - return total_texts - - hyps = [] - for log_probs, text in zip(total_log_probs, total_texts): - hyps.append(Hypothesis(y_sequence=log_probs, text=text, score=0.0, dec_state=None)) - return hyps - - def _setup_streaming_transcribe_dataloader( - self, paths2audio_files: List[str], batch_size: int, online_normalization=False - ): - """ - Setup function for a temporary data loader which wraps the provided audio file. - - Args: - paths2audio_files: (a list) of paths to audio files. - batch_size: (int) batch size to use during inference. - Bigger will result in better throughput performance but would use more memory. - online_normalization: whether to do online normalization - Returns: - a new batch streaming buffer - """ - from nemo.collections.asr.parts.utils.streaming_utils import CacheAwareStreamingAudioBuffer - - streaming_buffer = CacheAwareStreamingAudioBuffer(model=self, online_normalization=online_normalization) - for sample_idx, sample in enumerate(paths2audio_files): - processed_signal, processed_signal_length, stream_id = streaming_buffer.append_audio_file( - sample, stream_id=-1 - ) - logging.info(f'Added this sample to the buffer: {sample}') - if (sample_idx + 1) % batch_size == 0 or sample_idx == len(paths2audio_files) - 1: - logging.info(f"Starting to stream samples {sample_idx - len(streaming_buffer) + 1} to {sample_idx}...") - yield streaming_buffer - streaming_buffer.reset_buffer() - - -class VerificationMixin(ABC): - @staticmethod - def path2audio_files_to_manifest(paths2audio_files, manifest_filepath): - """ - Takes paths to audio files and manifest filepath and creates manifest file with the audios - Args: - paths2audio_files: paths to audio fragment to be verified - manifest_filepath: path to manifest file to bre created - """ - with open(manifest_filepath, 'w', encoding='utf-8') as fp: - for audio_file in paths2audio_files: - audio_file = audio_file.strip() - entry = {'audio_filepath': audio_file, 'offset': 0.0, 'duration': None, 'text': '-', 'label': 'infer'} - fp.write(json.dumps(entry) + '\n') - - -class DiarizationMixin(VerificationMixin): - @abstractmethod - def diarize(self, paths2audio_files: List[str], batch_size: int = 1) -> List[str]: - """ - Takes paths to audio files and returns speaker labels - Args: - paths2audio_files: paths to audio fragment to be transcribed - - Returns: - Speaker labels - """ - pass diff --git a/nemo/collections/asr/parts/mixins/multitalker_asr_mixins.py b/nemo/collections/asr/parts/mixins/multitalker_asr_mixins.py deleted file mode 100644 index d9629e4ab8981db8086f85ec506310814d31602c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/mixins/multitalker_asr_mixins.py +++ /dev/null @@ -1,279 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from abc import ABC -from typing import Optional - -import torch -import torch.nn as nn -from omegaconf import ListConfig - -from nemo.utils import logging - -__all__ = ['SpeakerKernelMixin'] - - -def get_spk_kernel_class(spk_kernel_type, input_size, d_model, dropout=0.5): - if spk_kernel_type == 'ff': - return nn.Sequential( - nn.Linear(input_size, d_model), nn.ReLU(), nn.Dropout(dropout), nn.Linear(d_model, input_size) - ) - else: - raise ValueError(f"Invalid speaker kernel type: {spk_kernel_type}") - # TODO: conv2d and mha speaker kernel classes - - -class SpeakerKernelMixin(ABC): - """ - Mixin class for models that need speaker kernel functionality. - - This mixin provides: - - Speaker kernel initialization - - Hook attachment for applying speaker kernels at specific encoder layers - - Support for both active and background speaker kernels - - Models using this mixin should have the following config parameters: - - spk_kernel_type: Type of speaker kernel ('mask', 'concat', 'sinusoidal') - - spk_kernel_layers: List of layer indices where to apply speaker kernels - - add_bg_spk_kernel: Whether to add background speaker kernels - """ - - def _init_speaker_kernel_config(self, cfg): - """ - Initialize speaker kernel configuration from model config. - - Args: - cfg: Model configuration containing speaker kernel parameters - """ - # Speaker kernel config - self.spk_kernel_type = cfg.get('spk_kernel_type', None) - self.spk_kernel_layers = cfg.get('spk_kernel_layers', [0]) - self.add_bg_spk_kernel = cfg.get('add_bg_spk_kernel', True) - - # Initialize speaker target containers - self.spk_targets = None - if self.add_bg_spk_kernel: - self.bg_spk_targets = None - - # Initialize speaker kernels - self._init_spk_kernel() - - def _init_spk_kernel(self): - """Initialize speaker kernel modules and register them to encoder layers.""" - if not isinstance(self.spk_kernel_layers, ListConfig): - if self.spk_kernel_type is not None: - raise ValueError(f"spk_kernel_layers must be a list, got {type(self.spk_kernel_layers)}") - return - - # Initialize speaker kernels for each specified layer - hidden_size = self.cfg.model_defaults.enc_hidden - self.spk_kernels = torch.nn.ModuleDict() - if self.add_bg_spk_kernel: - self.bg_spk_kernels = torch.nn.ModuleDict() - - # Create kernel for each layer index - for layer_idx in self.spk_kernel_layers: - self.spk_kernels[str(layer_idx)] = get_spk_kernel_class( - spk_kernel_type=self.spk_kernel_type, - input_size=hidden_size, - d_model=self.cfg.encoder.d_model, - dropout=0.5, - ) - if self.add_bg_spk_kernel: - self.bg_spk_kernels[str(layer_idx)] = get_spk_kernel_class( - spk_kernel_type=self.spk_kernel_type, - input_size=hidden_size, - d_model=self.cfg.encoder.d_model, - dropout=0.5, - ) - - if self.spk_kernels: - logging.info(f"Initialized speaker kernels for layers: {list(self.spk_kernels.keys())}") - self._attach_spk_kernel_hooks() - else: - logging.info("No speaker kernels initialized") - - def _attach_spk_kernel_hooks(self): - """ - Attach speaker kernel hooks to encoder layers. - Speaker kernels will inject the speaker information into the encoder layers. - """ - # Only attach hooks if not already attached - if hasattr(self, 'encoder_hooks'): - return - - self.encoder_hooks = [] - for layer_idx, kernel in self.spk_kernels.items(): - idx = int(layer_idx) - - if idx == 0: - hook = self.encoder.layers[idx].register_forward_pre_hook( - self._get_spk_kernel_hook_pre_layer(layer_idx), with_kwargs=True - ) - - if idx > 0: - # Attach a post-hook after each layer from 0 to 16. - # Since idx > 0, we attach to layer idx-1. - hook = self.encoder.layers[idx - 1].register_forward_hook( - self._get_spk_kernel_hook_post_layer(layer_idx) - ) - self.encoder_hooks.append(hook) - - def _get_spk_kernel_hook_pre_layer(self, layer_idx: str): - """ - Returns a hook function for applying speaker kernel transformation. - - Args: - layer_idx (str): Index of the layer to apply the kernel - - Returns: - callable: Hook function that applies speaker kernel - """ - - def hook_fn(module, args, kwargs): - # Pre-hooks with with_kwargs=True must return a (new_args, new_kwargs) tuple. - # The input tensor is passed as a keyword argument, so we find it in 'kwargs'. - - if 'x' in kwargs: - x = kwargs['x'] - x_spk = self.spk_kernels[layer_idx](self.mask_with_speaker_targets(x, self.spk_targets)) - # residual connection - x = x + x_spk - if self.add_bg_spk_kernel: - x_bg_spk = self.bg_spk_kernels[layer_idx]( - self.mask_with_speaker_targets(x, self.bg_spk_targets, default_value=0.0) - ) - x = x + x_bg_spk - kwargs['x'] = x - elif args: - # Fallback in case the call signature ever changes - x, *rest = args - x_spk = self.spk_kernels[layer_idx](self.mask_with_speaker_targets(x, self.spk_targets)) - # residual connection - x = x + x_spk - if self.add_bg_spk_kernel: - x_bg_spk = self.bg_spk_kernels[layer_idx]( - self.mask_with_speaker_targets(x, self.bg_spk_targets, default_value=0.0) - ) - x = x + x_bg_spk - args = (x, *rest) - - return args, kwargs - - return hook_fn - - def _get_spk_kernel_hook_post_layer(self, layer_idx: str): - """ - Returns a hook function for applying speaker kernel transformation. - - Args: - layer_idx (str): Index of the layer to apply the kernel - - Returns: - callable: Hook function that applies speaker kernel - """ - - def hook_fn(module, input, output): - if self.spk_targets is None: - return output - - if isinstance(output, tuple): - x, *cache = output - else: - x = output - - x_spk = self.spk_kernels[layer_idx](self.mask_with_speaker_targets(x, self.spk_targets)) - # residual connection - x = x + x_spk - - if self.add_bg_spk_kernel: - x_bg_spk = self.bg_spk_kernels[layer_idx]( - self.mask_with_speaker_targets(x, self.bg_spk_targets, default_value=0.0) - ) - x = x + x_bg_spk - - if isinstance(output, tuple): - return (x, *cache) - return x - - return hook_fn - - def _cleanup_speaker_kernel_hooks(self): - """ - Clean up speaker kernel hooks to prevent memory leaks. - Can be called during model cleanup or when switching between modes. - """ - if hasattr(self, 'encoder_hooks'): - for hook in self.encoder_hooks: - try: - hook.remove() - except Exception as e: - logging.warning(f"Failed to remove speaker kernel hook: {e}") - delattr(self, 'encoder_hooks') - logging.info("Speaker kernel hooks cleaned up") - - def set_speaker_targets( - self, spk_targets: Optional[torch.Tensor] = None, bg_spk_targets: Optional[torch.Tensor] = None - ): - """ - Set speaker targets for the model. - - Args: - spk_targets: Main speaker targets tensor - bg_spk_targets: Background speaker targets tensor - """ - self.spk_targets = spk_targets - if self.add_bg_spk_kernel: - self.bg_spk_targets = bg_spk_targets - - def clear_speaker_targets(self): - """Clear speaker targets.""" - self.spk_targets = None - if self.add_bg_spk_kernel: - self.bg_spk_targets = None - - def solve_length_mismatch(self, x: torch.Tensor, mask: torch.Tensor, default_value: float = 1.0): - """ - Solve length mismatch between x and mask. - """ - if mask is None: - mask = torch.ones_like(x[:, :, 0]) * default_value - logging.warning( - f"Mask is None, triggering single speaker mode and assigning all ones with shape: {mask.shape}" - ) - - if mask.shape[1] < x.shape[1]: - # pad zero to the left - mask = torch.nn.functional.pad(mask, (x.shape[1] - mask.shape[1], 0), mode='constant', value=default_value) - - if mask.shape[1] > x.shape[1]: - mask = mask[:, -x.shape[1] :] - - return mask - - def mask_with_speaker_targets(self, x: torch.Tensor, spk_targets: torch.Tensor, default_value: float = 1.0): - """ - Mask the input with speaker targets. - """ - mask = self.solve_length_mismatch(x, spk_targets, default_value) - x_spk = x * mask.unsqueeze(2) - return x_spk - - def concat_with_speaker_targets(self, x: torch.Tensor, spk_targets: torch.Tensor): - """ - Concatenate the input with speaker targets. - """ - mask = self.solve_length_mismatch(x, spk_targets) - x_spk = x * mask.unsqueeze(2) - return x_spk diff --git a/nemo/collections/asr/parts/mixins/streaming.py b/nemo/collections/asr/parts/mixins/streaming.py deleted file mode 100644 index 2db68da5a3d2a0060a73ae320a2b5cdce74005ba..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/mixins/streaming.py +++ /dev/null @@ -1,76 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from abc import ABC, abstractmethod - - -class StreamingEncoder(ABC): - @abstractmethod - def setup_streaming_params( - self, - max_look_ahead: int = 10000, - ): - """ - This function sets the needed values and parameters to perform streaming. The configuration (CacheAwareStreamingConfig) need to be stored in self.streaming_cfg. - The streaming configuration is needed to simulate streaming inference. It would set the following - """ - pass - - @abstractmethod - def get_initial_cache_state(self, batch_size, dtype, device, max_dim): - pass - - @staticmethod - def to_numpy(tensor): - if tensor is None: - return None - return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy() - - def cache_aware_stream_step( - self, - processed_signal, - processed_signal_length=None, - cache_last_channel=None, - cache_last_time=None, - cache_last_channel_len=None, - keep_all_outputs=True, - drop_extra_pre_encoded=None, - bypass_pre_encode=False, - ): - if self.streaming_cfg is None: - self.setup_streaming_params() - if drop_extra_pre_encoded is not None: - prev_drop_extra_pre_encoded = self.streaming_cfg.drop_extra_pre_encoded - self.streaming_cfg.drop_extra_pre_encoded = drop_extra_pre_encoded - else: - prev_drop_extra_pre_encoded = None - - if processed_signal_length is None: - processed_signal_length = processed_signal.new_full(processed_signal.size(0), processed_signal.size(-1)) - - encoder_output = self( - audio_signal=processed_signal, - length=processed_signal_length, - cache_last_channel=cache_last_channel, - cache_last_time=cache_last_time, - cache_last_channel_len=cache_last_channel_len, - bypass_pre_encode=bypass_pre_encode, - ) - - encoder_output = self.streaming_post_process(encoder_output, keep_all_outputs=keep_all_outputs) - - if prev_drop_extra_pre_encoded is not None: - self.streaming_cfg.drop_extra_pre_encoded = prev_drop_extra_pre_encoded - - return encoder_output diff --git a/nemo/collections/asr/parts/mixins/transcription.py b/nemo/collections/asr/parts/mixins/transcription.py deleted file mode 100644 index 7a48b99049b3b82eeff5c0433afffabe74db8f80..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/mixins/transcription.py +++ /dev/null @@ -1,811 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import json -import os -import tempfile -from abc import ABC, abstractmethod -from dataclasses import dataclass -from functools import partial -from typing import Any, Dict, List, Optional, Tuple, Union - -import numpy as np -import torch -from omegaconf import DictConfig -from torch.utils.data import DataLoader, Dataset -from tqdm import tqdm - -from nemo.collections.asr.parts.preprocessing.perturb import process_augmentations -from nemo.collections.asr.parts.preprocessing.segment import AudioSegment, ChannelSelectorType -from nemo.collections.asr.parts.utils import manifest_utils -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis -from nemo.collections.common.data.utils import move_data_to_device -from nemo.utils import logging, logging_mode - -TranscriptionReturnType = Union[List[str], List[Hypothesis], Tuple[List[str]], Tuple[List[Hypothesis]]] -GenericTranscriptionType = Union[List[Any], List[List[Any]], Tuple[Any], Tuple[List[Any]], Dict[str, List[Any]]] - - -@dataclass -class InternalTranscribeConfig: - # Internal values - device: Optional[torch.device] = None - dtype: Optional[torch.dtype] = None - training_mode: bool = False - logging_level: Optional[Any] = None - - # Preprocessor values - dither_value: float = 0.0 - pad_to_value: int = 0 - - # Scratch space - temp_dir: Optional[str] = None - manifest_filepath: Optional[str] = None - - -@dataclass -class TranscribeConfig: - use_lhotse: bool = True - batch_size: int = 4 - return_hypotheses: bool = False - num_workers: Optional[int] = None - channel_selector: ChannelSelectorType = None - augmentor: Optional[DictConfig] = None - timestamps: Optional[bool] = None # returns timestamps for each word and segments if model supports punctuations - verbose: bool = True - - # Utility - partial_hypothesis: Optional[List[Any]] = None - - _internal: Optional[InternalTranscribeConfig] = None - - -def get_value_from_transcription_config(trcfg, key, default): - """ - Utility function to get a value from the transcription config. - If the value is not present in the transcription config, the default value is returned. - - Args: - trcfg: A dataclass that represents the transcription config. - key: The name of the arg to retrieve. - default: The default value to return if the key is not present in the transcription config. - - Returns: - The value of the key in the transcription config or the default value. - """ - if hasattr(trcfg, key): - return getattr(trcfg, key) - else: - logging.debug( - f"Using default value of {default} for {key} because it is not present \ - in the transcription config {trcfg}." - ) - return default - - -class TranscriptionTensorDataset(Dataset): - def __init__(self, config: Dict[str, Any]): - super().__init__() - self.audio_tensors = config['audio_tensors'] - self.channel_selector = config['channel_selector'] - self.augmentor_cfg = config.get('augmentor', None) - self.sample_rate = config['sample_rate'] - - self.pad_min_duration = config.get('pad_min_duration', 1.0) - self.pad_direction = config.get('pad_direction', 'both') - self.pad_min_samples = int(self.pad_min_duration * self.sample_rate) - - if self.augmentor_cfg is not None: - self.augmentor = process_augmentations(self.augmentor_cfg, global_rank=0, world_size=1) - else: - self.augmentor = None - - self.length = len(self.audio_tensors) - - def __getitem__(self, index): - if index >= self.length: - raise IndexError(f"Index {index} out of range for dataset of size {self.length}") - - return self.get_item(index) - - def __len__(self): - return self.length - - def _pad_audio(self, samples: torch.Tensor) -> torch.Tensor: - """Pad audio to minimum duration, matching Lhotse dataloader behavior.""" - current_len = samples.shape[0] - if current_len >= self.pad_min_samples: - return samples - - pad_total = self.pad_min_samples - current_len - if self.pad_direction == 'both': - pad_left = pad_total // 2 - pad_right = pad_total - pad_left - elif self.pad_direction == 'left': - pad_left = pad_total - pad_right = 0 - else: # right (default) - pad_left = 0 - pad_right = pad_total - samples = torch.nn.functional.pad(samples, (pad_left, pad_right), mode='constant', value=0.0) - return samples - - def get_item(self, index): - samples = self.audio_tensors[index] - - if self.augmentor is not None: - logging.warning( - "Audio Augmentations are being applied during inference by moving the tensor onto CPU. " - "This is highly inefficient and therefore not recommended.", - mode=logging_mode.ONCE, - ) - - original_dtype = samples.dtype - samples = samples.to(device='cpu', dtype=torch.float32).numpy() - segment = AudioSegment( - samples, self.sample_rate, target_sr=self.sample_rate, channel_selector=self.channel_selector - ) - samples = self.augmentor.perturb(segment) - samples = torch.tensor(samples.samples, dtype=original_dtype) - - samples = self._pad_audio(samples) - seq_len = torch.tensor(samples.shape[0], dtype=torch.long) - - # Typically NeMo ASR models expect the mini-batch to be a 4-tuple of (audio, audio_len, text, text_len). - # For inference, we set text and text_len to None to not disrupt the shape of the tuple. - return samples, seq_len, None, None - - -class TranscriptionMixin(ABC): - """ - An abstract class for transcribe-able models. - - Creates a template function `transcribe()` that provides an interface to perform transcription of audio tensors or - filepaths. - - The following abstract classes must be implemented by the subclass: - - - `_transcribe_input_manifest_processing()`: - Process the provided input arguments (filepaths only) and return a - config dict for the dataloader. The data loader is should generally operate on NeMo manifests. - - - `_setup_transcribe_dataloader()`: - Setup the dataloader for transcription. Receives the output from - `_transcribe_input_manifest_processing()`. - - - `_transcribe_forward()`: - Implements the model's custom forward pass to return outputs that are processed by - `_transcribe_output_processing()`. - - - `_transcribe_output_processing()`: - Implements the post processing of the model's outputs to return the results to - the user. The result can be a list of objects, list of list of objects, tuple of objects, tuple of list of - objects, or a dict of list of objects. - - """ - - @torch.inference_mode() - def transcribe( - self, - audio: Union[str, List[str], np.ndarray, DataLoader], - use_lhotse: bool = True, - batch_size: int = 4, - return_hypotheses: bool = False, - num_workers: int = 0, - channel_selector: Optional[ChannelSelectorType] = None, - augmentor: DictConfig = None, - verbose: bool = True, - timestamps: Optional[bool] = None, - override_config: Optional[TranscribeConfig] = None, - **config_kwargs, - ) -> GenericTranscriptionType: - """ - Template function that defines the execution strategy for transcribing audio. - - Args: - audio: (a single or list) of paths to audio files or a np.ndarray audio array. - Can also be a dataloader object that provides values that can be consumed by the model. - Recommended length per file is between 5 and 25 seconds. - But it is possible to pass a few hours long file if enough GPU memory is available. - use_lhotse: (bool) If audio is not a dataloder, defines whether to create a lhotse dataloader or a - non-lhotse dataloader. - batch_size: (int) batch size to use during inference. - Bigger will result in better throughput performance but would use more memory. - return_hypotheses: (bool) Either return hypotheses or text - With hypotheses can do some postprocessing like getting timestamp or rescoring - num_workers: (int) number of workers for DataLoader - 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. - augmentor: (DictConfig): Augment audio samples during transcription if augmentor is applied. - verbose: (bool) whether to display tqdm progress bar - timestamps: Optional(Bool): timestamps will be returned if set to True as part of hypothesis object - (output.timestep['segment']/output.timestep['word']). Refer to `Hypothesis` class for more details. - Default is None and would retain the previous state set by using self.change_decoding_strategy(). - override_config: (Optional[TranscribeConfig]) override transcription config pre-defined by the user. - **Note**: All other arguments in the function will be ignored if override_config is passed. - You should call this argument as `model.transcribe(audio, override_config=TranscribeConfig(...))`. - **config_kwargs: (Optional[Dict]) additional arguments to override the default TranscribeConfig. - Note: If override_config is passed, these arguments will be ignored. - - Returns: - Output is defined by the subclass implementation of `TranscriptionMixin._transcribe_output_processing()`. - It can be: - - - List[str/Hypothesis] - - - List[List[str/Hypothesis]] - - - Tuple[str/Hypothesis] - - - Tuple[List[str/Hypothesis]] - - - Dict[str, List[str/Hypothesis]] - """ - - if override_config is None: - transcribe_cfg = TranscribeConfig( - use_lhotse=use_lhotse, - batch_size=batch_size, - return_hypotheses=return_hypotheses, - num_workers=num_workers, - channel_selector=channel_selector, - augmentor=augmentor, - verbose=verbose, - timestamps=timestamps, - **config_kwargs, - ) - else: - if not hasattr(override_config, '_internal'): - raise ValueError( - "`transcribe_cfg must have an `_internal` argument, which must be of an object of type " - "InternalTranscribeConfig or its subclass." - ) - - if override_config._internal is None: - override_config._internal = InternalTranscribeConfig() - - transcribe_cfg = override_config - - # Add new internal config - if transcribe_cfg._internal is None: - transcribe_cfg._internal = InternalTranscribeConfig() - else: - # Check if internal config is valid - if not isinstance(transcribe_cfg._internal, InternalTranscribeConfig): - raise ValueError( - "`transcribe_cfg._internal` must be of an object of type InternalTranscribeConfig or " - "its subclass" - ) - - # Hold the results here - results = None # type: GenericTranscriptionType - - try: - generator = self.transcribe_generator(audio, override_config=transcribe_cfg) - - for processed_outputs in generator: - # Store results - if isinstance(processed_outputs, list): - # Create a results of the same type as each element in processed_outputs - if results is None: - results = [] - - results.extend(processed_outputs) - - elif isinstance(processed_outputs, dict): - # Create a results of the same type as each element in processed_outputs - if results is None: - results = processed_outputs - else: - for k, v in processed_outputs.items(): - results[k].extend(v) - - elif isinstance(processed_outputs, tuple): - # Create a results of the same type as each element in processed_outputs - if results is None: - results = tuple([[] for _ in processed_outputs]) - - # If nested list structure - if isinstance(processed_outputs[0], list): - for i, processed_output in enumerate(processed_outputs): - results[i].extend(processed_output) - else: - # If flat list structure - if len(processed_outputs) != len(results): - raise RuntimeError( - f"The number of elements in the result ({len(results)}) does not " - f"match the results of the current batch ({len(processed_outputs)})." - ) - - for i, processed_output in enumerate(processed_outputs): - results[i].append(processed_output) - - else: - raise NotImplementedError( - "Given output result for transcription is not supported. " - "Please return a list of results, list of list of results, " - "a dict of list of results, or " - "a tuple of list of results." - ) - except StopIteration: - pass - - return results - - def transcribe_generator(self, audio, override_config: Optional[TranscribeConfig]): - """ - A generator version of `transcribe` function. - """ - - if override_config is None: - override_config = TranscribeConfig() - - if not hasattr(override_config, '_internal'): - raise ValueError( - "`transcribe_cfg must have an `_internal` argument, which must be of an object of type " - "InternalTranscribeConfig or its subclass." - ) - - # Add new internal config - if override_config._internal is None: - override_config._internal = InternalTranscribeConfig() - else: - # Check if internal config is valid - if not isinstance(override_config._internal, InternalTranscribeConfig): - raise ValueError( - "`transcribe_cfg._internal` must be of an object of type InternalTranscribeConfig or " - "its subclass" - ) - - transcribe_cfg = override_config - - try: - # Initialize and assert the transcription environment - self._transcribe_on_begin(audio, transcribe_cfg) - - # Work in tmp directory - will store manifest file there - with tempfile.TemporaryDirectory() as tmpdir: - transcribe_cfg._internal.temp_dir = tmpdir - - # Create a DataLoader if not already present - if not isinstance(audio, DataLoader): - dataloader = self._transcribe_input_processing(audio, transcribe_cfg) - else: - dataloader = audio - - if hasattr(transcribe_cfg, 'verbose'): - verbose = transcribe_cfg.verbose - else: - verbose = True - - for test_batch in tqdm(dataloader, desc="Transcribing", disable=not verbose): - # Move batch to device - test_batch = move_data_to_device(test_batch, transcribe_cfg._internal.device) - # Run forward pass - model_outputs = self._transcribe_forward(test_batch, transcribe_cfg) - processed_outputs = self._transcribe_output_processing(model_outputs, transcribe_cfg) - - # clear up memory - del test_batch, model_outputs - - # Yield results if generator - yield processed_outputs - - del processed_outputs - - finally: - # set mode back to its original value - self._transcribe_on_end(transcribe_cfg) - - """ - Transcribe Execution Flow - """ - - def _transcribe_on_begin(self, audio, trcfg: TranscribeConfig): - """ - Internal function to setup the model for transcription. Perform all setup and pre-checks here. - - Args: - audio: Of type `GenericTranscriptionType` - trcfg: The transcription config dataclass. Subclasses can change this to a different dataclass if needed. - """ - if audio is None: - return {} - - if isinstance(audio, (str, np.ndarray, torch.Tensor)): - audio = [audio] - - if isinstance(audio, list) and len(audio) == 0: - return {} - - _params = next(self.parameters()) - if trcfg._internal.device is None: - trcfg._internal.device = _params.device - - if trcfg._internal.dtype is None: - trcfg._internal.dtype = _params.dtype - - # Set num_workers - num_workers = get_value_from_transcription_config(trcfg, 'num_workers', default=0) - - if num_workers is None: - _batch_size = get_value_from_transcription_config(trcfg, 'batch_size', default=4) - num_workers = min(_batch_size, os.cpu_count() - 1) - - # Assign num_workers if available as key in trcfg - if hasattr(trcfg, 'num_workers'): - trcfg.num_workers = num_workers - - # Model's mode and device - trcfg._internal.training_mode = self.training - - # Switch model to evaluation mode - if hasattr(self, 'preprocessor'): - if hasattr(self.preprocessor, 'featurizer') and hasattr(self.preprocessor.featurizer, 'dither'): - trcfg._internal.dither_value = self.preprocessor.featurizer.dither - self.preprocessor.featurizer.dither = 0.0 - - if hasattr(self.preprocessor, 'featurizer') and hasattr(self.preprocessor.featurizer, 'pad_to'): - trcfg._internal.pad_to_value = self.preprocessor.featurizer.pad_to - self.preprocessor.featurizer.pad_to = 0 - - # Switch model to evaluation mode - self.eval() - - # Disable logging - trcfg._internal.logging_level = logging.get_verbosity() - logging.set_verbosity(logging.WARNING) - - def _transcribe_input_processing(self, audio, trcfg: TranscribeConfig): - """ - Internal function to process the input audio data and return a DataLoader. This function is called by - `transcribe()` and `transcribe_generator()` to setup the input data for transcription. - - Args: - audio: Of type `GenericTranscriptionType` - trcfg: The transcription config dataclass. Subclasses can change this to a different dataclass if needed. - - Returns: - A DataLoader object that is used to iterate over the input audio data. - """ - if isinstance(audio, (list, tuple)): - if len(audio) == 0: - raise ValueError("Input `audio` is empty") - else: - audio = [audio] - - # Check if audio is a list of strings (filepaths or manifests) - if isinstance(audio[0], str): - if len(audio) == 1 and audio[0].endswith('.json') or audio[0].endswith('.jsonl'): - # Assume it is a path to a manifest file - trcfg._internal.manifest_filepath = audio[0] - audio = manifest_utils.read_manifest(audio[0]) - - audio_files = list(audio) - - tmp_dir = trcfg._internal.temp_dir - ds_config = self._transcribe_input_manifest_processing(audio_files, tmp_dir, trcfg) - - temp_dataloader = self._setup_transcribe_dataloader(ds_config) - return temp_dataloader - - # Check if audio is a list of numpy or torch tensors - elif isinstance(audio[0], (np.ndarray, torch.Tensor)): - audio_tensors = list(audio) - - # Convert numpy tensors to torch tensors - if any([isinstance(_tensor, np.ndarray) for _tensor in audio_tensors]): - audio_tensors = [ - torch.as_tensor(audio_tensor) if isinstance(audio_tensor, np.ndarray) else audio_tensor - for audio_tensor in audio_tensors - ] - - tmp_dir = trcfg._internal.temp_dir - ds_config = self._transcribe_input_tensor_processing(audio_tensors, tmp_dir, trcfg) - - temp_dataloader = self._setup_transcribe_tensor_dataloader(ds_config, trcfg) - return temp_dataloader - - else: - raise ValueError( - f"Input `audio` is of type {type(audio[0])}. " - "Only `str` (path to audio file), `np.ndarray`, and `torch.Tensor` " - "are supported as input." - ) - - def _transcribe_input_tensor_processing( - self, audio_tensors: List[Union[np.ndarray, torch.Tensor]], temp_dir: str, trcfg: TranscribeConfig - ): - """ - Internal function to process the input audio tensors and return a config dict for the dataloader. - - Args: - audio_tensors: A list of numpy or torch tensors. The user must ensure that they satisfy the correct - sample rate and channel format. - temp_dir: A temporary directory to store intermediate files. - trcfg: The transcription config dataclass. Subclasses can change this to a different dataclass if needed. - - Returns: - A config dict that is used to setup the dataloader for transcription. - """ - # Check if sample rate is set - sample_rate = None - if hasattr(self, 'cfg') and 'sample_rate' in self.cfg: - sample_rate = self.cfg.sample_rate - elif hasattr(self, 'sample_rate'): - sample_rate = self.sample_rate - - if sample_rate is None: - raise RuntimeError( - "Provided `audio` data contains numpy or torch tensors, however the class " - "does not have `sample_rate` attribute. Please set `sample_rate` attribute to the model explicitly." - ) - - ds_config = { - 'use_lhotse': get_value_from_transcription_config(trcfg, 'use_lhotse', True), - 'audio_tensors': audio_tensors, - 'batch_size': get_value_from_transcription_config(trcfg, 'batch_size', 4), - 'temp_dir': temp_dir, - 'num_workers': get_value_from_transcription_config(trcfg, 'num_workers', 0), - 'channel_selector': get_value_from_transcription_config(trcfg, 'channel_selector', None), - 'sample_rate': sample_rate, - 'pad_min_duration': get_value_from_transcription_config(trcfg, 'pad_min_duration', 1.0), - 'pad_direction': get_value_from_transcription_config(trcfg, 'pad_direction', 'both'), - } - - augmentor = get_value_from_transcription_config(trcfg, 'augmentor', None) - if augmentor: - ds_config['augmentor'] = augmentor - - return ds_config - - @abstractmethod - def _transcribe_input_manifest_processing( - self, audio_files: List[str], temp_dir: str, trcfg: TranscribeConfig - ) -> Dict[str, Any]: - """ - Internal function to process the input audio filepaths and return a config dict for the dataloader. - - Args: - audio_files: A list of string filepaths for audio files, or a single string filepath for a manifest file. - temp_dir: A temporary directory to store intermediate files. - trcfg: The transcription config dataclass. Subclasses can change this to a different dataclass if needed. - - Returns: - A config dict that is used to setup the dataloader for transcription. - """ - pass - - @abstractmethod - def _setup_transcribe_dataloader(self, config: Dict) -> DataLoader: - """ - Internal function to setup the dataloader for transcription. This function is called by - `transcribe()` and `transcribe_generator()` to setup the input data for transcription. - - Args: - config: A config dict that is used to setup the dataloader for transcription. It can be generated either - by `_transcribe_input_manifest_processing()` or `_transcribe_input_tensor_processing()`. - - Returns: - A DataLoader object that is used to iterate over the input audio data. - """ - pass - - @abstractmethod - def _transcribe_forward(self, batch: Any, trcfg: TranscribeConfig): - """ - Internal function to perform the model's custom forward pass to return outputs that are processed by - `_transcribe_output_processing()`. - This function is called by `transcribe()` and `transcribe_generator()` to perform the model's forward pass. - - Args: - batch: A batch of input data from the data loader that is used to perform the model's forward pass. - trcfg: The transcription config dataclass. Subclasses can change this to a different dataclass if needed. - - Returns: - The model's outputs that are processed by `_transcribe_output_processing()`. - """ - pass - - @abstractmethod - def _transcribe_output_processing(self, outputs, trcfg: TranscribeConfig) -> GenericTranscriptionType: - """ - Internal function to process the model's outputs to return the results to the user. This function is called by - `transcribe()` and `transcribe_generator()` to process the model's outputs. - - Args: - outputs: The model's outputs that are processed by `_transcribe_forward()`. - trcfg: The transcription config dataclass. Subclasses can change this to a different dataclass if needed. - - Returns: - The output can be a list of - objects, list of list of objects, tuple of objects, tuple of list of objects, or a dict of list of objects. - Its type is defined in `TranscriptionReturnType`. - """ - pass - - def _transcribe_on_end(self, trcfg: TranscribeConfig): - """ - Internal function to teardown the model after transcription. Perform all teardown and post-checks here. - - Args: - trcfg: The transcription config dataclass. Subclasses can change this to a different dataclass if needed. - """ - # set mode back to its original value - self.train(mode=trcfg._internal.training_mode) - - if hasattr(self, 'preprocessor'): - if hasattr(self.preprocessor, 'featurizer') and hasattr(self.preprocessor.featurizer, 'dither'): - self.preprocessor.featurizer.dither = trcfg._internal.dither_value - - if hasattr(self.preprocessor, 'featurizer') and hasattr(self.preprocessor.featurizer, 'pad_to'): - self.preprocessor.featurizer.pad_to = trcfg._internal.pad_to_value - - if trcfg._internal.logging_level is not None: - logging.set_verbosity(trcfg._internal.logging_level) - - def _setup_transcribe_tensor_dataloader(self, config: Dict, trcfg: TranscribeConfig) -> DataLoader: - """ - Internal function to setup the dataloader for transcription. This function is called by - `transcribe()` and `transcribe_generator()` to setup the input data for transcription. - - Args: - config: A config dict that is used to setup the dataloader for transcription. It can be generated either - by `_transcribe_input_manifest_processing()` or `_transcribe_input_tensor_processing()`. - trcfg: The transcription config dataclass. Subclasses can change this to a different dataclass if needed. - - Returns: - A DataLoader object that is used to iterate over the input audio data. - """ - dataset = TranscriptionTensorDataset(config) - - # Import collate function here to avoid circular imports - from nemo.collections.asr.data.audio_to_text import _speech_collate_fn - - # Calculate pad id - if hasattr(self, 'tokenizer') and hasattr(self.tokenizer, 'pad_id'): - pad_id = self.tokenizer.pad_id - elif hasattr(self, 'transcribe_pad_id'): - logging.info("Pad id is explicitly set to `model.transcribe_pad_id` = {}".format(self.transcribe_pad_id)) - pad_id = self.transcribe_pad_id - else: - logging.info( - "Pad id is being set to 0 because it could not be resolved from the tokenizer. " - "This can happen for various reasons, especially for character based models. " - "If pad id is incorrect, please provide the pad id explicitly by setting " - "`model.transcribe_pad_id`." - ) - pad_id = 0 - - return DataLoader( - dataset=dataset, - shuffle=False, - batch_size=config['batch_size'], - num_workers=config['num_workers'], - pin_memory=False, - drop_last=False, - collate_fn=partial(_speech_collate_fn, pad_id=pad_id), - ) - - -class ASRTranscriptionMixin(TranscriptionMixin): - """ - An abstract class for ASR models that can transcribe audio. This class is a subclass of `TranscriptionMixin` that - implements the default implementation of common abstract methods among the speech recognition model classes. - - The following abstract classes must be implemented by the subclass: - - - _transcribe_forward(): - Implements the model's custom forward pass to return outputs that are processed by - `_transcribe_output_processing()`. - - - _transcribe_output_processing(): - Implements the post processing of the model's outputs to return the results to - the user. The result can be a list of objects, list of list of objects, tuple of objects, tuple of list of - """ - - def _transcribe_input_manifest_processing( - self, audio_files: List[str], temp_dir: str, trcfg: TranscribeConfig - ) -> Dict[str, Any]: - """ - Internal function to process the input audio filepaths and return a config dict for the dataloader. - Specializes to ASR models which can have Encoder-Decoder-Joint architectures. - - Args: - audio_files: A list of string filepaths for audio files. - temp_dir: A temporary directory to store intermediate files. - trcfg: The transcription config dataclass. Subclasses can change this to a different dataclass if needed. - - Returns: - A config dict that is used to setup the dataloader for transcription. - """ - with open(os.path.join(temp_dir, 'manifest.json'), 'w', encoding='utf-8') as fp: - for audio_file in audio_files: - if isinstance(audio_file, str): - entry = {'audio_filepath': audio_file, 'duration': 100000, 'text': ''} - fp.write(json.dumps(entry) + '\n') - elif isinstance(audio_file, dict): - fp.write(json.dumps(audio_file) + '\n') - else: - raise ValueError( - f"Input `audio` is of type {type(audio_file)}. " - "Only `str` (path to audio file) or `dict` are supported as input." - ) - - ds_config = { - 'use_lhotse': get_value_from_transcription_config(trcfg, 'use_lhotse', True), - 'paths2audio_files': audio_files, - 'batch_size': get_value_from_transcription_config(trcfg, 'batch_size', 4), - 'temp_dir': temp_dir, - 'num_workers': get_value_from_transcription_config(trcfg, 'num_workers', 0), - 'channel_selector': get_value_from_transcription_config(trcfg, 'channel_selector', None), - 'text_field': get_value_from_transcription_config(trcfg, 'text_field', 'text'), - 'lang_field': get_value_from_transcription_config(trcfg, 'lang_field', 'lang'), - } - - augmentor = get_value_from_transcription_config(trcfg, 'augmentor', None) - if augmentor: - ds_config['augmentor'] = augmentor - - return ds_config - - def _transcribe_on_begin(self, audio, trcfg: TranscribeConfig): - """ - Internal function to setup the model for transcription. Perform all setup and pre-checks here. - - Args: - audio: Of type `GenericTranscriptionType` - trcfg: The transcription config dataclass. Subclasses can change this to a different dataclass if needed. - """ - super()._transcribe_on_begin(audio, trcfg) - - # Freeze the encoder and decoder modules - if hasattr(self, 'encoder'): - self.encoder.freeze() - - if hasattr(self, 'decoder'): - self.decoder.freeze() - - if hasattr(self, 'joint'): - self.joint.freeze() - - def _transcribe_on_end(self, trcfg: TranscribeConfig): - """ - Internal function to teardown the model after transcription. Perform all teardown and post-checks here. - - Args: - trcfg: The transcription config dataclass. Subclasses can change this to a different dataclass if needed. - """ - super()._transcribe_on_end(trcfg) - - # Unfreeze the encoder and decoder modules - if hasattr(self, 'encoder'): - self.encoder.unfreeze(partial=True) - - if hasattr(self, 'decoder'): - self.decoder.unfreeze(partial=True) - - if hasattr(self, 'joint'): - self.joint.unfreeze(partial=True) - - @classmethod - def get_transcribe_config(cls) -> TranscribeConfig: - """ - Utility method that returns the default config for transcribe() function. - - Returns: - A dataclass - """ - return TranscribeConfig() diff --git a/nemo/collections/asr/parts/numba/__init__.py b/nemo/collections/asr/parts/numba/__init__.py deleted file mode 100644 index 77a23cf78c022fac041754632f0dfee3b7defa82..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/numba/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.asr.parts.numba.rnnt_loss.rnnt_pytorch import RNNTLossNumba diff --git a/nemo/collections/asr/parts/numba/rnnt_loss/__init__.py b/nemo/collections/asr/parts/numba/rnnt_loss/__init__.py deleted file mode 100644 index 055d7aeb5fd9caf2960b4a70b76be664671e1bad..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/numba/rnnt_loss/__init__.py +++ /dev/null @@ -1,20 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.asr.parts.numba.rnnt_loss.rnnt import rnnt_loss_cpu, rnnt_loss_gpu -from nemo.collections.asr.parts.numba.rnnt_loss.rnnt_pytorch import ( - MultiblankRNNTLossNumba, - RNNTLossNumba, - TDTLossNumba, -) diff --git a/nemo/collections/asr/parts/numba/rnnt_loss/rnnt.py b/nemo/collections/asr/parts/numba/rnnt_loss/rnnt.py deleted file mode 100644 index 046aea425e2050d30726a87f8f7369469ba04dfc..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/numba/rnnt_loss/rnnt.py +++ /dev/null @@ -1,483 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Copyright 2018-2019, Mingkun Huang -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import multiprocessing - -import torch -from numba import cuda - -from nemo.collections.asr.parts.numba.rnnt_loss.utils import global_constants, rnnt_helper -from nemo.collections.asr.parts.numba.rnnt_loss.utils.cpu_utils import cpu_rnnt -from nemo.collections.asr.parts.numba.rnnt_loss.utils.cuda_utils import gpu_rnnt - - -def rnnt_loss_cpu( - acts: torch.Tensor, - labels: torch.Tensor, - input_lengths: torch.Tensor, - label_lengths: torch.Tensor, - costs: torch.Tensor, - grads: torch.Tensor, - blank_label: int, - fastemit_lambda: float, - clamp: float, - num_threads: int, -): - """ - Wrapper method for accessing CPU RNNT loss. - - CPU implementation ported from [HawkAaron/warp-transducer](https://github.com/HawkAaron/warp-transducer). - - Args: - acts: Activation tensor of shape [B, T, U, V+1]. - labels: Ground truth labels of shape [B, U]. - input_lengths: Lengths of the acoustic sequence as a vector of ints [B]. - label_lengths: Lengths of the target sequence as a vector of ints [B]. - costs: Zero vector of length [B] in which costs will be set. - grads: Zero tensor of shape [B, T, U, V+1] where the gradient will be set. - blank_label: Index of the blank token in the vocabulary. - fastemit_lambda: Float scaling factor for FastEmit regularization. Refer to - FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization. - clamp: Float value. When set to value >= 0.0, will clamp the gradient to [-clamp, clamp]. - num_threads: Number of threads for OpenMP. - """ - # aliases - log_probs = acts - flat_labels = labels - - minibatch_size = log_probs.shape[0] - maxT = log_probs.shape[1] - maxU = log_probs.shape[2] - alphabet_size = log_probs.shape[3] - - if num_threads < 0: - num_threads = multiprocessing.cpu_count() - - num_threads = max(1, num_threads) # have to use at least 1 thread - - gpu_size, status = rnnt_helper.get_workspace_size(maxT, maxU, minibatch_size, gpu=False) - if status != global_constants.RNNTStatus.RNNT_STATUS_SUCCESS: - raise RuntimeError("Invalid parameter passed when calculating working space memory") - - cpu_workspace = torch.zeros(gpu_size, device=log_probs.device, dtype=log_probs.dtype, requires_grad=False) - - ### VIEW TENSORS AS VECTORS FOR POINTER INDEXING ### - log_probs, acts_shape = rnnt_helper.flatten_tensor(log_probs) - flat_labels, labels_shape = rnnt_helper.flatten_tensor(flat_labels) - - wrapper = cpu_rnnt.CPURNNT( - minibatch=minibatch_size, - maxT=maxT, - maxU=maxU, - alphabet_size=alphabet_size, - workspace=cpu_workspace, - blank=blank_label, - fastemit_lambda=fastemit_lambda, - clamp=clamp, - num_threads=num_threads, - batch_first=True, - ) - - if grads is None: - status = wrapper.score_forward( - log_probs=log_probs.data, - costs=costs, - flat_labels=flat_labels.data, - label_lengths=label_lengths.data, - input_lengths=input_lengths.data, - ) - - if status != global_constants.RNNTStatus.RNNT_STATUS_SUCCESS: - raise RuntimeError("Could not calculate forward scores") - - else: - ### FLATTEN GRAD TENSOR ### - grads, grads_shape = rnnt_helper.flatten_tensor(grads) - - status = wrapper.cost_and_grad( - log_probs=log_probs.data, - grads=grads.data, - costs=costs, - flat_labels=flat_labels.data, - label_lengths=label_lengths.data, - input_lengths=input_lengths.data, - ) - - if status != global_constants.RNNTStatus.RNNT_STATUS_SUCCESS: - raise RuntimeError("Could not calculate forward scores") - - del cpu_workspace, wrapper - return True - - -def rnnt_loss_gpu( - acts: torch.Tensor, - labels: torch.Tensor, - input_lengths: torch.Tensor, - label_lengths: torch.Tensor, - costs: torch.Tensor, - grads: torch.Tensor, - blank_label: int, - fastemit_lambda: float, - clamp: float, - num_threads: int, -): - """ - Wrapper method for accessing GPU RNNT loss. - - CUDA implementation ported from [HawkAaron/warp-transducer](https://github.com/HawkAaron/warp-transducer). - - Args: - acts: Activation tensor of shape [B, T, U, V+1]. - labels: Ground truth labels of shape [B, U]. - input_lengths: Lengths of the acoustic sequence as a vector of ints [B]. - label_lengths: Lengths of the target sequence as a vector of ints [B]. - costs: Zero vector of length [B] in which costs will be set. - grads: Zero tensor of shape [B, T, U, V+1] where the gradient will be set. - blank_label: Index of the blank token in the vocabulary. - fastemit_lambda: Float scaling factor for FastEmit regularization. Refer to - FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization. - clamp: Float value. When set to value >= 0.0, will clamp the gradient to [-clamp, clamp]. - num_threads: Number of threads for OpenMP. - """ - minibatch_size = acts.shape[0] - maxT = acts.shape[1] - maxU = acts.shape[2] - alphabet_size = acts.shape[3] - - if hasattr(cuda, 'external_stream'): - stream = cuda.external_stream(torch.cuda.current_stream(acts.device).cuda_stream) - else: - stream = cuda.default_stream() - - if num_threads < 0: - num_threads = multiprocessing.cpu_count() - - num_threads = max(1, num_threads) # have to use at least 1 thread - - gpu_size, status = rnnt_helper.get_workspace_size(maxT, maxU, minibatch_size, gpu=True) - if status != global_constants.RNNTStatus.RNNT_STATUS_SUCCESS: - raise RuntimeError("Invalid parameter passed when calculating working space memory") - - # Select GPU index - cuda.select_device(acts.device.index) - gpu_workspace = torch.zeros(gpu_size, device=acts.device, dtype=torch.float32, requires_grad=False) - - ### VIEW TENSORS AS VECTORS FOR POINTER INDEXING ### - acts, acts_shape = rnnt_helper.flatten_tensor(acts) - - wrapper = gpu_rnnt.GPURNNT( - minibatch=minibatch_size, - maxT=maxT, - maxU=maxU, - alphabet_size=alphabet_size, - workspace=gpu_workspace, - blank=blank_label, - fastemit_lambda=fastemit_lambda, - clamp=clamp, - num_threads=num_threads, - stream=stream, - ) - - if grads is None: - status = wrapper.score_forward( - acts=acts.data, - costs=costs.data, - pad_labels=labels.data, - label_lengths=label_lengths.data, - input_lengths=input_lengths.data, - ) - - if status != global_constants.RNNTStatus.RNNT_STATUS_SUCCESS: - raise RuntimeError("Could not calculate forward scores") - - else: - ### FLATTEN GRAD TENSOR ### - grads, grads_shape = rnnt_helper.flatten_tensor(grads) - - status = wrapper.cost_and_grad( - acts=acts.data, - grads=grads.data, - costs=costs.data, - pad_labels=labels.data, - label_lengths=label_lengths.data, - input_lengths=input_lengths.data, - ) - - if status != global_constants.RNNTStatus.RNNT_STATUS_SUCCESS: - raise RuntimeError("Could not calculate forward scores") - - del gpu_workspace, wrapper - return True - - -def tdt_loss_gpu( - label_acts: torch.Tensor, - duration_acts: torch.Tensor, - labels: torch.Tensor, - input_lengths: torch.Tensor, - label_lengths: torch.Tensor, - costs: torch.Tensor, - label_grads: torch.Tensor, - duration_grads: torch.Tensor, - blank_label: int, - durations: list, - fastemit_lambda: float, - clamp: float, - num_threads: int, - sigma: float, - omega: float, -): - """ - Wrapper method for accessing GPU TDT loss (https://arxiv.org/abs/2304.06795). - - CUDA implementation ported from [HawkAaron/warp-transducer](https://github.com/HawkAaron/warp-transducer). - - Args: - label_acts: Activation tensor of shape [B, T, U, V], where V includes the blank symbol. - duration_acts: Activation tensor of shape [B, T, U, D], where D is the number of durations. - labels: Ground truth labels of shape [B, U]. - input_lengths: Lengths of the acoustic sequence as a vector of ints [B]. - label_lengths: Lengths of the target sequence as a vector of ints [B]. - costs: Zero vector of length [B] in which costs will be set. - label_grads: Zero tensor of shape [B, T, U, V] where the gradient to label_acts will be set. - duration_grads: Zero tensor of shape [B, T, U, D] where the gradient to duration_acts will be set. - blank_label: Index of the standard blank token in the vocabulary. - durations: A list of supported durations for TDT. Must include 0 and 1. - fastemit_lambda: Float scaling factor for FastEmit regularization. Refer to - FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization. - clamp: Float value. When set to value >= 0.0, will clamp the gradient to [-clamp, clamp]. - num_threads: Number of threads for OpenMP. - sigma: logit-undernormalization weight used in the multi-blank model. Refer to - the multi-blank paper https://arxiv.org/abs/2304.06795 for detailed explanations. - omega: weight for regular RNN-T loss - """ - minibatch_size = label_acts.shape[0] - maxT = label_acts.shape[1] - maxU = label_acts.shape[2] - alphabet_size = label_acts.shape[3] - - if hasattr(cuda, 'external_stream'): - stream = cuda.external_stream(torch.cuda.current_stream(label_acts.device).cuda_stream) - else: - stream = cuda.default_stream() - - if num_threads < 0: - num_threads = multiprocessing.cpu_count() - - num_threads = max(1, num_threads) # have to use at least 1 thread - - gpu_size, status = rnnt_helper.get_workspace_size(maxT, maxU, minibatch_size, gpu=True) - - if status != global_constants.RNNTStatus.RNNT_STATUS_SUCCESS: - raise RuntimeError("Invalid parameter passed when calculating working space memory") - - # Select GPU index - cuda.select_device(label_acts.device.index) - gpu_workspace = torch.zeros(gpu_size, device=label_acts.device, dtype=label_acts.dtype, requires_grad=False) - - tdt_workspace = torch.zeros(len(durations), device=label_acts.device, dtype=torch.long, requires_grad=False) - - for i in range(0, len(durations)): - tdt_workspace[i] = durations[i] - - ### VIEW TENSORS AS VECTORS FOR POINTER INDEXING ### - label_acts, label_acts_shape = rnnt_helper.flatten_tensor(label_acts) - duration_acts, duration_acts_shape = rnnt_helper.flatten_tensor(duration_acts) - - wrapper = gpu_rnnt.GPUTDT( - minibatch=minibatch_size, - maxT=maxT, - maxU=maxU, - alphabet_size=alphabet_size, - workspace=gpu_workspace, - tdt_workspace=tdt_workspace, - num_durations=len(durations), - blank=blank_label, - fastemit_lambda=fastemit_lambda, - clamp=clamp, - num_threads=num_threads, - stream=stream, - sigma=sigma, - omega=omega, - ) - - if label_grads is None: - status = wrapper.score_forward( - label_acts=label_acts.data, - duration_acts=duration_acts.data, - costs=costs.data, - pad_labels=labels.data, - label_lengths=label_lengths.data, - input_lengths=input_lengths.data, - ) - - if status != global_constants.RNNTStatus.RNNT_STATUS_SUCCESS: - raise RuntimeError("Could not calculate forward scores") - - else: - ### FLATTEN GRAD TENSOR ### - label_grads, label_grads_shape = rnnt_helper.flatten_tensor(label_grads) - duration_grads, duration_grads_shape = rnnt_helper.flatten_tensor(duration_grads) - - status = wrapper.cost_and_grad( - label_acts=label_acts.data, - duration_acts=duration_acts.data, - label_grads=label_grads.data, - duration_grads=duration_grads.data, - costs=costs.data, - pad_labels=labels.data, - label_lengths=label_lengths.data, - input_lengths=input_lengths.data, - ) - - if status != global_constants.RNNTStatus.RNNT_STATUS_SUCCESS: - raise RuntimeError("Could not calculate forward scores") - - del gpu_workspace, tdt_workspace, wrapper - return True - - -def multiblank_rnnt_loss_gpu( - acts: torch.Tensor, - labels: torch.Tensor, - input_lengths: torch.Tensor, - label_lengths: torch.Tensor, - costs: torch.Tensor, - grads: torch.Tensor, - blank_label: int, - big_blank_durations: list, - fastemit_lambda: float, - clamp: float, - num_threads: int, - sigma: float, -): - """ - Wrapper method for accessing GPU Multi-blank RNNT loss (https://arxiv.org/pdf/2211.03541.pdf). - - CUDA implementation ported from [HawkAaron/warp-transducer](https://github.com/HawkAaron/warp-transducer). - - Args: - acts: Activation tensor of shape [B, T, U, V + num_big_blanks + 1]. - labels: Ground truth labels of shape [B, U]. - input_lengths: Lengths of the acoustic sequence as a vector of ints [B]. - label_lengths: Lengths of the target sequence as a vector of ints [B]. - costs: Zero vector of length [B] in which costs will be set. - grads: Zero tensor of shape [B, T, U, V + num_big_blanks + 1] where the gradient will be set. - blank_label: Index of the standard blank token in the vocabulary. - big_blank_durations: A list of supported durations for big blank symbols - in the model, e.g. [2, 4, 8]. Note we only include durations for ``big - blanks'' here and it should not include 1 for the standard blank. - Those big blanks have vocabulary indices after the standard blank index. - fastemit_lambda: Float scaling factor for FastEmit regularization. Refer to - FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization. - clamp: Float value. When set to value >= 0.0, will clamp the gradient to [-clamp, clamp]. - num_threads: Number of threads for OpenMP. - sigma: logit-undernormalization weight used in the multi-blank model. Refer to - the multi-blank paper https://arxiv.org/pdf/2211.03541 for detailed explanations. - """ - minibatch_size = acts.shape[0] - maxT = acts.shape[1] - maxU = acts.shape[2] - alphabet_size = acts.shape[3] - - if hasattr(cuda, 'external_stream'): - stream = cuda.external_stream(torch.cuda.current_stream(acts.device).cuda_stream) - else: - stream = cuda.default_stream() - - if num_threads < 0: - num_threads = multiprocessing.cpu_count() - - num_threads = max(1, num_threads) # have to use at least 1 thread - - gpu_size, status = rnnt_helper.get_workspace_size(maxT, maxU, minibatch_size, gpu=True) - - if status != global_constants.RNNTStatus.RNNT_STATUS_SUCCESS: - raise RuntimeError("Invalid parameter passed when calculating working space memory") - - # Select GPU index - cuda.select_device(acts.device.index) - gpu_workspace = torch.zeros(gpu_size, device=acts.device, dtype=acts.dtype, requires_grad=False) - - big_blank_workspace = torch.zeros( - len(big_blank_durations), device=acts.device, dtype=torch.long, requires_grad=False - ) - - for i in range(0, len(big_blank_durations)): - big_blank_workspace[i] = big_blank_durations[i] - - ### VIEW TENSORS AS VECTORS FOR POINTER INDEXING ### - acts, acts_shape = rnnt_helper.flatten_tensor(acts) - - wrapper = gpu_rnnt.MultiblankGPURNNT( - minibatch=minibatch_size, - maxT=maxT, - maxU=maxU, - alphabet_size=alphabet_size, - workspace=gpu_workspace, - big_blank_workspace=big_blank_workspace, - num_big_blanks=len(big_blank_durations), - blank=blank_label, - fastemit_lambda=fastemit_lambda, - clamp=clamp, - num_threads=num_threads, - stream=stream, - sigma=sigma, - ) - - if grads is None: - status = wrapper.score_forward( - acts=acts.data, - costs=costs.data, - pad_labels=labels.data, - label_lengths=label_lengths.data, - input_lengths=input_lengths.data, - ) - - if status != global_constants.RNNTStatus.RNNT_STATUS_SUCCESS: - raise RuntimeError("Could not calculate forward scores") - - else: - ### FLATTEN GRAD TENSOR ### - grads, grads_shape = rnnt_helper.flatten_tensor(grads) - - status = wrapper.cost_and_grad( - acts=acts.data, - grads=grads.data, - costs=costs.data, - pad_labels=labels.data, - label_lengths=label_lengths.data, - input_lengths=input_lengths.data, - ) - - if status != global_constants.RNNTStatus.RNNT_STATUS_SUCCESS: - raise RuntimeError("Could not calculate forward scores") - - del gpu_workspace, big_blank_workspace, wrapper - return True diff --git a/nemo/collections/asr/parts/numba/rnnt_loss/rnnt_numpy.py b/nemo/collections/asr/parts/numba/rnnt_loss/rnnt_numpy.py deleted file mode 100644 index 58508970aa830b53211157354d6d66606fa857ac..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/numba/rnnt_loss/rnnt_numpy.py +++ /dev/null @@ -1,369 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Copyright 2018-2019, Mingkun Huang -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import numpy as np -import torch -from torch.autograd import Function, Variable -from torch.nn import Module - - -def check_type(var, t, name): - if var.dtype is not t: - raise TypeError("{} must be {}".format(name, t)) - - -def check_contiguous(var, name): - if not var.is_contiguous(): - raise ValueError("{} must be contiguous".format(name)) - - -def check_dim(var, dim, name): - if len(var.shape) != dim: - raise ValueError("{} must be {}D".format(name, dim)) - - -def certify_inputs(log_probs, labels, lengths, label_lengths): - # check_type(log_probs, torch.float32, "log_probs") - check_type(labels, torch.int64, "labels") - check_type(label_lengths, torch.int64, "label_lengths") - check_type(lengths, torch.int64, "lengths") - check_contiguous(log_probs, "log_probs") - check_contiguous(labels, "labels") - check_contiguous(label_lengths, "label_lengths") - check_contiguous(lengths, "lengths") - - if lengths.shape[0] != log_probs.shape[0]: - raise ValueError( - f"Must have a length per example. " - f"Given lengths dim: {lengths.shape[0]}, " - f"Log probs dim : {log_probs.shape[0]}" - ) - if label_lengths.shape[0] != log_probs.shape[0]: - raise ValueError( - "Must have a label length per example. " - f"Given label lengths dim : {label_lengths.shape[0]}, " - f"Log probs dim : {log_probs.shape[0]}" - ) - - check_dim(log_probs, 4, "log_probs") - check_dim(labels, 2, "labels") - check_dim(lengths, 1, "lenghts") - check_dim(label_lengths, 1, "label_lenghts") - max_T = torch.max(lengths) - max_U = torch.max(label_lengths) - T, U = log_probs.shape[1:3] - if T != max_T: - raise ValueError(f"Input length mismatch! Given T: {T}, Expected max T from input lengths: {max_T}") - if U != max_U + 1: - raise ValueError(f"Output length mismatch! Given U: {U}, Expected max U from target lengths: {max_U} + 1") - - -def _assert_no_grad(tensor): - assert not tensor.requires_grad, ( - "gradients only computed for log_probs - please " "mark other tensors as not requiring gradients" - ) - - -class LogSoftmaxGradModification(Function): - @staticmethod - def forward(ctx, acts, clamp): - if clamp < 0: - raise ValueError("`clamp` must be 0.0 or positive float.") - - res = acts.new(acts) - ctx.clamp = clamp - return res - - @staticmethod - def backward(ctx, grad_output): - grad_output = torch.clamp(grad_output, -ctx.clamp, ctx.clamp) - return ( - grad_output, - None, - ) - - -def forward_pass(log_probs, labels, blank): - """ - Computes probability of the forward variable alpha. - - Args: - log_probs: Tensor of shape [T, U, V+1] - labels: Labels of shape [B, U] - blank: Index of the blank token. - - Returns: - A tuple of the forward variable probabilities - alpha of shape [T, U] - and the log likelihood of this forward step. - """ - T, U, _ = log_probs.shape - alphas = np.zeros((T, U), dtype='f') - - for t in range(1, T): - alphas[t, 0] = alphas[t - 1, 0] + log_probs[t - 1, 0, blank] - - for u in range(1, U): - alphas[0, u] = alphas[0, u - 1] + log_probs[0, u - 1, labels[u - 1]] - for t in range(1, T): - for u in range(1, U): - no_emit = alphas[t - 1, u] + log_probs[t - 1, u, blank] - emit = alphas[t, u - 1] + log_probs[t, u - 1, labels[u - 1]] - alphas[t, u] = np.logaddexp(emit, no_emit) - - loglike = alphas[T - 1, U - 1] + log_probs[T - 1, U - 1, blank] - return alphas, loglike - - -def backward_pass(log_probs, labels, blank): - """ - Computes probability of the backward variable beta. - - Args: - log_probs: Tensor of shape [T, U, V+1] - labels: Labels of shape [B, U] - blank: Index of the blank token. - - Returns: - A tuple of the backward variable probabilities - beta of shape [T, U] - and the log likelihood of this backward step. - """ - T, U, _ = log_probs.shape - betas = np.zeros((T, U), dtype='f') - betas[T - 1, U - 1] = log_probs[T - 1, U - 1, blank] - - for t in reversed(range(T - 1)): - betas[t, U - 1] = betas[t + 1, U - 1] + log_probs[t, U - 1, blank] - - for u in reversed(range(U - 1)): - betas[T - 1, u] = betas[T - 1, u + 1] + log_probs[T - 1, u, labels[u]] - - for t in reversed(range(T - 1)): - for u in reversed(range(U - 1)): - no_emit = betas[t + 1, u] + log_probs[t, u, blank] - emit = betas[t, u + 1] + log_probs[t, u, labels[u]] - betas[t, u] = np.logaddexp(emit, no_emit) - - return betas, betas[0, 0] - - -def compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda): - """ - Computes the gradients of the log_probs with respect to the log probability of this step occuring. - - Args: - Args: - log_probs: Tensor of shape [T, U, V+1] - alphas: Tensor of shape [T, U] which represents the forward variable. - betas: Tensor of shape [T, U] which represents the backward variable. - labels: Labels of shape [B, U] - blank: Index of the blank token. - - Returns: - Gradients of shape [T, U, V+1] with respect to the forward log probability - """ - T, U, _ = log_probs.shape - grads = np.full(log_probs.shape, -float("inf")) - log_like = betas[0, 0] # == alphas[T - 1, U - 1] + betas[T - 1, U - 1] - - # // grad to last blank transition - grads[T - 1, U - 1, blank] = alphas[T - 1, U - 1] - grads[: T - 1, :, blank] = alphas[: T - 1, :] + betas[1:, :] - - # // grad to label transition - for u, l in enumerate(labels): - grads[:, u, l] = alphas[:, u] + betas[:, u + 1] - - grads = -np.exp(grads + log_probs - log_like) - - if fastemit_lambda > 0.0: - for u, l in enumerate(labels): - grads[:, u, l] = (1.0 + fastemit_lambda) * grads[:, u, l] - - return grads - - -def fastemit_regularization(log_probs, labels, alphas, betas, blank, fastemit_lambda): - """ - Describes the computation of FastEmit regularization from the paper - - [FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization](https://arxiv.org/abs/2010.11148) - - Args: - log_probs: Tensor of shape [T, U, V+1] - labels: Unused. Labels of shape [B, U] - alphas: Tensor of shape [T, U] which represents the forward variable. - betas: Unused. Tensor of shape [T, U] which represents the backward variable. - blank: Index of the blank token. - fastemit_lambda: Float scaling factor for FastEmit regularization. - - Returns: - The regularized negative log likelihood - lambda * P˜(At, u|x) - """ - # General calculation of the fastemit regularization alignments - T, U, _ = log_probs.shape - # alignment = np.zeros((T, U), dtype='float32') - # - # for t in range(0, T): - # alignment[t, U - 1] = alphas[t, U - 1] + betas[t, U - 1] - # - # for t in range(0, T): - # for u in range(0, U - 1): - # emit = alphas[t, u] + log_probs[t, u, labels[u]] + betas[t, u + 1] - # alignment[t, u] = emit - # reg = fastemit_lambda * (alignment[T - 1, U - 1]) - - # The above is equivalent to below, without need of computing above - # reg = fastemit_lambda * (alphas[T - 1, U - 1] + betas[T - 1, U - 1]) - - # The above is also equivalent to below, without need of computing the betas alignment matrix - reg = fastemit_lambda * (alphas[T - 1, U - 1] + log_probs[T - 1, U - 1, blank]) - return -reg - - -def transduce(log_probs, labels, blank=0, fastemit_lambda=0.0): - """ - Args: - log_probs: 3D array with shape - [input len, output len + 1, vocab size] - labels: 1D array with shape [output time steps] - blank: Index of the blank token. - fastemit_lambda: Float scaling factor for FastEmit regularization. - - Returns: - float: The negative log-likelihood - 3D array: Gradients with respect to the - unnormalized input actications - 2d arrays: Alphas matrix (TxU) - 2d array: Betas matrix (TxU) - """ - alphas, ll_forward = forward_pass(log_probs, labels, blank) - betas, ll_backward = backward_pass(log_probs, labels, blank) - grads = compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda) - return -ll_forward, grads, alphas, betas - - -def transduce_batch(log_probs, labels, flen, glen, blank=0, fastemit_lambda=0.0): - """ - Compute the transducer loss of the batch. - - Args: - log_probs: [B, T, U, V+1]. Activation matrix normalized with log-softmax. - labels: [B, U+1] - ground truth labels with padded as blank token in the beginning. - flen: Length vector of the acoustic sequence. - glen: Length vector of the target sequence. - blank: Id of the blank token. - fastemit_lambda: Float scaling factor for FastEmit regularization. - - Returns: - Batch of transducer forward log probabilities (loss) and the gradients of the activation matrix. - """ - grads = np.zeros_like(log_probs) - costs = [] - for b in range(log_probs.shape[0]): - t = int(flen[b]) - u = int(glen[b]) + 1 - - ll, g, alphas, betas = transduce(log_probs[b, :t, :u, :], labels[b, : u - 1], blank, fastemit_lambda) - grads[b, :t, :u, :] = g - - reg = fastemit_regularization( - log_probs[b, :t, :u, :], labels[b, : u - 1], alphas, betas, blank, fastemit_lambda - ) - ll += reg - costs.append(ll) - return costs, grads - - -class _RNNT(Function): - @staticmethod - def forward(ctx, acts, labels, act_lens, label_lens, blank, fastemit_lambda): - costs, grads = transduce_batch( - acts.detach().cpu().numpy(), - labels.cpu().numpy(), - act_lens.cpu().numpy(), - label_lens.cpu().numpy(), - blank, - fastemit_lambda, - ) - - costs = torch.FloatTensor([sum(costs)]) - grads = torch.Tensor(grads).to(acts) - - ctx.grads = grads - return costs - - @staticmethod - def backward(ctx, grad_output): - grad_output = grad_output.view(-1, 1, 1, 1).to(ctx.grads) - return ctx.grads.mul(grad_output), None, None, None, None, None - - -class RNNTLoss(Module): - """ - Parameters: - `blank_label` (int): default 0 - label index of blank token - fastemit_lambda: Float scaling factor for FastEmit regularization. - """ - - def __init__(self, blank: int = 0, fastemit_lambda: float = 0.0, clamp: float = -1.0): - super(RNNTLoss, self).__init__() - self.blank = blank - self.fastemit_lambda = fastemit_lambda - self.clamp = float(clamp) if clamp > 0 else 0.0 - self.rnnt = _RNNT.apply - - def forward(self, acts, labels, act_lens, label_lens): - assert len(labels.size()) == 2 - _assert_no_grad(labels) - _assert_no_grad(act_lens) - _assert_no_grad(label_lens) - certify_inputs(acts, labels, act_lens, label_lens) - - # CPU Patch for fp16 - force cast to fp32 - if not acts.is_cuda and acts.dtype == torch.float16: - acts = acts.float() - - if self.clamp > 0.0: - acts = LogSoftmaxGradModification.apply(acts, self.clamp) - - acts = torch.nn.functional.log_softmax(acts, -1) - - return self.rnnt(acts, labels, act_lens, label_lens, self.blank, self.fastemit_lambda) - - -if __name__ == '__main__': - loss = RNNTLoss(fastemit_lambda=0.01) - - torch.manual_seed(0) - - acts = torch.randn(1, 2, 5, 3) - labels = torch.tensor([[0, 2, 1, 2]], dtype=torch.int64) - act_lens = torch.tensor([2], dtype=torch.int64) - label_lens = torch.tensor([len(labels[0])], dtype=torch.int64) - - loss_val = loss(acts, labels, act_lens, label_lens) diff --git a/nemo/collections/asr/parts/numba/rnnt_loss/rnnt_pytorch.py b/nemo/collections/asr/parts/numba/rnnt_loss/rnnt_pytorch.py deleted file mode 100644 index 01f78c0675cd871c4cb6dc2e7e20b7c4ddc265f4..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/numba/rnnt_loss/rnnt_pytorch.py +++ /dev/null @@ -1,634 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Copyright 2018-2019, Mingkun Huang -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import torch -from torch.autograd import Function -from torch.nn import Module - -from nemo.collections.asr.parts.numba.rnnt_loss import rnnt -from nemo.collections.asr.parts.numba.rnnt_loss.utils.cpu_utils import cpu_rnnt - -__all__ = ['rnnt_loss', 'RNNTLossNumba', 'MultiblankRNNTLossNumba', 'TDTLossNumba'] - - -class _RNNTNumba(Function): - @staticmethod - def forward(ctx, acts, labels, act_lens, label_lens, blank, reduction, fastemit_lambda, clamp): - """ - log_probs: Tensor of (batch x seqLength x labelLength x outputDim) containing output from network - labels: 2 dimensional Tensor containing all the targets of the batch with zero padded - act_lens: Tensor of size (batch) containing size of each output sequence from the network - label_lens: Tensor of (batch) containing label length of each example - fastemit_lambda: Float scaling factor for FastEmit regularization. Refer to - FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization. - """ - is_cuda = acts.is_cuda - - certify_inputs(acts, labels, act_lens, label_lens) - if clamp < 0: - raise ValueError("`clamp` must be 0.0 or positive float value.") - - loss_func = rnnt.rnnt_loss_gpu if is_cuda else rnnt.rnnt_loss_cpu - grads = torch.zeros_like(acts) if acts.requires_grad else None - minibatch_size = acts.size(0) - costs = torch.zeros(minibatch_size, device=acts.device, dtype=torch.float32) - - loss_func( - acts, - labels=labels, - input_lengths=act_lens, - label_lengths=label_lens, - costs=costs, - grads=grads, - blank_label=blank, - fastemit_lambda=fastemit_lambda, - clamp=clamp, - num_threads=0, - ) - - if reduction in ['sum', 'mean']: - costs = costs.sum().unsqueeze_(-1) - if reduction == 'mean': - costs /= minibatch_size - - if grads is not None: - grads /= minibatch_size - - ctx.save_for_backward(grads) - - return costs - - @staticmethod - def backward(ctx, grad_output): - (grads,) = ctx.saved_tensors - if grad_output is not None and grads is not None: - grad_output = grad_output.view(-1, 1, 1, 1).to(grads) - return grads.mul_(grad_output), None, None, None, None, None, None, None - - -class _TDTNumba(Function): - """ - Numba class for Token-and-Duration Transducer (TDT) loss (https://arxiv.org/abs/2304.06795) - """ - - @staticmethod - def forward( - ctx, - label_acts, - duration_acts, - labels, - act_lens, - label_lens, - blank, - durations, - reduction, - fastemit_lambda, - clamp, - sigma, - omega, - ): - """ - log_probs: Tensor of (batch x seqLength x labelLength x outputDim) containing output from network - labels: 2 dimensional Tensor containing all the targets of the batch with zero padded - act_lens: Tensor of size (batch) containing size of each output sequence from the network - label_lens: Tensor of (batch) containing label length of each example - fastemit_lambda: Float scaling factor for FastEmit regularization. Refer to - FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization. - durations: list of durations for TDT model, must include 0 and 1, e.g. - [0, 1, 2, 3, 4]. - sigma: hyper-parameter for logit under-normalization method for training - TDT models. Recommended value 0.05. - omega: probability for sampling the standard RNN-T loss. - Refer to https://arxiv.org/abs/2304.06795 for detailed explanations for - the above parameters; - """ - is_cuda = label_acts.is_cuda - - certify_inputs(label_acts, labels, act_lens, label_lens) - if clamp < 0: - raise ValueError("`clamp` must be 0.0 or positive float value.") - - if is_cuda: - loss_func = rnnt.tdt_loss_gpu - else: - raise ValueError("TDT is not yet implemented for non CUDA computation.") - - label_grads = torch.zeros_like(label_acts) if label_acts.requires_grad else None - duration_grads = torch.zeros_like(duration_acts) if duration_acts.requires_grad else None - minibatch_size = label_acts.size(0) - costs = torch.zeros(minibatch_size, device=label_acts.device, dtype=label_acts.dtype) - - loss_func( - label_acts, - duration_acts, - labels=labels, - input_lengths=act_lens, - label_lengths=label_lens, - costs=costs, - label_grads=label_grads, - duration_grads=duration_grads, - blank_label=blank, - durations=durations, - fastemit_lambda=fastemit_lambda, - clamp=clamp, - sigma=sigma, - omega=omega, - num_threads=0, - ) - - if reduction in ['sum', 'mean']: - costs = costs.sum().unsqueeze_(-1) - if reduction == 'mean': - costs /= minibatch_size - - if label_grads is not None: - label_grads /= minibatch_size - duration_grads /= minibatch_size - - ctx.save_for_backward(label_grads, duration_grads) - - return costs - - @staticmethod - def backward(ctx, grad_output): - label_grads, duration_grads = ctx.saved_tensors - if grad_output is not None and label_grads is not None: - grad_output = grad_output.view(-1, 1, 1, 1).to(label_grads) - return ( - label_grads.mul_(grad_output), - duration_grads.mul_(grad_output), - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - ) - - -class _MultiblankRNNTNumba(Function): - """ - Numba class for multi-blank transducer loss (https://arxiv.org/pdf/2211.03541.pdf) - """ - - @staticmethod - def forward( - ctx, acts, labels, act_lens, label_lens, blank, big_blank_durations, reduction, fastemit_lambda, clamp, sigma - ): - """ - big_blank_durations: list of durations for multi-blank transducer, e.g. - [2, 4, 8]. - sigma: hyper-parameter for logit under-normalization method for training - multi-blank transducers. Recommended value 0.05. - Refer to https://arxiv.org/pdf/2211.03541 for detailed explanations for - the above parameters; - For other parameters for this class, refer to comment for class _RNNTNumba - """ - is_cuda = acts.is_cuda - - certify_inputs(acts, labels, act_lens, label_lens) - if clamp < 0: - raise ValueError("`clamp` must be 0.0 or positive float value.") - - if is_cuda: - loss_func = rnnt.multiblank_rnnt_loss_gpu - else: - raise NotImplementedError() - - grads = torch.zeros_like(acts) if acts.requires_grad else None - minibatch_size = acts.size(0) - costs = torch.zeros(minibatch_size, device=acts.device, dtype=acts.dtype) - - loss_func( - acts, - labels=labels, - input_lengths=act_lens, - label_lengths=label_lens, - costs=costs, - grads=grads, - blank_label=blank, - big_blank_durations=big_blank_durations, - fastemit_lambda=fastemit_lambda, - clamp=clamp, - sigma=sigma, - num_threads=0, - ) - - if reduction in ['sum', 'mean']: - costs = costs.sum().unsqueeze_(-1) - if reduction == 'mean': - costs /= minibatch_size - - if grads is not None: - grads /= minibatch_size - - ctx.save_for_backward(grads) - - return costs - - @staticmethod - def backward(ctx, grad_output): - (grads,) = ctx.saved_tensors - if grad_output is not None and grads is not None: - grad_output = grad_output.view(-1, 1, 1, 1).to(grads) - return grads.mul_(grad_output), None, None, None, None, None, None, None, None, None, None - - -def rnnt_loss( - acts, labels, act_lens, label_lens, blank=0, reduction='mean', fastemit_lambda: float = 0.0, clamp: float = 0.0 -): - """RNN Transducer Loss (functional form) - Args: - acts: Tensor of (batch x seqLength x labelLength x outputDim) containing output from network - labels: 2 dimensional Tensor containing all the targets of the batch with zero padded - act_lens: Tensor of size (batch) containing size of each output sequence from the network - label_lens: Tensor of (batch) containing label length of each example - blank (int, optional): blank label. Default: 0. - reduction (string, optional): Specifies the reduction to apply to the output: - 'none' | 'mean' | 'sum'. 'none': no reduction will be applied, - 'mean': the output losses will be divided by the target lengths and - then the mean over the batch is taken. Default: 'mean' - """ - if not acts.is_cuda: - # Since CPU requires log_softmax to be computed explicitly, we need to perform grad clipping - # *after* we have obtained the gradients of loss(logsoftmax()). - # This is highly wasteful since it requires a copy of the entire joint tensor which is expensive. - # CUDA version is much more efficient since it performs an inplace logsoftmax, and therefore - # can inplace clamp the gradient. - if clamp > 0.0: - acts = cpu_rnnt.LogSoftmaxGradModification.apply(acts, clamp) - - # NOTE manually done log_softmax for CPU version, - # log_softmax is computed within GPU version. - acts = torch.nn.functional.log_softmax(acts, -1) - - return _RNNTNumba.apply(acts, labels, act_lens, label_lens, blank, reduction, fastemit_lambda, clamp) - - -def multiblank_rnnt_loss( - acts, - labels, - act_lens, - label_lens, - blank, - big_blank_durations=[], - reduction='mean', - fastemit_lambda: float = 0.0, - clamp: float = 0.0, -): - """ - Multi-blank RNN Transducer (https://arxiv.org/pdf/2211.03541.pdf) Loss (functional form) - Args: - acts: Tensor of (batch x seqLength x labelLength x outputDim) containing output from network - labels: 2 dimensional Tensor containing all the targets of the batch with zero padded - act_lens: Tensor of size (batch) containing size of each output sequence from the network - label_lens: Tensor of (batch) containing label length of each example - blank (int): standard blank label. - big_blank_durations: list of durations for multi-blank transducer, e.g. - [2, 4, 8]. - sigma: hyper-parameter for logit under-normalization method for training - multi-blank transducers. Recommended value 0.05. - Refer to https://arxiv.org/pdf/2211.03541 for detailed explanations for - the last two params. - reduction (string, optional): Specifies the reduction to apply to the output: - 'none' | 'mean' | 'sum'. 'none': no reduction will be applied, - 'mean': the output losses will be divided by the target lengths and - then the mean over the batch is taken. Default: 'mean' - """ - if not acts.is_cuda: - # Since CPU requires log_softmax to be computed explicitly, we need to perform grad clipping - # *after* we have obtained the gradients of loss(logsoftmax()). - # This is highly wasteful since it requires a copy of the entire joint tensor which is expensive. - # CUDA version is much more efficient since it performs an inplace logsoftmax, and therefore - # can inplace clamp the gradient. - if clamp > 0.0: - acts = cpu_rnnt.LogSoftmaxGradModification.apply(acts, clamp) - - # NOTE manually done log_softmax for CPU version, - # log_softmax is computed within GPU version. - acts = torch.nn.functional.log_softmax(acts, -1) - - return _MultiblankRNNTNumba.apply( - acts, labels, act_lens, label_lens, blank, big_blank_durations, reduction, fastemit_lambda, clamp - ) - - -def tdt_loss( - acts, - labels, - act_lens, - label_lens, - blank, - durations=[], - reduction='mean', - fastemit_lambda: float = 0.0, - clamp: float = 0.0, -): - """ - TDT RNN Transducer (https://arxiv.org/abs/2304.06795) Loss (functional form) - Args: - acts: Tensor of (batch x seqLength x labelLength x outputDim) containing output from network - labels: 2 dimensional Tensor containing all the targets of the batch with zero padded - act_lens: Tensor of size (batch) containing size of each output sequence from the network - label_lens: Tensor of (batch) containing label length of each example - blank (int): standard blank label. - durations: list of durations for TDT model, e.g. - [0,1,2,3,4]. - sigma: hyper-parameter for logit under-normalization method for training - multi-blank transducers. Recommended value 0.05. - Refer to https://arxiv.org/abs/2304.06795 for detailed explanations for - the last two params. - reduction (string, optional): Specifies the reduction to apply to the output: - 'none' | 'mean' | 'sum'. 'none': no reduction will be applied, - 'mean': the output losses will be divided by the target lengths and - then the mean over the batch is taken. Default: 'mean' - """ - if not acts.is_cuda: - # Since CPU requires log_softmax to be computed explicitly, we need to perform grad clipping - # *after* we have obtained the gradients of loss(logsoftmax()). - # This is highly wasteful since it requires a copy of the entire joint tensor which is expensive. - # CUDA version is much more efficient since it performs an inplace logsoftmax, and therefore - # can inplace clamp the gradient. - if clamp > 0.0: - acts = cpu_rnnt.LogSoftmaxGradModification.apply(acts, clamp) - - # NOTE manually done log_softmax for CPU version, - # log_softmax is computed within GPU version. - acts = torch.nn.functional.log_softmax(acts, -1) - - return _TDTNumba.apply(acts, labels, act_lens, label_lens, blank, durations, reduction, fastemit_lambda, clamp) - - -class RNNTLossNumba(Module): - """ - Parameters: - blank (int, optional): blank label. Default: 0. - reduction (string, optional): Specifies the reduction to apply to the output: - 'none' | 'mean' | 'sum'. 'none': no reduction will be applied, - 'mean': the output losses will be divided by the target lengths and - then the mean over the batch is taken. Default: 'mean' - fastemit_lambda: Float scaling factor for FastEmit regularization. Refer to - FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization. - clamp: Float value. When set to value >= 0.0, will clamp the gradient to [-clamp, clamp]. - """ - - def __init__(self, blank=0, reduction='mean', fastemit_lambda: float = 0.0, clamp: float = -1): - super(RNNTLossNumba, self).__init__() - self.blank = blank - self.fastemit_lambda = fastemit_lambda - self.clamp = float(clamp) if clamp > 0 else 0.0 - self.reduction = reduction - self.loss = _RNNTNumba.apply - - def forward(self, acts, labels, act_lens, label_lens): - """ - log_probs: Tensor of (batch x seqLength x labelLength x outputDim) containing output from network - labels: 2 dimensional Tensor containing all the targets of the batch with zero padded - act_lens: Tensor of size (batch) containing size of each output sequence from the network - label_lens: Tensor of (batch) containing label length of each example - """ - if not acts.is_cuda: - # Force FP32 until log_softmax() is implemented for fp16 on CPU - if acts.dtype == torch.float16: - acts = acts.float() - - # Since CPU requires log_softmax to be computed explicitly, we need to perform grad clipping - # *after* we have obtained the gradients of loss(logsoftmax()). - # This is highly wasteful since it requires a copy of the entire joint tensor which is expensive. - # CUDA version is much more efficient since it performs an inplace logsoftmax, and therefore - # can inplace clamp the gradient. - if self.clamp > 0.0: - acts = cpu_rnnt.LogSoftmaxGradModification.apply(acts, self.clamp) - - # NOTE manually done log_softmax for CPU version, - # log_softmax is computed within GPU version. - acts = torch.nn.functional.log_softmax(acts, -1) - - return self.loss( - acts, labels, act_lens, label_lens, self.blank, self.reduction, self.fastemit_lambda, self.clamp - ) - - -class MultiblankRNNTLossNumba(Module): - """ - Parameters: - blank (int): standard blank label. - big_blank_durations: list of durations for multi-blank transducer, e.g. - [2, 4, 8]. - sigma: hyper-parameter for logit under-normalization method for training - multi-blank transducers. Recommended value 0.05. - Refer to https://arxiv.org/pdf/2211.03541 for detailed explanations for - the above parameters; - reduction (string, optional): Specifies the reduction to apply to the output: - 'none' | 'mean' | 'sum'. 'none': no reduction will be applied, - 'mean': the output losses will be divided by the target lengths and - then the mean over the batch is taken. Default: 'mean' - fastemit_lambda: Float scaling factor for FastEmit regularization. Refer to - FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization. - clamp: Float value. When set to value >= 0.0, will clamp the gradient to [-clamp, clamp]. - """ - - def __init__( - self, - blank, - big_blank_durations, - reduction='mean', - fastemit_lambda: float = 0.0, - clamp: float = -1, - sigma: float = 0.0, - ): - super(MultiblankRNNTLossNumba, self).__init__() - self.blank = blank - self.big_blank_durations = big_blank_durations - self.fastemit_lambda = fastemit_lambda - self.clamp = float(clamp) if clamp > 0 else 0.0 - self.reduction = reduction - self.loss = _MultiblankRNNTNumba.apply - self.sigma = sigma - - def forward(self, acts, labels, act_lens, label_lens): - """ - log_probs: Tensor of (batch x seqLength x labelLength x outputDim) containing output from network - labels: 2 dimensional Tensor containing all the targets of the batch with zero padded - act_lens: Tensor of size (batch) containing size of each output sequence from the network - label_lens: Tensor of (batch) containing label length of each example - """ - if not acts.is_cuda: - # Since CPU requires log_softmax to be computed explicitly, we need to perform grad clipping - # *after* we have obtained the gradients of loss(logsoftmax()). - # This is highly wasteful since it requires a copy of the entire joint tensor which is expensive. - # CUDA version is much more efficient since it performs an inplace logsoftmax, and therefore - # can inplace clamp the gradient. - if self.clamp > 0.0: - acts = cpu_rnnt.LogSoftmaxGradModification.apply(acts, self.clamp) - - # NOTE manually done log_softmax for CPU version, - # log_softmax is computed within GPU version. - acts = torch.nn.functional.log_softmax(acts, -1) - - return self.loss( - acts, - labels, - act_lens, - label_lens, - self.blank, - self.big_blank_durations, - self.reduction, - self.fastemit_lambda, - self.clamp, - self.sigma, - ) - - -class TDTLossNumba(Module): - """ - Parameters: - blank (int): standard blank label. - durations: list of durations for TDT model, e.g. - [0, 1, 2, 3, 4]. - sigma: hyper-parameter for logit under-normalization method for training - TDT. Recommended value 0.05. - omega: hyper-parameter for RNN-T loss for loss combination. - Refer to https://arxiv.org/abs/2304.06795 for detailed explanations for - the above parameters; - - reduction (string, optional): Specifies the reduction to apply to the output: - 'none' | 'mean' | 'sum'. 'none': no reduction will be applied, - 'mean': the output losses will be divided by the target lengths and - then the mean over the batch is taken. Default: 'mean' - fastemit_lambda: Float scaling factor for FastEmit regularization. Refer to - FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization. - clamp: Float value. When set to value >= 0.0, will clamp the gradient to [-clamp, clamp]. - """ - - def __init__( - self, - blank, - durations=None, - reduction='mean', - fastemit_lambda: float = 0.0, - clamp: float = -1, - sigma: float = 0.0, - omega: float = 0.0, - ): - super(TDTLossNumba, self).__init__() - self.blank = blank - self.durations = durations if durations is not None else [] - self.fastemit_lambda = fastemit_lambda - self.clamp = float(clamp) if clamp > 0 else 0.0 - self.reduction = reduction - self.loss = _TDTNumba.apply - self.sigma = sigma - self.omega = omega - - def forward(self, acts, labels, act_lens, label_lens): - """ - log_probs: Tensor of (batch x seqLength x labelLength x outputDim) containing output from network - labels: 2 dimensional Tensor containing all the targets of the batch with zero padded - act_lens: Tensor of size (batch) containing size of each output sequence from the network - label_lens: Tensor of (batch) containing label length of each example - """ - - # TODO(hainan): in the future, we could further optimize this so that we don't need to - # make contiguous copies of the acts tensor. - label_acts, duration_acts = torch.split( - acts, [acts.shape[-1] - len(self.durations), len(self.durations)], dim=-1 - ) - label_acts = label_acts.contiguous() - duration_acts = torch.nn.functional.log_softmax(duration_acts, dim=-1).contiguous() - - return self.loss( - label_acts, - duration_acts, - labels, - act_lens, - label_lens, - self.blank, - self.durations, - self.reduction, - self.fastemit_lambda, - self.clamp, - self.sigma, - self.omega, - ) - - -def check_type(var, t, name): - if var.dtype is not t: - raise TypeError("{} must be {}".format(name, t)) - - -def check_contiguous(var, name): - if not var.is_contiguous(): - raise ValueError("{} must be contiguous".format(name)) - - -def check_dim(var, dim, name): - if len(var.shape) != dim: - raise ValueError("{} must be {}D".format(name, dim)) - - -def certify_inputs(log_probs, labels, lengths, label_lengths): - # check_type(log_probs, torch.float32, "log_probs") - check_type(labels, torch.int64, "labels") - check_type(label_lengths, torch.int64, "label_lengths") - check_type(lengths, torch.int64, "lengths") - check_contiguous(log_probs, "log_probs") - check_contiguous(labels, "labels") - check_contiguous(label_lengths, "label_lengths") - check_contiguous(lengths, "lengths") - - if lengths.shape[0] != log_probs.shape[0]: - raise ValueError( - f"Must have a length per example. " - f"Given lengths dim: {lengths.shape[0]}, " - f"Log probs dim : {log_probs.shape[0]}" - ) - if label_lengths.shape[0] != log_probs.shape[0]: - raise ValueError( - "Must have a label length per example. " - f"Given label lengths dim : {label_lengths.shape[0]}, " - f"Log probs dim : {log_probs.shape[0]}" - ) - - check_dim(log_probs, 4, "log_probs") - check_dim(labels, 2, "labels") - check_dim(lengths, 1, "lenghts") - check_dim(label_lengths, 1, "label_lenghts") - max_T = torch.max(lengths) - max_U = torch.max(label_lengths) - T, U = log_probs.shape[1:3] - if T != max_T: - raise ValueError(f"Input length mismatch! Given T: {T}, Expected max T from input lengths: {max_T}") - if U != max_U + 1: - raise ValueError(f"Output length mismatch! Given U: {U}, Expected max U from target lengths: {max_U} + 1") diff --git a/nemo/collections/asr/parts/numba/rnnt_loss/utils/__init__.py b/nemo/collections/asr/parts/numba/rnnt_loss/utils/__init__.py deleted file mode 100644 index bc443be41c4c3fcf0764eb9fd3e1828d63f8438c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/numba/rnnt_loss/utils/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/asr/parts/numba/rnnt_loss/utils/cpu_utils/__init__.py b/nemo/collections/asr/parts/numba/rnnt_loss/utils/cpu_utils/__init__.py deleted file mode 100644 index 1b4bbd40dff2c64244d18a0f4f0051cafe59b48d..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/numba/rnnt_loss/utils/cpu_utils/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Copyright 2018-2019, Mingkun Huang -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/asr/parts/numba/rnnt_loss/utils/cpu_utils/cpu_rnnt.py b/nemo/collections/asr/parts/numba/rnnt_loss/utils/cpu_utils/cpu_rnnt.py deleted file mode 100644 index bcc1865ab78ee7f9a82acbc7cacd7a1ddcf382c9..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/numba/rnnt_loss/utils/cpu_utils/cpu_rnnt.py +++ /dev/null @@ -1,422 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Copyright 2018-2019, Mingkun Huang -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import math -import multiprocessing -from typing import Optional - -import numba -import torch -from torch.autograd import Function - -from nemo.collections.asr.parts.numba.rnnt_loss.utils import global_constants - - -def log_sum_exp(a: torch.Tensor, b: torch.Tensor): - """ - Logsumexp with safety checks for infs. - """ - if torch.isinf(a): - return b - - if torch.isinf(b): - return a - - if a > b: - return math.log1p(math.exp(b - a)) + a - else: - return math.log1p(math.exp(a - b)) + b - - -class CpuRNNT_index: - def __init__(self, U: int, maxU: int, minibatch: int, alphabet_size: int, batch_first: bool): - """ - A placeholder Index computation class that emits the resolved index in a flattened tensor, - mimicing pointer indexing in CUDA kernels on the CPU. - - Args: - U: Length of the current target sample (without padding). - maxU: Max Length of the padded target samples. - minibatch: Minibatch index - alphabet_size: Size of the vocabulary including RNNT blank - V+1. - batch_first: Bool flag determining if batch index is first or third. - """ - super(CpuRNNT_index, self).__init__() - self.U = U - self.maxU = maxU - self.minibatch = minibatch - self.alphabet_size = alphabet_size - self.batch_first = batch_first - - def __call__(self, t: int, u: int, v: Optional[int] = None): - # if indexing all the values of the vocabulary, then only t, u are provided - if v is None: - return t * self.U + u - else: - # otherwise, t, u, v are provided to index particular value in the vocabulary. - if self.batch_first: - return (t * self.maxU + u) * self.alphabet_size + v - else: - return (t * self.maxU + u) * self.minibatch * self.alphabet_size + v - - -class CpuRNNT_metadata: - def __init__( - self, - T: int, - U: int, - workspace: torch.Tensor, - bytes_used: int, - blank: int, - labels: torch.Tensor, - log_probs: torch.Tensor, - idx: CpuRNNT_index, - ): - """ - Metadata for CPU based RNNT loss calculation. Holds the working space memory. - - Args: - T: Length of the acoustic sequence (without padding). - U: Length of the target sequence (without padding). - workspace: Working space memory for the CPU. - bytes_used: Number of bytes currently used for indexing the working space memory. Generally 0. - blank: Index of the blank token in the vocabulary. - labels: Ground truth padded labels matrix of shape [B, U] - log_probs: Log probs / activation matrix of flattented shape [B, T, U, V+1] - idx: - """ - super(CpuRNNT_metadata, self).__init__() - - self.alphas = workspace[bytes_used : bytes_used + T * U] - bytes_used += T * U - - self.betas = workspace[bytes_used : bytes_used + T * U] - bytes_used += T * U - - self.log_probs2 = workspace[bytes_used : bytes_used + T * U * 2] # // only store blank & label - bytes_used += T * U * 2 - - self.bytes_used = bytes_used - - self.setup_probs(T, U, labels, blank, log_probs, idx) - - def setup_probs( - self, T: int, U: int, labels: torch.Tensor, blank: int, log_probs: torch.Tensor, idx: CpuRNNT_index - ): - # initialize the log probs memory for blank and label token. - for t in range(T): - for u in range(U): - offset = (t * U + u) * 2 # mult with 2 is for selecting either blank or label token. Odd idx is blank. - self.log_probs2[offset] = log_probs[idx(t, u, blank)] - # // labels do not have first blank - if u < U - 1: - self.log_probs2[offset + 1] = log_probs[idx(t, u, labels[u])] - - -class LogSoftmaxGradModification(Function): - @staticmethod - def forward(ctx, acts, clamp): - if clamp < 0: - raise ValueError("`clamp` must be 0.0 or positive float.") - - # This is needed for correctness (inplace is problematic), - # but it wastes a log of memory. - res = acts.new(acts) - ctx.clamp = clamp - return res - - @staticmethod - def backward(ctx, grad_output): - # Clamp the gradients of loss(logsoftmax(...)) - # CPU computes logsoftmax explicitly, so we need to override t - grad_output = torch.clamp(grad_output, -ctx.clamp, ctx.clamp) - return ( - grad_output, - None, - ) - - -class CPURNNT: - def __init__( - self, - minibatch: int, - maxT: int, - maxU: int, - alphabet_size: int, - workspace: torch.Tensor, - blank: int, - fastemit_lambda: float, - clamp: float, - num_threads: int, - batch_first: bool, - ): - """ - Helper class to compute the Transducer Loss on CPU. - - Args: - minibatch: Size of the minibatch b. - maxT: The maximum possible acoustic sequence length. Represents T in the logprobs tensor. - maxU: The maximum possible target sequence length. Represents U in the logprobs tensor. - alphabet_size: The vocabulary dimension V+1 (inclusive of RNNT blank). - workspace: An allocated chunk of memory that will be sliced off and reshaped into required - blocks used as working memory. - blank: Index of the RNNT blank token in the vocabulary. Generally the first or last token in the vocab. - fastemit_lambda: Float scaling factor for FastEmit regularization. Refer to - FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization. - clamp: Float value. When set to value >= 0.0, will clamp the gradient to [-clamp, clamp]. - num_threads: Number of OMP threads to launch. - batch_first: Bool that decides if batch dimension is first or third. - """ - self.minibatch_ = minibatch - self.maxT_ = maxT - self.maxU_ = maxU - self.alphabet_size_ = alphabet_size - self.workspace = workspace # a flat vector of floatX numbers that represents allocated memory slices - self.blank_ = blank - self.fastemit_lambda_ = fastemit_lambda - self.clamp_ = abs(clamp) - self.num_threads_ = num_threads - self.batch_first = batch_first - - _torch_num_threads = torch.get_num_threads() - if num_threads > 0: - numba.set_num_threads(min(multiprocessing.cpu_count(), num_threads)) - self.num_threads_ = numba.get_num_threads() - else: - self.num_threads_ = numba.get_num_threads() - torch.set_num_threads(_torch_num_threads) - - def cost_and_grad_kernel( - self, - log_probs: torch.Tensor, - grad: torch.Tensor, - labels: torch.Tensor, - mb: int, - T: int, - U: int, - bytes_used: int, - ): - idx = CpuRNNT_index(U, self.maxU_, self.minibatch_, self.alphabet_size_, self.batch_first) - rnntm = CpuRNNT_metadata(T, U, self.workspace, bytes_used, self.blank_, labels, log_probs, idx) - - if self.batch_first: - # zero grads - grad *= 0.0 - - llForward = self.compute_alphas(rnntm.log_probs2, T, U, rnntm.alphas) - llBackward = self.compute_betas_and_grads( - grad, rnntm.log_probs2, T, U, rnntm.alphas, rnntm.betas, labels, llForward - ) - - # Scale llForward by FastEmit lambda - llForward += llForward * self.fastemit_lambda_ - llBackward += llBackward * self.fastemit_lambda_ - - diff = (llForward - llBackward).abs() - if diff > 0.1: - print(f"WARNING: Forward backward likelihood mismatch : {diff}") - - return -llForward - - def compute_alphas(self, log_probs: torch.Tensor, T: int, U: int, alphas: torch.Tensor): - """ - Compute the probability of the forward variable alpha. - - Args: - log_probs: Flattened tensor [B, T, U, V+1] - T: Length of the acoustic sequence T (not padded). - U: Length of the target sequence U (not padded). - alphas: Working space memory for alpha of shape [B, T, U]. - - Returns: - Loglikelihood of the forward variable alpha. - """ - idx = CpuRNNT_index(U, self.maxU_, self.minibatch_, self.alphabet_size_, self.batch_first) - - alphas[0] = 0 - for t in range(T): - for u in range(U): - if u == 0 and t > 0: - alphas[idx(t, 0)] = alphas[idx(t - 1, 0)] + log_probs[idx(t - 1, 0) * 2] - - if t == 0 and u > 0: - alphas[idx(0, u)] = alphas[idx(0, u - 1)] + log_probs[idx(0, u - 1) * 2 + 1] - - if t > 0 and u > 0: - no_emit = alphas[idx(t - 1, u)] + log_probs[idx(t - 1, u) * 2] - emit = alphas[idx(t, u - 1)] + log_probs[idx(t, u - 1) * 2 + 1] - alphas[idx(t, u)] = log_sum_exp(emit, no_emit) - - loglike = alphas[idx(T - 1, U - 1)] + log_probs[idx(T - 1, U - 1) * 2] - return loglike - - def compute_betas_and_grads( - self, - grad: torch.Tensor, - log_probs: torch.Tensor, - T: int, - U: int, - alphas: torch.Tensor, - betas: torch.Tensor, - labels: torch.Tensor, - logll: torch.Tensor, - ): - """ - Compute backward variable beta as well as gradients of the activation matrix wrt loglikelihood - of forward variable. - - Args: - grad: Working space memory of flattened shape [B, T, U, V+1] - log_probs: Activatio tensor of flattented shape [B, T, U, V+1] - T: Length of the acoustic sequence T (not padded). - U: Length of the target sequence U (not padded). - alphas: Working space memory for alpha of shape [B, T, U]. - betas: Working space memory for alpha of shape [B, T, U]. - labels: Ground truth label of shape [B, U] - logll: Loglikelihood of the forward variable. - - Returns: - Loglikelihood of the forward variable and inplace updates the grad tensor. - """ - # Patch for CPU + fp16 - if log_probs.dtype == torch.float16 and not log_probs.is_cuda: - log_probs = log_probs.float() - - idx = CpuRNNT_index(U, self.maxU_, self.minibatch_, self.alphabet_size_, self.batch_first) - betas[idx(T - 1, U - 1)] = log_probs[idx(T - 1, U - 1) * 2] - - for t in range(T - 1, -1, -1): - for u in range(U - 1, -1, -1): - if (u == U - 1) and (t < T - 1): - betas[idx(t, U - 1)] = betas[idx(t + 1, U - 1)] + log_probs[idx(t, U - 1) * 2] - - if (t == T - 1) and (u < U - 1): - betas[idx(T - 1, u)] = betas[idx(T - 1, u + 1)] + log_probs[idx(T - 1, u) * 2 + 1] - - if (t < T - 1) and (u < U - 1): - no_emit = betas[idx(t + 1, u)] + log_probs[idx(t, u) * 2] - emit = betas[idx(t, u + 1)] + log_probs[idx(t, u) * 2 + 1] - betas[idx(t, u)] = log_sum_exp(emit, no_emit) - - loglike = betas[0] - # // Gradients w.r.t. log probabilities - for t in range(T): - for u in range(U): - if t < T - 1: - g = alphas[idx(t, u)] + betas[idx(t + 1, u)] - grad[idx(t, u, self.blank_)] = -torch.exp(log_probs[idx(t, u) * 2] + g - loglike) - - if u < U - 1: - g = alphas[idx(t, u)] + betas[idx(t, u + 1)] - grad[idx(t, u, labels[u])] = -torch.exp( - math.log1p(self.fastemit_lambda_) + log_probs[idx(t, u) * 2 + 1] + g - loglike - ) - - # // gradient to the last blank transition - grad[idx(T - 1, U - 1, self.blank_)] = -torch.exp( - log_probs[idx(T - 1, U - 1) * 2] + alphas[idx(T - 1, U - 1)] - loglike - ) - - return loglike - - def cost_and_grad( - self, - log_probs: torch.Tensor, - grads: torch.Tensor, - costs: torch.Tensor, - flat_labels: torch.Tensor, - label_lengths: torch.Tensor, - input_lengths: torch.Tensor, - ) -> global_constants.RNNTStatus: - # // per minibatch memory - per_minibatch_bytes = 0 - - # // alphas & betas - per_minibatch_bytes += self.maxT_ * self.maxU_ * 2 - - # // blank & label log probability cache - per_minibatch_bytes += self.maxT_ * self.maxU_ * 2 - - for mb in range(self.minibatch_): - T = input_lengths[mb] # // Length of utterance (time) - U = label_lengths[mb] + 1 # // Number of labels in transcription - batch_size = self.alphabet_size_ - if self.batch_first: - batch_size = self.maxT_ * self.maxU_ * self.alphabet_size_ - - costs[mb] = self.cost_and_grad_kernel( - log_probs[(mb * batch_size) :], - grads[(mb * batch_size) :], - flat_labels[(mb * (self.maxU_ - 1)) :], - mb, - T, - U, - mb * per_minibatch_bytes, - ) - - return global_constants.RNNTStatus.RNNT_STATUS_SUCCESS - - def score_forward( - self, - log_probs: torch.Tensor, - costs: torch.Tensor, - flat_labels: torch.Tensor, - label_lengths: torch.Tensor, - input_lengths: torch.Tensor, - ): - # // per minibatch memory - per_minibatch_bytes = 0 - - # // alphas & betas - per_minibatch_bytes += self.maxT_ * self.maxU_ * 2 - - # // blank & label log probability cache - per_minibatch_bytes += self.maxT_ * self.maxU_ * 2 - - for mb in range(self.minibatch_): - T = input_lengths[mb] # // Length of utterance (time) - U = label_lengths[mb] + 1 # // Number of labels in transcription - batch_size = self.alphabet_size_ - if self.batch_first: - batch_size = self.maxT_ * self.maxU_ * self.alphabet_size_ - - idx = CpuRNNT_index(U, self.maxU_, self.minibatch_, self.alphabet_size_, self.batch_first) - rnntm = CpuRNNT_metadata( - T, - U, - self.workspace, - mb * per_minibatch_bytes, - self.blank_, - flat_labels[(mb * (self.maxU_ - 1)) :], - log_probs[(mb * batch_size) :], - idx, - ) - - costs[mb] = -self.compute_alphas(rnntm.log_probs2, T, U, rnntm.alphas) - - return global_constants.RNNTStatus.RNNT_STATUS_SUCCESS diff --git a/nemo/collections/asr/parts/numba/rnnt_loss/utils/cuda_utils/__init__.py b/nemo/collections/asr/parts/numba/rnnt_loss/utils/cuda_utils/__init__.py deleted file mode 100644 index 1b4bbd40dff2c64244d18a0f4f0051cafe59b48d..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/numba/rnnt_loss/utils/cuda_utils/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Copyright 2018-2019, Mingkun Huang -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/asr/parts/numba/rnnt_loss/utils/cuda_utils/gpu_rnnt.py b/nemo/collections/asr/parts/numba/rnnt_loss/utils/cuda_utils/gpu_rnnt.py deleted file mode 100644 index 87d6ee147deaee06b5562c692a982f81d7a83ad7..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/numba/rnnt_loss/utils/cuda_utils/gpu_rnnt.py +++ /dev/null @@ -1,807 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Copyright 2018-2019, Mingkun Huang -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import multiprocessing -import random -from typing import Optional, Tuple - -import numba -import torch -from numba import cuda - -from nemo.collections.asr.parts.numba.rnnt_loss.utils import global_constants, rnnt_helper -from nemo.collections.asr.parts.numba.rnnt_loss.utils.cuda_utils import gpu_rnnt_kernel, reduce - - -class GPURNNT: - def __init__( - self, - minibatch: int, - maxT: int, - maxU: int, - alphabet_size: int, - workspace, - blank: int, - fastemit_lambda: float, - clamp: float, - num_threads: int, - stream, - ): - """ - Helper class to launch the CUDA Kernels to compute the Transducer Loss. - - Args: - minibatch: Int representing the batch size. - maxT: The maximum possible acoustic sequence length. Represents T in the logprobs tensor. - maxU: The maximum possible target sequence length. Represents U in the logprobs tensor. - alphabet_size: The vocabulary dimension V+1 (inclusive of RNNT blank). - workspace: An allocated chunk of memory that will be sliced off and reshaped into required - blocks used as working memory. - blank: Index of the RNNT blank token in the vocabulary. Generally the first or last token in the vocab. - fastemit_lambda: Float scaling factor for FastEmit regularization. Refer to - FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization. - clamp: Float value. When set to value >= 0.0, will clamp the gradient to [-clamp, clamp]. - num_threads: Number of OMP threads to launch. - stream: Numba Cuda Stream. - """ - self.minibatch_ = minibatch - self.maxT_ = maxT - self.maxU_ = maxU - self.alphabet_size_ = alphabet_size - self.gpu_workspace = cuda.as_cuda_array( - workspace - ) # a flat vector of floatX numbers that represents allocated memory slices - self.blank_ = blank - self.fastemit_lambda_ = fastemit_lambda - self.clamp_ = abs(clamp) - self.num_threads_ = num_threads - self.stream_ = stream # type: cuda.cudadrv.driver.Stream - - _torch_num_threads = torch.get_num_threads() - if num_threads > 0: - numba.set_num_threads(min(multiprocessing.cpu_count(), num_threads)) - self.num_threads_ = numba.get_num_threads() - else: - self.num_threads_ = numba.get_num_threads() - torch.set_num_threads(_torch_num_threads) - - def log_softmax(self, acts: torch.Tensor, denom: torch.Tensor): - """ - Computes the log softmax denominator of the input activation tensor - and stores the result in denom. - - Args: - acts: Activation tensor of shape [B, T, U, V+1]. The input must be represented as a flat tensor - of shape [B * T * U * (V+1)] to allow pointer indexing. - denom: A zero tensor of same shape as acts. - - Updates: - This kernel inplace updates the `denom` tensor - """ - # // trans_acts + pred_acts -> log_softmax denominator - reduce.reduce_max( - acts, - denom, - rows=self.alphabet_size_, - cols=self.minibatch_ * self.maxT_ * self.maxU_, - minus=False, - stream=self.stream_, - ) - - reduce.reduce_exp( - acts, - denom, - rows=self.alphabet_size_, - cols=self.minibatch_ * self.maxT_ * self.maxU_, - minus=True, - stream=self.stream_, - ) - - def compute_cost_and_score( - self, - acts: torch.Tensor, - grads: Optional[torch.Tensor], - costs: torch.Tensor, - labels: torch.Tensor, - label_lengths: torch.Tensor, - input_lengths: torch.Tensor, - ) -> global_constants.RNNTStatus: - """ - Compute both the loss and the gradients. - - Args: - acts: A flattened tensor of shape [B, T, U, V+1] representing the activation matrix. - grad: A flattented zero tensor of same shape as acts. - costs: A zero vector of length B which will be updated inplace with the log probability costs. - flat_labels: A flattened matrix of labels of shape [B, U] - label_lengths: A vector of length B that contains the original lengths of the acoustic sequence. - input_lengths: A vector of length B that contains the original lengths of the target sequence. - - Updates: - This will launch kernels that will update inline the following variables: - - grads: Gradients of the activation matrix wrt the costs vector. - - costs: Negative log likelihood of the forward variable. - - Returns: - An enum that either represents a successful RNNT operation or failure. - """ - training = grads is not None - - if training: - grads *= 0.0 # zero grads - - used_offset, (denom, alphas, betas, llForward, llBackward) = self._prepare_workspace() - - ######## START EXECUTION ######## - self.log_softmax(acts, denom) - - # Compute alphas - gpu_rnnt_kernel.compute_alphas_kernel[self.minibatch_, self.maxU_, self.stream_, 0]( - acts, - denom, - alphas, - llForward, - input_lengths, - label_lengths, - labels, - self.minibatch_, - self.maxT_, - self.maxU_, - self.alphabet_size_, - self.blank_, - ) - - if training: - # Compute betas - gpu_rnnt_kernel.compute_betas_kernel[self.minibatch_, self.maxU_, self.stream_, 0]( - acts, - denom, - betas, - llBackward, - input_lengths, - label_lengths, - labels, - self.minibatch_, - self.maxT_, - self.maxU_, - self.alphabet_size_, - self.blank_, - ) - - # Compute gradient - grad_blocks_per_grid = self.minibatch_ * self.maxT_ * self.maxU_ - grad_threads_per_block = gpu_rnnt_kernel.GPU_RNNT_THREAD_SIZE - gpu_rnnt_kernel.compute_grad_kernel[grad_blocks_per_grid, grad_threads_per_block, self.stream_, 0]( - grads, - acts, - denom, - alphas, - betas, - llForward, - input_lengths, - label_lengths, - labels, - self.minibatch_, - self.maxT_, - self.maxU_, - self.alphabet_size_, - self.blank_, - self.fastemit_lambda_, - self.clamp_, - ) - - # // cost copy, negate (for log likelihood) and update with additional regularizers - # This needs to be done via CUDA, because we used temporary memory llForward - # passed to alpha, which was updated with log likelihoods. - # But copying this data into a pytorch pointer is more difficult (numba api is one way) - # Therefore launch a pointwise CUDA kernel to update the costs inplace from data of llForward - # Then negate to compute the loglikelihood. - threadsperblock = min(costs.shape[0], 32) - blockspergrid = (costs.shape[0] + (threadsperblock - 1)) // threadsperblock - rnnt_helper.compute_costs_data[blockspergrid, threadsperblock, self.stream_, 0]( - llForward, costs, self.fastemit_lambda_ - ) - self.stream_.synchronize() - - return global_constants.RNNTStatus.RNNT_STATUS_SUCCESS - - def cost_and_grad( - self, - acts: torch.Tensor, - grads: torch.Tensor, - costs: torch.Tensor, - pad_labels: torch.Tensor, - label_lengths: torch.Tensor, - input_lengths: torch.Tensor, - ): - if ( - acts is None - or grads is None - or costs is None - or pad_labels is None - or label_lengths is None - or input_lengths is None - ): - return global_constants.RNNTStatus.RNNT_STATUS_INVALID_VALUE - - return self.compute_cost_and_score(acts, grads, costs, pad_labels, label_lengths, input_lengths) - - def score_forward( - self, - acts: torch.Tensor, - costs: torch.Tensor, - pad_labels: torch.Tensor, - label_lengths: torch.Tensor, - input_lengths: torch.Tensor, - ): - if acts is None or costs is None or pad_labels is None or label_lengths is None or input_lengths is None: - return global_constants.RNNTStatus.RNNT_STATUS_INVALID_VALUE - - return self.compute_cost_and_score(acts, None, costs, pad_labels, label_lengths, input_lengths) - - def _prepare_workspace(self) -> Tuple[int, Tuple[torch.Tensor, ...]]: - """ - Helper method that uses the workspace and constructs slices of it that can be used. - - Returns: - An int, representing the offset of the used workspace (practically, the slice of the workspace consumed) - A tuple of tensors representing the shared workspace. - """ - used_offset = 0 - - # // denom - denom = self.gpu_workspace[used_offset : used_offset + self.maxT_ * self.maxU_ * self.minibatch_] - used_offset += self.maxT_ * self.maxU_ * self.minibatch_ - - # // alphas & betas - alphas = self.gpu_workspace[used_offset : used_offset + self.maxT_ * self.maxU_ * self.minibatch_] - used_offset += self.maxT_ * self.maxU_ * self.minibatch_ - betas = self.gpu_workspace[used_offset : used_offset + self.maxT_ * self.maxU_ * self.minibatch_] - used_offset += self.maxT_ * self.maxU_ * self.minibatch_ - - # // logllh - llForward = self.gpu_workspace[used_offset : used_offset + self.minibatch_] - used_offset += self.minibatch_ - llBackward = self.gpu_workspace[used_offset : used_offset + self.minibatch_] - used_offset += self.minibatch_ - - return used_offset, (denom, alphas, betas, llForward, llBackward) - - -class MultiblankGPURNNT(GPURNNT): - def __init__( - self, - sigma: float, - num_big_blanks: int, - minibatch: int, - maxT: int, - maxU: int, - alphabet_size: int, - workspace, - big_blank_workspace, - blank: int, - fastemit_lambda: float, - clamp: float, - num_threads: int, - stream, - ): - """ - Helper class to launch the CUDA Kernels to compute Multi-blank Transducer Loss (https://arxiv.org/pdf/2211.03541). - - Args: - sigma: Hyper-parameter related to the logit-normalization method in training multi-blank transducers. - num_big_blanks: Number of big blank symbols the model has. This should not include the standard blank symbol. - minibatch: Int representing the batch size. - maxT: The maximum possible acoustic sequence length. Represents T in the logprobs tensor. - maxU: The maximum possible target sequence length. Represents U in the logprobs tensor. - alphabet_size: The vocabulary dimension V + 1 + num-big-blanks - workspace: An allocated chunk of memory that will be sliced off and reshaped into required - blocks used as working memory. - big_blank_workspace: An allocated chunk of memory that will be sliced off and reshaped into required - blocks used as working memory specifically for the multi-blank related computations. - blank: Index of the RNNT blank token in the vocabulary. Generally the first or last token in the vocab. - fastemit_lambda: Float scaling factor for FastEmit regularization. Refer to - FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization. - clamp: Float value. When set to value >= 0.0, will clamp the gradient to [-clamp, clamp]. - num_threads: Number of OMP threads to launch. - stream: Numba Cuda Stream. - """ - super().__init__( - minibatch, maxT, maxU, alphabet_size, workspace, blank, fastemit_lambda, clamp, num_threads, stream - ) - self.big_blank_workspace = cuda.as_cuda_array( - big_blank_workspace - ) # a flat vector of integer numbers that represents allocated memory slices - - self.num_big_blanks = num_big_blanks - self.sigma = sigma - - def compute_cost_and_score( - self, - acts: torch.Tensor, - grads: Optional[torch.Tensor], - costs: torch.Tensor, - labels: torch.Tensor, - label_lengths: torch.Tensor, - input_lengths: torch.Tensor, - ) -> global_constants.RNNTStatus: - """ - Compute both the loss and the gradients. - - Args: - acts: A flattened tensor of shape [B, T, U, V+1] representing the activation matrix. - grad: A flattented zero tensor of same shape as acts. - costs: A zero vector of length B which will be updated inplace with the log probability costs. - flat_labels: A flattened matrix of labels of shape [B, U] - label_lengths: A vector of length B that contains the original lengths of the acoustic sequence. - input_lengths: A vector of length B that contains the original lengths of the target sequence. - - Updates: - This will launch kernels that will update inline the following variables: - - grads: Gradients of the activation matrix wrt the costs vector. - - costs: Negative log likelihood of the forward variable. - - Returns: - An enum that either represents a successful RNNT operation or failure. - """ - training = grads is not None - - if training: - grads *= 0.0 # zero grads - - _, (denom, alphas, betas, llForward, llBackward, bigblank_durations) = self._prepare_workspace() - - ######## START EXECUTION ######## - self.log_softmax(acts, denom) - - # Compute alphas - gpu_rnnt_kernel.compute_multiblank_alphas_kernel[self.minibatch_, self.maxU_, self.stream_, 0]( - acts, - denom, - self.sigma, - alphas, - llForward, - input_lengths, - label_lengths, - labels, - self.minibatch_, - self.maxT_, - self.maxU_, - self.alphabet_size_, - self.blank_, - bigblank_durations, - self.num_big_blanks, - ) - - if training: - # Compute betas - gpu_rnnt_kernel.compute_multiblank_betas_kernel[self.minibatch_, self.maxU_, self.stream_, 0]( - acts, - denom, - self.sigma, - betas, - llBackward, - input_lengths, - label_lengths, - labels, - self.minibatch_, - self.maxT_, - self.maxU_, - self.alphabet_size_, - self.blank_, - bigblank_durations, - self.num_big_blanks, - ) - - # Compute gradient - grad_blocks_per_grid = self.minibatch_ * self.maxT_ * self.maxU_ - grad_threads_per_block = gpu_rnnt_kernel.GPU_RNNT_THREAD_SIZE - gpu_rnnt_kernel.compute_multiblank_grad_kernel[ - grad_blocks_per_grid, grad_threads_per_block, self.stream_, 0 - ]( - grads, - acts, - denom, - self.sigma, - alphas, - betas, - llForward, - input_lengths, - label_lengths, - labels, - self.minibatch_, - self.maxT_, - self.maxU_, - self.alphabet_size_, - self.blank_, - bigblank_durations, - self.num_big_blanks, - self.fastemit_lambda_, - self.clamp_, - ) - - # // cost copy, negate (for log likelihood) and update with additional regularizers - # This needs to be done via CUDA, because we used temporary memory llForward - # passed to alpha, which was updated with log likelihoods. - # But copying this data into a pytorch pointer is more difficult (numba api is one way) - # Therefore launch a pointwise CUDA kernel to update the costs inplace from data of llForward - # Then negate to compute the loglikelihood. - threadsperblock = min(costs.shape[0], 32) - blockspergrid = (costs.shape[0] + (threadsperblock - 1)) // threadsperblock - rnnt_helper.compute_costs_data[blockspergrid, threadsperblock, self.stream_, 0]( - llForward, costs, self.fastemit_lambda_ - ) - self.stream_.synchronize() - - return global_constants.RNNTStatus.RNNT_STATUS_SUCCESS - - def cost_and_grad( - self, - acts: torch.Tensor, - grads: torch.Tensor, - costs: torch.Tensor, - pad_labels: torch.Tensor, - label_lengths: torch.Tensor, - input_lengths: torch.Tensor, - ): - if ( - acts is None - or grads is None - or costs is None - or pad_labels is None - or label_lengths is None - or input_lengths is None - ): - return global_constants.RNNTStatus.RNNT_STATUS_INVALID_VALUE - - return self.compute_cost_and_score(acts, grads, costs, pad_labels, label_lengths, input_lengths) - - def score_forward( - self, - acts: torch.Tensor, - costs: torch.Tensor, - pad_labels: torch.Tensor, - label_lengths: torch.Tensor, - input_lengths: torch.Tensor, - ): - if acts is None or costs is None or pad_labels is None or label_lengths is None or input_lengths is None: - return global_constants.RNNTStatus.RNNT_STATUS_INVALID_VALUE - - return self.compute_cost_and_score(acts, None, costs, pad_labels, label_lengths, input_lengths) - - def _prepare_workspace(self) -> (int, Tuple[torch.Tensor]): - """ - Helper method that uses the workspace and constructs slices of it that can be used. - - Returns: - An int, representing the offset of the used workspace (practically, the slice of the workspace consumed) - A tuple of tensors representing the shared workspace. - """ - used_offset, (denom, alphas, betas, llForward, llBackward) = super()._prepare_workspace() - - bigblank_durations = self.big_blank_workspace[: self.num_big_blanks] - - return used_offset, (denom, alphas, betas, llForward, llBackward, bigblank_durations) - - -class GPUTDT(GPURNNT): - def __init__( - self, - sigma: float, - omega: float, - num_durations: int, - minibatch: int, - maxT: int, - maxU: int, - alphabet_size: int, - workspace, - tdt_workspace, - blank: int, - fastemit_lambda: float, - clamp: float, - num_threads: int, - stream, - ): - """ - Helper class to launch the CUDA Kernels to compute TDT Loss (https://arxiv.org/pdf/2211.03541). - - Args: - sigma: Hyper-parameter related to the logit-normalization method in training tdt transducers. - omega: Hyper-parameter related to the sampled training. - num_durations: Number of durations the model supports. - minibatch: Int representing the batch size. - maxT: The maximum possible acoustic sequence length. Represents T in the logprobs tensor. - maxU: The maximum possible target sequence length. Represents U in the logprobs tensor. - alphabet_size: The vocabulary dimension V + 1 + num-big-blanks - workspace: An allocated chunk of memory that will be sliced off and reshaped into required - blocks used as working memory. - tdt_workspace: An allocated chunk of memory that will be sliced off and reshaped into required - blocks used as working memory specifically for the tdt related computations. - blank: Index of the blank token in the vocabulary. Must be the last token in the vocab. - fastemit_lambda: Float scaling factor for FastEmit regularization. Refer to - FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization. - clamp: Float value. When set to value >= 0.0, will clamp the gradient to [-clamp, clamp]. - num_threads: Number of OMP threads to launch. - stream: Numba Cuda Stream. - """ - super().__init__( - minibatch, maxT, maxU, alphabet_size, workspace, blank, fastemit_lambda, clamp, num_threads, stream - ) - self.tdt_workspace = cuda.as_cuda_array( - tdt_workspace - ) # a flat vector of integer numbers that represents allocated memory slices - - self.num_durations = num_durations - self.sigma = sigma - self.omega = omega - - def compute_cost_and_score( - self, - label_acts: torch.Tensor, - duration_acts: torch.Tensor, - label_grads: Optional[torch.Tensor], - duration_grads: Optional[torch.Tensor], - costs: torch.Tensor, - labels: torch.Tensor, - label_lengths: torch.Tensor, - input_lengths: torch.Tensor, - ) -> global_constants.RNNTStatus: - """ - Compute both the loss and the gradients. - - Args: - label_acts: A flattened tensor of shape [B, T, U, V] representing the activation matrix for tokens. - duration_acts: A flattened tensor of shape [B, T, U, D] representing the activation matrix for durations. - label_grad: A flattented zero tensor of same shape as label_acts. - duration_grad: A flattented zero tensor of same shape as duration_acts. - costs: A zero vector of length B which will be updated inplace with the log probability costs. - flat_labels: A flattened matrix of labels of shape [B, U] - label_lengths: A vector of length B that contains the original lengths of the acoustic sequence. - input_lengths: A vector of length B that contains the original lengths of the target sequence. - - Updates: - This will launch kernels that will update inline the following variables: - - *_grads: Gradients of the activation matrix wrt the costs vector. - - costs: Negative log likelihood of the forward variable. - - Returns: - An enum that either represents a successful RNNT operation or failure. - """ - training = label_grads is not None - - if training: - label_grads *= 0.0 # zero grads - duration_grads *= 0.0 # zero grads - - _, (denom, alphas, betas, llForward, llBackward, durations) = self._prepare_workspace() - - ######## START EXECUTION ######## - self.log_softmax(label_acts, denom) - - r = random.uniform(0, 1) - if r < self.omega: - # Compute alphas - gpu_rnnt_kernel.compute_alphas_kernel[self.minibatch_, self.maxU_, self.stream_, 0]( - label_acts, - denom, - alphas, - llForward, - input_lengths, - label_lengths, - labels, - self.minibatch_, - self.maxT_, - self.maxU_, - self.alphabet_size_, - self.blank_, - ) - else: - # Compute alphas - gpu_rnnt_kernel.compute_tdt_alphas_kernel[self.minibatch_, self.maxU_, self.stream_, 0]( - label_acts, - duration_acts, - denom, - self.sigma, - alphas, - llForward, - input_lengths, - label_lengths, - labels, - self.minibatch_, - self.maxT_, - self.maxU_, - self.alphabet_size_, - self.blank_, - durations, - self.num_durations, - ) - - if training: - # Compute betas - if r < self.omega: - gpu_rnnt_kernel.compute_betas_kernel[self.minibatch_, self.maxU_, self.stream_, 0]( - label_acts, - denom, - betas, - llBackward, - input_lengths, - label_lengths, - labels, - self.minibatch_, - self.maxT_, - self.maxU_, - self.alphabet_size_, - self.blank_, - ) - - # Compute gradient - grad_blocks_per_grid = self.minibatch_ * self.maxT_ * self.maxU_ - grad_threads_per_block = gpu_rnnt_kernel.GPU_RNNT_THREAD_SIZE - gpu_rnnt_kernel.compute_grad_kernel[grad_blocks_per_grid, grad_threads_per_block, self.stream_, 0]( - label_grads, - label_acts, - denom, - alphas, - betas, - llForward, - input_lengths, - label_lengths, - labels, - self.minibatch_, - self.maxT_, - self.maxU_, - self.alphabet_size_, - self.blank_, - self.fastemit_lambda_, - self.clamp_, - ) - else: - gpu_rnnt_kernel.compute_tdt_betas_kernel[self.minibatch_, self.maxU_, self.stream_, 0]( - label_acts, - duration_acts, - denom, - self.sigma, - betas, - llBackward, - input_lengths, - label_lengths, - labels, - self.minibatch_, - self.maxT_, - self.maxU_, - self.alphabet_size_, - self.blank_, - durations, - self.num_durations, - ) - - # Compute gradient - grad_blocks_per_grid = self.minibatch_ * self.maxT_ * self.maxU_ - grad_threads_per_block = gpu_rnnt_kernel.GPU_RNNT_THREAD_SIZE - gpu_rnnt_kernel.compute_tdt_grad_kernel[grad_blocks_per_grid, grad_threads_per_block, self.stream_, 0]( - label_grads, - duration_grads, - label_acts, - duration_acts, - denom, - self.sigma, - alphas, - betas, - llForward, - input_lengths, - label_lengths, - labels, - self.minibatch_, - self.maxT_, - self.maxU_, - self.alphabet_size_, - self.blank_, - durations, - self.num_durations, - self.fastemit_lambda_, - self.clamp_, - ) - - # // cost copy, negate (for log likelihood) and update with additional regularizers - # This needs to be done via CUDA, because we used temporary memory llForward - # passed to alpha, which was updated with log likelihoods. - # But copying this data into a pytorch pointer is more difficult (numba api is one way) - # Therefore launch a pointwise CUDA kernel to update the costs inplace from data of llForward - # Then negate to compute the loglikelihood. - threadsperblock = min(costs.shape[0], 32) - blockspergrid = (costs.shape[0] + (threadsperblock - 1)) // threadsperblock - rnnt_helper.compute_costs_data[blockspergrid, threadsperblock, self.stream_, 0]( - llForward, costs, self.fastemit_lambda_ - ) - self.stream_.synchronize() - - return global_constants.RNNTStatus.RNNT_STATUS_SUCCESS - - def cost_and_grad( - self, - label_acts: torch.Tensor, - duration_acts: torch.Tensor, - label_grads: torch.Tensor, - duration_grads: torch.Tensor, - costs: torch.Tensor, - pad_labels: torch.Tensor, - label_lengths: torch.Tensor, - input_lengths: torch.Tensor, - ): - if ( - duration_acts is None - or label_acts is None - or label_grads is None - or duration_grads is None - or costs is None - or pad_labels is None - or label_lengths is None - or input_lengths is None - ): - return global_constants.RNNTStatus.RNNT_STATUS_INVALID_VALUE - - return self.compute_cost_and_score( - label_acts, duration_acts, label_grads, duration_grads, costs, pad_labels, label_lengths, input_lengths - ) - - def score_forward( - self, - label_acts: torch.Tensor, - duration_acts: torch.Tensor, - costs: torch.Tensor, - pad_labels: torch.Tensor, - label_lengths: torch.Tensor, - input_lengths: torch.Tensor, - ): - if ( - label_acts is None - or duration_acts is None - or costs is None - or pad_labels is None - or label_lengths is None - or input_lengths is None - ): - return global_constants.RNNTStatus.RNNT_STATUS_INVALID_VALUE - - return self.compute_cost_and_score( - label_acts, duration_acts, None, None, costs, pad_labels, label_lengths, input_lengths - ) - - def _prepare_workspace(self) -> (int, Tuple[torch.Tensor]): - """ - Helper method that uses the workspace and constructs slices of it that can be used. - - Returns: - An int, representing the offset of the used workspace (practically, the slice of the workspace consumed) - A tuple of tensors representing the shared workspace. - """ - used_offset, (denom, alphas, betas, llForward, llBackward) = super()._prepare_workspace() - - durations = self.tdt_workspace[: self.num_durations] - - return used_offset, (denom, alphas, betas, llForward, llBackward, durations) diff --git a/nemo/collections/asr/parts/numba/rnnt_loss/utils/cuda_utils/gpu_rnnt_kernel.py b/nemo/collections/asr/parts/numba/rnnt_loss/utils/cuda_utils/gpu_rnnt_kernel.py deleted file mode 100644 index 219e9d0453b2d48ebaaeed9e743312636adad2d7..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/numba/rnnt_loss/utils/cuda_utils/gpu_rnnt_kernel.py +++ /dev/null @@ -1,1439 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Copyright 2018-2019, Mingkun Huang -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import math - -import torch -from numba import cuda - -from nemo.collections.asr.parts.numba.rnnt_loss.utils import rnnt_helper - -GPU_RNNT_THREAD_SIZE = 256 - -INF = 10000.0 - - -@cuda.jit(device=True, inline=True) -def logp( - denom: torch.Tensor, acts: torch.Tensor, maxT: int, maxU: int, alphabet_size: int, mb: int, t: int, u: int, v: int -): - """ - Compute the sum of log probability from the activation tensor and its denominator. - - Args: - denom: Tensor of shape [B, T, U] flattened. Represents the denominator of the logprobs activation tensor - across entire vocabulary. - acts: Tensor of shape [B, T, U, V+1] flattened. Represents the logprobs activation tensor. - maxT: The maximum possible acoustic sequence length. Represents T in the logprobs tensor. - maxU: The maximum possible target sequence length. Represents U in the logprobs tensor. - alphabet_size: The vocabulary dimension V+1 (inclusive of RNNT blank). - mb: Batch indexer. - t: Acoustic sequence timestep indexer. - u: Target sequence timestep indexer. - v: Vocabulary token indexer. - - Returns: - The sum of logprobs[mb, t, u, v] + denom[mb, t, u] - """ - col = (mb * maxT + t) * maxU + u - return denom[col] + acts[col * alphabet_size + v] - - -@cuda.jit(device=True, inline=True) -def logp_duration(acts: torch.Tensor, maxT: int, maxU: int, num_durations: int, mb: int, t: int, u: int, v: int): - col = (mb * maxT + t) * maxU + u - return acts[col * num_durations + v] - - -@cuda.jit() -def compute_alphas_kernel( - acts: torch.Tensor, - denom: torch.Tensor, - alphas: torch.Tensor, - llForward: torch.Tensor, - xlen: torch.Tensor, - ylen: torch.Tensor, - mlabels: torch.Tensor, # [B] - minibatch: int, - maxT: int, - maxU: int, - alphabet_size: int, - blank_: int, -): - """ - Compute alpha (forward variable) probabilities over the transduction step. - - Args: - acts: Tensor of shape [B, T, U, V+1] flattened. Represents the logprobs activation tensor. - denom: Tensor of shape [B, T, U] flattened. Represents the denominator of the logprobs activation tensor - across entire vocabulary. - alphas: Zero tensor of shape [B, T, U]. Will be updated inside the kernel with the forward variable - probabilities. - llForward: Zero tensor of shape [B]. Represents the log-likelihood of the forward pass. - Returned as the forward pass loss that is reduced by the optimizer. - xlen: Vector of length B which contains the actual acoustic sequence lengths in the padded - activation tensor. - ylen: Vector of length B which contains the actual target sequence lengths in the padded - activation tensor. - mlabels: Matrix of shape [B, U+1] (+1 here is due to token - usually the RNNT blank). - The matrix contains the padded target transcription that must be predicted. - minibatch: Int representing the batch size. - maxT: The maximum possible acoustic sequence length. Represents T in the logprobs tensor. - maxU: The maximum possible target sequence length. Represents U in the logprobs tensor. - alphabet_size: The vocabulary dimension V+1 (inclusive of RNNT blank). - blank_: Index of the RNNT blank token in the vocabulary. Generally the first or last token in the vocab. - - Updates: - Kernel inplace updates the following inputs: - - alphas: forward variable scores. - - llForward: log-likelihood of forward variable. - """ - # // launch B blocks, each block has U threads - b = cuda.blockIdx.x # // batch id - u = cuda.threadIdx.x # label id, u - T = xlen[b] # select AM length of current sample - U = ylen[b] + 1 # select target length of current sample, +1 for the blank token - - labels: torch.Tensor = mlabels[b] # mb label start point, equivalent to mlabels + b * (maxU - 1) - offset = b * maxT * maxU # pointer indexing offset - - # alphas += offset # pointer offset, ignored since we explicitly add offset - - # Initilize alpha[b, t=0, u=0] for all b in B - if u == 0: - alphas[offset] = 0 - - # sync until all alphas are initialized - cuda.syncthreads() - - # Ordinary alpha calculations, broadcast across B=b and U=u - # Look up forward variable calculation from rnnt_numpy.forward_pass() - for n in range(1, T + U - 1): - t = n - u - - if u == 0: - # for t in range(1, T) step to initialize alphas[b, t, 0] - if t > 0 and t < T: - alphas[offset + t * maxU + u] = alphas[offset + (t - 1) * maxU + u] + logp( - denom, acts, maxT, maxU, alphabet_size, b, t - 1, 0, blank_ - ) - elif u < U: - # for u in range(1, U) step to initialize alphas[b, 0, u] - if t == 0: - alphas[offset + u] = alphas[offset + u - 1] + logp( - denom, acts, maxT, maxU, alphabet_size, b, 0, u - 1, labels[u - 1] - ) - - # for t in range(1, T) for u in range(1, U) step to compute alphas[b, t, u] - elif t > 0 and t < T: - no_emit = alphas[offset + (t - 1) * maxU + u] + logp( - denom, acts, maxT, maxU, alphabet_size, b, t - 1, u, blank_ - ) - emit = alphas[offset + t * maxU + u - 1] + logp( - denom, acts, maxT, maxU, alphabet_size, b, t, u - 1, labels[u - 1] - ) - - alphas[offset + t * maxU + u] = rnnt_helper.log_sum_exp(emit, no_emit) - - # sync across all B=b and U=u - cuda.syncthreads() - - # After final sync, alphas[b, T-1, U - 1] + logprobs[b, T-1, U-1, blank] + denom[b, T-1, U-1] gives - # log-likelihood of forward pass. - if u == 0: - loglike = alphas[offset + (T - 1) * maxU + U - 1] + logp( - denom, acts, maxT, maxU, alphabet_size, b, T - 1, U - 1, blank_ - ) - llForward[b] = loglike - - -@cuda.jit() -def compute_betas_kernel( - acts: torch.Tensor, - denom: torch.Tensor, - betas: torch.Tensor, - llBackward: torch.Tensor, - xlen: torch.Tensor, - ylen: torch.Tensor, - mlabels: torch.Tensor, # [B, U] - minibatch: int, - maxT: int, - maxU: int, - alphabet_size: int, - blank_: int, -): - """ - Compute beta (backward variable) probabilities over the transduction step. - - Args: - acts: Tensor of shape [B, T, U, V+1] flattened. Represents the logprobs activation tensor. - denom: Tensor of shape [B, T, U] flattened. Represents the denominator of the logprobs activation tensor - across entire vocabulary. - betas: Zero tensor of shape [B, T, U]. Will be updated inside the kernel with the backward variable - probabilities. - llBackward: Zero tensor of shape [B]. Represents the log-likelihood of the backward pass. - Returned as the backward pass loss that is reduced by the optimizer. - xlen: Vector of length B which contains the actual acoustic sequence lengths in the padded - activation tensor. - ylen: Vector of length B which contains the actual target sequence lengths in the padded - activation tensor. - mlabels: Matrix of shape [B, U+1] (+1 here is due to token - usually the RNNT blank). - The matrix contains the padded target transcription that must be predicted. - minibatch: Int representing the batch size. - maxT: The maximum possible acoustic sequence length. Represents T in the logprobs tensor. - maxU: The maximum possible target sequence length. Represents U in the logprobs tensor. - alphabet_size: The vocabulary dimension V+1 (inclusive of RNNT blank). - blank_: Index of the RNNT blank token in the vocabulary. Generally the first or last token in the vocab. - - Updates: - Kernel inplace updates the following inputs: - - betas: backward variable scores. - - llBackward: log-likelihood of backward variable. - """ - # // launch B blocks, each block has U threads - b = cuda.blockIdx.x # // batch id - u = cuda.threadIdx.x # label id, u - T = xlen[b] # select AM length of current sample - U = ylen[b] + 1 # select target length of current sample, +1 for the blank token - - labels: torch.Tensor = mlabels[b] # mb label start point, equivalent to mlabels + b * (maxU - 1) - offset = b * maxT * maxU # pointer indexing offset - - # betas += offset # pointer offset, ignored since we explicitly add offset - - # Initilize beta[b, t=T-1, u=U-1] for all b in B with log_probs[b, t=T-1, u=U-1, blank] - if u == 0: - betas[offset + (T - 1) * maxU + U - 1] = logp(denom, acts, maxT, maxU, alphabet_size, b, T - 1, U - 1, blank_) - - # sync until all betas are initialized - cuda.syncthreads() - - # Ordinary beta calculations, broadcast across B=b and U=u - # Look up backward variable calculation from rnnt_numpy.backward_pass() - for n in range(T + U - 2, -1, -1): - t = n - u - - if u == (U - 1): - # for t in reversed(range(T - 1)) step to initialize betas[b, t, U-1] - if t >= 0 and t < (T - 1): - betas[offset + t * maxU + U - 1] = betas[offset + (t + 1) * maxU + U - 1] + logp( - denom, acts, maxT, maxU, alphabet_size, b, t, U - 1, blank_ - ) - elif u < U: - if t == T - 1: - # for u in reversed(range(U - 1)) step to initialize betas[b, T-1, u] - betas[offset + (T - 1) * maxU + u] = betas[offset + (T - 1) * maxU + u + 1] + logp( - denom, acts, maxT, maxU, alphabet_size, b, T - 1, u, labels[u] - ) - elif (t >= 0) and (t < T - 1): - # for t in reversed(range(T - 1)) for u in reversed(range(U - 1)) step to compute betas[b, t, u] - no_emit = betas[offset + (t + 1) * maxU + u] + logp( - denom, acts, maxT, maxU, alphabet_size, b, t, u, blank_ - ) - emit = betas[offset + t * maxU + u + 1] + logp( - denom, acts, maxT, maxU, alphabet_size, b, t, u, labels[u] - ) - betas[offset + t * maxU + u] = rnnt_helper.log_sum_exp(emit, no_emit) - - # sync across all B=b and U=u - cuda.syncthreads() - - # After final sync, betas[b, 0, 0] gives - # log-likelihood of backward pass. - if u == 0: - llBackward[b] = betas[offset] - - -@cuda.jit() -def compute_grad_kernel( - grads: torch.Tensor, - acts: torch.Tensor, - denom: torch.Tensor, - alphas: torch.Tensor, - betas: torch.Tensor, - logll: torch.Tensor, - xlen: torch.Tensor, - ylen: torch.Tensor, - mlabels: torch.Tensor, # [B, U] - minibatch: int, - maxT: int, - maxU: int, - alphabet_size: int, - blank_: int, - fastemit_lambda: float, - clamp: float, -): - """ - Compute gradients over the transduction step. - - Args: - grads: Zero Tensor of shape [B, T, U, V+1]. Is updated by this kernel to contain the gradients - of this batch of samples. - acts: Tensor of shape [B, T, U, V+1] flattened. Represents the logprobs activation tensor. - denom: Tensor of shape [B, T, U] flattened. Represents the denominator of the logprobs activation tensor - across entire vocabulary. - alphas: Alpha variable, contains forward probabilities. A tensor of shape [B, T, U]. - betas: Beta varoable, contains backward probabilities. A tensor of shape [B, T, U]. - logll: Log-likelihood of the forward variable, represented as a vector of shape [B]. - Represents the log-likelihood of the forward pass. - xlen: Vector of length B which contains the actual acoustic sequence lengths in the padded - activation tensor. - ylen: Vector of length B which contains the actual target sequence lengths in the padded - activation tensor. - mlabels: Matrix of shape [B, U+1] (+1 here is due to token - usually the RNNT blank). - The matrix contains the padded target transcription that must be predicted. - minibatch: Int representing the batch size. - maxT: The maximum possible acoustic sequence length. Represents T in the logprobs tensor. - maxU: The maximum possible target sequence length. Represents U in the logprobs tensor. - alphabet_size: The vocabulary dimension V+1 (inclusive of RNNT blank). - blank_: Index of the RNNT blank token in the vocabulary. Generally the first or last token in the vocab. - fastemit_lambda: Float scaling factor for FastEmit regularization. Refer to - FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization. - clamp: Float value. When set to value >= 0.0, will clamp the gradient to [-clamp, clamp]. - - Updates: - Kernel inplace updates the following inputs: - - grads: Gradients with respect to the log likelihood (logll). - """ - # Kernel call: - # blocks_per_grid = minibatch (b) * maxT (t) * maxU (u) - # threads_per_block = constant buffer size of parallel threads (v :: Constant) - tid = cuda.threadIdx.x # represents v, taking steps of some constant size - idx = tid # index of v < V+1; in steps of constant buffer size - col = cuda.blockIdx.x # represents a fused index of b * t * u - - # Decompose original indices from fused `col` - u = col % maxU # (b * t * u) % u = u - bt = (col - u) // maxU # (b * t * u - u) // U = b * t - t = bt % maxT # (b * t) % t = t - mb = (bt - t) // maxT # (b * t - t) // T = b - - # constants - T = xlen[mb] # select AM length of current sample - U = ylen[mb] + 1 # select target length of current sample, +1 for the blank token - labels: torch.Tensor = mlabels[mb] # labels = mlabels + mb * (maxU - 1); - - # Buffered gradient calculations, broadcast across B=b, T=t and U=u, looped over V with some constant stride. - # Look up gradient calculation from rnnt_numpy.compute_gradient() - if t < T and u < U: - # For cuda kernels, maximum number of threads per block is limited to some value. - # However, it may be the case that vocabulary size is larger than this limit - # To work around this, an arbitrary thread buffer size is chosen such that, - # 1) each element within the thread pool operates independently of the other - # 2) An inner while loop moves the index of each buffer element by the size of the buffer itself, - # such that all elements of the vocabulary size are covered in (V + 1 // thread_buffer) number of steps. - # As such, each thread will perform the while loop at least (V + 1 // thread_buffer) number of times - while idx < alphabet_size: - # remember, `col` represents the tri-index [b, t, u] - # therefore; logpk = denom[b, t, u] + acts[b, t, u, v] - logpk = denom[col] + acts[col * alphabet_size + idx] - # initialize the grad of the sample acts[b, t, u, v] - grad = math.exp(alphas[col] + betas[col] + logpk - logll[mb]) - - # If FastEmit regularization is enabled, calculate the gradeint of probability of predicting the next label - # at the current timestep. - # The formula for this is Equation 9 in https://arxiv.org/abs/2010.11148, multiplied by the log probability - # of the current step (t, u), normalized by the total log likelihood. - # Once the gradient has been calculated, scale it by `fastemit_lambda`, as in Equation 10. - if fastemit_lambda > 0.0 and u < U - 1: - fastemit_grad = fastemit_lambda * math.exp( - alphas[col] # alphas(t, u) - + (denom[col] + acts[col * alphabet_size + labels[u]]) # y_hat(t, u) - + betas[col + 1] # betas(t, u+1) - + logpk # log Pr(k|t, u) - - logll[mb] # total log likelihood for normalization - ) - else: - fastemit_grad = 0.0 - - # Update the gradient of act[b, t, u, v] with the gradient from FastEmit regularization - grad = grad + fastemit_grad - - # // grad to last blank transition - # grad[b, T-1, U-1, v=blank] -= exp(alphas[b, t, u) + logpk - logll[b]) - if (idx == blank_) and (t == T - 1) and (u == U - 1): - grad -= math.exp(alphas[col] + logpk - logll[mb]) - - # grad of blank across t < T; - # grad[b, t 0.0: - g = grads[col * alphabet_size + idx] - g = min(g, clamp) - g = max(g, -clamp) - grads[col * alphabet_size + idx] = g - - # update internal index through the thread_buffer; - # until idx < V + 1, such that entire vocabulary has been updated. - idx += GPU_RNNT_THREAD_SIZE - - -@cuda.jit() -def compute_multiblank_alphas_kernel( - acts: torch.Tensor, - denom: torch.Tensor, - sigma: float, - alphas: torch.Tensor, - llForward: torch.Tensor, - xlen: torch.Tensor, - ylen: torch.Tensor, - mlabels: torch.Tensor, - minibatch: int, - maxT: int, - maxU: int, - alphabet_size: int, - blank_: int, - big_blank_duration: torch.Tensor, - num_big_blanks: int, -): - """ - Compute alpha (forward variable) probabilities for multi-blank transducuer loss (https://arxiv.org/pdf/2211.03541). - - Args: - acts: Tensor of shape [B, T, U, V + 1 + num_big_blanks] flattened. Represents the logprobs activation tensor. - denom: Tensor of shape [B, T, U] flattened. Represents the denominator of the logprobs activation tensor - across entire vocabulary. - sigma: Hyper-parameter for logit-undernormalization technique for training multi-blank transducers. - alphas: Zero tensor of shape [B, T, U]. Will be updated inside the kernel with the forward variable - probabilities. - llForward: Zero tensor of shape [B]. Represents the log-likelihood of the forward pass. - Returned as the forward pass loss that is reduced by the optimizer. - xlen: Vector of length B which contains the actual acoustic sequence lengths in the padded - activation tensor. - ylen: Vector of length B which contains the actual target sequence lengths in the padded - activation tensor. - mlabels: Matrix of shape [B, U+1] (+1 here is due to token - usually the RNNT blank). - The matrix contains the padded target transcription that must be predicted. - minibatch: Int representing the batch size. - maxT: The maximum possible acoustic sequence length. Represents T in the logprobs tensor. - maxU: The maximum possible target sequence length. Represents U in the logprobs tensor. - alphabet_size: The vocabulary dimension V+1 (inclusive of RNNT blank). - blank_: Index of the RNNT standard blank token in the vocabulary. - big_blank_durations: Vector of supported big blank durations of the model. - num_big_blanks: Number of big blanks of the model. - - Updates: - Kernel inplace updates the following inputs: - - alphas: forward variable scores. - - llForward: log-likelihood of forward variable. - """ - # // launch B blocks, each block has U threads - b = cuda.blockIdx.x # // batch id - u = cuda.threadIdx.x # label id, u - T = xlen[b] # select AM length of current sample - U = ylen[b] + 1 # select target length of current sample, +1 for the blank token - - labels: torch.Tensor = mlabels[b] # mb label start point, equivalent to mlabels + b * (maxU - 1) - offset = b * maxT * maxU # pointer indexing offset - - # Initilize alpha[b, t=0, u=0] for all b in B - if u == 0: - alphas[offset] = 0 - - # sync until all alphas are initialized - cuda.syncthreads() - - # Ordinary alpha calculations, broadcast across B=b and U=u - # Look up forward variable calculation from rnnt_numpy.forward_pass() - # Note: because of the logit under-normalization, everytime logp() is called, - # it is always followed by a `-sigma` term. - for n in range(1, T + U - 1): - t = n - u - - if u == 0: - # for t in range(1, T) step to initialize alphas[b, t, 0] - if t > 0 and t < T: - alphas[offset + t * maxU + u] = ( - alphas[offset + (t - 1) * maxU + u] - + logp(denom, acts, maxT, maxU, alphabet_size, b, t - 1, 0, blank_) - - sigma - ) - - # Now add the weights for big blanks. - for i in range(num_big_blanks): - if t >= big_blank_duration[i]: - alphas[offset + t * maxU + u] = rnnt_helper.log_sum_exp( - alphas[offset + t * maxU + u], - alphas[offset + (t - big_blank_duration[i]) * maxU + u] - + logp( - denom, acts, maxT, maxU, alphabet_size, b, t - big_blank_duration[i], 0, blank_ - 1 - i - ) - - sigma, - ) - - elif u < U: - # for u in range(1, U) step to initialize alphas[b, 0, u] - if t == 0: - alphas[offset + u] = ( - alphas[offset + u - 1] - + logp(denom, acts, maxT, maxU, alphabet_size, b, 0, u - 1, labels[u - 1]) - - sigma - ) - - # for t in range(1, T) for u in range(1, U) step to compute alphas[b, t, u] - elif t > 0 and t < T: - no_emit = ( - alphas[offset + (t - 1) * maxU + u] - + logp(denom, acts, maxT, maxU, alphabet_size, b, t - 1, u, blank_) - - sigma - ) - emit = ( - alphas[offset + t * maxU + u - 1] - + logp(denom, acts, maxT, maxU, alphabet_size, b, t, u - 1, labels[u - 1]) - - sigma - ) - - alphas[offset + t * maxU + u] = rnnt_helper.log_sum_exp(emit, no_emit) - - # Now add the weights for big blanks. - for i in range(num_big_blanks): - if t >= big_blank_duration[i]: - # big-blank weight here is - # alpha(t - duration, u) * p(big-blank | t - duration, u) / exp(sigma), in log domain - # do this all all big-blanks if the above condition is met - big_blank_no_emit = ( - alphas[offset + (t - big_blank_duration[i]) * maxU + u] - + logp( - denom, acts, maxT, maxU, alphabet_size, b, t - big_blank_duration[i], u, blank_ - 1 - i - ) - - sigma - ) - alphas[offset + t * maxU + u] = rnnt_helper.log_sum_exp( - alphas[offset + t * maxU + u], big_blank_no_emit - ) - - # sync across all B=b and U=u - cuda.syncthreads() - - # After final sync, alphas[b, T-1, U - 1] + logprobs[b, T-1, U-1, blank] + denom[b, T-1, U-1] gives - # log-likelihood of forward pass. - if u == 0: - loglike = ( - alphas[offset + (T - 1) * maxU + U - 1] - + logp(denom, acts, maxT, maxU, alphabet_size, b, T - 1, U - 1, blank_) - - sigma - ) - - # Now add the weights for big blanks for the final weight computation. - for i in range(num_big_blanks): - if T >= big_blank_duration[i]: - big_blank_loglike = ( - alphas[offset + (T - big_blank_duration[i]) * maxU + U - 1] - + logp(denom, acts, maxT, maxU, alphabet_size, b, T - big_blank_duration[i], U - 1, blank_ - 1 - i) - - sigma - ) - loglike = rnnt_helper.log_sum_exp(loglike, big_blank_loglike) - - llForward[b] = loglike - - -@cuda.jit() -def compute_multiblank_betas_kernel( - acts: torch.Tensor, - denom: torch.Tensor, - sigma: float, - betas: torch.Tensor, - llBackward: torch.Tensor, - xlen: torch.Tensor, - ylen: torch.Tensor, - mlabels: torch.Tensor, # [B, U] - minibatch: int, - maxT: int, - maxU: int, - alphabet_size: int, - blank_: int, - big_blank_duration: torch.Tensor, - num_big_blanks: int, -): - """ - Compute beta (backward variable) probabilities for multi-blank transducer loss (https://arxiv.org/pdf/2211.03541). - - Args: - acts: Tensor of shape [B, T, U, V + 1 + num-big-blanks] flattened. Represents the logprobs activation tensor. - denom: Tensor of shape [B, T, U] flattened. Represents the denominator of the logprobs activation tensor - across entire vocabulary. - sigma: Hyper-parameter for logit-undernormalization technique for training multi-blank transducers. - betas: Zero tensor of shape [B, T, U]. Will be updated inside the kernel with the backward variable - probabilities. - llBackward: Zero tensor of shape [B]. Represents the log-likelihood of the backward pass. - Returned as the backward pass loss that is reduced by the optimizer. - xlen: Vector of length B which contains the actual acoustic sequence lengths in the padded - activation tensor. - ylen: Vector of length B which contains the actual target sequence lengths in the padded - activation tensor. - mlabels: Matrix of shape [B, U+1] (+1 here is due to token - usually the RNNT blank). - The matrix contains the padded target transcription that must be predicted. - minibatch: Int representing the batch size. - maxT: The maximum possible acoustic sequence length. Represents T in the logprobs tensor. - maxU: The maximum possible target sequence length. Represents U in the logprobs tensor. - alphabet_size: The vocabulary dimension V+1 (inclusive of RNNT blank). - blank_: Index of the RNNT standard blank token in the vocabulary. - big_blank_durations: Vector of supported big blank durations of the model. - num_big_blanks: Number of big blanks of the model. - - Updates: - Kernel inplace updates the following inputs: - - betas: backward variable scores. - - llBackward: log-likelihood of backward variable. - """ - # // launch B blocks, each block has U threads - b = cuda.blockIdx.x # // batch id - u = cuda.threadIdx.x # label id, u - T = xlen[b] # select AM length of current sample - U = ylen[b] + 1 # select target length of current sample, +1 for the blank token - - labels: torch.Tensor = mlabels[b] # mb label start point, equivalent to mlabels + b * (maxU - 1) - offset = b * maxT * maxU # pointer indexing offset - - # Note: just like the alphas, because of the logit under-normalization, everytime - # logp() is called, it is always followed by a `-sigma` term. - - # Initilize beta[b, t=T-1, u=U-1] for all b in B with log_probs[b, t=T-1, u=U-1, blank] - if u == 0: - betas[offset + (T - 1) * maxU + U - 1] = ( - logp(denom, acts, maxT, maxU, alphabet_size, b, T - 1, U - 1, blank_) - sigma - ) - - # sync until all betas are initialized - cuda.syncthreads() - - # Ordinary beta calculations, broadcast across B=b and U=u - # Look up backward variable calculation from rnnt_numpy.backward_pass() - for n in range(T + U - 2, -1, -1): - t = n - u - - if u == (U - 1): - # for t in reversed(range(T - 1)) step to initialize betas[b, t, U-1] - if t >= 0 and t < (T - 1): - # beta[t, U - 1] = beta[t + 1, U - 1] * p(blank | t, U - 1) / exp(sigma) - # this part is the same as regular RNN-T. - betas[offset + t * maxU + U - 1] = ( - betas[offset + (t + 1) * maxU + U - 1] - + logp(denom, acts, maxT, maxU, alphabet_size, b, t, U - 1, blank_) - - sigma - ) - - # now add the weights from big blanks - for i in range(num_big_blanks): - if t + big_blank_duration[i] < T: - # adding to beta[t, U - 1] of weight (in log domain), - # beta[t + duration, U - 1] * p(big-blank | t, U - 1) / exp(sigma) - betas[offset + t * maxU + U - 1] = rnnt_helper.log_sum_exp( - betas[offset + t * maxU + U - 1], - betas[offset + (t + big_blank_duration[i]) * maxU + U - 1] - + logp(denom, acts, maxT, maxU, alphabet_size, b, t, U - 1, blank_ - 1 - i) - - sigma, - ) - elif t + big_blank_duration[i] == T and big_blank_duration[i] != 1: - # adding to beta[T - duration, U - 1] of weight (in log domain), - # p(big-blank | T - duration, U - 1) / exp(sigma) - betas[offset + t * maxU + U - 1] = rnnt_helper.log_sum_exp( - betas[offset + t * maxU + U - 1], - logp(denom, acts, maxT, maxU, alphabet_size, b, t, U - 1, blank_ - 1 - i) - sigma, - ) - - elif u < U: - if t == T - 1: - # for u in reversed(range(U - 1)) step to initialize betas[b, T-1, u] - betas[offset + (T - 1) * maxU + u] = ( - betas[offset + (T - 1) * maxU + u + 1] - + logp(denom, acts, maxT, maxU, alphabet_size, b, T - 1, u, labels[u]) - - sigma - ) - elif (t >= 0) and (t < T - 1): - # for t in reversed(range(T - 1)) for u in reversed(range(U - 1)) step to compute betas[b, t, u] - no_emit = ( - betas[offset + (t + 1) * maxU + u] - + logp(denom, acts, maxT, maxU, alphabet_size, b, t, u, blank_) - - sigma - ) - emit = ( - betas[offset + t * maxU + u + 1] - + logp(denom, acts, maxT, maxU, alphabet_size, b, t, u, labels[u]) - - sigma - ) - betas[offset + t * maxU + u] = rnnt_helper.log_sum_exp(emit, no_emit) - - # now add the weights from big blanks - for i in range(num_big_blanks): - if t < T - big_blank_duration[i]: - # added weight for the big-blank, - # beta[t + duration, u] * p(big-blank | t, u) / exp(sigma) - big_blank_no_emit = ( - betas[offset + (t + big_blank_duration[i]) * maxU + u] - + logp(denom, acts, maxT, maxU, alphabet_size, b, t, u, blank_ - 1 - i) - - sigma - ) - betas[offset + t * maxU + u] = rnnt_helper.log_sum_exp( - betas[offset + t * maxU + u], big_blank_no_emit - ) - - # sync across all B=b and U=u - cuda.syncthreads() - - # After final sync, betas[b, 0, 0] gives - # log-likelihood of backward pass. - if u == 0: - llBackward[b] = betas[offset] - - -@cuda.jit() -def compute_multiblank_grad_kernel( - grads: torch.Tensor, - acts: torch.Tensor, - denom: torch.Tensor, - sigma: float, - alphas: torch.Tensor, - betas: torch.Tensor, - logll: torch.Tensor, - xlen: torch.Tensor, - ylen: torch.Tensor, - mlabels: torch.Tensor, # [B, U] - minibatch: int, - maxT: int, - maxU: int, - alphabet_size: int, - blank_: int, - big_blank_duration: torch.Tensor, - num_big_blanks: int, - fastemit_lambda: float, - clamp: float, -): - """ - Compute gradients for multi-blank transducer loss (https://arxiv.org/pdf/2211.03541). - - Args: - grads: Zero Tensor of shape [B, T, U, V + 1 + num_big_blanks]. Is updated by this kernel to contain the gradients - of this batch of samples. - acts: Tensor of shape [B, T, U, V + 1 + num_big_blanks] flattened. Represents the logprobs activation tensor. - denom: Tensor of shape [B, T, U] flattened. Represents the denominator of the logprobs activation tensor - across entire vocabulary. - sigma: Hyper-parameter for logit-undernormalization technique for training multi-blank transducers. - alphas: Alpha variable, contains forward probabilities. A tensor of shape [B, T, U]. - betas: Beta varoable, contains backward probabilities. A tensor of shape [B, T, U]. - logll: Log-likelihood of the forward variable, represented as a vector of shape [B]. - Represents the log-likelihood of the forward pass. - xlen: Vector of length B which contains the actual acoustic sequence lengths in the padded - activation tensor. - ylen: Vector of length B which contains the actual target sequence lengths in the padded - activation tensor. - mlabels: Matrix of shape [B, U+1] (+1 here is due to token - usually the RNNT blank). - The matrix contains the padded target transcription that must be predicted. - minibatch: Int representing the batch size. - maxT: The maximum possible acoustic sequence length. Represents T in the logprobs tensor. - maxU: The maximum possible target sequence length. Represents U in the logprobs tensor. - alphabet_size: The vocabulary dimension V+1 (inclusive of RNNT blank). - blank_: Index of the RNNT blank token in the vocabulary. Generally the first or last token in the vocab. - fastemit_lambda: Float scaling factor for FastEmit regularization. Refer to - FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization. - clamp: Float value. When set to value >= 0.0, will clamp the gradient to [-clamp, clamp]. - big_blank_durations: Vector of supported big blank durations of the model. - num_big_blanks: Number of big blanks of the model. - - Updates: - Kernel inplace updates the following inputs: - - grads: Gradients with respect to the log likelihood (logll). - """ - # Kernel call: - # blocks_per_grid = minibatch (b) * maxT (t) * maxU (u) - # threads_per_block = constant buffer size of parallel threads (v :: Constant) - tid = cuda.threadIdx.x # represents v, taking steps of some constant size - idx = tid # index of v < V+1; in steps of constant buffer size - col = cuda.blockIdx.x # represents a fused index of b * t * u - - # Decompose original indices from fused `col` - u = col % maxU # (b * t * u) % u = u - bt = (col - u) // maxU # (b * t * u - u) // U = b * t - t = bt % maxT # (b * t) % t = t - mb = (bt - t) // maxT # (b * t - t) // T = b - - # constants - T = xlen[mb] # select AM length of current sample - U = ylen[mb] + 1 # select target length of current sample, +1 for the blank token - labels: torch.Tensor = mlabels[mb] # labels = mlabels + mb * (maxU - 1); - - # Buffered gradient calculations, broadcast across B=b, T=t and U=u, looped over V with some constant stride. - # Look up gradient calculation from rnnt_numpy.compute_gradient() - if t < T and u < U: - # For cuda kernels, maximum number of threads per block is limited to some value. - # However, it may be the case that vocabulary size is larger than this limit - # To work around this, an arbitrary thread buffer size is chosen such that, - # 1) each element within the thread pool operates independently of the other - # 2) An inner while loop moves the index of each buffer element by the size of the buffer itself, - # such that all elements of the vocabulary size are covered in (V + 1 // thread_buffer) number of steps. - # As such, each thread will perform the while loop at least (V + 1 // thread_buffer) number of times - while idx < alphabet_size: - # remember, `col` represents the tri-index [b, t, u] - # therefore; logpk = denom[b, t, u] + acts[b, t, u, v] - logpk = denom[col] + acts[col * alphabet_size + idx] - # initialize the grad of the sample acts[b, t, u, v] - grad = math.exp(alphas[col] + betas[col] + logpk - logll[mb]) - - # In all of the following computation, whenever logpk is used, we - # need to subtract sigma based on our derivation of the gradient of - # the logit under-normalization method. - - # If FastEmit regularization is enabled, calculate the gradeint of probability of predicting the next label - # at the current timestep. - # The formula for this is Equation 9 in https://arxiv.org/abs/2010.11148, multiplied by the log probability - # of the current step (t, u), normalized by the total log likelihood. - # Once the gradient has been calculated, scale it by `fastemit_lambda`, as in Equation 10. - if fastemit_lambda > 0.0 and u < U - 1: - fastemit_grad = fastemit_lambda * math.exp( - alphas[col] # alphas(t, u) - + (denom[col] + acts[col * alphabet_size + labels[u]]) - + betas[col + 1] # betas(t, u+1) - + logpk # log Pr(k|t, u) - - sigma - - logll[mb] # total log likelihood for normalization - ) - else: - fastemit_grad = 0.0 - - # Update the gradient of act[b, t, u, v] with the gradient from FastEmit regularization - grad = grad + fastemit_grad - - # grad to last blank transition - # grad[b, T-1, U-1, v=blank] -= exp(alphas[b, t, u) + logpk - sigma - logll[b]) - if (idx == blank_) and (t == T - 1) and (u == U - 1): - grad -= math.exp(alphas[col] + logpk - sigma - logll[mb]) - else: - # this is one difference of the multi-blank gradient from standard RNN-T - # gradient -- basically, wherever the blank_ symbol is addressed in the - # original code, we need to do similar things to big blanks, and we need - # to change the if conditions to match the duration of the big-blank. - # grad[b, T-duration, U-1, v=big-blank] -= exp(alphas[b, t, u) + logpk - sigma - logll[b]) - for i in range(num_big_blanks): - if (idx == blank_ - 1 - i) and (t == T - big_blank_duration[i]) and (u == U - 1): - grad -= math.exp(alphas[col] + logpk - sigma - logll[mb]) - - # grad of blank across t < T; - # grad[b, t 0.0: - g = grads[col * alphabet_size + idx] - g = min(g, clamp) - g = max(g, -clamp) - grads[col * alphabet_size + idx] = g - - # update internal index through the thread_buffer; - # until idx < V + 1, such that entire vocabulary has been updated. - idx += GPU_RNNT_THREAD_SIZE - - -@cuda.jit() -def compute_tdt_alphas_kernel( - acts: torch.Tensor, - duration_acts: torch.Tensor, - denom: torch.Tensor, - sigma: float, - alphas: torch.Tensor, - llForward: torch.Tensor, - xlen: torch.Tensor, - ylen: torch.Tensor, - mlabels: torch.Tensor, # [B] - minibatch: int, - maxT: int, - maxU: int, - alphabet_size: int, - blank_: int, - durations: torch.Tensor, - num_durations: int, -): - """ - Compute alpha (forward variable) probabilities over the transduction step. - - Args: - acts: Tensor of shape [B, T, U, V] flattened. Represents the logprobs activation tensor for tokens. - duration_acts: Tensor of shape [B, T, U, D] flattened. Represents the logprobs activation tensor for duration. - denom: Tensor of shape [B, T, U] flattened. Represents the denominator of the logprobs activation tensor for tokens. - - alphas: Zero tensor of shape [B, T, U]. Will be updated inside the kernel with the forward variable - probabilities. - llForward: Zero tensor of shape [B]. Represents the log-likelihood of the forward pass. - Returned as the forward pass loss that is reduced by the optimizer. - xlen: Vector of length B which contains the actual acoustic sequence lengths in the padded - activation tensor. - ylen: Vector of length B which contains the actual target sequence lengths in the padded - activation tensor. - mlabels: Matrix of shape [B, U+1] (+1 here is due to token - usually the RNNT blank). - The matrix contains the padded target transcription that must be predicted. - minibatch: Int representing the batch size. - maxT: The maximum possible acoustic sequence length. Represents T in the logprobs tensor. - maxU: The maximum possible target sequence length. Represents U in the logprobs tensor. - alphabet_size: The vocabulary dimension V+1 (inclusive of RNNT blank). - blank_: Index of the TDT blank token in the vocabulary. Must be the last token in the vocab. - - Updates: - Kernel inplace updates the following inputs: - - alphas: forward variable scores. - - llForward: log-likelihood of forward variable. - """ - # // launch B blocks, each block has U threads - b = cuda.blockIdx.x # // batch id - u = cuda.threadIdx.x # label id, u - T = xlen[b] # select AM length of current sample - U = ylen[b] + 1 # select target length of current sample, +1 for the blank token - - labels: torch.Tensor = mlabels[b] # mb label start point, equivalent to mlabels + b * (maxU - 1) - offset = b * maxT * maxU # pointer indexing offset - - # alphas += offset # pointer offset, ignored since we explicitly add offset - - # Initilize alpha[b, t=0, u=0] for all b in B - if u == 0: - alphas[offset] = 0 - - # sync until all alphas are initialized - cuda.syncthreads() - - # Ordinary alpha calculations, broadcast across B=b and U=u - # Look up forward variable calculation from rnnt_numpy.forward_pass() - for n in range(1, T + U - 1): - t = n - u - - if u == 0: - # when u == 0, we only consider blank emissions. - if t > 0 and t < T: - alphas[offset + t * maxU + u] = -INF - - for i in range(num_durations): - if durations[i] == 0: # skip 0 since blank emission has to advance by at least one - continue - if t >= durations[i]: - alphas[offset + t * maxU + u] = rnnt_helper.log_sum_exp( - alphas[offset + t * maxU + u], # the current alpha value - alphas[offset + (t - durations[i]) * maxU + u] # alpha(t - duration, u) - + logp( - denom, acts, maxT, maxU, alphabet_size, b, t - durations[i], u, blank_ - ) # logp of blank emission - - sigma # logit under-normalization - + logp_duration( - duration_acts, maxT, maxU, num_durations, b, t - durations[i], u, i - ), # logp of duration - ) - else: - break # since durations are in ascending order, when we encounter a duration that is too large, then - # there is no need to check larger durations after that. - - elif u < U: - # when t == 0, we only consider the non-blank emission. - if t == 0: - if durations[0] == 0: - alphas[offset + u] = ( - alphas[offset + u - 1] # alpha(t, u - 1) - + logp( - denom, acts, maxT, maxU, alphabet_size, b, t, u - 1, labels[u - 1] - ) # logp of token emission - - sigma # logit under-normalization - + logp_duration( - duration_acts, maxT, maxU, num_durations, b, t, u - 1, 0 - ) # t = 0, so it must be duration = 0. Therefore the last argument passed to logp_duration() is 0. - ) - else: - alphas[offset + u] = -INF - - # now we have t != 0 and u != 0, and we need to consider both non-blank and blank emissions. - elif t > 0 and t < T: - no_emit = -INF # no_emit stores the score for all blank emissions. - for i in range(num_durations): - if durations[i] == 0: - continue - if t >= durations[i]: - no_emit = rnnt_helper.log_sum_exp( - no_emit, # current score - alphas[offset + (t - durations[i]) * maxU + u] # alpha(t - duration, u) - + logp( - denom, acts, maxT, maxU, alphabet_size, b, t - durations[i], u, blank_ - ) # logp of blank emission - - sigma # logit under-normalization - + logp_duration( - duration_acts, maxT, maxU, num_durations, b, t - durations[i], u, i - ), # logp of duration - ) - else: - break # we can exit the loop early here, same as the case for u == 0 above. - - emit = -INF # emit stores the score for non-blank emissions. - for i in range(num_durations): - if t >= durations[i]: - emit = rnnt_helper.log_sum_exp( - emit, # current score - alphas[offset + (t - durations[i]) * maxU + u - 1] # alpha(t - duration, u - 1) - + logp( - denom, acts, maxT, maxU, alphabet_size, b, t - durations[i], u - 1, labels[u - 1] - ) # logp of non-blank emission - - sigma # logit under-normalization - + logp_duration( - duration_acts, maxT, maxU, num_durations, b, t - durations[i], u - 1, i - ), # logp of duration - ) - else: - break # we can exit the loop early here, same as the case for u == 0 above. - - # combining blank and non-blank emissions. - alphas[offset + t * maxU + u] = rnnt_helper.log_sum_exp(emit, no_emit) - - # sync across all B=b and U=u - cuda.syncthreads() - - # After final sync, the forward log-likelihood can be computed as the summataion of - # alpha(T - duration, U - 1) + logp(blank, duration | t - duration, U - 1), over different durations. - if u == 0: - # initialize with negative infinite and start add terms later - loglike = -INF - - # then we add the scores for duration > 1, if such durations are possible given the audio lengths. - for i in range(num_durations): - if durations[i] == 0: - continue - if durations[i] == 1: - loglike = ( - alphas[offset + (T - 1) * maxU + U - 1] - + logp(denom, acts, maxT, maxU, alphabet_size, b, T - 1, U - 1, blank_) - - sigma - + logp_duration(duration_acts, maxT, maxU, num_durations, b, T - 1, U - 1, i) - ) - continue - if T >= durations[i]: - big_blank_loglike = ( - alphas[offset + (T - durations[i]) * maxU + U - 1] - + logp(denom, acts, maxT, maxU, alphabet_size, b, T - durations[i], U - 1, blank_) - - sigma - + logp_duration(duration_acts, maxT, maxU, num_durations, b, T - durations[i], U - 1, i) - ) - loglike = rnnt_helper.log_sum_exp(loglike, big_blank_loglike) - else: - break - - llForward[b] = loglike - - -@cuda.jit() -def compute_tdt_betas_kernel( - acts: torch.Tensor, - duration_acts: torch.Tensor, - denom: torch.Tensor, - sigma: float, - betas: torch.Tensor, - llBackward: torch.Tensor, - xlen: torch.Tensor, - ylen: torch.Tensor, - mlabels: torch.Tensor, # [B, U] - minibatch: int, - maxT: int, - maxU: int, - alphabet_size: int, - blank_: int, - durations: torch.Tensor, - num_durations: int, -): - """ - Compute beta (backward variable) probabilities over the transduction step. - - Args: - acts: Tensor of shape [B, T, U, V] flattened. Represents the logprobs activation tensor for tokens. - duration_acts: Tensor of shape [B, T, U, D] flattened. Represents the logprobs activation tensor for duations. - denom: Tensor of shape [B, T, U] flattened. Represents the denominator of the logprobs activation tensor - across entire vocabulary. - betas: Zero tensor of shape [B, T, U]. Will be updated inside the kernel with the backward variable - probabilities. - llBackward: Zero tensor of shape [B]. Represents the log-likelihood of the backward pass. - Returned as the backward pass loss that is reduced by the optimizer. - xlen: Vector of length B which contains the actual acoustic sequence lengths in the padded - activation tensor. - ylen: Vector of length B which contains the actual target sequence lengths in the padded - activation tensor. - mlabels: Matrix of shape [B, U+1] (+1 here is due to token - usually the RNNT blank). - The matrix contains the padded target transcription that must be predicted. - minibatch: Int representing the batch size. - maxT: The maximum possible acoustic sequence length. Represents T in the logprobs tensor. - maxU: The maximum possible target sequence length. Represents U in the logprobs tensor. - alphabet_size: The vocabulary dimension V+1 (inclusive of RNNT blank). - blank_: Index of the RNNT blank token in the vocabulary. Generally the first or last token in the vocab. - - Updates: - Kernel inplace updates the following inputs: - - betas: backward variable scores. - - llBackward: log-likelihood of backward variable. - """ - # // launch B blocks, each block has U threads - b = cuda.blockIdx.x # // batch id - u = cuda.threadIdx.x # label id, u - T = xlen[b] # select AM length of current sample - U = ylen[b] + 1 # select target length of current sample, +1 for the blank token - - labels: torch.Tensor = mlabels[b] # mb label start point, equivalent to mlabels + b * (maxU - 1) - offset = b * maxT * maxU # pointer indexing offset - - # betas += offset # pointer offset, ignored since we explicitly add offset - - # Initilize beta[b, t=T-1, u=U-1] for all b in B with log_probs[b, t=T-1, u=U-1, blank] - if u == 0: - if durations[0] == 1: - betas[offset + (T - 1) * maxU + U - 1] = ( - logp(denom, acts, maxT, maxU, alphabet_size, b, T - 1, U - 1, blank_) - - sigma - + logp_duration(duration_acts, maxT, maxU, num_durations, b, T - 1, U - 1, 0) - ) - elif durations[1] == 1: - betas[offset + (T - 1) * maxU + U - 1] = ( - logp(denom, acts, maxT, maxU, alphabet_size, b, T - 1, U - 1, blank_) - - sigma - + logp_duration(duration_acts, maxT, maxU, num_durations, b, T - 1, U - 1, 1) - ) - - # sync until all betas are initialized - cuda.syncthreads() - - # Ordinary beta calculations, broadcast across B=b and U=u - # Look up backward variable calculation from rnnt_numpy.backward_pass() - for n in range(T + U - 2, -1, -1): - t = n - u - - if u == U - 1: - # u == U - 1, we only consider blank emissions. - if t >= 0 and t + 1 < T: - betas[offset + t * maxU + U - 1] = -INF - for i in range(num_durations): - # although similar, the computation for beta's is slightly more complex for boundary cases. - # the following two cases correspond to whether t is exactly certain duration away from T. - # and they have slightly different update rules. - if durations[i] == 0: - continue - if t + durations[i] < T: - betas[offset + t * maxU + U - 1] = rnnt_helper.log_sum_exp( - betas[offset + t * maxU + U - 1], - betas[ - offset + (t + durations[i]) * maxU + U - 1 - ] # beta[t, U - 1] depends on the value beta[t + duration, U - 1] here. - + logp(denom, acts, maxT, maxU, alphabet_size, b, t, U - 1, blank_) # log prob of blank - + logp_duration( - duration_acts, maxT, maxU, num_durations, b, t, U - 1, i - ) # log prob of duration (durations[i]) - - sigma, # for logit undernormalization - ) - elif t + durations[i] == T: - betas[offset + t * maxU + U - 1] = rnnt_helper.log_sum_exp( - betas[offset + t * maxU + U - 1], - # here we have one fewer term than the "if" block above. This could be seen as having "0" here since - # beta[t + duration, U - 1] isn't defined because t + duration is out of bound. - logp(denom, acts, maxT, maxU, alphabet_size, b, t, U - 1, blank_) # log prob of blank - + logp_duration( - duration_acts, maxT, maxU, num_durations, b, t, U - 1, i - ) # log prob of duration (durations[i]) - - sigma, # for logit undernormalization. Basically every time sigma shows up is because of logit undernormalization. - ) - - elif u < U - 1: - if t == T - 1: - # t == T - 1, so we only consider non-blank with duration 0. (Note, we can't have blank emissions with duration = 0) - if durations[0] == 0: - betas[offset + (T - 1) * maxU + u] = ( - betas[offset + (T - 1) * maxU + u + 1] - + logp(denom, acts, maxT, maxU, alphabet_size, b, T - 1, u, labels[u]) # non-blank log prob - + logp_duration( - duration_acts, maxT, maxU, num_durations, b, T - 1, u, 0 - ) # log prob of duration 0 - - sigma - ) - else: - betas[offset + (T - 1) * maxU + u] = -INF - - elif t >= 0 and t < T - 1: - # now we need to consider both blank andnon-blanks. Similar to alphas, we first compute them separately with no_emit and emit. - no_emit = -INF - for i in range(num_durations): - if durations[i] == 0: - continue - if t + durations[i] < T: - no_emit = rnnt_helper.log_sum_exp( - no_emit, - betas[offset + (t + durations[i]) * maxU + u] - + logp(denom, acts, maxT, maxU, alphabet_size, b, t, u, blank_) - + logp_duration(duration_acts, maxT, maxU, num_durations, b, t, u, i) - - sigma, - ) - - emit = -INF - for i in range(num_durations): - if t + durations[i] < T: - emit = rnnt_helper.log_sum_exp( - emit, - betas[offset + (t + durations[i]) * maxU + u + 1] - + logp(denom, acts, maxT, maxU, alphabet_size, b, t, u, labels[u]) - + logp_duration(duration_acts, maxT, maxU, num_durations, b, t, u, i) - - sigma, - ) - - # combining all blank emissions and all non-blank emissions. - betas[offset + t * maxU + u] = rnnt_helper.log_sum_exp(emit, no_emit) - - # sync across all B=b and U=u - cuda.syncthreads() - - # After final sync, betas[b, 0, 0] gives log-likelihood of backward pass, same with conventional Transducers. - if u == 0: - llBackward[b] = betas[offset] - - -@cuda.jit() -def compute_tdt_grad_kernel( - label_grads: torch.Tensor, - duration_grads: torch.Tensor, - acts: torch.Tensor, - duration_acts: torch.Tensor, - denom: torch.Tensor, - sigma: float, - alphas: torch.Tensor, - betas: torch.Tensor, - logll: torch.Tensor, - xlen: torch.Tensor, - ylen: torch.Tensor, - mlabels: torch.Tensor, # [B, U] - minibatch: int, - maxT: int, - maxU: int, - alphabet_size: int, - blank_: int, - durations: torch.Tensor, - num_durations: int, - fastemit_lambda: float, - clamp: float, -): - """ - Compute gradients over the transduction step. - - Args: - grads: Zero Tensor of shape [B, T, U, V] to store gradients for tokens. - duration_grads: Zero Tensor of shape [B, T, U, D] to store gradients for durations. - - acts: Tensor of shape [B, T, U, V] flattened. Represents the logprobs activation tensor for tokens. - duration_acts: Tensor of shape [B, T, U, D] flattened. Represents the logprobs activation tensor for durations. - denom: Tensor of shape [B, T, U] flattened. Represents the denominator of the logprobs activation tensor - across entire vocabulary. - alphas: Alpha variable, contains forward probabilities. A tensor of shape [B, T, U]. - betas: Beta varoable, contains backward probabilities. A tensor of shape [B, T, U]. - logll: Log-likelihood of the forward variable, represented as a vector of shape [B]. - Represents the log-likelihood of the forward pass. - xlen: Vector of length B which contains the actual acoustic sequence lengths in the padded - activation tensor. - ylen: Vector of length B which contains the actual target sequence lengths in the padded - activation tensor. - mlabels: Matrix of shape [B, U+1] (+1 here is due to token - usually the RNNT blank). - The matrix contains the padded target transcription that must be predicted. - minibatch: Int representing the batch size. - maxT: The maximum possible acoustic sequence length. Represents T in the logprobs tensor. - maxU: The maximum possible target sequence length. Represents U in the logprobs tensor. - alphabet_size: The vocabulary dimension V+1 (inclusive of RNNT blank). - blank_: Index of the RNNT blank token in the vocabulary. Generally the first or last token in the vocab. - fastemit_lambda: Float scaling factor for FastEmit regularization. Refer to - FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization. - clamp: Float value. When set to value >= 0.0, will clamp the gradient to [-clamp, clamp]. - - Updates: - Kernel inplace updates the following inputs: - - grads: Gradients with respect to the log likelihood (logll). - """ - # Kernel call: - # blocks_per_grid = minibatch (b) * maxT (t) * maxU (u) - # threads_per_block = constant buffer size of parallel threads (v :: Constant) - tid = cuda.threadIdx.x # represents v, taking steps of some constant size - idx = tid # index of v < V+1; in steps of constant buffer size - col = cuda.blockIdx.x # represents a fused index of b * t * u - - # Decompose original indices from fused `col` - u = col % maxU # (b * t * u) % u = u - bt = (col - u) // maxU # (b * t * u - u) // U = b * t - t = bt % maxT # (b * t) % t = t - mb = (bt - t) // maxT # (b * t - t) // T = b - - # constants - T = xlen[mb] # select AM length of current sample - U = ylen[mb] + 1 # select target length of current sample, +1 for the blank token - labels: torch.Tensor = mlabels[mb] # labels = mlabels + mb * (maxU - 1); - - # Buffered gradient calculations, broadcast across B=b, T=t and U=u, looped over V with some constant stride. - # Look up gradient calculation from rnnt_numpy.compute_gradient() - - if t < T and u < U: - logpk_blank = ( - denom[col] + acts[col * alphabet_size + blank_] - sigma - ) # whenever sigma is used, it is for logit under-normalization. - - if idx < num_durations: - grad = 0.0 - if t + durations[idx] < T and u < U - 1: # for label - logpk_label = denom[col] + acts[col * alphabet_size + labels[u]] - sigma - grad -= math.exp(alphas[col] + betas[col + 1 + durations[idx] * maxU] + logpk_label - logll[mb]) - - if t + durations[idx] < T and durations[idx] > 0: # for blank in the middle - grad -= math.exp(alphas[col] + betas[col + durations[idx] * maxU] + logpk_blank - logll[mb]) - - if t + durations[idx] == T and u == U - 1 and durations[idx] > 0: # for blank as the last symbol - grad -= math.exp(alphas[col] + logpk_blank - logll[mb]) - - grad = grad * math.exp(duration_acts[col * num_durations + idx]) - duration_grads[col * num_durations + idx] = grad - - # For cuda kernels, maximum number of threads per block is limited to some value. - # However, it may be the case that vocabulary size is larger than this limit - # To work around this, an arbitrary thread buffer size is chosen such that, - # 1) each element within the thread pool operates independently of the other - # 2) An inner while loop moves the index of each buffer element by the size of the buffer itself, - # such that all elements of the vocabulary size are covered in (V + 1 // thread_buffer) number of steps. - # As such, each thread will perform the while loop at least (V + 1 // thread_buffer) number of times - while idx < alphabet_size: - # remember, `col` represents the tri-index [b, t, u] - # therefore; logpk = denom[b, t, u] + acts[b, t, u, v] - logpk = denom[col] + acts[col * alphabet_size + idx] - # initialize the grad of the sample acts[b, t, u, v] - grad = math.exp(alphas[col] + betas[col] + logpk - logll[mb]) - - # If FastEmit regularization is enabled, calculate the gradeint of probability of predicting the next label - # at the current timestep. - # The formula for this is Equation 9 in https://arxiv.org/abs/2010.11148, multiplied by the log probability - # of the current step (t, u), normalized by the total log likelihood. - # Once the gradient has been calculated, scale it by `fastemit_lambda`, as in Equation 10. - if fastemit_lambda > 0.0 and u < U - 1: - fastemit_grad = 0.0 - - for i in range(num_durations): - if t + durations[i] < T: - fastemit_grad += fastemit_lambda * math.exp( - alphas[col] # alphas(t, u) - + (denom[col] + acts[col * alphabet_size + labels[u]]) # log prob of token emission - + duration_acts[col * num_durations + i] # duration log-prob - + betas[col + 1 + durations[i] * maxU] # betas(t, u+1) - + logpk # log Pr(k|t, u) - - sigma # for logit under-normalization - - logll[mb] # total log likelihood for normalization - ) - else: - fastemit_grad = 0.0 - - # Update the gradient of act[b, t, u, v] with the gradient from FastEmit regularization - grad = grad + fastemit_grad - - # grad to last blank transition - # grad[b, T-1, U-1, v=blank] -= exp(alphas[b, t, u] + logpk - sigma - logll[b] + logp(duration) for all possible non-zero durations. - if idx == blank_ and u == U - 1: - for i in range(num_durations): - if durations[i] == 0: - continue - if t == T - durations[i]: - grad -= math.exp( - alphas[col] + logpk - sigma - logll[mb] + duration_acts[col * num_durations + i] - ) - - # grad of blank across t < T; - # grad[b, t 0.0: - g = label_grads[col * alphabet_size + idx] - g = min(g, clamp) - g = max(g, -clamp) - label_grads[col * alphabet_size + idx] = g - - # update internal index through the thread_buffer; - # until idx < V + 1, such that entire vocabulary has been updated. - idx += GPU_RNNT_THREAD_SIZE diff --git a/nemo/collections/asr/parts/numba/rnnt_loss/utils/cuda_utils/reduce.py b/nemo/collections/asr/parts/numba/rnnt_loss/utils/cuda_utils/reduce.py deleted file mode 100644 index c72026ae2fee853c72459b639ad08eeabc991dc6..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/numba/rnnt_loss/utils/cuda_utils/reduce.py +++ /dev/null @@ -1,362 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Copyright 2018-2019, Mingkun Huang -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import enum -import math - -import torch -from numba import cuda - -from nemo.collections.asr.parts.numba.rnnt_loss.utils import global_constants, rnnt_helper - -warp_size = global_constants.warp_size() -dtype = global_constants.dtype() - -CTA_REDUCE_SIZE = 128 - - -class I_Op(enum.Enum): - """ - Represents an operation that is performed on the input tensor - """ - - EXPONENTIAL = 0 - IDENTITY = 1 - - -class R_Op(enum.Enum): - """ - Represents a reduction operation performed on the input tensor - """ - - ADD = 0 - MAXIMUM = 1 - - -@cuda.jit(device=True) -def CTAReduce(tid: int, x, storage, count: int, R_opid: int): - """ - CUDA Warp reduction kernel. - - It is a device kernel to be called by other kernels. - - The data will be read from the right segement recursively, and reduced (ROP) onto the left half. - Operation continues while warp size is larger than a given offset. - Beyond this offset, warp reduction is performed via `shfl_down_sync`, which halves the reduction - space and sums the two halves at each call. - - Note: - Efficient warp occurs at input shapes of 2 ^ K. - - References: - - Warp Primitives [https://developer.nvidia.com/blog/using-cuda-warp-level-primitives/] - - Args: - tid: CUDA thread index - x: activation. Single float. - storage: shared memory of size CTA_REDUCE_SIZE used for reduction in parallel threads. - count: equivalent to num_rows, which is equivalent to alphabet_size (V+1) - R_opid: Operator ID for reduction. See R_Op for more information. - """ - storage[tid] = x - - cuda.syncthreads() - - # Fold the data in half with each pass - offset = CTA_REDUCE_SIZE // 2 - while offset >= warp_size: - if (tid + offset) < count and tid < offset: - # Read from the right half and store to the left half. - if R_opid == 0: - x = rnnt_helper.add(x, storage[offset + tid]) - else: - x = rnnt_helper.maximum(x, storage[offset + tid]) - - storage[tid] = x - - cuda.syncthreads() - offset = offset // 2 - - offset = warp_size // 2 - while offset > 0: - # warp reduction and sync - shuff = cuda.shfl_down_sync(0xFFFFFFFF, x, offset) - - if (tid + offset < count) and (tid < offset): - if R_opid == 0: - x = rnnt_helper.add(x, shuff) - else: - x = rnnt_helper.maximum(x, shuff) - - offset = offset // 2 - - return x - - -@cuda.jit() -def _reduce_rows(I_opid: int, R_opid: int, acts, output, num_rows: int): - """ - CUDA Warp reduction kernel which reduces via the R_Op.Maximum - - Reduces the input data such that I_Op = Identity and R_op = Maximum. - The result is stored in the blockIdx, and is stored as an identity op. - - Note: - Efficient warp occurs at input shapes of 2 ^ K. - - References: - - Warp Primitives [https://developer.nvidia.com/blog/using-cuda-warp-level-primitives/] - - Args: - I_opid: Operator ID for input. See I_Op for more information. For this kernel, - the Identity op is chosen in general, and therefore the input is reduced in place - without scaling. - R_opid: Operator ID for reduction. See R_Op for more information. - For this kernel, generally Maximum op is chosen. It reduces the kernel via max. - acts: Flatened activation matrix of shape [B * T * U * (V+1)]. - output: Flatened output matrix of shape [B * T * U * (V+1)]. Data will be overwritten. - num_rows: Vocabulary size (including blank token) - V+1. - """ - tid = cuda.threadIdx.x - idx = tid - col = cuda.blockIdx.x - - # allocate shared thread memory - storage = cuda.shared.array(shape=(CTA_REDUCE_SIZE,), dtype=acts.dtype) - - max = output[col] - - # // Each block works on a column - if idx < num_rows: - curr = acts[col * num_rows + idx] - max - if I_opid == 0: - curr = rnnt_helper.exponential(curr) - else: - curr = rnnt_helper.identity(curr) - - idx += CTA_REDUCE_SIZE - - while idx < num_rows: - activation_ = acts[col * num_rows + idx] - max - - if I_opid == 0 and R_opid == 0: - curr = rnnt_helper.add(curr, rnnt_helper.exponential(activation_)) - elif I_opid == 0 and R_opid == 1: - curr = rnnt_helper.maximum(curr, rnnt_helper.exponential(activation_)) - elif I_opid == 1 and R_opid == 0: - curr = rnnt_helper.add(curr, rnnt_helper.identity(activation_)) - else: - curr = rnnt_helper.maximum(curr, rnnt_helper.identity(activation_)) - - idx += CTA_REDUCE_SIZE - - # // Sum thread-totals over the CTA. - curr = CTAReduce(tid, curr, storage, num_rows, R_opid) - - # // Store result in out (inplace, I_op: identity) - if tid == 0: - output[col] = curr - - -@cuda.jit() -def _reduce_minus(I_opid: int, R_opid: int, acts, output, num_rows: int): - """ - CUDA Warp reduction kernel which reduces via the R_Op.Add - - Reduces the input data such that I_Op = Exponential and R_op = Add. - The result is stored in the blockIdx, and is stored as an exp op. - - Note: - Efficient warp occurs at input shapes of 2 ^ K. - - References: - - Warp Primitives [https://developer.nvidia.com/blog/using-cuda-warp-level-primitives/] - - Args: - I_opid: Operator ID for input. See I_Op for more information. For this kernel, - the Exponential op is chosen in general, and therefore the input is reduced in place - with scaling. - R_opid: Operator ID for reduction. See R_Op for more information. - For this kernel, generally Add op is chosen. It reduces the kernel via summation. - acts: Flatened activation matrix of shape [B * T * U * (V+1)]. - output: Flatened output matrix of shape [B * T * U * (V+1)]. Data will be overwritten. - num_rows: Vocabulary size (including blank token) - V+1. - """ - tid = cuda.threadIdx.x - idx = tid - col = cuda.blockIdx.x - - # allocate shared thread memory - storage = cuda.shared.array(shape=(CTA_REDUCE_SIZE,), dtype=acts.dtype) - - max = output[col] - - # // Each block works on a column - if idx < num_rows: - curr = acts[col * num_rows + idx] - max - if I_opid == 0: - curr = rnnt_helper.exponential(curr) - else: - curr = rnnt_helper.identity(curr) - - idx += CTA_REDUCE_SIZE - - while idx < num_rows: - activation_ = acts[col * num_rows + idx] - max - - if I_opid == 0 and R_opid == 0: - curr = rnnt_helper.add(curr, rnnt_helper.exponential(activation_)) - elif I_opid == 0 and R_opid == 1: - curr = rnnt_helper.maximum(curr, rnnt_helper.exponential(activation_)) - elif I_opid == 1 and R_opid == 0: - curr = rnnt_helper.add(curr, rnnt_helper.identity(activation_)) - else: - curr = rnnt_helper.maximum(curr, rnnt_helper.identity(activation_)) - - idx += CTA_REDUCE_SIZE - - # // Sum thread-totals over the CTA. - curr = CTAReduce(tid, curr, storage, num_rows, R_opid) - - # // Store result in out (inplace, I_op: exponential) - if tid == 0: - output[col] = -max - math.log(curr) - - -def ReduceHelper( - I_opid: int, - R_opid: int, - acts: torch.Tensor, - output: torch.Tensor, - num_rows: int, - num_cols: int, - minus: bool, - stream, -): - """ - CUDA Warp reduction kernel helper which reduces via the R_Op.Add and writes - the result to `output` according to I_op id. - - The result is stored in the blockIdx. - - Note: - Efficient warp occurs at input shapes of 2 ^ K. - - References: - - Warp Primitives [https://developer.nvidia.com/blog/using-cuda-warp-level-primitives/] - - Args: - I_opid: Operator ID for input. See I_Op for more information. - R_opid: Operator ID for reduction. See R_Op for more information. - acts: Flatened activation matrix of shape [B * T * U * (V+1)]. - output: Flatened output matrix of shape [B * T * U * (V+1)]. Data will be overwritten. - num_rows: Vocabulary size (including blank token) - V+1. - Represents the number of threads per block. - num_cols: Flattened shape of activation matrix, without vocabulary dimension (B * T * U). - Represents number of blocks per grid. - minus: Bool flag whether to add or subtract as reduction. - If minus is set; calls _reduce_minus, else calls _reduce_rows kernel. - stream: CUDA Stream. - """ - if minus: - grid_size = int(num_cols) # convert np.int64 to int - # call kernel - _reduce_minus[grid_size, CTA_REDUCE_SIZE, stream, 0](I_opid, R_opid, acts, output, num_rows) - - else: - grid_size = int(num_cols) # convert np.int64 to int - # call kernel - _reduce_rows[grid_size, CTA_REDUCE_SIZE, stream, 0](I_opid, R_opid, acts, output, num_rows) - - return True - - -def reduce_exp(acts: torch.Tensor, denom, rows: int, cols: int, minus: bool, stream): - """ - Helper method to call the Warp Reduction Kernel to perform `exp` reduction. - - Note: - Efficient warp occurs at input shapes of 2 ^ K. - - References: - - Warp Primitives [https://developer.nvidia.com/blog/using-cuda-warp-level-primitives/] - - Args: - acts: Flatened activation matrix of shape [B * T * U * (V+1)]. - output: Flatened output matrix of shape [B * T * U * (V+1)]. Data will be overwritten. - rows: Vocabulary size (including blank token) - V+1. - Represents the number of threads per block. - cols: Flattened shape of activation matrix, without vocabulary dimension (B * T * U). - Represents number of blocks per grid. - minus: Bool flag whether to add or subtract as reduction. - If minus is set; calls _reduce_minus, else calls _reduce_rows kernel. - stream: CUDA Stream. - """ - return ReduceHelper( - I_opid=I_Op.EXPONENTIAL.value, - R_opid=R_Op.ADD.value, - acts=acts, - output=denom, - num_rows=rows, - num_cols=cols, - minus=minus, - stream=stream, - ) - - -def reduce_max(acts: torch.Tensor, denom, rows: int, cols: int, minus: bool, stream): - """ - Helper method to call the Warp Reduction Kernel to perform `max` reduction. - - Note: - Efficient warp occurs at input shapes of 2 ^ K. - - References: - - Warp Primitives [https://developer.nvidia.com/blog/using-cuda-warp-level-primitives/] - - Args: - acts: Flatened activation matrix of shape [B * T * U * (V+1)]. - output: Flatened output matrix of shape [B * T * U * (V+1)]. Data will be overwritten. - rows: Vocabulary size (including blank token) - V+1. - Represents the number of threads per block. - cols: Flattened shape of activation matrix, without vocabulary dimension (B * T * U). - Represents number of blocks per grid. - minus: Bool flag whether to add or subtract as reduction. - If minus is set; calls _reduce_minus, else calls _reduce_rows kernel. - stream: CUDA Stream. - """ - return ReduceHelper( - I_opid=I_Op.IDENTITY.value, - R_opid=R_Op.MAXIMUM.value, - acts=acts, - output=denom, - num_rows=rows, - num_cols=cols, - minus=minus, - stream=stream, - ) diff --git a/nemo/collections/asr/parts/numba/rnnt_loss/utils/global_constants.py b/nemo/collections/asr/parts/numba/rnnt_loss/utils/global_constants.py deleted file mode 100644 index cc304753034ce70adf0f38df80d42d8e8f2ecdcf..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/numba/rnnt_loss/utils/global_constants.py +++ /dev/null @@ -1,68 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Copyright 2018-2019, Mingkun Huang -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import enum - -import numpy as np -from numba import float32 - -# Internal globals -_THREADS_PER_BLOCK = 32 -_WARP_SIZE = 32 -_DTYPE = float32 - -# Constants -FP32_INF = np.inf -FP32_NEG_INF = -np.inf -THRESHOLD = 1e-1 - -""" -Getters -""" - - -def threads_per_block(): - global _THREADS_PER_BLOCK - return _THREADS_PER_BLOCK - - -def warp_size(): - global _WARP_SIZE - return _WARP_SIZE - - -def dtype(): - global _DTYPE - return _DTYPE - - -# RNNT STATUS -class RNNTStatus(enum.Enum): - RNNT_STATUS_SUCCESS = 0 - RNNT_STATUS_INVALID_VALUE = 1 diff --git a/nemo/collections/asr/parts/numba/rnnt_loss/utils/rnnt_helper.py b/nemo/collections/asr/parts/numba/rnnt_loss/utils/rnnt_helper.py deleted file mode 100644 index 6ca7cd23726492c1bdb7504c6240c0c701866b2b..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/numba/rnnt_loss/utils/rnnt_helper.py +++ /dev/null @@ -1,148 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Copyright 2018-2019, Mingkun Huang -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import math -from typing import Optional, Tuple - -import numba -import torch -from numba import cuda - -from nemo.collections.asr.parts.numba.rnnt_loss.utils import global_constants - -threshold = global_constants.THRESHOLD - - -@cuda.jit(device=True, inline=True) -def log_sum_exp(a: float, b: float): - if a == global_constants.FP32_NEG_INF: - return b - - if b == global_constants.FP32_NEG_INF: - return a - - if a > b: - return math.log1p(math.exp(b - a)) + a - else: - return math.log1p(math.exp(a - b)) + b - - -@cuda.jit(device=True, inline=True) -def div_up(x: int, y: int): - return (x + y - 1) // y - - -@cuda.jit(device=True) -def maximum(x, y): - if x < y: - return y - else: - return x - - -@cuda.jit(device=True) -def add(x, y): - return x + y - - -@cuda.jit(device=True) -def identity(x): - return x - - -@cuda.jit(device=True) -def negate(x): - return -x - - -@cuda.jit(device=True) -def exponential(x): - return math.exp(x) - - -@cuda.jit(device=True) -def log_plus(p1: float, p2: float): - if p1 == global_constants.FP32_NEG_INF: - return p2 - - if p2 == global_constants.FP32_NEG_INF: - return p1 - - result = math.log1p(math.exp(-math.fabs(p1 - p2))) + maximum(p1, p2) - return result - - -@cuda.jit(device=True, inline=True) -def copy_data_1d(source: torch.Tensor, dest: torch.Tensor, idx: int): - dest[idx] = source[idx] - - -@cuda.jit() -def compute_costs_data(source: torch.Tensor, dest: torch.Tensor, fastemit_lambda: float): - block = cuda.blockIdx.x - tid = cuda.threadIdx.x - idx = block * cuda.blockDim.x + tid - length = source.shape[0] - - if idx < length: - copy_data_1d(source, dest, idx) - dest[idx] *= -1.0 - dest[idx] *= numba.float32(1.0 + fastemit_lambda) - - -def get_workspace_size( - maxT: int, maxU: int, minibatch: int, gpu: bool -) -> Tuple[Optional[int], global_constants.RNNTStatus]: - - if minibatch <= 0 or maxT <= 0 or maxU <= 0: - return (None, global_constants.RNNTStatus.RNNT_STATUS_INVALID_VALUE) - - # per minibatch memory - per_minibatch_size = 0 - - # alphas & betas - per_minibatch_size += maxT * maxU * 2 - - if not gpu: - # // blank & label log probability cache - per_minibatch_size += maxT * maxU * 2 - else: - # // softmax denominator - per_minibatch_size += maxT * maxU - # // forward - backward loglikelihood - per_minibatch_size += 2 - - size = per_minibatch_size * minibatch - return (size, global_constants.RNNTStatus.RNNT_STATUS_SUCCESS) - - -def flatten_tensor(x: torch.Tensor): - original_shape = x.shape - x = x.view([-1]) - return x, original_shape diff --git a/nemo/collections/asr/parts/numba/spec_augment/__init__.py b/nemo/collections/asr/parts/numba/spec_augment/__init__.py deleted file mode 100644 index 17a22fcf81889ff15d8cedd8c306bd0d383dcf58..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/numba/spec_augment/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.asr.parts.numba.spec_augment.spec_aug_numba import ( - SpecAugmentNumba, - spec_augment_launch_heuristics, -) diff --git a/nemo/collections/asr/parts/numba/spec_augment/spec_aug_numba.py b/nemo/collections/asr/parts/numba/spec_augment/spec_aug_numba.py deleted file mode 100644 index fcf5d5cebfebe432008b6d7c136129c79afb80f7..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/numba/spec_augment/spec_aug_numba.py +++ /dev/null @@ -1,305 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import torch -import torch.nn as nn -from numba import cuda - -from nemo.core.classes import Typing, typecheck -from nemo.core.neural_types import LengthsType, NeuralType, SpectrogramType -from nemo.utils import logging - -MAX_THREAD_BUFFER = 512 - - -@cuda.jit() -def spec_augment_kernel( - x: torch.Tensor, - x_len: torch.Tensor, - freq_starts: torch.Tensor, - freq_widths: torch.Tensor, - time_starts: torch.Tensor, - time_widths: torch.Tensor, - mask_value: float, -): - """ - Numba CUDA kernel to perform SpecAugment in-place on the GPU. - Parallelize over freq and time axis, parallel threads over batch. - Sequential over masks (adaptive in time). - - Args: - x: Pytorch tensor of shape [B, F, T] with the acoustic features. - x_len: Pytorch tensor of shape [B] with the lengths of the padded sequence. - freq_starts: Pytorch tensor of shape [B, M_f] with the start indices of freq masks. - freq_widths: Pytorch tensor of shape [B, M_f] with the width of freq masks. - time_starts: Pytorch tensor of shape [B, M_t] with the start indices of time masks. - time_widths: Pytorch tensor of shape [B, M_t] with the width of time masks. - mask_value: Float value that will be used as mask value. - """ - f = cuda.blockIdx.x # indexes the Freq dim - t = cuda.blockIdx.y # indexes the Time dim - tid = cuda.threadIdx.x # index of the current mask - threads_per_block = cuda.blockDim.x - - # Compute the number of masks over freq axis - len_f = freq_starts.shape[1] - # For all samples in the batch, apply the freq mask - for bidx in range(0, x.shape[0], threads_per_block): - # Resolve the index of the batch (case where more masks than MAX_THREAD_BUFFER) - bm_idx = bidx + tid - - # Access mask only if valid sample id in batch - if bm_idx < x.shape[0]: - # For `len_f` number of freq masks that must be applied - for fidx in range(0, len_f): - # Access the start index and width of this freq mask - f_start = freq_starts[bm_idx, fidx] - f_width = freq_widths[bm_idx, fidx] - - # If block idx `f` >= start and < (start + width) of this freq mask - if f >= f_start and f < (f_start + f_width): - x[bm_idx, f, t] = mask_value - - # Compute the number of masks over time axis - len_t = time_starts.shape[1] - # For all samples in the batch, apply the time mask - for b_idx in range(0, x.shape[0], threads_per_block): - # Resolve the index of the batch (case where more masks than MAX_THREAD_BUFFER) - bm_idx = b_idx + tid - - # Access mask only if valid sample id in batch - if bm_idx < x.shape[0]: - # For `len_t` number of freq masks that must be applied - for tidx in range(0, len_t): - # Access the start index and width of this time mask - t_start = time_starts[bm_idx, tidx] - t_width = time_widths[bm_idx, tidx] - - # If block idx `t` >= start and < (start + width) of this time mask - if t >= t_start and t < (t_start + t_width): - # Current block idx `t` < current seq length x_len[b] - # This ensure that we mask only upto the length of that sample - # Everything after that index is padded value so unnecessary to mask - if t < x_len[bm_idx]: - x[bm_idx, f, t] = mask_value - - -def spec_augment_launch_heuristics(x: torch.Tensor, length: torch.Tensor): - """ - Heuristics to determins whether pytorch implementation or numba implementation is selected. - Assumes numba cuda is supported. - - Args: - x: Torch tensor of shape [B, F, T] - length: Optional, Torch of tensor of shape [B] - containing lengths of the tensor. - - Returns: - True if numba kernel should be selected, else False - """ - if not x.is_cuda: - return False - - if length is None: - return False - - if x.shape[0] < 8: - return False - - return True - - -def launch_spec_augment_kernel( - x: torch.Tensor, - x_len: torch.Tensor, - freq_starts: torch.Tensor, - freq_lengths: torch.Tensor, - time_starts: torch.Tensor, - time_lengths: torch.Tensor, - freq_masks: int, - time_masks: int, - mask_value: float, -): - """ - Helper method to launch the SpecAugment kernel - - Args: - x: Pytorch tensor of shape [B, F, T] with the acoustic features. - x_len: Pytorch tensor of shape [B] with the lengths of the padded sequence. - freq_starts: Pytorch tensor of shape [B, M_f] with the start indices of freq masks. - freq_widths: Pytorch tensor of shape [B, M_f] with the width of freq masks. - time_starts: Pytorch tensor of shape [B, M_t] with the start indices of time masks. - time_widths: Pytorch tensor of shape [B, M_t] with the width of time masks. - freq_masks: Int value that determines the number of time masks. - time_masks: Int value that determines the number of freq masks. - mask_value: Float value that will be used as mask value. - - Returns: - The spec augmented tensor 'x' - """ - # Setup CUDA stream - sh = x.shape - stream = cuda.external_stream(torch.cuda.current_stream(x.device).cuda_stream) - - if time_masks > 0 or freq_masks > 0: - # Parallelize over freq and time axis, parallel threads over batch - # Sequential over masks (adaptive in time). - blocks_per_grid = tuple([sh[1], sh[2]]) - # threads_per_block = min(MAX_THREAD_BUFFER, max(freq_masks, time_masks)) - threads_per_block = min(MAX_THREAD_BUFFER, x.shape[0]) - - # Numba does not support fp16, force cast to fp32 temporarily at the expense of memory - original_dtype = x.dtype - cast_x = False - if x.dtype == torch.float16: - x = x.float() - cast_x = True - - # Launch CUDA kernel - spec_augment_kernel[blocks_per_grid, threads_per_block, stream, 0]( - x, x_len, freq_starts, freq_lengths, time_starts, time_lengths, mask_value - ) - torch.cuda.synchronize() - - # Recast back to original dtype if earlier cast was performed - if cast_x: - x = x.to(dtype=original_dtype) - - return x - - -class SpecAugmentNumba(nn.Module, Typing): - """ - Zeroes out(cuts) random continuous horisontal or - vertical segments of the spectrogram as described in - SpecAugment (https://arxiv.org/abs/1904.08779). - - Utilizes a Numba CUDA kernel to perform inplace edit of the input without loops. - Parallelize over freq and time axis, parallel threads over batch. - Sequential over masks (adaptive in time). - - Args: - freq_masks - how many frequency segments should be cut - time_masks - how many time segments should be cut - freq_width - maximum number of frequencies to be cut in one segment - time_width - maximum number of time steps to be cut in one segment. - Can be a positive integer or a float value in the range [0, 1]. - If positive integer value, defines maximum number of time steps - to be cut in one segment. - If a float value, defines maximum percentage of timesteps that - are cut adaptively. - rng: Ignored. - """ - - @property - def input_types(self): - """Returns definitions of module input types - """ - return { - "input_spec": NeuralType(('B', 'D', 'T'), SpectrogramType()), - "length": NeuralType(tuple('B'), LengthsType()), - } - - @property - def output_types(self): - """Returns definitions of module output types - """ - return {"augmented_spec": NeuralType(('B', 'D', 'T'), SpectrogramType())} - - def __init__( - self, freq_masks=0, time_masks=0, freq_width=10, time_width=0.1, rng=None, mask_value=0.0, - ): - super().__init__() - # Message to mention that numba specaugment kernel will be available - # if input device is CUDA and lengths are provided - logging.debug("Numba SpecAugment kernel is available") - - self.freq_masks = freq_masks - self.time_masks = time_masks - - self.freq_width = freq_width - self.time_width = time_width - - self.mask_value = mask_value - - # Unused - self.rng = rng - if self.rng is not None: - logging.warning("`rng` was supplied to SpecAugmentNumba, but it is not used.") - - if isinstance(time_width, int): - self.adaptive_temporal_width = False - else: - if time_width > 1.0 or time_width < 0.0: - raise ValueError('If `time_width` is a float value, must be in range [0, 1]') - - self.adaptive_temporal_width = True - - @typecheck() - @torch.no_grad() - def forward(self, input_spec, length): - sh = input_spec.shape - bs = sh[0] - - # Construct the freq and time masks as well as start positions - if self.freq_masks > 0: - freq_starts = torch.randint( - 0, sh[1] - self.freq_width + 1, size=[bs, self.freq_masks], device=input_spec.device - ) - freq_lengths = torch.randint(0, self.freq_width + 1, size=[bs, self.freq_masks], device=input_spec.device) - else: - freq_starts = torch.zeros([bs, 1], dtype=torch.int64, device=input_spec.device) - freq_lengths = torch.zeros([bs, 1], dtype=torch.int64, device=input_spec.device) - - if self.time_masks > 0: - if self.adaptive_temporal_width: - time_width = (length * self.time_width).int().clamp(min=1) - else: - time_width = ( - torch.tensor(self.time_width, dtype=torch.int32, device=input_spec.device) - .unsqueeze(0) - .repeat(sh[0]) - ) - - time_starts = [] - time_lengths = [] - for idx in range(sh[0]): - time_starts.append( - torch.randint( - 0, max(1, length[idx] - time_width[idx]), size=[1, self.time_masks], device=input_spec.device - ) - ) - time_lengths.append( - torch.randint(0, time_width[idx] + 1, size=[1, self.time_masks], device=input_spec.device) - ) - - time_starts = torch.cat(time_starts, 0) - time_lengths = torch.cat(time_lengths, 0) - - else: - time_starts = torch.zeros([bs, 1], dtype=torch.int64, device=input_spec.device) - time_lengths = torch.zeros([bs, 1], dtype=torch.int64, device=input_spec.device) - - x = launch_spec_augment_kernel( - input_spec, - length, - freq_starts=freq_starts, - freq_lengths=freq_lengths, - time_starts=time_starts, - time_lengths=time_lengths, - freq_masks=self.freq_masks, - time_masks=self.time_masks, - mask_value=self.mask_value, - ) - - return x diff --git a/nemo/collections/asr/parts/preprocessing/__init__.py b/nemo/collections/asr/parts/preprocessing/__init__.py deleted file mode 100644 index a0785c56bf2aaa09b2ebd1716d70bc59b5a0acdc..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/preprocessing/__init__.py +++ /dev/null @@ -1,36 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.asr.parts.preprocessing.feature_loader import ExternalFeatureLoader -from nemo.collections.asr.parts.preprocessing.features import FeaturizerFactory, FilterbankFeatures, WaveformFeaturizer -from nemo.collections.asr.parts.preprocessing.perturb import ( - AudioAugmentor, - AugmentationDataset, - GainPerturbation, - ImpulsePerturbation, - NoisePerturbation, - NoisePerturbationWithNormalization, - Perturbation, - RirAndNoisePerturbation, - ShiftPerturbation, - SilencePerturbation, - SpeedPerturbation, - TimeStretchPerturbation, - TranscodePerturbation, - WhiteNoisePerturbation, - perturbation_types, - process_augmentations, - register_perturbation, -) -from nemo.collections.asr.parts.preprocessing.segment import AudioSegment diff --git a/nemo/collections/asr/parts/preprocessing/feature_loader.py b/nemo/collections/asr/parts/preprocessing/feature_loader.py deleted file mode 100644 index e715d2dafb95396597e89d4f1a1eb1cc1dce417b..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/preprocessing/feature_loader.py +++ /dev/null @@ -1,78 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -from typing import Optional - -import numpy as np -import torch - - -class ExternalFeatureLoader(object): - """Feature loader that load external features store in certain format. - Currently support pickle, npy and npz format. - """ - - def __init__( - self, - augmentor: Optional["nemo.collections.asr.parts.perturb.FeatureAugmentor"] = None, - ): - """ - Feature loader - """ - self.augmentor = augmentor - - def load_feature_from_file(self, file_path: str): - """Load samples from file_path and convert it to be of type float32 - file_path (str) is the path of the file that stores feature/sample. - """ - - if file_path.endswith(".pt") or file_path.endswith(".pth"): - samples = torch.load(file_path, map_location="cpu").float().numpy() - return samples - else: - # load pickle/npy/npz file - samples = np.load(file_path, allow_pickle=True) - return self._convert_samples_to_float32(samples) - # TODO load other type of files such as kaldi io ark - - @staticmethod - def _convert_samples_to_float32(samples: np.ndarray) -> np.ndarray: - """Convert sample type to float32. - Integers will be scaled to [-1, 1] in float32. - """ - float32_samples = samples.astype('float32') - if samples.dtype in (np.int8, np.int16, np.int32, np.int64): - bits = np.iinfo(samples.dtype).bits - float32_samples *= 1.0 / 2 ** (bits - 1) - elif samples.dtype in (np.float16, np.float32, np.float64): - pass - else: - raise TypeError("Unsupported sample type: %s." % samples.dtype) - return float32_samples - - def process(self, file_path: str) -> torch.Tensor: - """Processes the features from the provided `file_path`.""" - features = self.load_feature_from_file(file_path) - features = self.process_segment(features) - return features - - def process_segment(self, feature_segment): - """Processes the provided feature segment.""" - if self.augmentor: - # augmentor for external features. Here possible augmentor for - # external embedding feature is Diaconis Augmentation and might - # be implemented later - self.augmentor.perturb(feature_segment) - return torch.tensor(feature_segment, dtype=torch.float) - - return torch.tensor(feature_segment, dtype=torch.float) diff --git a/nemo/collections/asr/parts/preprocessing/features.py b/nemo/collections/asr/parts/preprocessing/features.py deleted file mode 100644 index ec0fa8f6f74d35a577f7db556f111437361e091d..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/preprocessing/features.py +++ /dev/null @@ -1,492 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Copyright (c) 2018 Ryan Leary -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in all -# copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. -# This file contains code artifacts adapted from https://github.com/ryanleary/patter -import math -import random - -import librosa -import numpy as np -import torch -import torch.nn as nn - -from nemo.collections.asr.parts.preprocessing.perturb import AudioAugmentor -from nemo.collections.asr.parts.preprocessing.segment import AudioSegment -from nemo.utils import logging - -CONSTANT = 1e-5 - - -def normalize_batch(x, seq_len, normalize_type): - x_mean = None - x_std = None - if normalize_type == "per_feature": - batch_size = x.shape[0] - max_time = x.shape[2] - - # When doing stream capture to a graph, item() is not allowed - # becuase it calls cudaStreamSynchronize(). Therefore, we are - # sacrificing some error checking when running with cuda graphs. - if ( - torch.cuda.is_available() - and not torch.cuda.is_current_stream_capturing() - and torch.any(seq_len == 1).item() - ): - raise ValueError( - "normalize_batch with `per_feature` normalize_type received a tensor of length 1. This will result " - "in torch.std() returning nan. Make sure your audio length has enough samples for a single " - "feature (ex. at least `hop_length` for Mel Spectrograms)." - ) - time_steps = torch.arange(max_time, device=x.device).unsqueeze(0).expand(batch_size, max_time) - valid_mask = time_steps < seq_len.unsqueeze(1) - x_mean_numerator = torch.where(valid_mask.unsqueeze(1), x, 0.0).sum(axis=2) - x_mean_denominator = valid_mask.sum(axis=1) - x_mean = x_mean_numerator / x_mean_denominator.unsqueeze(1) - - # Subtract 1 in the denominator to correct for the bias. - x_std = torch.sqrt( - torch.sum(torch.where(valid_mask.unsqueeze(1), x - x_mean.unsqueeze(2), 0.0) ** 2, axis=2) - / (x_mean_denominator.unsqueeze(1) - 1.0) - ) - x_std = x_std.masked_fill(x_std.isnan(), 0.0) # edge case: only 1 frame in denominator - # make sure x_std is not zero - x_std += CONSTANT - return (x - x_mean.unsqueeze(2)) / x_std.unsqueeze(2), x_mean, x_std - elif normalize_type == "all_features": - x_mean = torch.zeros(seq_len.shape, dtype=x.dtype, device=x.device) - x_std = torch.zeros(seq_len.shape, dtype=x.dtype, device=x.device) - for i in range(x.shape[0]): - x_mean[i] = x[i, :, : seq_len[i].item()].mean() - x_std[i] = x[i, :, : seq_len[i].item()].std() - # make sure x_std is not zero - x_std += CONSTANT - return (x - x_mean.view(-1, 1, 1)) / x_std.view(-1, 1, 1), x_mean, x_std - elif "fixed_mean" in normalize_type and "fixed_std" in normalize_type: - x_mean = torch.tensor(normalize_type["fixed_mean"], device=x.device) - x_std = torch.tensor(normalize_type["fixed_std"], device=x.device) - return ( - (x - x_mean.view(x.shape[0], x.shape[1]).unsqueeze(2)) / x_std.view(x.shape[0], x.shape[1]).unsqueeze(2), - x_mean, - x_std, - ) - else: - return x, x_mean, x_std - - -def clean_spectrogram_batch(spectrogram: torch.Tensor, spectrogram_len: torch.Tensor, fill_value=0.0) -> torch.Tensor: - """ - Fill spectrogram values outside the length with `fill_value` - - Args: - spectrogram: Tensor with shape [B, C, L] containing batched spectrograms - spectrogram_len: Tensor with shape [B] containing the sequence length of each batch element - fill_value: value to fill with, 0.0 by default - - Returns: - cleaned spectrogram, tensor with shape equal to `spectrogram` - """ - device = spectrogram.device - batch_size, _, max_len = spectrogram.shape - mask = torch.arange(max_len, device=device)[None, :] >= spectrogram_len[:, None] - mask = mask.unsqueeze(1).expand_as(spectrogram) - return spectrogram.masked_fill(mask, fill_value) - - -def splice_frames(x, frame_splicing): - """Stacks frames together across feature dim - - input is batch_size, feature_dim, num_frames - output is batch_size, feature_dim*frame_splicing, num_frames - - """ - seq = [x] - for n in range(1, frame_splicing): - seq.append(torch.cat([x[:, :, :n], x[:, :, n:]], dim=2)) - return torch.cat(seq, dim=1) - - -@torch.jit.script_if_tracing -def make_seq_mask_like( - lengths: torch.Tensor, like: torch.Tensor, time_dim: int = -1, valid_ones: bool = True -) -> torch.Tensor: - """ - - Args: - lengths: Tensor with shape [B] containing the sequence length of each batch element - like: The mask will contain the same number of dimensions as this Tensor, and will have the same max - length in the time dimension of this Tensor. - time_dim: Time dimension of the `shape_tensor` and the resulting mask. Zero-based. - valid_ones: If True, valid tokens will contain value `1` and padding will be `0`. Else, invert. - - Returns: - A :class:`torch.Tensor` containing 1's and 0's for valid and invalid tokens, respectively, if `valid_ones`, else - vice-versa. Mask will have the same number of dimensions as `like`. Batch and time dimensions will match - the `like`. All other dimensions will be singletons. E.g., if `like.shape == [3, 4, 5]` and - `time_dim == -1', mask will have shape `[3, 1, 5]`. - """ - # Mask with shape [B, T] - mask = torch.arange(like.shape[time_dim], device=like.device).repeat(lengths.shape[0], 1).lt(lengths.view(-1, 1)) - # [B, T] -> [B, *, T] where * is any number of singleton dimensions to expand to like tensor - for _ in range(like.dim() - mask.dim()): - mask = mask.unsqueeze(1) - # If needed, transpose time dim - if time_dim != -1 and time_dim != mask.dim() - 1: - mask = mask.transpose(-1, time_dim) - # Maybe invert the padded vs. valid token values - if not valid_ones: - mask = ~mask - return mask - - -class WaveformFeaturizer(object): - def __init__(self, sample_rate=16000, int_values=False, augmentor=None): - self.augmentor = augmentor if augmentor is not None else AudioAugmentor() - self.sample_rate = sample_rate - self.int_values = int_values - - def max_augmentation_length(self, length): - return self.augmentor.max_augmentation_length(length) - - def process( - self, - file_path, - offset=0, - duration=0, - trim=False, - trim_ref=np.max, - trim_top_db=60, - trim_frame_length=2048, - trim_hop_length=512, - orig_sr=None, - channel_selector=None, - normalize_db=None, - ): - audio = AudioSegment.from_file( - file_path, - target_sr=self.sample_rate, - int_values=self.int_values, - offset=offset, - duration=duration, - trim=trim, - trim_ref=trim_ref, - trim_top_db=trim_top_db, - trim_frame_length=trim_frame_length, - trim_hop_length=trim_hop_length, - orig_sr=orig_sr, - channel_selector=channel_selector, - normalize_db=normalize_db, - ) - return self.process_segment(audio) - - def process_segment(self, audio_segment): - self.augmentor.perturb(audio_segment) - return torch.tensor(audio_segment.samples, dtype=torch.float) - - @classmethod - def from_config(cls, input_config, perturbation_configs=None): - if perturbation_configs is not None: - aa = AudioAugmentor.from_config(perturbation_configs) - else: - aa = None - - sample_rate = input_config.get("sample_rate", 16000) - int_values = input_config.get("int_values", False) - - return cls(sample_rate=sample_rate, int_values=int_values, augmentor=aa) - - -class FeaturizerFactory(object): - def __init__(self): - pass - - @classmethod - def from_config(cls, input_cfg, perturbation_configs=None): - return WaveformFeaturizer.from_config(input_cfg, perturbation_configs=perturbation_configs) - - -class FilterbankFeatures(nn.Module): - """Featurizer that converts wavs to Mel Spectrograms. - See AudioToMelSpectrogramPreprocessor for args. - """ - - def __init__( - self, - sample_rate=16000, - n_window_size=320, - n_window_stride=160, - window="hann", - normalize="per_feature", - n_fft=None, - preemph=0.97, - nfilt=64, - lowfreq=0, - highfreq=None, - log=True, - log_zero_guard_type="add", - log_zero_guard_value=2**-24, - dither=CONSTANT, - pad_to=16, - max_duration=16.7, - frame_splicing=1, - exact_pad=False, - pad_value=0, - mag_power=2.0, - use_grads=False, - rng=None, - nb_augmentation_prob=0.0, - nb_max_freq=4000, - mel_norm="slaney", - stft_exact_pad=False, # Deprecated arguments; kept for config compatibility - stft_conv=False, # Deprecated arguments; kept for config compatibility - ): - super().__init__() - if stft_conv or stft_exact_pad: - logging.warning( - "Using torch_stft is deprecated and has been removed. The values have been forcibly set to False " - "for FilterbankFeatures and AudioToMelSpectrogramPreprocessor. Please set exact_pad to True " - "as needed." - ) - if exact_pad and n_window_stride % 2 == 1: - raise NotImplementedError( - f"{self} received exact_pad == True, but hop_size was odd. If audio_length % hop_size == 0. Then the " - "returned spectrogram would not be of length audio_length // hop_size. Please use an even hop_size." - ) - self.log_zero_guard_value = log_zero_guard_value - if ( - n_window_size is None - or n_window_stride is None - or not isinstance(n_window_size, int) - or not isinstance(n_window_stride, int) - or n_window_size <= 0 - or n_window_stride <= 0 - ): - raise ValueError( - f"{self} got an invalid value for either n_window_size or " - f"n_window_stride. Both must be positive ints." - ) - - self.sample_rate = sample_rate - self.win_length = n_window_size - self.hop_length = n_window_stride - self.n_fft = n_fft or 2 ** math.ceil(math.log2(self.win_length)) - self.stft_pad_amount = (self.n_fft - self.hop_length) // 2 if exact_pad else None - self.exact_pad = exact_pad - self.sample_rate = sample_rate - - if exact_pad: - logging.info("STFT using exact pad") - torch_windows = { - 'hann': torch.hann_window, - 'hamming': torch.hamming_window, - 'blackman': torch.blackman_window, - 'bartlett': torch.bartlett_window, - 'none': None, - } - window_fn = torch_windows.get(window, None) - window_tensor = window_fn(self.win_length, periodic=False) if window_fn else None - self.register_buffer("window", window_tensor) - - self.normalize = normalize - self.log = log - self.dither = dither - self.frame_splicing = frame_splicing - self.nfilt = nfilt - self.preemph = preemph - self.pad_to = pad_to - highfreq = highfreq or sample_rate / 2 - - filterbanks = torch.tensor( - librosa.filters.mel( - sr=sample_rate, n_fft=self.n_fft, n_mels=nfilt, fmin=lowfreq, fmax=highfreq, norm=mel_norm - ), - dtype=torch.float, - ).unsqueeze(0) - self.register_buffer("fb", filterbanks) - - # Calculate maximum sequence length - max_length = self.get_seq_len(torch.tensor(max_duration * sample_rate, dtype=torch.float)) - max_pad = pad_to - (max_length % pad_to) if pad_to > 0 else 0 - self.max_length = max_length + max_pad - self.pad_value = pad_value - self.mag_power = mag_power - - # We want to avoid taking the log of zero - # There are two options: either adding or clamping to a small value - if log_zero_guard_type not in ["add", "clamp"]: - raise ValueError( - f"{self} received {log_zero_guard_type} for the " - f"log_zero_guard_type parameter. It must be either 'add' or " - f"'clamp'." - ) - - self.use_grads = use_grads - if not use_grads: - self.forward = torch.no_grad()(self.forward) - self._rng = random.Random() if rng is None else rng - self.nb_augmentation_prob = nb_augmentation_prob - if self.nb_augmentation_prob > 0.0: - if nb_max_freq >= sample_rate / 2: - self.nb_augmentation_prob = 0.0 - else: - self._nb_max_fft_bin = int((nb_max_freq / sample_rate) * n_fft) - - # log_zero_guard_value is the the small we want to use, we support - # an actual number, or "tiny", or "eps" - self.log_zero_guard_type = log_zero_guard_type - logging.debug(f"sr: {sample_rate}") - logging.debug(f"n_fft: {self.n_fft}") - logging.debug(f"win_length: {self.win_length}") - logging.debug(f"hop_length: {self.hop_length}") - logging.debug(f"n_mels: {nfilt}") - logging.debug(f"fmin: {lowfreq}") - logging.debug(f"fmax: {highfreq}") - logging.debug(f"using grads: {use_grads}") - logging.debug(f"nb_augmentation_prob: {nb_augmentation_prob}") - - def stft(self, x): - return torch.stft( - x, - n_fft=self.n_fft, - hop_length=self.hop_length, - win_length=self.win_length, - center=False if self.exact_pad else True, - window=self.window.to(dtype=torch.float, device=x.device), - return_complex=True, - pad_mode="constant", - ) - - def log_zero_guard_value_fn(self, x): - if isinstance(self.log_zero_guard_value, str): - if self.log_zero_guard_value == "tiny": - return torch.finfo(x.dtype).tiny - elif self.log_zero_guard_value == "eps": - return torch.finfo(x.dtype).eps - else: - raise ValueError( - f"{self} received {self.log_zero_guard_value} for the " - f"log_zero_guard_type parameter. It must be either a " - f"number, 'tiny', or 'eps'" - ) - else: - return self.log_zero_guard_value - - def get_seq_len(self, seq_len): - # Assuming that center is True is stft_pad_amount = 0 - pad_amount = self.stft_pad_amount * 2 if self.stft_pad_amount is not None else self.n_fft // 2 * 2 - seq_len = torch.floor_divide((seq_len + pad_amount - self.n_fft), self.hop_length) - return seq_len.to(dtype=torch.long) - - @property - def filter_banks(self): - return self.fb - - def forward(self, x, seq_len, linear_spec=False): - seq_len_time = seq_len - seq_len_unfixed = self.get_seq_len(seq_len) - # fix for seq_len = 0 for streaming; if size was 0, it is always padded to 1, and normalizer fails - seq_len = torch.where(seq_len == 0, torch.zeros_like(seq_len_unfixed), seq_len_unfixed) - - if self.stft_pad_amount is not None: - x = torch.nn.functional.pad( - x.unsqueeze(1), (self.stft_pad_amount, self.stft_pad_amount), "constant" - ).squeeze(1) - - # dither (only in training mode for eval determinism) - if self.training and self.dither > 0: - x += self.dither * torch.randn_like(x) - - # do preemphasis - if self.preemph is not None: - timemask = torch.arange(x.shape[1], device=x.device).unsqueeze(0) < seq_len_time.unsqueeze(1) - x = torch.cat((x[:, 0].unsqueeze(1), x[:, 1:] - self.preemph * x[:, :-1]), dim=1) - x = x.masked_fill(~timemask, 0.0) - - # disable autocast to get full range of stft values - with torch.amp.autocast(x.device.type, enabled=False): - x = self.stft(x) - - # torch stft returns complex tensor (of shape [B,N,T]); so convert to magnitude - # guard is needed for sqrt if grads are passed through - guard = 0 if not self.use_grads else CONSTANT - x = torch.view_as_real(x) - x = torch.sqrt(x.pow(2).sum(-1) + guard) - - if self.training and self.nb_augmentation_prob > 0.0: - for idx in range(x.shape[0]): - if self._rng.random() < self.nb_augmentation_prob: - x[idx, self._nb_max_fft_bin :, :] = 0.0 - - # get power spectrum - if self.mag_power != 1.0: - x = x.pow(self.mag_power) - - # return plain spectrogram if required - if linear_spec: - return x, seq_len - - # disable autocast, otherwise it might be automatically casted to fp16 - # on fp16 compatible GPUs and get NaN values for input value of 65520 - with torch.amp.autocast(x.device.type, enabled=False): - # dot with filterbank energies - x = torch.matmul(self.fb.to(x.dtype), x) - # log features if required - if self.log: - if self.log_zero_guard_type == "add": - x = torch.log(x + self.log_zero_guard_value_fn(x)) - elif self.log_zero_guard_type == "clamp": - x = torch.log(torch.clamp(x, min=self.log_zero_guard_value_fn(x))) - else: - raise ValueError("log_zero_guard_type was not understood") - - # frame splicing if required - if self.frame_splicing > 1: - x = splice_frames(x, self.frame_splicing) - - # normalize if required - if self.normalize: - x, _, _ = normalize_batch(x, seq_len, normalize_type=self.normalize) - - # mask to zero any values beyond seq_len in batch, pad to multiple of `pad_to` (for efficiency) - max_len = x.size(-1) - mask = torch.arange(max_len, device=x.device) - mask = mask.repeat(x.size(0), 1) >= seq_len.unsqueeze(1) - x = x.masked_fill(mask.unsqueeze(1).type(torch.bool).to(device=x.device), self.pad_value) - del mask - pad_to = self.pad_to - if pad_to == "max": - x = nn.functional.pad(x, (0, self.max_length - x.size(-1)), value=self.pad_value) - elif pad_to > 0: - pad_amt = x.size(-1) % pad_to - if pad_amt != 0: - x = nn.functional.pad(x, (0, pad_to - pad_amt), value=self.pad_value) - return x, seq_len diff --git a/nemo/collections/asr/parts/preprocessing/perturb.py b/nemo/collections/asr/parts/preprocessing/perturb.py deleted file mode 100644 index 6f1704d07f02dfeed923ae139fd67dec540acd2c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/preprocessing/perturb.py +++ /dev/null @@ -1,1397 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Copyright (c) 2018 Ryan Leary -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in all -# copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. -# This file contains code artifacts adapted from https://github.com/ryanleary/patter -import copy -import inspect -import io -import os -import random -import subprocess -from tempfile import NamedTemporaryFile -from typing import Any, List, Optional, Union - -import librosa -import numpy as np -import soundfile as sf -from scipy import signal - -from nemo.collections.asr.parts.preprocessing.segment import AudioSegment -from nemo.collections.common.parts.preprocessing import collections, parsers -from nemo.core.classes import IterableDataset -from nemo.utils import logging - -# TODO @blisc: Perhaps refactor instead of import guarding -HAVE_OMEGACONG_WEBDATASET = True -try: - from omegaconf import DictConfig, OmegaConf - - from nemo.utils import webdataset as wds - -except ModuleNotFoundError: - from nemo.utils.exceptions import LightningNotInstalledException - - HAVE_OMEGACONG_WEBDATASET = False - - -try: - from nemo.collections.asr.parts.utils import numba_utils - - HAVE_NUMBA = True -except (ImportError, ModuleNotFoundError): - HAVE_NUMBA = False - - -def read_one_audiosegment(manifest, target_sr, tarred_audio=False, audio_dataset=None): - if tarred_audio: - if audio_dataset is None: - raise TypeError("Expected augmentation dataset but got None") - audio_file, file_id, manifest_entry = next(audio_dataset) - - offset = 0 if manifest_entry.offset is None else manifest_entry.offset - duration = 0 if manifest_entry.duration is None else manifest_entry.duration - - else: - audio_record = random.sample(manifest.data, 1)[0] - audio_file = audio_record.audio_file - offset = 0 if audio_record.offset is None else audio_record.offset - duration = 0 if audio_record.duration is None else audio_record.duration - - return AudioSegment.from_file(audio_file, target_sr=target_sr, offset=offset, duration=duration) - - -class Perturbation(object): - def max_augmentation_length(self, length): - return length - - def perturb(self, data): - raise NotImplementedError - - -class SpeedPerturbation(Perturbation): - """ - Performs Speed Augmentation by re-sampling the data to a different sampling rate, - which does not preserve pitch. - - Note: This is a very slow operation for online augmentation. If space allows, - it is preferable to pre-compute and save the files to augment the dataset. - - Args: - sr: Original sampling rate. - resample_type: Type of resampling operation that will be performed. - For better speed using `resampy`'s fast resampling method, use `resample_type='kaiser_fast'`. - For high-quality resampling, set `resample_type='kaiser_best'`. - To use `scipy.signal.resample`, set `resample_type='fft'` or `resample_type='scipy'` - min_speed_rate: Minimum sampling rate modifier. - max_speed_rate: Maximum sampling rate modifier. - num_rates: Number of discrete rates to allow. Can be a positive or negative - integer. - If a positive integer greater than 0 is provided, the range of - speed rates will be discretized into `num_rates` values. - If a negative integer or 0 is provided, the full range of speed rates - will be sampled uniformly. - Note: If a positive integer is provided and the resultant discretized - range of rates contains the value '1.0', then those samples with rate=1.0, - will not be augmented at all and simply skipped. This is to unnecessary - augmentation and increase computation time. Effective augmentation chance - in such a case is = `prob * (num_rates - 1 / num_rates) * 100`% chance - where `prob` is the global probability of a sample being augmented. - rng: Random seed. Default is None - """ - - def __init__(self, sr, resample_type, min_speed_rate=0.9, max_speed_rate=1.1, num_rates=5, rng=None): - - min_rate = min(min_speed_rate, max_speed_rate) - if min_rate < 0.0: - raise ValueError("Minimum sampling rate modifier must be > 0.") - - if resample_type not in ('kaiser_best', 'kaiser_fast', 'fft', 'scipy'): - raise ValueError("Supported `resample_type` values are ('kaiser_best', 'kaiser_fast', 'fft', 'scipy')") - - self._sr = sr - self._min_rate = min_speed_rate - self._max_rate = max_speed_rate - self._num_rates = num_rates - if num_rates > 0: - self._rates = np.linspace(self._min_rate, self._max_rate, self._num_rates, endpoint=True) - self._res_type = resample_type - random.seed(rng) if rng else None - - def max_augmentation_length(self, length): - return length * self._max_rate - - def perturb(self, data): - # Select speed rate either from choice or random sample - if self._num_rates < 0: - speed_rate = random.uniform(self._min_rate, self._max_rate) - else: - speed_rate = random.choice(self._rates) - - # Skip perturbation in case of identity speed rate - if speed_rate == 1.0: - return - - new_sr = int(self._sr * speed_rate) - try: - data._samples = librosa.core.resample( - data._samples, orig_sr=self._sr, target_sr=new_sr, res_type=self._res_type - ) - except Exception as e: - logging.warning(f"Failed to resample audio from {self._sr} to {new_sr}. Skipping augmentation. Error: {e}") - return - - -class TimeStretchPerturbation(Perturbation): - """ - Time-stretch an audio series by a fixed rate while preserving pitch, based on [1]_, [2]_. - - Note: - This is a simplified implementation, intended primarily for reference and pedagogical purposes. - It makes no attempt to handle transients, and is likely to produce audible artifacts. - - References - ---------- - .. [1] Ellis, D. P. W. "A phase vocoder in Matlab." Columbia University, 2002. - ``_ - .. [2] librosa.effects.time_stretch - ``_ - - Args: - min_speed_rate: Minimum sampling rate modifier. - max_speed_rate: Maximum sampling rate modifier. - num_rates: Number of discrete rates to allow. Can be a positive or negative - integer. - If a positive integer greater than 0 is provided, the range of - speed rates will be discretized into `num_rates` values. - If a negative integer or 0 is provided, the full range of speed rates - will be sampled uniformly. - Note: If a positive integer is provided and the resultant discretized - range of rates contains the value '1.0', then those samples with rate=1.0, - will not be augmented at all and simply skipped. This is to avoid unnecessary - augmentation and increase computation time. Effective augmentation chance - in such a case is = `prob * (num_rates - 1 / num_rates) * 100`% chance - where `prob` is the global probability of a sample being augmented. - n_fft: Number of fft filters to be computed. - rng: Random seed. Default is None - """ - - def __init__(self, min_speed_rate=0.9, max_speed_rate=1.1, num_rates=5, n_fft=512, rng=None): - - min_rate = min(min_speed_rate, max_speed_rate) - if min_rate < 0.0: - raise ValueError("Minimum sampling rate modifier must be > 0.") - - self._min_rate = min_speed_rate - self._max_rate = max_speed_rate - self._num_rates = num_rates - if num_rates > 0: - self._rates = np.linspace(self._min_rate, self._max_rate, self._num_rates, endpoint=True) - random.seed(rng) if rng else None - - # Pre-compute constants - self._n_fft = int(n_fft) - self._hop_length = int(n_fft // 2) - - # Pre-allocate buffers - self._phi_advance_fast = np.linspace(0, np.pi * self._hop_length, self._hop_length + 1) - self._scale_buffer_fast = np.empty(self._hop_length + 1, dtype=np.float32) - - self._phi_advance_slow = np.linspace(0, np.pi * self._n_fft, self._n_fft + 1) - self._scale_buffer_slow = np.empty(self._n_fft + 1, dtype=np.float32) - - def max_augmentation_length(self, length): - return length * self._max_rate - - def perturb(self, data): - # Select speed rate either from choice or random sample - if self._num_rates < 0: - speed_rate = random.uniform(self._min_rate, self._max_rate) - else: - speed_rate = random.choice(self._rates) - - # Skip perturbation in case of identity speed rate - if speed_rate == 1.0: - return - - # Increase `n_fft` based on task (speed up or slow down audio) - # This greatly reduces upper bound of maximum time taken - # to compute slowed down audio segments. - if speed_rate >= 1.0: # Speed up audio - fft_multiplier = 1 - phi_advance = self._phi_advance_fast - scale_buffer = self._scale_buffer_fast - - else: # Slow down audio - fft_multiplier = 2 - phi_advance = self._phi_advance_slow - scale_buffer = self._scale_buffer_slow - - n_fft = int(self._n_fft * fft_multiplier) - hop_length = int(self._hop_length * fft_multiplier) - - # Perform short-term Fourier transform (STFT) - stft = librosa.core.stft(data._samples, n_fft=n_fft, hop_length=hop_length) - - # Stretch by phase vocoding - if HAVE_NUMBA: - stft_stretch = numba_utils.phase_vocoder(stft, speed_rate, phi_advance, scale_buffer) - - else: - stft_stretch = librosa.core.phase_vocoder(stft, speed_rate, hop_length) - - # Predict the length of y_stretch - len_stretch = int(round(len(data._samples) / speed_rate)) - - # Invert the STFT - y_stretch = librosa.core.istft( - stft_stretch, dtype=data._samples.dtype, hop_length=hop_length, length=len_stretch - ) - - data._samples = y_stretch - - -class SilencePerturbation(Perturbation): - """ - Applies random silence at the start and/or end of the audio. - - Args: - min_start_silence_secs (float): Min start silence level in secs - max_start_silence_secs (float): Max start silence level in secs - min_end_silence_secs (float): Min end silence level in secs - max_end_silence_secs (float): Max end silence level in secs - rng (int): Random seed. Default is None - value: (float): value representing silence to be added to audio array. - """ - - def __init__( - self, - min_start_silence_secs: float = 0, - max_start_silence_secs: float = 0, - min_end_silence_secs: float = 0, - max_end_silence_secs: float = 0, - rng: int = None, - value: float = 0, - ): - self._min_start_silence_secs = min_start_silence_secs - self._max_start_silence_secs = max_start_silence_secs - self._min_end_silence_secs = min_end_silence_secs - self._max_end_silence_secs = max_end_silence_secs - - random.seed(rng) if rng else None - self._value = value - - def perturb(self, data): - start_silence_len = random.uniform(self._min_start_silence_secs, self._max_start_silence_secs) - end_silence_len = random.uniform(self._min_end_silence_secs, self._max_end_silence_secs) - start = np.full((int(start_silence_len * data.sample_rate),), self._value) - end = np.full((int(end_silence_len * data.sample_rate),), self._value) - - data._samples = np.concatenate([start, data._samples, end]) - - -class GainPerturbation(Perturbation): - """ - Applies random gain to the audio. - - Args: - min_gain_dbfs (float): Min gain level in dB - max_gain_dbfs (float): Max gain level in dB - rng (int): Random seed. Default is None - """ - - def __init__(self, min_gain_dbfs=-10, max_gain_dbfs=10, rng=None): - self._min_gain_dbfs = min_gain_dbfs - self._max_gain_dbfs = max_gain_dbfs - random.seed(rng) if rng else None - - def perturb(self, data): - gain = random.uniform(self._min_gain_dbfs, self._max_gain_dbfs) - data._samples = data._samples * (10.0 ** (gain / 20.0)) - - -class ImpulsePerturbation(Perturbation): - """ - Convolves audio with a Room Impulse Response. - - Args: - manifest_path (list): Manifest file for RIRs - audio_tar_filepaths (list): Tar files, if RIR audio files are tarred - shuffle_n (int): Shuffle parameter for shuffling buffered files from the tar files - normalize_impulse (bool): Normalize impulse response to zero mean and amplitude 1 - shift_impulse (bool): Shift impulse response to adjust for delay at the beginning - rng (int): Random seed. Default is None - """ - - def __init__( - self, - manifest_path=None, - audio_tar_filepaths=None, - shuffle_n=128, - normalize_impulse=False, - shift_impulse=False, - rng=None, - ): - self._manifest = collections.ASRAudioText(manifest_path, parser=parsers.make_parser([]), index_by_file_id=True) - self._audiodataset = None - self._tarred_audio = False - self._normalize_impulse = normalize_impulse - self._shift_impulse = shift_impulse - self._data_iterator = None - - if audio_tar_filepaths: - self._tarred_audio = True - self._audiodataset = AugmentationDataset(manifest_path, audio_tar_filepaths, shuffle_n) - self._data_iterator = iter(self._audiodataset) - - self._rng = rng - random.seed(self._rng) if rng else None - - def perturb(self, data): - impulse = read_one_audiosegment( - self._manifest, - data.sample_rate, - tarred_audio=self._tarred_audio, - audio_dataset=self._data_iterator, - ) - - # normalize if necessary - if self._normalize_impulse: - # normalize the impulse response to zero mean and amplitude 1 - impulse_norm = impulse.samples - np.mean(impulse.samples) - impulse_norm /= max(abs(impulse_norm)) - else: - impulse_norm = impulse.samples - - # len of input data samples - len_data = len(data._samples) - - if max(abs(data._samples)) == 0: - logging.warning("Zero audio input found, skipping impulse perturbation.") - return - - # convolve with the full impulse response - data._samples = signal.fftconvolve(data._samples, impulse_norm, "full") - - # compensate the dominant path propagation delay - if self._shift_impulse: - # Find the peak of the IR and shift the output to the left - max_ind = np.argmax(np.abs(impulse_norm)) - data._samples = data._samples[max_ind:] - - # trim to match the input data length - data._samples = data._samples[:len_data] - - if max(abs(data._samples)) == 0: - logging.warning("Zero audio input found after impulse perturbation.") - return - - # normalize data samples to [-1,1] after rir convolution to avoid nans with fp16 training - data._samples = data._samples / max(abs(data._samples)) - - -class ShiftPerturbation(Perturbation): - """ - Perturbs audio by shifting the audio in time by a random amount between min_shift_ms and max_shift_ms. - The final length of the audio is kept unaltered by padding the audio with zeros. - - - Args: - min_shift_ms (float): Minimum time in milliseconds by which audio will be shifted - max_shift_ms (float): Maximum time in milliseconds by which audio will be shifted - rng (int): Random seed. Default is None - """ - - def __init__(self, min_shift_ms=-5.0, max_shift_ms=5.0, rng=None): - self._min_shift_ms = min_shift_ms - self._max_shift_ms = max_shift_ms - random.seed(rng) if rng else None - - def perturb(self, data): - shift_ms = random.uniform(self._min_shift_ms, self._max_shift_ms) - if abs(shift_ms) / 1000 > data.duration: - # TODO: do something smarter than just ignore this condition - return - shift_samples = int(shift_ms * data.sample_rate // 1000) - # logging.debug("shift: %s", shift_samples) - if shift_samples < 0: - data._samples[-shift_samples:] = data._samples[:shift_samples] - data._samples[:-shift_samples] = 0 - elif shift_samples > 0: - data._samples[:-shift_samples] = data._samples[shift_samples:] - data._samples[-shift_samples:] = 0 - - -class NoisePerturbation(Perturbation): - """ - Perturbation that adds noise to input audio. - - Args: - manifest_path (str): Manifest file with paths to noise files - min_snr_db (float): Minimum SNR of audio after noise is added - max_snr_db (float): Maximum SNR of audio after noise is added - max_gain_db (float): Maximum gain that can be applied on the noise sample - audio_tar_filepaths (list) : Tar files, if noise audio files are tarred - shuffle_n (int): Shuffle parameter for shuffling buffered files from the tar files - orig_sr (int): Original sampling rate of the noise files - rng (int): Random seed. Default is None - """ - - def __init__( - self, - manifest_path=None, - min_snr_db=10, - max_snr_db=50, - max_gain_db=300.0, - rng=None, - audio_tar_filepaths=None, - shuffle_n=100, - orig_sr=16000, - ): - self._manifest = collections.ASRAudioText(manifest_path, parser=parsers.make_parser([]), index_by_file_id=True) - self._audiodataset = None - self._tarred_audio = False - self._orig_sr = orig_sr - self._data_iterator = None - - if audio_tar_filepaths: - self._tarred_audio = True - self._audiodataset = AugmentationDataset(manifest_path, audio_tar_filepaths, shuffle_n) - self._data_iterator = iter(self._audiodataset) - - random.seed(rng) if rng else None - self._rng = rng - - self._min_snr_db = min_snr_db - self._max_snr_db = max_snr_db - self._max_gain_db = max_gain_db - - @property - def orig_sr(self): - return self._orig_sr - - def get_one_noise_sample(self, target_sr): - return read_one_audiosegment( - self._manifest, target_sr, tarred_audio=self._tarred_audio, audio_dataset=self._data_iterator - ) - - def perturb(self, data, ref_mic=0): - """ - Args: - data (AudioSegment): audio data - ref_mic (int): reference mic index for scaling multi-channel audios - """ - noise = read_one_audiosegment( - self._manifest, - data.sample_rate, - tarred_audio=self._tarred_audio, - audio_dataset=self._data_iterator, - ) - self.perturb_with_input_noise(data, noise, ref_mic=ref_mic) - - def perturb_with_input_noise(self, data, noise, data_rms=None, ref_mic=0): - """ - Args: - data (AudioSegment): audio data - noise (AudioSegment): noise data - data_rms (Union[float, List[float]): rms_db for data input - ref_mic (int): reference mic index for scaling multi-channel audios - """ - if data.num_channels != noise.num_channels: - raise ValueError( - f"Found mismatched channels for data ({data.num_channels}) and noise ({noise.num_channels})." - ) - - if not (0 <= ref_mic < data.num_channels): - raise ValueError( - f" reference mic ID must be an integer in [0, {data.num_channels}), got {ref_mic} instead." - ) - - snr_db = random.uniform(self._min_snr_db, self._max_snr_db) - - if data.is_empty(): - logging.warning( - f"Empty audio segment found for {data.audio_file} with offset {data.offset} and duration {data.duration}." - ) - - if data_rms is None: - data_rms = data.rms_db - - if noise.is_empty(): - logging.warning( - f"Empty noise segment found for {noise.audio_file} with offset {noise.offset} and duration {noise.duration}." - ) - noise_rms = -float("inf") - else: - noise_rms = noise.rms_db - - if data.is_empty() and noise.is_empty(): - logging.warning("Both data and noise segments are empty. Skipping perturbation.") - return - - if data.num_channels > 1: - noise_gain_db = data_rms[ref_mic] - noise_rms[ref_mic] - snr_db - else: - noise_gain_db = data_rms - noise_rms - snr_db - noise_gain_db = min(noise_gain_db, self._max_gain_db) - - # calculate noise segment to use - start_time = random.uniform(0.0, noise.duration - data.duration) - if noise.duration > (start_time + data.duration): - noise.subsegment(start_time=start_time, end_time=start_time + data.duration) - - # adjust gain for snr purposes and superimpose - noise.gain_db(noise_gain_db) - - if noise._samples.shape[0] < data._samples.shape[0]: - noise_idx = random.randint(0, data._samples.shape[0] - noise._samples.shape[0]) - data._samples[noise_idx : noise_idx + noise._samples.shape[0]] += noise._samples - - else: - data._samples += noise._samples - - def perturb_with_foreground_noise(self, data, noise, data_rms=None, max_noise_dur=2, max_additions=1, ref_mic=0): - """ - Args: - data (AudioSegment): audio data - noise (AudioSegment): noise data - data_rms (Union[float, List[float]): rms_db for data input - max_noise_dur: (float): max noise duration - max_additions (int): number of times for adding noise - ref_mic (int): reference mic index for scaling multi-channel audios - """ - if data.num_channels != noise.num_channels: - raise ValueError( - f"Found mismatched channels for data ({data.num_channels}) and noise ({noise.num_channels})." - ) - - if not (0 <= ref_mic < data.num_channels): - raise ValueError( - f" reference mic ID must be an integer in [0, {data.num_channels}), got {ref_mic} instead." - ) - - snr_db = random.uniform(self._min_snr_db, self._max_snr_db) - if not data_rms: - data_rms = data.rms_db - - if data.num_channels > 1: - noise_gain_db = data_rms[ref_mic] - noise.rms_db[ref_mic] - snr_db - else: - noise_gain_db = data_rms - noise.rms_db - snr_db - noise_gain_db = min(noise_gain_db, self._max_gain_db) - - n_additions = random.randint(1, max_additions) - - for i in range(n_additions): - noise_dur = random.uniform(0.0, max_noise_dur) - start_time = random.uniform(0.0, noise.duration) - start_sample = int(round(start_time * noise.sample_rate)) - end_sample = int(round(min(noise.duration, (start_time + noise_dur)) * noise.sample_rate)) - noise_samples = np.copy(noise._samples[start_sample:end_sample]) - # adjust gain for snr purposes and superimpose - noise_samples *= 10.0 ** (noise_gain_db / 20.0) - - if noise_samples.shape[0] > data._samples.shape[0]: - noise_samples = noise_samples[0 : data._samples.shape[0]] - - noise_idx = random.randint(0, data._samples.shape[0] - noise_samples.shape[0]) - data._samples[noise_idx : noise_idx + noise_samples.shape[0]] += noise_samples - - -class NoisePerturbationWithNormalization(Perturbation): - """ - Perturbation that adds noise to input audio, with normalisation to specific decibel level. - Also tiles shorter noise samples up to their corresponding clean audio length. - - Args: - manifest_path (str or list): Manifest file with paths to noise files, can be list if using multiple noise sources - min_snr_db (float): Minimum SNR of audio after noise is added - max_snr_db (float): Maximum SNR of audio after noise is added - snr_samples (list): A discrete list of SNRs DBs to sample from when mixing, will be used instead of [min_snr_db,max_snr_db] - norm_to_db (float): Will normalise clean, noise, and mixed samples to this DB - audio_tar_filepaths (str or list) : Tar files, if noise audio files are tarred, can be list for multiple sources - shuffle_n (int): Shuffle parameter for shuffling buffered files from the tar files - orig_sr (int): Original sampling rate of the noise files - rng (int): Random seed. Default is None - shard_strategy (str): if you're using tarred audio and wish to scatter instead of replicate, set this to 'scatter' - epsilon (float): minimum value for RMS DB normalisation to avoid divide by zero - """ - - def __init__( - self, - manifest_path=None, - min_snr_db=10, - max_snr_db=50, - snr_samples=None, - norm_to_db=None, - rng=None, - audio_tar_filepaths=None, - shuffle_n=128, - orig_sr=16000, - global_rank=0, - world_size=1, - shard_strategy='replicate', - epsilon=0.01, - ): - # import here to avoid circular import error - from nemo.collections.asr.data.audio_to_text import RandomizedChainDataset - - self._manifest = collections.ASRAudioText(manifest_path, parser=parsers.make_parser([]), index_by_file_id=True) - self._audiodataset = None - self._tarred_audio = False - self._orig_sr = orig_sr - self._data_iterator = None - - random.seed(rng) if rng else None - self._rng = rng - - if audio_tar_filepaths: - self._tarred_audio = True - if isinstance(manifest_path, str): - manifest_path = [manifest_path] - if isinstance(audio_tar_filepaths, str): - audio_tar_filepaths = [audio_tar_filepaths] - datasets = [] - for tarred_audio_filepath, manifest_filepath in zip(audio_tar_filepaths, manifest_path): - dataset = AugmentationDataset( - manifest_filepath, - tarred_audio_filepath, - shuffle_n, - rank=global_rank, - world_size=world_size, - shard_strategy=shard_strategy, - ) - datasets.append(dataset) - self._audiodataset = RandomizedChainDataset( - datasets, rnd_seed=(rng if rng else random.randint(0, 30000)) + global_rank - ) - if len(self._audiodataset) == 0: - raise RuntimeError( - "NoisePerturbationWithNormalization detected a zero length RandomizedChainDataset, should never happen" - ) - self._data_iterator = iter(self._audiodataset) - - self._min_snr_db = min_snr_db - self._max_snr_db = max_snr_db - self._norm_to_db = norm_to_db - self._snr_samples = snr_samples if isinstance(snr_samples, list) and len(snr_samples) > 0 else None - self._epsilon = epsilon - - @property - def orig_sr(self): - return self._orig_sr - - def read_one_audiosegment(self, target_sr): - if self._tarred_audio: - if self._data_iterator is None: - raise TypeError("Expected valid iterator but got None") - try: - audio_file, file_id, manifest_entry = next(self._data_iterator) - except StopIteration: - self._data_iterator = iter(self._audiodataset) - audio_file, file_id, manifest_entry = next(self._data_iterator) - - offset = 0 if manifest_entry.offset is None else manifest_entry.offset - duration = 0 if manifest_entry.duration is None else manifest_entry.duration - - else: - audio_record = random.sample(self._manifest.data, 1)[0] - audio_file = audio_record.audio_file - offset = 0 if audio_record.offset is None else audio_record.offset - duration = 0 if audio_record.duration is None else audio_record.duration - - return AudioSegment.from_file(audio_file, target_sr=target_sr, offset=offset, duration=duration) - - def perturb(self, data, ref_mic=0): - """ - Args: - data (AudioSegment): audio data - ref_mic (int): reference mic index for scaling multi-channel audios - """ - - noise = self.read_one_audiosegment(data.sample_rate) - - # noise samples need to be at least 1 second long to avoid strange oddities - # in the RMS SNR mixing, so we have a fail-safe here to ensure at least 1 sec duration - while noise.duration < 1: - noise = self.read_one_audiosegment(data.sample_rate) - - self.perturb_with_input_noise(data, noise, ref_mic=ref_mic, norm_to_db=self._norm_to_db) - - def snr_mixer(self, clean, noise, snr, norm_to_db=-25.0): - """ - Mixes the clean audio with the noise - Args: - clean (numpy array): the clean audio data - noise (numpy array): the noise audio data - snr (float): the SNR value for the mixing - norm_to_db (float): the DB value to normalise to before mixing - """ - clean = self.norm_audio_to_db(clean, norm_to_db) - noise = self.norm_audio_to_db(noise, norm_to_db) - - # Set the noise level for a given SNR - # note that if your noise doesn't overlap with your audio then your target SNR - # may not be achievable. Consider using an rms-threshold in the future - noisescalar = 10 ** (-snr / 20.0) - noisenewlevel = noise * noisescalar - noisyspeech = clean + noisenewlevel - - return clean, noisenewlevel, noisyspeech - - def norm_audio_to_db(self, x, norm_to_db): - """ - Normalises audio signal to particular db, with some epsilon in-case of divide by zero - Args: - x (numpy array): input audio signal - norm_to_db (float): the db to normalise to - """ - rms = (x**2).mean(axis=0) ** 0.5 - rms = np.where(np.isclose(rms, 0), self._epsilon, rms) - scalar = 10 ** (norm_to_db / 20.0) / rms - return x * scalar - - def concatenate_noise_sample(self, clean, noise, fs, silence_length=0.25): - """ - Tiles the noise array to match the clean audio array, with small silence between the joins - Args: - clean (numpy array): clean audio data - noise (numpy array): noise audio data - fs (int): sample rate used by both clean and noise audio data - silence_length (float): the amount of silence (in secs) to insert before tiling - """ - while len(noise) < len(clean): - if noise.ndim > 1: - zeros = np.zeros((int(fs * silence_length), noise.shape[-1])) - else: - zeros = np.zeros((int(fs * silence_length),)) - noiseconcat = np.append(noise, zeros, axis=0) - noise = np.append(noiseconcat, noise, axis=0) - - return noise - - def perturb_with_input_noise(self, data, noise, data_rms=None, ref_mic=0, norm_to_db=-25.0): - """ - Args: - data (AudioSegment): audio data - noise (AudioSegment): noise data - data_rms (Union[float, List[float]): rms_db for data input - ref_mic (int): reference mic index for scaling multi-channel audio, if set to None then - each channel will be scaled independently - norm_to_db (float): will normalise all audio to this DB - """ - if data.num_channels != noise.num_channels: - raise ValueError( - f"Found mismatched channels for data ({data.num_channels}) and noise ({noise.num_channels})." - ) - - if not (0 <= ref_mic < data.num_channels): - raise ValueError( - f" reference mic ID must be an integer in [0, {data.num_channels}), got {ref_mic} instead." - ) - - if self._snr_samples: - snr_db = random.sample(self._snr_samples, 1)[0] - else: - snr_db = random.uniform(self._min_snr_db, self._max_snr_db) - if data_rms is None: - data_rms = data.rms_db[ref_mic] if isinstance(data.rms_db, (list, np.ndarray)) else data.rms_db - - if norm_to_db is None: - norm_to_db = data_rms - - data_norm = data._samples - noise_norm = noise._samples - - if len(data_norm) == 0: - return - - if len(noise_norm) < len(data_norm): - noise_norm = self.concatenate_noise_sample(data_norm, noise_norm, data.sample_rate) - noise_norm = noise_norm[0 : len(data_norm)] - - _, _, noisy_snr = self.snr_mixer(clean=data_norm, noise=noise_norm, snr=snr_db, norm_to_db=norm_to_db) - - data._samples = noisy_snr - - -class WhiteNoisePerturbation(Perturbation): - """ - Perturbation that adds white noise to an audio file in the training dataset. - - Args: - min_level (int): Minimum level in dB at which white noise should be added - max_level (int): Maximum level in dB at which white noise should be added - rng (int): Random seed. Default is None - """ - - def __init__(self, min_level=-90, max_level=-46, rng=None): - self.min_level = int(min_level) - self.max_level = int(max_level) - np.random.seed(rng) if rng else None - - def perturb(self, data): - noise_level_db = np.random.randint(self.min_level, self.max_level, dtype='int32') - noise_signal = np.random.randn(data._samples.shape[0]) * (10.0 ** (noise_level_db / 20.0)) - data._samples += noise_signal - - -class RirAndNoisePerturbation(Perturbation): - """ - RIR augmentation with additive foreground and background noise. - In this implementation audio data is augmented by first convolving the audio with a Room Impulse Response - and then adding foreground noise and background noise at various SNRs. RIR, foreground and background noises - should either be supplied with a manifest file or as tarred audio files (faster). - - Different sets of noise audio files based on the original sampling rate of the noise. This is useful while - training a mixed sample rate model. For example, when training a mixed model with 8 kHz and 16 kHz audio with a - target sampling rate of 16 kHz, one would want to augment 8 kHz data with 8 kHz noise rather than 16 kHz noise. - - Args: - rir_manifest_path: Manifest file for RIRs - rir_tar_filepaths: Tar files, if RIR audio files are tarred - rir_prob: Probability of applying a RIR - noise_manifest_paths: Foreground noise manifest path - min_snr_db: Min SNR for foreground noise - max_snr_db: Max SNR for background noise, - noise_tar_filepaths: Tar files, if noise files are tarred - apply_noise_rir: Whether to convolve foreground noise with a a random RIR - orig_sample_rate: Original sampling rate of foreground noise audio - max_additions: Max number of times foreground noise is added to an utterance, - max_duration: Max duration of foreground noise - bg_noise_manifest_paths: Background noise manifest path - bg_min_snr_db: Min SNR for background noise - bg_max_snr_db: Max SNR for background noise - bg_noise_tar_filepaths: Tar files, if noise files are tarred - bg_orig_sample_rate: Original sampling rate of background noise audio - rng: Random seed. Default is None - - """ - - def __init__( - self, - rir_manifest_path=None, - rir_prob=0.5, - noise_manifest_paths=None, - noise_prob=1.0, - min_snr_db=0, - max_snr_db=50, - rir_tar_filepaths=None, - rir_shuffle_n=100, - noise_tar_filepaths=None, - apply_noise_rir=False, - orig_sample_rate=None, - max_additions=5, - max_duration=2.0, - bg_noise_manifest_paths=None, - bg_noise_prob=1.0, - bg_min_snr_db=10, - bg_max_snr_db=50, - bg_noise_tar_filepaths=None, - bg_orig_sample_rate=None, - rng=None, - ): - - self._rir_prob = rir_prob - self._noise_prob = noise_prob - self._bg_noise_prob = bg_noise_prob - random.seed(rng) if rng else None - self._rir_perturber = ImpulsePerturbation( - manifest_path=rir_manifest_path, - audio_tar_filepaths=rir_tar_filepaths, - shuffle_n=rir_shuffle_n, - shift_impulse=True, - ) - self._fg_noise_perturbers = None - self._bg_noise_perturbers = None - if noise_manifest_paths: - self._fg_noise_perturbers = {} - for i in range(len(noise_manifest_paths)): - if orig_sample_rate is None: - orig_sr = 16000 - else: - orig_sr = orig_sample_rate[i] - self._fg_noise_perturbers[orig_sr] = NoisePerturbation( - manifest_path=noise_manifest_paths[i], - min_snr_db=min_snr_db[i], - max_snr_db=max_snr_db[i], - audio_tar_filepaths=noise_tar_filepaths[i], - orig_sr=orig_sr, - ) - self._max_additions = max_additions - self._max_duration = max_duration - if bg_noise_manifest_paths: - self._bg_noise_perturbers = {} - for i in range(len(bg_noise_manifest_paths)): - if bg_orig_sample_rate is None: - orig_sr = 16000 - else: - orig_sr = bg_orig_sample_rate[i] - self._bg_noise_perturbers[orig_sr] = NoisePerturbation( - manifest_path=bg_noise_manifest_paths[i], - min_snr_db=bg_min_snr_db[i], - max_snr_db=bg_max_snr_db[i], - audio_tar_filepaths=bg_noise_tar_filepaths[i], - orig_sr=orig_sr, - ) - - self._apply_noise_rir = apply_noise_rir - - def perturb(self, data): - prob = random.uniform(0.0, 1.0) - - if prob < self._rir_prob: - self._rir_perturber.perturb(data) - - data_rms = data.rms_db - - if self._fg_noise_perturbers is not None and random.uniform(0.0, 1.0) < self._noise_prob: - orig_sr = data.orig_sr - if orig_sr not in self._fg_noise_perturbers: - orig_sr = max(self._fg_noise_perturbers.keys()) - fg_perturber = self._fg_noise_perturbers[orig_sr] - noise = fg_perturber.get_one_noise_sample(data.sample_rate) - if self._apply_noise_rir: - self._rir_perturber.perturb(noise) - fg_perturber.perturb_with_foreground_noise( - data, noise, data_rms=data_rms, max_noise_dur=self._max_duration, max_additions=self._max_additions - ) - - if self._bg_noise_perturbers is not None and random.uniform(0.0, 1.0) < self._bg_noise_prob: - orig_sr = data.orig_sr - if orig_sr not in self._bg_noise_perturbers: - orig_sr = max(self._bg_noise_perturbers.keys()) - bg_perturber = self._bg_noise_perturbers[orig_sr] - - noise = bg_perturber.get_one_noise_sample(data.sample_rate) - bg_perturber.perturb_with_input_noise(data, noise, data_rms=data_rms) - - -class TranscodePerturbation(Perturbation): - """ - Audio codec augmentation. This implementation uses sox to transcode audio with low rate audio codecs, - so users need to make sure that the installed sox version supports the codecs used here (G711 and amr-nb). - - Args: - codecs (List[str]):A list of codecs to be trancoded to. Default is None. - rng (int): Random seed. Default is None. - """ - - def __init__(self, codecs=None, rng=None): - random.seed(rng) if rng else None - self._codecs = codecs if codecs is not None else ["g711", "amr-nb", "ogg"] - self.att_factor = 0.8 # to avoid saturation while writing to wav - if codecs is not None: - for codec in codecs: - if codec not in ["g711", "amr-nb", "ogg"]: - raise ValueError( - f"TranscodePerturbation with {codec} isnot supported. Only {codecs} are supported" - ) - - def perturb(self, data): - max_level = np.max(np.abs(data._samples)) - if max_level > 0.8: - norm_factor = self.att_factor / max_level - norm_samples = norm_factor * data._samples - else: - norm_samples = data._samples - orig_f = NamedTemporaryFile(suffix=".wav") - sf.write(orig_f.name, norm_samples.transpose(), 16000) - - codec_ind = random.randint(0, len(self._codecs) - 1) - if self._codecs[codec_ind] == "amr-nb": - transcoded_f = NamedTemporaryFile(suffix="_amr.wav") - rates = list(range(0, 4)) - rate = rates[random.randint(0, len(rates) - 1)] - _ = subprocess.check_output( - f"sox {orig_f.name} -V0 -C {rate} -t amr-nb - | sox -t amr-nb - -V0 -b 16 -r 16000 {transcoded_f.name}", - shell=True, - ) - elif self._codecs[codec_ind] == "ogg": - transcoded_f = NamedTemporaryFile(suffix="_ogg.wav") - rates = list(range(-1, 8)) - rate = rates[random.randint(0, len(rates) - 1)] - _ = subprocess.check_output( - f"sox {orig_f.name} -V0 -C {rate} -t ogg - | sox -t ogg - -V0 -b 16 -r 16000 {transcoded_f.name}", - shell=True, - ) - elif self._codecs[codec_ind] == "g711": - transcoded_f = NamedTemporaryFile(suffix="_g711.wav") - _ = subprocess.check_output( - f"sox {orig_f.name} -V0 -r 8000 -c 1 -e a-law {transcoded_f.name} lowpass 3400 highpass 300", - shell=True, - ) - - new_data = AudioSegment.from_file(transcoded_f.name, target_sr=16000) - data._samples = new_data._samples[0 : data._samples.shape[0]] - return - - -class RandomSegmentPerturbation(Perturbation): - """ - Returns a random segment from input of duration "duration_sec". - If duration_sec > input audio length, pad_to_duration determines the outcome. - - RandomSegmentPerturbation is intended for self-supervised learning. - Not for supervised, as extracting corresponding text is not facilitated. - - - Args: - duration_sec (float): duration of the segment to be extracted - pad_to_duration (bool): zero pad if length of input audio < duration_sec - rng: Random seed. Default is None - min_rms_db: Minimum RMS db value for the perturbed audio. Default is None - max_trials: Maximum number of trials to find a segment with RMS db > min_rms_db. Default is 10 - verbose: If True, logs a warning if RMS db < min_rms_db after max_trials. Default is False - """ - - def __init__( - self, duration_sec=32.0, pad_to_duration=False, rng=None, min_rms_db=None, max_trials=10, verbose=False - ): - if duration_sec <= 0: - raise ValueError("duration_sec should be > 0") - - self._duration_sec = duration_sec - self._pad_to_duration = pad_to_duration - self._min_rms_db = min_rms_db - self._max_trials = max_trials - self._verbose = verbose - random.seed(rng) if rng else None - - def perturb(self, data: AudioSegment): - if self._duration_sec > data.duration: - if not self._pad_to_duration: - # don't do anything if pad_to_duration is False - return - start_time = 0.0 - pad_size = self._duration_sec * data.sample_rate - data.num_samples - data.pad(pad_size=pad_size) - else: - start_time = random.uniform(0.0, data.duration - self._duration_sec) - - end_time = start_time + self._duration_sec - new_data = copy.deepcopy(data) - new_data.subsegment(start_time=start_time, end_time=end_time) - if self._min_rms_db is not None: - rms_db = new_data.rms_db if new_data.num_channels == 1 else min(new_data.rms_db) - trial = 0 - while rms_db < self._min_rms_db and trial < self._max_trials: - start_time = random.uniform(0.0, data.duration - self._duration_sec) - end_time = start_time + self._duration_sec - new_data = copy.deepcopy(data) - new_data.subsegment(start_time=start_time, end_time=end_time) - rms_db = new_data.rms_db if new_data.num_channels == 1 else min(new_data.rms_db) - trial += 1 - if self._verbose and trial == self._max_trials and rms_db < self._min_rms_db: - logging.warning( - f"Could not find a segment with RMS db > {self._min_rms_db} after {self._max_trials} trials." - ) - data.subsegment(start_time=start_time, end_time=end_time) - - -perturbation_types = { - "speed": SpeedPerturbation, - "time_stretch": TimeStretchPerturbation, - "gain": GainPerturbation, - "silence": SilencePerturbation, - "impulse": ImpulsePerturbation, - "shift": ShiftPerturbation, - "noise": NoisePerturbation, - "noise_norm": NoisePerturbationWithNormalization, - "white_noise": WhiteNoisePerturbation, - "rir_noise_aug": RirAndNoisePerturbation, - "transcode_aug": TranscodePerturbation, - "random_segment": RandomSegmentPerturbation, -} - - -def register_perturbation(name: str, perturbation: Perturbation): - if name in perturbation_types.keys(): - raise KeyError( - f"Perturbation with the name {name} exists. " f"Type of perturbation : {perturbation_types[name]}." - ) - - perturbation_types[name] = perturbation - - -class AudioAugmentor(object): - def __init__(self, perturbations=None, rng=None): - random.seed(rng) if rng else None - self._pipeline = perturbations if perturbations is not None else [] - - def perturb(self, segment): - for prob, p in self._pipeline: - if random.random() < prob: - p.perturb(segment) - return - - def max_augmentation_length(self, length): - newlen = length - for prob, p in self._pipeline: - newlen = p.max_augmentation_length(newlen) - return newlen - - @classmethod - def from_config(cls, config): - ptbs = [] - for p in config: - if p['aug_type'] not in perturbation_types: - logging.warning("%s perturbation not known. Skipping.", p['aug_type']) - continue - perturbation = perturbation_types[p['aug_type']] - ptbs.append((p['prob'], perturbation(**p['cfg']))) - return cls(perturbations=ptbs) - - -def process_augmentations(augmenter, global_rank=0, world_size=1) -> Optional[AudioAugmentor]: - """Process list of online data augmentations. - Accepts either an AudioAugmentor object with pre-defined augmentations, - or a dictionary that points to augmentations that have been defined. - If a dictionary is passed, must follow the below structure: - Dict[str, Dict[str, Any]]: Which refers to a dictionary of string - names for augmentations, defined in `asr/parts/perturb.py`. - The inner dictionary may contain key-value arguments of the specific - augmentation, along with an essential key `prob`. `prob` declares the - probability of the augmentation being applied, and must be a float - value in the range [0, 1]. - # Example in YAML config file - Augmentations are generally applied only during training, so we can add - these augmentations to our yaml config file, and modify the behaviour - for training and evaluation. - ```yaml - AudioToSpeechLabelDataLayer: - ... # Parameters shared between train and evaluation time - train: - augmentor: - shift: - prob: 0.5 - min_shift_ms: -5.0 - max_shift_ms: 5.0 - white_noise: - prob: 1.0 - min_level: -90 - max_level: -46 - ... - eval: - ... - ``` - Then in the training script, - ```python - import copy - from ruamel.yaml import YAML - yaml = YAML(typ="safe") - with open(model_config) as f: - params = yaml.load(f) - # Train Config for Data Loader - train_dl_params = copy.deepcopy(params["AudioToTextDataLayer"]) - train_dl_params.update(params["AudioToTextDataLayer"]["train"]) - del train_dl_params["train"] - del train_dl_params["eval"] - data_layer_train = nemo_asr.AudioToTextDataLayer( - ..., - **train_dl_params, - ) - # Evaluation Config for Data Loader - eval_dl_params = copy.deepcopy(params["AudioToTextDataLayer"]) - eval_dl_params.update(params["AudioToTextDataLayer"]["eval"]) - del eval_dl_params["train"] - del eval_dl_params["eval"] - data_layer_eval = nemo_asr.AudioToTextDataLayer( - ..., - **eval_dl_params, - ) - ``` - # Registering your own Augmentations - To register custom augmentations to obtain the above convenience of - the declaring the augmentations in YAML, you can put additional keys in - `perturbation_types` dictionary as follows. - ```python - from nemo.collections.asr.parts import perturb - # Define your own perturbation here - class CustomPerturbation(perturb.Perturbation): - ... - perturb.register_perturbation(name_of_perturbation, CustomPerturbation) - ``` - Args: - augmenter: AudioAugmentor object or - dictionary of str -> kwargs (dict) which is parsed and used - to initialize an AudioAugmentor. - Note: It is crucial that each individual augmentation has - a keyword `prob`, that defines a float probability in the - the range [0, 1] of this augmentation being applied. - If this keyword is not present, then the augmentation is - disabled and a warning is logged. - Returns: AudioAugmentor object - """ - if augmenter is None: - return None - - if isinstance(augmenter, AudioAugmentor): - return augmenter - - augmenter_types = {dict} - if HAVE_OMEGACONG_WEBDATASET: - augmenter_types = {dict, DictConfig} - if not type(augmenter) in augmenter_types: - raise ValueError("Cannot parse augmenter. Must be a dict or an AudioAugmentor object ") - - if HAVE_OMEGACONG_WEBDATASET and isinstance(augmenter, DictConfig): - augmenter = OmegaConf.to_container(augmenter, resolve=True) - - augmenter = copy.deepcopy(augmenter) - - augmentations = [] - for augment_name, augment_kwargs in augmenter.items(): - prob = augment_kwargs.get('prob', None) - - if prob is None: - raise KeyError( - f'Augmentation "{augment_name}" will not be applied as ' - f'keyword argument "prob" was not defined for this augmentation.' - ) - - else: - _ = augment_kwargs.pop('prob') - - if prob < 0.0 or prob > 1.0: - raise ValueError("`prob` must be a float value between 0 and 1.") - - try: - augmentation_class = perturbation_types[augment_name] - if 'global_rank' in inspect.signature(augmentation_class).parameters: - augment_kwargs['global_rank'] = global_rank - if 'world_size' in inspect.signature(augmentation_class).parameters: - augment_kwargs['world_size'] = world_size - augmentation = augmentation_class(**augment_kwargs) - augmentations.append([prob, augmentation]) - except KeyError: - raise KeyError(f"Invalid perturbation name. Allowed values : {perturbation_types.keys()}") - - augmenter = AudioAugmentor(perturbations=augmentations) - return augmenter - - -class AugmentationDataset(IterableDataset): - """ - A class that loads tarred audio files and cycles over the files in the dataset. - Accepts a single comma-separated JSON manifest file (in the same style as for the AudioToCharDataset/AudioToBPEDataset), - as well as the path(s) to the tarball(s) containing the wav files. Each line of the manifest should - contain the information for one audio file, including at least the transcript and name of the audio - file within the tarball. - Valid formats for the audio_tar_filepaths argument include: - (1) a single string that can be brace-expanded, e.g. 'path/to/audio.tar' or 'path/to/audio_{1..100}.tar.gz', or - (2) a list of file paths that will not be brace-expanded, e.g. ['audio_1.tar', 'audio_2.tar', ...]. - Note: For brace expansion in (1), there may be cases where `{x..y}` syntax cannot be used due to shell interference. - This occurs most commonly inside SLURM scripts. Therefore we provide a few equivalent replacements. - Supported opening braces - { <=> (, [, < and the special tag _OP_. - Supported closing braces - } <=> ), ], > and the special tag _CL_. - For SLURM based tasks, we suggest the use of the special tags for ease of use. - See the WebDataset documentation for more information about accepted data and input formats. - """ - - def __init__( - self, - manifest_path: str, - tar_filepaths: Union[str, List[str]], - shuffle_n: int = 128, - rank: int = 0, - world_size: int = 1, - shard_strategy: str = "replicate", - ): - # import here to avoid circular import error - from nemo.collections.asr.data.audio_to_text import expand_sharded_filepaths - - self._manifest = collections.ASRAudioText(manifest_path, parser=parsers.make_parser([]), index_by_file_id=True) - - tar_filepaths = expand_sharded_filepaths( - tar_filepaths, shard_strategy=shard_strategy, world_size=world_size, global_rank=rank - ) - - if not HAVE_OMEGACONG_WEBDATASET: - raise LightningNotInstalledException(self) - self.audio_dataset = wds.DataPipeline( - wds.SimpleShardList(urls=tar_filepaths), - wds.shuffle(shuffle_n), - wds.tarfile_to_samples(), - wds.rename(audio='wav;ogg;flac', key='__key__'), - wds.to_tuple('audio', 'key'), - self._loop_offsets, - ) - - def __len__(self): - return len(self._manifest) - - def _loop_offsets(self, iterator): - """This function is used to iterate through utterances with different offsets for each file.""" - - class TarredAudioLoopOffsets: - def __init__(self, collection): - self.iterator = iterator - self.collection = collection - self.current_fn = None - self.current_bytes = None - self.offset_id = 0 - - def __iter__(self): - return self - - def __next__(self): - if self.current_fn is None: - self.current_bytes, self.current_fn = next(self.iterator) - self.offset_id = 0 - else: - offset_list = self.collection.mapping[self.current_fn] - if len(offset_list) == self.offset_id + 1: - self.current_bytes, self.current_fn = next(self.iterator) - self.offset_id = 0 - else: - self.offset_id += 1 - - return self.current_bytes, self.current_fn, self.offset_id - - return TarredAudioLoopOffsets(self._manifest) - - def __iter__(self): - audio_iter = iter(self.audio_dataset) - - while True: - try: - audio_bytes, audio_filename, offset_id = next(audio_iter) - file_id, _ = os.path.splitext(os.path.basename(audio_filename)) - manifest_idx = self._manifest.mapping[file_id][offset_id] - manifest_entry = self._manifest[manifest_idx] - - # Convert audio bytes to IO stream for processing (for SoundFile to read) - audio_file = io.BytesIO(audio_bytes) - yield audio_file, file_id, manifest_entry - except StopIteration: - audio_iter = iter(self.audio_dataset) diff --git a/nemo/collections/asr/parts/preprocessing/segment.py b/nemo/collections/asr/parts/preprocessing/segment.py deleted file mode 100644 index 00558769b0204eea08e0fde3027edfec5d096042..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/preprocessing/segment.py +++ /dev/null @@ -1,681 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Copyright (c) 2018 Ryan Leary -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in all -# copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. -# This file contains code artifacts adapted from https://github.com/ryanleary/patter - -import math -import os -import random -from typing import Iterable, List, Optional, Union - -import librosa -import numpy as np -import numpy.typing as npt -import soundfile as sf - -from nemo.utils import logging - -# TODO @blisc: Perhaps refactor instead of import guarding -HAVE_PYDUB = True -try: - from pydub import AudioSegment as Audio - from pydub.exceptions import CouldntDecodeError - - # FFMPEG for some formats needs explicitly defined coding-decoding strategy - ffmpeg_codecs = {'opus': 'opus'} - -except ModuleNotFoundError: - HAVE_PYDUB = False - - -available_formats = sf.available_formats() -sf_supported_formats = ["." + i.lower() for i in available_formats.keys()] - - -ChannelSelectorType = Union[int, Iterable[int], str] - - -def select_channels(signal: npt.NDArray, channel_selector: Optional[ChannelSelectorType] = None) -> npt.NDArray: - """ - Convert a multi-channel signal to a single-channel signal by averaging over channels or - selecting a single channel, or pass-through multi-channel signal when channel_selector is `None`. - - Args: - signal: numpy array with shape (..., num_channels) - channel selector: string denoting the downmix mode, an integer denoting the channel to be selected, - or an iterable of integers denoting a subset of channels. Channel selector is - using zero-based indexing. If set to `None`, the original signal will be returned. - Uses zero-based indexing. - - Returns: - numpy array - """ - if signal.ndim == 1: - # For one-dimensional input, return the input signal. - if channel_selector not in [None, 0, 'average']: - raise ValueError( - 'Input signal is one-dimensional, channel selector (%s) cannot not be used.', str(channel_selector) - ) - return signal - - num_channels = signal.shape[-1] - num_samples = signal.size // num_channels # handle multi-dimensional signals - - if num_channels >= num_samples: - logging.warning( - 'Number of channels (%d) is greater or equal than number of samples (%d). ' - 'Check for possible transposition.', - num_channels, - num_samples, - ) - - # Samples are arranged as (num_channels, ...) - if channel_selector is None: - # keep the original multi-channel signal - pass - elif channel_selector == 'average': - # default behavior: downmix by averaging across channels - signal = np.mean(signal, axis=-1) - elif isinstance(channel_selector, int): - # select a single channel - if channel_selector >= num_channels: - raise ValueError(f'Cannot select channel {channel_selector} from a signal with {num_channels} channels.') - signal = signal[..., channel_selector] - elif isinstance(channel_selector, Iterable): - # select multiple channels - if max(channel_selector) >= num_channels: - raise ValueError( - f'Cannot select channel subset {channel_selector} from a signal with {num_channels} channels.' - ) - signal = signal[..., channel_selector] - # squeeze the channel dimension if a single-channel is selected - # this is done to have the same shape as when using integer indexing - if len(channel_selector) == 1: - signal = np.squeeze(signal, axis=-1) - else: - raise ValueError(f'Unexpected value for channel_selector ({channel_selector})') - - return signal - - -def get_samples(audio_file: str, target_sr: int = 16000, dtype: str = 'float32'): - """ - Read the samples from the given audio_file path. If not specified, the input audio file is automatically - resampled to 16kHz. - - Args: - audio_file (str): - Path to the input audio file - target_sr (int): - Targeted sampling rate - Returns: - samples (numpy.ndarray): - Time-series sample data from the given audio file - """ - with sf.SoundFile(audio_file, 'r') as f: - samples = f.read(dtype=dtype) - if f.samplerate != target_sr: - samples = librosa.core.resample(samples, orig_sr=f.samplerate, target_sr=target_sr) - samples = samples.transpose() - return samples - - -class AudioSegment(object): - """Audio segment abstraction. - :param samples: Audio samples [num_samples x num_channels]. - :type samples: ndarray.float32 - :param sample_rate: Audio sample rate. - :type sample_rate: int - :raises TypeError: If the sample data type is not float or int. - """ - - def __init__( - self, - samples, - sample_rate, - target_sr=None, - trim=False, - trim_ref=np.max, - trim_top_db=60, - trim_frame_length=2048, - trim_hop_length=512, - orig_sr=None, - channel_selector=None, - normalize_db: Optional[float] = None, - ref_channel: Optional[int] = None, - audio_file: Optional[Union[str, List[str]]] = None, - offset: Optional[float] = None, - duration: Optional[float] = None, - ): - """Create audio segment from samples. - Samples are convert float32 internally, with int scaled to [-1, 1]. - """ - samples = self._convert_samples_to_float32(samples) - - # Check if channel selector is necessary - if samples.ndim == 1 and channel_selector not in [None, 0, 'average']: - raise ValueError( - 'Input signal is one-dimensional, channel selector (%s) cannot not be used.', str(channel_selector) - ) - elif samples.ndim == 2: - samples = select_channels(samples, channel_selector) - elif samples.ndim >= 3: - raise NotImplementedError( - 'Signals with more than two dimensions (sample, channel) are currently not supported.' - ) - - if target_sr is not None and target_sr != sample_rate: - # resample along the temporal dimension (axis=0) will be in librosa 0.10.0 (#1561) - samples = samples.transpose() - samples = librosa.core.resample(samples, orig_sr=sample_rate, target_sr=target_sr) - samples = samples.transpose() - sample_rate = target_sr - if trim: - # librosa is using channels-first layout (num_channels, num_samples), - # which is transpose of AudioSegment's layout - samples = samples.transpose() - samples, _ = librosa.effects.trim( - samples, top_db=trim_top_db, ref=trim_ref, frame_length=trim_frame_length, hop_length=trim_hop_length - ) - samples = samples.transpose() - self._samples = samples - self._sample_rate = sample_rate - self._orig_sr = orig_sr if orig_sr is not None else sample_rate - self._ref_channel = ref_channel - self._normalize_db = normalize_db - self._audio_file = audio_file - self._offset = offset - self._duration = duration - if normalize_db is not None: - self.normalize_db(normalize_db, ref_channel) - - def __eq__(self, other): - """Return whether two objects are equal.""" - if type(other) is not type(self): - return False - if self._sample_rate != other._sample_rate: - return False - if self._samples.shape != other._samples.shape: - return False - if np.any(self.samples != other._samples): - return False - return True - - def __ne__(self, other): - """Return whether two objects are unequal.""" - return not self.__eq__(other) - - def __str__(self): - """Return human-readable representation of segment.""" - if self.num_channels == 1: - return "%s: num_samples=%d, sample_rate=%d, duration=%.2fsec, rms=%.2fdB" % ( - type(self), - self.num_samples, - self.sample_rate, - self.duration, - self.rms_db, - ) - else: - rms_db_str = ', '.join([f'{rms:.2f}dB' for rms in self.rms_db]) - return "%s: num_samples=%d, sample_rate=%d, duration=%.2fsec, num_channels=%d, rms=[%s]" % ( - type(self), - self.num_samples, - self.sample_rate, - self.duration, - self.num_channels, - rms_db_str, - ) - - @staticmethod - def _convert_samples_to_float32(samples): - """Convert sample type to float32. - Audio sample type is usually integer or float-point. - Integers will be scaled to [-1, 1] in float32. - """ - float32_samples = samples.astype('float32') - if samples.dtype in (np.int8, np.int16, np.int32, np.int64): - bits = np.iinfo(samples.dtype).bits - float32_samples *= 1.0 / 2 ** (bits - 1) - elif samples.dtype in (np.float16, np.float32, np.float64): - pass - else: - raise TypeError("Unsupported sample type: %s." % samples.dtype) - return float32_samples - - @classmethod - def from_file( - cls, - audio_file, - target_sr=None, - int_values=False, - offset=0, - duration=0, - trim=False, - trim_ref=np.max, - trim_top_db=60, - trim_frame_length=2048, - trim_hop_length=512, - orig_sr=None, - channel_selector=None, - normalize_db=None, - ref_channel=None, - ): - """ - Load a file supported by librosa and return as an AudioSegment. - :param audio_file: path of file to load. - Alternatively, a list of paths of single-channel files can be provided - to form a multichannel signal. - :param target_sr: the desired sample rate - :param int_values: if true, load samples as 32-bit integers - :param offset: offset in seconds when loading audio - :param duration: duration in seconds when loading audio - :param trim: if true, trim leading and trailing silence from an audio signal - :param trim_ref: the reference amplitude. By default, it uses `np.max` and compares to the peak amplitude in - the signal - :param trim_top_db: the threshold (in decibels) below reference to consider as silence - :param trim_frame_length: the number of samples per analysis frame - :param trim_hop_length: the number of samples between analysis frames - :param orig_sr: the original sample rate - :param channel selector: string denoting the downmix mode, an integer denoting the channel to be selected, - or an iterable of integers denoting a subset of channels. Channel selector is using - zero-based indexing. If set to `None`, the original signal will be used. - :param normalize_db (Optional[float]): if not None, normalize the audio signal to a target RMS value - :param ref_channel (Optional[int]): channel to use as reference for normalizing multi-channel audio, - set None to use max RMS across channels - :return: AudioSegment instance - """ - samples = None - if isinstance(audio_file, list): - return cls.from_file_list( - audio_file_list=audio_file, - target_sr=target_sr, - int_values=int_values, - offset=offset, - duration=duration, - trim=trim, - trim_ref=trim_ref, - trim_top_db=trim_top_db, - trim_frame_length=trim_frame_length, - trim_hop_length=trim_hop_length, - orig_sr=orig_sr, - channel_selector=channel_selector, - normalize_db=normalize_db, - ref_channel=ref_channel, - ) - - if not isinstance(audio_file, str) or os.path.splitext(audio_file)[-1] in sf_supported_formats: - try: - with sf.SoundFile(audio_file, 'r') as f: - dtype = 'int32' if int_values else 'float32' - sample_rate = f.samplerate - if offset is not None and offset > 0: - f.seek(int(offset * sample_rate)) - if duration is not None and duration > 0: - samples = f.read(int(duration * sample_rate), dtype=dtype) - else: - samples = f.read(dtype=dtype) - except RuntimeError as e: - logging.error( - f"Loading {audio_file} via SoundFile raised RuntimeError: `{e}`. " - f"NeMo will fallback to loading via pydub." - ) - - if hasattr(audio_file, "seek"): - audio_file.seek(0) - - if HAVE_PYDUB and samples is None: - try: - samples = Audio.from_file(audio_file, codec=ffmpeg_codecs.get(os.path.splitext(audio_file)[-1])) - sample_rate = samples.frame_rate - num_channels = samples.channels - if offset is not None and offset > 0: - # pydub does things in milliseconds - seconds = offset * 1000 - samples = samples[int(seconds) :] - if duration is not None and duration > 0: - seconds = duration * 1000 - samples = samples[: int(seconds)] - samples = np.array(samples.get_array_of_samples()) - # For multi-channel signals, channels are stacked in a one-dimensional vector - if num_channels > 1: - samples = np.reshape(samples, (-1, num_channels)) - except CouldntDecodeError as err: - logging.error(f"Loading {audio_file} via pydub raised CouldntDecodeError: `{err}`.") - - if samples is None: - libs = "soundfile, and pydub" if HAVE_PYDUB else "soundfile" - raise Exception(f"Your audio file {audio_file} could not be decoded. We tried using {libs}.") - - return cls( - samples, - sample_rate, - target_sr=target_sr, - trim=trim, - trim_ref=trim_ref, - trim_top_db=trim_top_db, - trim_frame_length=trim_frame_length, - trim_hop_length=trim_hop_length, - orig_sr=orig_sr, - channel_selector=channel_selector, - normalize_db=normalize_db, - ref_channel=ref_channel, - audio_file=audio_file, - offset=offset, - duration=duration, - ) - - @classmethod - def from_file_list( - cls, - audio_file_list, - target_sr=None, - int_values=False, - offset=0, - duration=0, - trim=False, - channel_selector=None, - *args, - **kwargs, - ): - """ - Function wrapper for `from_file` method. Load a list of files from `audio_file_list`. - The length of each audio file is unified with the duration item in the input manifest file. - See `from_file` method for arguments. - - If a list of files is provided, load samples from individual single-channel files and - concatenate them along the channel dimension. - """ - if isinstance(channel_selector, int): - # Shortcut when selecting a single channel - if channel_selector >= len(audio_file_list): - raise RuntimeError( - f'Channel cannot be selected: channel_selector={channel_selector}, ' - f'num_audio_files={len(audio_file_list)}' - ) - # Select only a single file - audio_file_list = [audio_file_list[channel_selector]] - # Reset the channel selector since we applied it here - channel_selector = None - - samples = None - - for a_file in audio_file_list: - # Load audio from the current file - a_segment = cls.from_file( - audio_file=a_file, - target_sr=target_sr, - int_values=int_values, - offset=offset, - duration=duration, - channel_selector=None, - trim=False, # Do not apply trim to individual files, it will be applied to the concatenated signal - *args, - **kwargs, - ) - - # Only single-channel individual files are supported for now - if a_segment.num_channels != 1: - raise RuntimeError( - f'Expecting a single-channel audio signal, but loaded {a_segment.num_channels} ' - f'channels from file {a_file}' - ) - - if target_sr is None: - # All files need to be loaded with the same sample rate - target_sr = a_segment.sample_rate - - # Concatenate samples - a_samples = a_segment.samples[:, None] - - if samples is None: - samples = a_samples - else: - # Check the dimensions match - if len(a_samples) != len(samples): - raise RuntimeError( - f'Loaded samples need to have identical length: {a_samples.shape} != {samples.shape}' - ) - - # Concatenate along channel dimension - samples = np.concatenate([samples, a_samples], axis=1) - - # Final setup for class initialization - samples = np.squeeze(samples) - sample_rate = target_sr - - return cls( - samples, - sample_rate, - target_sr=target_sr, - trim=trim, - channel_selector=channel_selector, - audio_file=audio_file_list, - *args, - **kwargs, - ) - - @classmethod - def segment_from_file( - cls, - audio_file, - target_sr=None, - n_segments=0, - trim=False, - orig_sr=None, - channel_selector=None, - offset=None, - dtype='float32', - ): - """Grabs n_segments number of samples from audio_file. - If offset is not provided, n_segments are selected randomly. - If offset is provided, it is used to calculate the starting sample. - - Note that audio_file can be either the file path, or a file-like object. - - :param audio_file: path to a file or a file-like object - :param target_sr: sample rate for the output samples - :param n_segments: desired number of samples - :param trim: if true, trim leading and trailing silence from an audio signal - :param orig_sr: the original sample rate - :param channel selector: select a subset of channels. If set to `None`, the original signal will be used. - :param offset: fixed offset in seconds - :param dtype: data type to load audio as. - :return: numpy array of samples - """ - is_segmented = False - try: - with sf.SoundFile(audio_file, 'r') as f: - sample_rate = f.samplerate - if target_sr is not None: - n_segments_at_original_sr = math.ceil(n_segments * sample_rate / target_sr) - else: - n_segments_at_original_sr = n_segments - - if 0 < n_segments_at_original_sr < len(f): - max_audio_start = len(f) - n_segments_at_original_sr - if offset is None: - audio_start = random.randint(0, max_audio_start) - else: - audio_start = math.floor(offset * sample_rate) - if audio_start > max_audio_start: - raise RuntimeError( - f'Provided audio start ({audio_start}) is larger than the ' - f'maximum possible ({max_audio_start})' - ) - f.seek(audio_start) - samples = f.read(n_segments_at_original_sr, dtype=dtype) - is_segmented = True - elif n_segments_at_original_sr > len(f): - logging.warning( - f"Number of segments ({n_segments_at_original_sr}) is greater than the length ({len(f)}) " - f"of the audio file {audio_file}. This may lead to shape mismatch errors." - ) - samples = f.read(dtype=dtype) - else: - samples = f.read(dtype=dtype) - except RuntimeError as e: - logging.error(f"Loading {audio_file} via SoundFile raised RuntimeError: `{e}`.") - raise e - - features = cls( - samples, sample_rate, target_sr=target_sr, trim=trim, orig_sr=orig_sr, channel_selector=channel_selector - ) - - if is_segmented: - features._samples = features._samples[:n_segments] - - return features - - @property - def samples(self): - """Returns a copy of the samples.""" - return self._samples.copy() - - @property - def sample_rate(self): - """Returns the sample rate of the segment.""" - return self._sample_rate - - @property - def num_channels(self): - """Returns the number of channels in the segment.""" - if self._samples.ndim == 1: - return 1 - else: - return self._samples.shape[-1] - - @property - def num_samples(self): - """Returns the number of samples in the segment.""" - return self._samples.shape[0] - - @property - def duration(self): - """Returns the duration of the segment in seconds.""" - return self.num_samples / float(self._sample_rate) - - @property - def rms_db(self): - """Return per-channel RMS value.""" - mean_square = np.mean(self._samples**2, axis=0) - return 10 * np.log10(mean_square) - - @property - def orig_sr(self): - """Returns the original sample rate of the segment.""" - return self._orig_sr - - @property - def offset(self): - """Returns the offset used for the segment.""" - return float(self._offset) if self._offset is not None else None - - @property - def audio_file(self): - """Returns the audio file that the segment was loaded from.""" - return str(self._audio_file) if self._audio_file is not None else None - - def is_empty(self): - """Checks if the segment is empty.""" - mean_square = np.sum(np.mean(self._samples**2, axis=0)) - return self.num_samples == 0 or mean_square == 0 - - def gain_db(self, gain): - """Returns the gain in decibels.""" - self._samples *= 10.0 ** (gain / 20.0) - - def normalize_db(self, target_db=-20, ref_channel=None): - """Normalize the signal to a target RMS value in decibels. - For multi-channel audio, the RMS value is determined by the reference channel (if not None), - otherwise it will be the maximum RMS across all channels. - """ - rms_db = self.rms_db - if self.num_channels > 1: - rms_db = max(rms_db) if ref_channel is None else rms_db[ref_channel] - gain = target_db - rms_db - self.gain_db(gain) - - def pad(self, pad_size, symmetric=False): - """Add zero padding to the sample. The pad size is given in number - of samples. - If symmetric=True, `pad_size` will be added to both sides. If false, - `pad_size` - zeros will be added only to the end. - """ - samples_ndim = self._samples.ndim - if samples_ndim == 1: - pad_width = pad_size if symmetric else (0, pad_size) - elif samples_ndim == 2: - # pad samples, keep channels - pad_width = ((pad_size, pad_size), (0, 0)) if symmetric else ((0, pad_size), (0, 0)) - else: - raise NotImplementedError( - f"Padding not implemented for signals with more that 2 dimensions. " - f"Current samples dimension: {samples_ndim}." - ) - # apply padding - self._samples = np.pad( - self._samples, - pad_width, - mode='constant', - ) - - def subsegment(self, start_time=None, end_time=None): - """Cut the AudioSegment between given boundaries. - Note that this is an in-place transformation. - :param start_time: Beginning of subsegment in seconds. - :type start_time: float - :param end_time: End of subsegment in seconds. - :type end_time: float - :raise ValueError: If start_time or end_time is incorrectly set, - e.g. out of bounds in time. - """ - start_time = 0.0 if start_time is None else start_time - end_time = self.duration if end_time is None else end_time - if start_time < 0.0: - start_time = self.duration + start_time - if end_time < 0.0: - end_time = self.duration + end_time - if start_time < 0.0: - raise ValueError("The slice start position (%f s) is out of bounds." % start_time) - if end_time < 0.0: - raise ValueError("The slice end position (%f s) is out of bounds." % end_time) - if start_time > end_time: - raise ValueError( - "The slice start position (%f s) is later than the end position (%f s)." % (start_time, end_time) - ) - if end_time > self.duration: - raise ValueError("The slice end position (%f s) is out of bounds (> %f s)" % (end_time, self.duration)) - start_sample = int(round(start_time * self._sample_rate)) - end_sample = int(round(end_time * self._sample_rate)) - self._samples = self._samples[start_sample:end_sample] diff --git a/nemo/collections/asr/parts/submodules/__init__.py b/nemo/collections/asr/parts/submodules/__init__.py deleted file mode 100644 index bc443be41c4c3fcf0764eb9fd3e1828d63f8438c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/asr/parts/submodules/adapters/__init__.py b/nemo/collections/asr/parts/submodules/adapters/__init__.py deleted file mode 100644 index c51d935bddd4712c83785cc1a5aed82b4719a321..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/adapters/__init__.py +++ /dev/null @@ -1,34 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# fmt: off -from nemo.collections.asr.parts.submodules.adapters.attention_adapter_mixin import AttentionAdapterModuleMixin -from nemo.collections.asr.parts.submodules.adapters.multi_head_attention_adapter_module import ( - MHAResidualAddAdapterStrategy, - MHAResidualAddAdapterStrategyConfig, - MultiHeadAttentionAdapter, - MultiHeadAttentionAdapterConfig, - PositionalEncodingAdapter, - PositionalEncodingAdapterConfig, - RelPositionalEncodingAdapter, - RelPositionalEncodingAdapterConfig, - RelPositionMultiHeadAttentionAdapter, - RelPositionMultiHeadAttentionAdapterConfig, -) -from nemo.collections.asr.parts.submodules.adapters.transformer_multi_head_attention_adapter_module import ( - TransformerMultiHeadAttentionAdapter, - TransformerMultiHeadAttentionAdapterConfig, -) - -# fmt: on diff --git a/nemo/collections/asr/parts/submodules/adapters/attention_adapter_mixin.py b/nemo/collections/asr/parts/submodules/adapters/attention_adapter_mixin.py deleted file mode 100644 index 9efbcee76f0f8064db2f7d2c1a970dde53b08b91..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/adapters/attention_adapter_mixin.py +++ /dev/null @@ -1,133 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import torch - -from nemo.core.classes.mixins import adapter_mixins -from nemo.utils import logging, logging_mode - - -class AttentionAdapterModuleMixin(adapter_mixins.AdapterModuleMixin): - """ - Utility class that implements a custom forward method for Modules that are attention based. - Attention based adapters can support either linear adapters, and Multi-Head Attention adapters. - - However, Multi Head Attention adapters require additional arguments, such as `att_mask` and `pos_emb`. - This utility class unifies the adapter forward pass for both types of adapters. - - .. Usage: - - To use this class, inherit from this class, and when calling self.foward_enabled_adapters() pass the following: - - .. code-block:: python - - if self.is_adapter_available(): - # Call the MHA adapters - pack_ip = { - 'x': residual, - 'loc': 'mha', - 'att_mask': att_mask, - 'pos_emb': pos_emb, - } - pack_ip = self.forward_enabled_adapters(pack_ip) - residual = pack_ip['x'] - - if self.is_adapter_available(): - # Call the Linear adapters - pack_ip = { - 'x': x, - 'loc': 'post', - } - pack_ip = self.forward_enabled_adapters(pack_ip) - x = pack_ip['x'] - """ - - def forward_single_enabled_adapter_( - self, - input: dict, - adapter_module: torch.nn.Module, - *, - adapter_name: str, - adapter_strategy: 'nemo.core.classes.mixins.adapter_mixin_strategies.AbstractAdapterStrategy', - ): - """ - Perform the forward step of a single adapter module on some input data. - - **Note**: Subclasses can override this method to accommodate more complicate adapter forward steps. - - Args: - input: Dictionary of packed tensors. The dict should contain at least - `x`: output tensor - `loc`: Semantic location in module where this adapter was called. Can be 'mha' or 'post'. - `att_mask`: Optional, Attention mask - `pos_emb`: Optional, Positional Embedding for Relative Positional Encoding. - The output tensor of the calling module is the input to the first adapter, whose output - is then chained to the next adapter until all adapters are consumed. - adapter_module: The adapter module that is currently required to perform the forward pass. - adapter_name: The resolved name of the adapter that is undergoing the current forward pass. - adapter_strategy: A subclass of `AbstractAdapterStrategy`, that determines how the - output of the adapter should be merged with the input, or if it should be merged at all. - - Returns: - The result tensor, after the current active adapter has finished its forward pass. - """ - if not hasattr(self, 'self_attention_model'): - raise RuntimeError( - "self_attention_model attribute not found in the module! Please set in the module " - "a string attribute 'self_attention_model' with value 'abs_pos', 'rel_pos' or " - "other supported self-attention model types." - ) - - # Collect imports to prevent circular imports - from nemo.collections.asr.modules.transformer import transformer_modules as transformer_mha - from nemo.collections.asr.parts.submodules import multi_head_attention as conformer_mha - - # (input: torch.Tensor, adapter: torch.nn.Module, *, module: 'AdapterModuleMixin') - x = input['x'] - loc = input['loc'] - att_mask = input.get('att_mask', None) - pos_emb = input.get('pos_emb', None) - - from nemo.collections.common.parts import adapter_modules - - if isinstance(adapter_module, adapter_modules.LinearAdapter) and loc == 'post': - output = adapter_strategy(x, adapter_module, module=self) - - elif isinstance(adapter_module, conformer_mha.MultiHeadAttention) and loc == 'mha': - if self.self_attention_model == 'rel_pos': - x = dict(query=x, key=x, value=x, mask=att_mask, pos_emb=pos_emb) - output = adapter_strategy(x, adapter_module, module=self) - - elif self.self_attention_model == 'abs_pos': - x = dict(query=x, key=x, value=x, mask=att_mask) - output = adapter_strategy(x, adapter_module, module=self) - - else: - raise ValueError(f"Unsupported value of self_attention_model , provided {self.self_attention_model}!") - - elif isinstance(adapter_module, transformer_mha.MultiHeadAttention) and loc == 'mha': - x = dict(queries=x, keys=x, values=x, attention_mask=att_mask) - output = adapter_strategy(x, adapter_module, module=self) - - else: - # No adapter compatible, skip - logging.warning( - "No adapter compatible with the current module. Skipping adapter forward pass.", mode=logging_mode.ONCE - ) - - output = x - - input['x'] = output - - return input diff --git a/nemo/collections/asr/parts/submodules/adapters/multi_head_attention_adapter_module.py b/nemo/collections/asr/parts/submodules/adapters/multi_head_attention_adapter_module.py deleted file mode 100644 index 4f5f7364171e1b2adf22f411804bca3a44a4829c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/adapters/multi_head_attention_adapter_module.py +++ /dev/null @@ -1,428 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import math -from dataclasses import dataclass, field -from typing import Any, Optional - -import torch -from torch import nn as nn - -from nemo.collections.asr.parts.submodules import multi_head_attention as mha -from nemo.collections.common.parts import adapter_modules -from nemo.core.classes.mixins import adapter_mixin_strategies - - -class MHAResidualAddAdapterStrategy(adapter_mixin_strategies.ResidualAddAdapterStrategy): - """ - An implementation of residual addition of an adapter module with its input for the MHA Adapters. - """ - - def forward(self, input: dict, adapter: torch.nn.Module, *, module: 'AdapterModuleMixin'): - """ - A basic strategy, comprising of a residual connection over the input, after forward pass by - the underlying adapter. Additional work is done to pack and unpack the dictionary of inputs and outputs. - - Note: The `value` tensor is added to the output of the attention adapter as the residual connection. - - Args: - input: A dictionary of multiple input arguments for the adapter module. - - `query`, `key`, `value`: Original output tensor of the module, or the output of the - previous adapter (if more than one adapters are enabled). - - `mask`: Attention mask. - - `pos_emb`: Optional positional embedding for relative encoding. - - adapter: The adapter module that is currently required to perform the forward pass. - module: The calling module, in its entirety. It is a module that implements `AdapterModuleMixin`, - therefore the strategy can access all other adapters in this module via `module.adapter_layer`. - - Returns: - The result tensor, after one of the active adapters has finished its forward passes. - """ - out = self.compute_output(input, adapter, module=module) - - value_name = None - if 'value' in input: - value_name = 'value' - elif 'values' in input: - value_name = 'values' - else: - raise ValueError( - "Input dictionary must contain 'value' or 'values' key for residual connection. Input " - f"dictionary keys: {input.keys()}" - ) - - # If not in training mode, or probability of stochastic depth is 0, skip step. - p = self.stochastic_depth - if not module.training or p == 0.0: - pass - else: - out = self.apply_stochastic_depth(out, input[value_name], adapter, module=module) - - # Return the residual connection output = input + adapter(input) - result = input[value_name] + out - - # If l2_lambda is activated, register the loss value - self.compute_auxiliary_losses(result, input[value_name], adapter, module=module) - - return result - - def compute_output( - self, input: torch.Tensor, adapter: torch.nn.Module, *, module: 'AdapterModuleMixin' - ) -> torch.Tensor: - """ - Compute the output of a single adapter to some input. - - Args: - input: Original output tensor of the module, or the output of the previous adapter (if more than - one adapters are enabled). - adapter: The adapter module that is currently required to perform the forward pass. - module: The calling module, in its entirety. It is a module that implements `AdapterModuleMixin`, - therefore the strategy can access all other adapters in this module via `module.adapter_layer`. - - Returns: - The result tensor, after one of the active adapters has finished its forward passes. - """ - if isinstance(input, (list, tuple)): - out = adapter(*input) - elif isinstance(input, dict): - out = adapter(**input) - else: - out = adapter(input) - return out - - -@dataclass -class MHAResidualAddAdapterStrategyConfig(adapter_mixin_strategies.ResidualAddAdapterStrategyConfig): - _target_: str = "{0}.{1}".format( - MHAResidualAddAdapterStrategy.__module__, MHAResidualAddAdapterStrategy.__name__ - ) # mandatory field - - -class MultiHeadAttentionAdapter(mha.MultiHeadAttention, adapter_modules.AdapterModuleUtil): - """Multi-Head Attention layer of Transformer. - - Args: - n_head (int): number of heads - n_feat (int): size of the features - dropout_rate (float): dropout rate - proj_dim (int, optional): Optional integer value for projection before computing attention. - If None, then there is no projection (equivalent to proj_dim = n_feat). - If > 0, then will project the n_feat to proj_dim before calculating attention. - If <0, then will equal n_head, so that each head has a projected dimension of 1. - adapter_strategy: By default, MHAResidualAddAdapterStrategyConfig. An adapter composition function object. - """ - - def __init__( - self, - n_head: int, - n_feat: int, - dropout_rate: float, - proj_dim: Optional[int] = None, - adapter_strategy: MHAResidualAddAdapterStrategy = None, - use_pytorch_sdpa: bool = False, - use_pytorch_sdpa_backends: Optional[list] = None, - ): - super().__init__( - n_head=n_head, - n_feat=n_feat, - dropout_rate=dropout_rate, - max_cache_len=0, - use_pytorch_sdpa=use_pytorch_sdpa, - use_pytorch_sdpa_backends=use_pytorch_sdpa_backends, - ) - - self.pre_norm = nn.LayerNorm(n_feat) - - # Set the projection dim to number of heads automatically - if proj_dim is not None and proj_dim < 1: - proj_dim = n_head - - self.proj_dim = proj_dim - - # Recompute weights for projection dim - if self.proj_dim is not None: - if self.proj_dim % n_head != 0: - raise ValueError(f"proj_dim ({proj_dim}) is not divisible by n_head ({n_head})") - - self.d_k = self.proj_dim // n_head - self.s_d_k = math.sqrt(self.d_k) - self.linear_q = nn.Linear(n_feat, self.proj_dim) - self.linear_k = nn.Linear(n_feat, self.proj_dim) - self.linear_v = nn.Linear(n_feat, self.proj_dim) - self.linear_out = nn.Linear(self.proj_dim, n_feat) - - # Setup adapter strategy - self.setup_adapter_strategy(adapter_strategy) - - # reset parameters for Q to be identity operation - self.reset_parameters() - - def forward(self, query, key, value, mask, pos_emb=None, cache=None): - """Compute 'Scaled Dot Product Attention'. - Args: - query (torch.Tensor): (batch, time1, size) - key (torch.Tensor): (batch, time2, size) - value(torch.Tensor): (batch, time2, size) - mask (torch.Tensor): (batch, time1, time2) - cache (torch.Tensor) : (batch, time_cache, size) - - returns: - output (torch.Tensor): transformed `value` (batch, time1, d_model) weighted by the query dot key attention - cache (torch.Tensor) : (batch, time_cache_next, size) - """ - # Need to perform duplicate computations as at this point the tensors have been - # separated by the adapter forward - query = self.pre_norm(query) - key = self.pre_norm(key) - value = self.pre_norm(value) - - return super().forward(query, key, value, mask, pos_emb, cache=cache) - - def reset_parameters(self): - with torch.no_grad(): - nn.init.zeros_(self.linear_out.weight) - nn.init.zeros_(self.linear_out.bias) - - def get_default_strategy_config(self) -> 'dataclass': - return MHAResidualAddAdapterStrategyConfig() - - -@dataclass -class MultiHeadAttentionAdapterConfig: - n_head: int - n_feat: int - dropout_rate: float = 0.0 - proj_dim: Optional[int] = None - adapter_strategy: Optional[Any] = field(default_factory=lambda: MHAResidualAddAdapterStrategyConfig()) - use_pytorch_sdpa: bool = False - use_pytorch_sdpa_backends: Optional[list] = None - _target_: str = "{0}.{1}".format(MultiHeadAttentionAdapter.__module__, MultiHeadAttentionAdapter.__name__) - - -class RelPositionMultiHeadAttentionAdapter(mha.RelPositionMultiHeadAttention, adapter_modules.AdapterModuleUtil): - """Multi-Head Attention layer of Transformer-XL with support of relative positional encoding. - Paper: https://arxiv.org/abs/1901.02860 - - Args: - n_head (int): number of heads - n_feat (int): size of the features - dropout_rate (float): dropout rate - proj_dim (int, optional): Optional integer value for projection before computing attention. - If None, then there is no projection (equivalent to proj_dim = n_feat). - If > 0, then will project the n_feat to proj_dim before calculating attention. - If <0, then will equal n_head, so that each head has a projected dimension of 1. - adapter_strategy: By default, MHAResidualAddAdapterStrategyConfig. An adapter composition function object. - """ - - def __init__( - self, - n_head: int, - n_feat: int, - dropout_rate: float, - proj_dim: Optional[int] = None, - adapter_strategy: MHAResidualAddAdapterStrategyConfig = None, - use_pytorch_sdpa: bool = False, - use_pytorch_sdpa_backends: Optional[list] = None, - ): - super().__init__( - n_head=n_head, - n_feat=n_feat, - dropout_rate=dropout_rate, - pos_bias_u=None, - pos_bias_v=None, - max_cache_len=0, - use_pytorch_sdpa=use_pytorch_sdpa, - use_pytorch_sdpa_backends=use_pytorch_sdpa_backends, - ) - - self.pre_norm = nn.LayerNorm(n_feat) - - # Set the projection dim to number of heads automatically - if proj_dim is not None and proj_dim < 1: - proj_dim = n_head - - self.proj_dim = proj_dim - - # Recompute weights for projection dim - if self.proj_dim is not None: - if self.proj_dim % n_head != 0: - raise ValueError(f"proj_dim ({proj_dim}) is not divisible by n_head ({n_head})") - - self.d_k = self.proj_dim // n_head - self.s_d_k = math.sqrt(self.d_k) - self.linear_q = nn.Linear(n_feat, self.proj_dim) - self.linear_k = nn.Linear(n_feat, self.proj_dim) - self.linear_v = nn.Linear(n_feat, self.proj_dim) - self.linear_out = nn.Linear(self.proj_dim, n_feat) - self.linear_pos = nn.Linear(n_feat, self.proj_dim, bias=False) - self.pos_bias_u = nn.Parameter(torch.FloatTensor(self.h, self.d_k)) - self.pos_bias_v = nn.Parameter(torch.FloatTensor(self.h, self.d_k)) - - # Setup adapter strategy - self.setup_adapter_strategy(adapter_strategy) - - # reset parameters for Q to be identity operation - self.reset_parameters() - - def forward(self, query, key, value, mask, pos_emb, cache=None): - """Compute 'Scaled Dot Product Attention' with rel. positional encoding. - Args: - query (torch.Tensor): (batch, time1, size) - key (torch.Tensor): (batch, time2, size) - value(torch.Tensor): (batch, time2, size) - mask (torch.Tensor): (batch, time1, time2) - pos_emb (torch.Tensor) : (batch, time1, size) - cache (torch.Tensor) : (batch, time_cache, size) - Returns: - output (torch.Tensor): transformed `value` (batch, time1, d_model) weighted by the query dot key attention - cache_next (torch.Tensor) : (batch, time_cache_next, size) - """ - # Need to perform duplicate computations as at this point the tensors have been - # separated by the adapter forward - query = self.pre_norm(query) - key = self.pre_norm(key) - value = self.pre_norm(value) - - return super().forward(query, key, value, mask, pos_emb, cache=cache) - - def reset_parameters(self): - with torch.no_grad(): - nn.init.zeros_(self.linear_out.weight) - nn.init.zeros_(self.linear_out.bias) - - # NOTE: This exact procedure apparently highly important. - # Above operation is safe to do as self.linear_out.weight *= 0.0 (similar for bias) - # However: - # DO NOT REPLACE BELOW WITH self.pos_bias_u *= 0.0 OR self.pos_bias_v *= 0.0 - # For some reason at init sometimes it will cause the value of the tensor to become NaN - # All operations to compute matrix_ac and matrix_bd will then fail. - nn.init.zeros_(self.pos_bias_u) - nn.init.zeros_(self.pos_bias_v) - - def get_default_strategy_config(self) -> 'dataclass': - return MHAResidualAddAdapterStrategyConfig() - - -@dataclass -class RelPositionMultiHeadAttentionAdapterConfig: - n_head: int - n_feat: int - dropout_rate: float = 0.0 - proj_dim: Optional[int] = None - adapter_strategy: Optional[Any] = field(default_factory=lambda: MHAResidualAddAdapterStrategyConfig()) - use_pytorch_sdpa: bool = False - use_pytorch_sdpa_backends: Optional[list] = None - _target_: str = "{0}.{1}".format( - RelPositionMultiHeadAttentionAdapter.__module__, RelPositionMultiHeadAttentionAdapter.__name__ - ) - - -class PositionalEncodingAdapter(mha.PositionalEncoding, adapter_modules.AdapterModuleUtil): - """ - Absolute positional embedding adapter. - - .. note:: - - Absolute positional embedding value is added to the input tensor *without residual connection* ! - Therefore, the input is changed, if you only require the positional embedding, drop the returned `x` ! - - Args: - d_model (int): The input dimension of x. - max_len (int): The max sequence length. - xscale (float): The input scaling factor. Defaults to 1.0. - adapter_strategy (AbstractAdapterStrategy): By default, ReturnResultAdapterStrategyConfig. - An adapter composition function object. - NOTE: Since this is a positional encoding, it will not add a residual ! - """ - - def __init__( - self, - d_model: int, - max_len: int = 5000, - xscale=1.0, - adapter_strategy: adapter_mixin_strategies.ReturnResultAdapterStrategyConfig = None, - ): - - super().__init__( - d_model=d_model, - dropout_rate=0.0, - max_len=max_len, - xscale=xscale, - dropout_rate_emb=0.0, - ) - - # Setup adapter strategy - self.setup_adapter_strategy(adapter_strategy) - - def get_default_strategy_config(self) -> 'dataclass': - return adapter_mixin_strategies.ReturnResultAdapterStrategyConfig() - - -@dataclass -class PositionalEncodingAdapterConfig: - d_model: int - max_len: int = 5000 - xscale: float = 1.0 - adapter_strategy: Optional[Any] = field( - default_factory=lambda: adapter_mixin_strategies.ResidualAddAdapterStrategyConfig() - ) - _target_: str = "{0}.{1}".format(PositionalEncodingAdapter.__module__, PositionalEncodingAdapter.__name__) - - -class RelPositionalEncodingAdapter(mha.RelPositionalEncoding, adapter_modules.AdapterModuleUtil): - """ - Relative positional encoding for TransformerXL's layers - See : Appendix B in https://arxiv.org/abs/1901.02860 - - .. note:: - - Relative positional embedding value is **not** added to the input tensor ! - Therefore, the input should be updated changed, if you only require the positional embedding, drop the returned `x` ! - - Args: - d_model (int): embedding dim - max_len (int): maximum input length - xscale (bool): whether to scale the input by sqrt(d_model) - adapter_strategy: By default, ReturnResultAdapterStrategyConfig. An adapter composition function object. - """ - - def __init__( - self, - d_model: int, - max_len: int = 5000, - xscale=1.0, - adapter_strategy: adapter_mixin_strategies.ReturnResultAdapterStrategyConfig = None, - ): - super().__init__(d_model=d_model, dropout_rate=0.0, max_len=max_len, xscale=xscale, dropout_rate_emb=0.0) - - # Setup adapter strategy - self.setup_adapter_strategy(adapter_strategy) - - def get_default_strategy_config(self) -> 'dataclass': - return adapter_mixin_strategies.ReturnResultAdapterStrategyConfig() - - -@dataclass -class RelPositionalEncodingAdapterConfig: - d_model: int - max_len: int = 5000 - xscale: float = 1.0 - adapter_strategy: Optional[Any] = field( - default_factory=lambda: adapter_mixin_strategies.ResidualAddAdapterStrategyConfig() - ) - _target_: str = "{0}.{1}".format(RelPositionalEncodingAdapter.__module__, RelPositionalEncodingAdapter.__name__) diff --git a/nemo/collections/asr/parts/submodules/adapters/transformer_multi_head_attention_adapter_module.py b/nemo/collections/asr/parts/submodules/adapters/transformer_multi_head_attention_adapter_module.py deleted file mode 100644 index b0cf8cbc0035097d5f5f85de6422c9bc095a3f67..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/adapters/transformer_multi_head_attention_adapter_module.py +++ /dev/null @@ -1,129 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import math -from dataclasses import dataclass, field -from typing import Any, Optional - -import torch -from torch import nn as nn - -from nemo.collections.asr.modules.transformer import transformer_modules -from nemo.collections.asr.parts.submodules.adapters.multi_head_attention_adapter_module import ( - MHAResidualAddAdapterStrategy, - MHAResidualAddAdapterStrategyConfig, -) -from nemo.collections.common.parts import adapter_modules - - -class TransformerMultiHeadAttentionAdapter(transformer_modules.MultiHeadAttention, adapter_modules.AdapterModuleUtil): - """Multi-Head Attention layer of Transformer Encoder. - - Args: - hidden_size (int): number of heads - num_attention_heads (int): size of the features - attn_score_dropout (float): dropout rate for the attention scores - attn_layer_dropout (float): dropout rate for the layer - proj_dim (int, optional): Optional integer value for projection before computing attention. - If None, then there is no projection (equivalent to proj_dim = n_feat). - If > 0, then will project the n_feat to proj_dim before calculating attention. - If <0, then will equal n_head, so that each head has a projected dimension of 1. - adapter_strategy: By default, MHAResidualAddAdapterStrategyConfig. An adapter composition function object. - """ - - def __init__( - self, - hidden_size: int, - num_attention_heads: int, - attn_score_dropout: float = 0.0, - attn_layer_dropout: float = 0.0, - proj_dim: Optional[int] = None, - adapter_strategy: MHAResidualAddAdapterStrategy = None, - ): - super().__init__( - hidden_size=hidden_size, - num_attention_heads=num_attention_heads, - attn_score_dropout=attn_score_dropout, - attn_layer_dropout=attn_layer_dropout, - ) - - self.pre_norm = nn.LayerNorm(hidden_size) - - # Set the projection dim to number of heads automatically - if proj_dim is not None and proj_dim < 1: - proj_dim = num_attention_heads - - self.proj_dim = proj_dim - - # Recompute weights for projection dim - if self.proj_dim is not None: - if self.proj_dim % num_attention_heads != 0: - raise ValueError(f"proj_dim ({proj_dim}) is not divisible by n_head ({num_attention_heads})") - - self.attn_head_size = self.proj_dim // num_attention_heads - self.attn_scale = math.sqrt(math.sqrt(self.attn_head_size)) - self.query_net = nn.Linear(hidden_size, self.proj_dim) - self.key_net = nn.Linear(hidden_size, self.proj_dim) - self.value_net = nn.Linear(hidden_size, self.proj_dim) - self.out_projection = nn.Linear(self.proj_dim, hidden_size) - - # Setup adapter strategy - self.setup_adapter_strategy(adapter_strategy) - - # reset parameters for Q to be identity operation - self.reset_parameters() - - def forward(self, queries, keys, values, attention_mask): - """Compute 'Scaled Dot Product Attention'. - Args: - query (torch.Tensor): (batch, time1, size) - key (torch.Tensor): (batch, time2, size) - value(torch.Tensor): (batch, time2, size) - mask (torch.Tensor): (batch, time1, time2) - cache (torch.Tensor) : (batch, time_cache, size) - - returns: - output (torch.Tensor): transformed `value` (batch, time1, d_model) weighted by the query dot key attention - cache (torch.Tensor) : (batch, time_cache_next, size) - """ - # Need to perform duplicate computations as at this point the tensors have been - # separated by the adapter forward - query = self.pre_norm(queries) - key = self.pre_norm(keys) - value = self.pre_norm(values) - - output, extra_output = super().forward(query, key, value, attention_mask) - - return output - - def reset_parameters(self): - with torch.no_grad(): - nn.init.zeros_(self.out_projection.weight) - nn.init.zeros_(self.out_projection.bias) - - def get_default_strategy_config(self) -> 'dataclass': - return MHAResidualAddAdapterStrategyConfig() - - -@dataclass -class TransformerMultiHeadAttentionAdapterConfig: - hidden_size: int - num_attention_heads: int - attn_score_dropout: float = 0.0 - attn_layer_dropout: float = 0.0 - proj_dim: Optional[int] = None - adapter_strategy: Optional[Any] = field(default_factory=lambda: MHAResidualAddAdapterStrategyConfig()) - _target_: str = "{0}.{1}".format( - TransformerMultiHeadAttentionAdapter.__module__, TransformerMultiHeadAttentionAdapter.__name__ - ) diff --git a/nemo/collections/asr/parts/submodules/aed_decoding/__init__.py b/nemo/collections/asr/parts/submodules/aed_decoding/__init__.py deleted file mode 100644 index 30c675039aa064098090957750c2e08f446ad8f1..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/aed_decoding/__init__.py +++ /dev/null @@ -1,23 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.asr.parts.submodules.aed_decoding.aed_batched_streaming import ( - GreedyBatchedStreamingAEDComputer, - return_decoder_input_ids, -) - -__all__ = [ - "GreedyBatchedStreamingAEDComputer", - "return_decoder_input_ids", -] diff --git a/nemo/collections/asr/parts/submodules/aed_decoding/aed_batched_streaming.py b/nemo/collections/asr/parts/submodules/aed_decoding/aed_batched_streaming.py deleted file mode 100644 index da15ea110da8df0b609d99ce4f6eea6061186dbe..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/aed_decoding/aed_batched_streaming.py +++ /dev/null @@ -1,546 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from dataclasses import dataclass - -import torch -from omegaconf import OmegaConf - -from nemo.collections.asr.models.aed_multitask_models import EncDecMultiTaskModel, parse_multitask_prompt -from nemo.collections.asr.parts.submodules.multitask_decoding import AEDStreamingDecodingConfig -from nemo.collections.asr.parts.utils.eval_utils import compute_laal -from nemo.collections.asr.parts.utils.streaming_utils import ContextSize -from nemo.utils import logging - - -@dataclass -class AEDStreamingState: - decoder_input_ids: torch.Tensor | None = None # tokens ids of initial AED model prompt - pred_tokens_ids: torch.Tensor | None = None # buffer with predicted tokens ids - decoding_step: int = -1 # current decoding step - decoder_mems_list: list | None = None # decoder caches, helps to reduce the memory usage - is_last_chunk_batch: torch.Tensor = False # whether the current chunk is the last speech chunk in the audio - max_generation_length: int = ( - 256 # maximum number of tokens to be generated for each sample (can be bigger for long audio) - ) - max_tokens_per_one_second: int = 10 # maximum number of tokens to be generated per one second of audio - max_tokens_per_alignatt_step: int | None = ( - None # maximum number of tokens to be generated for each step of alignatt decoding policy - ) - use_avgpool_for_alignatt: bool = False # use avgpooling for alignatt decoding policy - tokens_frame_alignment: torch.Tensor | None = ( - None # frame alignment of the predicted tokens (used for LAAL calculation in alignatt) - ) - prev_encoder_shift: int = 0 # previous encoder shift (used for LAAL calculation in alignatt) - device: torch.device | None = None - - -class GreedyBatchedStreamingAEDComputer: - """ - Batched streaming AED decoding with support for waitk and alignatt decoding policies. - """ - - def __init__( - self, - asr_model: EncDecMultiTaskModel, - frame_chunk_size: int, - decoding_cfg: AEDStreamingDecodingConfig, - ): - """ - Init method. - Args: - asr_model: instance of ASR model (Canary) - frame_chunk_size: size of the frame chunk - decoding_cfg: decoding configuration - """ - - self.asr_model = asr_model - self.frame_chunk_size = frame_chunk_size - self.decoding_cfg = decoding_cfg - - # define the decoding method once during initialization - if decoding_cfg.streaming_policy == "waitk": - self._run_decoding_step = self.run_waitk_decoding_step - elif decoding_cfg.streaming_policy == "alignatt": - self._run_decoding_step = self.run_alignatt_decoding_step - else: - raise ValueError("Canary streaming decoding supports only alignatt or waitk decoding policy") - - def __call__( - self, - encoder_output: torch.Tensor, - encoder_output_len: torch.Tensor, - encoder_input_mask: torch.Tensor, - prev_batched_state: AEDStreamingState, - ) -> AEDStreamingState: - - self.state = prev_batched_state - self.state.encoder_output_len = encoder_output_len - - # initial waitk lagging. Applicable for Wait-k and AlignAtt decoding policies. Control the start of the decoding process. - if encoder_output_len.max() // self.frame_chunk_size < self.decoding_cfg.waitk_lagging and torch.any( - torch.logical_not(self.state.is_last_chunk_batch) - ): - # need to wait for more speech - return self.state - - # call the pre-determined decoding method - self._run_decoding_step(encoder_output, encoder_input_mask) - - return self.state - - def run_waitk_decoding_step(self, encoded_speech, encoder_input_mask): - """ - Run a decoding step for waitk streaming policy. - """ - if self.state.decoding_step < 0: - # first decoding step - pred_tokens_ids, batch_size, _ = self.asr_model.decoding.decoding.greedy_search._prepare_for_search( - self.state.decoder_input_ids, - encoded_speech, - ) - input_ids = pred_tokens_ids - else: - input_ids = self.state.pred_tokens_ids[ - self.state.batch_idxs, self.state.current_context_lengths - 1 - ].unsqueeze(-1) - - self.state.active_samples_inner_loop = ( - torch.ones(self.state.batch_size, dtype=torch.bool, device=self.state.device) * self.state.active_samples - ) - decoder_mems_list = self.state.decoder_mems_list - - # define start and max generation lengths - start_from = self.state.decoding_step + 1 - if torch.any(torch.logical_not(self.state.is_last_chunk_batch)): - # predict only one token per speech chunk if not the last one - max_generation_length = start_from + 1 - else: - max_generation_length = self.decoding_cfg.max_generation_length - - # inner decoding loop (with same speech chunk) - for i in range(start_from, max_generation_length): - - if not decoder_mems_list: - positional_indexes = torch.zeros_like(self.state.current_context_lengths) - else: - positional_indexes = self.state.current_context_lengths - 1 - - logits, decoder_mems_list, xatt_scores_list = ( - self.asr_model.decoding.decoding.greedy_search._one_step_forward( - input_ids, - encoded_speech, - encoder_input_mask, - decoder_mems_list, - positional_indexes, - return_scores=False, - ) - ) - next_tokens = torch.argmax(logits[:, -1], dim=-1) - - # compute eos tokens mask - is_eos_tokens = next_tokens == self.asr_model.tokenizer.eos - # rearange active samples (inner loop) depends on eos prediction - self.state.active_samples_inner_loop *= torch.logical_not(is_eos_tokens) - # disable samples (upper loop) with eos and end of speech - eos_and_end_speech_mask = is_eos_tokens * self.state.is_last_chunk_batch - self.state.active_samples = self.state.active_samples * torch.logical_not(eos_and_end_speech_mask) - - if not torch.any(self.state.active_samples_inner_loop): - break - - # write predicted tokens to the pred_tokens_ids tensor - torch.where(self.state.active_samples_inner_loop, next_tokens, self.state.eos_tokens, out=next_tokens) - self.state.pred_tokens_ids[self.state.batch_idxs, self.state.current_context_lengths] = next_tokens - - self.state.decoding_step += input_ids.size(-1) - - # check for hallucinations - if self.decoding_cfg.hallucinations_detector: - hallucination_mask = self.detect_hallucinations( - self.state.pred_tokens_ids, self.state.batch_idxs, self.state.current_context_lengths - ) - self.state.active_samples *= torch.logical_not(hallucination_mask) - self.state.active_samples_inner_loop *= torch.logical_not(hallucination_mask) - - self.state.current_context_lengths += self.state.active_samples_inner_loop - input_ids = self.state.pred_tokens_ids[ - self.state.batch_idxs, self.state.current_context_lengths - 1 - ].unsqueeze(-1) - - # disable samples with maximum context length - samples_with_max_context_length = ( - self.state.current_context_lengths == self.decoding_cfg.max_generation_length - 1 - ) - if torch.any(samples_with_max_context_length * self.state.active_samples): - logging.info("!!! maximum context length reached !!!") - self.state.active_samples *= torch.logical_not(samples_with_max_context_length) - self.state.active_samples_inner_loop *= torch.logical_not(samples_with_max_context_length) - - # zero out decoder_mems_list for non active samples - if torch.any(torch.logical_not(self.state.active_samples_inner_loop)): - for j in range(len(decoder_mems_list)): - decoder_mems_list[j][:, -1] *= self.state.active_samples_inner_loop.unsqueeze(-1) - self.state.decoder_mems_list = decoder_mems_list - - def run_alignatt_decoding_step(self, encoded_speech, encoder_input_mask): - """ - Run a decoding step for alignatt streaming policy. - """ - if self.state.decoding_step < 0: - # first decoding step - pred_tokens_ids, batch_size, _ = self.asr_model.decoding.decoding.greedy_search._prepare_for_search( - self.state.decoder_input_ids, - encoded_speech, - ) - input_ids = pred_tokens_ids - start_from = 0 - else: - input_ids = self.state.pred_tokens_ids[ - self.state.batch_idxs, self.state.current_context_lengths - 1 - ].unsqueeze(-1) - start_from = torch.min(self.state.current_context_lengths).item() - 1 - - decoder_mems_list = self.state.decoder_mems_list - self.state.steps_per_inner_loop = torch.zeros( - self.state.batch_size, dtype=torch.long, device=self.state.device - ) - self.state.active_samples_inner_loop = ( - torch.ones(self.state.batch_size, dtype=torch.bool, device=self.state.device) * self.state.active_samples - ) - - for i in range(start_from, self.state.max_generation_length): - # prepare positional indexes offset for attention decoder - if not decoder_mems_list: - positional_indexes = torch.zeros_like(self.state.current_context_lengths) - else: - positional_indexes = self.state.current_context_lengths - 1 - - logits, decoder_mems_list, xatt_scores_list = ( - self.asr_model.decoding.decoding.greedy_search._one_step_forward( - input_ids, - encoded_speech, - encoder_input_mask, - decoder_mems_list, - positional_indexes, - return_scores=False, - ) - ) - next_tokens = torch.argmax(logits[:, -1], dim=-1) - - # compute the most attended encoder token - xatt_scores = xatt_scores_list[self.decoding_cfg.xatt_scores_layer] - xatt_scores = torch.mean(xatt_scores, 1) - if i == 0 and xatt_scores.shape[-1] <= self.decoding_cfg.exclude_sink_frames: - exclude_sink_frames = xatt_scores.shape[-1] // 2 - else: - exclude_sink_frames = ( - self.decoding_cfg.exclude_sink_frames if self.state.prev_encoder_shift == 0 else 0 - ) - most_attended_idxs = torch.argmax(xatt_scores[:, :, exclude_sink_frames:], dim=-1) + exclude_sink_frames - - # we can try to smooth peaky xatt scores with avgpooling - if self.decoding_cfg.use_avgpool_for_alignatt: - average_pooling_xatt_scores = self.state.avgpool2d(xatt_scores[:, :, exclude_sink_frames:]) - most_attended_idxs_avgpool = torch.argmax(average_pooling_xatt_scores, dim=-1) + exclude_sink_frames - most_attended_idxs = most_attended_idxs_avgpool - - # select the last attended token for each sample - if most_attended_idxs.size(-1) > 1: - most_attended_idxs = most_attended_idxs[:, -1] - else: - most_attended_idxs = most_attended_idxs.squeeze(-1) - - # aligatt condition (True -- continue decoding, False -- wait for more speech) - alignatt_condition = ( - self.state.encoder_output_len - (most_attended_idxs + 1) >= self.decoding_cfg.alignatt_thr - ) - # alignatt condition is always True for the last speech chunk - alignatt_condition += self.state.is_last_chunk_batch - - # applay alignatt condition for inner loop - self.state.active_samples_inner_loop *= alignatt_condition - - # increase speech chunk if no active samples in the inner loop - if not torch.any(self.state.active_samples_inner_loop): - break - - # compute eos tokens mask - # TODO add a case of "." + EOS prediction for models with PC support? - is_eos_tokens = next_tokens == self.asr_model.tokenizer.eos - # rearange active samples (inner loop) depends on eos prediction - self.state.active_samples_inner_loop *= torch.logical_not(is_eos_tokens) - # disable samples (upper loop) with eos and end of speech - eos_and_end_speech_mask = is_eos_tokens * self.state.is_last_chunk_batch - self.state.active_samples *= torch.logical_not(eos_and_end_speech_mask) - - if not torch.any(self.state.active_samples_inner_loop): - break - - # write predicted tokens to the pred_tokens_ids tensor - torch.where(self.state.active_samples_inner_loop, next_tokens, self.state.eos_tokens, out=next_tokens) - self.state.pred_tokens_ids[self.state.batch_idxs, self.state.current_context_lengths] = next_tokens - - # update tokens frame alignment based on current encoder step (this alignment is used for LAAL calculation) - self.state.tokens_frame_alignment[self.state.batch_idxs, self.state.current_context_lengths] = ( - self.state.encoder_output_len - + self.state.prev_encoder_shift # we need to add the real frame position in the audio signal - ) - - self.state.decoding_step += input_ids.size(-1) - - # check for hallucinations - if self.decoding_cfg.hallucinations_detector: - hallucination_mask = self.detect_hallucinations( - self.state.pred_tokens_ids, self.state.batch_idxs, self.state.current_context_lengths - ) - if torch.any(hallucination_mask): - self.state.active_samples *= torch.logical_not(hallucination_mask) - self.state.active_samples_inner_loop *= torch.logical_not(hallucination_mask) - - # disable samples with maximum context length - samples_with_max_context_length = ( - self.state.current_context_lengths == self.state.max_generation_length - 1 - ) - if torch.any(samples_with_max_context_length * self.state.active_samples): - logging.info("!!! maximum context length reached !!!") - self.state.active_samples *= torch.logical_not(samples_with_max_context_length) - self.state.active_samples_inner_loop *= torch.logical_not(samples_with_max_context_length) - - # zero out decoder_mems_list for non active samples - # TODO batched decoding works wrong if first token was EOS for one of the samples - if torch.any(torch.logical_not(self.state.active_samples_inner_loop)): - for j in range(len(decoder_mems_list)): - decoder_mems_list[j][:, -1] *= self.state.active_samples_inner_loop.unsqueeze(-1) - - self.state.decoder_mems_list = decoder_mems_list - self.state.current_context_lengths += self.state.active_samples_inner_loop - # TODO model does not predicts any real tokens in the case of first EOS prediction (rare case for batched decoding) - input_ids = self.state.pred_tokens_ids[ - self.state.batch_idxs, self.state.current_context_lengths - 1 - ].unsqueeze(-1) - - # limit number of steps per inner loop if not end of speech - if self.state.max_tokens_per_alignatt_step is not None: - self.state.steps_per_inner_loop += self.state.active_samples_inner_loop - disable_samples_mask = self.state.steps_per_inner_loop >= self.state.max_tokens_per_alignatt_step - disable_samples_mask *= torch.logical_not(self.state.is_last_chunk_batch) - self.state.active_samples_inner_loop *= torch.logical_not(disable_samples_mask) - - if not torch.any(self.state.active_samples_inner_loop): - break - - def detect_hallucinations(self, pred_tokens_ids, batch_idxs, current_context_lengths): - - # we need to have at least 8 tokens to run hallucinations detector - if torch.any(current_context_lengths < 8): - return torch.zeros(pred_tokens_ids.shape[0], dtype=torch.bool, device=pred_tokens_ids.device) - - ccl = current_context_lengths - # pattern 1: four consecutive tokens are the same: "a a a a" - hallucination_mask_1 = ( - (pred_tokens_ids[batch_idxs, ccl] == pred_tokens_ids[batch_idxs, ccl - 1]) - * (pred_tokens_ids[batch_idxs, ccl] == pred_tokens_ids[batch_idxs, ccl - 2]) - * (pred_tokens_ids[batch_idxs, ccl] == pred_tokens_ids[batch_idxs, ccl - 3]) - * (pred_tokens_ids[batch_idxs, ccl] == pred_tokens_ids[batch_idxs, ccl - 4]) - ) - if torch.any(hallucination_mask_1): - logging.info("!!! hallucination 'a a a a' detected !!!") - # pattern 2: "a b a b a b" - hallucination_mask_2 = ( - (pred_tokens_ids[batch_idxs, ccl] == pred_tokens_ids[batch_idxs, ccl - 2]) - * (pred_tokens_ids[batch_idxs, ccl - 1] == pred_tokens_ids[batch_idxs, ccl - 3]) - * (pred_tokens_ids[batch_idxs, ccl] == pred_tokens_ids[batch_idxs, ccl - 4]) - * (pred_tokens_ids[batch_idxs, ccl - 1] == pred_tokens_ids[batch_idxs, ccl - 5]) - ) - if torch.any(hallucination_mask_2): - logging.info("!!! hallucination 'a b a b a b' detected !!!") - # pattern 3: "a b c a b c a b c" - hallucination_mask_3 = ( - (pred_tokens_ids[batch_idxs, ccl] == pred_tokens_ids[batch_idxs, ccl - 3]) - * (pred_tokens_ids[batch_idxs, ccl - 1] == pred_tokens_ids[batch_idxs, ccl - 4]) - * (pred_tokens_ids[batch_idxs, ccl - 2] == pred_tokens_ids[batch_idxs, ccl - 5]) - * (pred_tokens_ids[batch_idxs, ccl] == pred_tokens_ids[batch_idxs, ccl - 6]) - * (pred_tokens_ids[batch_idxs, ccl - 1] == pred_tokens_ids[batch_idxs, ccl - 7]) - * (pred_tokens_ids[batch_idxs, ccl - 2] == pred_tokens_ids[batch_idxs, ccl - 8]) - ) - if torch.any(hallucination_mask_3): - logging.info("!!! hallucination 'a b c a b c a b c' detected !!!") - hallucination_mask = hallucination_mask_1 + hallucination_mask_2 + hallucination_mask_3 - return hallucination_mask - - def compute_alignatt_lagging( - self, - records, - predicted_token_ids, - tokens_frame_alignment, - context_encoder_frames, - audio_encoder_fs, - BOW_PREFIX="\u2581", - ): - # import ipdb; ipdb.set_trace() - tokens_idx_shift = self.state.decoder_input_ids.size(-1) - target_length_word = [len(item['text'].split()) for item in records] - audio_signal_lengths = [float(item['duration']) * 1000 for item in records] - # import ipdb; ipdb.set_trace() - tokenizer_vocab = self.asr_model.tokenizer.vocab - eos_token = tokenizer_vocab[self.asr_model.tokenizer.eos_id] - laal_list = [] - for i, tokens in enumerate(predicted_token_ids): - if len(tokens) == 0: - laal_list.append(5000) - continue - audio_signal_length = audio_signal_lengths[i] - # obtain lagging for alignatt - lagging = [] - for j, cur_t in enumerate(tokens): - pred_idx = ( - tokens_frame_alignment[i][tokens_idx_shift + j] + context_encoder_frames.right - ) # TODO: check right_context - cur_t = tokenizer_vocab[cur_t.item()] - if (cur_t.startswith(BOW_PREFIX) and cur_t != BOW_PREFIX) or cur_t == eos_token: # word boundary - lagging.append(pred_idx * audio_encoder_fs) - if cur_t == eos_token: - break - if len(lagging) == 0: - lagging.append(0) - laal = compute_laal(lagging, audio_signal_length, target_length_word[i]) - if torch.is_tensor(laal): - laal_list.append(laal.item()) - else: - laal_list.append(laal) - return laal_list - - def compute_waitk_lagging( - self, records, predicted_token_ids, context_encoder_frames, audio_encoder_fs, BOW_PREFIX="\u2581" - ): - waitk_lagging = self.decoding_cfg.waitk_lagging - pre_decision_ratio = context_encoder_frames.chunk - target_length_word = [len(item['text'].split()) for item in records] - audio_signal_lengths = [float(item['duration']) * 1000 for item in records] - tokenizer_vocab = self.asr_model.tokenizer.vocab - laal_list = [] - for i, tokens in enumerate(predicted_token_ids): - lagging = [] - audio_signal_length = audio_signal_lengths[i] - for j, cur_t in enumerate(tokens): - cur_src_len = (j + waitk_lagging) * pre_decision_ratio + context_encoder_frames.right - cur_src_len *= audio_encoder_fs # to ms - cur_src_len = min(audio_signal_length, cur_src_len) - spm = tokenizer_vocab[cur_t.item()] - # reach word boundary - if ( - spm.startswith(BOW_PREFIX) and spm != BOW_PREFIX - ) or cur_t == self.asr_model.tokenizer.eos_id: # word boundary - lagging.append(cur_src_len) - if cur_t == self.asr_model.tokenizer.eos_id: - break - if len(lagging) == 0: - lagging.append(0) - laal = compute_laal(lagging, audio_signal_length, target_length_word[i]) - laal_list.append(laal) - return laal_list - - @classmethod - def initialize_aed_model_state( - cls, - asr_model, - decoder_input_ids: torch.Tensor, - batch_size: int, - context_encoder_frames: ContextSize, - chunk_secs: float, - right_context_secs: float, - ) -> AEDStreamingState: - """ - Initialize AED model state for streaming inference. - - Args: - asr_model: ASR model instance (used for tokenizer and device) - decoder_input_ids: Prompt tensor for decoder input - batch_size: Batch size for inference - context_encoder_frames: Context size configuration - - Returns: - Initialized AEDStreamingState object - """ - # initialize AED model state - model_state = AEDStreamingState(decoder_input_ids=decoder_input_ids, device=asr_model.device) - - model_state.frame_chunk_size = context_encoder_frames.chunk - model_state.batch_idxs = torch.arange(batch_size, dtype=torch.long, device=asr_model.device) - model_state.current_context_lengths = torch.zeros_like(model_state.batch_idxs) + decoder_input_ids.size(-1) - model_state.decoder_input_ids = decoder_input_ids[:batch_size] - model_state.pred_tokens_ids = torch.full( - [batch_size, model_state.max_generation_length], - asr_model.tokenizer.eos, - dtype=torch.long, - device=asr_model.device, - ) - model_state.pred_tokens_ids[:, : model_state.decoder_input_ids.size(-1)] = model_state.decoder_input_ids - model_state.tokens_frame_alignment = torch.zeros_like(model_state.pred_tokens_ids) - model_state.active_samples = torch.ones(batch_size, dtype=torch.bool, device=asr_model.device) - model_state.active_samples_inner_loop = torch.ones(batch_size, dtype=torch.bool, device=asr_model.device) - model_state.right_context = context_encoder_frames.right - model_state.eos_tokens = torch.full( - [batch_size], asr_model.tokenizer.eos, dtype=torch.long, device=asr_model.device - ) - model_state.avgpool2d = torch.nn.AvgPool2d(5, stride=1, padding=2, count_include_pad=False) - model_state.batch_size = batch_size - model_state.max_tokens_per_alignatt_step = model_state.max_tokens_per_one_second * int( - chunk_secs + right_context_secs - ) - - return model_state - - -def return_decoder_input_ids(decoding_config, asr_model) -> torch.Tensor: - """ - Obtain decoder input ids for decoding config. - """ - override_cfg = asr_model.get_transcribe_config() - override_cfg.prompt = parse_multitask_prompt(OmegaConf.to_container(decoding_config.prompt)) - - default_turns = asr_model.prompt.get_default_dialog_slots() - if not decoding_config.prompt: - # No turns were provided, use defaults. - turns = default_turns - else: - # Turns were provided, iterate over them and fill missing slot values using defaults.. - turns = override_cfg.prompt.copy() # shallow copy #1: don't override the config - for turn in turns: - role = turn["role"] - # Check if we have defaults for this role. - # There shouldn't be more than a single turn for a given role, but if there are, - # we'll emit a warning. - if default_turns_for_role := [t for t in default_turns if t["role"] == role]: - if len(default_turns_for_role) > 1: - logging.warning( - f"More than one default turn detected for {role=}. " - f"We'll be using default slot values for the first turn of {role=} only." - ) - default_slots = default_turns_for_role[0]["slots"] - turn["slots"] = turn["slots"].copy() # shallow copy #1: don't override the config - # fill missing slots using defaults - for slot, val in default_slots.items(): - if turn["slots"].get(slot) is None: - turn["slots"][slot] = val - - decoder_input_ids = ( - asr_model.prompt.encode_dialog(turns=turns)["context_ids"] - .unsqueeze(0) - .repeat(decoding_config.batch_size, 1) - .to(asr_model.device) - ) - - return decoder_input_ids diff --git a/nemo/collections/asr/parts/submodules/batchnorm.py b/nemo/collections/asr/parts/submodules/batchnorm.py deleted file mode 100644 index 66a69f761c14818a4b8f322e8eb643d80c711aa9..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/batchnorm.py +++ /dev/null @@ -1,103 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from __future__ import annotations - -from functools import reduce -from typing import List - -import torch -import torch.nn as nn - - -class FusedBatchNorm1d(nn.Module): - """ - Fused BatchNorm to use in Conformer to improve accuracy in finetuning with TTS scenario - Drop-in replacement for BatchNorm1d with simple affine projection - """ - - def __init__(self, num_features: int): - """ - Args: - num_features: number of channels, see original BatchNorm1d documentation - """ - super().__init__() - self.num_features = num_features - self.weight = nn.Parameter(torch.ones(num_features)) - self.bias = nn.Parameter(torch.zeros(num_features)) - - @classmethod - def from_batchnorm(cls, bn: nn.BatchNorm1d) -> FusedBatchNorm1d: - """ - Construct FusedBatchNorm1d module from BatchNorm1d - Args: - bn: original BatchNorm module - - Returns: - FusedBatchNorm1d module with initialized params; in eval mode result is equivalent to original BatchNorm - """ - assert isinstance(bn, nn.BatchNorm1d) - fused_bn = FusedBatchNorm1d(bn.num_features) - # init projection params from original batch norm - # so, for inference mode output is the same - std = torch.sqrt(bn.running_var.data + bn.eps) - fused_bn.weight.data = bn.weight.data / std - fused_bn.bias.data = bn.bias.data - bn.running_mean.data * fused_bn.weight.data - return fused_bn - - def forward(self, x: torch.Tensor): - if x.dim() == 3: - return x * self.weight.unsqueeze(-1) + self.bias.unsqueeze(-1) - assert x.dim() == 2 - return x * self.weight + self.bias - - -def _get_module_by_name(module: nn.Module, full_layer_name: str) -> nn.Module: - names = full_layer_name.split(sep='.') - return reduce(getattr, names, module) - - -def replace_bn_with_fused_bn(module: nn.Module, full_layer_name: str): - """ - Replace BatchNorm1d named `full_layer_name` in nn.Module with FusedBatchNorm1d - Args: - module: nn.Module instance, modified inplace - full_layer_name: name of BatchNorm1d submodule in module to replace - """ - bn = _get_module_by_name(module, full_layer_name) - assert isinstance(bn, nn.BatchNorm1d) - fused_bn = FusedBatchNorm1d.from_batchnorm(bn) - try: - parent_name, norm_name = full_layer_name.rsplit(".", maxsplit=1) - setattr(_get_module_by_name(module, parent_name), norm_name, fused_bn) - except ValueError: - norm_name = full_layer_name - setattr(module, norm_name, fused_bn) - - -def replace_bn_with_fused_bn_all(model: nn.Module) -> List[str]: - """ - Replace BatchNorm1d with FusedBatchNorm1d in model - Args: - model: nn.Module instance, modified inplace - - Returns: - list of replaced module names - """ - replaced_module_names = [] - for name, module in model.named_modules(): - if isinstance(module, nn.BatchNorm1d): - replace_bn_with_fused_bn(model, name) - replaced_module_names.append(name) - return replaced_module_names diff --git a/nemo/collections/asr/parts/submodules/causal_convs.py b/nemo/collections/asr/parts/submodules/causal_convs.py deleted file mode 100644 index 32f08a8d2feb463b2b46f5ee096a69e5047696f1..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/causal_convs.py +++ /dev/null @@ -1,150 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import Union - -import torch -import torch.nn.functional as F -from torch import nn - -__all__ = ['CausalConv2D', 'CausalConv1D'] - - -class CausalConv2D(nn.Conv2d): - """ - A causal version of nn.Conv2d where each location in the 2D matrix would have no access to locations on its right or down - All arguments are the same as nn.Conv2d except padding which should be set as None - """ - - def __init__( - self, - in_channels: int, - out_channels: int, - kernel_size: int, - stride: int = 1, - padding: Union[str, int] = 0, - dilation: int = 1, - groups: int = 1, - bias: bool = True, - padding_mode: str = 'zeros', - device=None, - dtype=None, - ) -> None: - if padding is not None: - raise ValueError("Argument padding should be set to None for CausalConv2D.") - self._left_padding = kernel_size - 1 - self._right_padding = stride - 1 - - padding = 0 - super(CausalConv2D, self).__init__( - in_channels, - out_channels, - kernel_size, - stride, - padding, - dilation, - groups, - bias, - padding_mode, - device, - dtype, - ) - - def forward( - self, x, - ): - x = F.pad(x, pad=(self._left_padding, self._right_padding, self._left_padding, self._right_padding)) - x = super().forward(x) - return x - - -class CausalConv1D(nn.Conv1d): - """ - A causal version of nn.Conv1d where each step would have limited access to locations on its right or left - All arguments are the same as nn.Conv1d except padding. - - If padding is set None, then paddings are set automatically to make it a causal convolution where each location would not see any steps on its right. - - If padding is set as a list (size of 2), then padding[0] would be used as left padding and padding[1] as right padding. - It would make it possible to control the number of steps to be accessible on the right and left. - This mode is not supported when stride > 1. padding[0]+padding[1] should be equal to (kernel_size - 1). - """ - - def __init__( - self, - in_channels: int, - out_channels: int, - kernel_size: int, - stride: int = 1, - padding: Union[str, int] = 0, - dilation: int = 1, - groups: int = 1, - bias: bool = True, - padding_mode: str = 'zeros', - device=None, - dtype=None, - ) -> None: - self.cache_drop_size = None - if padding is None: - self._left_padding = kernel_size - 1 - self._right_padding = stride - 1 - else: - if stride != 1 and padding != kernel_size - 1: - raise ValueError("No striding allowed for non-symmetric convolutions!") - if isinstance(padding, int): - self._left_padding = padding - self._right_padding = padding - elif isinstance(padding, list) and len(padding) == 2 and padding[0] + padding[1] == kernel_size - 1: - self._left_padding = padding[0] - self._right_padding = padding[1] - else: - raise ValueError(f"Invalid padding param: {padding}!") - - self._max_cache_len = self._left_padding - - super(CausalConv1D, self).__init__( - in_channels=in_channels, - out_channels=out_channels, - kernel_size=kernel_size, - stride=stride, - padding=0, - dilation=dilation, - groups=groups, - bias=bias, - padding_mode=padding_mode, - device=device, - dtype=dtype, - ) - - def update_cache(self, x, cache=None): - if cache is None: - new_x = F.pad(x, pad=(self._left_padding, self._right_padding)) - next_cache = cache - else: - new_x = F.pad(x, pad=(0, self._right_padding)) - new_x = torch.cat([cache, new_x], dim=-1) - if self.cache_drop_size > 0: - next_cache = new_x[:, :, : -self.cache_drop_size] - else: - next_cache = new_x - next_cache = next_cache[:, :, -cache.size(-1) :] - return new_x, next_cache - - def forward(self, x, cache=None): - x, cache = self.update_cache(x, cache=cache) - x = super().forward(x) - if cache is None: - return x - else: - return x, cache diff --git a/nemo/collections/asr/parts/submodules/classifier.py b/nemo/collections/asr/parts/submodules/classifier.py deleted file mode 100644 index 7d9e42593c1c2517ad2673028e56d7df71ed1925..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/classifier.py +++ /dev/null @@ -1,85 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import Dict, Optional - -import torch -from torch import nn as nn - -from nemo.collections.common.parts import transformer_weights_init -from nemo.core.classes import Exportable, NeuralModule -from nemo.core.neural_types import ChannelType, NeuralType - -__all__ = ['Classifier'] - - -class Classifier(NeuralModule, Exportable): - """ - A baseclass for modules to perform various classification tasks. - """ - - @property - def input_types(self) -> Optional[Dict[str, NeuralType]]: - """ - Returns definitions of module input ports. - We implement it here since all NLP classifiers have the same inputs - """ - return {"hidden_states": NeuralType(('B', 'T', 'D'), ChannelType())} - - def __init__(self, hidden_size: int, dropout: float = 0.0,) -> None: - """ - Initializes the Classifier base module. - Args: - hidden_size: the size of the hidden dimension - dropout: dropout to apply to the input hidden states - """ - super().__init__() - self._hidden_size = hidden_size - self.dropout = nn.Dropout(dropout) - - def post_init(self, use_transformer_init: bool): - """ - Common post-processing to be called at the end of concrete Classifiers init methods - Args: - use_transformer_init : whether or not to apply transformer_weights_init - """ - if use_transformer_init: - self.apply(lambda module: transformer_weights_init(module, xavier=False)) - - def input_example(self, max_batch=1, max_dim=256): - """ - Generates input examples for tracing etc. - Returns: - A tuple of input examples. - """ - sample = next(self.parameters()) - example = torch.randn(max_batch, max_dim, self._hidden_size).to(sample.device).to(sample.dtype) - return tuple([example]) - - def save_to(self, save_path: str): - """ - Saves the module to the specified path. - Args: - save_path: Path to where to save the module. - """ - pass - - @classmethod - def restore_from(cls, restore_path: str): - """ - Restores the module from the specified path. - Args: - restore_path: Path to restore the module from. - """ - pass diff --git a/nemo/collections/asr/parts/submodules/conformer_modules.py b/nemo/collections/asr/parts/submodules/conformer_modules.py deleted file mode 100644 index b3098ad89ffe0cefde84227cb18794eaa8f7dfab..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/conformer_modules.py +++ /dev/null @@ -1,397 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import torch -from torch import nn as nn -from torch.nn import LayerNorm - -from nemo.collections.asr.parts.submodules.adapters.attention_adapter_mixin import AttentionAdapterModuleMixin -from nemo.collections.asr.parts.submodules.batchnorm import FusedBatchNorm1d -from nemo.collections.asr.parts.submodules.causal_convs import CausalConv1D -from nemo.collections.asr.parts.submodules.multi_head_attention import ( - MultiHeadAttention, - RelPositionMultiHeadAttention, - RelPositionMultiHeadAttentionLongformer, -) -from nemo.collections.asr.parts.utils.activations import Swish -from nemo.collections.common.parts.utils import activation_registry -from nemo.core.classes.mixins import AccessMixin - -__all__ = ['ConformerConvolution', 'ConformerFeedForward', 'ConformerLayer'] - - -class ConformerLayer(torch.nn.Module, AttentionAdapterModuleMixin, AccessMixin): - """A single block of the Conformer encoder. - - Args: - d_model (int): input dimension of MultiheadAttentionMechanism and PositionwiseFeedForward - d_ff (int): hidden dimension of PositionwiseFeedForward - self_attention_model (str): type of the attention layer and positional encoding - 'rel_pos': relative positional embedding and Transformer-XL - 'rel_pos_local_attn': relative positional embedding and Transformer-XL with local attention using - overlapping chunks. Attention context is determined by att_context_size parameter. - 'abs_pos': absolute positional embedding and Transformer - Default is rel_pos. - global_tokens (int): number of tokens to be used for global attention. - Only relevant if self_attention_model is 'rel_pos_local_attn'. - Defaults to 0. - global_tokens_spacing (int): how far apart the global tokens are - Defaults to 1. - global_attn_separate (bool): whether the q, k, v layers used for global tokens should be separate. - Defaults to False. - n_heads (int): number of heads for multi-head attention - conv_kernel_size (int): kernel size for depthwise convolution in convolution module - dropout (float): dropout probabilities for linear layers - dropout_att (float): dropout probabilities for attention distributions - use_bias (bool): Apply bias to all Linear and Conv1d layers from each ConformerLayer to improve activation flow and stabilize training of huge models. - Defaults to True. - """ - - def __init__( - self, - d_model, - d_ff, - self_attention_model='rel_pos', - global_tokens=0, - global_tokens_spacing=1, - global_attn_separate=False, - n_heads=4, - conv_kernel_size=31, - conv_norm_type='batch_norm', - conv_context_size=None, - dropout=0.1, - dropout_att=0.1, - pos_bias_u=None, - pos_bias_v=None, - att_context_size=[-1, -1], - use_bias=True, - use_pytorch_sdpa=False, - use_pytorch_sdpa_backends=None, - ): - super(ConformerLayer, self).__init__() - - self.use_pytorch_sdpa = use_pytorch_sdpa - if use_pytorch_sdpa_backends is None: - use_pytorch_sdpa_backends = [] - self.use_pytorch_sdpa_backends = use_pytorch_sdpa_backends - self.self_attention_model = self_attention_model - self.n_heads = n_heads - self.fc_factor = 0.5 - - # first feed forward module - self.norm_feed_forward1 = LayerNorm(d_model) - self.feed_forward1 = ConformerFeedForward(d_model=d_model, d_ff=d_ff, dropout=dropout, use_bias=use_bias) - - # convolution module - self.norm_conv = LayerNorm(d_model) - self.conv = ConformerConvolution( - d_model=d_model, - kernel_size=conv_kernel_size, - norm_type=conv_norm_type, - conv_context_size=conv_context_size, - use_bias=use_bias, - ) - - # multi-headed self-attention module - self.norm_self_att = LayerNorm(d_model) - MHA_max_cache_len = att_context_size[0] - - if self_attention_model == 'rel_pos': - self.self_attn = RelPositionMultiHeadAttention( - n_head=n_heads, - n_feat=d_model, - dropout_rate=dropout_att, - pos_bias_u=pos_bias_u, - pos_bias_v=pos_bias_v, - max_cache_len=MHA_max_cache_len, - use_bias=use_bias, - use_pytorch_sdpa=self.use_pytorch_sdpa, - use_pytorch_sdpa_backends=self.use_pytorch_sdpa_backends, - ) - elif self_attention_model == 'rel_pos_local_attn': - self.self_attn = RelPositionMultiHeadAttentionLongformer( - n_head=n_heads, - n_feat=d_model, - dropout_rate=dropout_att, - pos_bias_u=pos_bias_u, - pos_bias_v=pos_bias_v, - max_cache_len=MHA_max_cache_len, - att_context_size=att_context_size, - global_tokens=global_tokens, - global_tokens_spacing=global_tokens_spacing, - global_attn_separate=global_attn_separate, - use_bias=use_bias, - ) - elif self_attention_model == 'abs_pos': - self.self_attn = MultiHeadAttention( - n_head=n_heads, - n_feat=d_model, - dropout_rate=dropout_att, - max_cache_len=MHA_max_cache_len, - use_bias=use_bias, - use_pytorch_sdpa=self.use_pytorch_sdpa, - use_pytorch_sdpa_backends=self.use_pytorch_sdpa_backends, - ) - else: - raise ValueError( - f"'{self_attention_model}' is not not a valid value for 'self_attention_model', " - f"valid values can be from ['rel_pos', 'rel_pos_local_attn', 'abs_pos']" - ) - - # second feed forward module - self.norm_feed_forward2 = LayerNorm(d_model) - self.feed_forward2 = ConformerFeedForward(d_model=d_model, d_ff=d_ff, dropout=dropout, use_bias=use_bias) - - self.dropout = nn.Dropout(dropout) - self.norm_out = LayerNorm(d_model) - - def forward(self, x, att_mask=None, pos_emb=None, pad_mask=None, cache_last_channel=None, cache_last_time=None): - """ - Args: - x (torch.Tensor): input signals (B, T, d_model) - att_mask (torch.Tensor): attention masks(B, T, T) - pos_emb (torch.Tensor): (L, 1, d_model) - pad_mask (torch.tensor): padding mask - cache_last_channel (torch.tensor) : cache for MHA layers (B, T_cache, d_model) - cache_last_time (torch.tensor) : cache for convolutional layers (B, d_model, T_cache) - Returns: - x (torch.Tensor): (B, T, d_model) - cache_last_channel (torch.tensor) : next cache for MHA layers (B, T_cache, d_model) - cache_last_time (torch.tensor) : next cache for convolutional layers (B, d_model, T_cache) - """ - residual = x - x = self.norm_feed_forward1(x) - x = self.feed_forward1(x) - residual = residual + self.dropout(x) * self.fc_factor - - x = self.norm_self_att(residual) - if self.self_attention_model == 'rel_pos': - x = self.self_attn(query=x, key=x, value=x, mask=att_mask, pos_emb=pos_emb, cache=cache_last_channel) - elif self.self_attention_model == 'rel_pos_local_attn': - x = self.self_attn(query=x, key=x, value=x, pad_mask=pad_mask, pos_emb=pos_emb, cache=cache_last_channel) - elif self.self_attention_model == 'abs_pos': - x = self.self_attn(query=x, key=x, value=x, mask=att_mask, cache=cache_last_channel) - else: - x = None - - if x is not None and cache_last_channel is not None: - (x, cache_last_channel) = x - - residual = residual + self.dropout(x) - - if self.is_adapter_available(): - # Call the MHA adapters - pack_input = { - 'x': residual, - 'loc': 'mha', - 'att_mask': att_mask, - 'pos_emb': pos_emb, - } - pack_input = self.forward_enabled_adapters(pack_input) - residual = pack_input['x'] - - x = self.norm_conv(residual) - x = self.conv(x, pad_mask=pad_mask, cache=cache_last_time) - if cache_last_time is not None: - (x, cache_last_time) = x - residual = residual + self.dropout(x) - - x = self.norm_feed_forward2(residual) - x = self.feed_forward2(x) - residual = residual + self.dropout(x) * self.fc_factor - - x = self.norm_out(residual) - - if self.is_adapter_available(): - # Call the adapters - pack_input = { - 'x': x, - 'loc': 'post', - } - pack_input = self.forward_enabled_adapters(pack_input) - x = pack_input['x'] - - if self.is_access_enabled(getattr(self, "model_guid", None)) and self.access_cfg.get( - 'save_encoder_tensors', False - ): - self.register_accessible_tensor(name='encoder', tensor=x) - if cache_last_channel is None: - return x - else: - return x, cache_last_channel, cache_last_time - - -class ConformerConvolution(nn.Module): - """The convolution module for the Conformer model. - Args: - d_model (int): hidden dimension - kernel_size (int): kernel size for depthwise convolution - pointwise_activation (str): name of the activation function to be used for the pointwise conv. - Note that Conformer uses a special key `glu_` which is treated as the original default from - the paper. - use_bias (bool): Use bias in all Linear and Conv1d layers improve activation flow and stabilize training of huge models. - Defaults to True - """ - - def __init__( - self, - d_model, - kernel_size, - norm_type='batch_norm', - conv_context_size=None, - pointwise_activation='glu_', - use_bias=True, - ): - super(ConformerConvolution, self).__init__() - assert (kernel_size - 1) % 2 == 0 - self.d_model = d_model - self.kernel_size = kernel_size - self.norm_type = norm_type - self.use_bias = use_bias - - if conv_context_size is None: - conv_context_size = (kernel_size - 1) // 2 - - if pointwise_activation in activation_registry: - self.pointwise_activation = activation_registry[pointwise_activation]() - dw_conv_input_dim = d_model * 2 - - if hasattr(self.pointwise_activation, 'inplace'): - self.pointwise_activation.inplace = True - else: - self.pointwise_activation = pointwise_activation - dw_conv_input_dim = d_model - - self.pointwise_conv1 = nn.Conv1d( - in_channels=d_model, - out_channels=d_model * 2, - kernel_size=1, - stride=1, - padding=0, - bias=self.use_bias, - ) - - self.depthwise_conv = CausalConv1D( - in_channels=dw_conv_input_dim, - out_channels=dw_conv_input_dim, - kernel_size=kernel_size, - stride=1, - padding=conv_context_size, - groups=dw_conv_input_dim, - bias=self.use_bias, - ) - - if norm_type == 'batch_norm': - self.batch_norm = nn.BatchNorm1d(dw_conv_input_dim) - elif norm_type == 'instance_norm': - self.batch_norm = nn.InstanceNorm1d(dw_conv_input_dim) - elif norm_type == 'layer_norm': - self.batch_norm = nn.LayerNorm(dw_conv_input_dim) - elif norm_type == 'fused_batch_norm': - self.batch_norm = FusedBatchNorm1d(dw_conv_input_dim) - elif norm_type.startswith('group_norm'): - num_groups = int(norm_type.replace("group_norm", "")) - self.batch_norm = nn.GroupNorm(num_groups=num_groups, num_channels=d_model) - else: - raise ValueError(f"conv_norm_type={norm_type} is not valid!") - - self.activation = Swish() - self.pointwise_conv2 = nn.Conv1d( - in_channels=dw_conv_input_dim, - out_channels=d_model, - kernel_size=1, - stride=1, - padding=0, - bias=self.use_bias, - ) - - def forward(self, x, pad_mask=None, cache=None): - x = x.transpose(1, 2) - x = self.pointwise_conv1(x) - - # Compute the activation function or use GLU for original Conformer - if self.pointwise_activation == 'glu_': - x = nn.functional.glu(x, dim=1) - else: - x = self.pointwise_activation(x) - - if pad_mask is not None: - x = x.masked_fill(pad_mask.unsqueeze(1), 0.0) - - x = self.depthwise_conv(x, cache=cache) - if cache is not None: - x, cache = x - - if self.norm_type == "layer_norm": - x = x.transpose(1, 2) - x = self.batch_norm(x) - x = x.transpose(1, 2) - else: - x = self.batch_norm(x) - - x = self.activation(x) - x = self.pointwise_conv2(x) - x = x.transpose(1, 2) - if cache is None: - return x - else: - return x, cache - - def reset_parameters_conv(self): - pw1_max = pw2_max = self.d_model**-0.5 - dw_max = self.kernel_size**-0.5 - - with torch.no_grad(): - nn.init.uniform_(self.pointwise_conv1.weight, -pw1_max, pw1_max) - nn.init.uniform_(self.pointwise_conv2.weight, -pw2_max, pw2_max) - nn.init.uniform_(self.depthwise_conv.weight, -dw_max, dw_max) - if self.use_bias: - nn.init.uniform_(self.pointwise_conv1.bias, -pw1_max, pw1_max) - nn.init.uniform_(self.pointwise_conv2.bias, -pw2_max, pw2_max) - nn.init.uniform_(self.depthwise_conv.bias, -dw_max, dw_max) - - -class ConformerFeedForward(nn.Module): - """ - feed-forward module of Conformer model. - use_bias (bool): Apply bias to all Linear and Conv1d layers improve activation flow and stabilize training of huge models. - """ - - def __init__(self, d_model, d_ff, dropout, activation=Swish(), use_bias=True): - super(ConformerFeedForward, self).__init__() - self.d_model = d_model - self.d_ff = d_ff - self.use_bias = use_bias - self.linear1 = nn.Linear(d_model, d_ff, bias=self.use_bias) - self.activation = activation - self.dropout = nn.Dropout(p=dropout) - self.linear2 = nn.Linear(d_ff, d_model, bias=self.use_bias) - - def forward(self, x): - x = self.linear1(x) - x = self.activation(x) - x = self.dropout(x) - x = self.linear2(x) - return x - - def reset_parameters_ff(self): - ffn1_max = self.d_model**-0.5 - ffn2_max = self.d_ff**-0.5 - with torch.no_grad(): - nn.init.uniform_(self.linear1.weight, -ffn1_max, ffn1_max) - nn.init.uniform_(self.linear2.weight, -ffn2_max, ffn2_max) - if self.use_bias: - nn.init.uniform_(self.linear1.bias, -ffn1_max, ffn1_max) - nn.init.uniform_(self.linear2.bias, -ffn2_max, ffn2_max) diff --git a/nemo/collections/asr/parts/submodules/ctc_batched_beam_decoding.py b/nemo/collections/asr/parts/submodules/ctc_batched_beam_decoding.py deleted file mode 100644 index 66165100f3ad8c10c87ad9359b46e3d3f66ad2fb..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/ctc_batched_beam_decoding.py +++ /dev/null @@ -1,751 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from dataclasses import dataclass, field -from typing import List, Optional, Union - -import numpy as np -import torch - -from nemo.collections.asr.parts.context_biasing import GPUBoostingTreeModel -from nemo.collections.asr.parts.submodules.ngram_lm import NGramGPULanguageModel -from nemo.collections.asr.parts.utils.asr_confidence_utils import ConfidenceMethodMixin -from nemo.collections.asr.parts.utils.batched_beam_decoding_utils import BatchedBeamHyps -from nemo.collections.common.parts.optional_cuda_graphs import WithOptionalCudaGraphs -from nemo.core.utils.cuda_python_utils import ( - NeMoCUDAPythonException, - check_cuda_python_cuda_graphs_conditional_nodes_supported, - cu_call, - run_nvrtc, - with_conditional_node, -) -from nemo.core.utils.optional_libs import CUDA_PYTHON_AVAILABLE, cuda_python_required -from nemo.utils import logging -from nemo.utils.enum import PrettyStrEnum - -if CUDA_PYTHON_AVAILABLE: - from cuda.bindings import runtime as cudart - - -NON_EXISTENT_LABEL_VALUE = -1 -INACTIVE_SCORE = float("-inf") - - -class BacthedBeamCTCState: - """ - State for Batched Beam Search for CTC models. Used only with CUDA graphs. - In initialization phase it is possible to assign values (tensors) to the state. - For algorithm code the storage should be reused (prefer copy data instead of assigning tensors). - """ - - max_time: int # maximum length of internal storage for time dimension - batch_size: int # (maximum) length of internal storage for batch dimension - device: torch.device # device to store preallocated tensors - beam_size: int # (maximum) length of internal storage for beam dimension - blank_index: int # the index of the blank token - - decoder_outputs: torch.Tensor # logprobs from decoder - decoder_output_lengths: torch.Tensor # lengths of the decoder outputs (i.e. max time for each utterance) - last_timesteps: torch.Tensor # last time step for each utterance (used to check if the decoding is finished) - - vocab: torch.Tensor # vocabulary of the model. Constant - vocab_blank_mask: torch.Tensor # mask for blank token in the vocabulary. Constant - - curr_frame_idx: torch.Tensor # current frame index for each utterance (used to check if the decoding is finished) - active_mask: torch.Tensor # mask for active hypotheses (the decoding is finished for the utterance if it is False) - active_mask_any: torch.Tensor # 0-dim bool tensor, condition for outer loop ('any element is still active') - - batched_hyps: BatchedBeamHyps # batched hypotheses - decoding result - - # fusion models related fields - fusion_models: Optional[List[NGramGPULanguageModel]] = None - fusion_states_list: Optional[List[torch.Tensor]] = None - fusion_states_candidates_list: Optional[List[torch.Tensor]] = None - - def __init__( - self, - batch_size: int, - beam_size: int, - max_time: int, - vocab_size: int, - device: torch.device, - float_dtype: torch.dtype, - blank_index: int, - ): - """ - Args: - batch_size: batch size for encoder output storage - beam_size: beam size for decoder output storage - max_time: maximum time for encoder output storage - vocab_size: vocabulary size of the model including blank - device: device to store tensors - float_dtype: default float dtype for tensors (should match projected encoder output) - blank_index: index of the blank symbol - """ - - self.device = device - self.float_dtype = float_dtype - self.batch_size = batch_size - self.beam_size = beam_size - self.max_time = max_time - self.blank_index = blank_index - self.vocab_size = vocab_size - - self.NON_EXISTENT_LABEL = torch.tensor(NON_EXISTENT_LABEL_VALUE, device=self.device, dtype=torch.long) - self.BLANK_TENSOR = torch.tensor(self.blank_index, device=self.device, dtype=torch.long) - self.INACTIVE_SCORE = torch.tensor(INACTIVE_SCORE, device=self.device, dtype=float_dtype) - - self.decoder_outputs = torch.zeros( - (self.batch_size, self.max_time, self.vocab_size), - dtype=float_dtype, - device=self.device, - ) - self.decoder_output_lengths = torch.zeros( - (self.batch_size, self.beam_size), dtype=torch.long, device=self.device - ) - self.last_timesteps = torch.zeros((self.batch_size, self.beam_size), dtype=torch.long, device=self.device) - - self.vocab = torch.arange(self.vocab_size, device=self.device, dtype=torch.long) - self.vocab_blank_mask = torch.eq(self.vocab, self.blank_index) - - self.curr_frame_idx = torch.zeros([self.beam_size], device=self.device, dtype=torch.long) - self.active_mask = torch.zeros((batch_size, self.beam_size), device=self.device, dtype=torch.bool) - self.active_mask_any = torch.tensor(True, device=self.device, dtype=torch.bool) - - self.batched_hyps = BatchedBeamHyps( - batch_size=batch_size, - beam_size=self.beam_size, - blank_index=self.blank_index, - init_length=max_time + 1, - device=device, - float_dtype=float_dtype, - model_type='ctc', - ) - - def need_reinit(self, encoder_output_projected: torch.Tensor) -> bool: - """Check if need to reinit state: larger batch_size/max_time, or new device""" - return ( - self.batch_size < encoder_output_projected.shape[0] - or self.max_time < encoder_output_projected.shape[1] - or self.device.index != encoder_output_projected.device.index - ) - - -@dataclass -class SeparateGraphsBatchedBeamCTC: - """Class to store Cuda graphs for decoding when separate graphs are used""" - - _before_process_batch: torch.cuda.CUDAGraph = field(default_factory=torch.cuda.CUDAGraph) - _process_batch: torch.cuda.CUDAGraph = field(default_factory=torch.cuda.CUDAGraph) - _after_process_batch: torch.cuda.CUDAGraph = field(default_factory=torch.cuda.CUDAGraph) - - -class BatchedBeamCTCComputer(WithOptionalCudaGraphs, ConfidenceMethodMixin): - """ - Batched beam search implementation for CTC models. - """ - - INITIAL_MAX_TIME = 375 # initial max time, used to init state for Cuda graphs - CUDA_PROGRAM_NAME = b"while_beam_batch_conditional_ctc.cu" - - class CudaGraphsMode(PrettyStrEnum): - FULL_GRAPH = "full_graph" # Cuda graphs with conditional nodes, fastest implementation - NO_WHILE_LOOPS = "no_while_loops" # Decoding with PyTorch while loops + partial Cuda graphs - NO_GRAPHS = "no_graphs" # decoding without graphs, stateful implementation, only for testing purposes - - separate_graphs: Optional[SeparateGraphsBatchedBeamCTC] - full_graph: Optional[torch.cuda.CUDAGraph] - cuda_graphs_mode: Optional[CudaGraphsMode] - state: Optional[BacthedBeamCTCState] - fusion_models: Optional[List[NGramGPULanguageModel]] - fusion_models_alpha: Optional[List[float]] - - def __init__( - self, - blank_index: int, - beam_size: int, - return_best_hypothesis: bool = True, - preserve_alignments=False, - compute_timestamps: bool = False, - fusion_models: List[NGramGPULanguageModel] = None, - fusion_models_alpha: List[float] = None, - beam_beta: float = 0.0, - beam_threshold: float = 20.0, - allow_cuda_graphs: bool = True, - ): - """ - Init method. - Args: - blank_index: index of blank symbol. - beam_size: beam size. - return_best_hypothesis: whether to return the best hypothesis or N-best hypotheses. - preserve_alignments: if alignments are needed. Defaults to False. - compute_timestamps: if timestamps are needed. Defaults to False. - fusion_models: list of fusion models. - fusion_models_alpha: list of weights for the fusion models. - beam_beta: word insertion weight. - beam_threshold: threshold for pruning candidates. - allow_cuda_graphs: whether to allow CUDA graphs. Defaults to True. - """ - - super().__init__() - self._blank_index = blank_index - - self.beam_size = beam_size - self.preserve_alignments = preserve_alignments - self.compute_timestamps = compute_timestamps - self.allow_cuda_graphs = allow_cuda_graphs - self.return_best_hypothesis = return_best_hypothesis - - self.beam_beta = beam_beta - self.beam_threshold = beam_threshold - - assert not self.preserve_alignments, "Preserve aligments is not supported" - - self.state = None - self.full_graph = None - self.separate_graphs = None - - self.cuda_graphs_mode = None - self.cuda_graphs_allow_fallback = True - self.maybe_enable_cuda_graphs() - - self.fusion_models = fusion_models - self.fusion_models_alpha = fusion_models_alpha - - def force_cuda_graphs_mode(self, mode: Optional[Union[str, CudaGraphsMode]]): - """ - Method to set graphs mode. Use only for testing purposes. - For debugging the algorithm use "no_graphs" mode, since it is impossible to debug CUDA graphs directly. - """ - self.cuda_graphs_mode = self.CudaGraphsMode(mode) if mode is not None else None - self.cuda_graphs_allow_fallback = False - self.state = None - - def maybe_enable_cuda_graphs(self) -> bool: - """Enable CUDA graphs if conditions met""" - if self.cuda_graphs_mode is not None: - # CUDA graphs are already enabled - return False - - if not self.allow_cuda_graphs: - self.cuda_graphs_mode = None - else: - # cuda graphs are allowed - # check while loops - try: - check_cuda_python_cuda_graphs_conditional_nodes_supported() - self.cuda_graphs_mode = self.CudaGraphsMode.FULL_GRAPH - except (ImportError, ModuleNotFoundError, EnvironmentError) as e: - logging.warning( - "No conditional node support for Cuda.\n" - "Cuda graphs with while loops are disabled, decoding speed will be slower\n" - f"Reason: {e}" - ) - self.cuda_graphs_mode = self.CudaGraphsMode.NO_GRAPHS - self.reset_cuda_graphs_state() - return self.cuda_graphs_mode is not None - - def disable_cuda_graphs(self) -> bool: - """Disable CUDA graphs, can be used to disable graphs temporary, e.g., in training process""" - if self.cuda_graphs_mode is None: - # nothing to disable - return False - self.cuda_graphs_mode = None - self.reset_cuda_graphs_state() - return True - - def reset_cuda_graphs_state(self): - """Reset state to release memory (for CUDA graphs implementations)""" - self.state = None - self.full_graph = None - self.separate_graphs = None - - @torch.no_grad() - def batched_beam_search_torch( - self, decoder_outputs: torch.Tensor, decoder_output_lengths: torch.Tensor - ) -> BatchedBeamHyps: - """ - Pure PyTorch implementation of the batched beam search algorithm. - - Args: - decoder_outputs (torch.Tensor): Tensor of shape [B, T, V+1], where B is the batch size, - T is the maximum sequence length, and V is the vocabulary size. The tensor contains log-probabilities. - decoder_output_lengths (torch.Tensor): Tensor of shape [B], contains lengths of each sequence in the batch. - Returns: - A list of NBestHypotheses objects, one for each sequence in the batch. - """ - - curr_batch_size, curr_max_time, vocab_size = decoder_outputs.shape - - vocab = torch.arange(vocab_size, device=decoder_outputs.device, dtype=torch.long) - vocab_blank_mask = vocab == self._blank_index - - batched_beam_hyps = BatchedBeamHyps( - batch_size=curr_batch_size, - beam_size=self.beam_size, - blank_index=self._blank_index, - init_length=curr_max_time + 1, - device=decoder_outputs.device, - float_dtype=decoder_outputs.dtype, - model_type='ctc', - ) - - # init fusion models - if self.fusion_models is not None: - fusion_states_list = [] - fusion_states_candidates_list = [] - for fusion_model in self.fusion_models: - fusion_model.to(decoder_outputs.device) - fusion_states_list.append( - fusion_model.get_init_states(batch_size=curr_batch_size * self.beam_size, bos=True) - ) - fusion_states_candidates_list.append(None) - - for frame_idx in range(curr_max_time): - active_mask = frame_idx < decoder_output_lengths.unsqueeze(1) - repeated_mask = batched_beam_hyps.last_label[:, :, None] == vocab[None, None, :] - repeated_or_blank_mask = repeated_mask | vocab_blank_mask[None, None, :] - - # step 2.1: getting the log probs and updating with fusion scores - log_probs = decoder_outputs[:, frame_idx, :].unsqueeze(1).repeat(1, self.beam_size, 1) - log_probs += batched_beam_hyps.scores.unsqueeze(-1) - - # step 2.2: updating non-blank and non-repeating token scores with `beam_beta` - log_probs = torch.where(repeated_or_blank_mask, log_probs, log_probs + self.beam_beta) - - if self.fusion_models is not None: - for fusion_idx, fusion_model in enumerate(self.fusion_models): - fusion_scores, fusion_states_candidates = fusion_model.advance( - states=fusion_states_list[fusion_idx].view(-1) - ) - fusion_scores = torch.where( - repeated_mask[..., :-1], 0, fusion_scores.view(curr_batch_size, self.beam_size, -1) - ) - log_probs[..., :-1] += self.fusion_models_alpha[fusion_idx] * fusion_scores.view( - curr_batch_size, self.beam_size, -1 - ) - fusion_states_candidates_list[fusion_idx] = fusion_states_candidates - - # step 2.3: getting `beam_size` best candidates - next_scores, next_candidates_indices = torch.topk( - log_probs.view(curr_batch_size, -1), k=self.beam_size, largest=True, sorted=True - ) - next_indices = next_candidates_indices // vocab_size - next_labels = next_candidates_indices % vocab_size - - # step 2.3: pruning candidates with threshold `beam_threshold` - batch_next_scores = next_scores.view(curr_batch_size, -1) - max_next_score = batch_next_scores.max(dim=-1, keepdim=True).values - batch_next_scores.masked_fill_(batch_next_scores <= max_next_score - self.beam_threshold, INACTIVE_SCORE) - next_scores.view(curr_batch_size, self.beam_size, -1) - - # step 2.4: preserving updated fusion states - if self.fusion_models is not None: - last_labels = torch.gather(batched_beam_hyps.last_label, dim=-1, index=next_indices) - blank_mask = next_labels == self._blank_index - repeating_mask = next_labels == last_labels - preserve_state_mask = repeating_mask | blank_mask | ~active_mask - - # step 2.4.1: masking blanks and inactive labels to pass to fusion models, as fusion models do not support blanks - next_labels_masked = torch.where(blank_mask, 0, next_labels) - - # step 2.4.2: gathering fusion states of extended hypotheses - # batch_fusion_states: [(BxBeam)] - # batch_fusion_states_candidates: [(BxBeam) x V (without blank)] - - for fusion_idx, fusion_model in enumerate(self.fusion_models): - next_indices_extended = next_indices[:, :, None].expand( - curr_batch_size, self.beam_size, fusion_states_candidates_list[fusion_idx].shape[-1] - ) - fusion_states_candidates = fusion_states_candidates_list[fusion_idx].view( - curr_batch_size, self.beam_size, -1 - ) - fusion_states_candidates = torch.gather( - fusion_states_candidates, dim=1, index=next_indices_extended - ) - fusion_states_prev = torch.gather( - fusion_states_list[fusion_idx].view(curr_batch_size, self.beam_size), dim=1, index=next_indices - ) - fusion_states = torch.gather( - fusion_states_candidates, dim=-1, index=next_labels_masked.unsqueeze(-1) - ).squeeze(-1) - - fusion_states_list[fusion_idx] = torch.where( - preserve_state_mask, fusion_states_prev, fusion_states - ).view(-1) - - # step 2.5: masking inactive hypotheses, updating + recombining batched beam hypoteses - next_labels = torch.where(active_mask, next_labels, NON_EXISTENT_LABEL_VALUE) - batched_beam_hyps.add_results_(next_indices, next_labels, next_scores) - batched_beam_hyps.recombine_hyps_() - - # step 3: updating fusoin scores with eos scores - if self.fusion_models is not None: - for fusion_idx, fusion_model in enumerate(self.fusion_models): - # only GPUBoostingTreeModel does not support eos scores for CTC models by default - if not isinstance(fusion_model, GPUBoostingTreeModel): - eos_score = fusion_model.get_final(fusion_states_list[fusion_idx]).view( - batched_beam_hyps.scores.shape - ) - batched_beam_hyps.scores += eos_score * self.fusion_models_alpha[fusion_idx] - - return batched_beam_hyps - - def batched_beam_search_cuda_graphs( - self, - decoder_outputs: torch.Tensor, - decoder_output_lengths: torch.Tensor, - ) -> BatchedBeamHyps: - """ - Cuda-Graphs implementation of the batched beam search algorithm. - - Args: - decoder_outputs (torch.Tensor): Tensor of shape [B, T, V+1], where B is the batch size, - T is the maximum sequence length, and V is the vocabulary size. The tensor contains log-probabilities. - decoder_output_lengths (torch.Tensor): Tensor of shape [B], contains lengths of each sequence in the batch. - Returns: - A list of NBestHypotheses objects, one for each sequence in the batch. - """ - - assert self.cuda_graphs_mode is not None - - curr_batch_size, curr_max_time, _ = decoder_outputs.shape - - if torch.is_autocast_enabled(): - decoder_outputs = decoder_outputs.to(torch.get_autocast_gpu_dtype()) - - # init or reinit graph - if self.state is None or self.state.need_reinit(decoder_outputs): - self._graph_reinitialize(decoder_outputs, decoder_output_lengths) - - # set length to zero for elements outside the current batch - self.state.decoder_output_lengths.fill_(0) - # copy (projected) encoder output and lenghts - self.state.decoder_outputs[:curr_batch_size, :curr_max_time, ...].copy_(decoder_outputs) - self.state.decoder_output_lengths[:curr_batch_size].copy_(decoder_output_lengths.unsqueeze(-1)) - if self.cuda_graphs_mode is self.CudaGraphsMode.FULL_GRAPH: - self.full_graph.replay() - elif self.cuda_graphs_mode is self.CudaGraphsMode.NO_WHILE_LOOPS: - self.separate_graphs._before_process_batch.replay() - while self.state.active_mask_any.item(): - self.separate_graphs._process_batch.replay() - self.separate_graphs._after_process_batch.replay() - elif self.cuda_graphs_mode is self.CudaGraphsMode.NO_GRAPHS: - # this mode is only for testing purposes - # manual loop instead of using graphs - self._before_process_batch() - while self.state.active_mask_any.item(): - self._process_batch() - self._after_process_batch() - else: - raise NotImplementedError(f"Unknown graph mode: {self.cuda_graphs_mode}") - - return self.state.batched_hyps - - @classmethod - def _create_process_batch_kernel(cls): - """ - Creates a kernel that evaluates whether to enter the outer loop body (not all hypotheses are decoded). - Condition: while(active_mask_any). - """ - kernel_string = r"""\ - typedef __device_builtin__ unsigned long long cudaGraphConditionalHandle; - - extern "C" __device__ __cudart_builtin__ void cudaGraphSetConditional(cudaGraphConditionalHandle handle, unsigned int value); - - extern "C" __global__ - void loop_conditional(cudaGraphConditionalHandle handle, const bool *active_mask_any) - { - cudaGraphSetConditional(handle, *active_mask_any); - } - """ - return run_nvrtc(kernel_string, b"loop_conditional", cls.CUDA_PROGRAM_NAME) - - def _graph_reinitialize( - self, - decoder_outputs: torch.Tensor, - decoder_output_lengths: torch.Tensor, - ): - """ - Reinitializes the graph state for the Beam Search computation. - This method sets up the internal state required for the decoding process, including initializing - decoder outputs, decoder states, and optional n-gram language model states. It also handles CUDA - graph compilation based on the specified mode. - Args: - encoder_output_projected (torch.Tensor): The projected encoder output tensor of shape - (batch_size, max_time, encoder_dim). - encoder_output_length (torch.Tensor): The lengths of the encoder outputs for each batch. - Raises: - NotImplementedError: If an unsupported CUDA graph mode is specified. - """ - - batch_size, max_time, vocab_size = decoder_outputs.shape - - self.state = BacthedBeamCTCState( - batch_size=batch_size, - beam_size=self.beam_size, - max_time=max(max_time, self.INITIAL_MAX_TIME), - vocab_size=vocab_size, - device=decoder_outputs.device, - float_dtype=decoder_outputs.dtype, - blank_index=self._blank_index, - ) - - # init fusion models - if self.fusion_models is not None: - self.state.fusion_states_list = [] - self.state.fusion_states_candidates_list = [] - for fusion_model in self.fusion_models: - fusion_model.to(decoder_outputs.device) - self.state.fusion_states_list.append( - fusion_model.get_init_states(batch_size=batch_size * self.beam_size, bos=True).view( - batch_size, self.beam_size - ) - ) - self.state.fusion_states_candidates_list.append( - torch.zeros([batch_size, fusion_model.vocab_size], dtype=torch.long, device=self.state.device) - ) - - if self.cuda_graphs_mode is self.CudaGraphsMode.FULL_GRAPH: - try: - self._full_graph_compile() - except NeMoCUDAPythonException as e: - if not self.cuda_graphs_allow_fallback: - raise RuntimeError("Full CUDA graph decoding failed. Mode is forced, raising exception") from e - logging.warning( - f"Full CUDA graph compilation failed: {e}. " - "Falling back to native PyTorch CUDA graphs. Decoding will be slower." - ) - self.cuda_graphs_mode = self.CudaGraphsMode.NO_WHILE_LOOPS - self._partial_graphs_compile() - elif self.cuda_graphs_mode is self.CudaGraphsMode.NO_WHILE_LOOPS: - self._partial_graphs_compile() - elif self.cuda_graphs_mode is self.CudaGraphsMode.NO_GRAPHS: - # no graphs needed - pass - else: - raise NotImplementedError - - def _partial_graphs_compile(self): - """Compile decoding by parts""" - # Always create a new stream, because the per-thread default stream disallows stream capture to a graph. - stream_for_graph = torch.cuda.Stream(self.state.device) - stream_for_graph.wait_stream(torch.cuda.default_stream(self.state.device)) - self.separate_graphs = SeparateGraphsBatchedBeamCTC() - with ( - torch.cuda.stream(stream_for_graph), - torch.inference_mode(), - torch.cuda.graph( - self.separate_graphs._before_process_batch, stream=stream_for_graph, capture_error_mode="thread_local" - ), - ): - self._before_process_batch() - - with ( - torch.cuda.stream(stream_for_graph), - torch.inference_mode(), - torch.cuda.graph( - self.separate_graphs._process_batch, stream=stream_for_graph, capture_error_mode="thread_local" - ), - ): - self._process_batch() - - with ( - torch.cuda.stream(stream_for_graph), - torch.inference_mode(), - torch.cuda.graph( - self.separate_graphs._after_process_batch, stream=stream_for_graph, capture_error_mode="thread_local" - ), - ): - self._after_process_batch() - - @cuda_python_required - def _full_graph_compile(self): - """Compile full graph for decoding""" - # Always create a new stream, because the per-thread default stream disallows stream capture to a graph. - stream_for_graph = torch.cuda.Stream(self.state.device) - self.full_graph = torch.cuda.CUDAGraph() - - with ( - torch.cuda.stream(stream_for_graph), - torch.inference_mode(), - torch.cuda.graph(self.full_graph, stream=stream_for_graph, capture_error_mode="thread_local"), - ): - self._before_process_batch() - # NB: depending on cuda-python version, cudaStreamGetCaptureInfo can return either 5 or 6 elements - capture_status, _, graph, *_ = cu_call( - cudart.cudaStreamGetCaptureInfo(torch.cuda.current_stream(device=self.state.device).cuda_stream) - ) - - assert capture_status == cudart.cudaStreamCaptureStatus.cudaStreamCaptureStatusActive - - # capture: while self.active_mask_any: - (loop_conditional_handle,) = cu_call(cudart.cudaGraphConditionalHandleCreate(graph, 0, 0)) - loop_kernel = self._create_process_batch_kernel() - active_mask_any_ptr = np.array([self.state.active_mask_any.data_ptr()], dtype=np.uint64) - loop_args = np.array( - [loop_conditional_handle.getPtr(), active_mask_any_ptr.ctypes.data], - dtype=np.uint64, - ) - # loop while there are active utterances - with with_conditional_node(loop_kernel, loop_args, loop_conditional_handle, device=self.state.device): - self._process_batch() - - self._after_process_batch() - - def _before_process_batch(self): - """ - Clears state and setups fusion models. - """ - # step 1.1: reset state - self.state.batched_hyps.clear_() - self.state.curr_frame_idx.fill_(0) - - # maximum time step for each utterance - torch.sub(self.state.decoder_output_lengths, 1, out=self.state.last_timesteps) - - # masks for utterances in batch - # same as: active_mask = self.encoder_output_length > 0 - torch.greater(self.state.decoder_output_lengths, 0, out=self.state.active_mask) - - # same as: self.active_mask_any = active_mask.any() - torch.any(self.state.active_mask, out=self.state.active_mask_any) - - # step 1.2: setup fusion models - if self.fusion_models is not None: - for fusion_idx, fusion_model in enumerate(self.fusion_models): - fusion_model.to(self.state.device) - fusion_states = fusion_model.get_init_states( - batch_size=self.state.batch_size * self.beam_size, bos=True - ) - # self.state.fusion_states_list[fusion_idx].copy_(fusion_states.view(self.state.batch_size, self.beam_size)) - self.state.fusion_states_list[fusion_idx].copy_( - fusion_states.view(self.state.batch_size, self.beam_size) - ) - self.state.fusion_states_candidates_list[fusion_idx] = torch.empty( - (self.state.batch_size, self.state.beam_size, fusion_model.vocab_size), - device=self.state.device, - dtype=torch.long, - ) - - def _process_batch(self): - """ - Performs a decoding step. - """ - repeated_mask = self.state.batched_hyps.last_label[:, :, None] == self.state.vocab[None, None, :] - repeated_or_blank_mask = repeated_mask | self.state.vocab_blank_mask[None, None, :] - - # step 2.1: getting the log probs and updating with fusion scores - log_probs = self.state.decoder_outputs.index_select(dim=1, index=self.state.curr_frame_idx) - log_probs += self.state.batched_hyps.scores[:, :, None] - - # step 2.2: updating non-blank and non-repeating token scores with `beam_beta` - log_probs = torch.where(repeated_or_blank_mask, log_probs, log_probs + self.beam_beta) - - if self.fusion_models is not None: - for fusion_idx, fusion_model in enumerate(self.fusion_models): - fusion_scores, fusion_states_candidates = fusion_model.advance( - states=self.state.fusion_states_list[fusion_idx].view(-1) - ) - fusion_scores = torch.where( - repeated_mask[..., :-1], 0, fusion_scores.view(log_probs.shape[0], self.beam_size, -1) - ) - log_probs[..., :-1] += self.fusion_models_alpha[fusion_idx] * fusion_scores.view( - log_probs.shape[0], self.beam_size, -1 - ) - self.state.fusion_states_candidates_list[fusion_idx].copy_( - fusion_states_candidates.view(self.state.batch_size, self.beam_size, -1) - ) - - # step 2.3: getting `beam_size` best candidates - next_scores, next_candidates_indices = torch.topk( - log_probs.view(self.state.batch_size, -1), k=self.beam_size, largest=True, sorted=True - ) - next_indices = next_candidates_indices // self.state.vocab_size - next_labels = next_candidates_indices % self.state.vocab_size - - # step 2.3: pruning candidates with threshold `beam_threshold` - batch_next_scores = next_scores.view(self.state.batch_size, -1) - max_next_score = batch_next_scores.max(dim=-1, keepdim=True).values - batch_next_scores.masked_fill_(batch_next_scores <= max_next_score - self.beam_threshold, INACTIVE_SCORE) - next_scores.view(self.state.batch_size, self.beam_size, -1) - - # step 2.4: preserving updated fusion states - if self.fusion_models is not None: - last_labels = torch.gather(self.state.batched_hyps.last_label, dim=-1, index=next_indices) - blank_mask = next_labels == self._blank_index - repeating_mask = next_labels == last_labels - preserve_state_mask = repeating_mask | blank_mask | ~self.state.active_mask - - # step 2.4.1: masking blanks and inactive labels to pass to fusion model, as fusion model does not support blanks - next_labels_masked = torch.where(blank_mask, 0, next_labels) - - # step 2.4.2: gathering fusion states of extended hypotheses - for fusion_idx, fusion_model in enumerate(self.fusion_models): - # fusion_states: [(BxBeam)] - # fusion_states_candidates: [(BxBeam) x V (without blank)] - next_indices_extended = next_indices[:, :, None].expand( - self.state.fusion_states_candidates_list[fusion_idx].shape - ) - fusion_states_candidates = torch.gather( - self.state.fusion_states_candidates_list[fusion_idx], dim=1, index=next_indices_extended - ) - fusion_states_prev = torch.gather(self.state.fusion_states_list[fusion_idx], dim=1, index=next_indices) - fusion_states = torch.gather( - fusion_states_candidates, dim=-1, index=next_labels_masked.unsqueeze(-1) - ).squeeze() - - # step 2.4.3: update fusion states in State - self.state.fusion_states_candidates_list[fusion_idx].copy_(fusion_states_candidates) - torch.where( - preserve_state_mask, - fusion_states_prev, - fusion_states, - out=self.state.fusion_states_list[fusion_idx], - ) - - # step 2.5: masking inactive hypotheses, updating + recombining batched beam hypoteses - torch.where(self.state.active_mask, next_labels, self.state.NON_EXISTENT_LABEL, out=next_labels) - self.state.batched_hyps.add_results_no_checks_(next_indices, next_labels, next_scores) - self.state.batched_hyps.recombine_hyps_() - - # step 2.6: updating frame idx and active masks - self.state.curr_frame_idx.add_(1) - torch.greater_equal(self.state.last_timesteps, self.state.curr_frame_idx, out=self.state.active_mask) - torch.any(self.state.active_mask, out=self.state.active_mask_any) - - def _after_process_batch(self): - """ - Finalizes the decoding process by updating the fusion scores with the end-of-sequence (eos) scores. - """ - - # step 3: updating fusion scores with eos scores - if self.fusion_models is not None: - for fusion_idx, fusion_model in enumerate(self.fusion_models): - if not isinstance(fusion_model, GPUBoostingTreeModel): - eos_score = fusion_model.get_final(self.state.fusion_states_list[fusion_idx]).view( - self.state.batched_hyps.scores.shape - ) - self.state.batched_hyps.scores += eos_score * self.fusion_models_alpha[fusion_idx] - - def __call__( - self, - x: torch.Tensor, - out_len: torch.Tensor, - ) -> BatchedBeamHyps: - if self.cuda_graphs_mode is not None and x.device.type == "cuda": - return self.batched_beam_search_cuda_graphs(decoder_outputs=x, decoder_output_lengths=out_len) - - return self.batched_beam_search_torch(decoder_outputs=x, decoder_output_lengths=out_len) diff --git a/nemo/collections/asr/parts/submodules/ctc_beam_decoding.py b/nemo/collections/asr/parts/submodules/ctc_beam_decoding.py deleted file mode 100644 index 362c784deaf505700add07fff78d347f66136235..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/ctc_beam_decoding.py +++ /dev/null @@ -1,1017 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from __future__ import annotations - -import math -import os -from dataclasses import dataclass, field -from typing import List, Optional, Tuple, Union - -import torch - -from nemo.collections.asr.parts.context_biasing import BoostingTreeModelConfig, GPUBoostingTreeModel -from nemo.collections.asr.parts.submodules.ctc_batched_beam_decoding import BatchedBeamCTCComputer -from nemo.collections.asr.parts.submodules.ngram_lm import DEFAULT_TOKEN_OFFSET, NGramGPULanguageModel -from nemo.collections.asr.parts.submodules.wfst_decoder import RivaDecoderConfig, WfstNbestHypothesis -from nemo.collections.asr.parts.utils import rnnt_utils -from nemo.collections.common.parts.optional_cuda_graphs import WithOptionalCudaGraphs -from nemo.collections.common.tokenizers.tokenizer_spec import TokenizerSpec -from nemo.core.classes import Typing, typecheck -from nemo.core.neural_types import HypothesisType, LengthsType, LogprobsType, NeuralType -from nemo.utils import logging - - -def pack_hypotheses( - hypotheses: List[rnnt_utils.NBestHypotheses], - logitlen: torch.Tensor, -) -> List[rnnt_utils.NBestHypotheses]: - - if logitlen is not None: - if hasattr(logitlen, 'cpu'): - logitlen_cpu = logitlen.to('cpu') - else: - logitlen_cpu = logitlen - - for idx, hyp in enumerate(hypotheses): # type: rnnt_utils.NBestHypotheses - for candidate_idx, cand in enumerate(hyp.n_best_hypotheses): - cand.y_sequence = torch.tensor(cand.y_sequence, dtype=torch.long) - - if logitlen is not None: - cand.length = logitlen_cpu[idx] - - if cand.dec_state is not None: - cand.dec_state = _states_to_device(cand.dec_state) - - return hypotheses - - -def pack_wfst_hypotheses( - hypotheses: List['WfstNbestHypothesis'], - logits: torch.Tensor, - logitlen: torch.Tensor, -) -> List[rnnt_utils.NBestHypotheses]: - - logitlen_cpu = logitlen.to('cpu') - - new_hypotheses = [] - for idx, nbest_hyp in enumerate(hypotheses): # type: WfstNbestHypothesis - new_hyp = [] - y_sequence = logits[idx, : logitlen[idx]].to('cpu') - length = logitlen_cpu[idx] - for candidate_idx, cand in enumerate(nbest_hyp): - cand_hyp = rnnt_utils.Hypothesis( - y_sequence=[], - score=cand.score, - text=" ".join(cand.words), - timestamp=list(cand.timesteps), - alignments=list(cand.alignment), - ) - cand_hyp.y_sequence = y_sequence - - if logitlen is not None: - cand_hyp.length = length - - new_hyp.append(cand_hyp) - - new_hypotheses.append(rnnt_utils.NBestHypotheses(new_hyp)) - - return new_hypotheses - - -def _states_to_device(dec_state, device='cpu'): - if torch.is_tensor(dec_state): - dec_state = dec_state.to(device) - - elif isinstance(dec_state, (list, tuple)): - dec_state = tuple(_states_to_device(dec_i, device) for dec_i in dec_state) - - return dec_state - - -class AbstractBeamCTCInfer(Typing): - """A beam CTC decoder. - - Provides a common abstraction for sample level beam decoding. - - Args: - blank_id: int, index of the blank token. Can be 0 or len(vocabulary). - beam_size: int, size of the beam used in the underlying beam search engine. - - """ - - @property - def input_types(self): - """Returns definitions of module input ports.""" - return { - "decoder_output": NeuralType(('B', 'T', 'D'), LogprobsType()), - "decoder_lengths": NeuralType(tuple('B'), LengthsType()), - } - - @property - def output_types(self): - """Returns definitions of module output ports.""" - return {"predictions": [NeuralType(elements_type=HypothesisType())]} - - def __init__(self, blank_id: int, beam_size: int): - self.blank_id = blank_id - - if beam_size < 1: - raise ValueError("Beam search size cannot be less than 1!") - - self.beam_size = beam_size - - # Variables set by corresponding setter methods - self.vocab = None - self.decoding_type = None - self.tokenizer = None - - # Utility maps for vocabulary - self.vocab_index_map = None - self.index_vocab_map = None - - # Internal variable, used to prevent double reduction of consecutive tokens (ctc collapse) - self.override_fold_consecutive_value = None - - def set_vocabulary(self, vocab: List[str]): - """ - Set the vocabulary of the decoding framework. - - Args: - vocab: List of str. Each token corresponds to its location in the vocabulary emitted by the model. - Note that this vocabulary must NOT contain the "BLANK" token. - """ - self.vocab = vocab - self.vocab_index_map = {v: i for i, v in enumerate(vocab)} - self.index_vocab_map = {i: v for i, v in enumerate(vocab)} - - def set_decoding_type(self, decoding_type: str): - """ - Sets the decoding type of the framework. Can support either char or subword models. - - Args: - decoding_type: Str corresponding to decoding type. Only supports "char" and "subword". - """ - decoding_type = decoding_type.lower() - supported_types = ['char', 'subword'] - - if decoding_type not in supported_types: - raise ValueError( - f"Unsupported decoding type. Supported types = {supported_types}.\n" f"Given = {decoding_type}" - ) - - self.decoding_type = decoding_type - - def set_tokenizer(self, tokenizer: TokenizerSpec): - """ - Set the tokenizer of the decoding framework. - - Args: - tokenizer: NeMo tokenizer object, which inherits from TokenizerSpec. - """ - self.tokenizer = tokenizer - - @typecheck() - def forward( - self, - decoder_output: torch.Tensor, - decoder_lengths: torch.Tensor, - ) -> Tuple[List[Union[rnnt_utils.Hypothesis, rnnt_utils.NBestHypotheses]]]: - """Returns a list of hypotheses given an input batch of the encoder hidden embedding. - Output token is generated auto-repressively. - - Args: - decoder_output: A tensor of size (batch, timesteps, features) or (batch, timesteps) (each timestep is a label). - decoder_lengths: list of int representing the length of each sequence - output sequence. - - Returns: - packed list containing batch number of sentences (Hypotheses). - """ - raise NotImplementedError() - - def __call__(self, *args, **kwargs): - return self.forward(*args, **kwargs) - - -class BeamCTCInfer(AbstractBeamCTCInfer): - """A beam CTC decoder. - - Provides a common abstraction for sample level and batch level greedy decoding. - - Args: - blank_index: int index of the blank token. Can be 0 or len(vocabulary). - preserve_alignments: Bool flag which preserves the history of logprobs generated during - decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `logprobs` in it. Here, `logprobs` is a torch.Tensors. - compute_timestamps: A bool flag, which determines whether to compute the character/subword, or - word based timestamp mapping the output log-probabilities to discrite intervals of timestamps. - The timestamps will be available in the returned Hypothesis.timestep as a dictionary. - - """ - - def __init__( - self, - blank_id: int, - beam_size: int, - search_type: str = "default", - return_best_hypothesis: bool = True, - preserve_alignments: bool = False, - compute_timestamps: bool = False, - ngram_lm_alpha: float = 0.3, - beam_beta: float = 0.0, - ngram_lm_model: str = None, - flashlight_cfg: Optional['FlashlightConfig'] = None, - pyctcdecode_cfg: Optional['PyCTCDecodeConfig'] = None, - ): - super().__init__(blank_id=blank_id, beam_size=beam_size) - - self.search_type = search_type - self.return_best_hypothesis = return_best_hypothesis - self.preserve_alignments = preserve_alignments - self.compute_timestamps = compute_timestamps - - if self.compute_timestamps: - raise ValueError("Currently this flag is not supported for beam search algorithms.") - - self.vocab = None # This must be set by specific method by user before calling forward() ! - - if search_type == "default" or search_type == "nemo": - self.search_algorithm = self.default_beam_search - elif search_type == "pyctcdecode": - self.search_algorithm = self._pyctcdecode_beam_search - elif search_type == "flashlight": - self.search_algorithm = self.flashlight_beam_search - else: - raise NotImplementedError( - f"The search type ({search_type}) supplied is not supported!\n" - f"Please use one of : (default, nemo, pyctcdecode)" - ) - - # Log the beam search algorithm - logging.info(f"Beam search algorithm: {search_type}") - - self.ngram_lm_alpha = ngram_lm_alpha - self.beam_beta = beam_beta - - # Default beam search args - self.ngram_lm_model = ngram_lm_model - - # PyCTCDecode params - if pyctcdecode_cfg is None: - pyctcdecode_cfg = PyCTCDecodeConfig() - self.pyctcdecode_cfg = pyctcdecode_cfg # type: PyCTCDecodeConfig - - if flashlight_cfg is None: - flashlight_cfg = FlashlightConfig() - self.flashlight_cfg = flashlight_cfg - - # Default beam search scorer functions - self.default_beam_scorer = None - self.pyctcdecode_beam_scorer = None - self.flashlight_beam_scorer = None - self.token_offset = 0 - - @typecheck() - def forward( - self, - decoder_output: torch.Tensor, - decoder_lengths: torch.Tensor, - ) -> Tuple[List[Union[rnnt_utils.Hypothesis, rnnt_utils.NBestHypotheses]]]: - """Returns a list of hypotheses given an input batch of the encoder hidden embedding. - Output token is generated auto-repressively. - - Args: - decoder_output: A tensor of size (batch, timesteps, features). - decoder_lengths: list of int representing the length of each sequence - output sequence. - - Returns: - packed list containing batch number of sentences (Hypotheses). - """ - if self.vocab is None: - raise RuntimeError("Please set the vocabulary with `set_vocabulary()` before calling this function.") - - if self.decoding_type is None: - raise ValueError("Please set the decoding type with `set_decoding_type()` before calling this function.") - - with torch.no_grad(), torch.inference_mode(): - # Process each sequence independently - prediction_tensor = decoder_output - - if prediction_tensor.ndim != 3: - raise ValueError( - f"`decoder_output` must be a tensor of shape [B, T, V] (log probs, float). " - f"Provided shape = {prediction_tensor.shape}" - ) - - # determine type of input - logprobs or labels - out_len = decoder_lengths if decoder_lengths is not None else None - hypotheses = self.search_algorithm(prediction_tensor, out_len) - - # Pack results into Hypotheses - packed_result = pack_hypotheses(hypotheses, decoder_lengths) - - # Pack the result - if self.return_best_hypothesis and isinstance(packed_result[0], rnnt_utils.NBestHypotheses): - packed_result = [res.n_best_hypotheses[0] for res in packed_result] # type: Hypothesis - - return (packed_result,) - - @torch.no_grad() - def default_beam_search( - self, x: torch.Tensor, out_len: torch.Tensor - ) -> List[Union[rnnt_utils.Hypothesis, rnnt_utils.NBestHypotheses]]: - """ - Open Seq2Seq Beam Search Algorithm (DeepSpeed) - - Args: - x: Tensor of shape [B, T, V+1], where B is the batch size, T is the maximum sequence length, - and V is the vocabulary size. The tensor contains log-probabilities. - out_len: Tensor of shape [B], contains lengths of each sequence in the batch. - - Returns: - A list of NBestHypotheses objects, one for each sequence in the batch. - """ - if self.compute_timestamps: - raise ValueError( - f"Beam Search with strategy `{self.search_type}` does not support time stamp calculation!" - ) - - if self.default_beam_scorer is None: - # Check for filepath - if self.ngram_lm_model is None or not os.path.exists(self.ngram_lm_model): - raise FileNotFoundError( - f"KenLM binary file not found at : {self.ngram_lm_model}. " - f"Please set a valid path in the decoding config." - ) - - # perform token offset for subword models - if self.decoding_type == 'subword': - vocab = [chr(idx + self.token_offset) for idx in range(len(self.vocab))] - else: - # char models - vocab = self.vocab - - # Must import at runtime to avoid circular dependency due to module level import. - from nemo.collections.asr.modules.beam_search_decoder import BeamSearchDecoderWithLM - - self.default_beam_scorer = BeamSearchDecoderWithLM( - vocab=vocab, - lm_path=self.ngram_lm_model, - beam_width=self.beam_size, - alpha=self.ngram_lm_alpha, - beta=self.beam_beta, - num_cpus=max(1, os.cpu_count()), - input_tensor=False, - ) - - x = x.to('cpu') - - with typecheck.disable_checks(): - data = [x[sample_id, : out_len[sample_id], :].softmax(dim=-1) for sample_id in range(len(x))] - beams_batch = self.default_beam_scorer.forward(log_probs=data, log_probs_length=None) - - # For each sample in the batch - nbest_hypotheses = [] - for beams_idx, beams in enumerate(beams_batch): - # For each beam candidate / hypothesis in each sample - hypotheses = [] - for candidate_idx, candidate in enumerate(beams): - hypothesis = rnnt_utils.Hypothesis( - score=0.0, y_sequence=[], dec_state=None, timestamp=[], last_token=None - ) - - # For subword encoding, NeMo will double encode the subword (multiple tokens) into a - # singular unicode id. In doing so, we preserve the semantic of the unicode token, and - # compress the size of the final KenLM ARPA / Binary file. - # In order to do double encoding, we shift the subword by some token offset. - # This step is ignored for character based models. - if self.decoding_type == 'subword': - pred_token_ids = [ord(c) - self.token_offset for c in candidate[1]] - else: - # Char models - pred_token_ids = [self.vocab_index_map[c] for c in candidate[1]] - - # We preserve the token ids and the score for this hypothesis - hypothesis.y_sequence = pred_token_ids - hypothesis.score = candidate[0] - - # If alignment must be preserved, we preserve a view of the output logprobs. - # Note this view is shared amongst all beams within the sample, be sure to clone it if you - # require specific processing for each sample in the beam. - # This is done to preserve memory. - if self.preserve_alignments: - hypothesis.alignments = x[beams_idx][: out_len[beams_idx]] - - hypotheses.append(hypothesis) - - # Wrap the result in NBestHypothesis. - hypotheses = rnnt_utils.NBestHypotheses(hypotheses) - nbest_hypotheses.append(hypotheses) - - return nbest_hypotheses - - @torch.no_grad() - def _pyctcdecode_beam_search( - self, x: torch.Tensor, out_len: torch.Tensor - ) -> List[Union[rnnt_utils.Hypothesis, rnnt_utils.NBestHypotheses]]: - """ - PyCTCDecode Beam Search Algorithm. Should support Char and Subword models. - - Args: - x: Tensor of shape [B, T, V+1], where B is the batch size, T is the maximum sequence length, - and V is the vocabulary size. The tensor contains log-probabilities. - out_len: Tensor of shape [B], contains lengths of each sequence in the batch. - - Returns: - A list of NBestHypotheses objects, one for each sequence in the batch. - """ - if self.compute_timestamps: - raise ValueError( - f"Beam Search with strategy `{self.search_type}` does not support time stamp calculation!" - ) - - try: - import pyctcdecode - except (ImportError, ModuleNotFoundError): - raise ImportError( - "Could not load `pyctcdecode` library. Please install it from pip using :\n" - "pip install --upgrade pyctcdecode" - ) - - if self.pyctcdecode_beam_scorer is None: - self.pyctcdecode_beam_scorer = pyctcdecode.build_ctcdecoder( - labels=self.vocab, kenlm_model_path=self.ngram_lm_model, alpha=self.ngram_lm_alpha, beta=self.beam_beta - ) # type: pyctcdecode.BeamSearchDecoderCTC - - x = x.to('cpu').numpy() - - with typecheck.disable_checks(): - beams_batch = [] - for sample_id in range(len(x)): - logprobs = x[sample_id, : out_len[sample_id], :] - result = self.pyctcdecode_beam_scorer.decode_beams( - logprobs, - beam_width=self.beam_size, - beam_prune_logp=self.pyctcdecode_cfg.beam_prune_logp, - token_min_logp=self.pyctcdecode_cfg.token_min_logp, - prune_history=self.pyctcdecode_cfg.prune_history, - hotwords=self.pyctcdecode_cfg.hotwords, - hotword_weight=self.pyctcdecode_cfg.hotword_weight, - lm_start_state=None, - ) # Output format: text, last_lm_state, text_frames, logit_score, lm_score - beams_batch.append(result) - - nbest_hypotheses = [] - for beams_idx, beams in enumerate(beams_batch): - hypotheses = [] - for candidate_idx, candidate in enumerate(beams): - # Candidate = (text, last_lm_state, text_frames, logit_score, lm_score) - hypothesis = rnnt_utils.Hypothesis( - score=0.0, y_sequence=[], dec_state=None, timestamp=[], last_token=None - ) - - # TODO: Requires token ids to be returned rather than text. - if self.decoding_type == 'subword': - if self.tokenizer is None: - raise ValueError("Tokenizer must be provided for subword decoding. Use set_tokenizer().") - - pred_token_ids = self.tokenizer.text_to_ids(candidate[0]) - else: - if self.vocab is None: - raise ValueError("Vocab must be provided for character decoding. Use set_vocab().") - - chars = list(candidate[0]) - pred_token_ids = [self.vocab_index_map[c] for c in chars] - - hypothesis.y_sequence = pred_token_ids - hypothesis.text = candidate[0] # text - hypothesis.score = candidate[4] # score - - # Inject word level timestamps - hypothesis.timestamp = candidate[2] # text_frames - - if self.preserve_alignments: - hypothesis.alignments = torch.from_numpy(x[beams_idx][: out_len[beams_idx]]) - - hypotheses.append(hypothesis) - - hypotheses = rnnt_utils.NBestHypotheses(hypotheses) - nbest_hypotheses.append(hypotheses) - - return nbest_hypotheses - - @torch.no_grad() - def flashlight_beam_search( - self, x: torch.Tensor, out_len: torch.Tensor - ) -> List[Union[rnnt_utils.Hypothesis, rnnt_utils.NBestHypotheses]]: - """ - Flashlight Beam Search Algorithm. Should support Char and Subword models. - - Args: - x: Tensor of shape [B, T, V+1], where B is the batch size, T is the maximum sequence length, - and V is the vocabulary size. The tensor contains log-probabilities. - out_len: Tensor of shape [B], contains lengths of each sequence in the batch. - - Returns: - A list of NBestHypotheses objects, one for each sequence in the batch. - """ - if self.compute_timestamps: - raise ValueError( - f"Beam Search with strategy `{self.search_type}` does not support time stamp calculation!" - ) - - if self.flashlight_beam_scorer is None: - # Check for filepath - if self.ngram_lm_model is None or not os.path.exists(self.ngram_lm_model): - raise FileNotFoundError( - f"KenLM binary file not found at : {self.ngram_lm_model}. " - "Please set a valid path in the decoding config." - ) - - # perform token offset for subword models - # if self.decoding_type == 'subword': - # vocab = [chr(idx + self.token_offset) for idx in range(len(self.vocab))] - # else: - # # char models - # vocab = self.vocab - - # Must import at runtime to avoid circular dependency due to module level import. - from nemo.collections.asr.modules.flashlight_decoder import FlashLightKenLMBeamSearchDecoder - - self.flashlight_beam_scorer = FlashLightKenLMBeamSearchDecoder( - lm_path=self.ngram_lm_model, - vocabulary=self.vocab, - tokenizer=self.tokenizer, - lexicon_path=self.flashlight_cfg.lexicon_path, - boost_path=self.flashlight_cfg.boost_path, - beam_size=self.beam_size, - beam_size_token=self.flashlight_cfg.beam_size_token, - beam_threshold=self.flashlight_cfg.beam_threshold, - lm_weight=self.ngram_lm_alpha, - word_score=self.beam_beta, - unk_weight=self.flashlight_cfg.unk_weight, - sil_weight=self.flashlight_cfg.sil_weight, - ) - - x = x.to('cpu') - - with typecheck.disable_checks(): - beams_batch = self.flashlight_beam_scorer.forward(log_probs=x) - - # For each sample in the batch - nbest_hypotheses = [] - for beams_idx, beams in enumerate(beams_batch): - # For each beam candidate / hypothesis in each sample - hypotheses = [] - for candidate_idx, candidate in enumerate(beams): - hypothesis = rnnt_utils.Hypothesis( - score=0.0, y_sequence=[], dec_state=None, timestamp=[], last_token=None - ) - - # We preserve the token ids and the score for this hypothesis - hypothesis.y_sequence = candidate['tokens'].tolist() - hypothesis.score = candidate['score'] - - # If alignment must be preserved, we preserve a view of the output logprobs. - # Note this view is shared amongst all beams within the sample, be sure to clone it if you - # require specific processing for each sample in the beam. - # This is done to preserve memory. - if self.preserve_alignments: - hypothesis.alignments = x[beams_idx][: out_len[beams_idx]] - - hypotheses.append(hypothesis) - - # Wrap the result in NBestHypothesis. - hypotheses = rnnt_utils.NBestHypotheses(hypotheses) - nbest_hypotheses.append(hypotheses) - - return nbest_hypotheses - - def set_decoding_type(self, decoding_type: str): - super().set_decoding_type(decoding_type) - - # Please check train_kenlm.py in scripts/asr_language_modeling/ to find out why we need - # TOKEN_OFFSET for BPE-based models - if self.decoding_type == 'subword': - self.token_offset = DEFAULT_TOKEN_OFFSET - - -class WfstCTCInfer(AbstractBeamCTCInfer): - """A WFST-based beam CTC decoder. - - Provides a common abstraction for sample level and batch level beam decoding. - - Args: - TBD - - """ - - def __init__( - self, - blank_id: int, - beam_size: int, - search_type: str = "riva", - return_best_hypothesis: bool = True, - preserve_alignments: bool = False, - compute_timestamps: bool = False, - decoding_mode: str = 'nbest', # 'nbest', 'mbr' ('mbr' works only for search_type == 'riva' and beam_size == 1) - open_vocabulary_decoding: bool = False, - beam_width: float = 10.0, - lm_weight: float = 1.0, - device: str = "cuda", - arpa_lm_path: str = None, - wfst_lm_path: str = None, - riva_decoding_cfg: Optional['RivaDecoderConfig'] = None, - ): - super().__init__(blank_id=blank_id, beam_size=beam_size) - - self.search_type = search_type - self.return_best_hypothesis = return_best_hypothesis - self.preserve_alignments = preserve_alignments - self.compute_timestamps = compute_timestamps - - self.decoding_algorithm = None - if search_type in ("default", "riva"): - self.decoding_algorithm = self._riva_decoding - - # Log the WFST search_type - logging.info(f"WFST beam search search_type: {search_type}") - self.search_type = search_type - - if beam_size > 1 and decoding_mode != 'nbest': - logging.warning( - f"`beam_size` > 1 is supported only for `decoding_mode` == `nbest`\n" - f"(provided: `{decoding_mode}`).\n" - f"`beam_size` rewritten as 1" - ) - self.beam_size = 1 - self.decoding_mode = decoding_mode - - self.open_vocabulary_decoding = open_vocabulary_decoding - self._tokenword_disambig_id = -1 - self.beam_width = beam_width - self.lm_weight = lm_weight - self.device = device - - # Default beam search args - self.arpa_lm_path = arpa_lm_path - self.wfst_lm_path = wfst_lm_path - - self.riva_decoding_cfg = riva_decoding_cfg - - # Default beam search scorer functions - self.riva_decoder = None - - @typecheck() - def forward( - self, - decoder_output: torch.Tensor, - decoder_lengths: torch.Tensor, - ) -> Tuple[List[Union[rnnt_utils.Hypothesis, rnnt_utils.NBestHypotheses]]]: - """Returns a list of hypotheses given an input batch of the encoder hidden embedding. - Output token is generated auto-repressively. - - Args: - decoder_output: A tensor of size (batch, timesteps, features). - decoder_lengths: list of int representing the length of each sequence - output sequence. - - Returns: - packed list containing batch number of sentences (Hypotheses). - """ - if self.vocab is None: - raise RuntimeError("Please set the vocabulary with `set_vocabulary()` before calling this function.") - - if self.decoding_type != 'subword': - raise ValueError( - f"`decoding_type` other than `subword` is not supported. Provided: `{self.decoding_type}`" - ) - elif self.tokenizer is None: - raise ValueError("Tokenizer must be provided for subword decoding. Use set_tokenizer().") - if self.decoding_algorithm is None: - raise NotImplementedError( - f"The decoding search_type ({self.search_type}) supplied is not supported!\n" - f"Please use one of : (default, riva)" - ) - - with torch.no_grad(), torch.inference_mode(): - # Process each sequence independently - prediction_tensor = decoder_output - - if prediction_tensor.ndim != 3: - raise ValueError( - f"`decoder_output` must be a tensor of shape [B, T, V] (log probs, float). " - f"Provided shape = {prediction_tensor.shape}" - ) - - hypotheses = self.decoding_algorithm(prediction_tensor, decoder_lengths) - - # Pack results into Hypotheses - packed_result = pack_wfst_hypotheses(hypotheses, prediction_tensor, decoder_lengths) - - # Pack the result - if self.return_best_hypothesis and isinstance(packed_result[0], rnnt_utils.NBestHypotheses): - packed_result = [res.n_best_hypotheses[0] for res in packed_result] # type: Hypothesis - - return (packed_result,) - - def _prepare_decoding_lm_wfst(self) -> Union[str, 'kaldifst.StdFst']: # noqa: F821 - """TBD""" - arpa_lm_path_exists = self.arpa_lm_path is not None and os.path.exists(self.arpa_lm_path) - wfst_lm_path_exists = self.wfst_lm_path is not None and os.path.exists(self.wfst_lm_path) - lm_fst = None - if wfst_lm_path_exists: - if self.search_type == "riva" and not self.wfst_lm_path.endswith(".fst"): - raise ValueError( - f"Search type `riva` expects WFSTs in the `.fst` format. Provided: `{self.wfst_lm_path}`" - ) - if arpa_lm_path_exists: - logging.warning( - "Both `arpa_lm_path` and `wfst_lm_path` are provided and not empty. The latter will be used." - ) - lm_fst = self.wfst_lm_path - elif not arpa_lm_path_exists: - raise FileNotFoundError( - f"Arpa LM file not found at `{self.arpa_lm_path}` and WFST LM is not found at `{self.wfst_lm_path}`.\n" - f"Please set a valid path in the decoding config for at least one of those." - ) - else: - logging.warning( - f"Since WFST LM is not found at `{self.wfst_lm_path}`, " - f"it will be made from the Arpa LM at `{self.arpa_lm_path}`.\n" - f"This procedure will take some time." - ) - if self.wfst_lm_path is not None: - logging.info(f"WFST LM will be buffered at `{self.wfst_lm_path}`.") - write_tlg_path = self.wfst_lm_path - else: - logging.warning("Consider providing a write-permitted `wfst_lm_path` for WFST LM buffering.") - write_tlg_path = None - ctc_topology = "default" # there is no way to indicate the need of other topologies - target = "kaldi" - - from nemo.collections.asr.parts.utils.wfst_utils import mkgraph_ctc_ov - - lm_fst, tokenword_disambig_id = mkgraph_ctc_ov( - tokenizer=self.tokenizer, - lm_path=self.arpa_lm_path, - topology_name=ctc_topology, - write_tlg_path=write_tlg_path, - open_vocabulary=self.open_vocabulary_decoding, - target=target, - ) - self._tokenword_disambig_id = tokenword_disambig_id - - return lm_fst - - @torch.no_grad() - def _riva_decoding(self, x: torch.Tensor, out_len: torch.Tensor) -> List['WfstNbestHypothesis']: - """ - Riva Asrlib WFST decoder Algorithm. - - Args: - x: Tensor of shape [B, T, V+1], where B is the batch size, T is the maximum sequence length, - and V is the vocabulary size. The tensor contains log-probabilities. - out_len: Tensor of shape [B], contains lengths of each sequence in the batch. - - Returns: - A list of WfstNbestHypothesis objects, one for each sequence in the batch. - """ - if self.riva_decoder is None: - lm_fst = self._prepare_decoding_lm_wfst() - if self.open_vocabulary_decoding and self._tokenword_disambig_id == -1: - # trying to extract tokenword_disambig_id from the lm_fst - if isinstance(lm_fst, str): - # use importer instead of direct import to possibly get an installation message - from nemo.collections.asr.parts.utils.wfst_utils import kaldifst_importer - - kaldifst = kaldifst_importer() - lm_fst = kaldifst.StdVectorFst.read(self.wfst_lm_path) - tokenword_disambig_id = lm_fst.output_symbols.find("#1") - if tokenword_disambig_id == -1: - raise ValueError( - "Cannot determine `tokenword_disambig_id` " - "which is required if `open_vocabulary_decoding` == True" - ) - self._tokenword_disambig_id = tokenword_disambig_id - if not self.device.startswith("cuda"): - raise ValueError(f"Riva decoder does not support non-cuda device. Provided: `{self.device}`") - - from nemo.collections.asr.parts.submodules.wfst_decoder import RivaGpuWfstDecoder - - self.riva_decoder = RivaGpuWfstDecoder( - lm_fst=lm_fst, - decoding_mode=self.decoding_mode, - beam_size=self.beam_width, - config=self.riva_decoding_cfg, - tokenword_disambig_id=self._tokenword_disambig_id, - lm_weight=self.lm_weight, - nbest_size=self.beam_size, - ) - - return self.riva_decoder.decode(x.to(device=self.device), out_len.to(device=self.device)) - - -class BeamBatchedCTCInfer(AbstractBeamCTCInfer, WithOptionalCudaGraphs): - """ - A batched beam CTC decoder. - - Args: - blank_index: int index of the blank token. Can be 0 or len(vocabulary). - beam_size: int size of the beam. - return_best_hypothesis: When set to True (default), returns a single Hypothesis. - When set to False, returns a NBestHypotheses container, which contains a list of Hypothesis. - preserve_alignments: Bool flag which preserves the history of logprobs generated during - decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `logprobs` in it. Here, `logprobs` is a torch.Tensors. - compute_timestamps: A bool flag, which determines whether to compute the character/subword, or - word based timestamp mapping the output log-probabilities to discrite intervals of timestamps. - The timestamps will be available in the returned Hypothesis.timestep as a dictionary. - ngram_lm_alpha: float, the language model weight. - beam_beta: float, the word insertion weight. - beam_threshold: float, the beam pruning threshold. - ngram_lm_model: str, the path to the ngram model. - boosting_tree: BoostingTreeModelConfig, the boosting tree model config. - boosting_tree_alpha: float, the boosting tree alpha. - allow_cuda_graphs: bool, whether to allow cuda graphs for the beam search algorithm. - """ - - def __init__( - self, - blank_index: int, - beam_size: int, - return_best_hypothesis: bool = True, - preserve_alignments: bool = False, - compute_timestamps: bool = False, - ngram_lm_alpha: float = 1.0, - beam_beta: float = 0.0, - beam_threshold: float = 20.0, - ngram_lm_model: str = None, - boosting_tree: BoostingTreeModelConfig = None, - boosting_tree_alpha: float = 0.0, - allow_cuda_graphs: bool = True, - tokenizer: TokenizerSpec = None, - ): - super().__init__(blank_id=blank_index, beam_size=beam_size) - - self.return_best_hypothesis = return_best_hypothesis - self.preserve_alignments = preserve_alignments - self.compute_timestamps = compute_timestamps - self.allow_cuda_graphs = allow_cuda_graphs - - if self.compute_timestamps: - raise ValueError("`Compute timestamps` is not supported for batched beam search.") - if self.preserve_alignments: - raise ValueError("`Preserve alignments` is not supported for batched beam search.") - - self.beam_beta = beam_beta - self.beam_threshold = beam_threshold - - # load fusion models from paths (ngram_lm_model and boosting_tree_model) - fusion_models, fusion_models_alpha = [], [] - if ngram_lm_model is not None: - assert blank_index != 0, "Blank should not be the first token in the vocabulary" - fusion_models.append(NGramGPULanguageModel.from_file(lm_path=ngram_lm_model, vocab_size=blank_index)) - fusion_models_alpha.append(ngram_lm_alpha) - if boosting_tree and not BoostingTreeModelConfig.is_empty(boosting_tree): - assert blank_index != 0, "Blank should not be the first token in the vocabulary" - fusion_models.append(GPUBoostingTreeModel.from_config(boosting_tree, tokenizer=tokenizer)) - fusion_models_alpha.append(boosting_tree_alpha) - if not fusion_models: - fusion_models = None - fusion_models_alpha = None - - # # Default beam search args - - self.search_algorithm = BatchedBeamCTCComputer( - blank_index=blank_index, - beam_size=beam_size, - return_best_hypothesis=return_best_hypothesis, - preserve_alignments=preserve_alignments, - compute_timestamps=compute_timestamps, - fusion_models=fusion_models, - fusion_models_alpha=fusion_models_alpha, - beam_beta=beam_beta, - beam_threshold=beam_threshold, - allow_cuda_graphs=allow_cuda_graphs, - ) - - def disable_cuda_graphs(self) -> bool: - """Disable CUDA graphs (e.g., for decoding in training)""" - if isinstance(self.search_algorithm, WithOptionalCudaGraphs): - return self.search_algorithm.disable_cuda_graphs() - return False - - def maybe_enable_cuda_graphs(self) -> bool: - """Enable CUDA graphs (if allowed)""" - if isinstance(self.search_algorithm, WithOptionalCudaGraphs): - return self.search_algorithm.maybe_enable_cuda_graphs() - return False - - @typecheck() - def forward( - self, - decoder_output: torch.Tensor, - decoder_lengths: torch.Tensor, - ) -> Tuple[List[Union[rnnt_utils.Hypothesis, rnnt_utils.NBestHypotheses]]]: - """Returns a list of hypotheses given an input batch of the encoder hidden embedding. - Output token is generated auto-repressively. - - Args: - decoder_output: A tensor of size (batch, timesteps, features). - decoder_lengths: list of int representing the length of each sequence - output sequence. - - Returns: - packed list containing batch number of sentences (Hypotheses). - """ - with torch.no_grad(), torch.inference_mode(): - if decoder_output.ndim != 3: - raise ValueError( - f"`decoder_output` must be a tensor of shape [B, T, V] (log probs, float). " - f"Provided shape = {decoder_output.shape}" - ) - - batched_beam_hyps = self.search_algorithm(decoder_output, decoder_lengths) - - batch_size = decoder_lengths.shape[0] - if self.return_best_hypothesis: - hyps = batched_beam_hyps.to_hyps_list(score_norm=False)[:batch_size] - else: - hyps = batched_beam_hyps.to_nbest_hyps_list(score_norm=False)[:batch_size] - - return (hyps,) - - -@dataclass -class PyCTCDecodeConfig: - # These arguments cannot be imported from pyctcdecode (optional dependency) - # Therefore we copy the values explicitly - # Taken from pyctcdecode.constant - beam_prune_logp: float = -10.0 - token_min_logp: float = -5.0 - prune_history: bool = False - hotwords: Optional[List[str]] = None - hotword_weight: float = 10.0 - - -@dataclass -class FlashlightConfig: - lexicon_path: Optional[str] = None - boost_path: Optional[str] = None - beam_size_token: int = 16 - beam_threshold: float = 20.0 - unk_weight: float = -math.inf - sil_weight: float = 0.0 - - -@dataclass -class BeamCTCInferConfig: - beam_size: int - search_type: str = 'default' - preserve_alignments: bool = False - compute_timestamps: bool = False - return_best_hypothesis: bool = True - allow_cuda_graphs: bool = True - - beam_alpha: Optional[float] = None # Deprecated - beam_beta: float = 1.0 - beam_threshold: float = 20.0 - kenlm_path: Optional[str] = None # Deprecated, default should be None - ngram_lm_alpha: Optional[float] = 1.0 - ngram_lm_model: Optional[str] = None - boosting_tree: BoostingTreeModelConfig = field(default_factory=BoostingTreeModelConfig) - boosting_tree_alpha: Optional[float] = 0.0 - - flashlight_cfg: Optional[FlashlightConfig] = field(default_factory=lambda: FlashlightConfig()) - pyctcdecode_cfg: Optional[PyCTCDecodeConfig] = field(default_factory=lambda: PyCTCDecodeConfig()) - - -@dataclass -class WfstCTCInferConfig: - beam_size: int - search_type: str = "riva" - return_best_hypothesis: bool = True - preserve_alignments: bool = False - compute_timestamps: bool = False - decoding_mode: str = 'nbest' # 'nbest', 'mbr' ('mbr' works only for search_type == 'riva' and beam_size == 1) - open_vocabulary_decoding: bool = False - beam_width: float = 10.0 - lm_weight: float = 1.0 - device: str = "cuda" - arpa_lm_path: Optional[str] = None - wfst_lm_path: Optional[str] = None - riva_decoding_cfg: Optional['RivaDecoderConfig'] = field(default_factory=lambda: RivaDecoderConfig()) diff --git a/nemo/collections/asr/parts/submodules/ctc_decoding.py b/nemo/collections/asr/parts/submodules/ctc_decoding.py deleted file mode 100644 index 9d8fcbc49f4cdbf1fa26aad607565b7ceb67f574..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/ctc_decoding.py +++ /dev/null @@ -1,1387 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import copy -import re -from abc import abstractmethod, abstractproperty -from dataclasses import dataclass, field, is_dataclass -from typing import Dict, List, Optional, Set, Union - -import numpy as np -import torch -from omegaconf import DictConfig, OmegaConf - -from nemo.collections.asr.parts.submodules import ctc_beam_decoding, ctc_greedy_decoding -from nemo.collections.asr.parts.utils.asr_confidence_utils import ConfidenceConfig, ConfidenceMixin -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis, NBestHypotheses -from nemo.collections.asr.parts.utils.timestamp_utils import get_segment_offsets, get_words_offsets -from nemo.collections.asr.parts.utils.tokenizer_utils import define_spe_tokenizer_type, extract_punctuation_from_vocab -from nemo.collections.common.tokenizers.aggregate_tokenizer import DummyTokenizer -from nemo.collections.common.tokenizers.tokenizer_spec import TokenizerSpec -from nemo.utils import logging, logging_mode - - -def move_dimension_to_the_front(tensor, dim_index): - all_dims = list(range(tensor.ndim)) - return tensor.permute(*([dim_index] + all_dims[:dim_index] + all_dims[dim_index + 1 :])) - - -class AbstractCTCDecoding(ConfidenceMixin): - """ - Used for performing CTC auto-regressive / non-auto-regressive decoding of the logprobs. - - Args: - decoding_cfg: A dict-like object which contains the following key-value pairs. - strategy: - str value which represents the type of decoding that can occur. - Possible values are : - - greedy (for greedy decoding). - - beam (for DeepSpeed KenLM based decoding). - - compute_timestamps: - A bool flag, which determines whether to compute the character/subword, or - word based timestamp mapping the output log-probabilities to discrite intervals of timestamps. - The timestamps will be available in the returned Hypothesis.timestep as a dictionary. - - ctc_timestamp_type: - A str value, which represents the types of timestamps that should be calculated. - Can take the following values - "char" for character/subword time stamps, "word" for word level - time stamps and "all" (default), for both character level and word level time stamps. - - word_seperator: - Str token representing the seperator between words. - - segment_seperators: - List containing tokens representing the seperator(s) between segments. - - segment_gap_threshold: - The threshold (in frames) that caps the gap between two words necessary for forming the segments. - - preserve_alignments: - Bool flag which preserves the history of logprobs generated during - decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `logprobs` in it. Here, `logprobs` is a torch.Tensors. - - confidence_cfg: - A dict-like object which contains the following key-value pairs related to confidence - scores. In order to obtain hypotheses with confidence scores, please utilize - `ctc_decoder_predictions_tensor` function with the `preserve_frame_confidence` flag set to True. - - preserve_frame_confidence: - Bool flag which preserves the history of per-frame confidence scores - generated during decoding. When set to true, the Hypothesis will contain - the non-null value for `frame_confidence` in it. Here, `frame_confidence` is a List of floats. - - preserve_token_confidence: - Bool flag which preserves the history of per-token confidence scores - generated during greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `token_confidence` in it. Here, `token_confidence` is a List of floats. - - The length of the list corresponds to the number of recognized tokens. - - preserve_word_confidence: - Bool flag which preserves the history of per-word confidence scores - generated during greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `word_confidence` in it. Here, `word_confidence` is a List of floats. - - The length of the list corresponds to the number of recognized words. - - exclude_blank: - Bool flag indicating that blank token confidence scores are to be excluded - from the `token_confidence`. - - aggregation: - Which aggregation type to use for collapsing per-token confidence into per-word confidence. - Valid options are `mean`, `min`, `max`, `prod`. - - tdt_include_duration: Bool flag indicating that the duration confidence scores are to be calculated and - attached to the regular frame confidence, - making TDT frame confidence element a pair: (`prediction_confidence`, `duration_confidence`). - - method_cfg: - A dict-like object which contains the method name and settings to compute per-frame - confidence scores. - - name: - The method name (str). - Supported values: - - 'max_prob' for using the maximum token probability as a confidence. - - 'entropy' for using a normalized entropy of a log-likelihood vector. - - entropy_type: - Which type of entropy to use (str). - Used if confidence_method_cfg.name is set to `entropy`. - Supported values: - - - 'gibbs' for the (standard) Gibbs entropy. If the alpha (α) is provided, - the formula is the following: H_α = -sum_i((p^α_i)*log(p^α_i)). - Note that for this entropy, the alpha should comply the following inequality: - (log(V)+2-sqrt(log^2(V)+4))/(2*log(V)) <= α <= (1+log(V-1))/log(V-1) - where V is the model vocabulary size. - - - 'tsallis' for the Tsallis entropy with the Boltzmann constant one. - Tsallis entropy formula is the following: H_α = 1/(α-1)*(1-sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/Tsallis_entropy - - - 'renyi' for the Rényi entropy. - Rényi entropy formula is the following: H_α = 1/(1-α)*log_2(sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/R%C3%A9nyi_entropy - - alpha: - Power scale for logsoftmax (α for entropies). Here we restrict it to be > 0. - When the alpha equals one, scaling is not applied to 'max_prob', - and any entropy type behaves like the Shannon entropy: H = -sum_i(p_i*log(p_i)) - - entropy_norm: - A mapping of the entropy value to the interval [0,1]. - Supported values: - - - 'lin' for using the linear mapping. - - - 'exp' for using exponential mapping with linear shift. - - batch_dim_index: - Index of the batch dimension of ``targets`` and ``predictions`` parameters of - ``ctc_decoder_predictions_tensor`` methods. Can be either 0 or 1. - - The config may further contain the following sub-dictionaries: - - "greedy": - preserve_alignments: Same as above, overrides above value. - compute_timestamps: Same as above, overrides above value. - preserve_frame_confidence: Same as above, overrides above value. - confidence_method_cfg: Same as above, overrides confidence_cfg.method_cfg. - - "beam": - beam_size: - int, defining the beam size for beam search. Must be >= 1. - If beam_size == 1, will perform cached greedy search. This might be slightly different - results compared to the greedy search above. - - return_best_hypothesis: - optional bool, whether to return just the best hypothesis or all of the - hypotheses after beam search has concluded. This flag is set by default. - - ngram_lm_alpha: - float, the strength of the Language model on the final score of a token. - final_score = acoustic_score + ngram_lm_alpha * lm_score + beam_beta * seq_length. - - beam_beta: - float, the strength of the sequence length penalty on the final score of a token. - final_score = acoustic_score + ngram_lm_alpha * lm_score + beam_beta * seq_length. - - ngram_lm_model: - str, path to a KenLM ARPA or .binary file (depending on the strategy chosen). - If the path is invalid (file is not found at path), will raise a deferred error at the moment - of calculation of beam search, so that users may update / change the decoding strategy - to point to the correct file. - - boosting_tree: - BoostingTreeModelConfig, config for the boosting tree model - - boosting_tree_alpha: - float, the strength of the boosting tree model on the final score of a token. - final_score = acoustic_score + boosting_tree_alpha * boosting_tree_score + beam_beta * seq_length. - - blank_id: - The id of the RNNT blank token. - supported_punctuation: - Set of punctuation marks in the vocabulary. - """ - - def __init__(self, decoding_cfg, blank_id: int, supported_punctuation: Optional[Set] = None): - super().__init__() - - # Convert dataclas to config - if is_dataclass(decoding_cfg): - decoding_cfg = OmegaConf.structured(decoding_cfg) - - if not isinstance(decoding_cfg, DictConfig): - decoding_cfg = OmegaConf.create(decoding_cfg) - - OmegaConf.set_struct(decoding_cfg, False) - - # update minimal config - minimal_cfg = ['greedy'] - for item in minimal_cfg: - if item not in decoding_cfg: - decoding_cfg[item] = OmegaConf.create({}) - - self.cfg = decoding_cfg - self.blank_id = blank_id - self.supported_punctuation = supported_punctuation - self.preserve_alignments = self.cfg.get('preserve_alignments', None) - self.compute_timestamps = self.cfg.get('compute_timestamps', None) - self.batch_dim_index = self.cfg.get('batch_dim_index', 0) - self.word_seperator = self.cfg.get('word_seperator', ' ') - self.segment_seperators = self.cfg.get('segment_seperators', ['.', '?', '!']) - self.segment_gap_threshold = self.cfg.get('segment_gap_threshold', None) - - possible_strategies = ['greedy', 'greedy_batch', 'beam', 'pyctcdecode', 'flashlight', 'wfst', 'beam_batch'] - if self.cfg.strategy not in possible_strategies: - raise ValueError(f"Decoding strategy must be one of {possible_strategies}. Given {self.cfg.strategy}") - - # Update preserve alignments - if self.preserve_alignments is None: - if self.cfg.strategy in ['greedy', 'greedy_batch']: - self.preserve_alignments = self.cfg.greedy.get('preserve_alignments', False) - else: - self.preserve_alignments = self.cfg.beam.get('preserve_alignments', False) - - # Update compute timestamps - if self.compute_timestamps is None: - if self.cfg.strategy in ['greedy', 'greedy_batch']: - self.compute_timestamps = self.cfg.greedy.get('compute_timestamps', False) - elif self.cfg.strategy in ['beam']: - self.compute_timestamps = self.cfg.beam.get('compute_timestamps', False) - - # Check if the model supports punctuation - # and compile regex pattern to remove A space before supported punctuation marks if applicable - # We remove only one space before punctuation marks as for some models punctuation marks are included in the vocabulary with a space. - # The presence of multiple spaces before punctuation marks is a result of erroneous prediction of the ASR model, which should not be fixed during the decoding process. - if self.supported_punctuation: - punct_pattern = '|'.join([re.escape(p) for p in self.supported_punctuation]) - self.space_before_punct_pattern = re.compile(r'(\s)(' + punct_pattern + ')') - - # initialize confidence-related fields - self._init_confidence(self.cfg.get('confidence_cfg', None)) - - # Confidence estimation is not implemented for strategies other than `greedy` and `greedy_batch` - if ( - not self.preserve_frame_confidence - and self.cfg.strategy not in ('greedy', 'greedy_batch') - and self.cfg.beam.get('preserve_frame_confidence', False) - ): - raise NotImplementedError(f"Confidence calculation is not supported for strategy `{self.cfg.strategy}`") - - # we need timestamps to extract non-blank per-frame confidence - if self.compute_timestamps is not None: - self.compute_timestamps |= self.preserve_frame_confidence - - if self.cfg.strategy in ['flashlight', 'wfst', 'beam_batch', 'pyctcdecode', 'beam']: - if self.cfg.beam.beam_alpha is not None: - logging.warning( - "`beam_alpha` is deprecated and will be removed in a future release. " - "Please use `ngram_lm_alpha` instead." - ) - self.cfg.beam.ngram_lm_alpha = self.cfg.beam.beam_alpha - if self.cfg.beam.kenlm_path is not None: - logging.warning( - "`kenlm_path` is deprecated and will be removed in a future release. " - "Please use `ngram_lm_model` instead." - ) - self.cfg.beam.ngram_lm_model = self.cfg.beam.kenlm_path - - if self.cfg.strategy == 'greedy': - self.decoding = ctc_greedy_decoding.GreedyCTCInfer( - blank_id=self.blank_id, - preserve_alignments=self.preserve_alignments, - compute_timestamps=self.compute_timestamps, - preserve_frame_confidence=self.preserve_frame_confidence, - confidence_method_cfg=self.confidence_method_cfg, - ) - - elif self.cfg.strategy == "greedy_batch": - self.decoding = ctc_greedy_decoding.GreedyBatchedCTCInfer( - blank_id=self.blank_id, - preserve_alignments=self.preserve_alignments, - compute_timestamps=self.compute_timestamps, - preserve_frame_confidence=self.preserve_frame_confidence, - confidence_method_cfg=self.confidence_method_cfg, - ngram_lm_model=self.cfg.greedy.get("ngram_lm_model", None), - ngram_lm_alpha=self.cfg.greedy.get("ngram_lm_alpha", 0.0), - boosting_tree=self.cfg.greedy.get("boosting_tree", None), - boosting_tree_alpha=self.cfg.greedy.get("boosting_tree_alpha", 0.0), - allow_cuda_graphs=self.cfg.greedy.get("allow_cuda_graphs", True), - tokenizer=getattr(self, 'tokenizer', None), - ) - - elif self.cfg.strategy == 'beam': - - self.decoding = ctc_beam_decoding.BeamCTCInfer( - blank_id=blank_id, - beam_size=self.cfg.beam.get('beam_size', 1), - search_type='default', - return_best_hypothesis=self.cfg.beam.get('return_best_hypothesis', True), - preserve_alignments=self.preserve_alignments, - compute_timestamps=self.compute_timestamps, - ngram_lm_alpha=self.cfg.beam.get('ngram_lm_alpha', 1.0), - beam_beta=self.cfg.beam.get('beam_beta', 0.0), - ngram_lm_model=self.cfg.beam.get('ngram_lm_model', None), - ) - - self.decoding.override_fold_consecutive_value = False - - elif self.cfg.strategy == 'pyctcdecode': - - self.decoding = ctc_beam_decoding.BeamCTCInfer( - blank_id=blank_id, - beam_size=self.cfg.beam.get('beam_size', 1), - search_type='pyctcdecode', - return_best_hypothesis=self.cfg.beam.get('return_best_hypothesis', True), - preserve_alignments=self.preserve_alignments, - compute_timestamps=self.compute_timestamps, - ngram_lm_alpha=self.cfg.beam.get('ngram_lm_alpha', 1.0), - beam_beta=self.cfg.beam.get('beam_beta', 0.0), - ngram_lm_model=self.cfg.beam.get('ngram_lm_model', None), - pyctcdecode_cfg=self.cfg.beam.get('pyctcdecode_cfg', None), - ) - - self.decoding.override_fold_consecutive_value = False - - elif self.cfg.strategy == 'flashlight': - - self.decoding = ctc_beam_decoding.BeamCTCInfer( - blank_id=blank_id, - beam_size=self.cfg.beam.get('beam_size', 1), - search_type='flashlight', - return_best_hypothesis=self.cfg.beam.get('return_best_hypothesis', True), - preserve_alignments=self.preserve_alignments, - compute_timestamps=self.compute_timestamps, - ngram_lm_alpha=self.cfg.beam.get('ngram_lm_alpha', 1.0), - beam_beta=self.cfg.beam.get('beam_beta', 0.0), - ngram_lm_model=self.cfg.beam.get('ngram_lm_model', None), - flashlight_cfg=self.cfg.beam.get('flashlight_cfg', None), - ) - - self.decoding.override_fold_consecutive_value = False - - elif self.cfg.strategy == 'wfst': - - self.decoding = ctc_beam_decoding.WfstCTCInfer( - blank_id=blank_id, - beam_size=self.cfg.wfst.get('beam_size', 1), - search_type=self.cfg.wfst.get('search_type', 'riva'), - return_best_hypothesis=self.cfg.wfst.get('return_best_hypothesis', True), - preserve_alignments=self.preserve_alignments, - compute_timestamps=self.compute_timestamps, - decoding_mode=self.cfg.wfst.get('decoding_mode', 'nbest'), - open_vocabulary_decoding=self.cfg.wfst.get('open_vocabulary_decoding', False), - beam_width=self.cfg.wfst.get('beam_width', 10.0), - lm_weight=self.cfg.wfst.get('lm_weight', 1.0), - device=self.cfg.wfst.get('device', 'cuda'), - arpa_lm_path=self.cfg.wfst.get('arpa_lm_path', None), - wfst_lm_path=self.cfg.wfst.get('wfst_lm_path', None), - riva_decoding_cfg=self.cfg.wfst.get('riva_decoding_cfg', None), - ) - - self.decoding.override_fold_consecutive_value = False - - elif self.cfg.strategy == 'beam_batch': - - self.decoding = ctc_beam_decoding.BeamBatchedCTCInfer( - blank_index=blank_id, - beam_size=self.cfg.beam.get('beam_size', 1), - return_best_hypothesis=self.cfg.beam.get('return_best_hypothesis', True), - preserve_alignments=self.preserve_alignments, - compute_timestamps=self.compute_timestamps, - ngram_lm_alpha=self.cfg.beam.get('ngram_lm_alpha', 1.0), - beam_beta=self.cfg.beam.get('beam_beta', 0.0), - beam_threshold=self.cfg.beam.get('beam_threshold', 20.0), - ngram_lm_model=self.cfg.beam.get('ngram_lm_model', None), - boosting_tree=self.cfg.beam.get("boosting_tree", None), - boosting_tree_alpha=self.cfg.beam.get("boosting_tree_alpha", 0.0), - allow_cuda_graphs=self.cfg.beam.get('allow_cuda_graphs', True), - tokenizer=getattr(self, 'tokenizer', None), - ) - - self.decoding.override_fold_consecutive_value = False - - else: - raise ValueError( - f"Incorrect decoding strategy supplied. Must be one of {possible_strategies}\n" - f"but was provided {self.cfg.strategy}" - ) - - @abstractproperty - def tokenizer_type(self): - """ - Implemented by subclass in order to get tokenizer type information for timestamps extraction. - """ - raise NotImplementedError() - - def ctc_decoder_predictions_tensor( - self, - decoder_outputs: torch.Tensor, - decoder_lengths: torch.Tensor = None, - fold_consecutive: bool = True, - return_hypotheses: bool = False, - ) -> Union[List[Hypothesis], List[List[Hypothesis]]]: - """ - Decodes a sequence of labels to words - - Args: - decoder_outputs: An integer torch.Tensor of shape [Batch, Time, {Vocabulary}] (if ``batch_index_dim == 0``) or [Time, Batch] - (if ``batch_index_dim == 1``) of integer indices that correspond to the index of some character in the - label set. - decoder_lengths: Optional tensor of length `Batch` which contains the integer lengths - of the sequence in the padded `predictions` tensor. - fold_consecutive: Bool, determine whether to perform "ctc collapse", folding consecutive tokens - into a single token. - return_hypotheses: Bool flag whether to return just the decoding predictions of the model - or a Hypothesis object that holds information such as the decoded `text`, - the `alignment` of emited by the CTC Model, and the `length` of the sequence (if available). - May also contain the log-probabilities of the decoder (if this method is called via - transcribe()) - - Returns: - A list of Hypothesis objects containing additional information. - """ - - if isinstance(decoder_outputs, torch.Tensor): - decoder_outputs = move_dimension_to_the_front(decoder_outputs, self.batch_dim_index) - - if ( - hasattr(self.decoding, 'override_fold_consecutive_value') - and self.decoding.override_fold_consecutive_value is not None - ): - logging.info( - f"Beam search requires that consecutive ctc tokens are not folded. \n" - f"Overriding provided value of `fold_consecutive` = {fold_consecutive} to " - f"{self.decoding.override_fold_consecutive_value}", - mode=logging_mode.ONCE, - ) - fold_consecutive = self.decoding.override_fold_consecutive_value - - with torch.inference_mode(): - # Resolve the forward step of the decoding strategy - hypotheses_list = self.decoding( - decoder_output=decoder_outputs, decoder_lengths=decoder_lengths - ) # type: List[List[Hypothesis]] - - # extract the hypotheses - hypotheses_list = hypotheses_list[0] # type: List[Hypothesis] - - if isinstance(hypotheses_list[0], NBestHypotheses): - if self.cfg.strategy == 'wfst': - all_hypotheses = [hyp.n_best_hypotheses for hyp in hypotheses_list] - else: - all_hypotheses = [] - - for nbest_hyp in hypotheses_list: # type: NBestHypotheses - n_hyps = nbest_hyp.n_best_hypotheses # Extract all hypotheses for this sample - decoded_hyps = self.decode_hypothesis( - n_hyps, fold_consecutive - ) # type: List[Union[Hypothesis, NBestHypotheses]] - - # If computing timestamps - if self.compute_timestamps is True: - timestamp_type = self.cfg.get('ctc_timestamp_type', 'all') - for hyp_idx in range(len(decoded_hyps)): - decoded_hyps[hyp_idx] = self.compute_ctc_timestamps(decoded_hyps[hyp_idx], timestamp_type) - - all_hypotheses.append(decoded_hyps) - - if return_hypotheses: - return all_hypotheses # type: List[List[Hypothesis]] - - # alaptev: The line below might contain a bug. Do we really want all_hyp_text to be flat? - all_hyp = [[Hypothesis(h.score, h.y_sequence, h.text) for h in hh] for hh in all_hypotheses] - return all_hyp - - else: - if self.cfg.strategy == 'wfst': - hypotheses = hypotheses_list - else: - hypotheses = self.decode_hypothesis( - hypotheses_list, fold_consecutive - ) # type: List[Union[Hypothesis, NBestHypotheses]] - - # If computing timestamps - if self.compute_timestamps is True: - # greedy decoding, can get high-level confidence scores - if return_hypotheses and (self.preserve_word_confidence or self.preserve_token_confidence): - hypotheses = self.compute_confidence(hypotheses) - else: - # remove unused token_repetitions from Hypothesis.text - for hyp in hypotheses: - hyp.text = hyp.text[:2] - timestamp_type = self.cfg.get('ctc_timestamp_type', 'all') - for hyp_idx in range(len(hypotheses)): - hypotheses[hyp_idx] = self.compute_ctc_timestamps(hypotheses[hyp_idx], timestamp_type) - - if return_hypotheses: - return hypotheses - - return [Hypothesis(h.score, h.y_sequence, h.text) for h in hypotheses] - - def decode_hypothesis( - self, hypotheses_list: List[Hypothesis], fold_consecutive: bool - ) -> List[Union[Hypothesis, NBestHypotheses]]: - """ - Decode a list of hypotheses into a list of strings. - - Args: - hypotheses_list: List of Hypothesis. - fold_consecutive: Whether to collapse the ctc blank tokens or not. - - Returns: - A list of strings. - """ - for ind in range(len(hypotheses_list)): - # Extract the integer encoded hypothesis - hyp = hypotheses_list[ind] - prediction = hyp.y_sequence - predictions_len = hyp.length if hyp.length > 0 else None - - if fold_consecutive: - if type(prediction) != list: - prediction = prediction.numpy().tolist() - - if predictions_len is not None: - prediction = prediction[:predictions_len] - - # CTC decoding procedure - decoded_prediction = [] - token_lengths = [] # preserve token lengths - token_repetitions = [] # preserve number of repetitions per token - - previous = self.blank_id - last_length = 0 - last_repetition = 1 - - for pidx, p in enumerate(prediction): - if (p != previous or previous == self.blank_id) and p != self.blank_id: - decoded_prediction.append(p) - - token_lengths.append(pidx - last_length) - last_length = pidx - token_repetitions.append(last_repetition) - last_repetition = 1 - - if p == previous and previous != self.blank_id: - last_repetition += 1 - - previous = p - - if len(token_repetitions) > 0: - token_repetitions = token_repetitions[1:] + [last_repetition] - - else: - if predictions_len is not None: - prediction = prediction[:predictions_len] - decoded_prediction = prediction[prediction != self.blank_id].tolist() - token_lengths = [1] * len(decoded_prediction) # preserve number of repetitions per token - token_repetitions = [1] * len(decoded_prediction) # preserve number of repetitions per token - - # De-tokenize the integer tokens; if not computing timestamps - if self.compute_timestamps is True: - # keep the original predictions, wrap with the number of repetitions per token - # this is done so that `ctc_decoder_predictions_tensor()` can process this hypothesis - # in order to compute exact time stamps. - hypothesis = (decoded_prediction, token_lengths, token_repetitions) - else: - hypothesis = self.decode_tokens_to_str_with_strip_punctuation(decoded_prediction) - - # Preserve this wrapped hypothesis or decoded text tokens. - hypotheses_list[ind].text = hypothesis - - return hypotheses_list - - def compute_confidence(self, hypotheses_list: List[Hypothesis]) -> List[Hypothesis]: - """ - Computes high-level (per-token and/or per-word) confidence scores for a list of hypotheses. - Assumes that `frame_confidence` is present in the hypotheses. - - Args: - hypotheses_list: List of Hypothesis. - - Returns: - A list of hypotheses with high-level confidence scores. - """ - for hyp in hypotheses_list: - if not isinstance(hyp.text, tuple) or len(hyp.text) != 3: - # the method must have been called in the wrong place - raise ValueError( - """Wrong format of the `text` attribute of a hypothesis.\n - Expected: (decoded_prediction, token_repetitions)\n - The method invocation is expected between .decode_hypothesis() and .compute_ctc_timestamps()""" - ) - token_repetitions = hyp.text[2] - hyp.text = hyp.text[:2] - token_confidence = [] - if self.exclude_blank_from_confidence: - non_blank_frame_confidence = hyp.non_blank_frame_confidence - i = 0 - for tr in token_repetitions: - # token repetition can be zero - j = i + tr - token_confidence.append(self._aggregate_confidence(non_blank_frame_confidence[i:j])) - i = j - else: - # tokens are considered to belong to the last non-blank token, if any. - token_lengths = hyp.text[1] - if len(token_lengths) > 0: - ts = token_lengths[0] - for tl in token_lengths[1:] + [len(hyp.frame_confidence)]: - token_confidence.append(self._aggregate_confidence(hyp.frame_confidence[ts : ts + tl])) - ts += tl - hyp.token_confidence = token_confidence - if self.preserve_word_confidence: - for hyp in hypotheses_list: - hyp.word_confidence = self._aggregate_token_confidence(hyp) - return hypotheses_list - - @abstractmethod - def decode_tokens_to_str(self, tokens: List[int]) -> str: - """ - Implemented by subclass in order to decoder a token id list into a string. - - Args: - tokens: List of int representing the token ids. - - Returns: - A decoded string. - """ - raise NotImplementedError() - - @abstractmethod - def decode_ids_to_tokens(self, tokens: List[int]) -> List[str]: - """ - Implemented by subclass in order to decode a token id list into a token list. - A token list is the string representation of each token id. - - Args: - tokens: List of int representing the token ids. - - Returns: - A list of decoded tokens. - """ - raise NotImplementedError() - - def decode_ids_to_str(self, tokens: List[int]) -> str: - """ - Decodes a list of tokens ids to a string. - """ - return self.decode_tokens_to_str(self.decode_ids_to_tokens(tokens)) - - def decode_tokens_to_str_with_strip_punctuation(self, tokens: List[int]) -> str: - """ - Decodes a list of tokens to a string and removes a space before supported punctuation marks. - """ - text = self.decode_ids_to_str(tokens) - - if self.supported_punctuation: - text = self.space_before_punct_pattern.sub(r'\2', text) - - return text - - def compute_ctc_timestamps(self, hypothesis: Hypothesis, timestamp_type: str = "all"): - """ - Method to compute time stamps at char/subword, and word level given some hypothesis. - Requires the input hypothesis to contain a `text` field that is the tuple. The tuple contains - - the ctc collapsed integer ids, and the number of repetitions of each token. - - Args: - hypothesis: A Hypothesis object, with a wrapped `text` field. - The `text` field must contain a tuple with two values - - The ctc collapsed integer ids - A list of integers that represents the number of repetitions per token. - timestamp_type: A str value that represents the type of time stamp calculated. - Can be one of "char", "word" "segment" or "all" - - Returns: - A Hypothesis object with a modified `timestep` value, which is now a dictionary containing - the time stamp information. - """ - assert timestamp_type in ['char', 'word', 'segment', 'all'] - - # Unpack the temporary storage, and set the decoded predictions - decoded_prediction, token_lengths = hypothesis.text - hypothesis.text = decoded_prediction - - # Retrieve offsets - char_offsets = word_offsets = None - char_offsets = self._compute_offsets(hypothesis, token_lengths, self.blank_id) - - # Assert number of offsets and hypothesis tokens are 1:1 match. - if len(char_offsets) != len(hypothesis.text): - raise ValueError( - f"`char_offsets`: {char_offsets} and `processed_tokens`: {hypothesis.text}" - " have to be of the same length, but are: " - f"`len(offsets)`: {len(char_offsets)} and `len(processed_tokens)`:" - f" {len(hypothesis.text)}" - ) - - encoded_char_offsets = copy.deepcopy(char_offsets) - - # Correctly process the token ids to chars/subwords. - # char_offsets contains chars as strings, encoded_char_offsets contains tokens corresponding to chars. - # e.g. in char_offsets, char_offsets[i]["char"] = "token", in encoded_char_offsets, encoded_char_offsets[i]["char"] = "_token" - # These 2 dictionaries are used to get the word offsets. - for i, char in enumerate(hypothesis.text): - encoded_char_offsets[i]["char"] = self.decode_ids_to_tokens([char])[0] - char_offsets[i]["char"] = self.decode_tokens_to_str([encoded_char_offsets[i]["char"]]) - - encoded_char_offsets, char_offsets = self._refine_timestamps( - encoded_char_offsets=encoded_char_offsets, - char_offsets=char_offsets, - supported_punctuation=self.supported_punctuation, - ) - - # retrieve word offsets from character offsets - word_offsets = None - if timestamp_type in ['word', 'segment', 'all']: - word_offsets = get_words_offsets( - char_offsets=char_offsets, - encoded_char_offsets=encoded_char_offsets, - word_delimiter_char=self.word_seperator, - supported_punctuation=self.supported_punctuation, - tokenizer_type=self.tokenizer_type, - decode_tokens_to_str=self.decode_tokens_to_str, - ) - - segment_offsets = None - if timestamp_type in ['segment', 'all']: - segment_offsets = get_segment_offsets( - word_offsets, - segment_delimiter_tokens=self.segment_seperators, - supported_punctuation=self.supported_punctuation, - segment_gap_threshold=self.segment_gap_threshold, - ) - - # attach results - if len(hypothesis.timestamp) > 0: - timestep_info = hypothesis.timestamp - else: - timestep_info = [] - - # Setup defaults - hypothesis.timestamp = {"timestep": timestep_info} - - # Add char / subword time stamps - if char_offsets is not None and timestamp_type in ['char', 'all']: - hypothesis.timestamp['char'] = char_offsets - - # Add word time stamps - if word_offsets is not None and timestamp_type in ['word', 'all']: - hypothesis.timestamp['word'] = word_offsets - - # Add segment time stamps - if segment_offsets is not None and timestamp_type in ['segment', 'all']: - hypothesis.timestamp['segment'] = segment_offsets - - # Convert the token indices to text - hypothesis.text = self.decode_tokens_to_str_with_strip_punctuation(hypothesis.text) - - return hypothesis - - @staticmethod - def _compute_offsets( - hypothesis: Hypothesis, token_lengths: List[int], ctc_token: int - ) -> List[Dict[str, Union[str, int]]]: - """ - Utility method that calculates the indidual time indices where a token starts and ends. - - Args: - hypothesis: A Hypothesis object that contains `text` field that holds the character / subword token - emitted at every time step after ctc collapse. - token_lengths: A list of ints representing the lengths of each emitted token. - ctc_token: The integer of the ctc blank token used during ctc collapse. - - Returns: - - """ - start_index = 0 - - # If the exact timestep information is available, utilize the 1st non-ctc blank token timestep - # as the start index. - if hypothesis.timestamp is not None and len(hypothesis.timestamp) > 0: - start_index = max(0, hypothesis.timestamp[0] - 1) - - # Construct the start and end indices brackets - end_indices = np.asarray(token_lengths).cumsum() - start_indices = np.concatenate(([start_index], end_indices[:-1])) - - # Merge the results per token into a list of dictionaries - offsets = [ - {"char": t, "start_offset": s, "end_offset": e} - for t, s, e in zip(hypothesis.text, start_indices, end_indices) - ] - - # Filter out CTC token - offsets = list(filter(lambda offsets: offsets["char"] != ctc_token, offsets)) - return offsets - - @staticmethod - def _refine_timestamps( - encoded_char_offsets: List[Dict[str, Union[str, int]]], - char_offsets: List[Dict[str, Union[str, int]]], - supported_punctuation: Optional[Set] = None, - ) -> List[Dict[str, Union[str, int]]]: - - if not supported_punctuation: - return encoded_char_offsets, char_offsets - - for i, offset in enumerate(char_offsets): - # Check if token is a punctuation mark - # If so, set its end offset as its start offset - # This is done because there was observed a behaviour for CTC decoding, - # when punctuation marks are predicted for long frames - if offset['char'] and offset['char'][0] in supported_punctuation and i > 0: - encoded_char_offsets[i]['end_offset'] = offset['end_offset'] = offset['start_offset'] - - return encoded_char_offsets, char_offsets - - @property - def preserve_alignments(self): - return self._preserve_alignments - - @preserve_alignments.setter - def preserve_alignments(self, value): - self._preserve_alignments = value - - if hasattr(self, 'decoding'): - self.decoding.preserve_alignments = value - - @property - def compute_timestamps(self): - return self._compute_timestamps - - @compute_timestamps.setter - def compute_timestamps(self, value): - self._compute_timestamps = value - - if hasattr(self, 'decoding'): - self.decoding.compute_timestamps = value - - @property - def preserve_frame_confidence(self): - return self._preserve_frame_confidence - - @preserve_frame_confidence.setter - def preserve_frame_confidence(self, value): - self._preserve_frame_confidence = value - - if hasattr(self, 'decoding'): - self.decoding.preserve_frame_confidence = value - - -class CTCDecoding(AbstractCTCDecoding): - """ - Used for performing CTC auto-regressive / non-auto-regressive decoding of the logprobs for character - based models. - - Args: - decoding_cfg: A dict-like object which contains the following key-value pairs. - - strategy: - str value which represents the type of decoding that can occur. - Possible values are : - - - greedy (for greedy decoding). - - - beam (for DeepSpeed KenLM based decoding). - - compute_timestamps: - A bool flag, which determines whether to compute the character/subword, or - word based timestamp mapping the output log-probabilities to discrite intervals of timestamps. - The timestamps will be available in the returned Hypothesis.timestep as a dictionary. - - ctc_timestamp_type: - A str value, which represents the types of timestamps that should be calculated. - Can take the following values - "char" for character/subword time stamps, "word" for word level - time stamps and "all" (default), for both character level and word level time stamps. - - word_seperator: - Str token representing the seperator between words. - - segment_seperators: - List containing tokens representing the seperator(s) between segments. - - segment_gap_threshold: - The threshold (in frames) that caps the gap between two words necessary for forming the segments. - - preserve_alignments: - Bool flag which preserves the history of logprobs generated during - decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `logprobs` in it. Here, `logprobs` is a torch.Tensors. - - confidence_cfg: - A dict-like object which contains the following key-value pairs related to confidence - scores. In order to obtain hypotheses with confidence scores, please utilize - `ctc_decoder_predictions_tensor` function with the `preserve_frame_confidence` flag set to True. - - preserve_frame_confidence: - Bool flag which preserves the history of per-frame confidence scores - generated during decoding. When set to true, the Hypothesis will contain - the non-null value for `frame_confidence` in it. Here, `frame_confidence` is a List of floats. - - preserve_token_confidence: - Bool flag which preserves the history of per-token confidence scores - generated during greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `token_confidence` in it. Here, `token_confidence` is a List of floats. - - The length of the list corresponds to the number of recognized tokens. - - preserve_word_confidence: - Bool flag which preserves the history of per-word confidence scores - generated during greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `word_confidence` in it. Here, `word_confidence` is a List of floats. - - The length of the list corresponds to the number of recognized words. - - exclude_blank: - Bool flag indicating that blank token confidence scores are to be excluded - from the `token_confidence`. - - aggregation: - Which aggregation type to use for collapsing per-token confidence into per-word confidence. - Valid options are `mean`, `min`, `max`, `prod`. - - tdt_include_duration: Bool flag indicating that the duration confidence scores are to be calculated and - attached to the regular frame confidence, - making TDT frame confidence element a pair: (`prediction_confidence`, `duration_confidence`). - - method_cfg: - A dict-like object which contains the method name and settings to compute per-frame - confidence scores. - - name: - The method name (str). - Supported values: - - - 'max_prob' for using the maximum token probability as a confidence. - - - 'entropy' for using a normalized entropy of a log-likelihood vector. - - entropy_type: - Which type of entropy to use (str). - Used if confidence_method_cfg.name is set to `entropy`. - Supported values: - - - 'gibbs' for the (standard) Gibbs entropy. If the alpha (α) is provided, - the formula is the following: H_α = -sum_i((p^α_i)*log(p^α_i)). - Note that for this entropy, the alpha should comply the following inequality: - (log(V)+2-sqrt(log^2(V)+4))/(2*log(V)) <= α <= (1+log(V-1))/log(V-1) - where V is the model vocabulary size. - - - 'tsallis' for the Tsallis entropy with the Boltzmann constant one. - Tsallis entropy formula is the following: H_α = 1/(α-1)*(1-sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/Tsallis_entropy - - - 'renyi' for the Rényi entropy. - Rényi entropy formula is the following: H_α = 1/(1-α)*log_2(sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/R%C3%A9nyi_entropy - - alpha: - Power scale for logsoftmax (α for entropies). Here we restrict it to be > 0. - When the alpha equals one, scaling is not applied to 'max_prob', - and any entropy type behaves like the Shannon entropy: H = -sum_i(p_i*log(p_i)) - - entropy_norm: - A mapping of the entropy value to the interval [0,1]. - Supported values: - - - 'lin' for using the linear mapping. - - - 'exp' for using exponential mapping with linear shift. - - batch_dim_index: - Index of the batch dimension of ``targets`` and ``predictions`` parameters of - ``ctc_decoder_predictions_tensor`` methods. Can be either 0 or 1. - - The config may further contain the following sub-dictionaries: - - "greedy": - preserve_alignments: Same as above, overrides above value. - compute_timestamps: Same as above, overrides above value. - preserve_frame_confidence: Same as above, overrides above value. - confidence_method_cfg: Same as above, overrides confidence_cfg.method_cfg. - - "beam": - beam_size: - int, defining the beam size for beam search. Must be >= 1. - If beam_size == 1, will perform cached greedy search. This might be slightly different - results compared to the greedy search above. - - return_best_hypothesis: - optional bool, whether to return just the best hypothesis or all of the - hypotheses after beam search has concluded. This flag is set by default. - - ngram_lm_alpha: - float, the strength of the Language model on the final score of a token. - final_score = acoustic_score + ngram_lm_alpha * lm_score + beam_beta * seq_length. - - beam_beta: - float, the strength of the sequence length penalty on the final score of a token. - final_score = acoustic_score + ngram_lm_alpha * lm_score + beam_beta * seq_length. - - ngram_lm_model: - str, path to a KenLM ARPA or .binary file (depending on the strategy chosen). - If the path is invalid (file is not found at path), will raise a deferred error at the moment - of calculation of beam search, so that users may update / change the decoding strategy - to point to the correct file. - - blank_id: The id of the RNNT blank token. - """ - - def __init__( - self, - decoding_cfg, - vocabulary, - ): - blank_id = len(vocabulary) - self.vocabulary = vocabulary - self.labels_map = dict([(i, vocabulary[i]) for i in range(len(vocabulary))]) - - supported_punctuation = extract_punctuation_from_vocab(vocabulary) - - super().__init__(decoding_cfg=decoding_cfg, blank_id=blank_id, supported_punctuation=supported_punctuation) - - # Finalize Beam Search Decoding framework - if isinstance(self.decoding, ctc_beam_decoding.AbstractBeamCTCInfer): - self.decoding.set_vocabulary(self.vocabulary) - self.decoding.set_decoding_type('char') - - @property - def tokenizer_type(self): - return "char" - - def _aggregate_token_confidence(self, hypothesis: Hypothesis) -> List[float]: - """ - Implemented by subclass in order to aggregate token confidence to a word-level confidence. - - Args: - hypothesis: Hypothesis - - Returns: - A list of word-level confidence scores. - """ - return self._aggregate_token_confidence_chars( - self.decode_tokens_to_str(hypothesis.text[0]).split(), hypothesis.token_confidence - ) - - def decode_tokens_to_str(self, tokens: List[str]) -> str: - """ - Implemented by subclass in order to decoder a token list into a string. - - Args: - tokens: List of str representing the token str. - - Returns: - A decoded string. - """ - hypothesis = ''.join(tokens) - return hypothesis - - def decode_ids_to_tokens(self, tokens: List[int]) -> List[str]: - """ - Implemented by subclass in order to decode a token id list into a token list. - A token list is the string representation of each token id. - - Args: - tokens: List of int representing the token ids. - - Returns: - A list of decoded tokens. - """ - token_list = [self.labels_map[c] for c in tokens if c != self.blank_id] - return token_list - - -class CTCBPEDecoding(AbstractCTCDecoding): - """ - Used for performing CTC auto-regressive / non-auto-regressive decoding of the logprobs for subword based - models. - - Args: - decoding_cfg: A dict-like object which contains the following key-value pairs. - - strategy: - str value which represents the type of decoding that can occur. - Possible values are : - - - greedy (for greedy decoding). - - - beam (for DeepSpeed KenLM based decoding). - - compute_timestamps: - A bool flag, which determines whether to compute the character/subword, or - word based timestamp mapping the output log-probabilities to discrite intervals of timestamps. - The timestamps will be available in the returned Hypothesis.timestep as a dictionary. - - ctc_timestamp_type: - A str value, which represents the types of timestamps that should be calculated. - Can take the following values - "char" for character/subword time stamps, "word" for word level - time stamps and "all" (default), for both character level and word level time stamps. - - word_seperator: - Str token representing the seperator between words. - - preserve_alignments: - Bool flag which preserves the history of logprobs generated during - decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `logprobs` in it. Here, `logprobs` is a torch.Tensors. - - confidence_cfg: - A dict-like object which contains the following key-value pairs related to confidence - scores. In order to obtain hypotheses with confidence scores, please utilize - `ctc_decoder_predictions_tensor` function with the `preserve_frame_confidence` flag set to True. - - preserve_frame_confidence: - Bool flag which preserves the history of per-frame confidence scores - generated during decoding. When set to true, the Hypothesis will contain - the non-null value for `frame_confidence` in it. Here, `frame_confidence` is a List of floats. - - preserve_token_confidence: - Bool flag which preserves the history of per-token confidence scores - generated during greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `token_confidence` in it. Here, `token_confidence` is a List of floats. - - The length of the list corresponds to the number of recognized tokens. - - preserve_word_confidence: - Bool flag which preserves the history of per-word confidence scores - generated during greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `word_confidence` in it. Here, `word_confidence` is a List of floats. - - The length of the list corresponds to the number of recognized words. - - exclude_blank: - Bool flag indicating that blank token confidence scores are to be excluded - from the `token_confidence`. - - aggregation: - Which aggregation type to use for collapsing per-token confidence into per-word confidence. - Valid options are `mean`, `min`, `max`, `prod`. - - tdt_include_duration: Bool flag indicating that the duration confidence scores are to be calculated and - attached to the regular frame confidence, - making TDT frame confidence element a pair: (`prediction_confidence`, `duration_confidence`). - - method_cfg: - A dict-like object which contains the method name and settings to compute per-frame - confidence scores. - - name: - The method name (str). - Supported values: - - - 'max_prob' for using the maximum token probability as a confidence. - - - 'entropy' for using a normalized entropy of a log-likelihood vector. - - entropy_type: - Which type of entropy to use (str). - Used if confidence_method_cfg.name is set to `entropy`. - Supported values: - - - 'gibbs' for the (standard) Gibbs entropy. If the alpha (α) is provided, - the formula is the following: H_α = -sum_i((p^α_i)*log(p^α_i)). - Note that for this entropy, the alpha should comply the following inequality: - (log(V)+2-sqrt(log^2(V)+4))/(2*log(V)) <= α <= (1+log(V-1))/log(V-1) - where V is the model vocabulary size. - - - 'tsallis' for the Tsallis entropy with the Boltzmann constant one. - Tsallis entropy formula is the following: H_α = 1/(α-1)*(1-sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/Tsallis_entropy - - - 'renyi' for the Rényi entropy. - Rényi entropy formula is the following: H_α = 1/(1-α)*log_2(sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/R%C3%A9nyi_entropy - - alpha: - Power scale for logsoftmax (α for entropies). Here we restrict it to be > 0. - When the alpha equals one, scaling is not applied to 'max_prob', - and any entropy type behaves like the Shannon entropy: H = -sum_i(p_i*log(p_i)) - - entropy_norm: - A mapping of the entropy value to the interval [0,1]. - Supported values: - - - 'lin' for using the linear mapping. - - - 'exp' for using exponential mapping with linear shift. - - batch_dim_index: - Index of the batch dimension of ``targets`` and ``predictions`` parameters of - ``ctc_decoder_predictions_tensor`` methods. Can be either 0 or 1. - - The config may further contain the following sub-dictionaries: - - "greedy": - preserve_alignments: Same as above, overrides above value. - compute_timestamps: Same as above, overrides above value. - preserve_frame_confidence: Same as above, overrides above value. - confidence_method_cfg: Same as above, overrides confidence_cfg.method_cfg. - - "beam": - beam_size: - int, defining the beam size for beam search. Must be >= 1. - If beam_size == 1, will perform cached greedy search. This might be slightly different - results compared to the greedy search above. - - return_best_hypothesis: - optional bool, whether to return just the best hypothesis or all of the - hypotheses after beam search has concluded. This flag is set by default. - - ngram_lm_alpha: - float, the strength of the Language model on the final score of a token. - final_score = acoustic_score + ngram_lm_alpha * lm_score + beam_beta * seq_length. - - beam_beta: - float, the strength of the sequence length penalty on the final score of a token. - final_score = acoustic_score + ngram_lm_alpha * lm_score + beam_beta * seq_length. - - ngram_lm_model: - str, path to a KenLM ARPA or .binary file (depending on the strategy chosen). - If the path is invalid (file is not found at path), will raise a deferred error at the moment - of calculation of beam search, so that users may update / change the decoding strategy - to point to the correct file. - - boosting_tree: - BoostingTreeModelConfig, config for the boosting tree model - - boosting_tree_alpha: - float, the strength of the boosting tree model on the final score of a token. - final_score = acoustic_score + boosting_tree_alpha * boosting_tree_score + beam_beta * seq_length. - - tokenizer: NeMo tokenizer object, which inherits from TokenizerSpec. - """ - - def __init__(self, decoding_cfg, tokenizer: TokenizerSpec): - blank_id = tokenizer.tokenizer.vocab_size - self.tokenizer = tokenizer - - if hasattr(tokenizer, 'supported_punctuation'): - supported_punctuation = tokenizer.supported_punctuation - else: - supported_punctuation = extract_punctuation_from_vocab(tokenizer.vocab) - - super().__init__(decoding_cfg=decoding_cfg, blank_id=blank_id, supported_punctuation=supported_punctuation) - - # Finalize Beam Search Decoding framework - if isinstance(self.decoding, ctc_beam_decoding.AbstractBeamCTCInfer): - if hasattr(self.tokenizer.tokenizer, 'get_vocab'): - vocab_dict = self.tokenizer.tokenizer.get_vocab() - if isinstance(self.tokenizer.tokenizer, DummyTokenizer): # AggregateTokenizer.DummyTokenizer - vocab = vocab_dict - else: - vocab = list(vocab_dict.keys()) - self.decoding.set_vocabulary(vocab) - self.decoding.set_tokenizer(tokenizer) - else: - logging.warning("Could not resolve the vocabulary of the tokenizer !") - - self.decoding.set_decoding_type('subword') - - @property - def tokenizer_type(self): - return define_spe_tokenizer_type(self.tokenizer.vocab) - - def _aggregate_token_confidence(self, hypothesis: Hypothesis) -> List[float]: - """ - Implemented by subclass in order to aggregate token confidence to a word-level confidence. - - **Note**: Only supports Sentencepiece based tokenizers! - - Args: - hypothesis: Hypothesis - - Returns: - A list of word-level confidence scores. - """ - return self._aggregate_token_confidence_subwords_sentencepiece( - self.decode_tokens_to_str(hypothesis.text[0]).split(), hypothesis.token_confidence, hypothesis.text[0] - ) - - def decode_tokens_to_str(self, tokens: List[str]) -> str: - """ - Implemented by subclass in order to decoder a token list into a string. - - Args: - tokens: List of str representing the tokens. - - Returns: - A decoded string. - """ - hypothesis = self.tokenizer.tokens_to_text(tokens) - return hypothesis - - def decode_ids_to_tokens(self, tokens: List[int]) -> List[str]: - """ - Implemented by subclass in order to decode a token id list into a token list. - A token list is the string representation of each token id. - - Args: - tokens: List of int representing the token ids. - - Returns: - A list of decoded tokens. - """ - token_list = self.tokenizer.ids_to_tokens(tokens) - return token_list - - -@dataclass -class CTCDecodingConfig: - strategy: str = "greedy_batch" - - # preserve decoding alignments - preserve_alignments: Optional[bool] = None - - # compute ctc time stamps - compute_timestamps: Optional[bool] = None - - # token representing word seperator - word_seperator: str = " " - - # tokens representing segments seperators - segment_seperators: Optional[List[str]] = field(default_factory=lambda: [".", "!", "?"]) - - # threshold (in frames) that caps the gap between two words necessary for forming the segments - segment_gap_threshold: Optional[int] = None - - # type of timestamps to calculate - ctc_timestamp_type: str = "all" # can be char, word or all for both - - # batch dimension - batch_dim_index: int = 0 - - # greedy decoding config - greedy: ctc_greedy_decoding.GreedyCTCInferConfig = field( - default_factory=lambda: ctc_greedy_decoding.GreedyCTCInferConfig() - ) - - # beam decoding config - beam: ctc_beam_decoding.BeamCTCInferConfig = field( - default_factory=lambda: ctc_beam_decoding.BeamCTCInferConfig(beam_size=4) - ) - - # wfst decoding config - wfst: ctc_beam_decoding.WfstCTCInferConfig = field( - default_factory=lambda: ctc_beam_decoding.WfstCTCInferConfig(beam_size=4) - ) - - # confidence config - confidence_cfg: ConfidenceConfig = field(default_factory=lambda: ConfidenceConfig()) - - # can be used to change temperature for decoding - temperature: float = 1.0 - - -@dataclass -class CTCBPEDecodingConfig(CTCDecodingConfig): - pass diff --git a/nemo/collections/asr/parts/submodules/ctc_greedy_decoding.py b/nemo/collections/asr/parts/submodules/ctc_greedy_decoding.py deleted file mode 100644 index 7e587fd75c441c14a7666454c549f8eeb2316259..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/ctc_greedy_decoding.py +++ /dev/null @@ -1,1032 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from dataclasses import dataclass, field -from pathlib import Path -from typing import List, Optional, Union - -import numpy as np -import torch -from omegaconf import DictConfig, OmegaConf - -from nemo.collections.asr.parts.context_biasing import BoostingTreeModelConfig, GPUBoostingTreeModel -from nemo.collections.asr.parts.submodules.ngram_lm import NGramGPULanguageModel -from nemo.collections.asr.parts.utils import rnnt_utils -from nemo.collections.asr.parts.utils.asr_confidence_utils import ConfidenceMethodConfig, ConfidenceMethodMixin -from nemo.collections.common.parts.optional_cuda_graphs import WithOptionalCudaGraphs -from nemo.collections.common.tokenizers.tokenizer_spec import TokenizerSpec -from nemo.core.classes import Typing, typecheck -from nemo.core.neural_types import HypothesisType, LengthsType, LogprobsType, NeuralType -from nemo.core.utils.cuda_python_utils import ( - NeMoCUDAPythonException, - check_cuda_python_cuda_graphs_conditional_nodes_supported, - cu_call, - run_nvrtc, - with_conditional_node, -) -from nemo.core.utils.optional_libs import CUDA_PYTHON_AVAILABLE, cuda_python_required -from nemo.utils import logging, logging_mode -from nemo.utils.enum import PrettyStrEnum - -if CUDA_PYTHON_AVAILABLE: - from cuda.bindings import runtime as cudart - -NEG_INF = float("-inf") - - -class CTCDecoderCudaGraphsState: - """ - State for greedy CTC with NGPU-LM decoding. Used only with CUDA graphs. - In initialization phase it is possible to assign values (tensors) to the state. - For algorithm code the storage should be reused (prefer copy data instead of assigning tensors). - """ - - max_time: int # maximum length of internal storage for time dimension - batch_size: int # (maximum) length of internal storage for batch dimension - device: torch.device # device to store preallocated tensors - float_dtype: torch.dtype - - frame_idx: torch.Tensor - active_mask: torch.Tensor - - decoder_outputs: torch.Tensor # decoder output (probs) - decoder_lengths: torch.Tensor # decoder output lengths - - labels: torch.Tensor # storage for current labels - last_labels: torch.Tensor # storage for previous labels - scores: torch.Tensor # storage for current scores - - batch_indices: torch.Tensor # indices of elements in batch (constant, range [0, batch_size-1]) - - batch_lm_states: Optional[torch.Tensor] = None - lm_scores: Optional[torch.Tensor] = None - batch_lm_states_candidates: Optional[torch.Tensor] = None - - prediction_labels: torch.Tensor - prediction_logprobs: torch.Tensor - - full_graph = None - - def __init__( - self, - batch_size: int, - max_time: int, - vocab_dim: int, - device: torch.device, - float_dtype: torch.dtype, - ): - """ - - Args: - batch_size: batch size for encoder output storage - max_time: maximum time for encoder output storage - vocab_dim: number of vocabulary tokens (including blank) - device: device to store tensors - float_dtype: default float dtype for tensors (should match projected encoder output) - """ - self.device = device - self.float_dtype = float_dtype - self.batch_size = batch_size - self.max_time = max_time - - self.frame_idx = torch.tensor( - 0, dtype=torch.long, device=device - ) # current frame index for each utterance (used to check if the decoding is finished) - self.active_mask = torch.tensor(True, dtype=torch.bool, device=device) - - self.decoder_outputs = torch.zeros( - (self.batch_size, self.max_time, vocab_dim), - dtype=float_dtype, - device=self.device, - ) - self.decoder_lengths = torch.zeros((self.batch_size,), dtype=torch.long, device=self.device) - - self.labels = torch.zeros([self.batch_size], dtype=torch.long, device=self.device) - self.last_labels = torch.zeros([self.batch_size], dtype=torch.long, device=self.device) - self.scores = torch.zeros([self.batch_size], dtype=float_dtype, device=self.device) - - # indices of elements in batch (constant) - self.batch_indices = torch.arange(self.batch_size, dtype=torch.long, device=self.device) - - # LM states - self.batch_lm_states = torch.zeros([batch_size], dtype=torch.long, device=device) - - self.predictions_labels = torch.zeros([batch_size, max_time], device=device, dtype=torch.long) - self.predictions_logprobs = torch.zeros([batch_size, max_time], device=device, dtype=float_dtype) - - def need_reinit(self, logits: torch.Tensor) -> bool: - """Check if need to reinit state: larger batch_size/max_time, or new device""" - return ( - self.batch_size < logits.shape[0] - or self.max_time < logits.shape[1] - or self.device.index != logits.device.index - ) - - -def pack_hypotheses( - hypotheses: List[rnnt_utils.Hypothesis], - logitlen: torch.Tensor, -) -> List[rnnt_utils.Hypothesis]: - - if logitlen is not None: - if hasattr(logitlen, 'cpu'): - logitlen_cpu = logitlen.to('cpu') - else: - logitlen_cpu = logitlen - - for idx, hyp in enumerate(hypotheses): # type: rnnt_utils.Hypothesis - hyp.y_sequence = torch.tensor(hyp.y_sequence, dtype=torch.long) - - if logitlen is not None: - hyp.length = logitlen_cpu[idx] - - if hyp.dec_state is not None: - hyp.dec_state = _states_to_device(hyp.dec_state) - - return hypotheses - - -def _states_to_device(dec_state, device='cpu'): - if torch.is_tensor(dec_state): - dec_state = dec_state.to(device) - - elif isinstance(dec_state, (list, tuple)): - dec_state = tuple(_states_to_device(dec_i, device) for dec_i in dec_state) - - return dec_state - - -_DECODER_LENGTHS_NONE_WARNING = "Passing in decoder_lengths=None for CTC decoding is likely to be an error, since it is unlikely that each element of your batch has exactly the same length. decoder_lengths will default to decoder_output.shape[0]." - - -class GreedyCTCInfer(Typing, ConfidenceMethodMixin): - """A greedy CTC decoder. - - Provides a common abstraction for sample level and batch level greedy decoding. - - Args: - blank_index: int index of the blank token. Can be 0 or len(vocabulary). - preserve_alignments: Bool flag which preserves the history of logprobs generated during - decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `logprobs` in it. Here, `logprobs` is a torch.Tensors. - compute_timestamps: A bool flag, which determines whether to compute the character/subword, or - word based timestamp mapping the output log-probabilities to discrite intervals of timestamps. - The timestamps will be available in the returned Hypothesis.timestep as a dictionary. - preserve_frame_confidence: Bool flag which preserves the history of per-frame confidence scores - generated during decoding. When set to true, the Hypothesis will contain - the non-null value for `frame_confidence` in it. Here, `frame_confidence` is a List of floats. - confidence_method_cfg: A dict-like object which contains the method name and settings to compute per-frame - confidence scores. - - name: The method name (str). - Supported values: - - 'max_prob' for using the maximum token probability as a confidence. - - 'entropy' for using a normalized entropy of a log-likelihood vector. - - entropy_type: Which type of entropy to use (str). Used if confidence_method_cfg.name is set to `entropy`. - Supported values: - - 'gibbs' for the (standard) Gibbs entropy. If the alpha (α) is provided, - the formula is the following: H_α = -sum_i((p^α_i)*log(p^α_i)). - Note that for this entropy, the alpha should comply the following inequality: - (log(V)+2-sqrt(log^2(V)+4))/(2*log(V)) <= α <= (1+log(V-1))/log(V-1) - where V is the model vocabulary size. - - 'tsallis' for the Tsallis entropy with the Boltzmann constant one. - Tsallis entropy formula is the following: H_α = 1/(α-1)*(1-sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/Tsallis_entropy - - 'renyi' for the Rényi entropy. - Rényi entropy formula is the following: H_α = 1/(1-α)*log_2(sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/R%C3%A9nyi_entropy - - alpha: Power scale for logsoftmax (α for entropies). Here we restrict it to be > 0. - When the alpha equals one, scaling is not applied to 'max_prob', - and any entropy type behaves like the Shannon entropy: H = -sum_i(p_i*log(p_i)) - - entropy_norm: A mapping of the entropy value to the interval [0,1]. - Supported values: - - 'lin' for using the linear mapping. - - 'exp' for using exponential mapping with linear shift. - - """ - - @property - def input_types(self): - """Returns definitions of module input ports.""" - # Input can be of dimension - - # ('B', 'T', 'D') [Log probs] or ('B', 'T') [Labels] - - return { - "decoder_output": NeuralType(None, LogprobsType()), - "decoder_lengths": NeuralType(tuple('B'), LengthsType()), - } - - @property - def output_types(self): - """Returns definitions of module output ports.""" - return {"predictions": [NeuralType(elements_type=HypothesisType())]} - - def __init__( - self, - blank_id: int, - preserve_alignments: bool = False, - compute_timestamps: bool = False, - preserve_frame_confidence: bool = False, - confidence_method_cfg: Optional[DictConfig] = None, - ): - super().__init__() - - self.blank_id = blank_id - self.preserve_alignments = preserve_alignments - # we need timestamps to extract non-blank per-frame confidence - self.compute_timestamps = compute_timestamps | preserve_frame_confidence - self.preserve_frame_confidence = preserve_frame_confidence - - # set confidence calculation method - self._init_confidence_method(confidence_method_cfg) - - @typecheck() - def forward( - self, - decoder_output: torch.Tensor, - decoder_lengths: Optional[torch.Tensor], - ): - """Returns a list of hypotheses given an input batch of the encoder hidden embedding. - Output token is generated auto-repressively. - - Args: - decoder_output: A tensor of size (batch, timesteps, features) or (batch, timesteps) (each timestep is a label). - decoder_lengths: list of int representing the length of each sequence - output sequence. - - Returns: - packed list containing batch number of sentences (Hypotheses). - """ - - logging.warning( - "CTC decoding strategy 'greedy' is slower than 'greedy_batch', which implements the same exact interface. Consider changing your strategy to 'greedy_batch' for a free performance improvement.", - mode=logging_mode.ONCE, - ) - - if decoder_lengths is None: - logging.warning(_DECODER_LENGTHS_NONE_WARNING, mode=logging_mode.ONCE) - - with torch.inference_mode(): - hypotheses = [] - # Process each sequence independently - - if decoder_output.is_cuda: - # This two-liner is around twenty times faster than: - # `prediction_cpu_tensor = decoder_output.cpu()` - # cpu() does not use pinned memory, meaning that a slow pageable - # copy must be done instead. - prediction_cpu_tensor = torch.empty( - decoder_output.shape, dtype=decoder_output.dtype, device=torch.device("cpu"), pin_memory=True - ) - prediction_cpu_tensor.copy_(decoder_output, non_blocking=True) - else: - prediction_cpu_tensor = decoder_output - - if decoder_lengths is not None and isinstance(decoder_lengths, torch.Tensor): - # Before this change, self._greedy_decode_labels would copy - # each scalar from GPU to CPU one at a time, in the line: - # prediction = prediction[:out_len] - # Doing one GPU to CPU copy ahead of time amortizes that overhead. - decoder_lengths = decoder_lengths.cpu() - - if prediction_cpu_tensor.ndim < 2 or prediction_cpu_tensor.ndim > 3: - raise ValueError( - f"`decoder_output` must be a tensor of shape [B, T] (labels, int) or " - f"[B, T, V] (log probs, float). Provided shape = {prediction_cpu_tensor.shape}" - ) - - # determine type of input - logprobs or labels - if prediction_cpu_tensor.ndim == 2: # labels - greedy_decode = self._greedy_decode_labels - else: - greedy_decode = self._greedy_decode_logprobs - - for ind in range(prediction_cpu_tensor.shape[0]): - out_len = decoder_lengths[ind] if decoder_lengths is not None else None - hypothesis = greedy_decode(prediction_cpu_tensor[ind], out_len) - hypotheses.append(hypothesis) - - # Pack results into Hypotheses - packed_result = pack_hypotheses(hypotheses, decoder_lengths) - - return (packed_result,) - - @torch.no_grad() - def _greedy_decode_logprobs(self, x: torch.Tensor, out_len: Optional[torch.Tensor]): - # x: [T, D] - # out_len: [seq_len] - - # Initialize blank state and empty label set in Hypothesis - hypothesis = rnnt_utils.Hypothesis(score=0.0, y_sequence=[], dec_state=None, timestamp=[], last_token=None) - prediction = x.cpu() - - if out_len is not None: - prediction = prediction[:out_len] - - prediction_logprobs, prediction_labels = prediction.max(dim=-1) - - non_blank_ids = prediction_labels != self.blank_id - hypothesis.y_sequence = prediction_labels.tolist() - hypothesis.score = (prediction_logprobs[non_blank_ids]).sum() - - if self.preserve_alignments: - # Preserve the logprobs, as well as labels after argmax - hypothesis.alignments = (prediction.clone(), prediction_labels.clone()) - - if self.compute_timestamps: - hypothesis.timestamp = torch.nonzero(non_blank_ids, as_tuple=False)[:, 0].tolist() - - if self.preserve_frame_confidence: - hypothesis.frame_confidence = self._get_confidence(prediction) - - return hypothesis - - @torch.no_grad() - def _greedy_decode_labels(self, x: torch.Tensor, out_len: Optional[torch.Tensor]): - # x: [T] - # out_len: [seq_len] - - # Initialize blank state and empty label set in Hypothesis - hypothesis = rnnt_utils.Hypothesis(score=0.0, y_sequence=[], dec_state=None, timestamp=[], last_token=None) - prediction_labels = x.cpu() - - if out_len is not None: - prediction_labels = prediction_labels[:out_len] - - non_blank_ids = prediction_labels != self.blank_id - hypothesis.y_sequence = prediction_labels.tolist() - hypothesis.score = -1.0 - - if self.preserve_alignments: - raise ValueError("Requested for alignments, but predictions provided were labels, not log probabilities.") - - if self.compute_timestamps: - hypothesis.timestamp = torch.nonzero(non_blank_ids, as_tuple=False)[:, 0].tolist() - - if self.preserve_frame_confidence: - raise ValueError( - "Requested for per-frame confidence, but predictions provided were labels, not log probabilities." - ) - - return hypothesis - - def __call__(self, *args, **kwargs): - return self.forward(*args, **kwargs) - - -class GreedyBatchedCTCInfer(Typing, ConfidenceMethodMixin, WithOptionalCudaGraphs): - """A vectorized greedy CTC decoder. - - This is basically always faster than GreedyCTCInfer, and supports - the same interface. See issue #8891 on github for what is wrong - with GreedyCTCInfer. GreedyCTCInfer loops over each element in the - batch, running kernels at batch size one. CPU overheads end up - dominating. This implementation does appropriate masking to - appropriately do the same operation in a batched manner. - - Args: - blank_index: int index of the blank token. Can be 0 or len(vocabulary). - preserve_alignments: Bool flag which preserves the history of logprobs generated during - decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `logprobs` in it. Here, `logprobs` is a torch.Tensors. - compute_timestamps: A bool flag, which determines whether to compute the character/subword, or - word based timestamp mapping the output log-probabilities to discrite intervals of timestamps. - The timestamps will be available in the returned Hypothesis.timestep as a dictionary. - preserve_frame_confidence: Bool flag which preserves the history of per-frame confidence scores - generated during decoding. When set to true, the Hypothesis will contain - the non-null value for `frame_confidence` in it. Here, `frame_confidence` is a List of floats. - confidence_method_cfg: A dict-like object which contains the method name and settings to compute per-frame - confidence scores. - - name: The method name (str). - Supported values: - - 'max_prob' for using the maximum token probability as a confidence. - - 'entropy' for using a normalized entropy of a log-likelihood vector. - - entropy_type: Which type of entropy to use (str). Used if confidence_method_cfg.name is set to `entropy`. - Supported values: - - 'gibbs' for the (standard) Gibbs entropy. If the alpha (α) is provided, - the formula is the following: H_α = -sum_i((p^α_i)*log(p^α_i)). - Note that for this entropy, the alpha should comply the following inequality: - (log(V)+2-sqrt(log^2(V)+4))/(2*log(V)) <= α <= (1+log(V-1))/log(V-1) - where V is the model vocabulary size. - - 'tsallis' for the Tsallis entropy with the Boltzmann constant one. - Tsallis entropy formula is the following: H_α = 1/(α-1)*(1-sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/Tsallis_entropy - - 'renyi' for the Rényi entropy. - Rényi entropy formula is the following: H_α = 1/(1-α)*log_2(sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/R%C3%A9nyi_entropy - - alpha: Power scale for logsoftmax (α for entropies). Here we restrict it to be > 0. - When the alpha equals one, scaling is not applied to 'max_prob', - and any entropy type behaves like the Shannon entropy: H = -sum_i(p_i*log(p_i)) - - entropy_norm: A mapping of the entropy value to the interval [0,1]. - Supported values: - - 'lin' for using the linear mapping. - - 'exp' for using exponential mapping with linear shift. - - """ - - fusion_models: Optional[List[NGramGPULanguageModel]] - fusion_models_alpha: Optional[List[float]] - - class CudaGraphsMode(PrettyStrEnum): - FULL_GRAPH = "full_graph" # Cuda graphs with conditional nodes, fastest implementation - NO_WHILE_LOOPS = "no_while_loops" # Decoding with PyTorch while loops + partial Cuda graphs - NO_GRAPHS = "no_graphs" # d - - @property - def input_types(self): - """Returns definitions of module input ports.""" - # Input can be of dimension - - # ('B', 'T', 'D') [Log probs] or ('B', 'T') [Labels] - - return { - "decoder_output": NeuralType(None, LogprobsType()), - "decoder_lengths": NeuralType(tuple('B'), LengthsType()), - } - - @property - def output_types(self): - """Returns definitions of module output ports.""" - return {"predictions": [NeuralType(elements_type=HypothesisType())]} - - def __init__( - self, - blank_id: int, - preserve_alignments: bool = False, - compute_timestamps: bool = False, - preserve_frame_confidence: bool = False, - confidence_method_cfg: Optional[DictConfig] = None, - ngram_lm_model: Optional[str | Path] = None, - ngram_lm_alpha: float = 0.0, - boosting_tree: Optional[BoostingTreeModelConfig] = None, - boosting_tree_alpha: float = 0.0, - allow_cuda_graphs: bool = True, - tokenizer: Optional[TokenizerSpec] = None, - ): - super().__init__() - - self.blank_id = blank_id - self.preserve_alignments = preserve_alignments - # we need timestamps to extract non-blank per-frame confidence - self.compute_timestamps = compute_timestamps | preserve_frame_confidence - self.preserve_frame_confidence = preserve_frame_confidence - - # set confidence calculation method - self._init_confidence_method(confidence_method_cfg) - - # load fusion models from paths (ngram_lm_model and boosting_tree_model) - self.fusion_models, self.fusion_models_alpha = [], [] - if ngram_lm_model is not None: - self.fusion_models.append( - NGramGPULanguageModel.from_file(lm_path=ngram_lm_model, vocab_size=self.blank_id) - ) - self.fusion_models_alpha.append(ngram_lm_alpha) - if boosting_tree and not BoostingTreeModelConfig.is_empty(boosting_tree): - self.fusion_models.append(GPUBoostingTreeModel.from_config(boosting_tree, tokenizer=tokenizer)) - self.fusion_models_alpha.append(boosting_tree_alpha) - - if not self.fusion_models: - self.fusion_models = None - self.fusion_models_alpha = None - self.allow_cuda_graphs = False - self.cuda_graphs_mode = None - else: - self.allow_cuda_graphs = allow_cuda_graphs - self.cuda_graphs_mode = None - self.maybe_enable_cuda_graphs() - self.state: CTCDecoderCudaGraphsState | None = None - self.cuda_graphs_allow_fallback = True - - @typecheck() - def forward( - self, - decoder_output: torch.Tensor, - decoder_lengths: Optional[torch.Tensor], - ): - """Returns a list of hypotheses given an input batch of the encoder hidden embedding. - Output token is generated auto-repressively. - - Args: - decoder_output: A tensor of size (batch, timesteps, features) or (batch, timesteps) (each timestep is a label). - decoder_lengths: list of int representing the length of each sequence - output sequence. - - Returns: - packed list containing batch number of sentences (Hypotheses). - """ - - input_decoder_lengths = decoder_lengths - - if decoder_lengths is None: - logging.warning(_DECODER_LENGTHS_NONE_WARNING, mode=logging_mode.ONCE) - decoder_lengths = torch.tensor( - [decoder_output.shape[1]], dtype=torch.long, device=decoder_output.device - ).expand(decoder_output.shape[0]) - - # GreedyCTCInfer::forward(), by accident, works with - # decoder_lengths on either CPU or GPU when decoder_output is - # on GPU. For the sake of backwards compatibility, we also - # allow decoder_lengths to be on the CPU device. In this case, - # we simply copy the decoder_lengths from CPU to GPU. If both - # tensors are already on the same device, this is a no-op. - decoder_lengths = decoder_lengths.to(decoder_output.device) - - if decoder_output.ndim == 2: - if self.fusion_models is not None: - raise NotImplementedError - hypotheses = self._greedy_decode_labels_batched(decoder_output, decoder_lengths) - else: - hypotheses = self._greedy_decode_logprobs_batched(decoder_output, decoder_lengths) - packed_result = pack_hypotheses(hypotheses, input_decoder_lengths) - return (packed_result,) - - @torch.no_grad() - def _greedy_decode_logprobs_batched(self, x: torch.Tensor, out_len: torch.Tensor): - # x: [B, T, D] - # out_len: [B] - - batch_size = x.shape[0] - max_time = x.shape[1] - - predictions = x - - if self.fusion_models is None: - # In CTC greedy decoding, each output maximum likelihood token - # is calculated independent of the other tokens. - predictions_logprobs, predictions_labels = predictions.max(dim=-1) - else: - - for fusion_model in self.fusion_models: - fusion_model.to(x.device) - # decoding with NGPU-LM and Boosting Tree - if self.cuda_graphs_mode is not None and x.device.type == "cuda": - predictions_labels, predictions_logprobs = ( - self._greedy_decode_logprobs_batched_fusion_models_cuda_graphs(logits=x, out_len=out_len) - ) - else: - predictions_labels, predictions_logprobs = self._greedy_decode_logprobs_batched_fusion_models_torch( - logits=x, out_len=out_len - ) - - # Since predictions_logprobs is a padded matrix in the time - # dimension, we consider invalid timesteps to be "blank". - time_steps = torch.arange(max_time, device=x.device).unsqueeze(0).expand(batch_size, max_time) - non_blank_ids_mask = torch.logical_and(predictions_labels != self.blank_id, time_steps < out_len.unsqueeze(1)) - # Sum the non-blank labels to compute the score of the - # transcription. This follows from Eq. (3) of "Connectionist - # Temporal Classification: Labelling Unsegmented Sequence Data - # with Recurrent Neural Networks". - scores = torch.where(non_blank_ids_mask, predictions_logprobs, 0.0).sum(axis=1) - - scores = scores.cpu() - predictions_labels = predictions_labels.cpu() - out_len = out_len.cpu() - - if self.preserve_alignments or self.preserve_frame_confidence: - predictions = predictions.cpu() - - hypotheses = [] - - # This mimics the for loop in GreedyCTCInfer::forward. - for i in range(batch_size): - hypothesis = rnnt_utils.Hypothesis(score=0.0, y_sequence=[], dec_state=None, timestamp=[], last_token=None) - hypothesis.score = scores[i] - - prediction_labels_no_padding = predictions_labels[i, : out_len[i]].tolist() - - assert predictions_labels.dtype == torch.int64 - hypothesis.y_sequence = prediction_labels_no_padding - - if self.preserve_alignments: - hypothesis.alignments = ( - predictions[i, : out_len[i], :].clone(), - predictions_labels[i, : out_len[i]].clone(), - ) - if self.compute_timestamps: - # TOOD: Could do this in a vectorized manner... Would - # prefer to have nonzero_static, though, for sanity. - # Or do a prefix sum on out_len - hypothesis.timestamp = torch.nonzero(non_blank_ids_mask[i], as_tuple=False)[:, 0].cpu().tolist() - if self.preserve_frame_confidence: - hypothesis.frame_confidence = self._get_confidence(predictions[i, : out_len[i], :]) - - hypotheses.append(hypothesis) - - return hypotheses - - @torch.no_grad() - def _greedy_decode_labels_batched(self, x: torch.Tensor, out_len: torch.Tensor): - """ - This does greedy decoding in the case where you have already found the - most likely token at each timestep. - """ - # x: [B, T] - # out_len: [B] - - batch_size = x.shape[0] - max_time = x.shape[1] - - predictions_labels = x - time_steps = torch.arange(max_time, device=x.device).unsqueeze(0).expand(batch_size, max_time) - non_blank_ids_mask = torch.logical_and(predictions_labels != self.blank_id, time_steps < out_len.unsqueeze(1)) - predictions_labels = predictions_labels.cpu() - out_len = out_len.cpu() - - hypotheses = [] - - for i in range(batch_size): - hypothesis = rnnt_utils.Hypothesis(score=0.0, y_sequence=[], dec_state=None, timestamp=[], last_token=None) - hypothesis.y_sequence = predictions_labels[i, : out_len[i]].tolist() - hypothesis.score = -1.0 - - if self.preserve_alignments: - raise ValueError( - "Requested for alignments, but predictions provided were labels, not log probabilities." - ) - if self.compute_timestamps: - # TOOD: Could do this in a vectorized manner... Would - # prefer to have nonzero_static, though, for sanity. - # Or do a prefix sum on out_len - hypothesis.timestamp = torch.nonzero(non_blank_ids_mask[i], as_tuple=False)[:, 0].cpu().tolist() - if self.preserve_frame_confidence: - raise ValueError( - "Requested for per-frame confidence, but predictions provided were labels, not log probabilities." - ) - - hypotheses.append(hypothesis) - - return hypotheses - - @torch.no_grad() - def _greedy_decode_logprobs_batched_fusion_models_torch(self, logits: torch.Tensor, out_len: torch.Tensor): - batch_size = logits.shape[0] - max_time = logits.shape[1] - device = logits.device - float_dtype = logits.dtype - batch_indices = torch.arange(batch_size, device=device, dtype=torch.long) - - # Step 1: Initialization - batch_fusion_states_list = [] - for fusion_model in self.fusion_models: - batch_fusion_states_list.append(fusion_model.get_init_states(batch_size=batch_size, bos=True)) - last_labels = torch.full([batch_size], fill_value=self.blank_id, device=device, dtype=torch.long) - # resulting labels and logprobs storage - predictions_labels = torch.zeros([batch_size, max_time], device=device, dtype=torch.long) - predictions_logprobs = torch.zeros([batch_size, max_time], device=device, dtype=float_dtype) - - for i in range(max_time): - # Step 2: Get most likely labels for current frame - log_probs, labels = logits[:, i].max(dim=-1) - log_probs_w_fusion = logits[:, i].clone() - - # Step 3: Get fusion scores - fusion_states_candidates_list = [] - for fusion_idx, fusion_model in enumerate(self.fusion_models): - fusion_scores, batch_fusion_states_candidates = fusion_model.advance( - states=batch_fusion_states_list[fusion_idx] - ) - fusion_scores = fusion_scores.to(dtype=float_dtype) - log_probs_w_fusion[:, :-1] += self.fusion_models_alpha[fusion_idx] * fusion_scores - fusion_states_candidates_list.append(batch_fusion_states_candidates) - - # Step 4: Get most likely labels with fusion scores. Labels that are blank or repeated are ignored. - # Note: no need to mask blank labels log_probs_w_fusion[:, -1] = NEG_INF, as argmax is without blanks - # Note: for efficiency, use scatter instead of log_probs_w_fusion[batch_indices, last_labels] = NEG_INF - log_probs_w_fusion.scatter_(dim=1, index=last_labels.unsqueeze(-1), value=NEG_INF) - log_probs_w_fusion, labels_w_fusion = log_probs_w_fusion[:, :-1].max(dim=-1) - - # Step 5: Update labels if they initially weren't blank or repeated - blank_or_repeated = (labels == self.blank_id) | (labels == last_labels) - torch.where(blank_or_repeated, labels, labels_w_fusion, out=labels) - torch.where(blank_or_repeated, log_probs, log_probs_w_fusion, out=log_probs_w_fusion) - - # Step 6: Update fusion states and scores for non-blank and non-repeated labels - for fusion_idx, fusion_model in enumerate(self.fusion_models): - torch.where( - blank_or_repeated, - batch_fusion_states_list[fusion_idx], - fusion_states_candidates_list[fusion_idx][batch_indices, labels * ~blank_or_repeated], - out=batch_fusion_states_list[fusion_idx], - ) - - predictions_labels[:, i] = labels - predictions_logprobs[:, i] = log_probs_w_fusion - last_labels = labels - - return predictions_labels, predictions_logprobs - - @torch.no_grad() - def _before_loop(self): - """ - Initializes the state. - """ - - # Step 1: Initialization for fusion models - self.state.fusion_states_list = [] - self.state.fusion_states_candidates_list = [] - - for fusion_model in self.fusion_models: - self.state.fusion_states_list.append( - fusion_model.get_init_states(batch_size=self.state.batch_size, bos=True) - ) - self.state.fusion_states_candidates_list.append( - torch.zeros( - [self.state.batch_size, fusion_model.vocab_size], dtype=torch.long, device=self.state.device - ) - ) - - self.state.last_labels.fill_(self.blank_id) - self.state.frame_idx.fill_(0) - self.state.active_mask.copy_((self.state.decoder_lengths > 0).any()) - # resulting labels and logprobs storage - self.state.predictions_labels.zero_() - self.state.predictions_logprobs.zero_() - - @torch.no_grad() - def _inner_loop(self): - """ - Performs a decoding step. - """ - # Step 2: Get most likely labels for current frame - logits = self.state.decoder_outputs[:, self.state.frame_idx.unsqueeze(0)].squeeze(1) - log_probs, labels = logits.max(dim=-1) - log_probs_w_fusion = logits.clone() - - # Step 3: Get fusion scores - for fusion_idx, fusion_model in enumerate(self.fusion_models): - fusion_scores, fusion_states_candidates = fusion_model.advance( - states=self.state.fusion_states_list[fusion_idx] - ) - fusion_scores = fusion_scores.to(dtype=self.state.float_dtype) - log_probs_w_fusion[:, :-1] += self.fusion_models_alpha[fusion_idx] * fusion_scores - self.state.fusion_states_candidates_list[fusion_idx].copy_(fusion_states_candidates) - - # Step 4: Get most likely labels with fusion scores. Labels that are blank or repeated are ignored. - # Note: no need to mask blank labels log_probs_w_fusion[:, -1] = NEG_INF, as argmax is without blanks - # Note: for efficiency, use scatter instead of log_probs_w_fusion[batch_indices, last_labels] = NEG_INF - log_probs_w_fusion.scatter_(dim=1, index=self.state.last_labels.unsqueeze(-1), value=NEG_INF) - log_probs_w_fusion, labels_w_fusion = log_probs_w_fusion[:, :-1].max(dim=-1) - - # Step 5: Update labels if they initially weren't blank or repeated - blank_or_repeated = (labels == self.blank_id) | (labels == self.state.last_labels) - torch.where(blank_or_repeated, labels, labels_w_fusion, out=labels) - torch.where(blank_or_repeated, log_probs, log_probs_w_fusion, out=log_probs_w_fusion) - - self.state.predictions_labels[:, self.state.frame_idx.unsqueeze(0)] = labels.unsqueeze(-1) - self.state.predictions_logprobs[:, self.state.frame_idx.unsqueeze(0)] = log_probs_w_fusion.unsqueeze(-1) - - # Step 6: Update fusion states and scores for non-blank and non-repeated labels - for fusion_idx, fusion_model in enumerate(self.fusion_models): - torch.where( - blank_or_repeated, - self.state.fusion_states_list[fusion_idx], - self.state.fusion_states_candidates_list[fusion_idx][ - self.state.batch_indices, labels * ~blank_or_repeated - ], - out=self.state.fusion_states_list[fusion_idx], - ) - - self.state.last_labels.copy_(labels) - self.state.frame_idx += 1 - self.state.active_mask.copy_((self.state.decoder_lengths > self.state.frame_idx).any()) - - @classmethod - def _create_while_loop_kernel(cls): - """ - Creates a kernel that evaluates whether to enter the outer loop body (not all hypotheses are decoded). - Condition: while(active_mask_any). - """ - kernel_string = r"""\ - typedef __device_builtin__ unsigned long long cudaGraphConditionalHandle; - - extern "C" __device__ __cudart_builtin__ void cudaGraphSetConditional(cudaGraphConditionalHandle handle, unsigned int value); - - extern "C" __global__ - void ctc_loop_conditional(cudaGraphConditionalHandle handle, const bool *decoding_active) - { - cudaGraphSetConditional(handle, *decoding_active); - } - """ - return run_nvrtc(kernel_string, b"ctc_loop_conditional", b"while_conditional_ctc.cu") - - def _graph_reinitialize(self, logits, logits_len): - batch_size, max_time, vocab_dim = logits.shape - self.state = CTCDecoderCudaGraphsState( - batch_size=batch_size, - max_time=max(max_time, 375), - vocab_dim=vocab_dim, - device=logits.device, - float_dtype=logits.dtype, - ) - if self.cuda_graphs_mode is self.CudaGraphsMode.FULL_GRAPH: - try: - self._full_graph_compile() - except NeMoCUDAPythonException as e: - if not self.cuda_graphs_allow_fallback: - raise RuntimeError("Full CUDA graph decoding failed. Mode is forced, raising exception") from e - logging.warning( - f"Full CUDA graph compilation failed: {e}. " - "Falling back to native PyTorch CUDA graphs. Decoding will be slower." - ) - self.cuda_graphs_mode = self.CudaGraphsMode.NO_WHILE_LOOPS - self._partial_graphs_compile() - elif self.cuda_graphs_mode is self.CudaGraphsMode.NO_WHILE_LOOPS: - self._partial_graphs_compile() - elif self.cuda_graphs_mode is self.CudaGraphsMode.NO_GRAPHS: - # no graphs needed - pass - else: - raise NotImplementedError(f"Unknown graph mode: {self.cuda_graphs_mode}") - - @cuda_python_required - def _full_graph_compile(self): - """Compiling full graph""" - stream_for_graph = torch.cuda.Stream(self.state.device) - stream_for_graph.wait_stream(torch.cuda.default_stream(self.state.device)) - self.state.full_graph = torch.cuda.CUDAGraph() - with ( - torch.cuda.stream(stream_for_graph), - torch.inference_mode(), - torch.cuda.graph(self.state.full_graph, stream=stream_for_graph, capture_error_mode="thread_local"), - ): - self._before_loop() - - # NB: depending on cuda-python version, cudaStreamGetCaptureInfo can return either 5 or 6 elements - capture_status, _, graph, *_ = cu_call( - cudart.cudaStreamGetCaptureInfo(torch.cuda.current_stream(device=self.state.device).cuda_stream) - ) - assert capture_status == cudart.cudaStreamCaptureStatus.cudaStreamCaptureStatusActive - - # capture: while decoding_active: - (loop_conditional_handle,) = cu_call(cudart.cudaGraphConditionalHandleCreate(graph, 0, 0)) - loop_kernel = self._create_while_loop_kernel() - decoding_active_ptr = np.array([self.state.active_mask.data_ptr()], dtype=np.uint64) - loop_args = np.array( - [loop_conditional_handle.getPtr(), decoding_active_ptr.ctypes.data], - dtype=np.uint64, - ) - # loop while there are active utterances - with with_conditional_node( - loop_kernel, - loop_args, - loop_conditional_handle, - device=self.state.device, - ): - self._inner_loop() - - def _partial_graphs_compile(self): - """Compiling partial graphs""" - stream_for_graph = torch.cuda.Stream(self.state.device) - stream_for_graph.wait_stream(torch.cuda.default_stream(self.state.device)) - self.state.before_loop_graph = torch.cuda.CUDAGraph() - self.state.inner_loop_graph = torch.cuda.CUDAGraph() - with ( - torch.cuda.stream(stream_for_graph), - torch.inference_mode(), - torch.cuda.graph( - self.state.before_loop_graph, - stream=stream_for_graph, - capture_error_mode="thread_local", - ), - ): - self._before_loop() - - with ( - torch.cuda.stream(stream_for_graph), - torch.inference_mode(), - torch.cuda.graph( - self.state.inner_loop_graph, - stream=stream_for_graph, - capture_error_mode="thread_local", - ), - ): - self._inner_loop() - - def _greedy_decode_logprobs_batched_fusion_models_cuda_graphs(self, logits: torch.Tensor, out_len: torch.Tensor): - current_batch_size = logits.shape[0] - current_max_time = logits.shape[1] - - if torch.is_autocast_enabled(): - logits = logits.to(torch.get_autocast_gpu_dtype()) - - # init or reinit graph - if self.state is None or self.state.need_reinit(logits): - self._graph_reinitialize(logits=logits, logits_len=out_len) - - # copy decoder outputs and lenghts - self.state.decoder_outputs[:current_batch_size, :current_max_time, ...].copy_(logits) - self.state.decoder_lengths[: logits.shape[0]].copy_(out_len) - # set length to zero for elements outside the current batch - self.state.decoder_lengths[current_batch_size:].fill_(0) - - if self.cuda_graphs_mode is self.CudaGraphsMode.FULL_GRAPH: - self.state.full_graph.replay() - elif self.cuda_graphs_mode is self.CudaGraphsMode.NO_WHILE_LOOPS: - self.state.before_loop_graph.replay() - for _ in range(current_max_time): - self.state.inner_loop_graph.replay() - elif self.cuda_graphs_mode is self.CudaGraphsMode.NO_GRAPHS: - # this mode is only for testing purposes - # manual loop instead of using graphs - self._before_loop() - for _ in range(current_max_time): - self._inner_loop() - else: - raise NotImplementedError(f"Unknown graph mode: {self.cuda_graphs_mode}") - - return ( - self.state.predictions_labels[:current_batch_size, :current_max_time].clone(), - self.state.predictions_logprobs[:current_batch_size, :current_max_time].clone(), - ) - - def force_cuda_graphs_mode(self, mode: Optional[Union[str, CudaGraphsMode]]): - """ - Method to set graphs mode. Use only for testing purposes. - For debugging the algorithm use "no_graphs" mode, since it is impossible to debug CUDA graphs directly. - """ - self.cuda_graphs_mode = self.CudaGraphsMode(mode) if mode is not None else None - self.cuda_graphs_allow_fallback = False - self.state = None - - def maybe_enable_cuda_graphs(self): - """Enable CUDA graphs if conditions met""" - if self.cuda_graphs_mode is not None: - # CUDA graphs are already enabled - return False - - if not self.allow_cuda_graphs: - self.cuda_graphs_mode = None - else: - # cuda graphs are allowed - # check while loops - try: - check_cuda_python_cuda_graphs_conditional_nodes_supported() - self.cuda_graphs_mode = self.CudaGraphsMode.FULL_GRAPH - except (ImportError, ModuleNotFoundError, EnvironmentError) as e: - logging.warning( - "No conditional node support for Cuda.\n" - "Cuda graphs with while loops are disabled, decoding speed will be slower\n" - f"Reason: {e}" - ) - self.cuda_graphs_mode = self.CudaGraphsMode.NO_GRAPHS - self.reset_cuda_graphs_state() - return self.cuda_graphs_mode is not None - - def disable_cuda_graphs(self) -> bool: - """Disable CUDA graphs, can be used to disable graphs temporary, e.g., in training process""" - if self.cuda_graphs_mode is None: - # nothing to disable - return False - self.cuda_graphs_mode = None - self.reset_cuda_graphs_state() - return True - - def reset_cuda_graphs_state(self): - """Reset state to release memory (for CUDA graphs implementations)""" - self.state = None - - def __call__(self, *args, **kwargs): - return self.forward(*args, **kwargs) - - -@dataclass -class GreedyCTCInferConfig: - preserve_alignments: bool = False - compute_timestamps: bool = False - preserve_frame_confidence: bool = False - confidence_method_cfg: Optional[ConfidenceMethodConfig] = field(default_factory=lambda: ConfidenceMethodConfig()) - - ngram_lm_model: Optional[str] = None - ngram_lm_alpha: float = 0.0 - boosting_tree: BoostingTreeModelConfig = field(default_factory=BoostingTreeModelConfig) - boosting_tree_alpha: Optional[float] = 0.0 - allow_cuda_graphs: bool = True - - def __post_init__(self): - # OmegaConf.structured ensures that post_init check is always executed - self.confidence_method_cfg = OmegaConf.structured( - self.confidence_method_cfg - if isinstance(self.confidence_method_cfg, ConfidenceMethodConfig) - else ConfidenceMethodConfig(**self.confidence_method_cfg) - ) diff --git a/nemo/collections/asr/parts/submodules/cuda_graph_rnnt_greedy_decoding.py b/nemo/collections/asr/parts/submodules/cuda_graph_rnnt_greedy_decoding.py deleted file mode 100644 index 5e4e179266a75eb14b6bcaad13ade764364482cb..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/cuda_graph_rnnt_greedy_decoding.py +++ /dev/null @@ -1,374 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from typing import List, Optional - -import numpy as np -import torch - -from nemo.collections.asr.parts.utils import rnnt_utils -from nemo.core.utils.cuda_python_utils import ( - check_cuda_python_cuda_graphs_conditional_nodes_supported, - cu_call, - run_nvrtc, - with_conditional_node, -) -from nemo.core.utils.optional_libs import CUDA_PYTHON_AVAILABLE, cuda_python_required - -if CUDA_PYTHON_AVAILABLE: - from cuda.bindings import runtime as cudart - -_CUDA_PROGRAM_NAME = b"while_loop_conditional.cu" - - -def create_outer_for_loop_kernel(): - """ - Creates a kernel that evaluates whether or not to enter the for loop body. - Effectively substitutes for `for time_idx in range(trip_count)` - such that that for loop can run on a GPU. - """ - kernel_string = r"""\ - typedef __device_builtin__ unsigned long long cudaGraphConditionalHandle; - - extern "C" __device__ __cudart_builtin__ void cudaGraphSetConditional(cudaGraphConditionalHandle handle, unsigned int value); - - extern "C" __global__ - void for_loop_conditional(cudaGraphConditionalHandle handle, const long *time_idx, const long *trip_count) - { - cudaGraphSetConditional(handle, *time_idx < *trip_count); - } - """ - return run_nvrtc(kernel_string, b"for_loop_conditional", _CUDA_PROGRAM_NAME) - - -def create_inner_while_loop_kernel(): - """ - Evaluates whether or not to keep evaluating the inner while loop body. - Continue until all elements of the batch output blank or the while loop - has run max_symbols times. - """ - kernel_string = r"""\ - typedef __device_builtin__ unsigned long long cudaGraphConditionalHandle; - - extern "C" __device__ __cudart_builtin__ void cudaGraphSetConditional(cudaGraphConditionalHandle handle, unsigned int value); - - extern "C" __global__ - void while_loop_conditional(cudaGraphConditionalHandle handle, const bool *not_blank, const long *symbols_added, const long *max_symbols) - { - cudaGraphSetConditional(handle, *not_blank && *symbols_added < *max_symbols); - } - """ - return run_nvrtc(kernel_string, b"while_loop_conditional", _CUDA_PROGRAM_NAME) - - -class RNNTGreedyDecodeCudaGraph: - def __init__(self, max_symbols: int, caller): - if CUDA_PYTHON_AVAILABLE: - check_cuda_python_cuda_graphs_conditional_nodes_supported() - else: - raise ValueError("Cannot instantiate RNNTGreedyDecodeCudaGraph without `pip install cuda-python`") - - assert max_symbols is not None - - self.max_symbols = max_symbols - - # These are cuda torch.Tensors which will be lazily allocated the first time _reinitialize() is called. - # We don't do it here because we don't know which cuda device we are using yet. - self.symbols_added_t = None - self.max_symbols_t = None - self.not_all_blank_t = None - self.time_idx_t = None - self.max_out_len_t = None - - self.encoder_output = None - self.encoder_output_length = None - self.f = None - # We also lazily initialize a variable holding the current device - self.device = None - - # Reasonable default maximum time. 375 frames * (80ms / frame) = 30 seconds - # 80ms is the frame size of recent fastconformer models - # This does not affect correctness. - self.max_time = 375 - self.batch_size = 0 - - self.scores_cpu = None - self.labels_cpu = None - self.graph = None - - self.first_call = True - - self.caller = caller - - @cuda_python_required - def _reinitialize(self, max_time, batch_size, encoder_output, encoder_output_length): - if self.first_call: - # We need to call the original _greedy_decode_blank_as_pad - # implementation at least once beforehand in order to make - # sure that pytorch is "initialized". Pytorch may be - # uninitialized if this code runs before any other pytorch - # operation in this process. Pytorch often lazily - # initializes things like a cudnnHandle_t via - # cudnnCreate(), which can involve synchronizing with the - # host. Such actions are not stream capturable to a graph. - with torch.cuda.stream(torch.cuda.Stream(self.device)): - self.caller._greedy_decode_blank_as_pad_loop_frames( - encoder_output, encoder_output_length, encoder_output.device - ) - - self.device = encoder_output.device - - self.symbols_added_t = torch.tensor(0, dtype=torch.int64, device=encoder_output.device) - self.max_symbols_t = torch.tensor(self.max_symbols, dtype=torch.int64, device=encoder_output.device) - self.not_all_blank_t = torch.tensor(True, dtype=torch.bool, device=encoder_output.device) - - self.time_idx_t = torch.tensor(0, dtype=torch.int64, device=encoder_output.device) - self.max_out_len_t = torch.tensor(0, dtype=torch.int64, device=encoder_output.device) - - self.first_call = False - - self.max_time = max(self.max_time, max_time) - self.batch_size = max(self.batch_size, batch_size) - - self.encoder_output = torch.zeros( - (self.batch_size, self.max_time, encoder_output.shape[-1]), - dtype=encoder_output.dtype, - device=encoder_output.device, - ) - self.encoder_output_length = torch.zeros( - (self.batch_size,), dtype=encoder_output_length.dtype, device=encoder_output_length.device - ) - - self.zero_t = torch.tensor(0.0, dtype=encoder_output.dtype, device=encoder_output.device) - self.blank_index_t = torch.tensor(self.caller._blank_index, dtype=torch.long, device=encoder_output.device) - - self.scores_cpu = torch.zeros( - (self.batch_size, self.max_time, self.max_symbols), - dtype=encoder_output.dtype, - device="cpu", - pin_memory=True, - ) - self.labels_cpu = torch.zeros( - (self.batch_size, self.max_time, self.max_symbols), dtype=torch.int64, device="cpu", pin_memory=True - ) - - self.graph = None - - self.graph = torch.cuda.CUDAGraph() - - # Always create a new stream, because the per-thread default stream disallows stream capture to a graph. - stream_for_graph = torch.cuda.Stream(self.device) - with ( - torch.cuda.stream(stream_for_graph), - torch.inference_mode(), - torch.cuda.graph(self.graph, stream=stream_for_graph, capture_error_mode="thread_local"), - ): - # This is failing... - self.f = torch.zeros( - (self.batch_size, 1, self.encoder_output.shape[-1]), - dtype=encoder_output.dtype, - device=encoder_output.device, - ) - hidden = self.caller.decoder.initialize_state(self.f) - self.last_label = torch.full( - [self.batch_size], fill_value=self.caller._SOS, dtype=torch.long, device=encoder_output.device - ) - self.blank_mask = torch.full( - [self.batch_size], fill_value=0, dtype=torch.bool, device=encoder_output.device - ) - self.seq_idx_t = torch.zeros([1], dtype=torch.int64, device=encoder_output.device) - - self.scores = torch.zeros( - (self.max_time * self.max_symbols, self.batch_size), - dtype=encoder_output.dtype, - device=encoder_output.device, - ) - self.labels = torch.full( - (self.max_time * self.max_symbols, self.batch_size), - fill_value=self.caller._blank_index, - dtype=torch.int64, - device=encoder_output.device, - ) - # Get max sequence length - self.max_out_len_t = self.encoder_output_length.max() - - # NB: depending on cuda-python version, cudaStreamGetCaptureInfo can return either 5 or 6 elements - capture_status, _, graph, *_ = cu_call( - cudart.cudaStreamGetCaptureInfo(torch.cuda.current_stream(device=self.device).cuda_stream) - ) - assert capture_status == cudart.cudaStreamCaptureStatus.cudaStreamCaptureStatusActive - - (for_loop_conditional_handle,) = cu_call(cudart.cudaGraphConditionalHandleCreate(graph, 0, 0)) - for_loop_kernel = create_outer_for_loop_kernel() - time_idx_ptr = np.array([self.time_idx_t.data_ptr()], dtype=np.uint64) - max_out_len_ptr = np.array([self.max_out_len_t.data_ptr()], dtype=np.uint64) - for_loop_args = np.array( - [for_loop_conditional_handle.getPtr(), time_idx_ptr.ctypes.data, max_out_len_ptr.ctypes.data], - dtype=np.uint64, - ) - - with with_conditional_node(for_loop_kernel, for_loop_args, for_loop_conditional_handle, self.device): - torch.index_select(self.encoder_output, 1, self.time_idx_t.unsqueeze(0), out=self.f) - - self.not_all_blank_t.fill_(True) - self.symbols_added_t.fill_(0) - - torch.ge(self.time_idx_t, self.encoder_output_length, out=self.blank_mask) - - while_loop_kernel = create_inner_while_loop_kernel() - (while_loop_conditional_handle,) = cu_call(cudart.cudaGraphConditionalHandleCreate(graph, 0, 0)) - not_blank_ptr = np.array([self.not_all_blank_t.data_ptr()], dtype=np.uint64) - symbols_added_ptr = np.array([self.symbols_added_t.data_ptr()], dtype=np.uint64) - max_symbols_ptr = np.array([self.max_symbols_t.data_ptr()], dtype=np.uint64) - while_loop_args = np.array( - [ - while_loop_conditional_handle.getPtr(), - not_blank_ptr.ctypes.data, - symbols_added_ptr.ctypes.data, - max_symbols_ptr.ctypes.data, - ], - dtype=np.uint64, - ) - with with_conditional_node( - while_loop_kernel, while_loop_args, while_loop_conditional_handle, self.device - ): - g, hidden_prime = self.caller._pred_step( - self.last_label.unsqueeze(1), hidden, batch_size=self.batch_size - ) - logp = self.caller._joint_step(self.f, g, log_normalize=None)[:, 0, 0, :] - - v, k = logp.max(1) - torch.where(self.blank_mask, self.zero_t, v, out=v) - torch.where(self.blank_mask, self.blank_index_t, k, out=k) - # Commented out code unnecessarily causes D2H copy, which is synchronous. See pytorch issue #105641 - # self.scores[self.seq_idx_t, :] = v - # self.labels[self.seq_idx_t, :] = k - self.scores.index_copy_(0, self.seq_idx_t, v.unsqueeze(0)) - self.labels.index_copy_(0, self.seq_idx_t, k.unsqueeze(0)) - - self.blank_mask.logical_or_(k == self.caller._blank_index) - - not_blank_mask = ~self.blank_mask - - self.caller.decoder.batch_replace_states_mask( - src_states=hidden_prime, dst_states=hidden, mask=not_blank_mask - ) - torch.where(self.blank_mask, self.last_label, k, out=self.last_label) - - torch.any(not_blank_mask, 0, out=self.not_all_blank_t) - self.symbols_added_t += 1 - self.seq_idx_t += 1 - - self.time_idx_t += 1 - self.seq_idx_t += self.max_symbols_t - self.symbols_added_t - - self.scores_cpu.copy_( - self.scores.transpose(0, 1).contiguous().reshape((self.batch_size, self.max_time, self.max_symbols)), - non_blocking=True, - ) - self.labels_cpu.copy_( - self.labels.transpose(0, 1).contiguous().reshape((self.batch_size, self.max_time, self.max_symbols)), - non_blocking=True, - ) - - self.last_label.fill_(self.caller._SOS) - self.time_idx_t.fill_(0) - - def __call__( - self, - x: torch.Tensor, - out_len: torch.Tensor, - device: torch.device, - partial_hypotheses: Optional[List[rnnt_utils.Hypothesis]] = None, - ): - if x.device.type != "cuda": - # If CUDA graphs are enabled and "frame-looping" algorithm is requested, current class - # is not suitable to handle non-CUDA inputs; thus we are passing them to original caller - return self.caller._greedy_decode_blank_as_pad_loop_frames( - x=x, out_len=out_len, device=device, partial_hypotheses=partial_hypotheses - ) - - if partial_hypotheses is not None: - raise NotImplementedError( - "`partial_hypotheses` support is not available " - "with Frame-Looping algorithm with Cuda graphs (not implemented yet)" - ) - - if self.caller.preserve_alignments: - raise NotImplementedError( - "`preserve_alignments` support is not available" - "with Frame-Looping algorithm with Cuda graphs (not implemented yet)" - ) - - if self.caller.preserve_frame_confidence: - raise NotImplementedError( - "`preserve_frame_confidence` support is not available" - "with Frame-Looping algorithm with Cuda graphs (not implemented yet)" - ) - - batch_size = x.shape[0] - # We could use out_len.max() here instead of x.shape[1], in - # case for some reason the user passes in a larger buffer than - # required, since we know that `out_len.max() <= x.shape[1]`. - max_time = x.shape[1] - - if torch.is_autocast_enabled(): - x = x.to(torch.get_autocast_gpu_dtype()) - - if max_time > self.max_time or batch_size > self.batch_size or self.device != x.device: - # In the first two cases, we need to recreate the cuda - # graph to handle larger tensor sizes. In the third case, - # we need to recreate the graph, as well as all tensors, - # because the computation is now happening on a different - # GPU. Therefore, in the third case, we unconditionally - # set self.first_call to True to make sure that all - # possibly blocking initializers are initialized properly - # again on the new device. - if self.device != x.device: - self.first_call = True - self._reinitialize(max_time, batch_size, x, out_len) - - self.encoder_output[: x.shape[0], : x.shape[1], ...].copy_(x) - self.encoder_output_length[: out_len.shape[0]].copy_(out_len) - self.graph.replay() - torch.cuda.current_stream(device=self.device).synchronize() - - self.scores_cpu[self.labels_cpu == self.caller._blank_index] = 0.0 - total_scores = self.scores_cpu.sum(dtype=torch.float32, axis=(1, 2)) - - tokens_per_timestep = (self.labels_cpu != self.caller._blank_index).sum(axis=-1) - timesteps_packed = torch.repeat_interleave( - torch.arange(self.max_time).repeat(self.batch_size), tokens_per_timestep.flatten() - ) - timestep_segments = tokens_per_timestep.sum(axis=-1) - - valid_labels_mask = self.labels_cpu != self.caller._blank_index - labels_segments = valid_labels_mask.sum(axis=(1, 2)) - labels_packed = self.labels_cpu[valid_labels_mask] - - hypotheses = [ - rnnt_utils.Hypothesis(score=0.0, y_sequence=[], timestamp=[], dec_state=None) for _ in range(batch_size) - ] - - timestep_start = 0 - labels_start = 0 - for i in range(batch_size): - hypotheses[i].timestamp = timesteps_packed[timestep_start : timestep_start + timestep_segments[i]].tolist() - timestep_start += timestep_segments[i] - hypotheses[i].score = float(total_scores[i]) - hypotheses[i].y_sequence = labels_packed[labels_start : labels_start + labels_segments[i]].tolist() - labels_start += labels_segments[i] - - return hypotheses diff --git a/nemo/collections/asr/parts/submodules/jasper.py b/nemo/collections/asr/parts/submodules/jasper.py deleted file mode 100644 index f29332ea522b83e30cc29dc32e770cba67b1c1bd..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/jasper.py +++ /dev/null @@ -1,1186 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import math -from typing import Callable, Iterable, List, Optional, Tuple - -import torch -import torch.nn as nn -import torch.nn.functional as F -from torch import Tensor -from torch.nn.init import _calculate_correct_fan -from torch.nn.modules.utils import _single - -from nemo.collections.common.parts.utils import activation_registry -from nemo.core.classes.mixins import AccessMixin -from nemo.core.classes.mixins.adapter_mixins import AdapterModuleMixin -from nemo.utils import logging - -try: - from pytorch_quantization import calib - from pytorch_quantization import nn as quant_nn - from pytorch_quantization import quant_modules - from pytorch_quantization.tensor_quant import QuantDescriptor - - PYTORCH_QUANTIZATION_AVAILABLE = True -except ImportError: - PYTORCH_QUANTIZATION_AVAILABLE = False - -jasper_activations = activation_registry - - -def tds_uniform_(tensor, mode='fan_in'): - """ - Uniform Initialization from the paper [Sequence-to-Sequence Speech Recognition with Time-Depth Separable Convolutions](https://www.isca-speech.org/archive/Interspeech_2019/pdfs/2460.pdf) - Normalized to - - - .. math:: - \\text{bound} = \\text{2} \\times \\sqrt{\\frac{1}{\\text{fan\\_mode}}} - - Args: - tensor: an n-dimensional `torch.Tensor` - mode: either ``'fan_in'`` (default) or ``'fan_out'``. Choosing ``'fan_in'`` - preserves the magnitude of the variance of the weights in the - forward pass. Choosing ``'fan_out'`` preserves the magnitudes in the - backwards pass. - """ - fan = _calculate_correct_fan(tensor, mode) - gain = 2.0 # sqrt(4.0) = 2 - std = gain / math.sqrt(fan) # sqrt(4.0 / fan_in) - bound = std # Calculate uniform bounds from standard deviation - with torch.no_grad(): - return tensor.uniform_(-bound, bound) - - -def tds_normal_(tensor, mode='fan_in'): - """ - Normal Initialization from the paper [Sequence-to-Sequence Speech Recognition with Time-Depth Separable Convolutions](https://www.isca-speech.org/archive/Interspeech_2019/pdfs/2460.pdf) - Normalized to - - - .. math:: - \\text{bound} = \\text{2} \\times \\sqrt{\\frac{1}{\\text{fan\\_mode}}} - - Args: - tensor: an n-dimensional `torch.Tensor` - mode: either ``'fan_in'`` (default) or ``'fan_out'``. Choosing ``'fan_in'`` - preserves the magnitude of the variance of the weights in the - forward pass. Choosing ``'fan_out'`` preserves the magnitudes in the - backwards pass. - """ - fan = _calculate_correct_fan(tensor, mode) - gain = 2.0 - std = gain / math.sqrt(fan) # sqrt(4.0 / fan_in) - bound = std # Calculate uniform bounds from standard deviation - with torch.no_grad(): - return tensor.normal_(0.0, bound) - - -def init_weights(m, mode: Optional[str] = 'xavier_uniform'): - if isinstance(m, MaskedConv1d): - init_weights(m.conv, mode) - if isinstance(m, (nn.Conv1d, nn.Linear)): - if mode is not None: - if mode == 'xavier_uniform': - nn.init.xavier_uniform_(m.weight, gain=1.0) - elif mode == 'xavier_normal': - nn.init.xavier_normal_(m.weight, gain=1.0) - elif mode == 'kaiming_uniform': - nn.init.kaiming_uniform_(m.weight, nonlinearity="relu") - elif mode == 'kaiming_normal': - nn.init.kaiming_normal_(m.weight, nonlinearity="relu") - elif mode == 'tds_uniform': - tds_uniform_(m.weight) - elif mode == 'tds_normal': - tds_normal_(m.weight) - else: - raise ValueError("Unknown Initialization mode: {0}".format(mode)) - elif isinstance(m, nn.BatchNorm1d): - if m.track_running_stats: - m.running_mean.zero_() - m.running_var.fill_(1) - m.num_batches_tracked.zero_() - if m.affine: - nn.init.ones_(m.weight) - nn.init.zeros_(m.bias) - - -def compute_new_kernel_size(kernel_size, kernel_width): - new_kernel_size = max(int(kernel_size * kernel_width), 1) - # If kernel is even shape, round up to make it odd - if new_kernel_size % 2 == 0: - new_kernel_size += 1 - return new_kernel_size - - -def get_same_padding(kernel_size, stride, dilation) -> int: - if stride > 1 and dilation > 1: - raise ValueError("Only stride OR dilation may be greater than 1") - return (dilation * (kernel_size - 1)) // 2 - - -def get_asymtric_padding(kernel_size, stride, dilation, future_context): - if stride > 1 and dilation > 1: - raise ValueError("Only stride OR dilation may be greater than 1") - - left_context = kernel_size - 1 - future_context - right_context = future_context - - symmetric_padding = get_same_padding(kernel_size, stride, dilation) - - if kernel_size <= future_context: - # kernel size is smaller than future context, equivalent to using entire context of kernel - # simply return symmetric padding for this scenario - logging.warning( - f"Future context window is larger than the kernel size!\n" - f"Left context = {left_context} | Right context = greater than {right_context} | " - f"Kernel size = {kernel_size}\n" - f"Switching to symmetric padding (left context = right context = {symmetric_padding})" - ) - return symmetric_padding - - if left_context < symmetric_padding: - logging.warning( - f"Future context window is larger than half the kernel size!\n" - f"Conv layer therefore uses more future information than past to compute its output!\n" - f"Left context = {left_context} | Right context = {right_context} | " - f"Kernel size = {kernel_size}" - ) - - if dilation > 1: - left_context = dilation * kernel_size - 1 - dilation * future_context - right_context = dilation * future_context - return (left_context, right_context) - - return (left_context, right_context) - - -@torch.jit.script -def _se_pool_step_script_infer(x: torch.Tensor, context_window: int, mask: torch.Tensor): - """ - Calculates the masked average over padded limited context segment during inference mode. - - Args: - x: Input tensor. Shape = [B, C, T] - context_window: Integer context window, must be 0 or greater. - mask: Mask tensor, 1 represents value index, 0 represents padded index. Shape = [B, 1, T]. - - Returns: - A tensor reduced via masked average pool over some limited context. Shape = [B, C, 1] - """ - timesteps = x.shape[-1] - if timesteps < context_window: - y = torch.sum(x, dim=-1, keepdim=True) / mask.sum(dim=-1, keepdim=True).to(x.dtype) - else: - # << During inference prefer to use entire context >> - # x = x[:, :, :context_window] # [B, C, context_window] - # mask = mask[:, :, :context_window] # [B, 1, context_window] - # - # mask = mask.sum(dim=-1, keepdim=True).to(x.dtype) # [B, C, 1] - # y = x.sum(dim=-1, keepdim=True) # [B, 1, 1] - # y = y / (mask + 1e-8) # [B, C, 1] - y = torch.sum(x, dim=-1, keepdim=True) / mask.sum(dim=-1, keepdim=True).to(x.dtype) - - return y - - -@torch.jit.script -def _se_pool_step_script_train(x: torch.Tensor, context_window: int, mask: torch.Tensor): - """ - Calculates the masked average over padded limited context segment during training mode. - Randomly slices a segment of length `context_window` from signal+padded input tensor across all channels and - uses it for computing masked limited context. - - Args: - x: Input tensor. Shape = [B, C, T] - context_window: Integer context window, must be 0 or greater. - mask: Mask tensor, 1 represents value index, 0 represents padded index. Shape = [B, 1, T]. - - Returns: - A tensor reduced via masked average pool over some limited context. Shape = [B, C, 1] - """ - timesteps = x.shape[-1] - if timesteps < context_window: - y = torch.sum(x, dim=-1, keepdim=True) / mask.sum(dim=-1, keepdim=True).to(x.dtype) - else: - start_idx = torch.randint(0, timesteps - context_window, size=[1], dtype=torch.int32)[0] - x = x[:, :, start_idx : (start_idx + context_window)] # [B, C, context_window] - mask = mask[:, :, start_idx : (start_idx + context_window)] # [B, 1, context_window] - - mask = mask.sum(dim=-1, keepdim=True).to(x.dtype) # [B, C, 1] - y = x.sum(dim=-1, keepdim=True) # [B, 1, 1] - y = y / (mask + 1e-8) # [B, C, 1] - - return y - - -@torch.jit.script -def _masked_conv_init_lens(lens: torch.Tensor, current_maxlen: int, original_maxlen: torch.Tensor): - if current_maxlen > original_maxlen: - new_lens = torch.arange(current_maxlen) - new_max_lens = torch.tensor(current_maxlen) - else: - new_lens = lens - new_max_lens = original_maxlen - return new_lens, new_max_lens - - -class MaskedConv1d(nn.Module): - __constants__ = ["use_conv_mask", "real_out_channels", "heads"] - - def __init__( - self, - in_channels, - out_channels, - kernel_size, - stride=1, - padding=0, - dilation=1, - groups=1, - heads=-1, - bias=False, - use_mask=True, - quantize=False, - ): - super(MaskedConv1d, self).__init__() - - if not (heads == -1 or groups == in_channels): - raise ValueError("Only use heads for depthwise convolutions") - - self.real_out_channels = out_channels - if heads != -1: - in_channels = heads - out_channels = heads - groups = heads - - # preserve original padding - self._padding = padding - - # if padding is a tuple/list, it is considered as asymmetric padding - if type(padding) in (tuple, list): - self.pad_layer = nn.ConstantPad1d(padding, value=0.0) - # reset padding for conv since pad_layer will handle this - padding = 0 - else: - self.pad_layer = None - - if PYTORCH_QUANTIZATION_AVAILABLE and quantize: - self.conv = quant_nn.QuantConv1d( - in_channels, - out_channels, - kernel_size, - stride=stride, - padding=padding, - dilation=dilation, - groups=groups, - bias=bias, - ) - elif not PYTORCH_QUANTIZATION_AVAILABLE and quantize: - raise ImportError( - "pytorch-quantization is not installed. Install from " - "https://github.com/NVIDIA/TensorRT/tree/master/tools/pytorch-quantization." - ) - else: - self.conv = nn.Conv1d( - in_channels, - out_channels, - kernel_size, - stride=stride, - padding=padding, - dilation=dilation, - groups=groups, - bias=bias, - ) - self.use_mask = use_mask - self.heads = heads - - # Calculations for "same" padding cache - self.same_padding = (self.conv.stride[0] == 1) and ( - 2 * self.conv.padding[0] == self.conv.dilation[0] * (self.conv.kernel_size[0] - 1) - ) - if self.pad_layer is None: - self.same_padding_asymmetric = False - else: - self.same_padding_asymmetric = (self.conv.stride[0] == 1) and ( - sum(self._padding) == self.conv.dilation[0] * (self.conv.kernel_size[0] - 1) - ) - - # `self.lens` caches consecutive integers from 0 to `self.max_len` that are used to compute the mask for a - # batch. Recomputed to bigger size as needed. Stored on a device of the latest batch lens. - if self.use_mask: - self.max_len = torch.tensor(0) - self.lens = torch.tensor(0) - - def get_seq_len(self, lens): - if self.same_padding or self.same_padding_asymmetric: - return lens - - if self.pad_layer is None: - return ( - torch.div( - lens + 2 * self.conv.padding[0] - self.conv.dilation[0] * (self.conv.kernel_size[0] - 1) - 1, - self.conv.stride[0], - rounding_mode='trunc', - ) - + 1 - ) - else: - return ( - torch.div( - lens + sum(self._padding) - self.conv.dilation[0] * (self.conv.kernel_size[0] - 1) - 1, - self.conv.stride[0], - rounding_mode='trunc', - ) - + 1 - ) - - def forward(self, x, lens): - if self.use_mask: - # Generally will be called by ConvASREncoder, but kept as single gpu backup. - if x.size(2) > self.max_len: - self.update_masked_length(x.size(2), device=lens.device) - x = self.mask_input(x, lens) - - # Update lengths - lens = self.get_seq_len(lens) - - # asymmtric pad if necessary - if self.pad_layer is not None: - x = self.pad_layer(x) - - sh = x.shape - if self.heads != -1: - x = x.view(-1, self.heads, sh[-1]) - - out = self.conv(x) - - if self.heads != -1: - out = out.view(sh[0], self.real_out_channels, -1) - - return out, lens - - def update_masked_length(self, max_len, seq_range=None, device=None): - if seq_range is None: - self.lens, self.max_len = _masked_conv_init_lens(self.lens, max_len, self.max_len) - self.lens = self.lens.to(device) - else: - self.lens = seq_range - self.max_len = torch.tensor(max_len) - - def mask_input(self, x, lens): - max_len = x.size(2) - mask = self.lens[:max_len].unsqueeze(0).to(lens.device) < lens.unsqueeze(1) - x = x * mask.unsqueeze(1).to(device=x.device) - return x - - -class GroupShuffle(nn.Module): - def __init__(self, groups, channels): - super(GroupShuffle, self).__init__() - - self.groups = groups - self.channels_per_group = channels // groups - - def forward(self, x): - sh = x.shape - - x = x.view(-1, self.groups, self.channels_per_group, sh[-1]) - - x = torch.transpose(x, 1, 2).contiguous() - - x = x.view(-1, self.groups * self.channels_per_group, sh[-1]) - - return x - - -class SqueezeExcite(nn.Module): - def __init__( - self, - channels: int, - reduction_ratio: int, - context_window: int = -1, - interpolation_mode: str = 'nearest', - activation: Optional[Callable] = None, - quantize: bool = False, - ): - """ - Squeeze-and-Excitation sub-module. - - Args: - channels: Input number of channels. - reduction_ratio: Reduction ratio for "squeeze" layer. - context_window: Integer number of timesteps that the context - should be computed over, using stride 1 average pooling. - If value < 1, then global context is computed. - interpolation_mode: Interpolation mode of timestep dimension. - Used only if context window is > 1. - The modes available for resizing are: `nearest`, `linear` (3D-only), - `bilinear`, `area` - activation: Intermediate activation function used. Must be a - callable activation function. - """ - super(SqueezeExcite, self).__init__() - self.interpolation_mode = interpolation_mode - self._quantize = quantize - - self.pool = None # prepare a placeholder which will be updated - - if activation is None: - activation = nn.ReLU(inplace=True) - - if PYTORCH_QUANTIZATION_AVAILABLE and quantize: - self.fc = nn.Sequential( - quant_nn.QuantLinear(channels, channels // reduction_ratio, bias=False), - activation, - quant_nn.QuantLinear(channels // reduction_ratio, channels, bias=False), - ) - elif not PYTORCH_QUANTIZATION_AVAILABLE and quantize: - raise ImportError( - "pytorch-quantization is not installed. Install from " - "https://github.com/NVIDIA/TensorRT/tree/master/tools/pytorch-quantization." - ) - else: - self.fc = nn.Sequential( - nn.Linear(channels, channels // reduction_ratio, bias=False), - activation, - nn.Linear(channels // reduction_ratio, channels, bias=False), - ) - self.gap = nn.AdaptiveAvgPool1d(1) - - # Set default context window - self.change_context_window(context_window=context_window) - - # Set default max sequence length - self.set_max_len(16) - - def forward(self, x, lengths): - return self.forward_for_export(x, lengths) - - def forward_for_export(self, x, lengths): - # The use of negative indices on the transpose allow for expanded SqueezeExcite - max_len = x.shape[-1] - if max_len > self.max_len: - self.set_max_len(max_len) - dtype = x.dtype - # Computes in float32 to avoid instabilities during training with AMP. - with torch.amp.autocast(x.device.type, enabled=False): - # Create sample mask - 1 represents value, 0 represents pad - mask = self.make_pad_mask(lengths, max_audio_length=max_len, device=x.device) - mask = ~mask # 0 represents value, 1 represents pad - - # Ensure SE runs in FP32: cast fc weights and activations to float32 - if self.fc[0].weight.dtype != torch.float32: - self.fc.float() - if x.dtype != torch.float32: - x = x.float() - - x = x.masked_fill(mask, 0.0) # mask padded values explicitly to 0 - y = self._se_pool_step(x, mask) # [B, C, 1] - y = y.transpose(1, -1) # [B, 1, C] - y = self.fc(y) # [B, 1, C] - y = y.transpose(1, -1) # [B, C, 1] - - # Note: Keep for future, in case we improve WER from doing so. - # if self.context_window >= 0: - # y = F.interpolate(y, size=x.shape[-1], mode=self.interpolation_mode) - - y = torch.sigmoid(y) - y = x * y - # Cast back to original dtype for downstream consistency - y = y.to(dtype) - return y, lengths - - def _se_pool_step(self, x, mask): - # Negate mask back to represent 1 for signal and 0 for padded timestep. - mask = ~mask - - if self.context_window < 0: - # [B, C, 1] - Masked Average over value + padding. - y = torch.sum(x, dim=-1, keepdim=True) / mask.sum(dim=-1, keepdim=True).type(x.dtype) - else: - # [B, C, 1] - Masked Average over value + padding with limited context. - # During training randomly subsegments a context_window chunk of timesteps. - # During inference selects only the first context_window chunk of timesteps. - if self.training: - y = _se_pool_step_script_train(x, self.context_window, mask) - else: - y = _se_pool_step_script_infer(x, self.context_window, mask) - return y - - def set_max_len(self, max_len, seq_range=None): - """Sets maximum input length. - Pre-calculates internal seq_range mask. - """ - self.max_len = max_len - if seq_range is None: - device = next(self.parameters()).device - seq_range = torch.arange(0, self.max_len, device=device) - if hasattr(self, 'seq_range'): - self.seq_range = seq_range - else: - self.register_buffer('seq_range', seq_range, persistent=False) - - def make_pad_mask(self, seq_lens, max_audio_length, device=None): - """Make masking for padding.""" - if device and self.seq_range.device != device: - self.seq_range = self.seq_range.to(device) - if self.seq_range.device != seq_lens.device: - seq_lens = seq_lens.to(self.seq_range.device) - - mask = self.seq_range[:max_audio_length].expand(seq_lens.size(0), -1) < seq_lens.unsqueeze(-1) # [B, T]; bool - mask = mask.unsqueeze(1) # [B, 1, T] - - return mask - - def change_context_window(self, context_window: int): - """ - Update the context window of the SqueezeExcitation module, in-place if possible. - - Will update the pooling layer to either nn.AdaptiveAvgPool1d() (for global SE) or nn.AvgPool1d() - (for limited context SE). - - If only the context window is changing but still a limited SE context block - then - the earlier instance of nn.AvgPool1d() will be updated. - - Args: - context_window: An integer representing the number of input timeframes that will be used - to compute the context. Each timeframe corresponds to a single window stride of the - STFT features. - - Say the window_stride = 0.01s, then a context window of 128 represents 128 * 0.01 s - of context to compute the Squeeze step. - """ - if hasattr(self, 'context_window'): - logging.info(f"Changing Squeeze-Excitation context window from {self.context_window} to {context_window}") - - self.context_window = context_window - - -class JasperBlock(nn.Module, AdapterModuleMixin, AccessMixin): - """ - Constructs a single "Jasper" block. With modified parameters, also constructs other blocks for models - such as `QuartzNet` and `Citrinet`. - - - For `Jasper` : `separable` flag should be False - - For `QuartzNet` : `separable` flag should be True - - For `Citrinet` : `separable` flag and `se` flag should be True - - Note that above are general distinctions, each model has intricate differences that expand over - multiple such blocks. - - For further information about the differences between models which use JasperBlock, please review - the configs for ASR models found in the ASR examples directory. - - Args: - inplanes: Number of input channels. - planes: Number of output channels. - repeat: Number of repeated sub-blocks (R) for this block. - kernel_size: Convolution kernel size across all repeated sub-blocks. - kernel_size_factor: Floating point scale value that is multiplied with kernel size, - then rounded down to nearest odd integer to compose the kernel size. Defaults to 1.0. - stride: Stride of the convolutional layers. - dilation: Integer which defined dilation factor of kernel. Note that when dilation > 1, stride must - be equal to 1. - padding: String representing type of padding. Currently only supports "same" padding, - which symmetrically pads the input tensor with zeros. - dropout: Floating point value, determins percentage of output that is zeroed out. - activation: String representing activation functions. Valid activation functions are : - {"hardtanh": nn.Hardtanh, "relu": nn.ReLU, "selu": nn.SELU, "swish": Swish}. - Defaults to "relu". - residual: Bool that determined whether a residual branch should be added or not. - All residual branches are constructed using a pointwise convolution kernel, that may or may not - perform strided convolution depending on the parameter `residual_mode`. - groups: Number of groups for Grouped Convolutions. Defaults to 1. - separable: Bool flag that describes whether Time-Channel depthwise separable convolution should be - constructed, or ordinary convolution should be constructed. - heads: Number of "heads" for the masked convolution. Defaults to -1, which disables it. - normalization: String that represents type of normalization performed. Can be one of - "batch", "group", "instance" or "layer" to compute BatchNorm1D, GroupNorm1D, InstanceNorm or - LayerNorm (which are special cases of GroupNorm1D). - norm_groups: Number of groups used for GroupNorm (if `normalization` == "group"). - residual_mode: String argument which describes whether the residual branch should be simply - added ("add") or should first stride, then add ("stride_add"). Required when performing stride on - parallel branch as well as utilizing residual add. - residual_panes: Number of residual panes, used for Jasper-DR models. Please refer to the paper. - conv_mask: Bool flag which determines whether to utilize masked convolutions or not. In general, - it should be set to True. - se: Bool flag that determines whether Squeeze-and-Excitation layer should be used. - se_reduction_ratio: Integer value, which determines to what extend the hidden dimension of the SE - intermediate step should be reduced. Larger values reduce number of parameters, but also limit - the effectiveness of SE layers. - se_context_window: Integer value determining the number of timesteps that should be utilized in order - to compute the averaged context window. Defaults to -1, which means it uses global context - such - that all timesteps are averaged. If any positive integer is used, it will utilize limited context - window of that size. - se_interpolation_mode: String used for interpolation mode of timestep dimension for SE blocks. - Used only if context window is > 1. - The modes available for resizing are: `nearest`, `linear` (3D-only), - `bilinear`, `area`. - stride_last: Bool flag that determines whether all repeated blocks should stride at once, - (stride of S^R when this flag is False) or just the last repeated block should stride - (stride of S when this flag is True). - future_context: Int value that determins how many "right" / "future" context frames will be utilized - when calculating the output of the conv kernel. All calculations are done for odd kernel sizes only. - - By default, this is -1, which is recomputed as the symmetric padding case. - - When future_context >= 0, will compute the asymmetric padding as follows : - (left context, right context) = [K - 1 - future_context, future_context] - - Determining an exact formula to limit future context is dependent on global layout of the model. - As such, we provide both "local" and "global" guidelines below. - - Local context limit (should always be enforced) - - future context should be <= half the kernel size for any given layer - - future context > kernel size defaults to symmetric kernel - - future context of layer = number of future frames * width of each frame (dependent on stride) - - Global context limit (should be carefully considered) - - future context should be layed out in an ever reducing pattern. Initial layers should restrict - future context less than later layers, since shallow depth (and reduced stride) means each frame uses - less amounts of future context. - - Beyond a certain point, future context should remain static for a given stride level. This is - the upper bound of the amount of future context that can be provided to the model on a global scale. - - future context is calculated (roughly) as - (2 ^ stride) * (K // 2) number of future frames. - This resultant value should be bound to some global maximum number of future seconds of audio (in ms). - - Note: In the special case where K < future_context, it is assumed that the kernel is too small to limit - its future context, so symmetric padding is used instead. - - Note: There is no explicit limitation on the amount of future context used, as long as - K > future_context constraint is maintained. This might lead to cases where future_context is - more than half the actual kernel size K! In such cases, the conv layer is utilizing more of the future - context than its current and past context to compute the output. While this is possible to do, - it is not recommended and the layer will raise a warning to notify the user of such cases. - It is advised to simply use symmetric padding for such cases. - - Example: - Say we have a model that performs 8x stride and receives spectrogram frames with stride of 0.01s. - Say we wish to upper bound future context to 80 ms. - - Layer ID, Kernel Size, Stride, Future Context, Global Context - 0, K=5, S=1, FC=8, GC= 2 * (2^0) = 2 * 0.01 ms (special case, K < FC so use symmetric pad) - 1, K=7, S=1, FC=3, GC= 3 * (2^0) = 3 * 0.01 ms (note that symmetric pad here uses 3 FC frames!) - 2, K=11, S=2, FC=4, GC= 4 * (2^1) = 8 * 0.01 ms (note that symmetric pad here uses 5 FC frames!) - 3, K=15, S=1, FC=4, GC= 4 * (2^1) = 8 * 0.01 ms (note that symmetric pad here uses 7 FC frames!) - 4, K=21, S=2, FC=2, GC= 2 * (2^2) = 8 * 0.01 ms (note that symmetric pad here uses 10 FC frames!) - 5, K=25, S=2, FC=1, GC= 1 * (2^3) = 8 * 0.01 ms (note that symmetric pad here uses 14 FC frames!) - 6, K=29, S=1, FC=1, GC= 1 * (2^3) = 8 * 0.01 ms ... - quantize: Bool flag whether to quantize the Convolutional blocks. - layer_idx (int, optional): can be specified to allow layer output capture for InterCTC loss. Defaults to -1. - """ - - __constants__ = ["conv_mask", "separable", "residual_mode", "res", "mconv"] - - def __init__( - self, - inplanes, - planes, - repeat=3, - kernel_size=11, - kernel_size_factor=1, - stride=1, - dilation=1, - padding='same', - dropout=0.2, - activation=None, - residual=True, - groups=1, - separable=False, - heads=-1, - normalization="batch", - norm_groups=1, - residual_mode='add', - residual_panes=[], - conv_mask=False, - se=False, - se_reduction_ratio=16, - se_context_window=-1, - se_interpolation_mode='nearest', - stride_last=False, - future_context: int = -1, - quantize=False, - layer_idx: int = -1, # only used for capturing tensors for interctc loss - ): - super(JasperBlock, self).__init__() - - if padding != "same": - raise ValueError("currently only 'same' padding is supported") - - kernel_size_factor = float(kernel_size_factor) - if isinstance(kernel_size, Iterable): - kernel_size = [compute_new_kernel_size(k, kernel_size_factor) for k in kernel_size] - else: - kernel_size = [compute_new_kernel_size(kernel_size, kernel_size_factor)] - - if future_context < 0: - padding_val = get_same_padding(kernel_size[0], stride[0], dilation[0]) - else: - padding_val = get_asymtric_padding(kernel_size[0], stride[0], dilation[0], future_context) - - self.inplanes = inplanes - self.planes = planes - self.conv_mask = conv_mask - self.separable = separable - self.residual_mode = residual_mode - self.se = se - self.quantize = quantize - self.layer_idx = layer_idx - # will be set in self.forward() if defined in AccessMixin config - self.interctc_should_capture = None - - inplanes_loop = inplanes - conv = nn.ModuleList() - - for _ in range(repeat - 1): - # Stride last means only the last convolution in block will have stride - if stride_last: - stride_val = [1] - else: - stride_val = stride - - conv.extend( - self._get_conv_bn_layer( - inplanes_loop, - planes, - kernel_size=kernel_size, - stride=stride_val, - dilation=dilation, - padding=padding_val, - groups=groups, - heads=heads, - separable=separable, - normalization=normalization, - norm_groups=norm_groups, - quantize=quantize, - ) - ) - - conv.extend(self._get_act_dropout_layer(drop_prob=dropout, activation=activation)) - - inplanes_loop = planes - - conv.extend( - self._get_conv_bn_layer( - inplanes_loop, - planes, - kernel_size=kernel_size, - stride=stride, - dilation=dilation, - padding=padding_val, - groups=groups, - heads=heads, - separable=separable, - normalization=normalization, - norm_groups=norm_groups, - quantize=quantize, - ) - ) - - if se: - conv.append( - SqueezeExcite( - planes, - reduction_ratio=se_reduction_ratio, - context_window=se_context_window, - interpolation_mode=se_interpolation_mode, - activation=activation, - quantize=quantize, - ) - ) - - self.mconv = conv - - res_panes = residual_panes.copy() - self.dense_residual = residual - - if residual: - res_list = nn.ModuleList() - - if residual_mode == 'stride_add': - stride_val = stride - else: - stride_val = [1] - - if len(residual_panes) == 0: - res_panes = [inplanes] - self.dense_residual = False - for ip in res_panes: - res = nn.ModuleList( - self._get_conv_bn_layer( - ip, - planes, - kernel_size=1, - normalization=normalization, - norm_groups=norm_groups, - stride=stride_val, - quantize=quantize, - ) - ) - - res_list.append(res) - - self.res = res_list - if PYTORCH_QUANTIZATION_AVAILABLE and self.quantize: - self.residual_quantizer = quant_nn.TensorQuantizer(quant_nn.QuantConv2d.default_quant_desc_input) - elif not PYTORCH_QUANTIZATION_AVAILABLE and quantize: - raise ImportError( - "pytorch-quantization is not installed. Install from " - "https://github.com/NVIDIA/TensorRT/tree/master/tools/pytorch-quantization." - ) - else: - self.res = None - - self.mout = nn.Sequential(*self._get_act_dropout_layer(drop_prob=dropout, activation=activation)) - - def _get_conv( - self, - in_channels, - out_channels, - kernel_size=11, - stride=1, - dilation=1, - padding=0, - bias=False, - groups=1, - heads=-1, - separable=False, - quantize=False, - ): - use_mask = self.conv_mask - if use_mask: - return MaskedConv1d( - in_channels, - out_channels, - kernel_size, - stride=stride, - dilation=dilation, - padding=padding, - bias=bias, - groups=groups, - heads=heads, - use_mask=use_mask, - quantize=quantize, - ) - else: - if PYTORCH_QUANTIZATION_AVAILABLE and quantize: - return quant_nn.QuantConv1d( - in_channels, - out_channels, - kernel_size, - stride=stride, - dilation=dilation, - padding=padding, - bias=bias, - groups=groups, - ) - elif not PYTORCH_QUANTIZATION_AVAILABLE and quantize: - raise ImportError( - "pytorch-quantization is not installed. Install from " - "https://github.com/NVIDIA/TensorRT/tree/master/tools/pytorch-quantization." - ) - else: - return nn.Conv1d( - in_channels, - out_channels, - kernel_size, - stride=stride, - dilation=dilation, - padding=padding, - bias=bias, - groups=groups, - ) - - def _get_conv_bn_layer( - self, - in_channels, - out_channels, - kernel_size=11, - stride=1, - dilation=1, - padding=0, - bias=False, - groups=1, - heads=-1, - separable=False, - normalization="batch", - norm_groups=1, - quantize=False, - ): - if norm_groups == -1: - norm_groups = out_channels - - if separable: - layers = [ - self._get_conv( - in_channels, - in_channels, - kernel_size, - stride=stride, - dilation=dilation, - padding=padding, - bias=bias, - groups=in_channels, - heads=heads, - quantize=quantize, - ), - self._get_conv( - in_channels, - out_channels, - kernel_size=1, - stride=1, - dilation=1, - padding=0, - bias=bias, - groups=groups, - quantize=quantize, - ), - ] - else: - layers = [ - self._get_conv( - in_channels, - out_channels, - kernel_size, - stride=stride, - dilation=dilation, - padding=padding, - bias=bias, - groups=groups, - quantize=quantize, - ) - ] - - if normalization == "group": - layers.append(nn.GroupNorm(num_groups=norm_groups, num_channels=out_channels)) - elif normalization == "instance": - layers.append(nn.GroupNorm(num_groups=out_channels, num_channels=out_channels)) - elif normalization == "layer": - layers.append(nn.GroupNorm(num_groups=1, num_channels=out_channels)) - elif normalization == "batch": - layers.append(nn.BatchNorm1d(out_channels, eps=1e-3, momentum=0.1)) - else: - raise ValueError( - f"Normalization method ({normalization}) does not match" f" one of [batch, layer, group, instance]." - ) - - if groups > 1: - layers.append(GroupShuffle(groups, out_channels)) - return layers - - def _get_act_dropout_layer(self, drop_prob=0.2, activation=None): - if activation is None: - activation = nn.Hardtanh(min_val=0.0, max_val=20.0) - layers = [activation, nn.Dropout(p=drop_prob)] - return layers - - def forward(self, input_: Tuple[List[Tensor], Optional[Tensor]]) -> Tuple[List[Tensor], Optional[Tensor]]: - """ - Forward pass of the module. - - Args: - input_: The input is a tuple of two values - the preprocessed audio signal as well as the lengths - of the audio signal. The audio signal is padded to the shape [B, D, T] and the lengths are - a torch vector of length B. - - Returns: - The output of the block after processing the input through `repeat` number of sub-blocks, - as well as the lengths of the encoded audio after padding/striding. - """ - lens_orig = None - xs = input_[0] - if len(input_) == 2: - xs, lens_orig = input_ - - # compute forward convolutions - out = xs[-1] - - lens = lens_orig - for i, l in enumerate(self.mconv): - # if we're doing masked convolutions, we need to pass in and - # possibly update the sequence lengths - # if (i % 4) == 0 and self.conv_mask: - if isinstance(l, (MaskedConv1d, SqueezeExcite)): - out, lens = l(out, lens) - else: - out = l(out) - - # compute the residuals - if self.res is not None: - for i, layer in enumerate(self.res): - res_out = xs[i] - for j, res_layer in enumerate(layer): - if isinstance(res_layer, MaskedConv1d): - res_out, _ = res_layer(res_out, lens_orig) - else: - res_out = res_layer(res_out) - - if self.residual_mode == 'add' or self.residual_mode == 'stride_add': - if PYTORCH_QUANTIZATION_AVAILABLE and self.quantize: - out = self.residual_quantizer(out) + res_out - elif not PYTORCH_QUANTIZATION_AVAILABLE and self.quantize: - raise ImportError( - "pytorch-quantization is not installed. Install from " - "https://github.com/NVIDIA/TensorRT/tree/master/tools/pytorch-quantization." - ) - else: - out = out + res_out - else: - out = torch.max(out, res_out) - - # compute the output - out = self.mout(out) - - # Support ASR Adapters - if self.is_adapter_available(): - # Check for all available and enabled adapters - adapter_names = self.get_enabled_adapters() - - if len(adapter_names) > 0: - out = out.transpose(1, 2) # (B, T, C) - - # Call the adapters - out = self.forward_enabled_adapters(out) - - out = out.transpose(1, 2) # (B, C, T) - - if self.is_access_enabled(getattr(self, "model_guid", None)): - # for adapters - if self.access_cfg.get('save_encoder_tensors', False): - self.register_accessible_tensor(name='encoder', tensor=out) - # for interctc - even though in some cases it's the same, we - # want to register separate key to be able to modify it later - # during interctc processing, if required - if self.interctc_should_capture is None: - capture_layers = self.access_cfg.get('interctc', {}).get('capture_layers', []) - self.interctc_should_capture = self.layer_idx in capture_layers - if self.interctc_should_capture: - # shape is the same as the shape of audio_signal output, i.e. [B, D, T] - self.register_accessible_tensor(name=f'interctc/layer_output_{self.layer_idx}', tensor=out) - self.register_accessible_tensor(name=f'interctc/layer_length_{self.layer_idx}', tensor=lens) - - if self.res is not None and self.dense_residual: - return xs + [out], lens - - return [out], lens - - -class ParallelBlock(nn.Module): - """ - Computational module that computes several `blocks` independently from each other and aggregates the outputs. - It expects audio inputs to be passed together with lengths, just like Jasper blocks, and all outputs to have - the same dimensions but it does not impose any additional requirements on the structure of the blocks themselves. - - Args: - blocks: List of Jasper blocks that will be computed concurently. It is expected that they accept the same - input and return outputs with the same number of channels. - aggregation_mode: an optional string, indicating how the outputs will be aggregated. Supported values are - ['sum', 'dropout']. "sum" value forces outputs to be summed together. "dropout" value enables tower - dropout training with different blocks being dropped out during training. - block_dropout_prob: a probability of dropping any individual block during training with "dropout" aggregation - mode. Acts as a regularization technique. - residual_mode: an optional string indicating how residuals will be applied. Supported values are - ['sum', 'conv']. In 'sum' mode input features are summed together with the output. This will fail if the - number of channels in the input is different from the number of channels in an output tensor. In 'conv' mode - inputs are passed through pointwise convolution to make input channel dimension match output channel - dimension. In this mode `in_filters` and `out_filters` params are required. - in_filters: number of filters (channels) in the input tensor of each block. - out_filters: number of filters (channels) in the output tensor of each block. - """ - - def __init__( - self, - blocks, - aggregation_mode: str = "sum", - block_dropout_prob: int = 0.0, - residual_mode: str = "sum", - in_filters: int = None, - out_filters: int = None, - ): - super().__init__() - self.blocks = nn.ModuleList(blocks) - - self.supported_aggregations = ["sum", "dropout"] - if aggregation_mode not in self.supported_aggregations: - raise ValueError( - f"Got non-supported aggregation mode: {aggregation_mode}. Supported values are {self.supported_aggregations}." - ) - self.aggregation_mode = aggregation_mode - - if aggregation_mode == "dropout": - self.weights = nn.Parameter(torch.ones(len(blocks)), requires_grad=False) - self.dropout = nn.Dropout(block_dropout_prob) - - self.supported_residuals = ["sum", "conv"] - if residual_mode not in self.supported_residuals: - raise ValueError( - f"Got non-supported residual mode: {residual_mode}. Supported values are {self.supported_residuals}." - ) - self.residual_mode = residual_mode - - if residual_mode == "conv": - if in_filters is None or out_filters is None: - raise ValueError("in_filters and out_filters have to be specified when using 'conv' residual mode.") - self.res_conv = MaskedConv1d(in_filters, out_filters, kernel_size=1, bias=False, use_mask=True) - - def get_dropout_mask(self): - weights = self.dropout(self.weights) - while torch.sum(weights) == 0 and self.dropout.p < 1.0: - weights = self.dropout(self.weights) - return weights - - def forward(self, x: Tuple[List[Tensor], Optional[Tensor]]): - """ - Forward pass computing aggregated output. - - Args: - x: tuple of padded signal and lengths the signal. The shape of the signal is [B, D, T]. The lengths are - 1D torch tensor of length B. - - Returns: - torch tensor after passing input throught each block and aggregating these outputs according to the - aggregation mode. - """ - if len(self.blocks) == 1: - return self.blocks[0](x) - - result = None - max_mask = None - - scaling_weights = None - if self.aggregation_mode == "dropout": - scaling_weights = self.get_dropout_mask() - - for i, block in enumerate(self.blocks): - output, mask = block(x) - - weighted_output = output[-1] - if self.aggregation_mode == "dropout": - weighted_output = scaling_weights[i] * output[-1] - - if result is None: - result = weighted_output - else: - result = result + weighted_output - - if max_mask is None: - max_mask = mask - else: - max_mask = torch.max(torch.stack([mask, max_mask]), dim=0)[0] - input_feat = x[0][-1] - lens = x[1] - if self.residual_mode == "sum": - result = result + input_feat - elif self.residual_mode == "conv": - result = result + self.res_conv(input_feat, lens)[0] - return [result], max_mask diff --git a/nemo/collections/asr/parts/submodules/multi_head_attention.py b/nemo/collections/asr/parts/submodules/multi_head_attention.py deleted file mode 100644 index 3e6c056bd7b5dd3e0d1a3ab9a6d5b2f8a27dc60b..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/multi_head_attention.py +++ /dev/null @@ -1,1147 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -# Copyright 2017 Johns Hopkins University (Shinji Watanabe) -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -""" -Part of this code is adopted from https://github.com/espnet/espnet -""" - -import math -from functools import lru_cache -from typing import List, Tuple - -import torch -import torch.nn as nn -import torch.nn.attention -import torch.nn.functional as F - -from nemo.utils import avoid_float16_autocast_context - -__all__ = [ - 'RelPositionMultiHeadAttention', - 'RelPositionalEncoding', - 'PositionalEncoding', -] - -INF_VAL = 10000.0 - - -class MultiHeadAttention(nn.Module): - """Multi-Head Attention layer of Transformer. - Args: - n_head (int): number of heads - n_feat (int): size of the features - dropout_rate (float): dropout rate - use_bias (bool): whether to remove bias in linear and conv layers - use_pytorch_sdpa (bool): use torch sdpa instead of manual attention - use_pytorch_sdpa_backends list[str]: list of backend names to use in sdpa. None or empty list means all backends. e.g. ["MATH"] - """ - - def __init__( - self, - n_head, - n_feat, - dropout_rate, - max_cache_len=0, - use_bias=True, - use_pytorch_sdpa=False, - use_pytorch_sdpa_backends=None, - ): - """Construct an MultiHeadedAttention object.""" - super(MultiHeadAttention, self).__init__() - self.use_pytorch_sdpa = use_pytorch_sdpa - if self.use_pytorch_sdpa and use_pytorch_sdpa_backends: - use_pytorch_sdpa_backends = list( - map( - lambda backend_name: getattr(torch.nn.attention.SDPBackend, backend_name), - use_pytorch_sdpa_backends, - ) - ) - self.use_pytorch_sdpa_backends = use_pytorch_sdpa_backends - - self.cache_drop_size = None - self.use_bias = use_bias - self.dropout_rate = dropout_rate - assert n_feat % n_head == 0 - # We assume d_v always equals d_k - self.d_k = n_feat // n_head - self.s_d_k = math.sqrt(self.d_k) - self.h = n_head - self.linear_q = nn.Linear(n_feat, n_feat, bias=use_bias) - self.linear_k = nn.Linear(n_feat, n_feat, bias=use_bias) - self.linear_v = nn.Linear(n_feat, n_feat, bias=use_bias) - self.linear_out = nn.Linear(n_feat, n_feat, bias=use_bias) - self.dropout = nn.Dropout(p=dropout_rate) - - self._max_cache_len = max_cache_len - - def forward_qkv(self, query, key, value): - """Transforms query, key and value. - Args: - query (torch.Tensor): (batch, time1, size) - key (torch.Tensor): (batch, time2, size) - value (torch.Tensor): (batch, time2, size) - returns: - q (torch.Tensor): (batch, head, time1, size) - k (torch.Tensor): (batch, head, time2, size) - v (torch.Tensor): (batch, head, time2, size) - """ - n_batch = query.size(0) - q = self.linear_q(query).view(n_batch, -1, self.h, self.d_k) - k = self.linear_k(key).view(n_batch, -1, self.h, self.d_k) - v = self.linear_v(value).view(n_batch, -1, self.h, self.d_k) - q = q.transpose(1, 2) - k = k.transpose(1, 2) - v = v.transpose(1, 2) - - return q, k, v - - def forward_attention(self, value, scores, mask): - """Compute attention context vector. - Args: - value (torch.Tensor): (batch, time2, size) - scores(torch.Tensor): (batch, time1, time2) - mask(torch.Tensor): (batch, time1, time2) - returns: - value (torch.Tensor): transformed `value` (batch, time2, d_model) weighted by the attention scores - """ - n_batch = value.size(0) - if mask is not None: - mask = mask.unsqueeze(1) # (batch, 1, time1, time2) - scores = scores.masked_fill(mask, -INF_VAL) - attn = torch.softmax(scores, dim=-1).masked_fill(mask, 0.0) # (batch, head, time1, time2) - else: - attn = torch.softmax(scores, dim=-1) # (batch, head, time1, time2) - - p_attn = self.dropout(attn) - x = torch.matmul(p_attn, value) # (batch, head, time1, d_k) - x = x.transpose(1, 2).reshape(n_batch, -1, self.h * self.d_k) # (batch, time1, d_model) - - return self.linear_out(x) # (batch, time1, d_model) - - def forward(self, query, key, value, mask, pos_emb=None, cache=None): - """Compute 'Scaled Dot Product Attention'. - Args: - query (torch.Tensor): (batch, time1, size) - key (torch.Tensor): (batch, time2, size) - value(torch.Tensor): (batch, time2, size) - mask (torch.Tensor): (batch, time1, time2) - cache (torch.Tensor) : (batch, time_cache, size) - - returns: - output (torch.Tensor): transformed `value` (batch, time1, d_model) weighted by the query dot key attention - cache (torch.Tensor) : (batch, time_cache_next, size) - """ - key, value, query, cache = self.update_cache(key=key, value=value, query=query, cache=cache) - - if torch.is_autocast_enabled(): - query, key, value = query.to(torch.float32), key.to(torch.float32), value.to(torch.float32) - - # temporary until we solve this more gracefully - with avoid_float16_autocast_context(): - q, k, v = self.forward_qkv(query, key, value) - - if self.use_pytorch_sdpa: - n_batch = value.size(0) - - if mask is not None: - mask = ~mask.unsqueeze(1) - - dropout_rate = self.dropout_rate if self.training else 0 - if self.use_pytorch_sdpa_backends: - with torch.nn.attention.sdpa_kernel(self.use_pytorch_sdpa_backends): - out = torch.nn.functional.scaled_dot_product_attention( - q, k, v, attn_mask=mask, dropout_p=dropout_rate - ) - else: - out = torch.nn.functional.scaled_dot_product_attention( - q, k, v, attn_mask=mask, dropout_p=dropout_rate - ) - - # this IF block can be deleted when https://github.com/pytorch/pytorch/pull/131863 is in the stable version - if mask is not None: - all_masked_rows = torch.all(~mask, dim=-1) - all_masked_rows.unsqueeze_(-1) - out = out.masked_fill(all_masked_rows, 0.0) - - out = out.transpose(1, 2).reshape(n_batch, -1, self.h * self.d_k) # (batch, time1, d_model) - out = self.linear_out(out) # (batch, time1, d_model) - else: - scores = torch.matmul(q, k.transpose(-2, -1)) / self.s_d_k - out = self.forward_attention(v, scores, mask) - - if cache is None: - return out - else: - return out, cache - - def update_cache(self, key, value, query, cache): - if cache is not None: - key = value = torch.cat([cache, key], dim=1) - q_keep_size = query.shape[1] - self.cache_drop_size - cache = torch.cat([cache[:, q_keep_size:, :], query[:, :q_keep_size, :]], dim=1) - return key, value, query, cache - - -class RelPositionMultiHeadAttention(MultiHeadAttention): - """Multi-Head Attention layer of Transformer-XL with support of relative positional encoding. - Paper: https://arxiv.org/abs/1901.02860 - Args: - n_head (int): number of heads - n_feat (int): size of the features - dropout_rate (float): dropout rate - use_bias (bool): whether to apply bias in linear and conv layers of MultiHeadAttention - """ - - def __init__( - self, - n_head, - n_feat, - dropout_rate, - pos_bias_u, - pos_bias_v, - max_cache_len=0, - use_bias=True, - use_pytorch_sdpa=False, - use_pytorch_sdpa_backends=None, - ): - """Construct an RelPositionMultiHeadedAttention object.""" - super().__init__( - n_head=n_head, - n_feat=n_feat, - dropout_rate=dropout_rate, - max_cache_len=max_cache_len, - use_bias=use_bias, - use_pytorch_sdpa=use_pytorch_sdpa, - use_pytorch_sdpa_backends=use_pytorch_sdpa_backends, - ) - # linear transformation for positional encoding - self.linear_pos = nn.Linear(n_feat, n_feat, bias=False) - # these two learnable biases are used in matrix c and matrix d - # as described in https://arxiv.org/abs/1901.02860 Section 3.3 - if pos_bias_u is None or pos_bias_v is None: - self.pos_bias_u = nn.Parameter(torch.FloatTensor(self.h, self.d_k)) - self.pos_bias_v = nn.Parameter(torch.FloatTensor(self.h, self.d_k)) - # nn.init.normal_(self.pos_bias_u, 0.0, 0.02) - # nn.init.normal_(self.pos_bias_v, 0.0, 0.02) - nn.init.zeros_(self.pos_bias_u) - nn.init.zeros_(self.pos_bias_v) - else: - self.pos_bias_u = pos_bias_u - self.pos_bias_v = pos_bias_v - - def rel_shift(self, x): - """Compute relative positional encoding. - Args: - x (torch.Tensor): (batch, nheads, time, 2*time-1) - """ - b, h, qlen, pos_len = x.size() # (b, h, t1, t2) - # need to add a column of zeros on the left side of last dimension to perform the relative shifting - x = torch.nn.functional.pad(x, pad=(1, 0)) # (b, h, t1, t2+1) - x = x.view(b, h, -1, qlen) # (b, h, t2+1, t1) - # need to drop the first row - x = x[:, :, 1:].view(b, h, qlen, pos_len) # (b, h, t1, t2) - return x - - def forward(self, query, key, value, mask, pos_emb, cache=None): - """Compute 'Scaled Dot Product Attention' with rel. positional encoding. - Args: - query (torch.Tensor): (batch, time1, size) - key (torch.Tensor): (batch, time2, size) - value(torch.Tensor): (batch, time2, size) - mask (torch.Tensor): (batch, time1, time2) - pos_emb (torch.Tensor) : (batch, time1, size) - cache (torch.Tensor) : (batch, time_cache, size) - - Returns: - output (torch.Tensor): transformed `value` (batch, time1, d_model) weighted by the query dot key attention - cache (torch.Tensor) : (batch, time_cache_next, size) - """ - key, value, query, cache = self.update_cache(key=key, value=value, query=query, cache=cache) - - if torch.is_autocast_enabled(): - query, key, value = query.to(torch.float32), key.to(torch.float32), value.to(torch.float32) - - # temporary until we solve this more gracefully - with avoid_float16_autocast_context(): - q, k, v = self.forward_qkv(query, key, value) - q = q.transpose(1, 2) # (batch, time1, head, d_k) - - n_batch_pos = pos_emb.size(0) - n_batch = value.size(0) - p = self.linear_pos(pos_emb).view(n_batch_pos, -1, self.h, self.d_k) - p = p.transpose(1, 2) # (batch, head, time1, d_k) - - # (batch, head, time1, d_k) - q_with_bias_u = (q + self.pos_bias_u).transpose(1, 2) - # (batch, head, time1, d_k) - q_with_bias_v = (q + self.pos_bias_v).transpose(1, 2) - - # compute attention score - # first compute matrix a and matrix c - # as described in https://arxiv.org/abs/1901.02860 Section 3.3 - # (batch, head, time1, time2) - - # compute matrix b and matrix d - # (batch, head, time1, time2) - matrix_bd = torch.matmul(q_with_bias_v, p.transpose(-2, -1)) - matrix_bd = self.rel_shift(matrix_bd) - - if self.use_pytorch_sdpa: - scale_factor = 1 / math.sqrt(q_with_bias_u.size(-1)) - matrix_bd = matrix_bd[:, :, :, : k.size(-2)] * scale_factor - - if mask is not None: - mask = mask.unsqueeze(1) - matrix_bd.masked_fill_(mask, -INF_VAL) - - dropout_rate = self.dropout_rate if self.training else 0 - if self.use_pytorch_sdpa_backends: - with torch.nn.attention.sdpa_kernel(self.use_pytorch_sdpa_backends): - out = torch.nn.functional.scaled_dot_product_attention( - q_with_bias_u, k, v, attn_mask=matrix_bd, dropout_p=dropout_rate - ) - else: - out = torch.nn.functional.scaled_dot_product_attention( - q_with_bias_u, k, v, attn_mask=matrix_bd, dropout_p=dropout_rate - ) - - # this IF block can be deleted when https://github.com/pytorch/pytorch/pull/131863 is in the stable version - if mask is not None: - all_masked_rows = torch.all(mask, dim=-1) - all_masked_rows.unsqueeze_(-1) - all_masked_rows = all_masked_rows.expand(-1, out.size(1), -1, out.size(-1)) - out = out.masked_fill(all_masked_rows, 0.0) - - out = out.transpose(1, 2).reshape(n_batch, -1, self.h * self.d_k) # (batch, time1, d_model) - out = self.linear_out(out) # (batch, time1, d_model) - else: - # drops extra elements in the matrix_bd to match the matrix_ac's size - matrix_ac = torch.matmul(q_with_bias_u, k.transpose(-2, -1)) - matrix_bd = matrix_bd[:, :, :, : matrix_ac.size(-1)] - scores = (matrix_ac + matrix_bd) / self.s_d_k # (batch, head, time1, time2) - out = self.forward_attention(v, scores, mask) - - if cache is None: - return out - else: - return out, cache - - -class RelPositionMultiHeadAttentionLongformer(RelPositionMultiHeadAttention): - """Multi-Head Attention layer of Transformer-XL with sliding window local+global attention from Longformer. - Partially adapted from allenai (https://github.com/allenai/longformer/blob/master/longformer/sliding_chunks.py) - and huggingface (https://github.com/huggingface/transformers/blob/main/src/transformers/models/longformer/modeling_longformer.py) - Paper: https://arxiv.org/abs/1901.02860 (Transformer-XL), - https://arxiv.org/abs/2004.05150 (Longformer) - Args: - n_head (int): number of heads - n_feat (int): size of the features - dropout_rate (float): dropout rate - pos_bias_u (Tensor): the positional bias matrix U - pos_bias_v (Tensor): the positional bias matrix V - att_context_size (List[int]): List of 2 ints corresponding to left and right attention context sizes. - max_cache_len (int): the maximum size of cache - global_tokens (int): number of tokens to be used for global attention - global_tokens_spacing (int): how far apart the global tokens are - global_attn_separate (bool): whether the q, k, v layers used for global tokens should be separate - use_bias (bool): whether to apply bias in linear and conv layers of MultiHeadAttention - """ - - def __init__( - self, - n_head, - n_feat, - dropout_rate, - pos_bias_u, - pos_bias_v, - att_context_size, - max_cache_len=0, - global_tokens=0, - global_tokens_spacing=1, - global_attn_separate=False, - use_bias=True, - use_pytorch_sdpa=False, - use_pytorch_sdpa_backends=None, - ): - """Construct an RelPositionMultiHeadAttentionLongformer object.""" - super().__init__( - n_head=n_head, - n_feat=n_feat, - dropout_rate=dropout_rate, - pos_bias_u=pos_bias_u, - pos_bias_v=pos_bias_v, - max_cache_len=max_cache_len, - use_bias=use_bias, - use_pytorch_sdpa=use_pytorch_sdpa, - use_pytorch_sdpa_backends=use_pytorch_sdpa_backends, - ) - - if use_pytorch_sdpa: - raise NotImplementedError("Not implemented for Longformer yet") - - self.att_context_size = att_context_size - self.global_tokens = global_tokens - self.global_tokens_spacing = global_tokens_spacing - self.global_attn_separate = global_attn_separate - - if self.global_attn_separate: - self.global_q = nn.Linear(n_feat, n_feat, bias=use_bias) - self.global_k = nn.Linear(n_feat, n_feat, bias=use_bias) - self.global_v = nn.Linear(n_feat, n_feat, bias=use_bias) - - def forward(self, query, key, value, pad_mask, pos_emb, cache=None): - """Compute Scaled Dot Product Local Attention with rel. positional encoding. using overlapping chunks - Args: - query (torch.Tensor): (batch, time, size) - key (torch.Tensor): (batch, time, size) - value(torch.Tensor): (batch, time, size) - pad_mask (torch.Tensor): (batch, time) - pos_emb (torch.Tensor) : (batch, 2w + 1, size) - cache (torch.Tensor) : (batch, time_cache, size) - Returns: - output (torch.Tensor): transformed `value` (batch, time1, d_model) weighted by the query dot key attention - cache (torch.Tensor) : (batch, time_cache_next, size) - """ - - key, value, query, cache = self.update_cache(key=key, value=value, query=query, cache=cache) - - if torch.is_autocast_enabled(): - query, key, value = query.to(torch.float32), key.to(torch.float32), value.to(torch.float32) - - # temporary until we solve this more gracefully - with avoid_float16_autocast_context(): - q, k, v = self.forward_qkv(query, key, value) - n_batch, _, T, _ = q.size() - - w = max(self.att_context_size[0], self.att_context_size[1]) - if w <= 0: - raise ValueError("When using local attention, context size must be set > 0") - pad_len = (2 * w - T % (2 * w)) % (2 * w) # pad time to 2w - q = F.pad(q, (0, 0, 0, pad_len)) # (batch, head, time, size) - k = F.pad(k, (0, 0, 0, pad_len)) # (batch, head, time, size) - v = F.pad(v, (0, 0, 0, pad_len)) # (batch, head, time, size) - mask = F.pad(pad_mask, (0, pad_len), value=1.0) - - q_with_bias_u = q + self.pos_bias_u.unsqueeze(1) # (batch, head, time, size) - q_with_bias_v = q + self.pos_bias_v.unsqueeze(1) # (batch, head, time, size) - - diagonal_matrix_ac = self.sliding_chunks_matmul_qk( - q_with_bias_u, k, w, padding_value=0.0 - ) # (batch, head, time, 2w + 1) - - # add relative positional embedding - - n_batch_pos = pos_emb.size(0) - p = self.linear_pos(pos_emb).view(n_batch_pos, -1, self.h, self.d_k).transpose(1, 2) - # (batch, head, 2w, size) - diagonal_matrix_bd = torch.matmul(q_with_bias_v, p.transpose(-2, -1)) - # (batch, head, time, 2w + 1) - - start_pos = w - self.att_context_size[0] - end_pos = w + self.att_context_size[1] - - diagonal_matrix_ac[:, :, :, : self.att_context_size[0]] += diagonal_matrix_bd[ - :, :, :, : self.att_context_size[0] - ] - diagonal_matrix_ac[:, :, :, -(self.att_context_size[1] + 1) :] += diagonal_matrix_bd[ - :, :, :, self.att_context_size[0] : - ] - scores = diagonal_matrix_ac / self.s_d_k - # (batch, head, time, 2w + 1) - - # mask invalid positions - scores[:, :, :, :start_pos] = -INF_VAL - scores[:, :, :, end_pos + 1 :] = -INF_VAL - - # This implementation is fast and takes very little memory because num_heads x hidden_size = 1 - # from (bsz x seq_len) to (bsz x num_heads x seqlen x hidden_size) - mask = mask.unsqueeze(dim=1).unsqueeze(dim=-1) - # cast to float/half then replace 1's with -inf - float_mask = mask.type_as(scores).masked_fill(mask, -INF_VAL) - ones = float_mask.new_ones(size=float_mask.size()) # tensor of ones - # diagonal mask with zeros everywhere and -inf inplace of padding - d_mask = self.sliding_chunks_matmul_qk(ones, float_mask, w, padding_value=0.0) - # (batch, head, time, 2w + 1) - - scores += d_mask - - if self.global_tokens > 0: - - # create q, k, v for global attn - if self.global_attn_separate: - global_q = self.global_q(query).view(n_batch, -1, self.h, self.d_k) - global_k = self.global_k(key).view(n_batch, -1, self.h, self.d_k) - global_v = self.global_v(value).view(n_batch, -1, self.h, self.d_k) - global_q = global_q.transpose(1, 2) - global_k = global_k.transpose(1, 2) - global_v = global_v.transpose(1, 2) - global_q = F.pad(global_q, (0, 0, 0, pad_len)) # (batch, head, time, size) - global_k = F.pad(global_k, (0, 0, 0, pad_len)) # (batch, head, time, size) - global_v = F.pad(global_v, (0, 0, 0, pad_len)) # (batch, head, time, size) - else: - global_q, global_k, global_v = q, k, v - - global_q /= self.s_d_k - - # assign which tokens are global - is_index_global_attn = torch.zeros_like(pad_mask) - is_index_global_attn[ - :, : self.global_tokens * self.global_tokens_spacing : self.global_tokens_spacing - ] = 1.0 - - # compute global attn indices - ( - max_num_global_attn_indices, - is_index_global_attn_nonzero, - is_local_index_global_attn_nonzero, - is_local_index_no_global_attn_nonzero, - ) = self._get_global_attn_indices(is_index_global_attn=is_index_global_attn) - - # calculate global attn probs with global keys - # (batch, time, head, max_num_global_attn_indices) - global_key_attn = self._compute_global_key_attn( - query=global_q.transpose(1, 2), - key=global_k.transpose(1, 2), - max_num_global_attn_indices=max_num_global_attn_indices, - is_index_global_attn_nonzero=is_index_global_attn_nonzero, - is_local_index_global_attn_nonzero=is_local_index_global_attn_nonzero, - is_local_index_no_global_attn_nonzero=is_local_index_no_global_attn_nonzero, - ).transpose(1, 2) - - # concat to local_attn_probs - # (batch, time, head, max_num_global_attn_indices + 2*w) - scores = torch.cat((global_key_attn, scores), dim=-1) - - # free memory - del global_key_attn - - attn = torch.softmax(scores, dim=-1).masked_fill(mask, 0.0) - p_attn = self.dropout(attn) - # (batch, head, time, 2w + 1) - - if self.global_tokens > 0: - # compute sum of global and local attn - out = self._compute_attn_output_with_global_indices( - value=v, - attn_probs=p_attn, - max_num_global_attn_indices=max_num_global_attn_indices, - is_index_global_attn_nonzero=is_index_global_attn_nonzero, - is_local_index_global_attn_nonzero=is_local_index_global_attn_nonzero, - w=w, - ) - else: - # compute local attn only - out = self.sliding_chunks_matmul_pv(p_attn, v, w) - - out = out.reshape(n_batch, -1, self.h * self.d_k)[:, :T] - - if self.global_tokens > 0: - out_global_to_all = self._compute_out_global_to_all( - query=global_q, - key=global_k, - value=global_v, - max_num_global_attn_indices=max_num_global_attn_indices, - is_local_index_global_attn_nonzero=is_local_index_global_attn_nonzero, - is_index_global_attn_nonzero=is_index_global_attn_nonzero, - is_local_index_no_global_attn_nonzero=is_local_index_no_global_attn_nonzero, - is_index_masked=mask, - ) - - # overwrite values with global attention - out[is_index_global_attn_nonzero] = out_global_to_all - - ret = self.linear_out(out) - - if cache is None: - return ret - else: - return ret, cache - - def _get_global_attn_indices(self, is_index_global_attn: torch.Tensor) -> Tuple: - """ - Compute global attention indices. - - Args: - is_index_global_attn (torch.Tensor): (batch, time) A boolean tensor indicating if an index is a global attention index. - - Returns: - max_num_global_attn_indices (int): Maximum number of global attention indices in the batch. - is_index_global_attn_nonzero (tuple): Indices of global attention (non-zero elements). - is_local_index_global_attn_nonzero (tuple): Indices of non-padding values within global attention indices. - is_local_index_no_global_attn_nonzero (tuple): Indices of padding values within global attention indices. - """ - # Calculate the number of global attention indices in the batch - num_global_attn_indices = is_index_global_attn.long().sum(dim=1) - - # Find the maximum number of global attention indices in the batch - max_num_global_attn_indices = num_global_attn_indices.max() - - # Get the indices of global attention (non-zero elements) - is_index_global_attn_nonzero = is_index_global_attn.nonzero(as_tuple=True) - - # Create a helper tensor to find the local indices of global attention - is_local_index_global_attn = torch.arange( - max_num_global_attn_indices, device=is_index_global_attn.device - ) < num_global_attn_indices.unsqueeze(dim=-1) - - # Find the non-padding values within global attention indices - is_local_index_global_attn_nonzero = is_local_index_global_attn.nonzero(as_tuple=True) - - # Find the padding values within global attention indices - is_local_index_no_global_attn_nonzero = (is_local_index_global_attn == 0).nonzero(as_tuple=True) - - return ( - max_num_global_attn_indices, - is_index_global_attn_nonzero, - is_local_index_global_attn_nonzero, - is_local_index_no_global_attn_nonzero, - ) - - def _compute_global_key_attn( - self, - key: torch.Tensor, - query: torch.Tensor, - max_num_global_attn_indices: int, - is_index_global_attn_nonzero: tuple, - is_local_index_global_attn_nonzero: tuple, - is_local_index_no_global_attn_nonzero: tuple, - ) -> torch.Tensor: - """ - Compute the attention probabilities using only global key vectors. - - Args: - key (torch.Tensor): (batch, time, head, head_dim) The key vectors. - query (torch.Tensor): (batch, time, head, head_dim) The query vectors. - max_num_global_attn_indices (int): Maximum number of global attention indices in the batch. - is_index_global_attn_nonzero (tuple): Indices of global attention (non-zero elements). - is_local_index_global_attn_nonzero (tuple): Non-padding values within global attention indices. - is_local_index_no_global_attn_nonzero (tuple): Padding values within global attention indices. - - Returns: - attn_probs_from_global_key (torch.Tensor): (batch, time, head, max_num_global_attn_indices) The computed attention probabilities using only global key vectors. - """ - batch_size = key.shape[0] - - # create only global key vectors - key_only_global = key.new_zeros(batch_size, max_num_global_attn_indices, self.h, self.d_k) - - key_only_global[is_local_index_global_attn_nonzero] = key[is_index_global_attn_nonzero] - - # (batch_size, seq_len, head, max_num_global_attn_indices) - attn_probs_from_global_key = torch.einsum("blhd,bshd->blhs", (query, key_only_global)) - - # need to transpose since ONNX export only supports consecutive indexing: https://pytorch.org/docs/stable/onnx.html#writes-sets - attn_probs_from_global_key = attn_probs_from_global_key.transpose(1, 3) - attn_probs_from_global_key[ - is_local_index_no_global_attn_nonzero[0], is_local_index_no_global_attn_nonzero[1], :, : - ] = torch.finfo(attn_probs_from_global_key.dtype).min - attn_probs_from_global_key = attn_probs_from_global_key.transpose(1, 3) - - return attn_probs_from_global_key - - def _compute_attn_output_with_global_indices( - self, - value: torch.Tensor, - attn_probs: torch.Tensor, - max_num_global_attn_indices: int, - is_index_global_attn_nonzero: tuple, - is_local_index_global_attn_nonzero: tuple, - w: int, - ) -> torch.Tensor: - """ - Compute the attention output with global indices. - - Args: - value (torch.Tensor): (batch, head, time, head_dim) The value vectors for global attention. - attn_probs (torch.Tensor): (batch, time, head, 2w) The attention probabilities. - max_num_global_attn_indices (int): Maximum number of global attention indices in the batch. - is_index_global_attn_nonzero (tuple): Indices of global attention (non-zero elements). - is_local_index_global_attn_nonzero (tuple): Non-padding values within global attention indices. - w (int): Local context size - Returns: - torch.Tensor: (batch, time, head x head_dim) The attention output of all tokens attending to global. - """ - batch_size, time = attn_probs.shape[0], attn_probs.shape[2] - - value = value.transpose(1, 2) - - # get value vectors for global only - value_vectors_only_global = value.new_zeros(batch_size, max_num_global_attn_indices, self.h, self.d_k) - value_vectors_only_global[is_local_index_global_attn_nonzero] = value[is_index_global_attn_nonzero] - - # cut local attn probs to global only - attn_probs_only_global = attn_probs.narrow(-1, 0, max_num_global_attn_indices) - # compute attn output only global - attn_output_only_global = torch.matmul( - attn_probs_only_global.clone(), value_vectors_only_global.transpose(1, 2).clone() - ).transpose(1, 2) - - # reshape attn probs - attn_probs_without_global = attn_probs.narrow( - -1, max_num_global_attn_indices, attn_probs.size(-1) - max_num_global_attn_indices - ).contiguous() - - # compute attn output with global - attn_output_without_global = self.sliding_chunks_matmul_pv(attn_probs_without_global, value.transpose(1, 2), w) - - return attn_output_only_global + attn_output_without_global - - def _compute_out_global_to_all( - self, - query: torch.Tensor, - key: torch.Tensor, - value: torch.Tensor, - max_num_global_attn_indices: int, - is_local_index_global_attn_nonzero: tuple, - is_index_global_attn_nonzero: tuple, - is_local_index_no_global_attn_nonzero: tuple, - is_index_masked: torch.Tensor, - ) -> Tuple[torch.Tensor, torch.Tensor]: - """ - Compute the attention output of global tokens attending to all. - - Args: - query (torch.Tensor): (batch, head, time, head_dim) The queries for global attention. - key (torch.Tensor): (batch, head, time, head_dim) The keys for global attention. - value (torch.Tensor): (batch, head, time, head_dim) The values for global attention. - max_num_global_attn_indices (int): Maximum number of global attention indices in the batch. - is_local_index_global_attn_nonzero (tuple): Non-padding values within global attention indices. - is_index_global_attn_nonzero (tuple): Indices of global attention (non-zero elements). - is_local_index_no_global_attn_nonzero (tuple): Padding values within global attention indices. - is_index_masked (torch.Tensor): (batch, time) A boolean tensor indicating if an index is masked. - - Returns: - global_attn_output (torch.Tensor): (batch, max_num_global_attn_indices, head x head_dim) - The attention output of global tokens attending to all. - """ - - batch_size = key.shape[0] - seq_len = key.shape[2] - - global_k = key.reshape(batch_size * self.h, -1, self.d_k) - global_v = value.reshape(batch_size * self.h, -1, self.d_k) - - global_q = query.transpose(1, 2) - global_q_from_global = global_q.new_zeros(batch_size, max_num_global_attn_indices, self.h, self.d_k) - global_q_from_global[is_local_index_global_attn_nonzero] = global_q[is_index_global_attn_nonzero] - global_q_from_global = global_q_from_global.transpose(0, 1).reshape(batch_size * self.h, -1, self.d_k) - - # compute attn scores - global_attn_scores = torch.bmm(global_q_from_global, global_k.transpose(1, 2)) - global_attn_scores = global_attn_scores.view(batch_size, self.h, max_num_global_attn_indices, seq_len) - - # need to transpose since ONNX export only supports consecutive indexing: https://pytorch.org/docs/stable/onnx.html#writes-sets - global_attn_scores = global_attn_scores.transpose(1, 2) - global_attn_scores[ - is_local_index_no_global_attn_nonzero[0], is_local_index_no_global_attn_nonzero[1], :, : - ] = torch.finfo(global_attn_scores.dtype).min - global_attn_scores = global_attn_scores.transpose(1, 2) - - global_attn_scores = global_attn_scores.masked_fill( - is_index_masked.transpose(2, 3), - torch.finfo(global_attn_scores.dtype).min, - ) - - global_attn_scores = global_attn_scores.view(batch_size * self.h, max_num_global_attn_indices, seq_len) - - # compute global attn probs - if self.training: - global_attn_probs_float = nn.functional.softmax(global_attn_scores, dim=-1, dtype=torch.float32) - else: - global_attn_probs_float = nn.functional.softmax(global_attn_scores, dim=-1) - - global_attn_probs = self.dropout(global_attn_probs_float) - - # global attn output - global_attn_output = torch.bmm(global_attn_probs, global_v) - global_attn_output = global_attn_output.view(batch_size, self.h, max_num_global_attn_indices, self.d_k) - - global_attn_output = global_attn_output[ - is_local_index_global_attn_nonzero[0], :, is_local_index_global_attn_nonzero[1] - ] - - global_attn_output = global_attn_output.reshape(global_attn_output.shape[0], -1) - - return global_attn_output - - # Longformer implementation for overlap case - # - def _skew(self, x: torch.Tensor, direction: List[int], padding_value: float) -> torch.Tensor: - """Convert diagonals into columns (or columns into diagonals depending on `direction` - - Args: - x (torch.Tensor): (batch x head, chunk_count, 2w, 2w) - direction (List[int]): padding directions - padding_value (float): value to pad with - - Returns: - output (torch.Tensor): (batch x head, chunk_count, 2w, 2w + 1) - - """ - x_padded = F.pad(x, direction, value=padding_value) - x_padded = x_padded.view(*x_padded.size()[:-2], x_padded.size(-1), x_padded.size(-2)) - return x_padded - - def _skew2(self, x: torch.Tensor, padding_value: float) -> torch.Tensor: - """Shift every row 1 step to right converting columns into diagonals - - Args: - x (torch.Tensor): (batch x head, chunks_count + 1, w, 2w + 1) - padding_value (float): value to pad with - - Returns: - output (torch.Tensor): (batch x head, chunks_count + 1, w, 3w) - """ - # X = B x C x M x L - B, C, M, L = x.size() - x = F.pad(x, (0, M + 1), value=padding_value) # B x C x M x (L+M+1) - x = x.view(B, C, -1) # B x C x ML+MM+M - x = x[:, :, :-M] # B x C x ML+MM - x = x.view(B, C, M, M + L) # B x C, M x L+M - x = x[:, :, :, :-1] - return x - - def _chunk_overlap(self, x: torch.Tensor, w: int) -> torch.Tensor: - """Convert into overlapping chunks. - - Args: - x (torch.Tensor): # (batch x head, time, size) - w (int): Chunk overlap size - - Returns: - output (torch.Tensor): # (batch x head, chunk_count, 2w, size) - """ - - # non-overlapping chunks of size = 2w - x = x.view(x.size(0), x.size(1) // (w * 2), w * 2, x.size(2)) - - # use `as_strided` to make the chunks overlap with an overlap size = w - chunk_size = list(x.size()) - chunk_size[1] = chunk_size[1] * 2 - 1 - - chunk_stride = list(x.stride()) - chunk_stride[1] = chunk_stride[1] // 2 - return x.as_strided(size=chunk_size, stride=chunk_stride) - - @lru_cache() - def _get_invalid_locations_mask(self, w: int, device: str): - - diagonals_list = [] - for j in range(-w, 1): - diagonal_mask = torch.zeros(w, device='cpu', dtype=torch.uint8) - diagonal_mask[:-j] = 1 - diagonals_list.append(diagonal_mask) - - mask = torch.stack(diagonals_list, dim=-1) - mask = mask[None, None, :, :] - - ending_mask = mask.flip(dims=(2, 3)).bool().to(device) - return mask.bool().to(device), ending_mask - - def mask_invalid_locations( - self, - input_tensor: torch.Tensor, - w: int, - ): - """ - Mask locations invalid for the sliding window attention - - Args: - input_tensor (torch.Tensor): # (batch x head, time, size) - w (int): Chunk overlap size - """ - beginning_mask, ending_mask = self._get_invalid_locations_mask(w, input_tensor.device) - seq_len = input_tensor.size(2) - beginning_input = input_tensor[:, :, :w, : w + 1] - beginning_mask = beginning_mask[:, :, :seq_len].expand(beginning_input.size()) - beginning_input.masked_fill_(beginning_mask, -float('inf')) - - ending_input = input_tensor[:, :, -w:, -(w + 1) :] - ending_mask = ending_mask[:, :, -seq_len:].expand(ending_input.size()) - ending_input.masked_fill_(ending_mask, -float('inf')) - - def sliding_chunks_matmul_qk(self, q: torch.Tensor, k: torch.Tensor, w: int, padding_value: float) -> torch.Tensor: - """Matrix multiplication of query x key tensors using with a sliding window attention pattern. - This implementation splits the input into overlapping chunks of size 2w - with an overlap of size w - - Args: - q (torch.Tensor): (batch, head, time, size) - k (torch.Tensor): (batch, head, time, size) - w (int): Chunk overlap size - padding_value (float): Value to pad with - - Returns: - output (torch.Tensor): (batch, head, time, 2w + 1) - """ - bsz, num_heads, seqlen, head_dim = q.size() - assert seqlen % (w * 2) == 0 - assert q.size() == k.size() - - chunks_count = seqlen // w - 1 - - # group bsz and num_heads dimensions into one, then chunk seqlen into chunks of size w * 2 - q = q.reshape(bsz * num_heads, seqlen, head_dim) - k = k.reshape(bsz * num_heads, seqlen, head_dim) - - chunk_q = self._chunk_overlap(q, w) # (batch x head, chunk_count, 2w, size) - chunk_k = self._chunk_overlap(k, w) # (batch x head, chunk_count, 2w, size) - - # matrix multipication - # bcxd: bsz*num_heads x chunks x 2w x head_dim - # bcyd: bsz*num_heads x chunks x 2w x head_dim - # bcxy: bsz*num_heads x chunks x 2w x 2w - chunk_attn = torch.einsum('bcxd,bcyd->bcxy', (chunk_q, chunk_k)) # multiply - # (batch x head, chunk_count, 2w, 2w) - - # convert diagonals into columns - diagonal_chunk_attn = self._skew(chunk_attn, direction=(0, 0, 0, 1), padding_value=padding_value) - # (batch x head, chunk_count, 2w, 2w + 1) - - # allocate space for the overall attention matrix where the chunks are combined. The last dimension - # has (w * 2 + 1) columns. The first (w) columns are the w lower triangles (attention from a word to - # w previous words). The following column is attention score from each word to itself, then - # followed by w columns for the upper triangle. - - diagonal_attn = diagonal_chunk_attn.new_empty((bsz * num_heads, chunks_count + 1, w, w * 2 + 1)) - # (batch x head, chunk_count + 1, w, 2w + 1) - - # copy parts from diagonal_chunk_attn into the compined matrix of attentions - # - copying the main diagonal and the upper triangle - diagonal_attn[:, :-1, :, w:] = diagonal_chunk_attn[:, :, :w, : w + 1] - diagonal_attn[:, -1, :, w:] = diagonal_chunk_attn[:, -1, w:, : w + 1] - # - copying the lower triangle - diagonal_attn[:, 1:, :, :w] = diagonal_chunk_attn[:, :, -(w + 1) : -1, w + 1 :] - diagonal_attn[:, 0, 1:w, 1:w] = diagonal_chunk_attn[:, 0, : w - 1, 1 - w :] - - # separate bsz and num_heads dimensions again - diagonal_attn = diagonal_attn.view(bsz, num_heads, seqlen, 2 * w + 1) - # (batch, head, time, 2w + 1) - - self.mask_invalid_locations(diagonal_attn, w) - - return diagonal_attn - - def sliding_chunks_matmul_pv(self, prob: torch.Tensor, v: torch.Tensor, w: int): - """Same as sliding_chunks_matmul_qk but for prob and value tensors. - - Args: - prob (torch.Tensor): (batch, head, time, size) - v (torch.Tensor): (batch, head, time, size) - w (int): Chunk overlap size - - Returns: - output (torch.Tensor): (batch, time, head, size) - """ - bsz, num_heads, seqlen, head_dim = v.size() - chunks_count = seqlen // w - 1 - # group bsz and num_heads dimensions into one, then chunk seqlen into chunks of size 2w - chunk_prob = prob.reshape(bsz * num_heads, seqlen // w, w, 2 * w + 1) - # (batch x head, chunks_count + 1, w, 2w + 1) - - # group bsz and num_heads dimensions into one - v = v.reshape(bsz * num_heads, seqlen, head_dim) - # (batch x head, time, size) - - # pad seqlen with w at the beginning of the sequence and another w at the end - padded_v = F.pad(v, (0, 0, w, w), value=-1) - # (batch x head, time + 2w, size) - - # chunk padded_v into chunks of size 3w and an overlap of size w - chunk_v_size = (bsz * num_heads, chunks_count + 1, 3 * w, head_dim) - chunk_v_stride = padded_v.stride() - chunk_v_stride = chunk_v_stride[0], w * chunk_v_stride[1], chunk_v_stride[1], chunk_v_stride[2] - chunk_v = padded_v.as_strided(size=chunk_v_size, stride=chunk_v_stride) - # (batch x head, chunks_count + 1, 3w, size) - - skewed_prob = self._skew2(chunk_prob, padding_value=0) - # (batch x head, chunks_count + 1, w, 3w) - - context = torch.einsum('bcwd,bcdh->bcwh', (skewed_prob, chunk_v)) - # (batch x head, chunks_count + 1, w, size) - - return context.view(bsz, num_heads, seqlen, head_dim).transpose(1, 2) - - -class PositionalEncoding(torch.nn.Module): - """Fixed sinusoidal positional encoding. - Args: - d_model (int): embedding dim - dropout_rate (float): dropout rate - max_len (int): maximum input length - xscale (bool): whether to scale the input by sqrt(d_model) - dropout_rate_emb (float): dropout rate for the positional embeddings - """ - - def __init__(self, d_model, dropout_rate, max_len=5000, xscale=None, dropout_rate_emb=0.0): - """Construct an PositionalEncoding object.""" - super(PositionalEncoding, self).__init__() - self.d_model = d_model - self.xscale = xscale - self.dropout = torch.nn.Dropout(p=dropout_rate) - self.max_len = max_len - if dropout_rate_emb > 0: - self.dropout_emb = nn.Dropout(dropout_rate_emb) - else: - self.dropout_emb = None - - def create_pe(self, positions, dtype): - pos_length = positions.size(0) - pe = torch.zeros(pos_length, self.d_model, device=positions.device) - div_term = torch.exp( - torch.arange(0, self.d_model, 2, dtype=torch.float32, device=positions.device) - * -(math.log(INF_VAL) / self.d_model) - ) - pe[:, 0::2] = torch.sin(positions * div_term) - pe[:, 1::2] = torch.cos(positions * div_term) - pe = pe.unsqueeze(0).to(dtype) - if hasattr(self, 'pe'): - self.pe = pe - else: - self.register_buffer('pe', pe, persistent=False) - - def extend_pe(self, length, device, dtype): - """Reset and extend the positional encodings if needed.""" - if hasattr(self, 'pe') and self.pe.size(1) >= length: - return - positions = torch.arange(0, length, dtype=torch.float32, device=device).unsqueeze(1) - self.create_pe(positions=positions, dtype=dtype) - - def forward(self, x: torch.Tensor, cache_len=0): - """Adds positional encoding. - Args: - x (torch.Tensor): Input. Its shape is (batch, time, feature_size) - cache_len (int): the size of the cache which is used to shift positions - Returns: - x+pos_emb (torch.Tensor): Its shape is (batch, time, feature_size) - pos_emb (torch.Tensor): Its shape is (1, time, feature_size) - """ - input_len = x.size(1) + cache_len - if self.xscale: - x = x * self.xscale - pos_emb = self.pe[:, :input_len] - if self.dropout_emb: - pos_emb = self.dropout_emb(pos_emb) - x = x + pos_emb - return self.dropout(x), pos_emb - - -class RelPositionalEncoding(PositionalEncoding): - """Relative positional encoding for TransformerXL's layers - See : Appendix B in https://arxiv.org/abs/1901.02860 - Args: - d_model (int): embedding dim - dropout_rate (float): dropout rate - max_len (int): maximum input length - xscale (bool): whether to scale the input by sqrt(d_model) - dropout_rate_emb (float): dropout rate for the positional embeddings - """ - - def extend_pe(self, length, device, dtype): - """Reset and extend the positional encodings if needed.""" - needed_size = 2 * length - 1 - if hasattr(self, 'pe') and self.pe.size(1) >= needed_size: - return - # positions would be from negative numbers to positive - # positive positions would be used for left positions and negative for right positions - positions = torch.arange(length - 1, -length, -1, dtype=torch.float32, device=device).unsqueeze(1) - self.create_pe(positions=positions, dtype=dtype) - - def forward(self, x, cache_len=0): - """Compute positional encoding. - Args: - x (torch.Tensor): Input. Its shape is (batch, time, feature_size) - cache_len (int): the size of the cache which is used to shift positions - Returns: - x (torch.Tensor): Its shape is (batch, time, feature_size) - pos_emb (torch.Tensor): Its shape is (1, time, feature_size) - """ - - if self.xscale: - x = x * self.xscale - - # center_pos would be the index of position 0 - # negative positions would be used for right and positive for left tokens - # for input of length L, 2*L-1 positions are needed, positions from (L-1) to -(L-1) - input_len = x.size(1) + cache_len - center_pos = self.pe.size(1) // 2 + 1 - start_pos = center_pos - input_len - end_pos = center_pos + input_len - 1 - pos_emb = self.pe[:, start_pos:end_pos] - if self.dropout_emb: - pos_emb = self.dropout_emb(pos_emb) - return self.dropout(x), pos_emb - - -class LocalAttRelPositionalEncoding(PositionalEncoding): - """Relative positional encoding for sliding window attention or chunked attention. - See above for relative positional encoding based on Transformer-XL paper - Args: - left_chunk_size (int): number of frames to in past chunks - chunk size (int): number of frames (max frames if using multimode) in current chunk - d_model (int): embedding dim - dropout_rate (float): dropout rate - max_len (int): maximum input length - xscale (bool): whether to scale the input by sqrt(d_model) - dropout_rate_emb (float): dropout rate for the positional embeddings - """ - - def __init__(self, att_context_size, **kwargs): - super(LocalAttRelPositionalEncoding, self).__init__(**kwargs) - self.left_context = att_context_size[0] - self.right_context = att_context_size[1] - - def extend_pe(self, length, device, dtype): - """Reset and extend the positional encodings only at the beginning""" - if hasattr(self, 'pe'): - return - - positions = torch.arange( - self.left_context, -self.right_context - 1, -1, dtype=torch.float32, device=device - ).unsqueeze(1) - self.create_pe(positions=positions, dtype=dtype) - - def forward(self, x, cache_len=0): - """Compute positional encoding. - Args: - x (torch.Tensor): Input. Its shape is (batch, time, feature_size) - Returns: - x (torch.Tensor): Its shape is (batch, time, feature_size) - pos_emb (torch.Tensor): Its shape is (1, time, feature_size) - """ - - if self.xscale: - x = x * self.xscale - - end_pos = self.left_context + self.right_context + 1 - pos_emb = self.pe[:, :end_pos] - if self.dropout_emb: - pos_emb = self.dropout_emb(pos_emb) - return self.dropout(x), pos_emb diff --git a/nemo/collections/asr/parts/submodules/multitask_beam_decoding.py b/nemo/collections/asr/parts/submodules/multitask_beam_decoding.py deleted file mode 100644 index 3c2a424dcd09974aa193e73967c658c75c55b754..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/multitask_beam_decoding.py +++ /dev/null @@ -1,325 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from abc import ABC, abstractmethod -from dataclasses import dataclass, field -from pathlib import Path -from typing import List, Optional, Union - -import torch - -from nemo.collections.asr.modules.transformer import ( - BeamSearchSequenceGenerator, - BeamSearchSequenceGeneratorWithFusionModels, -) -from nemo.collections.asr.parts.context_biasing import BoostingTreeModelConfig, GPUBoostingTreeModel -from nemo.collections.asr.parts.submodules.ngram_lm import NGramGPULanguageModel -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis, NBestHypotheses -from nemo.collections.common.tokenizers.tokenizer_spec import TokenizerSpec -from nemo.core import Typing, typecheck -from nemo.core.neural_types import ChannelType, HypothesisType, LabelsType, MaskType, NeuralType -from nemo.utils import logging - - -def pack_hypotheses( - hypotheses: List[Hypothesis], - beam_hypotheses: torch.Tensor, - scores: List[Optional[float]], - xatt_scores_list: List[torch.Tensor] = None, -) -> List[Hypothesis]: - - for idx, hyp in enumerate(hypotheses): # type: Hypothesis - if scores[idx] is not None: - hyp.score = scores[idx] - - hypi = beam_hypotheses[idx] - if torch.is_tensor(hypi): - hyp.y_sequence = hypi.long() - else: - hyp.y_sequence = torch.tensor(hypi, dtype=torch.long) - - if hyp.dec_state is not None: - hyp.dec_state = _states_to_device(hyp.dec_state) - - if xatt_scores_list is not None: - hyp.xatt_scores = [xatt_layer[idx] for xatt_layer in xatt_scores_list] - - return hypotheses - - -def _states_to_device(dec_state, device='cpu'): - if torch.is_tensor(dec_state): - dec_state = dec_state.to(device) - - elif isinstance(dec_state, (list, tuple)): - dec_state = tuple(_states_to_device(dec_i, device) for dec_i in dec_state) - - return dec_state - - -class AEDBeamInfer(ABC): - def __init__( - self, - transformer_decoder: torch.nn.Module, - log_softmax_module: torch.nn.Module, - tokenizer: TokenizerSpec, - search_type: str = 'default', - return_best_hypothesis: bool = True, - preserve_alignments: bool = False, - ): - super().__init__() - - self.transformer_decoder = transformer_decoder - self.log_softmax_module = log_softmax_module - self.tokenizer = tokenizer - - self.search_type = search_type - self.return_best_hypothesis = return_best_hypothesis - self.preserve_alignments = preserve_alignments - - def __call__(self, *args, **kwargs): - return self.forward(*args, **kwargs) - - @abstractmethod - def forward( - self, - encoder_hidden_states: torch.Tensor, - encoder_input_mask: torch.Tensor, - decoder_input_ids: Optional[torch.Tensor] = None, - partial_hypotheses: Optional[List[Hypothesis]] = None, - ): - raise NotImplementedError() - - def set_decoding_type(self, decoding_type: str): - self.decoding_type = decoding_type - - -class TransformerAEDBeamInfer(AEDBeamInfer, Typing): - """A beam decoder engine for AED Transformer models. - - Provides a common abstraction for batch level beam decoding. - - """ - - @property - def input_types(self): - """Returns definitions of module input ports.""" - # Input can be of dimention - - # ('B', 'T', 'D') [Log probs] or ('B', 'T') [Labels] - - return { - "encoder_hidden_states": NeuralType(tuple(('B', 'T', 'D')), ChannelType()), - "encoder_input_mask": NeuralType(tuple(('B', 'T')), MaskType()), - "decoder_input_ids": NeuralType(('B', 'T'), LabelsType()), - "partial_hypotheses": NeuralType(optional=True), - } - - @property - def output_types(self): - """Returns definitions of module output ports.""" - return {"predictions": [NeuralType(elements_type=HypothesisType())]} - - def __init__( - self, - transformer_decoder: torch.nn.Module, - log_softmax_module: torch.nn.Module, - tokenizer: TokenizerSpec, - search_type: str = 'default', - beam_size: int = 1, - length_penalty: float = 0.0, - max_generation_delta: int = 50, - return_best_hypothesis: bool = True, - preserve_alignments: bool = False, - ngram_lm_model: Path | str | None = None, - ngram_lm_alpha: float = 0.0, - boosting_tree: BoostingTreeModelConfig | None = None, - boosting_tree_alpha: float = 0.0, - return_xattn_scores: bool = False, - ): - super().__init__( - transformer_decoder=transformer_decoder, - log_softmax_module=log_softmax_module, - tokenizer=tokenizer, - search_type=search_type, - return_best_hypothesis=return_best_hypothesis, - preserve_alignments=preserve_alignments, - ) - self.beam_size = beam_size - self.bos = tokenizer.bos - self.pad = tokenizer.pad - self.eos = tokenizer.eos - - # load boosting tree model - boosting_tree_model = None - if boosting_tree and not BoostingTreeModelConfig.is_empty(boosting_tree): - boosting_tree_model = GPUBoostingTreeModel.from_config(boosting_tree, tokenizer=tokenizer) - - # initialize fusion models (ngram LM, boosting tree) - fusion_models, fusion_models_alpha = [], [] - if ngram_lm_model is not None: - fusion_models.append( - NGramGPULanguageModel.from_file(lm_path=ngram_lm_model, vocab_size=tokenizer.vocab_size) - ) - fusion_models_alpha.append(ngram_lm_alpha) - if boosting_tree_model is not None: - fusion_models.append(boosting_tree_model) - fusion_models_alpha.append(boosting_tree_alpha) - - if not fusion_models: - self.beam_search = BeamSearchSequenceGenerator( - embedding=transformer_decoder.embedding, - decoder=transformer_decoder.decoder, - log_softmax=log_softmax_module, - max_sequence_length=transformer_decoder.max_sequence_length, - beam_size=beam_size, - bos=self.bos, - pad=self.pad, - eos=self.eos, - len_pen=length_penalty, - max_delta_length=max_generation_delta, - return_xattn_scores=return_xattn_scores, - ) - else: - self.beam_search = BeamSearchSequenceGeneratorWithFusionModels( - embedding=transformer_decoder.embedding, - decoder=transformer_decoder.decoder, - log_softmax=log_softmax_module, - max_sequence_length=transformer_decoder.max_sequence_length, - beam_size=beam_size, - bos=self.bos, - pad=self.pad, - eos=self.eos, - len_pen=length_penalty, - max_delta_length=max_generation_delta, - fusion_models=fusion_models, - fusion_models_alpha=fusion_models_alpha, - return_xattn_scores=return_xattn_scores, - ) - - self.preserve_alignments = preserve_alignments - if self.preserve_alignments: - logging.info( - "Preservation of alignments was requested but {} does not implement it.".format( - self.__class__.__name__ - ) - ) - - @typecheck() - def forward( - self, - encoder_hidden_states: torch.Tensor, - encoder_input_mask: torch.Tensor, - decoder_input_ids: Optional[torch.Tensor] = None, - partial_hypotheses: Optional[List[Hypothesis]] = None, - ): - """Returns a list of hypotheses given an input batch of the encoder hidden embedding. - Output token is generated auto-repressively. - - Args: - decoder_output: A tensor of size (batch, timesteps, features) or (batch, timesteps) (each timestep is a label). - decoder_lengths: list of int representing the length of each sequence - output sequence. - - Returns: - packed list containing batch number of sentences (Hypotheses). - """ - with torch.inference_mode(): - self.transformer_decoder.eval() - self.log_softmax_module.eval() - - topk_hypotheses, beam_scores, best_hypo, xatt_scores_list = self.beam_search( - encoder_hidden_states=encoder_hidden_states, - encoder_input_mask=encoder_input_mask, - decoder_input_ids=decoder_input_ids, - return_beam_scores=True, - ) - - if not self.return_best_hypothesis: - topk_hypotheses = [x.detach().cpu() for x in topk_hypotheses] # each item is [beam, seq_len] - beam_scores = [x.detach().cpu() for x in beam_scores] # each item is [beam,] - packed_result = [] - for i in range(len(topk_hypotheses)): - hypotheses = [Hypothesis(score=0.0, y_sequence=[], timestamp=[]) for _ in range(self.beam_size)] - # Pack results into Hypotheses - hypotheses = pack_hypotheses(hypotheses, topk_hypotheses[i], beam_scores[i]) - packed_result.append(NBestHypotheses(hypotheses)) - self.format_hypotheses(packed_result, decoder_input_ids) - else: - beam_scores = [None for _ in range(len(best_hypo))] - best_hypo = best_hypo.detach().cpu() - if xatt_scores_list is not None: - xatt_scores_list = [xatt_layer.detach().cpu() for xatt_layer in xatt_scores_list] - hypotheses = [ - Hypothesis(score=0.0, y_sequence=[], timestamp=[]) for _ in range(encoder_hidden_states.shape[0]) - ] - # Pack results into Hypotheses - packed_result = pack_hypotheses(hypotheses, best_hypo, beam_scores, xatt_scores_list) - self.format_hypotheses(packed_result, decoder_input_ids) - - self.transformer_decoder.train() - self.log_softmax_module.train() - - return (packed_result,) - - def format_hypotheses( - self, packed_result: List[Hypothesis | NBestHypotheses], decoder_input_ids: Union[torch.Tensor, None] - ) -> None: - """ - For each hypothesis in the mini-batch: - * Remove the decoder input ids (prompt) from the predictions - * Remove BOS, EOS, and PAD ids from the predictions. - Modifies results in-place. - """ - if decoder_input_ids is not None: - assert ( - len(packed_result) == decoder_input_ids.shape[0] - ), f"Mismatching number of examples {len(packed_result)=} {decoder_input_ids.shape[0]=}" - decoder_input_ids = decoder_input_ids.detach().cpu() - - for h, prefix in zip(packed_result, decoder_input_ids): - hypotheses = h.n_best_hypotheses if isinstance(h, NBestHypotheses) else [h] - for hyp in hypotheses: - assert (hyp.y_sequence[: prefix.shape[0]] == prefix).all(), ( - f"The decoder input IDs were not found at the beginning of prediction: " - f"{hyp.y_sequence=} {prefix=}" - ) - hyp.y_sequence = hyp.y_sequence[prefix.shape[0] :] - - for h in packed_result: - hyps = h.n_best_hypotheses if isinstance(h, NBestHypotheses) else [h] - for hyp in hyps: - ids = hyp.y_sequence - ids_len = ids.shape[0] - pos = -1 - while ids[pos] == self.pad or ids[pos] == self.eos: - pos -= 1 - if ids_len + pos == -1: - break # empty sequence - if pos < -1: - hyp.y_sequence = ids[: pos + 1] - - -@dataclass -class AEDBeamInferConfig: - beam_size: int = 1 - search_type: str = 'default' - len_pen: float = 1.0 - max_generation_delta: int = -1 # -1 means up to the max length of the decoder - return_best_hypothesis: bool = True - preserve_alignments: bool = False - # fusion models params - ngram_lm_model: Optional[str] = None - ngram_lm_alpha: float = 0.0 - boosting_tree: BoostingTreeModelConfig = field(default_factory=lambda: BoostingTreeModelConfig(depth_scaling=1.0)) - boosting_tree_alpha: float = 0.0 diff --git a/nemo/collections/asr/parts/submodules/multitask_decoding.py b/nemo/collections/asr/parts/submodules/multitask_decoding.py deleted file mode 100644 index 1d49a8bbda8ffa53dadd5166a1774d68f3ca43ce..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/multitask_decoding.py +++ /dev/null @@ -1,665 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from abc import abstractmethod -from dataclasses import dataclass, field, is_dataclass -from typing import List, Optional, Union - -import torch -from omegaconf import OmegaConf - -from nemo.collections.asr.parts.submodules.multitask_beam_decoding import ( - AEDBeamInfer, - AEDBeamInferConfig, - TransformerAEDBeamInfer, -) -from nemo.collections.asr.parts.submodules.multitask_greedy_decoding import ( - AEDGreedyInferConfig, - TransformerAEDGreedyInfer, -) -from nemo.collections.asr.parts.utils.asr_confidence_utils import ConfidenceConfig, ConfidenceMixin -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis, NBestHypotheses -from nemo.collections.common.tokenizers.aggregate_tokenizer import AggregateTokenizer -from nemo.collections.common.tokenizers.tokenizer_spec import TokenizerSpec -from nemo.utils import logging - - -class AbstractMultiTaskDecoding(ConfidenceMixin): - """ - Used for performing AED auto-regressive decoding of the Multi task model given the encoder state. - - Args: - decoding_cfg: A dict-like object which contains the following key-value pairs. - strategy: str value which represents the type of decoding that can occur. - Possible values are : - - greedy, greedy_batch (for greedy decoding). - - beam, tsd, alsd (for beam search decoding). - - compute_langs: a bool flag, which allows to compute language id (LID) information per token, - word, and the entire sample (most likely language id). The LIDS will be available - in the returned Hypothesis object as a dictionary - - compute_hypothesis_token_set: A bool flag, which determines whether to compute a list of decoded - tokens as well as the decoded string. Default is False in order to avoid double decoding - unless required. - - preserve_alignments: Bool flag which preserves the history of logprobs generated during - decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `alignments` in it. Here, `alignments` is a List of List of - Tuple(Tensor (of length V + 1), Tensor(scalar, label after argmax)). - - In order to obtain this hypothesis, please utilize `rnnt_decoder_predictions_tensor` function - with the `return_hypotheses` flag set to True. - - confidence_cfg: A dict-like object which contains the following key-value pairs related to confidence scores. - preserve_frame_confidence: Bool flag which preserves the history of per-frame confidence scores - generated during greedy decoding. When set to true, the Hypothesis will contain the non-null value - for `frame_confidence` in it. Here, `frame_confidence` is a List of tensor floats. - - preserve_token_confidence: Bool flag which preserves the history of per-token confidence scores - generated during greedy decoding. When set to true, the Hypothesis will contain the non-null value - for `token_confidence` in it. Here, `token_confidence` is a List of tensor floats. - The length of the list corresponds to the number of recognized tokens. - - preserve_word_confidence: Bool flag which preserves the history of per-word confidence scores - generated during greedy decoding. When set to true, the Hypothesis will contain the non-null value - for `word_confidence` in it. Here, `word_confidence` is a List of tensor floats. - The length of the list corresponds to the number of recognized words. - - aggregation: Which aggregation type to use for collapsing per-token confidence into per-word - confidence. Valid options are `mean`, `min`, `max`, `prod`. - - method_cfg: A dict-like object which contains settings to compute per-frame confidence scores. - name: The method name (str). - Supported values: - - 'max_prob' for using the maximum token probability as a confidence. - - 'entropy' for using a normalized entropy of a log-likelihood vector. - entropy_type: Which type of entropy to use (str). Used if confidence_method_cfg.name is set to `entropy`. - Supported values: - - 'gibbs' for the (standard) Gibbs entropy. If the alpha (α) is provided, - the formula is the following: H_α = -sum_i((p^α_i)*log(p^α_i)). - Note that for this entropy, the alpha should comply the following inequality: - (log(V)+2-sqrt(log^2(V)+4))/(2*log(V)) <= α <= (1+log(V-1))/log(V-1) - where V is the model vocabulary size. - - 'tsallis' for the Tsallis entropy with the Boltzmann constant one. - Tsallis entropy formula is the following: H_α = 1/(α-1)*(1-sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/Tsallis_entropy - - 'renyi' for the Rényi entropy. - Rényi entropy formula is the following: H_α = 1/(1-α)*log_2(sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/R%C3%A9nyi_entropy - alpha: Power scale for logsoftmax (α for entropies). Here we restrict it to be > 0. - When the alpha equals one, scaling is not applied to 'max_prob', - and any entropy type behaves like the Shannon entropy: H = -sum_i(p_i*log(p_i)) - entropy_norm: A mapping of the entropy value to the interval [0,1]. - Supported values: - - 'lin' for using the linear mapping. - - 'exp' for using exponential mapping with linear shift. - - The config may further contain the following sub-dictionaries: - "greedy": - temperature: None (disabled) or float, specifying this enables temperature sampling instead of greedy decoding. - max_generation_delta: int = -1 # -1 means up to the max length of the decoder - preserve_alignments: bool = False (unsupported) - - "beam": - beam_size: int, defining the beam size for beam search. Must be >= 1. - If beam_size == 1, will perform cached greedy search. This might be slightly different - results compared to the greedy search above. - - length_penalty: float, length penalty for beam search decoding. Must be >= 0.0. - - max_generation_delta: int,in case of encoder-decoder generation (e.g. NMT), - forbids generated sequences to be longer than the length of source sequences plus max_generation_delta - - return_best_hypothesis: optional bool, whether to return just the best hypothesis or all of the - hypotheses after beam search has concluded. This flag is set by default. - - - transformer_decoder: Transformer decoder module. - log_softmax_module: Log Softmax projection module to the vocab size. - tokenizer: Aggregate Tokenizer. - """ - - def __init__( - self, - decoding_cfg, - transformer_decoder: torch.nn.Module, - log_softmax_module: torch.nn.Module, - tokenizer: TokenizerSpec, - ): - super().__init__() - - # Convert dataclass to config object - if is_dataclass(decoding_cfg): - decoding_cfg = OmegaConf.structured(decoding_cfg) - - self.cfg = decoding_cfg - - self.preserve_alignments = self.cfg.get('preserve_alignments', None) - self.compute_langs = self.cfg.get('compute_langs', False) - self.compute_hypothesis_token_set = self.cfg.get('compute_hypothesis_token_set', False) - self.transformer_decoder = transformer_decoder - self.log_softmax_module = log_softmax_module - self.tokenizer = tokenizer - - # initialize confidence-related fields - self._init_confidence(self.cfg.get('confidence_cfg', None)) - - self.change_strategy(self.cfg.strategy) - - def change_strategy(self, strategy: str) -> "AbstractMultiTaskDecoding": - possible_strategies = ['greedy', 'greedy_batch', 'beam'] - if strategy not in possible_strategies: - raise ValueError(f"Decoding strategy must be one of {possible_strategies}" f"but was provided {strategy}") - - # Update preserve alignments - if self.preserve_alignments is None: - if strategy in ['greedy', 'greedy_batch']: - self.preserve_alignments = self.cfg.greedy.get('preserve_alignments', False) - - elif strategy in ['beam']: - self.preserve_alignments = self.cfg.beam.get('preserve_alignments', False) - - if strategy in ['greedy', 'greedy_batch']: - if self.cfg.greedy.get('ngram_lm_model') is not None: - raise ValueError( - "Greedy strategy cannot be used with ngram_lm_model. Use beam strategy with beam=1 instead." - ) - self.decoding = TransformerAEDGreedyInfer( - transformer_decoder=self.transformer_decoder, - log_softmax_module=self.log_softmax_module, - tokenizer=self.tokenizer, - max_generation_delta=self.cfg.greedy.get('max_generation_delta', -1), - preserve_alignments=self.preserve_alignments, - preserve_token_confidence=self.preserve_token_confidence or self.preserve_frame_confidence, - confidence_method_cfg=self.confidence_method_cfg, - temperature=self.cfg.greedy.temperature, - n_samples=self.cfg.greedy.n_samples, - return_xattn_scores=self.cfg.get('return_xattn_scores', False), - ) - - elif strategy == 'beam': - - self.decoding = TransformerAEDBeamInfer( - transformer_decoder=self.transformer_decoder, - log_softmax_module=self.log_softmax_module, - tokenizer=self.tokenizer, - search_type=self.cfg.beam.get('search_type', 'default'), - beam_size=self.cfg.beam.beam_size, - length_penalty=self.cfg.beam.get('length_penalty', 0.0), - max_generation_delta=self.cfg.beam.get('max_generation_delta', -1), - return_best_hypothesis=self.cfg.beam.get('return_best_hypothesis', True), - preserve_alignments=self.preserve_alignments, - ngram_lm_model=self.cfg.beam.get('ngram_lm_model', None), - ngram_lm_alpha=self.cfg.beam.get('ngram_lm_alpha', 0.0), - boosting_tree=self.cfg.beam.get('boosting_tree', None), - boosting_tree_alpha=self.cfg.beam.get('boosting_tree_alpha', 0.0), - return_xattn_scores=self.cfg.get('return_xattn_scores', False), - ) - - else: - - raise ValueError( - f"Incorrect decoding strategy provided. Must be one of {possible_strategies}\n" - f"but was provided {strategy}" - ) - - def decode_predictions_tensor( - self, - encoder_hidden_states: torch.Tensor, - encoder_input_mask: torch.Tensor, - decoder_input_ids: Optional[torch.Tensor] = None, - return_hypotheses: bool = False, - partial_hypotheses: Optional[List[Hypothesis]] = None, - ) -> Union[List[Hypothesis], List[List[Hypothesis]]]: - """ - Decode an encoder output by autoregressive decoding of the Decoder+Joint networks. - - Args: - encoder_output: torch.Tensor of shape [B, D, T]. - encoded_lengths: torch.Tensor containing lengths of the padded encoder outputs. Shape [B]. - return_hypotheses: bool. If set to True it will return list of Hypothesis or NBestHypotheses - - Returns: - If `return_all_hypothesis` is set: - A list[list[Hypothesis]]. - Look at rnnt_utils.Hypothesis for more information. - - If `return_all_hypothesis` is not set: - A list[Hypothesis]. - List of best hypotheses - Look at rnnt_utils.Hypothesis for more information. - """ - # Compute hypotheses - with torch.inference_mode(): - hypotheses_list = self.decoding( - encoder_hidden_states=encoder_hidden_states, - encoder_input_mask=encoder_input_mask, - decoder_input_ids=decoder_input_ids, - partial_hypotheses=partial_hypotheses, - ) # type: [List[Hypothesis]] - - # extract the hypotheses - hypotheses_list = hypotheses_list[0] # type: List[Hypothesis] - - prediction_list = hypotheses_list - - if isinstance(prediction_list[0], NBestHypotheses): - hypotheses = [] - all_hypotheses = [] - - for nbest_hyp in prediction_list: # type: NBestHypotheses - n_hyps = nbest_hyp.n_best_hypotheses # Extract all hypotheses for this sample - decoded_hyps = self.decode_hypothesis(n_hyps) - - hypotheses.append(decoded_hyps[0]) # best hypothesis - all_hypotheses.append(decoded_hyps) - - if return_hypotheses: - return all_hypotheses - - all_hyp = [[Hypothesis(h.score, h.y_sequence, h.text) for h in hh] for hh in all_hypotheses] - return all_hyp - - else: - hypotheses = self.decode_hypothesis(prediction_list) - - if return_hypotheses: - # greedy decoding, can get high-level confidence scores - if self.preserve_frame_confidence and ( - self.preserve_word_confidence or self.preserve_token_confidence - ): - hypotheses = self.compute_confidence(hypotheses) - return hypotheses - - return [Hypothesis(h.score, h.y_sequence, h.text) for h in hypotheses] - - def decode_hypothesis(self, hypotheses_list: List[Hypothesis]) -> List[Union[Hypothesis, NBestHypotheses]]: - """ - Decode a list of hypotheses into a list of strings. - - Args: - hypotheses_list: List of Hypothesis. - - Returns: - A list of strings. - """ - for ind in range(len(hypotheses_list)): - # Extract the integer encoded hypothesis - prediction = hypotheses_list[ind].y_sequence - - if type(prediction) != list: - prediction = prediction.tolist() - - hypothesis = self.decode_ids_to_str(prediction) - - if self.compute_hypothesis_token_set: - hypotheses_list[ind].tokens = self.decode_ids_to_tokens(prediction) - - # De-tokenize the integer tokens - hypotheses_list[ind].text = hypothesis - - return hypotheses_list - - def compute_confidence(self, hypotheses_list: List[Hypothesis]) -> List[Hypothesis]: - """ - Compute high-level (per-token and/or per-word) confidence scores for a list of hypotheses. - Assumes that `token_confidence` is present in the hypotheses. - - Args: - hypotheses_list: List of Hypothesis. - - Returns: - A list of hypotheses with high-level confidence scores. - """ - if self.preserve_word_confidence: - for hyp in hypotheses_list: - hyp.word_confidence = self._aggregate_token_confidence(hyp) - return hypotheses_list - - def _aggregate_token_confidence(self, hypothesis: Hypothesis) -> List[float]: - """ - Implemented by subclass in order to reduce token confidence to a word-level confidence. - - **Note**: Only supports Sentencepiece based tokenizers! - - Args: - hypothesis: Hypothesis - - Returns: - A list of word-level confidence scores. - """ - return self._aggregate_token_confidence_subwords_sentencepiece( - hypothesis.words, hypothesis.token_confidence, hypothesis.y_sequence - ) - - @abstractmethod - def decode_tokens_to_str(self, tokens: List[int]) -> str: - """ - Implemented by subclass in order to decoder a token id list into a string. - - Args: - tokens: List of int representing the token ids. - - Returns: - A decoded string. - """ - raise NotImplementedError() - - @abstractmethod - def decode_ids_to_tokens(self, tokens: List[int]) -> List[str]: - """ - Implemented by subclass in order to decode a token id list into a token list. - A token list is the string representation of each token id. - - Args: - tokens: List of int representing the token ids. - - Returns: - A list of decoded tokens. - """ - raise NotImplementedError() - - @abstractmethod - def decode_tokens_to_lang(self, tokens: List[int]) -> str: - """ - Implemented by subclass in order to - compute the most likely language ID (LID) string given the tokens. - - Args: - tokens: List of int representing the token ids. - - Returns: - A decoded LID string. - """ - raise NotImplementedError() - - @abstractmethod - def decode_ids_to_langs(self, tokens: List[int]) -> List[str]: - """ - Implemented by subclass in order to - decode a token id list into language ID (LID) list. - - Args: - tokens: List of int representing the token ids. - - Returns: - A list of decoded LIDS. - """ - raise NotImplementedError() - - -class MultiTaskDecoding(AbstractMultiTaskDecoding): - """ - Used for performing AED auto-regressive decoding of the Multi task model given the encoder state. - - Args: - decoding_cfg: A dict-like object which contains the following key-value pairs. - strategy: str value which represents the type of decoding that can occur. - Possible values are : - - greedy, greedy_batch (for greedy decoding). - - beam, tsd, alsd (for beam search decoding). - - compute_langs: a bool flag, which allows to compute language id (LID) information per token, - word, and the entire sample (most likely language id). The LIDS will be available - in the returned Hypothesis object as a dictionary - - compute_hypothesis_token_set: A bool flag, which determines whether to compute a list of decoded - tokens as well as the decoded string. Default is False in order to avoid double decoding - unless required. - - preserve_alignments: Bool flag which preserves the history of logprobs generated during - decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `alignments` in it. Here, `alignments` is a List of List of - Tuple(Tensor (of length V + 1), Tensor(scalar, label after argmax)). - - In order to obtain this hypothesis, please utilize `rnnt_decoder_predictions_tensor` function - with the `return_hypotheses` flag set to True. - - confidence_cfg: A dict-like object which contains the following key-value pairs related to confidence scores. - preserve_frame_confidence: Bool flag which preserves the history of per-frame confidence scores - generated during greedy decoding. When set to true, the Hypothesis will contain the non-null value - for `frame_confidence` in it. Here, `frame_confidence` is a List of tensor floats. - - preserve_token_confidence: Bool flag which preserves the history of per-token confidence scores - generated during greedy decoding. When set to true, the Hypothesis will contain the non-null value - for `token_confidence` in it. Here, `token_confidence` is a List of tensor floats. - The length of the list corresponds to the number of recognized tokens. - - preserve_word_confidence: Bool flag which preserves the history of per-word confidence scores - generated during greedy decoding. When set to true, the Hypothesis will contain the non-null value - for `word_confidence` in it. Here, `word_confidence` is a List of tensor floats. - The length of the list corresponds to the number of recognized words. - - aggregation: Which aggregation type to use for collapsing per-token confidence into per-word - confidence. Valid options are `mean`, `min`, `max`, `prod`. - - method_cfg: A dict-like object which contains settings to compute per-frame confidence scores. - name: The method name (str). - Supported values: - - 'max_prob' for using the maximum token probability as a confidence. - - 'entropy' for using a normalized entropy of a log-likelihood vector. - entropy_type: Which type of entropy to use (str). Used if confidence_method_cfg.name is set to `entropy`. - Supported values: - - 'gibbs' for the (standard) Gibbs entropy. If the alpha (α) is provided, - the formula is the following: H_α = -sum_i((p^α_i)*log(p^α_i)). - Note that for this entropy, the alpha should comply the following inequality: - (log(V)+2-sqrt(log^2(V)+4))/(2*log(V)) <= α <= (1+log(V-1))/log(V-1) - where V is the model vocabulary size. - - 'tsallis' for the Tsallis entropy with the Boltzmann constant one. - Tsallis entropy formula is the following: H_α = 1/(α-1)*(1-sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/Tsallis_entropy - - 'renyi' for the Rényi entropy. - Rényi entropy formula is the following: H_α = 1/(1-α)*log_2(sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/R%C3%A9nyi_entropy - alpha: Power scale for logsoftmax (α for entropies). Here we restrict it to be > 0. - When the alpha equals one, scaling is not applied to 'max_prob', - and any entropy type behaves like the Shannon entropy: H = -sum_i(p_i*log(p_i)) - entropy_norm: A mapping of the entropy value to the interval [0,1]. - Supported values: - - 'lin' for using the linear mapping. - - 'exp' for using exponential mapping with linear shift. - - The config may further contain the following sub-dictionaries: - "greedy": - temperature: None (disabled) or float, specifying this enables temperature sampling instead of greedy decoding. - - max_generation_delta: int = -1 # -1 means up to the max length of the decoder - - preserve_alignments: bool = False (unsupported) - - "beam": - beam_size: int, defining the beam size for beam search. Must be >= 1. - If beam_size == 1, will perform cached greedy search. This might be slightly different - results compared to the greedy search above. - - length_penalty: float, length penalty for beam search decoding. Must be >= 0.0. - - max_generation_delta: int, maximum number of additional target tokens to generate - - return_best_hypothesis: optional bool, whether to return just the best hypothesis or all of the - hypotheses after beam search has concluded. This flag is set by default. - - - transformer_decoder: Transformer decoder module. - log_softmax_module: Log Softmax projection module to the vocab size. - tokenizer: TokenizerSpec. - """ - - def __init__( - self, - decoding_cfg, - transformer_decoder: torch.nn.Module, - log_softmax_module: torch.nn.Module, - tokenizer: TokenizerSpec, - ): - self.tokenizer = tokenizer - - super().__init__( - decoding_cfg=decoding_cfg, - transformer_decoder=transformer_decoder, - log_softmax_module=log_softmax_module, - tokenizer=tokenizer, - ) - - if isinstance(self.decoding, AEDBeamInfer): - self.decoding.set_decoding_type('subword') - - def decode_tokens_to_str(self, tokens: List[str], lang: Optional[str] = None) -> str: - """ - Implemented by subclass in order to decoder a token str into a string. - - Args: - tokens: List of str representing the tokens. - - Returns: - A decoded string. - """ - if lang is not None: - hypothesis = self.tokenizer.tokens_to_text(tokens, lang) - else: - hypothesis = self.tokenizer.tokens_to_text(tokens) - return hypothesis - - def decode_ids_to_str(self, tokens: List[int]) -> str: - """ - Implemented by subclass in order to decoder a token list into a string. - - Args: - tokens: List of int representing the token ids. - - Returns: - A decoded string. - """ - hypothesis = self.tokenizer.ids_to_text(tokens) - return hypothesis - - def decode_ids_to_tokens(self, tokens: List[int]) -> List[str]: - """ - Implemented by subclass in order to decode a token id list into a token list. - A token list is the string representation of each token id. - - Args: - tokens: List of int representing the token ids. - - Returns: - A list of decoded tokens. - """ - token_list = self.tokenizer.ids_to_tokens(tokens) - return token_list - - def decode_tokens_to_lang(self, tokens: List[int]) -> str: - """ - Compute the most likely language ID (LID) string given the tokens. - - Args: - tokens: List of int representing the token ids. - - Returns: - A decoded LID string. - """ - lang = self.tokenizer.ids_to_lang(tokens) - return lang - - def decode_ids_to_langs(self, tokens: List[int]) -> List[str]: - """ - Decode a token id list into language ID (LID) list. - - Args: - tokens: List of int representing the token ids. - - Returns: - A list of decoded LIDS. - """ - lang_list = self.tokenizer.ids_to_text_and_langs(tokens) - return lang_list - - def decode_hypothesis(self, hypotheses_list: List[Hypothesis]) -> List[Union[Hypothesis, NBestHypotheses]]: - """ - Decode a list of hypotheses into a list of strings. - Overrides the super() method optionally adding lang information - - Args: - hypotheses_list: List of Hypothesis. - - Returns: - A list of strings. - """ - hypotheses = super().decode_hypothesis(hypotheses_list) - if self.compute_langs: - if isinstance(self.tokenizer, AggregateTokenizer): - for ind in range(len(hypotheses_list)): - # Extract the integer encoded hypothesis - prediction = hypotheses_list[ind].y_sequence - - if type(prediction) != list: - prediction = prediction.tolist() - - hypotheses[ind].langs = self.decode_tokens_to_lang(prediction) - hypotheses[ind].langs_chars = self.decode_ids_to_langs(prediction) - else: - logging.warning( - "Ignoring request for lang output in hypotheses since the model does not use an aggregate tokenizer" - ) - - return hypotheses - - -@dataclass -class AEDStreamingDecodingConfig: - streaming_policy: str = "waitk" # "waitk" or "alignatt" - alignatt_thr: float = 8 # frames threshold for alignatt - waitk_lagging: int = 2 # number of chunks to wait in the beginning (works for waitk and alignatt) - exclude_sink_frames: int = ( - 8 # number of frames to exclude from the xatt scores calculation (token can attend to first frames in the audio signal) - ) - xatt_scores_layer: int = -2 # layer to get cross-attention (xatt) scores from - max_tokens_per_alignatt_step: int = ( - 30 # maximum number of tokens to be generated for each step of alignatt decoding policy (before the last speech chunk) - ) - max_generation_length: int = 512 # maximum number of tokens to be generated for each sample - use_avgpool_for_alignatt: bool = False # use avgpool for alignatt to smooth peaky xatt scores - hallucinations_detector: bool = True # detect hallucinations in the predicted tokens - - -@dataclass -class MultiTaskDecodingConfig: - strategy: str = "beam" - - compute_hypothesis_token_set: bool = False - - # preserve decoding alignments - preserve_alignments: Optional[bool] = None - - # confidence config - confidence_cfg: ConfidenceConfig = field(default_factory=lambda: ConfidenceConfig()) - - # compute language IDs - compute_langs: bool = False - - # greedy decoding config - greedy: AEDGreedyInferConfig = field(default_factory=AEDGreedyInferConfig) - - # beam decoding config - beam: AEDBeamInferConfig = field(default_factory=lambda: AEDBeamInferConfig(beam_size=1)) - - # can be used to change temperature for decoding - temperature: float = 1.0 - - # if set to true, return attention scores; ignore them to save memory otherwise - return_xattn_scores: bool = False diff --git a/nemo/collections/asr/parts/submodules/multitask_greedy_decoding.py b/nemo/collections/asr/parts/submodules/multitask_greedy_decoding.py deleted file mode 100644 index 71dd97265ce7b751067e45263f7d794451e82289..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/multitask_greedy_decoding.py +++ /dev/null @@ -1,296 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from abc import ABC, abstractmethod -from dataclasses import dataclass, field -from typing import List, Optional, Union - -import torch -from omegaconf import DictConfig, OmegaConf - -from nemo.collections.asr.modules.transformer import GreedySequenceGenerator -from nemo.collections.asr.parts.utils.asr_confidence_utils import ConfidenceMethodConfig -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis, NBestHypotheses -from nemo.collections.common.tokenizers.tokenizer_spec import TokenizerSpec -from nemo.core import Typing, typecheck -from nemo.core.neural_types import ChannelType, HypothesisType, LabelsType, MaskType, NeuralType -from nemo.utils import logging - - -def pack_hypotheses( - hypotheses: List[Hypothesis], - beam_hypotheses: torch.Tensor, - scores: List[Optional[float]], - step_confidence: Optional[torch.Tensor] = None, - xatt_scores: Optional[List[torch.Tensor]] = None, -) -> List[Hypothesis]: - - for idx, hyp in enumerate(hypotheses): # type: Hypothesis - if scores[idx] is not None: - hyp.score = scores[idx] - - if step_confidence is not None: - hyp.frame_confidence = step_confidence[idx] - hyp.token_confidence = hyp.frame_confidence - - hypi = beam_hypotheses[idx] - if torch.is_tensor(hypi): - hyp.y_sequence = hypi.long() - else: - hyp.y_sequence = torch.tensor(hypi, dtype=torch.long) - - if hyp.dec_state is not None: - hyp.dec_state = _states_to_device(hyp.dec_state) - - if xatt_scores is not None: - hyp.xatt_scores = [xatt_layer[idx] for xatt_layer in xatt_scores] - - return hypotheses - - -def _states_to_device(dec_state, device='cpu'): - if torch.is_tensor(dec_state): - dec_state = dec_state.to(device) - - elif isinstance(dec_state, (list, tuple)): - dec_state = tuple(_states_to_device(dec_i, device) for dec_i in dec_state) - - return dec_state - - -class AEDGreedyInfer(ABC): - def __init__( - self, - transformer_decoder: torch.nn.Module, - log_softmax_module: torch.nn.Module, - tokenizer: TokenizerSpec, - search_type: str = 'default', - preserve_alignments: bool = False, - ): - super().__init__() - - self.transformer_decoder = transformer_decoder - self.log_softmax_module = log_softmax_module - self.tokenizer = tokenizer - self.search_type = search_type - - self.preserve_alignments = preserve_alignments - - def __call__(self, *args, **kwargs): - return self.forward(*args, **kwargs) - - @abstractmethod - def forward( - self, - encoder_hidden_states: torch.Tensor, - encoder_input_mask: torch.Tensor, - decoder_input_ids: Optional[torch.Tensor] = None, - partial_hypotheses: Optional[List[Hypothesis]] = None, - ): - raise NotImplementedError() - - def set_decoding_type(self, decoding_type: str): - self.decoding_type = decoding_type - - -class TransformerAEDGreedyInfer(AEDGreedyInfer, Typing): - """ - A greedy decoder engine for AED Transformer models with support for temperature sampling. - """ - - @property - def input_types(self): - """Returns definitions of module input ports.""" - # Input can be of dimention - - # ('B', 'T', 'D') [Log probs] or ('B', 'T') [Labels] - - return { - "encoder_hidden_states": NeuralType(tuple(('B', 'T', 'D')), ChannelType()), - "encoder_input_mask": NeuralType(tuple(('B', 'T')), MaskType()), - "decoder_input_ids": NeuralType(('B', 'T'), LabelsType()), - "partial_hypotheses": NeuralType(optional=True), - } - - @property - def output_types(self): - """Returns definitions of module output ports.""" - return {"predictions": [NeuralType(elements_type=HypothesisType())]} - - def __init__( - self, - transformer_decoder: torch.nn.Module, - log_softmax_module: torch.nn.Module, - tokenizer: TokenizerSpec, - temperature: float | None = None, - max_generation_delta: int = 50, - preserve_alignments: bool = False, - preserve_token_confidence: bool = False, - confidence_method_cfg: Optional[DictConfig] = None, - n_samples: int = 1, - return_xattn_scores: bool = False, - ): - super().__init__( - transformer_decoder=transformer_decoder, - log_softmax_module=log_softmax_module, - tokenizer=tokenizer, - preserve_alignments=preserve_alignments, - ) - self.temperature = temperature - self.n_samples = n_samples - self.bos = tokenizer.bos - self.pad = tokenizer.pad - self.eos = tokenizer.eos - self.greedy_search = GreedySequenceGenerator( - embedding=transformer_decoder.embedding, - decoder=transformer_decoder.decoder, - classifier=log_softmax_module, - max_sequence_length=transformer_decoder.max_sequence_length, - bos=self.bos, - pad=self.pad, - eos=self.eos, - max_delta_length=max_generation_delta, - temperature=self.temperature, - n_samples=n_samples, - preserve_step_confidence=preserve_token_confidence, - confidence_method_cfg=confidence_method_cfg, - return_xattn_scores=return_xattn_scores, - ) - - self.preserve_alignments = preserve_alignments - if self.preserve_alignments: - logging.info( - "Preservation of alignments was requested but {} does not implement it.".format( - self.__class__.__name__ - ) - ) - - @typecheck() - def forward( - self, - encoder_hidden_states: torch.Tensor, - encoder_input_mask: torch.Tensor, - decoder_input_ids: Optional[torch.Tensor] = None, - partial_hypotheses: Optional[List[Hypothesis]] = None, - ): - """Returns a list of hypotheses given an input batch of the encoder hidden embedding. - Output token is generated auto-repressively. - - Args: - decoder_output: A tensor of size (batch, timesteps, features) or (batch, timesteps) (each timestep is a label). - decoder_lengths: list of int representing the length of each sequence - output sequence. - - Returns: - packed list containing batch number of sentences (Hypotheses). - """ - with torch.inference_mode(): - self.transformer_decoder.eval() - self.log_softmax_module.eval() - - best_hypo, topk_hypotheses, step_confidence, xatt_scores_list = self.greedy_search( - encoder_hidden_states=encoder_hidden_states, - encoder_input_mask=encoder_input_mask, - decoder_input_ids=decoder_input_ids, - ) - - if topk_hypotheses is not None: - topk_hypotheses = [x.detach().cpu() for x in topk_hypotheses] # each item is [beam, seq_len] - beam_scores = [[None] * self.n_samples for _ in topk_hypotheses] # each item is [beam,] - packed_result = [] - if xatt_scores_list is not None: - xatt_scores_list = [ - xatt_layer.view(len(topk_hypotheses), -1, *xatt_layer.shape[1:]).detach().cpu() - for xatt_layer in xatt_scores_list - ] - for i in range(len(topk_hypotheses)): - # Pack results into Hypotheses - hypotheses = [Hypothesis(score=0.0, y_sequence=[], timestamp=[]) for _ in range(self.n_samples)] - self.format_hypotheses(hypotheses, decoder_input_ids) - topk_xatt_scores = None - if xatt_scores_list is not None: - topk_xatt_scores = [xatt_layer[i] for xatt_layer in xatt_scores_list] - packed_result.append( - NBestHypotheses( - pack_hypotheses( - hypotheses, topk_hypotheses[i], beam_scores[i], step_confidence, topk_xatt_scores - ) - ) - ) - else: - beam_scores = [None for _ in range(len(best_hypo))] - best_hypo = best_hypo.cpu() - if xatt_scores_list is not None: - xatt_scores_list = [xatt_scores_layer.detach().cpu() for xatt_scores_layer in xatt_scores_list] - hypotheses = [ - Hypothesis(score=0.0, y_sequence=[], timestamp=[]) for _ in range(encoder_hidden_states.shape[0]) - ] - # Pack results into Hypotheses - packed_result = pack_hypotheses(hypotheses, best_hypo, beam_scores, step_confidence, xatt_scores_list) - self.format_hypotheses(packed_result, decoder_input_ids) - - self.transformer_decoder.train() - self.log_softmax_module.train() - return (packed_result,) - - def format_hypotheses(self, packed_result: List[Hypothesis], decoder_input_ids: Union[torch.Tensor, None]) -> None: - """ - For each hypothesis in the mini-batch: - * Remove the decoder input ids (prompt) from the predictions - * Remove BOS, EOS, and PAD ids from the predictions. - Modifies results in-place. - """ - if decoder_input_ids is not None: - assert ( - len(packed_result) == decoder_input_ids.shape[0] - ), f"Mismatching number of examples {len(packed_result)=} {decoder_input_ids.shape[0]=}" - decoder_input_ids = decoder_input_ids.detach().cpu() - for hyp, prefix in zip(packed_result, decoder_input_ids): - assert ( - hyp.y_sequence[: prefix.shape[0]] == prefix - ).all(), f"The decoder input IDs were not found at the beginning of prediction: {hyp.y_sequence=} {prefix=})" - hyp.y_sequence = hyp.y_sequence[prefix.shape[0] :] - hyp.token_confidence = ( - hyp.token_confidence[prefix.shape[0] :] if hyp.token_confidence is not None else None - ) - for hyp in packed_result: - ids = hyp.y_sequence - ids_len = ids.shape[0] - pos = -1 - while ids[pos] == self.pad or ids[pos] == self.eos: - pos -= 1 - if ids_len + pos == -1: - break # empty sequence - if pos < -1: - hyp.y_sequence = ids[: pos + 1] - hyp.token_confidence = hyp.token_confidence[: pos + 1] if hyp.token_confidence is not None else None - if hyp.xatt_scores is not None: - hyp.xatt_scores = [xatt_layer[:, : pos + 1, :] for xatt_layer in hyp.xatt_scores] - - -@dataclass -class AEDGreedyInferConfig: - temperature: float | None = None - max_generation_delta: int = -1 # -1 means up to the max length of the decoder - preserve_alignments: bool = False - preserve_token_confidence: bool = False - confidence_method_cfg: Optional[ConfidenceMethodConfig] = field(default_factory=lambda: ConfidenceMethodConfig()) - n_samples: int = 1 - - def __post_init__(self): - # OmegaConf.structured ensures that post_init check is always executed - self.confidence_method_cfg = OmegaConf.structured( - self.confidence_method_cfg - if isinstance(self.confidence_method_cfg, ConfidenceMethodConfig) - else ConfidenceMethodConfig(**self.confidence_method_cfg) - ) diff --git a/nemo/collections/asr/parts/submodules/ngram_lm/__init__.py b/nemo/collections/asr/parts/submodules/ngram_lm/__init__.py deleted file mode 100644 index f0657d8aadaa0dc540cc5d15c0119c54439a29fa..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/ngram_lm/__init__.py +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from nemo.collections.asr.parts.submodules.ngram_lm.constants import DEFAULT_TOKEN_OFFSET -from nemo.collections.asr.parts.submodules.ngram_lm.ngram_lm_batched import KenLMBatchedWrapper, NGramGPULanguageModel - -__all__ = ["DEFAULT_TOKEN_OFFSET", "NGramGPULanguageModel", "KenLMBatchedWrapper"] diff --git a/nemo/collections/asr/parts/submodules/ngram_lm/constants.py b/nemo/collections/asr/parts/submodules/ngram_lm/constants.py deleted file mode 100644 index 1b7c5d86efdb1e2848ecc869f2e45cdd45390b4e..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/ngram_lm/constants.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -DEFAULT_TOKEN_OFFSET = 100 # Default token offset for building ARPA LM diff --git a/nemo/collections/asr/parts/submodules/ngram_lm/kenlm_utils.py b/nemo/collections/asr/parts/submodules/ngram_lm/kenlm_utils.py deleted file mode 100644 index a38a6ab8d5069c58e4b94af75b316a7332de8ce5..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/ngram_lm/kenlm_utils.py +++ /dev/null @@ -1,245 +0,0 @@ -# Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -""" -Utility methods to be used for training N-gram LM with KenLM in train_kenlm.py - -The BPE sub-words are encoded using the Unicode table. -This encoding scheme reduces the required memory significantly, and the LM and its binary blob format require less storage space. -The value DEFAULT_TOKEN_OFFSET from nemo.collections.asr.parts.submodules.ctc_beam_decoding is utilized as the offset value. -""" - -CHUNK_SIZE = 8192 -CHUNK_BUFFER_SIZE = 512 - -import gzip -import json -import os - -import numpy as np -import torch -from joblib import Parallel, delayed -from tqdm.auto import tqdm - -import nemo.collections.asr as nemo_asr -from nemo.collections.asr.parts.submodules.ngram_lm.constants import DEFAULT_TOKEN_OFFSET -from nemo.collections.common.tokenizers import AggregateTokenizer -from nemo.utils import logging - -# List of the supported models to be used with N-gram LM and beam search decoding -SUPPORTED_MODELS = { - 'EncDecCTCModelBPE': 'subword', - 'EncDecCTCModel': 'char', - 'EncDecRNNTBPEModel': 'subword', - 'EncDecRNNTModel': 'char', - 'EncDecHybridRNNTCTCBPEModel': 'subword', - 'EncDecHybridRNNTCTCModel': 'char', - 'EncDecMultiTaskModel': 'subword', -} - - -def softmax(x): - e = np.exp(x - np.max(x)) - return e / e.sum(axis=-1).reshape([x.shape[0], 1]) - - -def get_train_list(args_train_path): - - train_path = [] - for train_item in args_train_path: - if os.path.isdir(train_item): - file_list = os.listdir(train_item) - train_path.extend([os.path.join(train_item, file) for file in file_list]) - - elif os.path.isfile(train_item): - train_path.append(train_item) - return sorted(train_path) - - -def setup_tokenizer(nemo_model_file): - """TOKENIZER SETUP - nemo_model_file (str): The path to the NeMo model file (.nemo). - """ - logging.info(f"Loading nemo model '{nemo_model_file}' ...") - if nemo_model_file.endswith('.nemo'): - model = nemo_asr.models.ASRModel.restore_from(nemo_model_file, map_location=torch.device('cpu')) - else: - logging.warning( - "tokenizer_model_file does not end with .model or .nemo, therefore trying to load a pretrained model with this name." - ) - model = nemo_asr.models.ASRModel.from_pretrained(nemo_model_file, map_location=torch.device('cpu')) - - is_aggregate_tokenizer = False - tokenizer_nemo = None - full_vocab_size = None - encoding_level = SUPPORTED_MODELS.get(type(model).__name__, None) - if not encoding_level: - logging.warning( - f"Model type '{type(model).__name__}' may not be supported. Would try to train a char-level LM." - ) - encoding_level = 'char' - - if encoding_level == 'subword': - is_aggregate_tokenizer = isinstance(model.tokenizer, AggregateTokenizer) - tokenizer_nemo = model.tokenizer - - full_vocab_size = tokenizer_nemo.vocab_size - - # sanity check for LM (blank_id == vocab_size) - if isinstance(model, nemo_asr.models.EncDecCTCModelBPE): - assert full_vocab_size == model.decoding.decoding.blank_id - elif isinstance(model, nemo_asr.models.EncDecRNNTBPEModel): - assert full_vocab_size == model.decoding.decoding._blank_index - elif isinstance(model, nemo_asr.models.EncDecHybridRNNTCTCBPEModel): - try: - # rnnt head - assert full_vocab_size == model.decoding.decoding._blank_index - except AttributeError: - # ctc head - assert full_vocab_size == model.decoding.decoding.blank_id - elif isinstance(model, nemo_asr.models.EncDecMultiTaskModel): - assert full_vocab_size == model.decoding.decoding.beam_search.num_tokens - else: - logging.warning(f"Unknown type of model {type(model).__name__}") - - del model - - return tokenizer_nemo, encoding_level, is_aggregate_tokenizer, full_vocab_size - - -def iter_files(source_path, dest_path, tokenizer, encoding_level, is_aggregate_tokenizer, verbose): - if isinstance(dest_path, list): - paths = zip(dest_path, source_path) - else: # dest_path is stdin of KenLM - paths = [(dest_path, path) for path in source_path] - - for dest_path, input_path in paths: - dataset = read_train_file(input_path, is_aggregate_tokenizer=is_aggregate_tokenizer, verbose=verbose) - if encoding_level == "subword": - tokenize_text( - data=dataset, - tokenizer=tokenizer, - path=dest_path, - chunk_size=CHUNK_SIZE, - buffer_size=CHUNK_BUFFER_SIZE, - ) - else: # encoding_level == "char" - if isinstance(dest_path, str): - with open(dest_path, 'w', encoding='utf-8') as f: - for line in dataset: - f.write(line[0] + "\n") - else: # write to stdin of KenLM - for line in dataset: - dest_path.write((line[0] + '\n').encode()) - - -def read_train_file( - path, - is_aggregate_tokenizer: bool = False, - verbose: int = 0, -): - lines_read = 0 - text_dataset, lang_dataset = [], [] - if path[-8:] == '.json.gz': # for Common Crawl dataset - fin = gzip.open(path, 'r') - else: - fin = open(path, 'r', encoding='utf-8') - - if verbose > 0: - reader = tqdm(iter(lambda: fin.readline(), ''), desc="Read 0 lines", unit=' lines') - else: - reader = fin - - for line in reader: - lang = None - if line: - if path[-8:] == '.json.gz': # for Common Crawl dataset - line = json.loads(line.decode('utf-8'))['text'] - elif path.endswith('.json') or path.endswith(".jsonl"): - jline = json.loads(line) - line = jline['text'] - if is_aggregate_tokenizer: - lang = jline['lang'] - - line_list = line.split("\n") - - line = " ".join(line_list) - if line: - text_dataset.append(line) - if lang: - lang_dataset.append(lang) - lines_read += 1 - if verbose > 0 and lines_read % 100000 == 0: - reader.set_description(f"Read {lines_read} lines") - else: - break - fin.close() - if is_aggregate_tokenizer: - assert len(text_dataset) == len( - lang_dataset - ), f"text_dataset length {len(text_dataset)} and lang_dataset length {len(lang_dataset)} must be the same!" - return list(zip(text_dataset, lang_dataset)) - else: - return [[text] for text in text_dataset] - - -def tokenize_str(texts, tokenizer): - tokenized_text = [] - for text in texts: - tok_text = tokenizer.text_to_ids(*text) - tok_text = [chr(token + DEFAULT_TOKEN_OFFSET) for token in tok_text] - tokenized_text.append(tok_text) - return tokenized_text - - -def tokenize_text(data, tokenizer, path, chunk_size=8192, buffer_size=32): - dataset_len = len(data) - current_step = 0 - if isinstance(path, str) and os.path.exists(path): - os.remove(path) - - with Parallel(n_jobs=-2, verbose=0) as parallel: - while True: - start = current_step * chunk_size - end = min((current_step + buffer_size) * chunk_size, dataset_len) - - tokenized_data = parallel( - delayed(tokenize_str)(data[start : start + chunk_size], tokenizer) - for start in range(start, end, chunk_size) - ) - - # Write dataset - write_dataset(tokenized_data, path) - current_step += len(tokenized_data) - logging.info( - f"Finished writing {len(tokenized_data)} chunks to {path}. Current chunk index = {current_step}" - ) - del tokenized_data - if end >= dataset_len: - break - - -def write_dataset(chunks, path): - if isinstance(path, str): - with open(path, 'a+', encoding='utf-8') as f: - for chunk_idx in tqdm(range(len(chunks)), desc='Chunk ', total=len(chunks), unit=' chunks'): - for text in chunks[chunk_idx]: - line = ' '.join(text) - f.write(f"{line}\n") - else: # write to stdin of KenLM - for chunk_idx in range(len(chunks)): - for text in chunks[chunk_idx]: - line = ' '.join(text) - path.write((line + '\n').encode()) diff --git a/nemo/collections/asr/parts/submodules/ngram_lm/ngram_lm_batched.py b/nemo/collections/asr/parts/submodules/ngram_lm/ngram_lm_batched.py deleted file mode 100644 index b5335d2ed3a47791cedcb300687f20554804ce0c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/ngram_lm/ngram_lm_batched.py +++ /dev/null @@ -1,1129 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import re -from collections import defaultdict -from collections.abc import Iterator -from dataclasses import InitVar, dataclass, field -from pathlib import Path -from typing import NamedTuple, Optional, Union, cast - -import numpy as np -import torch -import torch.nn as nn -from lightning.pytorch import Trainer -from omegaconf import MISSING, DictConfig, OmegaConf -from torch.nn.utils.rnn import pad_sequence -from tqdm.auto import tqdm - -from nemo.collections.asr.parts.submodules.ngram_lm.constants import DEFAULT_TOKEN_OFFSET -from nemo.collections.common.parts import NEG_INF -from nemo.core import ModelPT, PretrainedModelInfo -from nemo.core.utils.optional_libs import KENLM_AVAILABLE, TRITON_AVAILABLE, kenlm_required, triton_required -from nemo.utils import logging - -if KENLM_AVAILABLE: - import kenlm - -if TRITON_AVAILABLE: - import triton - - from nemo.collections.asr.parts.submodules.ngram_lm.ngram_lm_triton import ngram_advance_triton_kernel - -# Define constants for parsing ARPA -_BOS_ID = -1 # Begin-of-Sentence -_EOS_ID = -2 # End-of-Sentence -_UNK_ID = -3 # Unk -_SPECIAL_SYMBOLS_MAP = {"": _BOS_ID, "": _EOS_ID, "": _UNK_ID} - - -def _log_10_to_e(score): - """Convert logarithm with base 10 to natural""" - return score / np.log10(np.e) - - -class KenLMBatchedWrapper: - """ - KenLM model wrapper for single element and batched queries (slow) for reference decoding and testing purposes. - """ - - @kenlm_required - def __init__(self, lm_path: Path | str, vocab_size: int, token_offset: int = DEFAULT_TOKEN_OFFSET): - """ - Constructor from KenLM (binary) or ARPA (text) model - - Args: - lm_path: path to the LM file (binary KenLM or text ARPA model) - vocab_size: full vocabulary size for the LM - token_offset: offset for the tokens used for building LM - """ - self.ngram_lm = kenlm.Model(str(lm_path)) - self.token_offset = token_offset - self.vocab_size = vocab_size - - @classmethod - def from_file( - cls, lm_path: Path | str, vocab_size: int, token_offset: int = DEFAULT_TOKEN_OFFSET - ) -> "KenLMBatchedWrapper": - """ - Constructor from KenLM (binary) or ARPA (text) model (same as `__init__`). - Useful for fast switching between NGramGPULanguageModel and this class. - - Args: - lm_path: path to .nemo checkpoint or ARPA (text) file - vocab_size: model vocabulary size: - token_offset: offset for the tokens used for building ARPA LM - - Returns: - KenLMBatchedWrapper instance - """ - return cls(lm_path=lm_path, vocab_size=vocab_size, token_offset=token_offset) - - def get_init_state(self, bos=True) -> "kenlm.State": - """ - Get initial state for the LM (KenLM) - - Args: - bos: use begin-of-sentence (start-of-sentence) state, default True - - Returns: - initial state - """ - init_lm_state = kenlm.State() - - if not bos: - return init_lm_state - - self.ngram_lm.BeginSentenceWrite(init_lm_state) - return init_lm_state - - def get_init_states(self, batch_size: int, bos=True) -> list["kenlm.State"]: - """ - Get initial states for the LM (KenLM) for batched queries - - Args: - batch_size: batch size - bos: use begin-of-sentence (start-of-sentence) state, default True - - Returns: - batch (list) of states - """ - return [self.get_init_state(bos=bos) for _ in range(batch_size)] - - def advance(self, states: list["kenlm.State"]) -> tuple[torch.Tensor, list[list["kenlm.State"]]]: - """ - Advance `states` [B]: return scores [B, V] and next states [B, V] for full vocab - Args: - states: batch of states - - Returns: - tuple containing next states and scores - """ - batch_size = len(states) - new_states = [[] for _ in range(len(states))] - scores = torch.zeros(batch_size, self.vocab_size) - for i, state in enumerate(states): - for label in range(self.vocab_size): - score, new_state = self.advance_single(state, label) - scores[i, label] = score - new_states[i].append(new_state) - - return scores, new_states - - def advance_single(self, state: "kenlm.State", label: int) -> tuple[float, "kenlm.State"]: - """ - Computes the score with KenLM N-gram language model for `label` given `state` - Args: - state: KenLM state - label: text token - - Returns: - tuple: score, next state - """ - if self.token_offset: - label = chr(label + self.token_offset) - else: - label = str(label) - - next_state = kenlm.State() - lm_score = self.ngram_lm.BaseScore(state, label, next_state) - lm_score /= np.log10(np.e) - - return lm_score, next_state - - def score_sentence(self, sentence: list[int], bos: bool = True, eos: bool = False) -> torch.Tensor: - """ - Compute log-probabilities for all labels in the sentence using N-Gram LM. - - Args: - sentence: list of tokens - bos: start with BOS symbol - - Returns: - Tensor with scores for the sentence. Size: [L+1] if eos else [L] - """ - state = self.get_init_state(bos=bos) - scores = [] - for label in sentence: - score, state = self.advance_single(state=state, label=label) - scores.append(score) - if eos: - scores.append(self.get_final_single(state=state)) - return torch.FloatTensor(scores) - - def score_sentences(self, sentences: list[list[int]], bos: bool = True, eos: bool = False) -> torch.Tensor: - """ - Compute log-probabilities for all labels in sentences using N-Gram LM. - - Args: - sentences: list of sequences of tokens - bos: start with BOS symbol - - Returns: - Tensor with scores for each sentence. Size: [B, L+1] if eos else [B, L] - """ - return pad_sequence( - [self.score_sentence(sentence, bos=bos, eos=eos) for sentence in sentences], batch_first=True - ) - - def get_final_single(self, state: "kenlm.State") -> float: - """ - Get final score for the state - - Args: - state: state - - Returns: - final score - """ - new_state = kenlm.State() # needed for query, but we ignore it further since not needed in decoding - return _log_10_to_e(self.ngram_lm.BaseScore(state, "", new_state)) - - def get_final(self, states: list["kenlm.State"]) -> torch.Tensor: - """ - Get final scores for the states - - Args: - states: list of states - - Returns: - Tensor [B] with final scores - """ - final_scores = torch.zeros(len(states)) - for i, state in enumerate(states): - final_scores[i] = self.get_final_single(state) - - return final_scores - - -class NGram(NamedTuple): - """Structure (tuple) to represent N-Gram element (symbols, weight, backoff)""" - - symbols: tuple[int, ...] - weight: float - backoff: float - - -class Arc(NamedTuple): - """Structure (tuple) to represent arc in the weighted acceptor""" - - weight: float - ilabel: int - to: int - - -@dataclass -class SuffixTreeStorage: - """ - NumPy-based storage for suffix tree (weighted acceptor) for N-Gram LM - """ - - num_states_max: InitVar[int] - num_arcs_max: InitVar[int] - - vocab_size: int - max_order: int - - separate_bos_state: InitVar[bool] = True - - arcs: np.ndarray = field(init=False) - states: np.ndarray = field(init=False) - - _arc_cache: dict[tuple[int, ...], int] = field(default_factory=dict) - - unk_prob: float = float("-inf") - normalize_unk: bool = True - - num_states: int = 0 - num_arcs: int = 0 - - start_state: int = 0 - bos_state: int = 1 - - def __post_init__(self, num_states_max: int, num_arcs_max: int, separate_bos_state: bool = True): - if max(num_states_max, num_arcs_max) < np.iinfo(np.int32).max: - int_np_dtype = np.int32 - else: - int_np_dtype = np.int64 - self.arcs = np.zeros( - [num_arcs_max], - dtype=[("from", int_np_dtype), ("to", int_np_dtype), ("ilabel", int_np_dtype), ("weight", np.float32)], - ) - self.states = np.zeros( - [num_states_max], - dtype=[ - ("arcs_start", int_np_dtype), - ("arcs_end", int_np_dtype), - ("order", int_np_dtype), - ("backoff_to", int_np_dtype), - ("backoff_w", np.float32), - ("final", np.float32), - ], - ) - self.states["final"] = NEG_INF - self.bos_state = 1 if separate_bos_state else self.start_state - - def _add_unigrams(self, ngrams: np.ndarray, bos_id: int, unk_id: int): - """Add all unigrams""" - assert bos_id < 0 and unk_id < 0 - bos_unigram = None - - ngrams.sort(order="symbols") - for ngram in ngrams: - assert len(ngram["symbols"]) == 1 # unigrams - symbol = ngram["symbols"][-1] - if symbol == unk_id: - self.unk_prob = ngram["weight"] - elif symbol == bos_id: - bos_unigram = ngram - assert bos_unigram is not None - - self.num_states = 2 # SOS + BOS - self.num_arcs = 0 - # state: start_arcs, end_arcs, order, backoff_to, backoff_weight - self.states[self.start_state] = (0, self.vocab_size, 1, self.start_state, 0.0, NEG_INF) - added_symbols = set() - num_vocab_labels = 0 - for ngram in ngrams: - ilabel = ngram["symbols"][-1] - if ilabel < 0: - # special symbol - if ilabel == _EOS_ID: - self.states[self.start_state]["final"] = ngram["weight"] - continue - assert ilabel < self.vocab_size - arc_id = ilabel - added_symbols.add(ilabel) - next_state = self.num_states - self.num_states += 1 - self.arcs[arc_id] = (self.start_state, next_state, ilabel, ngram["weight"]) - self.num_arcs += 1 - # state order - self.states[next_state] = ( - 0, - 0, - self.states[self.start_state]["order"] + 1, - self.start_state, - ngram["backoff"], - NEG_INF, - ) - num_vocab_labels += 1 - - if self.normalize_unk: - num_unk_labels = self.vocab_size - num_vocab_labels - if num_unk_labels > 1: - self.unk_prob -= np.log(num_unk_labels) - for ilabel in range(self.vocab_size): - if ilabel not in added_symbols: - self.arcs[ilabel] = (self.start_state, self.start_state, ilabel, self.unk_prob) - self.num_arcs += 1 - - # add BOS unigram - assert self.bos_state == 1 - # NB: we do not add BOS unigram to the arcs, but only to the states - self.states[self.bos_state] = ( - 0, - 0, - self.states[self.start_state]["order"] + 1, - self.start_state, - bos_unigram["backoff"], - NEG_INF, - ) - - def _find_state(self, symbols: tuple[int, ...], bos_id: int) -> int: - """ - Find the state given sequence of symbols - Args: - symbols: sequence of symbols - bos_id: ID of the Begin-of-Sentence symbol - - Returns: - state in tree for the last symbol - """ - if len(symbols) > 1: - return self._arc_cache[tuple(symbols)] - assert len(symbols) == 1 - label = symbols[0] - if label == bos_id: - return 1 - elif label >= 0: - return self.arcs[label]["to"] - raise ValueError(f"Invalid symbol {label}") - - def _add_ngrams_next_order(self, ngrams: np.ndarray, bos_id: int): - """Add ngrams for the order > 1; should be called after adding unigrams, using increasing order""" - ngrams.sort(order="symbols") - new_arc_cache = dict() - for ngram in tqdm(ngrams): - symbols = ngram["symbols"].item() - ilabel = symbols[-1] - from_state = self._find_state(symbols[:-1], bos_id=bos_id) - if ilabel < 0: - assert ilabel == _EOS_ID - self.states[from_state]["final"] = ngram["weight"] - continue - assert ilabel < self.vocab_size - backoff_state = self._find_state(symbols[1:], bos_id=bos_id) - - arc_id = self.num_arcs - next_state = self.num_states - self.num_arcs += 1 - self.num_states += 1 - self.arcs[arc_id] = (from_state, next_state, ilabel, ngram["weight"]) - # state: start_arcs, end_arcs, order, backoff_to, backoff_weight - self.states[next_state] = ( - 0, - 0, - self.states[from_state]["order"] + 1, - backoff_state, - ngram["backoff"], - NEG_INF, - ) - - if self.states[from_state]["arcs_start"] == 0: - self.states[from_state]["arcs_start"] = arc_id - self.states[from_state]["arcs_end"] = arc_id + 1 - else: - assert self.states[from_state]["arcs_end"] == arc_id - self.states[from_state]["arcs_end"] = arc_id + 1 - # cache state - new_arc_cache[symbols] = next_state - self._arc_cache = new_arc_cache # replace arc cache, previous is not needed - - def _start_adding_ngrams_for_order(self, order: int, max_ngrams: int): - """Prepare for adding ngrams for the given order: initialize temporary storage""" - self._start_arcs = self.num_arcs - self._cur_order = order - if order < self.max_order: - dtype = [ - ("symbols", [(f"{i}", np.int32) for i in range(order)]), - ("weight", np.float32), - ("backoff", np.float32), - ] - self._ngrams = np.zeros([max_ngrams], dtype=dtype) - self._ngrams_cnt = 0 - # for max order - no need in accumulator - - def _add_ngram(self, ngram: NGram, bos_id: int): - """Helper to add ngram""" - assert len(ngram.symbols) == self._cur_order - if self._cur_order == self.max_order: - self._add_ngram_max_order(ngram=ngram, bos_id=bos_id) - return - self._ngrams[self._ngrams_cnt] = (ngram.symbols, ngram.weight, ngram.backoff) - self._ngrams_cnt += 1 - - def _end_adding_ngrams_for_order(self, order: int, bos_id: int, unk_id: int): - """Finish adding ngrams for the given order""" - if order == 1: - assert self._ngrams.shape[0] == self._ngrams_cnt - self._add_unigrams(ngrams=self._ngrams, bos_id=bos_id, unk_id=unk_id) - self._ngrams = None - self._ngrams_cnt = 0 - elif order < self.max_order: - assert self._ngrams.shape[0] == self._ngrams_cnt - self._add_ngrams_next_order(ngrams=self._ngrams, bos_id=bos_id) - self._ngrams = None - self._ngrams_cnt = 0 - else: - self._end_adding_ngrams_max_order() - - def _add_ngram_max_order(self, ngram: NGram, bos_id: int): - """Add ngram for the maximum order""" - ilabel = ngram.symbols[-1] - from_state = self._find_state(ngram.symbols[:-1], bos_id=bos_id) - if ilabel < 0: - assert ilabel == _EOS_ID - self.states[from_state]["final"] = ngram.weight - return - backoff_state = self._find_state(ngram.symbols[1:], bos_id=bos_id) - - arc_id = self.num_arcs - self.num_arcs += 1 - self.arcs[arc_id] = (from_state, backoff_state, ilabel, ngram.weight) - - def _end_adding_ngrams_max_order(self): - """Finish adding ngrams for the maximum order""" - self.arcs[self._start_arcs : self.num_arcs].sort(order=["from", "ilabel"]) - for arc_i in range(self._start_arcs, self.num_arcs): - from_state = self.arcs[arc_i]["from"] - if self.states[from_state]["arcs_start"] == 0: - self.states[from_state]["arcs_start"] = arc_i - self.states[from_state]["arcs_end"] = arc_i + 1 - - def sanity_check(self): - """Sanity check for the model""" - assert (self.arcs["ilabel"][: self.num_arcs] < self.vocab_size).all() - assert (self.arcs["ilabel"][: self.num_arcs] >= 0).all() - - -@dataclass -class NGramLMConfig: - """ - N-Gram LM Config - """ - - num_states: int = MISSING - num_arcs: int = MISSING - max_order: int = MISSING - vocab_size: int = MISSING - separate_bos_state: bool = True - use_triton: bool | None = None - - -class NGramGPULanguageModel(ModelPT): - """ - N-Gram GPU-accelerated Language Model (NGPU-LM) supporting batched queries. - Fast implementation for parallel queries for full vocabulary. - Supports autograd (differentiable weights). - """ - - START_STATE = 0 - - def __init__( - self, - cfg: DictConfig, - trainer: Trainer = None, - ): - """ - Stubs for constructor that does not initialize the structure. - This constructor can be useful when storing/loading module using native torch serialization mechanism - instead of directly reading ARPA model -> converting to Torch, which can be slow for large N-Gram models - (of several GBs). - - Args: - cfg: - num_states: number of states in graph - num_arcs: number of arcs (transitions) in graph - max_order: maximum order of n-gram LM (maximum possible nubmer of transitions without backoffs) - vocab_size: vocabulary size (existing vocabulary units in LM; should not include blank etc.) - separate_bos_state: separate Begin-of-Sentence state (default: True - for n-gram LM) - use_triton: allow using Triton implementation; - None (default) means "auto" (used if available), True means forced mode - (will crash if Triton is unavailable) - trainer: Lightning trainer (optional) - """ - super().__init__(cfg=cfg, trainer=trainer) - cfg = cast(NGramLMConfig, cfg) - self.use_triton = cfg.use_triton if cfg.use_triton is not None else TRITON_AVAILABLE - if not self.use_triton: - logging.warning( - "Triton is disabled. Version without Triton is not compatible with Cuda graphs; decoding can be slow" - ) - - self.bos_state: int = 1 if cfg.separate_bos_state else self.START_STATE - self.vocab_size: int = cfg.vocab_size - self.num_states: int = cfg.num_states - self.num_arcs: int = cfg.num_arcs - self.max_order: int = cfg.max_order - self.num_arcs_extended: int = cfg.num_arcs + self.vocab_size # + extra padding - - # parameters: weights (forward/backoff/final) - self.arcs_weights = nn.Parameter(torch.zeros([self.num_arcs_extended])) - self.backoff_weights = nn.Parameter(torch.zeros([self.num_states])) - self.final_weights = nn.Parameter(torch.zeros([self.num_states])) - - if max(self.num_states, self.num_arcs_extended) < torch.iinfo(torch.int32).max: - int_dtype = torch.int32 - else: - int_dtype = torch.int64 - # buffers: LM (suffix tree) structure - # arcs data - self.from_states = nn.Buffer(torch.zeros([self.num_arcs_extended], dtype=int_dtype)) - self.to_states = nn.Buffer(torch.zeros([self.num_arcs_extended], dtype=int_dtype)) - self.ilabels = nn.Buffer(torch.zeros([self.num_arcs_extended], dtype=int_dtype)) - - # states data - self.backoff_to_states = nn.Buffer(torch.zeros([self.num_states], dtype=int_dtype)) - self.start_end_arcs = nn.Buffer(torch.zeros([self.num_states, 2], dtype=int_dtype)) - self.state_order = nn.Buffer(torch.zeros([self.num_states], dtype=int_dtype)) - - self._final_resolved = False - - @classmethod - def list_available_models(cls) -> list[PretrainedModelInfo]: - """Stub necessary to create the ModelPT. Not used for LM""" - return [] - - def setup_training_data(self, train_data_config: Union[DictConfig, dict]): - """Stub necessary to create the ModelPT. Not used for LM""" - pass - - def setup_validation_data(self, val_data_config: Union[DictConfig, dict]): - """Stub necessary to create the ModelPT. Not used for LM""" - pass - - def compatible_with_cuda_graphs(self) -> bool: - """True if model can be compiled as a part of CUDA graph, False otherwise""" - return self.use_triton - - @classmethod - def from_nemo( - cls, - lm_path: Path | str, - vocab_size: int, - use_triton: bool | None = None, - ) -> "NGramGPULanguageModel": - """ - Constructor from Nemo checkpoint (state dict). - - Args: - lm_path: path to .nemo checkpoint - vocab_size: model vocabulary size - use_triton: allow using Triton implementation; None (default) means "auto" (used if available) - """ - model = cls.restore_from(restore_path=str(lm_path), map_location="cpu") - model._resolve_final() - assert model.vocab_size == vocab_size - model.use_triton = use_triton if use_triton is not None else TRITON_AVAILABLE - if not model.use_triton: - logging.warning( - "Triton is disabled. Version without Triton is not compatible with Cuda graphs; decoding can be slow" - ) - return model - - @classmethod - def from_file( - cls, - lm_path: Path | str, - vocab_size: int, - normalize_unk: bool = True, - use_triton: bool | None = None, - token_offset: int = DEFAULT_TOKEN_OFFSET, - ) -> "NGramGPULanguageModel": - """ - Constructor from ARPA or Nemo (`.nemo`) checkpoint. - - Args: - lm_path: path to .nemo checkpoint or ARPA (text) file - vocab_size: model vocabulary size: - normalize_unk: normalize unk probabilities (for tokens missing in LM) to make - all unigram probabilities sum to 1.0 (default: True) - use_triton: allow using Triton implementation; None (default) means "auto" (used if available) - token_offset: offset for the tokens used for building ARPA LM - - Returns: - NGramGPULanguageModel instance - """ - if not isinstance(lm_path, Path): - lm_path = Path(lm_path) - if lm_path.suffix == ".nemo": - return cls.from_nemo(lm_path=lm_path, vocab_size=vocab_size, use_triton=use_triton) - return cls.from_arpa( - lm_path=lm_path, - vocab_size=vocab_size, - normalize_unk=normalize_unk, - token_offset=token_offset, - use_triton=use_triton, - ) - - @classmethod - def from_arpa( - cls, - lm_path: Path | str, - vocab_size: int, - normalize_unk: bool = True, - use_triton: bool | None = None, - token_offset: int = DEFAULT_TOKEN_OFFSET, - ) -> "NGramGPULanguageModel": - """ - Constructor from ARPA LM (text format). - - Args: - lm_path: path to ARPA model (human-readable) - vocab_size: vocabulary size (existing vocabulary units in LM; should not include blank etc.) - normalize_unk: unk normalization to make all output probabilities sum to 1.0 (default: True). - Setting to False can be useful for one-to-one comparison with KenLM (tests, etc.). - use_triton: allow using Triton implementation; - None (default) means "auto" (used if available), True means forced mode - (will crash if Triton is unavailable) - token_offset: offset for the tokens used for building ARPA LM - - Returns: - NGramGPULanguageModel instance - """ - logging.info(f"{cls.__name__}: reading LM from {lm_path}") - with open(lm_path, "r", encoding="utf-8") as f: - order2cnt = cls._read_header(f=f) - # init suffix tree storage - max_order = max(order2cnt.keys()) - total_ngrams = sum(order2cnt.values()) - max_states = 2 + vocab_size + sum(order2cnt[o] for o in range(2, max_order)) # without last! - suffix_tree_np = SuffixTreeStorage( - num_states_max=max_states, - num_states=0, - num_arcs=0, - num_arcs_max=total_ngrams + vocab_size * 2 + 1, - normalize_unk=normalize_unk, - vocab_size=vocab_size, - max_order=max_order, - ) - # add ngrams to suffix tree - ngram_cur_order_i = 0 - cur_order = 1 - for ngram in tqdm(cls._read_ngrams(f=f, token_offset=token_offset), total=total_ngrams): - if ngram_cur_order_i == 0: - suffix_tree_np._start_adding_ngrams_for_order(order=cur_order, max_ngrams=order2cnt[cur_order]) - ngram_cur_order_i += 1 - suffix_tree_np._add_ngram(ngram=ngram, bos_id=_BOS_ID) - - if ngram_cur_order_i == order2cnt[cur_order]: - suffix_tree_np._end_adding_ngrams_for_order(order=cur_order, bos_id=_BOS_ID, unk_id=_UNK_ID) - logging.debug(f"Processed {order2cnt[cur_order]} n-grams of order {cur_order}") - cur_order += 1 - ngram_cur_order_i = 0 - - assert ngram_cur_order_i == 0 - suffix_tree_np.sanity_check() - return NGramGPULanguageModel.from_suffix_tree(suffix_tree_np=suffix_tree_np, use_triton=use_triton) - - @classmethod - def dummy_unigram_lm( - cls, - vocab_size: int, - use_triton: bool | None = None, - ) -> "NGramGPULanguageModel": - """ - Constructs a trivial unigram LM with uniform distribution over the vocabulary. - Useful for testing purposes (e.g., decoding). - - Returns: - NGramGPULanguageModel instance - """ - model = NGramGPULanguageModel( - OmegaConf.structured( - NGramLMConfig( - num_states=2, - num_arcs=vocab_size, - max_order=1, - vocab_size=vocab_size, - use_triton=use_triton, - ) - ) - ) - unigram_weight = -np.log(vocab_size) - - # start state - model.backoff_weights.data[0] = 0.0 - model.final_weights.data[0] = unigram_weight - model.backoff_to_states.data[0] = 0 - model.start_end_arcs.data[0, :] = torch.tensor([0, vocab_size], dtype=model.start_end_arcs.dtype) - model.state_order.data[0] = 1 - - # BOS state - model.backoff_weights.data[1] = 0.0 - model.final_weights.data[1] = unigram_weight - model.backoff_to_states.data[1] = 0 # to start state - model.start_end_arcs.data[1, :] = torch.tensor( - [vocab_size, vocab_size], dtype=model.start_end_arcs.dtype - ) # no arcs - model.state_order.data[1] = 2 - - # all tokens - unigrams from start to start state (cycles) - model.arcs_weights.data.fill_(unigram_weight) - model.from_states.data.fill_(model.START_STATE) - model.to_states.data.fill_(model.START_STATE) - model.ilabels.data[:vocab_size].copy_(torch.arange(vocab_size, dtype=model.ilabels.dtype)) - - model._resolve_final() - return model - - @classmethod - def from_suffix_tree( - cls, suffix_tree_np: SuffixTreeStorage, use_triton: bool | None = None - ) -> "NGramGPULanguageModel": - """ - Constructor from suffix tree storage. - - Args: - suffix_tree_np: suffix tree - use_triton: allow using Triton implementation; - None (default) means "auto" (used if available), True means forced mode - (will crash if Triton is unavailable) - - Returns: - NGramGPULanguageModel instance - """ - model = NGramGPULanguageModel( - OmegaConf.structured( - NGramLMConfig( - num_states=suffix_tree_np.num_states, - num_arcs=suffix_tree_np.num_arcs, - max_order=suffix_tree_np.max_order, - vocab_size=suffix_tree_np.vocab_size, - use_triton=use_triton, - ) - ) - ) - model._init_from_suffix_tree_np(suffix_tree_np=suffix_tree_np) - model._resolve_final() - return model - - @classmethod - def _read_header(cls, f) -> dict[int, int]: - """ - Parse ARPA header - - Args: - f: file object - - Returns: - dictionary with order -> number of ngrams - """ - is_start = True - order2cnt: dict[int, int] = defaultdict(int) - for line in f: - line = line.strip() - if is_start: - assert line == "\\data\\" - is_start = False - continue - - if line.startswith("ngram"): - ngram_order, cnt = line.split("=") - order = int(ngram_order.split()[-1]) - cnt = int(cnt) - order2cnt[order] = cnt - continue - else: - assert not line, "empty line expected after header" - break - return order2cnt - - @classmethod - def _read_ngrams(cls, f, token_offset: int) -> Iterator[NGram]: - special_words_pattern = '|'.join(re.escape(symbol) for symbol in _SPECIAL_SYMBOLS_MAP) - pattern = re.compile(rf'({special_words_pattern}|.)\s?') - for line in f: - if line.endswith("\n"): - line = line[:-1] - - if not line: - continue - - if line.startswith("\\end\\"): - break - - if line.startswith("\\"): - continue - - ngram = cls._line_to_ngram(line=line, pattern=pattern, token_offset=token_offset) - yield ngram - - @staticmethod - def _line_to_ngram(line: str, pattern: re.Pattern, token_offset: int) -> NGram: - """Parse ARPA line to N-Gram structure""" - weight, symbols_str, *backoff_opt = line.split("\t") - if backoff_opt: - assert len(backoff_opt) == 1 - backoff = _log_10_to_e(float(backoff_opt[0])) - else: - backoff = 0.0 - weight = _log_10_to_e(float(weight)) - symbols_re = pattern.findall(symbols_str) - - symbols = tuple( - (ord(symbol) - token_offset if symbol not in _SPECIAL_SYMBOLS_MAP else _SPECIAL_SYMBOLS_MAP[symbol]) - for symbol in symbols_re - ) - return NGram(symbols=symbols, weight=weight, backoff=backoff) - - def _init_from_suffix_tree_np(self, suffix_tree_np: SuffixTreeStorage): - """Helper function to init params from suffix tree params""" - # parameters: weights - self.arcs_weights.data.copy_(torch.from_numpy(suffix_tree_np.arcs["weight"][: self.num_arcs_extended])) - self.backoff_weights.data.copy_(torch.from_numpy(suffix_tree_np.states["backoff_w"][: self.num_states])) - self.final_weights.data.copy_(torch.from_numpy(suffix_tree_np.states["final"][: self.num_states])) - - # buffers: LM (suffix tree) structure - self.from_states.data.copy_(torch.from_numpy(suffix_tree_np.arcs["from"][: self.num_arcs_extended])) - self.to_states.data.copy_(torch.from_numpy(suffix_tree_np.arcs["to"][: self.num_arcs_extended])) - self.ilabels.data.copy_(torch.from_numpy(suffix_tree_np.arcs["ilabel"][: self.num_arcs_extended])) - self.backoff_to_states.data.copy_(torch.from_numpy(suffix_tree_np.states["backoff_to"][: self.num_states])) - - self.start_end_arcs.data[:, 0].copy_(torch.from_numpy(suffix_tree_np.states["arcs_start"][: self.num_states])) - self.start_end_arcs.data[:, 1].copy_(torch.from_numpy(suffix_tree_np.states["arcs_end"][: self.num_states])) - self.state_order.data.copy_(torch.from_numpy(suffix_tree_np.states["order"][: self.num_states])) - - # sanity check - assert self.state_order.min().item() == 1 - assert self.state_order.max().item() <= self.max_order - - def get_init_states(self, batch_size: int, bos=True) -> torch.Tensor: - """ - Get batch of the initial states - - Args: - batch_size: batch size - bos: use begin-of-sentence state - - Returns: - tensor [B] of initial states - """ - device = self.arcs_weights.device - return torch.full( - [batch_size], fill_value=self.bos_state if bos else self.START_STATE, device=device, dtype=torch.long - ) - - def forward( - self, - labels: torch.Tensor, - labels_lengths: Optional[torch.Tensor] = None, - bos: bool = True, - eos: bool = False, - ) -> torch.Tensor: - """ - Compute log-probabilities for all labels in utterances using N-Gram LM. - - Args: - labels: label sequences [B x L] if eos=False, [B x (L+1)] if eos=True - labels_lengths (optional): lengths of the label sequences - bos: start with BOS symbol - eos: add EOS score after the sentence - - Returns: - Tensor [B x L] with scores for each label in the utterance - """ - return self.score_sentences(labels=labels, labels_lengths=labels_lengths, bos=bos, eos=eos) - - def score_sentences( - self, - labels: torch.Tensor, - labels_lengths: Optional[torch.Tensor] = None, - bos: bool = True, - eos: bool = False, - ) -> torch.Tensor: - """ - Compute log-probabilities for all labels in utterances using N-Gram LM. - - Args: - labels: label sequences [B x L] if eos=False, [B x (L+1)] if eos=True - labels_lengths (optional): lengths of the label sequences - bos: start with BOS symbol - eos: add EOS score after the sentence - - Returns: - Tensor [B x (L + 1) if eos else B x L] with scores for each label in the utterance - """ - device = labels.device - batch_size, max_length = labels.shape - if labels_lengths is None: - labels_lengths = torch.full([batch_size], fill_value=max_length, dtype=torch.int32, device=device) - batch_size, max_length = labels.shape - scores = torch.zeros([batch_size, max_length + (1 if eos else 0)], device=device) - states = self.get_init_states(batch_size=batch_size, bos=bos) - # NB: It is possible to speedup this algorithm with a custom kernel (no need to retrieve all weights/labels) - for i in range(max_length): - # NB: _advance_triton is not differentiable (need to implement backward manually); - # for training _advance_pytorch only can be used - prev_states = states - step_scores, states = self._advance_pytorch(states) - scores[:, i] = step_scores.gather(dim=1, index=labels[:, i].unsqueeze(-1)).squeeze(-1) * ( - i < labels_lengths - ) - # get next states, preserve last state if the utterance ended - states = torch.where( - i < labels_lengths, states.gather(dim=1, index=labels[:, i].unsqueeze(-1)).squeeze(-1), prev_states - ) - if eos: - final_weights = self.get_final(states) - scores.scatter_(dim=1, index=labels_lengths.unsqueeze(-1).to(torch.int64), src=final_weights.unsqueeze(-1)) - return scores - - def advance(self, states: torch.Tensor, eos_id: Optional[int] = None) -> tuple[torch.Tensor, torch.Tensor]: - """ - Advance `states` [B]: return scores [B, V] and next states [B, V] for full vocab - Args: - states: batch of states - eos_id: if not None, for eos symbol use final state weight - - Returns: - tuple with next states and scores - """ - if self.use_triton and states.device.type == "cuda": - scores, next_states = self._advance_triton(states=states) - else: - scores, next_states = self._advance_pytorch(states=states) - - # replace weight corresponding to eos_id with final state weight - if eos_id is not None: - scores[:, eos_id] = self.get_final(states=states) - next_states[:, eos_id] = states - return scores, next_states - - def _advance_pytorch(self, states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: - """ - Advance `states` [B]: return scores [B, V] and next states [B, V] for full vocab. - PyTorch implementation (slow, differentiable). - - Args: - states: batch of states - - Returns: - tuple of scores and next states - """ - batch_size = states.shape[0] - device = states.device - current_states = states.clone() - states_dtype = current_states.dtype - - # init output tensors - out_scores = torch.zeros(batch_size, self.vocab_size, device=device) - out_states = torch.full([batch_size, self.vocab_size], fill_value=-1, dtype=states_dtype, device=device) - - # helper ranges - vocab_range = torch.arange(self.vocab_size, device=device) - batch_indices = torch.arange(batch_size, device=device) - - # backoff weight accumulator - accumulated_backoff = torch.zeros(batch_size, device=device) - # loop condition - start_state_not_processed = torch.full([batch_size], fill_value=True, dtype=torch.bool, device=device) - - num_iterations = 0 - while start_state_not_processed.any(): - assert num_iterations <= self.max_order, "Infinite loop in LM advance" - num_iterations += 1 - # get arc boundaries - start, end = self.start_end_arcs[current_states].unbind(dim=1) - # number of arcs for each state cannot be larger than vocab size - indices = start[:, None] + vocab_range[None, :] - mask = indices < end[:, None] - mask &= start_state_not_processed[:, None] - mask_flat = mask.view(-1) - indices_flat = indices.view(-1) - # map indices outside the mask to vocab_size + 1 - scores_add = torch.zeros([batch_size, self.vocab_size + 1], device=device, dtype=out_scores.dtype) - out_states_add = torch.full( - [batch_size, self.vocab_size + 1], fill_value=-1, device=device, dtype=states_dtype - ) - ilabels = self.ilabels[indices_flat] * mask_flat + ~mask_flat * self.vocab_size - scores_add[batch_indices.repeat_interleave(self.vocab_size), ilabels] = self.arcs_weights[indices_flat] - out_states_add[batch_indices.repeat_interleave(self.vocab_size), ilabels] = self.to_states[ - indices_flat - ].to(states_dtype) - # fill out_scores and out_states with new values where state is not found yet - state_found = out_states != -1 - out_scores = torch.where( - state_found, out_scores, accumulated_backoff.unsqueeze(-1) + scores_add[:, : self.vocab_size] - ) - out_states = torch.where(state_found, out_states, out_states_add[:, : self.vocab_size]) - # update loop condition; process backoffs - start_state_not_processed &= current_states != self.START_STATE - accumulated_backoff += self.backoff_weights[current_states] * start_state_not_processed - torch.where( - start_state_not_processed, self.backoff_to_states[current_states], current_states, out=current_states - ) - return out_scores, out_states - - @triton_required - def _advance_triton(self, states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: - """ - Advance `states` [B]: return scores [B, V] and next states [B, V] for full vocab. - Triton implementation. Currently not differentiable. - - Args: - states: batch of states - - Returns: - tuple of scores and next states - """ - batch_size = states.shape[0] - device = states.device - scores = torch.empty([batch_size, self.vocab_size], device=device, dtype=self.arcs_weights.dtype) - new_states = torch.empty([batch_size, self.vocab_size], dtype=torch.long, device=device) - - ngram_advance_triton_kernel[batch_size,]( - vocab_size=self.vocab_size, - states_ptr=states, - new_states_ptr=new_states, - scores_ptr=scores, - start_state=self.START_STATE, - to_states_ptr=self.to_states, - ilabels_ptr=self.ilabels, - arcs_weights_ptr=self.arcs_weights, - start_end_arcs_ptr=self.start_end_arcs, - backoff_to_states_ptr=self.backoff_to_states, - backoff_weights_ptr=self.backoff_weights, - BLOCK_SIZE=triton.next_power_of_2(self.vocab_size), - ) - - return scores, new_states - - def get_final(self, states: torch.Tensor) -> torch.Tensor: - """ - Get final weights for states - - Args: - states: batch of states - - Returns: - tensor [B] with final weights for each state - """ - if self._final_resolved: - return self.final_weights[states] - logging.warning("Final weights are not resolved; using slow implementation") - return self._get_final_pytorch(states=states) - - def _resolve_final(self): - """Resolve final weights for all states by iterating over backoffs""" - if self._final_resolved: - return - with torch.no_grad(): - self.final_weights.data.copy_( - self._get_final_pytorch(states=torch.arange(self.num_states, device=self.final_weights.device)) - ) - self._final_resolved = True - - def _get_final_pytorch(self, states: torch.Tensor) -> torch.Tensor: - """ - Get final weights for states, resolving backoffs - - Args: - states: batch of states - - Returns: - batch of final weights - """ - cur_states = states.clone().detach() - out_scores = self.final_weights[cur_states] - accumulated_backoff = torch.zeros_like(out_scores) - while (out_scores <= NEG_INF).any() and (cur_states != self.START_STATE).any(): - accumulated_backoff += self.backoff_weights[cur_states] - cur_states = self.backoff_to_states[cur_states] - cur_final = self.final_weights[cur_states] - out_scores = torch.where( - (out_scores > NEG_INF) | (cur_final <= NEG_INF), out_scores, accumulated_backoff + cur_final - ) - return out_scores diff --git a/nemo/collections/asr/parts/submodules/ngram_lm/ngram_lm_triton.py b/nemo/collections/asr/parts/submodules/ngram_lm/ngram_lm_triton.py deleted file mode 100644 index 0eb957e6b1a5982dc786e6934f317b2f02a80d31..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/ngram_lm/ngram_lm_triton.py +++ /dev/null @@ -1,177 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import triton -import triton.language as tl - - -@triton.jit -def ngram_advance_triton_kernel( - vocab_size: "tl.constexpr", - states_ptr, - new_states_ptr, - scores_ptr, - start_state: int, - to_states_ptr, - ilabels_ptr, - arcs_weights_ptr, - start_end_arcs_ptr, - backoff_to_states_ptr, - backoff_weights_ptr, - BLOCK_SIZE: "tl.constexpr", -): - """ - Triton kernel for N-Gram LM advance operation. - Args: - vocab_size: LM vocabulary size - states_ptr: pointer to tensor with batch of current states [B] - new_states_ptr: pointer to tensor [B, V] to store new states - scores_ptr: pointer to tensor [B, V] to store scores - start_state: start state of the LM (usually 0) - to_states_ptr: pointer to the tensor with target states (arcs data) - ilabels_ptr: pointer to the tensor with labels (arcs data) - arcs_weights_ptr: pointer to the tensor with weights (arcs data) - start_end_arcs_ptr: pointer to the tensor with (start, end) indices of arcs (states data) - backoff_to_states_ptr: pointer to the tensor with backoff target states (states data) - backoff_weights_ptr: pointer to the tensor with backoff weights (states data) - BLOCK_SIZE: block size, should be >= vocab_size - """ - batch_i = tl.program_id(0) # index of the element in the batch - cur_state = tl.load(states_ptr + batch_i) # current state - - # NB: number of arcs in current state is <= vocab_size and BLOCK_SIZE - vocab_offsets = tl.arange(0, BLOCK_SIZE) - vocab_mask = vocab_offsets < vocab_size - # fill in initial values: new_states = -1 (not found yet), scores = 0 - tl.store(new_states_ptr + batch_i * vocab_size + vocab_offsets, -1, mask=vocab_mask) - tl.store(scores_ptr + batch_i * vocab_size + vocab_offsets, 0.0, mask=vocab_mask) - - accumulated_backoff = 0.0 - start_state_not_processed = True - # loop until we process start state; it should be guaranteed that in the start state we have all vocabulary tokens - while start_state_not_processed: - tl.debug_barrier() # force threads synchronization - start_idx, end_idx = tl.load(start_end_arcs_ptr + cur_state * 2 + tl.arange(0, 2)).split() - indices = start_idx + vocab_offsets - mask = indices < end_idx - - # load arcs - cur_ilabels = tl.load(ilabels_ptr + indices, mask=mask) - cur_weights = tl.load(arcs_weights_ptr + indices, mask=mask) - cur_to_states = tl.load(to_states_ptr + indices, mask=mask) - - # store scores for arcs reached in the current state (but not processed previously) - not_final_mask = tl.load(new_states_ptr + batch_i * vocab_size + cur_ilabels, mask=mask, other=0) == -1 - tl.store( - scores_ptr + batch_i * vocab_size + cur_ilabels, - cur_weights + accumulated_backoff, - mask=not_final_mask, - ) - tl.store(new_states_ptr + batch_i * vocab_size + cur_ilabels, cur_to_states, mask=not_final_mask) - - start_state_not_processed = cur_state != start_state - # process backoffs - accumulated_backoff += tl.load(backoff_weights_ptr + cur_state) - cur_state = tl.load(backoff_to_states_ptr + cur_state).to(states_ptr.dtype.element_ty) - - -@triton.jit -def ngram_multi_advance_triton_kernel( - vocab_size: "tl.constexpr", - states_ptr, - new_states_out_ptr, - scores_out_ptr, - start_state: int, - model_ids_ptr, - states_offsets_ptr, - arcs_offsets_ptr, - to_states_ptr, - ilabels_ptr, - arcs_weights_ptr, - start_end_arcs_ptr, - backoff_to_states_ptr, - backoff_weights_ptr, - BLOCK_SIZE: "tl.constexpr", -): - """ - Triton kernel for N-Gram LM advance operation. - Args: - vocab_size: LM vocabulary size - states_ptr: pointer to tensor with batch of current states [B] - new_states_out_ptr: pointer to tensor [B, V] to store new states - scores_out_ptr: pointer to tensor [B, V] to store scores - start_state: start state of the LM (usually 0) - model_ids_ptr: pointer to the tensor with model ids - states_offsets_ptr: pointer to tensor with mapping model id -> start of states - arcs_offsets_ptr: pointer to tensor with mapping model id -> start of arcs - to_states_ptr: pointer to the tensor with target states (arcs data) - ilabels_ptr: pointer to the tensor with labels (arcs data) - arcs_weights_ptr: pointer to the tensor with weights (arcs data) - start_end_arcs_ptr: pointer to the tensor with (start, end) indices of arcs (states data) - backoff_to_states_ptr: pointer to the tensor with backoff target states (states data) - backoff_weights_ptr: pointer to the tensor with backoff weights (states data) - BLOCK_SIZE: block size, should be >= vocab_size - """ - batch_i = tl.program_id(0) # index of the element in the batch - cur_state = tl.load(states_ptr + batch_i) # current state - - # load model id - model_id = tl.load(model_ids_ptr + batch_i) - # model_id < 0 - apply dummy values (0 scores, -1 states, filled in by caller) - if model_id < 0: - return - - # load offsets for model states and arcs (based on model id) - model_states_offset = tl.load(states_offsets_ptr + model_id) - model_arcs_offset = tl.load(arcs_offsets_ptr + model_id) - - to_states_ptr += model_arcs_offset - ilabels_ptr += model_arcs_offset - arcs_weights_ptr += model_arcs_offset - start_end_arcs_ptr += model_states_offset * 2 # start_end_arcs tensor has 2 elements in each row - backoff_to_states_ptr += model_states_offset - backoff_weights_ptr += model_states_offset - - # NB: number of arcs in current state is <= vocab_size and BLOCK_SIZE - vocab_offsets = tl.arange(0, BLOCK_SIZE) - # fill in initial values: new_states = -1 (not found yet), scores = 0: moved to caller function - # (NB: caller function should fill scores with 0, states with -1) - - accumulated_backoff = 0.0 - start_state_not_processed = True - # loop until we process start state; it should be guaranteed that in the start state we have all vocabulary tokens - while start_state_not_processed: - tl.debug_barrier() # force threads synchronization - start_idx, end_idx = tl.load(start_end_arcs_ptr + cur_state * 2 + tl.arange(0, 2)).split() - indices = start_idx + vocab_offsets - mask = indices < end_idx - - # load arcs - cur_ilabels = tl.load(ilabels_ptr + indices, mask=mask) - cur_weights = tl.load(arcs_weights_ptr + indices, mask=mask) - cur_to_states = tl.load(to_states_ptr + indices, mask=mask) - - # store scores for arcs reached in the current state (but not processed previously) - not_final_mask = tl.load(new_states_out_ptr + batch_i * vocab_size + cur_ilabels, mask=mask, other=0) == -1 - tl.store( - scores_out_ptr + batch_i * vocab_size + cur_ilabels, - cur_weights + accumulated_backoff, - mask=not_final_mask, - ) - tl.store(new_states_out_ptr + batch_i * vocab_size + cur_ilabels, cur_to_states, mask=not_final_mask) - - start_state_not_processed = cur_state != start_state - # process backoffs - accumulated_backoff += tl.load(backoff_weights_ptr + cur_state) - cur_state = tl.load(backoff_to_states_ptr + cur_state).to(states_ptr.dtype.element_ty) diff --git a/nemo/collections/asr/parts/submodules/rnnt_beam_decoding.py b/nemo/collections/asr/parts/submodules/rnnt_beam_decoding.py deleted file mode 100644 index d0b02a73daaf7804fe7c53815723ba349ee571a0..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/rnnt_beam_decoding.py +++ /dev/null @@ -1,1737 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Copyright 2017 Johns Hopkins University (Shinji Watanabe) -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import copy -from dataclasses import dataclass, field -from typing import Any, Dict, List, Optional, Tuple, Union - -import numpy as np -import torch -from tqdm import tqdm - -from nemo.collections.asr.modules import rnnt_abstract -from nemo.collections.asr.parts.context_biasing import BoostingTreeModelConfig -from nemo.collections.asr.parts.submodules.ngram_lm import DEFAULT_TOKEN_OFFSET, NGramGPULanguageModel -from nemo.collections.asr.parts.submodules.rnnt_maes_batched_computer import ModifiedAESBatchedRNNTComputer -from nemo.collections.asr.parts.submodules.rnnt_malsd_batched_computer import ModifiedALSDBatchedRNNTComputer -from nemo.collections.asr.parts.utils.asr_confidence_utils import ConfidenceMethodMixin -from nemo.collections.asr.parts.utils.batched_beam_decoding_utils import BlankLMScoreMode, PruningMode -from nemo.collections.asr.parts.utils.rnnt_utils import ( - HATJointOutput, - Hypothesis, - NBestHypotheses, - is_prefix, - select_k_expansions, -) -from nemo.collections.common.parts.optional_cuda_graphs import WithOptionalCudaGraphs -from nemo.core.classes import Typing, typecheck -from nemo.core.neural_types import AcousticEncodedRepresentation, HypothesisType, LengthsType, NeuralType -from nemo.utils import logging - -try: - import kenlm - - KENLM_AVAILABLE = True -except (ImportError, ModuleNotFoundError): - KENLM_AVAILABLE = False - - -def pack_hypotheses(hypotheses: List[Hypothesis]) -> List[Hypothesis]: - """ - Packs a list of hypotheses into a tensor and prepares decoder states. - - This function takes a list of token sequences (hypotheses) and converts - it into a tensor format. If any decoder states are on the GPU, they - are moved to the CPU. Additionally, the function removes any timesteps - with a value of -1 from the sequences. - - Args: - hypotheses (list): A list of token sequences representing hypotheses. - - Returns: - list: A list of packed hypotheses in tensor format. - """ - for idx, hyp in enumerate(hypotheses): # type: rnnt_utils.Hypothesis - hyp.y_sequence = torch.tensor(hyp.y_sequence, dtype=torch.long) - - if hyp.dec_state is not None: - hyp.dec_state = _states_to_device(hyp.dec_state) - - if hyp.timestamp is not None and len(hyp.timestamp) > 0 and hyp.timestamp[0] == -1: - # Remove -1 from timestep - hyp.timestamp = hyp.timestamp[1:] - hyp.y_sequence = hyp.y_sequence[1:] # remove to have equal lengths with timestamps - - return hypotheses - - -def _states_to_device(dec_state, device='cpu'): - """ - Transfers decoder states to the specified device. - - This function moves the provided decoder states to the specified device (e.g., 'cpu' or 'cuda'). - - Args: - dec_state (Tensor): The decoder states to be transferred. - device (str): The target device to which the decoder states should be moved. Defaults to 'cpu'. - - Returns: - Tensor: The decoder states on the specified device. - """ - if torch.is_tensor(dec_state): - dec_state = dec_state.to(device) - - elif isinstance(dec_state, (list, tuple)): - dec_state = tuple(_states_to_device(dec_i, device) for dec_i in dec_state) - - return dec_state - - -class BeamRNNTInfer(Typing): - """ - Beam Search implementation ported from ESPNet implementation - - https://github.com/espnet/espnet/blob/master/espnet/nets/beam_search_transducer.py - - Sequence level beam decoding or batched-beam decoding, performed auto-repressively - depending on the search type chosen. - - Args: - decoder_model: rnnt_utils.AbstractRNNTDecoder implementation. - joint_model: rnnt_utils.AbstractRNNTJoint implementation. - - beam_size: number of beams for beam search. Must be a positive integer >= 1. - If beam size is 1, defaults to stateful greedy search. - This greedy search might result in slightly different results than - the greedy results obtained by GreedyRNNTInfer due to implementation differences. - - For accurate greedy results, please use GreedyRNNTInfer or GreedyBatchedRNNTInfer. - - search_type: str representing the type of beam search to perform. - Must be one of ['beam', 'tsd', 'alsd']. 'nsc' is currently not supported. - - Algoritm used: - - `beam` - basic beam search strategy. Larger beams generally result in better decoding, - however the time required for the search also grows steadily. - - `tsd` - time synchronous decoding. Please refer to the paper: - [Alignment-Length Synchronous Decoding for RNN Transducer] - (https://ieeexplore.ieee.org/document/9053040) - for details on the algorithm implemented. - - Time synchronous decoding (TSD) execution time grows by the factor T * max_symmetric_expansions. - For longer sequences, T is greater, and can therefore take a long time for beams to obtain - good results. This also requires greater memory to execute. - - `alsd` - alignment-length synchronous decoding. Please refer to the paper: - [Alignment-Length Synchronous Decoding for RNN Transducer] - (https://ieeexplore.ieee.org/document/9053040) - for details on the algorithm implemented. - - Alignment-length synchronous decoding (ALSD) execution time is faster than TSD, with growth - factor of T + U_max, where U_max is the maximum target length expected during execution. - - Generally, T + U_max < T * max_symmetric_expansions. However, ALSD beams are non-unique, - therefore it is required to use larger beam sizes to achieve the same (or close to the same) - decoding accuracy as TSD. - - For a given decoding accuracy, it is possible to attain faster decoding via ALSD than TSD. - - `maes` = modified adaptive expansion searcn. Please refer to the paper: - [Accelerating RNN Transducer Inference via Adaptive Expansion Search] - (https://ieeexplore.ieee.org/document/9250505) - - Modified Adaptive Synchronous Decoding (mAES) execution time is adaptive w.r.t the - number of expansions (for tokens) required per timestep. The number of expansions can usually - be constrained to 1 or 2, and in most cases 2 is sufficient. - - This beam search technique can possibly obtain superior WER while sacrificing some evaluation time. - - score_norm: bool, whether to normalize the scores of the log probabilities. - - return_best_hypothesis: bool, decides whether to return a single hypothesis (the best out of N), - or return all N hypothesis (sorted with best score first). The container class changes based - this flag - - When set to True (default), returns a single Hypothesis. - When set to False, returns a NBestHypotheses container, which contains a list of Hypothesis. - - # The following arguments are specific to the chosen `search_type` - - tsd_max_sym_exp_per_step: Used for `search_type=tsd`. The maximum symmetric expansions allowed - per timestep during beam search. Larger values should be used to attempt decoding of longer - sequences, but this in turn increases execution time and memory usage. - - alsd_max_target_len: Used for `search_type=alsd`. The maximum expected target sequence length - during beam search. Larger values allow decoding of longer sequences at the expense of - execution time and memory. - - # The following two flags are placeholders and unused until `nsc` implementation is stabilized. - nsc_max_timesteps_expansion: Unused int. - - nsc_prefix_alpha: Unused int. - - # mAES flags - maes_num_steps: Number of adaptive steps to take. From the paper, 2 steps is generally sufficient. int > 1. - - maes_prefix_alpha: Maximum prefix length in prefix search. Must be an integer, and is advised to keep this as 1 - in order to reduce expensive beam search cost later. int >= 0. - - maes_expansion_beta: Maximum number of prefix expansions allowed, in addition to the beam size. - Effectively, the number of hypothesis = beam_size + maes_expansion_beta. Must be an int >= 0, - and affects the speed of inference since large values will perform large beam search in the next step. - - maes_expansion_gamma: Float pruning threshold used in the prune-by-value step when computing the expansions. - The default (2.3) is selected from the paper. It performs a comparison - (max_log_prob - gamma <= log_prob[v]) where v is all vocabulary indices in the Vocab set and max_log_prob - is the "most" likely token to be predicted. Gamma therefore provides a margin of additional tokens which - can be potential candidates for expansion apart from the "most likely" candidate. - Lower values will reduce the number of expansions (by increasing pruning-by-value, thereby improving speed - but hurting accuracy). Higher values will increase the number of expansions (by reducing pruning-by-value, - thereby reducing speed but potentially improving accuracy). This is a hyper parameter to be experimentally - tuned on a validation set. - - softmax_temperature: Scales the logits of the joint prior to computing log_softmax. - - preserve_alignments: Bool flag which preserves the history of alignments generated during - beam decoding (sample). When set to true, the Hypothesis will contain - the non-null value for `alignments` in it. Here, `alignments` is a List of List of Tensor (of length V + 1) - - The length of the list corresponds to the Acoustic Length (T). - Each value in the list (Ti) is a torch.Tensor (U), representing 1 or more targets from a vocabulary. - U is the number of target tokens for the current timestep Ti. - - NOTE: `preserve_alignments` is an invalid argument for any `search_type` - other than basic beam search. - - ngram_lm_model: str - The path to the N-gram LM - ngram_lm_alpha: float - Alpha weight of N-gram LM - tokens_type: str - Tokenization type ['subword', 'char'] - """ - - @property - def input_types(self): - """Returns definitions of module input ports.""" - return { - "encoder_output": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), - "encoded_lengths": NeuralType(tuple('B'), LengthsType()), - "partial_hypotheses": [NeuralType(elements_type=HypothesisType(), optional=True)], # must always be last - } - - @property - def output_types(self): - """Returns definitions of module output ports.""" - return {"predictions": [NeuralType(elements_type=HypothesisType())]} - - def __init__( - self, - decoder_model: rnnt_abstract.AbstractRNNTDecoder, - joint_model: rnnt_abstract.AbstractRNNTJoint, - beam_size: int, - search_type: str = 'default', - score_norm: bool = True, - return_best_hypothesis: bool = True, - tsd_max_sym_exp_per_step: Optional[int] = 50, - alsd_max_target_len: Union[int, float] = 1.0, - nsc_max_timesteps_expansion: int = 1, - nsc_prefix_alpha: int = 1, - maes_num_steps: int = 2, - maes_prefix_alpha: int = 1, - maes_expansion_gamma: float = 2.3, - maes_expansion_beta: int = 2, - language_model: Optional[Dict[str, Any]] = None, - softmax_temperature: float = 1.0, - preserve_alignments: bool = False, - ngram_lm_model: Optional[str] = None, - ngram_lm_alpha: float = 0.0, - hat_subtract_ilm: bool = False, - hat_ilm_weight: float = 0.0, - max_symbols_per_step: Optional[int] = None, - blank_lm_score_mode: Optional[str] = "no_score", - pruning_mode: Optional[str] = "early", - allow_cuda_graphs: bool = False, - ): - self.decoder = decoder_model - self.joint = joint_model - - self.blank = decoder_model.blank_idx - self.vocab_size = decoder_model.vocab_size - self.search_type = search_type - self.return_best_hypothesis = return_best_hypothesis - - if beam_size < 1: - raise ValueError("Beam search size cannot be less than 1!") - - self.beam_size = beam_size - self.score_norm = score_norm - self.max_candidates = beam_size - - if self.beam_size == 1: - logging.info("Beam size of 1 was used, switching to sample level `greedy_search`") - self.search_algorithm = self.greedy_search - elif search_type == "default": - self.search_algorithm = self.default_beam_search - elif search_type == "tsd": - self.search_algorithm = self.time_sync_decoding - elif search_type == "alsd": - self.search_algorithm = self.align_length_sync_decoding - elif search_type == "nsc": - raise NotImplementedError("`nsc` (Constrained Beam Search) has not been implemented.") - # self.search_algorithm = self.nsc_beam_search - elif search_type == "maes": - self.search_algorithm = self.modified_adaptive_expansion_search - else: - raise NotImplementedError( - f"The search type ({search_type}) supplied is not supported!\n" - f"Please use one of : (default, tsd, alsd, nsc)" - ) - - if max_symbols_per_step is not None: - logging.warning( - f"Not supported parameter `max_symbols_per_step` for decoding strategy {self.search_algorithm }" - ) - - if allow_cuda_graphs: - logging.warning( - f"""Cuda Graphs are not supported for the decoding strategy {self.search_algorithm}. - Decoding will proceed without Cuda Graphs.""" - ) - - strategies = ["default", "tsd", "alsd", "maes", "nsc"] - strategies_batch = ["maes_batch", "malsd_batch"] - if (pruning_mode, blank_lm_score_mode) != ("early", "no_score"): - logging.warning( - f"""Decoding strategies {strategies} support early pruning and the 'no_score' blank scoring mode. - Please choose a strategy from {strategies_batch} for {pruning_mode} pruning - and {blank_lm_score_mode} blank scoring mode." - """ - ) - - if tsd_max_sym_exp_per_step is None: - tsd_max_sym_exp_per_step = -1 - - if search_type in ['tsd', 'alsd', 'nsc'] and not self.decoder.blank_as_pad: - raise ValueError( - f"Search type was chosen as '{search_type}', however the decoder module provided " - f"does not support the `blank` token as a pad value. {search_type} requires " - f"the blank token as pad value support in order to perform batched beam search." - f"Please chose one of the other beam search methods, or re-train your model " - f"with this support." - ) - - self.tsd_max_symmetric_expansion_per_step = tsd_max_sym_exp_per_step - self.alsd_max_target_length = alsd_max_target_len - self.nsc_max_timesteps_expansion = nsc_max_timesteps_expansion - self.nsc_prefix_alpha = int(nsc_prefix_alpha) - self.maes_prefix_alpha = int(maes_prefix_alpha) - self.maes_num_steps = int(maes_num_steps) - self.maes_expansion_gamma = float(maes_expansion_gamma) - self.maes_expansion_beta = int(maes_expansion_beta) - - if self.search_type == 'maes' and self.maes_prefix_alpha < 0: - raise ValueError("`maes_prefix_alpha` must be a positive integer.") - - if self.search_type == 'maes' and self.vocab_size < beam_size + maes_expansion_beta: - raise ValueError( - f"beam_size ({beam_size}) + expansion_beta ({maes_expansion_beta}) " - f"should be smaller or equal to vocabulary size ({self.vocab_size})." - ) - - if search_type == 'maes': - self.max_candidates += maes_expansion_beta - - if self.search_type == 'maes' and self.maes_num_steps < 2: - raise ValueError("`maes_num_steps` must be greater than 1.") - - if softmax_temperature != 1.0 and language_model is not None: - logging.warning( - "Softmax temperature is not supported with LM decoding." "Setting softmax-temperature value to 1.0." - ) - - self.softmax_temperature = 1.0 - else: - self.softmax_temperature = softmax_temperature - self.language_model = language_model - self.preserve_alignments = preserve_alignments - - self.token_offset = 0 - - if ngram_lm_model: - self.ngram_lm = ngram_lm_model - self.ngram_lm_alpha = ngram_lm_alpha - else: - self.ngram_lm = None - - if hat_subtract_ilm: - assert hasattr(self.joint, "return_hat_ilm") - assert search_type == "maes" - self.hat_subtract_ilm = hat_subtract_ilm - self.hat_ilm_weight = hat_ilm_weight - - @typecheck() - def __call__( - self, - encoder_output: torch.Tensor, - encoded_lengths: torch.Tensor, - partial_hypotheses: Optional[List[Hypothesis]] = None, - ) -> Union[Hypothesis, NBestHypotheses]: - """Perform general beam search. - - Args: - encoder_output: Encoded speech features (B, D_enc, T_max) - encoded_lengths: Lengths of the encoder outputs - - Returns: - Either a list containing a single Hypothesis (when `return_best_hypothesis=True`, - otherwise a list containing a single NBestHypotheses, which itself contains a list of - Hypothesis. This list is sorted such that the best hypothesis is the first element. - """ - # Preserve decoder and joint training state - decoder_training_state = self.decoder.training - joint_training_state = self.joint.training - - # setup hat outputs mode - return_hat_ilm_default = False - if self.hat_subtract_ilm: - assert hasattr(self.joint, "return_hat_ilm") - return_hat_ilm_default = self.joint.return_hat_ilm - self.joint.return_hat_ilm = self.hat_subtract_ilm - - with torch.inference_mode(): - # Apply optional preprocessing - encoder_output = encoder_output.transpose(1, 2) # (B, T, D) - - self.decoder.eval() - self.joint.eval() - - hypotheses = [] - with tqdm( - range(encoder_output.size(0)), - desc='Beam search progress:', - total=encoder_output.size(0), - unit='sample', - ) as idx_gen: - - _p = next(self.joint.parameters()) - dtype = _p.dtype - - # Decode every sample in the batch independently. - for batch_idx in idx_gen: - inseq = encoder_output[batch_idx : batch_idx + 1, : encoded_lengths[batch_idx], :] # [1, T, D] - logitlen = encoded_lengths[batch_idx] - - if inseq.dtype != dtype: - inseq = inseq.to(dtype=dtype) - - # Extract partial hypothesis if exists - partial_hypothesis = partial_hypotheses[batch_idx] if partial_hypotheses is not None else None - - # Execute the specific search strategy - nbest_hyps = self.search_algorithm( - inseq, logitlen, partial_hypotheses=partial_hypothesis - ) # sorted list of hypothesis - - # Prepare the list of hypotheses - nbest_hyps = pack_hypotheses(nbest_hyps) - - # Pack the result - if self.return_best_hypothesis: - best_hypothesis = nbest_hyps[0] # type: Hypothesis - else: - best_hypothesis = NBestHypotheses(nbest_hyps) # type: NBestHypotheses - hypotheses.append(best_hypothesis) - - self.decoder.train(decoder_training_state) - self.joint.train(joint_training_state) - if self.hat_subtract_ilm: - self.joint.return_hat_ilm = return_hat_ilm_default - - return (hypotheses,) - - def sort_nbest(self, hyps: List[Hypothesis]) -> List[Hypothesis]: - """Sort hypotheses by score or score given sequence length. - - Args: - hyps: list of hypotheses - - Return: - hyps: sorted list of hypotheses - """ - if self.score_norm: - return sorted(hyps, key=lambda x: x.score / len(x.y_sequence), reverse=True) - else: - return sorted(hyps, key=lambda x: x.score, reverse=True) - - def greedy_search( - self, h: torch.Tensor, encoded_lengths: torch.Tensor, partial_hypotheses: Optional[Hypothesis] = None - ) -> List[Hypothesis]: - """Greedy search implementation for transducer. - Generic case when beam size = 1. Results might differ slightly due to implementation details - as compared to `GreedyRNNTInfer` and `GreedyBatchRNNTInfer`. - - Args: - h: Encoded speech features (1, T_max, D_enc) - - Returns: - hyp: 1-best decoding results - """ - if self.preserve_alignments: - # Alignments is a 2-dimensional dangling list representing T x U - alignments = [[]] - else: - alignments = None - - # Initialize zero state vectors - dec_state = self.decoder.initialize_state(h) - - # Construct initial hypothesis - hyp = Hypothesis( - score=0.0, y_sequence=[self.blank], dec_state=dec_state, timestamp=[-1], length=encoded_lengths - ) - - if partial_hypotheses is not None: - if len(partial_hypotheses.y_sequence) > 0: - hyp.y_sequence = [int(partial_hypotheses.y_sequence[-1].cpu().numpy())] - hyp.dec_state = partial_hypotheses.dec_state - hyp.dec_state = _states_to_device(hyp.dec_state, h.device) - - cache = {} - - # Initialize state and first token - y, state, _ = self.decoder.score_hypothesis(hyp, cache) - - for i in range(int(encoded_lengths)): - hi = h[:, i : i + 1, :] # [1, 1, D] - - not_blank = True - symbols_added = 0 - - # TODO: Figure out how to remove this hard coding afterwords - while not_blank and (symbols_added < 5): - ytu = torch.log_softmax(self.joint.joint(hi, y) / self.softmax_temperature, dim=-1) # [1, 1, 1, V + 1] - ytu = ytu[0, 0, 0, :] # [V + 1] - - # max() requires float - if ytu.dtype != torch.float32: - ytu = ytu.float() - - logp, pred = torch.max(ytu, dim=-1) # [1, 1] - pred = pred.item() - - if self.preserve_alignments: - # insert logprobs into last timestep - alignments[-1].append((ytu.to('cpu'), torch.tensor(pred, dtype=torch.int32))) - - if pred == self.blank: - not_blank = False - - if self.preserve_alignments: - # convert Ti-th logits into a torch array - alignments.append([]) # blank buffer for next timestep - else: - # Update state and current sequence - hyp.y_sequence.append(int(pred)) - hyp.score += float(logp) - hyp.dec_state = state - hyp.timestamp.append(i) - - # Compute next state and token - y, state, _ = self.decoder.score_hypothesis(hyp, cache) - symbols_added += 1 - - # Remove trailing empty list of alignments - if self.preserve_alignments: - if len(alignments[-1]) == 0: - del alignments[-1] - - # attach alignments to hypothesis - hyp.alignments = alignments - - # Remove the original input label if partial hypothesis was provided - if partial_hypotheses is not None: - hyp.y_sequence = hyp.y_sequence[1:] - - return [hyp] - - def default_beam_search( - self, h: torch.Tensor, encoded_lengths: torch.Tensor, partial_hypotheses: Optional[Hypothesis] = None - ) -> List[Hypothesis]: - """Beam search implementation. - - Args: - x: Encoded speech features (1, T_max, D_enc) - - Returns: - nbest_hyps: N-best decoding results - """ - # Initialize states - beam = min(self.beam_size, self.vocab_size) - beam_k = min(beam, (self.vocab_size - 1)) - blank_tensor = torch.tensor([self.blank], device=h.device, dtype=torch.long) - - # Precompute some constants for blank position - ids = list(range(self.vocab_size + 1)) - ids.remove(self.blank) - - # Used when blank token is first vs last token - if self.blank == 0: - index_incr = 1 - else: - index_incr = 0 - - # Initialize zero vector states - dec_state = self.decoder.initialize_state(h) - - # Initialize first hypothesis for the beam (blank) - kept_hyps = [Hypothesis(score=0.0, y_sequence=[self.blank], dec_state=dec_state, timestamp=[-1], length=0)] - cache = {} - - if partial_hypotheses is not None: - if len(partial_hypotheses.y_sequence) > 0: - kept_hyps[0].y_sequence = [int(partial_hypotheses.y_sequence[-1].cpu().numpy())] - kept_hyps[0].dec_state = partial_hypotheses.dec_state - kept_hyps[0].dec_state = _states_to_device(kept_hyps[0].dec_state, h.device) - - if self.preserve_alignments: - kept_hyps[0].alignments = [[]] - - for i in range(int(encoded_lengths)): - hi = h[:, i : i + 1, :] # [1, 1, D] - hyps = kept_hyps - kept_hyps = [] - - while True: - max_hyp = max(hyps, key=lambda x: x.score) - hyps.remove(max_hyp) - - # update decoder state and get next score - y, state, lm_tokens = self.decoder.score_hypothesis(max_hyp, cache) # [1, 1, D] - - # get next token - ytu = torch.log_softmax(self.joint.joint(hi, y) / self.softmax_temperature, dim=-1) # [1, 1, 1, V + 1] - ytu = ytu[0, 0, 0, :] # [V + 1] - - # preserve alignments - if self.preserve_alignments: - logprobs = ytu.cpu().clone() - - # remove blank token before top k - top_k = ytu[ids].topk(beam_k, dim=-1) - - # Two possible steps - blank token or non-blank token predicted - ytu = ( - torch.cat((top_k[0], ytu[self.blank].unsqueeze(0))), - torch.cat((top_k[1] + index_incr, blank_tensor)), - ) - - # for each possible step - for logp, k in zip(*ytu): - # construct hypothesis for step - new_hyp = Hypothesis( - score=(max_hyp.score + float(logp)), - y_sequence=max_hyp.y_sequence[:], - dec_state=max_hyp.dec_state, - lm_state=max_hyp.lm_state, - timestamp=max_hyp.timestamp[:], - length=encoded_lengths, - ) - - if self.preserve_alignments: - new_hyp.alignments = copy.deepcopy(max_hyp.alignments) - - # if current token is blank, dont update sequence, just store the current hypothesis - if k == self.blank: - kept_hyps.append(new_hyp) - else: - # if non-blank token was predicted, update state and sequence and then search more hypothesis - new_hyp.dec_state = state - new_hyp.y_sequence.append(int(k)) - new_hyp.timestamp.append(i) - - hyps.append(new_hyp) - - # Determine whether the alignment should be blank or token - if self.preserve_alignments: - if k == self.blank: - new_hyp.alignments[-1].append( - (logprobs.clone(), torch.tensor(self.blank, dtype=torch.int32)) - ) - else: - new_hyp.alignments[-1].append( - (logprobs.clone(), torch.tensor(new_hyp.y_sequence[-1], dtype=torch.int32)) - ) - - # keep those hypothesis that have scores greater than next search generation - hyps_max = float(max(hyps, key=lambda x: x.score).score) - kept_most_prob = sorted( - [hyp for hyp in kept_hyps if hyp.score > hyps_max], - key=lambda x: x.score, - ) - - # If enough hypothesis have scores greater than next search generation, - # stop beam search. - if len(kept_most_prob) >= beam: - if self.preserve_alignments: - # convert Ti-th logits into a torch array - for kept_h in kept_most_prob: - kept_h.alignments.append([]) # blank buffer for next timestep - - kept_hyps = kept_most_prob - break - - # Remove trailing empty list of alignments - if self.preserve_alignments: - for h in kept_hyps: - if len(h.alignments[-1]) == 0: - del h.alignments[-1] - - # Remove the original input label if partial hypothesis was provided - if partial_hypotheses is not None: - for hyp in kept_hyps: - if hyp.y_sequence[0] == partial_hypotheses.y_sequence[-1] and len(hyp.y_sequence) > 1: - hyp.y_sequence = hyp.y_sequence[1:] - - return self.sort_nbest(kept_hyps) - - def time_sync_decoding( - self, h: torch.Tensor, encoded_lengths: torch.Tensor, partial_hypotheses: Optional[Hypothesis] = None - ) -> List[Hypothesis]: - """Time synchronous beam search implementation. - Based on https://ieeexplore.ieee.org/document/9053040 - - Args: - h: Encoded speech features (1, T_max, D_enc) - - Returns: - nbest_hyps: N-best decoding results - """ - if partial_hypotheses is not None: - raise NotImplementedError("`partial_hypotheses` support is not supported") - - # Precompute some constants for blank position - ids = list(range(self.vocab_size + 1)) - ids.remove(self.blank) - - # Used when blank token is first vs last token - if self.blank == 0: - index_incr = 1 - else: - index_incr = 0 - - # prepare the batched beam states - beam = min(self.beam_size, self.vocab_size) - beam_state = self.decoder.initialize_state( - torch.zeros(beam, device=h.device, dtype=h.dtype) - ) # [L, B, H], [L, B, H] (for LSTMs) - - # Initialize first hypothesis for the beam (blank) - B = [ - Hypothesis( - y_sequence=[self.blank], - score=0.0, - dec_state=self.decoder.batch_select_state(beam_state, 0), - timestamp=[-1], - length=0, - ) - ] - cache = {} - - # Initialize alignments - if self.preserve_alignments: - for hyp in B: - hyp.alignments = [[]] - - for i in range(int(encoded_lengths)): - hi = h[:, i : i + 1, :] - - # Update caches - A = [] - C = B - - h_enc = hi - - # For a limited number of symmetric expansions per timestep "i" - for v in range(self.tsd_max_symmetric_expansion_per_step): - D = [] - - # Decode a batch of beam states and scores - beam_y, beam_state = self.decoder.batch_score_hypothesis(C, cache) - - # Extract the log probabilities and the predicted tokens - beam_logp = torch.log_softmax( - self.joint.joint(h_enc, torch.stack(beam_y)) / self.softmax_temperature, dim=-1 - ) # [B, 1, 1, V + 1] - beam_logp = beam_logp[:, 0, 0, :] # [B, V + 1] - beam_topk = beam_logp[:, ids].topk(beam, dim=-1) - - seq_A = [h.y_sequence for h in A] - - for j, hyp in enumerate(C): - # create a new hypothesis in A - if hyp.y_sequence not in seq_A: - # If the sequence is not in seq_A, add it as the blank token - # In this step, we dont add a token but simply update score - _temp_hyp = Hypothesis( - score=(hyp.score + float(beam_logp[j, self.blank])), - y_sequence=hyp.y_sequence[:], - dec_state=hyp.dec_state, - lm_state=hyp.lm_state, - timestamp=hyp.timestamp[:], - length=encoded_lengths, - ) - - # Preserve the blank token alignment - if self.preserve_alignments: - _temp_hyp.alignments = copy.deepcopy(hyp.alignments) - _temp_hyp.alignments[-1].append( - (beam_logp[j].clone(), torch.tensor(self.blank, dtype=torch.int32)), - ) - - A.append(_temp_hyp) - else: - # merge the existing blank hypothesis score with current score. - dict_pos = seq_A.index(hyp.y_sequence) - - A[dict_pos].score = np.logaddexp( - A[dict_pos].score, (hyp.score + float(beam_logp[j, self.blank])) - ) - - if v < self.tsd_max_symmetric_expansion_per_step: - for j, hyp in enumerate(C): - # for each current hypothesis j - # extract the top token score and top token id for the jth hypothesis - for logp, k in zip(beam_topk[0][j], beam_topk[1][j] + index_incr): - # create new hypothesis and store in D - # Note: This loop does *not* include the blank token! - new_hyp = Hypothesis( - score=(hyp.score + float(logp)), - y_sequence=(hyp.y_sequence + [int(k)]), - dec_state=beam_state[j], - lm_state=hyp.lm_state, - timestamp=hyp.timestamp[:] + [i], - length=encoded_lengths, - ) - - # Preserve token alignment - if self.preserve_alignments: - new_hyp.alignments = copy.deepcopy(hyp.alignments) - new_hyp.alignments[-1].append( - (beam_topk[0].clone().cpu(), torch.tensor(k, dtype=torch.int32)), - ) - - D.append(new_hyp) - - # Prune beam - C = sorted(D, key=lambda x: x.score, reverse=True)[:beam] - - if self.preserve_alignments: - # convert Ti-th logits into a torch array - for C_i in C: - # Check if the last token emitted at last timestep was a blank - # If so, move to next timestep - logp, label = C_i.alignments[-1][-1] # The last alignment of this step - if int(label) == self.blank: - C_i.alignments.append([]) # blank buffer for next timestep - - # Prune beam - B = sorted(A, key=lambda x: x.score, reverse=True)[:beam] - - if self.preserve_alignments: - # convert Ti-th logits into a torch array - for B_i in B: - # Check if the last token emitted at last timestep was a blank - # If so, move to next timestep - logp, label = B_i.alignments[-1][-1] # The last alignment of this step - if int(label) == self.blank: - B_i.alignments.append([]) # blank buffer for next timestep - - # Remove trailing empty list of alignments - if self.preserve_alignments: - for h in B: - if len(h.alignments[-1]) == 0: - del h.alignments[-1] - - return self.sort_nbest(B) - - def align_length_sync_decoding( - self, h: torch.Tensor, encoded_lengths: torch.Tensor, partial_hypotheses: Optional[Hypothesis] = None - ) -> List[Hypothesis]: - """Alignment-length synchronous beam search implementation. - Based on https://ieeexplore.ieee.org/document/9053040 - - Args: - h: Encoded speech features (1, T_max, D_enc) - - Returns: - nbest_hyps: N-best decoding results - """ - # delay this import here instead of at the beginning to avoid circular imports. - from nemo.collections.asr.modules.rnnt import RNNTDecoder, StatelessTransducerDecoder - - if partial_hypotheses is not None: - raise NotImplementedError("`partial_hypotheses` support is not supported") - - # Precompute some constants for blank position - ids = list(range(self.vocab_size + 1)) - ids.remove(self.blank) - - # Used when blank token is first vs last token - if self.blank == 0: - index_incr = 1 - else: - index_incr = 0 - - # prepare the batched beam states - beam = min(self.beam_size, self.vocab_size) - - h = h[0] # [T, D] - h_length = int(encoded_lengths) - beam_state = self.decoder.initialize_state( - torch.zeros(beam, device=h.device, dtype=h.dtype) - ) # [L, B, H], [L, B, H] for LSTMS - beam_state = [self.decoder.batch_select_state(beam_state, 0)] - - # compute u_max as either a specific static limit, - # or a multiple of current `h_length` dynamically. - if type(self.alsd_max_target_length) == float: - u_max = int(self.alsd_max_target_length * h_length) - else: - u_max = int(self.alsd_max_target_length) - - # Initialize first hypothesis for the beam (blank) - B = [ - Hypothesis( - y_sequence=[self.blank], - score=0.0, - dec_state=beam_state[0], - timestamp=[-1], - length=0, - ) - ] - - # Initialize alignments - if self.preserve_alignments: - B[0].alignments = [[]] - - final = [] - cache = {} - - # ALSD runs for T + U_max steps - for i in range(h_length + u_max): - # Update caches - A = [] - B_ = [] - h_states = [] - - # preserve the list of batch indices which are added into the list - # and those which are removed from the list - # This is necessary to perform state updates in the correct batch indices later - batch_ids = list(range(len(B))) # initialize as a list of all batch ids - batch_removal_ids = [] # update with sample ids which are removed - - for bid, hyp in enumerate(B): - u = len(hyp.y_sequence) - 1 - t = i - u - - if t > (h_length - 1): - batch_removal_ids.append(bid) - continue - - B_.append(hyp) - h_states.append((t, h[t])) - - if B_: - # Compute the subset of batch ids which were *not* removed from the list above - sub_batch_ids = None - if len(B_) != beam: - sub_batch_ids = batch_ids - for id in batch_removal_ids: - # sub_batch_ids contains list of ids *that were not removed* - sub_batch_ids.remove(id) - - # extract the states of the sub batch only. - if isinstance(self.decoder, RNNTDecoder) or isinstance(self.decoder, StatelessTransducerDecoder): - beam_state_ = (beam_state[sub_batch_id] for sub_batch_id in sub_batch_ids) - else: - raise NotImplementedError("Unknown decoder type.") - - else: - # If entire batch was used (none were removed), simply take all the states - beam_state_ = beam_state - - # Decode a batch/sub-batch of beam states and scores - beam_y, beam_state_ = self.decoder.batch_score_hypothesis(B_, cache) - - # If only a subset of batch ids were updated (some were removed) - if sub_batch_ids is not None: - # For each state in the RNN (2 for LSTM) - # Update the current batch states with the sub-batch states (in the correct indices) - # These indices are specified by sub_batch_ids, the ids of samples which were updated. - if isinstance(self.decoder, RNNTDecoder) or isinstance(self.decoder, StatelessTransducerDecoder): - # LSTM decoder, state is [layer x batch x hidden] - index = 0 - for sub_batch_id in sub_batch_ids: - beam_state[sub_batch_id] = beam_state_[index] - index += 1 - else: - raise NotImplementedError("Unknown decoder type.") - else: - # If entire batch was updated, simply update all the states - beam_state = beam_state_ - - # h_states = list of [t, h[t]] - # so h[1] here is a h[t] of shape [D] - # Simply stack all of the h[t] within the sub_batch/batch (T <= beam) - h_enc = torch.stack([h[1] for h in h_states]) # [T=beam, D] - h_enc = h_enc.unsqueeze(1) # [B=beam, T=1, D]; batch over the beams - - # Extract the log probabilities and the predicted tokens - beam_logp = torch.log_softmax( - self.joint.joint(h_enc, torch.stack(beam_y)) / self.softmax_temperature, dim=-1 - ) # [B=beam, 1, 1, V + 1] - beam_logp = beam_logp[:, 0, 0, :] # [B=beam, V + 1] - beam_topk = beam_logp[:, ids].topk(beam, dim=-1) - - for j, hyp in enumerate(B_): - # For all updated samples in the batch, add it as the blank token - # In this step, we dont add a token but simply update score - new_hyp = Hypothesis( - score=(hyp.score + float(beam_logp[j, self.blank])), - y_sequence=hyp.y_sequence[:], - dec_state=hyp.dec_state, - lm_state=hyp.lm_state, - timestamp=hyp.timestamp[:], - length=i, - ) - - if self.preserve_alignments: - new_hyp.alignments = copy.deepcopy(hyp.alignments) - - # Add the alignment of blank at this step - new_hyp.alignments[-1].append( - (beam_logp[j].clone().cpu(), torch.tensor(self.blank, dtype=torch.int32)) - ) - - # Add blank prediction to A - A.append(new_hyp) - - # If the prediction "timestep" t has reached the length of the input sequence - # we can add it to the "finished" hypothesis list. - if h_states[j][0] == (h_length - 1): - final.append(new_hyp) - - # Here, we carefully select the indices of the states that we want to preserve - # for the next token (non-blank) update. - if sub_batch_ids is not None: - h_states_idx = sub_batch_ids[j] - else: - h_states_idx = j - - # for each current hypothesis j - # extract the top token score and top token id for the jth hypothesis - for logp, k in zip(beam_topk[0][j], beam_topk[1][j] + index_incr): - # create new hypothesis and store in A - # Note: This loop does *not* include the blank token! - new_hyp = Hypothesis( - score=(hyp.score + float(logp)), - y_sequence=(hyp.y_sequence[:] + [int(k)]), - dec_state=beam_state[h_states_idx], - lm_state=hyp.lm_state, - timestamp=hyp.timestamp[:] + [i], - length=i, - ) - - if self.preserve_alignments: - new_hyp.alignments = copy.deepcopy(hyp.alignments) - - # Add the alignment of Uj for this beam candidate at this step - new_hyp.alignments[-1].append( - (beam_logp[j].clone().cpu(), torch.tensor(new_hyp.y_sequence[-1], dtype=torch.int32)) - ) - - A.append(new_hyp) - - # Prune and recombine same hypothesis - # This may cause next beam to be smaller than max beam size - # Therefore larger beam sizes may be required for better decoding. - B = sorted(A, key=lambda x: x.score, reverse=True)[:beam] - B = self.recombine_hypotheses(B) - - if self.preserve_alignments: - # convert Ti-th logits into a torch array - for B_i in B: - # Check if the last token emitted at last timestep was a blank - # If so, move to next timestep - logp, label = B_i.alignments[-1][-1] # The last alignment of this step - if int(label) == self.blank: - B_i.alignments.append([]) # blank buffer for next timestep - - # If B_ is empty list, then we may be able to early exit - elif len(batch_ids) == len(batch_removal_ids): - # break early - break - - if final: - # Remove trailing empty list of alignments - if self.preserve_alignments: - for h in final: - if len(h.alignments[-1]) == 0: - del h.alignments[-1] - - return self.sort_nbest(final) - else: - # Remove trailing empty list of alignments - if self.preserve_alignments: - for h in B: - if len(h.alignments[-1]) == 0: - del h.alignments[-1] - - return B - - def modified_adaptive_expansion_search( - self, h: torch.Tensor, encoded_lengths: torch.Tensor, partial_hypotheses: Optional[Hypothesis] = None - ) -> List[Hypothesis]: - """ - Based on/modified from https://ieeexplore.ieee.org/document/9250505 - - Args: - h: Encoded speech features (1, T_max, D_enc) - - Returns: - nbest_hyps: N-best decoding results - """ - if partial_hypotheses is not None: - raise NotImplementedError("`partial_hypotheses` support is not supported") - - h = h[0] # [T, D] - - # prepare the batched beam states - beam = min(self.beam_size, self.vocab_size) - beam_state = self.decoder.initialize_state( - torch.zeros(1, device=h.device, dtype=h.dtype) - ) # [L, B, H], [L, B, H] for LSTMS - - # Initialize first hypothesis for the beam (blank) - init_tokens = [ - Hypothesis( - y_sequence=[self.blank], - score=0.0, - dec_state=self.decoder.batch_select_state(beam_state, 0), - timestamp=[-1], - length=0, - ) - ] - - cache = {} - - # Initialize alignment buffer - if self.preserve_alignments: - for hyp in init_tokens: - hyp.alignments = [[]] - - # Decode a batch of beam states and scores - beam_dec_out, beam_state = self.decoder.batch_score_hypothesis(init_tokens, cache) - state = beam_state[0] - - # Setup ngram LM: - if self.ngram_lm: - init_lm_state = kenlm.State() - self.ngram_lm.BeginSentenceWrite(init_lm_state) - - # TODO: Setup LM - if self.language_model is not None: - # beam_lm_states, beam_lm_scores = self.lm.buff_predict( - # None, beam_lm_tokens, 1 - # ) - # lm_state = select_lm_state( - # beam_lm_states, 0, self.lm_layers, self.is_wordlm - # ) - # lm_scores = beam_lm_scores[0] - raise NotImplementedError() - else: - lm_state = None - lm_scores = None - - # Initialize first hypothesis for the beam (blank) for kept hypotheses - kept_hyps = [ - Hypothesis( - y_sequence=[self.blank], - score=0.0, - dec_state=state, - dec_out=[beam_dec_out[0]], - lm_state=lm_state, - lm_scores=lm_scores, - timestamp=[-1], - length=0, - ) - ] - if self.ngram_lm: - kept_hyps[0].ngram_lm_state = init_lm_state - - # Initialize alignment buffer - if self.preserve_alignments: - for hyp in kept_hyps: - hyp.alignments = [[]] - - for t in range(encoded_lengths): - enc_out_t = h[t : t + 1].unsqueeze(0) # [1, 1, D] - - # Perform prefix search to obtain hypothesis - hyps = self.prefix_search( - sorted(kept_hyps, key=lambda x: len(x.y_sequence), reverse=True), - enc_out_t, - prefix_alpha=self.maes_prefix_alpha, - ) # type: List[Hypothesis] - kept_hyps = [] - - # Prepare output tensor - beam_enc_out = enc_out_t - - # List that contains the blank token emisions - list_b = [] - duplication_check = [hyp.y_sequence for hyp in hyps] - - # Repeat for number of mAES steps - for n in range(self.maes_num_steps): - # Pack the decoder logits for all current hypothesis - beam_dec_out = torch.stack([h.dec_out[-1] for h in hyps]) # [H, 1, D] - - # Extract the log probabilities - ytm, ilm_ytm = self.resolve_joint_output(beam_enc_out, beam_dec_out) - beam_logp, beam_idx = ytm.topk(self.max_candidates, dim=-1) - - beam_logp = beam_logp[:, 0, 0, :] # [B, V + 1] - beam_idx = beam_idx[:, 0, 0, :] # [B, max_candidates] - - # Compute k expansions for all the current hypotheses - k_expansions = select_k_expansions( - hyps, beam_idx, beam_logp, self.maes_expansion_gamma, self.maes_expansion_beta - ) - - # List that contains the hypothesis after prefix expansion - list_exp = [] - for i, hyp in enumerate(hyps): # For all hypothesis - for k, new_score in k_expansions[i]: # for all expansion within these hypothesis - new_hyp = Hypothesis( - y_sequence=hyp.y_sequence[:], - score=new_score, - dec_out=hyp.dec_out[:], - dec_state=hyp.dec_state, - lm_state=hyp.lm_state, - lm_scores=hyp.lm_scores, - timestamp=hyp.timestamp[:], - length=t, - ) - if self.ngram_lm: - new_hyp.ngram_lm_state = hyp.ngram_lm_state - - # If the expansion was for blank - if k == self.blank: - list_b.append(new_hyp) - else: - # If the expansion was a token - # new_hyp.y_sequence.append(int(k)) - if (new_hyp.y_sequence + [int(k)]) not in duplication_check: - new_hyp.y_sequence.append(int(k)) - new_hyp.timestamp.append(t) - - # Setup ngram LM: - if self.ngram_lm: - lm_score, new_hyp.ngram_lm_state = self.compute_ngram_score( - hyp.ngram_lm_state, int(k) - ) - if self.hat_subtract_ilm: - new_hyp.score += self.ngram_lm_alpha * lm_score - float( - self.hat_ilm_weight * ilm_ytm[i, 0, 0, k] - ) - else: - new_hyp.score += self.ngram_lm_alpha * lm_score - - # TODO: Setup LM - if self.language_model is not None: - # new_hyp.score += self.lm_weight * float( - # hyp.lm_scores[k] - # ) - pass - - list_exp.append(new_hyp) - - # Preserve alignments - if self.preserve_alignments: - new_hyp.alignments = copy.deepcopy(hyp.alignments) - - if k == self.blank: - new_hyp.alignments[-1].append( - (beam_logp[i].clone().cpu(), torch.tensor(self.blank, dtype=torch.int32)), - ) - else: - new_hyp.alignments[-1].append( - ( - beam_logp[i].clone().cpu(), - torch.tensor(new_hyp.y_sequence[-1], dtype=torch.int32), - ), - ) - - # If there were no token expansions in any of the hypotheses, - # Early exit - if not list_exp: - kept_hyps = sorted(list_b, key=lambda x: x.score, reverse=True)[:beam] - - # Update aligments with next step - if self.preserve_alignments: - # convert Ti-th logits into a torch array - for h_i in kept_hyps: - # Check if the last token emitted at last timestep was a blank - # If so, move to next timestep - logp, label = h_i.alignments[-1][-1] # The last alignment of this step - if int(label) == self.blank: - h_i.alignments.append([]) # blank buffer for next timestep - - # Early exit - break - - else: - # Decode a batch of beam states and scores - beam_dec_out, beam_state = self.decoder.batch_score_hypothesis( - list_exp, - cache, - # self.language_model is not None, - ) - - # TODO: Setup LM - if self.language_model is not None: - # beam_lm_states = create_lm_batch_states( - # [hyp.lm_state for hyp in list_exp], - # self.lm_layers, - # self.is_wordlm, - # ) - # beam_lm_states, beam_lm_scores = self.lm.buff_predict( - # beam_lm_states, beam_lm_tokens, len(list_exp) - # ) - pass - - # If this isnt the last mAES step - if n < (self.maes_num_steps - 1): - # For all expanded hypothesis - for i, hyp in enumerate(list_exp): - # Preserve the decoder logits for the current beam - hyp.dec_out.append(beam_dec_out[i]) - hyp.dec_state = beam_state[i] - - # TODO: Setup LM - if self.language_model is not None: - # hyp.lm_state = select_lm_state( - # beam_lm_states, i, self.lm_layers, self.is_wordlm - # ) - # hyp.lm_scores = beam_lm_scores[i] - pass - - # Copy the expanded hypothesis - hyps = list_exp[:] - - # Update aligments with next step - if self.preserve_alignments: - # convert Ti-th logits into a torch array - for h_i in hyps: - # Check if the last token emitted at last timestep was a blank - # If so, move to next timestep - logp, label = h_i.alignments[-1][-1] # The last alignment of this step - if int(label) == self.blank: - h_i.alignments.append([]) # blank buffer for next timestep - - else: - # Extract the log probabilities - beam_logp, _ = self.resolve_joint_output(beam_enc_out, torch.stack(beam_dec_out)) - beam_logp = beam_logp[:, 0, 0, :] - - # For all expansions, add the score for the blank label - for i, hyp in enumerate(list_exp): - hyp.score += float(beam_logp[i, self.blank]) - - # Preserve the decoder's output and state - hyp.dec_out.append(beam_dec_out[i]) - hyp.dec_state = beam_state[i] - - # TODO: Setup LM - if self.language_model is not None: - # hyp.lm_state = select_lm_state( - # beam_lm_states, i, self.lm_layers, self.is_wordlm - # ) - # hyp.lm_scores = beam_lm_scores[i] - pass - - # Finally, update the kept hypothesis of sorted top Beam candidates - kept_hyps = sorted(list_b + list_exp, key=lambda x: x.score, reverse=True)[:beam] - - # Update aligments with next step - if self.preserve_alignments: - # convert Ti-th logits into a torch array - for h_i in kept_hyps: - # Check if the last token emitted at last timestep was a blank - # If so, move to next timestep - logp, label = h_i.alignments[-1][-1] # The last alignment of this step - if int(label) == self.blank: - h_i.alignments.append([]) # blank buffer for next timestep - - # Remove trailing empty list of alignments - if self.preserve_alignments: - for h in kept_hyps: - if len(h.alignments[-1]) == 0: - del h.alignments[-1] - - # Sort the hypothesis with best scores - return self.sort_nbest(kept_hyps) - - def recombine_hypotheses(self, hypotheses: List[Hypothesis]) -> List[Hypothesis]: - """Recombine hypotheses with equivalent output sequence. - - Args: - hypotheses (list): list of hypotheses - - Returns: - final (list): list of recombined hypotheses - """ - final = [] - - for hyp in hypotheses: - seq_final = [f.y_sequence for f in final if f.y_sequence] - - if hyp.y_sequence in seq_final: - seq_pos = seq_final.index(hyp.y_sequence) - - final[seq_pos].score = np.logaddexp(final[seq_pos].score, hyp.score) - else: - final.append(hyp) - - return final - - def resolve_joint_output(self, enc_out: torch.Tensor, dec_out: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: - """ - Resolve output types for RNNT and HAT joint models - """ - - joint_output = self.joint.joint(enc_out, dec_out) - if torch.is_tensor(joint_output): - ytm = torch.log_softmax(joint_output / self.softmax_temperature, dim=-1) - ilm_ytm = None - elif self.hat_subtract_ilm and isinstance(joint_output, HATJointOutput): - ytm, ilm_ytm = joint_output.hat_logprobs, joint_output.ilm_logprobs - else: - raise TypeError( - f"Joint output ({type(joint_output)}) must be torch.Tensor or HATJointOutput in case of HAT joint" - ) - - return ytm, ilm_ytm - - def prefix_search( - self, hypotheses: List[Hypothesis], enc_out: torch.Tensor, prefix_alpha: int - ) -> List[Hypothesis]: - """ - Prefix search for NSC and mAES strategies. - Based on https://arxiv.org/pdf/1211.3711.pdf - """ - - for j, hyp_j in enumerate(hypotheses[:-1]): - for hyp_i in hypotheses[(j + 1) :]: - curr_id = len(hyp_j.y_sequence) - pref_id = len(hyp_i.y_sequence) - - if is_prefix(hyp_j.y_sequence, hyp_i.y_sequence) and (curr_id - pref_id) <= prefix_alpha: - logp, ilm_logp = self.resolve_joint_output(enc_out, hyp_i.dec_out[-1]) - logp = logp[0, 0, 0, :] - curr_score = hyp_i.score + float(logp[hyp_j.y_sequence[pref_id]]) - # Setup ngram LM: - if self.ngram_lm: - lm_score, next_state = self.compute_ngram_score( - hyp_i.ngram_lm_state, int(hyp_j.y_sequence[pref_id]) - ) - if self.hat_subtract_ilm: - curr_score += self.ngram_lm_alpha * lm_score - self.hat_ilm_weight * float( - ilm_logp[0, 0, hyp_j.y_sequence[pref_id]] - ) - else: - curr_score += self.ngram_lm_alpha * lm_score - - for k in range(pref_id, (curr_id - 1)): - logp, ilm_logp = self.resolve_joint_output(enc_out, hyp_j.dec_out[k]) - logp = logp[0, 0, 0, :] - curr_score += float(logp[hyp_j.y_sequence[k + 1]]) - # Setup ngram LM: - if self.ngram_lm: - lm_score, next_state = self.compute_ngram_score(next_state, int(hyp_j.y_sequence[k + 1])) - if self.hat_subtract_ilm: - curr_score += self.ngram_lm_alpha * lm_score - self.hat_ilm_weight * float( - ilm_logp[0, 0, hyp_j.y_sequence[k + 1]] - ) - else: - curr_score += self.ngram_lm_alpha * lm_score - - hyp_j.score = np.logaddexp(hyp_j.score, curr_score) - - return hypotheses - - def compute_ngram_score(self, current_lm_state: "kenlm.State", label: int) -> Tuple[float, "kenlm.State"]: - """ - Score computation for kenlm ngram language model. - """ - - if self.token_offset: - label = chr(label + self.token_offset) - else: - label = str(label) - next_state = kenlm.State() - lm_score = self.ngram_lm.BaseScore(current_lm_state, label, next_state) - lm_score *= 1.0 / np.log10(np.e) - - return lm_score, next_state - - def set_decoding_type(self, decoding_type: str): - """ - Sets decoding type. Please check train_kenlm.py in scripts/asr_language_modeling/ to find out why we need - Args: - decoding_type: decoding type - """ - # TOKEN_OFFSET for BPE-based models - if decoding_type == 'subword': - self.token_offset = DEFAULT_TOKEN_OFFSET - - -class BeamBatchedRNNTInfer(Typing, ConfidenceMethodMixin, WithOptionalCudaGraphs): - @property - def input_types(self): - """Returns definitions of module input ports.""" - return { - "encoder_output": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), - "encoded_lengths": NeuralType(tuple('B'), LengthsType()), - "partial_hypotheses": [NeuralType(elements_type=HypothesisType(), optional=True)], # must always be last - } - - def __init__( - self, - decoder_model: rnnt_abstract.AbstractRNNTDecoder, - joint_model: rnnt_abstract.AbstractRNNTJoint, - blank_index: int, - beam_size: int, - search_type: str = 'malsd_batch', - score_norm: bool = True, - maes_num_steps: Optional[int] = 2, - maes_expansion_gamma: Optional[float] = 2.3, - maes_expansion_beta: Optional[int] = 2, - max_symbols_per_step: Optional[int] = 10, - preserve_alignments: bool = False, - fusion_models: Optional[List[NGramGPULanguageModel]] = None, - fusion_models_alpha: Optional[List[float]] = None, - blank_lm_score_mode: Optional[str | BlankLMScoreMode] = BlankLMScoreMode.LM_WEIGHTED_FULL, - pruning_mode: Optional[str | PruningMode] = PruningMode.LATE, - allow_cuda_graphs: Optional[bool] = True, - return_best_hypothesis: Optional[str] = True, - ): - """ - Init method. - Args: - decoder: Prediction network from RNN-T - joint: Joint module from RNN-T - blank_index: index of blank symbol - beam_size: beam size - search_type: strategy from [`maes_batch`. `malsd_batch`]. Defaults to `malsd_batch` - score_norm: whether to normalize scores before best hypothesis extraction - maes_num_steps: Number of adaptive steps to take. From the paper, 2 steps is generally sufficient. int > 1. - maes_expansion_gamma: Float pruning threshold used in the prune-by-value step when computing the expansions. - The default (2.3) is selected from the paper. It performs a comparison - (max_log_prob - gamma <= log_prob[v]) where v is all vocabulary indices in the Vocab set and max_log_prob - is the "most" likely token to be predicted. Gamma therefore provides a margin of additional tokens which - can be potential candidates for expansion apart from the "most likely" candidate. - Lower values will reduce the number of expansions (by increasing pruning-by-value, thereby improving speed - but hurting accuracy). Higher values will increase the number of expansions (by reducing pruning-by-value, - thereby reducing speed but potentially improving accuracy). This is a hyper parameter to be experimentally - tuned on a validation set. - maes_expansion_beta: Maximum number of prefix expansions allowed, in addition to the beam size. - Effectively, the number of hypothesis = beam_size + maes_expansion_beta. Must be an int >= 0, - and affects the speed of inference since large values will perform large beam search in the next step. - max_symbols_per_step: max symbols to emit on each step (to avoid infinite looping) - preserve_alignments: if alignments are needed - fusion_models: list of fusion models to use for decoding - fusion_models_alpha: list of alpha values for fusion models - blank_lm_score_mode: mode for scoring blank symbol with LM - pruning_mode: mode for pruning hypotheses with LM - allow_cuda_graphs: whether to allow CUDA graphs - return_best_hypothesis: whether to return the best hypothesis or N-best hypotheses - tokenizer: tokenizer for the model - """ - - super().__init__() - self.decoder = decoder_model - self.joint = joint_model - - self._blank_index = blank_index - self._SOS = blank_index # Start of single index - self.beam_size = beam_size - self.score_norm = score_norm - self.return_best_hypothesis = return_best_hypothesis - - if max_symbols_per_step is not None and max_symbols_per_step <= 0: - raise ValueError(f"Expected max_symbols_per_step > 0 (or None), got {max_symbols_per_step}") - self.max_symbols = max_symbols_per_step - self.preserve_alignments = preserve_alignments - - if search_type == "malsd_batch": - # Depending on availability of `blank_as_pad` support - # switch between more efficient batch decoding technique - self._decoding_computer = ModifiedALSDBatchedRNNTComputer( - decoder=self.decoder, - joint=self.joint, - beam_size=self.beam_size, - blank_index=self._blank_index, - max_symbols_per_step=self.max_symbols, - preserve_alignments=preserve_alignments, - fusion_models=fusion_models, - fusion_models_alpha=fusion_models_alpha, - blank_lm_score_mode=blank_lm_score_mode, - pruning_mode=pruning_mode, - allow_cuda_graphs=allow_cuda_graphs, - ) - elif search_type == "maes_batch": - self._decoding_computer = ModifiedAESBatchedRNNTComputer( - decoder=self.decoder, - joint=self.joint, - beam_size=self.beam_size, - blank_index=self._blank_index, - maes_num_steps=maes_num_steps, - maes_expansion_beta=maes_expansion_beta, - maes_expansion_gamma=maes_expansion_gamma, - preserve_alignments=preserve_alignments, - ngram_lm_model=fusion_models[0] if fusion_models is not None else None, - ngram_lm_alpha=fusion_models_alpha[0] if fusion_models_alpha is not None else 0.0, - blank_lm_score_mode=blank_lm_score_mode, - pruning_mode=pruning_mode, - allow_cuda_graphs=allow_cuda_graphs, - ) - - def disable_cuda_graphs(self) -> bool: - """Disable CUDA graphs (e.g., for decoding in training)""" - if isinstance(self._decoding_computer, WithOptionalCudaGraphs): - return self._decoding_computer.disable_cuda_graphs() - return False - - def maybe_enable_cuda_graphs(self) -> bool: - """Enable CUDA graphs (if allowed)""" - if isinstance(self._decoding_computer, WithOptionalCudaGraphs): - return self._decoding_computer.maybe_enable_cuda_graphs() - return False - - @property - def output_types(self): - """Returns definitions of module output ports.""" - return {"predictions": [NeuralType(elements_type=HypothesisType())]} - - def __call__(self, *args, **kwargs): - return self.forward(*args, **kwargs) - - @typecheck() - def forward( - self, - encoder_output: torch.Tensor, - encoded_lengths: torch.Tensor, - partial_hypotheses: Optional[list[Hypothesis]] = None, - ) -> Tuple[list[Hypothesis] | List[NBestHypotheses]]: - """Returns a list of hypotheses given an input batch of the encoder hidden embedding. - Output token is generated auto-regressively. - - Args: - encoder_output: A tensor of size (batch, features, timesteps). - encoded_lengths: list of int representing the length of each sequence - output sequence. - - Returns: - Tuple of a list of hypotheses for each batch. Each hypothesis contains - the decoded sequence, timestamps and associated scores. - If ``return_best_hypothesis`` is True, returns the best hypothesis for each batch; - otherwise, returns the N-best hypotheses for each batch. - """ - if partial_hypotheses is not None: - raise NotImplementedError("Partial hypotheses feature is not yet supported in batched beam search.") - # Preserve decoder and joint training state - decoder_training_state = self.decoder.training - joint_training_state = self.joint.training - - with torch.inference_mode(): - # Apply optional preprocessing - encoder_output = encoder_output.transpose(1, 2) # (B, T, D) - logitlen = encoded_lengths - - self.decoder.eval() - self.joint.eval() - - inseq = encoder_output # [B, T, D] - batched_beam_hyps = self._decoding_computer(x=inseq, out_len=logitlen) - - batch_size = encoder_output.shape[0] - if self.return_best_hypothesis: - hyps = batched_beam_hyps.to_hyps_list(score_norm=self.score_norm)[:batch_size] - else: - hyps = batched_beam_hyps.to_nbest_hyps_list(score_norm=self.score_norm)[:batch_size] - - self.decoder.train(decoder_training_state) - self.joint.train(joint_training_state) - - return (hyps,) - - -@dataclass -class BeamRNNTInferConfig: - """ - Beam RNNT Inference config. - """ - - beam_size: int - search_type: str = 'default' - score_norm: bool = True - return_best_hypothesis: bool = True - tsd_max_sym_exp_per_step: Optional[int] = 50 - alsd_max_target_len: float = 1.0 - nsc_max_timesteps_expansion: int = 1 - nsc_prefix_alpha: int = 1 - maes_num_steps: int = 2 - maes_prefix_alpha: int = 1 - maes_expansion_gamma: float = 2.3 - maes_expansion_beta: int = 2 - language_model: Optional[Dict[str, Any]] = None - softmax_temperature: float = 1.0 - preserve_alignments: bool = False - ngram_lm_model: Optional[str] = None - ngram_lm_alpha: Optional[float] = 0.0 - boosting_tree: BoostingTreeModelConfig = field(default_factory=BoostingTreeModelConfig) - boosting_tree_alpha: Optional[float] = 0.0 - hat_subtract_ilm: bool = False - hat_ilm_weight: float = 0.0 - max_symbols_per_step: Optional[int] = 10 - blank_lm_score_mode: Optional[str | BlankLMScoreMode] = BlankLMScoreMode.LM_WEIGHTED_FULL - pruning_mode: Optional[str | PruningMode] = PruningMode.LATE - allow_cuda_graphs: Optional[bool] = True diff --git a/nemo/collections/asr/parts/submodules/rnnt_decoding.py b/nemo/collections/asr/parts/submodules/rnnt_decoding.py deleted file mode 100644 index c9a0989d102237b71c0da8166d6e545ec04bf721..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/rnnt_decoding.py +++ /dev/null @@ -1,1865 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import copy -import re -from abc import abstractmethod, abstractproperty -from dataclasses import dataclass, field, is_dataclass -from typing import Dict, List, Optional, Set, Union - -import torch -from omegaconf import OmegaConf - -from nemo.collections.asr.parts.context_biasing import BoostingTreeModelConfig, GPUBoostingTreeModel -from nemo.collections.asr.parts.submodules import rnnt_beam_decoding, rnnt_greedy_decoding, tdt_beam_decoding -from nemo.collections.asr.parts.submodules.ngram_lm import NGramGPULanguageModel -from nemo.collections.asr.parts.utils.asr_confidence_utils import ConfidenceConfig, ConfidenceMixin -from nemo.collections.asr.parts.utils.batched_beam_decoding_utils import BlankLMScoreMode, PruningMode -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis, NBestHypotheses -from nemo.collections.asr.parts.utils.timestamp_utils import get_segment_offsets, get_words_offsets -from nemo.collections.asr.parts.utils.tokenizer_utils import define_spe_tokenizer_type, extract_punctuation_from_vocab -from nemo.collections.common.tokenizers.aggregate_tokenizer import AggregateTokenizer -from nemo.collections.common.tokenizers.tokenizer_spec import TokenizerSpec -from nemo.utils import logging -from nemo.utils.enum import PrettyStrEnum - -try: - import kenlm - - KENLM_AVAILABLE = True -except (ImportError, ModuleNotFoundError): - KENLM_AVAILABLE = False - - -class TransducerModelType(PrettyStrEnum): - RNNT = "rnnt" - TDT = "tdt" - MULTI_BLANK = "multi_blank" - - -class TransducerDecodingStrategyType(PrettyStrEnum): - GREEDY = "greedy" - GREEDY_BATCH = "greedy_batch" - BEAM = "beam" - TSD = "tsd" - MAES = "maes" - ALSD = "alsd" - MALSD_BATCH = "malsd_batch" - MAES_BATCH = "maes_batch" - - -TRANSDUCER_SUPPORTED_STRATEGIES: dict[TransducerModelType, set[TransducerDecodingStrategyType]] = { - TransducerModelType.RNNT: { - TransducerDecodingStrategyType.GREEDY, - TransducerDecodingStrategyType.GREEDY_BATCH, - TransducerDecodingStrategyType.BEAM, - TransducerDecodingStrategyType.MAES, - TransducerDecodingStrategyType.ALSD, - TransducerDecodingStrategyType.TSD, - TransducerDecodingStrategyType.MALSD_BATCH, - TransducerDecodingStrategyType.MAES_BATCH, - }, - TransducerModelType.TDT: { - TransducerDecodingStrategyType.GREEDY, - TransducerDecodingStrategyType.GREEDY_BATCH, - TransducerDecodingStrategyType.BEAM, - TransducerDecodingStrategyType.MAES, - TransducerDecodingStrategyType.MALSD_BATCH, - }, - TransducerModelType.MULTI_BLANK: { - TransducerDecodingStrategyType.GREEDY, - TransducerDecodingStrategyType.GREEDY_BATCH, - }, -} - - -class AbstractRNNTDecoding(ConfidenceMixin): - """ - Used for performing RNN-T auto-regressive decoding of the Decoder+Joint network given the encoder state. - - Args: - decoding_cfg: A dict-like object which contains the following key-value pairs. - strategy: str value which represents the type of decoding that can occur. - Possible values are : - - greedy, greedy_batch (for greedy decoding). - - beam, tsd, alsd (for beam search decoding). - - compute_hypothesis_token_set: A bool flag, which determines whether to compute a list of decoded - tokens as well as the decoded string. Default is False in order to avoid double decoding - unless required. - - preserve_alignments: Bool flag which preserves the history of logprobs generated during - decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `alignments` in it. Here, `alignments` is a List of List of - Tuple(Tensor (of length V + 1), Tensor(scalar, label after argmax)). - - In order to obtain this hypothesis, please utilize `rnnt_decoder_predictions_tensor` function - with the `return_hypotheses` flag set to True. - - The length of the list corresponds to the Acoustic Length (T). - Each value in the list (Ti) is a torch.Tensor (U), representing 1 or more targets from a vocabulary. - U is the number of target tokens for the current timestep Ti. - - tdt_include_token_duration: Bool flag, which determines whether predicted durations for each token - need to be included in the Hypothesis object. Defaults to False. - - compute_timestamps: A bool flag, which determines whether to compute the character/subword, or - word based timestamp mapping the output log-probabilities to discrete intervals of timestamps. - The timestamps will be available in the returned Hypothesis.timestep as a dictionary. - - rnnt_timestamp_type: A str value, which represents the types of timestamps that should be calculated. - Can take the following values - "char" for character/subword time stamps, "word" for word level - time stamps, "segment" for segment level time stamps and "all" (default), for character, word and - segment level time stamps. - - word_seperator: Str token representing the seperator between words. - - segment_seperators: List containing tokens representing the seperator(s) between segments. - - segment_gap_threshold: The threshold (in frames) that caps the gap between two words necessary for forming - the segments. - - preserve_frame_confidence: Bool flag which preserves the history of per-frame confidence scores - generated during decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `frame_confidence` in it. Here, `alignments` is a List of List of ints. - - confidence_cfg: A dict-like object which contains the following key-value pairs related to confidence - scores. In order to obtain hypotheses with confidence scores, please utilize - `rnnt_decoder_predictions_tensor` function with the `preserve_frame_confidence` flag set to True. - - preserve_frame_confidence: Bool flag which preserves the history of per-frame confidence scores - generated during decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `frame_confidence` in it. Here, `alignments` is a List of List of floats. - - The length of the list corresponds to the Acoustic Length (T). - Each value in the list (Ti) is a torch.Tensor (U), representing 1 or more confidence scores. - U is the number of target tokens for the current timestep Ti. - preserve_token_confidence: Bool flag which preserves the history of per-token confidence scores - generated during greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `token_confidence` in it. Here, `token_confidence` is a List of floats. - - The length of the list corresponds to the number of recognized tokens. - preserve_word_confidence: Bool flag which preserves the history of per-word confidence scores - generated during greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `word_confidence` in it. Here, `word_confidence` is a List of floats. - - The length of the list corresponds to the number of recognized words. - exclude_blank: Bool flag indicating that blank token confidence scores are to be excluded - from the `token_confidence`. - aggregation: Which aggregation type to use for collapsing per-token confidence into per-word - confidence. Valid options are `mean`, `min`, `max`, `prod`. - tdt_include_duration: Bool flag indicating that the duration confidence scores are to be calculated and - attached to the regular frame confidence, - making TDT frame confidence element a pair: (`prediction_confidence`, `duration_confidence`). - method_cfg: A dict-like object which contains the method name and settings to compute per-frame - confidence scores. - - name: The method name (str). - Supported values: - - 'max_prob' for using the maximum token probability as a confidence. - - 'entropy' for using a normalized entropy of a log-likelihood vector. - - entropy_type: Which type of entropy to use (str). - Used if confidence_method_cfg.name is set to `entropy`. - Supported values: - - 'gibbs' for the (standard) Gibbs entropy. If the alpha (α) is provided, - the formula is the following: H_α = -sum_i((p^α_i)*log(p^α_i)). - Note that for this entropy, the alpha should comply the following inequality: - (log(V)+2-sqrt(log^2(V)+4))/(2*log(V)) <= α <= (1+log(V-1))/log(V-1) - where V is the model vocabulary size. - - 'tsallis' for the Tsallis entropy with the Boltzmann constant one. - Tsallis entropy formula is the following: H_α = 1/(α-1)*(1-sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/Tsallis_entropy - - 'renyi' for the Rényi entropy. - Rényi entropy formula is the following: H_α = 1/(1-α)*log_2(sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/R%C3%A9nyi_entropy - - alpha: Power scale for logsoftmax (α for entropies). Here we restrict it to be > 0. - When the alpha equals one, scaling is not applied to 'max_prob', - and any entropy type behaves like the Shannon entropy: H = -sum_i(p_i*log(p_i)) - - entropy_norm: A mapping of the entropy value to the interval [0,1]. - Supported values: - - 'lin' for using the linear mapping. - - 'exp' for using exponential mapping with linear shift. - - The config may further contain the following sub-dictionaries: - "greedy": - max_symbols: int, describing the maximum number of target tokens to decode per - timestep during greedy decoding. Setting to larger values allows longer sentences - to be decoded, at the cost of increased execution time. - preserve_frame_confidence: Same as above, overrides above value. - confidence_method_cfg: Same as above, overrides confidence_cfg.method_cfg. - - "beam": - beam_size: int, defining the beam size for beam search. Must be >= 1. - If beam_size == 1, will perform cached greedy search. This might be slightly different - results compared to the greedy search above. - - score_norm: optional bool, whether to normalize the returned beam score in the hypotheses. - Set to True by default. - - return_best_hypothesis: optional bool, whether to return just the best hypothesis or all of the - hypotheses after beam search has concluded. This flag is set by default. - - tsd_max_sym_exp: optional int, determines number of symmetric expansions of the target symbols - per timestep of the acoustic model. Larger values will allow longer sentences to be decoded, - at increased cost to execution time. - - alsd_max_target_len: optional int or float, determines the potential maximum target sequence length. - If an integer is provided, it can decode sequences of that particular maximum length. - If a float is provided, it can decode sequences of int(alsd_max_target_len * seq_len), - where seq_len is the length of the acoustic model output (T). - - NOTE: - If a float is provided, it can be greater than 1! - By default, a float of 2.0 is used so that a target sequence can be at most twice - as long as the acoustic model output length T. - - maes_num_steps: Number of adaptive steps to take. From the paper, 2 steps is generally sufficient, - and can be reduced to 1 to improve decoding speed while sacrificing some accuracy. int > 0. - - maes_prefix_alpha: Maximum prefix length in prefix search. Must be an integer, and is advised to keep - this as 1 in order to reduce expensive beam search cost later. int >= 0. - - maes_expansion_beta: Maximum number of prefix expansions allowed, in addition to the beam size. - Effectively, the number of hypothesis = beam_size + maes_expansion_beta. Must be an int >= 0, - and affects the speed of inference since large values will perform large beam search in the next - step. - - maes_expansion_gamma: Float pruning threshold used in the prune-by-value step when computing the - expansions. The default (2.3) is selected from the paper. It performs a comparison - (max_log_prob - gamma <= log_prob[v]) where v is all vocabulary indices in the Vocab set and - max_log_prob is the "most" likely token to be predicted. Gamma therefore provides a margin of - additional tokens which can be potential candidates for expansion apart from the "most likely" - candidate. Lower values will reduce the number of expansions (by increasing pruning-by-value, - thereby improving speed but hurting accuracy). Higher values will increase the number of expansions - (by reducing pruning-by-value, thereby reducing speed but potentially improving accuracy). This is - a hyper parameter to be experimentally tuned on a validation set. - - softmax_temperature: Scales the logits of the joint prior to computing log_softmax. - - decoder: The Decoder/Prediction network module. - joint: The Joint network module. - blank_id: The id of the RNNT blank token. - supported_punctuation: Set of punctuation marks in the vocabulary - """ - - def __init__(self, decoding_cfg, decoder, joint, blank_id: int, supported_punctuation: Optional[Set] = None): - super(AbstractRNNTDecoding, self).__init__() - - # Convert dataclass to config object - if is_dataclass(decoding_cfg): - decoding_cfg = OmegaConf.structured(decoding_cfg) - - self.cfg = decoding_cfg - self.blank_id = blank_id - self.supported_punctuation = supported_punctuation - self.num_extra_outputs = joint.num_extra_outputs - self.big_blank_durations = self.cfg.get("big_blank_durations", None) - self.durations = self.cfg.get("durations", None) - self.compute_hypothesis_token_set = self.cfg.get("compute_hypothesis_token_set", False) - self.compute_langs = decoding_cfg.get('compute_langs', False) - self.preserve_alignments = self.cfg.get('preserve_alignments', None) - self.joint_fused_batch_size = self.cfg.get('fused_batch_size', None) - self.compute_timestamps = self.cfg.get('compute_timestamps', None) - self.tdt_include_token_duration = self.cfg.get('tdt_include_token_duration', False) - self.word_seperator = self.cfg.get('word_seperator', ' ') - self.segment_seperators = self.cfg.get('segment_seperators', ['.', '?', '!']) - self.segment_gap_threshold = self.cfg.get('segment_gap_threshold', None) - - self._is_tdt = self.durations is not None and self.durations != [] # this means it's a TDT model. - self._with_multiple_blanks = self.big_blank_durations is not None and len(self.big_blank_durations) > 0 - - if self._is_tdt: - if blank_id == 0: - raise ValueError("blank_id must equal len(non_blank_vocabs) for TDT models") - if self._with_multiple_blanks: - raise ValueError("duration and big_blank_durations can't both be not None") - - if self._with_multiple_blanks and blank_id == 0: - raise ValueError("blank_id must equal len(vocabs) for multi-blank RNN-T models") - - strategy = TransducerDecodingStrategyType(self.cfg.strategy) - - if self._is_tdt: - model_type = TransducerModelType.TDT - elif self._with_multiple_blanks: - model_type = TransducerModelType.MULTI_BLANK - else: - model_type = TransducerModelType.RNNT - - self._model_type = model_type - self._decoding_strategy_type = strategy - - # Update preserve alignments - if self.preserve_alignments is None: - if self.cfg.strategy in ['greedy', 'greedy_batch']: - self.preserve_alignments = self.cfg.greedy.get('preserve_alignments', False) - - elif self.cfg.strategy in ['beam', 'tsd', 'alsd', 'maes']: - self.preserve_alignments = self.cfg.beam.get('preserve_alignments', False) - - # Update compute timestamps - if self.compute_timestamps is None: - if self.cfg.strategy in ['greedy', 'greedy_batch']: - self.compute_timestamps = self.cfg.greedy.get('compute_timestamps', False) - - elif self.cfg.strategy in ['beam', 'tsd', 'alsd', 'maes']: - self.compute_timestamps = self.cfg.beam.get('compute_timestamps', False) - - # Check if the model supports punctuation - # and compile regex pattern to remove A space before supported punctuation marks if applicable - # We remove only one space before punctuation marks as for some models punctuation marks are included in the vocabulary with a space. - # The presence of multiple spaces before punctuation marks is a result of erroneous prediction of the ASR model, which should not be fixed during the decoding process. - if self.supported_punctuation: - punct_pattern = '|'.join([re.escape(p) for p in self.supported_punctuation]) - self.space_before_punct_pattern = re.compile(r'(\s)(' + punct_pattern + ')') - - # initialize confidence-related fields - self._init_confidence(self.cfg.get('confidence_cfg', None)) - - if model_type is TransducerModelType.TDT: - self.tdt_include_token_duration = self.tdt_include_token_duration or self.compute_timestamps - self._compute_offsets = self._compute_offsets_tdt - self._refine_timestamps = self._refine_timestamps_tdt - - # Confidence estimation is not implemented for these strategies - if ( - not self.preserve_frame_confidence - and self.cfg.strategy in ['beam', 'tsd', 'alsd', 'maes'] - and self.cfg.beam.get('preserve_frame_confidence', False) - ): - raise NotImplementedError(f"Confidence calculation is not supported for strategy `{self.cfg.strategy}`") - - if strategy in {TransducerDecodingStrategyType.GREEDY, TransducerDecodingStrategyType.GREEDY_BATCH}: - ngram_lm_model = self.cfg.greedy.get('ngram_lm_model', None) - ngram_lm_alpha = self.cfg.greedy.get('ngram_lm_alpha', 0) - boosting_tree = self.cfg.greedy.get('boosting_tree', None) - boosting_tree_alpha = self.cfg.greedy.get('boosting_tree_alpha', 0) - else: - ngram_lm_model = self.cfg.beam.get('ngram_lm_model', None) - ngram_lm_alpha = self.cfg.beam.get('ngram_lm_alpha', 0) - boosting_tree = self.cfg.beam.get('boosting_tree', None) - boosting_tree_alpha = self.cfg.beam.get('boosting_tree_alpha', 0) - - # load fusion models from paths (ngram_lm_model and boosting_tree_model) - fusion_models, fusion_models_alpha = [], [] - # load ngram_lm model from path - if ngram_lm_model is not None: - if strategy is TransducerDecodingStrategyType.MAES: - fusion_models.append(self._load_kenlm_model(ngram_lm_model)) - else: - fusion_models.append(NGramGPULanguageModel.from_file(lm_path=ngram_lm_model, vocab_size=self.blank_id)) - fusion_models_alpha.append(ngram_lm_alpha) - # load boosting tree model from path - if boosting_tree and not BoostingTreeModelConfig.is_empty(boosting_tree): - if strategy is TransducerDecodingStrategyType.MAES: - raise NotImplementedError( - f"Model {model_type} with strategy `{strategy}` does not support boosting tree." - ) - fusion_models.append( - GPUBoostingTreeModel.from_config(boosting_tree, tokenizer=getattr(self, 'tokenizer', None)) - ) - fusion_models_alpha.append(boosting_tree_alpha) - if not fusion_models: - fusion_models = None - fusion_models_alpha = None - - match strategy, model_type: - # greedy strategy - case TransducerDecodingStrategyType.GREEDY, TransducerModelType.RNNT: - if fusion_models is not None: - raise NotImplementedError( - f"Model {model_type} with strategy `{strategy}` does not support n-gram LM models and boosting tree." - f"Recommended greedy strategy with LM is `greedy_batch`." - ) - self.decoding = rnnt_greedy_decoding.GreedyRNNTInfer( - decoder_model=decoder, - joint_model=joint, - blank_index=self.blank_id, - max_symbols_per_step=( - self.cfg.greedy.get('max_symbols', None) or self.cfg.greedy.get('max_symbols_per_step', None) - ), - preserve_alignments=self.preserve_alignments, - preserve_frame_confidence=self.preserve_frame_confidence, - confidence_method_cfg=self.confidence_method_cfg, - ) - case TransducerDecodingStrategyType.GREEDY, TransducerModelType.TDT: - if fusion_models is not None: - raise NotImplementedError( - f"Model {model_type} with strategy `{strategy}` does not support n-gram LM models and boosting tree. " - f"Recommended greedy strategy with LM is `greedy_batch`." - ) - self.decoding = rnnt_greedy_decoding.GreedyTDTInfer( - decoder_model=decoder, - joint_model=joint, - blank_index=self.blank_id, - durations=self.durations, - max_symbols_per_step=( - self.cfg.greedy.get('max_symbols', None) or self.cfg.greedy.get('max_symbols_per_step', None) - ), - preserve_alignments=self.preserve_alignments, - preserve_frame_confidence=self.preserve_frame_confidence, - include_duration=self.tdt_include_token_duration, - include_duration_confidence=self.tdt_include_duration_confidence, - confidence_method_cfg=self.confidence_method_cfg, - ) - case TransducerDecodingStrategyType.GREEDY, TransducerModelType.MULTI_BLANK: - if fusion_models is not None: - raise NotImplementedError( - f"Model {model_type} with strategy `{strategy}` does not support n-gram LM models and boosting tree." - ) - self.decoding = rnnt_greedy_decoding.GreedyMultiblankRNNTInfer( - decoder_model=decoder, - joint_model=joint, - blank_index=self.blank_id, - big_blank_durations=self.big_blank_durations, - max_symbols_per_step=( - self.cfg.greedy.get('max_symbols', None) or self.cfg.greedy.get('max_symbols_per_step', None) - ), - preserve_alignments=self.preserve_alignments, - preserve_frame_confidence=self.preserve_frame_confidence, - confidence_method_cfg=self.confidence_method_cfg, - ) - # greedy_batch strategy - case TransducerDecodingStrategyType.GREEDY_BATCH, TransducerModelType.RNNT: - self.decoding = rnnt_greedy_decoding.GreedyBatchedRNNTInfer( - decoder_model=decoder, - joint_model=joint, - blank_index=self.blank_id, - max_symbols_per_step=( - self.cfg.greedy.get('max_symbols', None) or self.cfg.greedy.get('max_symbols_per_step', None) - ), - preserve_alignments=self.preserve_alignments, - preserve_frame_confidence=self.preserve_frame_confidence, - confidence_method_cfg=self.confidence_method_cfg, - loop_labels=self.cfg.greedy.get('loop_labels', True), - use_cuda_graph_decoder=self.cfg.greedy.get('use_cuda_graph_decoder', True), - fusion_models=fusion_models, - fusion_models_alpha=fusion_models_alpha, - enable_per_stream_biasing=self.cfg.greedy.get('enable_per_stream_biasing', False), - ) - case TransducerDecodingStrategyType.GREEDY_BATCH, TransducerModelType.TDT: - self.decoding = rnnt_greedy_decoding.GreedyBatchedTDTInfer( - decoder_model=decoder, - joint_model=joint, - blank_index=self.blank_id, - durations=self.durations, - max_symbols_per_step=( - self.cfg.greedy.get('max_symbols', None) or self.cfg.greedy.get('max_symbols_per_step', None) - ), - preserve_alignments=self.preserve_alignments, - preserve_frame_confidence=self.preserve_frame_confidence, - include_duration=self.tdt_include_token_duration, - include_duration_confidence=self.tdt_include_duration_confidence, - confidence_method_cfg=self.confidence_method_cfg, - use_cuda_graph_decoder=self.cfg.greedy.get('use_cuda_graph_decoder', True), - fusion_models=fusion_models, - fusion_models_alpha=fusion_models_alpha, - enable_per_stream_biasing=self.cfg.greedy.get('enable_per_stream_biasing', False), - ) - case TransducerDecodingStrategyType.GREEDY_BATCH, TransducerModelType.MULTI_BLANK: - if fusion_models is not None: - raise NotImplementedError( - f"Model {model_type} with strategy `{strategy}` does not support n-gram LM models and boosting tree." - ) - self.decoding = rnnt_greedy_decoding.GreedyBatchedMultiblankRNNTInfer( - decoder_model=decoder, - joint_model=joint, - blank_index=self.blank_id, - big_blank_durations=self.big_blank_durations, - max_symbols_per_step=( - self.cfg.greedy.get('max_symbols', None) or self.cfg.greedy.get('max_symbols_per_step', None) - ), - preserve_alignments=self.preserve_alignments, - preserve_frame_confidence=self.preserve_frame_confidence, - confidence_method_cfg=self.confidence_method_cfg, - ) - # beam, maes, alsd, tsd strategies - case TransducerDecodingStrategyType.BEAM, TransducerModelType.RNNT: - if fusion_models is not None: - raise NotImplementedError( - f"Model {model_type} with strategy `{strategy}` does not support n-gram LM models and boosting tree." - f"Recommended beam decoding strategy with LM is `malsd_batch`." - ) - logging.warning( - f"Decoding strategy `{strategy}` is experimental. " - "Recommended beam decoding strategy is `malsd_batch`." - ) - self.decoding = rnnt_beam_decoding.BeamRNNTInfer( - decoder_model=decoder, - joint_model=joint, - beam_size=self.cfg.beam.beam_size, - return_best_hypothesis=decoding_cfg.beam.get('return_best_hypothesis', True), - search_type='default', - score_norm=self.cfg.beam.get('score_norm', True), - softmax_temperature=self.cfg.beam.get('softmax_temperature', 1.0), - preserve_alignments=self.preserve_alignments, - ) - case TransducerDecodingStrategyType.BEAM, TransducerModelType.TDT: - if fusion_models is not None: - raise NotImplementedError( - f"Model {model_type} with strategy `{strategy}` does not support n-gram LM models and boosting tree." - f"Recommended beam decoding strategy with LM is `malsd_batch`." - ) - logging.warning( - f"Decoding strategy `{strategy}` is experimental. " - "Recommended beam decoding strategy is `malsd_batch`." - ) - self.decoding = tdt_beam_decoding.BeamTDTInfer( - decoder_model=decoder, - joint_model=joint, - durations=self.durations, - beam_size=self.cfg.beam.beam_size, - return_best_hypothesis=decoding_cfg.beam.get('return_best_hypothesis', True), - search_type='default', - score_norm=self.cfg.beam.get('score_norm', True), - softmax_temperature=self.cfg.beam.get('softmax_temperature', 1.0), - preserve_alignments=self.preserve_alignments, - ) - case TransducerDecodingStrategyType.TSD, TransducerModelType.RNNT: - if fusion_models is not None: - raise NotImplementedError( - f"Model {model_type} with strategy `{strategy}` does not support n-gram LM models and boosting tree." - f"Recommended beam decoding strategy with LM is `malsd_batch`." - ) - logging.warning( - f"Decoding strategy `{strategy}` is experimental. " - "Recommended beam decoding strategy is `malsd_batch`." - ) - self.decoding = rnnt_beam_decoding.BeamRNNTInfer( - decoder_model=decoder, - joint_model=joint, - beam_size=self.cfg.beam.beam_size, - return_best_hypothesis=decoding_cfg.beam.get('return_best_hypothesis', True), - search_type='tsd', - score_norm=self.cfg.beam.get('score_norm', True), - tsd_max_sym_exp_per_step=self.cfg.beam.get('tsd_max_sym_exp', 10), - softmax_temperature=self.cfg.beam.get('softmax_temperature', 1.0), - preserve_alignments=self.preserve_alignments, - ) - case TransducerDecodingStrategyType.ALSD, TransducerModelType.RNNT: - if fusion_models is not None: - raise NotImplementedError( - f"Model {model_type} with strategy `{strategy}` does not support n-gram LM models and boosting tree." - f"Recommended beam decoding strategy with LM is `malsd_batch`." - ) - logging.warning( - f"Decoding strategy `{strategy}` is experimental. " - "Recommended beam decoding strategy is `malsd_batch`." - ) - self.decoding = rnnt_beam_decoding.BeamRNNTInfer( - decoder_model=decoder, - joint_model=joint, - beam_size=self.cfg.beam.beam_size, - return_best_hypothesis=decoding_cfg.beam.get('return_best_hypothesis', True), - search_type='alsd', - score_norm=self.cfg.beam.get('score_norm', True), - alsd_max_target_len=self.cfg.beam.get('alsd_max_target_len', 2), - softmax_temperature=self.cfg.beam.get('softmax_temperature', 1.0), - preserve_alignments=self.preserve_alignments, - ) - case TransducerDecodingStrategyType.MAES, TransducerModelType.RNNT: - logging.warning( - f"Decoding strategy `{strategy}` is experimental. " - "Recommended beam decoding strategy is `malsd_batch`." - ) - self.decoding = rnnt_beam_decoding.BeamRNNTInfer( - decoder_model=decoder, - joint_model=joint, - beam_size=self.cfg.beam.beam_size, - return_best_hypothesis=decoding_cfg.beam.get('return_best_hypothesis', True), - search_type='maes', - score_norm=self.cfg.beam.get('score_norm', True), - maes_num_steps=self.cfg.beam.get('maes_num_steps', 2), - maes_prefix_alpha=self.cfg.beam.get('maes_prefix_alpha', 1), - maes_expansion_gamma=self.cfg.beam.get('maes_expansion_gamma', 2.3), - maes_expansion_beta=self.cfg.beam.get('maes_expansion_beta', 2.0), - softmax_temperature=self.cfg.beam.get('softmax_temperature', 1.0), - preserve_alignments=self.preserve_alignments, - ngram_lm_model=fusion_models[0] if fusion_models is not None else None, - ngram_lm_alpha=fusion_models_alpha[0] if fusion_models_alpha is not None else 0.0, - hat_subtract_ilm=self.cfg.beam.get('hat_subtract_ilm', False), - hat_ilm_weight=self.cfg.beam.get('hat_ilm_weight', 0.0), - ) - case TransducerDecodingStrategyType.MAES, TransducerModelType.TDT: - logging.warning( - f"Decoding strategy `{strategy}` is experimental. " - "Recommended beam decoding strategy is `malsd_batch`." - ) - self.decoding = tdt_beam_decoding.BeamTDTInfer( - decoder_model=decoder, - joint_model=joint, - durations=self.durations, - beam_size=self.cfg.beam.beam_size, - return_best_hypothesis=decoding_cfg.beam.get('return_best_hypothesis', True), - search_type='maes', - score_norm=self.cfg.beam.get('score_norm', True), - maes_num_steps=self.cfg.beam.get('maes_num_steps', 2), - maes_prefix_alpha=self.cfg.beam.get('maes_prefix_alpha', 1), - maes_expansion_gamma=self.cfg.beam.get('maes_expansion_gamma', 2.3), - maes_expansion_beta=self.cfg.beam.get('maes_expansion_beta', 2.0), - softmax_temperature=self.cfg.beam.get('softmax_temperature', 1.0), - preserve_alignments=self.preserve_alignments, - ngram_lm_model=fusion_models[0] if fusion_models is not None else None, - ngram_lm_alpha=fusion_models_alpha[0] if fusion_models_alpha is not None else 0.0, - ) - # beam batch: malsd_batch and maes_batch strategies - case TransducerDecodingStrategyType.MALSD_BATCH, TransducerModelType.RNNT: - self.decoding = rnnt_beam_decoding.BeamBatchedRNNTInfer( - decoder_model=decoder, - joint_model=joint, - blank_index=self.blank_id, - beam_size=self.cfg.beam.beam_size, - search_type='malsd_batch', - max_symbols_per_step=self.cfg.beam.get("max_symbols", 10), - preserve_alignments=self.preserve_alignments, - fusion_models=fusion_models, - fusion_models_alpha=fusion_models_alpha, - blank_lm_score_mode=self.cfg.beam.get('blank_lm_score_mode', BlankLMScoreMode.LM_WEIGHTED_FULL), - pruning_mode=self.cfg.beam.get('pruning_mode', PruningMode.LATE), - score_norm=self.cfg.beam.get('score_norm', True), - allow_cuda_graphs=self.cfg.beam.get('allow_cuda_graphs', True), - return_best_hypothesis=self.cfg.beam.get('return_best_hypothesis', True), - ) - case TransducerDecodingStrategyType.MALSD_BATCH, TransducerModelType.TDT: - self.decoding = tdt_beam_decoding.BeamBatchedTDTInfer( - decoder_model=decoder, - joint_model=joint, - blank_index=self.blank_id, - durations=self.durations, - beam_size=self.cfg.beam.beam_size, - search_type='malsd_batch', - max_symbols_per_step=self.cfg.beam.get("max_symbols", 10), - preserve_alignments=self.preserve_alignments, - fusion_models=fusion_models, - fusion_models_alpha=fusion_models_alpha, - blank_lm_score_mode=self.cfg.beam.get('blank_lm_score_mode', BlankLMScoreMode.LM_WEIGHTED_FULL), - pruning_mode=self.cfg.beam.get('pruning_mode', PruningMode.LATE), - score_norm=self.cfg.beam.get('score_norm', True), - allow_cuda_graphs=self.cfg.beam.get('allow_cuda_graphs', True), - return_best_hypothesis=self.cfg.beam.get('return_best_hypothesis', True), - ) - case TransducerDecodingStrategyType.MAES_BATCH, TransducerModelType.RNNT: - self.decoding = rnnt_beam_decoding.BeamBatchedRNNTInfer( - decoder_model=decoder, - joint_model=joint, - blank_index=self.blank_id, - beam_size=self.cfg.beam.beam_size, - search_type='maes_batch', - maes_num_steps=self.cfg.beam.get('maes_num_steps', 2), - maes_expansion_beta=self.cfg.beam.get('maes_expansion_beta', 2), - maes_expansion_gamma=self.cfg.beam.get('maes_expansion_gamma', 2.3), - preserve_alignments=self.preserve_alignments, - fusion_models=fusion_models, - fusion_models_alpha=fusion_models_alpha, - blank_lm_score_mode=self.cfg.beam.get('blank_lm_score_mode', BlankLMScoreMode.LM_WEIGHTED_FULL), - pruning_mode=self.cfg.beam.get('pruning_mode', PruningMode.LATE), - score_norm=self.cfg.beam.get('score_norm', True), - allow_cuda_graphs=self.cfg.beam.get('allow_cuda_graphs', False), - return_best_hypothesis=self.cfg.beam.get('return_best_hypothesis', True), - ) - case _, _: - raise NotImplementedError( - f"Transducer model of {model_type} type does not support {strategy} strategy. " - f"Supported strategies: {', '.join(map(str, TRANSDUCER_SUPPORTED_STRATEGIES[model_type]))}" - ) - - # Update the joint fused batch size or disable it entirely if needed. - self.update_joint_fused_batch_size() - - @abstractproperty - def tokenizer_type(self): - """ - Implemented by subclass in order to get tokenizer type information for timestamps extraction. - """ - raise NotImplementedError() - - def rnnt_decoder_predictions_tensor( - self, - encoder_output: torch.Tensor, - encoded_lengths: torch.Tensor, - return_hypotheses: bool = False, - partial_hypotheses: Optional[List[Hypothesis]] = None, - ) -> Union[List[Hypothesis], List[List[Hypothesis]]]: - """ - Decode an encoder output by autoregressive decoding of the Decoder+Joint networks. - - Args: - encoder_output: torch.Tensor of shape [B, D, T]. - encoded_lengths: torch.Tensor containing lengths of the padded encoder outputs. Shape [B]. - return_hypotheses: bool. If set to True it will return list of Hypothesis or NBestHypotheses - - Returns: - If `return_all_hypothesis` is set: - A list[list[Hypothesis]]. - Look at rnnt_utils.Hypothesis for more information. - - If `return_all_hypothesis` is not set: - A list[Hypothesis]. - List of best hypotheses - Look at rnnt_utils.Hypothesis for more information. - """ - # Compute hypotheses - with torch.inference_mode(): - hypotheses_list = self.decoding( - encoder_output=encoder_output, encoded_lengths=encoded_lengths, partial_hypotheses=partial_hypotheses - ) # type: [List[Hypothesis]] - - # extract the hypotheses - hypotheses_list = hypotheses_list[0] # type: List[Hypothesis] - - prediction_list = hypotheses_list - - if isinstance(prediction_list[0], NBestHypotheses): - hypotheses = [] - all_hypotheses = [] - - for nbest_hyp in prediction_list: # type: NBestHypotheses - n_hyps = nbest_hyp.n_best_hypotheses # Extract all hypotheses for this sample - decoded_hyps = self.decode_hypothesis(n_hyps) # type: List[str] - - # If computing timestamps - if self.compute_timestamps is True: - timestamp_type = self.cfg.get('rnnt_timestamp_type', 'all') - for hyp_idx in range(len(decoded_hyps)): - decoded_hyps[hyp_idx] = self.compute_rnnt_timestamps(decoded_hyps[hyp_idx], timestamp_type) - - hypotheses.append(decoded_hyps[0]) # best hypothesis - all_hypotheses.append(decoded_hyps) - - if return_hypotheses: - return all_hypotheses # type: list[list[Hypothesis]] - - all_hyp = [[Hypothesis(h.score, h.y_sequence, h.text) for h in hh] for hh in all_hypotheses] - return all_hyp - - else: - hypotheses = self.decode_hypothesis(prediction_list) # type: List[str] - - # If computing timestamps - if self.compute_timestamps is True: - timestamp_type = self.cfg.get('rnnt_timestamp_type', 'all') - for hyp_idx in range(len(hypotheses)): - hypotheses[hyp_idx] = self.compute_rnnt_timestamps(hypotheses[hyp_idx], timestamp_type) - - if return_hypotheses: - # greedy decoding, can get high-level confidence scores - if self.preserve_frame_confidence and ( - self.preserve_word_confidence or self.preserve_token_confidence - ): - hypotheses = self.compute_confidence(hypotheses) - return hypotheses - - return [Hypothesis(h.score, h.y_sequence, h.text) for h in hypotheses] - - def decode_hypothesis(self, hypotheses_list: List[Hypothesis]) -> List[Union[Hypothesis, NBestHypotheses]]: - """ - Decode a list of hypotheses into a list of strings. - - Args: - hypotheses_list: List of Hypothesis. - - Returns: - A list of strings. - """ - for hyp in hypotheses_list: - # Extract the integer encoded hypothesis - prediction = hyp.y_sequence - - if type(prediction) != list: - prediction = prediction.tolist() - - # RNN-T sample level is already preprocessed by implicit RNNT decoding - # Simply remove any blank and possibly big blank tokens - if self.big_blank_durations is not None and self.big_blank_durations != []: # multi-blank RNNT - num_extra_outputs = len(self.big_blank_durations) - prediction = [p for p in prediction if p < self.blank_id - num_extra_outputs] - elif self._is_tdt: # TDT model. - prediction = [p for p in prediction if p < self.blank_id] - else: # standard RNN-T - prediction = [p for p in prediction if p != self.blank_id] - - # De-tokenize the integer tokens; - hyp.text = self.decode_tokens_to_str_with_strip_punctuation(prediction) - - if self.compute_hypothesis_token_set: - hyp.tokens = self.decode_ids_to_tokens(prediction) - - return hypotheses_list - - def compute_confidence(self, hypotheses_list: List[Hypothesis]) -> List[Hypothesis]: - """ - Computes high-level (per-token and/or per-word) confidence scores for a list of hypotheses. - Assumes that `frame_confidence` is present in the hypotheses. - - Args: - hypotheses_list: List of Hypothesis. - - Returns: - A list of hypotheses with high-level confidence scores. - """ - if self._is_tdt: - # if self.tdt_include_duration_confidence is True then frame_confidence elements consist of two numbers - maybe_pre_aggregate = ( - (lambda x: self._aggregate_confidence(x)) if self.tdt_include_duration_confidence else (lambda x: x) - ) - for hyp in hypotheses_list: - token_confidence = [] - # trying to recover frame_confidence according to alignments - subsequent_blank_confidence = [] - # going backwards since tokens are considered belonging to the last non-blank token. - for fc, fa in zip(hyp.frame_confidence[::-1], hyp.alignments[::-1]): - # there is only one score per frame most of the time - if len(fa) > 1: - for i, a in reversed(list(enumerate(fa))): - if a[-1] == self.blank_id: - if not self.exclude_blank_from_confidence: - subsequent_blank_confidence.append(maybe_pre_aggregate(fc[i])) - elif not subsequent_blank_confidence: - token_confidence.append(maybe_pre_aggregate(fc[i])) - else: - token_confidence.append( - self._aggregate_confidence( - [maybe_pre_aggregate(fc[i])] + subsequent_blank_confidence - ) - ) - subsequent_blank_confidence = [] - else: - i, a = 0, fa[0] - if a[-1] == self.blank_id: - if not self.exclude_blank_from_confidence: - subsequent_blank_confidence.append(maybe_pre_aggregate(fc[i])) - elif not subsequent_blank_confidence: - token_confidence.append(maybe_pre_aggregate(fc[i])) - else: - token_confidence.append( - self._aggregate_confidence([maybe_pre_aggregate(fc[i])] + subsequent_blank_confidence) - ) - subsequent_blank_confidence = [] - token_confidence = token_confidence[::-1] - hyp.token_confidence = token_confidence - else: - if self.exclude_blank_from_confidence: - for hyp in hypotheses_list: - hyp.token_confidence = hyp.non_blank_frame_confidence - else: - for hyp in hypotheses_list: - timestep = hyp.timestamp.tolist() if isinstance(hyp.timestamp, torch.Tensor) else hyp.timestamp - offset = 0 - token_confidence = [] - if len(timestep) > 0: - for ts, te in zip(timestep, timestep[1:] + [len(hyp.frame_confidence)]): - if ts != te: - # tokens are considered to belong to the last non-blank token, if any. - token_confidence.append( - self._aggregate_confidence( - [hyp.frame_confidence[ts][offset]] - + [fc[0] for fc in hyp.frame_confidence[ts + 1 : te]] - ) - ) - offset = 0 - else: - token_confidence.append(hyp.frame_confidence[ts][offset]) - offset += 1 - hyp.token_confidence = token_confidence - if self.preserve_word_confidence: - for hyp in hypotheses_list: - hyp.word_confidence = self._aggregate_token_confidence(hyp) - return hypotheses_list - - @abstractmethod - def decode_tokens_to_str(self, tokens: List[int]) -> str: - """ - Implemented by subclass in order to decoder a token id list into a string. - - Args: - tokens: List of int representing the token ids. - - Returns: - A decoded string. - """ - raise NotImplementedError() - - @abstractmethod - def decode_ids_to_tokens(self, tokens: List[int]) -> List[str]: - """ - Implemented by subclass in order to decode a token id list into a token list. - A token list is the string representation of each token id. - - Args: - tokens: List of int representing the token ids. - - Returns: - A list of decoded tokens. - """ - raise NotImplementedError() - - @abstractmethod - def decode_tokens_to_lang(self, tokens: List[int]) -> str: - """ - Implemented by subclass in order to - compute the most likely language ID (LID) string given the tokens. - - Args: - tokens: List of int representing the token ids. - - Returns: - A decoded LID string. - """ - raise NotImplementedError() - - @abstractmethod - def decode_ids_to_langs(self, tokens: List[int]) -> List[str]: - """ - Implemented by subclass in order to - decode a token id list into language ID (LID) list. - - Args: - tokens: List of int representing the token ids. - - Returns: - A list of decoded LIDS. - """ - raise NotImplementedError() - - def decode_ids_to_str(self, tokens: List[int]) -> str: - """ - Decodes a list of tokens ids to a string. - """ - if hasattr(self, 'tokenizer') and isinstance(self.tokenizer, AggregateTokenizer): - return self.tokenizer.ids_to_text(tokens) - else: - return self.decode_tokens_to_str(self.decode_ids_to_tokens(tokens)) - - def decode_tokens_to_str_with_strip_punctuation(self, tokens: List[int]) -> str: - """ - Decodes a list of tokens to a string and removes a space before supported punctuation marks. - """ - text = self.decode_ids_to_str(tokens) - if self.supported_punctuation: - text = self.space_before_punct_pattern.sub(r'\2', text) - return text - - def update_joint_fused_batch_size(self): - """ " - Updates the fused batch size for the joint module if applicable. - - If `joint_fused_batch_size` is set, verifies that the joint module has - the required `set_fused_batch_size` and `set_fuse_loss_wer` functions. - If present, updates the batch size; otherwise, logs a warning. - - If `joint_fused_batch_size` is <= 0, disables fused batch processing. - """ - if self.joint_fused_batch_size is None: - # do nothing and let the Joint itself handle setting up of the fused batch - return - - if not hasattr(self.decoding.joint, 'set_fused_batch_size'): - logging.warning( - "The joint module does not have `set_fused_batch_size(int)` as a setter function.\n" - "Ignoring update of joint fused batch size." - ) - return - - if not hasattr(self.decoding.joint, 'set_fuse_loss_wer'): - logging.warning( - "The joint module does not have `set_fuse_loss_wer(bool, RNNTLoss, RNNTWER)` " - "as a setter function.\n" - "Ignoring update of joint fused batch size." - ) - return - - if self.joint_fused_batch_size > 0: - self.decoding.joint.set_fused_batch_size(self.joint_fused_batch_size) - else: - logging.info("Joint fused batch size <= 0; Will temporarily disable fused batch step in the Joint.") - self.decoding.joint.set_fuse_loss_wer(False) - - def compute_rnnt_timestamps(self, hypothesis: Hypothesis, timestamp_type: str = "all"): - """ - Computes character, word, and segment timestamps for an RNN-T hypothesis. - - This function generates timestamps for characters, words, and segments within - a hypothesis sequence. The type of timestamps computed depends on `timestamp_type`, - which can be 'char', 'word', 'segment', or 'all'. - - Args: - hypothesis (Hypothesis): Hypothesis. - timestamp_type (str): Type of timestamps to compute. Options are 'char', 'word', 'segment', or 'all'. - Defaults to 'all'. - - Returns: - Hypothesis: The updated hypothesis with computed timestamps for characters, words, and/or segments. - """ - assert timestamp_type in ['char', 'word', 'segment', 'all'] - - # Retrieve offsets - char_offsets = word_offsets = None - char_offsets = self._compute_offsets(hypothesis, self.blank_id) - y_sequence_blank_removed = [t for t in hypothesis.y_sequence if t != self.blank_id] - - if len(char_offsets) != len(y_sequence_blank_removed): - raise ValueError( - f"`char_offsets`: {char_offsets} and `processed_tokens`: {y_sequence_blank_removed}" - " have to be of the same length, but are: " - f"`len(offsets)`: {len(char_offsets)} and `len(processed_tokens)`:" - f" {len(y_sequence_blank_removed)}" - ) - - encoded_char_offsets = copy.deepcopy(char_offsets) - - # Correctly process the token ids to chars/subwords. - for i, offsets in enumerate(char_offsets): - chars_text = [] - chars_tokens = [] - for char in offsets['char']: - # NB: if blank tokens are present, _refine_timestamps will not work properly - # as offests and encoded_offsets will not be 1:1 match - assert char != self.blank_id, "Offsets should not contain blank tokens" - chars_tokens.append(self.decode_ids_to_tokens([int(char)])[0]) - chars_text.append(self.decode_ids_to_str([int(char)])) - char_offsets[i]["char"] = chars_text - encoded_char_offsets[i]["char"] = chars_tokens - - encoded_char_offsets, char_offsets = self._refine_timestamps( - encoded_char_offsets, char_offsets, self.supported_punctuation - ) - - # detect char vs subword models - lens = [] - for v in char_offsets: - tokens = v["char"] - # each token may be either 1 unicode token or multiple unicode token - # for character based models, only 1 token is used - # for subword, more than one token can be used. - # Computing max, then summing up total lens is a test to check for char vs subword - # For char models, len(lens) == sum(lens) - # but this is violated for subword models. - max_len = max(len(c) for c in tokens) - lens.append(max_len) - - # retrieve word offsets from character offsets - word_offsets = None - if timestamp_type in ['word', 'segment', 'all']: - word_offsets = get_words_offsets( - char_offsets=char_offsets, - encoded_char_offsets=encoded_char_offsets, - word_delimiter_char=self.word_seperator, - supported_punctuation=self.supported_punctuation, - tokenizer_type=self.tokenizer_type, - decode_tokens_to_str=self.decode_tokens_to_str, - ) - - segment_offsets = None - if timestamp_type in ['segment', 'all']: - segment_offsets = get_segment_offsets( - word_offsets, - segment_delimiter_tokens=self.segment_seperators, - supported_punctuation=self.supported_punctuation, - segment_gap_threshold=self.segment_gap_threshold, - ) - - # attach results - if len(hypothesis.timestamp) > 0: - timestep_info = hypothesis.timestamp - else: - timestep_info = [] - - # Setup defaults - hypothesis.timestamp = {"timestep": timestep_info} - - # Add char / subword time stamps - if char_offsets is not None and timestamp_type in ['char', 'all']: - hypothesis.timestamp['char'] = char_offsets - - # Add word time stamps - if word_offsets is not None and timestamp_type in ['word', 'all']: - hypothesis.timestamp['word'] = word_offsets - - # Add segment time stamps - if segment_offsets is not None and timestamp_type in ['segment', 'all']: - hypothesis.timestamp['segment'] = segment_offsets - - return hypothesis - - @staticmethod - def _compute_offsets(hypothesis: Hypothesis, blank_id: int) -> List[Dict[str, Union[str, int]]]: - """ - Utility method that calculates the indidual time indices where a token starts and ends. - - Args: - hypothesis: A Hypothesis object that contains `text` field that holds the character / subword token - emitted at every time step after rnnt collapse. - - Returns: - List[Dict[str, Union[str, int]]]: A list of dictionaries, where each dictionary contains: - - "char": List[str] - The character/subword token - - "start_offset": int - The start time index of the token - - "end_offset": int - The end time index of the token - - **Note**: Blank tokens are not included in the offsets. - """ - if isinstance(hypothesis.timestamp, torch.Tensor): - hypothesis.timestamp = hypothesis.timestamp.cpu().tolist() - - # Merge the results per token into a list of dictionaries - offsets = [ - {"char": [t], "start_offset": s, "end_offset": s + 1} - for t, s in zip(hypothesis.y_sequence, hypothesis.timestamp) - if t != blank_id - ] - - return offsets - - @staticmethod - def _compute_offsets_tdt(hypothesis: Hypothesis, blank_id: int, *args) -> List[Dict[str, Union[str, int]]]: - """ - Utility method that calculates the indidual time indices where a token starts and ends. - - Args: - hypothesis: A Hypothesis object that contains `text` field that holds the character / subword token - emitted at a specific time step considering predicted durations of the previous tokens. - - Returns: - List[Dict[str, Union[str, int]]]: A list of dictionaries, where each dictionary contains: - - "char": List[str] - The character/subword token - - "start_offset": int - The start time index of the token - - "end_offset": int - The end time index of the token - - **Note**: Blank tokens are not included in the offsets. - """ - if isinstance(hypothesis.timestamp, torch.Tensor): - hypothesis.token_duration = hypothesis.token_duration.cpu().tolist() - - if isinstance(hypothesis.timestamp, torch.Tensor): - hypothesis.timestamp = hypothesis.timestamp.cpu().tolist() - - # Merge the results per token into a list of dictionaries - offsets = [ - {"char": [t], "start_offset": s, "end_offset": s + d} - for t, s, d in zip(hypothesis.y_sequence, hypothesis.timestamp, hypothesis.token_duration) - if t != blank_id - ] - return offsets - - @staticmethod - def _refine_timestamps( - encoded_char_offsets: List[Dict[str, Union[str, int]]], - char_offsets: List[Dict[str, Union[str, int]]], - supported_punctuation: Optional[Set] = None, - ) -> List[Dict[str, Union[str, int]]]: - - # no refinement for rnnt - - return encoded_char_offsets, char_offsets - - @staticmethod - def _refine_timestamps_tdt( - encoded_char_offsets: List[Dict[str, Union[str, int]]], - char_offsets: List[Dict[str, Union[str, int]]], - supported_punctuation: Optional[Set] = None, - ) -> List[Dict[str, Union[str, int]]]: - - if not supported_punctuation: - return encoded_char_offsets, char_offsets - - for i, offset in enumerate(char_offsets): - - # Check if token is a punctuation mark - # If so, set its start and end offset as start and end of the previous token - # This is done because there was observed a behaviour, when punctuation marks are - # predicted long after preceding token (i.e. after silence) - if offset['char'][0] in supported_punctuation and i > 0: - encoded_char_offsets[i]['start_offset'] = offset['start_offset'] = char_offsets[i - 1]['end_offset'] - encoded_char_offsets[i]['end_offset'] = offset['end_offset'] = offset['start_offset'] - - return encoded_char_offsets, char_offsets - - @staticmethod - def _load_kenlm_model(ngram_lm_model: str): - """ - Load a KenLM model from a file path. - """ - if KENLM_AVAILABLE: - return kenlm.Model(ngram_lm_model) - else: - raise ImportError( - "KenLM package (https://github.com/kpu/kenlm) is not installed. " "Use ngram_lm_model=None." - ) - - -class RNNTDecoding(AbstractRNNTDecoding): - """ - Used for performing RNN-T auto-regressive decoding of the Decoder+Joint network given the encoder state. - - Args: - decoding_cfg: A dict-like object which contains the following key-value pairs. - - strategy: - str value which represents the type of decoding that can occur. - Possible values are : - - - greedy, greedy_batch (for greedy decoding). - - - beam, tsd, alsd (for beam search decoding). - - compute_hypothesis_token_set: A bool flag, which determines whether to compute a list of decoded - tokens as well as the decoded string. Default is False in order to avoid double decoding - unless required. - - preserve_alignments: Bool flag which preserves the history of logprobs generated during - decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `logprobs` in it. Here, `alignments` is a List of List of - Tuple(Tensor (of length V + 1), Tensor(scalar, label after argmax)). - - In order to obtain this hypothesis, please utilize `rnnt_decoder_predictions_tensor` function - with the `return_hypotheses` flag set to True. - - The length of the list corresponds to the Acoustic Length (T). - Each value in the list (Ti) is a torch.Tensor (U), representing 1 or more targets from a vocabulary. - U is the number of target tokens for the current timestep Ti. - - confidence_cfg: A dict-like object which contains the following key-value pairs related to confidence - scores. In order to obtain hypotheses with confidence scores, please utilize - `rnnt_decoder_predictions_tensor` function with the `preserve_frame_confidence` flag set to True. - - preserve_frame_confidence: Bool flag which preserves the history of per-frame confidence scores - generated during decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `frame_confidence` in it. Here, `alignments` is a List of List of floats. - - The length of the list corresponds to the Acoustic Length (T). - Each value in the list (Ti) is a torch.Tensor (U), representing 1 or more confidence scores. - U is the number of target tokens for the current timestep Ti. - preserve_token_confidence: Bool flag which preserves the history of per-token confidence scores - generated during greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `token_confidence` in it. Here, `token_confidence` is a List of floats. - - The length of the list corresponds to the number of recognized tokens. - preserve_word_confidence: Bool flag which preserves the history of per-word confidence scores - generated during greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `word_confidence` in it. Here, `word_confidence` is a List of floats. - - The length of the list corresponds to the number of recognized words. - exclude_blank: Bool flag indicating that blank token confidence scores are to be excluded - from the `token_confidence`. - aggregation: Which aggregation type to use for collapsing per-token confidence into per-word - confidence. - Valid options are `mean`, `min`, `max`, `prod`. - tdt_include_duration: Bool flag indicating that the duration confidence scores are to be calculated and - attached to the regular frame confidence, - making TDT frame confidence element a pair: (`prediction_confidence`, `duration_confidence`). - method_cfg: A dict-like object which contains the method name and settings to compute per-frame - confidence scores. - - name: - The method name (str). - Supported values: - - - 'max_prob' for using the maximum token probability as a confidence. - - - 'entropy' for using a normalized entropy of a log-likelihood vector. - - entropy_type: - Which type of entropy to use (str). - Used if confidence_method_cfg.name is set to `entropy`. - Supported values: - - - 'gibbs' for the (standard) Gibbs entropy. If the alpha (α) is provided, - the formula is the following: H_α = -sum_i((p^α_i)*log(p^α_i)). - Note that for this entropy, the alpha should comply the following inequality: - (log(V)+2-sqrt(log^2(V)+4))/(2*log(V)) <= α <= (1+log(V-1))/log(V-1) - where V is the model vocabulary size. - - - 'tsallis' for the Tsallis entropy with the Boltzmann constant one. - Tsallis entropy formula is the following: H_α = 1/(α-1)*(1-sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/Tsallis_entropy - - - 'renyi' for the Rényi entropy. - Rényi entropy formula is the following: H_α = 1/(1-α)*log_2(sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/R%C3%A9nyi_entropy - - alpha: - Power scale for logsoftmax (α for entropies). Here we restrict it to be > 0. - When the alpha equals one, scaling is not applied to 'max_prob', - and any entropy type behaves like the Shannon entropy: H = -sum_i(p_i*log(p_i)) - - entropy_norm: - A mapping of the entropy value to the interval [0,1]. - Supported values: - - - 'lin' for using the linear mapping. - - - 'exp' for using exponential mapping with linear shift. - - The config may further contain the following sub-dictionaries: - - "greedy": - max_symbols: int, describing the maximum number of target tokens to decode per - timestep during greedy decoding. Setting to larger values allows longer sentences - to be decoded, at the cost of increased execution time. - - preserve_frame_confidence: Same as above, overrides above value. - - confidence_method_cfg: Same as above, overrides confidence_cfg.method_cfg. - - "beam": - beam_size: int, defining the beam size for beam search. Must be >= 1. - If beam_size == 1, will perform cached greedy search. This might be slightly different - results compared to the greedy search above. - - score_norm: optional bool, whether to normalize the returned beam score in the hypotheses. - Set to True by default. - - return_best_hypothesis: optional bool, whether to return just the best hypothesis or all of the - hypotheses after beam search has concluded. This flag is set by default. - - tsd_max_sym_exp: optional int, determines number of symmetric expansions of the target symbols - per timestep of the acoustic model. Larger values will allow longer sentences to be decoded, - at increased cost to execution time. - - alsd_max_target_len: optional int or float, determines the potential maximum target sequence - length. If an integer is provided, it can decode sequences of that particular maximum length. - If a float is provided, it can decode sequences of int(alsd_max_target_len * seq_len), - where seq_len is the length of the acoustic model output (T). - - NOTE: - If a float is provided, it can be greater than 1! - By default, a float of 2.0 is used so that a target sequence can be at most twice - as long as the acoustic model output length T. - - maes_num_steps: Number of adaptive steps to take. From the paper, 2 steps is generally sufficient, - and can be reduced to 1 to improve decoding speed while sacrificing some accuracy. int > 0. - - maes_prefix_alpha: Maximum prefix length in prefix search. Must be an integer, and is advised to - keep this as 1 in order to reduce expensive beam search cost later. int >= 0. - - maes_expansion_beta: Maximum number of prefix expansions allowed, in addition to the beam size. - Effectively, the number of hypothesis = beam_size + maes_expansion_beta. Must be an int >= 0, - and affects the speed of inference since large values will perform large beam search in the - next step. - - maes_expansion_gamma: Float pruning threshold used in the prune-by-value step when computing the - expansions. The default (2.3) is selected from the paper. It performs a comparison - (max_log_prob - gamma <= log_prob[v]) where v is all vocabulary indices in the Vocab set and - max_log_prob is the "most" likely token to be predicted. Gamma therefore provides a margin of - additional tokens which can be potential candidates for expansion apart from the "most likely" - candidate. Lower values will reduce the number of expansions (by increasing pruning-by-value, - thereby improving speed but hurting accuracy). Higher values will increase the number of - expansions (by reducing pruning-by-value, thereby reducing speed but potentially improving - accuracy). This is a hyper parameter to be experimentally tuned on a validation set. - - softmax_temperature: Scales the logits of the joint prior to computing log_softmax. - - decoder: The Decoder/Prediction network module. - joint: The Joint network module. - vocabulary: The vocabulary (excluding the RNNT blank token) which will be used for decoding. - """ - - def __init__( - self, - decoding_cfg, - decoder, - joint, - vocabulary, - ): - # we need to ensure blank is the last token in the vocab for the case of RNNT and Multi-blank RNNT. - blank_id = len(vocabulary) + joint.num_extra_outputs - supported_punctuation = extract_punctuation_from_vocab(vocabulary) - - if hasattr(decoding_cfg, 'model_type') and decoding_cfg.model_type == 'tdt': - blank_id = len(vocabulary) - - self.labels_map = dict([(i, vocabulary[i]) for i in range(len(vocabulary))]) - - super(RNNTDecoding, self).__init__( - decoding_cfg=decoding_cfg, - decoder=decoder, - joint=joint, - blank_id=blank_id, - supported_punctuation=supported_punctuation, - ) - - if isinstance(self.decoding, rnnt_beam_decoding.BeamRNNTInfer) or isinstance( - self.decoding, tdt_beam_decoding.BeamTDTInfer - ): - self.decoding.set_decoding_type('char') - - @property - def tokenizer_type(self): - return "char" - - def _aggregate_token_confidence(self, hypothesis: Hypothesis) -> List[float]: - """ - Implemented by subclass in order to aggregate token confidence to a word-level confidence. - - Args: - hypothesis: Hypothesis - - Returns: - A list of word-level confidence scores. - """ - return self._aggregate_token_confidence_chars(hypothesis.words, hypothesis.token_confidence) - - def decode_tokens_to_str(self, tokens: List[str]) -> str: - """ - Implemented by subclass in order to decoder a token list into a string. - - Args: - tokens: List of int representing the token ids. - - Returns: - A decoded string. - """ - hypothesis = ''.join(tokens) - return hypothesis - - def decode_ids_to_tokens(self, tokens: List[int]) -> List[str]: - """ - Implemented by subclass in order to decode a token id list into a token list. - A token list is the string representation of each token id. - - Args: - tokens: List of int representing the token ids. - - Returns: - A list of decoded tokens. - """ - token_list = [self.labels_map[c] for c in tokens if c < self.blank_id - self.num_extra_outputs] - return token_list - - def decode_tokens_to_lang(self, tokens: List[int]) -> str: - """ - Compute the most likely language ID (LID) string given the tokens. - - Args: - tokens: List of int representing the token ids. - - Returns: - A decoded LID string. - """ - lang = self.tokenizer.ids_to_lang(tokens) - return lang - - def decode_ids_to_langs(self, tokens: List[int]) -> List[str]: - """ - Decode a token id list into language ID (LID) list. - - Args: - tokens: List of int representing the token ids. - - Returns: - A list of decoded LIDS. - """ - lang_list = self.tokenizer.ids_to_text_and_langs(tokens) - return lang_list - - -class RNNTBPEDecoding(AbstractRNNTDecoding): - """ - Used for performing RNN-T auto-regressive decoding of the Decoder+Joint network given the encoder state. - - Args: - decoding_cfg: A dict-like object which contains the following key-value pairs. - - strategy: - str value which represents the type of decoding that can occur. - Possible values are : - - - greedy, greedy_batch (for greedy decoding). - - - beam, tsd, alsd (for beam search decoding). - - compute_hypothesis_token_set: A bool flag, which determines whether to compute a list of decoded - tokens as well as the decoded string. Default is False in order to avoid double decoding - unless required. - - preserve_alignments: Bool flag which preserves the history of logprobs generated during - decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `alignments` in it. Here, `alignments` is a List of List of - Tuple(Tensor (of length V + 1), Tensor(scalar, label after argmax)). - - In order to obtain this hypothesis, please utilize `rnnt_decoder_predictions_tensor` function - with the `return_hypotheses` flag set to True. - - The length of the list corresponds to the Acoustic Length (T). - Each value in the list (Ti) is a torch.Tensor (U), representing 1 or more targets from a vocabulary. - U is the number of target tokens for the current timestep Ti. - - compute_timestamps: A bool flag, which determines whether to compute the character/subword, or - word based timestamp mapping the output log-probabilities to discrete intervals of timestamps. - The timestamps will be available in the returned Hypothesis.timestep as a dictionary. - - compute_langs: a bool flag, which allows to compute language id (LID) information per token, - word, and the entire sample (most likely language id). The LIDS will be available - in the returned Hypothesis object as a dictionary - - rnnt_timestamp_type: A str value, which represents the types of timestamps that should be calculated. - Can take the following values - "char" for character/subword time stamps, "word" for word level - time stamps and "all" (default), for both character level and word level time stamps. - - word_seperator: Str token representing the seperator between words. - - segment_seperators: List containing tokens representing the seperator(s) between segments. - - segment_gap_threshold: The threshold (in frames) that caps the gap between two words necessary for forming - the segments. - - preserve_frame_confidence: Bool flag which preserves the history of per-frame confidence scores - generated during decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `frame_confidence` in it. Here, `alignments` is a List of List of ints. - - confidence_cfg: A dict-like object which contains the following key-value pairs related to confidence - scores. In order to obtain hypotheses with confidence scores, please utilize - `rnnt_decoder_predictions_tensor` function with the `preserve_frame_confidence` flag set to True. - - preserve_frame_confidence: Bool flag which preserves the history of per-frame confidence scores - generated during decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `frame_confidence` in it. Here, `alignments` is a List of List of floats. - - The length of the list corresponds to the Acoustic Length (T). - Each value in the list (Ti) is a torch.Tensor (U), representing 1 or more confidence scores. - U is the number of target tokens for the current timestep Ti. - preserve_token_confidence: Bool flag which preserves the history of per-token confidence scores - generated during greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `token_confidence` in it. Here, `token_confidence` is a List of floats. - - The length of the list corresponds to the number of recognized tokens. - preserve_word_confidence: Bool flag which preserves the history of per-word confidence scores - generated during greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `word_confidence` in it. Here, `word_confidence` is a List of floats. - - The length of the list corresponds to the number of recognized words. - exclude_blank: Bool flag indicating that blank token confidence scores are to be excluded - from the `token_confidence`. - aggregation: Which aggregation type to use for collapsing per-token confidence into per-word - confidence. Valid options are `mean`, `min`, `max`, `prod`. - tdt_include_duration: Bool flag indicating that the duration confidence scores are to be calculated and - attached to the regular frame confidence, - making TDT frame confidence element a pair: (`prediction_confidence`, `duration_confidence`). - method_cfg: A dict-like object which contains the method name and settings to compute per-frame - confidence scores. - - name: - The method name (str). - Supported values: - - - 'max_prob' for using the maximum token probability as a confidence. - - - 'entropy' for using a normalized entropy of a log-likelihood vector. - - entropy_type: Which type of entropy to use (str). - Used if confidence_method_cfg.name is set to `entropy`. - Supported values: - - - 'gibbs' for the (standard) Gibbs entropy. If the alpha (α) is provided, - the formula is the following: H_α = -sum_i((p^α_i)*log(p^α_i)). - Note that for this entropy, the alpha should comply the following inequality: - (log(V)+2-sqrt(log^2(V)+4))/(2*log(V)) <= α <= (1+log(V-1))/log(V-1) - where V is the model vocabulary size. - - - 'tsallis' for the Tsallis entropy with the Boltzmann constant one. - Tsallis entropy formula is the following: H_α = 1/(α-1)*(1-sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/Tsallis_entropy - - - 'renyi' for the Rényi entropy. - Rényi entropy formula is the following: H_α = 1/(1-α)*log_2(sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/R%C3%A9nyi_entropy - - alpha: Power scale for logsoftmax (α for entropies). Here we restrict it to be > 0. - When the alpha equals one, scaling is not applied to 'max_prob', - and any entropy type behaves like the Shannon entropy: H = -sum_i(p_i*log(p_i)) - - entropy_norm: A mapping of the entropy value to the interval [0,1]. - Supported values: - - - 'lin' for using the linear mapping. - - - 'exp' for using exponential mapping with linear shift. - - The config may further contain the following sub-dictionaries: - - "greedy": - max_symbols: int, describing the maximum number of target tokens to decode per - timestep during greedy decoding. Setting to larger values allows longer sentences - to be decoded, at the cost of increased execution time. - - preserve_frame_confidence: Same as above, overrides above value. - - confidence_method_cfg: Same as above, overrides confidence_cfg.method_cfg. - - "beam": - beam_size: int, defining the beam size for beam search. Must be >= 1. - If beam_size == 1, will perform cached greedy search. This might be slightly different - results compared to the greedy search above. - - score_norm: optional bool, whether to normalize the returned beam score in the hypotheses. - Set to True by default. - - return_best_hypothesis: optional bool, whether to return just the best hypothesis or all of the - hypotheses after beam search has concluded. - - tsd_max_sym_exp: optional int, determines number of symmetric expansions of the target symbols - per timestep of the acoustic model. Larger values will allow longer sentences to be decoded, - at increased cost to execution time. - - alsd_max_target_len: optional int or float, determines the potential maximum target sequence - length.If an integer is provided, it can decode sequences of that particular maximum length. - If a float is provided, it can decode sequences of int(alsd_max_target_len * seq_len), - where seq_len is the length of the acoustic model output (T). - - NOTE: - If a float is provided, it can be greater than 1! - By default, a float of 2.0 is used so that a target sequence can be at most twice - as long as the acoustic model output length T. - - maes_num_steps: Number of adaptive steps to take. From the paper, 2 steps is generally sufficient, - and can be reduced to 1 to improve decoding speed while sacrificing some accuracy. int > 0. - - maes_prefix_alpha: Maximum prefix length in prefix search. Must be an integer, and is advised to - keep this as 1 in order to reduce expensive beam search cost later. int >= 0. - - maes_expansion_beta: Maximum number of prefix expansions allowed, in addition to the beam size. - Effectively, the number of hypothesis = beam_size + maes_expansion_beta. Must be an int >= 0, - and affects the speed of inference since large values will perform large beam search in the - next step. - - maes_expansion_gamma: Float pruning threshold used in the prune-by-value step when computing the - expansions. The default (2.3) is selected from the paper. It performs a comparison - (max_log_prob - gamma <= log_prob[v]) where v is all vocabulary indices in the Vocab set and - max_log_prob is the "most" likely token to be predicted. Gamma therefore provides a margin of - additional tokens which can be potential candidates for expansion apart from the "most likely" - candidate. Lower values will reduce the number of expansions (by increasing pruning-by-value, - thereby improving speed but hurting accuracy). Higher values will increase the number of - expansions (by reducing pruning-by-value, thereby reducing speed but potentially improving - accuracy). This is a hyper parameter to be experimentally tuned on a validation set. - - softmax_temperature: Scales the logits of the joint prior to computing log_softmax. - - decoder: The Decoder/Prediction network module. - joint: The Joint network module. - tokenizer: The tokenizer which will be used for decoding. - """ - - def __init__(self, decoding_cfg, decoder, joint, tokenizer: TokenizerSpec): - blank_id = tokenizer.tokenizer.vocab_size # RNNT or TDT models. - - if hasattr(tokenizer, 'supported_punctuation'): - supported_punctuation = tokenizer.supported_punctuation - else: - supported_punctuation = extract_punctuation_from_vocab(tokenizer.vocab) - - # multi-blank RNNTs - if hasattr(decoding_cfg, 'model_type') and decoding_cfg.model_type == 'multiblank': - blank_id = tokenizer.tokenizer.vocab_size + joint.num_extra_outputs - - self.tokenizer = tokenizer - - super(RNNTBPEDecoding, self).__init__( - decoding_cfg=decoding_cfg, - decoder=decoder, - joint=joint, - blank_id=blank_id, - supported_punctuation=supported_punctuation, - ) - - if isinstance(self.decoding, rnnt_beam_decoding.BeamRNNTInfer) or isinstance( - self.decoding, tdt_beam_decoding.BeamTDTInfer - ): - self.decoding.set_decoding_type('subword') - - @property - def tokenizer_type(self): - return define_spe_tokenizer_type(self.tokenizer.vocab) - - def _aggregate_token_confidence(self, hypothesis: Hypothesis) -> List[float]: - """ - Implemented by subclass in order to reduce token confidence to a word-level confidence. - - **Note**: Only supports Sentencepiece based tokenizers! - - Args: - hypothesis: Hypothesis - - Returns: - A list of word-level confidence scores. - """ - return self._aggregate_token_confidence_subwords_sentencepiece( - hypothesis.words, hypothesis.token_confidence, hypothesis.y_sequence - ) - - def decode_tokens_to_str(self, tokens: List[str]) -> str: - """ - Implemented by subclass in order to decoder a token list into a string. - - Args: - tokens: List of str representing the tokens. - - Returns: - A decoded string. - """ - hypothesis = self.tokenizer.tokens_to_text(tokens) - return hypothesis - - def decode_ids_to_tokens(self, tokens: List[int]) -> List[str]: - """ - Implemented by subclass in order to decode a token id list into a token list. - A token list is the string representation of each token id. - - Args: - tokens: List of int representing the token ids. - - Returns: - A list of decoded tokens. - """ - token_list = self.tokenizer.ids_to_tokens(tokens) - return token_list - - def decode_tokens_to_lang(self, tokens: List[int]) -> str: - """ - Compute the most likely language ID (LID) string given the tokens. - - Args: - tokens: List of int representing the token ids. - - Returns: - A decoded LID string. - """ - lang = self.tokenizer.ids_to_lang(tokens) - return lang - - def decode_ids_to_langs(self, tokens: List[int]) -> List[str]: - """ - Decode a token id list into language ID (LID) list. - - Args: - tokens: List of int representing the token ids. - - Returns: - A list of decoded LIDS. - """ - lang_list = self.tokenizer.ids_to_text_and_langs(tokens) - return lang_list - - def decode_hypothesis(self, hypotheses_list: List[Hypothesis]) -> List[Union[Hypothesis, NBestHypotheses]]: - """ - Decode a list of hypotheses into a list of strings. - Overrides the super() method optionally adding lang information - - Args: - hypotheses_list: List of Hypothesis. - - Returns: - A list of strings. - """ - hypotheses = super().decode_hypothesis(hypotheses_list) - if self.compute_langs: - if isinstance(self.tokenizer, AggregateTokenizer): - for ind in range(len(hypotheses_list)): - # Extract the integer encoded hypothesis - prediction = hypotheses_list[ind].y_sequence - - if type(prediction) != list: - prediction = prediction.tolist() - - # RNN-T sample level is already preprocessed by implicit RNNT decoding - # Simply remove any blank tokens - prediction = [p for p in prediction if p != self.blank_id] - - hypotheses[ind].langs = self.decode_tokens_to_lang(prediction) - hypotheses[ind].langs_chars = self.decode_ids_to_langs(prediction) - else: - logging.warning( - "Ignoring request for lang output in hypotheses since the model does not use an aggregate \ - tokenizer" - ) - - return hypotheses - - -@dataclass -class RNNTDecodingConfig: - """ - RNNT Decoding config - """ - - model_type: str = "rnnt" # one of "rnnt", "multiblank" or "tdt" - strategy: str = "greedy_batch" - - compute_hypothesis_token_set: bool = False - - # preserve decoding alignments - preserve_alignments: Optional[bool] = None - - # include token duration - tdt_include_token_duration: Optional[bool] = None - - # confidence config - confidence_cfg: ConfidenceConfig = field(default_factory=lambda: ConfidenceConfig()) - - # RNNT Joint fused batch size - fused_batch_size: Optional[int] = None - - # compute RNNT time stamps - compute_timestamps: Optional[bool] = None - - # compute language IDs - compute_langs: bool = False - - # token representing word seperator - word_seperator: str = " " - - # tokens representing segments seperators - segment_seperators: Optional[List[str]] = field(default_factory=lambda: [".", "!", "?"]) - - # threshold (in frames) that caps the gap between two words necessary for forming the segments - segment_gap_threshold: Optional[int] = None - - # type of timestamps to calculate - rnnt_timestamp_type: str = "all" # can be char, word or all for both - - # greedy decoding config - greedy: rnnt_greedy_decoding.GreedyBatchedRNNTInferConfig = field( - default_factory=rnnt_greedy_decoding.GreedyBatchedRNNTInferConfig - ) - - # beam decoding config - beam: rnnt_beam_decoding.BeamRNNTInferConfig = field( - default_factory=lambda: rnnt_beam_decoding.BeamRNNTInferConfig(beam_size=4) - ) - - # can be used to change temperature for decoding - temperature: float = 1.0 - - # config for TDT decoding. - durations: Optional[List[int]] = field(default_factory=list) - - # config for multiblank decoding. - big_blank_durations: Optional[List[int]] = field(default_factory=list) - - -@dataclass -class RNNTBPEDecodingConfig(RNNTDecodingConfig): - """ - RNNT BPE Decoding Config - """ - - pass diff --git a/nemo/collections/asr/parts/submodules/rnnt_greedy_decoding.py b/nemo/collections/asr/parts/submodules/rnnt_greedy_decoding.py deleted file mode 100644 index e6cfdcd45b4bcfefaa61c713bd59a8e90203068d..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/rnnt_greedy_decoding.py +++ /dev/null @@ -1,3010 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Copyright 2017 Johns Hopkins University (Shinji Watanabe) -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from dataclasses import dataclass, field -from typing import List, Optional, Tuple, Union - -import numpy as np -import torch -from omegaconf import DictConfig, OmegaConf - -from nemo.collections.asr.modules import rnnt_abstract -from nemo.collections.asr.parts.context_biasing import BoostingTreeModelConfig, GPUBoostingTreeModel -from nemo.collections.asr.parts.submodules.ngram_lm import NGramGPULanguageModel -from nemo.collections.asr.parts.submodules.transducer_decoding import ( - GreedyBatchedRNNTLabelLoopingComputer, - GreedyBatchedTDTLabelLoopingComputer, -) -from nemo.collections.asr.parts.utils import rnnt_utils -from nemo.collections.asr.parts.utils.asr_confidence_utils import ConfidenceMethodConfig, ConfidenceMethodMixin -from nemo.collections.common.parts.optional_cuda_graphs import WithOptionalCudaGraphs -from nemo.collections.common.parts.rnn import label_collate -from nemo.core.classes import Typing, typecheck -from nemo.core.neural_types import AcousticEncodedRepresentation, HypothesisType, LengthsType, NeuralType -from nemo.utils import logging - - -def pack_hypotheses( - hypotheses: List[rnnt_utils.Hypothesis], - logitlen: torch.Tensor, -) -> List[rnnt_utils.Hypothesis]: - """ - Packs a list of hypotheses into a tensor and prepares decoder states. - - This function takes a list of token sequences (hypotheses) and converts - it into a tensor format. If any decoder states are on the GPU, they - are moved to the CPU. Additionally, the function removes any timesteps - with a value of -1 from the sequences. - - Args: - hypotheses (list): A list of token sequences representing hypotheses. - - Returns: - list: A list of packed hypotheses in tensor format. - """ - if hasattr(logitlen, 'cpu'): - logitlen_cpu = logitlen.to('cpu') - else: - logitlen_cpu = logitlen - - for idx, hyp in enumerate(hypotheses): # type: rnnt_utils.Hypothesis - hyp.y_sequence = ( - hyp.y_sequence.to(torch.long) - if isinstance(hyp.y_sequence, torch.Tensor) - else torch.tensor(hyp.y_sequence, dtype=torch.long) - ) - hyp.length = logitlen_cpu[idx] - - if hyp.dec_state is not None: - hyp.dec_state = _states_to_device(hyp.dec_state) - - return hypotheses - - -def _states_to_device(dec_state, device='cpu'): - if torch.is_tensor(dec_state): - dec_state = dec_state.to(device) - - elif isinstance(dec_state, (list, tuple)): - dec_state = tuple(_states_to_device(dec_i, device) for dec_i in dec_state) - - return dec_state - - -class _GreedyRNNTInfer(Typing, ConfidenceMethodMixin): - """A greedy transducer decoder. - - Provides a common abstraction for sample level and batch level greedy decoding. - - Args: - decoder_model: rnnt_utils.AbstractRNNTDecoder implementation. - joint_model: rnnt_utils.AbstractRNNTJoint implementation. - blank_index: int index of the blank token. Can be 0 or len(vocabulary). - max_symbols_per_step: Optional int. The maximum number of symbols that can be added - to a sequence in a single time step; if set to None then there is - no limit. - preserve_alignments: Bool flag which preserves the history of alignments generated during - greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `alignments` in it. Here, `alignments` is a List of List of - Tuple(Tensor (of length V + 1), Tensor(scalar, label after argmax)). - - The length of the list corresponds to the Acoustic Length (T). - Each value in the list (Ti) is a torch.Tensor (U), representing 1 or more targets from a vocabulary. - U is the number of target tokens for the current timestep Ti. - preserve_frame_confidence: Bool flag which preserves the history of per-frame confidence scores generated - during greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `frame_confidence` in it. Here, `frame_confidence` is a List of List of floats. - - The length of the list corresponds to the Acoustic Length (T). - Each value in the list (Ti) is a torch.Tensor (U), representing 1 or more confidence scores. - U is the number of target tokens for the current timestep Ti. - confidence_method_cfg: A dict-like object which contains the method name and settings to compute per-frame - confidence scores. - - name: The method name (str). - Supported values: - - 'max_prob' for using the maximum token probability as a confidence. - - 'entropy' for using a normalized entropy of a log-likelihood vector. - - entropy_type: Which type of entropy to use (str). Used if confidence_method_cfg.name is set to `entropy`. - Supported values: - - 'gibbs' for the (standard) Gibbs entropy. If the alpha (α) is provided, - the formula is the following: H_α = -sum_i((p^α_i)*log(p^α_i)). - Note that for this entropy, the alpha should comply the following inequality: - (log(V)+2-sqrt(log^2(V)+4))/(2*log(V)) <= α <= (1+log(V-1))/log(V-1) - where V is the model vocabulary size. - - 'tsallis' for the Tsallis entropy with the Boltzmann constant one. - Tsallis entropy formula is the following: H_α = 1/(α-1)*(1-sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/Tsallis_entropy - - 'renyi' for the Rényi entropy. - Rényi entropy formula is the following: H_α = 1/(1-α)*log_2(sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/R%C3%A9nyi_entropy - - alpha: Power scale for logsoftmax (α for entropies). Here we restrict it to be > 0. - When the alpha equals one, scaling is not applied to 'max_prob', - and any entropy type behaves like the Shannon entropy: H = -sum_i(p_i*log(p_i)) - - entropy_norm: A mapping of the entropy value to the interval [0,1]. - Supported values: - - 'lin' for using the linear mapping. - - 'exp' for using exponential mapping with linear shift. - """ - - @property - def input_types(self): - """Returns definitions of module input ports.""" - return { - "encoder_output": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), - "encoded_lengths": NeuralType(tuple('B'), LengthsType()), - "partial_hypotheses": [NeuralType(elements_type=HypothesisType(), optional=True)], # must always be last - } - - @property - def output_types(self): - """Returns definitions of module output ports.""" - return {"predictions": [NeuralType(elements_type=HypothesisType())]} - - def __init__( - self, - decoder_model: rnnt_abstract.AbstractRNNTDecoder, - joint_model: rnnt_abstract.AbstractRNNTJoint, - blank_index: int, - max_symbols_per_step: Optional[int] = None, - preserve_alignments: bool = False, - preserve_frame_confidence: bool = False, - confidence_method_cfg: Optional[DictConfig] = None, - ): - super().__init__() - self.decoder = decoder_model - self.joint = joint_model - - self._blank_index = blank_index - self._SOS = blank_index # Start of single index - - if max_symbols_per_step is not None and max_symbols_per_step <= 0: - raise ValueError(f"Expected max_symbols_per_step > 0 (or None), got {max_symbols_per_step}") - self.max_symbols = max_symbols_per_step - self.preserve_alignments = preserve_alignments - self.preserve_frame_confidence = preserve_frame_confidence - - # set confidence calculation method - self._init_confidence_method(confidence_method_cfg) - - def __call__(self, *args, **kwargs): - return self.forward(*args, **kwargs) - - @torch.no_grad() - def _pred_step( - self, - label: Union[torch.Tensor, int], - hidden: Optional[torch.Tensor], - add_sos: bool = False, - batch_size: Optional[int] = None, - ) -> Tuple[torch.Tensor, torch.Tensor]: - """ - Common prediction step based on the AbstractRNNTDecoder implementation. - - Args: - label: (int/torch.Tensor): Label or "Start-of-Signal" token. - hidden: (Optional torch.Tensor): RNN State vector - add_sos (bool): Whether to add a zero vector at the begging as "start of sentence" token. - batch_size: Batch size of the output tensor. - - Returns: - g: (B, U, H) if add_sos is false, else (B, U + 1, H) - hid: (h, c) where h is the final sequence hidden state and c is - the final cell state: - h (tensor), shape (L, B, H) - c (tensor), shape (L, B, H) - """ - if isinstance(label, torch.Tensor): - # label: [batch, 1] - if label.dtype != torch.long: - label = label.long() - - else: - # Label is an integer - if label == self._SOS: - return self.decoder.predict(None, hidden, add_sos=add_sos, batch_size=batch_size) - - label = label_collate([[label]]) - - # output: [B, 1, K] - return self.decoder.predict(label, hidden, add_sos=add_sos, batch_size=batch_size) - - def _joint_step(self, enc, pred, log_normalize: Optional[bool] = None): - """ - Common joint step based on AbstractRNNTJoint implementation. - - Args: - enc: Output of the Encoder model. A torch.Tensor of shape [B, 1, H1] - pred: Output of the Decoder model. A torch.Tensor of shape [B, 1, H2] - log_normalize: Whether to log normalize or not. None will log normalize only for CPU. - - Returns: - logits of shape (B, T=1, U=1, V + 1) - """ - with torch.no_grad(): - logits = self.joint.joint(enc, pred) - - if log_normalize is None: - if not logits.is_cuda: # Use log softmax only if on CPU - logits = logits.log_softmax(dim=len(logits.shape) - 1) - else: - if log_normalize: - logits = logits.log_softmax(dim=len(logits.shape) - 1) - - return logits - - def _joint_step_after_projection(self, enc, pred, log_normalize: Optional[bool] = None) -> torch.Tensor: - """ - Common joint step based on AbstractRNNTJoint implementation. - - Args: - enc: Output of the Encoder model after projection. A torch.Tensor of shape [B, 1, H] - pred: Output of the Decoder model after projection. A torch.Tensor of shape [B, 1, H] - log_normalize: Whether to log normalize or not. None will log normalize only for CPU. - - Returns: - logits of shape (B, T=1, U=1, V + 1) - """ - with torch.no_grad(): - logits = self.joint.joint_after_projection(enc, pred) - - if log_normalize is None: - if not logits.is_cuda: # Use log softmax only if on CPU - logits = logits.log_softmax(dim=len(logits.shape) - 1) - else: - if log_normalize: - logits = logits.log_softmax(dim=len(logits.shape) - 1) - - return logits - - -class GreedyRNNTInfer(_GreedyRNNTInfer): - """A greedy transducer decoder. - - Sequence level greedy decoding, performed auto-regressively. - - Args: - decoder_model: rnnt_utils.AbstractRNNTDecoder implementation. - joint_model: rnnt_utils.AbstractRNNTJoint implementation. - blank_index: int index of the blank token. Can be 0 or len(vocabulary). - max_symbols_per_step: Optional int. The maximum number of symbols that can be added - to a sequence in a single time step; if set to None then there is - no limit. - preserve_alignments: Bool flag which preserves the history of alignments generated during - greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `alignments` in it. Here, `alignments` is a List of List of - Tuple(Tensor (of length V + 1), Tensor(scalar, label after argmax)). - - The length of the list corresponds to the Acoustic Length (T). - Each value in the list (Ti) is a torch.Tensor (U), representing 1 or more targets from a vocabulary. - U is the number of target tokens for the current timestep Ti. - preserve_frame_confidence: Bool flag which preserves the history of per-frame confidence scores generated - during greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `frame_confidence` in it. Here, `frame_confidence` is a List of List of floats. - - The length of the list corresponds to the Acoustic Length (T). - Each value in the list (Ti) is a torch.Tensor (U), representing 1 or more confidence scores. - U is the number of target tokens for the current timestep Ti. - confidence_method_cfg: A dict-like object which contains the method name and settings to compute per-frame - confidence scores. - - name: The method name (str). - Supported values: - - 'max_prob' for using the maximum token probability as a confidence. - - 'entropy' for using a normalized entropy of a log-likelihood vector. - - entropy_type: Which type of entropy to use (str). Used if confidence_method_cfg.name is set to `entropy`. - Supported values: - - 'gibbs' for the (standard) Gibbs entropy. If the alpha (α) is provided, - the formula is the following: H_α = -sum_i((p^α_i)*log(p^α_i)). - Note that for this entropy, the alpha should comply the following inequality: - (log(V)+2-sqrt(log^2(V)+4))/(2*log(V)) <= α <= (1+log(V-1))/log(V-1) - where V is the model vocabulary size. - - 'tsallis' for the Tsallis entropy with the Boltzmann constant one. - Tsallis entropy formula is the following: H_α = 1/(α-1)*(1-sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/Tsallis_entropy - - 'renyi' for the Rényi entropy. - Rényi entropy formula is the following: H_α = 1/(1-α)*log_2(sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/R%C3%A9nyi_entropy - - alpha: Power scale for logsoftmax (α for entropies). Here we restrict it to be > 0. - When the alpha equals one, scaling is not applied to 'max_prob', - and any entropy type behaves like the Shannon entropy: H = -sum_i(p_i*log(p_i)) - - entropy_norm: A mapping of the entropy value to the interval [0,1]. - Supported values: - - 'lin' for using the linear mapping. - - 'exp' for using exponential mapping with linear shift. - """ - - def __init__( - self, - decoder_model: rnnt_abstract.AbstractRNNTDecoder, - joint_model: rnnt_abstract.AbstractRNNTJoint, - blank_index: int, - max_symbols_per_step: Optional[int] = None, - preserve_alignments: bool = False, - preserve_frame_confidence: bool = False, - confidence_method_cfg: Optional[DictConfig] = None, - ): - super().__init__( - decoder_model=decoder_model, - joint_model=joint_model, - blank_index=blank_index, - max_symbols_per_step=max_symbols_per_step, - preserve_alignments=preserve_alignments, - preserve_frame_confidence=preserve_frame_confidence, - confidence_method_cfg=confidence_method_cfg, - ) - - @typecheck() - def forward( - self, - encoder_output: torch.Tensor, - encoded_lengths: torch.Tensor, - partial_hypotheses: Optional[List[rnnt_utils.Hypothesis]] = None, - ): - """Returns a list of hypotheses given an input batch of the encoder hidden embedding. - Output token is generated auto-regressively. - - Args: - encoder_output: A tensor of size (batch, features, timesteps). - encoded_lengths: list of int representing the length of each sequence - output sequence. - - Returns: - packed list containing batch number of sentences (Hypotheses). - """ - # Preserve decoder and joint training state - decoder_training_state = self.decoder.training - joint_training_state = self.joint.training - - with torch.inference_mode(): - # Apply optional preprocessing - encoder_output = encoder_output.transpose(1, 2) # (B, T, D) - - self.decoder.eval() - self.joint.eval() - - hypotheses = [] - # Process each sequence independently - for batch_idx in range(encoder_output.size(0)): - inseq = encoder_output[batch_idx, :, :].unsqueeze(1) # [T, 1, D] - logitlen = encoded_lengths[batch_idx] - - partial_hypothesis = partial_hypotheses[batch_idx] if partial_hypotheses is not None else None - hypothesis = self._greedy_decode(inseq, logitlen, partial_hypotheses=partial_hypothesis) - hypotheses.append(hypothesis) - - # Pack results into Hypotheses - packed_result = pack_hypotheses(hypotheses, encoded_lengths) - - self.decoder.train(decoder_training_state) - self.joint.train(joint_training_state) - - return (packed_result,) - - @torch.no_grad() - def _greedy_decode( - self, x: torch.Tensor, out_len: torch.Tensor, partial_hypotheses: Optional[rnnt_utils.Hypothesis] = None - ): - # x: [T, 1, D] - # out_len: [seq_len] - - # Initialize blank state and empty label set in Hypothesis - hypothesis = rnnt_utils.Hypothesis(score=0.0, y_sequence=[], dec_state=None, timestamp=[], last_token=None) - - if partial_hypotheses is not None: - hypothesis.last_token = partial_hypotheses.last_token - hypothesis.y_sequence = ( - partial_hypotheses.y_sequence.cpu().tolist() - if isinstance(partial_hypotheses.y_sequence, torch.Tensor) - else partial_hypotheses.y_sequence - ) - if partial_hypotheses.dec_state is not None: - hypothesis.dec_state = self.decoder.batch_concat_states([partial_hypotheses.dec_state]) - hypothesis.dec_state = _states_to_device(hypothesis.dec_state, x.device) - - if self.preserve_alignments: - # Alignments is a 2-dimensional dangling list representing T x U - hypothesis.alignments = [[]] - - if self.preserve_frame_confidence: - hypothesis.frame_confidence = [[]] - - # For timestep t in X_t - for time_idx in range(out_len): - # Extract encoder embedding at timestep t - # f = x[time_idx, :, :].unsqueeze(0) # [1, 1, D] - f = x.narrow(dim=0, start=time_idx, length=1) - - # Setup exit flags and counter - not_blank = True - symbols_added = 0 - # While blank is not predicted, or we dont run out of max symbols per timestep - while not_blank and (self.max_symbols is None or symbols_added < self.max_symbols): - # In the first timestep, we initialize the network with RNNT Blank - # In later timesteps, we provide previous predicted label as input. - if hypothesis.last_token is None and hypothesis.dec_state is None: - last_label = self._SOS - else: - last_label = label_collate([[hypothesis.last_token]]) - - # Perform prediction network and joint network steps. - g, hidden_prime = self._pred_step(last_label, hypothesis.dec_state) - # If preserving per-frame confidence, log_normalize must be true - logp = self._joint_step(f, g, log_normalize=True if self.preserve_frame_confidence else None)[ - 0, 0, 0, : - ] - - del g - - # torch.max(0) op doesnt exist for FP 16. - if logp.dtype != torch.float32: - logp = logp.float() - - # get index k, of max prob - v, k = logp.max(0) - k = k.item() # K is the label at timestep t_s in inner loop, s >= 0. - - if self.preserve_alignments: - # insert logprobs into last timestep - hypothesis.alignments[-1].append((logp.to('cpu'), torch.tensor(k, dtype=torch.int32))) - - if self.preserve_frame_confidence: - # insert confidence into last timestep - hypothesis.frame_confidence[-1].append(self._get_confidence(logp)) - - del logp - - # If blank token is predicted, exit inner loop, move onto next timestep t - if k == self._blank_index: - not_blank = False - else: - # Append token to label set, update RNN state. - hypothesis.y_sequence.append(k) - hypothesis.score += float(v) - hypothesis.timestamp.append(time_idx) - hypothesis.dec_state = hidden_prime - hypothesis.last_token = k - - # Increment token counter. - symbols_added += 1 - - if self.preserve_alignments: - # convert Ti-th logits into a torch array - hypothesis.alignments.append([]) # blank buffer for next timestep - - if self.preserve_frame_confidence: - hypothesis.frame_confidence.append([]) # blank buffer for next timestep - - # Remove trailing empty list of Alignments - if self.preserve_alignments: - if len(hypothesis.alignments[-1]) == 0: - del hypothesis.alignments[-1] - - # Remove trailing empty list of per-frame confidence - if self.preserve_frame_confidence: - if len(hypothesis.frame_confidence[-1]) == 0: - del hypothesis.frame_confidence[-1] - - # Unpack the hidden states - hypothesis.dec_state = self.decoder.batch_select_state(hypothesis.dec_state, 0) - - return hypothesis - - -class GreedyBatchedRNNTInfer(_GreedyRNNTInfer, WithOptionalCudaGraphs): - """A batch level greedy transducer decoder. - - Batch level greedy decoding, performed auto-regressively. - - Args: - decoder_model: rnnt_utils.AbstractRNNTDecoder implementation. - joint_model: rnnt_utils.AbstractRNNTJoint implementation. - blank_index: int index of the blank token. Can be 0 or len(vocabulary). - max_symbols_per_step: Optional int. The maximum number of symbols that can be added - to a sequence in a single time step; if set to None then there is - no limit. - preserve_alignments: Bool flag which preserves the history of alignments generated during - greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `alignments` in it. Here, `alignments` is a List of List of - Tuple(Tensor (of length V + 1), Tensor(scalar, label after argmax)). - - The length of the list corresponds to the Acoustic Length (T). - Each value in the list (Ti) is a torch.Tensor (U), representing 1 or more targets from a vocabulary. - U is the number of target tokens for the current timestep Ti. - preserve_frame_confidence: Bool flag which preserves the history of per-frame confidence scores generated - during greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `frame_confidence` in it. Here, `frame_confidence` is a List of List of floats. - - The length of the list corresponds to the Acoustic Length (T). - Each value in the list (Ti) is a torch.Tensor (U), representing 1 or more confidence scores. - U is the number of target tokens for the current timestep Ti. - confidence_method_cfg: A dict-like object which contains the method name and settings to compute per-frame - confidence scores. - - name: The method name (str). - Supported values: - - 'max_prob' for using the maximum token probability as a confidence. - - 'entropy' for using a normalized entropy of a log-likelihood vector. - - entropy_type: Which type of entropy to use (str). Used if confidence_method_cfg.name is set to `entropy`. - Supported values: - - 'gibbs' for the (standard) Gibbs entropy. If the alpha (α) is provided, - the formula is the following: H_α = -sum_i((p^α_i)*log(p^α_i)). - Note that for this entropy, the alpha should comply the following inequality: - (log(V)+2-sqrt(log^2(V)+4))/(2*log(V)) <= α <= (1+log(V-1))/log(V-1) - where V is the model vocabulary size. - - 'tsallis' for the Tsallis entropy with the Boltzmann constant one. - Tsallis entropy formula is the following: H_α = 1/(α-1)*(1-sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/Tsallis_entropy - - 'renyi' for the Rényi entropy. - Rényi entropy formula is the following: H_α = 1/(1-α)*log_2(sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/R%C3%A9nyi_entropy - - alpha: Power scale for logsoftmax (α for entropies). Here we restrict it to be > 0. - When the alpha equals one, scaling is not applied to 'max_prob', - and any entropy type behaves like the Shannon entropy: H = -sum_i(p_i*log(p_i)) - - entropy_norm: A mapping of the entropy value to the interval [0,1]. - Supported values: - - 'lin' for using the linear mapping. - - 'exp' for using exponential mapping with linear shift. - loop_labels: Switching between decoding algorithms. Both algorithms produce equivalent results. - loop_labels=True (default) algorithm is faster (especially for large batches) but can use a bit more memory - (negligible overhead compared to the amount of memory used by the encoder). - loop_labels=False is an implementation of a traditional decoding algorithm, which iterates over - frames (encoder output vectors), and in the inner loop, decodes labels for the current frame one by one, - stopping when is found. - loop_labels=True iterates over labels, on each step finding the next non-blank label - (evaluating Joint multiple times in inner loop); It uses a minimal possible amount of calls - to prediction network (with maximum possible batch size), - which makes it especially useful for scaling the prediction network. - use_cuda_graph_decoder: if CUDA graphs should be enabled for decoding - (currently recommended only for inference) - fusion_models: list of fusion models (ngram_lm_model and boosting_tree_model) - fusion_models_alpha: list of fusion model weights (ngram_lm_alpha and boosting_tree_alpha) - enable_per_stream_biasing: enable multi-biasing model for per-stream customization - """ - - def __init__( - self, - decoder_model: rnnt_abstract.AbstractRNNTDecoder, - joint_model: rnnt_abstract.AbstractRNNTJoint, - blank_index: int, - max_symbols_per_step: Optional[int] = None, - preserve_alignments: bool = False, - preserve_frame_confidence: bool = False, - confidence_method_cfg: Optional[DictConfig] = None, - loop_labels: bool = True, - use_cuda_graph_decoder: bool = True, - fusion_models: Optional[List[NGramGPULanguageModel | GPUBoostingTreeModel]] = None, - fusion_models_alpha: Optional[List[float]] = None, - enable_per_stream_biasing: bool = False, - ): - super().__init__( - decoder_model=decoder_model, - joint_model=joint_model, - blank_index=blank_index, - max_symbols_per_step=max_symbols_per_step, - preserve_alignments=preserve_alignments, - preserve_frame_confidence=preserve_frame_confidence, - confidence_method_cfg=confidence_method_cfg, - ) - - self.use_cuda_graph_decoder = use_cuda_graph_decoder - self.loop_labels = loop_labels - - # Depending on availability of `blank_as_pad` support - # switch between more efficient batch decoding technique - self.decoding_computer = None - if self.decoder.blank_as_pad: - if self.loop_labels: - # Label-Looping algorithm (default, faster) - self._greedy_decode = self._greedy_decode_blank_as_pad_loop_labels - self.decoding_computer = GreedyBatchedRNNTLabelLoopingComputer( - decoder=self.decoder, - joint=self.joint, - blank_index=self._blank_index, - max_symbols_per_step=self.max_symbols, - preserve_alignments=preserve_alignments, - preserve_frame_confidence=preserve_frame_confidence, - confidence_method_cfg=confidence_method_cfg, - allow_cuda_graphs=self.use_cuda_graph_decoder, - fusion_models=fusion_models, - fusion_models_alpha=fusion_models_alpha, - enable_per_stream_biasing=enable_per_stream_biasing, - ) - else: - # Frame-Looping algorithm - if enable_per_stream_biasing: - raise NotImplementedError("Per-stream biasing is not implemented with frame-looping algorithm") - if fusion_models: - raise NotImplementedError( - "N-Gram Language Model and Boosting Tree fusion is not implemented with frame-looping algorithm" - ) - if not self.use_cuda_graph_decoder: - self._greedy_decode = self._greedy_decode_blank_as_pad_loop_frames - else: - if self.preserve_alignments: - logging.warning("`preserve_alignments` is not implemented for Frame-Looping + CUDA graphs") - self.use_cuda_graph_decoder = False - if self.preserve_frame_confidence: - logging.warning( - "`preserve_frame_confidence` is not implemented for Frame-Looping + CUDA graphs" - ) - self.use_cuda_graph_decoder = False - if not torch.cuda.is_available(): - self.use_cuda_graph_decoder = False - - if self.use_cuda_graph_decoder: - try: - from nemo.collections.asr.parts.submodules.cuda_graph_rnnt_greedy_decoding import ( - RNNTGreedyDecodeCudaGraph, - ) - - self._greedy_decode = RNNTGreedyDecodeCudaGraph(max_symbols_per_step, self) - except (ImportError, ModuleNotFoundError, ValueError, EnvironmentError) as e: - self.use_cuda_graph_decoder = False - logging.warning(f"Cannot use decoder with CUDA graphs, reason: {e}") - self._greedy_decode = self._greedy_decode_blank_as_pad_loop_frames - else: - self._greedy_decode = self._greedy_decode_blank_as_pad_loop_frames - else: - if fusion_models: - raise NotImplementedError( - "N-Gram Language Model and Boosting Tree fusion is not implemented with `blank_as_pad=False`" - ) - if enable_per_stream_biasing: - raise NotImplementedError("Per-stream biasing is not implemented with `blank_as_pad=False`") - self._greedy_decode = self._greedy_decode_masked - - def disable_cuda_graphs(self) -> bool: - """Disable CUDA graphs (e.g., for decoding in training)""" - if not self.use_cuda_graph_decoder: - # CUDA graphs not allowed, nothing to do - return False - - if not self.decoder.blank_as_pad: - # blank as pad uses decoding without CUDA graphs - return False - - if self.loop_labels: - # Label-Looping implementation - return self.decoding_computer.disable_cuda_graphs() - else: - greedy_decode_prev = self._greedy_decode - self._greedy_decode = self._greedy_decode_blank_as_pad_loop_frames - return self._greedy_decode != greedy_decode_prev - - def maybe_enable_cuda_graphs(self) -> bool: - """Enable CUDA graphs (if allowed)""" - if not self.use_cuda_graph_decoder: - # CUDA graphs not allowed, nothing to do - return False - - if not self.decoder.blank_as_pad: - # blank as pad uses decoding without CUDA graphs - return False - - if self.loop_labels: - # Label-Looping implementation - return self.decoding_computer.maybe_enable_cuda_graphs() - else: - from nemo.collections.asr.parts.submodules.cuda_graph_rnnt_greedy_decoding import RNNTGreedyDecodeCudaGraph - - greedy_decode_prev = self._greedy_decode - self._greedy_decode = RNNTGreedyDecodeCudaGraph(self.max_symbols, self) - return self._greedy_decode != greedy_decode_prev - - @typecheck() - def forward( - self, - encoder_output: torch.Tensor, - encoded_lengths: torch.Tensor, - partial_hypotheses: Optional[List[rnnt_utils.Hypothesis]] = None, - ): - """Returns a list of hypotheses given an input batch of the encoder hidden embedding. - Output token is generated auto-regressively. - - Args: - encoder_output: A tensor of size (batch, features, timesteps). - encoded_lengths: list of int representing the length of each sequence - output sequence. - - Returns: - packed list containing batch number of sentences (Hypotheses). - """ - # Preserve decoder and joint training state - decoder_training_state = self.decoder.training - joint_training_state = self.joint.training - - with torch.inference_mode(): - # Apply optional preprocessing - encoder_output = encoder_output.transpose(1, 2) # (B, T, D) - logitlen = encoded_lengths - - self.decoder.eval() - self.joint.eval() - - inseq = encoder_output # [B, T, D] - - hypotheses = self._greedy_decode( - inseq, logitlen, device=inseq.device, partial_hypotheses=partial_hypotheses - ) - - # Pack the hypotheses results - packed_result = pack_hypotheses(hypotheses, logitlen) - - self.decoder.train(decoder_training_state) - self.joint.train(joint_training_state) - - return (packed_result,) - - @torch.inference_mode() - def _greedy_decode_blank_as_pad_loop_labels( - self, - x: torch.Tensor, - out_len: torch.Tensor, - device: torch.device, - partial_hypotheses: Optional[list[rnnt_utils.Hypothesis | None]] = None, - ) -> list[rnnt_utils.Hypothesis]: - """ - Optimized batched greedy decoding. - The main idea: search for next labels for the whole batch (evaluating Joint) - and thus always evaluate prediction network with maximum possible batch size - """ - # setup batched state - if partial_hypotheses is None or all((hyp is None or hyp.dec_state is None) for hyp in partial_hypotheses): - batched_state = None - else: - batched_state = self.decoding_computer.merge_to_batched_state( - [hyp.dec_state if hyp is not None else None for hyp in partial_hypotheses] - ) - # setup fused biasing ids - if self.decoding_computer.per_stream_biasing_enabled: - batch_size = out_len.shape[0] - multi_biasing_ids = np.full([batch_size], fill_value=-1) - if partial_hypotheses is not None: - for batch_i, hyp in enumerate(partial_hypotheses): - if hyp is None or (not hyp.has_biasing_request()): - continue - # biasing_cfg is not empty - if hyp.biasing_cfg.multi_model_id is None: - logging.warning(f"Boosting tree requested in index {batch_i}, not compiled, skipping") - continue - multi_biasing_ids[batch_i] = hyp.biasing_cfg.multi_model_id - multi_biasing_ids = torch.from_numpy(multi_biasing_ids).to(device=x.device) - else: - multi_biasing_ids = None - batched_hyps, alignments, batched_state = self.decoding_computer( - x=x, - out_len=out_len, - prev_batched_state=batched_state, - multi_biasing_ids=multi_biasing_ids, - ) - hyps = rnnt_utils.batched_hyps_to_hypotheses(batched_hyps, alignments, batch_size=x.shape[0]) - for hyp, state_item in zip(hyps, self.decoding_computer.split_batched_state(batched_state)): - hyp.dec_state = state_item - - if partial_hypotheses: - for i, (hyp, hyp_continuation) in enumerate(zip(partial_hypotheses, hyps)): - if hyp is not None: - hyp.merge_(hyp_continuation) - else: - partial_hypotheses[i] = hyp_continuation - return partial_hypotheses - return hyps - - def _greedy_decode_blank_as_pad_loop_frames( - self, - x: torch.Tensor, - out_len: torch.Tensor, - device: torch.device, - partial_hypotheses: Optional[List[rnnt_utils.Hypothesis]] = None, - ): - if partial_hypotheses is not None: - raise NotImplementedError("`partial_hypotheses` support is not supported") - - with torch.inference_mode(): - # x: [B, T, D] - # out_len: [B] - # device: torch.device - - # Initialize list of Hypothesis - batchsize = x.shape[0] - hypotheses = [ - rnnt_utils.Hypothesis(score=0.0, y_sequence=[], timestamp=[], token_duration=[], dec_state=None) - for _ in range(batchsize) - ] - - # Initialize Hidden state matrix (shared by entire batch) - hidden = None - - # If alignments need to be preserved, register a dangling list to hold the values - if self.preserve_alignments: - # alignments is a 3-dimensional dangling list representing B x T x U - for hyp in hypotheses: - hyp.alignments = [[]] - - # If confidence scores need to be preserved, register a dangling list to hold the values - if self.preserve_frame_confidence: - # frame_confidence is a 3-dimensional dangling list representing B x T x U - for hyp in hypotheses: - hyp.frame_confidence = [[]] - - # Last Label buffer + Last Label without blank buffer - # batch level equivalent of the last_label - last_label = torch.full([batchsize, 1], fill_value=self._blank_index, dtype=torch.long, device=device) - - # Mask buffers - blank_mask = torch.full([batchsize], fill_value=0, dtype=torch.bool, device=device) - blank_mask_prev = None - - # Get max sequence length - max_out_len = out_len.max() - for time_idx in range(max_out_len): - f = x.narrow(dim=1, start=time_idx, length=1) # [B, 1, D] - - # Prepare t timestamp batch variables - not_blank = True - symbols_added = 0 - - # Reset blank mask - blank_mask.mul_(False) - - # Update blank mask with time mask - # Batch: [B, T, D], but Bi may have seq len < max(seq_lens_in_batch) - # Forcibly mask with "blank" tokens, for all sample where current time step T > seq_len - blank_mask = time_idx >= out_len - blank_mask_prev = blank_mask.clone() - - # Start inner loop - while not_blank and (self.max_symbols is None or symbols_added < self.max_symbols): - # Batch prediction and joint network steps - # If very first prediction step, submit SOS tag (blank) to pred_step. - # This feeds a zero tensor as input to AbstractRNNTDecoder to prime the state - if time_idx == 0 and symbols_added == 0 and hidden is None: - g, hidden_prime = self._pred_step(self._SOS, hidden, batch_size=batchsize) - else: - # Perform batch step prediction of decoder, getting new states and scores ("g") - g, hidden_prime = self._pred_step(last_label, hidden, batch_size=batchsize) - - # Batched joint step - Output = [B, V + 1] - # If preserving per-frame confidence, log_normalize must be true - logp = self._joint_step(f, g, log_normalize=True if self.preserve_frame_confidence else None)[ - :, 0, 0, : - ] - - if logp.dtype != torch.float32: - logp = logp.float() - - # Get index k, of max prob for batch - v, k = logp.max(1) - del g - - # Update blank mask with current predicted blanks - # This is accumulating blanks over all time steps T and all target steps min(max_symbols, U) - k_is_blank = k == self._blank_index - blank_mask.bitwise_or_(k_is_blank) - - del k_is_blank - - # If preserving alignments, check if sequence length of sample has been reached - # before adding alignment - if self.preserve_alignments: - # Insert logprobs into last timestep per sample - logp_vals = logp.to('cpu') - logp_ids = logp_vals.max(1)[1] - for batch_idx, is_blank in enumerate(blank_mask): - # we only want to update non-blanks and first-time blanks, - # otherwise alignments will contain duplicate predictions - if time_idx < out_len[batch_idx] and (not blank_mask_prev[batch_idx] or not is_blank): - hypotheses[batch_idx].alignments[-1].append( - (logp_vals[batch_idx], logp_ids[batch_idx]) - ) - del logp_vals - - # If preserving per-frame confidence, check if sequence length of sample has been reached - # before adding confidence scores - if self.preserve_frame_confidence: - # Insert probabilities into last timestep per sample - confidence = self._get_confidence(logp) - for batch_idx, is_blank in enumerate(blank_mask): - if time_idx < out_len[batch_idx] and (not blank_mask_prev[batch_idx] or not is_blank): - hypotheses[batch_idx].frame_confidence[-1].append(confidence[batch_idx]) - del logp - - blank_mask_prev.bitwise_or_(blank_mask) - - # If all samples predict / have predicted prior blanks, exit loop early - # This is equivalent to if single sample predicted k - if blank_mask.all(): - not_blank = False - else: - # Collect batch indices where blanks occurred now/past - blank_indices = (blank_mask == 1).nonzero(as_tuple=False) - - # Recover prior state for all samples which predicted blank now/past - if hidden is not None: - # LSTM has 2 states - hidden_prime = self.decoder.batch_copy_states(hidden_prime, hidden, blank_indices) - - elif len(blank_indices) > 0 and hidden is None: - # Reset state if there were some blank and other non-blank predictions in batch - # Original state is filled with zeros so we just multiply - # LSTM has 2 states - hidden_prime = self.decoder.batch_copy_states(hidden_prime, None, blank_indices, value=0.0) - - # Recover prior predicted label for all samples which predicted blank now/past - k[blank_indices] = last_label[blank_indices, 0] - - # Update new label and hidden state for next iteration - last_label = k.clone().view(-1, 1) - hidden = hidden_prime - - # Update predicted labels, accounting for time mask - # If blank was predicted even once, now or in the past, - # Force the current predicted label to also be blank - # This ensures that blanks propogate across all timesteps - # once they have occured (normally stopping condition of sample level loop). - for kidx, ki in enumerate(k): - if blank_mask[kidx] == 0: - hypotheses[kidx].y_sequence.append(ki) - hypotheses[kidx].timestamp.append(time_idx) - hypotheses[kidx].score += float(v[kidx]) - symbols_added += 1 - - # If preserving alignments, convert the current Uj alignments into a torch.Tensor - # Then preserve U at current timestep Ti - # Finally, forward the timestep history to Ti+1 for that sample - # All of this should only be done iff the current time index <= sample-level AM length. - # Otherwise ignore and move to next sample / next timestep. - if self.preserve_alignments: - - # convert Ti-th logits into a torch array - for batch_idx in range(batchsize): - - # this checks if current timestep <= sample-level AM length - # If current timestep > sample-level AM length, no alignments will be added - # Therefore the list of Uj alignments is empty here. - if len(hypotheses[batch_idx].alignments[-1]) > 0: - hypotheses[batch_idx].alignments.append([]) # blank buffer for next timestep - - # Do the same if preserving per-frame confidence - if self.preserve_frame_confidence: - - for batch_idx in range(batchsize): - if len(hypotheses[batch_idx].frame_confidence[-1]) > 0: - hypotheses[batch_idx].frame_confidence.append([]) # blank buffer for next timestep - - # Remove trailing empty list of alignments at T_{am-len} x Uj - if self.preserve_alignments: - for batch_idx in range(batchsize): - if len(hypotheses[batch_idx].alignments[-1]) == 0: - del hypotheses[batch_idx].alignments[-1] - - # Remove trailing empty list of confidence scores at T_{am-len} x Uj - if self.preserve_frame_confidence: - for batch_idx in range(batchsize): - if len(hypotheses[batch_idx].frame_confidence[-1]) == 0: - del hypotheses[batch_idx].frame_confidence[-1] - - # Preserve states - for batch_idx in range(batchsize): - hypotheses[batch_idx].dec_state = self.decoder.batch_select_state(hidden, batch_idx) - - return hypotheses - - def _greedy_decode_masked( - self, - x: torch.Tensor, - out_len: torch.Tensor, - device: torch.device, - partial_hypotheses: Optional[List[rnnt_utils.Hypothesis]] = None, - ): - if partial_hypotheses is not None: - raise NotImplementedError("`partial_hypotheses` support is not supported") - - # x: [B, T, D] - # out_len: [B] - # device: torch.device - - # Initialize state - batchsize = x.shape[0] - hypotheses = [ - rnnt_utils.Hypothesis(score=0.0, y_sequence=[], timestamp=[], dec_state=None) for _ in range(batchsize) - ] - - # Initialize Hidden state matrix (shared by entire batch) - hidden = None - - # If alignments need to be preserved, register a danling list to hold the values - if self.preserve_alignments: - # alignments is a 3-dimensional dangling list representing B x T x U - for hyp in hypotheses: - hyp.alignments = [[]] - - # If confidence scores need to be preserved, register a danling list to hold the values - if self.preserve_frame_confidence: - # frame_confidence is a 3-dimensional dangling list representing B x T x U - for hyp in hypotheses: - hyp.frame_confidence = [[]] - - # Last Label buffer + Last Label without blank buffer - # batch level equivalent of the last_label - last_label = torch.full([batchsize, 1], fill_value=self._blank_index, dtype=torch.long, device=device) - last_label_without_blank = last_label.clone() - - # Mask buffers - blank_mask = torch.full([batchsize], fill_value=0, dtype=torch.bool, device=device) - blank_mask_prev = None - - # Get max sequence length - max_out_len = out_len.max() - - with torch.inference_mode(): - for time_idx in range(max_out_len): - f = x.narrow(dim=1, start=time_idx, length=1) # [B, 1, D] - - # Prepare t timestamp batch variables - not_blank = True - symbols_added = 0 - - # Reset blank mask - blank_mask.mul_(False) - - # Update blank mask with time mask - # Batch: [B, T, D], but Bi may have seq len < max(seq_lens_in_batch) - # Forcibly mask with "blank" tokens, for all sample where current time step T > seq_len - blank_mask = time_idx >= out_len - blank_mask_prev = blank_mask.clone() - - # Start inner loop - while not_blank and (self.max_symbols is None or symbols_added < self.max_symbols): - # Batch prediction and joint network steps - # If very first prediction step, submit SOS tag (blank) to pred_step. - # This feeds a zero tensor as input to AbstractRNNTDecoder to prime the state - if time_idx == 0 and symbols_added == 0 and hidden is None: - g, hidden_prime = self._pred_step(self._SOS, hidden, batch_size=batchsize) - else: - # Set a dummy label for the blank value - # This value will be overwritten by "blank" again the last label update below - # This is done as vocabulary of prediction network does not contain "blank" token of RNNT - last_label_without_blank_mask = last_label == self._blank_index - last_label_without_blank[last_label_without_blank_mask] = 0 # temp change of label - last_label_without_blank[~last_label_without_blank_mask] = last_label[ - ~last_label_without_blank_mask - ] - - # Perform batch step prediction of decoder, getting new states and scores ("g") - g, hidden_prime = self._pred_step(last_label_without_blank, hidden, batch_size=batchsize) - - # Batched joint step - Output = [B, V + 1] - # If preserving per-frame confidence, log_normalize must be true - logp = self._joint_step(f, g, log_normalize=True if self.preserve_frame_confidence else None)[ - :, 0, 0, : - ] - - if logp.dtype != torch.float32: - logp = logp.float() - - # Get index k, of max prob for batch - v, k = logp.max(1) - del g - - # Update blank mask with current predicted blanks - # This is accumulating blanks over all time steps T and all target steps min(max_symbols, U) - k_is_blank = k == self._blank_index - blank_mask.bitwise_or_(k_is_blank) - - # If preserving alignments, check if sequence length of sample has been reached - # before adding alignment - if self.preserve_alignments: - # Insert logprobs into last timestep per sample - logp_vals = logp.to('cpu') - logp_ids = logp_vals.max(1)[1] - for batch_idx, is_blank in enumerate(blank_mask): - # we only want to update non-blanks and first-time blanks, - # otherwise alignments will contain duplicate predictions - if time_idx < out_len[batch_idx] and (not blank_mask_prev[batch_idx] or not is_blank): - hypotheses[batch_idx].alignments[-1].append( - (logp_vals[batch_idx], logp_ids[batch_idx]) - ) - - del logp_vals - - # If preserving per-frame confidence, check if sequence length of sample has been reached - # before adding confidence scores - if self.preserve_frame_confidence: - # Insert probabilities into last timestep per sample - confidence = self._get_confidence(logp) - for batch_idx, is_blank in enumerate(blank_mask): - if time_idx < out_len[batch_idx] and (not blank_mask_prev[batch_idx] or not is_blank): - hypotheses[batch_idx].frame_confidence[-1].append(confidence[batch_idx]) - del logp - - blank_mask_prev.bitwise_or_(blank_mask) - - # If all samples predict / have predicted prior blanks, exit loop early - # This is equivalent to if single sample predicted k - if blank_mask.all(): - not_blank = False - else: - # Collect batch indices where blanks occurred now/past - blank_indices = (blank_mask == 1).nonzero(as_tuple=False) - - # Recover prior state for all samples which predicted blank now/past - if hidden is not None: - # LSTM has 2 states - hidden_prime = self.decoder.batch_copy_states(hidden_prime, hidden, blank_indices) - - elif len(blank_indices) > 0 and hidden is None: - # Reset state if there were some blank and other non-blank predictions in batch - # Original state is filled with zeros so we just multiply - # LSTM has 2 states - hidden_prime = self.decoder.batch_copy_states(hidden_prime, None, blank_indices, value=0.0) - - # Recover prior predicted label for all samples which predicted blank now/past - k[blank_indices] = last_label[blank_indices, 0] - - # Update new label and hidden state for next iteration - last_label = k.view(-1, 1) - hidden = hidden_prime - - # Update predicted labels, accounting for time mask - # If blank was predicted even once, now or in the past, - # Force the current predicted label to also be blank - # This ensures that blanks propogate across all timesteps - # once they have occured (normally stopping condition of sample level loop). - for kidx, ki in enumerate(k): - if blank_mask[kidx] == 0: - hypotheses[kidx].y_sequence.append(ki) - hypotheses[kidx].timestamp.append(time_idx) - hypotheses[kidx].score += float(v[kidx]) - - symbols_added += 1 - - # If preserving alignments, convert the current Uj alignments into a torch.Tensor - # Then preserve U at current timestep Ti - # Finally, forward the timestep history to Ti+1 for that sample - # All of this should only be done iff the current time index <= sample-level AM length. - # Otherwise ignore and move to next sample / next timestep. - if self.preserve_alignments: - - # convert Ti-th logits into a torch array - for batch_idx in range(batchsize): - - # this checks if current timestep <= sample-level AM length - # If current timestep > sample-level AM length, no alignments will be added - # Therefore the list of Uj alignments is empty here. - if len(hypotheses[batch_idx].alignments[-1]) > 0: - hypotheses[batch_idx].alignments.append([]) # blank buffer for next timestep - - # Do the same if preserving per-frame confidence - if self.preserve_frame_confidence: - - for batch_idx in range(batchsize): - if len(hypotheses[batch_idx].frame_confidence[-1]) > 0: - hypotheses[batch_idx].frame_confidence.append([]) # blank buffer for next timestep - - # Remove trailing empty list of alignments at T_{am-len} x Uj - if self.preserve_alignments: - for batch_idx in range(batchsize): - if len(hypotheses[batch_idx].alignments[-1]) == 0: - del hypotheses[batch_idx].alignments[-1] - - # Remove trailing empty list of confidence scores at T_{am-len} x Uj - if self.preserve_frame_confidence: - for batch_idx in range(batchsize): - if len(hypotheses[batch_idx].frame_confidence[-1]) == 0: - del hypotheses[batch_idx].frame_confidence[-1] - - # Preserve states - for batch_idx in range(batchsize): - hypotheses[batch_idx].dec_state = self.decoder.batch_select_state(hidden, batch_idx) - - return hypotheses - - -class ExportedModelGreedyBatchedRNNTInfer: - """ - Exported Model Greedy Batched RNNT Infer class - """ - - def __init__(self, encoder_model: str, decoder_joint_model: str, max_symbols_per_step: Optional[int] = None): - self.encoder_model_path = encoder_model - self.decoder_joint_model_path = decoder_joint_model - self.max_symbols_per_step = max_symbols_per_step - - # Will be populated at runtime - self._blank_index = None - - def __call__(self, audio_signal: torch.Tensor, length: torch.Tensor): - """Returns a list of hypotheses given an input batch of the encoder hidden embedding. - Output token is generated auto-regressively. - - Args: - encoder_output: A tensor of size (batch, features, timesteps). - encoded_lengths: list of int representing the length of each sequence - output sequence. - - Returns: - packed list containing batch number of sentences (Hypotheses). - """ - with torch.no_grad(): - # Apply optional preprocessing - encoder_output, encoded_lengths = self.run_encoder(audio_signal=audio_signal, length=length) - - if torch.is_tensor(encoder_output): - encoder_output = encoder_output.transpose(1, 2) - else: - encoder_output = encoder_output.transpose([0, 2, 1]) # (B, T, D) - logitlen = encoded_lengths - - inseq = encoder_output # [B, T, D] - hypotheses, timestamps = self._greedy_decode(inseq, logitlen) - - # Pack the hypotheses results - packed_result = [rnnt_utils.Hypothesis(score=-1.0, y_sequence=[]) for _ in range(len(hypotheses))] - for i in range(len(packed_result)): - packed_result[i].y_sequence = torch.tensor(hypotheses[i], dtype=torch.long) - packed_result[i].length = timestamps[i] - - del hypotheses - - return packed_result - - def _greedy_decode(self, x, out_len): - # x: [B, T, D] - # out_len: [B] - - # Initialize state - batchsize = x.shape[0] - hidden = self._get_initial_states(batchsize) - target_lengths = torch.ones(batchsize, dtype=torch.int32) - - # Output string buffer - label = [[] for _ in range(batchsize)] - timesteps = [[] for _ in range(batchsize)] - - # Last Label buffer + Last Label without blank buffer - # batch level equivalent of the last_label - last_label = torch.full([batchsize, 1], fill_value=self._blank_index, dtype=torch.long).numpy() - if torch.is_tensor(x): - last_label = torch.from_numpy(last_label).to(self.device) - - # Mask buffers - blank_mask = torch.full([batchsize], fill_value=0, dtype=torch.bool).numpy() - - # Get max sequence length - max_out_len = out_len.max() - for time_idx in range(max_out_len): - f = x[:, time_idx : time_idx + 1, :] # [B, 1, D] - - if torch.is_tensor(f): - f = f.transpose(1, 2) - else: - f = f.transpose([0, 2, 1]) - - # Prepare t timestamp batch variables - not_blank = True - symbols_added = 0 - - # Reset blank mask - blank_mask *= False - - # Update blank mask with time mask - # Batch: [B, T, D], but Bi may have seq len < max(seq_lens_in_batch) - # Forcibly mask with "blank" tokens, for all sample where current time step T > seq_len - blank_mask = time_idx >= out_len - # Start inner loop - while not_blank and (self.max_symbols_per_step is None or symbols_added < self.max_symbols_per_step): - - # Batch prediction and joint network steps - # If very first prediction step, submit SOS tag (blank) to pred_step. - # This feeds a zero tensor as input to AbstractRNNTDecoder to prime the state - if time_idx == 0 and symbols_added == 0: - g = torch.tensor([self._blank_index] * batchsize, dtype=torch.int32).view(-1, 1) - else: - if torch.is_tensor(last_label): - g = last_label.type(torch.int32) - else: - g = last_label.astype(np.int32) - - # Batched joint step - Output = [B, V + 1] - joint_out, hidden_prime = self.run_decoder_joint(f, g, target_lengths, *hidden) - logp, pred_lengths = joint_out - logp = logp[:, 0, 0, :] - - # Get index k, of max prob for batch - if torch.is_tensor(logp): - v, k = logp.max(1) - else: - k = np.argmax(logp, axis=1).astype(np.int32) - - # Update blank mask with current predicted blanks - # This is accumulating blanks over all time steps T and all target steps min(max_symbols, U) - k_is_blank = k == self._blank_index - blank_mask |= k_is_blank - - del k_is_blank - del logp - - # If all samples predict / have predicted prior blanks, exit loop early - # This is equivalent to if single sample predicted k - if blank_mask.all(): - not_blank = False - - else: - # Collect batch indices where blanks occurred now/past - if torch.is_tensor(blank_mask): - blank_indices = (blank_mask == 1).nonzero(as_tuple=False) - else: - blank_indices = blank_mask.astype(np.int32).nonzero() - - if type(blank_indices) in (list, tuple): - blank_indices = blank_indices[0] - - # Recover prior state for all samples which predicted blank now/past - if hidden is not None: - # LSTM has 2 states - for state_id in range(len(hidden)): - hidden_prime[state_id][:, blank_indices, :] = hidden[state_id][:, blank_indices, :] - - elif len(blank_indices) > 0 and hidden is None: - # Reset state if there were some blank and other non-blank predictions in batch - # Original state is filled with zeros so we just multiply - # LSTM has 2 states - for state_id in range(len(hidden_prime)): - hidden_prime[state_id][:, blank_indices, :] *= 0.0 - - # Recover prior predicted label for all samples which predicted blank now/past - k[blank_indices] = last_label[blank_indices, 0] - - # Update new label and hidden state for next iteration - if torch.is_tensor(k): - last_label = k.clone().reshape(-1, 1) - else: - last_label = k.copy().reshape(-1, 1) - hidden = hidden_prime - - # Update predicted labels, accounting for time mask - # If blank was predicted even once, now or in the past, - # Force the current predicted label to also be blank - # This ensures that blanks propogate across all timesteps - # once they have occured (normally stopping condition of sample level loop). - for kidx, ki in enumerate(k): - if blank_mask[kidx] == 0: - label[kidx].append(ki) - timesteps[kidx].append(time_idx) - - symbols_added += 1 - - return label, timesteps - - def _setup_blank_index(self): - raise NotImplementedError() - - def run_encoder(self, audio_signal, length): - """ - Runs encoder network: - - Args: - audio_signal: audio signal - length: audio length - """ - raise NotImplementedError() - - def run_decoder_joint(self, enc_logits, targets, target_length, *states): - """ - Runs decoder joint networks. - - Args: - enc_logits: encoder logits - targets: targets - target_length: target length - states: states - """ - raise NotImplementedError() - - def _get_initial_states(self, batchsize): - raise NotImplementedError() - - -class ONNXGreedyBatchedRNNTInfer(ExportedModelGreedyBatchedRNNTInfer): - """ - ONNX Greedy Batched RNNT Infer class - """ - - def __init__(self, encoder_model: str, decoder_joint_model: str, max_symbols_per_step: Optional[int] = 10): - super().__init__( - encoder_model=encoder_model, - decoder_joint_model=decoder_joint_model, - max_symbols_per_step=max_symbols_per_step, - ) - - try: - import onnx - import onnxruntime - except (ModuleNotFoundError, ImportError): - raise ImportError("`onnx` or `onnxruntime` could not be imported, please install the libraries.\n") - - if torch.cuda.is_available(): - # Try to use onnxruntime-gpu - providers = ['TensorrtExecutionProvider', 'CUDAExecutionProvider'] - else: - # Fall back to CPU and onnxruntime-cpu - providers = ['CPUExecutionProvider'] - - onnx_session_opt = onnxruntime.SessionOptions() - onnx_session_opt.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_ENABLE_ALL - - onnx_model = onnx.load(self.encoder_model_path) - onnx.checker.check_model(onnx_model, full_check=True) - self.encoder_model = onnx_model - self.encoder = onnxruntime.InferenceSession( - onnx_model.SerializeToString(), providers=providers, provider_options=onnx_session_opt - ) - - onnx_model = onnx.load(self.decoder_joint_model_path) - onnx.checker.check_model(onnx_model, full_check=True) - self.decoder_joint_model = onnx_model - self.decoder_joint = onnxruntime.InferenceSession( - onnx_model.SerializeToString(), providers=providers, provider_options=onnx_session_opt - ) - - logging.info("Successfully loaded encoder, decoder and joint onnx models !") - - # Will be populated at runtime - self._blank_index = None - self.max_symbols_per_step = max_symbols_per_step - - self._setup_encoder_input_output_keys() - self._setup_decoder_joint_input_output_keys() - self._setup_blank_index() - - def _setup_encoder_input_output_keys(self): - self.encoder_inputs = list(self.encoder_model.graph.input) - self.encoder_outputs = list(self.encoder_model.graph.output) - - def _setup_decoder_joint_input_output_keys(self): - self.decoder_joint_inputs = list(self.decoder_joint_model.graph.input) - self.decoder_joint_outputs = list(self.decoder_joint_model.graph.output) - - def _setup_blank_index(self): - # ASSUME: Single input with no time length information - dynamic_dim = 257 - shapes = self.encoder_inputs[0].type.tensor_type.shape.dim - ip_shape = [] - for shape in shapes: - if hasattr(shape, 'dim_param') and 'dynamic' in shape.dim_param: - ip_shape.append(dynamic_dim) # replace dynamic axes with constant - else: - ip_shape.append(int(shape.dim_value)) - - enc_logits, encoded_length = self.run_encoder( - audio_signal=torch.randn(*ip_shape), length=torch.randint(0, 1, size=(dynamic_dim,)) - ) - - # prepare states - states = self._get_initial_states(batchsize=dynamic_dim) - - # run decoder 1 step - joint_out, states = self.run_decoder_joint(enc_logits, None, None, *states) - log_probs, lengths = joint_out - - self._blank_index = log_probs.shape[-1] - 1 # last token of vocab size is blank token - logging.info( - f"Enc-Dec-Joint step was evaluated, \ - blank token id = {self._blank_index}; vocab size = {log_probs.shape[-1]}" - ) - - def run_encoder(self, audio_signal, length): - if hasattr(audio_signal, 'cpu'): - audio_signal = audio_signal.cpu().numpy() - - if hasattr(length, 'cpu'): - length = length.cpu().numpy() - - ip = { - self.encoder_inputs[0].name: audio_signal, - self.encoder_inputs[1].name: length, - } - enc_out = self.encoder.run(None, ip) - enc_out, encoded_length = enc_out # ASSUME: single output - return enc_out, encoded_length - - def run_decoder_joint(self, enc_logits, targets, target_length, *states): - # ASSUME: Decoder is RNN Transducer - if targets is None: - targets = torch.zeros(enc_logits.shape[0], 1, dtype=torch.int32) - target_length = torch.ones(enc_logits.shape[0], dtype=torch.int32) - - if hasattr(targets, 'cpu'): - targets = targets.cpu().numpy() - - if hasattr(target_length, 'cpu'): - target_length = target_length.cpu().numpy() - - ip = { - self.decoder_joint_inputs[0].name: enc_logits, - self.decoder_joint_inputs[1].name: targets, - self.decoder_joint_inputs[2].name: target_length, - } - - num_states = 0 - if states is not None and len(states) > 0: - num_states = len(states) - for idx, state in enumerate(states): - if hasattr(state, 'cpu'): - state = state.cpu().numpy() - - ip[self.decoder_joint_inputs[len(ip)].name] = state - - dec_out = self.decoder_joint.run(None, ip) - - # unpack dec output - if num_states > 0: - new_states = dec_out[-num_states:] - dec_out = dec_out[:-num_states] - else: - new_states = None - - return dec_out, new_states - - def _get_initial_states(self, batchsize): - # ASSUME: LSTM STATES of shape (layers, batchsize, dim) - input_state_nodes = [ip for ip in self.decoder_joint_inputs if 'state' in ip.name] - num_states = len(input_state_nodes) - if num_states == 0: - return - - input_states = [] - for state_id in range(num_states): - node = input_state_nodes[state_id] - ip_shape = [] - for shape_idx, shape in enumerate(node.type.tensor_type.shape.dim): - if hasattr(shape, 'dim_param') and 'dynamic' in shape.dim_param: - ip_shape.append(batchsize) # replace dynamic axes with constant - else: - ip_shape.append(int(shape.dim_value)) - - input_states.append(torch.zeros(*ip_shape)) - - return input_states - - -class TorchscriptGreedyBatchedRNNTInfer(ExportedModelGreedyBatchedRNNTInfer): - """ - Torchscript Greedy Batched RNNT Infer - """ - - def __init__( - self, - encoder_model: str, - decoder_joint_model: str, - cfg: DictConfig, - device: str, - max_symbols_per_step: Optional[int] = 10, - ): - super().__init__( - encoder_model=encoder_model, - decoder_joint_model=decoder_joint_model, - max_symbols_per_step=max_symbols_per_step, - ) - - self.cfg = cfg - self.device = device - - self.encoder = torch.jit.load(self.encoder_model_path, map_location=self.device) - self.decoder_joint = torch.jit.load(self.decoder_joint_model_path, map_location=self.device) - - logging.info("Successfully loaded encoder, decoder and joint torchscript models !") - - # Will be populated at runtime - self._blank_index = None - self.max_symbols_per_step = max_symbols_per_step - - self._setup_encoder_input_keys() - self._setup_decoder_joint_input_keys() - self._setup_blank_index() - - def _setup_encoder_input_keys(self): - arguments = self.encoder.forward.schema.arguments[1:] - self.encoder_inputs = [arg for arg in arguments] - - def _setup_decoder_joint_input_keys(self): - arguments = self.decoder_joint.forward.schema.arguments[1:] - self.decoder_joint_inputs = [arg for arg in arguments] - - def _setup_blank_index(self): - self._blank_index = len(self.cfg.joint.vocabulary) - - logging.info(f"Blank token id = {self._blank_index}; vocab size = {len(self.cfg.joint.vocabulary) + 1}") - - def run_encoder(self, audio_signal, length): - enc_out = self.encoder(audio_signal, length) - enc_out, encoded_length = enc_out # ASSUME: single output - return enc_out, encoded_length - - def run_decoder_joint(self, enc_logits, targets, target_length, *states): - # ASSUME: Decoder is RNN Transducer - if targets is None: - targets = torch.zeros(enc_logits.shape[0], 1, dtype=torch.int32, device=enc_logits.device) - target_length = torch.ones(enc_logits.shape[0], dtype=torch.int32, device=enc_logits.device) - - num_states = 0 - if states is not None and len(states) > 0: - num_states = len(states) - - dec_out = self.decoder_joint(enc_logits, targets, target_length, *states) - - # unpack dec output - if num_states > 0: - new_states = dec_out[-num_states:] - dec_out = dec_out[:-num_states] - else: - new_states = None - - return dec_out, new_states - - def _get_initial_states(self, batchsize): - # ASSUME: LSTM STATES of shape (layers, batchsize, dim) - input_state_nodes = [ip for ip in self.decoder_joint_inputs if 'state' in ip.name] - num_states = len(input_state_nodes) - if num_states == 0: - return - - input_states = [] - for state_id in range(num_states): - # Hardcode shape size for LSTM (1 is for num layers in LSTM, which is flattened for export) - ip_shape = [1, batchsize, self.cfg.model_defaults.pred_hidden] - input_states.append(torch.zeros(*ip_shape, device=self.device)) - - return input_states - - -class GreedyMultiblankRNNTInfer(GreedyRNNTInfer): - """A greedy transducer decoder for multi-blank RNN-T. - - Sequence level greedy decoding, performed auto-regressively. - - Args: - decoder_model: rnnt_utils.AbstractRNNTDecoder implementation. - joint_model: rnnt_utils.AbstractRNNTJoint implementation. - blank_index: int index of the blank token. Must be len(vocabulary) for multi-blank RNNTs. - big_blank_durations: a list containing durations for big blanks the model supports. - max_symbols_per_step: Optional int. The maximum number of symbols that can be added - to a sequence in a single time step; if set to None then there is - no limit. - preserve_alignments: Bool flag which preserves the history of alignments generated during - greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `alignments` in it. Here, `alignments` is a List of List of - Tuple(Tensor (of length V + 1 + num-big-blanks), Tensor(scalar, label after argmax)). - The length of the list corresponds to the Acoustic Length (T). - Each value in the list (Ti) is a torch.Tensor (U), representing 1 or more targets from a vocabulary. - U is the number of target tokens for the current timestep Ti. - preserve_frame_confidence: Bool flag which preserves the history of per-frame confidence scores generated - during greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `frame_confidence` in it. Here, `frame_confidence` is a List of List of floats. - The length of the list corresponds to the Acoustic Length (T). - Each value in the list (Ti) is a torch.Tensor (U), representing 1 or more confidence scores. - U is the number of target tokens for the current timestep Ti. - confidence_method_cfg: A dict-like object which contains the method name and settings to compute per-frame - confidence scores. - - name: The method name (str). - Supported values: - - 'max_prob' for using the maximum token probability as a confidence. - - 'entropy' for using a normalized entropy of a log-likelihood vector. - - entropy_type: Which type of entropy to use (str). Used if confidence_method_cfg.name is set to `entropy`. - Supported values: - - 'gibbs' for the (standard) Gibbs entropy. If the alpha (α) is provided, - the formula is the following: H_α = -sum_i((p^α_i)*log(p^α_i)). - Note that for this entropy, the alpha should comply the following inequality: - (log(V)+2-sqrt(log^2(V)+4))/(2*log(V)) <= α <= (1+log(V-1))/log(V-1) - where V is the model vocabulary size. - - 'tsallis' for the Tsallis entropy with the Boltzmann constant one. - Tsallis entropy formula is the following: H_α = 1/(α-1)*(1-sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/Tsallis_entropy - - 'renyi' for the Rényi entropy. - Rényi entropy formula is the following: H_α = 1/(1-α)*log_2(sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/R%C3%A9nyi_entropy - - alpha: Power scale for logsoftmax (α for entropies). Here we restrict it to be > 0. - When the alpha equals one, scaling is not applied to 'max_prob', - and any entropy type behaves like the Shannon entropy: H = -sum_i(p_i*log(p_i)) - - entropy_norm: A mapping of the entropy value to the interval [0,1]. - Supported values: - - 'lin' for using the linear mapping. - - 'exp' for using exponential mapping with linear shift. - """ - - def __init__( - self, - decoder_model: rnnt_abstract.AbstractRNNTDecoder, - joint_model: rnnt_abstract.AbstractRNNTJoint, - blank_index: int, - big_blank_durations: list, - max_symbols_per_step: Optional[int] = None, - preserve_alignments: bool = False, - preserve_frame_confidence: bool = False, - confidence_method_cfg: Optional[DictConfig] = None, - ): - super().__init__( - decoder_model=decoder_model, - joint_model=joint_model, - blank_index=blank_index, - max_symbols_per_step=max_symbols_per_step, - preserve_alignments=preserve_alignments, - preserve_frame_confidence=preserve_frame_confidence, - confidence_method_cfg=confidence_method_cfg, - ) - self.big_blank_durations = big_blank_durations - self._SOS = blank_index - len(big_blank_durations) - - @torch.no_grad() - def _greedy_decode( - self, x: torch.Tensor, out_len: torch.Tensor, partial_hypotheses: Optional[rnnt_utils.Hypothesis] = None - ): - # x: [T, 1, D] - # out_len: [seq_len] - - # Initialize blank state and empty label set in Hypothesis - hypothesis = rnnt_utils.Hypothesis(score=0.0, y_sequence=[], dec_state=None, timestamp=[], last_token=None) - - if partial_hypotheses is not None: - hypothesis.last_token = partial_hypotheses.last_token - hypothesis.y_sequence = ( - partial_hypotheses.y_sequence.cpu().tolist() - if isinstance(partial_hypotheses.y_sequence, torch.Tensor) - else partial_hypotheses.y_sequence - ) - if partial_hypotheses.dec_state is not None: - hypothesis.dec_state = self.decoder.batch_concat_states([partial_hypotheses.dec_state]) - hypothesis.dec_state = _states_to_device(hypothesis.dec_state, x.device) - - if self.preserve_alignments: - # Alignments is a 2-dimensional dangling list representing T x U - hypothesis.alignments = [[]] - - if self.preserve_frame_confidence: - hypothesis.frame_confidence = [[]] - - # if this variable is > 1, it means the last emission was a big-blank and we need to skip frames. - big_blank_duration = 1 - - # For timestep t in X_t - for time_idx in range(out_len): - if big_blank_duration > 1: - # skip frames until big_blank_duration == 1. - big_blank_duration -= 1 - continue - # Extract encoder embedding at timestep t - # f = x[time_idx, :, :].unsqueeze(0) # [1, 1, D] - f = x.narrow(dim=0, start=time_idx, length=1) - - # Setup exit flags and counter - not_blank = True - symbols_added = 0 - - # While blank is not predicted, or we dont run out of max symbols per timestep - while not_blank and (self.max_symbols is None or symbols_added < self.max_symbols): - # In the first timestep, we initialize the network with RNNT Blank - # In later timesteps, we provide previous predicted label as input. - if hypothesis.last_token is None and hypothesis.dec_state is None: - last_label = self._SOS - else: - last_label = label_collate([[hypothesis.last_token]]) - - # Perform prediction network and joint network steps. - g, hidden_prime = self._pred_step(last_label, hypothesis.dec_state) - # If preserving per-frame confidence, log_normalize must be true - logp = self._joint_step(f, g, log_normalize=True if self.preserve_frame_confidence else None)[ - 0, 0, 0, : - ] - - del g - - # torch.max(0) op doesnt exist for FP 16. - if logp.dtype != torch.float32: - logp = logp.float() - - # get index k, of max prob - v, k = logp.max(0) - k = k.item() # K is the label at timestep t_s in inner loop, s >= 0. - - # Note, we have non-blanks in the vocab first, followed by big blanks, and standard blank at last. - # here we check if it's a big blank and if yes, set the duration variable. - if k >= self._blank_index - len(self.big_blank_durations) and k < self._blank_index: - big_blank_duration = self.big_blank_durations[self._blank_index - k - 1] - - if self.preserve_alignments: - # insert logprobs into last timestep - hypothesis.alignments[-1].append((logp.to('cpu'), torch.tensor(k, dtype=torch.int32))) - - if self.preserve_frame_confidence: - # insert confidence into last timestep - hypothesis.frame_confidence[-1].append(self._get_confidence(logp)) - - del logp - - # If any type of blank token is predicted, exit inner loop, move onto next timestep t - if k >= self._blank_index - len(self.big_blank_durations): - not_blank = False - else: - # Append token to label set, update RNN state. - hypothesis.y_sequence.append(k) - hypothesis.score += float(v) - hypothesis.timestamp.append(time_idx) - hypothesis.dec_state = hidden_prime - hypothesis.last_token = k - - # Increment token counter. - symbols_added += 1 - - if self.preserve_alignments: - # convert Ti-th logits into a torch array - hypothesis.alignments.append([]) # blank buffer for next timestep - - if self.preserve_frame_confidence: - hypothesis.frame_confidence.append([]) # blank buffer for next timestep - - # Remove trailing empty list of Alignments - if self.preserve_alignments: - if len(hypothesis.alignments[-1]) == 0: - del hypothesis.alignments[-1] - - # Remove trailing empty list of per-frame confidence - if self.preserve_frame_confidence: - if len(hypothesis.frame_confidence[-1]) == 0: - del hypothesis.frame_confidence[-1] - - # Unpack the hidden states - hypothesis.dec_state = self.decoder.batch_select_state(hypothesis.dec_state, 0) - - return hypothesis - - -class GreedyBatchedMultiblankRNNTInfer(GreedyBatchedRNNTInfer): - """A batch level greedy transducer decoder. - Batch level greedy decoding, performed auto-regressively. - Args: - decoder_model: rnnt_utils.AbstractRNNTDecoder implementation. - joint_model: rnnt_utils.AbstractRNNTJoint implementation. - blank_index: int index of the blank token. Must be len(vocabulary) for multi-blank RNNTs. - big_blank_durations: a list containing durations for big blanks the model supports. - max_symbols_per_step: Optional int. The maximum number of symbols that can be added - to a sequence in a single time step; if set to None then there is - no limit. - preserve_alignments: Bool flag which preserves the history of alignments generated during - greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `alignments` in it. Here, `alignments` is a List of List of - Tuple(Tensor (of length V + 1 + num-big-blanks), Tensor(scalar, label after argmax)). - The length of the list corresponds to the Acoustic Length (T). - Each value in the list (Ti) is a torch.Tensor (U), representing 1 or more targets from a vocabulary. - U is the number of target tokens for the current timestep Ti. - preserve_frame_confidence: Bool flag which preserves the history of per-frame confidence scores generated - during greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `frame_confidence` in it. Here, `frame_confidence` is a List of List of floats. - The length of the list corresponds to the Acoustic Length (T). - Each value in the list (Ti) is a torch.Tensor (U), representing 1 or more confidence scores. - U is the number of target tokens for the current timestep Ti. - confidence_method_cfg: A dict-like object which contains the method name and settings to compute per-frame - confidence scores. - - name: The method name (str). - Supported values: - - 'max_prob' for using the maximum token probability as a confidence. - - 'entropy' for using a normalized entropy of a log-likelihood vector. - - entropy_type: Which type of entropy to use (str). Used if confidence_method_cfg.name is set to `entropy`. - Supported values: - - 'gibbs' for the (standard) Gibbs entropy. If the alpha (α) is provided, - the formula is the following: H_α = -sum_i((p^α_i)*log(p^α_i)). - Note that for this entropy, the alpha should comply the following inequality: - (log(V)+2-sqrt(log^2(V)+4))/(2*log(V)) <= α <= (1+log(V-1))/log(V-1) - where V is the model vocabulary size. - - 'tsallis' for the Tsallis entropy with the Boltzmann constant one. - Tsallis entropy formula is the following: H_α = 1/(α-1)*(1-sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/Tsallis_entropy - - 'renyi' for the Rényi entropy. - Rényi entropy formula is the following: H_α = 1/(1-α)*log_2(sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/R%C3%A9nyi_entropy - - alpha: Power scale for logsoftmax (α for entropies). Here we restrict it to be > 0. - When the alpha equals one, scaling is not applied to 'max_prob', - and any entropy type behaves like the Shannon entropy: H = -sum_i(p_i*log(p_i)) - - entropy_norm: A mapping of the entropy value to the interval [0,1]. - Supported values: - - 'lin' for using the linear mapping. - - 'exp' for using exponential mapping with linear shift. - """ - - def __init__( - self, - decoder_model: rnnt_abstract.AbstractRNNTDecoder, - joint_model: rnnt_abstract.AbstractRNNTJoint, - blank_index: int, - big_blank_durations: List[int], - max_symbols_per_step: Optional[int] = None, - preserve_alignments: bool = False, - preserve_frame_confidence: bool = False, - confidence_method_cfg: Optional[DictConfig] = None, - ): - super().__init__( - decoder_model=decoder_model, - joint_model=joint_model, - blank_index=blank_index, - max_symbols_per_step=max_symbols_per_step, - preserve_alignments=preserve_alignments, - preserve_frame_confidence=preserve_frame_confidence, - confidence_method_cfg=confidence_method_cfg, - ) - self.big_blank_durations = big_blank_durations - - # Depending on availability of `blank_as_pad` support - # switch between more efficient batch decoding technique - if self.decoder.blank_as_pad: - self._greedy_decode = self._greedy_decode_blank_as_pad - else: - self._greedy_decode = self._greedy_decode_masked - self._SOS = blank_index - len(big_blank_durations) - - def _greedy_decode_blank_as_pad( - self, - x: torch.Tensor, - out_len: torch.Tensor, - device: torch.device, - partial_hypotheses: Optional[List[rnnt_utils.Hypothesis]] = None, - ): - if partial_hypotheses is not None: - raise NotImplementedError("`partial_hypotheses` support is not supported") - - with torch.inference_mode(): - # x: [B, T, D] - # out_len: [B] - # device: torch.device - - # Initialize list of Hypothesis - batchsize = x.shape[0] - hypotheses = [ - rnnt_utils.Hypothesis(score=0.0, y_sequence=[], timestamp=[], dec_state=None) for _ in range(batchsize) - ] - - # Initialize Hidden state matrix (shared by entire batch) - hidden = None - - # If alignments need to be preserved, register a danling list to hold the values - if self.preserve_alignments: - # alignments is a 3-dimensional dangling list representing B x T x U - for hyp in hypotheses: - hyp.alignments = [[]] - - # If confidence scores need to be preserved, register a danling list to hold the values - if self.preserve_frame_confidence: - # frame_confidence is a 3-dimensional dangling list representing B x T x U - for hyp in hypotheses: - hyp.frame_confidence = [[]] - - # Last Label buffer + Last Label without blank buffer - # batch level equivalent of the last_label - last_label = torch.full([batchsize, 1], fill_value=self._SOS, dtype=torch.long, device=device) - - # this mask is true for if the emission is *any type* of blank. - blank_mask = torch.full([batchsize], fill_value=0, dtype=torch.bool, device=device) - - # Get max sequence length - max_out_len = out_len.max() - - # We have a mask for each big blank. A mask is "true" means: the previous emission is exactly the big-blank - # with the corresponding duration, or has larger duration. E.g., for big_blank_mask for duration 2, it will - # be set true if the previous emission was a big blank with duration 4, or 3 or 2; but false if prevoius - # emission was a standard blank (with duration = 1). - big_blank_masks = [torch.full([batchsize], fill_value=0, dtype=torch.bool, device=device)] * len( - self.big_blank_durations - ) - - # if this variable > 1, it means the previous emission was big-blank and we need to skip frames. - big_blank_duration = 1 - - for time_idx in range(max_out_len): - if big_blank_duration > 1: - # skip frames until big_blank_duration == 1 - big_blank_duration -= 1 - continue - f = x.narrow(dim=1, start=time_idx, length=1) # [B, 1, D] - - # Prepare t timestamp batch variables - not_blank = True - symbols_added = 0 - - # Reset all blank masks - blank_mask.mul_(False) - for i in range(len(big_blank_masks)): - big_blank_masks[i].mul_(False) - - # Update blank mask with time mask - # Batch: [B, T, D], but Bi may have seq len < max(seq_lens_in_batch) - # Forcibly mask with "blank" tokens, for all sample where current time step T > seq_len - blank_mask = time_idx >= out_len - for i in range(len(big_blank_masks)): - big_blank_masks[i] = time_idx >= out_len - - # Start inner loop - while not_blank and (self.max_symbols is None or symbols_added < self.max_symbols): - # Batch prediction and joint network steps - # If very first prediction step, submit SOS tag (blank) to pred_step. - # This feeds a zero tensor as input to AbstractRNNTDecoder to prime the state - if time_idx == 0 and symbols_added == 0 and hidden is None: - g, hidden_prime = self._pred_step(self._SOS, hidden, batch_size=batchsize) - else: - # Perform batch step prediction of decoder, getting new states and scores ("g") - g, hidden_prime = self._pred_step(last_label, hidden, batch_size=batchsize) - - # Batched joint step - Output = [B, V + 1 + num-big-blanks] - # If preserving per-frame confidence, log_normalize must be true - logp = self._joint_step(f, g, log_normalize=True if self.preserve_frame_confidence else None)[ - :, 0, 0, : - ] - - if logp.dtype != torch.float32: - logp = logp.float() - - # Get index k, of max prob for batch - v, k = logp.max(1) - del g - - # Update blank mask with current predicted blanks - # This is accumulating blanks over all time steps T and all target steps min(max_symbols, U) - k_is_blank = k >= self._blank_index - len(self.big_blank_durations) - blank_mask.bitwise_or_(k_is_blank) - - for i in range(len(big_blank_masks)): - # using <= since as we mentioned before, the mask doesn't store exact matches. - # instead, it is True when the predicted blank's duration is >= the duration that the - # mask corresponds to. - k_is_big_blank = k <= self._blank_index - 1 - i - - # need to do a bitwise_and since it could also be a non-blank. - k_is_big_blank.bitwise_and_(k_is_blank) - big_blank_masks[i].bitwise_or_(k_is_big_blank) - - del k_is_blank - - # If preserving alignments, check if sequence length of sample has been reached - # before adding alignment - if self.preserve_alignments: - # Insert logprobs into last timestep per sample - logp_vals = logp.to('cpu') - logp_ids = logp_vals.max(1)[1] - for batch_idx in range(batchsize): - if time_idx < out_len[batch_idx]: - hypotheses[batch_idx].alignments[-1].append( - (logp_vals[batch_idx], logp_ids[batch_idx]) - ) - del logp_vals - - # If preserving per-frame confidence, check if sequence length of sample has been reached - # before adding confidence scores - if self.preserve_frame_confidence: - # Insert probabilities into last timestep per sample - confidence = self._get_confidence(logp) - for batch_idx in range(batchsize): - if time_idx < out_len[batch_idx]: - hypotheses[batch_idx].frame_confidence[-1].append(confidence[batch_idx]) - del logp - - # If all samples predict / have predicted prior blanks, exit loop early - # This is equivalent to if single sample predicted k - if blank_mask.all(): - not_blank = False - else: - # Collect batch indices where blanks occurred now/past - blank_indices = (blank_mask == 1).nonzero(as_tuple=False) - - # Recover prior state for all samples which predicted blank now/past - if hidden is not None: - # LSTM has 2 states - hidden_prime = self.decoder.batch_copy_states(hidden_prime, hidden, blank_indices) - - elif len(blank_indices) > 0 and hidden is None: - # Reset state if there were some blank and other non-blank predictions in batch - # Original state is filled with zeros so we just multiply - # LSTM has 2 states - hidden_prime = self.decoder.batch_copy_states(hidden_prime, None, blank_indices, value=0.0) - - # Recover prior predicted label for all samples which predicted blank now/past - k[blank_indices] = last_label[blank_indices, 0] - - # Update new label and hidden state for next iteration - last_label = k.clone().view(-1, 1) - hidden = hidden_prime - - # Update predicted labels, accounting for time mask - # If blank was predicted even once, now or in the past, - # Force the current predicted label to also be blank - # This ensures that blanks propogate across all timesteps - # once they have occured (normally stopping condition of sample level loop). - for kidx, ki in enumerate(k): - if blank_mask[kidx] == 0: - hypotheses[kidx].y_sequence.append(ki) - hypotheses[kidx].timestamp.append(time_idx) - hypotheses[kidx].score += float(v[kidx]) - - symbols_added += 1 - - for i in range(len(big_blank_masks) + 1): - # The task here is find the shortest blank duration of all batches. - # so we start from the shortest blank duration and go up, - # and stop once we found the duration whose corresponding mask isn't all True. - if i == len(big_blank_masks) or not big_blank_masks[i].all(): - big_blank_duration = self.big_blank_durations[i - 1] if i > 0 else 1 - break - - # If preserving alignments, convert the current Uj alignments into a torch.Tensor - # Then preserve U at current timestep Ti - # Finally, forward the timestep history to Ti+1 for that sample - # All of this should only be done iff the current time index <= sample-level AM length. - # Otherwise ignore and move to next sample / next timestep. - if self.preserve_alignments: - - # convert Ti-th logits into a torch array - for batch_idx in range(batchsize): - - # this checks if current timestep <= sample-level AM length - # If current timestep > sample-level AM length, no alignments will be added - # Therefore the list of Uj alignments is empty here. - if len(hypotheses[batch_idx].alignments[-1]) > 0: - hypotheses[batch_idx].alignments.append([]) # blank buffer for next timestep - - # Do the same if preserving per-frame confidence - if self.preserve_frame_confidence: - - for batch_idx in range(batchsize): - if len(hypotheses[batch_idx].frame_confidence[-1]) > 0: - hypotheses[batch_idx].frame_confidence.append([]) # blank buffer for next timestep - - # Remove trailing empty list of alignments at T_{am-len} x Uj - if self.preserve_alignments: - for batch_idx in range(batchsize): - if len(hypotheses[batch_idx].alignments[-1]) == 0: - del hypotheses[batch_idx].alignments[-1] - - # Remove trailing empty list of confidence scores at T_{am-len} x Uj - if self.preserve_frame_confidence: - for batch_idx in range(batchsize): - if len(hypotheses[batch_idx].frame_confidence[-1]) == 0: - del hypotheses[batch_idx].frame_confidence[-1] - - # Preserve states - for batch_idx in range(batchsize): - hypotheses[batch_idx].dec_state = self.decoder.batch_select_state(hidden, batch_idx) - - return hypotheses - - def _greedy_decode_masked( - self, - x: torch.Tensor, - out_len: torch.Tensor, - device: torch.device, - partial_hypotheses: Optional[List[rnnt_utils.Hypothesis]] = None, - ): - if partial_hypotheses is not None: - raise NotImplementedError("`partial_hypotheses` support is not supported") - - if self.big_blank_durations != [1] * len(self.big_blank_durations): - raise NotImplementedError( - "Efficient frame-skipping version for multi-blank masked decoding is not supported." - ) - - # x: [B, T, D] - # out_len: [B] - # device: torch.device - - # Initialize state - batchsize = x.shape[0] - hypotheses = [ - rnnt_utils.Hypothesis(score=0.0, y_sequence=[], timestamp=[], dec_state=None) for _ in range(batchsize) - ] - - # Initialize Hidden state matrix (shared by entire batch) - hidden = None - - # If alignments need to be preserved, register a danling list to hold the values - if self.preserve_alignments: - # alignments is a 3-dimensional dangling list representing B x T x U - for hyp in hypotheses: - hyp.alignments = [[]] - else: - hyp.alignments = None - - # If confidence scores need to be preserved, register a danling list to hold the values - if self.preserve_frame_confidence: - # frame_confidence is a 3-dimensional dangling list representing B x T x U - for hyp in hypotheses: - hyp.frame_confidence = [[]] - - # Last Label buffer + Last Label without blank buffer - # batch level equivalent of the last_label - last_label = torch.full([batchsize, 1], fill_value=self._blank_index, dtype=torch.long, device=device) - last_label_without_blank = last_label.clone() - - # Mask buffers - blank_mask = torch.full([batchsize], fill_value=0, dtype=torch.bool, device=device) - - # Get max sequence length - max_out_len = out_len.max() - - with torch.inference_mode(): - for time_idx in range(max_out_len): - f = x.narrow(dim=1, start=time_idx, length=1) # [B, 1, D] - - # Prepare t timestamp batch variables - not_blank = True - symbols_added = 0 - - # Reset blank mask - blank_mask.mul_(False) - - # Update blank mask with time mask - # Batch: [B, T, D], but Bi may have seq len < max(seq_lens_in_batch) - # Forcibly mask with "blank" tokens, for all sample where current time step T > seq_len - blank_mask = time_idx >= out_len - - # Start inner loop - while not_blank and (self.max_symbols is None or symbols_added < self.max_symbols): - # Batch prediction and joint network steps - # If very first prediction step, submit SOS tag (blank) to pred_step. - # This feeds a zero tensor as input to AbstractRNNTDecoder to prime the state - if time_idx == 0 and symbols_added == 0 and hidden is None: - g, hidden_prime = self._pred_step(self._SOS, hidden, batch_size=batchsize) - else: - # Set a dummy label for the blank value - # This value will be overwritten by "blank" again the last label update below - # This is done as vocabulary of prediction network does not contain "blank" token of RNNT - last_label_without_blank_mask = last_label >= self._blank_index - last_label_without_blank[last_label_without_blank_mask] = 0 # temp change of label - last_label_without_blank[~last_label_without_blank_mask] = last_label[ - ~last_label_without_blank_mask - ] - - # Perform batch step prediction of decoder, getting new states and scores ("g") - g, hidden_prime = self._pred_step(last_label_without_blank, hidden, batch_size=batchsize) - - # Batched joint step - Output = [B, V + 1 + num-big-blanks] - # If preserving per-frame confidence, log_normalize must be true - logp = self._joint_step(f, g, log_normalize=True if self.preserve_frame_confidence else None)[ - :, 0, 0, : - ] - - if logp.dtype != torch.float32: - logp = logp.float() - - # Get index k, of max prob for batch - v, k = logp.max(1) - del g - - # Update blank mask with current predicted blanks - # This is accumulating blanks over all time steps T and all target steps min(max_symbols, U) - k_is_blank = k == self._blank_index - blank_mask.bitwise_or_(k_is_blank) - - # If preserving alignments, check if sequence length of sample has been reached - # before adding alignment - if self.preserve_alignments: - # Insert logprobs into last timestep per sample - logp_vals = logp.to('cpu') - logp_ids = logp_vals.max(1)[1] - for batch_idx in range(batchsize): - if time_idx < out_len[batch_idx]: - hypotheses[batch_idx].alignments[-1].append( - (logp_vals[batch_idx], logp_ids[batch_idx]) - ) - del logp_vals - - # If preserving per-frame confidence, check if sequence length of sample has been reached - # before adding confidence scores - if self.preserve_frame_confidence: - # Insert probabilities into last timestep per sample - confidence = self._get_confidence(logp) - for batch_idx in range(batchsize): - if time_idx < out_len[batch_idx]: - hypotheses[batch_idx].frame_confidence[-1].append(confidence[batch_idx]) - del logp - - # If all samples predict / have predicted prior blanks, exit loop early - # This is equivalent to if single sample predicted k - if blank_mask.all(): - not_blank = False - else: - # Collect batch indices where blanks occurred now/past - blank_indices = (blank_mask == 1).nonzero(as_tuple=False) - - # Recover prior state for all samples which predicted blank now/past - if hidden is not None: - # LSTM has 2 states - hidden_prime = self.decoder.batch_copy_states(hidden_prime, hidden, blank_indices) - - elif len(blank_indices) > 0 and hidden is None: - # Reset state if there were some blank and other non-blank predictions in batch - # Original state is filled with zeros so we just multiply - # LSTM has 2 states - hidden_prime = self.decoder.batch_copy_states(hidden_prime, None, blank_indices, value=0.0) - - # Recover prior predicted label for all samples which predicted blank now/past - k[blank_indices] = last_label[blank_indices, 0] - - # Update new label and hidden state for next iteration - last_label = k.view(-1, 1) - hidden = hidden_prime - - # Update predicted labels, accounting for time mask - # If blank was predicted even once, now or in the past, - # Force the current predicted label to also be blank - # This ensures that blanks propogate across all timesteps - # once they have occured (normally stopping condition of sample level loop). - for kidx, ki in enumerate(k): - if blank_mask[kidx] == 0: - hypotheses[kidx].y_sequence.append(ki) - hypotheses[kidx].timestamp.append(time_idx) - hypotheses[kidx].score += float(v[kidx]) - - symbols_added += 1 - - # If preserving alignments, convert the current Uj alignments into a torch.Tensor - # Then preserve U at current timestep Ti - # Finally, forward the timestep history to Ti+1 for that sample - # All of this should only be done iff the current time index <= sample-level AM length. - # Otherwise ignore and move to next sample / next timestep. - if self.preserve_alignments: - - # convert Ti-th logits into a torch array - for batch_idx in range(batchsize): - - # this checks if current timestep <= sample-level AM length - # If current timestep > sample-level AM length, no alignments will be added - # Therefore the list of Uj alignments is empty here. - if len(hypotheses[batch_idx].alignments[-1]) > 0: - hypotheses[batch_idx].alignments.append([]) # blank buffer for next timestep - - # Do the same if preserving per-frame confidence - if self.preserve_frame_confidence: - - for batch_idx in range(batchsize): - if len(hypotheses[batch_idx].frame_confidence[-1]) > 0: - hypotheses[batch_idx].frame_confidence.append([]) # blank buffer for next timestep - - # Remove trailing empty list of alignments at T_{am-len} x Uj - if self.preserve_alignments: - for batch_idx in range(batchsize): - if len(hypotheses[batch_idx].alignments[-1]) == 0: - del hypotheses[batch_idx].alignments[-1] - - # Remove trailing empty list of confidence scores at T_{am-len} x Uj - if self.preserve_frame_confidence: - for batch_idx in range(batchsize): - if len(hypotheses[batch_idx].frame_confidence[-1]) == 0: - del hypotheses[batch_idx].frame_confidence[-1] - - # Preserve states - for batch_idx in range(batchsize): - hypotheses[batch_idx].dec_state = self.decoder.batch_select_state(hidden, batch_idx) - - return hypotheses - - -@dataclass -class GreedyRNNTInferConfig: - """Greedy RNNT Infer Config""" - - max_symbols_per_step: Optional[int] = 10 - preserve_alignments: bool = False - preserve_frame_confidence: bool = False - tdt_include_token_duration: bool = False - tdt_include_duration_confidence: bool = False - confidence_method_cfg: Optional[ConfidenceMethodConfig] = field(default_factory=lambda: ConfidenceMethodConfig()) - - def __post_init__(self): - # OmegaConf.structured ensures that post_init check is always executed - self.confidence_method_cfg = OmegaConf.structured( - self.confidence_method_cfg - if isinstance(self.confidence_method_cfg, ConfidenceMethodConfig) - else ConfidenceMethodConfig(**self.confidence_method_cfg) - ) - - -@dataclass -class GreedyBatchedRNNTInferConfig: - """Greedy Batched RNNT Infer Config""" - - max_symbols_per_step: Optional[int] = 10 - preserve_alignments: bool = False - preserve_frame_confidence: bool = False - tdt_include_token_duration: bool = False - tdt_include_duration_confidence: bool = False - confidence_method_cfg: Optional[ConfidenceMethodConfig] = field(default_factory=lambda: ConfidenceMethodConfig()) - loop_labels: bool = True - use_cuda_graph_decoder: bool = True - ngram_lm_model: Optional[str] = None - ngram_lm_alpha: float = 0.0 - boosting_tree: BoostingTreeModelConfig = field(default_factory=BoostingTreeModelConfig) - boosting_tree_alpha: float = 0.0 - enable_per_stream_biasing: bool = False - - def __post_init__(self): - # OmegaConf.structured ensures that post_init check is always executed - self.confidence_method_cfg = OmegaConf.structured( - self.confidence_method_cfg - if isinstance(self.confidence_method_cfg, ConfidenceMethodConfig) - else ConfidenceMethodConfig(**self.confidence_method_cfg) - ) - - -class GreedyTDTInfer(_GreedyRNNTInfer): - """A greedy TDT decoder. - - Sequence level greedy decoding, performed auto-regressively. - - Args: - decoder_model: rnnt_utils.AbstractRNNTDecoder implementation. - joint_model: rnnt_utils.AbstractRNNTJoint implementation. - blank_index: int index of the blank token. Must be len(vocabulary) for TDT models. - durations: a list containing durations for TDT. - max_symbols_per_step: Optional int. The maximum number of symbols that can be added - to a sequence in a single time step; if set to None then there is - no limit. - preserve_alignments: Bool flag which preserves the history of alignments generated during - greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `alignments` in it. Here, `alignments` is a List of List of - Tuple(Tensor (of length V + 1 + num-big-blanks), Tensor(scalar, label after argmax)). - The length of the list corresponds to the Acoustic Length (T). - Each value in the list (Ti) is a torch.Tensor (U), representing 1 or more targets from a vocabulary. - U is the number of target tokens for the current timestep Ti. - preserve_frame_confidence: Bool flag which preserves the history of per-frame confidence scores generated - during greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `frame_confidence` in it. Here, `frame_confidence` is a List of List of floats. - The length of the list corresponds to the Acoustic Length (T). - Each value in the list (Ti) is a torch.Tensor (U), representing 1 or more confidence scores. - U is the number of target tokens for the current timestep Ti. - include_duration: Bool flag, which determines whether predicted durations for each token - need to be included in the Hypothesis object. Defaults to False. - include_duration_confidence: Bool flag indicating that the duration confidence scores are to be calculated and - attached to the regular frame confidence, - making TDT frame confidence element a pair: (`prediction_confidence`, `duration_confidence`). - confidence_method_cfg: A dict-like object which contains the method name and settings to compute per-frame - confidence scores. - - name: The method name (str). - Supported values: - - 'max_prob' for using the maximum token probability as a confidence. - - 'entropy' for using a normalized entropy of a log-likelihood vector. - - entropy_type: Which type of entropy to use (str). Used if confidence_method_cfg.name is set to `entropy`. - Supported values: - - 'gibbs' for the (standard) Gibbs entropy. If the alpha (α) is provided, - the formula is the following: H_α = -sum_i((p^α_i)*log(p^α_i)). - Note that for this entropy, the alpha should comply the following inequality: - (log(V)+2-sqrt(log^2(V)+4))/(2*log(V)) <= α <= (1+log(V-1))/log(V-1) - where V is the model vocabulary size. - - 'tsallis' for the Tsallis entropy with the Boltzmann constant one. - Tsallis entropy formula is the following: H_α = 1/(α-1)*(1-sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/Tsallis_entropy - - 'renyi' for the Rényi entropy. - Rényi entropy formula is the following: H_α = 1/(1-α)*log_2(sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/R%C3%A9nyi_entropy - - alpha: Power scale for logsoftmax (α for entropies). Here we restrict it to be > 0. - When the alpha equals one, scaling is not applied to 'max_prob', - and any entropy type behaves like the Shannon entropy: H = -sum_i(p_i*log(p_i)) - - entropy_norm: A mapping of the entropy value to the interval [0,1]. - Supported values: - - 'lin' for using the linear mapping. - - 'exp' for using exponential mapping with linear shift. - """ - - def __init__( - self, - decoder_model: rnnt_abstract.AbstractRNNTDecoder, - joint_model: rnnt_abstract.AbstractRNNTJoint, - blank_index: int, - durations: list, - max_symbols_per_step: Optional[int] = None, - preserve_alignments: bool = False, - preserve_frame_confidence: bool = False, - include_duration: bool = False, - include_duration_confidence: bool = False, - confidence_method_cfg: Optional[DictConfig] = None, - ): - super().__init__( - decoder_model=decoder_model, - joint_model=joint_model, - blank_index=blank_index, - max_symbols_per_step=max_symbols_per_step, - preserve_alignments=preserve_alignments, - preserve_frame_confidence=preserve_frame_confidence, - confidence_method_cfg=confidence_method_cfg, - ) - self.durations = durations - self.include_duration = include_duration - self.include_duration_confidence = include_duration_confidence - - @typecheck() - def forward( - self, - encoder_output: torch.Tensor, - encoded_lengths: torch.Tensor, - partial_hypotheses: Optional[List[rnnt_utils.Hypothesis]] = None, - ): - """Returns a list of hypotheses given an input batch of the encoder hidden embedding. - Output token is generated auto-regressively. - - Args: - encoder_output: A tensor of size (batch, features, timesteps). - encoded_lengths: list of int representing the length of each sequence - output sequence. - - Returns: - packed list containing batch number of sentences (Hypotheses). - """ - # Preserve decoder and joint training state - decoder_training_state = self.decoder.training - joint_training_state = self.joint.training - - with torch.inference_mode(): - # Apply optional preprocessing - encoder_output = encoder_output.transpose(1, 2) # (B, T, D) - - self.decoder.eval() - self.joint.eval() - - hypotheses = [] - # Process each sequence independently - for batch_idx in range(encoder_output.size(0)): - inseq = encoder_output[batch_idx, :, :].unsqueeze(1) # [T, 1, D] - logitlen = encoded_lengths[batch_idx] - - partial_hypothesis = partial_hypotheses[batch_idx] if partial_hypotheses is not None else None - hypothesis = self._greedy_decode(inseq, logitlen, partial_hypotheses=partial_hypothesis) - hypotheses.append(hypothesis) - - # Pack results into Hypotheses - packed_result = pack_hypotheses(hypotheses, encoded_lengths) - - self.decoder.train(decoder_training_state) - self.joint.train(joint_training_state) - - return (packed_result,) - - @torch.no_grad() - def _greedy_decode( - self, x: torch.Tensor, out_len: torch.Tensor, partial_hypotheses: Optional[rnnt_utils.Hypothesis] = None - ): - # x: [T, 1, D] - # out_len: [seq_len] - - # Initialize blank state and empty label set in Hypothesis - hypothesis = rnnt_utils.Hypothesis( - score=0.0, y_sequence=[], dec_state=None, timestamp=[], token_duration=[], last_token=None - ) - - if partial_hypotheses is not None: - hypothesis.last_token = partial_hypotheses.last_token - hypothesis.y_sequence = ( - partial_hypotheses.y_sequence.cpu().tolist() - if isinstance(partial_hypotheses.y_sequence, torch.Tensor) - else partial_hypotheses.y_sequence - ) - if partial_hypotheses.dec_state is not None: - hypothesis.dec_state = self.decoder.batch_concat_states([partial_hypotheses.dec_state]) - hypothesis.dec_state = _states_to_device(hypothesis.dec_state, x.device) - - if self.preserve_alignments: - # Alignments is a 2-dimensional dangling list representing T x U - hypothesis.alignments = [[]] - - if self.preserve_frame_confidence: - hypothesis.frame_confidence = [[]] - - time_idx = 0 - while time_idx < out_len: - # Extract encoder embedding at timestep t - # f = x[time_idx, :, :].unsqueeze(0) # [1, 1, D] - f = x.narrow(dim=0, start=time_idx, length=1) - - # Setup exit flags and counter - symbols_added = 0 - - need_loop = True - # While blank is not predicted, or we dont run out of max symbols per timestep - while need_loop and (self.max_symbols is None or symbols_added < self.max_symbols): - # In the first timestep, we initialize the network with RNNT Blank - # In later timesteps, we provide previous predicted label as input. - if hypothesis.last_token is None and hypothesis.dec_state is None: - last_label = self._SOS - else: - last_label = label_collate([[hypothesis.last_token]]) - - # Perform prediction network and joint network steps. - g, hidden_prime = self._pred_step(last_label, hypothesis.dec_state) - # If preserving per-frame confidence, log_normalize must be true - logits = self._joint_step(f, g, log_normalize=False) - logp = logits[0, 0, 0, : -len(self.durations)] - if self.preserve_frame_confidence: - logp = torch.log_softmax(logp, -1) - - duration_logp = torch.log_softmax(logits[0, 0, 0, -len(self.durations) :], dim=-1) - del g - - # torch.max(0) op doesnt exist for FP 16. - if logp.dtype != torch.float32: - logp = logp.float() - - # get index k, of max prob - v, k = logp.max(0) - k = k.item() # K is the label at timestep t_s in inner loop, s >= 0. - - d_v, d_k = duration_logp.max(0) - d_k = d_k.item() - - skip = self.durations[d_k] - - if self.preserve_alignments: - # insert logprobs into last timestep - hypothesis.alignments[-1].append((logp.to('cpu'), torch.tensor(k, dtype=torch.int32))) - - if self.preserve_frame_confidence: - # insert confidence into last timestep - hypothesis.frame_confidence[-1].append( - (self._get_confidence_tensor(logp), self._get_confidence_tensor(duration_logp)) - if self.include_duration_confidence - else self._get_confidence_tensor(logp) - ) - - del logp - - # If blank token is predicted, exit inner loop, move onto next timestep t - if k != self._blank_index: - # Append token to label set, update RNN state. - hypothesis.y_sequence.append(k) - hypothesis.score += float(v) - hypothesis.timestamp.append(time_idx) - hypothesis.dec_state = hidden_prime - hypothesis.last_token = k - if self.include_duration: - hypothesis.token_duration.append(skip) - - # Increment token counter. - symbols_added += 1 - time_idx += skip - need_loop = skip == 0 - - # this rarely happens, but we manually increment the `skip` number - # if blank is emitted and duration=0 is predicted. This prevents possible - # infinite loops. - if skip == 0: - skip = 1 - - if self.preserve_alignments: - # convert Ti-th logits into a torch array - for i in range(skip): - hypothesis.alignments.append([]) # blank buffer until next timestep - - if self.preserve_frame_confidence: - for i in range(skip): - hypothesis.frame_confidence.append([]) # blank buffer for next timestep - - if symbols_added == self.max_symbols: - time_idx += 1 - - # Remove trailing empty list of Alignments - if self.preserve_alignments: - if len(hypothesis.alignments[-1]) == 0: - del hypothesis.alignments[-1] - - # Remove trailing empty list of per-frame confidence - if self.preserve_frame_confidence: - if len(hypothesis.frame_confidence[-1]) == 0: - del hypothesis.frame_confidence[-1] - - # Unpack the hidden states - hypothesis.dec_state = self.decoder.batch_select_state(hypothesis.dec_state, 0) - - return hypothesis - - -class GreedyBatchedTDTInfer(_GreedyRNNTInfer, WithOptionalCudaGraphs): - """A batch level greedy TDT decoder. - - Batch level greedy decoding, performed auto-regressively. - - Args: - decoder_model: rnnt_utils.AbstractRNNTDecoder implementation. - joint_model: rnnt_utils.AbstractRNNTJoint implementation. - blank_index: int index of the blank token. Must be len(vocabulary) for TDT models. - durations: a list containing durations. - max_symbols_per_step: Optional int. The maximum number of symbols that can be added - to a sequence in a single time step; if set to None then there is - no limit. - preserve_alignments: Bool flag which preserves the history of alignments generated during - greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `alignments` in it. Here, `alignments` is a List of List of - Tuple(Tensor (of length V + 1 + num-big-blanks), Tensor(scalar, label after argmax)). - The length of the list corresponds to the Acoustic Length (T). - Each value in the list (Ti) is a torch.Tensor (U), representing 1 or more targets from a vocabulary. - U is the number of target tokens for the current timestep Ti. - preserve_frame_confidence: Bool flag which preserves the history of per-frame confidence scores generated - during greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `frame_confidence` in it. Here, `frame_confidence` is a List of List of floats. - The length of the list corresponds to the Acoustic Length (T). - Each value in the list (Ti) is a torch.Tensor (U), representing 1 or more confidence scores. - U is the number of target tokens for the current timestep Ti. - include_duration: Bool flag, which determines whether predicted durations for each token - need to be included in the Hypothesis object. Defaults to False. - include_duration_confidence: Bool flag indicating that the duration confidence scores are to be calculated and - attached to the regular frame confidence, - making TDT frame confidence element a pair: (`prediction_confidence`, `duration_confidence`). - confidence_method_cfg: A dict-like object which contains the method name and settings to compute per-frame - confidence scores. - - name: The method name (str). - Supported values: - - 'max_prob' for using the maximum token probability as a confidence. - - 'entropy' for using a normalized entropy of a log-likelihood vector. - - entropy_type: Which type of entropy to use (str). Used if confidence_method_cfg.name is set to `entropy`. - Supported values: - - 'gibbs' for the (standard) Gibbs entropy. If the alpha (α) is provided, - the formula is the following: H_α = -sum_i((p^α_i)*log(p^α_i)). - Note that for this entropy, the alpha should comply the following inequality: - (log(V)+2-sqrt(log^2(V)+4))/(2*log(V)) <= α <= (1+log(V-1))/log(V-1) - where V is the model vocabulary size. - - 'tsallis' for the Tsallis entropy with the Boltzmann constant one. - Tsallis entropy formula is the following: H_α = 1/(α-1)*(1-sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/Tsallis_entropy - - 'renyi' for the Rényi entropy. - Rényi entropy formula is the following: H_α = 1/(1-α)*log_2(sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/R%C3%A9nyi_entropy - - alpha: Power scale for logsoftmax (α for entropies). Here we restrict it to be > 0. - When the alpha equals one, scaling is not applied to 'max_prob', - and any entropy type behaves like the Shannon entropy: H = -sum_i(p_i*log(p_i)) - - entropy_norm: A mapping of the entropy value to the interval [0,1]. - Supported values: - - 'lin' for using the linear mapping. - - 'exp' for using exponential mapping with linear shift. - - use_cuda_graph_decoder: if CUDA graphs should be enabled for decoding - (currently recommended only for inference) - fusion_models: list of fusion models (ngram_lm_model and boosting_tree_model) - fusion_models_alpha: list of fusion model weights (ngram_lm_alpha and boosting_tree_alpha) - enable_per_stream_biasing: enable multi-biasing model for per-stream customization - """ - - def __init__( - self, - decoder_model: rnnt_abstract.AbstractRNNTDecoder, - joint_model: rnnt_abstract.AbstractRNNTJoint, - blank_index: int, - durations: List[int], - max_symbols_per_step: Optional[int] = None, - preserve_alignments: bool = False, - preserve_frame_confidence: bool = False, - include_duration: bool = False, - include_duration_confidence: bool = False, - confidence_method_cfg: Optional[DictConfig] = None, - use_cuda_graph_decoder: bool = True, - fusion_models: Optional[List[NGramGPULanguageModel]] = None, - fusion_models_alpha: Optional[List[float]] = None, - enable_per_stream_biasing: bool = False, - ): - super().__init__( - decoder_model=decoder_model, - joint_model=joint_model, - blank_index=blank_index, - max_symbols_per_step=max_symbols_per_step, - preserve_alignments=preserve_alignments, - preserve_frame_confidence=preserve_frame_confidence, - confidence_method_cfg=confidence_method_cfg, - ) - self.durations = durations - self.include_duration = include_duration - self.include_duration_confidence = include_duration_confidence - - # Depending on availability of `blank_as_pad` support - # switch between more efficient batch decoding technique - self.decoding_computer = None - - if self.decoder.blank_as_pad: - # batched "loop frames" is not implemented for TDT - self.decoding_computer = GreedyBatchedTDTLabelLoopingComputer( - decoder=self.decoder, - joint=self.joint, - blank_index=self._blank_index, - durations=self.durations, - max_symbols_per_step=self.max_symbols, - preserve_alignments=preserve_alignments, - preserve_frame_confidence=preserve_frame_confidence, - include_duration=include_duration, - include_duration_confidence=include_duration_confidence, - confidence_method_cfg=confidence_method_cfg, - allow_cuda_graphs=use_cuda_graph_decoder, - fusion_models=fusion_models, - fusion_models_alpha=fusion_models_alpha, - enable_per_stream_biasing=enable_per_stream_biasing, - ) - self._greedy_decode = self._greedy_decode_blank_as_pad_loop_labels - else: - if fusion_models is not None: - raise NotImplementedError("Fusion models are not implemented with `blank_as_pad=False`") - if enable_per_stream_biasing: - raise NotImplementedError("Per-stream biasing is not implemented with `blank_as_pad=False`") - self._greedy_decode = self._greedy_decode_masked - - @typecheck() - def forward( - self, - encoder_output: torch.Tensor, - encoded_lengths: torch.Tensor, - partial_hypotheses: Optional[List[rnnt_utils.Hypothesis]] = None, - ): - """Returns a list of hypotheses given an input batch of the encoder hidden embedding. - Output token is generated auto-regressively. - - Args: - encoder_output: A tensor of size (batch, features, timesteps). - encoded_lengths: list of int representing the length of each sequence - output sequence. - - Returns: - packed list containing batch number of sentences (Hypotheses). - """ - # Preserve decoder and joint training state - decoder_training_state = self.decoder.training - joint_training_state = self.joint.training - - with torch.inference_mode(): - # Apply optional preprocessing - encoder_output = encoder_output.transpose(1, 2) # (B, T, D) - logitlen = encoded_lengths - - self.decoder.eval() - self.joint.eval() - - inseq = encoder_output # [B, T, D] - hypotheses = self._greedy_decode( - inseq, logitlen, device=inseq.device, partial_hypotheses=partial_hypotheses - ) - - # Pack the hypotheses results - packed_result = pack_hypotheses(hypotheses, logitlen) - - self.decoder.train(decoder_training_state) - self.joint.train(joint_training_state) - - return (packed_result,) - - def _greedy_decode_masked( - self, - x: torch.Tensor, - out_len: torch.Tensor, - device: torch.device, - partial_hypotheses: Optional[List[rnnt_utils.Hypothesis]] = None, - ): - raise NotImplementedError("masked greedy-batched decode is not supported for TDT models.") - - @torch.inference_mode() - def _greedy_decode_blank_as_pad_loop_labels( - self, - x: torch.Tensor, - out_len: torch.Tensor, - device: torch.device, - partial_hypotheses: Optional[list[rnnt_utils.Hypothesis | None]] = None, - ) -> list[rnnt_utils.Hypothesis]: - """ - Optimized batched greedy decoding. - The main idea: search for next labels for the whole batch (evaluating Joint) - and thus always evaluate prediction network with maximum possible batch size - """ - # setup batched state - if partial_hypotheses is None or all((hyp is None or hyp.dec_state is None) for hyp in partial_hypotheses): - batched_state = None - else: - batched_state = self.decoding_computer.merge_to_batched_state( - [hyp.dec_state if hyp is not None else None for hyp in partial_hypotheses] - ) - # setup fused biasing ids - if self.decoding_computer.per_stream_biasing_enabled: - batch_size = out_len.shape[0] - multi_biasing_ids = np.full([batch_size], fill_value=-1) - if partial_hypotheses is not None: - for batch_i, hyp in enumerate(partial_hypotheses): - if hyp is None or (not hyp.has_biasing_request()): - continue - # biasing_cfg is not empty - if hyp.biasing_cfg.multi_model_id is None: - logging.warning(f"Boosting tree requested in index {batch_i}, not compiled, skipping") - continue - multi_biasing_ids[batch_i] = hyp.biasing_cfg.multi_model_id - multi_biasing_ids = torch.from_numpy(multi_biasing_ids).to(device=x.device) - else: - multi_biasing_ids = None - batched_hyps, alignments, batched_state = self.decoding_computer( - x=x, - out_len=out_len, - prev_batched_state=batched_state, - multi_biasing_ids=multi_biasing_ids, - ) - hyps = rnnt_utils.batched_hyps_to_hypotheses(batched_hyps, alignments, batch_size=x.shape[0]) - for hyp, state_item in zip(hyps, self.decoding_computer.split_batched_state(batched_state)): - hyp.dec_state = state_item - - if partial_hypotheses: - for i, (hyp, hyp_continuation) in enumerate(zip(partial_hypotheses, hyps)): - if hyp is not None: - hyp.merge_(hyp_continuation) - else: - partial_hypotheses[i] = hyp_continuation - return partial_hypotheses - return hyps - - def disable_cuda_graphs(self) -> bool: - """Disable CUDA graphs (e.g., for decoding in training)""" - if self.decoding_computer is not None: - return self.decoding_computer.disable_cuda_graphs() - return False - - def maybe_enable_cuda_graphs(self) -> bool: - """Enable CUDA graphs (if allowed)""" - if self.decoding_computer is not None: - return self.decoding_computer.maybe_enable_cuda_graphs() - return False diff --git a/nemo/collections/asr/parts/submodules/rnnt_maes_batched_computer.py b/nemo/collections/asr/parts/submodules/rnnt_maes_batched_computer.py deleted file mode 100644 index 1af34f11ac8ec115f168826d9d81b14c95ece44c..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/rnnt_maes_batched_computer.py +++ /dev/null @@ -1,442 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -from pathlib import Path -from typing import Optional - -import torch - -from nemo.collections.asr.parts.utils.asr_confidence_utils import ConfidenceMethodMixin -from nemo.collections.asr.parts.utils.batched_beam_decoding_utils import ( - INACTIVE_SCORE, - NON_EXISTENT_LABEL_VALUE, - BatchedBeamHyps, - BlankLMScoreMode, - PruningMode, -) -from nemo.utils import logging - - -class ModifiedAESBatchedRNNTComputer(ConfidenceMethodMixin): - """ - Batched Adaptive Expansion search implementation. Callable. - Based on https://ieeexplore.ieee.org/document/9250505 with the following modficiations: - - does not support prediction network caching - - supports prefix search with only longest prefix - """ - - def __init__( - self, - decoder, - joint, - blank_index: int, - beam_size: int, - maes_num_steps: int, - maes_expansion_beta: int, - maes_expansion_gamma: int, - preserve_alignments=False, - ngram_lm_model: Optional[str | Path] = None, - ngram_lm_alpha: float = 0.0, - blank_lm_score_mode: Optional[str | BlankLMScoreMode] = BlankLMScoreMode.NO_SCORE, - pruning_mode: Optional[str | PruningMode] = PruningMode.EARLY, - allow_cuda_graphs: Optional[bool] = True, - ): - """ - Init method. - Args: - decoder: Prediction network from RNN-T - joint: Joint module from RNN-T - blank_index: index of blank symbol - maes_num_steps: Number of adaptive steps to take. From the paper, 2 steps is generally sufficient. int > 1. - maes_expansion_beta: Maximum number of prefix expansions allowed, in addition to the beam size. - Effectively, the number of hypothesis = beam_size + maes_expansion_beta. Must be an int >= 0, - and affects the speed of inference since large values will perform large beam search in the next step. - maes_expansion_gamma: Float pruning threshold used in the prune-by-value step when computing the expansions. - The default (2.3) is selected from the paper. It performs a comparison - (max_log_prob - gamma <= log_prob[v]) where v is all vocabulary indices in the Vocab set and max_log_prob - is the "most" likely token to be predicted. Gamma therefore provides a margin of additional tokens which - can be potential candidates for expansion apart from the "most likely" candidate. - Lower values will reduce the number of expansions (by increasing pruning-by-value, thereby improving speed - but hurting accuracy). Higher values will increase the number of expansions (by reducing pruning-by-value, - thereby reducing speed but potentially improving accuracy). This is a hyper parameter to be experimentally - tuned on a validation set. - preserve_alignments: if alignments are needed - ngram_lm_model: path to the NGPU-LM n-gram LM model: .arpa or .nemo formats - ngram_lm_alpha: weight for the n-gram LM scores - blank_lm_score_mode: mode for scoring blank symbol with LM - pruning_mode: mode for pruning hypotheses with LM - allow_cuda_graphs: whether to allow CUDA graphs - """ - - super().__init__() - self.decoder = decoder - self.joint = joint - self._blank_index = blank_index - - self.beam_size = beam_size - self.maes_num_steps = maes_num_steps - self.maes_expansion_beta = maes_expansion_beta - self.maes_expansion_gamma = maes_expansion_gamma - self.preserve_alignments = preserve_alignments - self._SOS = self._blank_index - self.pruning_mode = pruning_mode - self.blank_lm_score_mode = blank_lm_score_mode - - self.maes_num_expansions = self.beam_size + self.maes_expansion_beta - - if self.preserve_alignments: - raise NotImplementedError("Preserve alignments is not supported") - - if allow_cuda_graphs: - logging.info("CUDA Graphs are unsupported for `maes_batch`; preceeding pure pytorch decoding") - - if ngram_lm_model is not None: - expected_blank_index = self.joint.num_classes_with_blank - self.joint.num_extra_outputs - 1 - if self._blank_index != expected_blank_index: - raise ValueError(f"Invalid blank index: expected {expected_blank_index}, got {self._blank_index}") - self.ngram_lm_batch = ngram_lm_model - - self.pruning_mode = PruningMode.EARLY if pruning_mode is None else PruningMode(pruning_mode) - self.blank_lm_score_mode = ( - BlankLMScoreMode.LM_WEIGHTED_FULL - if blank_lm_score_mode is None - else BlankLMScoreMode(blank_lm_score_mode) - ) - else: - self.ngram_lm_batch = None - self.blank_lm_score_mode = None - self.ngram_lm_alpha = ngram_lm_alpha - - def batched_modified_adaptive_expansion_search_torch( - self, - encoder_output: torch.Tensor, - encoder_output_length: torch.Tensor, - ) -> BatchedBeamHyps: - """ - Pure PyTorch implementation - - Args: - encoder_output: output from the encoder - encoder_output_length: lengths of the utterances in `encoder_output` - """ - batch_size, max_time, _unused = encoder_output.shape - device = encoder_output.device - - encoder_output_projected = self.joint.project_encoder(encoder_output) - float_dtype = encoder_output_projected.dtype - - # init empty batched hypotheses - batched_hyps = BatchedBeamHyps( - batch_size=batch_size, - beam_size=self.beam_size, - blank_index=self._blank_index, - init_length=max_time * (self.maes_num_steps + 1) if self.maes_num_steps is not None else max_time, - device=device, - float_dtype=float_dtype, - store_prefix_hashes=True, - ) - - last_labels_wb = torch.full( - [batch_size, self.beam_size], fill_value=self._SOS, device=device, dtype=torch.long - ) - - batch_indices = ( - torch.arange(batch_size, device=device)[:, None].expand(batch_size, self.beam_size).clone() - ) # size: batch_size x beam_size - beam_indices = ( - torch.arange(self.beam_size, device=device)[None, :].expand(batch_size, self.beam_size).clone() - ) # size: batch_size x beam_size - expansion_beam_indices = ( - torch.arange(self.beam_size, device=device)[None, :, None] - .expand(batch_size, self.beam_size, self.maes_num_expansions) - .clone() - ) # size: batch_size x beam_size x beam_size + maes_expansion_beta - - time_indices = torch.zeros_like(batch_indices) - safe_time_indices = torch.zeros_like(time_indices) - last_timesteps = (encoder_output_length - 1)[:, None].expand(batch_size, self.beam_size) - active_mask = time_indices <= last_timesteps - - # setup N-gram LM if available - if self.ngram_lm_batch is not None: - self.ngram_lm_batch.to(device) - batch_lm_states = self.ngram_lm_batch.get_init_states(batch_size=batch_size * self.beam_size, bos=True) - lm_scores, batch_lm_states_candidates = self.ngram_lm_batch.advance( - states=batch_lm_states - ) # vocab_size_no_blank - lm_scores = lm_scores.to(dtype=float_dtype).view(batch_size, self.beam_size, -1) * self.ngram_lm_alpha - - decoder_output, decoder_state, *_ = self.decoder.predict( - last_labels_wb.view(-1, 1), None, add_sos=False, batch_size=batch_size * self.beam_size - ) - # do not recalculate joint projection - decoder_output = self.joint.project_prednet(decoder_output) - - while active_mask.any(): # frames loop - to_update = active_mask.clone() # mask for expansions loop - - # step 1: get joint output - logits = ( - self.joint.joint_after_projection( - encoder_output_projected[batch_indices.flatten(), safe_time_indices.flatten()].unsqueeze(1), - decoder_output, - ) - .squeeze(1) - .squeeze(1) - ) - logps = torch.log_softmax(logits, dim=-1).view(batch_size, self.beam_size, -1) - - # step 2: perform prefix search - updated_logps = self.combine_scores(logps, lm_scores) if self.ngram_lm_batch is not None else logps - batched_hyps.recombine_prefixes(updated_logps, active_mask) - - expansion_steps = 0 - # step 3: performs `maes_num_steps` non-blank expansions - while to_update.any() and expansion_steps < self.maes_num_steps: # expansions loop - # step 3.1: get `maes_num_expansion` best expansions (in total beam x maes_num_expansion expansions) - if self.ngram_lm_batch is None: - # step 3.1.1: choose topk expansions (beam x beam hypotheses for each sample) - label_logps, next_labels = logps.topk(self.maes_num_expansions, dim=-1, largest=True, sorted=True) - next_hyps_probs = batched_hyps.scores.unsqueeze(-1) + label_logps - - # step 3.1.2: prune with threshold parameter gamma - next_hyps_probs[ - next_hyps_probs <= next_hyps_probs.max(dim=-1, keepdim=True).values - self.maes_expansion_gamma - ] = INACTIVE_SCORE - else: - next_labels, next_hyps_probs = self.topk_lm(batched_hyps, lm_scores, logps) - - # step 3.2: get `beam` best expansions - # step 3.2.1: mask inactive hypotheses - next_labels = torch.where(to_update.unsqueeze(-1), next_labels, NON_EXISTENT_LABEL_VALUE) - next_hyps_probs = torch.where(to_update.unsqueeze(-1), next_hyps_probs, INACTIVE_SCORE) - - # step 3.2.2: remove duplicate hypotheses - next_hyps_probs = batched_hyps.remove_duplicates(next_labels, next_hyps_probs) - - # step 3.2.3: add hypotheses from the previous expansion steps of current frame hypotheses to the beam. - # Expansions from step s are compared against the top beam expansions from steps 1 to s-1. - next_hyps_probs[..., -1] = torch.where(to_update, next_hyps_probs[..., -1], batched_hyps.scores) - - # step 3.2.4: get top-k expansions - next_hyps_probs, idx = next_hyps_probs.view(batch_size, -1).topk( - self.beam_size, dim=-1, largest=True, sorted=True - ) - next_labels = next_labels.view(batch_size, -1)[batch_indices, idx] - hyp_indices = expansion_beam_indices.view(batch_size, -1)[batch_indices, idx] - - # step 3.3: update batched beam hypotheses structure - batched_hyps.add_results_(hyp_indices, next_labels, next_hyps_probs) - - # step 3.4: update - last_labels_wb = torch.where(next_labels >= 0, next_labels, self._blank_index) - preserve_state = last_labels_wb == self._blank_index - - # size: decoder_output [(B x Beam), 1, Dim] - # size: state tuple, each is of [Layers, (BxBeam), Dim] - # step 3.5: update decoder + lm state - # step 3.5.1: storing current decoder output and states of extended hypotheses - prev_decoder_output = torch.gather( - decoder_output.view(batch_size, self.beam_size, 1, -1), - dim=1, - index=hyp_indices[:, :, None, None].expand( - batch_size, self.beam_size, 1, decoder_output.shape[-1] - ), - ).view(batch_size * self.beam_size, 1, -1) - prev_decoder_state = self.decoder.batch_aggregate_states_beam( - decoder_state, batch_size, self.beam_size, hyp_indices - ) - - # step 3.5.2: get next decoder output and states for extended hypotheses - decoder_output, decoder_state, *_ = self.decoder.predict( - last_labels_wb.view(-1, 1), - prev_decoder_state, - add_sos=False, - batch_size=batch_size * self.beam_size, - ) - decoder_output = self.joint.project_prednet(decoder_output) # do not recalculate joint projection - - # step 3.5.3: update decoder state and output only for non-blank and active hypotheses - decoder_output = torch.where( - preserve_state.view(-1)[:, None, None], prev_decoder_output, decoder_output - ) - self.decoder.batch_replace_states_mask( - src_states=prev_decoder_state, dst_states=decoder_state, mask=preserve_state.view(-1) - ) - - if self.ngram_lm_batch is not None: - # batch_lm_states: size: [(batch_size x beam_size)] - # batch_lm_states_candidates: [(batch_size x beam_size) x V (without blank)] - batch_lm_states_candidates = torch.gather( - batch_lm_states_candidates.view(batch_size, self.beam_size, -1), - dim=1, - index=hyp_indices[:, :, None].expand( - batch_size, self.beam_size, batch_lm_states_candidates.shape[-1] - ), - ) - batch_lm_states_prev = torch.gather( - batch_lm_states.view(batch_size, self.beam_size), dim=1, index=hyp_indices - ) - last_labels_wb_blank_replaced = torch.where(preserve_state, 0, last_labels_wb) - - batch_lm_states = torch.gather( - batch_lm_states_candidates, dim=-1, index=last_labels_wb_blank_replaced.unsqueeze(-1) - ).squeeze(-1) - batch_lm_states = torch.where(preserve_state, batch_lm_states_prev, batch_lm_states).view(-1) - - lm_scores, batch_lm_states_candidates = self.ngram_lm_batch.advance( - states=batch_lm_states - ) # vocab_size_no_blank - lm_scores = ( - lm_scores.to(dtype=float_dtype).view(batch_size, self.beam_size, -1) * self.ngram_lm_alpha - ) - - # step 3.6: get log-probs for next expansion step - logits = self.joint.joint_after_projection( - encoder_output_projected[batch_indices.flatten(), safe_time_indices.flatten()].unsqueeze(1), - decoder_output, - ) - logps = torch.log_softmax(logits, dim=-1).squeeze(1).squeeze(1).view(batch_size, self.beam_size, -1) - to_update = torch.logical_and(to_update, last_labels_wb != self._blank_index) - - expansion_steps += 1 - if to_update.any(): - # step 4: force blank to active hypotheses - next_hyps_probs = torch.where(to_update, batched_hyps.scores + logps[..., -1], batched_hyps.scores) - next_labels = torch.where(to_update, self._blank_index, -1) - batched_hyps.add_results_(beam_indices, next_labels, next_hyps_probs) - - # step 5: update time indices + active mask - time_indices += 1 - active_mask = time_indices <= last_timesteps - safe_time_indices = torch.where(active_mask, time_indices, last_timesteps) - - return batched_hyps - - def combine_scores(self, log_probs, lm_scores): - """ - Combines acoustic model log probabilities with language model scores based on the specified blank LM score mode. - - Args: - log_probs (torch.Tensor): Log probabilities from the acoustic model. - Shape: (..., vocab_size), where the last dimension corresponds to the vocabulary size. - lm_scores (torch.Tensor): Scores from the language model. - Shape: (..., vocab_size - 1), excluding the blank token. - - Returns: - torch.Tensor: Combined scores with the same shape as `log_probs`. - - Raises: - NotImplementedError: If the `blank_lm_score_mode` is not supported. - """ - res = log_probs.clone() - if self.blank_lm_score_mode is BlankLMScoreMode.NO_SCORE: - # choosing topk from acoustic and Ngram models - res[..., :-1] += lm_scores - else: - blank_logprob = log_probs[..., -1] - non_blank_logprob = torch.log1p(-torch.clamp(torch.exp(blank_logprob), max=1.0 - 1e-6)) - res[..., :-1] += non_blank_logprob.unsqueeze(-1) * self.ngram_lm_alpha + lm_scores - res[..., -1] *= 1 + self.ngram_lm_alpha - - return res - - def topk_lm(self, batched_hyps, lm_scores, log_probs): - """ - Performs top-k selection and pruning for language model (LM) and automatic speech recognition (ASR) outputs - based on the specified pruning and blank scoring modes. - Args: - batched_hyps (object): Hypotheses from the ASR model, containing scores and other relevant information. - lm_scores (Tensor): Precomputed language model scores for the current batch. - log_probs (Tensor): Log probabilities from the ASR model. - Returns: - Tuple[Tensor, Tensor]: - - labels (Tensor): The top-k labels selected after pruning and scoring. - - total_logps (Tensor): The corresponding total log probabilities for the selected labels. - Raises: - NotImplementedError: If the combination of `blank_lm_score_mode` and `pruning_mode` is not implemented. - """ - - match self.pruning_mode, self.blank_lm_score_mode: - case PruningMode.LATE, BlankLMScoreMode.NO_SCORE | BlankLMScoreMode.LM_WEIGHTED_FULL: - # step 1: combining LM and ASR outputs + choosing top `beam` most probable - log_probs = self.combine_scores(log_probs, lm_scores) - label_logps, labels = log_probs.topk( - self.beam_size + self.maes_expansion_beta, dim=-1, largest=True, sorted=True - ) - - # step 2: pruning with threshold gamma - total_logps = batched_hyps.scores.unsqueeze(-1) + label_logps - total_logps[ - total_logps <= total_logps.max(dim=-1, keepdim=True).values - self.maes_expansion_gamma - ] = INACTIVE_SCORE - - case PruningMode.EARLY, BlankLMScoreMode.NO_SCORE: - # step 1: choosing topk from ASR output - label_logps, labels = log_probs.topk( - self.beam_size + self.maes_expansion_beta, dim=-1, largest=True, sorted=True - ) - - # step 2: pruning with threshold gamma - total_logps = batched_hyps.scores.unsqueeze(-1) + label_logps - total_logps[ - total_logps <= total_logps.max(dim=-1, keepdim=True).values - self.maes_expansion_gamma - ] = INACTIVE_SCORE - - # step 3: adding scores from ngram LM - masked_labels = torch.where(labels == self._blank_index, 0, labels) - total_logps = torch.where( - labels == self._blank_index, - total_logps, - total_logps + torch.gather(lm_scores, dim=-1, index=masked_labels), - ) - - case PruningMode.EARLY, BlankLMScoreMode.LM_WEIGHTED_FULL: - # step 1: choosing topk from ASR output - label_logps, labels = log_probs.topk( - self.beam_size + self.maes_expansion_beta, dim=-1, largest=True, sorted=True - ) - - # step 2: pruning with threshold gamma - total_logps = batched_hyps.scores.unsqueeze(-1) + label_logps - label_logps[ - total_logps <= total_logps.max(dim=-1, keepdim=True).values - self.maes_expansion_gamma - ] = INACTIVE_SCORE - - # step 3: adding scores from ngram LM - blank_logprob = log_probs[..., -1] - non_blank_logprob = torch.log1p(-torch.clamp(torch.exp(blank_logprob), max=1.0 - 1e-6)) - - masked_labels = torch.where(labels == self._blank_index, 0, labels) - total_logps = torch.where( - labels == self._blank_index, - total_logps + label_logps * (1 + self.ngram_lm_alpha), - total_logps - + label_logps - + non_blank_logprob.unsqueeze(-1) * self.ngram_lm_alpha - + torch.gather(lm_scores, dim=-1, index=masked_labels), - ) - - case _: - raise NotImplementedError( - f"Unsupported pruning mode {self.pruning_mode} or blank LM score mode {self.blank_lm_score_mode}" - ) - - return labels, total_logps - - def __call__( - self, - x: torch.Tensor, - out_len: torch.Tensor, - ) -> BatchedBeamHyps: - return self.batched_modified_adaptive_expansion_search_torch(encoder_output=x, encoder_output_length=out_len) diff --git a/nemo/collections/asr/parts/submodules/rnnt_malsd_batched_computer.py b/nemo/collections/asr/parts/submodules/rnnt_malsd_batched_computer.py deleted file mode 100644 index f1ef93c64f5d0c9a78edd3ffa81a44d0a9023239..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/rnnt_malsd_batched_computer.py +++ /dev/null @@ -1,1184 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -from dataclasses import dataclass, field -from typing import Any, List, Optional, Union - -import numpy as np -import torch -import torch.nn.functional as F - -from nemo.collections.asr.parts.submodules.ngram_lm import NGramGPULanguageModel -from nemo.collections.asr.parts.utils.asr_confidence_utils import ConfidenceMethodMixin -from nemo.collections.asr.parts.utils.batched_beam_decoding_utils import ( - INACTIVE_SCORE, - NON_EXISTENT_LABEL_VALUE, - BatchedBeamHyps, - BlankLMScoreMode, - PruningMode, -) -from nemo.collections.common.parts.optional_cuda_graphs import WithOptionalCudaGraphs -from nemo.core.utils.cuda_python_utils import ( - NeMoCUDAPythonException, - check_cuda_python_cuda_graphs_conditional_nodes_supported, - cu_call, - run_nvrtc, - with_conditional_node, -) -from nemo.core.utils.optional_libs import CUDA_PYTHON_AVAILABLE, cuda_python_required -from nemo.utils import logging -from nemo.utils.enum import PrettyStrEnum - -if CUDA_PYTHON_AVAILABLE: - from cuda.bindings import runtime as cudart - - -class MALSDState: - """ - State for batched ALSD algorithm for RNN-T models. Used only with CUDA graphs. - In initialization phase it is possible to assign values (tensors) to the state. - For algorithm code the storage should be reused (prefer copy data instead of assigning tensors). - """ - - max_time: int # maximum length of internal storage for time dimension - batch_size: int # (maximum) length of internal storage for batch dimension - device: torch.device # device to store preallocated tensors - beam_size: int # (maximum) length of internal storage for beam dimension - blank_index: int # the index of the blank token - - NON_EXISTENT_LABEL: torch.Tensor # tensor for non existent label constant - BLANK_TENSOR: torch.Tensor # tensor for non blank constant - INACTIVE_SCORE: torch.Tensor # tensor for inactive score constant - - encoder_output_projected: torch.Tensor # projected output from the encoder for decoding algorithm - encoder_output_length: torch.Tensor # length of the (projected) output from the encoder - - next_labels: torch.Tensor # storage for next labels - next_scores: torch.Tensor # storage for next scores - next_idx: torch.Tensor # storage for next scores - - batch_indices: torch.Tensor # indices of elements in batch (constant, range [0, batch_size-1]) - beam_indices: torch.Tensor # indices of elements in batch (constant, range [0, beam_size-1]) - - time_indices: torch.Tensor # current time indices for each element in batch - safe_time_indices: torch.Tensor # current time indices, but guaranteed to be < encoder_output_length - last_timesteps: torch.Tensor # indices of the last timesteps for each element (encoder_output_length - 1) - last_labels_wb: torch.Tensor # last labels with blank - hyp_scores: torch.Tensor # scores for hypotheses - - active_mask: torch.Tensor # mask for active hypotheses (the decoding is finished for the utterance if it is False) - blank_mask: torch.Tensor # if the element is blank - active_mask_any: torch.Tensor # 0-dim bool tensor, condition for outer loop ('any element is still active') - - last_decoder_state: Any # last state from the decoder, needed for the output - decoder_state: Any # current decoder state - decoder_output: torch.Tensor # output from the decoder (projected) - prev_decoder_state: Any # current decoder state - prev_decoder_output: torch.Tensor # output from the decoder (projected) - init_decoder_state: Any # current decoder state - init_decoder_output: torch.Tensor # output from the decoder (projected) - - batched_hyps: BatchedBeamHyps # batched hypotheses - decoding result - - # fusion models related fields - fusion_models: Optional[List[NGramGPULanguageModel]] = None # list of fusion models - fusion_models_alpha: Optional[List[float]] = None # list of weights for the fusion models scores - fusion_states_list: Optional[List[torch.Tensor]] = None # list of fusion states - fusion_states_candidates_list: Optional[List[torch.Tensor]] = None # list of fusion states candidates - fusion_scores_list: Optional[List[torch.Tensor]] = None # list of fusion scores - fusion_states_prev_list: Optional[List[torch.Tensor]] = None # list of previous fusion states - init_fusion_states_list: Optional[List[torch.Tensor]] = None # list of initial fusion states - init_fusion_states_candidates_list: Optional[List[torch.Tensor]] = None # list of initial fusion states candidates - init_fusion_scores_list: Optional[List[torch.Tensor]] = None # list of initial fusion scores - - def __init__( - self, - batch_size: int, - beam_size: int, - max_time: int, - encoder_dim: int, - max_symbols: int, - device: torch.device, - float_dtype: torch.dtype, - blank_index: int, - ): - """ - Args: - batch_size: batch size for encoder output storage - beam_size: beam size for decoder output storage - max_time: maximum time for encoder output storage - encoder_dim: last dimension for encoder output storage (projected encoder output) - max_symbols: max symbols per step (to avoid infinite looping and pre-allocate storage) - device: device to store tensors - float_dtype: default float dtype for tensors (should match projected encoder output) - blank_index: index of the blank symbol - """ - - self.device = device - self.float_dtype = float_dtype - self.batch_size = batch_size - self.beam_size = beam_size - self.max_time = max_time - self.blank_index = blank_index - - self.NON_EXISTENT_LABEL = torch.tensor(NON_EXISTENT_LABEL_VALUE, device=self.device, dtype=torch.long) - self.BLANK_TENSOR = torch.tensor(self.blank_index, device=self.device, dtype=torch.long) - self.INACTIVE_SCORE = torch.tensor(INACTIVE_SCORE, device=self.device, dtype=float_dtype) - - self.encoder_output_projected = torch.zeros( - (self.batch_size, self.max_time, encoder_dim), - dtype=float_dtype, - device=self.device, - ) - self.encoder_output_length = torch.zeros( - [self.batch_size, self.beam_size], dtype=torch.long, device=self.device - ) - - self.next_idx = torch.zeros([self.batch_size, self.beam_size], dtype=torch.long, device=self.device) - self.next_labels = torch.zeros([self.batch_size, self.beam_size], dtype=torch.long, device=self.device) - self.next_scores = torch.zeros([self.batch_size, self.beam_size], dtype=float_dtype, device=self.device) - - self.last_labels_wb = torch.full( - [self.batch_size, self.beam_size], device=self.device, dtype=torch.long, fill_value=self.blank_index - ) - self.hyp_scores = torch.full( - [self.batch_size, self.beam_size], fill_value=self.INACTIVE_SCORE, device=self.device, dtype=float_dtype - ) - - # indices of elements in batch and beam (constant) - self.batch_indices = ( - torch.arange(batch_size, dtype=torch.long, device=device)[:, None] - .expand(batch_size, self.beam_size) - .clone() - ) # size: batch_size x beam_size - self.beam_indices = ( - torch.arange(self.beam_size, dtype=torch.long, device=self.device)[None, :, None] - .expand(self.batch_size, -1, self.beam_size) - .clone() - ) # size: batch_size x beam_size x beam_size - - self.time_indices = torch.zeros_like(self.batch_indices) - self.safe_time_indices = torch.zeros_like(self.batch_indices) - self.last_timesteps = torch.zeros_like(self.batch_indices) - - self.active_mask = torch.zeros_like(self.batch_indices, dtype=torch.bool) - self.blank_mask = torch.zeros_like(self.active_mask, dtype=torch.bool) - self.active_mask_any = torch.tensor(True, device=self.device, dtype=torch.bool) - - self.batched_hyps = BatchedBeamHyps( - batch_size=batch_size, - beam_size=self.beam_size, - blank_index=self.blank_index, - init_length=max_time * (max_symbols + 1) if max_symbols is not None else max_time, - device=device, - float_dtype=float_dtype, - ) - - def need_reinit(self, encoder_output_projected: torch.Tensor) -> bool: - """Check if need to reinit state: larger batch_size/max_time, or new device""" - return ( - self.batch_size < encoder_output_projected.shape[0] - or self.max_time < encoder_output_projected.shape[1] - or self.device.index != encoder_output_projected.device.index - ) - - -@dataclass -class SeparateGraphsMALSD: - """Class to store Cuda graphs for decoding when separate graphs are used""" - - before_loop: torch.cuda.CUDAGraph = field(default_factory=torch.cuda.CUDAGraph) - loop_body: torch.cuda.CUDAGraph = field(default_factory=torch.cuda.CUDAGraph) - loop_update_decoder: torch.cuda.CUDAGraph = field(default_factory=torch.cuda.CUDAGraph) - - -class ModifiedALSDBatchedRNNTComputer(WithOptionalCudaGraphs, ConfidenceMethodMixin): - """ - Batched Alignment-Length Synchronous Decoding implementation. Callable. - Based on https://ieeexplore.ieee.org/document/9053040 with the following modficiations: - - does not support prediction network caching - - does not employ transcript length estimation, instead, limits the number of expansions for every frame. - """ - - INITIAL_MAX_TIME = 375 # initial max time, used to init state for Cuda graphs - CUDA_PROGRAM_NAME = b"while_malsd_batch_conditional_rnnt.cu" - - class CudaGraphsMode(PrettyStrEnum): - FULL_GRAPH = "full_graph" # Cuda graphs with conditional nodes, fastest implementation - NO_WHILE_LOOPS = "no_while_loops" # Decoding with PyTorch while loops + partial Cuda graphs - NO_GRAPHS = "no_graphs" # decoding without graphs, stateful implementation, only for testing purposes - - separate_graphs: Optional[SeparateGraphsMALSD] - full_graph: Optional[torch.cuda.CUDAGraph] - cuda_graphs_mode: Optional[CudaGraphsMode] - state: Optional[MALSDState] - fusion_models: Optional[List[NGramGPULanguageModel]] - - def __init__( - self, - decoder, - joint, - blank_index: int, - beam_size: int, - max_symbols_per_step: Optional[int] = 10, - preserve_alignments=False, - fusion_models: Optional[List[NGramGPULanguageModel]] = None, - fusion_models_alpha: Optional[List[float]] = None, - blank_lm_score_mode: Optional[str | BlankLMScoreMode] = None, - pruning_mode: Optional[str | PruningMode] = None, - allow_cuda_graphs: bool = True, - ): - """ - Init method. - Args: - decoder: Prediction network from RNN-T - joint: Joint module from RNN-T - blank_index: index of blank symbol - beam_size: beam size - max_symbols_per_step: max symbols to emit on each step (to avoid infinite looping) - preserve_alignments: if alignments are needed - fusion_models: list of fusion models (ngram_lm_model and boosting_tree_model) - fusion_models_alpha: list of weights for the fusion models scores - blank_lm_score_mode: mode for scoring blank symbol with fusion models - pruning_mode: mode for pruning hypotheses with fusion models - allow_cuda_graphs: whether to allow CUDA graphs - """ - - super().__init__() - self.decoder = decoder - self.joint = joint - self._blank_index = blank_index - - self.beam_size = beam_size - self.max_symbols = max_symbols_per_step - self.preserve_alignments = preserve_alignments - self._SOS = self._blank_index - self.allow_cuda_graphs = allow_cuda_graphs - - if self.preserve_alignments: - raise NotImplementedError("Preserve alignments is not supported") - - self.state = None - self.full_graph = None - self.separate_graphs = None - - self.cuda_graphs_mode = None - self.cuda_graphs_allow_fallback = True - self.maybe_enable_cuda_graphs() - - if fusion_models is not None: - expected_blank_index = self.joint.num_classes_with_blank - self.joint.num_extra_outputs - 1 - if self._blank_index != expected_blank_index: - raise ValueError(f"Invalid blank index: expected {expected_blank_index}, got {self._blank_index}") - - self.fusion_models = fusion_models - self.fusion_models_alpha = fusion_models_alpha - - self.pruning_mode = PruningMode.EARLY if pruning_mode is None else PruningMode(pruning_mode) - self.blank_lm_score_mode = ( - BlankLMScoreMode.LM_WEIGHTED_FULL - if blank_lm_score_mode is None - else BlankLMScoreMode(blank_lm_score_mode) - ) - else: - self.fusion_models = None - self.blank_lm_score_mode = None - - def force_cuda_graphs_mode(self, mode: Optional[Union[str, CudaGraphsMode]]): - """ - Method to set graphs mode. Use only for testing purposes. - For debugging the algorithm use "no_graphs" mode, since it is impossible to debug CUDA graphs directly. - """ - self.cuda_graphs_mode = self.CudaGraphsMode(mode) if mode is not None else None - self.cuda_graphs_allow_fallback = False - self.state = None - - def maybe_enable_cuda_graphs(self) -> bool: - """Enable CUDA graphs if conditions met""" - if self.cuda_graphs_mode is not None: - # CUDA graphs are already enabled - return False - - if not self.allow_cuda_graphs: - self.cuda_graphs_mode = None - else: - # cuda graphs are allowed - # check basic requirements for cuda graphs - if self.max_symbols is None: - logging.warning("Max symbols per step is None, which is not allowed with Cuda graphs. Setting to `10`") - self.max_symbols = 10 - # basic requirements met, need to check while loops - try: - check_cuda_python_cuda_graphs_conditional_nodes_supported() - self.cuda_graphs_mode = self.CudaGraphsMode.FULL_GRAPH - except (ImportError, ModuleNotFoundError, EnvironmentError) as e: - logging.warning( - "No conditional node support for Cuda.\n" - "Cuda graphs with while loops are disabled, decoding speed will be slower\n" - f"Reason: {e}" - ) - self.cuda_graphs_mode = self.CudaGraphsMode.NO_WHILE_LOOPS - self.reset_cuda_graphs_state() - return self.cuda_graphs_mode is not None - - def disable_cuda_graphs(self) -> bool: - """Disable CUDA graphs, can be used to disable graphs temporary, e.g., in training process""" - if self.cuda_graphs_mode is None: - # nothing to disable - return False - self.cuda_graphs_mode = None - self.reset_cuda_graphs_state() - return True - - def reset_cuda_graphs_state(self): - """Reset state to release memory (for CUDA graphs implementations)""" - self.state = None - self.full_graph = None - self.separate_graphs = None - - def modified_alsd_torch( - self, - encoder_output: torch.Tensor, - encoder_output_length: torch.Tensor, - ) -> BatchedBeamHyps: - """ - Pytorch implementation of the batched ALSD algorithm for RNN-T. - Args: - encoder_output (torch.Tensor): The output from the encoder network with shape - [batch_size, max_time, encoder_dim]. - encoder_output_length (torch.Tensor): The lengths of the encoder outputs for each batch - with shape [batch_size]. - Returns: - BatchedBeamHyps: Batched beam hypotheses. - """ - batch_size, max_time, _ = encoder_output.shape - device = encoder_output.device - - if torch.is_autocast_enabled(): - encoder_output = encoder_output.to(torch.get_autocast_gpu_dtype()) - - # do not recalculate joint projection, project only once - encoder_output_projected = self.joint.project_encoder(encoder_output) - float_dtype = encoder_output_projected.dtype - - # init empty batched beam hypotheses - batched_hyps = BatchedBeamHyps( - batch_size=batch_size, - beam_size=self.beam_size, - blank_index=self._blank_index, - init_length=max_time * (self.max_symbols + 1) if self.max_symbols is not None else max_time, - device=device, - float_dtype=float_dtype, - ) - - last_labels_wb = torch.full( - [batch_size, self.beam_size], fill_value=self._SOS, device=device, dtype=torch.long - ) - - batch_beam_indices = ( - torch.arange(batch_size, dtype=torch.long, device=device)[:, None] - .expand(batch_size, self.beam_size) - .clone() - ) # size: batch_size x beam_size - batch_beam_beam_indices = ( - torch.arange(self.beam_size, dtype=torch.long, device=device)[None, :, None] - .expand(batch_size, -1, self.beam_size) - .clone() - ) # size: batch_size x beam_size x beam_size - - time_indices = torch.zeros_like(batch_beam_indices) - safe_time_indices = torch.zeros_like(time_indices) # time indices, guaranteed to be < out_len - last_timesteps = (encoder_output_length - 1)[:, None].expand_as(batch_beam_indices) - active_mask = time_indices <= last_timesteps - - # setup fusion models if available - if self.fusion_models is not None: - fusion_states_list = [] - fusion_states_candidates_list = [] - fusion_scores_list = [] - for fusion_model_idx, fusion_model in enumerate(self.fusion_models): - fusion_model.to(device) - fusion_states = fusion_model.get_init_states(batch_size=batch_size * self.beam_size, bos=True) - fusion_scores, fusion_states_candidates = fusion_model.advance( - states=fusion_states - ) # vocab_size_no_blank - - fusion_scores = ( - fusion_scores.to(dtype=float_dtype).view(batch_size, self.beam_size, -1) - * self.fusion_models_alpha[fusion_model_idx] - ) - fusion_states_list.append(fusion_states) - fusion_states_candidates_list.append(fusion_states_candidates) - fusion_scores_list.append(fusion_scores) - - decoder_state = self.decoder.initialize_state( - torch.empty( - [ - batch_size * self.beam_size, - ], - dtype=float_dtype, - device=device, - ) - ) - - decoder_output, state, *_ = self.decoder.predict( - last_labels_wb.view(-1, 1), None, add_sos=False, batch_size=batch_size * self.beam_size - ) - # do not recalculate joint projection - decoder_output = self.joint.project_prednet(decoder_output) # size: [(batch_size x beam_size), 1, Dim] - self.decoder.batch_replace_states_all(state, dst_states=decoder_state) - - while active_mask.any(): - # step 1: get joint output + fuse with fusion models (if present) - logits = ( - self.joint.joint_after_projection( - encoder_output_projected[batch_beam_indices.view(-1), safe_time_indices.view(-1)].unsqueeze(1), - decoder_output, - ) - .squeeze(1) - .squeeze(1) - ) - log_probs = F.log_softmax(logits, dim=-1, dtype=float_dtype).view( - batch_size, self.beam_size, -1 - ) # [(B x Beam), V] - - if self.fusion_models is not None: - log_probs_top_k, labels_top_k = self.topk_fusion_model(fusion_scores_list, log_probs) - else: - log_probs_top_k, labels_top_k = torch.topk( - log_probs, self.beam_size, dim=-1, largest=True, sorted=True - ) - - # step 2: Make hyps candidates. Add new scores to hyps, force blank if necessary, recombine hyps, prune - # step 2.1: hyps candidates - log_probs_blank = log_probs[ - ..., self._blank_index - ] # blank scores size: batch_size x beam_size - hyps_scores = batched_hyps.scores # previous hyp scores size: batch_size x beam_size - hyps_candidates_prob = ( - hyps_scores.unsqueeze(-1) + log_probs_top_k - ) # hyps with top-k labels size: batch_size x beam_size x beam_size - hyps_candidates_prob_forced_blank = ( - hyps_scores + log_probs_blank - ) # hyps with forced blank size: batch_size x beam_size - - # step 2.2 force add final (fully decoded) hyps with to the beam (without updating the score) - # mask inactive (final) hyps with -inf - hyps_candidates_prob = torch.where( - active_mask.unsqueeze(-1), - hyps_candidates_prob, - INACTIVE_SCORE, - ) - # keep inactive (final hypotheses) at the first position in beam - hyps_candidates_prob[..., 0] = torch.where( - active_mask, - hyps_candidates_prob[..., 0], - hyps_scores, - ) - # mark the labels corresponding to final hypotheses with negative label (e.g., -1) - labels_top_k = torch.where(active_mask.unsqueeze(-1), labels_top_k, NON_EXISTENT_LABEL_VALUE) - - # step 2.3: force blank extension with respect to self.max_symbols - if self.max_symbols is not None: - force_blank = (batched_hyps.last_timestamp_lasts >= self.max_symbols) & active_mask - else: - force_blank = torch.full_like(active_mask, fill_value=False) - # mask beams if forced blank - hyps_candidates_prob = torch.where(force_blank.unsqueeze(-1), INACTIVE_SCORE, hyps_candidates_prob) - # keep hypotheses with forced blank at the first position in beam - hyps_candidates_prob[..., 0] = torch.where( - force_blank, hyps_candidates_prob_forced_blank, hyps_candidates_prob[..., 0] - ) - # change labels to blank if forced blank - labels_top_k = torch.where(force_blank.unsqueeze(-1), self._blank_index, labels_top_k) - - # step 2.4: final pruning - get top-beam from (beam_size x beam_size) hyps - next_hyps_prob, hyps_candidates_indices = torch.topk( - hyps_candidates_prob.view(batch_size, -1), k=self.beam_size, largest=True, sorted=True - ) - hyps_indices = torch.gather( - batch_beam_beam_indices.reshape(batch_size, -1), dim=-1, index=hyps_candidates_indices - ) # indices in beam extended with new label - next_labels = torch.gather( - labels_top_k.reshape(batch_size, -1), dim=-1, index=hyps_candidates_indices - ) # labels for extended hypotheses - - # step 3: store results - if self.max_symbols is None: - batched_hyps.add_results_(hyps_indices, next_labels, next_hyps_prob) - else: - batched_hyps.add_results_no_checks_(hyps_indices, next_labels, next_hyps_prob) - - # step 4: recombine hypotheses: sum probabilities of identical hypotheses. - batched_hyps.recombine_hyps_() - - # step 5: update decoder state + decoder output (+ fusion models state/scores) - # step 5.1: mask invalid value labels with blank to avoid errors (refer to step 2.2) - last_labels_wb = torch.where(next_labels >= 0, next_labels, self._blank_index) - preserve_state = last_labels_wb == self._blank_index - - # size: decoder_output [(B x Beam), 1, Dim] - # size: state tuple, each is of [Layers, (BxBeam), Dim] - # step 5.2: update decoder + fusion models state - # step 5.2.1: storing current decoder output and states of extended hypotheses - prev_decoder_output = torch.gather( - decoder_output.view(batch_size, self.beam_size, 1, -1), - dim=1, - index=hyps_indices[:, :, None, None].expand(batch_size, self.beam_size, 1, decoder_output.shape[-1]), - ).view(batch_size * self.beam_size, 1, -1) - prev_decoder_state = self.decoder.batch_aggregate_states_beam( - decoder_state, batch_size, self.beam_size, hyps_indices - ) - - # step 5.2.2: get next decoder output and states for extended hypotheses - decoder_output, decoder_state, *_ = self.decoder.predict( - last_labels_wb.view(-1).unsqueeze(1), - prev_decoder_state, - add_sos=False, - batch_size=batch_size * self.beam_size, - ) - decoder_output = self.joint.project_prednet(decoder_output) # do not recalculate joint projection - - # step 5.2.3: update decoder state and output only for non-blank and active hypotheses - decoder_output = torch.where(preserve_state.view(-1)[:, None, None], prev_decoder_output, decoder_output) - self.decoder.batch_replace_states_mask( - src_states=prev_decoder_state, dst_states=decoder_state, mask=preserve_state.view(-1) - ) - - if self.fusion_models is not None: - # fusion_states: size: [(batch_size x beam_size)] - # fusion_states_candidates: [(batch_size x beam_size) x V (without blank)] - for fusion_model_idx, fusion_model in enumerate(self.fusion_models): - fusion_states_candidates = torch.gather( - fusion_states_candidates_list[fusion_model_idx].view(batch_size, self.beam_size, -1), - dim=1, - index=hyps_indices[:, :, None].expand( - batch_size, self.beam_size, fusion_states_candidates_list[fusion_model_idx].shape[-1] - ), - ) - fusion_states_prev = torch.gather( - fusion_states_list[fusion_model_idx].view(batch_size, self.beam_size), - dim=1, - index=hyps_indices, - ) - last_labels_wb_blank_replaced = torch.where(preserve_state, 0, last_labels_wb) - - fusion_states = torch.gather( - fusion_states_candidates, dim=-1, index=last_labels_wb_blank_replaced.unsqueeze(-1) - ).squeeze(-1) - fusion_states = torch.where(preserve_state, fusion_states_prev, fusion_states).view(-1) - - fusion_scores, fusion_states_candidates = fusion_model.advance(states=fusion_states) - fusion_scores = ( - fusion_scores.to(dtype=float_dtype).view(batch_size, self.beam_size, -1) - * self.fusion_models_alpha[fusion_model_idx] - ) - fusion_states_list[fusion_model_idx] = fusion_states - fusion_states_candidates_list[fusion_model_idx] = fusion_states_candidates - fusion_scores_list[fusion_model_idx] = fusion_scores - - # step 6: update time indices + active mask - time_indices = batched_hyps.next_timestamp - torch.minimum(time_indices, last_timesteps, out=safe_time_indices) - active_mask = time_indices <= last_timesteps - - return batched_hyps - - def topk_fusion_model(self, fusion_scores_list, log_probs, eps=1e-2): - """ - Computes the top-k log probabilities and corresponding labels for hypotheses, - incorporating fusion models scores based on the pruning and blank scoring modes. - - Args: - fusion_scores_list (List[torch.Tensor]): List of fusion model scores for hypotheses, shape [batch_size, beam_size, vocab_size]. - log_probs (torch.Tensor): Log probabilities from the joint network, shape [batch_size, beam_size, vocab_size]. - eps (float): Epsilon value for numerical stability. Default is 1e-2 for bf16 precision. - - Returns: - Tuple[torch.Tensor, torch.Tensor]: - - log_probs_top_k: Top-k log probabilities, shape [batch_size, beam_size, beam_size]. - - labels_top_k: Corresponding top-k labels, shape [batch_size, beam_size, beam_size]. - """ - - fusion_scores_sum = sum(fusion_scores_list) - fusion_scores_alpha_sum = sum(self.fusion_models_alpha) - - match self.pruning_mode, self.blank_lm_score_mode: - case PruningMode.LATE, BlankLMScoreMode.NO_SCORE: - log_probs[..., :-1] += fusion_scores_sum - log_probs_top_k, labels_top_k = torch.topk( - log_probs, self.beam_size, dim=-1, largest=True, sorted=True - ) - - case PruningMode.LATE, BlankLMScoreMode.LM_WEIGHTED_FULL: - blank_logprob = log_probs[..., -1] - non_blank_logprob = torch.log1p( - -torch.clamp(torch.exp(blank_logprob), max=1.0 - eps) - ) # 1e-2 is used here instead of 1e-6 to address numerical instability with bf16 precision. - log_probs[..., :-1] += non_blank_logprob.unsqueeze(-1) * fusion_scores_alpha_sum + fusion_scores_sum - log_probs[..., -1] *= 1 + fusion_scores_alpha_sum - log_probs_top_k, labels_top_k = torch.topk( - log_probs, self.beam_size, dim=-1, largest=True, sorted=True - ) - - case PruningMode.EARLY, BlankLMScoreMode.NO_SCORE: - log_probs_top_k, labels_top_k = torch.topk( - log_probs, self.beam_size, dim=-1, largest=True, sorted=True - ) - masked_labels = torch.where(labels_top_k == self._blank_index, 0, labels_top_k) - log_probs_top_k = torch.where( - labels_top_k == self._blank_index, - log_probs_top_k, - log_probs_top_k + torch.gather(fusion_scores_sum, dim=-1, index=masked_labels), - ) - - case PruningMode.EARLY, BlankLMScoreMode.LM_WEIGHTED_FULL: - log_probs_top_k, labels_top_k = log_probs.topk(self.beam_size, dim=-1, largest=True, sorted=True) - - blank_logprob = log_probs[..., -1] - non_blank_logprob = torch.log1p(-torch.clamp(torch.exp(blank_logprob), max=1.0 - eps)) - - masked_labels = torch.where(labels_top_k == self._blank_index, 0, labels_top_k) - log_probs_top_k = torch.where( - labels_top_k == self._blank_index, - log_probs_top_k * (1 + fusion_scores_alpha_sum), - log_probs_top_k - + non_blank_logprob.unsqueeze(-1) * fusion_scores_alpha_sum - + torch.gather(fusion_scores_sum, dim=-1, index=masked_labels), - ) - - case _: - raise NotImplementedError( - f"Unsupported pruning mode {self.pruning_mode} or blank LM score mode {self.blank_lm_score_mode}" - ) - - return log_probs_top_k, labels_top_k - - def modified_alsd_cuda_graphs( - self, - encoder_output: torch.Tensor, - encoder_output_length: torch.Tensor, - ) -> BatchedBeamHyps: - """ - Cuda-Graphs implementation of the batched ALSD algorithm. - Args: - encoder_output (torch.Tensor): The output from the encoder network with shape - [batch_size, max_time, encoder_dim]. - encoder_output_length (torch.Tensor): The lengths of the encoder outputs for each batch - with shape [batch_size]. - Returns: - BathcedBeamHyps: Batched beam hypotheses. - """ - - assert self.cuda_graphs_mode is not None - - # do not recalculate joint projection, project only once - encoder_output = self.joint.project_encoder(encoder_output) - current_batch_size = encoder_output.shape[0] - current_max_time = encoder_output.shape[1] - - if torch.is_autocast_enabled(): - encoder_output = encoder_output.to(torch.get_autocast_gpu_dtype()) - - # init or reinit graph - if self.state is None or self.state.need_reinit(encoder_output): - self._graph_reinitialize(encoder_output, encoder_output_length) - - # set length to zero for elements outside the current batch - self.state.encoder_output_length.fill_(0) - # copy (projected) encoder output and lenghts - self.state.encoder_output_projected[:current_batch_size, :current_max_time, ...].copy_(encoder_output) - self.state.encoder_output_length[:current_batch_size].copy_(encoder_output_length.unsqueeze(-1)) - if self.cuda_graphs_mode is self.CudaGraphsMode.FULL_GRAPH: - self.full_graph.replay() - elif self.cuda_graphs_mode is self.CudaGraphsMode.NO_WHILE_LOOPS: - self.separate_graphs.before_loop.replay() - while self.state.active_mask_any.item(): - self.separate_graphs.loop_body.replay() - self.separate_graphs.loop_update_decoder.replay() - elif self.cuda_graphs_mode is self.CudaGraphsMode.NO_GRAPHS: - # this mode is only for testing purposes - # manual loop instead of using graphs - self._before_loop() - while self.state.active_mask_any.item(): - self._loop_body() - self._loop_update_decoder() - else: - raise NotImplementedError(f"Unknown graph mode: {self.cuda_graphs_mode}") - - return self.state.batched_hyps - - @classmethod - def _create_loop_body_kernel(cls): - """ - Creates a kernel that evaluates whether to enter the outer loop body (not all hypotheses are decoded). - Condition: while(active_mask_any). - """ - kernel_string = r"""\ - typedef __device_builtin__ unsigned long long cudaGraphConditionalHandle; - - extern "C" __device__ __cudart_builtin__ void cudaGraphSetConditional(cudaGraphConditionalHandle handle, unsigned int value); - - extern "C" __global__ - void loop_conditional(cudaGraphConditionalHandle handle, const bool *active_mask_any) - { - cudaGraphSetConditional(handle, *active_mask_any); - } - """ - return run_nvrtc(kernel_string, b"loop_conditional", cls.CUDA_PROGRAM_NAME) - - def _graph_reinitialize( - self, - encoder_output_projected: torch.Tensor, - encoder_output_length: torch.Tensor, - ): - """ - Reinitializes the graph state for the MALSD computation. - This method sets up the internal state required for the decoding process, including initializing - decoder outputs, decoder states, and optional n-gram language model states. It also handles CUDA - graph compilation based on the specified mode. - Args: - encoder_output_projected (torch.Tensor): The projected encoder output tensor of shape - (batch_size, max_time, encoder_dim). - encoder_output_length (torch.Tensor): The lengths of the encoder outputs for each batch. - Raises: - NotImplementedError: If an unsupported CUDA graph mode is specified. - """ - - batch_size, max_time, encoder_dim = encoder_output_projected.shape - - self.state = MALSDState( - batch_size=batch_size, - beam_size=self.beam_size, - max_time=max(max_time, self.INITIAL_MAX_TIME), - encoder_dim=encoder_dim, - max_symbols=self.max_symbols, - device=encoder_output_projected.device, - float_dtype=encoder_output_projected.dtype, - blank_index=self._blank_index, - ) - - self.state.decoder_state = self.decoder.initialize_state( - torch.empty( - [ - batch_size * self.beam_size, - ], - dtype=encoder_output_projected.dtype, - device=encoder_output_projected.device, - ) - ) - self.state.prev_decoder_state = self.decoder.initialize_state( - torch.empty( - [ - batch_size * self.beam_size, - ], - dtype=encoder_output_projected.dtype, - device=encoder_output_projected.device, - ) - ) - - init_decoder_output, self.state.init_decoder_state, *_ = self.decoder.predict( - self.state.last_labels_wb.view(-1, 1), None, add_sos=False, batch_size=batch_size * self.beam_size - ) - self.state.init_decoder_output = self.joint.project_prednet(init_decoder_output).to( - dtype=self.state.float_dtype - ) # do not recalculate joint projection - - self.decoder.batch_replace_states_all(self.state.init_decoder_state, dst_states=self.state.decoder_state) - self.state.decoder_output = self.state.init_decoder_output.clone() - - self.decoder.batch_replace_states_all(self.state.init_decoder_state, dst_states=self.state.prev_decoder_state) - self.state.prev_decoder_output = self.state.init_decoder_output.clone() - - if self.fusion_models is not None: - - device = encoder_output_projected.device - - self.state.init_fusion_states_list = [] - self.state.init_fusion_states_candidates_list = [] - self.state.init_fusion_scores_list = [] - - self.state.fusion_states_list = [] - self.state.fusion_states_candidates_list = [] - self.state.fusion_scores_list = [] - self.state.fusion_states_prev_list = [] - - for fusion_model_idx, fusion_model in enumerate(self.fusion_models): - fusion_model.to(device) - - init_fusion_states = fusion_model.get_init_states( - batch_size=self.state.batch_size * self.beam_size, bos=True - ).view(self.state.batch_size, self.beam_size) - init_fusion_scores, init_fusion_states_candidates = fusion_model.advance( - states=init_fusion_states.view(-1) - ) - self.state.init_fusion_scores_list.append( - init_fusion_scores.to(dtype=self.state.float_dtype).view(self.state.batch_size, self.beam_size, -1) - * self.fusion_models_alpha[fusion_model_idx] - ) - self.state.init_fusion_states_candidates_list.append( - init_fusion_states_candidates.view(self.state.batch_size, self.beam_size, -1) - ) - self.state.init_fusion_states_list.append(init_fusion_states) - - self.state.fusion_states_list.append(init_fusion_states.clone()) - self.state.fusion_states_candidates_list.append( - self.state.init_fusion_states_candidates_list[fusion_model_idx].clone() - ) - self.state.fusion_scores_list.append(self.state.init_fusion_scores_list[fusion_model_idx].clone()) - self.state.fusion_states_prev_list.append(init_fusion_states.clone()) - - if self.cuda_graphs_mode is self.CudaGraphsMode.FULL_GRAPH: - try: - self._full_graph_compile() - except NeMoCUDAPythonException as e: - if not self.cuda_graphs_allow_fallback: - raise RuntimeError("Full CUDA graph decoding failed. Mode is forced, raising exception") from e - logging.warning( - f"Full CUDA graph compilation failed: {e}. " - "Falling back to native PyTorch CUDA graphs. Decoding will be slower." - ) - self.cuda_graphs_mode = self.CudaGraphsMode.NO_WHILE_LOOPS - self._partial_graphs_compile() - elif self.cuda_graphs_mode is self.CudaGraphsMode.NO_WHILE_LOOPS: - self._partial_graphs_compile() - elif self.cuda_graphs_mode is self.CudaGraphsMode.NO_GRAPHS: - # no graphs needed - pass - else: - raise NotImplementedError - - def _partial_graphs_compile(self): - """Compile decoding by parts""" - # Always create a new stream, because the per-thread default stream disallows stream capture to a graph. - stream_for_graph = torch.cuda.Stream(self.state.device) - stream_for_graph.wait_stream(torch.cuda.default_stream(self.state.device)) - self.separate_graphs = SeparateGraphsMALSD() - with ( - torch.cuda.stream(stream_for_graph), - torch.inference_mode(), - torch.cuda.graph( - self.separate_graphs.before_loop, stream=stream_for_graph, capture_error_mode="thread_local" - ), - ): - self._before_loop() - - with ( - torch.cuda.stream(stream_for_graph), - torch.inference_mode(), - torch.cuda.graph( - self.separate_graphs.loop_body, stream=stream_for_graph, capture_error_mode="thread_local" - ), - ): - self._loop_body() - - with ( - torch.cuda.stream(stream_for_graph), - torch.inference_mode(), - torch.cuda.graph( - self.separate_graphs.loop_update_decoder, stream=stream_for_graph, capture_error_mode="thread_local" - ), - ): - self._loop_update_decoder() - - @cuda_python_required - def _full_graph_compile(self): - """Compile full graph for decoding""" - # Always create a new stream, because the per-thread default stream disallows stream capture to a graph. - stream_for_graph = torch.cuda.Stream(self.state.device) - self.full_graph = torch.cuda.CUDAGraph() - - with ( - torch.cuda.stream(stream_for_graph), - torch.inference_mode(), - torch.cuda.graph(self.full_graph, stream=stream_for_graph, capture_error_mode="thread_local"), - ): - self._before_loop() - # NB: depending on cuda-python version, cudaStreamGetCaptureInfo can return either 5 or 6 elements - capture_status, _, graph, *_ = cu_call( - cudart.cudaStreamGetCaptureInfo(torch.cuda.current_stream(device=self.state.device).cuda_stream) - ) - - assert capture_status == cudart.cudaStreamCaptureStatus.cudaStreamCaptureStatusActive - - # capture: while self.active_mask_any: - (loop_conditional_handle,) = cu_call(cudart.cudaGraphConditionalHandleCreate(graph, 0, 0)) - loop_kernel = self._create_loop_body_kernel() - active_mask_any_ptr = np.array([self.state.active_mask_any.data_ptr()], dtype=np.uint64) - loop_args = np.array( - [loop_conditional_handle.getPtr(), active_mask_any_ptr.ctypes.data], - dtype=np.uint64, - ) - # loop while there are active utterances - with with_conditional_node(loop_kernel, loop_args, loop_conditional_handle, device=self.state.device): - self._loop_body() - self._loop_update_decoder() - - def _before_loop(self): - """ - Clears state and compute initial active mask - """ - - self.state.batched_hyps.clear_() - - # initial state for fusion models - if self.fusion_models is not None: - for fusion_idx, fusion_model in enumerate(self.fusion_models): - self.state.fusion_states_list[fusion_idx].copy_(self.state.init_fusion_states_list[fusion_idx]) - self.state.fusion_states_candidates_list[fusion_idx].copy_( - self.state.init_fusion_states_candidates_list[fusion_idx] - ) - self.state.fusion_scores_list[fusion_idx].copy_(self.state.init_fusion_scores_list[fusion_idx]) - self.state.fusion_states_prev_list[fusion_idx].copy_(self.state.init_fusion_states_list[fusion_idx]) - - # last found labels - initially () symbol - self.state.last_labels_wb.fill_(self._SOS) - self.state.next_scores.fill_(0.0) - self.state.next_labels.fill_(0.0) - self.state.next_idx.fill_(0.0) - - # time indices - self.state.time_indices.fill_(0) - self.state.safe_time_indices.fill_(0) # safe time indices: guaranteed to be < encoder_output_length - - torch.sub(self.state.encoder_output_length, 1, out=self.state.last_timesteps) - - # masks for utterances in batch - # same as: active_mask = self.encoder_output_length > 0 - torch.greater(self.state.encoder_output_length, 0, out=self.state.active_mask) - - # same as: self.active_mask_any = active_mask.any() - torch.any(self.state.active_mask, out=self.state.active_mask_any) - - # set decoder state and output to initial values - self.state.decoder_output.copy_(self.state.init_decoder_output) - self.state.decoder_state[0].copy_(self.state.init_decoder_state[0]) - self.state.decoder_state[1].copy_(self.state.init_decoder_state[1]) - - # set previous decoder state and output to initial values - self.state.prev_decoder_output.fill_(0) - self.state.prev_decoder_state[0].fill_(0) - self.state.prev_decoder_state[1].fill_(0) - - def _loop_body(self): - """Perform a single iteration of the batched RNN-T decoding loop.""" - # step 1: get joint output + fuse with fusion models (if present) - logits = self.joint.joint_after_projection( - self.state.encoder_output_projected[ - self.state.batch_indices.view(-1), self.state.safe_time_indices.view(-1) - ].unsqueeze(1), - self.state.decoder_output, - ).squeeze() - log_probs = F.log_softmax(logits, dim=-1, dtype=self.state.float_dtype).view( - self.state.batch_size, self.beam_size, -1 - ) # [(B x Beam), V] - - if self.fusion_models is not None: - log_probs_top_k, labels_top_k = self.topk_fusion_model(self.state.fusion_scores_list, log_probs) - else: - log_probs_top_k, labels_top_k = torch.topk(log_probs, self.beam_size, dim=-1, largest=True, sorted=True) - - # step 2: Make hyps candidates. Add new scores to hyps, force blank if necessary, recombine hyps, prune - # step 2.1: hyps candidates - log_probs_blank = log_probs[..., self._blank_index] # blank scores size: batch_size x beam_size - hyps_scores = self.state.batched_hyps.scores # previous hyp scores size: batch_size x beam_size - hyps_candidates_prob = ( - hyps_scores.unsqueeze(-1) + log_probs_top_k - ) # hyps with top-k labels size: batch_size x beam_size x beam_size - hyps_candidates_prob_forced_blank = ( - hyps_scores + log_probs_blank - ) # hyps with forced blank size: batch_size x beam_size - - # step 2.2 force add final (fully decoded) hyps with to the beam (without updating the score) - # mask inactive (final) hyps with -inf - torch.where( - self.state.active_mask.unsqueeze(-1), - hyps_candidates_prob, - self.state.INACTIVE_SCORE, - out=hyps_candidates_prob, - ) - # keep inactive (final hypotheses) at the first position in beam - torch.where( - self.state.active_mask, hyps_candidates_prob[..., 0], hyps_scores, out=hyps_candidates_prob[..., 0] - ) - # mark the labels corresponding to final hypotheses with negative label (e.g., -1) - torch.where( - self.state.active_mask.unsqueeze(-1), labels_top_k, self.state.NON_EXISTENT_LABEL, out=labels_top_k - ) - - # step 2.3: force blank extension with respect to self.max_symbols - if self.max_symbols is not None: - force_blank = (self.state.batched_hyps.last_timestamp_lasts >= self.max_symbols) & self.state.active_mask - else: - force_blank = torch.full_like(self.state.active_mask, fill_value=False) - # mask beams if forced blank - torch.where( - force_blank.unsqueeze(-1), self.state.INACTIVE_SCORE, hyps_candidates_prob, out=hyps_candidates_prob - ) - # keep hypotheses with forced blank at the first position in beam - torch.where( - force_blank, - hyps_candidates_prob_forced_blank, - hyps_candidates_prob[..., 0], - out=hyps_candidates_prob[..., 0], - ) - # change labels to blank if forced blank - torch.where(force_blank.unsqueeze(-1), self.state.BLANK_TENSOR, labels_top_k, out=labels_top_k) - - # step 2.4: final pruning - get top-beam from (beam x beam) hyps - next_hyps_prob, hyps_candidates_indices = torch.topk( - hyps_candidates_prob.view(self.state.batch_size, -1), k=self.beam_size, largest=True, sorted=True - ) - torch.gather( - self.state.beam_indices.reshape(self.state.batch_size, -1), - dim=-1, - index=hyps_candidates_indices, - out=self.state.next_idx, - ) # indices in beam extended with new label - torch.gather( - labels_top_k.reshape(self.state.batch_size, -1), - dim=-1, - index=hyps_candidates_indices, - out=self.state.next_labels, - ) # labels for extended hypotheses - self.state.next_scores.copy_(next_hyps_prob) - - # step 3: store results - if self.max_symbols is None: - self.state.batched_hyps.add_results_(self.state.next_idx, self.state.next_labels, self.state.next_scores) - else: - self.state.batched_hyps.add_results_no_checks_( - self.state.next_idx, self.state.next_labels, self.state.next_scores - ) - - # step 4: recombine hypotheses: sum probabilities of identical hypotheses. - self.state.batched_hyps.recombine_hyps_() - - def _loop_update_decoder(self): - """ - Updates the decoder state, decoder output, and optionally the fusion models state - for the next iteration of the decoding loop in a batched RNNT (Recurrent Neural Network Transducer) setup. - """ - - # step 5: update decoder state + decoder output (+ fusion models state/scores) - # step 5.1: mask invalid value labels with blank to avoid errors (refer to step 2.2) - torch.where( - self.state.next_labels >= 0, self.state.next_labels, self.state.BLANK_TENSOR, out=self.state.last_labels_wb - ) - preserve_state = self.state.last_labels_wb == self._blank_index - - # size: decoder_output [(B x Beam), 1, Dim] - # size: state tuple, each is of [Layers, (BxBeam), Dim] - # step 5.2: update decoder + fusion models state - # step 5.2.1: storing current decoder output and states of extended hypotheses - torch.gather( - self.state.decoder_output.view(self.state.batch_size, self.beam_size, 1, -1), - dim=1, - index=self.state.next_idx[:, :, None, None].expand( - self.state.batch_size, self.beam_size, 1, self.state.decoder_output.shape[-1] - ), - out=self.state.prev_decoder_output.view(self.state.batch_size, self.beam_size, 1, -1), - ) - self.decoder.batch_aggregate_states_beam( - self.state.decoder_state, - self.state.batch_size, - self.beam_size, - self.state.next_idx, - self.state.prev_decoder_state, - ) - - # step 5.2.2: get next decoder output and states for extended hypotheses - decoder_output, decoder_state, *_ = self.decoder.predict( - self.state.last_labels_wb.view(-1, 1), - self.state.prev_decoder_state, - add_sos=False, - batch_size=self.state.batch_size * self.beam_size, - ) - - # step 5.2.3: update decoder state and output only for non-blank and active hypotheses - torch.where( - preserve_state.view(-1)[:, None, None], - self.state.prev_decoder_output, - self.joint.project_prednet(decoder_output), - out=self.state.decoder_output, - ) - self.decoder.batch_replace_states_mask( - src_states=self.state.prev_decoder_state, - dst_states=self.state.decoder_state, - mask=preserve_state.view(-1), - other_src_states=decoder_state, - ) - - if self.fusion_models is not None: - # fusion_states: size: [(batch_size x beam_size)] - # fusion_states_candidates: [(batch_size x beam_size) x V (without blank)] - for fusion_idx, fusion_model in enumerate(self.fusion_models): - self.state.fusion_states_candidates_list[fusion_idx].copy_( - torch.gather( - self.state.fusion_states_candidates_list[fusion_idx], - dim=1, - index=self.state.next_idx[:, :, None].expand( - self.state.batch_size, - self.beam_size, - self.state.fusion_states_candidates_list[fusion_idx].shape[-1], - ), - ) - ) - torch.gather( - self.state.fusion_states_list[fusion_idx], - dim=1, - index=self.state.next_idx, - out=self.state.fusion_states_prev_list[fusion_idx], - ) - last_labels_wb_blank_replaced = torch.where(preserve_state, 0, self.state.last_labels_wb) - - torch.gather( - self.state.fusion_states_candidates_list[fusion_idx], - dim=-1, - index=last_labels_wb_blank_replaced.unsqueeze(-1), - out=self.state.fusion_states_list[fusion_idx].unsqueeze(-1), - ) - torch.where( - preserve_state, - self.state.fusion_states_prev_list[fusion_idx], - self.state.fusion_states_list[fusion_idx], - out=self.state.fusion_states_list[fusion_idx], - ) - fusion_scores, fusion_states_candidates = fusion_model.advance( - states=self.state.fusion_states_list[fusion_idx].view(-1) - ) - fusion_scores = ( - fusion_scores.to(dtype=self.state.float_dtype).view(self.state.batch_size, self.beam_size, -1) - * self.fusion_models_alpha[fusion_idx] - ) - self.state.fusion_states_candidates_list[fusion_idx].copy_( - fusion_states_candidates.view(self.state.batch_size, self.state.beam_size, -1) - ) - self.state.fusion_scores_list[fusion_idx].copy_(fusion_scores) - - # step 6: update time indices + active mask - self.state.time_indices.copy_(self.state.batched_hyps.next_timestamp) - torch.minimum(self.state.time_indices, self.state.last_timesteps, out=self.state.safe_time_indices) - torch.less_equal(self.state.time_indices, self.state.last_timesteps, out=self.state.active_mask) - torch.any(self.state.active_mask, out=self.state.active_mask_any) - - def __call__( - self, - x: torch.Tensor, - out_len: torch.Tensor, - ) -> BatchedBeamHyps: - if self.cuda_graphs_mode is not None and x.device.type == "cuda": - with torch.amp.autocast(device_type="cuda", enabled=False): - return self.modified_alsd_cuda_graphs(encoder_output=x, encoder_output_length=out_len) - - return self.modified_alsd_torch(encoder_output=x, encoder_output_length=out_len) diff --git a/nemo/collections/asr/parts/submodules/spectr_augment.py b/nemo/collections/asr/parts/submodules/spectr_augment.py deleted file mode 100644 index 5bc7104816afd375424a5f1b49680b409a506f7a..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/spectr_augment.py +++ /dev/null @@ -1,263 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import random - -import numpy as np -import torch -import torch.nn as nn - -from nemo.core.classes import Typing, typecheck -from nemo.core.neural_types import LengthsType, NeuralType, SpectrogramType - - -class SpecAugment(nn.Module, Typing): - """ - Zeroes out(cuts) random continuous horisontal or - vertical segments of the spectrogram as described in - SpecAugment (https://arxiv.org/abs/1904.08779). - - params: - freq_masks - how many frequency segments should be cut - time_masks - how many time segments should be cut - freq_width - maximum number of frequencies to be cut in one segment - time_width - maximum number of time steps to be cut in one segment. - Can be a positive integer or a float value in the range [0, 1]. - If positive integer value, defines maximum number of time steps - to be cut in one segment. - If a float value, defines maximum percentage of timesteps that - are cut adaptively. - use_vectorized_code - GPU-based implementation with batched masking and GPU rng, - setting it to False reverts to the legacy implementation. - Fast implementation is inspired by torchaudio: - https://github.com/pytorch/audio/blob/ea437b31ce316ea3d66fe73768c0dcb94edb79ad/src/torchaudio/functional/functional.py#L816 - """ - - FREQ_AXIS = 1 # Frequency axis in the spectrogram tensor - TIME_AXIS = 2 # Time axis in the spectrogram tensor - - @property - def input_types(self): - """Returns definitions of module input types""" - return { - "input_spec": NeuralType(('B', 'D', 'T'), SpectrogramType()), - "length": NeuralType(tuple('B'), LengthsType()), - } - - @property - def output_types(self): - """Returns definitions of module output types""" - return {"augmented_spec": NeuralType(('B', 'D', 'T'), SpectrogramType())} - - def __init__( - self, - freq_masks: int = 0, - time_masks: int = 0, - freq_width: int = 10, - time_width: int | float = 10, - rng: random.Random | None = None, - mask_value: float = 0.0, - use_vectorized_code: bool = True, - ): - super().__init__() - - self._rng = random.Random() if rng is None else rng - - self.freq_masks = freq_masks - self.time_masks = time_masks - - self.freq_width = freq_width - self.time_width = time_width - - self.mask_value = mask_value - self.use_vectorized_code = use_vectorized_code - - if isinstance(time_width, int): - self.adaptive_temporal_width = False - else: - if time_width > 1.0 or time_width < 0.0: - raise ValueError("If `time_width` is a float value, must be in range [0, 1]") - - self.adaptive_temporal_width = True - - @typecheck() - @torch.no_grad() - def forward(self, input_spec, length): - if self.use_vectorized_code: - return self._forward_vectorized(input_spec, length) - else: - return self._forward_legacy(input_spec, length) - - def _forward_legacy(self, input_spec, length): - batch_size, num_freq_bins, _ = input_spec.shape - # Move lengths to CPU before repeated indexing - lengths_cpu = length.cpu().numpy() - # Generate a numpy boolean mask. `True` elements represent where the input spec will be augmented. - fill_mask: np.array = np.full(shape=input_spec.shape, fill_value=False) - freq_start_upper_bound = num_freq_bins - self.freq_width - # Choose different mask ranges for each element of the batch - for idx in range(batch_size): - # Set freq masking - for _ in range(self.freq_masks): - start = self._rng.randint(0, freq_start_upper_bound) - width = self._rng.randint(0, self.freq_width) - fill_mask[idx, start : start + width, :] = True - - # Derive time width, sometimes based percentage of input length. - if self.adaptive_temporal_width: - time_max_width = max(1, int(lengths_cpu[idx] * self.time_width)) - else: - time_max_width = self.time_width - time_start_upper_bound = max(1, lengths_cpu[idx] - time_max_width) - - # Set time masking - for _ in range(self.time_masks): - start = self._rng.randint(0, time_start_upper_bound) - width = self._rng.randint(0, time_max_width) - fill_mask[idx, :, start : start + width] = True - # Bring the mask to device and fill spec - fill_mask = torch.from_numpy(fill_mask).to(input_spec.device) - masked_spec = input_spec.masked_fill(mask=fill_mask, value=self.mask_value) - return masked_spec - - def _forward_vectorized(self, input_spec: torch.Tensor, length: torch.Tensor) -> torch.Tensor: - # time masks - input_spec = self._apply_masks( - input_spec=input_spec, - num_masks=self.time_masks, - length=length, - width=self.time_width, - axis=self.TIME_AXIS, - mask_value=self.mask_value, - ) - # freq masks - input_spec = self._apply_masks( - input_spec=input_spec, - num_masks=self.freq_masks, - length=length, - width=self.freq_width, - axis=self.FREQ_AXIS, - mask_value=self.mask_value, - ) - return input_spec - - def _apply_masks( - self, - input_spec: torch.Tensor, - num_masks: int, - length: torch.Tensor, - width: int | float, - mask_value: float, - axis: int, - ) -> torch.Tensor: - - assert axis in ( - self.FREQ_AXIS, - self.TIME_AXIS, - ), f"Axis can be only be equal to frequency \ - ({self.FREQ_AXIS}) or time ({self.TIME_AXIS}). Received: {axis=}" - assert not ( - isinstance(width, float) and axis == self.FREQ_AXIS - ), "Float width supported \ - only with time axis." - - batch_size = input_spec.shape[0] - axis_length = input_spec.shape[axis] - - # If width is float then it is transformed into a tensor - if axis == self.TIME_AXIS and isinstance(width, float): - width = torch.clamp(width * length, max=axis_length).unsqueeze(1) - - # Generate [0-1) random numbers and then scale the tensors. - # Use float32 dtype for begin/end mask markers before they are quantized to long. - mask_width = torch.rand((batch_size, num_masks), device=input_spec.device, dtype=torch.float32) * width - mask_width = mask_width.long() - mask_start = torch.rand((batch_size, num_masks), device=input_spec.device, dtype=torch.float32) - - if axis == self.TIME_AXIS: - # length can only be used for the time axis - mask_start = mask_start * (length.unsqueeze(1) - mask_width) - else: - mask_start = mask_start * (axis_length - mask_width) - - mask_start = mask_start.long() - mask_end = mask_start + mask_width - - # Create mask values using vectorized indexing - indices = torch.arange(axis_length, device=input_spec.device) - # Create a mask_tensor with all the indices. - # The mask_tensor shape is (batch_size, num_masks, axis_length). - mask_tensor = (indices >= mask_start.unsqueeze(-1)) & (indices < mask_end.unsqueeze(-1)) - - # Reduce masks to one mask - mask_tensor = mask_tensor.any(dim=1) - - # Create a final mask that aligns with the full tensor - mask = torch.zeros_like(input_spec, dtype=torch.bool) - if axis == self.TIME_AXIS: - mask_ranges = mask_tensor[:, None, :] - else: # axis == self.FREQ_AXIS - mask_ranges = mask_tensor[:, :, None] - mask[:, :, :] = mask_ranges - - # Apply the mask value - return input_spec.masked_fill(mask=mask, value=mask_value) - - -class SpecCutout(nn.Module, Typing): - """ - Zeroes out(cuts) random rectangles in the spectrogram - as described in (https://arxiv.org/abs/1708.04552). - - params: - rect_masks - how many rectangular masks should be cut - rect_freq - maximum size of cut rectangles along the frequency dimension - rect_time - maximum size of cut rectangles along the time dimension - """ - - @property - def input_types(self): - """Returns definitions of module input types""" - return {"input_spec": NeuralType(('B', 'D', 'T'), SpectrogramType())} - - @property - def output_types(self): - """Returns definitions of module output types""" - return {"augmented_spec": NeuralType(('B', 'D', 'T'), SpectrogramType())} - - def __init__(self, rect_masks=0, rect_time=5, rect_freq=20, rng=None): - super(SpecCutout, self).__init__() - - self._rng = random.Random() if rng is None else rng - - self.rect_masks = rect_masks - self.rect_time = rect_time - self.rect_freq = rect_freq - - @typecheck() - @torch.no_grad() - def forward(self, input_spec): - sh = input_spec.shape - - for idx in range(sh[0]): - for i in range(self.rect_masks): - rect_x = self._rng.randint(0, sh[1] - self.rect_freq) - rect_y = self._rng.randint(0, sh[2] - self.rect_time) - - w_x = self._rng.randint(0, self.rect_freq) - w_y = self._rng.randint(0, self.rect_time) - - input_spec[idx, rect_x : rect_x + w_x, rect_y : rect_y + w_y] = 0.0 - - return input_spec diff --git a/nemo/collections/asr/parts/submodules/ssl_quantizers.py b/nemo/collections/asr/parts/submodules/ssl_quantizers.py deleted file mode 100644 index 26e69fa6d08788e2899959704d21159e15ac5e61..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/ssl_quantizers.py +++ /dev/null @@ -1,198 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import torch -import torch.nn.functional as F -from torch import nn - -from nemo.collections.asr.parts.submodules.jasper import jasper_activations -from nemo.core import NeuralModule -from nemo.core.neural_types import EncodedRepresentation, LossType, NeuralType - - -class GumbelVectorQuantizer(NeuralModule): - def __init__( - self, - dim, - num_vars, - temp, - groups, - combine_groups, - vq_dim, - time_first, - activation="gelu", - weight_proj_depth=1, - weight_proj_factor=1, - ): - """Vector quantization using gumbel softmax - - Args: - dim: input dimension (channels) - num_vars: number of quantized vectors per group - temp: temperature for training. this should be a tuple of 3 elements: (start, stop, decay factor) - groups: number of groups for vector quantization - combine_groups: whether to use the vectors for all groups - vq_dim: dimensionality of the resulting quantized vector - time_first: if true, expect input in BxTxC format, otherwise in BxCxT - activation: what activation to use (should be a module). this is only used if weight_proj_depth is > 1 - weight_proj_depth: number of layers (with activation in between) to project input before computing logits - weight_proj_factor: this is used only if weight_proj_depth is > 1. scales the inner dimensionality of - projections by this factor - """ - super().__init__() - - self.groups = groups - self.combine_groups = combine_groups - self.input_dim = dim - self.num_vars = num_vars - self.time_first = time_first - - assert vq_dim % groups == 0, f"dim {vq_dim} must be divisible by groups {groups} for concatenation" - - var_dim = vq_dim // groups - num_groups = groups if not combine_groups else 1 - - self.vars = nn.Parameter(torch.FloatTensor(1, num_groups * num_vars, var_dim)) - nn.init.uniform_(self.vars) - - if weight_proj_depth > 1: - activation = jasper_activations["gelu"] - - def block(input_dim, output_dim): - return nn.Sequential(nn.Linear(input_dim, output_dim), activation) - - inner_dim = self.input_dim * weight_proj_factor - self.weight_proj = nn.Sequential( - *[block(self.input_dim if i == 0 else inner_dim, inner_dim) for i in range(weight_proj_depth - 1)], - nn.Linear(inner_dim, groups * num_vars), - ) - else: - self.weight_proj = nn.Linear(self.input_dim, groups * num_vars) - nn.init.normal_(self.weight_proj.weight, mean=0, std=1) - nn.init.zeros_(self.weight_proj.bias) - - assert len(temp) == 3, "Quantize temperature should be a tuple of 3 elements: (start, stop, decay factor)" - - self.max_temp, self.min_temp, self.temp_decay = temp - self.curr_temp = self.max_temp - self.codebook_indices = None - - def set_num_updates(self, num_updates): - self.curr_temp = max(self.max_temp * self.temp_decay**num_updates, self.min_temp) - - def get_codebook_indices(self): - if self.codebook_indices is None: - from itertools import product - - p = [range(self.num_vars)] * self.groups - inds = list(product(*p)) - self.codebook_indices = torch.tensor(inds, dtype=torch.long, device=self.vars.device).flatten() - - if not self.combine_groups: - self.codebook_indices = self.codebook_indices.view(self.num_vars**self.groups, -1) - for b in range(1, self.groups): - self.codebook_indices[:, b] += self.num_vars * b - self.codebook_indices = self.codebook_indices.flatten() - return self.codebook_indices - - def sample_from_codebook(self, b, n): - indices = self.get_codebook_indices() - indices = indices.view(-1, self.groups) - cb_size = indices.size(0) - assert n < cb_size, f"sample size {n} is greater than size of codebook {cb_size}" - sample_idx = torch.randint(low=0, high=cb_size, size=(b * n,)) - indices = indices[sample_idx] - - z = self.vars.squeeze(0).index_select(0, indices.flatten()).view(b, n, -1) - return z - - @property - def input_types(self): - """Returns definitions of module input ports.""" - if self.time_first: - return {"x": NeuralType(('B', 'T', 'D'), EncodedRepresentation())} - return {"x": NeuralType(('B', 'D', 'T'), EncodedRepresentation())} - - @property - def output_types(self): - """Returns definitions of module output ports.""" - if self.time_first: - return { - "x": NeuralType(('B', 'T', 'D'), EncodedRepresentation()), - "quantize_prob_ppl": NeuralType(elements_type=LossType()), - } - return { - "x": NeuralType(('B', 'D', 'T'), EncodedRepresentation()), - "quantize_prob_ppl": NeuralType(elements_type=LossType()), - } - - def forward(self, x, return_ids=False): - - if not self.time_first: - x = x.transpose(1, 2) - - bsz, tsz, fsz = x.shape - x = x.reshape(-1, fsz) - x = self.weight_proj(x) - x = x.view(bsz * tsz * self.groups, -1) - - _, k = x.max(-1) - hard_x = x.new_zeros(*x.shape).scatter_(-1, k.view(-1, 1), 1.0).view(bsz * tsz, self.groups, -1) - - # Calculate quantize prob perplexity - num_vars = self.num_vars * self.groups - avg_probs = torch.softmax(x.view(bsz * tsz, self.groups, -1).float(), dim=-1).mean(dim=0) - quantize_prob_ppl = torch.exp(-torch.sum(avg_probs * torch.log(avg_probs + 1e-7), dim=-1)).sum() - quantize_prob_ppl = (num_vars - quantize_prob_ppl) / num_vars - - if self.training: - x = F.gumbel_softmax(x.float(), tau=self.curr_temp, hard=True).type_as(x) - else: - x = hard_x - - x = x.view(bsz * tsz, -1) - - vars = self.vars - if self.combine_groups: - vars = vars.repeat(1, self.groups, 1) - - x = x.unsqueeze(-1) * vars - x = x.view(bsz * tsz, self.groups, self.num_vars, -1) - x = x.sum(-2) - x = x.view(bsz, tsz, -1) - - cur_codebook_temp = self.curr_temp - - if not self.time_first: - x = x.transpose(1, 2) # BTC -> BCT - - if return_ids: - hard_x_max = hard_x.argmax(-1).reshape(bsz, tsz, -1) - # BxTxG - - # create single id from multiple group ids - target_ids = hard_x.new_zeros(bsz, tsz).long() - - for i in range(self.groups): - target_ids *= self.num_vars - target_ids += hard_x_max[:, :, i] - - return x, quantize_prob_ppl, cur_codebook_temp, target_ids - else: - return x, quantize_prob_ppl, cur_codebook_temp diff --git a/nemo/collections/asr/parts/submodules/stateless_net.py b/nemo/collections/asr/parts/submodules/stateless_net.py deleted file mode 100644 index 7581fdc2834d7acee9ad5c2c008c948955fff945..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/stateless_net.py +++ /dev/null @@ -1,125 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import Any, Dict, List, Optional, Tuple, Union - -import torch - - -class StatelessNet(torch.nn.Module): - """ - Helper class used in transducer models with stateless decoders. This stateless - simply outputs embedding or concatenated embeddings for the input label[s], - depending on the configured context size. - - Args: - context_size: history context size for the stateless decoder network. Could be any positive integer. We recommend setting this as 2. - vocab_size: total vocabulary size. - emb_dim: total embedding size of the stateless net output. - blank_idx: index for the blank symbol for the transducer model. - normalization_mode: normalization run on the output embeddings. Could be either 'layer' or None. We recommend using 'layer' to stabilize training. - dropout: dropout rate on the embedding outputs. - """ - - def __init__(self, context_size, vocab_size, emb_dim, blank_idx, normalization_mode, dropout): - super().__init__() - assert context_size > 0 - self.context_size = context_size - self.vocab_size = vocab_size - self.emb_dim = emb_dim - self.dropout = torch.nn.Dropout(dropout) - self.norm = torch.nn.Identity() - if normalization_mode == 'layer': - self.norm = torch.nn.LayerNorm(emb_dim, elementwise_affine=False) - - embeds = [] - for i in range(self.context_size): - # We use different embedding matrices for different context positions. - # In this list, a smaller index means more recent history word. - # We assign more dimensions for the most recent word in the history. - # The detailed method is, we first allocate half the embedding-size - # to the most recent history word, and then allocate the remaining - # dimensions evenly among all history contexts. E.g. if total embedding - # size is 200, and context_size is 2, then we allocate 150 dimensions - # to the last word, and 50 dimensions to the second-to-last word. - if i != 0: - embed_size = emb_dim // 2 // self.context_size - else: - embed_size = emb_dim - (emb_dim // 2 // self.context_size) * (self.context_size - 1) - - embed = torch.nn.Embedding(vocab_size + 1, embed_size, padding_idx=blank_idx) - embeds.append(embed) - - self.embeds = torch.nn.ModuleList(embeds) - self.blank_idx = blank_idx - - def forward( - self, y: Optional[torch.Tensor] = None, state: Optional[List[torch.Tensor]] = None, - ): - """ - Although this is a *stateless* net, we use the "state" parameter to - pass in the previous labels, unlike LSTMs where state would represent - hidden activations of the network. - - Args: - y: a Integer tensor of shape B x U. - state: a list of 1 tensor in order to be consistent with the stateful - decoder interface, and the element is a tensor of shape [B x context-length]. - - Returns: - The return dimension of this function's output is B x U x D, with D being the total embedding dim. - """ - outs = [] - - [B, U] = y.shape - appended_y = y - if state != None: - appended_y = torch.concat([state[0], y], axis=1) - context_size = appended_y.shape[1] - - if context_size < self.context_size: - # This is the case at the beginning of an utterance where we have - # seen less words than context_size. In this case, we need to pad - # it to the right length. - padded_state = torch.ones([B, self.context_size], dtype=torch.long, device=y.device) * self.blank_idx - padded_state[:, self.context_size - context_size :] = appended_y - elif context_size == self.context_size + 1: - padded_state = appended_y[:, 1:] - # This is the case where the previous state already has reached context_size. - # We need to truncate the history by omitting the 0'th token. - else: - # Context has just the right size. Copy directly. - padded_state = appended_y - - for i in range(self.context_size): - out = self.embeds[i](padded_state[:, self.context_size - 1 - i : self.context_size - i]) - outs.append(out) - else: - for i in range(self.context_size): - out = self.embeds[i](y) - - if i != 0: - out[:, i:, :] = out[ - :, :-i, : - ].clone() # needs clone() here or it might complain about src and dst mem location have overlaps. - out[:, :i, :] *= 0.0 - outs.append(out) - - out = self.dropout(torch.concat(outs, axis=-1)) - out = self.norm(out) - - state = None - if y is not None: - state = [appended_y[:, appended_y.shape[1] - self.context_size + 1 :]] - return out, state diff --git a/nemo/collections/asr/parts/submodules/subsampling.py b/nemo/collections/asr/parts/submodules/subsampling.py deleted file mode 100644 index 7f9fc606991cb2a32411e38a6ec34f19007456d2..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/subsampling.py +++ /dev/null @@ -1,689 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import math - -import torch -import torch.nn as nn -from torch.nn import LayerNorm - -from nemo.collections.asr.parts.submodules.causal_convs import CausalConv1D, CausalConv2D -from nemo.utils import logging - - -class StackingSubsampling(torch.nn.Module): - """Stacking subsampling which simply stacks consecutive frames to reduce the sampling rate - Args: - subsampling_factor (int): The subsampling factor - feat_in (int): size of the input features - feat_out (int): size of the output features - norm (bool): whether to use an MLP layer after the stacking along with normalization. default is False. - """ - - def __init__(self, subsampling_factor, feat_in, feat_out, norm=False): - super(StackingSubsampling, self).__init__() - self.subsampling_factor = subsampling_factor - self.proj_out = torch.nn.Linear(subsampling_factor * feat_in, feat_out) - if norm: - self.pre_norm = LayerNorm(feat_in) - else: - self.pre_norm = None - - def get_sampling_frames(self): - return self.subsampling_factor - - def get_streaming_cache_size(self): - return 0 - - def forward(self, x, lengths): - b, t, h = x.size() - pad_size = (self.subsampling_factor - (t % self.subsampling_factor)) % self.subsampling_factor - x = torch.nn.functional.pad(x, (0, 0, 0, pad_size)) - if self.pre_norm is not None: - x = self.pre_norm(x) - _, t, _ = x.size() - x = torch.reshape(x, (b, t // self.subsampling_factor, h * self.subsampling_factor)) - x = self.proj_out(x) - lengths = torch.div(lengths + pad_size, self.subsampling_factor, rounding_mode='floor') - return x, lengths - - -class ConvSubsampling(torch.nn.Module): - """Convolutional subsampling which supports VGGNet and striding approach introduced in: - VGGNet Subsampling: Transformer-transducer: end-to-end speech recognition with self-attention (https://arxiv.org/pdf/1910.12977.pdf) - Striding Subsampling: "Speech-Transformer: A No-Recurrence Sequence-to-Sequence Model for Speech Recognition" by Linhao Dong et al. (https://ieeexplore.ieee.org/document/8462506) - Args: - subsampling (str): The subsampling technique from {"vggnet", "striding", "dw-striding"} - subsampling_factor (int): The subsampling factor which should be a power of 2 - subsampling_conv_chunking_factor (int): Input chunking factor which can be -1 (no chunking) - 1 (auto) or a power of 2. Default is 1 - feat_in (int): size of the input features - feat_out (int): size of the output features - conv_channels (int): Number of channels for the convolution layers. - activation (Module): activation function, default is nn.ReLU() - """ - - def __init__( - self, - subsampling, - subsampling_factor, - feat_in, - feat_out, - conv_channels, - subsampling_conv_chunking_factor=1, - activation=nn.ReLU(), - is_causal=False, - ): - super(ConvSubsampling, self).__init__() - self._subsampling = subsampling - self._conv_channels = conv_channels - self._feat_in = feat_in - self._feat_out = feat_out - - if subsampling_factor % 2 != 0: - raise ValueError("Sampling factor should be a multiply of 2!") - self._sampling_num = int(math.log(subsampling_factor, 2)) - self.subsampling_factor = subsampling_factor - self.is_causal = is_causal - - if ( - subsampling_conv_chunking_factor != -1 - and subsampling_conv_chunking_factor != 1 - and subsampling_conv_chunking_factor % 2 != 0 - ): - raise ValueError("subsampling_conv_chunking_factor should be -1, 1, or a power of 2") - self.subsampling_conv_chunking_factor = subsampling_conv_chunking_factor - - in_channels = 1 - layers = [] - - if subsampling == 'vggnet': - self._stride = 2 - self._kernel_size = 2 - self._ceil_mode = True - - self._left_padding = 0 - self._right_padding = 0 - - for i in range(self._sampling_num): - layers.append( - torch.nn.Conv2d( - in_channels=in_channels, out_channels=conv_channels, kernel_size=3, stride=1, padding=1 - ) - ) - layers.append(activation) - layers.append( - torch.nn.Conv2d( - in_channels=conv_channels, out_channels=conv_channels, kernel_size=3, stride=1, padding=1 - ) - ) - layers.append(activation) - layers.append( - torch.nn.MaxPool2d( - kernel_size=self._kernel_size, - stride=self._stride, - padding=self._left_padding, - ceil_mode=self._ceil_mode, - ) - ) - in_channels = conv_channels - - elif subsampling == 'dw_striding': - self._stride = 2 - self._kernel_size = 3 - self._ceil_mode = False - - if self.is_causal: - self._left_padding = self._kernel_size - 1 - self._right_padding = self._stride - 1 - self._max_cache_len = subsampling_factor + 1 - else: - self._left_padding = (self._kernel_size - 1) // 2 - self._right_padding = (self._kernel_size - 1) // 2 - self._max_cache_len = 0 - - # Layer 1 - if self.is_causal: - layers.append( - CausalConv2D( - in_channels=in_channels, - out_channels=conv_channels, - kernel_size=self._kernel_size, - stride=self._stride, - padding=None, - ) - ) - else: - layers.append( - torch.nn.Conv2d( - in_channels=in_channels, - out_channels=conv_channels, - kernel_size=self._kernel_size, - stride=self._stride, - padding=self._left_padding, - ) - ) - in_channels = conv_channels - layers.append(activation) - - for i in range(self._sampling_num - 1): - if self.is_causal: - layers.append( - CausalConv2D( - in_channels=in_channels, - out_channels=in_channels, - kernel_size=self._kernel_size, - stride=self._stride, - padding=None, - groups=in_channels, - ) - ) - else: - layers.append( - torch.nn.Conv2d( - in_channels=in_channels, - out_channels=in_channels, - kernel_size=self._kernel_size, - stride=self._stride, - padding=self._left_padding, - groups=in_channels, - ) - ) - - layers.append( - torch.nn.Conv2d( - in_channels=in_channels, - out_channels=conv_channels, - kernel_size=1, - stride=1, - padding=0, - groups=1, - ) - ) - layers.append(activation) - in_channels = conv_channels - - elif subsampling == 'striding': - self._stride = 2 - self._kernel_size = 3 - self._ceil_mode = False - - if self.is_causal: - self._left_padding = self._kernel_size - 1 - self._right_padding = self._stride - 1 - self._max_cache_len = subsampling_factor + 1 - else: - self._left_padding = (self._kernel_size - 1) // 2 - self._right_padding = (self._kernel_size - 1) // 2 - self._max_cache_len = 0 - - for i in range(self._sampling_num): - if self.is_causal: - layers.append( - CausalConv2D( - in_channels=in_channels, - out_channels=conv_channels, - kernel_size=self._kernel_size, - stride=self._stride, - padding=None, - ) - ) - else: - layers.append( - torch.nn.Conv2d( - in_channels=in_channels, - out_channels=conv_channels, - kernel_size=self._kernel_size, - stride=self._stride, - padding=self._left_padding, - ) - ) - layers.append(activation) - in_channels = conv_channels - - elif subsampling == 'striding_conv1d': - - in_channels = feat_in - - self._stride = 2 - self._kernel_size = 5 - self._ceil_mode = False - - if self.is_causal: - self._left_padding = self._kernel_size - 1 - self._right_padding = self._stride - 1 - self._max_cache_len = subsampling_factor + 1 - else: - self._left_padding = (self._kernel_size - 1) // 2 - self._right_padding = (self._kernel_size - 1) // 2 - self._max_cache_len = 0 - - for i in range(self._sampling_num): - if self.is_causal: - layers.append( - CausalConv1D( - in_channels=in_channels, - out_channels=feat_out if self._sampling_num == i + 1 else conv_channels, - kernel_size=self._kernel_size, - stride=self._stride, - padding=None, - ) - ) - else: - layers.append( - torch.nn.Conv1d( - in_channels=in_channels, - out_channels=feat_out if self._sampling_num == i + 1 else conv_channels, - kernel_size=self._kernel_size, - stride=self._stride, - padding=self._left_padding, - ) - ) - layers.append(activation) - in_channels = conv_channels - - elif subsampling == 'dw_striding_conv1d': - - in_channels = feat_in - - self._stride = 2 - self._kernel_size = 5 - self._ceil_mode = False - - self._left_padding = (self._kernel_size - 1) // 2 - self._right_padding = (self._kernel_size - 1) // 2 - - # Layer 1 - layers.extend( - [ - torch.nn.Conv1d( - in_channels=in_channels, - out_channels=in_channels, - kernel_size=self._kernel_size, - stride=self._stride, - padding=self._left_padding, - groups=in_channels, - ), - torch.nn.Conv1d( - in_channels=in_channels, - out_channels=feat_out if self._sampling_num == 1 else conv_channels, - kernel_size=1, - stride=1, - padding=0, - groups=1, - ), - ] - ) - in_channels = conv_channels - layers.append(activation) - - for i in range(self._sampling_num - 1): - layers.extend( - [ - torch.nn.Conv1d( - in_channels=in_channels, - out_channels=in_channels, - kernel_size=self._kernel_size, - stride=self._stride, - padding=self._left_padding, - groups=in_channels, - ), - torch.nn.Conv1d( - in_channels=in_channels, - out_channels=feat_out if self._sampling_num == i + 2 else conv_channels, - kernel_size=1, - stride=1, - padding=0, - groups=1, - ), - ] - ) - layers.append(activation) - in_channels = conv_channels - - else: - raise ValueError(f"Not valid sub-sampling: {subsampling}!") - - if subsampling in ["vggnet", "dw_striding", "striding"]: - - in_length = torch.tensor(feat_in, dtype=torch.float) - out_length = calc_length( - lengths=in_length, - all_paddings=self._left_padding + self._right_padding, - kernel_size=self._kernel_size, - stride=self._stride, - ceil_mode=self._ceil_mode, - repeat_num=self._sampling_num, - ) - self.out = torch.nn.Linear(conv_channels * int(out_length), feat_out) - self.conv2d_subsampling = True - elif subsampling in ["striding_conv1d", "dw_striding_conv1d"]: - self.out = None - self.conv2d_subsampling = False - else: - raise ValueError(f"Not valid sub-sampling: {subsampling}!") - - self.conv = MaskedConvSequential(*layers) - - def get_sampling_frames(self): - return [1, self.subsampling_factor] - - def get_streaming_cache_size(self): - return [0, self.subsampling_factor + 1] - - def forward(self, x, lengths): - out_lengths = calc_length( - lengths, - all_paddings=self._left_padding + self._right_padding, - kernel_size=self._kernel_size, - stride=self._stride, - ceil_mode=self._ceil_mode, - repeat_num=self._sampling_num, - ) - - # Transpose to Channel First mode - if not self.conv2d_subsampling: - x = x.transpose(1, 2) - - # split inputs if chunking_factor is set - if self.subsampling_conv_chunking_factor != -1 and self.conv2d_subsampling: - if self.subsampling_conv_chunking_factor == 1: - # if subsampling_conv_chunking_factor is 1, we split only if needed - # avoiding a bug / feature limiting indexing of tensors to 2**31 - # see https://github.com/pytorch/pytorch/issues/80020 - x_ceil = 2**31 / self._conv_channels * self._stride * self._stride - if torch.numel(x) > x_ceil: - need_to_split = True - else: - need_to_split = False - else: - # if subsampling_conv_chunking_factor > 1 we always split - need_to_split = True - - if need_to_split: - x, lengths, success = self.conv_split_by_batch(x, lengths) - if not success: # if unable to split by batch, try by channel - if self._subsampling == 'dw_striding': - # TODO: implement lengths inside conv_split_by_channel - x = self.conv_split_by_channel(x) - lengths = out_lengths - else: - x, lengths = self.conv(x, lengths) # try anyway - else: - x, lengths = self.conv(x, lengths) - else: - x, lengths = self.conv(x) - - # Flatten Channel and Frequency Axes - if self.conv2d_subsampling: - b, c, t, f = x.size() - x = self.out(x.transpose(1, 2).reshape(b, t, -1)) - # Transpose to Channel Last mode - else: - x = x.transpose(1, 2) - - return x, lengths - - def reset_parameters(self): - # initialize weights - if self._subsampling == 'dw_striding': - with torch.no_grad(): - # init conv - scale = 1.0 / self._kernel_size - dw_max = (self._kernel_size**2) ** -0.5 - pw_max = self._conv_channels**-0.5 - - torch.nn.init.uniform_(self.conv[0].weight, -scale, scale) - torch.nn.init.uniform_(self.conv[0].bias, -scale, scale) - - for idx in range(2, len(self.conv), 3): - torch.nn.init.uniform_(self.conv[idx].weight, -dw_max, dw_max) - torch.nn.init.uniform_(self.conv[idx].bias, -dw_max, dw_max) - torch.nn.init.uniform_(self.conv[idx + 1].weight, -pw_max, pw_max) - torch.nn.init.uniform_(self.conv[idx + 1].bias, -pw_max, pw_max) - - # init fc (80 * 64 = 5120 from https://github.com/kssteven418/Squeezeformer/blob/13c97d6cf92f2844d2cb3142b4c5bfa9ad1a8951/src/models/conformer_encoder.py#L487 - fc_scale = (self._feat_out * self._feat_in / self._sampling_num) ** -0.5 - torch.nn.init.uniform_(self.out.weight, -fc_scale, fc_scale) - torch.nn.init.uniform_(self.out.bias, -fc_scale, fc_scale) - - def conv_split_by_batch(self, x, lengths): - """Tries to split input by batch, run conv and concat results""" - b, *_ = x.size() - if b == 1: # can't split if batch size is 1 - return x, lengths, False - - if self.subsampling_conv_chunking_factor > 1: - cf = self.subsampling_conv_chunking_factor - logging.debug(f'using manually set chunking factor: {cf}') - else: - # avoiding a bug / feature limiting indexing of tensors to 2**31 - # see https://github.com/pytorch/pytorch/issues/80020 - x_ceil = 2**31 / self._conv_channels * self._stride * self._stride - p = math.ceil(math.log(torch.numel(x) / x_ceil, 2)) - cf = 2**p - logging.debug(f'using auto set chunking factor: {cf}') - - new_batch_size = b // cf - if new_batch_size == 0: # input is too big - return x, lengths, False - - logging.debug(f'conv subsampling: using split batch size {new_batch_size}') - - ans = [ - self.conv(chunk, ln) - for chunk, ln in zip( - torch.split(x, new_batch_size, 0), - torch.split(lengths, new_batch_size, 0), - ) - ] - return torch.cat([a[0] for a in ans]), torch.cat([a[1] for a in ans]), True - - def conv_split_by_channel(self, x): - """For dw convs, tries to split input by time, run conv and concat results""" - - # Note: this method doesn't use the convolution masking implemented in MaskedConvolutionSequential - x = x.unsqueeze(0) - x = self.conv[0](x) # full conv2D - x = self.conv[1](x) # activation - - for i in range(self._sampling_num - 1): - _, c, t, _ = x.size() - - if self.subsampling_conv_chunking_factor > 1: - cf = self.subsampling_conv_chunking_factor - logging.debug(f'using manually set chunking factor: {cf}') - else: - # avoiding a bug / feature limiting indexing of tensors to 2**31 - # see https://github.com/pytorch/pytorch/issues/80020 - p = math.ceil(math.log(torch.numel(x) / 2**31, 2)) - cf = 2**p - logging.debug(f'using auto set chunking factor: {cf}') - - new_c = int(c // cf) - if new_c == 0: - logging.warning(f'chunking factor {cf} is too high; splitting down to one channel.') - new_c = 1 - - new_t = int(t // cf) - if new_t == 0: - logging.warning(f'chunking factor {cf} is too high; splitting down to one timestep.') - new_t = 1 - - logging.debug(f'conv dw subsampling: using split C size {new_c} and split T size {new_t}') - x = self.channel_chunked_conv(self.conv[i * 3 + 2], new_c, x) # conv2D, depthwise - - # splitting pointwise convs by time - x = torch.cat([self.conv[i * 3 + 3](chunk) for chunk in torch.split(x, new_t, 2)], 2) # conv2D, pointwise - x = self.conv[i * 3 + 4](x) # activation - return x - - def channel_chunked_conv(self, conv, chunk_size, x): - """Performs channel chunked convolution""" - - ind = 0 - out_chunks = [] - for chunk in torch.split(x, chunk_size, 1): - step = chunk.size()[1] - - if self.is_causal: - chunk = nn.functional.pad( - chunk, pad=(self._kernel_size - 1, self._stride - 1, self._kernel_size - 1, self._stride - 1) - ) - ch_out = nn.functional.conv2d( - chunk, - conv.weight[ind : ind + step, :, :, :], - bias=conv.bias[ind : ind + step], - stride=self._stride, - padding=0, - groups=step, - ) - else: - ch_out = nn.functional.conv2d( - chunk, - conv.weight[ind : ind + step, :, :, :], - bias=conv.bias[ind : ind + step], - stride=self._stride, - padding=self._left_padding, - groups=step, - ) - out_chunks.append(ch_out) - ind += step - - return torch.cat(out_chunks, 1) - - def change_subsampling_conv_chunking_factor(self, subsampling_conv_chunking_factor: int): - if ( - subsampling_conv_chunking_factor != -1 - and subsampling_conv_chunking_factor != 1 - and subsampling_conv_chunking_factor % 2 != 0 - ): - raise ValueError("subsampling_conv_chunking_factor should be -1, 1, or a power of 2") - self.subsampling_conv_chunking_factor = subsampling_conv_chunking_factor - - -def calc_length(lengths, all_paddings, kernel_size, stride, ceil_mode, repeat_num=1): - """Calculates the output length of a Tensor passed through a convolution or max pooling layer""" - add_pad: float = all_paddings - kernel_size - one: float = 1.0 - for i in range(repeat_num): - lengths = torch.div(lengths.to(dtype=torch.float) + add_pad, stride) + one - if ceil_mode: - lengths = torch.ceil(lengths) - else: - lengths = torch.floor(lengths) - return lengths.to(dtype=torch.int) - - -class SubsamplingReductionModule(nn.Module): - """Downsamples the audio signal in time dimension.""" - - def __init__(self, reduction: str, d_model: int, reduction_factor: int = 2): - super().__init__() - - assert reduction in ['pooling', 'striding'] - - self.reduction = reduction - self.d_model = d_model - self._sampling_num = int(math.log(reduction_factor, 2)) - - if reduction == 'pooling': - self.reduction_enc = nn.MaxPool1d(kernel_size=reduction_factor) - self.padding = 0 - self.kernel_size = self.reduction_enc.kernel_size - self.stride = self.reduction_enc.stride - elif reduction == 'striding': - self.reduction_enc = ConvSubsampling( - subsampling='striding', - subsampling_factor=reduction_factor, - feat_in=d_model, - feat_out=d_model, - conv_channels=d_model, - activation=nn.ReLU(), - is_causal=False, - ) - - def forward(self, x, lengths): - """Shapes: - - x: [B, T, C] - - lengths: [B] - """ - - if self.reduction == 'striding': - x, lengths = self.reduction_enc(x=x, lengths=lengths) - else: - x = torch.transpose(x, 1, 2) # [B, C, T] - lengths = calc_length( - lengths=lengths, - all_paddings=self.padding, - kernel_size=self.kernel_size, - stride=self.stride, - ceil_mode=False, - repeat_num=self._sampling_num, - ) - x = self.reduction_enc(x) - x = torch.transpose(x, 1, 2) # [B, T, C] - - return x, lengths - - -def apply_channel_mask(tensor, mask): - """Apply mask to tensor with channel dimension.""" - # tensor: (batch, channels, time, features) - # mask: (batch, time, features) - batch_size, channels, time, features = tensor.shape - expanded_mask = mask.unsqueeze(1).expand(batch_size, channels, time, features) - return tensor * expanded_mask - - -def calculate_conv_output_size(input_size: torch.Tensor, kernel_size: int, stride: int, padding: tuple[int, int]): - """Calculate exact output size after convolution.""" - return (input_size + padding[0] + padding[1] - kernel_size) // stride + 1 - - -class MaskedConvSequential(nn.Sequential): - def forward(self, x, lengths): - # Convert input (batch, time, features) to conv format - x = x.unsqueeze(1) # (batch, 1, time, features) - current_lengths = lengths.clone().float() - mask = self._create_mask(x, current_lengths.long()) - - # Process through each layer with mask propagation - for i, layer in enumerate(self): - # Apply current mask before layer - x = apply_channel_mask(x, mask) - - # Apply layer - x = layer(x) - - # Update lengths for stride operations with proper padding - if hasattr(layer, 'stride') and layer.stride != (1, 1): - if hasattr(layer, "_left_padding"): - padding = (layer._left_padding, layer._right_padding) # CausalConv2D - else: - padding = layer.padding - current_lengths = calculate_conv_output_size( - current_lengths, layer.kernel_size[0], layer.stride[0], padding - ) - mask = self._create_mask(x, current_lengths.long()) - - # Final masking - x = apply_channel_mask(x, mask) - return x, current_lengths.long() - - def _create_mask(self, tensor, lengths): - """Create mask matching tensor dimensions.""" - batch_size, channels, time, features = tensor.shape - time_mask = torch.arange(time, device=tensor.device).expand(batch_size, time) < lengths.unsqueeze(1) - return time_mask.unsqueeze(-1).expand(batch_size, time, features).to(tensor.dtype) diff --git a/nemo/collections/asr/parts/submodules/tdnn_attention.py b/nemo/collections/asr/parts/submodules/tdnn_attention.py deleted file mode 100644 index 0b504efcef7a531cb9d5272d4fef67d30cdacffb..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/tdnn_attention.py +++ /dev/null @@ -1,339 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import List - -import torch -from numpy import inf -from torch import nn as nn -from torch.nn import functional as F - -from nemo.collections.asr.parts.submodules.jasper import get_same_padding, init_weights - - -class StatsPoolLayer(nn.Module): - """Statistics and time average pooling (TAP) layer - - This computes mean and, optionally, standard deviation statistics across the time dimension. - - Args: - feat_in: Input features with shape [B, D, T] - pool_mode: Type of pool mode. Supported modes are 'xvector' (mean and standard deviation) and 'tap' (time - average pooling, i.e., mean) - eps: Epsilon, minimum value before taking the square root, when using 'xvector' mode. - unbiased: Whether to use the biased estimator for the standard deviation when using 'xvector' mode. The default - for torch.Tensor.std() is True. - - Returns: - Pooled statistics with shape [B, D]. - - Raises: - ValueError if an unsupported pooling mode is specified. - """ - - def __init__(self, feat_in: int, pool_mode: str = 'xvector', eps: float = 1e-10, unbiased: bool = True): - super().__init__() - supported_modes = {"xvector", "tap"} - if pool_mode not in supported_modes: - raise ValueError(f"Pool mode must be one of {supported_modes}; got '{pool_mode}'") - self.pool_mode = pool_mode - self.feat_in = feat_in - self.eps = eps - self.unbiased = unbiased - if self.pool_mode == 'xvector': - # Mean + std - self.feat_in *= 2 - - def forward(self, encoder_output, length=None): - if length is None: - mean = encoder_output.mean(dim=-1) # Time Axis - if self.pool_mode == 'xvector': - correction = 1 if self.unbiased else 0 - std = encoder_output.std(dim=-1, correction=correction).clamp(min=self.eps) - pooled = torch.cat([mean, std], dim=-1) - else: - pooled = mean - else: - mask = make_seq_mask_like(like=encoder_output, lengths=length, valid_ones=False) - encoder_output = encoder_output.masked_fill(mask, 0.0) - # [B, D, T] -> [B, D] - means = encoder_output.mean(dim=-1) - # Re-scale to get padded means - means = means * (encoder_output.shape[-1] / length).unsqueeze(-1) - if self.pool_mode == "xvector": - correction = 1 if self.unbiased else 0 - stds = ( - encoder_output.sub(means.unsqueeze(-1)) - .masked_fill(mask, 0.0) - .pow(2.0) - .sum(-1) # [B, D, T] -> [B, D] - .div(length.view(-1, 1).sub(correction)) - .clamp(min=self.eps) - .sqrt() - ) - pooled = torch.cat((means, stds), dim=-1) - else: - pooled = means - return pooled - - -@torch.jit.script_if_tracing -def make_seq_mask_like( - like: torch.Tensor, lengths: torch.Tensor, valid_ones: bool = True, time_dim: int = -1 -) -> torch.Tensor: - mask = torch.arange(like.shape[time_dim], device=like.device).repeat(lengths.shape[0], 1).lt(lengths.unsqueeze(-1)) - # Match number of dims in `like` tensor - for _ in range(like.dim() - mask.dim()): - mask = mask.unsqueeze(1) - # If time dim != -1, transpose to proper dim. - if time_dim != -1: - mask = mask.transpose(time_dim, -1) - if not valid_ones: - mask = ~mask - return mask - - -def lens_to_mask(lens: List[int], max_len: int, device: str = None): - """ - outputs masking labels for list of lengths of audio features, with max length of any - mask as max_len - input: - lens: list of lens - max_len: max length of any audio feature - output: - mask: masked labels - num_values: sum of mask values for each feature (useful for computing statistics later) - """ - lens_mat = torch.arange(max_len).to(device) - mask = lens_mat[:max_len].unsqueeze(0) < lens.unsqueeze(1) - mask = mask.unsqueeze(1) - num_values = torch.sum(mask, dim=2, keepdim=True) - return mask, num_values - - -def get_statistics_with_mask(x: torch.Tensor, m: torch.Tensor, dim: int = 2, eps: float = 1e-10): - """ - compute mean and standard deviation of input(x) provided with its masking labels (m) - input: - x: feature input - m: averaged mask labels - output: - mean: mean of input features - std: stadard deviation of input features - """ - mean = torch.sum((m * x), dim=dim) - std = torch.sqrt((m * (x - mean.unsqueeze(dim)).pow(2)).sum(dim).clamp(eps)) - return mean, std - - -class TDNNModule(nn.Module): - """ - Time Delayed Neural Module (TDNN) - 1D - input: - inp_filters: input filter channels for conv layer - out_filters: output filter channels for conv layer - kernel_size: kernel weight size for conv layer - dilation: dilation for conv layer - stride: stride for conv layer - padding: padding for conv layer (default None: chooses padding value such that input and output feature shape matches) - output: - tdnn layer output - """ - - def __init__( - self, - inp_filters: int, - out_filters: int, - kernel_size: int = 1, - dilation: int = 1, - stride: int = 1, - padding: int = None, - ): - super().__init__() - if padding is None: - padding = get_same_padding(kernel_size, stride=stride, dilation=dilation) - - self.conv_layer = nn.Conv1d( - in_channels=inp_filters, - out_channels=out_filters, - kernel_size=kernel_size, - dilation=dilation, - padding=padding, - ) - - self.activation = nn.ReLU() - self.bn = nn.BatchNorm1d(out_filters) - - def forward(self, x, length=None): - x = self.conv_layer(x) - x = self.activation(x) - return self.bn(x) - - -class MaskedSEModule(nn.Module): - """ - Squeeze and Excite module implementation with conv1d layers - input: - inp_filters: input filter channel size - se_filters: intermediate squeeze and excite channel output and input size - out_filters: output filter channel size - kernel_size: kernel_size for both conv1d layers - dilation: dilation size for both conv1d layers - - output: - squeeze and excite layer output - """ - - def __init__(self, inp_filters: int, se_filters: int, out_filters: int, kernel_size: int = 1, dilation: int = 1): - super().__init__() - self.se_layer = nn.Sequential( - nn.Conv1d( - inp_filters, - se_filters, - kernel_size=kernel_size, - dilation=dilation, - ), - nn.ReLU(), - nn.BatchNorm1d(se_filters), - nn.Conv1d( - se_filters, - out_filters, - kernel_size=kernel_size, - dilation=dilation, - ), - nn.Sigmoid(), - ) - - def forward(self, input, length=None): - if length is None: - x = torch.mean(input, dim=2, keep_dim=True) - else: - max_len = input.size(2) - mask, num_values = lens_to_mask(length, max_len=max_len, device=input.device) - x = torch.sum((input * mask), dim=2, keepdim=True) / (num_values) - - out = self.se_layer(x) - return out * input - - -class TDNNSEModule(nn.Module): - """ - Modified building SE_TDNN group module block from ECAPA implementation for faster training and inference - Reference: ECAPA-TDNN Embeddings for Speaker Diarization (https://arxiv.org/pdf/2104.01466.pdf) - inputs: - inp_filters: input filter channel size - out_filters: output filter channel size - group_scale: scale value to group wider conv channels (deafult:8) - se_channels: squeeze and excite output channel size (deafult: 1024/8= 128) - kernel_size: kernel_size for group conv1d layers (default: 1) - dilation: dilation size for group conv1d layers (default: 1) - """ - - def __init__( - self, - inp_filters: int, - out_filters: int, - group_scale: int = 8, - se_channels: int = 128, - kernel_size: int = 1, - dilation: int = 1, - init_mode: str = 'xavier_uniform', - ): - super().__init__() - self.out_filters = out_filters - padding_val = get_same_padding(kernel_size=kernel_size, dilation=dilation, stride=1) - - group_conv = nn.Conv1d( - out_filters, - out_filters, - kernel_size=kernel_size, - dilation=dilation, - padding=padding_val, - groups=group_scale, - ) - self.group_tdnn_block = nn.Sequential( - TDNNModule(inp_filters, out_filters, kernel_size=1, dilation=1), - group_conv, - nn.ReLU(), - nn.BatchNorm1d(out_filters), - TDNNModule(out_filters, out_filters, kernel_size=1, dilation=1), - ) - - self.se_layer = MaskedSEModule(out_filters, se_channels, out_filters) - - self.apply(lambda x: init_weights(x, mode=init_mode)) - - def forward(self, input, length=None): - x = self.group_tdnn_block(input) - x = self.se_layer(x, length) - return x + input - - -class AttentivePoolLayer(nn.Module): - """ - Attention pooling layer for pooling speaker embeddings - Reference: ECAPA-TDNN Embeddings for Speaker Diarization (https://arxiv.org/pdf/2104.01466.pdf) - inputs: - inp_filters: input feature channel length from encoder - attention_channels: intermediate attention channel size - kernel_size: kernel_size for TDNN and attention conv1d layers (default: 1) - dilation: dilation size for TDNN and attention conv1d layers (default: 1) - """ - - def __init__( - self, - inp_filters: int, - attention_channels: int = 128, - kernel_size: int = 1, - dilation: int = 1, - eps: float = 1e-10, - ): - super().__init__() - - self.feat_in = 2 * inp_filters - - self.attention_layer = nn.Sequential( - TDNNModule(inp_filters * 3, attention_channels, kernel_size=kernel_size, dilation=dilation), - nn.Tanh(), - nn.Conv1d( - in_channels=attention_channels, - out_channels=inp_filters, - kernel_size=kernel_size, - dilation=dilation, - ), - ) - self.eps = eps - - def forward(self, x, length=None): - max_len = x.size(2) - - if length is None: - length = torch.ones(x.shape[0], device=x.device) - - mask, num_values = lens_to_mask(length, max_len=max_len, device=x.device) - - # encoder statistics - mean, std = get_statistics_with_mask(x, mask / num_values) - mean = mean.unsqueeze(2).repeat(1, 1, max_len) - std = std.unsqueeze(2).repeat(1, 1, max_len) - attn = torch.cat([x, mean, std], dim=1) - - # attention statistics - attn = self.attention_layer(attn) # attention pass - attn = attn.masked_fill(mask == 0, -inf) - alpha = F.softmax(attn, dim=2) # attention values, α - mu, sg = get_statistics_with_mask(x, alpha) # µ and ∑ - - # gather - return torch.cat((mu, sg), dim=1).unsqueeze(2) diff --git a/nemo/collections/asr/parts/submodules/tdt_beam_decoding.py b/nemo/collections/asr/parts/submodules/tdt_beam_decoding.py deleted file mode 100644 index 65255b85849df97ef4097d32f823674827f2050d..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/tdt_beam_decoding.py +++ /dev/null @@ -1,976 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Copyright 2017 Johns Hopkins University (Shinji Watanabe) -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import List, Optional, Tuple - -import numpy as np -import torch -from tqdm import tqdm - -from nemo.collections.asr.modules import rnnt_abstract -from nemo.collections.asr.parts.submodules.ngram_lm import NGramGPULanguageModel -from nemo.collections.asr.parts.submodules.rnnt_beam_decoding import pack_hypotheses -from nemo.collections.asr.parts.submodules.tdt_malsd_batched_computer import ModifiedALSDBatchedTDTComputer -from nemo.collections.asr.parts.utils.asr_confidence_utils import ConfidenceMethodMixin -from nemo.collections.asr.parts.utils.batched_beam_decoding_utils import BlankLMScoreMode, PruningMode -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis, NBestHypotheses, is_prefix -from nemo.collections.common.parts.optional_cuda_graphs import WithOptionalCudaGraphs -from nemo.core.classes import Typing, typecheck -from nemo.core.neural_types import AcousticEncodedRepresentation, HypothesisType, LengthsType, NeuralType -from nemo.utils import logging - -try: - import kenlm - - KENLM_AVAILABLE = True -except (ImportError, ModuleNotFoundError): - KENLM_AVAILABLE = False - - -class BeamTDTInfer(Typing): - """ - Beam search implementation for Token-andDuration Transducer (TDT) models. - - Sequence level beam decoding or batched-beam decoding, performed auto-repressively - depending on the search type chosen. - - Args: - decoder_model: rnnt_utils.AbstractRNNTDecoder implementation. - joint_model: rnnt_utils.AbstractRNNTJoint implementation. - durations: list of duration values from TDT model. - - beam_size: number of beams for beam search. Must be a positive integer >= 1. - If beam size is 1, defaults to stateful greedy search. - For accurate greedy results, please use GreedyRNNTInfer or GreedyBatchedRNNTInfer. - - search_type: str representing the type of beam search to perform. - Must be one of ['beam', 'maes']. - - Algorithm used: - - `default` - basic beam search strategy. Larger beams generally result in better decoding, - however the time required for the search also grows steadily. - - `maes` = modified adaptive expansion search. Please refer to the paper: - [Accelerating RNN Transducer Inference via Adaptive Expansion Search] - (https://ieeexplore.ieee.org/document/9250505) - - Modified Adaptive Synchronous Decoding (mAES) execution time is adaptive w.r.t the - number of expansions (for tokens) required per timestep. The number of expansions can usually - be constrained to 1 or 2, and in most cases 2 is sufficient. - - This beam search technique can possibly obtain superior WER while sacrificing some evaluation time. - - score_norm: bool, whether to normalize the scores of the log probabilities. - - return_best_hypothesis: bool, decides whether to return a single hypothesis (the best out of N), - or return all N hypothesis (sorted with best score first). The container class changes based - this flag - - When set to True (default), returns a single Hypothesis. - When set to False, returns a NBestHypotheses container, which contains a list of Hypothesis. - - # The following arguments are specific to the chosen `search_type` - - # mAES flags - maes_num_steps: Number of adaptive steps to take. From the paper, 2 steps is generally sufficient. int > 1. - - maes_prefix_alpha: Maximum prefix length in prefix search. Must be an integer, and is advised to keep this as 1 - in order to reduce expensive beam search cost later. int >= 0. - - maes_expansion_beta: Maximum number of prefix expansions allowed, in addition to the beam size. - Effectively, the number of hypothesis = beam_size + maes_expansion_beta. Must be an int >= 0, - and affects the speed of inference since large values will perform large beam search in the next step. - - maes_expansion_gamma: Float pruning threshold used in the prune-by-value step when computing the expansions. - The default (2.3) is selected from the paper. It performs a comparison - (max_log_prob - gamma <= log_prob[v]) where v is all vocabulary indices in the Vocab set and max_log_prob - is the "most" likely token to be predicted. Gamma therefore provides a margin of additional tokens which - can be potential candidates for expansion apart from the "most likely" candidate. - Lower values will reduce the number of expansions (by increasing pruning-by-value, thereby improving speed - but hurting accuracy). Higher values will increase the number of expansions (by reducing pruning-by-value, - thereby reducing speed but potentially improving accuracy). This is a hyper parameter to be experimentally - tuned on a validation set. - - softmax_temperature: Scales the logits of the joint prior to computing log_softmax. - - preserve_alignments: Bool flag which preserves the history of alignments generated during - beam decoding (sample). When set to true, the Hypothesis will contain - the non-null value for `alignments` in it. Here, `alignments` is a List of List of Tensor (of length V + 1) - - The length of the list corresponds to the Acoustic Length (T). - Each value in the list (Ti) is a torch.Tensor (U), representing 1 or more targets from a vocabulary. - U is the number of target tokens for the current timestep Ti. - - NOTE: `preserve_alignments` is an invalid argument for any `search_type` - other than basic beam search. - - ngram_lm_model: str - The path to the N-gram LM. - ngram_lm_alpha: float - Alpha weight of N-gram LM. - """ - - @property - def input_types(self): - """Returns definitions of module input ports.""" - return { - "encoder_output": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), - "encoded_lengths": NeuralType(tuple('B'), LengthsType()), - "partial_hypotheses": [NeuralType(elements_type=HypothesisType(), optional=True)], # must always be last - } - - @property - def output_types(self): - """Returns definitions of module output ports.""" - return {"predictions": [NeuralType(elements_type=HypothesisType())]} - - def __init__( - self, - decoder_model: rnnt_abstract.AbstractRNNTDecoder, - joint_model: rnnt_abstract.AbstractRNNTJoint, - durations: list, - beam_size: int, - search_type: str = 'default', - score_norm: bool = True, - return_best_hypothesis: bool = True, - maes_num_steps: int = 2, - maes_prefix_alpha: int = 1, - maes_expansion_gamma: float = 2.3, - maes_expansion_beta: int = 2, - softmax_temperature: float = 1.0, - preserve_alignments: bool = False, - ngram_lm_model: Optional[str] = None, - ngram_lm_alpha: float = 0.3, - max_symbols_per_step: Optional[int] = None, - blank_lm_score_mode: Optional[str] = "no_score", - pruning_mode: Optional[str] = "early", - allow_cuda_graphs: bool = False, - ): - self.joint = joint_model - self.decoder = decoder_model - self.durations = durations - - self.token_offset = 0 - self.search_type = search_type - self.blank = decoder_model.blank_idx - self.vocab_size = decoder_model.vocab_size - self.return_best_hypothesis = return_best_hypothesis - - self.beam_size = beam_size - self.score_norm = score_norm - self.max_candidates = beam_size - self.softmax_temperature = softmax_temperature - self.preserve_alignments = preserve_alignments - - if preserve_alignments: - raise ValueError("Alignment preservation has not been implemented.") - if beam_size < 1: - raise ValueError("Beam search size cannot be less than 1!") - - if self.preserve_alignments: - raise NotImplementedError("Preserving alignments is not implemented.") - - if search_type == "default": - if self.beam_size == 1: - logging.info( - """If beam size is 1, defaults to stateful greedy search. - For accurate greedy results, please use GreedyTDTInfer or GreedyBatchedTDTInfer.""" - ) - self.search_algorithm = self.default_beam_search - elif search_type == "tsd": - raise NotImplementedError("`tsd` (Time Synchronous Decoding) has not been implemented.") - elif search_type == "alsd": - raise NotImplementedError("`alsd` (Alignment Length Synchronous Decoding) has not been implemented.") - elif search_type == "nsc": - raise NotImplementedError("`nsc` (Constrained Beam Search) has not been implemented.") - elif search_type == "maes": - self.search_algorithm = self.modified_adaptive_expansion_search - else: - raise NotImplementedError( - f"The search type ({search_type}) supplied is not supported!\n" f"Please use one of : (default, maes)" - ) - - if max_symbols_per_step is not None: - logging.warning( - f"Not supported parameter `max_symbols_per_step` for decoding strategy {self.search_algorithm }" - ) - - if allow_cuda_graphs: - logging.warning( - f"""Cuda Graphs are not supported for the decoding strategy {self.search_algorithm}. - Decoding will proceed without Cuda Graphs.""" - ) - - strategies = ["default", "maes"] - strategies_batch = ["malsd_batch"] - if (pruning_mode, blank_lm_score_mode) != ("early", "no_score"): - logging.warning( - f"""Decoding strategies {strategies} support early pruning and the 'no_score' blank scoring mode. - Please choose a strategy from {strategies_batch} for {pruning_mode} pruning - and {blank_lm_score_mode} blank scoring mode." - """ - ) - - if self.search_type == 'maes': - self.maes_num_steps = int(maes_num_steps) - self.maes_prefix_alpha = int(maes_prefix_alpha) - self.maes_expansion_beta = int(maes_expansion_beta) - self.maes_expansion_gamma = float(maes_expansion_gamma) - - self.max_candidates += maes_expansion_beta - - if self.maes_prefix_alpha < 0: - raise ValueError("`maes_prefix_alpha` must be a positive integer.") - - if self.vocab_size < beam_size + maes_expansion_beta: - raise ValueError( - f"beam_size ({beam_size}) + expansion_beta ({maes_expansion_beta}) " - f"should be smaller or equal to vocabulary size ({self.vocab_size})." - ) - - if self.maes_num_steps < 1: - raise ValueError("`maes_num_steps` must be greater than 0.") - - try: - self.zero_duration_idx = self.durations.index(0) - except ValueError: - self.zero_duration_idx = None - self.min_non_zero_duration_idx = int( - np.argmin(np.ma.masked_where(np.array(self.durations) == 0, self.durations)) - ) - - if ngram_lm_model: - if search_type != "maes": - raise ValueError("For decoding with language model `maes` decoding strategy must be chosen.") - self.ngram_lm = ngram_lm_model - self.ngram_lm_alpha = ngram_lm_alpha - else: - self.ngram_lm = None - - @typecheck() - def __call__( - self, - encoder_output: torch.Tensor, - encoded_lengths: torch.Tensor, - partial_hypotheses: tuple[list[Hypothesis | NBestHypotheses],] = None, - ) -> tuple[list[Hypothesis | NBestHypotheses],]: - """Perform general beam search. - - Args: - encoder_output: encoder outputs (batch, features, timesteps). - encoded_lengths: lengths of the encoder outputs. - - Returns: - Either a list containing a single Hypothesis (when `return_best_hypothesis=True`, - otherwise a list containing a single NBestHypotheses, which itself contains a list of - Hypothesis. This list is sorted such that the best hypothesis is the first element. - """ - # Preserve decoder and joint training state - decoder_training_state = self.decoder.training - joint_training_state = self.joint.training - - with torch.inference_mode(): - # Apply optional preprocessing - encoder_output = encoder_output.transpose(1, 2) # (B, T, D) - - self.decoder.eval() - self.joint.eval() - - hypotheses = [] - with tqdm( - range(encoder_output.size(0)), - desc='Beam search progress:', - total=encoder_output.size(0), - unit='sample', - ) as idx_gen: - - _p = next(self.joint.parameters()) - dtype = _p.dtype - - # Decode every sample in the batch independently. - for batch_idx in idx_gen: - inseq = encoder_output[batch_idx : batch_idx + 1, : encoded_lengths[batch_idx], :] # [1, T, D] - logitlen = encoded_lengths[batch_idx] - - if inseq.dtype != dtype: - inseq = inseq.to(dtype=dtype) - - # Extract partial hypothesis if exists - partial_hypothesis = partial_hypotheses[batch_idx] if partial_hypotheses is not None else None - - # Execute the specific search strategy - nbest_hyps = self.search_algorithm( - inseq, logitlen, partial_hypotheses=partial_hypothesis - ) # sorted list of hypothesis - - # Prepare the list of hypotheses - nbest_hyps = pack_hypotheses(nbest_hyps) - - # Pack the result - if self.return_best_hypothesis: - best_hypothesis: Hypothesis = nbest_hyps[0] - else: - best_hypothesis: NBestHypotheses = NBestHypotheses(nbest_hyps) - hypotheses.append(best_hypothesis) - - self.decoder.train(decoder_training_state) - self.joint.train(joint_training_state) - - return (hypotheses,) - - def default_beam_search( - self, - encoder_outputs: torch.Tensor, - encoded_lengths: torch.Tensor, - partial_hypotheses: Optional[Hypothesis] = None, - ) -> List[Hypothesis]: - """Default Beam search implementation for TDT models. - - Args: - encoder_outputs: encoder outputs (batch, features, timesteps). - encoded_lengths: lengths of the encoder outputs. - partial_hypotheses: partial hypoteses. - - Returns: - nbest_hyps: N-best decoding results - """ - if partial_hypotheses is not None: - raise NotImplementedError("Support for `partial_hypotheses` is not implemented.") - - beam = min(self.beam_size, self.vocab_size) - beam_k = min(beam, (self.vocab_size - 1)) - durations_beam_k = min(beam, len(self.durations)) - - # Initialize zero vector states. - decoder_state = self.decoder.initialize_state(encoder_outputs) - # Cache decoder results to avoid duplicate computations. - cache = {} - - # Initialize hypothesis array with blank hypothesis. - start_hyp = Hypothesis( - score=0.0, y_sequence=[self.blank], dec_state=decoder_state, timestamp=[-1], length=0, last_frame=0 - ) - kept_hyps = [start_hyp] - - for time_idx in range(int(encoded_lengths)): - # Retrieve hypotheses for current and future frames - hyps = [hyp for hyp in kept_hyps if hyp.last_frame == time_idx] # hypotheses for current frame - kept_hyps = [hyp for hyp in kept_hyps if hyp.last_frame > time_idx] # hypothesis for future frames - - # Loop over hypotheses of current frame - while len(hyps) > 0: - max_hyp = max(hyps, key=lambda x: x.score) - hyps.remove(max_hyp) - - # Update decoder state and get probability distribution over vocabulary and durations. - encoder_output = encoder_outputs[:, time_idx : time_idx + 1, :] # [1, 1, D] - decoder_output, decoder_state, _ = self.decoder.score_hypothesis(max_hyp, cache) # [1, 1, D] - logits = ( - self.joint.joint(encoder_output, decoder_output) / self.softmax_temperature - ) # [1, 1, 1, V + NUM_DURATIONS + 1] - logp = torch.log_softmax(logits[0, 0, 0, : -len(self.durations)], dim=-1) # [V + 1] - durations_logp = torch.log_softmax(logits[0, 0, 0, -len(self.durations) :], dim=-1) # [NUM_DURATIONS] - - # Proccess non-blank tokens - # Retrieve the top `beam_k` most probable tokens and the top `duration_beam_k` most probable durations. - # Then, select the top `beam_k` pairs of (token, duration) based on the highest combined probabilities. - # Note that indices are obtained in the flattened array. - logp_topks, logp_topk_idxs = logp[:-1].topk(beam_k, dim=-1) # topk of tokens without blank token - durations_logp_topks, durations_logp_topk_idxs = durations_logp.topk(durations_beam_k, dim=-1) - total_logp_topks, total_logp_topk_idxs = ( - torch.cartesian_prod(durations_logp_topks, logp_topks).sum(dim=-1).topk(beam_k, dim=-1) - ) - - # Loop over pairs of (token, duration) with highest combined log prob - for total_logp_topk, total_logp_topk_idx in zip(total_logp_topks, total_logp_topk_idxs): - # Restore indices from flattened array indices - token_idx = int(logp_topk_idxs[total_logp_topk_idx % beam_k]) - duration_idx = int(durations_logp_topk_idxs[total_logp_topk_idx // beam_k]) - - duration = self.durations[duration_idx] - # Construct hypothesis for non-blank token - new_hyp = Hypothesis( - score=float(max_hyp.score + total_logp_topk), # update score - y_sequence=max_hyp.y_sequence + [token_idx], # update hypothesis sequence - dec_state=decoder_state, # update decoder state - timestamp=max_hyp.timestamp + [time_idx + duration], # update timesteps - length=encoded_lengths, - last_frame=max_hyp.last_frame + duration, - ) # update frame idx where last token appeared - - # Update current frame hypotheses if duration is zero and future frame hypotheses otherwise - if duration == 0: - hyps.append(new_hyp) - else: - kept_hyps.append(new_hyp) - - # Update future frames with blank tokens - # Note: blank token can have only non-zero duration - for duration_idx in durations_logp_topk_idxs: - duration_idx = int(duration_idx) - # If zero is the only duration in topk, switch to closest non-zero duration to continue - if duration_idx == self.zero_duration_idx: - if durations_logp_topk_idxs.shape[0] == 1: - duration_idx = self.min_non_zero_duration_idx - else: - continue - - duration = self.durations[duration_idx] - new_hyp = Hypothesis( - score=float(max_hyp.score + logp[self.blank] + durations_logp[duration_idx]), # update score - y_sequence=max_hyp.y_sequence[:], # no need to update sequence - dec_state=max_hyp.dec_state, # no need to update decoder state - timestamp=max_hyp.timestamp[:], # no need to update timesteps - length=encoded_lengths, - last_frame=max_hyp.last_frame + duration, - ) # update frame idx where last token appeared - kept_hyps.append(new_hyp) - - # Merge duplicate hypotheses. - # If two consecutive blank tokens are predicted and their duration values sum up to the same number, - # it will produce two hypotheses with the same token sequence but different scores. - kept_hyps = self.merge_duplicate_hypotheses(kept_hyps) - - if len(hyps) > 0: - # Keep those hypothesis that have scores greater than next search generation - hyps_max = float(max(hyps, key=lambda x: x.score).score) - kept_most_prob = sorted( - [hyp for hyp in kept_hyps if hyp.score > hyps_max], - key=lambda x: x.score, - ) - # If enough hypotheses have scores greater than next search generation, - # stop beam search. - if len(kept_most_prob) >= beam: - kept_hyps = kept_most_prob - break - else: - # If there are no hypotheses in a current frame, - # keep only `beam` best hypotheses for the next search generation. - kept_hyps = sorted(kept_hyps, key=lambda x: x.score, reverse=True)[:beam] - return self.sort_nbest(kept_hyps) - - def modified_adaptive_expansion_search( - self, - encoder_outputs: torch.Tensor, - encoded_lengths: torch.Tensor, - partial_hypotheses: Optional[Hypothesis] = None, - ) -> List[Hypothesis]: - """ - Modified Adaptive Exoansion Search algorithm for TDT models. - Based on/modified from https://ieeexplore.ieee.org/document/9250505. - Supports N-gram language model shallow fusion. - - Args: - encoder_outputs: encoder outputs (batch, features, timesteps). - encoded_lengths: lengths of the encoder outputs. - partial_hypotheses: partial hypotheses. - - Returns: - nbest_hyps: N-best decoding results - """ - if partial_hypotheses is not None: - raise NotImplementedError("Support for `partial_hypotheses` is not implemented.") - - beam = min(self.beam_size, self.vocab_size) - beam_state = self.decoder.initialize_state( - torch.zeros(1, device=encoder_outputs.device, dtype=encoder_outputs.dtype) - ) # [L, B, H], [L, B, H] for LSTMS - - # Initialize first hypothesis for the beam (blank). - start_hyp = Hypothesis( - y_sequence=[self.blank], - score=0.0, - dec_state=self.decoder.batch_select_state(beam_state, 0), - timestamp=[-1], - length=0, - last_frame=0, - ) - init_tokens = [start_hyp] - - # Cache decoder results to avoid duplicate computations. - cache = {} - - # Decode a batch of beam states and scores - beam_decoder_output, beam_state = self.decoder.batch_score_hypothesis(init_tokens, cache) - state = beam_state[0] - - # Initialize first hypothesis for the beam (blank) for kept hypotheses - start_hyp_kept = Hypothesis( - y_sequence=[self.blank], - score=0.0, - dec_state=state, - dec_out=[beam_decoder_output[0]], - timestamp=[-1], - length=0, - last_frame=0, - ) - - kept_hyps = [start_hyp_kept] - - # Setup ngram LM: - if self.ngram_lm: - init_lm_state = kenlm.State() - self.ngram_lm.BeginSentenceWrite(init_lm_state) - start_hyp_kept.ngram_lm_state = init_lm_state - - for time_idx in range(encoded_lengths): - # Select current iteration hypotheses - hyps = [x for x in kept_hyps if x.last_frame == time_idx] - kept_hyps = [x for x in kept_hyps if x.last_frame > time_idx] - - if len(hyps) == 0: - continue - - beam_encoder_output = encoder_outputs[:, time_idx : time_idx + 1] # [1, 1, D] - # Perform prefix search to update hypothesis scores. - if self.zero_duration_idx is not None: - hyps = self.prefix_search( - sorted(hyps, key=lambda x: len(x.y_sequence), reverse=True), - beam_encoder_output, - prefix_alpha=self.maes_prefix_alpha, - ) - - list_b = [] # List that contains the blank token emissions - list_nb = [] # List that contains the non-zero duration non-blank token emissions - # Repeat for number of mAES steps - for n in range(self.maes_num_steps): - # Pack the decoder logits for all current hypotheses - beam_decoder_output = torch.stack([h.dec_out[-1] for h in hyps]) # [H, 1, D] - - # Extract the log probabilities - beam_logits = self.joint.joint(beam_encoder_output, beam_decoder_output) / self.softmax_temperature - beam_logp = torch.log_softmax(beam_logits[:, 0, 0, : -len(self.durations)], dim=-1) - beam_duration_logp = torch.log_softmax(beam_logits[:, 0, 0, -len(self.durations) :], dim=-1) - - # Retrieve the top `max_candidades` most probable tokens. - # Then, select the top `max_candidates` pairs of (token, duration) - # based on the highest combined probabilities. - # Note that indices are obtained in flattened array. - beam_logp_topks, beam_idx_topks = beam_logp.topk(self.max_candidates, dim=-1) - beam_total_logp = (beam_duration_logp[:, :, None] + beam_logp_topks[:, None, :]).view( - len(hyps), -1 - ) # [B, MAX_CANDIDATES*DURATION_BEAM] - beam_total_logp_topks, beam_total_logp_topk_idxs = beam_total_logp.topk( - self.max_candidates, dim=-1 - ) # [B, MAX_CANDIDATES] - - # Prune hypothesis to obtain k expansions - beam_best_expansion_scores = beam_total_logp_topks.max(dim=-1, keepdim=True).values - beam_masks = beam_total_logp_topks >= beam_best_expansion_scores - self.maes_expansion_gamma - beam_kexpansions_idxs = [ - sum_logp_topk_idxs[mask] for sum_logp_topk_idxs, mask in zip(beam_total_logp_topk_idxs, beam_masks) - ] - - list_exp = [] # List that contains the hypothesis expansion - list_nb_exp = [] # List that contains the hypothesis expansion - for hyp_idx, hyp in enumerate(hyps): # For all hypothesis - for idx in beam_kexpansions_idxs[hyp_idx]: # For all expansions within this hypothesis - # Restore indices in logp and durations_logp arrays from flattened indices. - k = int(beam_idx_topks[hyp_idx][idx % self.max_candidates]) - duration = self.durations[int(idx // self.max_candidates)] - total_logp = float(beam_total_logp[hyp_idx][idx]) - - # Forcing blank token to have non-zero duration - if k == self.blank and duration == 0: - duration = self.durations[self.min_non_zero_duration_idx] - - new_hyp = Hypothesis( - score=hyp.score + total_logp, - y_sequence=hyp.y_sequence[:], - dec_out=hyp.dec_out[:], - dec_state=hyp.dec_state, - timestamp=hyp.timestamp[:], - length=time_idx, - last_frame=hyp.last_frame + duration, - ) - - if self.ngram_lm: - new_hyp.ngram_lm_state = hyp.ngram_lm_state - - # If the expansion was for blank - if k == self.blank: - list_b.append(new_hyp) - else: - new_hyp.y_sequence.append(k) - new_hyp.timestamp.append(time_idx + duration) - - if self.ngram_lm: - lm_score, new_hyp.ngram_lm_state = self.compute_ngram_score(hyp.ngram_lm_state, int(k)) - new_hyp.score += self.ngram_lm_alpha * lm_score - - # If token duration is 0 adding to expansions list - if duration == 0: - list_exp.append(new_hyp) - else: - list_nb_exp.append(new_hyp) - - # Update states for hypothesis that do not end with blank - hyps_to_update = list_nb_exp + list_exp - if len(hyps_to_update) > 0: - # Decode a batch of beam states and scores - beam_decoder_output, beam_state = self.decoder.batch_score_hypothesis( - hyps_to_update, - cache, - ) - for hyp_idx, hyp in enumerate(hyps_to_update): - # Preserve the decoder logits for the current beam - hyp.dec_out.append(beam_decoder_output[hyp_idx]) - hyp.dec_state = beam_state[hyp_idx] - - # If there were no token expansions in any of the hypotheses, - # Early exit - list_nb += list_nb_exp - if not list_exp: - kept_hyps = kept_hyps + list_b + list_nb - kept_hyps = self.merge_duplicate_hypotheses(kept_hyps) - kept_hyps = sorted(kept_hyps, key=lambda x: x.score, reverse=True)[:beam] - - break - else: - # If this isn't the last mAES step - if n < (self.maes_num_steps - 1): - # Copy the expanded hypothesis for the next iteration - hyps = self.merge_duplicate_hypotheses(list_exp) - else: - # If this is the last mAES step add probabilities of the blank token to the end. - # Extract the log probabilities - beam_decoder_output = torch.stack([h.dec_out[-1] for h in list_exp]) # [H, 1, D] - beam_logits = ( - self.joint.joint(beam_encoder_output, beam_decoder_output) / self.softmax_temperature - ) - beam_logp = torch.log_softmax(beam_logits[:, 0, 0, : -len(self.durations)], dim=-1) - - # Get most probable durations - beam_duration_logp = torch.log_softmax(beam_logits[:, 0, 0, -len(self.durations) :], dim=-1) - _, beam_max_duration_idx = torch.max(beam_duration_logp, dim=-1) - - # For all expansions, add the score for the blank label - for hyp_idx, hyp in enumerate(list_exp): - # If zero duration was obtained, change to the closest non-zero duration - duration_idx = int(beam_max_duration_idx[hyp_idx]) - if duration_idx == self.zero_duration_idx: - duration_idx = self.min_non_zero_duration_idx - - total_logp = float( - beam_logp[hyp_idx, self.blank] + beam_duration_logp[hyp_idx, duration_idx] - ) - hyp.score += total_logp - hyp.last_frame += self.durations[duration_idx] - - # Finally, update the kept hypothesis of sorted top Beam candidates - kept_hyps = kept_hyps + list_b + list_exp + list_nb - kept_hyps = self.merge_duplicate_hypotheses(kept_hyps) - kept_hyps = sorted(kept_hyps, key=lambda x: x.score, reverse=True)[:beam] - - # Sort the hypothesis with best scores - return self.sort_nbest(kept_hyps) - - def merge_duplicate_hypotheses(self, hypotheses): - """ - Merges hypotheses with identical token sequences and lengths. - The combined hypothesis's probability is the sum of the probabilities of all duplicates. - Duplicate hypotheses occur when two consecutive blank tokens are predicted - and their duration values sum up to the same number. - - Args: - hypotheses: list of hypotheses. - - Returns: - hypotheses: list if hypotheses without duplicates. - """ - sorted_hyps = sorted(hypotheses, key=lambda x: x.score, reverse=True) - kept_hyps = {} - for hyp in sorted_hyps: - hyp_key = (tuple(hyp.y_sequence), int(hyp.last_frame)) - if hyp_key in kept_hyps: - kept_hyp = kept_hyps[hyp_key] - kept_hyp.score = float(torch.logaddexp(torch.tensor(kept_hyp.score), torch.tensor(hyp.score))) - else: - kept_hyps[hyp_key] = hyp - return list(kept_hyps.values()) - - def set_decoding_type(self, decoding_type: str): - """ - Sets decoding type. Please check train_kenlm.py in scripts/asr_language_modeling/ to find out why we need - Args: - decoding_type: decoding type - """ - # TOKEN_OFFSET for BPE-based models - if decoding_type == 'subword': - from nemo.collections.asr.parts.submodules.ctc_beam_decoding import DEFAULT_TOKEN_OFFSET - - self.token_offset = DEFAULT_TOKEN_OFFSET - - def prefix_search( - self, hypotheses: List[Hypothesis], encoder_output: torch.Tensor, prefix_alpha: int - ) -> List[Hypothesis]: - """ - Performs a prefix search and updates the scores of the hypotheses in place. - Based on https://arxiv.org/pdf/1211.3711.pdf. - - Args: - hypotheses: a list of hypotheses sorted by the length from the longest to the shortest. - encoder_output: encoder output. - prefix_alpha: maximum allowable length difference between hypothesis and a prefix. - - Returns: - hypotheses: list of hypotheses with updated scores. - """ - # Iterate over hypotheses. - for curr_idx, curr_hyp in enumerate(hypotheses[:-1]): - # For each hypothesis, iterate over the subsequent hypotheses. - # If a hypothesis is a prefix of the current one, update current score. - for pref_hyp in hypotheses[(curr_idx + 1) :]: - curr_hyp_length = len(curr_hyp.y_sequence) - pref_hyp_length = len(pref_hyp.y_sequence) - - if ( - is_prefix(curr_hyp.y_sequence, pref_hyp.y_sequence) - and (curr_hyp_length - pref_hyp_length) <= prefix_alpha - ): - # Compute the score of the first token - # that follows the prefix hypothesis tokens in current hypothesis. - # Use the decoder output, which is stored in the prefix hypothesis. - logits = self.joint.joint(encoder_output, pref_hyp.dec_out[-1]) / self.softmax_temperature - logp = torch.log_softmax(logits[0, 0, 0, : -len(self.durations)], dim=-1) - duration_logp = torch.log_softmax(logits[0, 0, 0, -len(self.durations) :], dim=-1) - curr_score = pref_hyp.score + float( - logp[curr_hyp.y_sequence[pref_hyp_length]] + duration_logp[self.zero_duration_idx] - ) - - if self.ngram_lm: - lm_score, next_state = self.compute_ngram_score( - pref_hyp.ngram_lm_state, int(curr_hyp.y_sequence[pref_hyp_length]) - ) - curr_score += self.ngram_lm_alpha * lm_score - - for k in range(pref_hyp_length, (curr_hyp_length - 1)): - # Compute the score of the next token. - # Approximate decoder output with the one that is stored in current hypothesis. - logits = self.joint.joint(encoder_output, curr_hyp.dec_out[k]) / self.softmax_temperature - logp = torch.log_softmax(logits[0, 0, 0, : -len(self.durations)], dim=-1) - duration_logp = torch.log_softmax(logits[0, 0, 0, -len(self.durations) :], dim=-1) - curr_score += float(logp[curr_hyp.y_sequence[k + 1]] + duration_logp[self.zero_duration_idx]) - - if self.ngram_lm: - lm_score, next_state = self.compute_ngram_score( - next_state, int(curr_hyp.y_sequence[k + 1]) - ) - curr_score += self.ngram_lm_alpha * lm_score - - # Update current hypothesis score - curr_hyp.score = np.logaddexp(curr_hyp.score, curr_score) - return hypotheses - - def compute_ngram_score(self, current_lm_state: "kenlm.State", label: int) -> Tuple[float, "kenlm.State"]: - """ - Computes the score for KenLM Ngram language model. - - Args: - current_lm_state: current state of the KenLM language model. - label: next label. - - Returns: - lm_score: score for `label`. - """ - if self.token_offset: - label = chr(label + self.token_offset) - else: - label = str(label) - - next_state = kenlm.State() - lm_score = self.ngram_lm.BaseScore(current_lm_state, label, next_state) - lm_score *= 1.0 / np.log10(np.e) - - return lm_score, next_state - - def sort_nbest(self, hyps: List[Hypothesis]) -> List[Hypothesis]: - """Sort hypotheses by score or score given sequence length. - - Args: - hyps: list of hypotheses - - Return: - hyps: sorted list of hypotheses - """ - if self.score_norm: - return sorted(hyps, key=lambda x: x.score / len(x.y_sequence), reverse=True) - else: - return sorted(hyps, key=lambda x: x.score, reverse=True) - - -class BeamBatchedTDTInfer(Typing, ConfidenceMethodMixin, WithOptionalCudaGraphs): - @property - def input_types(self): - """Returns definitions of module input ports.""" - return { - "encoder_output": NeuralType(('B', 'D', 'T'), AcousticEncodedRepresentation()), - "encoded_lengths": NeuralType(tuple('B'), LengthsType()), - "partial_hypotheses": [NeuralType(elements_type=HypothesisType(), optional=True)], # must always be last - } - - def __init__( - self, - decoder_model: rnnt_abstract.AbstractRNNTDecoder, - joint_model: rnnt_abstract.AbstractRNNTJoint, - durations: list, - blank_index: int, - beam_size: int, - search_type: str = 'malsd_batch', - score_norm: bool = True, - max_symbols_per_step: Optional[int] = None, - preserve_alignments: bool = False, - fusion_models: Optional[List[NGramGPULanguageModel]] = None, - fusion_models_alpha: Optional[List[float]] = None, - blank_lm_score_mode: Optional[str | BlankLMScoreMode] = BlankLMScoreMode.NO_SCORE, - pruning_mode: Optional[str | PruningMode] = PruningMode.EARLY, - allow_cuda_graphs: Optional[bool] = True, - return_best_hypothesis: Optional[str] = True, - ): - """ - Init method. - Args: - decoder_model: Prediction network from RNN-T - joint_model: Joint module from RNN-T - durations: Token durations tensor for TDT - blank_index: index of blank symbol - beam_size: beam size - max_symbols_per_step: max symbols to emit on each step (to avoid infinite looping) - preserve_alignments: if alignments are needed - fusion_models: list of fusion models to use for decoding - fusion_models_alpha: list of alpha values for fusion models - blank_lm_score_mode: mode for scoring blank symbol with LM - pruning_mode: mode for pruning hypotheses with LM - allow_cuda_graphs: whether to allow CUDA graphs - score_norm: whether to normalize scores before best hypothesis extraction - """ - super().__init__() - self.decoder = decoder_model - self.joint = joint_model - - self.durations = durations - self._blank_index = blank_index - self._SOS = blank_index # Start of single index - self.beam_size = beam_size - self.return_best_hypothesis = return_best_hypothesis - self.score_norm = score_norm - - if max_symbols_per_step is not None and max_symbols_per_step <= 0: - raise ValueError(f"Expected max_symbols_per_step > 0 (or None), got {max_symbols_per_step}") - self.max_symbols = max_symbols_per_step - self.preserve_alignments = preserve_alignments - - if search_type == "malsd_batch": - # Depending on availability of `blank_as_pad` support - # switch between more efficient batch decoding technique - self._decoding_computer = ModifiedALSDBatchedTDTComputer( - decoder=self.decoder, - joint=self.joint, - durations=durations, - beam_size=self.beam_size, - blank_index=self._blank_index, - max_symbols_per_step=self.max_symbols, - preserve_alignments=preserve_alignments, - fusion_models=fusion_models, - fusion_models_alpha=fusion_models_alpha, - blank_lm_score_mode=blank_lm_score_mode, - pruning_mode=pruning_mode, - allow_cuda_graphs=allow_cuda_graphs, - ) - else: - raise Exception(f"Decoding strategy {search_type} nor implemented.") - - def disable_cuda_graphs(self) -> bool: - """Disable CUDA graphs (e.g., for decoding in training)""" - if isinstance(self._decoding_computer, WithOptionalCudaGraphs): - return self._decoding_computer.disable_cuda_graphs() - return False - - def maybe_enable_cuda_graphs(self) -> bool: - """Enable CUDA graphs (if allowed)""" - if isinstance(self._decoding_computer, WithOptionalCudaGraphs): - return self._decoding_computer.maybe_enable_cuda_graphs() - return False - - @property - def output_types(self): - """Returns definitions of module output ports.""" - return {"predictions": [NeuralType(elements_type=HypothesisType())]} - - def __call__(self, *args, **kwargs): - return self.forward(*args, **kwargs) - - @typecheck() - def forward( - self, - encoder_output: torch.Tensor, - encoded_lengths: torch.Tensor, - partial_hypotheses: Optional[list[Hypothesis]] = None, - ) -> Tuple[list[Hypothesis] | List[NBestHypotheses]]: - """Returns a list of hypotheses given an input batch of the encoder hidden embedding. - Output token is generated auto-regressively. - - Args: - encoder_output: A tensor of size (batch, features, timesteps). - encoded_lengths: list of int representing the length of each sequence - output sequence. - - Returns: - Tuple of a list of hypotheses for each batch. Each hypothesis contains - the decoded sequence, timestamps and associated scores. - If ``return_best_hypothesis`` is True, returns the best hypothesis for each batch; - otherwise, returns the N-best hypotheses for each batch. - """ - if partial_hypotheses is not None: - raise NotImplementedError("Partial hypotheses feature is not yet supported in batched beam search.") - # Preserve decoder and joint training state - decoder_training_state = self.decoder.training - joint_training_state = self.joint.training - - with torch.inference_mode(): - # Apply optional preprocessing - encoder_output = encoder_output.transpose(1, 2) # (B, T, D) - logitlen = encoded_lengths - - self.decoder.eval() - self.joint.eval() - - inseq = encoder_output # [B, T, D] - batched_beam_hyps = self._decoding_computer(x=inseq, out_len=logitlen) - - # Ensures the correct number of hypotheses (batch_size) for CUDA Graphs compatibility - batch_size = encoder_output.shape[0] - if self.return_best_hypothesis: - hyps = batched_beam_hyps.to_hyps_list(score_norm=self.score_norm)[:batch_size] - else: - hyps = batched_beam_hyps.to_nbest_hyps_list(score_norm=self.score_norm)[:batch_size] - - self.decoder.train(decoder_training_state) - self.joint.train(joint_training_state) - - return (hyps,) diff --git a/nemo/collections/asr/parts/submodules/tdt_malsd_batched_computer.py b/nemo/collections/asr/parts/submodules/tdt_malsd_batched_computer.py deleted file mode 100644 index 45ecfed299a5a08c3b95e93966b8bfb7794cc40b..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/tdt_malsd_batched_computer.py +++ /dev/null @@ -1,1307 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -from dataclasses import dataclass, field -from typing import Any, List, Optional, Union - -import numpy as np -import torch -import torch.nn.functional as F - -from nemo.collections.asr.parts.submodules.ngram_lm import NGramGPULanguageModel -from nemo.collections.asr.parts.utils.asr_confidence_utils import ConfidenceMethodMixin -from nemo.collections.asr.parts.utils.batched_beam_decoding_utils import ( - INACTIVE_SCORE, - NON_EXISTENT_LABEL_VALUE, - BatchedBeamHyps, - BlankLMScoreMode, - PruningMode, -) -from nemo.collections.common.parts.optional_cuda_graphs import WithOptionalCudaGraphs -from nemo.core.utils.cuda_python_utils import ( - NeMoCUDAPythonException, - check_cuda_python_cuda_graphs_conditional_nodes_supported, - cu_call, - run_nvrtc, - with_conditional_node, -) -from nemo.core.utils.optional_libs import CUDA_PYTHON_AVAILABLE, cuda_python_required -from nemo.utils import logging -from nemo.utils.enum import PrettyStrEnum - -if CUDA_PYTHON_AVAILABLE: - from cuda.bindings import runtime as cudart - - -class MALSDState: - """ - State for batched ALSD algorithm for TDT models. Used only with CUDA graphs. - In initialization phase it is possible to assign values (tensors) to the state. - For algorithm code the storage should be reused (prefer copy data instead of assigning tensors). - """ - - durations: torch.Tensor # durations from the model - max_time: int # maximum length of internal storage for time dimension - batch_size: int # (maximum) length of internal storage for batch dimension - device: torch.device # device to store preallocated tensors - beam_size: int # (maximum) length of internal storage for beam dimension - blank_index: int # the index of the blank token - - ONE_TENSOR: torch.Tensor # constant tensor storing value 1 - NON_EXISTENT_LABEL: torch.Tensor # tensor for non existent label constant - BLANK_TENSOR: torch.Tensor # tensor for non blank constant - INACTIVE_SCORE: torch.Tensor # tensor for inactive score constant - - encoder_output_projected: torch.Tensor # projected output from the encoder for decoding algorithm - encoder_output_length: torch.Tensor # length of the (projected) output from the encoder - - next_labels: torch.Tensor # storage for next labels - next_scores: torch.Tensor # storage for next scores - next_idx: torch.Tensor # storage for next scores - - batch_indices: torch.Tensor # indices of elements in batch (constant, range [0, batch_size-1]) - beam_indices: torch.Tensor # indices of elements in batch (constant, range [0, beam_size-1]) - - time_indices: torch.Tensor # current time indices for each element in batch - safe_time_indices: torch.Tensor # current time indices, but guaranteed to be < encoder_output_length - last_timestamps: torch.Tensor # indices of the last timesteps for each element (encoder_output_length - 1) - last_labels_wb: torch.Tensor # last labels with blank - hyp_scores: torch.Tensor # scores for hypotheses - - active_mask: torch.Tensor # mask for active hypotheses (the decoding is finished for the utterance if it is False) - blank_mask: torch.Tensor # if the element is blank - active_mask_any: torch.Tensor # 0-dim bool tensor, condition for outer loop ('any element is still active') - - last_decoder_state: Any # last state from the decoder, needed for the output - decoder_state: Any # current decoder state - decoder_output: torch.Tensor # output from the decoder (projected) - prev_decoder_state: Any # current decoder state - prev_decoder_output: torch.Tensor # output from the decoder (projected) - init_decoder_state: Any # current decoder state - init_decoder_output: torch.Tensor # output from the decoder (projected) - - batched_hyps: BatchedBeamHyps # batched hypotheses - decoding result - - # fusion models related fields - fusion_models: Optional[List[NGramGPULanguageModel]] = None - fusion_models_alpha: Optional[List[float]] = None - fusion_states_list: Optional[List[torch.Tensor]] = None - fusion_states_candidates_list: Optional[List[torch.Tensor]] = None - fusion_scores_list: Optional[List[torch.Tensor]] = None - fusion_states_prev_list: Optional[List[torch.Tensor]] = None - init_fusion_states_list: Optional[List[torch.Tensor]] = None - init_fusion_states_candidates_list: Optional[List[torch.Tensor]] = None - init_fusion_scores_list: Optional[List[torch.Tensor]] = None - - def __init__( - self, - durations, - batch_size: int, - beam_size: int, - max_time: int, - encoder_dim: int, - max_symbols: int, - device: torch.device, - float_dtype: torch.dtype, - blank_index: int, - ): - """ - Args: - durations: durations from the TDT model - batch_size: batch size for encoder output storage - beam_size: beam size for decoder output storage - max_time: maximum time for encoder output storage - encoder_dim: last dimension for encoder output storage (projected encoder output) - max_symbols: max symbols per step (to avoid infinite looping and pre-allocate storage) - device: device to store tensors - float_dtype: default float dtype for tensors (should match projected encoder output) - blank_index: index of the blank symbol - """ - - self.durations = durations - self.device = device - self.float_dtype = float_dtype - self.batch_size = batch_size - self.beam_size = beam_size - self.max_time = max_time - self.blank_index = blank_index - - self.ONE_TENSOR = torch.tensor(1, device=self.device, dtype=torch.long) - self.NON_EXISTENT_LABEL = torch.tensor(NON_EXISTENT_LABEL_VALUE, device=self.device, dtype=torch.long) - self.BLANK_TENSOR = torch.tensor(self.blank_index, device=self.device, dtype=torch.long) - self.INACTIVE_SCORE = torch.tensor(INACTIVE_SCORE, device=self.device, dtype=float_dtype) - - self.encoder_output_projected = torch.zeros( - (self.batch_size, self.max_time, encoder_dim), - dtype=float_dtype, - device=self.device, - ) - self.encoder_output_length = torch.zeros( - [self.batch_size, self.beam_size], dtype=torch.long, device=self.device - ) - - self.next_idx = torch.zeros([self.batch_size, self.beam_size], dtype=torch.long, device=self.device) - self.next_labels = torch.zeros([self.batch_size, self.beam_size], dtype=torch.long, device=self.device) - self.next_scores = torch.zeros([self.batch_size, self.beam_size], dtype=float_dtype, device=self.device) - self.next_label_durations = torch.zeros( - [self.batch_size, self.beam_size], dtype=torch.long, device=self.device - ) - - self.last_labels_wb = torch.full( - [self.batch_size, self.beam_size], device=self.device, dtype=torch.long, fill_value=self.blank_index - ) - self.hyp_scores = torch.full( - [self.batch_size, self.beam_size], fill_value=self.INACTIVE_SCORE, device=self.device, dtype=float_dtype - ) - - # indices of elements in batch and beam (constant) - self.batch_indices = ( - torch.arange(batch_size, dtype=torch.long, device=device)[:, None] - .expand(batch_size, self.beam_size) - .clone() - ) # size: batch_size x beam_size - self.beam_indices = ( - torch.arange(self.beam_size, dtype=torch.long, device=self.device)[None, :, None] - .expand(self.batch_size, -1, self.beam_size) - .clone() - ) # size: batch_size x beam_size x beam_size - - self.time_indices = torch.zeros_like(self.batch_indices) - self.safe_time_indices = torch.zeros_like(self.batch_indices) - self.last_timestamps = torch.zeros_like(self.time_indices) - - self.active_mask = torch.zeros_like(self.batch_indices, dtype=torch.bool) - self.blank_mask = torch.zeros_like(self.active_mask, dtype=torch.bool) - self.active_mask_any = torch.tensor(True, device=self.device, dtype=torch.bool) - - self.batched_hyps = BatchedBeamHyps( - batch_size=batch_size, - beam_size=self.beam_size, - blank_index=self.blank_index, - init_length=max_time * (max_symbols + 1) if max_symbols is not None else max_time, - device=device, - float_dtype=float_dtype, - model_type='tdt', - ) - - def need_reinit(self, encoder_output_projected: torch.Tensor) -> bool: - """Check if need to reinit state: larger batch_size/max_time, or new device""" - return ( - self.batch_size < encoder_output_projected.shape[0] - or self.max_time < encoder_output_projected.shape[1] - or self.device.index != encoder_output_projected.device.index - ) - - -@dataclass -class SeparateGraphsMALSD: - """Class to store Cuda graphs for decoding when separate graphs are used""" - - before_loop: torch.cuda.CUDAGraph = field(default_factory=torch.cuda.CUDAGraph) - loop_body: torch.cuda.CUDAGraph = field(default_factory=torch.cuda.CUDAGraph) - loop_update_decoder: torch.cuda.CUDAGraph = field(default_factory=torch.cuda.CUDAGraph) - - -class ModifiedALSDBatchedTDTComputer(WithOptionalCudaGraphs, ConfidenceMethodMixin): - """ - Batched Alignment-Length Synchronous Decoding adaptaion for TDT models. Callable. - Based on https://ieeexplore.ieee.org/document/9053040 with the following modficiations: - - does not prediction network caching - - does not employ transcript length estimation, instead, limits the number of expansions for every frame. - """ - - INITIAL_MAX_TIME = 375 # initial max time, used to init state for Cuda graphs - CUDA_PROGRAM_NAME = b"while_malsd_batch_conditional_tdt.cu" - - class CudaGraphsMode(PrettyStrEnum): - FULL_GRAPH = "full_graph" # Cuda graphs with conditional nodes, fastest implementation - NO_WHILE_LOOPS = "no_while_loops" # Decoding with PyTorch while loops + partial Cuda graphs - NO_GRAPHS = "no_graphs" # decoding without graphs, stateful implementation, only for testing purposes - - separate_graphs: Optional[SeparateGraphsMALSD] - full_graph: Optional[torch.cuda.CUDAGraph] - cuda_graphs_mode: Optional[CudaGraphsMode] - state: Optional[MALSDState] - fusion_models: Optional[List[NGramGPULanguageModel]] - fusion_models_alpha: Optional[List[float]] - - def __init__( - self, - decoder, - joint, - durations, - blank_index: int, - beam_size: int, - max_symbols_per_step: Optional[int] = 10, - preserve_alignments=False, - fusion_models: Optional[List[NGramGPULanguageModel]] = None, - fusion_models_alpha: Optional[List[float]] = None, - blank_lm_score_mode: Optional[str | BlankLMScoreMode] = None, - pruning_mode: Optional[str | PruningMode] = None, - allow_cuda_graphs: bool = False, - ): - """ - Init method. - Args: - decoder: Prediction network from RNN-T - joint: Joint module from RNN-T - blank_index: index of blank symbol - beam_size: beam size - max_symbols_per_step: max symbols to emit on each step (to avoid infinite looping) - preserve_alignments: if alignments are needed - fusion_models: list of fusion models (ngram_lm_model and boosting_tree_model) - fusion_models_alpha: list of weights for the fusion models scores - blank_lm_score_mode: mode for scoring blank symbol with fusion models - pruning_mode: mode for pruning hypotheses with fusion models - allow_cuda_graphs: whether to allow CUDA graphs - """ - - super().__init__() - self.decoder = decoder - self.joint = joint - self._blank_index = blank_index - - self.beam_size = beam_size - self.max_symbols = max_symbols_per_step - self.preserve_alignments = preserve_alignments - self._SOS = self._blank_index - self.durations = durations - self.allow_cuda_graphs = allow_cuda_graphs - - if self.preserve_alignments: - raise NotImplementedError("Preserve alignments is not supported") - - self.state = None - self.full_graph = None - self.separate_graphs = None - - self.cuda_graphs_mode = None - self.cuda_graphs_allow_fallback = True - self.maybe_enable_cuda_graphs() - - if fusion_models is not None: - expected_blank_index = self.joint.num_classes_with_blank - self.joint.num_extra_outputs - 1 - if self._blank_index != expected_blank_index: - raise ValueError(f"Invalid blank index: expected {expected_blank_index}, got {self._blank_index}") - - self.fusion_models = fusion_models - self.fusion_models_alpha = fusion_models_alpha - - self.pruning_mode = PruningMode.EARLY if pruning_mode is None else PruningMode(pruning_mode) - self.blank_lm_score_mode = ( - BlankLMScoreMode.LM_WEIGHTED_FULL - if blank_lm_score_mode is None - else BlankLMScoreMode(blank_lm_score_mode) - ) - else: - self.fusion_models = None - self.blank_lm_score_mode = None - - def force_cuda_graphs_mode(self, mode: Optional[Union[str, CudaGraphsMode]]): - """ - Method to set graphs mode. Use only for testing purposes. - For debugging the algorithm use "no_graphs" mode, since it is impossible to debug CUDA graphs directly. - """ - self.cuda_graphs_mode = self.CudaGraphsMode(mode) if mode is not None else None - self.cuda_graphs_allow_fallback = False - self.state = None - - def maybe_enable_cuda_graphs(self) -> bool: - """Enable CUDA graphs if conditions met""" - if self.cuda_graphs_mode is not None: - # CUDA graphs are already enabled - return False - - if not self.allow_cuda_graphs: - self.cuda_graphs_mode = None - else: - # cuda graphs are allowed - # check basic requirements for cuda graphs - if self.max_symbols is None: - logging.warning("Max symbols per step is None, which is not allowed with Cuda graphs. Setting to `10`") - self.max_symbols = 10 - # basic requirements met, need to check while loops - try: - check_cuda_python_cuda_graphs_conditional_nodes_supported() - self.cuda_graphs_mode = self.CudaGraphsMode.FULL_GRAPH - except (ImportError, ModuleNotFoundError, EnvironmentError) as e: - logging.warning( - "No conditional node support for Cuda.\n" - "Cuda graphs with while loops are disabled, decoding speed will be slower\n" - f"Reason: {e}" - ) - self.cuda_graphs_mode = self.CudaGraphsMode.NO_WHILE_LOOPS - self.reset_cuda_graphs_state() - return self.cuda_graphs_mode is not None - - def disable_cuda_graphs(self) -> bool: - """Disable CUDA graphs, can be used to disable graphs temporary, e.g., in training process""" - if self.cuda_graphs_mode is None: - # nothing to disable - return False - self.cuda_graphs_mode = None - self.reset_cuda_graphs_state() - return True - - def reset_cuda_graphs_state(self): - """Reset state to release memory (for CUDA graphs implementations)""" - self.state = None - self.full_graph = None - self.separate_graphs = None - - def modified_alsd_torch( - self, - encoder_output: torch.Tensor, - encoder_output_length: torch.Tensor, - ) -> BatchedBeamHyps: - """ - Pytorch implementation of the batched ALSD algorithm for TDT models. - Args: - encoder_output (torch.Tensor): The output from the encoder network with shape - [batch_size, max_time, encoder_dim]. - encoder_output_length (torch.Tensor): The lengths of the encoder outputs for each batch - with shape [batch_size]. - Returns: - BatchedBeamHyps: Batched beam hypotheses. - """ - - batch_size, max_time, _ = encoder_output.shape - device = encoder_output.device - - if torch.is_autocast_enabled(): - encoder_output = encoder_output.to(torch.get_autocast_gpu_dtype()) - - # do not recalculate joint projection, project only once - encoder_output_projected = self.joint.project_encoder(encoder_output) - float_dtype = encoder_output_projected.dtype - - # init empty batched beam hypotheses - batched_hyps = BatchedBeamHyps( - batch_size=batch_size, - beam_size=self.beam_size, - blank_index=self._blank_index, - init_length=max_time * (self.max_symbols + 1) if self.max_symbols is not None else max_time, - device=device, - float_dtype=float_dtype, - model_type='tdt', - ) - - last_labels_wb = torch.full( - [batch_size, self.beam_size], fill_value=self._SOS, device=device, dtype=torch.long - ) - - batch_beam_indices = ( - torch.arange(batch_size, dtype=torch.long, device=device)[:, None] - .expand(batch_size, self.beam_size) - .clone() - ) - batch_beam_beam_indices = ( - torch.arange(self.beam_size, dtype=torch.long, device=device)[None, :, None] - .expand(batch_size, -1, self.beam_size) - .clone() - ) # size: batch_size x beam_size x beam_size - - time_indices = torch.zeros_like(batch_beam_indices) - safe_time_indices = torch.zeros_like(time_indices) # time indices, guaranteed to be < out_len - last_timesteps = (encoder_output_length - 1)[:, None].expand_as(batch_beam_indices) - active_mask = time_indices <= last_timesteps - - # setup fusion models if available - if self.fusion_models is not None: - fusion_states_list = [] - fusion_states_candidates_list = [] - fusion_scores_list = [] - for fusion_model_idx, fusion_model in enumerate(self.fusion_models): - fusion_model.to(device) - fusion_states = fusion_model.get_init_states(batch_size=batch_size * self.beam_size, bos=True) - fusion_scores, fusion_states_candidates = fusion_model.advance(states=fusion_states) - - fusion_scores = ( - fusion_scores.to(dtype=float_dtype).view(batch_size, self.beam_size, -1) - * self.fusion_models_alpha[fusion_model_idx] - ) - fusion_states_list.append(fusion_states) - fusion_states_candidates_list.append(fusion_states_candidates) - fusion_scores_list.append(fusion_scores) - - decoder_state = self.decoder.initialize_state( - torch.empty( - [ - batch_size * self.beam_size, - ], - dtype=float_dtype, - device=device, - ) - ) - - decoder_output, state, *_ = self.decoder.predict( - last_labels_wb.view(-1, 1), None, add_sos=False, batch_size=batch_size * self.beam_size - ) - # do not recalculate joint projection - decoder_output = self.joint.project_prednet(decoder_output) # size: [(batch_size x beam_size), 1, Dim] - self.decoder.batch_replace_states_all(state, dst_states=decoder_state) - - while active_mask.any(): - # step 1: get joint output + fuse with fusion models (if present) - logits = ( - self.joint.joint_after_projection( - encoder_output_projected[batch_beam_indices.view(-1), safe_time_indices.view(-1)].unsqueeze(1), - decoder_output, - ) - .squeeze(1) - .squeeze(1) - ) - log_probs = F.log_softmax(logits[..., : -len(self.durations)], dim=-1, dtype=float_dtype).view( - batch_size, self.beam_size, -1 - ) # [(B x Beam), V] - duration_log_probs = F.log_softmax(logits[..., -len(self.durations) :], dim=-1, dtype=float_dtype).view( - batch_size, self.beam_size, -1 - ) # [(B x Beam), V] - - if self.fusion_models is not None: - log_probs_top_k, labels_top_k, durations_top_k = self.topk_fusion_model( - fusion_scores_list, log_probs, duration_log_probs - ) - else: - total_log_probs = ( - log_probs[:, :, :, None] + duration_log_probs[:, :, None, :] - ) # size: batch_size x beam_size x (V + 1) x num_durations - log_probs_top_k, total_idx_top_k = torch.topk( - total_log_probs.view(batch_size, self.beam_size, -1), - self.beam_size, - dim=-1, - largest=True, - sorted=True, - ) - - labels_top_k = total_idx_top_k // len(self.durations) - durations_top_k = total_idx_top_k % len(self.durations) - - # forcing blank to have non-zero duration - durations_top_k = torch.where( - torch.logical_and(labels_top_k == self._blank_index, durations_top_k == 0), 1, durations_top_k - ) - - # step 2: Make hyps candidates. Add new scores to hyps, force blank if necessary, recombine hyps, prune - # step 2.1: hyps candidates - log_probs_blank = log_probs[..., -1] + duration_log_probs.max(dim=-1).values - hyps_scores = batched_hyps.scores - hyps_candidates_prob = hyps_scores.unsqueeze(-1) + log_probs_top_k # hyps from top-k (top-k-prev x top_k) - hyps_candidates_prob_forced_blank = ( - hyps_scores + log_probs_blank - ) # hyps with forced blank (top-k-prev x blank) - - # step 2.2 force add final (fully decoded) hyps with to the beam (without updating the score) - # mask inactive (final) hyps with -inf - hyps_candidates_prob = torch.where( - active_mask.unsqueeze(-1), - hyps_candidates_prob, - INACTIVE_SCORE, - ) - # keep inactive (final hypotheses) at the first position in beam - hyps_candidates_prob[..., 0] = torch.where( - active_mask, - hyps_candidates_prob[..., 0], - hyps_scores, - ) - # mark the labels corresponding to final hypotheses with negative label (e.g., -1) - labels_top_k = torch.where(active_mask.unsqueeze(-1), labels_top_k, NON_EXISTENT_LABEL_VALUE) - - # step 2.3: force blank extension with respect to self.max_symbols - if self.max_symbols is not None: - force_blank = (batched_hyps.last_timestamp_lasts >= self.max_symbols) & active_mask - else: - force_blank = torch.full_like(active_mask, fill_value=False) - # mask beams if forced blank - hyps_candidates_prob = torch.where(force_blank.unsqueeze(-1), INACTIVE_SCORE, hyps_candidates_prob) - # keep hypotheses with forced blank at the first position in beam - hyps_candidates_prob[..., 0] = torch.where( - force_blank, hyps_candidates_prob_forced_blank, hyps_candidates_prob[..., 0] - ) - # change labels to blank if forced blank - labels_top_k = torch.where(force_blank.unsqueeze(-1), self._blank_index, labels_top_k) - # force duration 1 for forced blank - durations_top_k = torch.where( - torch.logical_and(force_blank.unsqueeze(-1), durations_top_k == 0), 1, durations_top_k - ) - - # step 2.4: final pruning - get top-beam from (beam_size x beam_size) hyps - next_hyps_prob, hyps_candidates_indices = torch.topk( - hyps_candidates_prob.view(batch_size, -1), k=self.beam_size, largest=True, sorted=True - ) - hyps_indices = torch.gather( - batch_beam_beam_indices.reshape(batch_size, -1), dim=-1, index=hyps_candidates_indices - ) # indices in beam extended with new label - next_labels = torch.gather( - labels_top_k.reshape(batch_size, -1), dim=-1, index=hyps_candidates_indices - ) # labels for extended hypotheses - next_label_durations = torch.gather( - durations_top_k.reshape(batch_size, -1), dim=-1, index=hyps_candidates_indices - ) # durations for extended hypotheses - - # step 3: store results - if self.max_symbols is None: - batched_hyps.add_results_(hyps_indices, next_labels, next_hyps_prob, next_label_durations) - else: - batched_hyps.add_results_no_checks_(hyps_indices, next_labels, next_hyps_prob, next_label_durations) - - # step 4: recombine hypotheses: sum probabilities of identical hypotheses. - batched_hyps.recombine_hyps_() - - # step 5: update decoder state + decoder output (+ fusion models state/scores) - # step 5.1: mask invalid value labels with blank to avoid errors (refer to step 2.2) - last_labels_wb = torch.where(next_labels >= 0, next_labels, self._blank_index) - preserve_state = last_labels_wb == self._blank_index - - # size: decoder_output [(B x Beam), 1, Dim] - # size: state tuple, each is of [Layers, (BxBeam), Dim] - # step 5.2: update decoder + fusion models state - # step 5.2.1: storing current decoder output and states of extended hypotheses - prev_decoder_output = torch.gather( - decoder_output.view(batch_size, self.beam_size, 1, -1), - dim=1, - index=hyps_indices[:, :, None, None].expand(batch_size, self.beam_size, 1, decoder_output.shape[-1]), - ).view(batch_size * self.beam_size, 1, -1) - prev_decoder_state = self.decoder.batch_aggregate_states_beam( - decoder_state, batch_size, self.beam_size, hyps_indices - ) - - # step 5.2.2: get next decoder output and states for extended hypotheses - decoder_output, decoder_state, *_ = self.decoder.predict( - last_labels_wb.view(-1).unsqueeze(1), - prev_decoder_state, - add_sos=False, - batch_size=batch_size * self.beam_size, - ) - decoder_output = self.joint.project_prednet(decoder_output) # do not recalculate joint projection - - # step 5.2.3: update decoder state and output only for non-blank and active hypotheses - decoder_output = torch.where(preserve_state.view(-1)[:, None, None], prev_decoder_output, decoder_output) - self.decoder.batch_replace_states_mask( - src_states=prev_decoder_state, dst_states=decoder_state, mask=preserve_state.view(-1) - ) - - if self.fusion_models is not None: - # fusion_states: size: [(batch_size x beam_size)] - # fusion_states_candidates: [(batch_size x beam_size) x V (without blank)] - for fusion_model_idx, fusion_model in enumerate(self.fusion_models): - fusion_states_candidates = torch.gather( - fusion_states_candidates_list[fusion_model_idx].view(batch_size, self.beam_size, -1), - dim=1, - index=hyps_indices[:, :, None].expand( - batch_size, self.beam_size, fusion_states_candidates_list[fusion_model_idx].shape[-1] - ), - ) - fusion_states_prev = torch.gather( - fusion_states_list[fusion_model_idx].view(batch_size, self.beam_size), - dim=1, - index=hyps_indices, - ) - last_labels_wb_blank_replaced = torch.where(preserve_state, 0, last_labels_wb) - - fusion_states = torch.gather( - fusion_states_candidates, dim=-1, index=last_labels_wb_blank_replaced.unsqueeze(-1) - ).squeeze(-1) - fusion_states = torch.where(preserve_state, fusion_states_prev, fusion_states).view(-1) - - fusion_scores, fusion_states_candidates = fusion_model.advance(states=fusion_states) - fusion_scores = ( - fusion_scores.to(dtype=float_dtype).view(batch_size, self.beam_size, -1) - * self.fusion_models_alpha[fusion_model_idx] - ) - fusion_states_list[fusion_model_idx] = fusion_states - fusion_states_candidates_list[fusion_model_idx] = fusion_states_candidates - fusion_scores_list[fusion_model_idx] = fusion_scores - - # step 6: update time indices + active mask - time_indices.copy_(batched_hyps.next_timestamp) - torch.minimum(time_indices, last_timesteps, out=safe_time_indices) - torch.less_equal(time_indices, last_timesteps, out=active_mask) - - return batched_hyps - - def topk_fusion_model(self, fusion_scores_list, log_probs, duration_log_probs, eps=1e-2): - """ - Computes the top-k log probabilities and corresponding labels for hypotheses, - incorporating fusion models scores based on the pruning and blank scoring modes. - - Args: - fusion_scores_list (List[torch.Tensor]): List of fusion model scores for hypotheses, shape [batch_size, beam_size, vocab_size]. - log_probs (torch.Tensor): Log probabilities from the joint network, shape [batch_size, beam_size, vocab_size]. - duration_log_probs (torch.Tensor): Log probabilities from the duration network, shape [batch_size, beam_size, vocab_size]. - eps (float): Epsilon value for numerical stability. Default is 1e-2 for bf16 precision. - Returns: - Tuple[torch.Tensor, torch.Tensor]: - - log_probs_top_k: Top-k log probabilities, shape [batch_size, beam_size, beam_size]. - - labels_top_k: Corresponding top-k labels, shape [batch_size, beam_size, beam_size]. - """ - - batch_size = log_probs.shape[0] - fusion_scores_sum = sum(fusion_scores_list) - fusion_scores_sum_alpha = sum(self.fusion_models_alpha) - - match self.pruning_mode, self.blank_lm_score_mode: - case PruningMode.LATE, BlankLMScoreMode.NO_SCORE: - log_probs[..., :-1] += fusion_scores_sum - total_log_probs = log_probs[:, :, :, None] + duration_log_probs[:, :, None, :] - - log_probs_top_k, total_idx_top_k = torch.topk( - total_log_probs.view(batch_size, self.beam_size, -1), - self.beam_size, - dim=-1, - largest=True, - sorted=True, - ) - labels_top_k = total_idx_top_k // len(self.durations) - durations_top_k = total_idx_top_k % len(self.durations) - - case PruningMode.LATE, BlankLMScoreMode.LM_WEIGHTED_FULL: - blank_logprob = log_probs[..., -1] - non_blank_logprob = torch.log1p( - -torch.clamp(torch.exp(blank_logprob), max=1.0 - eps) - ) # 1e-2 is used here instead of 1e-6 to address numerical instability with bf16 precision. - log_probs[..., :-1] += non_blank_logprob.unsqueeze(-1) * fusion_scores_sum_alpha + fusion_scores_sum - log_probs[..., -1] *= 1 + fusion_scores_sum_alpha - - total_log_probs = log_probs[:, :, :, None] + duration_log_probs[:, :, None, :] - log_probs_top_k, total_idx_top_k = torch.topk( - total_log_probs.view(batch_size, self.beam_size, -1), - self.beam_size, - dim=-1, - largest=True, - sorted=True, - ) - - labels_top_k = total_idx_top_k // len(self.durations) - durations_top_k = total_idx_top_k % len(self.durations) - - case PruningMode.EARLY, BlankLMScoreMode.NO_SCORE: - log_probs_top_k, labels_top_k = torch.topk( - log_probs, self.beam_size, dim=-1, largest=True, sorted=True - ) - - masked_labels = torch.where(labels_top_k == self._blank_index, 0, labels_top_k) - log_probs_top_k = torch.where( - labels_top_k == self._blank_index, - log_probs_top_k, - log_probs_top_k + torch.gather(fusion_scores_sum, dim=-1, index=masked_labels), - ) - - total_log_probs = log_probs_top_k[:, :, :, None] + duration_log_probs[:, :, None, :] - log_probs_top_k, total_idx_top_k = torch.topk( - total_log_probs.view(batch_size, self.beam_size, -1), - self.beam_size, - dim=-1, - largest=True, - sorted=True, - ) - labels_top_k = torch.gather(labels_top_k, dim=-1, index=total_idx_top_k // len(self.durations)) - durations_top_k = total_idx_top_k % len(self.durations) - - case PruningMode.EARLY, BlankLMScoreMode.LM_WEIGHTED_FULL: - log_probs_top_k, labels_top_k = torch.topk( - log_probs, self.beam_size, dim=-1, largest=True, sorted=True - ) - - blank_logprob = log_probs[..., -1] - non_blank_logprob = torch.log1p(-torch.clamp(torch.exp(blank_logprob), max=1.0 - eps)) - - masked_labels = torch.where(labels_top_k == self._blank_index, 0, labels_top_k) - log_probs_top_k = torch.where( - labels_top_k == self._blank_index, - log_probs_top_k * (1 + fusion_scores_sum_alpha), - log_probs_top_k - + non_blank_logprob.unsqueeze(-1) * fusion_scores_sum_alpha - + torch.gather(fusion_scores_sum, dim=-1, index=masked_labels), - ) - - total_log_probs = log_probs_top_k[:, :, :, None] + duration_log_probs[:, :, None, :] - log_probs_top_k, total_idx_top_k = torch.topk( - total_log_probs.view(batch_size, self.beam_size, -1), - self.beam_size, - dim=-1, - largest=True, - sorted=True, - ) - labels_top_k = torch.gather(labels_top_k, dim=-1, index=total_idx_top_k // len(self.durations)) - durations_top_k = total_idx_top_k % len(self.durations) - - case _: - raise NotImplementedError( - f"Unsupported pruning mode {self.pruning_mode} or blank LM score mode {self.blank_lm_score_mode}" - ) - - return log_probs_top_k, labels_top_k, durations_top_k - - def modified_alsd_cuda_graphs( - self, - encoder_output: torch.Tensor, - encoder_output_length: torch.Tensor, - ) -> BatchedBeamHyps: - """ - Cuda-Graphs implementation of the batched ALSD algorithm. - Args: - encoder_output (torch.Tensor): The output from the encoder network with shape - [batch_size, max_time, encoder_dim]. - encoder_output_length (torch.Tensor): The lengths of the encoder outputs for each batch - with shape [batch_size]. - Returns: - BathedBeamHyps: Batched beam hypotheses. - """ - - assert self.cuda_graphs_mode is not None - - # do not recalculate joint projection, project only once - encoder_output = self.joint.project_encoder(encoder_output) - current_batch_size = encoder_output.shape[0] - current_max_time = encoder_output.shape[1] - - if torch.is_autocast_enabled(): - encoder_output = encoder_output.to(torch.get_autocast_gpu_dtype()) - - # init or reinit graph - if self.state is None or self.state.need_reinit(encoder_output): - self._graph_reinitialize(encoder_output, encoder_output_length) - - # set length to zero for elements outside the current batch - self.state.encoder_output_length.fill_(0) - # copy (projected) encoder output and lenghts - self.state.encoder_output_projected[:current_batch_size, :current_max_time, ...].copy_(encoder_output) - self.state.encoder_output_length[:current_batch_size].copy_(encoder_output_length.unsqueeze(-1)) - if self.cuda_graphs_mode is self.CudaGraphsMode.FULL_GRAPH: - self.full_graph.replay() - elif self.cuda_graphs_mode is self.CudaGraphsMode.NO_WHILE_LOOPS: - self.separate_graphs.before_loop.replay() - while self.state.active_mask_any.item(): - self.separate_graphs.loop_body.replay() - self.separate_graphs.loop_update_decoder.replay() - elif self.cuda_graphs_mode is self.CudaGraphsMode.NO_GRAPHS: - # this mode is only for testing purposes - # manual loop instead of using graphs - self._before_loop() - while self.state.active_mask_any.item(): - self._loop_body() - self._loop_update_decoder() - else: - raise NotImplementedError(f"Unknown graph mode: {self.cuda_graphs_mode}") - - return self.state.batched_hyps - - @classmethod - def _create_loop_body_kernel(cls): - """ - Creates a kernel that evaluates whether to enter the outer loop body (not all hypotheses are decoded). - Condition: while(active_mask_any). - """ - kernel_string = r"""\ - typedef __device_builtin__ unsigned long long cudaGraphConditionalHandle; - - extern "C" __device__ __cudart_builtin__ void cudaGraphSetConditional(cudaGraphConditionalHandle handle, unsigned int value); - - extern "C" __global__ - void loop_conditional(cudaGraphConditionalHandle handle, const bool *active_mask_any) - { - cudaGraphSetConditional(handle, *active_mask_any); - } - """ - return run_nvrtc(kernel_string, b"loop_conditional", cls.CUDA_PROGRAM_NAME) - - def _graph_reinitialize( - self, - encoder_output_projected: torch.Tensor, - encoder_output_length: torch.Tensor, - ): - """ - Reinitializes the graph state for the MALSD computation. - This method sets up the internal state required for the decoding process, including initializing - decoder outputs, decoder states, and optional n-gram language model states. It also handles CUDA - graph compilation based on the specified mode. - Args: - encoder_output_projected (torch.Tensor): The projected encoder output tensor of shape - (batch_size, max_time, encoder_dim). - encoder_output_length (torch.Tensor): The lengths of the encoder outputs for each batch. - Raises: - NotImplementedError: If an unsupported CUDA graph mode is specified. - """ - - batch_size, max_time, encoder_dim = encoder_output_projected.shape - - self.state = MALSDState( - durations=self.durations, - batch_size=batch_size, - beam_size=self.beam_size, - max_time=max(max_time, self.INITIAL_MAX_TIME), - encoder_dim=encoder_dim, - max_symbols=self.max_symbols, - device=encoder_output_projected.device, - float_dtype=encoder_output_projected.dtype, - blank_index=self._blank_index, - ) - - self.state.decoder_state = self.decoder.initialize_state( - torch.empty( - [ - batch_size * self.beam_size, - ], - dtype=encoder_output_projected.dtype, - device=encoder_output_projected.device, - ) - ) - self.state.prev_decoder_state = self.decoder.initialize_state( - torch.empty( - [ - batch_size * self.beam_size, - ], - dtype=encoder_output_projected.dtype, - device=encoder_output_projected.device, - ) - ) - - init_decoder_output, self.state.init_decoder_state, *_ = self.decoder.predict( - self.state.last_labels_wb.view(-1, 1), None, add_sos=False, batch_size=batch_size * self.beam_size - ) - self.state.init_decoder_output = self.joint.project_prednet(init_decoder_output).to( - dtype=self.state.float_dtype - ) # do not recalculate joint projection - - self.decoder.batch_replace_states_all(self.state.init_decoder_state, dst_states=self.state.decoder_state) - self.state.decoder_output = self.state.init_decoder_output.clone() - - self.decoder.batch_replace_states_all(self.state.init_decoder_state, dst_states=self.state.prev_decoder_state) - self.state.prev_decoder_output = self.state.init_decoder_output.clone() - - # setup fusion models if available - if self.fusion_models is not None: - - device = encoder_output_projected.device - - self.state.init_fusion_states_list = [] - self.state.init_fusion_states_candidates_list = [] - self.state.init_fusion_scores_list = [] - - self.state.fusion_states_list = [] - self.state.fusion_states_candidates_list = [] - self.state.fusion_scores_list = [] - self.state.fusion_states_prev_list = [] - - for fusion_model_idx, fusion_model in enumerate(self.fusion_models): - fusion_model.to(device) - - init_fusion_states = fusion_model.get_init_states( - batch_size=self.state.batch_size * self.beam_size, bos=True - ).view(self.state.batch_size, self.beam_size) - init_fusion_scores, init_fusion_states_candidates = fusion_model.advance( - states=init_fusion_states.view(-1) - ) - self.state.init_fusion_scores_list.append( - init_fusion_scores.to(dtype=self.state.float_dtype).view(self.state.batch_size, self.beam_size, -1) - * self.fusion_models_alpha[fusion_model_idx] - ) - self.state.init_fusion_states_candidates_list.append( - init_fusion_states_candidates.view(self.state.batch_size, self.beam_size, -1) - ) - self.state.init_fusion_states_list.append(init_fusion_states) - - self.state.fusion_states_list.append(init_fusion_states.clone()) - self.state.fusion_states_candidates_list.append( - self.state.init_fusion_states_candidates_list[fusion_model_idx].clone() - ) - self.state.fusion_scores_list.append(self.state.init_fusion_scores_list[fusion_model_idx].clone()) - self.state.fusion_states_prev_list.append(init_fusion_states.clone()) - - if self.cuda_graphs_mode is self.CudaGraphsMode.FULL_GRAPH: - try: - self._full_graph_compile() - except NeMoCUDAPythonException as e: - if not self.cuda_graphs_allow_fallback: - raise RuntimeError("Full CUDA graph decoding failed. Mode is forced, raising exception") from e - logging.warning( - f"Full CUDA graph compilation failed: {e}. " - "Falling back to native PyTorch CUDA graphs. Decoding will be slower." - ) - self.cuda_graphs_mode = self.CudaGraphsMode.NO_WHILE_LOOPS - self._partial_graphs_compile() - elif self.cuda_graphs_mode is self.CudaGraphsMode.NO_WHILE_LOOPS: - self._partial_graphs_compile() - elif self.cuda_graphs_mode is self.CudaGraphsMode.NO_GRAPHS: - # no graphs needed - pass - else: - raise NotImplementedError - - def _partial_graphs_compile(self): - """Compile decoding by parts""" - # Always create a new stream, because the per-thread default stream disallows stream capture to a graph. - stream_for_graph = torch.cuda.Stream(self.state.device) - stream_for_graph.wait_stream(torch.cuda.default_stream(self.state.device)) - self.separate_graphs = SeparateGraphsMALSD() - with ( - torch.cuda.stream(stream_for_graph), - torch.inference_mode(), - torch.cuda.graph( - self.separate_graphs.before_loop, stream=stream_for_graph, capture_error_mode="thread_local" - ), - ): - self._before_loop() - - with ( - torch.cuda.stream(stream_for_graph), - torch.inference_mode(), - torch.cuda.graph( - self.separate_graphs.loop_body, stream=stream_for_graph, capture_error_mode="thread_local" - ), - ): - self._loop_body() - - with ( - torch.cuda.stream(stream_for_graph), - torch.inference_mode(), - torch.cuda.graph( - self.separate_graphs.loop_update_decoder, stream=stream_for_graph, capture_error_mode="thread_local" - ), - ): - self._loop_update_decoder() - - @cuda_python_required - def _full_graph_compile(self): - """Compile full graph for decoding""" - # Always create a new stream, because the per-thread default stream disallows stream capture to a graph. - stream_for_graph = torch.cuda.Stream(self.state.device) - self.full_graph = torch.cuda.CUDAGraph() - - with ( - torch.cuda.stream(stream_for_graph), - torch.inference_mode(), - torch.cuda.graph(self.full_graph, stream=stream_for_graph, capture_error_mode="thread_local"), - ): - self._before_loop() - # NB: depending on cuda-python version, cudaStreamGetCaptureInfo can return either 5 or 6 elements - capture_status, _, graph, *_ = cu_call( - cudart.cudaStreamGetCaptureInfo(torch.cuda.current_stream(device=self.state.device).cuda_stream) - ) - - assert capture_status == cudart.cudaStreamCaptureStatus.cudaStreamCaptureStatusActive - - # capture: while self.active_mask_any: - (loop_conditional_handle,) = cu_call(cudart.cudaGraphConditionalHandleCreate(graph, 0, 0)) - loop_kernel = self._create_loop_body_kernel() - active_mask_any_ptr = np.array([self.state.active_mask_any.data_ptr()], dtype=np.uint64) - loop_args = np.array( - [loop_conditional_handle.getPtr(), active_mask_any_ptr.ctypes.data], - dtype=np.uint64, - ) - # loop while there are active utterances - with with_conditional_node(loop_kernel, loop_args, loop_conditional_handle, device=self.state.device): - self._loop_body() - self._loop_update_decoder() - - def _before_loop(self): - """ - Clears state and compute initial active mask - """ - - self.state.batched_hyps.clear_() - - # initial state for fusion models - if self.fusion_models is not None: - for fusion_idx, fusion_model in enumerate(self.fusion_models): - self.state.fusion_states_list[fusion_idx].copy_(self.state.init_fusion_states_list[fusion_idx]) - self.state.fusion_states_candidates_list[fusion_idx].copy_( - self.state.init_fusion_states_candidates_list[fusion_idx] - ) - self.state.fusion_scores_list[fusion_idx].copy_(self.state.init_fusion_scores_list[fusion_idx]) - self.state.fusion_states_prev_list[fusion_idx].copy_(self.state.init_fusion_states_list[fusion_idx]) - - # last found labels - initially () symbol - self.state.last_labels_wb.fill_(self._SOS) - self.state.next_scores.fill_(0.0) - self.state.next_labels.fill_(0.0) - self.state.next_idx.fill_(0.0) - - # time indices - self.state.time_indices.fill_(0) - self.state.safe_time_indices.fill_(0) # safe time indices: guaranteed to be < encoder_output_length - - torch.sub(self.state.encoder_output_length, 1, out=self.state.last_timestamps) - - # masks for utterances in batch - # same as: active_mask = self.encoder_output_length > 0 - torch.greater(self.state.encoder_output_length, 0, out=self.state.active_mask) - - # for storing the last state we need to know what elements became "inactive" on this step - # same as: self.active_mask_any = active_mask.any() - torch.any(self.state.active_mask, out=self.state.active_mask_any) - - self.state.decoder_output.copy_(self.state.init_decoder_output) - self.state.decoder_state[0].copy_(self.state.init_decoder_state[0]) - self.state.decoder_state[1].copy_(self.state.init_decoder_state[1]) - - self.state.prev_decoder_output.fill_(0) - self.state.prev_decoder_state[0].fill_(0) - self.state.prev_decoder_state[1].fill_(0) - - def _loop_body(self): - """Perform a single iteration of the batched RNN-T decoding loop.""" - - # step 1: get joint output + fuse with fusion models (if present) - logits = ( - self.joint.joint_after_projection( - self.state.encoder_output_projected[ - self.state.batch_indices.view(-1), self.state.safe_time_indices.view(-1) - ].unsqueeze(1), - self.state.decoder_output, - ) - .squeeze(1) - .squeeze(1) - ) - log_probs = F.log_softmax(logits[..., : -len(self.durations)], dim=-1, dtype=self.state.float_dtype).view( - self.state.batch_size, self.beam_size, -1 - ) # [(batch_size x beam_size), V] - duration_log_probs = F.log_softmax( - logits[..., -len(self.durations) :], dim=-1, dtype=self.state.float_dtype - ).view( - self.state.batch_size, self.beam_size, -1 - ) # [(batch_size x beam_size), num_durations] - - if self.fusion_models is not None: - log_probs_top_k, labels_top_k, durations_top_k = self.topk_fusion_model( - self.state.fusion_scores_list, log_probs, duration_log_probs - ) - else: - total_log_probs = log_probs[:, :, :, None] + duration_log_probs[:, :, None, :] - log_probs_top_k, total_idx_top_k = torch.topk( - total_log_probs.view(self.state.batch_size, self.beam_size, -1), - self.beam_size, - dim=-1, - largest=True, - sorted=True, - ) - - labels_top_k = total_idx_top_k // len(self.durations) - durations_top_k = total_idx_top_k % len(self.durations) - - # forcing blank to have non-zero duration - torch.where( - torch.logical_and(labels_top_k == self._blank_index, durations_top_k == 0), - self.state.ONE_TENSOR, - durations_top_k, - out=durations_top_k, - ) - - # step 2: Make hyps candidates. Add new scores to hyps, force blank if necessary, recombine hyps, prune - # step 2.1: hyps candidates - log_probs_blank = log_probs[..., -1] + duration_log_probs.max(dim=-1).values - hyps_scores = self.state.batched_hyps.scores - hyps_candidates_prob = hyps_scores.unsqueeze(-1) + log_probs_top_k # hyps from top-k (top-k-prev x top_k) - hyps_candidates_prob_forced_blank = ( - hyps_scores + log_probs_blank - ) # hyps with forced blank (top-k-prev x blank) - - # step 2.2 force add final (fully decoded) hyps with to the beam (without updating the score) - # mask inactive (final) hyps with -inf - torch.where( - self.state.active_mask.unsqueeze(-1), - hyps_candidates_prob, - self.state.INACTIVE_SCORE, - out=hyps_candidates_prob, - ) - # keep inactive (final hypotheses) at the first position in beam - torch.where( - self.state.active_mask, hyps_candidates_prob[..., 0], hyps_scores, out=hyps_candidates_prob[..., 0] - ) - # mark the labels corresponding to final hypotheses with negative label (e.g., -1) - torch.where( - self.state.active_mask.unsqueeze(-1), labels_top_k, self.state.NON_EXISTENT_LABEL, out=labels_top_k - ) - - # step 2.3: force blank extension with respect to self.max_symbols - if self.max_symbols is not None: - force_blank = (self.state.batched_hyps.last_timestamp_lasts >= self.max_symbols) & self.state.active_mask - else: - force_blank = torch.full_like(self.state.active_mask, fill_value=False) - # mask all extensions with -inf - torch.where( - force_blank.unsqueeze(-1), self.state.INACTIVE_SCORE, hyps_candidates_prob, out=hyps_candidates_prob - ) - # keep hypotheses with forced blank at the first position in beam - torch.where( - force_blank, - hyps_candidates_prob_forced_blank, - hyps_candidates_prob[..., 0], - out=hyps_candidates_prob[..., 0], - ) - # change labels to blank if forced blank - torch.where(force_blank.unsqueeze(-1), self.state.BLANK_TENSOR, labels_top_k, out=labels_top_k) - # force duration 1 for forced blank - torch.where( - torch.logical_and(force_blank.unsqueeze(-1), durations_top_k == 0), - self.state.ONE_TENSOR, - durations_top_k, - out=durations_top_k, - ) - - # step 2.4: final pruning - get top-k from (top-k x top-k) hyps - next_hyps_prob, hyps_candidates_indices = torch.topk( - hyps_candidates_prob.view(self.state.batch_size, -1), k=self.beam_size, largest=True, sorted=True - ) - torch.gather( - self.state.beam_indices.reshape(self.state.batch_size, -1), - dim=-1, - index=hyps_candidates_indices, - out=self.state.next_idx, - ) # indices in beam extended with new label - torch.gather( - labels_top_k.reshape(self.state.batch_size, -1), - dim=-1, - index=hyps_candidates_indices, - out=self.state.next_labels, - ) - torch.gather( - durations_top_k.reshape(self.state.batch_size, -1), - dim=-1, - index=hyps_candidates_indices, - out=self.state.next_label_durations, - ) # labels for extended hypotheses - self.state.next_scores.copy_(next_hyps_prob) - - # step 3: store results - if self.max_symbols is None: - self.state.batched_hyps.add_results_( - self.state.next_idx, self.state.next_labels, self.state.next_scores, self.state.next_label_durations - ) - else: - self.state.batched_hyps.add_results_no_checks_( - self.state.next_idx, self.state.next_labels, self.state.next_scores, self.state.next_label_durations - ) - - # step 4: recombine hypotheses: sum probabilities of identical hypotheses. - self.state.batched_hyps.recombine_hyps_() - - def _loop_update_decoder(self): - """ - Updates the decoder state, decoder output, and optionally the fusion models state - for the next iteration of the decoding loop in a batched RNNT (Recurrent Neural Network Transducer) setup. - """ - - # step 5: update decoder state + decoder output (+ fusion models state/scores) - # step 5.1: mask invalid value labels with blank to avoid errors (refer to step 2.2) - torch.where( - self.state.next_labels >= 0, self.state.next_labels, self.state.BLANK_TENSOR, out=self.state.last_labels_wb - ) - preserve_state = self.state.last_labels_wb == self._blank_index - - # size: decoder_output [(B x Beam), 1, Dim] - # size: state tuple, each is of [Layers, (BxBeam), Dim] - # step 5.2: update decoder + fusion models state - # step 5.2.1: storing current decoder output and states of extended hypotheses - torch.gather( - self.state.decoder_output.view(self.state.batch_size, self.beam_size, 1, -1), - dim=1, - index=self.state.next_idx[:, :, None, None].expand( - self.state.batch_size, self.beam_size, 1, self.state.decoder_output.shape[-1] - ), - out=self.state.prev_decoder_output.view(self.state.batch_size, self.beam_size, 1, -1), - ) - self.decoder.batch_aggregate_states_beam( - self.state.decoder_state, - self.state.batch_size, - self.beam_size, - self.state.next_idx, - self.state.prev_decoder_state, - ) - - # step 5.2.2: get next decoder output and states for extended hypotheses - decoder_output, decoder_state, *_ = self.decoder.predict( - self.state.last_labels_wb.view(-1, 1), - self.state.prev_decoder_state, - add_sos=False, - batch_size=self.state.batch_size * self.beam_size, - ) - - # step 5.2.3: update decoder state and output only for non-blank and active hypotheses - torch.where( - preserve_state.view(-1)[:, None, None], - self.state.prev_decoder_output, - self.joint.project_prednet(decoder_output), - out=self.state.decoder_output, - ) - self.decoder.batch_replace_states_mask( - src_states=self.state.prev_decoder_state, - dst_states=self.state.decoder_state, - mask=preserve_state.view(-1), - other_src_states=decoder_state, - ) - - if self.fusion_models is not None: - # fusion_states: size: [(batch_size x beam_size)] - # fusion_states_candidates: [(batch_size x beam_size) x V (without blank)] - for fusion_idx, fusion_model in enumerate(self.fusion_models): - self.state.fusion_states_candidates_list[fusion_idx].copy_( - torch.gather( - self.state.fusion_states_candidates_list[fusion_idx], - dim=1, - index=self.state.next_idx[:, :, None].expand( - self.state.batch_size, - self.beam_size, - self.state.fusion_states_candidates_list[fusion_idx].shape[-1], - ), - ) - ) - torch.gather( - self.state.fusion_states_list[fusion_idx], - dim=1, - index=self.state.next_idx, - out=self.state.fusion_states_prev_list[fusion_idx], - ) - last_labels_wb_blank_replaced = torch.where(preserve_state, 0, self.state.last_labels_wb) - - torch.gather( - self.state.fusion_states_candidates_list[fusion_idx], - dim=-1, - index=last_labels_wb_blank_replaced.unsqueeze(-1), - out=self.state.fusion_states_list[fusion_idx].unsqueeze(-1), - ) - torch.where( - preserve_state, - self.state.fusion_states_prev_list[fusion_idx], - self.state.fusion_states_list[fusion_idx], - out=self.state.fusion_states_list[fusion_idx], - ) - fusion_scores, fusion_states_candidates = fusion_model.advance( - states=self.state.fusion_states_list[fusion_idx].view(-1) - ) - fusion_scores = ( - fusion_scores.to(dtype=self.state.float_dtype).view(self.state.batch_size, self.beam_size, -1) - * self.fusion_models_alpha[fusion_idx] - ) - self.state.fusion_states_candidates_list[fusion_idx].copy_( - fusion_states_candidates.view(self.state.batch_size, self.state.beam_size, -1) - ) - self.state.fusion_scores_list[fusion_idx].copy_(fusion_scores) - - # step 6: update time indices + active mask - self.state.time_indices.copy_(self.state.batched_hyps.next_timestamp) - torch.minimum(self.state.time_indices, self.state.last_timestamps, out=self.state.safe_time_indices) - torch.less_equal(self.state.time_indices, self.state.last_timestamps, out=self.state.active_mask) - torch.any(self.state.active_mask, out=self.state.active_mask_any) - - def __call__( - self, - x: torch.Tensor, - out_len: torch.Tensor, - ) -> BatchedBeamHyps: - if self.cuda_graphs_mode is not None and x.device.type == "cuda": - with torch.amp.autocast(device_type="cuda", enabled=False): - return self.modified_alsd_cuda_graphs(encoder_output=x, encoder_output_length=out_len) - - return self.modified_alsd_torch(encoder_output=x, encoder_output_length=out_len) diff --git a/nemo/collections/asr/parts/submodules/token_classifier.py b/nemo/collections/asr/parts/submodules/token_classifier.py deleted file mode 100644 index cc435308fcae700e041bf0f7549318258abbb7af..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/token_classifier.py +++ /dev/null @@ -1,194 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -from contextlib import contextmanager -from dataclasses import dataclass -from typing import Dict, Optional - -import torch -from torch import nn as nn - -from nemo.collections.asr.parts.submodules.classifier import Classifier -from nemo.collections.common.parts import MultiLayerPerceptron -from nemo.core.classes import typecheck -from nemo.core.neural_types import ChannelType, FloatType, LogitsType, LogprobsType, NeuralType - -__all__ = ['BertPretrainingTokenClassifier', 'TokenClassifier'] - -ACT2FN = {"gelu": nn.functional.gelu, "relu": nn.functional.relu} - - -@dataclass -class TokenClassifierConfig: - num_layers: int = 1 - activation: str = 'relu' - log_softmax: bool = True - dropout: float = 0.0 - use_transformer_init: bool = True - - -class TokenClassifier(Classifier): - """ - A module to perform token level classification tasks such as Named entity recognition. - """ - - @property - def input_types(self) -> Dict[str, NeuralType]: - return { - "hidden_states": NeuralType(('B', 'T', 'D'), ChannelType()), - } - - @property - def output_types(self) -> Dict[str, NeuralType]: - """ - Returns definitions of module output ports. - """ - if not self.mlp.log_softmax: - return {"logits": NeuralType(('B', 'T', 'C'), LogitsType())} - else: - return {"log_probs": NeuralType(('B', 'T', 'C'), LogprobsType())} - - def __init__( - self, - hidden_size: int, - num_classes: int, - num_layers: int = 1, - activation: str = 'relu', - log_softmax: bool = True, - dropout: float = 0.0, - use_transformer_init: bool = True, - ) -> None: - """ - Initializes the Token Classifier module. - - Args: - hidden_size: the size of the hidden dimension - num_classes: number of classes - num_layers: number of fully connected layers in the multilayer perceptron (MLP) - activation: activation to usee between fully connected layers in the MLP - log_softmax: whether to apply softmax to the output of the MLP - dropout: dropout to apply to the input hidden states - use_transformer_init: whether to initialize the weights of the classifier head with the same approach used in Transformer - """ - super().__init__(hidden_size=hidden_size, dropout=dropout) - self.mlp = MultiLayerPerceptron( - hidden_size, num_classes, num_layers=num_layers, activation=activation, log_softmax=log_softmax - ) - self.post_init(use_transformer_init=use_transformer_init) - - @property - def log_softmax(self) -> bool: - return self.mlp.log_softmax - - @contextmanager - def with_log_softmax_enabled(self, value: bool) -> "TokenClassifier": - prev = self.mlp.log_softmax - self.mlp.log_softmax = value - yield self - self.mlp.log_softmax = prev - - @typecheck() - def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: - """ - Performs the forward step of the module. - Args: - hidden_states: batch of hidden states (for example, from the BERT encoder module) - [BATCH_SIZE x SEQ_LENGTH x HIDDEN_SIZE] - Returns: logits value for each class [BATCH_SIZE x SEQ_LENGTH x NUM_CLASSES] - """ - hidden_states = self.dropout(hidden_states) - logits = self.mlp(hidden_states) - return logits - - -class BertPretrainingTokenClassifier(Classifier): - """ - A module to perform token level classification tasks for Bert pretraining. - """ - - @property - def input_types(self) -> Dict[str, NeuralType]: - return { - "hidden_states": NeuralType(('B', 'T', 'D'), ChannelType()), - } - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - """ - Returns definitions of module output ports. - """ - if not self.mlp.log_softmax: - return {"logits": NeuralType(('B', 'T', 'C'), LogitsType())} - else: - return {"log_probs": NeuralType(('B', 'T', 'C'), LogprobsType())} - - def __init__( - self, - hidden_size: int, - num_classes: int, - num_layers: int = 1, - activation: str = 'relu', - log_softmax: bool = True, - dropout: float = 0.0, - use_transformer_init: bool = True, - ) -> None: - """ - Initializes the Token Classifier module. - - Args: - hidden_size: the size of the hidden dimension - num_classes: number of classes - num_layers: number of fully connected layers in the multilayer perceptron (MLP) - activation: activation to usee between fully connected layers in the MLP - log_softmax: whether to apply softmax to the output of the MLP - dropout: dropout to apply to the input hidden states - use_transformer_init: whether to initialize the weights of the classifier head with the same approach used in Transformer - """ - super().__init__(hidden_size=hidden_size, dropout=dropout) - - if activation not in ACT2FN: - raise ValueError(f'activation "{activation}" not found') - self.dense = nn.Linear(hidden_size, hidden_size) - self.act = ACT2FN[activation] - self.norm = nn.LayerNorm(hidden_size, eps=1e-12) - self.mlp = MultiLayerPerceptron( - hidden_size, num_classes, num_layers=num_layers, activation=activation, log_softmax=log_softmax - ) - self.post_init(use_transformer_init=use_transformer_init) - - @property - def log_softmax(self) -> bool: - return self.mlp.log_softmax - - @contextmanager - def with_log_softmax_enabled(self, value: bool) -> "TokenClassifier": - prev = self.mlp.log_softmax - self.mlp.log_softmax = value - yield self - self.mlp.log_softmax = prev - - @typecheck() - def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: - """ - Performs the forward step of the module. - Args: - hidden_states: batch of hidden states (for example, from the BERT encoder module) - [BATCH_SIZE x SEQ_LENGTH x HIDDEN_SIZE] - Returns: logits value for each class [BATCH_SIZE x SEQ_LENGTH x NUM_CLASSES] - """ - hidden_states = self.dropout(hidden_states) - hidden_states = self.dense(hidden_states) - hidden_states = self.act(hidden_states) - transform = self.norm(hidden_states) - logits = self.mlp(transform) - return logits diff --git a/nemo/collections/asr/parts/submodules/transducer_decoding/__init__.py b/nemo/collections/asr/parts/submodules/transducer_decoding/__init__.py deleted file mode 100644 index 07ba03407b36410f48f14f1a4c821cde89d6249e..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/transducer_decoding/__init__.py +++ /dev/null @@ -1,31 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.asr.parts.submodules.transducer_decoding.label_looping_base import ( - BatchedLabelLoopingState, - GreedyBatchedLabelLoopingComputerBase, -) -from nemo.collections.asr.parts.submodules.transducer_decoding.rnnt_label_looping import ( - GreedyBatchedRNNTLabelLoopingComputer, -) -from nemo.collections.asr.parts.submodules.transducer_decoding.tdt_label_looping import ( - GreedyBatchedTDTLabelLoopingComputer, -) - -__all__ = [ - "GreedyBatchedLabelLoopingComputerBase", - "GreedyBatchedRNNTLabelLoopingComputer", - "GreedyBatchedTDTLabelLoopingComputer", - "BatchedLabelLoopingState", -] diff --git a/nemo/collections/asr/parts/submodules/transducer_decoding/label_looping_base.py b/nemo/collections/asr/parts/submodules/transducer_decoding/label_looping_base.py deleted file mode 100644 index 30a4b97366cdea07747c3116d163176e0c257f66..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/transducer_decoding/label_looping_base.py +++ /dev/null @@ -1,309 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from abc import ABC, abstractmethod -from dataclasses import dataclass, field -from typing import Any, Optional - -import torch - -from nemo.collections.asr.parts.context_biasing.biasing_multi_model import GPUBiasingMultiModelBase -from nemo.collections.asr.parts.submodules.ngram_lm import NGramGPULanguageModel -from nemo.collections.asr.parts.utils import rnnt_utils -from nemo.collections.common.parts.optional_cuda_graphs import WithOptionalCudaGraphs -from nemo.core.utils.cuda_python_utils import check_cuda_python_cuda_graphs_conditional_nodes_supported -from nemo.utils import logging -from nemo.utils.enum import PrettyStrEnum - - -@dataclass -class SeparateGraphsLabelLooping: - """Class to store Cuda graphs for decoding when separate graphs are used""" - - before_outer_loop: torch.cuda.CUDAGraph = field(default_factory=torch.cuda.CUDAGraph) - before_inner_loop: torch.cuda.CUDAGraph = field(default_factory=torch.cuda.CUDAGraph) - inner_loop_code: torch.cuda.CUDAGraph = field(default_factory=torch.cuda.CUDAGraph) - after_inner_loop: torch.cuda.CUDAGraph = field(default_factory=torch.cuda.CUDAGraph) - - -@dataclass -class BatchedLabelLoopingState: - """Decoding state to pass between invocations""" - - predictor_states: Any - predictor_outputs: torch.Tensor - labels: torch.Tensor - decoded_lengths: torch.Tensor - fusion_states_list: list[torch.Tensor] = field(default_factory=list) - time_jumps: torch.Tensor | None = None - - -@dataclass -class LabelLoopingStateItem: - """Decoding state to pass between invocations""" - - predictor_state: Any - predictor_output: torch.Tensor - label: torch.Tensor - decoded_length: torch.Tensor - fusion_state_list: list[torch.Tensor] = field(default_factory=list) - time_jump: torch.Tensor | None = None - - -@dataclass -class FusionModelWithParams: - model: NGramGPULanguageModel | GPUBiasingMultiModelBase - alpha: float | None = None - is_multi_model: bool = False - - -class GreedyBatchedLabelLoopingComputerBase(WithOptionalCudaGraphs, ABC): - """ - Base class for Label-Looping algorithm implementation https://arxiv.org/abs/2406.06220 - for optimized batched greedy decoding. - Iterates over labels, on each step finding the next non-blank label - (evaluating Joint multiple times in inner loop); It uses a minimal possible amount of calls - to prediction network (with maximum possible batch size), - which makes it especially useful for scaling the prediction network. - During decoding all active hypotheses ("texts") have the same lengths. - """ - - class CudaGraphsMode(PrettyStrEnum): - FULL_GRAPH = "full_graph" # Cuda graphs with conditional nodes, fastest implementation - NO_WHILE_LOOPS = "no_while_loops" # Decoding with PyTorch while loops + partial Cuda graphs - NO_GRAPHS = "no_graphs" # decoding without graphs, stateful implementation, only for testing purposes - - cuda_graphs_mode: Optional[CudaGraphsMode] - cuda_graphs_allow_fallback: bool - max_symbols: Optional[int] - allow_cuda_graphs: bool - biasing_multi_model: GPUBiasingMultiModelBase | None - fusion_models: list[NGramGPULanguageModel] - fusion_models_alpha: list[float] - - def force_cuda_graphs_mode(self, mode: Optional[str | CudaGraphsMode]): - """ - Method to set graphs mode. Use only for testing purposes. - For debugging and testing the algorithm: - - use "no_graphs" mode for debugging, since it is impossible to debug CUDA graphs directly. - - forced mode disallows fallback to native PyTorch CUDA graphs - """ - self.cuda_graphs_mode = self.CudaGraphsMode(mode) if mode is not None else None - self.cuda_graphs_allow_fallback = False - self.state = None - - def maybe_enable_cuda_graphs(self) -> bool: - """Enable CUDA graphs if conditions met""" - if self.cuda_graphs_mode is not None: - # CUDA graphs are already enabled - return False - - if not self.allow_cuda_graphs: - self.cuda_graphs_mode = None - else: - # cuda graphs are allowed - # check basic requirements for cuda graphs - if self.max_symbols is None: - logging.warning("Max symbols per step is None, which is not allowed with Cuda graphs. Setting to `10`") - self.max_symbols = 10 - # basic requirements met, need to check while loops - try: - check_cuda_python_cuda_graphs_conditional_nodes_supported() - self.cuda_graphs_mode = self.CudaGraphsMode.FULL_GRAPH - except (ImportError, ModuleNotFoundError, EnvironmentError) as e: - logging.warning( - "No conditional node support for Cuda.\n" - "Cuda graphs with while loops are disabled, decoding speed will be slower\n" - f"Reason: {e}" - ) - self.cuda_graphs_mode = self.CudaGraphsMode.NO_WHILE_LOOPS - self.reset_cuda_graphs_state() - return self.cuda_graphs_mode is not None - - def disable_cuda_graphs(self) -> bool: - """Disable CUDA graphs, can be used to disable graphs temporary, e.g., in training process""" - if self.cuda_graphs_mode is None: - # nothing to disable - return False - self.cuda_graphs_mode = None - self.reset_cuda_graphs_state() - return True - - # fusion models-related methods - @property - def per_stream_biasing_enabled(self): - return self.biasing_multi_model is not None - - def _all_fusion_models( - self, with_multi_model: bool = True - ) -> list[NGramGPULanguageModel | GPUBiasingMultiModelBase]: - if with_multi_model and self.per_stream_biasing_enabled: - return self.fusion_models + [self.biasing_multi_model] - return self.fusion_models - - def _all_fusion_models_with_params(self, with_multi_model: bool = True) -> list[FusionModelWithParams]: - models_with_params = [ - FusionModelWithParams(model=model, alpha=alpha, is_multi_model=False) - for model, alpha in zip(self.fusion_models, self.fusion_models_alpha) - ] - if with_multi_model and self.per_stream_biasing_enabled: - models_with_params.append( - FusionModelWithParams(model=self.biasing_multi_model, alpha=None, is_multi_model=True) - ) - return models_with_params - - def has_fusion_models(self, with_multi_model: bool = True) -> bool: - if len(self.fusion_models) > 0: - return True - return with_multi_model and self.per_stream_biasing_enabled - - def _move_fusion_models_to_device(self, device: torch.device): - """ - Move all fusion models to device. - We need to do this since `self` is not nn.Module instance, but owns fusion models (nn.Module instances). - """ - with torch.inference_mode(mode=False): - # NB: we avoid inference mode since otherwise all model params/buffers will be inference tensors, - # which will make further inplace manipulations impossible - # (e.g., `remove_model` for multi-model will throw errors) - for fusion_model in self._all_fusion_models(): - fusion_model.to(device) # fusion_models is nn.Module, but self is not; need to move manually - - def advance_fusion_models( - self, fusion_states_list: list[torch.Tensor], multi_biasing_ids: torch.Tensor | None, float_dtype: torch.dtype - ) -> tuple[list[torch.Tensor], list[torch.Tensor]]: - fusion_states_candidates_list = [] - fusion_scores_list = [] - for fusion_idx, fusion_model_with_params in enumerate(self._all_fusion_models_with_params()): - fusion_scores, fusion_states_candidates = fusion_model_with_params.model.advance( - states=fusion_states_list[fusion_idx], - **({"model_ids": multi_biasing_ids} if fusion_model_with_params.is_multi_model else {}), - ) - fusion_scores = fusion_scores.to(dtype=float_dtype) - if not fusion_model_with_params.is_multi_model: - fusion_scores *= fusion_model_with_params.alpha - # save fusion scores and states candidates - fusion_scores_list.append(fusion_scores) - fusion_states_candidates_list.append(fusion_states_candidates) - return fusion_scores_list, fusion_states_candidates_list - - @abstractmethod - def torch_impl( - self, - encoder_output: torch.Tensor, - encoder_output_length: torch.Tensor, - prev_batched_state: Optional[BatchedLabelLoopingState] = None, - multi_biasing_ids: Optional[torch.Tensor] = None, - ) -> tuple[rnnt_utils.BatchedHyps, Optional[rnnt_utils.BatchedAlignments], BatchedLabelLoopingState]: - """ - Pure PyTorch implementation - - Args: - encoder_output: output from the encoder - encoder_output_length: lengths of the utterances in `encoder_output` - prev_batched_state: previous batched decoding state - multi_biasing_ids: optional tensor [Batch] with ids of fused biasing models - """ - raise NotImplementedError - - @abstractmethod - def cuda_graphs_impl( - self, - encoder_output: torch.Tensor, - encoder_output_length: torch.Tensor, - prev_batched_state: Optional[BatchedLabelLoopingState] = None, - multi_biasing_ids: Optional[torch.Tensor] = None, - ) -> tuple[rnnt_utils.BatchedHyps, Optional[rnnt_utils.BatchedAlignments], BatchedLabelLoopingState]: - """ - Implementation with CUDA graphs. - - Args: - encoder_output: output from the encoder - encoder_output_length: lengths of the utterances in `encoder_output` - prev_batched_state: previous batched decoding state - multi_biasing_ids: optional tensor [Batch] with ids of multi-biasing models - """ - raise NotImplementedError - - @abstractmethod - def reset_cuda_graphs_state(self): - """Reset state to release memory (for CUDA graphs implementations)""" - raise NotImplementedError - - @abstractmethod - def split_batched_state(self, state: BatchedLabelLoopingState) -> list[LabelLoopingStateItem]: - """ - Split batched state into list of items, each item contains state for one hypothesis. - This is used to pass state between invocations of the algorithm. - - Args: - state: batched decoding state - """ - raise NotImplementedError - - @abstractmethod - def merge_to_batched_state(self, state_items: list[LabelLoopingStateItem | None]) -> BatchedLabelLoopingState: - """ - Merge list of items into batched state, each item contains state for one hypothesis. - This is used to pass state between invocations of the algorithm. - - Args: - state_items: list of items to merge - """ - raise NotImplementedError - - def reset_state_by_mask(self, state: BatchedLabelLoopingState, mask: torch.Tensor) -> BatchedLabelLoopingState: - """ - Reset state for masked elements in the batched state. - This is used to reset state for elements that are not active anymore to start a new decoding session. - - Args: - state: batched decoding state - mask: mask for elements to reset - """ - raise NotImplementedError - - def __call__( - self, - x: torch.Tensor, - out_len: torch.Tensor, - prev_batched_state: Optional[BatchedLabelLoopingState] = None, - multi_biasing_ids: Optional[torch.Tensor] = None, - ) -> tuple[rnnt_utils.BatchedHyps, Optional[rnnt_utils.BatchedAlignments], BatchedLabelLoopingState]: - """ - Entry point for the decoding algorithm - - Args: - x: encoder output - out_len: encoder output length - prev_batched_state: previous batched decoding state - multi_biasing_ids: optional tensor [Batch] with ids of fused biasing models - """ - if self.cuda_graphs_mode is not None and x.device.type == "cuda": - # disable CUDA graphs if Mixed Precision is used due to incorrect behavior - with torch.amp.autocast(device_type="cuda", enabled=False): - # TODO(vbataev): fix issue with mixed precision, remove this restriction - return self.cuda_graphs_impl( - encoder_output=x, - encoder_output_length=out_len, - prev_batched_state=prev_batched_state, - multi_biasing_ids=multi_biasing_ids, - ) - - return self.torch_impl( - encoder_output=x, - encoder_output_length=out_len, - prev_batched_state=prev_batched_state, - multi_biasing_ids=multi_biasing_ids, - ) diff --git a/nemo/collections/asr/parts/submodules/transducer_decoding/rnnt_label_looping.py b/nemo/collections/asr/parts/submodules/transducer_decoding/rnnt_label_looping.py deleted file mode 100644 index a732f45e2721283a429a1bfc68535cedf8b86d33..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/transducer_decoding/rnnt_label_looping.py +++ /dev/null @@ -1,1266 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from typing import Any, List, Optional - -import numpy as np -import torch -import torch.nn.functional as F -from omegaconf import DictConfig - -from nemo.collections.asr.parts.context_biasing.biasing_multi_model import GPUBiasingMultiModel -from nemo.collections.asr.parts.submodules.ngram_lm import NGramGPULanguageModel -from nemo.collections.asr.parts.submodules.transducer_decoding.label_looping_base import ( - BatchedLabelLoopingState, - GreedyBatchedLabelLoopingComputerBase, - LabelLoopingStateItem, - SeparateGraphsLabelLooping, -) -from nemo.collections.asr.parts.utils import rnnt_utils -from nemo.collections.asr.parts.utils.asr_confidence_utils import ConfidenceMethodMixin -from nemo.core.utils.cuda_python_utils import NeMoCUDAPythonException, cu_call, run_nvrtc, with_conditional_node -from nemo.core.utils.optional_libs import CUDA_PYTHON_AVAILABLE, cuda_python_required -from nemo.utils import logging - -if CUDA_PYTHON_AVAILABLE: - from cuda.bindings import runtime as cudart - - -class LabelLoopingState: - """ - State for Loop Labels algorithm. Used only with CUDA graphs. - In initialization phase it is possible to assign values (tensors) to the state. - For algorithm code the storage should be reused (prefer copy data instead of assigning tensors). - """ - - max_time: int # maximum length of internal storage for time dimension - batch_size: int # (maximum) length of internal storage for batch dimension - device: torch.device # device to store preallocated tensors - - encoder_output_projected: torch.Tensor # projected output from the encoder for decoding algorithm - encoder_output_length: torch.Tensor # length of the (projected) output from the encoder - - labels: torch.Tensor # storage for current labels - scores: torch.Tensor # storage for current scores - - batch_indices: torch.Tensor # indices of elements in batch (constant, range [0, batch_size-1]) - - time_indices: torch.Tensor # current time indices for each element in batch - safe_time_indices: torch.Tensor # current time indices, but guaranteed to be < encoder_output_length - time_indices_current_labels: torch.Tensor # time indices for found labels (corresponding to `labels` field) - last_timesteps: torch.Tensor # indices of the last timesteps for each element (encoder_output_length - 1) - - active_mask: torch.Tensor # mask for active hypotheses (the decoding is finished for the utterance if it is False) - advance_mask: torch.Tensor # mask for "advancing" hypotheses (blank is found for the element on the current step) - blank_mask: torch.Tensor # if the element is blank - - active_mask_any: torch.Tensor # 0-dim bool tensor, condition for outer loop ('any element is still active') - advance_mask_any: torch.Tensor # 0-dim bool tensor, condition for inner loop ('should advance any index') - - decoder_state: Any # current decoder state - decoder_output: torch.Tensor # output from the decoder (projected) - - decoder_state_after_sos: Any # decoder state after _SOS symbol (for initialization) - decoder_output_after_sos: ( - torch.Tensor - ) # output from the decoder (projected) after _SOS symbol (for initialization) - - batched_hyps: rnnt_utils.BatchedHyps # batched hypotheses - decoding result - alignments: Optional[rnnt_utils.BatchedAlignments] = None # batched alignments - - # for fusion models - fusion_states_list: list[torch.Tensor] - fusion_states_candidates_list: list[torch.Tensor] - fusion_scores_list: list[torch.Tensor] - multi_biasing_ids: torch.Tensor - - def __init__( - self, - batch_size: int, - max_time: int, - encoder_dim: int, - max_symbols: int, - device: torch.device, - float_dtype: torch.dtype, - logits_dim: int, - preserve_alignments=False, - preserve_frame_confidence=False, - ): - """ - - Args: - batch_size: batch size for encoder output storage - max_time: maximum time for encoder output storage - encoder_dim: last dimension for encoder output storage (projected encoder output) - max_symbols: max symbols per step (to avoid infinite looping and pre-allocate storage) - device: device to store tensors - float_dtype: default float dtype for tensors (should match projected encoder output) - logits_dim: output dimension for Joint - preserve_alignments: if alignments are needed - preserve_frame_confidence: if frame confidence is needed - """ - self.device = device - self.float_dtype = float_dtype - self.batch_size = batch_size - self.max_time = max_time - - self.encoder_output_projected = torch.zeros( - (self.batch_size, self.max_time, encoder_dim), - dtype=float_dtype, - device=self.device, - ) - self.encoder_output_length = torch.zeros((self.batch_size,), dtype=torch.long, device=self.device) - - self.labels = torch.zeros([self.batch_size], dtype=torch.long, device=self.device) - self.scores = torch.zeros([self.batch_size], dtype=float_dtype, device=self.device) - - # indices of elements in batch (constant) - self.batch_indices = torch.arange(self.batch_size, dtype=torch.long, device=self.device) - - self.time_indices = torch.zeros_like(self.batch_indices) - self.safe_time_indices = torch.zeros_like(self.batch_indices) - self.time_indices_current_labels = torch.zeros_like(self.time_indices) - self.last_timesteps = torch.zeros_like(self.time_indices) - - self.active_mask = torch.zeros([self.batch_size], dtype=torch.bool, device=self.device) - self.advance_mask = torch.zeros_like(self.active_mask) - self.blank_mask = torch.zeros_like(self.active_mask) - - self.active_mask_any = torch.tensor(True, device=self.device, dtype=torch.bool) - self.advance_mask_any = torch.tensor(True, device=self.device, dtype=torch.bool) - - self.multi_biasing_ids = torch.full([self.batch_size], fill_value=-1, dtype=torch.long, device=self.device) - self.fusion_states_list = [] - self.fusion_states_candidates_list = [] - self.fusion_scores_list = [] - self.batched_hyps = rnnt_utils.BatchedHyps( - batch_size=self.batch_size, - init_length=self.max_time * max_symbols, - device=self.device, - float_dtype=float_dtype, - ) - if preserve_alignments or preserve_frame_confidence: - self.alignments = rnnt_utils.BatchedAlignments( - batch_size=batch_size, - logits_dim=logits_dim, - init_length=max_time * (max_symbols + 1), - device=self.device, - float_dtype=self.float_dtype, - store_alignments=preserve_alignments, - store_frame_confidence=preserve_frame_confidence, - ) - else: - self.alignments = None - - def need_reinit(self, encoder_output_projected: torch.Tensor) -> bool: - """Check if need to reinit state: larger batch_size/max_time, or new device""" - return ( - self.batch_size < encoder_output_projected.shape[0] - or self.max_time < encoder_output_projected.shape[1] - or self.device.index != encoder_output_projected.device.index - ) - - -class GreedyBatchedRNNTLabelLoopingComputer(GreedyBatchedLabelLoopingComputerBase, ConfidenceMethodMixin): - """ - Label-Looping algorithm implementation https://arxiv.org/abs/2406.06220 for optimized batched greedy decoding. - Iterates over labels, on each step finding the next non-blank label - (evaluating Joint multiple times in inner loop); It uses a minimal possible amount of calls - to prediction network (with maximum possible batch size), - which makes it especially useful for scaling the prediction network. - During decoding all active hypotheses ("texts") have the same lengths. - """ - - INITIAL_MAX_TIME = 375 # initial max time, used to init state for Cuda graphs - CUDA_PROGRAM_NAME = b"while_label_looping_conditional_rnnt.cu" - - separate_graphs: Optional[SeparateGraphsLabelLooping] - full_graph: Optional[torch.cuda.CUDAGraph] - state: Optional[LabelLoopingState] - fusion_models: Optional[List[NGramGPULanguageModel]] - - def __init__( - self, - decoder, - joint, - blank_index: int, - max_symbols_per_step: Optional[int] = None, - preserve_alignments=False, - preserve_frame_confidence=False, - confidence_method_cfg: Optional[DictConfig] = None, - allow_cuda_graphs: bool = True, - fusion_models: Optional[List[NGramGPULanguageModel]] = None, - fusion_models_alpha: Optional[List[float]] = None, - enable_per_stream_biasing: bool = False, - ): - """ - Init method. - Args: - decoder: Prediction network from RNN-T - joint: Joint module from RNN-T - blank_index: index of blank symbol - max_symbols_per_step: max symbols to emit on each step (to avoid infinite looping) - preserve_alignments: if alignments are needed - preserve_frame_confidence: if frame confidence is needed - confidence_method_cfg: config for the confidence - fusion_models: list of fusion models (ngram_lm_model and boosting_tree_model) - fusion_models_alpha: list of fusion model weights (ngram_lm_alpha and boosting_tree_alpha) - enable_per_stream_biasing: enable multi-biasing model for per-stream customization - """ - super().__init__() - self.decoder = decoder - self.joint = joint - self._blank_index = blank_index - self.max_symbols = max_symbols_per_step - self.preserve_alignments = preserve_alignments - self.preserve_frame_confidence = preserve_frame_confidence - self._SOS = self._blank_index - self._init_confidence_method(confidence_method_cfg=confidence_method_cfg) - assert self._SOS == self._blank_index # "blank as pad" algorithm only - - self.fusion_models = fusion_models or [] - self.fusion_models_alpha = fusion_models_alpha or [] - - self.biasing_multi_model = ( - GPUBiasingMultiModel(vocab_size=self._blank_index, reallocation_callback_fn=self.reset_cuda_graphs_state) - if enable_per_stream_biasing - else None - ) - if allow_cuda_graphs: - for fusion_model in self._all_fusion_models(): - if not fusion_model.compatible_with_cuda_graphs(): - logging.warning( - "Fusion model used that is incompatible with CUDA graphs." - " Switching off CUDA graphs, decoding may be slow." - ) - allow_cuda_graphs = False - break - - self.allow_cuda_graphs = allow_cuda_graphs - - self.state = None - self.full_graph = None - self.separate_graphs = None - - self.cuda_graphs_mode = None - self.cuda_graphs_allow_fallback = True - self.maybe_enable_cuda_graphs() - - def reset_cuda_graphs_state(self): - """Reset state to release memory (for CUDA graphs implementations)""" - self.state = None - self.full_graph = None - self.separate_graphs = None - - def _get_frame_confidence(self, logits: torch.Tensor) -> Optional[torch.Tensor]: - float_dtype = logits.dtype - return ( - self._get_confidence_tensor(F.log_softmax(logits, dim=-1)).to(dtype=float_dtype) - if self.preserve_frame_confidence - else None - ) - - def torch_impl( - self, - encoder_output: torch.Tensor, - encoder_output_length: torch.Tensor, - prev_batched_state: Optional[BatchedLabelLoopingState] = None, - multi_biasing_ids: Optional[torch.Tensor] = None, - ) -> tuple[rnnt_utils.BatchedHyps, Optional[rnnt_utils.BatchedAlignments], BatchedLabelLoopingState]: - """ - Pure PyTorch implementation - - Args: - encoder_output: output from the encoder - encoder_output_length: lengths of the utterances in `encoder_output` - prev_batched_state: previous batched decoding state - multi_biasing_ids: optional tensor [Batch] with ids of multi-biasing models - """ - batch_size, max_time, _unused = encoder_output.shape - device = encoder_output.device - self._move_fusion_models_to_device(device=device) - if self.per_stream_biasing_enabled and multi_biasing_ids is None: - multi_biasing_ids = torch.full([batch_size], fill_value=-1, dtype=torch.long, device=device) - - # do not recalculate joint projection, project only once - encoder_output_projected = self.joint.project_encoder(encoder_output) - float_dtype = encoder_output_projected.dtype - - # init output structures: BatchedHyps (for results), BatchedAlignments + last decoder state - # init empty batched hypotheses - batched_hyps = rnnt_utils.BatchedHyps( - batch_size=batch_size, - init_length=max_time * self.max_symbols if self.max_symbols is not None else max_time, - device=device, - float_dtype=float_dtype, - ) - # init alignments if necessary - use_alignments = self.preserve_alignments or self.preserve_frame_confidence - # always use alignments variable - for torch.jit adaptation, but keep it as minimal as possible - alignments = rnnt_utils.BatchedAlignments( - batch_size=batch_size, - logits_dim=self.joint.num_classes_with_blank, - init_length=max_time * 2 if use_alignments else 1, # blank for each timestep + text tokens - device=device, - float_dtype=float_dtype, - store_alignments=self.preserve_alignments, - store_frame_confidence=self.preserve_frame_confidence, - ) - - # indices of elements in batch (constant) - batch_indices = torch.arange(batch_size, dtype=torch.long, device=device) - - # time indices - last_timesteps = torch.maximum(encoder_output_length - 1, torch.zeros_like(encoder_output_length)) - time_indices = torch.zeros_like(batch_indices) - safe_time_indices = torch.minimum(time_indices, last_timesteps) # time indices, guaranteed to be < out_len - time_indices_current_labels = torch.zeros_like(time_indices) - - # masks for utterances in batch - active_mask: torch.Tensor = time_indices < encoder_output_length - advance_mask = torch.empty_like(active_mask) - - if prev_batched_state is None: - # initial state, needed for torch.jit to compile (cannot handle None) - state = self.decoder.initialize_state(encoder_output_projected) - # last found labels - initially () symbol - labels = torch.full_like(batch_indices, fill_value=self._SOS) - decoder_output, state, *_ = self.decoder.predict( - labels.unsqueeze(1), state, add_sos=False, batch_size=batch_size - ) - decoder_output = self.joint.project_prednet(decoder_output) # do not recalculate joint projection - - # fusion models - fusion_states_list = [] - for fusion_model in self._all_fusion_models(): - fusion_states_list.append(fusion_model.get_init_states(batch_size=batch_size, bos=True)) - else: - decoder_output = prev_batched_state.predictor_outputs - state = prev_batched_state.predictor_states - fusion_states_list = prev_batched_state.fusion_states_list - - fusion_scores_list, fusion_states_candidates_list = [], [] - - # loop while there are active utterances - while active_mask.any(): - # stage 1: get joint output, iteratively seeking for non-blank labels - # blank label in `labels` tensor means "end of hypothesis" (for this index) - - # stage 1.1: get first joint output - logits = ( - self.joint.joint_after_projection( - encoder_output_projected[batch_indices, safe_time_indices].unsqueeze(1), - decoder_output, - ) - .squeeze(1) - .squeeze(1) - ) - scores, labels = logits.max(-1) - - if self.has_fusion_models(): - fusion_scores_list, fusion_states_candidates_list = self.advance_fusion_models( - fusion_states_list=fusion_states_list, - multi_biasing_ids=multi_biasing_ids, - float_dtype=float_dtype, - ) - logits_with_fusion = logits.clone() - for fusion_scores in fusion_scores_list: - logits_with_fusion[:, :-1] += fusion_scores - - # get max scores and labels without blank - fusion_scores_max, fusion_labels_max = logits_with_fusion[:, :-1].max(dim=-1) - # preserve "blank" / "non-blank" category - torch.where(labels == self._blank_index, labels, fusion_labels_max, out=labels) - torch.where(labels == self._blank_index, scores, fusion_scores_max, out=scores) - - # search for non-blank labels using joint, advancing time indices for blank labels - # checking max_symbols is not needed, since we already forced advancing time indices for such cases - blank_mask = labels == self._blank_index - time_indices_current_labels.copy_(time_indices) - if use_alignments: - alignments.add_results_masked_( - active_mask=active_mask, - time_indices=time_indices_current_labels, - logits=logits if self.preserve_alignments else None, - labels=labels if self.preserve_alignments else None, - confidence=self._get_frame_confidence(logits=logits), - ) - - # advance_mask is a mask for current batch for searching non-blank labels; - # each element is True if non-blank symbol is not yet found AND we can increase the time index - time_indices += blank_mask - torch.minimum(time_indices, last_timesteps, out=safe_time_indices) - torch.less(time_indices, encoder_output_length, out=active_mask) - torch.logical_and(active_mask, blank_mask, out=advance_mask) - - # stage 1.2: inner loop - find next non-blank labels (if exist) - while advance_mask.any(): - # same as: time_indices_current_labels[advance_mask] = time_indices[advance_mask], but non-blocking - # store current time indices to use further for storing the results - torch.where(advance_mask, time_indices, time_indices_current_labels, out=time_indices_current_labels) - logits = ( - self.joint.joint_after_projection( - encoder_output_projected[batch_indices, safe_time_indices].unsqueeze(1), - decoder_output, - ) - .squeeze(1) - .squeeze(1) - ) - # get labels (greedy) and scores from current logits, replace labels/scores with new - # labels[advance_mask] are blank, and we are looking for non-blank labels - more_scores, more_labels = logits.max(dim=-1) - - if self.has_fusion_models(): - logits_with_fusion = logits.clone() - for fusion_scores in fusion_scores_list: - logits_with_fusion[:, :-1] += fusion_scores - # get max scores and labels without blank - more_scores_w_fusion, more_labels_w_fusion = logits_with_fusion[:, :-1].max(dim=-1) - # preserve "blank" / "non-blank" category - torch.where(more_labels == self._blank_index, more_labels, more_labels_w_fusion, out=more_labels) - - # same as: labels[advance_mask] = more_labels[advance_mask], but non-blocking - torch.where(advance_mask, more_labels, labels, out=labels) - # same as: scores[advance_mask] = more_scores[advance_mask], but non-blocking - torch.where(advance_mask, more_scores, scores, out=scores) - - if use_alignments: - alignments.add_results_masked_( - active_mask=advance_mask, - time_indices=time_indices_current_labels, - logits=logits if self.preserve_alignments else None, - labels=more_labels if self.preserve_alignments else None, - confidence=self._get_frame_confidence(logits=logits), - ) - - blank_mask = labels == self._blank_index - time_indices += blank_mask - torch.minimum(time_indices, last_timesteps, out=safe_time_indices) - torch.less(time_indices, encoder_output_length, out=active_mask) - torch.logical_and(active_mask, blank_mask, out=advance_mask) - - # stage 2: store hypotheses - if self.max_symbols is not None: - # pre-allocated memory, no need for checks - batched_hyps.add_results_masked_no_checks_( - active_mask=active_mask, - labels=labels, - time_indices=time_indices_current_labels, - scores=scores, - ) - else: - # auto-adjusted storage - batched_hyps.add_results_masked_( - active_mask=active_mask, - labels=labels, - time_indices=time_indices_current_labels, - scores=scores, - ) - - # stage 3: get decoder (prediction network) output with found labels - # NB: if active_mask is False, this step is redundant; - # but such check will require device-to-host synchronization, so we avoid it - # preserve state/decoder_output for inactive elements - prev_state = state - prev_decoder_output = decoder_output - decoder_output, state, *_ = self.decoder.predict( - labels.unsqueeze(1), state, add_sos=False, batch_size=batch_size - ) - decoder_output = self.joint.project_prednet(decoder_output) # do not recalculate joint projection - - # preserve correct states/outputs for inactive elements - self.decoder.batch_replace_states_mask( - src_states=prev_state, - dst_states=state, - mask=~active_mask, - ) - torch.where( - active_mask.unsqueeze(-1).unsqueeze(-1), decoder_output, prev_decoder_output, out=decoder_output - ) - - for fusion_states, fusion_states_candidates in zip(fusion_states_list, fusion_states_candidates_list): - torch.where( - active_mask, - fusion_states_candidates[batch_indices, labels * active_mask], - fusion_states, - out=fusion_states, - ) - - # stage 4: to avoid infinite looping, go to the next frame after max_symbols emission - if self.max_symbols is not None: - # if labels are non-blank (not end-of-utterance), check that last observed timestep with label: - # if it is equal to the current time index, and number of observations is >= max_symbols, force blank - force_blank_mask = torch.logical_and( - active_mask, - torch.logical_and( - torch.logical_and( - labels != self._blank_index, - batched_hyps.last_timestamp_lasts >= self.max_symbols, - ), - batched_hyps.last_timestamp == time_indices, - ), - ) - time_indices += force_blank_mask # emit blank => advance time indices - # update safe_time_indices, non-blocking - torch.minimum(time_indices, last_timesteps, out=safe_time_indices) - # same as: active_mask = time_indices < encoder_output_length - torch.less(time_indices, encoder_output_length, out=active_mask) - - # fix timestamps for iterative decoding - if prev_batched_state is not None: - batched_hyps.timestamps += prev_batched_state.decoded_lengths.unsqueeze(1) - if use_alignments: - alignments.timestamps += prev_batched_state.decoded_lengths.unsqueeze(1) - # NB: last labels can not exist (nothing decoded on this step). - # return the last labels from the previous state in this case - last_labels = batched_hyps.get_last_labels(pad_id=self._SOS) - decoding_state = BatchedLabelLoopingState( - predictor_states=state, - predictor_outputs=decoder_output, - labels=( - torch.where(last_labels == self._SOS, prev_batched_state.labels, last_labels) - if prev_batched_state is not None - else last_labels - ), - decoded_lengths=( - encoder_output_length.clone() - if prev_batched_state is None - else encoder_output_length + prev_batched_state.decoded_lengths - ), - fusion_states_list=fusion_states_list, - time_jumps=None, - ) - if use_alignments: - return batched_hyps, alignments, decoding_state - return batched_hyps, None, decoding_state - - def _get_decoding_state_item_after_sos(self, device: torch.device | str) -> LabelLoopingStateItem: - """Get decoding state item after symbol, used for initialization from empty hypotheses.""" - batched_state = self._get_batched_decoding_state_after_sos(device=device, batch_size=1) - return self.split_batched_state(batched_state)[0] - - def _get_batched_decoding_state_after_sos( - self, device: torch.device | str, batch_size: int - ) -> BatchedLabelLoopingState: - """Get batched decoding state after symbol, used for initialization from empty hypotheses.""" - labels = torch.full([batch_size], fill_value=self._SOS, dtype=torch.long, device=device) - decoder_output, state, *_ = self.decoder.predict( - labels.unsqueeze(1), None, add_sos=False, batch_size=batch_size - ) - decoder_output = self.joint.project_prednet(decoder_output) # do not recalculate joint projection - state = BatchedLabelLoopingState( - predictor_states=state, - predictor_outputs=decoder_output, - labels=labels, - decoded_lengths=torch.zeros([batch_size], dtype=torch.long, device=device), - fusion_states_list=( - [ - fusion_model.get_init_states(batch_size=batch_size, bos=True).to(device) - for fusion_model in self._all_fusion_models() - ] - ), - time_jumps=None, - ) - return state - - def reset_state_by_mask(self, state: BatchedLabelLoopingState, mask: torch.Tensor) -> BatchedLabelLoopingState: - """ - Reset state for masked elements in the batched state. - This is used to reset state for elements that are not active anymore to start a new decoding session. - - Args: - state: batched decoding state - mask: mask for elements to reset - """ - state_after_sos = self._get_batched_decoding_state_after_sos( - device=state.predictor_outputs.device, batch_size=state.labels.shape[0] - ) - self.decoder.batch_replace_states_mask( - src_states=state_after_sos.predictor_states, dst_states=state.predictor_states, mask=mask - ) - torch.where( - mask[:, None, None], - state_after_sos.predictor_outputs, - state.predictor_outputs, - out=state.predictor_outputs, - ) - torch.where(mask, state_after_sos.labels, state.labels, out=state.labels) - torch.where(mask, state_after_sos.decoded_lengths, state.decoded_lengths, out=state.decoded_lengths) - for fusion_idx, fusion_states in enumerate(state.fusion_states_list): - torch.where( - mask, - state_after_sos.fusion_states_list[fusion_idx], - fusion_states, - out=state.fusion_states_list[fusion_idx], - ) - return state - - def split_batched_state(self, state: BatchedLabelLoopingState) -> list[LabelLoopingStateItem]: - """ - Split batched state into list of items, each item contains state for one hypothesis. - This is used to pass state between invocations of the algorithm. - - Args: - state: batched decoding state - """ - state_items: list[LabelLoopingStateItem] = [] - for i, predictor_state in enumerate(self.decoder.batch_split_states(state.predictor_states)): - state_items.append( - LabelLoopingStateItem( - predictor_state=predictor_state, - predictor_output=state.predictor_outputs[i], - label=state.labels[i], - decoded_length=state.decoded_lengths[i], - fusion_state_list=([fusion_state[i] for fusion_state in state.fusion_states_list]), - time_jump=None, - ) - ) - return state_items - - def merge_to_batched_state(self, state_items: list[LabelLoopingStateItem | None]) -> BatchedLabelLoopingState: - """ - Merge list of items into batched state, each item contains state for one hypothesis. - This is used to pass state between invocations of the algorithm. - - Args: - state_items: list of items to merge - """ - if any(item is None for item in state_items): - not_none_item = next(item for item in state_items if item is not None) - assert not_none_item is not None - device = not_none_item.predictor_output.device - start_item = self._get_decoding_state_item_after_sos(device=device) - for i, item in enumerate(state_items): - if item is None: - state_items[i] = start_item - - fusion_states_list = [] - for fusion_idx in range(len(self._all_fusion_models())): - fusion_states_list.append(torch.stack([item.fusion_state_list[fusion_idx] for item in state_items])) - - batched_state = BatchedLabelLoopingState( - predictor_states=self.decoder.batch_unsplit_states([item.predictor_state for item in state_items]), - predictor_outputs=torch.stack([item.predictor_output for item in state_items]), - labels=torch.stack([item.label for item in state_items]), - decoded_lengths=torch.stack([item.decoded_length for item in state_items]), - fusion_states_list=fusion_states_list, - time_jumps=None, - ) - return batched_state - - def cuda_graphs_impl( - self, - encoder_output: torch.Tensor, - encoder_output_length: torch.Tensor, - prev_batched_state: Optional[BatchedLabelLoopingState] = None, - multi_biasing_ids: Optional[torch.Tensor] = None, - ) -> tuple[rnnt_utils.BatchedHyps, Optional[rnnt_utils.BatchedAlignments], BatchedLabelLoopingState]: - """ - Implementation with CUDA graphs. - - Args: - encoder_output: output from the encoder - encoder_output_length: lengths of the utterances in `encoder_output` - prev_batched_state: previous batched decoding state - multi_biasing_ids: optional tensor [Batch] with ids of multi-biasing models - """ - assert self.cuda_graphs_mode is not None - device = encoder_output.device - - # do not recalculate joint projection, project only once - encoder_output = self.joint.project_encoder(encoder_output) - current_batch_size = encoder_output.shape[0] - current_max_time = encoder_output.shape[1] - - if torch.is_autocast_enabled(): - encoder_output = encoder_output.to(torch.get_autocast_gpu_dtype()) - else: - # since autocast could be enabled outside and disallowed here, - # we need to cast encoder output to dtype of params - float_dtype = next(self.joint.parameters()).dtype - encoder_output = encoder_output.to(float_dtype) - - # init or reinit graph - if self.state is None or self.state.need_reinit(encoder_output): - self._graph_reinitialize(encoder_output) - - # copy (projected) encoder output and lengths - self.state.encoder_output_projected[:current_batch_size, :current_max_time, ...].copy_(encoder_output) - self.state.encoder_output_length[: encoder_output_length.shape[0]].copy_(encoder_output_length) - # set length to zero for elements outside the current batch - self.state.encoder_output_length[current_batch_size:].fill_(0) - if self.per_stream_biasing_enabled: - if multi_biasing_ids is None: - multi_biasing_ids = torch.full( - [encoder_output_length.shape[0]], fill_value=-1, dtype=torch.long, device=device - ) - self.state.multi_biasing_ids[:current_batch_size].copy_(multi_biasing_ids) - self.state.multi_biasing_ids[current_batch_size:].fill_(-1) - - self._init_decoding_state(current_batch_size=current_batch_size, prev_batched_state=prev_batched_state) - - if self.cuda_graphs_mode is self.CudaGraphsMode.FULL_GRAPH: - self.full_graph.replay() - elif self.cuda_graphs_mode is self.CudaGraphsMode.NO_WHILE_LOOPS: - self.separate_graphs.before_outer_loop.replay() - while self.state.active_mask_any.item(): - self.separate_graphs.before_inner_loop.replay() - while self.state.advance_mask_any.item(): - self.separate_graphs.inner_loop_code.replay() - self.separate_graphs.after_inner_loop.replay() - elif self.cuda_graphs_mode is self.CudaGraphsMode.NO_GRAPHS: - # this mode is only for testing purposes - # manual loop instead of using graphs - self._before_outer_loop() - while self.state.active_mask_any.item(): - self._before_inner_loop_get_joint_output() - while self.state.advance_mask_any.item(): - self._inner_loop_step_find_next_non_blank() - self._after_inner_loop_step() - else: - raise NotImplementedError(f"Unknown graph mode: {self.cuda_graphs_mode}") - - if prev_batched_state is not None: - self._fix_timestamps_for_iterative_decoding( - current_batch_size=current_batch_size, prev_batched_state=prev_batched_state - ) - # NB: last labels can not exist (nothing decoded on this step). - # return the last labels from the previous state in this case - last_labels = self.state.batched_hyps.get_last_labels(pad_id=self._SOS) - pad_batch_size = ( - self.state.batch_size - prev_batched_state.labels.shape[-1] if prev_batched_state is not None else 0 - ) - - decoding_state = BatchedLabelLoopingState( - predictor_states=self.decoder.clone_state(self.state.decoder_state), - predictor_outputs=self.state.decoder_output.clone(), - labels=( - torch.where( - last_labels == self._SOS, - F.pad(prev_batched_state.labels, (0, pad_batch_size), value=self._SOS), - last_labels, - ) - if prev_batched_state is not None - else last_labels - ), - decoded_lengths=( - self.state.encoder_output_length.clone() - if prev_batched_state is None - else self.state.encoder_output_length - + F.pad(prev_batched_state.decoded_lengths, (0, pad_batch_size), value=0) - ), - fusion_states_list=([fusion_state.clone() for fusion_state in self.state.fusion_states_list]), - time_jumps=None, - ) - - # NB: return an independent copy of hyps/alignments/state - # to avoid any manipulations with allocated memory outside the decoder - return ( - self.state.batched_hyps.clone(), - self.state.alignments.clone() if self.preserve_alignments else None, - decoding_state, - ) - - @classmethod - def _create_outer_while_loop_kernel(cls): - """ - Creates a kernel that evaluates whether to enter the outer loop body (not all hypotheses are decoded). - Condition: while(active_mask_any). - """ - kernel_string = r"""\ - typedef __device_builtin__ unsigned long long cudaGraphConditionalHandle; - - extern "C" __device__ __cudart_builtin__ void cudaGraphSetConditional(cudaGraphConditionalHandle handle, unsigned int value); - - extern "C" __global__ - void outer_label_looping_conditional(cudaGraphConditionalHandle handle, const bool *active_mask_any) - { - cudaGraphSetConditional(handle, *active_mask_any); - } - """ - return run_nvrtc(kernel_string, b"outer_label_looping_conditional", cls.CUDA_PROGRAM_NAME) - - @classmethod - def _create_inner_while_loop_kernel(cls): - """ - Creates a kernel that evaluates whether to enter the inner loop body (not all non-blank labels found). - Condition: while(advance_mask_any). - """ - kernel_string = r"""\ - typedef __device_builtin__ unsigned long long cudaGraphConditionalHandle; - - extern "C" __device__ __cudart_builtin__ void cudaGraphSetConditional(cudaGraphConditionalHandle handle, unsigned int value); - - extern "C" __global__ - void inner_find_non_blank_conditional(cudaGraphConditionalHandle handle, const bool *advance_mask_any) - { - cudaGraphSetConditional(handle, *advance_mask_any); - } - """ - return run_nvrtc(kernel_string, b"inner_find_non_blank_conditional", cls.CUDA_PROGRAM_NAME) - - def _graph_reinitialize( - self, - encoder_output_projected: torch.Tensor, - ): - batch_size, max_time, encoder_dim = encoder_output_projected.shape - - self.state = LabelLoopingState( - batch_size=batch_size, - max_time=max(max_time, self.INITIAL_MAX_TIME), - encoder_dim=encoder_dim, - max_symbols=self.max_symbols, - device=encoder_output_projected.device, - float_dtype=encoder_output_projected.dtype, - logits_dim=self.joint.num_classes_with_blank, - preserve_alignments=self.preserve_alignments, - preserve_frame_confidence=self.preserve_frame_confidence, - ) - - # init decoder state - self.state.labels.fill_(self._SOS) - decoder_output, new_state, *_ = self.decoder.predict( - self.state.labels.unsqueeze(1), - self.decoder.initialize_state(self.state.encoder_output_projected), - add_sos=False, - batch_size=self.state.batch_size, - ) - self.state.decoder_state_after_sos = new_state - self.state.decoder_state = self.decoder.initialize_state(encoder_output_projected) - self.decoder.batch_replace_states_all( - src_states=self.state.decoder_state_after_sos, dst_states=self.state.decoder_state - ) - # to avoid recalculation of joint projection, store decoder output in state - self.state.decoder_output_after_sos = self.joint.project_prednet(decoder_output) - self.state.decoder_output = self.state.decoder_output_after_sos.clone() - - # init fusion models states and scores - self.state.fusion_states_list = [] - self.state.fusion_states_candidates_list = [] - self.state.fusion_scores_list = [] - device = encoder_output_projected.device - float_dtype = encoder_output_projected.dtype - - self._move_fusion_models_to_device(device=device) - for fusion_model in self._all_fusion_models(): - vocab_size = fusion_model.vocab_size - self.state.fusion_states_list.append( - fusion_model.get_init_states(batch_size=self.state.batch_size, bos=True) - ) - self.state.fusion_states_candidates_list.append( - torch.zeros([batch_size, vocab_size], dtype=torch.long, device=device) - ) - - self.state.fusion_scores_list.append( - torch.zeros([batch_size, vocab_size], dtype=float_dtype, device=device) - ) - - # warmup before graph compilation - if self.cuda_graphs_mode is not self.CudaGraphsMode.NO_GRAPHS: - self._warmup_for_cuda_graphs() - - if self.cuda_graphs_mode is self.CudaGraphsMode.FULL_GRAPH: - try: - self._full_graph_compile() - except NeMoCUDAPythonException as e: - if not self.cuda_graphs_allow_fallback: - raise RuntimeError("Full CUDA graph decoding failed. Mode is forced, raising exception") from e - logging.warning( - f"Full CUDA graph compilation failed: {e}. " - "Falling back to native PyTorch CUDA graphs. Decoding will be slower." - ) - self.cuda_graphs_mode = self.CudaGraphsMode.NO_WHILE_LOOPS - self._partial_graphs_compile() - elif self.cuda_graphs_mode is self.CudaGraphsMode.NO_WHILE_LOOPS: - self._partial_graphs_compile() - elif self.cuda_graphs_mode is self.CudaGraphsMode.NO_GRAPHS: - # no graphs needed - pass - else: - raise NotImplementedError - - def _warmup_for_cuda_graphs(self): - """Warmup before compiling CUDA graphs""" - is_ddp = torch.distributed.is_available() and torch.distributed.is_initialized() - # 11 warmup steps required in DDP mode - # see https://pytorch.org/docs/stable/notes/cuda.html#usage-with-distributeddataparallel - num_runs = 11 if is_ddp else 3 - self.state.encoder_output_projected.fill_(0.0) - self.state.encoder_output_length.fill_(1) - s = torch.cuda.Stream() - s.wait_stream(torch.cuda.current_stream()) - with torch.cuda.stream(s): - for _ in range(num_runs): - self._before_outer_loop() - self._before_inner_loop_get_joint_output() - self._inner_loop_step_find_next_non_blank() - self._after_inner_loop_step() - torch.cuda.current_stream().wait_stream(s) - self.state.encoder_output_length.fill_(0) - - def _partial_graphs_compile(self): - """Compile decoding by parts""" - # Always create a new stream, because the per-thread default stream disallows stream capture to a graph. - stream_for_graph = torch.cuda.Stream(self.state.device) - stream_for_graph.wait_stream(torch.cuda.default_stream(self.state.device)) - self.separate_graphs = SeparateGraphsLabelLooping() - with ( - torch.cuda.stream(stream_for_graph), - torch.inference_mode(), - torch.cuda.graph( - self.separate_graphs.before_outer_loop, stream=stream_for_graph, capture_error_mode="thread_local" - ), - ): - self._before_outer_loop() - - with ( - torch.cuda.stream(stream_for_graph), - torch.inference_mode(), - torch.cuda.graph( - self.separate_graphs.before_inner_loop, stream=stream_for_graph, capture_error_mode="thread_local" - ), - ): - self._before_inner_loop_get_joint_output() - - with ( - torch.cuda.stream(stream_for_graph), - torch.inference_mode(), - torch.cuda.graph( - self.separate_graphs.inner_loop_code, stream=stream_for_graph, capture_error_mode="thread_local" - ), - ): - self._inner_loop_step_find_next_non_blank() - - with ( - torch.cuda.stream(stream_for_graph), - torch.inference_mode(), - torch.cuda.graph( - self.separate_graphs.after_inner_loop, stream=stream_for_graph, capture_error_mode="thread_local" - ), - ): - self._after_inner_loop_step() - - @cuda_python_required - def _full_graph_compile(self): - """Compile full graph for decoding""" - # Always create a new stream, because the per-thread default stream disallows stream capture to a graph. - stream_for_graph = torch.cuda.Stream(self.state.device) - stream_for_graph.wait_stream(torch.cuda.default_stream(self.state.device)) - self.full_graph = torch.cuda.CUDAGraph() - with ( - torch.cuda.stream(stream_for_graph), - torch.inference_mode(), - torch.cuda.graph(self.full_graph, stream=stream_for_graph, capture_error_mode="thread_local"), - ): - self._before_outer_loop() - - # NB: depending on cuda-python version, cudaStreamGetCaptureInfo can return either 5 or 6 elements - capture_status, _, graph, *_ = cu_call( - cudart.cudaStreamGetCaptureInfo(torch.cuda.current_stream(device=self.state.device).cuda_stream) - ) - assert capture_status == cudart.cudaStreamCaptureStatus.cudaStreamCaptureStatusActive - - # capture: while self.active_mask_any: - (outer_loop_conditional_handle,) = cu_call(cudart.cudaGraphConditionalHandleCreate(graph, 0, 0)) - outer_loop_kernel = self._create_outer_while_loop_kernel() - active_mask_any_ptr = np.array([self.state.active_mask_any.data_ptr()], dtype=np.uint64) - outer_loop_args = np.array( - [outer_loop_conditional_handle.getPtr(), active_mask_any_ptr.ctypes.data], - dtype=np.uint64, - ) - - # loop while there are active utterances - # while self.active_mask_any: - with with_conditional_node( - outer_loop_kernel, outer_loop_args, outer_loop_conditional_handle, device=self.state.device - ): - self._before_inner_loop_get_joint_output() - # capture: while self.advance_mask_any.item(): - inner_while_loop_kernel = self._create_inner_while_loop_kernel() - (inner_loop_conditional_handle,) = cu_call(cudart.cudaGraphConditionalHandleCreate(graph, 0, 0)) - advance_mask_any_ptr = np.array([self.state.advance_mask_any.data_ptr()], dtype=np.uint64) - inner_loop_args = np.array( - [ - inner_loop_conditional_handle.getPtr(), - advance_mask_any_ptr.ctypes.data, - ], - dtype=np.uint64, - ) - # while self.advance_mask_any.item(): - with with_conditional_node( - inner_while_loop_kernel, inner_loop_args, inner_loop_conditional_handle, device=self.state.device - ): - self._inner_loop_step_find_next_non_blank() - self._after_inner_loop_step() - - def _init_decoding_state( - self, current_batch_size: int, prev_batched_state: Optional[BatchedLabelLoopingState] = None - ): - # NB: we can speedup the case when prev_batched_state is None by using CUDA graphs - if prev_batched_state is None: - # last found labels - initially () symbol - self.state.labels.fill_(self._SOS) - self.decoder.batch_replace_states_all( - src_states=self.state.decoder_state_after_sos, dst_states=self.state.decoder_state - ) - self.state.decoder_output.copy_(self.state.decoder_output_after_sos) - - # init fusion models states - for fusion_model_idx, fusion_model in enumerate(self._all_fusion_models()): - self.state.fusion_states_list[fusion_model_idx].copy_( - fusion_model.get_init_states(batch_size=self.state.batch_size, bos=True) - ) - else: - # labels - self.state.labels[:current_batch_size].copy_(prev_batched_state.labels[:current_batch_size]) - # initial state - self.decoder.batch_replace_states_all( - src_states=prev_batched_state.predictor_states, - dst_states=self.state.decoder_state, - batch_size=current_batch_size, - ) - self.state.decoder_output[:current_batch_size].copy_( - prev_batched_state.predictor_outputs[:current_batch_size] - ) - - # init fusion models states - for fusion_model_idx, fusion_model in enumerate(self._all_fusion_models()): - self.state.fusion_states_list[fusion_model_idx][:current_batch_size].copy_( - prev_batched_state.fusion_states_list[fusion_model_idx][:current_batch_size] - ) - - def _before_outer_loop(self): - """Clear state and compute initial active mask""" - self.state.batched_hyps.clear_() - if self.state.alignments is not None: - self.state.alignments.clear_() - - self.state.scores.fill_(0.0) - - # time indices - self.state.time_indices.fill_(0) - self.state.safe_time_indices.fill_(0) # safe time indices: guaranteed to be < encoder_output_length - self.state.time_indices_current_labels.fill_(0) - torch.sub(self.state.encoder_output_length, 1, out=self.state.last_timesteps) - - # masks for utterances in batch - # same as: active_mask = self.encoder_output_length > 0 - torch.greater(self.state.encoder_output_length, 0, out=self.state.active_mask) - - # same as: self.active_mask_any = active_mask.any() - torch.any(self.state.active_mask, out=self.state.active_mask_any) - - def _before_inner_loop_get_joint_output(self): - """Get Joint output after decoder output, prepare inner loop to search for all next non-blank labels""" - # stage 1: get joint output, iteratively seeking for non-blank labels - # blank label in `labels` tensor means "end of hypothesis" (for this index) - logits = ( - self.joint.joint_after_projection( - self.state.encoder_output_projected[self.state.batch_indices, self.state.safe_time_indices].unsqueeze( - 1 - ), - self.state.decoder_output, - ) - .squeeze(1) - .squeeze(1) - ) - # same as: scores, labels = logits.max(-1) - torch.max(logits, dim=-1, out=(self.state.scores, self.state.labels)) - - if self.has_fusion_models(): - fusion_scores_list, fusion_states_candidates_list = self.advance_fusion_models( - fusion_states_list=self.state.fusion_states_list, - multi_biasing_ids=self.state.multi_biasing_ids, - float_dtype=self.state.float_dtype, - ) - for fusion_model_idx in range(len(fusion_scores_list)): - # get fusion scores/states - self.state.fusion_states_candidates_list[fusion_model_idx].copy_( - fusion_states_candidates_list[fusion_model_idx] - ) - self.state.fusion_scores_list[fusion_model_idx].copy_(fusion_scores_list[fusion_model_idx]) - # update logits with fusion scores - logits[:, :-1] += fusion_scores_list[fusion_model_idx] - # get labels (greedy) and scores from current logits, replace labels/scores with new - scores_w_fusion, labels_w_fusion = logits[:, :-1].max(dim=-1) - # preserve "blank" / "non-blank" category - torch.where( - self.state.labels == self._blank_index, self.state.labels, labels_w_fusion, out=self.state.labels - ) - torch.where( - self.state.labels == self._blank_index, self.state.scores, scores_w_fusion, out=self.state.scores - ) - - # search for non-blank labels using joint, advancing time indices for blank labels - # checking max_symbols is not needed, since we already forced advancing time indices for such cases - torch.eq(self.state.labels, self._blank_index, out=self.state.blank_mask) - # blank_mask = self.labels == self._blank_index - self.state.time_indices_current_labels.copy_(self.state.time_indices) - if self.state.alignments is not None: - self.state.alignments.add_results_masked_no_checks_( - active_mask=self.state.active_mask, - time_indices=self.state.time_indices_current_labels, - logits=logits if self.preserve_alignments else None, - labels=self.state.labels if self.preserve_alignments else None, - confidence=self._get_frame_confidence(logits=logits), - ) - - # advance_mask is a mask for current batch for searching non-blank labels; - # each element is True if non-blank symbol is not yet found AND we can increase the time index - self.state.time_indices.add_(self.state.blank_mask) - torch.minimum(self.state.time_indices, self.state.last_timesteps, out=self.state.safe_time_indices) - torch.less(self.state.time_indices, self.state.encoder_output_length, out=self.state.active_mask) - torch.logical_and(self.state.active_mask, self.state.blank_mask, out=self.state.advance_mask) - - # inner loop: find next non-blank labels (if exist) - # same as: self.advance_mask_any = advance_mask.any() - torch.any(self.state.advance_mask, out=self.state.advance_mask_any) - - def _inner_loop_step_find_next_non_blank(self): - """Find next non-blank labels - one iteration""" - # same as: time_indices_current_labels[advance_mask] = time_indices[advance_mask], but non-blocking - # store current time indices to use further for storing the results - torch.where( - self.state.advance_mask, - self.state.time_indices, - self.state.time_indices_current_labels, - out=self.state.time_indices_current_labels, - ) - logits = ( - self.joint.joint_after_projection( - self.state.encoder_output_projected[self.state.batch_indices, self.state.safe_time_indices].unsqueeze( - 1 - ), - self.state.decoder_output, - ) - .squeeze(1) - .squeeze(1) - ) - # get labels (greedy) and scores from current logits, replace labels/scores with new - # labels[advance_mask] are blank, and we are looking for non-blank labels - more_scores, more_labels = logits.max(-1) - - if self.has_fusion_models(): - for fusion_model_idx, fusion_scores in enumerate(self.state.fusion_scores_list): - # update logits with fusion scores - logits[:, :-1] += fusion_scores - # # get labels (greedy) and scores from current logits, replace labels/scores with new - more_scores_w_fusion, more_labels_w_fusion = logits[:, :-1].max(dim=-1) - # preserve "blank" / "non-blank" category - torch.where(more_labels == self._blank_index, more_labels, more_labels_w_fusion, out=more_labels) - torch.where(more_labels == self._blank_index, more_scores, more_scores_w_fusion, out=more_scores) - - # same as: labels[advance_mask] = more_labels[advance_mask], but non-blocking - torch.where(self.state.advance_mask, more_labels, self.state.labels, out=self.state.labels) - # same as: scores[advance_mask] = more_scores[advance_mask], but non-blocking - torch.where(self.state.advance_mask, more_scores, self.state.scores, out=self.state.scores) - - if self.state.alignments is not None: - self.state.alignments.add_results_masked_no_checks_( - active_mask=self.state.advance_mask, - time_indices=self.state.time_indices_current_labels, - logits=logits if self.preserve_alignments else None, - labels=more_labels if self.preserve_alignments else None, - confidence=self._get_frame_confidence(logits=logits), - ) - - # blank_mask = self.labels == self._blank_index - torch.eq(self.state.labels, self._blank_index, out=self.state.blank_mask) - # self.time_indices += self.blank_mask - self.state.time_indices.add_(self.state.blank_mask) - - torch.minimum(self.state.time_indices, self.state.last_timesteps, out=self.state.safe_time_indices) - torch.less(self.state.time_indices, self.state.encoder_output_length, out=self.state.active_mask) - torch.logical_and(self.state.active_mask, self.state.blank_mask, out=self.state.advance_mask) - torch.any(self.state.advance_mask, out=self.state.advance_mask_any) - - def _after_inner_loop_step(self): - """After inner loop: store labels, query decoder/fusion models, force max symbols""" - self._after_inner_loop_store_labels() - self._after_inner_loop_select_fusion_states() - self._after_inner_loop_get_decoder_output() - self._after_inner_loop_force_max_symbols() - - def _after_inner_loop_store_labels(self): - """Stage 3.1: Store hypotheses, update decoder state""" - self.state.batched_hyps.add_results_masked_no_checks_( - active_mask=self.state.active_mask, - labels=self.state.labels, - time_indices=self.state.time_indices_current_labels, - scores=self.state.scores, - ) - - def _after_inner_loop_select_fusion_states(self): - """Stage 3.2: Select fusion states with new labels""" - for fusion_model_idx, fusion_states_candidates in enumerate(self.state.fusion_states_candidates_list): - # select necessary fusion states based on chosen labels - torch.where( - self.state.active_mask, - fusion_states_candidates[self.state.batch_indices, self.state.labels * self.state.active_mask], - self.state.fusion_states_list[fusion_model_idx], - out=self.state.fusion_states_list[fusion_model_idx], - ) - - def _after_inner_loop_get_decoder_output(self): - """Stage 3.3: Get decoder (prediction network) output using new labels""" - decoder_output, new_state, *_ = self.decoder.predict( - self.state.labels.unsqueeze(1), self.state.decoder_state, add_sos=False, batch_size=self.state.batch_size - ) - self.decoder.batch_replace_states_mask( - src_states=new_state, dst_states=self.state.decoder_state, mask=self.state.active_mask - ) - decoder_output_projected = self.joint.project_prednet(decoder_output) # do not recalculate joint projection - torch.where( - self.state.active_mask.unsqueeze(-1).unsqueeze(-1), - decoder_output_projected, - self.state.decoder_output, - out=self.state.decoder_output, - ) - - def _after_inner_loop_force_max_symbols(self): - """Stage 4: to avoid looping, go to next frame after max_symbols emission""" - # if labels are non-blank (not end-of-utterance), check that last observed timestep with label: - # if it is equal to the current time index, and number of observations is >= max_symbols, force blank - force_blank_mask = torch.logical_and( - self.state.active_mask, - torch.logical_and( - torch.logical_and( - self.state.labels != self._blank_index, - self.state.batched_hyps.last_timestamp_lasts >= self.max_symbols, - ), - self.state.batched_hyps.last_timestamp == self.state.time_indices, - ), - ) - self.state.time_indices.add_(force_blank_mask) # emit blank => advance time indices - # update safe_time_indices, non-blocking - torch.minimum(self.state.time_indices, self.state.last_timesteps, out=self.state.safe_time_indices) - # same as: active_mask = time_indices < encoder_output_length - torch.less(self.state.time_indices, self.state.encoder_output_length, out=self.state.active_mask) - torch.any(self.state.active_mask, out=self.state.active_mask_any) - - def _fix_timestamps_for_iterative_decoding( - self, current_batch_size: int, prev_batched_state: BatchedLabelLoopingState - ): - """ - Fix timestamps: if we are in iterative decoding mode, - we need to add the length of the previous batch to current timestamps - """ - self.state.batched_hyps.timestamps[:current_batch_size] += prev_batched_state.decoded_lengths[ - :current_batch_size - ].unsqueeze(1) - if self.state.alignments is not None: - self.state.alignments.timestamps[:current_batch_size] -= prev_batched_state.decoded_lengths[ - :current_batch_size - ].unsqueeze(1) diff --git a/nemo/collections/asr/parts/submodules/transducer_decoding/tdt_label_looping.py b/nemo/collections/asr/parts/submodules/transducer_decoding/tdt_label_looping.py deleted file mode 100644 index 52aa71e98f3ef03fc68f8264573d8289bd3689ca..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/transducer_decoding/tdt_label_looping.py +++ /dev/null @@ -1,1373 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from typing import Any, List, Optional - -import numpy as np -import torch -import torch.nn.functional as F -from omegaconf import DictConfig, ListConfig - -from nemo.collections.asr.parts.context_biasing.biasing_multi_model import GPUBiasingMultiModel -from nemo.collections.asr.parts.submodules.ngram_lm import NGramGPULanguageModel -from nemo.collections.asr.parts.submodules.transducer_decoding.label_looping_base import ( - BatchedLabelLoopingState, - GreedyBatchedLabelLoopingComputerBase, - LabelLoopingStateItem, - SeparateGraphsLabelLooping, -) -from nemo.collections.asr.parts.utils import rnnt_utils -from nemo.collections.asr.parts.utils.asr_confidence_utils import ConfidenceMethodMixin -from nemo.core.utils.cuda_python_utils import NeMoCUDAPythonException, cu_call, run_nvrtc, with_conditional_node -from nemo.core.utils.optional_libs import CUDA_PYTHON_AVAILABLE, cuda_python_required -from nemo.utils import logging - -if CUDA_PYTHON_AVAILABLE: - from cuda.bindings import runtime as cudart - - -class LabelLoopingState: - """ - State for Loop Labels algorithm. Used only with CUDA graphs. - In initialization phase it is possible to assign values (tensors) to the state. - For algorithm code the storage should be reused (prefer copy data instead of assigning tensors). - """ - - max_time: int # maximum length of internal storage for time dimension - batch_size: int # (maximum) length of internal storage for batch dimension - device: torch.device # device to store preallocated tensors - - model_durations: torch.Tensor - - encoder_output_projected: torch.Tensor # projected output from the encoder for decoding algorithm - encoder_output_length: torch.Tensor # length of the (projected) output from the encoder - - labels: torch.Tensor # storage for current labels - scores: torch.Tensor # storage for current scores - durations: torch.Tensor # storage for current predicted durations - - batch_indices: torch.Tensor # indices of elements in batch (constant, range [0, batch_size-1]) - - time_indices: torch.Tensor # current time indices for each element in batch - safe_time_indices: torch.Tensor # current time indices, but guaranteed to be < encoder_output_length - time_indices_current_labels: torch.Tensor # time indices for found labels (corresponding to `labels` field) - last_timesteps: torch.Tensor # indices of the last timesteps for each element (encoder_output_length - 1) - - active_mask: torch.Tensor # mask for active hypotheses (the decoding is finished for the utterance if it is False) - advance_mask: torch.Tensor # mask for "advancing" hypotheses (blank is found for the element on the current step) - blank_mask: torch.Tensor # if the element is blank - active_mask_prev: torch.Tensor # if the element was active on the previous step - found_labels_mask: torch.Tensor # mask for found labels (non-blank) - - active_mask_any: torch.Tensor # 0-dim bool tensor, condition for outer loop ('any element is still active') - advance_mask_any: torch.Tensor # 0-dim bool tensor, condition for inner loop ('should advance any index') - - decoder_state: Any # current decoder state - decoder_output: torch.Tensor # output from the decoder (projected) - - decoder_state_after_sos: Any # decoder state after _SOS symbol (for initialization) - decoder_output_after_sos: ( - torch.Tensor - ) # output from the decoder (projected) after _SOS symbol (for initialization) - - batched_hyps: rnnt_utils.BatchedHyps # batched hypotheses - decoding result - alignments: Optional[rnnt_utils.BatchedAlignments] = None # batched alignments - - # for fusion models - fusion_states_list: list[torch.Tensor] - fusion_states_candidates_list: list[torch.Tensor] - fusion_scores_list: list[torch.Tensor] - multi_biasing_ids: torch.Tensor - - def __init__( - self, - batch_size: int, - max_time: int, - encoder_dim: int, - max_symbols: int, - device: torch.device, - float_dtype: torch.dtype, - logits_dim: int, - preserve_alignments=False, - preserve_frame_confidence=False, - include_duration_confidence: bool = False, - include_duration: bool = False, - ): - """ - - Args: - batch_size: batch size for encoder output storage - max_time: maximum time for encoder output storage - encoder_dim: last dimension for encoder output storage (projected encoder output) - max_symbols: max symbols per step (to avoid infinite looping and pre-allocate storage) - device: device to store tensors - float_dtype: default float dtype for tensors (should match projected encoder output) - logits_dim: output dimension for Joint - preserve_alignments: if alignments are needed - preserve_frame_confidence: if frame confidence is needed - include_duration_confidence: if duration confidence is needed to be added to the frame confidence - include_duration: if predicted token durations are needed to be added to the Hypothesis object - """ - self.device = device - self.float_dtype = float_dtype - self.batch_size = batch_size - self.max_time = max_time - self.include_duration = include_duration - - self.encoder_output_projected = torch.zeros( - (self.batch_size, self.max_time, encoder_dim), - dtype=float_dtype, - device=self.device, - ) - self.encoder_output_length = torch.zeros((self.batch_size,), dtype=torch.long, device=self.device) - - self.labels = torch.zeros([self.batch_size], dtype=torch.long, device=self.device) - self.scores = torch.zeros([self.batch_size], dtype=float_dtype, device=self.device) - - # indices of elements in batch (constant) - self.batch_indices = torch.arange(self.batch_size, dtype=torch.long, device=self.device) - - self.time_indices = torch.zeros_like(self.batch_indices) - self.safe_time_indices = torch.zeros_like(self.batch_indices) - self.time_indices_current_labels = torch.zeros_like(self.time_indices) - self.last_timesteps = torch.zeros_like(self.time_indices) - self.durations = torch.zeros([self.batch_size], dtype=torch.long, device=self.device) - - self.active_mask = torch.zeros([self.batch_size], dtype=torch.bool, device=self.device) - self.advance_mask = torch.zeros_like(self.active_mask) - self.blank_mask = torch.zeros_like(self.active_mask) - self.active_mask_prev = torch.zeros_like(self.active_mask) - self.found_labels_mask = torch.zeros_like(self.active_mask) - - self.active_mask_any = torch.tensor(True, device=self.device, dtype=torch.bool) - self.advance_mask_any = torch.tensor(True, device=self.device, dtype=torch.bool) - - self.multi_biasing_ids = torch.full([self.batch_size], fill_value=-1, dtype=torch.long, device=self.device) - self.fusion_states_list = [] - self.fusion_states_candidates_list = [] - self.fusion_scores_list = [] - self.batched_hyps = rnnt_utils.BatchedHyps( - batch_size=self.batch_size, - init_length=self.max_time * max_symbols, - device=self.device, - float_dtype=float_dtype, - is_with_durations=include_duration, - ) - if preserve_alignments or preserve_frame_confidence: - self.alignments = rnnt_utils.BatchedAlignments( - batch_size=batch_size, - logits_dim=logits_dim, - init_length=max_time * (max_symbols + 1), - device=self.device, - float_dtype=self.float_dtype, - store_alignments=preserve_alignments, - store_frame_confidence=preserve_frame_confidence, - with_duration_confidence=include_duration_confidence, - ) - else: - self.alignments = None - - def need_reinit(self, encoder_output_projected: torch.Tensor) -> bool: - """Check if need to reinit state: larger batch_size/max_time, or new device""" - return ( - self.batch_size < encoder_output_projected.shape[0] - or self.max_time < encoder_output_projected.shape[1] - or self.device.index != encoder_output_projected.device.index - ) - - -class GreedyBatchedTDTLabelLoopingComputer(GreedyBatchedLabelLoopingComputerBase, ConfidenceMethodMixin): - """ - Label-Looping algorithm implementation https://arxiv.org/abs/2406.06220 for optimized batched greedy decoding. - Iterates over labels, on each step finding the next non-blank label - (evaluating Joint multiple times in inner loop); It uses a minimal possible amount of calls - to prediction network (with maximum possible batch size), - which makes it especially useful for scaling the prediction network. - During decoding all active hypotheses ("texts") have the same lengths. - """ - - INITIAL_MAX_TIME = 375 # initial max time, used to init state for Cuda graphs - CUDA_PROGRAM_NAME = b"while_label_looping_conditional_tdt.cu" - - separate_graphs: Optional[SeparateGraphsLabelLooping] - full_graph: Optional[torch.cuda.CUDAGraph] - state: Optional[LabelLoopingState] - fusion_models: Optional[List[NGramGPULanguageModel]] - - def __init__( - self, - decoder, - joint, - blank_index: int, - durations: list[int] | ListConfig[int], - max_symbols_per_step: Optional[int] = None, - preserve_alignments=False, - preserve_frame_confidence=False, - include_duration: bool = False, - include_duration_confidence: bool = False, - confidence_method_cfg: Optional[DictConfig] = None, - allow_cuda_graphs: bool = True, - fusion_models: Optional[List[NGramGPULanguageModel]] = None, - fusion_models_alpha: Optional[List[float]] = None, - enable_per_stream_biasing: bool = False, - ): - """ - Init method. - Args: - decoder: Prediction network from RNN-T - joint: Joint module from RNN-T - blank_index: index of blank symbol - durations: list of TDT durations, e.g., [0, 1, 2, 4, 8] - max_symbols_per_step: max symbols to emit on each step (to avoid infinite looping) - preserve_alignments: if alignments are needed - preserve_frame_confidence: if frame confidence is needed - include_duration: if predicted token durations are needed to be added to the Hypothesis object - include_duration_confidence: if duration confidence is needed to be added to the frame confidence - confidence_method_cfg: config for the confidence - fusion_models: list of fusion models (ngram_lm_model and boosting_tree_model) - fusion_models_alpha: list of fusion model weights (ngram_lm_alpha and boosting_tree_alpha) - enable_per_stream_biasing: enable multi-biasing model for per-stream customization - """ - super().__init__() - self.decoder = decoder - self.joint = joint - # keep durations on CPU to avoid side effects in multi-gpu environment - self.durations = torch.tensor(list(durations), device="cpu").to(torch.long) - self._blank_index = blank_index - self.max_symbols = max_symbols_per_step - self.preserve_alignments = preserve_alignments - self.preserve_frame_confidence = preserve_frame_confidence - self.preserve_alignments = preserve_alignments or preserve_frame_confidence - self.include_duration = include_duration - self.include_duration_confidence = include_duration_confidence - self._SOS = self._blank_index - self._init_confidence_method(confidence_method_cfg=confidence_method_cfg) - assert self._SOS == self._blank_index # "blank as pad" algorithm only - - self.fusion_models = fusion_models or [] - self.fusion_models_alpha = fusion_models_alpha or [] - - self.biasing_multi_model = ( - GPUBiasingMultiModel(vocab_size=self._blank_index, reallocation_callback_fn=self.reset_cuda_graphs_state) - if enable_per_stream_biasing - else None - ) - - if allow_cuda_graphs: - for fusion_model in self._all_fusion_models(): - if not fusion_model.compatible_with_cuda_graphs(): - logging.warning( - "Fusion model used that is incompatible with CUDA graphs." - " Switching off CUDA graphs, decoding may be slow." - ) - allow_cuda_graphs = False - break - - self.allow_cuda_graphs = allow_cuda_graphs - - self.state = None - self.full_graph = None - self.separate_graphs = None - - self.cuda_graphs_mode = None - self.cuda_graphs_allow_fallback = True - self.maybe_enable_cuda_graphs() - - def reset_cuda_graphs_state(self): - """Reset state to release memory (for CUDA graphs implementations)""" - self.state = None - self.full_graph = None - self.separate_graphs = None - - def _get_frame_confidence(self, logits: torch.Tensor, num_durations: int) -> Optional[torch.Tensor]: - float_dtype = logits.dtype - return ( - torch.stack( - ( - self._get_confidence_tensor(F.log_softmax(logits[:, :-num_durations], dim=-1)).to( - dtype=float_dtype - ), - self._get_confidence_tensor(F.log_softmax(logits[:, -num_durations:], dim=-1)).to( - dtype=float_dtype - ), - ), - dim=-1, - ) - if self.include_duration_confidence - else ( - self._get_confidence_tensor(F.log_softmax(logits[:, :-num_durations], dim=-1)).to(dtype=float_dtype) - if self.preserve_frame_confidence - else None - ) - ) - - def torch_impl( - self, - encoder_output: torch.Tensor, - encoder_output_length: torch.Tensor, - prev_batched_state: Optional[BatchedLabelLoopingState] = None, - multi_biasing_ids: Optional[torch.Tensor] = None, - ) -> tuple[rnnt_utils.BatchedHyps, Optional[rnnt_utils.BatchedAlignments], BatchedLabelLoopingState]: - """ - Pure PyTorch implementation - - Args: - encoder_output: output from the encoder - encoder_output_length: lengths of the utterances in `encoder_output` - prev_batched_state: previous batched decoding state - multi_biasing_ids: optional tensor [Batch] with ids of multi-biasing models - """ - batch_size, max_time, _unused = encoder_output.shape - device = encoder_output.device - self._move_fusion_models_to_device(device=device) - if self.biasing_multi_model is not None and multi_biasing_ids is None: - multi_biasing_ids = torch.full([batch_size], fill_value=-1, dtype=torch.long, device=device) - - # do not recalculate joint projection, project only once - encoder_output_projected = self.joint.project_encoder(encoder_output) - float_dtype = encoder_output_projected.dtype - - # init output structures: BatchedHyps (for results), BatchedAlignments + last decoder state - # init empty batched hypotheses - batched_hyps = rnnt_utils.BatchedHyps( - batch_size=batch_size, - init_length=max_time * self.max_symbols if self.max_symbols is not None else max_time, - device=device, - float_dtype=float_dtype, - is_with_durations=self.include_duration, - ) - # init alignments if necessary - use_alignments = self.preserve_alignments or self.preserve_frame_confidence - # always use alignments variable - for torch.jit adaptation, but keep it as minimal as possible - alignments = rnnt_utils.BatchedAlignments( - batch_size=batch_size, - logits_dim=self.joint.num_classes_with_blank, - init_length=max_time * 2 if use_alignments else 1, # blank for each timestep + text tokens - device=device, - float_dtype=float_dtype, - store_alignments=self.preserve_alignments, - store_frame_confidence=self.preserve_frame_confidence, - with_duration_confidence=self.include_duration_confidence, - ) - - # durations - model_durations = self.durations.to(device, non_blocking=True) - num_durations = model_durations.shape[0] - - # indices of elements in batch (constant) - batch_indices = torch.arange(batch_size, dtype=torch.long, device=device) - - # time indices - last_timesteps = torch.maximum(encoder_output_length - 1, torch.zeros_like(encoder_output_length)) - time_indices = ( - torch.zeros_like(batch_indices) if prev_batched_state is None else prev_batched_state.time_jumps.clone() - ) - safe_time_indices = torch.minimum(time_indices, last_timesteps) # time indices, guaranteed to be < out_len - time_indices_current_labels = torch.zeros_like(time_indices) - - # masks for utterances in batch - active_mask: torch.Tensor = time_indices < encoder_output_length - active_mask_prev = active_mask.clone() - advance_mask = torch.empty_like(active_mask) - - if prev_batched_state is None: - # initial state, needed for torch.jit to compile (cannot handle None) - state = self.decoder.initialize_state(encoder_output_projected) - # last found labels - initially () symbol - labels = torch.full_like(batch_indices, fill_value=self._SOS) - decoder_output, state, *_ = self.decoder.predict( - labels.unsqueeze(1), state, add_sos=False, batch_size=batch_size - ) - decoder_output = self.joint.project_prednet(decoder_output) # do not recalculate joint projection - - # fusion models - fusion_states_list = [] - for fusion_model in self._all_fusion_models(): - fusion_states_list.append(fusion_model.get_init_states(batch_size=batch_size, bos=True)) - else: - decoder_output = prev_batched_state.predictor_outputs - state = prev_batched_state.predictor_states - fusion_states_list = prev_batched_state.fusion_states_list - - fusion_scores_list, fusion_states_candidates_list = [], [] - - # loop while there are active utterances - while active_mask.any(): - # stage 1: get joint output, iteratively seeking for non-blank labels - # blank label in `labels` tensor means "end of hypothesis" (for this index) - active_mask_prev.copy_(active_mask) - - # stage 1.1: get first joint output - logits = ( - self.joint.joint_after_projection( - encoder_output_projected[batch_indices, safe_time_indices].unsqueeze(1), - decoder_output, - ) - .squeeze(1) - .squeeze(1) - ) - scores, labels = logits[:, :-num_durations].max(dim=-1) - - if self.has_fusion_models(): - fusion_scores_list, fusion_states_candidates_list = self.advance_fusion_models( - fusion_states_list=fusion_states_list, - multi_biasing_ids=multi_biasing_ids, - float_dtype=float_dtype, - ) - logits_with_fusion = logits.clone() - for fusion_scores in fusion_scores_list: - logits_with_fusion[:, : -num_durations - 1] += fusion_scores - - # get max scores and labels without blank - fusion_scores_max, fusion_labels_max = logits_with_fusion[:, : -num_durations - 1].max(dim=-1) - # preserve "blank" / "non-blank" category - torch.where(labels == self._blank_index, labels, fusion_labels_max, out=labels) - torch.where(labels == self._blank_index, scores, fusion_scores_max, out=scores) - - jump_durations_indices = logits[:, -num_durations:].argmax(dim=-1) - durations = model_durations[jump_durations_indices] - - # search for non-blank labels using joint, advancing time indices for blank labels - # checking max_symbols is not needed, since we already forced advancing time indices for such cases - blank_mask = labels == self._blank_index - # for blank labels force duration >= 1 - durations.masked_fill_(torch.logical_and(durations == 0, blank_mask), 1) - time_indices_current_labels.copy_(time_indices) - if use_alignments: - alignments.add_results_masked_( - active_mask=active_mask, - time_indices=time_indices_current_labels, - logits=logits if self.preserve_alignments else None, - labels=labels if self.preserve_alignments else None, - confidence=self._get_frame_confidence(logits=logits, num_durations=num_durations), - ) - - # advance_mask is a mask for current batch for searching non-blank labels; - # each element is True if non-blank symbol is not yet found AND we can increase the time index - time_indices += durations * active_mask - torch.minimum(time_indices, last_timesteps, out=safe_time_indices) - torch.less(time_indices, encoder_output_length, out=active_mask) - torch.logical_and(active_mask, blank_mask, out=advance_mask) - - # stage 1.2: inner loop - find next non-blank labels (if exist) - while advance_mask.any(): - # same as: time_indices_current_labels[advance_mask] = time_indices[advance_mask], but non-blocking - # store current time indices to use further for storing the results - torch.where(advance_mask, time_indices, time_indices_current_labels, out=time_indices_current_labels) - logits = ( - self.joint.joint_after_projection( - encoder_output_projected[batch_indices, safe_time_indices].unsqueeze(1), - decoder_output, - ) - .squeeze(1) - .squeeze(1) - ) - # get labels (greedy) and scores from current logits, replace labels/scores with new - # labels[advance_mask] are blank, and we are looking for non-blank labels - more_scores, more_labels = logits[:, :-num_durations].max(dim=-1) - - if self.has_fusion_models(): - logits_with_fusion = logits.clone() - for fusion_scores in fusion_scores_list: - logits_with_fusion[:, : -num_durations - 1] += fusion_scores - # get max scores and labels without blank - more_scores_w_fusion, more_labels_w_fusion = logits_with_fusion[:, : -num_durations - 1].max( - dim=-1 - ) - # preserve "blank" / "non-blank" category - torch.where(more_labels == self._blank_index, more_labels, more_labels_w_fusion, out=more_labels) - - # same as: labels[advance_mask] = more_labels[advance_mask], but non-blocking - torch.where(advance_mask, more_labels, labels, out=labels) - # same as: scores[advance_mask] = more_scores[advance_mask], but non-blocking - torch.where(advance_mask, more_scores, scores, out=scores) - jump_durations_indices = logits[:, -num_durations:].argmax(dim=-1) - durations = model_durations[jump_durations_indices] - - if use_alignments: - alignments.add_results_masked_( - active_mask=advance_mask, - time_indices=time_indices_current_labels, - logits=logits if self.preserve_alignments else None, - labels=more_labels if self.preserve_alignments else None, - confidence=self._get_frame_confidence(logits=logits, num_durations=num_durations), - ) - - blank_mask = labels == self._blank_index - # for blank labels force duration >= 1 - durations.masked_fill_(torch.logical_and(durations == 0, blank_mask), 1) - # same as time_indices[advance_mask] += durations[advance_mask], but non-blocking - torch.where(advance_mask, time_indices + durations, time_indices, out=time_indices) - torch.minimum(time_indices, last_timesteps, out=safe_time_indices) - torch.less(time_indices, encoder_output_length, out=active_mask) - torch.logical_and(active_mask, blank_mask, out=advance_mask) - - # NB: difference between RNN-T and TDT here, at the end of utterance: - # For RNN-T, if we found a non-blank label, the utterance is active (need to find blank to stop decoding) - # For TDT, we could find a non-blank label, add duration, and the utterance may become inactive - found_labels_mask = torch.logical_and(active_mask_prev, labels != self._blank_index) - # store hypotheses - if self.max_symbols is not None: - # pre-allocated memory, no need for checks - batched_hyps.add_results_masked_no_checks_( - active_mask=found_labels_mask, - labels=labels, - time_indices=time_indices_current_labels, - scores=scores, - token_durations=durations if self.include_duration else None, - ) - else: - # auto-adjusted storage - batched_hyps.add_results_masked_( - active_mask=found_labels_mask, - labels=labels, - time_indices=time_indices_current_labels, - scores=scores, - token_durations=durations if self.include_duration else None, - ) - - # stage 3: get decoder (prediction network) output with found labels - # NB: if active_mask is False, this step is redundant; - # but such check will require device-to-host synchronization, so we avoid it - # preserve state/decoder_output for inactive elements - prev_state = state - prev_decoder_output = decoder_output - decoder_output, state, *_ = self.decoder.predict( - labels.unsqueeze(1), state, add_sos=False, batch_size=batch_size - ) - decoder_output = self.joint.project_prednet(decoder_output) # do not recalculate joint projection - - # preserve correct states/outputs for inactive elements - self.decoder.batch_replace_states_mask( - src_states=prev_state, - dst_states=state, - mask=~found_labels_mask, - ) - torch.where( - found_labels_mask.unsqueeze(-1).unsqueeze(-1), decoder_output, prev_decoder_output, out=decoder_output - ) - - for fusion_states, fusion_states_candidates in zip(fusion_states_list, fusion_states_candidates_list): - torch.where( - found_labels_mask, - fusion_states_candidates[batch_indices, labels * found_labels_mask], - fusion_states, - out=fusion_states, - ) - - # stage 4: to avoid infinite looping, go to the next frame after max_symbols emission - if self.max_symbols is not None: - # if labels are non-blank (not end-of-utterance), check that last observed timestep with label: - # if it is equal to the current time index, and number of observations is >= max_symbols, force blank - force_blank_mask = torch.logical_and( - active_mask, - torch.logical_and( - torch.logical_and( - labels != self._blank_index, - batched_hyps.last_timestamp_lasts >= self.max_symbols, - ), - batched_hyps.last_timestamp == time_indices, - ), - ) - time_indices += force_blank_mask # emit blank => advance time indices - # update safe_time_indices, non-blocking - torch.minimum(time_indices, last_timesteps, out=safe_time_indices) - # same as: active_mask = time_indices < encoder_output_length - torch.less(time_indices, encoder_output_length, out=active_mask) - - # fix timestamps for iterative decoding - if prev_batched_state is not None: - batched_hyps.timestamps += prev_batched_state.decoded_lengths.unsqueeze(1) - if use_alignments: - alignments.timestamps += prev_batched_state.decoded_lengths.unsqueeze(1) - # NB: last labels can not exist (nothing decoded on this step). - # return the last labels from the previous state in this case - last_labels = batched_hyps.get_last_labels(pad_id=self._SOS) - decoding_state = BatchedLabelLoopingState( - predictor_states=state, - predictor_outputs=decoder_output, - labels=( - torch.where(last_labels == self._SOS, prev_batched_state.labels, last_labels) - if prev_batched_state is not None - else last_labels - ), - decoded_lengths=( - encoder_output_length.clone() - if prev_batched_state is None - else encoder_output_length + prev_batched_state.decoded_lengths - ), - fusion_states_list=fusion_states_list, - time_jumps=time_indices - encoder_output_length, - ) - if use_alignments: - return batched_hyps, alignments, decoding_state - return batched_hyps, None, decoding_state - - def _get_decoding_state_item_after_sos(self, device: torch.device | str) -> LabelLoopingStateItem: - """Get decoding state item after symbol, used for initialization from empty hypotheses.""" - batched_state = self._get_batched_decoding_state_after_sos(device=device, batch_size=1) - return self.split_batched_state(batched_state)[0] - - def _get_batched_decoding_state_after_sos( - self, device: torch.device | str, batch_size: int - ) -> BatchedLabelLoopingState: - """Get batched decoding state after symbol, used for initialization from empty hypotheses.""" - labels = torch.full([batch_size], fill_value=self._SOS, dtype=torch.long, device=device) - decoder_output, state, *_ = self.decoder.predict( - labels.unsqueeze(1), None, add_sos=False, batch_size=batch_size - ) - decoder_output = self.joint.project_prednet(decoder_output) # do not recalculate joint projection - state = BatchedLabelLoopingState( - predictor_states=state, - predictor_outputs=decoder_output, - labels=labels, - decoded_lengths=torch.zeros([batch_size], dtype=torch.long, device=device), - fusion_states_list=( - [ - fusion_model.get_init_states(batch_size=batch_size, bos=True).to(device) - for fusion_model in self._all_fusion_models() - ] - ), - time_jumps=torch.zeros([batch_size], dtype=torch.long, device=device), - ) - return state - - def reset_state_by_mask(self, state: BatchedLabelLoopingState, mask: torch.Tensor) -> BatchedLabelLoopingState: - """ - Reset state for masked elements in the batched state. - This is used to reset state for elements that are not active anymore to start a new decoding session. - - Args: - state: batched decoding state - mask: mask for elements to reset - """ - state_after_sos = self._get_batched_decoding_state_after_sos( - device=state.predictor_outputs.device, batch_size=state.labels.shape[0] - ) - self.decoder.batch_replace_states_mask( - src_states=state_after_sos.predictor_states, dst_states=state.predictor_states, mask=mask - ) - torch.where( - mask[:, None, None], - state_after_sos.predictor_outputs, - state.predictor_outputs, - out=state.predictor_outputs, - ) - torch.where(mask, state_after_sos.labels, state.labels, out=state.labels) - torch.where(mask, state_after_sos.decoded_lengths, state.decoded_lengths, out=state.decoded_lengths) - for fusion_idx, fusion_states in enumerate(state.fusion_states_list): - torch.where( - mask, - state_after_sos.fusion_states_list[fusion_idx], - fusion_states, - out=state.fusion_states_list[fusion_idx], - ) - torch.where(mask, state_after_sos.time_jumps, state.time_jumps, out=state.time_jumps) - return state - - def split_batched_state(self, state: BatchedLabelLoopingState) -> list[LabelLoopingStateItem]: - """ - Split batched state into list of items, each item contains state for one hypothesis. - This is used to pass state between invocations of the algorithm. - - Args: - state: batched decoding state - """ - state_items: list[LabelLoopingStateItem] = [] - for i, predictor_state in enumerate(self.decoder.batch_split_states(state.predictor_states)): - state_items.append( - LabelLoopingStateItem( - predictor_state=predictor_state, - predictor_output=state.predictor_outputs[i], - label=state.labels[i], - decoded_length=state.decoded_lengths[i], - fusion_state_list=([fusion_state[i] for fusion_state in state.fusion_states_list]), - time_jump=state.time_jumps[i], - ) - ) - return state_items - - def merge_to_batched_state(self, state_items: list[LabelLoopingStateItem | None]) -> BatchedLabelLoopingState: - """ - Merge list of items into batched state, each item contains state for one hypothesis. - This is used to pass state between invocations of the algorithm. - - Args: - state_items: list of items to merge - """ - if any(item is None for item in state_items): - not_none_item = next(item for item in state_items if item is not None) - assert not_none_item is not None - device = not_none_item.predictor_output.device - start_item = self._get_decoding_state_item_after_sos(device=device) - for i, item in enumerate(state_items): - if item is None: - state_items[i] = start_item - - fusion_states_list = [] - for fusion_idx in range(len(self._all_fusion_models())): - fusion_states_list.append(torch.stack([item.fusion_state_list[fusion_idx] for item in state_items])) - - batched_state = BatchedLabelLoopingState( - predictor_states=self.decoder.batch_unsplit_states([item.predictor_state for item in state_items]), - predictor_outputs=torch.stack([item.predictor_output for item in state_items]), - labels=torch.stack([item.label for item in state_items]), - decoded_lengths=torch.stack([item.decoded_length for item in state_items]), - fusion_states_list=fusion_states_list, - time_jumps=torch.stack([item.time_jump for item in state_items]), - ) - return batched_state - - def cuda_graphs_impl( - self, - encoder_output: torch.Tensor, - encoder_output_length: torch.Tensor, - prev_batched_state: Optional[BatchedLabelLoopingState] = None, - multi_biasing_ids: Optional[torch.Tensor] = None, - ) -> tuple[rnnt_utils.BatchedHyps, Optional[rnnt_utils.BatchedAlignments], BatchedLabelLoopingState]: - """ - Implementation with CUDA graphs. - - Args: - encoder_output: output from the encoder - encoder_output_length: lengths of the utterances in `encoder_output` - prev_batched_state: previous batched decoding state - multi_biasing_ids: optional tensor [Batch] with ids of multi-biasing models - """ - assert self.cuda_graphs_mode is not None - device = encoder_output.device - - # do not recalculate joint projection, project only once - encoder_output = self.joint.project_encoder(encoder_output) - current_batch_size = encoder_output.shape[0] - current_max_time = encoder_output.shape[1] - - if torch.is_autocast_enabled(): - encoder_output = encoder_output.to(torch.get_autocast_gpu_dtype()) - else: - # since autocast could be enabled outside and disallowed here, - # we need to cast encoder output to dtype of params - float_dtype = next(self.joint.parameters()).dtype - encoder_output = encoder_output.to(float_dtype) - - # init or reinit graph - if self.state is None or self.state.need_reinit(encoder_output): - self._graph_reinitialize(encoder_output) - - # copy (projected) encoder output and lengths - self.state.encoder_output_projected[:current_batch_size, :current_max_time, ...].copy_(encoder_output) - self.state.encoder_output_length[: encoder_output_length.shape[0]].copy_(encoder_output_length) - # set length to zero for elements outside the current batch - self.state.encoder_output_length[current_batch_size:].fill_(0) - if self.biasing_multi_model is not None: - if multi_biasing_ids is None: - multi_biasing_ids = torch.full( - [encoder_output_length.shape[0]], fill_value=-1, dtype=torch.long, device=device - ) - self.state.multi_biasing_ids[:current_batch_size].copy_(multi_biasing_ids) - self.state.multi_biasing_ids[current_batch_size:].fill_(-1) - - self._init_decoding_state(current_batch_size=current_batch_size, prev_batched_state=prev_batched_state) - - if self.cuda_graphs_mode is self.CudaGraphsMode.FULL_GRAPH: - self.full_graph.replay() - elif self.cuda_graphs_mode is self.CudaGraphsMode.NO_WHILE_LOOPS: - self.separate_graphs.before_outer_loop.replay() - while self.state.active_mask_any.item(): - self.separate_graphs.before_inner_loop.replay() - while self.state.advance_mask_any.item(): - self.separate_graphs.inner_loop_code.replay() - self.separate_graphs.after_inner_loop.replay() - elif self.cuda_graphs_mode is self.CudaGraphsMode.NO_GRAPHS: - # this mode is only for testing purposes - # manual loop instead of using graphs - self._before_outer_loop() - while self.state.active_mask_any.item(): - self._before_inner_loop_get_joint_output() - while self.state.advance_mask_any.item(): - self._inner_loop_step_find_next_non_blank() - self._after_inner_loop_step() - else: - raise NotImplementedError(f"Unknown graph mode: {self.cuda_graphs_mode}") - - if prev_batched_state is not None: - self._fix_timestamps_for_iterative_decoding( - current_batch_size=current_batch_size, prev_batched_state=prev_batched_state - ) - # NB: last labels can not exist (nothing decoded on this step). - # return the last labels from the previous state in this case - last_labels = self.state.batched_hyps.get_last_labels(pad_id=self._SOS) - pad_batch_size = ( - self.state.batch_size - prev_batched_state.labels.shape[-1] if prev_batched_state is not None else 0 - ) - - decoding_state = BatchedLabelLoopingState( - predictor_states=self.decoder.clone_state(self.state.decoder_state), - predictor_outputs=self.state.decoder_output.clone(), - labels=( - torch.where( - last_labels == self._SOS, - F.pad(prev_batched_state.labels, (0, pad_batch_size), value=self._SOS), - last_labels, - ) - if prev_batched_state is not None - else last_labels - ), - decoded_lengths=( - self.state.encoder_output_length.clone() - if prev_batched_state is None - else self.state.encoder_output_length - + F.pad(prev_batched_state.decoded_lengths, (0, pad_batch_size), value=0) - ), - fusion_states_list=([fusion_state.clone() for fusion_state in self.state.fusion_states_list]), - time_jumps=self.state.time_indices - self.state.encoder_output_length, - ) - - # NB: return an independent copy of hyps/alignments/state - # to avoid any manipulations with allocated memory outside the decoder - return ( - self.state.batched_hyps.clone(), - self.state.alignments.clone() if self.preserve_alignments else None, - decoding_state, - ) - - @classmethod - def _create_outer_while_loop_kernel(cls): - """ - Creates a kernel that evaluates whether to enter the outer loop body (not all hypotheses are decoded). - Condition: while(active_mask_any). - """ - kernel_string = r"""\ - typedef __device_builtin__ unsigned long long cudaGraphConditionalHandle; - - extern "C" __device__ __cudart_builtin__ void cudaGraphSetConditional(cudaGraphConditionalHandle handle, unsigned int value); - - extern "C" __global__ - void outer_label_looping_conditional(cudaGraphConditionalHandle handle, const bool *active_mask_any) - { - cudaGraphSetConditional(handle, *active_mask_any); - } - """ - return run_nvrtc(kernel_string, b"outer_label_looping_conditional", cls.CUDA_PROGRAM_NAME) - - @classmethod - def _create_inner_while_loop_kernel(cls): - """ - Creates a kernel that evaluates whether to enter the inner loop body (not all non-blank labels found). - Condition: while(advance_mask_any). - """ - kernel_string = r"""\ - typedef __device_builtin__ unsigned long long cudaGraphConditionalHandle; - - extern "C" __device__ __cudart_builtin__ void cudaGraphSetConditional(cudaGraphConditionalHandle handle, unsigned int value); - - extern "C" __global__ - void inner_find_non_blank_conditional(cudaGraphConditionalHandle handle, const bool *advance_mask_any) - { - cudaGraphSetConditional(handle, *advance_mask_any); - } - """ - return run_nvrtc(kernel_string, b"inner_find_non_blank_conditional", cls.CUDA_PROGRAM_NAME) - - def _graph_reinitialize( - self, - encoder_output_projected: torch.Tensor, - ): - batch_size, max_time, encoder_dim = encoder_output_projected.shape - - self.state = LabelLoopingState( - batch_size=batch_size, - max_time=max(max_time, self.INITIAL_MAX_TIME), - encoder_dim=encoder_dim, - max_symbols=self.max_symbols, - device=encoder_output_projected.device, - float_dtype=encoder_output_projected.dtype, - logits_dim=self.joint.num_classes_with_blank, - preserve_alignments=self.preserve_alignments, - preserve_frame_confidence=self.preserve_frame_confidence, - include_duration_confidence=self.include_duration_confidence, - include_duration=self.include_duration, - ) - self.state.model_durations = self.durations.to(self.state.device, non_blocking=True) - - # init decoder state - self.state.labels.fill_(self._SOS) - decoder_output, new_state, *_ = self.decoder.predict( - self.state.labels.unsqueeze(1), - self.decoder.initialize_state(self.state.encoder_output_projected), - add_sos=False, - batch_size=self.state.batch_size, - ) - self.state.decoder_state_after_sos = new_state - self.state.decoder_state = self.decoder.initialize_state(encoder_output_projected) - self.decoder.batch_replace_states_all( - src_states=self.state.decoder_state_after_sos, dst_states=self.state.decoder_state - ) - # to avoid recalculation of joint projection, store decoder output in state - self.state.decoder_output_after_sos = self.joint.project_prednet(decoder_output) - self.state.decoder_output = self.state.decoder_output_after_sos.clone() - - # init fusion models states and scores - self.state.fusion_states_list = [] - self.state.fusion_states_candidates_list = [] - self.state.fusion_scores_list = [] - device = encoder_output_projected.device - float_dtype = encoder_output_projected.dtype - - self._move_fusion_models_to_device(device=device) - for fusion_model in self._all_fusion_models(): - vocab_size = fusion_model.vocab_size - self.state.fusion_states_list.append( - fusion_model.get_init_states(batch_size=self.state.batch_size, bos=True) - ) - self.state.fusion_states_candidates_list.append( - torch.zeros([batch_size, vocab_size], dtype=torch.long, device=device) - ) - - self.state.fusion_scores_list.append( - torch.zeros([batch_size, vocab_size], dtype=float_dtype, device=device) - ) - - # warmup before graph compilation - if self.cuda_graphs_mode is not self.CudaGraphsMode.NO_GRAPHS: - self._warmup_for_cuda_graphs() - - if self.cuda_graphs_mode is self.CudaGraphsMode.FULL_GRAPH: - try: - self._full_graph_compile() - except NeMoCUDAPythonException as e: - if not self.cuda_graphs_allow_fallback: - raise RuntimeError("Full CUDA graph decoding failed. Mode is forced, raising exception") from e - logging.warning( - f"Full CUDA graph compilation failed: {e}. " - "Falling back to native PyTorch CUDA graphs. Decoding will be slower." - ) - self.cuda_graphs_mode = self.CudaGraphsMode.NO_WHILE_LOOPS - self._partial_graphs_compile() - elif self.cuda_graphs_mode is self.CudaGraphsMode.NO_WHILE_LOOPS: - self._partial_graphs_compile() - elif self.cuda_graphs_mode is self.CudaGraphsMode.NO_GRAPHS: - # no graphs needed - pass - else: - raise NotImplementedError - - def _warmup_for_cuda_graphs(self): - """Warmup before compiling CUDA graphs""" - is_ddp = torch.distributed.is_available() and torch.distributed.is_initialized() - # 11 warmup steps required in DDP mode - # see https://pytorch.org/docs/stable/notes/cuda.html#usage-with-distributeddataparallel - num_runs = 11 if is_ddp else 3 - self.state.encoder_output_projected.fill_(0.0) - self.state.encoder_output_length.fill_(1) - s = torch.cuda.Stream() - s.wait_stream(torch.cuda.current_stream()) - with torch.cuda.stream(s): - for _ in range(num_runs): - self._before_outer_loop() - self._before_inner_loop_get_joint_output() - self._inner_loop_step_find_next_non_blank() - self._after_inner_loop_step() - torch.cuda.current_stream().wait_stream(s) - self.state.encoder_output_length.fill_(0) - - def _partial_graphs_compile(self): - """Compile decoding by parts""" - # Always create a new stream, because the per-thread default stream disallows stream capture to a graph. - stream_for_graph = torch.cuda.Stream(self.state.device) - stream_for_graph.wait_stream(torch.cuda.default_stream(self.state.device)) - self.separate_graphs = SeparateGraphsLabelLooping() - with ( - torch.cuda.stream(stream_for_graph), - torch.inference_mode(), - torch.cuda.graph( - self.separate_graphs.before_outer_loop, stream=stream_for_graph, capture_error_mode="thread_local" - ), - ): - self._before_outer_loop() - - with ( - torch.cuda.stream(stream_for_graph), - torch.inference_mode(), - torch.cuda.graph( - self.separate_graphs.before_inner_loop, stream=stream_for_graph, capture_error_mode="thread_local" - ), - ): - self._before_inner_loop_get_joint_output() - - with ( - torch.cuda.stream(stream_for_graph), - torch.inference_mode(), - torch.cuda.graph( - self.separate_graphs.inner_loop_code, stream=stream_for_graph, capture_error_mode="thread_local" - ), - ): - self._inner_loop_step_find_next_non_blank() - - with ( - torch.cuda.stream(stream_for_graph), - torch.inference_mode(), - torch.cuda.graph( - self.separate_graphs.after_inner_loop, stream=stream_for_graph, capture_error_mode="thread_local" - ), - ): - self._after_inner_loop_step() - - @cuda_python_required - def _full_graph_compile(self): - """Compile full graph for decoding""" - # Always create a new stream, because the per-thread default stream disallows stream capture to a graph. - stream_for_graph = torch.cuda.Stream(self.state.device) - stream_for_graph.wait_stream(torch.cuda.default_stream(self.state.device)) - self.full_graph = torch.cuda.CUDAGraph() - with ( - torch.cuda.stream(stream_for_graph), - torch.inference_mode(), - torch.cuda.graph(self.full_graph, stream=stream_for_graph, capture_error_mode="thread_local"), - ): - self._before_outer_loop() - - # NB: depending on cuda-python version, cudaStreamGetCaptureInfo can return either 5 or 6 elements - capture_status, _, graph, *_ = cu_call( - cudart.cudaStreamGetCaptureInfo(torch.cuda.current_stream(device=self.state.device).cuda_stream) - ) - assert capture_status == cudart.cudaStreamCaptureStatus.cudaStreamCaptureStatusActive - - # capture: while self.active_mask_any: - (outer_loop_conditional_handle,) = cu_call(cudart.cudaGraphConditionalHandleCreate(graph, 0, 0)) - outer_loop_kernel = self._create_outer_while_loop_kernel() - active_mask_any_ptr = np.array([self.state.active_mask_any.data_ptr()], dtype=np.uint64) - outer_loop_args = np.array( - [outer_loop_conditional_handle.getPtr(), active_mask_any_ptr.ctypes.data], - dtype=np.uint64, - ) - - # loop while there are active utterances - # while self.active_mask_any: - with with_conditional_node( - outer_loop_kernel, outer_loop_args, outer_loop_conditional_handle, device=self.state.device - ): - self._before_inner_loop_get_joint_output() - # capture: while self.advance_mask_any.item(): - inner_while_loop_kernel = self._create_inner_while_loop_kernel() - (inner_loop_conditional_handle,) = cu_call(cudart.cudaGraphConditionalHandleCreate(graph, 0, 0)) - advance_mask_any_ptr = np.array([self.state.advance_mask_any.data_ptr()], dtype=np.uint64) - inner_loop_args = np.array( - [ - inner_loop_conditional_handle.getPtr(), - advance_mask_any_ptr.ctypes.data, - ], - dtype=np.uint64, - ) - # while self.advance_mask_any.item(): - with with_conditional_node( - inner_while_loop_kernel, inner_loop_args, inner_loop_conditional_handle, device=self.state.device - ): - self._inner_loop_step_find_next_non_blank() - self._after_inner_loop_step() - - def _init_decoding_state( - self, current_batch_size: int, prev_batched_state: Optional[BatchedLabelLoopingState] = None - ): - # NB: we can speedup the case when prev_batched_state is None by using CUDA graphs - if prev_batched_state is None: - # last found labels - initially () symbol - self.state.labels.fill_(self._SOS) - self.decoder.batch_replace_states_all( - src_states=self.state.decoder_state_after_sos, dst_states=self.state.decoder_state - ) - self.state.decoder_output.copy_(self.state.decoder_output_after_sos) - - # init fusion models states - for fusion_model_idx, fusion_model in enumerate(self._all_fusion_models()): - self.state.fusion_states_list[fusion_model_idx].copy_( - fusion_model.get_init_states(batch_size=self.state.batch_size, bos=True) - ) - - self.state.time_indices.fill_(0) - else: - # labels - self.state.labels[:current_batch_size].copy_(prev_batched_state.labels[:current_batch_size]) - # initial state - self.decoder.batch_replace_states_all( - src_states=prev_batched_state.predictor_states, - dst_states=self.state.decoder_state, - batch_size=current_batch_size, - ) - self.state.decoder_output[:current_batch_size].copy_( - prev_batched_state.predictor_outputs[:current_batch_size] - ) - - # init fusion models states - for fusion_model_idx, fusion_model in enumerate(self._all_fusion_models()): - self.state.fusion_states_list[fusion_model_idx][:current_batch_size].copy_( - prev_batched_state.fusion_states_list[fusion_model_idx][:current_batch_size] - ) - - self.state.time_indices[:current_batch_size].copy_(prev_batched_state.time_jumps[:current_batch_size]) - - def _before_outer_loop(self): - """Clear state and compute initial active mask""" - self.state.batched_hyps.clear_() - if self.state.alignments is not None: - self.state.alignments.clear_() - - self.state.scores.fill_(0.0) - - # time indices - self.state.time_indices_current_labels.copy_(self.state.time_indices) - # safe time indices: guaranteed to be < encoder_output_length - torch.sub(self.state.encoder_output_length, 1, out=self.state.last_timesteps) - torch.minimum(self.state.time_indices, self.state.last_timesteps, out=self.state.safe_time_indices) - - # masks for utterances in batch - torch.less(self.state.time_indices, self.state.encoder_output_length, out=self.state.active_mask) - - # same as: self.active_mask_any = active_mask.any() - torch.any(self.state.active_mask, out=self.state.active_mask_any) - self.state.durations.fill_(0) - - def _before_inner_loop_get_joint_output(self): - """Get Joint output after decoder output, prepare inner loop to search for all next non-blank labels""" - # stage 1: get joint output, iteratively seeking for non-blank labels - # blank label in `labels` tensor means "end of hypothesis" (for this index) - self.state.active_mask_prev.copy_(self.state.active_mask) - logits = ( - self.joint.joint_after_projection( - self.state.encoder_output_projected[self.state.batch_indices, self.state.safe_time_indices].unsqueeze( - 1 - ), - self.state.decoder_output, - ) - .squeeze(1) - .squeeze(1) - ) - # same as: scores, labels = logits[:, : -self.state.model_durations.shape[0]].max(-1) - torch.max( - logits[:, : -self.state.model_durations.shape[0]], dim=-1, out=(self.state.scores, self.state.labels) - ) - - if self.has_fusion_models(): - fusion_scores_list, fusion_states_candidates_list = self.advance_fusion_models( - fusion_states_list=self.state.fusion_states_list, - multi_biasing_ids=self.state.multi_biasing_ids, - float_dtype=self.state.float_dtype, - ) - for fusion_model_idx in range(len(fusion_scores_list)): - # get fusion scores/states - self.state.fusion_states_candidates_list[fusion_model_idx].copy_( - fusion_states_candidates_list[fusion_model_idx] - ) - self.state.fusion_scores_list[fusion_model_idx].copy_(fusion_scores_list[fusion_model_idx]) - # update logits with fusion scores - logits[:, : -self.state.model_durations.shape[0] - 1] += fusion_scores_list[fusion_model_idx] - # get labels (greedy) and scores from current logits, replace labels/scores with new - scores_w_fusion, labels_w_fusion = logits[:, : -self.state.model_durations.shape[0] - 1].max(dim=-1) - # preserve "blank" / "non-blank" category - torch.where( - self.state.labels == self._blank_index, self.state.labels, labels_w_fusion, out=self.state.labels - ) - torch.where( - self.state.labels == self._blank_index, self.state.scores, scores_w_fusion, out=self.state.scores - ) - - jump_durations_indices = logits[:, -self.state.model_durations.shape[0] :].argmax(dim=-1) - self.state.durations.copy_(self.state.model_durations[jump_durations_indices]) - - # search for non-blank labels using joint, advancing time indices for blank labels - # checking max_symbols is not needed, since we already forced advancing time indices for such cases - torch.eq(self.state.labels, self._blank_index, out=self.state.blank_mask) - # blank_mask = self.labels == self._blank_index - self.state.time_indices_current_labels.copy_(self.state.time_indices) - # for blank labels force duration >= 1 - self.state.durations.masked_fill_(torch.logical_and(self.state.durations == 0, self.state.blank_mask), 1) - - if self.state.alignments is not None: - self.state.alignments.add_results_masked_no_checks_( - active_mask=self.state.active_mask, - time_indices=self.state.time_indices_current_labels, - logits=logits if self.preserve_alignments else None, - labels=self.state.labels if self.preserve_alignments else None, - confidence=self._get_frame_confidence( - logits=logits, num_durations=self.state.model_durations.shape[0] - ), - ) - - # advance_mask is a mask for current batch for searching non-blank labels; - # each element is True if non-blank symbol is not yet found AND we can increase the time index - self.state.time_indices.add_(self.state.durations * self.state.active_mask) - torch.minimum(self.state.time_indices, self.state.last_timesteps, out=self.state.safe_time_indices) - torch.less(self.state.time_indices, self.state.encoder_output_length, out=self.state.active_mask) - torch.logical_and(self.state.active_mask, self.state.blank_mask, out=self.state.advance_mask) - - # inner loop: find next non-blank labels (if exist) - # same as: self.advance_mask_any = advance_mask.any() - torch.any(self.state.advance_mask, out=self.state.advance_mask_any) - - def _inner_loop_step_find_next_non_blank(self): - """Find next non-blank labels - one iteration""" - # same as: time_indices_current_labels[advance_mask] = time_indices[advance_mask], but non-blocking - # store current time indices to use further for storing the results - torch.where( - self.state.advance_mask, - self.state.time_indices, - self.state.time_indices_current_labels, - out=self.state.time_indices_current_labels, - ) - logits = ( - self.joint.joint_after_projection( - self.state.encoder_output_projected[self.state.batch_indices, self.state.safe_time_indices].unsqueeze( - 1 - ), - self.state.decoder_output, - ) - .squeeze(1) - .squeeze(1) - ) - # get labels (greedy) and scores from current logits, replace labels/scores with new - # labels[advance_mask] are blank, and we are looking for non-blank labels - more_scores, more_labels = logits[:, : -self.state.model_durations.shape[0]].max(-1) - - if self.has_fusion_models(): - for fusion_model_idx, fusion_scores in enumerate(self.state.fusion_scores_list): - # update logits with fusion scores - logits[:, : -self.state.model_durations.shape[0] - 1] += fusion_scores - # # get labels (greedy) and scores from current logits, replace labels/scores with new - more_scores_w_fusion, more_labels_w_fusion = logits[:, : -self.state.model_durations.shape[0] - 1].max( - dim=-1 - ) - # preserve "blank" / "non-blank" category - torch.where(more_labels == self._blank_index, more_labels, more_labels_w_fusion, out=more_labels) - torch.where(more_labels == self._blank_index, more_scores, more_scores_w_fusion, out=more_scores) - - jump_durations_indices = logits[:, -self.state.model_durations.shape[0] :].argmax(dim=-1) - more_durations = self.state.model_durations[jump_durations_indices] - # same as: labels[advance_mask] = more_labels[advance_mask], but non-blocking - torch.where(self.state.advance_mask, more_labels, self.state.labels, out=self.state.labels) - # same as: scores[advance_mask] = more_scores[advance_mask], but non-blocking - torch.where(self.state.advance_mask, more_scores, self.state.scores, out=self.state.scores) - - if self.state.alignments is not None: - self.state.alignments.add_results_masked_no_checks_( - active_mask=self.state.advance_mask, - time_indices=self.state.time_indices_current_labels, - logits=logits if self.preserve_alignments else None, - labels=more_labels if self.preserve_alignments else None, - confidence=self._get_frame_confidence( - logits=logits, num_durations=self.state.model_durations.shape[0] - ), - ) - - # blank_mask = self.labels == self._blank_index - torch.eq(self.state.labels, self._blank_index, out=self.state.blank_mask) - # for blank labels force duration >= 1 - more_durations.masked_fill_(torch.logical_and(more_durations == 0, self.state.blank_mask), 1) - # self.time_indices += self.blank_mask - torch.where( - self.state.advance_mask, - self.state.time_indices + more_durations, - self.state.time_indices, - out=self.state.time_indices, - ) - - torch.where(self.state.advance_mask, more_durations, self.state.durations, out=self.state.durations) - - torch.minimum(self.state.time_indices, self.state.last_timesteps, out=self.state.safe_time_indices) - torch.less(self.state.time_indices, self.state.encoder_output_length, out=self.state.active_mask) - torch.logical_and(self.state.active_mask, self.state.blank_mask, out=self.state.advance_mask) - torch.any(self.state.advance_mask, out=self.state.advance_mask_any) - - def _after_inner_loop_step(self): - """After inner loop: store labels, query decoder/fusion models, force max symbols""" - self._after_inner_loop_store_labels() - self._after_inner_loop_select_fusion_states() - self._after_inner_loop_get_decoder_output() - self._after_inner_loop_force_max_symbols() - - def _after_inner_loop_store_labels(self): - """Stage 3.1: Store hypotheses, update decoder state""" - self.state.found_labels_mask.copy_( - torch.logical_and(self.state.active_mask_prev, self.state.labels != self._blank_index) - ) - self.state.batched_hyps.add_results_masked_no_checks_( - active_mask=self.state.found_labels_mask, - labels=self.state.labels, - time_indices=self.state.time_indices_current_labels, - scores=self.state.scores, - token_durations=self.state.durations if self.include_duration else None, - ) - - def _after_inner_loop_select_fusion_states(self): - """Stage 3.2: Select fusion states with new labels""" - for fusion_model_idx, fusion_states_candidates in enumerate(self.state.fusion_states_candidates_list): - # select necessary fusion states based on chosen labels - torch.where( - self.state.found_labels_mask, - fusion_states_candidates[self.state.batch_indices, self.state.labels * self.state.found_labels_mask], - self.state.fusion_states_list[fusion_model_idx], - out=self.state.fusion_states_list[fusion_model_idx], - ) - - def _after_inner_loop_get_decoder_output(self): - """Stage 3.3: Get decoder (prediction network) output using new labels""" - decoder_output, new_state, *_ = self.decoder.predict( - self.state.labels.unsqueeze(1), self.state.decoder_state, add_sos=False, batch_size=self.state.batch_size - ) - self.decoder.batch_replace_states_mask( - src_states=new_state, dst_states=self.state.decoder_state, mask=self.state.found_labels_mask - ) - decoder_output_projected = self.joint.project_prednet(decoder_output) # do not recalculate joint projection - torch.where( - self.state.found_labels_mask.unsqueeze(-1).unsqueeze(-1), - decoder_output_projected, - self.state.decoder_output, - out=self.state.decoder_output, - ) - - def _after_inner_loop_force_max_symbols(self): - """Stage 4: to avoid looping, go to next frame after max_symbols emission""" - # if labels are non-blank (not end-of-utterance), check that last observed timestep with label: - # if it is equal to the current time index, and number of observations is >= max_symbols, force blank - force_blank_mask = torch.logical_and( - self.state.active_mask, - torch.logical_and( - torch.logical_and( - self.state.labels != self._blank_index, - self.state.batched_hyps.last_timestamp_lasts >= self.max_symbols, - ), - self.state.batched_hyps.last_timestamp == self.state.time_indices, - ), - ) - self.state.time_indices.add_(force_blank_mask) # emit blank => advance time indices - # update safe_time_indices, non-blocking - torch.minimum(self.state.time_indices, self.state.last_timesteps, out=self.state.safe_time_indices) - # same as: active_mask = time_indices < encoder_output_length - torch.less(self.state.time_indices, self.state.encoder_output_length, out=self.state.active_mask) - torch.any(self.state.active_mask, out=self.state.active_mask_any) - - def _fix_timestamps_for_iterative_decoding( - self, current_batch_size: int, prev_batched_state: BatchedLabelLoopingState - ): - """ - Fix timestamps: if we are in iterative decoding mode, - we need to add the length of the previous batch to current timestamps - """ - self.state.batched_hyps.timestamps[:current_batch_size] += prev_batched_state.decoded_lengths[ - :current_batch_size - ].unsqueeze(1) - if self.state.alignments is not None: - self.state.alignments.timestamps[:current_batch_size] -= prev_batched_state.decoded_lengths[ - :current_batch_size - ].unsqueeze(1) diff --git a/nemo/collections/asr/parts/submodules/wfst_decoder.py b/nemo/collections/asr/parts/submodules/wfst_decoder.py deleted file mode 100644 index a6155ace4fc82c9f2b6fe8e9aed92b12cfa7afae..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/wfst_decoder.py +++ /dev/null @@ -1,791 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import copy -import gc -import tempfile -from abc import ABC, abstractmethod -from collections import defaultdict -from pathlib import Path -from typing import Any, Dict, List, NamedTuple, Optional, Tuple, Union - -import torch -from jiwer import wer as word_error_rate -from omegaconf import DictConfig - -from nemo.collections.asr.parts.utils.wfst_utils import TW_BREAK, kaldifst_importer - -RIVA_DECODER_INSTALLATION_MESSAGE = ( - "riva decoder is not installed or is installed incorrectly.\n" - "please run `bash scripts/installers/install_riva_decoder.sh` or `pip install riva-asrlib-decoder` to install." -) - - -def riva_decoder_importer(): - """Import helper function that returns Riva asrlib decoder package or raises ImportError exception.""" - try: - import riva.asrlib.decoder.python_decoder as riva_decoder - except (ImportError, ModuleNotFoundError): - raise ImportError(RIVA_DECODER_INSTALLATION_MESSAGE) - return riva_decoder - - -def _riva_config_to_dict(conf: Any) -> Dict[str, Any]: - """ - Helper function for parsing Riva configs (namely BatchedMappedDecoderCudaConfig) into a dictionary. - - Args: - conf: - Inner Riva config. - - Returns: - Dictionary corresponding to the Riva config. - """ - result = {} - for name in conf.__dir__(): - if not name.startswith("__"): - attribute = getattr(conf, name) - result[name] = ( - attribute if attribute.__class__.__module__ == 'builtins' else _riva_config_to_dict(attribute) - ) - return result - - -def _fill_inner_riva_config_(riva_conf, nemo_conf): - """ - Helper function for filling Riva configs (namely BatchedMappedDecoderCudaConfig) - according to the corresponding NeMo config. - - Note: in-place for the first argument. - - Args: - riva_conf: - Inner Riva config. - - nemo_conf: - Corresponding NeMo config. - """ - for nemo_k, nemo_v in nemo_conf.items(): - if isinstance(nemo_v, DictConfig): - _fill_inner_riva_config_(getattr(riva_conf, nemo_k), nemo_v) - else: - setattr(riva_conf, nemo_k, nemo_v) - - -class RivaDecoderConfig(DictConfig): - """ - NeMo config for the RivaGpuWfstDecoder. - """ - - def __init__(self): - try: - riva_decoder = riva_decoder_importer() - - config = riva_decoder.BatchedMappedDecoderCudaConfig() - config.online_opts.lattice_postprocessor_opts.acoustic_scale = 10.0 - config.n_input_per_chunk = 50 - config.online_opts.decoder_opts.default_beam = 20.0 - config.online_opts.decoder_opts.max_active = 10000 - config.online_opts.determinize_lattice = True - config.online_opts.max_batch_size = 800 - config.online_opts.num_channels = 800 - config.online_opts.frame_shift_seconds = 1 # not actual frame shift - config.online_opts.lattice_postprocessor_opts.word_ins_penalty = 0.0 - - content = _riva_config_to_dict(config) - except ImportError: - content = {} - super().__init__(content) - - -class WfstNbestUnit(NamedTuple): - """ - Container for a single RivaGpuWfstDecoder n-best hypothesis. - """ - - words: Tuple[str] - timesteps: Tuple[int] - alignment: Tuple[int] - score: float - - -class WfstNbestHypothesis: - """ - Container for the RivaGpuWfstDecoder n-best results represented as a list of WfstNbestUnit objects. - """ - - def __init__(self, raw_hypotheses: Tuple[Tuple[Tuple[str], Tuple[int], Tuple[int], float]]): - for i, rh in enumerate(raw_hypotheses): - assert isinstance(rh[0], tuple), f"{rh[0]}" - assert isinstance(rh[1], tuple), f"{rh[1]}, {rh[0]}" - assert isinstance(rh[2], tuple), f"{rh[2]}" - assert isinstance(rh[3], float), f"{rh[3]}" - assert len(rh[0]) == len(rh[1]) or len(rh[1]) == 0, "words do not match timesteps" - - self._hypotheses = sorted([WfstNbestUnit(*rh) for rh in raw_hypotheses], key=lambda hyp: hyp.score) - self._shape0 = len(self._hypotheses) - self._shape1 = [len(h.words) for h in self._hypotheses] - self._has_timesteps = len(self._hypotheses[0].timesteps) > 0 - self._has_alignment = len(self._hypotheses[0].alignment) > 0 - - def __iter__(self): - yield from self._hypotheses - - def __getitem__(self, index): - return self._hypotheses[index] - - def __len__(self): - return self.shape0 - - def replace_unit_( - self, index: int, new_unit: Union[WfstNbestUnit, Tuple[Tuple[str], Tuple[int], Tuple[int], float]] - ): - """ - Replaces a WfstNbestUnit by index. - - Note: in-place operation. - - Args: - index: - Index of the unit to be replaced. - - new_unit: - Replacement unit. - """ - assert 0 <= index < self.shape0 - assert ( - self.has_timesteps - and len(new_unit[0]) == len(new_unit[1]) - or not self.has_timesteps - and len(new_unit[1]) == 0 - ) - assert ( - index == 0 - and (len(self._hypotheses) == 1 or new_unit[3] <= self._hypotheses[index + 1].score) - or index == self.shape0 - 1 - and self._hypotheses[index - 1].score <= new_unit[3] - or self._hypotheses[index - 1].score <= new_unit[3] <= self._hypotheses[index + 1].score - ) - - if not isinstance(new_unit, WfstNbestUnit): - new_unit = WfstNbestUnit(*new_unit) - self._hypotheses[index] = new_unit - self._shape1[index] = len(new_unit.words) - - @property - def shape0(self): - return self._shape0 - - @property - def shape1(self): - return self._shape1 - - @property - def has_timesteps(self): - return self._has_timesteps - - @property - def has_alignment(self): - return self._has_alignment - - -def collapse_tokenword_hypotheses( - hypotheses: List[WfstNbestHypothesis], tokenword_disambig_str: str -) -> List[WfstNbestHypothesis]: - """ - Searches for tokenwords in the input hypotheses and collapses them into words. - - Args: - hypotheses: - List of input WfstNbestHypothesis. - - tokenword_disambig_str: - Tokenword disambiguation symbol (e.g. `#1`). - - Returns: - List of WfstNbestHypothesis. - """ - new_hypotheses = copy.deepcopy(hypotheses) - for hyp in new_hypotheses: - for k, h_unit in enumerate(hyp): - twds_list = [] - for i, word in enumerate(h_unit.words): - if word == tokenword_disambig_str: - twds_list.append(i) - if len(twds_list) > 0: - # a rare case when the recognition stopped before completing the tokenword - old_words = list(h_unit.words) - old_timesteps = list(h_unit.timesteps) - words_len = len(old_words) - if len(twds_list) % 2 == 1: - twds_list.append(words_len) - new_words, new_timesteps = [], [] - j_prev = 0 - for i, j in zip(twds_list[::2], twds_list[1::2]): - new_words += old_words[j_prev:i] - # drop tokenword disambig -> remove token disanbig suffix -> remove word begin mark - new_word = "".join(old_words[i + 1 : j]).replace(f"{TW_BREAK}{tokenword_disambig_str}", "")[1:] - new_words.append(new_word) - new_timesteps += old_timesteps[j_prev:i] + [ - old_timesteps[i], - ] - j_prev = j + 1 - if j_prev < words_len: - new_words += old_words[j_prev:words_len] - new_timesteps += old_timesteps[j_prev:words_len] - hyp.replace_unit_(k, (tuple(new_words), tuple(new_timesteps), h_unit.alignment, h_unit.score)) - return new_hypotheses - - -class AbstractWFSTDecoder(ABC): - """ - Used for performing WFST decoding of the logprobs. - - Args: - lm_fst: - Language model WFST. - - decoding_mode: - Decoding mode. E.g. `nbest`. - - beam_size: - Beam width (float) for the WFST decoding. - - config: - Decoder config. - - tokenword_disambig_id: - Tokenword disambiguation index. Set to -1 to disable the tokenword mode. - - lm_weight: - Language model weight in decoding. - """ - - def __init__( - self, - lm_fst: Any, - decoding_mode: str, - beam_size: float, - config: Optional[Any], - tokenword_disambig_id: int = -1, - lm_weight: float = 1.0, - ): - self._lm_fst = lm_fst - self._beam_size = beam_size - self._tokenword_disambig_id = tokenword_disambig_id - self._open_vocabulary_decoding = self._tokenword_disambig_id >= 0 - self._lm_weight = lm_weight - self._id2word, self._word2id = None, None - self._id2token, self._token2id = None, None - self._decoding_mode, self._config, self._decoder = None, None, None - - self._set_decoding_mode(decoding_mode) - self._set_decoder_config(config) - self._init_decoder() - - @abstractmethod - def _set_decoder_config(self, config: Optional[Any] = None): - pass - - @abstractmethod - def _set_decoding_mode(self, decoding_mode: str): - pass - - @abstractmethod - def _init_decoder(self): - pass - - @property - def decoding_mode(self): - return self._decoding_mode - - @decoding_mode.setter - def decoding_mode(self, value: str): - self._decoding_mode_setter(value) - - @abstractmethod - def _decoding_mode_setter(self, value: str): - pass - - @property - def beam_size(self): - return self._beam_size - - @beam_size.setter - def beam_size(self, value: float): - self._beam_size_setter(value) - - @abstractmethod - def _beam_size_setter(self, value: float): - pass - - @property - def lm_weight(self): - return self._lm_weight - - @lm_weight.setter - def lm_weight(self, value: float): - self._lm_weight_setter(value) - - @abstractmethod - def _lm_weight_setter(self, value: float): - pass - - @property - def tokenword_disambig_id(self): - return self._tokenword_disambig_id - - @property - def open_vocabulary_decoding(self): - return self._open_vocabulary_decoding - - @abstractmethod - def decode(self, log_probs: torch.Tensor, log_probs_length: torch.Tensor) -> List[Any]: - """ - Decodes logprobs into recognition hypotheses. - - Args: - log_probs: - A torch.Tensor of the predicted log-probabilities of shape [Batch, Time, Vocabulary]. - - log_probs_length: - A torch.Tensor of length `Batch` which contains the lengths of the log_probs elements. - - Returns: - List of recognition hypotheses. - """ - pass - - @abstractmethod - def _post_decode(self, hypotheses: List[Any]) -> List[Any]: - """ - Does various post-processing of the recognition hypotheses. - - Args: - hypotheses: - List of recognition hypotheses. - - Returns: - List of processed recognition hypotheses. - """ - pass - - @abstractmethod - def calibrate_lm_weight( - self, log_probs: torch.Tensor, log_probs_length: torch.Tensor, reference_texts: List[str] - ) -> Tuple[float, float]: - """ - Calibrates LM weight to achieve the best WER for given logprob-text pairs. - - Args: - log_probs: - A torch.Tensor of the predicted log-probabilities of shape [Batch, Time, Vocabulary]. - - log_probs_length: - A torch.Tensor of length `Batch` which contains the lengths of the log_probs elements. - - reference_texts: - List of reference word sequences. - - Returns: - Pair of (best_lm_weight, best_wer). - """ - pass - - @abstractmethod - def calculate_oracle_wer( - self, log_probs: torch.Tensor, log_probs_length: torch.Tensor, reference_texts: List[str] - ) -> Tuple[float, List[float]]: - """ - Calculates the oracle (the best possible WER for given logprob-text pairs. - - Args: - log_probs: - A torch.Tensor of the predicted log-probabilities of shape [Batch, Time, Vocabulary]. - - log_probs_length: - A torch.Tensor of length `Batch` which contains the lengths of the log_probs elements. - - reference_texts: - List of reference word sequences. - - Returns: - Pair of (oracle_wer, oracle_wer_per_utterance). - """ - pass - - -class RivaGpuWfstDecoder(AbstractWFSTDecoder): - """ - Used for performing WFST decoding of the logprobs with the Riva WFST decoder. - - Args: - lm_fst: - Kaldi-type language model WFST or its path. - - decoding_mode: - Decoding mode. Choices: `nbest`, `mbr`, `lattice`. - - beam_size: - Beam width (float) for the WFST decoding. - - config: - Riva Decoder config. - - tokenword_disambig_id: - Tokenword disambiguation index. Set to -1 to disable the tokenword mode. - - lm_weight: - Language model weight in decoding. - - nbest_size: - N-best size for decoding_mode == `nbest` - """ - - def __init__( - self, - lm_fst: Union['kaldifst.StdFst', Path, str], - decoding_mode: str = 'mbr', - beam_size: float = 10.0, - config: Optional['RivaDecoderConfig'] = None, - tokenword_disambig_id: int = -1, - lm_weight: float = 1.0, - nbest_size: int = 1, - ): - self._nbest_size = nbest_size - self._load_word_lattice = None - super().__init__(lm_fst, decoding_mode, beam_size, config, tokenword_disambig_id, lm_weight) - - def _set_decoder_config(self, config: Optional['RivaDecoderConfig'] = None): - if config is None or len(config) == 0: - config = RivaDecoderConfig() - if not hasattr(config, "online_opts"): - # most likely empty config - # call importer to raise the exception + installation message - riva_decoder_importer() - # just in case - raise RuntimeError("Unexpected config error. Please debug manually.") - config.online_opts.decoder_opts.lattice_beam = self._beam_size - config.online_opts.lattice_postprocessor_opts.lm_scale = ( - self._lm_weight * config.online_opts.lattice_postprocessor_opts.acoustic_scale - ) - config.online_opts.lattice_postprocessor_opts.nbest = self._nbest_size - self._config = config - - def _init_decoder(self): - - # use importers instead of direct import to possibly get an installation message - kaldifst = kaldifst_importer() - riva_decoder = riva_decoder_importer() - - from nemo.collections.asr.parts.utils.wfst_utils import load_word_lattice - - self._load_word_lattice = load_word_lattice - # BatchedMappedDecoderCuda supports filepaths only - # TODO: fix when possible - lm_fst = self._lm_fst - tmp_fst = None - tmp_fst_file = None - if isinstance(lm_fst, (Path, str)): - # We only read lm_fst to extract words.txt and num_tokens_with_blank - tmp_fst = kaldifst.StdVectorFst.read(lm_fst) - elif isinstance(lm_fst, (kaldifst.StdVectorFst, kaldifst.StdConstFst)): - tmp_fst = lm_fst - tmp_fst_file = tempfile.NamedTemporaryFile(mode='w+t') - tmp_fst.write(tmp_fst_file.name) - lm_fst = tmp_fst_file.name - else: - raise ValueError(f"Unsupported lm_fst type: {type(lm_fst)}") - - # we assume that lm_fst has at least one disambig after real tokens - num_tokens_with_blank = tmp_fst.input_symbols.find('#0') - 1 - if self._id2word is None: - self._id2word = { - int(line.split("\t")[1]): line.split("\t")[0] - for line in str(tmp_fst.output_symbols).strip().split("\n") - } - word2id = self._id2word.__class__(map(reversed, self._id2word.items())) - word_unk_id = word2id[""] - self._word2id = defaultdict(lambda: word_unk_id) - for k, v in word2id.items(): - self._word2id[k] = v - if self._id2token is None: - self._id2token = { - int(line.split("\t")[1]): line.split("\t")[0] - for line in str(tmp_fst.input_symbols).strip().split("\n") - } - token2id = self._id2token.__class__(map(reversed, self._id2token.items())) - token_unk_id = token2id[""] - self._token2id = defaultdict(lambda: token_unk_id) - for k, v in token2id.items(): - self._token2id[k] = v - with tempfile.NamedTemporaryFile(mode='w+t') as words_tmp: - tmp_fst.output_symbols.write_text(words_tmp.name) - config = riva_decoder.BatchedMappedDecoderCudaConfig() - _fill_inner_riva_config_(config, self._config) - self._decoder = riva_decoder.BatchedMappedDecoderCuda( - config, lm_fst, words_tmp.name, num_tokens_with_blank - ) - if tmp_fst_file: - tmp_fst_file.close() - - def _set_decoding_mode(self, decoding_mode: str): - if decoding_mode == 'nbest': - self._decode = self._decode_nbest - elif decoding_mode == 'mbr': - self._decode = self._decode_mbr - elif decoding_mode == 'lattice': - self._decode = self._decode_lattice - else: - raise ValueError(f"Unsupported mode: {decoding_mode}") - self._decoding_mode = decoding_mode - - def _beam_size_setter(self, value: float): - if self._beam_size != value: - self._release_gpu_memory() - self._config.online_opts.decoder_opts.lattice_beam = value - self._init_decoder() - self._beam_size = value - - def _lm_weight_setter(self, value: float): - if self._lm_weight != value: - self._release_gpu_memory() - self._config.online_opts.lattice_postprocessor_opts.lm_scale = ( - value * self._config.online_opts.lattice_postprocessor_opts.acoustic_scale - ) - self._init_decoder() - self._lm_weight = value - - def _decoding_mode_setter(self, value: str): - if self._decoding_mode != value: - self._set_decoding_mode(value) - - @property - def nbest_size(self): - return self._nbest_size - - @nbest_size.setter - def nbest_size(self, value: float): - self._nbest_size_setter(value) - - def _nbest_size_setter(self, value: float): - if self._nbest_size != value: - self._release_gpu_memory() - self._config.online_opts.lattice_postprocessor_opts.nbest = value - self._init_decoder() - self._nbest_size = value - - def _decode_nbest( - self, log_probs: torch.Tensor, log_probs_length: torch.Tensor - ) -> List[WfstNbestHypothesis]: # words, timesteps, alignment, score - """ - Decodes logprobs into recognition hypotheses via the N-best decoding decoding. - - Args: - log_probs: - A torch.Tensor of the predicted log-probabilities of shape [Batch, Time, Vocabulary]. - - log_probs_length: - A torch.Tensor of length `Batch` which contains the lengths of the log_probs elements. - - Returns: - List of WfstNbestHypothesis with empty alignment and trivial score. - """ - hypotheses_nbest = self._decoder.decode_nbest(log_probs, log_probs_length) - hypotheses = [] - for nh in hypotheses_nbest: - nbest_container = [] - for h in nh: - words, timesteps = [], [] - for w, t in zip(h.words, h.word_start_times_seconds): - if w != 0: - words.append(self._id2word[w]) - timesteps.append(int(t)) - alignment = [ilabel - 1 for ilabel in h.ilabels] - score = h.score - nbest_container.append(tuple([tuple(words), tuple(timesteps), tuple(alignment), score])) - hypotheses.append(WfstNbestHypothesis(tuple(nbest_container))) - return hypotheses - - def _decode_mbr(self, log_probs: torch.Tensor, log_probs_length: torch.Tensor) -> List[WfstNbestHypothesis]: - """ - Decodes logprobs into recognition hypotheses via the Minimum Bayes Risk (MBR) decoding. - - Args: - log_probs: - A torch.Tensor of the predicted log-probabilities of shape [Batch, Time, Vocabulary]. - - log_probs_length: - A torch.Tensor of length `Batch` which contains the lengths of the log_probs elements. - - Returns: - List of WfstNbestHypothesis with empty alignment and trivial score. - """ - hypotheses_mbr = self._decoder.decode_mbr(log_probs, log_probs_length) - hypotheses = [] - for h in hypotheses_mbr: - words, timesteps = [], [] - for e in h: - words.append(e[0]) - timesteps.append(int(e[1])) - hypotheses.append(WfstNbestHypothesis(tuple([tuple([tuple(words), tuple(timesteps), tuple(), 0.0])]))) - return hypotheses - - def _decode_lattice(self, log_probs: torch.Tensor, log_probs_length: torch.Tensor) -> List['KaldiWordLattice']: - """ - Decodes logprobs into kaldi-type lattices. - - Args: - log_probs: - A torch.Tensor of the predicted log-probabilities of shape [Batch, Time, Vocabulary]. - - log_probs_length: - A torch.Tensor of length `Batch` which contains the lengths of the log_probs elements. - - Returns: - List of KaldiWordLattice. - """ - with tempfile.NamedTemporaryFile() as tmp_lat: - tmp_lat_name = f"{tmp_lat.name}.lats" - self._decoder.decode_write_lattice( - log_probs, log_probs_length, [str(i) for i in range(len(log_probs))], f"ark,t:{tmp_lat_name}" - ) - hypotheses_lattice = self._load_word_lattice( - tmp_lat_name, self._id2word, self._id2word - ) # input and output token ids are the same - hypotheses = [hypotheses_lattice[str(i)] for i in range(len(log_probs))] - return hypotheses - - def decode( - self, log_probs: torch.Tensor, log_probs_length: torch.Tensor - ) -> Union[List[WfstNbestHypothesis], List['KaldiWordLattice']]: - """ - Decodes logprobs into recognition hypotheses. - - Args: - log_probs: - A torch.Tensor of the predicted log-probabilities of shape [Batch, Time, Vocabulary]. - - log_probs_length: - A torch.Tensor of length `Batch` which contains the lengths of the log_probs elements. - - Returns: - List of recognition hypotheses. - """ - log_probs = log_probs.contiguous() - log_probs_length = log_probs_length.to(torch.long).to('cpu').contiguous() - hypotheses = self._decode(log_probs, log_probs_length) - hypotheses = self._post_decode(hypotheses) - return hypotheses - - def _post_decode( - self, hypotheses: Union[List[WfstNbestHypothesis], List['KaldiWordLattice']] - ) -> Union[List[WfstNbestHypothesis], List['KaldiWordLattice']]: - """ - Does various post-processing of the recognition hypotheses. - - Args: - hypotheses: - List of recognition hypotheses. - - Returns: - List of processed recognition hypotheses. - """ - if self._open_vocabulary_decoding and self._decoding_mode in ('nbest', 'mbr'): - return collapse_tokenword_hypotheses(hypotheses, self._id2word[self._tokenword_disambig_id]) - else: - return hypotheses - - def calibrate_lm_weight( - self, log_probs: torch.Tensor, log_probs_length: torch.Tensor, reference_texts: List[str] - ) -> Tuple[float, float]: - """ - Calibrates LM weight to achieve the best WER for given logprob-text pairs. - - Args: - log_probs: - A torch.Tensor of the predicted log-probabilities of shape [Batch, Time, Vocabulary]. - - log_probs_length: - A torch.Tensor of length `Batch` which contains the lengths of the log_probs elements. - - reference_texts: - List of reference word sequences. - - Returns: - Pair of (best_lm_weight, best_wer). - """ - assert len(log_probs) == len(reference_texts) - decoding_mode_backup = self.decoding_mode - lm_weight_backup = self.lm_weight - self.decoding_mode = "mbr" - best_lm_weight, best_wer = -1.0, float('inf') - for lm_weight in range(1, 21): # enough for most cases - self.lm_weight = lm_weight / 10 - hypotheses = self.decode(log_probs, log_probs_length) - wer = word_error_rate([" ".join(h[0].words) for h in hypotheses], reference_texts) - print(lm_weight, wer) - if wer < best_wer: - best_lm_weight, best_wer = self.lm_weight, wer - self.decoding_mode = decoding_mode_backup - self.lm_weight = lm_weight_backup - return best_lm_weight, best_wer - - def calculate_oracle_wer( - self, log_probs: torch.Tensor, log_probs_length: torch.Tensor, reference_texts: List[str] - ) -> Tuple[float, List[float]]: - """ - Calculates the oracle (the best possible WER for given logprob-text pairs. - - Args: - log_probs: - A torch.Tensor of the predicted log-probabilities of shape [Batch, Time, Vocabulary]. - - log_probs_length: - A torch.Tensor of length `Batch` which contains the lengths of the log_probs elements. - - reference_texts: - List of reference word sequences. - - Returns: - Pair of (oracle_wer, oracle_wer_per_utterance). - """ - if self._open_vocabulary_decoding: - raise NotImplementedError - assert len(log_probs) == len(reference_texts) - decoding_mode_backup = self.decoding_mode - self.decoding_mode = "lattice" - lattices = self.decode(log_probs, log_probs_length) - scores, counts, wer_per_utt = [], [], [] - for lattice, text in zip(lattices, reference_texts): - word_ids = [self._word2id[w] for w in text.strip().split()] - counts.append(len(word_ids) if word_ids else 1) - scores.append(lattice.edit_distance(word_ids)) - wer_per_utt.append(scores[-1] / counts[-1]) - self.decoding_mode = decoding_mode_backup - return sum(scores) / sum(counts), wer_per_utt - - def _release_gpu_memory(self): - """ - Forces freeing of GPU memory by deleting the Riva decoder object. - """ - try: - del self._decoder - except Exception: - # apparently self._decoder was previously deleted, do nothing - pass - gc.collect() - - def __del__(self): - self._release_gpu_memory() diff --git a/nemo/collections/asr/parts/utils/__init__.py b/nemo/collections/asr/parts/utils/__init__.py deleted file mode 100644 index f1b3db0d294fb90ed2429040dbe3b65a2390f725..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.asr.parts.utils.rnnt_utils import BatchedAlignments, BatchedHyps, Hypothesis, NBestHypotheses diff --git a/nemo/collections/asr/parts/utils/activations.py b/nemo/collections/asr/parts/utils/activations.py deleted file mode 100644 index c4ba911e2e11329afd63d94bfe77377dc337591e..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/activations.py +++ /dev/null @@ -1,50 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import torch -import torch.nn as nn - -__all__ = ['Swish', 'Snake'] - - -@torch.jit.script -def snake(x: torch.Tensor, alpha: torch.Tensor, eps: float = 1e-9) -> torch.Tensor: - """ - equation for snake activation function: x + (alpha + eps)^-1 * sin(alpha * x)^2 - """ - shape = x.shape - x = x.reshape(shape[0], shape[1], -1) - x = x + (alpha + eps).reciprocal() * torch.sin(alpha * x).pow(2) - x = x.reshape(shape) - return x - - -class Snake(nn.Module): - """ - Snake activation function introduced in 'https://arxiv.org/abs/2006.08195' - """ - - def __init__(self, channels: int): - super().__init__() - self.alpha = nn.Parameter(torch.ones(1, channels, 1)) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - return snake(x, self.alpha) - - -class Swish(nn.SiLU): - """ - Swish activation function introduced in 'https://arxiv.org/abs/1710.05941' - Mathematically identical to SiLU. See note in nn.SiLU for references. - """ diff --git a/nemo/collections/asr/parts/utils/adapter_utils.py b/nemo/collections/asr/parts/utils/adapter_utils.py deleted file mode 100644 index b85bdee7051add57632496cdeb44f749dda36306..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/adapter_utils.py +++ /dev/null @@ -1,88 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from dataclasses import is_dataclass - -import torch -from omegaconf import DictConfig, OmegaConf - -from nemo.utils import logging - -# Constants -LINEAR_ADAPTER_CLASSPATH = "nemo.collections.common.parts.adapter_modules.LinearAdapter" - -# Conformer Adapters -MHA_ADAPTER_CLASSPATH = ( - "nemo.collections.asr.parts.submodules.adapters.multi_head_attention_adapter_module.MultiHeadAttentionAdapter" -) -RELMHA_ADAPTER_CLASSPATH = "nemo.collections.asr.parts.submodules.adapters.multi_head_attention_adapter_module.RelPositionMultiHeadAttentionAdapter" -POS_ENCODING_ADAPTER_CLASSPATH = ( - "nemo.collections.asr.parts.submodules.adapters.multi_head_attention_adapter_module.PositionalEncodingAdapter" -) -REL_POS_ENCODING_ADAPTER_CLASSPATH = ( - "nemo.collections.asr.parts.submodules.adapters.multi_head_attention_adapter_module.RelPositionalEncodingAdapter" -) - -# Transformer Adapters -TRANSFORMER_MHA_ADAPTER_CLASSPATH = "nemo.collections.asr.parts.submodules.adapters.transformer_multi_head_attention_adapter_module.TransformerMultiHeadAttentionAdapter" - - -def convert_adapter_cfg_to_dict_config(cfg: DictConfig): - # Convert to DictConfig from dict or Dataclass - if is_dataclass(cfg): - cfg = OmegaConf.structured(cfg) - - if not isinstance(cfg, DictConfig): - cfg = DictConfig(cfg) - - return cfg - - -def update_adapter_cfg_input_dim(module: torch.nn.Module, cfg: DictConfig, *, module_dim: int): - """ - Update the input dimension of the provided adapter config with some default value. - - Args: - module: The module that implements AdapterModuleMixin. - cfg: A DictConfig or a Dataclass representing the adapter config. - module_dim: A default module dimension, used if cfg has an incorrect input dimension. - - Returns: - A DictConfig representing the adapter's config. - """ - cfg = convert_adapter_cfg_to_dict_config(cfg) - - input_dim_valid_keys = ['in_features', 'n_feat', 'hidden_size'] - input_key = None - - for key in input_dim_valid_keys: - if key in cfg: - input_key = key - break - - if input_key is None: - raise ValueError( - f"Failed to infer the input dimension of the Adapter cfg. \nExpected one of : {input_dim_valid_keys}.\n" - f"Provided config : \n" - f"{OmegaConf.to_yaml(cfg)}" - ) - - input_dim = cfg[input_key] - - if input_dim != module_dim: - logging.info(f"Updating {module.__class__.__name__} Adapter input dim from {input_dim} to {module_dim}") - input_dim = module_dim - - cfg[input_key] = input_dim - return cfg diff --git a/nemo/collections/asr/parts/utils/aligner_utils.py b/nemo/collections/asr/parts/utils/aligner_utils.py deleted file mode 100644 index 9b18e934783bb3c3c285172a7e824b17990f0d8f..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/aligner_utils.py +++ /dev/null @@ -1,1060 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from dataclasses import dataclass, field -from pathlib import Path -from typing import List, Optional, Union - -import numpy as np -import torch -from torch.utils.data import DataLoader -from tqdm.auto import tqdm - -from nemo.collections.asr.models.asr_model import ASRModel -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis -from nemo.utils import logging - -BLANK_TOKEN = "" -SPACE_TOKEN = "" - - -@dataclass -class Token: - text: str = None - text_cased: str = None - token_id: int = None - token: str = None - s_start: int = None - s_end: int = None - t_start: float = None - t_end: float = None - - -@dataclass -class Word: - text: str = None - s_start: int = None - s_end: int = None - t_start: float = None - t_end: float = None - tokens: List[Token] = field(default_factory=list) - - -@dataclass -class Segment: - text: str = None - s_start: int = None - s_end: int = None - t_start: float = None - t_end: float = None - words_and_tokens: List[Union[Word, Token]] = field(default_factory=list) - - -@dataclass -class Utterance: - token_ids_with_blanks: List[int] = field(default_factory=list) - segments_and_tokens: List[Union[Segment, Token]] = field(default_factory=list) - text: Optional[str] = None - pred_text: Optional[str] = None - audio_filepath: Optional[str] = None - utt_id: Optional[str] = None - saved_output_files: dict = field(default_factory=dict) - - -def is_sub_or_superscript_pair(ref_text, text): - """returns True if ref_text is a subscript or superscript version of text""" - sub_or_superscript_to_num = { - "⁰": "0", - "¹": "1", - "²": "2", - "³": "3", - "⁴": "4", - "⁵": "5", - "⁶": "6", - "⁷": "7", - "⁸": "8", - "⁹": "9", - "₀": "0", - "₁": "1", - "₂": "2", - "₃": "3", - "₄": "4", - "₅": "5", - "₆": "6", - "₇": "7", - "₈": "8", - "₉": "9", - } - - if text in sub_or_superscript_to_num: - if sub_or_superscript_to_num[text] == ref_text: - return True - return False - - -def restore_token_case(word: str, word_tokens: List[str]) -> List[str]: - - # remove repeated "▁" and "_" from word as that is what the tokenizer will do - while "▁▁" in word: - word = word.replace("▁▁", "▁") - - while "__" in word: - word = word.replace("__", "_") - - word_tokens_cased = [] - word_char_pointer = 0 - - for token in word_tokens: - token_cased = "" - - for token_char in token: - if token_char == word[word_char_pointer]: - token_cased += token_char - word_char_pointer += 1 - - else: - if token_char.upper() == word[word_char_pointer] or is_sub_or_superscript_pair( - token_char, word[word_char_pointer] - ): - token_cased += token_char.upper() - word_char_pointer += 1 - else: - if token_char == "▁" or token_char == "_": - if ( - word[word_char_pointer] == "▁" - or word[word_char_pointer] == "_" - or word[word_char_pointer] == " " - ): - token_cased += token_char - word_char_pointer += 1 - elif word_char_pointer == 0: - token_cased += token_char - else: - raise RuntimeError( - f"Unexpected error - failed to recover capitalization of tokens for word {word}" - ) - - word_tokens_cased.append(token_cased) - - return word_tokens_cased - - -def get_char_tokens(text, model): - tokens = [] - for character in text: - if character in model.decoder.vocabulary: - tokens.append(model.decoder.vocabulary.index(character)) - else: - tokens.append(len(model.decoder.vocabulary)) # return unk token (same as blank token) - - return tokens - - -def _get_utt_id(audio_filepath, audio_filepath_parts_in_utt_id): - fp_parts = Path(audio_filepath).parts[-audio_filepath_parts_in_utt_id:] - utt_id = Path("_".join(fp_parts)).stem - utt_id = utt_id.replace(" ", "-") # replace any spaces in the filepath with dashes - return utt_id - - -def get_utt_obj( - text: str, - T: int, - model: ASRModel, - segment_separators: Union[str, List[str]] = ['.', '?', '!', '...'], - word_separator: Optional[str] = " ", - audio_filepath: Optional[str] = None, - utt_id: Optional[str] = None, -): - """ - Function to create an Utterance object and add all necessary information to it except - for timings of the segments / words / tokens according to the alignment - that will - be done later in a different function, after the alignment is done. - - The Utterance object has a list segments_and_tokens which contains Segment objects and - Token objects (for blank tokens in between segments). - Within the Segment objects, there is a list words_and_tokens which contains Word objects and - Token objects (for blank tokens in between words). - Within the Word objects, there is a list tokens tokens which contains Token objects for - blank and non-blank tokens. - We will be building up these lists in this function. This data structure will then be useful for - generating the various output files that we wish to save. - - Args: - text: the text to be aligned. - model: the ASR model to be used for alignment. It must have a `tokenizer` or `vocabulary` attribute. - separator: a string or a list of strings, that will be used to split the text into segments. - T: the number of frames in the log_probs. - audio_filepath: the path to the audio file. - utt_id: the ID of the utterance. - - Returns: - Utterance object with the following fields: - - text: the text to be aligned. - - audio_filepath: the path to the audio file if provided. - - utt_id: the ID of the utterance if provided. - - token_ids_with_blanks: a list of token IDs with blanks. - """ - - utt = Utterance( - text=text, - audio_filepath=audio_filepath, - utt_id=utt_id, - ) - - if not segment_separators: # if separator is not defined - treat the whole text as one segment - segments = [text.strip()] - else: - segment_separators = [segment_separators] if isinstance(segment_separators, str) else segment_separators - segments = [] - last_sep_idx = -1 - - for i, letter in enumerate(text): - # check if the current letter is a separator and the next letter is a space - # the additional space check is done to avoid splitting the words like "a.m." into segments - next_letter = text[i + 1] if i + 1 < len(text) else "" - if letter in segment_separators and next_letter == " ": - segments.append(text[last_sep_idx + 1 : i + 1].strip()) - last_sep_idx = i + 1 - - if last_sep_idx < len(text): - segments.append(text[last_sep_idx + 1 :].strip()) - - # remove any empty segments - segments = [seg for seg in segments if len(seg) > 0] - - # build up lists: token_ids_with_blanks, segments_and_tokens. - # The code for these is different depending on whether we use char-based tokens or not - if hasattr(model, 'tokenizer'): - if hasattr(model, 'blank_id'): - BLANK_ID = model.blank_id - else: - BLANK_ID = model.tokenizer.vocab_size - - if hasattr(model.tokenizer, 'unk_id'): - UNK_ID = model.tokenizer.unk_id - else: - UNK_ID = 0 - - UNK_WORD = model.tokenizer.ids_to_text([UNK_ID]).strip() - UNK_TOKEN = model.tokenizer.ids_to_tokens([UNK_ID])[0] - - utt.token_ids_with_blanks = [BLANK_ID] - - if len(text) == 0: - return utt - - # check for # tokens being > T - all_tokens = model.tokenizer.text_to_ids(text) - if len(all_tokens) > T: - logging.info( - f"Utterance with ID: {utt_id} has too many tokens compared to the audio file duration." - " Will not generate output alignment files for this utterance." - ) - return utt - - # build up data structures containing segments/words/tokens - utt.segments_and_tokens.append( - Token( - text=BLANK_TOKEN, - text_cased=BLANK_TOKEN, - token_id=BLANK_ID, - s_start=0, - s_end=0, - ) - ) - - segment_s_pointer = 1 # first segment will start at s=1 because s=0 is a blank - word_s_pointer = 1 # first word will start at s=1 because s=0 is a blank - - for segment in segments: - # add the segment to segment_info and increment the segment_s_pointer - segment_tokens = [] - sub_segments = segment.split(UNK_WORD) - for i, sub_segment in enumerate(sub_segments): - sub_segment_tokens = model.tokenizer.text_to_tokens(sub_segment.strip()) - segment_tokens.extend(sub_segment_tokens) - if i < len(sub_segments) - 1: - segment_tokens.append(UNK_ID) - # segment_tokens do not contain blanks => need to muliply by 2 - # s_end needs to be the index of the final token (including blanks) of the current segment: - # segment_s_pointer + len(segment_tokens) * 2 is the index of the first token of the next segment => - # => need to subtract 2 - - s_end = segment_s_pointer + len(segment_tokens) * 2 - 2 - utt.segments_and_tokens.append( - Segment( - text=segment, - s_start=segment_s_pointer, - s_end=s_end, - ) - ) - segment_s_pointer = s_end + 2 - - words = segment.split(word_separator) if word_separator not in [None, ""] else [segment] - - for word_i, word in enumerate(words): - - if word == UNK_WORD: - word_tokens = [UNK_TOKEN] - word_token_ids = [UNK_ID] - word_tokens_cased = [UNK_TOKEN] - elif UNK_WORD in word: - word_tokens = [] - word_token_ids = [] - word_tokens_cased = [] - for sub_word in word.split(UNK_WORD): - sub_word_tokens = model.tokenizer.text_to_tokens(sub_word) - sub_word_token_ids = model.tokenizer.text_to_ids(sub_word) - sub_word_tokens_cased = restore_token_case(sub_word, sub_word_tokens) - - word_tokens.extend(sub_word_tokens) - word_token_ids.extend(sub_word_token_ids) - word_tokens_cased.extend(sub_word_tokens_cased) - word_tokens.append(UNK_TOKEN) - word_token_ids.append(UNK_ID) - word_tokens_cased.append(UNK_TOKEN) - - word_tokens = word_tokens[:-1] - word_token_ids = word_token_ids[:-1] - word_tokens_cased = word_tokens_cased[:-1] - else: - word_tokens = model.tokenizer.text_to_tokens(word) - word_token_ids = model.tokenizer.text_to_ids(word) - word_tokens_cased = restore_token_case(word, word_tokens) - - # add the word to word_info and increment the word_s_pointer - word_s_end = word_s_pointer + len(word_tokens) * 2 - 2 - utt.segments_and_tokens[-1].words_and_tokens.append( - Word(text=word, s_start=word_s_pointer, s_end=word_s_end) - ) - word_s_pointer = word_s_end + 2 - - for token_i, (token, token_id, token_cased) in enumerate( - zip(word_tokens, word_token_ids, word_tokens_cased) - ): - # add the text tokens and the blanks in between them - # to our token-based variables - utt.token_ids_with_blanks.extend([token_id, BLANK_ID]) - # adding Token object for non-blank token - utt.segments_and_tokens[-1].words_and_tokens[-1].tokens.append( - Token( - text=token, - text_cased=token_cased, - token_id=token_id, - # utt.token_ids_with_blanks has the form [...., , ] => - # => if do len(utt.token_ids_with_blanks) - 1 you get the index of the final - # => we want to do len(utt.token_ids_with_blanks) - 2 to get the index of - s_start=len(utt.token_ids_with_blanks) - 2, - # s_end is same as s_start since the token only occupies one element in the list - s_end=len(utt.token_ids_with_blanks) - 2, - ) - ) - - # adding Token object for blank tokens in between the tokens of the word - # (ie do not add another blank if you have reached the end) - if token_i < len(word_tokens) - 1: - utt.segments_and_tokens[-1].words_and_tokens[-1].tokens.append( - Token( - text=BLANK_TOKEN, - text_cased=BLANK_TOKEN, - token_id=BLANK_ID, - # utt.token_ids_with_blanks has the form [...., ] => - # => if do len(utt.token_ids_with_blanks) -1 you get the index of this - s_start=len(utt.token_ids_with_blanks) - 1, - # s_end is same as s_start since the token only occupies one element in the list - s_end=len(utt.token_ids_with_blanks) - 1, - ) - ) - - # add a Token object for blanks in between words in this segment - # (but only *in between* - do not add the token if it is after the final word) - if word_i < len(words) - 1: - utt.segments_and_tokens[-1].words_and_tokens.append( - Token( - text=BLANK_TOKEN, - text_cased=BLANK_TOKEN, - token_id=BLANK_ID, - # utt.token_ids_with_blanks has the form [...., ] => - # => if do len(utt.token_ids_with_blanks) -1 you get the index of this - s_start=len(utt.token_ids_with_blanks) - 1, - # s_end is same as s_start since the token only occupies one element in the list - s_end=len(utt.token_ids_with_blanks) - 1, - ) - ) - - # add the blank token in between segments/after the final segment - utt.segments_and_tokens.append( - Token( - text=BLANK_TOKEN, - text_cased=BLANK_TOKEN, - token_id=BLANK_ID, - # utt.token_ids_with_blanks has the form [...., ] => - # => if do len(utt.token_ids_with_blanks) -1 you get the index of this - s_start=len(utt.token_ids_with_blanks) - 1, - # s_end is same as s_start since the token only occupies one element in the list - s_end=len(utt.token_ids_with_blanks) - 1, - ) - ) - - return utt - - elif hasattr(model.decoder, "vocabulary"): # i.e. tokenization is simply character-based - - BLANK_ID = len(model.decoder.vocabulary) - SPACE_ID = model.decoder.vocabulary.index(" ") - - utt.token_ids_with_blanks = [BLANK_ID] - - # check for text being 0 length - if len(text) == 0: - return utt - - # check for # tokens + token repetitions being > T - all_tokens = get_char_tokens(text, model) - n_token_repetitions = 0 - for i_tok in range(1, len(all_tokens)): - if all_tokens[i_tok] == all_tokens[i_tok - 1]: - n_token_repetitions += 1 - - if len(all_tokens) + n_token_repetitions > T: - logging.info( - f"Utterance {utt_id} has too many tokens compared to the audio file duration." - " Will not generate output alignment files for this utterance." - ) - return utt - - # build up data structures containing segments/words/tokens - utt.segments_and_tokens.append( - Token( - text=BLANK_TOKEN, - text_cased=BLANK_TOKEN, - token_id=BLANK_ID, - s_start=0, - s_end=0, - ) - ) - - segment_s_pointer = 1 # first segment will start at s=1 because s=0 is a blank - word_s_pointer = 1 # first word will start at s=1 because s=0 is a blank - - for i_segment, segment in enumerate(segments): - # add the segment to segment_info and increment the segment_s_pointer - segment_tokens = get_char_tokens(segment, model) - utt.segments_and_tokens.append( - Segment( - text=segment, - s_start=segment_s_pointer, - # segment_tokens do not contain blanks => need to muliply by 2 - # s_end needs to be the index of the final token (including blanks) of the current segment: - # segment_s_pointer + len(segment_tokens) * 2 is the index of the first token of the next segment => - # => need to subtract 2 - s_end=segment_s_pointer + len(segment_tokens) * 2 - 2, - ) - ) - - # for correct calculation: multiply len(segment_tokens) by 2 to account for blanks (which are not present in segment_tokens) - # and + 2 to account for [, ] - segment_s_pointer += len(segment_tokens) * 2 + 2 - - words = segment.split(" ") # we define words to be space-separated substrings - for i_word, word in enumerate(words): - - # convert string to list of characters - word_tokens = list(word) - # convert list of characters to list of their ids in the vocabulary - word_token_ids = get_char_tokens(word, model) - - # add the word to word_info and increment the word_s_pointer - utt.segments_and_tokens[-1].words_and_tokens.append( - # note for s_end: - # word_tokens do not contain blanks => need to muliply by 2 - # s_end needs to be the index of the final token (including blanks) of the current word: - # word_s_pointer + len(word_tokens) * 2 is the index of the first token of the next word => - # => need to subtract 2 - Word(text=word, s_start=word_s_pointer, s_end=word_s_pointer + len(word_tokens) * 2 - 2) - ) - - # for correct calculation: multiply len(word_tokens) by 2 to account for blanks (which are not present in word_tokens) - # and + 2 to account for [, ] - word_s_pointer += len(word_tokens) * 2 + 2 - - for token_i, (token, token_id) in enumerate(zip(word_tokens, word_token_ids)): - # add the text tokens and the blanks in between them - # to our token-based variables - utt.token_ids_with_blanks.extend([token_id]) - utt.segments_and_tokens[-1].words_and_tokens[-1].tokens.append( - Token( - text=token, - text_cased=token, - token_id=token_id, - # utt.token_ids_with_blanks has the form [..., ] - # => do len(utt.token_ids_with_blanks) - 1 to get the index of this non-blank token - s_start=len(utt.token_ids_with_blanks) - 1, - # s_end is same as s_start since the token only occupies one element in the list - s_end=len(utt.token_ids_with_blanks) - 1, - ) - ) - - if token_i < len(word_tokens) - 1: # only add blank tokens that are in the middle of words - utt.token_ids_with_blanks.extend([BLANK_ID]) - utt.segments_and_tokens[-1].words_and_tokens[-1].tokens.append( - Token( - text=BLANK_TOKEN, - text_cased=BLANK_TOKEN, - token_id=BLANK_ID, - # utt.token_ids_with_blanks has the form [..., ] - # => do len(utt.token_ids_with_blanks) - 1 to get the index of this blank token - s_start=len(utt.token_ids_with_blanks) - 1, - # s_end is same as s_start since the token only occupies one element in the list - s_end=len(utt.token_ids_with_blanks) - 1, - ) - ) - - # add space token (and the blanks around it) unless this is the final word in a segment - if i_word < len(words) - 1: - utt.token_ids_with_blanks.extend([BLANK_ID, SPACE_ID, BLANK_ID]) - utt.segments_and_tokens[-1].words_and_tokens.append( - Token( - text=BLANK_TOKEN, - text_cased=BLANK_TOKEN, - token_id=BLANK_ID, - # utt.token_ids_with_blanks has the form - # [..., , , , ] - # => do len(utt.token_ids_with_blanks) - 3 to get the index of the blank token before the space token - s_start=len(utt.token_ids_with_blanks) - 3, - # s_end is same as s_start since the token only occupies one element in the list - s_end=len(utt.token_ids_with_blanks) - 3, - ) - ) - utt.segments_and_tokens[-1].words_and_tokens.append( - Token( - text=SPACE_TOKEN, - text_cased=SPACE_TOKEN, - token_id=SPACE_ID, - # utt.token_ids_with_blanks has the form - # [..., , , , ] - # => do len(utt.token_ids_with_blanks) - 2 to get the index of the space token - s_start=len(utt.token_ids_with_blanks) - 2, - # s_end is same as s_start since the token only occupies one element in the list - s_end=len(utt.token_ids_with_blanks) - 2, - ) - ) - utt.segments_and_tokens[-1].words_and_tokens.append( - Token( - text=BLANK_TOKEN, - text_cased=BLANK_TOKEN, - token_id=BLANK_ID, - # utt.token_ids_with_blanks has the form - # [..., , , , ] - # => do len(utt.token_ids_with_blanks) - 1 to get the index of the blank token after the space token - s_start=len(utt.token_ids_with_blanks) - 1, - # s_end is same as s_start since the token only occupies one element in the list - s_end=len(utt.token_ids_with_blanks) - 1, - ) - ) - - # add a blank to the segment, and add a space after if this is not the final segment - utt.token_ids_with_blanks.extend([BLANK_ID]) - utt.segments_and_tokens.append( - Token( - text=BLANK_TOKEN, - text_cased=BLANK_TOKEN, - token_id=BLANK_ID, - # utt.token_ids_with_blanks has the form [..., ] - # => do len(utt.token_ids_with_blanks) - 1 to get the index of this blank token - s_start=len(utt.token_ids_with_blanks) - 1, - # s_end is same as s_start since the token only occupies one element in the list - s_end=len(utt.token_ids_with_blanks) - 1, - ) - ) - - if i_segment < len(segments) - 1: - utt.token_ids_with_blanks.extend([SPACE_ID, BLANK_ID]) - utt.segments_and_tokens.append( - Token( - text=SPACE_TOKEN, - text_cased=SPACE_TOKEN, - token_id=SPACE_ID, - # utt.token_ids_with_blanks has the form - # [..., , ] - # => do len(utt.token_ids_with_blanks) - 2 to get the index of the space token - s_start=len(utt.token_ids_with_blanks) - 2, - # s_end is same as s_start since the token only occupies one element in the list - s_end=len(utt.token_ids_with_blanks) - 2, - ) - ) - utt.segments_and_tokens.append( - Token( - text=BLANK_TOKEN, - text_cased=BLANK_TOKEN, - token_id=BLANK_ID, - # utt.token_ids_with_blanks has the form - # [..., , ] - # => do len(utt.token_ids_with_blanks) - 1 to get the index of the blank token - s_start=len(utt.token_ids_with_blanks) - 1, - # s_end is same as s_start since the token only occupies one element in the list - s_end=len(utt.token_ids_with_blanks) - 1, - ) - ) - - return utt - - else: - raise RuntimeError( - "Cannot get tokens of this model as it does not have a `tokenizer` or `vocabulary` attribute." - ) - - -def add_t_start_end_to_utt_obj(utt_obj: Utterance, alignment_utt: List[int], output_timestep_duration: float): - """ - Function to add t_start and t_end (representing time in seconds) to the Utterance object utt_obj. - Args: - utt_obj: Utterance object to which we will add t_start and t_end for its - constituent segments/words/tokens. - alignment_utt: a list of ints indicating which token does the alignment pass through at each - timestep (will take the form [0, 0, 1, 1, ..., ]). - output_timestep_duration: a float indicating the duration of a single output timestep from - the ASR Model. - - Returns: - utt_obj: updated Utterance object. - """ - - # General idea for the algorithm of how we add t_start and t_end - # the timestep where a token s starts is the location of the first appearance of s_start in alignment_utt - # the timestep where a token s ends is the location of the final appearance of s_end in alignment_utt - # We will make dictionaries num_to_first_alignment_appearance and - # num_to_last_appearance and use that to update all of - # the t_start and t_end values in utt_obj. - # We will put t_start = t_end = -1 for tokens that are skipped (should only be blanks) - - num_to_first_alignment_appearance = dict() - num_to_last_alignment_appearance = dict() - - prev_token_idx = -1 # use prev_token_idx to keep track of when the token_idx changes - for timestep, token_idx in enumerate(alignment_utt): - if token_idx > prev_token_idx: - num_to_first_alignment_appearance[token_idx] = timestep - - if prev_token_idx >= 0: # dont record prev_token_idx = -1 - num_to_last_alignment_appearance[prev_token_idx] = timestep - 1 - prev_token_idx = token_idx - # add last appearance of the final s - num_to_last_alignment_appearance[prev_token_idx] = len(alignment_utt) - 1 - - # update all the t_start and t_end in utt_obj - for segment_or_token in utt_obj.segments_and_tokens: - if type(segment_or_token) is Segment: - segment = segment_or_token - - if segment.s_start in num_to_first_alignment_appearance: - segment.t_start = num_to_first_alignment_appearance[segment.s_start] * output_timestep_duration - else: - segment.t_start = -1 - - if segment.s_end in num_to_last_alignment_appearance: - segment.t_end = (num_to_last_alignment_appearance[segment.s_end] + 1) * output_timestep_duration - else: - segment.t_end = -1 - - for word_or_token in segment.words_and_tokens: - if type(word_or_token) is Word: - word = word_or_token - - if word.s_start in num_to_first_alignment_appearance: - word.t_start = num_to_first_alignment_appearance[word.s_start] * output_timestep_duration - else: - word.t_start = -1 - - if word.s_end in num_to_last_alignment_appearance: - word.t_end = (num_to_last_alignment_appearance[word.s_end] + 1) * output_timestep_duration - else: - word.t_end = -1 - - for token in word.tokens: - if token.s_start in num_to_first_alignment_appearance: - token.t_start = num_to_first_alignment_appearance[token.s_start] * output_timestep_duration - else: - token.t_start = -1 - - if token.s_end in num_to_last_alignment_appearance: - token.t_end = ( - num_to_last_alignment_appearance[token.s_end] + 1 - ) * output_timestep_duration - else: - token.t_end = -1 - else: - token = word_or_token - if token.s_start in num_to_first_alignment_appearance: - token.t_start = num_to_first_alignment_appearance[token.s_start] * output_timestep_duration - else: - token.t_start = -1 - - if token.s_end in num_to_last_alignment_appearance: - token.t_end = (num_to_last_alignment_appearance[token.s_end] + 1) * output_timestep_duration - else: - token.t_end = -1 - - else: - token = segment_or_token - if token.s_start in num_to_first_alignment_appearance: - token.t_start = num_to_first_alignment_appearance[token.s_start] * output_timestep_duration - else: - token.t_start = -1 - - if token.s_end in num_to_last_alignment_appearance: - token.t_end = (num_to_last_alignment_appearance[token.s_end] + 1) * output_timestep_duration - else: - token.t_end = -1 - - return utt_obj - - -def viterbi_decoding( - log_probs_batch: torch.Tensor, - y_batch: torch.Tensor, - T_batch: torch.Tensor, - U_batch: torch.Tensor, - viterbi_device: Optional[torch.device] = None, - padding_value: float = -3.4e38, -): - """ - Do Viterbi decoding with an efficient algorithm (the only for-loop in the 'forward pass' is over the time dimension). - Args: - log_probs_batch: tensor of shape (B, T_max, V). The parts of log_probs_batch which are 'padding' are filled - with 'padding_value' - y_batch: tensor of shape (B, U_max) - contains token IDs including blanks. The parts of - y_batch which are padding are filled with the number 'V'. V = the number of tokens in the vocabulary + 1 for - the blank token. - T_batch: tensor of shape (B) - contains the durations of the log_probs_batch (so we can ignore the - parts of log_probs_batch which are padding) - U_batch: tensor of shape (B) - contains the lengths of y_batch (so we can ignore the parts of y_batch - which are padding). - viterbi_device: the torch device on which Viterbi decoding will be done. - padding_value: - a large negative number which represents a very low probability. Default to -3.4e38, the smallest number in torch.float32. - - Returns: - alignments_batch: list of lists containing locations for the tokens we align to at each timestep. - Looks like: [[0, 0, 1, 2, 2, 3, 3, ..., ], ..., [0, 1, 2, 2, 2, 3, 4, ....]]. - Each list inside alignments_batch is of length T_batch[location of utt in batch]. - """ - - if viterbi_device is None: - viterbi_device = "cuda" if torch.cuda.is_available() else "cpu" - - B, T_max, _ = log_probs_batch.shape - U_max = y_batch.shape[1] - - # transfer all tensors to viterbi_device - log_probs_batch = log_probs_batch.to(viterbi_device) - y_batch = y_batch.to(viterbi_device) - T_batch = T_batch.to(viterbi_device) - U_batch = U_batch.to(viterbi_device) - - # make tensor that we will put at timesteps beyond the duration of the audio - padding_for_log_probs = padding_value * torch.ones((B, T_max, 1), device=viterbi_device) - # make log_probs_padded tensor of shape (B, T_max, V +1 ) where all of - # log_probs_padded[:,:,-1] is the 'padding_value' - log_probs_padded = torch.cat((log_probs_batch, padding_for_log_probs), dim=2) - - # initialize v_prev - tensor of previous timestep's viterbi probabilies, of shape (B, U_max) - v_prev = padding_value * torch.ones((B, U_max), device=viterbi_device) - - v_prev[:, :2] = torch.gather(input=log_probs_padded[:, 0, :], dim=1, index=y_batch[:, :2]) - - # initialize backpointers_rel - which contains values like 0 to indicate the backpointer is to the same u index, - # 1 to indicate the backpointer pointing to the u-1 index and 2 to indicate the backpointer is pointing to the u-2 index - backpointers_rel = -99 * torch.ones((B, T_max, U_max), dtype=torch.int8, device=viterbi_device) - - # Make a letter_repetition_mask the same shape as y_batch - # the letter_repetition_mask will have 'True' where the token (including blanks) is the same - # as the token two places before it in the ground truth (and 'False everywhere else). - # We will use letter_repetition_mask to determine whether the Viterbi algorithm needs to look two tokens back or - # three tokens back - y_shifted_left = torch.roll(y_batch, shifts=2, dims=1) - letter_repetition_mask = y_batch - y_shifted_left - letter_repetition_mask[:, :2] = 1 # make sure dont apply mask to first 2 tokens - letter_repetition_mask = letter_repetition_mask == 0 - - for t in range(1, T_max): - - # e_current is a tensor of shape (B, U_max) of the log probs of every possible token at the current timestep - e_current = torch.gather(input=log_probs_padded[:, t, :], dim=1, index=y_batch) - - # apply a mask to e_current to cope with the fact that we do not keep the whole v_matrix and continue - # calculating viterbi probabilities during some 'padding' timesteps - t_exceeded_T_batch = t >= T_batch - - U_can_be_final = torch.logical_or( - torch.arange(0, U_max, device=viterbi_device).unsqueeze(0) == (U_batch.unsqueeze(1) - 0), - torch.arange(0, U_max, device=viterbi_device).unsqueeze(0) == (U_batch.unsqueeze(1) - 1), - ) - - mask = torch.logical_not( - torch.logical_and( - t_exceeded_T_batch.unsqueeze(1), - U_can_be_final, - ) - ).long() - - e_current = e_current * mask - - # v_prev_shifted is a tensor of shape (B, U_max) of the viterbi probabilities 1 timestep back and 1 token position back - v_prev_shifted = torch.roll(v_prev, shifts=1, dims=1) - # by doing a roll shift of size 1, we have brought the viterbi probability in the final token position to the - # first token position - let's overcome this by 'zeroing out' the probabilities in the firest token position - v_prev_shifted[:, 0] = padding_value - - # v_prev_shifted2 is a tensor of shape (B, U_max) of the viterbi probabilities 1 timestep back and 2 token position back - v_prev_shifted2 = torch.roll(v_prev, shifts=2, dims=1) - v_prev_shifted2[:, :2] = padding_value # zero out as we did for v_prev_shifted - # use our letter_repetition_mask to remove the connections between 2 blanks (so we don't skip over a letter) - # and to remove the connections between 2 consective letters (so we don't skip over a blank) - v_prev_shifted2.masked_fill_(letter_repetition_mask, padding_value) - - # we need this v_prev_dup tensor so we can calculated the viterbi probability of every possible - # token position simultaneously - v_prev_dup = torch.cat( - ( - v_prev.unsqueeze(2), - v_prev_shifted.unsqueeze(2), - v_prev_shifted2.unsqueeze(2), - ), - dim=2, - ) - - # candidates_v_current are our candidate viterbi probabilities for every token position, from which - # we will pick the max and record the argmax - candidates_v_current = v_prev_dup + e_current.unsqueeze(2) - # we straight away save results in v_prev instead of v_current, so that the variable v_prev will be ready for the - # next iteration of the for-loop - v_prev, bp_relative = torch.max(candidates_v_current, dim=2) - - backpointers_rel[:, t, :] = bp_relative - - # trace backpointers - alignments_batch = [] - for b in range(B): - T_b = int(T_batch[b]) - U_b = int(U_batch[b]) - - if U_b == 1: # i.e. we put only a blank token in the reference text because the reference text is empty - current_u = 0 # set initial u to 0 and let the rest of the code block run as usual - else: - current_u = int(torch.argmax(v_prev[b, U_b - 2 : U_b])) + U_b - 2 - alignment_b = [current_u] - for t in range(T_max - 1, 0, -1): - current_u = current_u - int(backpointers_rel[b, t, current_u]) - alignment_b.insert(0, current_u) - alignment_b = alignment_b[:T_b] - alignments_batch.append(alignment_b) - - return alignments_batch - - -def get_batch_variables( - audio: Union[str, List[str], np.ndarray, DataLoader, Hypothesis], - model: ASRModel, - segment_separators: Union[str, List[str]] = ['.', '?', '!', '...'], - word_separator: Optional[str] = " ", - align_using_pred_text: bool = False, - audio_filepath_parts_in_utt_id: int = 1, - gt_text_batch: Union[List[str], str] = None, - output_timestep_duration: Optional[float] = None, - simulate_cache_aware_streaming: bool = False, - use_buffered_chunked_streaming: bool = False, - buffered_chunk_params: dict = {}, - padding_value: float = -3.4e38, - has_hypotheses: bool = False, - verbose: bool = True, -): - """ - Args: - audio: a single audio file, a list of audio files, a numpy array, or a DataLoader that needs to be transcribed. - Note: if using streaming mode, audio must be a list of audio files or a single audio file (not a numpy array or a DataLoader). - model: an ASRModel, supports transcribe and transcribe_simulate_cache_aware_streaming methods. - separator: a string or a list of strings, that will be used to split the text into segments. - align_using_pred_text: a boolean, if True, the predicted text will be used for alignment. - audio_filepath_parts_in_utt_id: an integer, the number of parts of the audio filepath to use for the utterance ID. - gt_text_batch: a list of ground truth texts for the audio files. If provided, it will be used for alignment instead of the predicted text. - output_timestep_duration: a float, the duration of a single frame (output timestep) in seconds. - simulate_cache_aware_streaming: a boolean, if True, the cache-aware streaming will be used. - use_buffered_chunked_streaming: a boolean, if True, the buffered chunked streaming will be used. - buffered_chunk_params: a dictionary, containing the parameters for the buffered chunked streaming. - padding_value: a float, the value to use for padding the log_probs tensor. - has_hypotheses: a boolean, if True, the audio has already been processed and hypotheses are provided. - - Returns: - log_probs_batch: a tensor of shape (B, T_max, V) - contains the log probabilities of the tokens for each utterance in the batch. - The parts of log_probs_batch which are 'padding' are filled with 'padding_value', which is a large negative number. - y_batch: a tensor of shape (B, U_max) - contains token IDs including blanks in every other position. - The parts of y_batch which are padding are filled with the number 'V'. V = the number of tokens in the vocabulary + 1 for the blank token. - T_batch: a tensor of shape (B) - contains the number of frames in the log_probs for each utterance in the batch. - U_batch: a tensor of shape (B) - contains the lengths of token_ids_with_blanks for each utterance in the batch. - utt_obj_batch: a list of Utterance objects for every utterance in the batch. Each Utterance object contains the token_ids_with_blanks, segments_and_tokens, text, pred_text, audio_filepath, utt_id, and saved_output_files. - output_timestep_duration: a float indicating the duration of a single output timestep from - the ASR Model in milliseconds. - """ - - if output_timestep_duration is None: - try: - output_timestep_duration = model.cfg['preprocessor']['window_stride'] * model.encoder.subsampling_factor - logging.info( - f"`output_timestep_duration` is not provided, so we calculated that the model output_timestep_duration is {output_timestep_duration} ms." - " -- will use this for all batches" - ) - except: - raise ValueError("output_timestep_duration is not provided and cannot be calculated from the model.") - - if simulate_cache_aware_streaming or use_buffered_chunked_streaming: - if not (isinstance(audio, list) and all(isinstance(item, str) for item in audio)) and not isinstance( - audio, str - ): - raise ValueError("Audio must be a list of audio files or a single audio file when using streaming mode.") - - if isinstance(audio, str): - audio = [audio] - - if gt_text_batch is not None: - if isinstance(gt_text_batch, str): - gt_text_batch = [gt_text_batch] - if len(gt_text_batch) != len(audio): - raise ValueError("`gt_text_batch` must be the same length as `audio` for performing alignment.") - - # get hypotheses by calling 'transcribe' - # we will use the output log_probs, the duration of the log_probs, - # and (optionally) the predicted ASR text from the hypotheses - - batch_size = len(audio) - log_probs_list_batch = [] # log_probs is the output of the ASR model, with a shape (T, V+1) - T_list_batch = [] # T is the number of frames in the log_probs - pred_text_batch = [] # pred_text is the predicted text from the ASR model - - if not use_buffered_chunked_streaming: - if not simulate_cache_aware_streaming: - with torch.no_grad(): - if has_hypotheses: - hypotheses = audio - else: - hypotheses = model.transcribe( - audio, return_hypotheses=True, batch_size=batch_size, verbose=verbose - ) - else: - assert isinstance(audio, list) or isinstance( - audio, str - ), "audio must be a list of audio files or a single audio file" - with torch.no_grad(): - hypotheses = model.transcribe_simulate_cache_aware_streaming( - audio, return_hypotheses=True, batch_size=batch_size - ) - - # if hypotheses form a tuple (from Hybrid model), extract just "best" hypothesis - if type(hypotheses) == tuple and len(hypotheses) == 2: - hypotheses = hypotheses[0] - - for hypothesis in hypotheses: - log_probs_list_batch.append(hypothesis.y_sequence) - T_list_batch.append(hypothesis.y_sequence.shape[0]) - pred_text_batch.append(hypothesis.text) - else: - delay = buffered_chunk_params["delay"] - model_stride_in_secs = buffered_chunk_params["model_stride_in_secs"] - tokens_per_chunk = buffered_chunk_params["tokens_per_chunk"] - for audio_sample in tqdm(audio, desc="Sample:"): - model.reset() - model.read_audio_file(audio_sample, delay, model_stride_in_secs) - hyp, logits = model.transcribe(tokens_per_chunk, delay, keep_logits=True) - log_probs_list_batch.append(logits) - T_list_batch.append(logits.shape[0]) - pred_text_batch.append(hyp) - - # we loop over every line in the manifest that is in our current batch, - # and record the y (list of tokens, including blanks), U (list of lengths of y) and - # token_info_batch, word_info_batch, segment_info_batch - - y_list_batch = [] # List of lists of token IDs with blanks, where each token is followed by a blank - U_list_batch = [] # List of lengths of y_list_batch - utt_obj_batch = [] # List of Utterance objects for every utterance in the batch - - for idx, sample in enumerate(audio): - - if align_using_pred_text: - # normalizes the predicted text by removing extra spaces - gt_text_for_alignment = pred_text_batch[idx] - else: - gt_text_for_alignment = gt_text_batch[idx] - - gt_text_for_alignment = " ".join(gt_text_for_alignment.split()) - - utt_obj = get_utt_obj( - text=gt_text_for_alignment, - model=model, - segment_separators=segment_separators, - word_separator=word_separator, - T=T_list_batch[idx], - audio_filepath=sample if isinstance(sample, str) else f"audio_{idx}", - utt_id=_get_utt_id(sample if isinstance(sample, str) else f"audio_{idx}", audio_filepath_parts_in_utt_id), - ) - - if len(gt_text_for_alignment) == 0: - logging.info( - f"'text' of utterance with ID: {utt_obj.utt_id} is empty - we will not generate" - " any output alignment files for this utterance" - ) - - if align_using_pred_text: - utt_obj.pred_text = pred_text_batch[idx] - utt_obj.text = " ".join(pred_text_batch[idx].split()) if pred_text_batch[idx] else None - - y_list_batch.append(utt_obj.token_ids_with_blanks) - U_list_batch.append(len(utt_obj.token_ids_with_blanks)) - utt_obj_batch.append(utt_obj) - - # turn log_probs, y, T, U into dense tensors for fast computation during Viterbi decoding - T_max = max(T_list_batch) - U_max = max(U_list_batch) - - # V = the number of tokens in the vocabulary + 1 for the blank token. - if hasattr(model, 'tokenizer'): - V = len(model.tokenizer.vocab) + 1 - else: - V = len(model.decoder.vocabulary) + 1 - - T_batch = torch.tensor(T_list_batch) - U_batch = torch.tensor(U_list_batch) - - # make log_probs_batch tensor of shape (B x T_max x V) - log_probs_batch = padding_value * torch.ones((batch_size, T_max, V)) - for b, log_probs_utt in enumerate(log_probs_list_batch): - t = T_list_batch[b] - log_probs_batch[b, :t, :] = log_probs_utt - - # make y tensor of shape (B x U_max) - # populate it initially with all 'V' numbers so that the 'V's will remain in the areas that - # are 'padding'. This will be useful for when we make 'log_probs_reorderd' during Viterbi decoding - # in a different function. - y_batch = V * torch.ones((batch_size, U_max), dtype=torch.int64) - for b, y_utt in enumerate(y_list_batch): - U_utt = U_batch[b] - y_batch[b, :U_utt] = torch.tensor(y_utt) - - return ( - log_probs_batch, - y_batch, - T_batch, - U_batch, - utt_obj_batch, - output_timestep_duration, - ) diff --git a/nemo/collections/asr/parts/utils/asr_batching.py b/nemo/collections/asr/parts/utils/asr_batching.py deleted file mode 100644 index c9bdab94f1f452cf0d095ac41b0f4275e9d55e53..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/asr_batching.py +++ /dev/null @@ -1,240 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import math -from typing import Iterator, List, Optional, Union - -import numpy as np -import torch -from torch.utils.data.distributed import DistributedSampler - -from nemo.collections.asr.data.audio_to_text import AudioToBPEDataset, AudioToCharDataset -from nemo.collections.asr.models.asr_model import ASRModel -from nemo.utils import logging - - -class SemiSortBatchSampler(DistributedSampler): - def __init__( - self, - global_rank: int, - world_size: int, - durations: List[int], - batch_size: int, - batch_shuffle: bool = True, - drop_last: bool = False, - randomization_factor: Optional[float] = None, - seed: int = 42, - ) -> None: - r""" - Semi Sorted Batching, as proposed in _SSB ("Speed up training with variable - length inputs by efficient batching strategies.", Zhenhao Ge et al. (2021).). - - The Semi Sorted Batch Sampler (SSB) samples the indices by their duration - with the addition of pseudo noise that is sampled from the uniform - distribution \mathbb{U}\left[ -delta * r, delta * r \right], where delta is - defined as the difference between the maximum and minimum duration and r is - the randomization factor that controls the strength of the noise (when r = 0, - there will be a strong sorting). The heuristic value of the r according to - the experiments from paper is 0.2. - - The torch calls the set_epoch method from the distributed data loader sampler - at the end of each epoch to shuffle the samples according to the seed and - epoch number. So the SSB is passed to the dataloader as a sampler with the - dataloader's batch size options and the batch_sampler option set to None to - disable automatical batching. In this case, the sampler has become an iterator - that returns a list of batch indices. - - Args: - global_rank: Rank among all GPUs. - world_size: The number of GPUs used. - durations: Sample durations parsed from `dataset.manifest_processor`. - batch_size: Micro batch size or batch size per singe gpu. - batch_shuffle: Batch sort before each epoch. - drop_last: Drop the last batch if the number of samples is less than batch - size. Defaults to False. - randomization_factor: The strength of noise that will be added to the sample - duration. If no value is passed, the value 0.2 will be used. - seed: Seed for batch shuffleling. Defaults to 42. - - Raises: - ValueError: Wrong randomization factor value. - RuntimeError: Unexpected behavior. - - .. SSB_: - https://www.isca-archive.org/interspeech_2021/ge21_interspeech.pdf - """ - if randomization_factor is None: - randomization_factor = 0.1 - logging.info("Randomization factor not found in config, default value 0.1 will be set.") - else: - logging.info(f"A randomization factor {randomization_factor} will be used.") - - if randomization_factor < 0.0: - raise ValueError(f'Randomization factor must be non-negative but found {randomization_factor}.') - - self.rank: List = global_rank - self.num_replicas: int = world_size - - self.durations: np.array = np.array(durations, dtype=np.float32) - - self.shuffle: bool = batch_shuffle - self.micro_batch_size: int = batch_size - self.drop_last: bool = drop_last - self.epoch: int = 0 - self.seed: int = seed - self.randomization_factor: float = randomization_factor - - self.local_num_batches: int = self._calculate_local_num_batches() - - logging.info(f"Semi Sorted Batch Sampler will be used") - - def _calculate_local_num_batches(self) -> int: - init_num_samples = len(self.durations) - - # delete batches with a non-integer number of samples - if self.drop_last: - init_num_samples -= init_num_samples % self.micro_batch_size - - # calculate the number of batches according to the counted number of samples - global_num_batches = math.ceil(init_num_samples / self.micro_batch_size) - - # add extra batches to make it divisible by world size (num replicas) - num_batches_pad = (self.num_replicas - global_num_batches % self.num_replicas) % self.num_replicas - global_num_batches += num_batches_pad - - # calculate the number of batches per rank - local_num_batches = global_num_batches // self.num_replicas - - return local_num_batches - - def _make_batches(self) -> List[np.array]: - max_duration: float = np.max(self.durations) - min_duration: float = np.min(self.durations) - bound: float = (max_duration - min_duration) * self.randomization_factor / 2 - - # generate pseudo noise - noise: np.array = np.random.uniform(low=-bound, high=bound, size=len(self.durations)) - - # sort indices accroding to pseudo noise - sorted_indices: np.array = np.argsort(self.durations + noise) - - # delete batches with a non-integer number of samples - tail = 0 - if self.drop_last: - tail: int = len(sorted_indices) % self.micro_batch_size - exclude = np.random.choice(len(sorted_indices), tail, replace=False) - sorted_indices = np.delete(sorted_indices, exclude) - logging.warning(f"Drop last is set to True, so {len(exclude)} samples will be dropped.") - - global_num_batches: int = math.ceil(len(sorted_indices) / self.micro_batch_size) - - # if the global_num_batches is zero than return empty list - if global_num_batches == 0: - logging.warning( - f"The number of all batches is {global_num_batches}, than dataloader will " - "be empty. To avoid this try to decrease batch size or world size or set " - "drop_last to False." - ) - return [] - - # add extra batches to make it divisible by world size (num replicas) - pad_batches_num: int = (self.num_replicas - global_num_batches % self.num_replicas) % self.num_replicas - if global_num_batches < self.num_replicas: - logging.warning( - f"The number of all batches is {global_num_batches}, which is less than the " - f"world size of {self.num_replicas}. SSB Sampler will add {pad_batches_num} " - "batches. To avoid this try to decrease batch size or world size." - ) - - if pad_batches_num != 0: - # randomly select batch indeces to pad and concatenate them - batch_indeces_pad: np.array = np.random.randint( - low=0, - high=len(sorted_indices), - size=pad_batches_num * self.micro_batch_size, - ) - sorted_indices: np.array = np.concatenate( - (sorted_indices, sorted_indices[batch_indeces_pad]), - axis=0, - ) - - # local indeces are selected by world size and local rank - local_indices: np.array = sorted_indices[self.rank :: self.num_replicas] - - # split local batches - size_mask = range(self.micro_batch_size, len(local_indices), self.micro_batch_size) - local_batches = np.split(local_indices, size_mask, axis=0) - - if len(local_batches) != self.local_num_batches: - raise RuntimeError( - f'Number of calculated indices {len(local_batches)} is not equal to calculated ' - f'number of local batches {self.local_num_batches}.' - ) - - return local_batches - - def __iter__(self) -> Iterator[List[int]]: - local_batches = self._make_batches() - - if self.shuffle: - g = torch.Generator() - g.manual_seed(self.seed + self.epoch + 1) - indices = torch.randperm(self.local_num_batches, generator=g) - else: - indices = torch.arange(0, self.local_num_batches) - - for _, index in enumerate(indices): - yield local_batches[index] - - def __len__(self) -> int: - return self.local_num_batches - - -def get_semi_sorted_batch_sampler( - model: ASRModel, dataset: Union[AudioToCharDataset, AudioToBPEDataset], config: dict -) -> SemiSortBatchSampler: - """ - Instantiates a Semi Sorted (Batch) Sampler. - - Args: - model: ASR Model. - dataset: Dataset which allow iterate over all object and parse durations. - config: Train, Vaidation or Test dataset config. - - Raises: - ValueError: Wrong dataset type. - - Returns: - SemiSortBatchSampler: Semi Sorted Batch Sampler class. - """ - if not (isinstance(dataset, AudioToCharDataset) or isinstance(dataset, AudioToBPEDataset)): - raise ValueError( - "Only AudioToCharDataset or AudioToBPEDataset supported with semi sorted batching, " - f"but found {type(dataset)}." - ) - - durations = [sample.duration for sample in dataset.manifest_processor.collection.data] - - sampler = SemiSortBatchSampler( - global_rank=model.global_rank, - world_size=model.world_size, - durations=durations, - batch_size=config['batch_size'], - batch_shuffle=config.get('shuffle', True), - drop_last=config.get('drop_last', False), - randomization_factor=config.get('randomization_factor', None), - seed=config.get('semi_sort_sampler_seed', 42), - ) - - return sampler diff --git a/nemo/collections/asr/parts/utils/asr_confidence_benchmarking_utils.py b/nemo/collections/asr/parts/utils/asr_confidence_benchmarking_utils.py deleted file mode 100644 index f91d205f0760baed4e3eca51ca3008b2b4a5bdaf..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/asr_confidence_benchmarking_utils.py +++ /dev/null @@ -1,173 +0,0 @@ -# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import copy -import os -from pathlib import Path -from typing import List, Optional, Tuple, Union - -import numpy as np -import torch -from kaldialign import align -from omegaconf import open_dict - -from nemo.collections.asr.models import ASRModel, EncDecRNNTModel -from nemo.collections.asr.parts.utils.confidence_metrics import ( - auc_nt, - auc_pr, - auc_roc, - auc_yc, - ece, - nce, - save_confidence_hist, - save_custom_confidence_curve, - save_nt_curve, - save_pr_curve, - save_roc_curve, -) -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis - - -def get_correct_marks(r: Union[List[int], List[str]], h: Union[List[int], List[str]]) -> List[bool]: - """Get correct marks by aligning the reference text with a hypothesis. - - This method considers only insertions and substitutions as incorrect marks. - """ - alignment = align( - [str(rr) for rr in r], - [str(hh) for hh in h], - "", - ) - return [a == b for a, b in alignment if b != ""] - - -def get_token_targets_with_confidence(hyp: Hypothesis) -> List[Tuple[str, float]]: - return [(y, c) for y, c in zip(hyp.y_sequence, hyp.token_confidence)] - - -def get_word_targets_with_confidence(hyp: Hypothesis) -> List[Tuple[str, float]]: - return [(y, c) for y, c in zip(hyp.words, hyp.word_confidence)] - - -def run_confidence_benchmark( - model: ASRModel, - target_level: str, - filepaths: List[str], - reference_texts: List[str], - batch_size: int = 8, - num_workers: int = 4, - plot_dir: Optional[Union[str, Path]] = None, - use_amp: Optional[bool] = False, -): - """Run benchmark and plot histograms and curves, if plot_dir is provided. - - Returns: - Dictionary with benchmark results of the following scheme: - `level: (auc_roc, auc_pr, auc_nt, nce, ece, auc_yc, std_yc, max_yc)` with `level` being 'token' or 'word'. - """ - draw_plot = plot_dir is not None - if isinstance(plot_dir, str): - plot_dir = Path(plot_dir) - - # transcribe audio - with torch.amp.autocast(model.device.type, enabled=use_amp): - with torch.no_grad(): - transcriptions = model.transcribe( - audio=filepaths, batch_size=batch_size, return_hypotheses=True, num_workers=num_workers - ) - - levels = [] - if target_level != "word": - levels.append("token") - if target_level != "token": - levels.append("word") - results = {} - for level in levels: - if level == "token": - targets_with_confidence = [get_token_targets_with_confidence(tran) for tran in transcriptions] - correct_marks = [ - get_correct_marks(model.tokenizer.text_to_ids(r), model.tokenizer.text_to_ids(h.text)) - for r, h in zip(reference_texts, transcriptions) - ] - else: # "word" - targets_with_confidence = [get_word_targets_with_confidence(tran) for tran in transcriptions] - correct_marks = [get_correct_marks(r.split(), h.words) for r, h in zip(reference_texts, transcriptions)] - - y_true, y_score = np.array( - [[f, p[1]] for cm, twc in zip(correct_marks, targets_with_confidence) for f, p in zip(cm, twc)] - ).T - # output scheme: yc.mean(), yc.max(), yc.std() or yc.mean(), yc.max(), yc.std(), (thresholds, yc) - result_yc = auc_yc(y_true, y_score, return_std_maximum=True, return_curve=draw_plot) - # output scheme: ece or ece, (thresholds, ece_curve) - results_ece = ece(y_true, y_score, return_curve=draw_plot) - results[level] = [ - auc_roc(y_true, y_score), - auc_pr(y_true, y_score), - auc_nt(y_true, y_score), - nce(y_true, y_score), - results_ece if isinstance(results_ece, float) else results_ece[0], - ] + list(result_yc[:3]) - - if draw_plot: - os.makedirs(plot_dir, exist_ok=True) - - mask_correct = y_true == 1 - y_score_correct = y_score[mask_correct] - y_score_incorrect = y_score[~mask_correct] - # histogram of the correct distribution - save_confidence_hist(y_score_correct, plot_dir, level + "_" + "hist_correct") - # histogram of the incorrect distribution - save_confidence_hist(y_score_incorrect, plot_dir, level + "_" + "hist_incorrect") - # AUC-ROC curve - save_roc_curve(y_true, y_score, plot_dir, level + "_" + "roc") - # AUC-PR curve - save_pr_curve(y_true, y_score, plot_dir, level + "_" + "pr") - # AUC-NT curve - save_nt_curve(y_true, y_score, plot_dir, level + "_" + "nt") - # AUC-YC curve - yc_thresholds, yc_values = result_yc[-1] - save_custom_confidence_curve( - yc_thresholds, - yc_values, - plot_dir, - level + "_" + "yc", - "Threshold", - "True positive rate − False Positive Rate", - ) - # ECE curve - ece_thresholds, ece_values = results_ece[-1] - ece_values /= max(ece_values) - save_custom_confidence_curve( - ece_thresholds, ece_values, plot_dir, level + "_" + "ece", "Threshold", "|Accuracy − Confidence score|" - ) - - return results - - -def apply_confidence_parameters(decoding_cfg, hp): - """Apply parameters from a parameter grid to a decoding config. - - Returns: - Updated decoding config. - """ - new_decoding_cfg = copy.deepcopy(decoding_cfg) - confidence_cfg_fields = ("aggregation", "exclude_blank", "tdt_include_duration") - confidence_method_cfg_fields = ("name", "alpha", "entropy_type", "entropy_norm") - with open_dict(new_decoding_cfg): - for p, v in hp.items(): - if p in confidence_cfg_fields: - new_decoding_cfg.confidence_cfg[p] = v - elif p in confidence_method_cfg_fields: - new_decoding_cfg.confidence_cfg.method_cfg[p] = v - return new_decoding_cfg diff --git a/nemo/collections/asr/parts/utils/asr_confidence_utils.py b/nemo/collections/asr/parts/utils/asr_confidence_utils.py deleted file mode 100644 index 35a9ae30937ff58177aa5186f2f386664edcd9e9..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/asr_confidence_utils.py +++ /dev/null @@ -1,470 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import math -from abc import ABC, abstractmethod -from dataclasses import dataclass, field -from functools import partial -from typing import List, Optional - -import torch -from omegaconf import DictConfig, OmegaConf - -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis - - -class ConfidenceMethodConstants: - NAMES = ("max_prob", "entropy") - ENTROPY_TYPES = ("gibbs", "tsallis", "renyi") - ENTROPY_NORMS = ("lin", "exp") - - @classmethod - def print(cls): - return ( - cls.__name__ - + ": " - + str({"NAMES": cls.NAMES, "ENTROPY_TYPES": cls.ENTROPY_TYPES, "ENTROPY_NORMS": cls.ENTROPY_NORMS}) - ) - - -class ConfidenceConstants: - AGGREGATIONS = ("mean", "min", "max", "prod") - - @classmethod - def print(cls): - return cls.__name__ + ": " + str({"AGGREGATIONS": cls.AGGREGATIONS}) - - -@dataclass -class ConfidenceMethodConfig: - """A Config which contains the method name and settings to compute per-frame confidence scores. - - Args: - name: The method name (str). - Supported values: - - 'max_prob' for using the maximum token probability as a confidence. - - 'entropy' for using a normalized entropy of a log-likelihood vector. - - entropy_type: Which type of entropy to use (str). - Used if confidence_method_cfg.name is set to `entropy`. - Supported values: - - 'gibbs' for the (standard) Gibbs entropy. If the alpha (α) is provided, - the formula is the following: H_α = -sum_i((p^α_i)*log(p^α_i)). - Note that for this entropy, the alpha should comply the following inequality: - (log(V)+2-sqrt(log^2(V)+4))/(2*log(V)) <= α <= (1+log(V-1))/log(V-1) - where V is the model vocabulary size. - - 'tsallis' for the Tsallis entropy with the Boltzmann constant one. - Tsallis entropy formula is the following: H_α = 1/(α-1)*(1-sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/Tsallis_entropy - - 'renyi' for the Rényi entropy. - Rényi entropy formula is the following: H_α = 1/(1-α)*log_2(sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/R%C3%A9nyi_entropy - - alpha: Power scale for logsoftmax (α for entropies). Here we restrict it to be > 0. - When the alpha equals one, scaling is not applied to 'max_prob', - and any entropy type behaves like the Shannon entropy: H = -sum_i(p_i*log(p_i)) - - entropy_norm: A mapping of the entropy value to the interval [0,1]. - Supported values: - - 'lin' for using the linear mapping. - - 'exp' for using exponential mapping with linear shift. - """ - - name: str = "entropy" - entropy_type: str = "tsallis" - alpha: float = 0.33 - entropy_norm: str = "exp" - temperature: str = "DEPRECATED" - - def __post_init__(self): - if self.temperature != "DEPRECATED": - # self.temperature has type str - self.alpha = float(self.temperature) - self.temperature = "DEPRECATED" - if self.name not in ConfidenceMethodConstants.NAMES: - raise ValueError( - f"`name` must be one of the following: " - f"{'`' + '`, `'.join(ConfidenceMethodConstants.NAMES) + '`'}. Provided: `{self.name}`" - ) - if self.entropy_type not in ConfidenceMethodConstants.ENTROPY_TYPES: - raise ValueError( - f"`entropy_type` must be one of the following: " - f"{'`' + '`, `'.join(ConfidenceMethodConstants.ENTROPY_TYPES) + '`'}. Provided: `{self.entropy_type}`" - ) - if self.alpha <= 0.0: - raise ValueError(f"`alpha` must be > 0. Provided: {self.alpha}") - if self.entropy_norm not in ConfidenceMethodConstants.ENTROPY_NORMS: - raise ValueError( - f"`entropy_norm` must be one of the following: " - f"{'`' + '`, `'.join(ConfidenceMethodConstants.ENTROPY_NORMS) + '`'}. Provided: `{self.entropy_norm}`" - ) - - -@dataclass -class ConfidenceConfig: - """A config which contains the following key-value pairs related to confidence scores. - - Args: - preserve_frame_confidence: Bool flag which preserves the history of per-frame confidence scores - generated during decoding. When set to true, the Hypothesis will contain - the non-null value for `frame_confidence` in it. Here, `frame_confidence` is a List of floats. - preserve_token_confidence: Bool flag which preserves the history of per-token confidence scores - generated during greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `token_confidence` in it. Here, `token_confidence` is a List of floats. - - The length of the list corresponds to the number of recognized tokens. - preserve_word_confidence: Bool flag which preserves the history of per-word confidence scores - generated during greedy decoding (sample / batched). When set to true, the Hypothesis will contain - the non-null value for `word_confidence` in it. Here, `word_confidence` is a List of floats. - - The length of the list corresponds to the number of recognized words. - exclude_blank: Bool flag indicating that blank token confidence scores are to be excluded - from the `token_confidence`. - aggregation: Which aggregation type to use for collapsing per-token confidence into per-word confidence. - Valid options are `mean`, `min`, `max`, `prod`. - tdt_include_duration: Bool flag indicating that the duration confidence scores are to be calculated and - attached to the regular frame confidence, - making TDT frame confidence element a pair: (`prediction_confidence`, `duration_confidence`). - method_cfg: A dict-like object which contains the method name and settings to compute per-frame - confidence scores. - - name: The method name (str). - Supported values: - - 'max_prob' for using the maximum token probability as a confidence. - - 'entropy' for using a normalized entropy of a log-likelihood vector. - - entropy_type: Which type of entropy to use (str). Used if confidence_method_cfg.name is set to `entropy`. - Supported values: - - 'gibbs' for the (standard) Gibbs entropy. If the alpha (α) is provided, - the formula is the following: H_α = -sum_i((p^α_i)*log(p^α_i)). - Note that for this entropy, the alpha should comply the following inequality: - (log(V)+2-sqrt(log^2(V)+4))/(2*log(V)) <= α <= (1+log(V-1))/log(V-1) - where V is the model vocabulary size. - - 'tsallis' for the Tsallis entropy with the Boltzmann constant one. - Tsallis entropy formula is the following: H_α = 1/(α-1)*(1-sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/Tsallis_entropy - - 'renyi' for the Rényi entropy. - Rényi entropy formula is the following: H_α = 1/(1-α)*log_2(sum_i(p^α_i)), - where α is a parameter. When α == 1, it works like the Gibbs entropy. - More: https://en.wikipedia.org/wiki/R%C3%A9nyi_entropy - - alpha: Power scale for logsoftmax (α for entropies). Here we restrict it to be > 0. - When the alpha equals one, scaling is not applied to 'max_prob', - and any entropy type behaves like the Shannon entropy: H = -sum_i(p_i*log(p_i)) - - entropy_norm: A mapping of the entropy value to the interval [0,1]. - Supported values: - - 'lin' for using the linear mapping. - - 'exp' for using exponential mapping with linear shift. - """ - - preserve_frame_confidence: bool = False - preserve_token_confidence: bool = False - preserve_word_confidence: bool = False - exclude_blank: bool = True - aggregation: str = "min" - tdt_include_duration: bool = False - method_cfg: ConfidenceMethodConfig = field(default_factory=lambda: ConfidenceMethodConfig()) - - def __post_init__(self): - # OmegaConf.structured ensures that post_init check is always executed - self.method_cfg = OmegaConf.structured( - self.method_cfg - if isinstance(self.method_cfg, ConfidenceMethodConfig) - else ConfidenceMethodConfig(**self.method_cfg) - ) - if self.aggregation not in ConfidenceConstants.AGGREGATIONS: - raise ValueError( - f"`aggregation` has to be one of the following: " - f"{'`' + '`, `'.join(ConfidenceConstants.AGGREGATIONS) + '`'}. Provided: `{self.aggregation}`" - ) - - -def get_confidence_measure_bank(): - """Generate a dictionary with confidence measure functionals. - - Supported confidence measures: - max_prob: normalized maximum probability - entropy_gibbs_lin: Gibbs entropy with linear normalization - entropy_gibbs_exp: Gibbs entropy with exponential normalization - entropy_tsallis_lin: Tsallis entropy with linear normalization - entropy_tsallis_exp: Tsallis entropy with exponential normalization - entropy_renyi_lin: Rényi entropy with linear normalization - entropy_renyi_exp: Rényi entropy with exponential normalization - - Returns: - dictionary with lambda functions. - """ - # helper functions - # Gibbs entropy is implemented without alpha - neg_entropy_gibbs = lambda x: (x.exp() * x).sum(-1) - neg_entropy_alpha = lambda x, t: (x * t).exp().sum(-1) - neg_entropy_alpha_gibbs = lambda x, t: ((x * t).exp() * x).sum(-1) - - # too big for a lambda - def entropy_tsallis_exp(x, v, t): - exp_neg_max_ent = math.exp((1 - math.pow(v, 1 - t)) / (1 - t)) - return (((1 - neg_entropy_alpha(x, t)) / (1 - t)).exp() - exp_neg_max_ent) / (1 - exp_neg_max_ent) - - def entropy_gibbs_exp(x, v, t): - exp_neg_max_ent = math.pow(v, -t * math.pow(v, 1 - t)) - return ((neg_entropy_alpha_gibbs(x, t) * t).exp() - exp_neg_max_ent) / (1 - exp_neg_max_ent) - - # use Gibbs entropies for Tsallis and Rényi with t == 1.0 - entropy_gibbs_lin_baseline = lambda x, v: 1 + neg_entropy_gibbs(x) / math.log(v) - entropy_gibbs_exp_baseline = lambda x, v: (neg_entropy_gibbs(x).exp() * v - 1) / (v - 1) - # fill the measure bank - confidence_measure_bank = {} - # Maximum probability measure is implemented without alpha - confidence_measure_bank["max_prob"] = lambda x, v, t: ( - (x.max(dim=-1)[0].exp() * v - 1) / (v - 1) - if t == 1.0 - else ((x.max(dim=-1)[0] * t).exp() * math.pow(v, t) - 1) / (math.pow(v, t) - 1) - ) - confidence_measure_bank["entropy_gibbs_lin"] = lambda x, v, t: ( - entropy_gibbs_lin_baseline(x, v) - if t == 1.0 - else 1 + neg_entropy_alpha_gibbs(x, t) / math.log(v) / math.pow(v, 1 - t) - ) - confidence_measure_bank["entropy_gibbs_exp"] = lambda x, v, t: ( - entropy_gibbs_exp_baseline(x, v) if t == 1.0 else entropy_gibbs_exp(x, v, t) - ) - confidence_measure_bank["entropy_tsallis_lin"] = lambda x, v, t: ( - entropy_gibbs_lin_baseline(x, v) if t == 1.0 else 1 + (1 - neg_entropy_alpha(x, t)) / (math.pow(v, 1 - t) - 1) - ) - confidence_measure_bank["entropy_tsallis_exp"] = lambda x, v, t: ( - entropy_gibbs_exp_baseline(x, v) if t == 1.0 else entropy_tsallis_exp(x, v, t) - ) - confidence_measure_bank["entropy_renyi_lin"] = lambda x, v, t: ( - entropy_gibbs_lin_baseline(x, v) if t == 1.0 else 1 + neg_entropy_alpha(x, t).log2() / (t - 1) / math.log(v, 2) - ) - confidence_measure_bank["entropy_renyi_exp"] = lambda x, v, t: ( - entropy_gibbs_exp_baseline(x, v) if t == 1.0 else (neg_entropy_alpha(x, t).pow(1 / (t - 1)) * v - 1) / (v - 1) - ) - return confidence_measure_bank - - -def get_confidence_aggregation_bank(): - """Generate a dictionary with confidence aggregation functions. - - Supported confidence aggregation functions: - min: minimum - max: maximum - mean: arithmetic mean - prod: product - - Returns: - dictionary with functions. - """ - confidence_aggregation_bank = {"mean": lambda x: sum(x) / len(x), "min": min, "max": max} - # python 3.7 and earlier do not have math.prod - if hasattr(math, "prod"): - confidence_aggregation_bank["prod"] = math.prod - else: - import operator - from functools import reduce - - confidence_aggregation_bank["prod"] = lambda x: reduce(operator.mul, x, 1) - return confidence_aggregation_bank - - -class ConfidenceMethodMixin(ABC): - """Confidence Method Mixin class. - - It initializes per-frame confidence method. - """ - - def _init_confidence_method(self, confidence_method_cfg: Optional[DictConfig] = None): - """Initialize per-frame confidence method from config.""" - # OmegaConf.structured ensures that post_init check is always executed - confidence_method_cfg = OmegaConf.structured( - ConfidenceMethodConfig() - if confidence_method_cfg is None - else ConfidenceMethodConfig(**confidence_method_cfg) - ) - - # set confidence calculation method - if not hasattr(self, "num_tokens"): - # we suppose that self.blank_id == len(vocabulary) - self.num_tokens = (self.blank_id if hasattr(self, "blank_id") else self._blank_index) + 1 - self.alpha = confidence_method_cfg.alpha - - # init confidence measure bank - self.confidence_measure_bank = get_confidence_measure_bank() - - measure = None - # construct measure_name - measure_name = "" - if confidence_method_cfg.name == "max_prob": - measure_name = "max_prob" - elif confidence_method_cfg.name == "entropy": - measure_name = '_'.join( - [confidence_method_cfg.name, confidence_method_cfg.entropy_type, confidence_method_cfg.entropy_norm] - ) - else: - raise ValueError(f"Unsupported `confidence_method_cfg.name`: `{confidence_method_cfg.name}`") - if measure_name not in self.confidence_measure_bank: - raise ValueError(f"Unsupported measure setup: `{measure_name}`") - measure = partial(self.confidence_measure_bank[measure_name], v=self.num_tokens, t=self.alpha) - - self._confidence_measure = measure - - def _get_confidence(self, x: torch.Tensor) -> list[float]: - """Compute confidence, return list of confidence items for each item in batch""" - return self._get_confidence_tensor(x).tolist() - - def _get_confidence_tensor(self, x: torch.Tensor) -> torch.Tensor: - """Compute confidence, return tensor""" - return self._confidence_measure(torch.nan_to_num(x)) - - -class ConfidenceMixin(ABC): - """Confidence Mixin class. - - It is responsible for confidence estimation method initialization and high-level confidence score calculation. - """ - - def _init_confidence(self, confidence_cfg: Optional[DictConfig] = None): - """Initialize confidence-related fields and confidence aggregation function from config.""" - # OmegaConf.structured ensures that post_init check is always executed - confidence_cfg = OmegaConf.structured( - ConfidenceConfig() if confidence_cfg is None else ConfidenceConfig(**confidence_cfg) - ) - self.confidence_method_cfg = confidence_cfg.method_cfg - - # extract the config - self.preserve_word_confidence = confidence_cfg.get('preserve_word_confidence', False) - # set preserve_frame_confidence and preserve_token_confidence to True - # if preserve_word_confidence is True - self.preserve_token_confidence = ( - confidence_cfg.get('preserve_token_confidence', False) | self.preserve_word_confidence - ) - # set preserve_frame_confidence to True if preserve_token_confidence is True - self.preserve_frame_confidence = ( - confidence_cfg.get('preserve_frame_confidence', False) | self.preserve_token_confidence - ) - self.exclude_blank_from_confidence = confidence_cfg.get('exclude_blank', True) - self.tdt_include_duration_confidence = confidence_cfg.get('tdt_include_duration', False) - self.word_confidence_aggregation = confidence_cfg.get('aggregation', "min") - - # define aggregation functions - self.confidence_aggregation_bank = get_confidence_aggregation_bank() - self._aggregate_confidence = self.confidence_aggregation_bank[self.word_confidence_aggregation] - - # Update preserve frame confidence - if self.cfg.strategy in ['greedy', 'greedy_batch']: - if not self.preserve_frame_confidence: - self.preserve_frame_confidence = self.cfg.greedy.get('preserve_frame_confidence', False) - # OmegaConf.structured ensures that post_init check is always executed - confidence_method_cfg = OmegaConf.structured(self.cfg.greedy).get('confidence_method_cfg', None) - self.confidence_method_cfg = ( - OmegaConf.structured(ConfidenceMethodConfig()) - if confidence_method_cfg is None - else OmegaConf.structured(ConfidenceMethodConfig(**confidence_method_cfg)) - ) - if not self.tdt_include_duration_confidence: - self.tdt_include_duration_confidence = self.cfg.greedy.get('tdt_include_duration_confidence', False) - - @abstractmethod - def compute_confidence(self, hypotheses_list: List[Hypothesis]) -> List[Hypothesis]: - """Computes high-level (per-token and/or per-word) confidence scores for a list of hypotheses. - Assumes that `frame_confidence` is present in the hypotheses. - - Args: - hypotheses_list: List of Hypothesis. - - Returns: - A list of hypotheses with high-level confidence scores. - """ - raise NotImplementedError() - - @abstractmethod - def _aggregate_token_confidence(self, hypothesis: Hypothesis) -> List[float]: - """Implemented by subclass in order to aggregate token confidence to a word-level confidence. - - Args: - hypothesis: Hypothesis - - Returns: - A list of word-level confidence scores. - """ - raise NotImplementedError() - - def _aggregate_token_confidence_chars(self, words: List[str], token_confidence: List[float]) -> List[float]: - """Implementation of token confidence aggregation for character-based models. - - Args: - words: List of words of a hypothesis. - token_confidence: List of token-level confidence scores of a hypothesis. - - Returns: - A list of word-level confidence scores. - """ - word_confidence = [] - i = 0 - for word in words: - word_len = len(word) - word_confidence.append(self._aggregate_confidence(token_confidence[i : i + word_len])) - # we assume that there is exactly one space token between words and exclude it from word confidence - i += word_len + 1 - return word_confidence - - def _aggregate_token_confidence_subwords_sentencepiece( - self, words: List[str], token_confidence: List[float], token_ids: List[int] - ) -> List[float]: - """Implementation of token confidence aggregation for subword-based models. - - **Note**: Only supports Sentencepiece based tokenizers ! - - Args: - words: List of words of a hypothesis. - token_confidence: List of token-level confidence scores of a hypothesis. - token_ids: List of token ids of a hypothesis. - - Returns: - A list of word-level confidence scores. - """ - word_confidence = [] - # run only if there are final words - if len(words) > 0: - j = 0 - prev_unk = False - prev_underline = False - for i, token_id in enumerate(token_ids): - token = self.decode_ids_to_tokens([int(token_id)])[0] - token_text = self.decode_ids_to_str([int(token_id)]) - # treat `` as a separate word regardless of the next token - # to match the result of `tokenizer.ids_to_text` - if (token != token_text or prev_unk) and i > j: - # do not add confidence for `▁` if the current token starts with `▁` - # to match the result of `tokenizer.ids_to_text` - if not prev_underline: - word_confidence.append(self._aggregate_confidence(token_confidence[j:i])) - j = i - prev_unk = token == '' - prev_underline = token == '▁' - if not prev_underline: - word_confidence.append(self._aggregate_confidence(token_confidence[j : len(token_ids)])) - if len(words) != len(word_confidence): - raise RuntimeError( - f"""Something went wrong with word-level confidence aggregation.\n - Please check these values for debugging:\n - len(words): {len(words)},\n - len(word_confidence): {len(word_confidence)},\n - recognized text: `{' '.join(words)}`""" - ) - return word_confidence diff --git a/nemo/collections/asr/parts/utils/asr_module_utils.py b/nemo/collections/asr/parts/utils/asr_module_utils.py deleted file mode 100644 index e077d7948c0dd7770876b8604bf54d23de5c5294..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/asr_module_utils.py +++ /dev/null @@ -1,82 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import Optional - -from omegaconf import DictConfig, open_dict - -from nemo.collections.asr.modules import conv_asr -from nemo.collections.asr.parts.submodules import jasper -from nemo.utils import logging - - -def change_conv_asr_se_context_window(model: 'ASRModel', context_window: int, update_config: bool = True): - """ - Update the context window of the SqueezeExcitation module if the provided model contains an - `encoder` which is an instance of `ConvASREncoder`. - - Args: - model: A subclass of `ASRModel`, itself a subclass of `ModelPT`. - context_window: An integer representing the number of input timeframes that will be used - to compute the context. Each timeframe corresponds to a single window stride of the - STFT features. - - Say the window_stride = 0.01s, then a context window of 128 represents 128 * 0.01 s - of context to compute the Squeeze step. - update_config: Whether to update the config or not with the new context window. - """ - if update_config and not hasattr(model.cfg, 'encoder'): - logging.info( - "Could not change the context window in SqueezeExcite module " - "since the model provided does not contain an `encoder` module in its config." - ) - return - - if not isinstance(model.encoder, conv_asr.ConvASREncoder): - logging.info( - f"Could not change the context window in SqueezeExcite module " - f"since the `encoder` module is not an instance of `ConvASREncoder`.\n" - f"Provided encoder class = {model.encoder.__class__.__name__}" - ) - return - - enc_cfg = model.cfg.encoder if update_config else None - - if enc_cfg is not None: - with open_dict(enc_cfg): - _update_se_context_window(model, context_window, cfg=enc_cfg) - else: - _update_se_context_window(model, context_window) - - # Update model config - if update_config: - model.cfg.encoder = enc_cfg - - -def _update_se_context_window(model: 'ASRModel', context_window: int, cfg: Optional[DictConfig] = None): - jasper_block_counter = -1 - for name, m in model.named_modules(): - if type(m) == jasper.JasperBlock: - jasper_block_counter += 1 - - if type(m) == jasper.MaskedConv1d: - if m.conv.stride[0] > 1 and 'mconv' in name: - context_window = context_window // m.conv.stride[0] - - if type(m) == jasper.SqueezeExcite: - m.change_context_window(context_window=context_window) - - # update config - if cfg is not None: - cfg.jasper[jasper_block_counter].se_context_size = context_window diff --git a/nemo/collections/asr/parts/utils/asr_multispeaker_utils.py b/nemo/collections/asr/parts/utils/asr_multispeaker_utils.py deleted file mode 100644 index d0bb3aa82226462b8211ab5d2e1bf91cae0a49b9..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/asr_multispeaker_utils.py +++ /dev/null @@ -1,696 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import json -import logging -import math -import random -from collections import defaultdict -from copy import deepcopy -from typing import Optional, Union - -import torch.utils.data -from cytoolz import groupby -from lhotse import AudioSource, Recording, SupervisionSegment, SupervisionSet -from lhotse.cut import Cut, MixedCut, MixTrack, MonoCut -from lhotse.lazy import LazyJsonlIterator -from lhotse.utils import compute_num_samples, uuid4 - - -def find_first_nonzero(mat: torch.Tensor, max_cap_val=-1, thres: float = 0.5) -> torch.Tensor: - """ - Finds the first nonzero value in the matrix, discretizing it to the specified maximum capacity. - - Args: - mat (Tensor): A torch tensor representing the matrix. - max_cap_val (int): The maximum capacity to which the matrix values will be discretized. - thres (float): The threshold value for discretizing the matrix values. - - Returns: - mask_max_indices (Tensor): A torch tensor representing the discretized matrix with the first - nonzero value in each row. - """ - # Discretize the matrix to the specified maximum capacity - labels_discrete = mat.clone() - labels_discrete[labels_discrete < thres] = 0 - labels_discrete[labels_discrete >= thres] = 1 - - # non zero values mask - non_zero_mask = labels_discrete != 0 - # operations on the mask to find first nonzero values in the rows - mask_max_values, mask_max_indices = torch.max(non_zero_mask, dim=1) - # if the max-mask is zero, there is no nonzero value in the row - mask_max_indices[mask_max_values == 0] = max_cap_val - return mask_max_indices - - -def find_best_permutation(match_score: torch.Tensor, speaker_permutations: torch.Tensor) -> torch.Tensor: - """ - Finds the best permutation indices based on the match score. - - Args: - match_score (torch.Tensor): A tensor containing the match scores for each permutation. - Shape: (batch_size, num_permutations) - speaker_permutations (torch.Tensor): A tensor containing all possible speaker permutations. - Shape: (num_permutations, num_speakers) - - Returns: - torch.Tensor: A tensor containing the best permutation indices for each batch. - Shape: (batch_size, num_speakers) - """ - batch_best_perm = torch.argmax(match_score, axis=1) - rep_speaker_permutations = speaker_permutations.repeat(batch_best_perm.shape[0], 1).to(match_score.device) - perm_size = speaker_permutations.shape[0] - global_inds_vec = ( - torch.arange(0, perm_size * batch_best_perm.shape[0], perm_size).to(batch_best_perm.device) + batch_best_perm - ) - return rep_speaker_permutations[global_inds_vec.to(rep_speaker_permutations.device), :] - - -def reconstruct_labels(labels: torch.Tensor, batch_perm_inds: torch.Tensor) -> torch.Tensor: - """ - Reconstructs the labels using the best permutation indices with matrix operations. - - Args: - labels (torch.Tensor): A tensor containing the original labels. - Shape: (batch_size, num_frames, num_speakers) - batch_perm_inds (torch.Tensor): A tensor containing the best permutation indices for each batch. - Shape: (batch_size, num_speakers) - - Returns: - torch.Tensor: A tensor containing the reconstructed labels using the best permutation indices. - Shape: (batch_size, num_frames, num_speakers) - """ - # Expanding batch_perm_inds to align with labels dimensions - batch_size, num_frames, num_speakers = labels.shape - batch_perm_inds_exp = batch_perm_inds.unsqueeze(1).expand(-1, num_frames, -1) - - # Reconstructing the labels using advanced indexing - reconstructed_labels = torch.gather(labels, 2, batch_perm_inds_exp) - return reconstructed_labels - - -def get_ats_targets( - labels: torch.Tensor, - preds: torch.Tensor, - speaker_permutations: torch.Tensor, - thres: float = 0.5, - tolerance: float = 0, -) -> torch.Tensor: - """ - Sorts labels and predictions to get the optimal of all arrival-time ordered permutations. - - Args: - labels (torch.Tensor): A tensor containing the original labels. - Shape: (batch_size, num_frames, num_speakers) - preds (torch.Tensor): A tensor containing the predictions. - Shape: (batch_size, num_frames, num_speakers) - speaker_permutations (torch.Tensor): A tensor containing all possible speaker permutations. - Shape: (num_permutations, num_speakers) - thres (float): The threshold value for discretizing the matrix values. Default is 0.5. - tolerance (float): The tolerance for comparing the first speech frame indices. Default is 0. - - Returns: - torch.Tensor: A tensor containing the reconstructed labels using the best permutation indices. - Shape: (batch_size, num_frames, num_speakers) - """ - # Find the first nonzero frame index for each speaker in each batch - nonzero_ind = find_first_nonzero( - mat=labels, max_cap_val=labels.shape[1], thres=thres - ) # (batch_size, num_speakers) - - # Sort the first nonzero frame indices for arrival-time ordering - sorted_values = torch.sort(nonzero_ind)[0] # (batch_size, num_speakers) - perm_size = speaker_permutations.shape[0] # Scalar value (num_permutations) - permed_labels = labels[:, :, speaker_permutations] # (batch_size, num_frames, num_permutations, num_speakers) - permed_nonzero_ind = find_first_nonzero( - mat=permed_labels, max_cap_val=labels.shape[1] - ) # (batch_size, num_permutations, num_speakers) - - # Compare the first frame indices of sorted labels with those of the permuted labels using tolerance - perm_compare = ( - torch.abs(sorted_values.unsqueeze(1) - permed_nonzero_ind) <= tolerance - ) # (batch_size, num_permutations, num_speakers) - perm_mask = torch.all(perm_compare, dim=2).float() # (batch_size, num_permutations) - preds_rep = torch.unsqueeze(preds, 2).repeat( - 1, 1, perm_size, 1 - ) # Exapnd the preds: (batch_size, num_frames, num_permutations, num_speakers) - - # Compute the match score for each permutation by comparing permuted labels with preds - match_score = ( - torch.sum(permed_labels * preds_rep, axis=1).sum(axis=2) * perm_mask - ) # (batch_size, num_permutations) - batch_perm_inds = find_best_permutation(match_score, speaker_permutations) # (batch_size, num_speakers) - max_score_permed_labels = reconstruct_labels(labels, batch_perm_inds) # (batch_size, num_frames, num_speakers) - return max_score_permed_labels # (batch_size, num_frames, num_speakers) - - -def get_pil_targets(labels: torch.Tensor, preds: torch.Tensor, speaker_permutations: torch.Tensor) -> torch.Tensor: - """ - Sorts labels and predictions to get the optimal permutation based on the match score. - - Args: - labels (torch.Tensor): A tensor containing the ground truth labels. - Shape: (batch_size, num_speakers, num_classes) - preds (torch.Tensor): A tensor containing the predicted values. - Shape: (batch_size, num_speakers, num_classes) - speaker_permutations (torch.Tensor): A tensor containing all possible speaker permutations. - Shape: (num_permutations, num_speakers) - - Returns: - torch.Tensor: A tensor of permuted labels that best match the predictions. - Shape: (batch_size, num_speakers, num_classes) - """ - permed_labels = labels[:, :, speaker_permutations] # (batch_size, num_classes, num_permutations, num_speakers) - # Repeat preds to match permutations for comparison - preds_rep = torch.unsqueeze(preds, 2).repeat( - 1, 1, speaker_permutations.shape[0], 1 - ) # (batch_size, num_speakers, num_permutations, num_classes) - match_score = torch.sum(permed_labels * preds_rep, axis=1).sum(axis=2) # (batch_size, num_permutations) - batch_perm_inds = find_best_permutation(match_score, speaker_permutations) # (batch_size, num_speakers) - # Reconstruct labels based on the best permutation for each batch - max_score_permed_labels = reconstruct_labels(labels, batch_perm_inds) # (batch_size, num_speakers, num_classes) - return max_score_permed_labels # (batch_size, num_speakers, num_classes) - - -def find_segments_from_rttm( - recording_id: str, - rttms: SupervisionSet, - start_after: float, - end_before: float, - adjust_offset: bool = True, - tolerance: float = 0.001, -): - """ - Finds segments from the given rttm file. - This function is designed to replace rttm - - Args: - recording_id (str): The recording ID in string format. - rttms (SupervisionSet): The SupervisionSet instance. - start_after (float): The start time after which segments are selected. - end_before (float): The end time before which segments are selected. - adjust_offset (bool): Whether to adjust the offset of the segments. - tolerance (float): The tolerance for time matching. 0.001 by default. - Returns: - segments (List[SupervisionSegment]): A list of SupervisionSegment instances. - """ - segment_by_recording_id = rttms._segments_by_recording_id - if segment_by_recording_id is None: - from cytoolz import groupby - - segment_by_recording_id = groupby(lambda seg: seg.recording_id, rttms) - - return [ - # We only modify the offset - the duration remains the same, as we're only shifting the segment - # relative to the Cut's start, and not truncating anything. - segment.with_offset(-start_after) if adjust_offset else segment - for segment in segment_by_recording_id.get(recording_id, []) - if segment.start < end_before + tolerance and segment.end > start_after + tolerance - ] - - -def get_mask_from_segments( - segments: list, - a_cut: Optional[Union[MonoCut, MixedCut]], - speaker_to_idx_map: torch.Tensor, - num_speakers: int = 4, - feat_per_sec: int = 100, -): - """ - Generate mask matrix from segments list. - This function is needed for speaker diarization with ASR model trainings. - - Args: - segments: A list of Lhotse Supervision segments iterator. - cut (MonoCut, MixedCut): Lhotse MonoCut or MixedCut instance. - speaker_to_idx_map (dict): A dictionary mapping speaker names to indices. - num_speakers (int): max number of speakers for all cuts ("mask" dim0), 4 by default - feat_per_sec (int): number of frames per second, 100 by default, 0.01s frame rate - - Returns: - mask (Tensor): A numpy array of shape (num_speakers, encoder_hidden_len). - Dimension: (num_speakers, num_frames) - """ - # get targets with 0.01s frame rate - num_samples = round(a_cut.duration * feat_per_sec) - mask = torch.zeros((num_samples, num_speakers)) - for rttm_sup in segments: - speaker_idx = speaker_to_idx_map[rttm_sup.speaker] - - stt = max(rttm_sup.start, 0) - ent = min(rttm_sup.end, a_cut.duration) - stf = int(stt * feat_per_sec) - enf = int(ent * feat_per_sec) - mask[stf:enf, speaker_idx] = 1.0 - return mask - - -def get_soft_mask(feat_level_target, num_frames, stride): - """ - Get soft mask from feat_level_target with stride. - This function is needed for speaker diarization with ASR model trainings. - - Args: - feat_level_target (Tensor): A numpy array of shape (num_frames, num_speakers). - Dimension: (num_frames, num_speakers) - num_sample (int): The total number of samples. - stride (int): The stride for the mask. - - Returns: - mask: The soft mask of shape (num_frames, num_speakers). - Dimension: (num_frames, num_speakers) - """ - - num_speakers = feat_level_target.shape[1] - mask = torch.zeros(num_frames, num_speakers) - - for index in range(num_frames): - if index == 0: - seg_stt_feat = 0 - else: - seg_stt_feat = stride * index - 1 - int(stride / 2) - if index == num_frames - 1: - seg_end_feat = feat_level_target.shape[0] - else: - seg_end_feat = stride * index - 1 + int(stride / 2) - mask[index] = torch.mean(feat_level_target[seg_stt_feat : seg_end_feat + 1, :], axis=0) - return mask - - -def get_hidden_length_from_sample_length( - num_samples: int, num_sample_per_mel_frame: int = 160, num_mel_frame_per_asr_frame: int = 8 -) -> int: - """ - Calculate the hidden length from the given number of samples. - This function is needed for speaker diarization with ASR model trainings. - - This function computes the number of frames required for a given number of audio samples, - considering the number of samples per mel frame and the number of mel frames per ASR frame. - - Please refer to the following function for more on feature frame length calculation: - NeMo/nemo/collections/asr/parts/preprocessing/features.py::FilterbankFeatures::get_seq_len - - Parameters: - num_samples (int): The total number of audio samples. - num_sample_per_mel_frame (int, optional): The number of samples per mel frame. Default is 160. - num_mel_frame_per_asr_frame (int, optional): The number of mel frames per ASR frame. Default is 8. - - Returns: - hidden_length (int): The calculated hidden length in terms of the number of frames. - """ - mel_frame_count = math.ceil(num_samples / num_sample_per_mel_frame) - hidden_length = math.ceil(mel_frame_count / num_mel_frame_per_asr_frame) - return int(hidden_length) - - -def speaker_to_target( - a_cut, - num_speakers: Optional[int] = None, - num_sample_per_mel_frame: int = 160, - num_mel_frame_per_asr_frame: int = 8, - boundary_segments: bool = False, - soft_label: bool = False, - soft_thres: float = 0.5, - return_text: bool = False, -): - ''' - Get rttm samples corresponding to one cut, generate speaker mask numpy.ndarray with shape (num_speaker, hidden_length) - This function is needed for speaker diarization with ASR model trainings. - - Args: - a_cut (MonoCut, MixedCut): Lhotse Cut instance which is MonoCut or MixedCut instance. - num_speakers (int): max number of speakers for all cuts ("mask" dim0), 4 by default - num_sample_per_mel_frame (int): number of sample per mel frame, sample_rate / 1000 * window_stride, 160 by default (10ms window stride) - num_mel_frame_per_asr_frame (int): encoder subsampling_factor, 8 by default - boundary_segments (bool): set to True to include segments containing the boundary of the cut, False by default for multi-speaker ASR training - soft_label (bool): set to True to use soft label that enables values in [0, 1] range, False by default and leads to binary labels. - soft_thres (float): the threshold for the soft label, 0.5 by default. - return_text (bool): set to True to return the text of the speakers (if it is available), False by default. - - Returns: - mask (Tensor): speaker mask with shape (num_speaker, hidden_lenght) - ''' - # get cut-related segments from rttms - if isinstance(a_cut, MixedCut): - cut_list = [track.cut for track in a_cut.tracks if isinstance(track.cut, MonoCut)] - offsets = [track.offset for track in a_cut.tracks if isinstance(track.cut, MonoCut)] - elif isinstance(a_cut, MonoCut): - cut_list = [a_cut] - offsets = [0] - else: - raise ValueError(f"Unsupported cut type type{a_cut}: only MixedCut and MonoCut are supported") - - segments_total = [] - - for i, cut in enumerate(cut_list): - if cut.custom.get('rttm_filepath', None): - rttms = SupervisionSet.from_rttm(cut.rttm_filepath) - elif cut.supervisions: - rttms = SupervisionSet(cut.supervisions) - else: - logging.warning(f"No rttm or supervisions found for cut {cut.id}") - continue - - start = cut.offset if hasattr(cut, 'offset') else cut.start - end = start + cut.duration - recording_id = rttms[0].recording_id if len(rttms) > 0 else cut.recording_id - if boundary_segments: # segments with seg_start < total_end and seg_end > total_start are included - segments_iterator = find_segments_from_rttm( - recording_id=recording_id, rttms=rttms, start_after=start, end_before=end, tolerance=0.0 - ) - else: # segments with seg_start > total_start and seg_end < total_end are included - segments_iterator = rttms.find( - recording_id=recording_id, start_after=start, end_before=end, adjust_offset=True - ) # , tolerance=0.0) - - for seg in segments_iterator: - if seg.start < 0: - seg.duration += seg.start - seg.start = 0 - if seg.end > cut.duration: - seg.duration -= seg.end - cut.duration - seg.start += offsets[i] - segments_total.append(seg) - # apply arrival time sorting to the existing segments - segments_total.sort(key=lambda rttm_sup: rttm_sup.start) - - seen = set() - seen_add = seen.add - speaker_ats = [s.speaker for s in segments_total if not (s.speaker in seen or seen_add(s.speaker))] - - speaker_to_idx_map = {spk: idx for idx, spk in enumerate(speaker_ats)} - - if num_speakers is None: - num_speakers_dim = len(speaker_ats) - else: - if len(speaker_ats) > num_speakers: - logging.warning( - "Number of speakers in the target %s is greater than " - "the maximum number of speakers %s. Truncating extra speakers. " - "Set the `num_speakers` to higher value to avoid this warning.", - len(speaker_ats), - num_speakers, - ) - num_speakers_dim = max(len(speaker_ats), num_speakers) - # initialize mask matrices (num_speaker, encoder_hidden_len) - feat_per_sec = int(a_cut.sampling_rate / num_sample_per_mel_frame) # 100 by default - num_samples = get_hidden_length_from_sample_length( - a_cut.num_samples, num_sample_per_mel_frame, num_mel_frame_per_asr_frame - ) - frame_mask = get_mask_from_segments(segments_total, a_cut, speaker_to_idx_map, num_speakers_dim, feat_per_sec) - soft_mask = get_soft_mask(frame_mask, num_samples, num_mel_frame_per_asr_frame) - - if soft_label: - mask = soft_mask - else: - mask = (soft_mask > soft_thres).float() - - if return_text: - speaker2text = defaultdict(list) - for seg in segments_total: - speaker2text[seg.speaker].append(seg.text) - texts = [' '.join(speaker2text[speaker]) for speaker in speaker_ats] - return mask, texts - else: - return mask - - -def read_seglst(seglst_filepath: str, session_id: Optional[str] = None): - """ - Read the seglst file and return a list of SupervisionSegment. - """ - with open(seglst_filepath, 'r', encoding='utf-8') as f: - seglst = json.load(f) - return [ - SupervisionSegment( - id=f'{seg["session_id"]}-sup{i:05d}', - recording_id=seg['session_id'] if session_id is None else session_id, - start=float(seg['start_time']), - duration=float(seg['end_time']) - float(seg['start_time']), - text=seg['words'], - speaker=seg['speaker'], - ) - for i, seg in enumerate(seglst) - ] - - -class MultiSpeakerMixtureGenerator: - """ - This class is used to simulate multi-speaker audio data, - which can be used for multi-speaker ASR and speaker diarization training. - """ - - def __init__( - self, - manifest_filepath, - sample_rate, - simulator_type, - min_duration=0.1, - max_duration=50.0, - min_delay=0.5, - random_seed=42, - num_speakers=2, - global_rank=0, - world_size=1, - ): - """ - Args: - cuts (CutSet): The cutset that contains single-speaker audio cuts. - Please make sure that the cuts have the 'speaker_id' attribute. - num_speakers (int): The number of speakers in the simulated audio. - We only simulate the samples with the fixed number of speakers. - The variation of the number of speakers is controlled by the weights in Lhotse dataloader config. - simulator_type (str): The type of simulator to use. - - 'lsmix': LibriSpeechMix-style training sample. - - 'meeting': Meeting-style training sample. - - 'conversation': Conversation-style training sample. - speaker_distribution (list): The distribution of speakers in the simulated audio. - The length of the list is the maximum number of speakers. - The list elements are the weights for each speaker. - min_delay (float): The minimum delay between speakers - to avoid the same starting time for multiple speakers. - """ - self.random_seed = random_seed - self.global_rank = global_rank - self.world_size = world_size - - self.manifest_filepath = manifest_filepath - self.manifests = list(LazyJsonlIterator(manifest_filepath)) - self.sample_rate = sample_rate - - self.min_duration = min_duration - self.max_duration = max_duration - self.min_delay = min_delay - self.simulator_type = simulator_type - self.max_speakers = num_speakers - - print("====== simulator_type", simulator_type) - - type2simulator = {'lsmix': self.LibriSpeechMixSimulator, 'mixture_loader': self.MultiSpeakerMixtureLoader} - - self.simulator = type2simulator[simulator_type] - - if simulator_type == 'lsmix': - self.spk2manifests = groupby(lambda x: x["speaker_id"], self.manifests) - self.speaker_ids = list(self.spk2manifests.keys()) - - self.count = 0 - - def __iter__(self): - return self - - def __next__(self): - self.count += 1 - return self.simulator() - - def LibriSpeechMixSimulator(self): - """ - This function simulates a LibriSpeechMix-style training sample. - Ref: - Paper: https://arxiv.org/abs/2003.12687 - Github: https://github.com/NaoyukiKanda/LibriSpeechMix - """ - # Sample the speakers - sampled_speaker_ids = random.sample(self.speaker_ids, self.max_speakers) - # Sample the cuts for each speaker - mono_cuts = [] - for speaker_id in sampled_speaker_ids: - manifest = random.choice(self.spk2manifests[speaker_id]) - mono_cuts.append(self._json_to_cut(manifest)) - mono_cuts[-1].supervisions.append( - SupervisionSegment( - id=uuid4(), - recording_id=uuid4(), - start=0.0, - duration=mono_cuts[-1].duration, - text=mono_cuts[-1].custom['text'], - speaker=speaker_id, - ) - ) - - tracks = [] - offset = 0.0 - for speaker_id, mono_cut in zip(sampled_speaker_ids, mono_cuts): - tracks.append(MixTrack(cut=deepcopy(mono_cut), type=type(mono_cut), offset=offset)) - offset += random.uniform(self.min_delay, mono_cut.duration) - - mixed_cut = MixedCut( - id='lsmix_' + '_'.join([track.cut.id for track in tracks]) + '_' + str(uuid4()), tracks=tracks - ) - - return mixed_cut - - def MultiSpeakerMixtureLoader(self): - """ - Load a multi-speaker mixture from the manifest, - and generate a mixed cut with a random duration. - The timestamps and transcript are from the seglst file, - where the format is: - { - "session_id": "session_id", - "speaker": "speaker_id", - "words": "transcript", - "start_time": "start_time", - "end_time": "end_time", - "duration": "duration" - ... - } - Supervisions are generated from the seglst file and sorted by start time. - """ - - manifest = random.choice(self.manifests) - audio_filepath = manifest['audio_filepath'] - seglst_filepath = manifest['seglst_filepath'] - - supervisions = read_seglst(seglst_filepath, session_id=manifest['session_id']) - supervisions = sorted(supervisions, key=lambda x: x.start) - - segment_offset, segment_duration = self._get_offset_and_duration(supervisions) - - json_dict = { - 'audio_filepath': audio_filepath, - 'duration': segment_duration, - 'offset': segment_offset, - 'supervisions': find_segments_from_rttm( - recording_id=supervisions[0].recording_id, - rttms=SupervisionSet(supervisions), - start_after=segment_offset, - end_before=segment_offset + segment_duration, - adjust_offset=False, - ), - } - cut = self._json_to_cut(json_dict) - - return cut - - def _get_offset_and_duration(self, supervisions): - """ - Get a random offset and duration of the segment. - supervisions should be sorted by start time - """ - non_overlap_supervisions_indices = self._get_non_overlap_supervisions_indices(supervisions) - # find the start and the end of the segment - start_idx = random.choice(non_overlap_supervisions_indices) - end_idx = start_idx - offset = supervisions[start_idx].start - for i in range(start_idx + 1, len(supervisions)): - end_idx = i - if supervisions[i].end - offset <= self.min_duration: - pass - else: - if i in non_overlap_supervisions_indices: - break - segment_offset = offset - segment_duration = supervisions[end_idx].end - offset - - return segment_offset, segment_duration - - def _get_non_overlap_supervisions_indices(self, supervisions): - """ - Get the indices of the non-overlapping supervisions. - supervisions should be sorted by start time - """ - non_overlap_supervisions_indices = [] - max_end = -1 - for i in range(len(supervisions)): - if supervisions[i].start >= max_end: - non_overlap_supervisions_indices.append(i) - max_end = max(max_end, supervisions[i].end) - return non_overlap_supervisions_indices - - def _json_to_cut(self, json_dict): - """ - Convert a json dictionary to a Cut instance. - """ - audio_path = json_dict["audio_filepath"] - duration = json_dict["duration"] - offset = json_dict.get("offset", 0.0) - supervisions = json_dict.get("supervisions", []) - cut = self._create_cut( - audio_path=audio_path, - offset=offset, - duration=duration, - sampling_rate=json_dict.get("sampling_rate", None), - ) - # Note that start=0 and not start=offset because supervision's start if relative to the - # start of the cut; and cut.start is already set to offset - - if json_dict.get("text") is not None and json_dict.get("text") != "": - cut_text = json_dict.get("text") - else: - cut_text = " ".join(json_dict.get("words", [])) - if cut_text == " ": - cut_text = "" - - cut.supervisions.extend(supervisions) - cut.custom = json_dict - cut.duration = duration - return cut - - def _create_cut( - self, - audio_path: str, - offset: float, - duration: float, - sampling_rate: int | None = None, - channel: int = 0, - ) -> Cut: - - recording = self._create_recording(audio_path, duration, sampling_rate) - cut = recording.to_cut() - if isinstance(cut.channel, list) and len(cut.channel) > 1: - cut.channel = [channel] - if offset is not None: - cut = cut.truncate(offset=offset, duration=duration, preserve_id=True) - cut.id = f"{cut.id}-{round(offset * 1e2):06d}-{round(duration * 1e2):06d}" - return cut - - def _create_recording( - self, - audio_path: str, - duration: float, - sampling_rate: int | None = None, - ) -> Recording: - if sampling_rate is not None: - # TODO(pzelasko): It will only work with single-channel audio in the current shape. - return Recording( - id=audio_path, - sources=[AudioSource(type="file", channels=[0], source=audio_path)], - sampling_rate=sampling_rate, - num_samples=compute_num_samples(duration, sampling_rate), - duration=duration, - channel_ids=[0], - ) - else: - return Recording.from_file(audio_path) diff --git a/nemo/collections/asr/parts/utils/batched_beam_decoding_utils.py b/nemo/collections/asr/parts/utils/batched_beam_decoding_utils.py deleted file mode 100644 index e0af3b7623d7b8b3d25b86adc9505a327d1e1f1a..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/batched_beam_decoding_utils.py +++ /dev/null @@ -1,623 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -from typing import Optional - -import torch - -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis, NBestHypotheses -from nemo.utils.enum import PrettyStrEnum - -# Constants used for hashing text sequences. -MULTIPLIER = 6364136223846793005 -INCREMENT = 1 -MODULUS = 2**64 - -# Constants used for initializing and managing beam search hypotheses. -INACTIVE_SCORE = -float("inf") # Represents the score of inactive hypotheses. -INIT_POINTER_VALUE = -1 # Initial value for pointers in the hypothesis tree structure. -INIT_HASH_VALUE = 0 # Initial hash value for transcript hashes. -INIT_PREFIX_HASH_VALUE = 0 # Initial hash value for prefix hashes. -NON_EXISTENT_LABEL_VALUE = -1 # Placeholder value for non-existent labels in hypotheses. Needs to be negative. - - -def hash_text(prev_hash: torch.Tensor, add_labels: torch.Tensor) -> torch.Tensor: - """ - Computes a new hash value by updating previous hash tensor with added labels tensor. - Reference: https://stackoverflow.com/a/77213071 - - Args: - prev_hash (torch.Tensor): A tensor representing the previous hash value. - add_labels (torch.Tensor): A tensor containing added labels. - - Returns: - torch.Tensor: A tensor representing the updated hash value. - """ - return prev_hash * MULTIPLIER + INCREMENT + add_labels - - -class BlankLMScoreMode(PrettyStrEnum): - """ - Defines the strategies for handling blank token scores in a external Ngram LM - when combined with an automatic speech recognition (ASR) model. - """ - - # No score for blank. - NO_SCORE = "no_score" - # Blank score for LM is set equal to blank score from ASR model; non-blank LM scores are reweighted to sum to 1. - LM_WEIGHTED_FULL = "lm_weighted_full" - - -class PruningMode(PrettyStrEnum): - """Specifies when pruning is applied external Ngram LM shallow fusion..""" - - # Hyps are pruned based on ASR probs, then rescored with LM - EARLY = "early" - # Hyps are scored based on combined ASR and LM probs., then pruned - LATE = "late" - - -class ASRModelTypeEnum(PrettyStrEnum): - """Specifies model type.""" - - RNNT = "rnnt" - TDT = "tdt" - CTC = "ctc" - - -class BatchedBeamHyps: - """Class to store batch of beam hypotheses (labels, time_indices, scores) for efficient batched beam decoding""" - - def __init__( - self, - batch_size: int, - beam_size: int, - init_length: int, - blank_index: int, - device: torch.device = None, - float_dtype: torch.dtype = None, - store_prefix_hashes: Optional[bool] = False, - model_type: Optional[ASRModelTypeEnum | str] = ASRModelTypeEnum.RNNT, - ): - """ - Initializes the batched beam hypotheses utility for Transducer decoding (RNN-T and TDT models). - Args: - batch_size (int): Batch size. - beam_size (int): Beam size. - init_length (int): The initial maximum length of the hypotheses. - blank_index (int): The index representing the blank token in the vocabulary. - device (torch.device): The device on which tensors will be allocated. Defaults to None. - float_dtype (torch.dtype): The floating-point data type. Defaults to None. - store_prefix_hashes (bool, optional): Whether to store prefix hashes for hypotheses. Defaults to False. - model_type: (str or ModelTypeEnum, optional): Model type, either 'rnnt', 'tdt' or 'ctc'. Defaults to 'rnnt'. - """ - - if beam_size <= 0: - raise ValueError("Beam size must be greater than 0.") - if batch_size <= 0: - raise ValueError("Batch size must be greater than 0.") - if init_length <= 0: - raise ValueError("Initial hypothesis lengths must be greater than 0.") - - self.device = device - self.INACTIVE_SCORE_TENSOR = torch.tensor(INACTIVE_SCORE, device=device, dtype=float_dtype) - self.ZERO_TENSOR = torch.tensor(0, device=device, dtype=torch.long) - - self.model_type = ASRModelTypeEnum(model_type) - self.store_prefix_hashes = store_prefix_hashes - self._max_length = init_length - self.beam_size = beam_size - self.blank_index = blank_index - self.batch_size = batch_size - self.batch_indices = torch.arange(self.batch_size, device=device) - self.beam_indices = torch.arange(self.beam_size, device=device) - - # Non-blank (non-blank and non-repeating for CTC) and full lengths - self.current_lengths_nb = torch.zeros([batch_size, self.beam_size], device=device, dtype=torch.long) - self.current_lengths_wb = torch.zeros([batch_size, self.beam_size], device=device, dtype=torch.long) - - # Initializing tree structure for hypothesis storing - self.transcript_wb = torch.full( - (batch_size, self.beam_size, self._max_length), - fill_value=NON_EXISTENT_LABEL_VALUE, - device=device, - dtype=torch.long, - ) # current labels - self.transcript_wb_prev_ptr = torch.full( - (batch_size, self.beam_size, self._max_length), - fill_value=INIT_POINTER_VALUE, - device=device, - dtype=torch.long, - ) # links to prefices - - # Initializing beam scores: Initially, only a single hypothesis is active within the beam. - self.scores = torch.full( - [batch_size, self.beam_size], device=device, dtype=float_dtype, fill_value=INACTIVE_SCORE - ) - self.scores[:, 0].fill_(0.0) - - self.last_label = torch.full( - (batch_size, self.beam_size), fill_value=NON_EXISTENT_LABEL_VALUE, device=device, dtype=torch.long - ) - - self.transcript_hash = torch.full( - [batch_size, self.beam_size], device=device, dtype=torch.long, fill_value=INIT_HASH_VALUE - ) - if store_prefix_hashes: - self.transcript_prefix_hash = torch.full( - [batch_size, self.beam_size], device=device, dtype=torch.long, fill_value=INIT_PREFIX_HASH_VALUE - ) - - if self.model_type == ASRModelTypeEnum.CTC: - # CTC frames and tokens are aligned, so we can precompute timestamps - self.timestamps = self._create_timestamps_tensor(self._max_length) # timestamps - else: - # timestamps for transducer models - self.timestamps = torch.zeros( - (batch_size, self.beam_size, self._max_length), device=device, dtype=torch.long - ) # timestamps - - # tracking last frame index and number of labels for the last frama - self.next_timestamp = torch.zeros((batch_size, self.beam_size), device=device, dtype=torch.long) - self.last_timestamp_lasts = torch.zeros((batch_size, self.beam_size), device=device, dtype=torch.long) - - def clear_(self): - """ - Clears and resets the internal state of the object. - """ - - self.current_lengths_nb.fill_(0) - self.current_lengths_wb.fill_(0) - - self.transcript_wb.fill_(NON_EXISTENT_LABEL_VALUE) - self.transcript_wb_prev_ptr.fill_(INIT_POINTER_VALUE) - - self.scores.fill_(INACTIVE_SCORE) - self.scores[:, 0].fill_(0.0) - - self.last_label.fill_(NON_EXISTENT_LABEL_VALUE) - - self.transcript_hash.fill_(INIT_HASH_VALUE) - if self.store_prefix_hashes: - self.transcript_prefix_hash.fill_(INIT_PREFIX_HASH_VALUE) - - # model specific parameters - if self.model_type == ASRModelTypeEnum.CTC: - self.timestamps.copy_(self._create_timestamps_tensor(self._max_length)) - else: - self.timestamps.fill_(0) - self.next_timestamp.fill_(0) - self.last_timestamp_lasts.fill_(0) - - def _allocate_more(self): - """ - Dynamically allocates more memory for the internal buffers. - This method doubles the size of the following tensors: `transcript_wb`, `transcript_wb_prev_ptr`. - """ - self.transcript_wb = torch.cat( - (self.transcript_wb, torch.full_like(self.transcript_wb, fill_value=NON_EXISTENT_LABEL_VALUE)), dim=-1 - ) - self.transcript_wb_prev_ptr = torch.cat( - (self.transcript_wb_prev_ptr, torch.full_like(self.transcript_wb_prev_ptr, fill_value=INIT_POINTER_VALUE)), - dim=-1, - ) - if self.model_type == ASRModelTypeEnum.CTC: - self.timestamps = self._create_timestamps_tensor(2 * self._max_length) - else: - self.timestamps = torch.cat((self.timestamps, torch.zeros_like(self.timestamps)), dim=-1) - - self._max_length *= 2 - - def add_results_( - self, - next_indices: torch.Tensor, - next_labels: torch.Tensor, - next_hyps_prob: torch.Tensor, - next_label_durations: Optional[torch.Tensor] = None, - ): - """ - Updates batch of beam hypotheses with labels. If the maximum allowed length - is exceeded, underlying memory is doubled. - Args: - next_indices (torch.Tensor): Indices of the hypotheses to be updated. - next_labels (torch.Tensor): Labels corresponding to the next step in the beam search. - next_hyps_prob (torch.Tensor): Probabilities of the next hypotheses. - next_label_durations (torch.Tensor, optional): Durations associated with the next labels. Required when `model_type='tdt'`. - """ - - if self.model_type == ASRModelTypeEnum.TDT and next_label_durations is None: - raise ValueError("`next_label_durations` is required when model type is TDT.") - - if (self.current_lengths_wb + 1).max() >= self._max_length: - self._allocate_more() - - self.add_results_no_checks_( - next_indices=next_indices, - next_labels=next_labels, - next_hyps_prob=next_hyps_prob, - next_label_durations=next_label_durations, - ) - - def add_results_no_checks_( - self, - next_indices: torch.Tensor, - next_labels: torch.Tensor, - next_hyps_prob: torch.Tensor, - next_label_durations: Optional[torch.Tensor] = None, - ): - """ - Updates batch of beam hypotheses with labels. - Args: - next_indices (torch.Tensor): Indices of the hypotheses to be updated. - next_labels (torch.Tensor): Labels corresponding to the next step in the beam search. - next_hyps_prob (torch.Tensor): Probabilities of the next hypotheses. - next_label_durations (torch.Tensor, optional): Durations associated with the next labels. Required when `model_type='tdt'`. - """ - if self.model_type == ASRModelTypeEnum.TDT and next_label_durations is None: - raise ValueError("`next_label_durations` is required when model type is TDT.") - - last_labels = torch.gather(self.last_label, dim=-1, index=next_indices) - self.transcript_wb.scatter_(dim=-1, index=self.current_lengths_wb.unsqueeze(-1), src=next_labels.unsqueeze(-1)) - self.transcript_wb_prev_ptr.scatter_( - dim=-1, index=self.current_lengths_wb.unsqueeze(-1), src=next_indices.unsqueeze(-1) - ) - - is_extended = next_labels >= 0 - extended_with_blank = next_labels == self.blank_index - extended_with_label = (is_extended) & (~extended_with_blank) - if self.model_type == ASRModelTypeEnum.CTC: - # for CTC last non-blank and non-repeated label - extended_with_label = (extended_with_label) & (next_labels != last_labels) # non-repeated non-blank label - - if self.model_type == ASRModelTypeEnum.RNNT: - timesteps = torch.gather(self.next_timestamp, dim=-1, index=next_indices) - self.timestamps.scatter_( - dim=-1, - index=self.current_lengths_wb.unsqueeze(-1), - src=(timesteps + extended_with_blank).unsqueeze(-1), - ) - self.next_timestamp.copy_(timesteps + extended_with_blank) - torch.where( - extended_with_blank, - self.ZERO_TENSOR, - torch.gather(self.last_timestamp_lasts, dim=-1, index=next_indices) + extended_with_label, - out=self.last_timestamp_lasts, - ) - elif self.model_type == ASRModelTypeEnum.TDT: - timesteps = torch.gather(self.next_timestamp, dim=-1, index=next_indices) - next_label_durations = torch.where(is_extended, next_label_durations, 0) - self.timestamps.scatter_( - dim=-1, - index=self.current_lengths_wb.unsqueeze(-1), - src=(timesteps + next_label_durations).unsqueeze(-1), - ) - torch.where(is_extended, timesteps + next_label_durations, timesteps, out=self.next_timestamp) - torch.where( - is_extended & (next_label_durations > 0), - self.ZERO_TENSOR, - torch.gather(self.last_timestamp_lasts, dim=-1, index=next_indices) + extended_with_label, - out=self.last_timestamp_lasts, - ) - - self.current_lengths_nb.copy_( - torch.gather(self.current_lengths_nb, dim=-1, index=next_indices) + extended_with_label - ) - torch.add(self.current_lengths_wb, 1, out=self.current_lengths_wb) - self.scores.copy_(next_hyps_prob) - - prev_transcript_hash = torch.gather(self.transcript_hash, dim=-1, index=next_indices) - # update hashes and prefix hashes - torch.where( - extended_with_label, - hash_text(prev_transcript_hash, next_labels), - prev_transcript_hash, - out=self.transcript_hash, - ) - - if self.model_type == ASRModelTypeEnum.CTC: - # track last label - torch.where(is_extended, next_labels, last_labels, out=self.last_label) - else: - # track last non-blank label - torch.where(extended_with_label, next_labels, last_labels, out=self.last_label) - - # store prefix hashes for batched maes - if self.store_prefix_hashes: - prev_transcript_prefix_hash = torch.gather(self.transcript_prefix_hash, dim=-1, index=next_indices) - torch.where( - extended_with_label, prev_transcript_hash, prev_transcript_prefix_hash, out=self.transcript_prefix_hash - ) - - def recombine_hyps_(self): - """ - Recombines hypotheses in the beam search by merging equivalent hypotheses and updating their scores. - This method identifies hypotheses that are equivalent based on their transcript hash, last label, - and current lengths. It then merges these equivalent hypotheses by computing a new score using - log-sum-exp over their scores and updates the scores tensor accordingly. - Returns: - Note: The method modifies the `self.scores` tensor in place to reflect the recombined hypotheses. - """ - - if self.beam_size <= 1: - return - - hyps_equal = ( - (self.transcript_hash[:, :, None] == self.transcript_hash[:, None, :]) - & (self.last_label[:, :, None] == self.last_label[:, None, :]) - & (self.current_lengths_nb[:, :, None] == self.current_lengths_nb[:, None, :]) - ) - - if self.model_type == ASRModelTypeEnum.TDT: - hyps_equal &= self.next_timestamp[:, :, None] == self.next_timestamp[:, None, :] - - scores_matrix = torch.where( - hyps_equal, - self.scores[:, None, :].expand(self.batch_size, self.beam_size, self.beam_size), - self.INACTIVE_SCORE_TENSOR, - ) - scores_argmax = scores_matrix.argmax(-1, keepdim=False) - scores_to_keep = ( - torch.arange(self.beam_size, device=scores_argmax.device, dtype=torch.long)[None, :] == scores_argmax - ) - if self.model_type == ASRModelTypeEnum.CTC: - new_scores = torch.max(scores_matrix, dim=-1, keepdim=False).values - else: - new_scores = torch.logsumexp(scores_matrix, dim=-1, keepdim=False) - torch.where(scores_to_keep, new_scores.to(self.scores.dtype), self.INACTIVE_SCORE_TENSOR, out=self.scores) - - def remove_duplicates(self, labels: torch.Tensor, total_logps: torch.Tensor): - """ - Removes duplicate hypotheses that may arise after updating beam hypotheses with labels during the beam search process. - Args: - labels (torch.Tensor): A tensor containing the labels for the current beam - search step. Shape: [batch_size, beam_size, ...]. - total_logps (torch.Tensor): A tensor containing the total log probabilities - for the current beam search step. Shape: [batch_size, beam_size, ...]. - Returns: - torch.Tensor: Updated total log probabilities with duplicates removed. - Shape: [batch_size, beam_size, ...]. - """ - - if self.beam_size <= 1: - return total_logps - - # updating hashes for label expansions - non_blank_mask = labels != self.blank_index - expansion_hashes = hash_text(self.transcript_hash.unsqueeze(-1), labels) - expansion_hashes = torch.where(non_blank_mask, expansion_hashes, self.transcript_hash.unsqueeze(-1)).view( - self.batch_size, -1 - ) - - # masking inactive hypotheses - inactive_hyps_mask = self.scores != INACTIVE_SCORE - masked_hashes = torch.where(inactive_hyps_mask, self.transcript_hash, -1) - - init_expansions_equal = (expansion_hashes[:, :, None] == masked_hashes[:, None, :]).any(dim=-1) - - init_expansions_equal = torch.logical_and(non_blank_mask.view(self.batch_size, -1), init_expansions_equal) - expansions_equal = expansion_hashes[:, :, None] == expansion_hashes[:, None, :] - expansion_scores = total_logps.view(self.batch_size, -1) - expansion_scores = torch.where(init_expansions_equal, INACTIVE_SCORE, expansion_scores) - expansion_scores = expansion_scores[:, None, :].expand(expansions_equal.shape) - - expansion_scores = torch.where(expansions_equal, expansion_scores, INACTIVE_SCORE) - expansion_scores, expansion_scores_argmax = expansion_scores.max(dim=-1) - - scores_range = torch.arange( - expansion_scores_argmax.shape[-1], device=expansion_scores_argmax.device, dtype=torch.long - ) - scores_to_keep = scores_range[None, :] == expansion_scores_argmax - total_logps = torch.where(scores_to_keep, expansion_scores, INACTIVE_SCORE).view( - self.batch_size, self.beam_size, -1 - ) - - return total_logps - - def recombine_prefixes(self, label_logps: torch.Tensor, active_mask: torch.Tensor): - """ - Recombines prefixes (prefix search) in the beam search process by updating scores for hypotheses - that share common prefixes. - Args: - label_logps (torch.Tensor): A tensor of shape (batch_size, beam_size, vocab_size) - containing the log probabilities of the labels for each beam. - active_mask (torch.Tensor): A boolean tensor of shape (batch_size, beam_size) - indicating which beams are active. - """ - - if self.beam_size <= 1: - return - - # if hypotheses are empty skip - if (self.current_lengths_wb == 0).any(): - return - - # mask prefix hashes if hypotheses of the beam do not have prefixes (e.g. no non-blank labels were appended) - prefix_hashes = torch.where(self.current_lengths_nb == 0, -2, self.transcript_prefix_hash) - - prefix_equal = self.transcript_hash[:, None, :] == prefix_hashes[:, :, None] - - last_labels = torch.where(self.last_label == NON_EXISTENT_LABEL_VALUE, self.blank_index, self.last_label) - prefix_labels = last_labels.unsqueeze(1).repeat((1, self.beam_size, 1)) - prefix_scores = self.scores.unsqueeze(1).repeat((1, self.beam_size, 1)) - - prefix_label_logps = torch.gather(label_logps, dim=-1, index=prefix_labels) - prefix_label_logps = prefix_scores + prefix_label_logps.transpose(dim0=-1, dim1=-2) - prefix_label_logps = torch.where(prefix_equal, prefix_label_logps, INACTIVE_SCORE) - prefix_label_logps = torch.logsumexp(prefix_label_logps, dim=-1) - - to_update_mask = torch.logical_and(active_mask, self.scores != INACTIVE_SCORE) - self.scores = torch.where(to_update_mask, torch.logaddexp(self.scores, prefix_label_logps), self.scores) - - def to_hyps_list(self, score_norm: bool = True) -> list[Hypothesis]: - """ - Converts the batched beam search results into a list of signle best hypotheses for each batch. - Args: - score_norm (bool): If True, normalize the scores before sorting. Defaults to True. - Returns: - list[Hypothesis]: A list where each element corresponds to a batch and contains - best hypothesis. - """ - self.flatten_sort_(score_norm) - - scores = self.scores[self.batch_indices, 0].tolist() - - max_idx = self.current_lengths_wb.max() - 1 - timestamps = self.timestamps[..., 0, : max_idx + 1] - transcripts = self.transcript_wb[..., 0, : max_idx + 1] - hypotheses = [ - Hypothesis( - score=scores[batch_idx], - y_sequence=transcripts[batch_idx][mask := self._create_transcripts_mask(transcripts[batch_idx])] - .cpu() - .detach() - .numpy(), - timestamp=timestamps[batch_idx][mask].cpu().detach().numpy(), - alignments=None, - dec_state=None, - ) - for batch_idx in range(self.batch_size) - ] - return hypotheses - - def to_nbest_hyps_list(self, score_norm: bool = True) -> list[NBestHypotheses]: - """ - Converts the batched beam search results into a list of N-best hypotheses for each batch. - Args: - score_norm (bool, optional): If True, normalize the scores before sorting. Defaults to True. - Returns: - list[NBestHypotheses]: A list where each element corresponds to a batch and contains - N-best hypotheses. - """ - - self.flatten_sort_(score_norm) - - scores = self.scores.tolist() - - max_idx = self.current_lengths_wb.max() - 1 - transcripts = self.transcript_wb[..., : max_idx + 1] - timestamps = self.timestamps[..., : max_idx + 1] - hypotheses = [ - NBestHypotheses( - [ - Hypothesis( - score=scores[batch_idx][beam_idx], - y_sequence=transcripts[batch_idx][beam_idx][ - mask := self._create_transcripts_mask(transcripts[batch_idx][beam_idx]) - ] - .cpu() - .detach() - .numpy(), - timestamp=timestamps[batch_idx][beam_idx][mask].cpu().detach().numpy(), - alignments=None, - dec_state=None, - ) - for beam_idx in range(self.beam_size) - if scores[batch_idx][beam_idx] > INACTIVE_SCORE - ] - ) - for batch_idx in range(self.batch_size) - ] - return hypotheses - - def flatten_sort_(self, score_norm: bool = True): - """ - Sorts and flattens the tree structure of hypotheses in a batched beam search decoding process. - Args: - score_norm (bool, optional): If True, normalizes the scores by dividing - them by the current lengths of the hypotheses plus one. Defaults to True. - This method performs the following steps: - 1. Normalizes the scores if `score_norm` is True. - 2. Sorts the normalized scores in descending order and retrieves the corresponding indices. - 3. Iteratively reconstructs the tokens and timestamps for each hypothesis in reverse order. - 4. Updates the internal state of the object, including transcripts, timestamps, scores, - lengths, labels, and other metadata, based on the sorted order. - """ - - # add one for consistency with non-batched decodings, that use SOS. - normalized_scores = ( - self.scores / (self.current_lengths_nb.to(self.scores.dtype) + 1) if score_norm else self.scores - ) - normalized_scores, indices = torch.sort(normalized_scores, dim=-1, descending=True) - - max_idx = self.current_lengths_wb.max() - 1 - ptrs = indices - - for idx in range(max_idx, -1, -1): - self.transcript_wb[..., idx].copy_(self.transcript_wb[self.batch_indices.unsqueeze(-1), ptrs, idx]) - if self.model_type == ASRModelTypeEnum.TDT or self.model_type == ASRModelTypeEnum.RNNT: - self.timestamps[..., idx].copy_(self.timestamps[self.batch_indices.unsqueeze(-1), ptrs, idx]) - ptrs = self.transcript_wb_prev_ptr[self.batch_indices.unsqueeze(-1), ptrs, idx] - self.transcript_wb_prev_ptr[..., : max_idx + 1].copy_(self.beam_indices.unsqueeze(0).unsqueeze(-1)) - - self.scores.copy_(torch.gather(self.scores, dim=-1, index=indices)) - self.current_lengths_nb.copy_(torch.gather(self.current_lengths_nb, dim=-1, index=indices)) - self.current_lengths_wb.copy_(torch.gather(self.current_lengths_wb, dim=-1, index=indices)) - - self.last_label.copy_(torch.gather(self.last_label, dim=-1, index=indices)) - - if self.model_type == ASRModelTypeEnum.TDT or self.model_type == ASRModelTypeEnum.RNNT: - self.next_timestamp.copy_(torch.gather(self.next_timestamp, dim=-1, index=indices)) - self.last_timestamp_lasts.copy_(torch.gather(self.last_timestamp_lasts, dim=-1, index=indices)) - - self.transcript_hash.copy_(torch.gather(self.transcript_hash, dim=-1, index=indices)) - if self.store_prefix_hashes: - self.transcript_prefix_hash.copy_(torch.gather(self.transcript_prefix_hash, dim=-1, index=indices)) - - def _create_fold_consecutive_mask(self, transcript): - """ - Creates a mask to filter consecutive duplicates, blanks, and invalid tokens in a transcript. - Args: - transcript (torch.Tensor): 1D tensor of token sequence. - Returns: - torch.Tensor: Boolean mask indicating valid tokens. - """ - device = transcript.device - mask = ( - (transcript >= 0) - & torch.cat([torch.tensor([True], device=device), transcript[1:] != transcript[:-1]]) - & (transcript != self.blank_index) - ) - - return mask - - def _create_timestamps_tensor(self, max_time): - """ - Generates a tensor of timestamps. - - In CTC, labels align with input frames, allowing timestamps to be precomputed. - - Args: - max_time (int): The maximum number of time steps (frames) to include in the tensor. - - Returns: - torch.Tensor: A tensor of shape (batch_size, beam_size, max_time) containing - sequential timestamps for each batch and beam. - """ - return torch.arange(max_time, device=self.device, dtype=torch.long)[None, None, :].repeat( - self.batch_size, self.beam_size, 1 - ) - - def _create_transcripts_mask(self, transcripts: torch.Tensor): - """ - Processes the transcripts. - For RNN-T and TDT removes blanks. - For CTC removes remove consecutive duplicates and blanks. - Args: - transcripts (torch.Tensor): 1D tensor of token sequence. - Returns: - torch.Tensor: Binary mask indicating valid tokens. - """ - if self.model_type == ASRModelTypeEnum.CTC: - return self._create_fold_consecutive_mask(transcripts) - else: - return (transcripts >= 0) & (transcripts != self.blank_index) diff --git a/nemo/collections/asr/parts/utils/chunking_utils.py b/nemo/collections/asr/parts/utils/chunking_utils.py deleted file mode 100644 index 83be3a3be3f70317850fefabee54fceab4c4df5b..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/chunking_utils.py +++ /dev/null @@ -1,451 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import torch - -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis -from nemo.collections.asr.parts.utils.timestamp_utils import get_segment_offsets, get_words_offsets - - -def merge_parallel_chunks(hypotheses, encoded_len, model, timestamps, subsampling_factor, window_stride, decoding): - """ - Merges hypotheses from parallel chunks into a single hypothesis with proper text, - token sequences, and timestamps. - - Args: - hypotheses: List of Hypothesis objects from each chunk - encoded_len: Tensor of encoded lengths for each chunk to use for finding offsets - model: The ASR model instance (needed for LCS alignment) - timestamps: Timestamps generation is enabled - subsampling_factor: The encoder's subsampling factor - window_stride: The preprocessor's window stride - decoding: The decoding instance for converting tokens to text - - Returns: - Hypothesis: A single merged hypothesis with combined text, tokens, and timestamps - """ - # we take the overlap to be 1 second, and count number of tokens in it - delay = int(1 / (subsampling_factor / 100)) - # Merge tokens from character level timestamps if timestamps are enabled - if timestamps: - merged_tokens = [char['token_id'] for char in hypotheses[0].timestamp['char']] - else: - merged_tokens = hypotheses[0].y_sequence.tolist() - # avoid circular import - from nemo.collections.asr.parts.utils.streaming_utils import lcs_alignment_merge_buffer - - for i in range(1, len(hypotheses)): - if timestamps: - data = [char['token_id'] for char in hypotheses[i].timestamp['char']] - else: - data = hypotheses[i].y_sequence.tolist() - merged_tokens = lcs_alignment_merge_buffer( - buffer=merged_tokens, - data=data[: int(delay * 0.6)], # only approximately 60% of the tokens are non blank - delay=delay, - model=model, - max_steps_per_timestep=2, - min_lcs_length=1, - parallel_chunking=True, - ) - merged_tokens += data[int(delay * 0.6) :] - - # Convert merged tokens to text - final_text = decoding.decode_tokens_to_str(merged_tokens) - - merged_hypotheses = Hypothesis( - score=0.0, - y_sequence=torch.tensor([]), - timestamp=([] if not timestamps else {'word': [], 'segment': []}), - ) - merged_hypotheses = join_y_sequence(merged_hypotheses, hypotheses) - merged_hypotheses = join_confidence_values(merged_hypotheses, hypotheses) - merged_hypotheses.text = final_text - # Merge timestamps and add word and segment level timestamps - if timestamps: - chunk_offsets = [0] + [ - (x * subsampling_factor - 100) if i >= 1 else (x * subsampling_factor) - for i, x in enumerate(encoded_len.tolist(), start=1) - ] - merged_hypotheses = join_timestamp_and_add_word_and_segment_level_timestamps( - merged_hypotheses, hypotheses, chunk_offsets, subsampling_factor, window_stride, decoding, merged_tokens - ) - - return merged_hypotheses - - -def join_y_sequence(merged_hypothesis, hypotheses): - """ - Concatenate y_sequence tensors from multiple hypotheses into a single sequence. - - Args: - merged_hypothesis: Target hypothesis to update with concatenated sequence - hypotheses: List of hypotheses containing y_sequence tensors - - Returns: - Hypothesis: Updated merged_hypothesis with concatenated y_sequence - """ - merged_hypothesis.y_sequence = torch.cat([h.y_sequence for h in hypotheses]) - return merged_hypothesis - - -def join_confidence_values(merged_hypothesis, hypotheses): - """ - Concatenate confidence values from multiple hypotheses into a single sequence. - - Args: - merged_hypothesis: Target hypothesis to update with concatenated confidence - hypotheses: List of hypotheses containing confidence values - - Returns: - Hypothesis: Updated merged_hypothesis with concatenated confidence values - """ - # Merge frame_confidence - frame_confidences = [h.frame_confidence for h in hypotheses if h.frame_confidence is not None] - if frame_confidences: - if isinstance(frame_confidences[0], torch.Tensor): - merged_hypothesis.frame_confidence = torch.cat(frame_confidences) - elif isinstance(frame_confidences[0], list): - merged_hypothesis.frame_confidence = [c for conf_list in frame_confidences for c in conf_list] - - # Merge token_confidence - token_confidences = [h.token_confidence for h in hypotheses if h.token_confidence is not None] - if token_confidences: - if isinstance(token_confidences[0], torch.Tensor): - merged_hypothesis.token_confidence = torch.cat(token_confidences) - elif isinstance(token_confidences[0], list): - merged_hypothesis.token_confidence = [c for conf_list in token_confidences for c in conf_list] - - # Merge word_confidence - word_confidences = [h.word_confidence for h in hypotheses if h.word_confidence is not None] - if word_confidences: - if isinstance(word_confidences[0], torch.Tensor): - merged_hypothesis.word_confidence = torch.cat(word_confidences) - elif isinstance(word_confidences[0], list): - merged_hypothesis.word_confidence = [c for conf_list in word_confidences for c in conf_list] - - return merged_hypothesis - - -def join_timestamp_and_add_word_and_segment_level_timestamps( - merged_hypotheses, hypotheses, chunk_offsets, subsampling_factor, window_stride, decoding, merged_tokens=None -): - """ - Combine character-level timestamps from chunks and generate word/segment timestamps. - - Args: - merged_hypotheses: Target hypothesis to update with timestamps - hypotheses: List of hypotheses from different chunks - chunk_offsets: Frame offsets for each chunk - subsampling_factor: Subsampling factor of the encoder - window_stride: Time stride per frame in seconds - decoding: Decoding that is used for decoding tokens into text in `get_words_offsets` - merged_tokens: Optional token sequence for filtering (default: None) - - Returns: - Hypothesis: Updated merged_hypotheses with word and segment timestamps - """ - - # First, combine char-level timestamps from all chunks - char_timestamps = join_char_level_timestamps( - hypotheses, chunk_offsets, subsampling_factor, window_stride, merged_tokens - ) - # Create encoded_char_offsets for word/segment generation - encoded_char_offsets = [] - for char_offset in char_timestamps: - enc_char_offset = char_offset.copy() - enc_char_offset['char'] = enc_char_offset['token'] - encoded_char_offsets.append(enc_char_offset) - - # Generate word-level timestamps from combined char timestamps - word_offsets = get_words_offsets( - char_offsets=char_timestamps, - decode_tokens_to_str=decoding.decode_tokens_to_str, - encoded_char_offsets=encoded_char_offsets, - supported_punctuation={',', '.', '!', '?'}, - ) - - # Generate segment-level timestamps from word timestamps - segment_offsets = get_segment_offsets(word_offsets=word_offsets, segment_delimiter_tokens={'.', '!', '?', "..."}) - # Update the merged hypothesis with word and segment timestamps - merged_hypotheses.timestamp['word'] = word_offsets - merged_hypotheses.timestamp['segment'] = segment_offsets - - return merged_hypotheses - - -def join_char_level_timestamps( - hypotheses, - chunk_offsets, - subsampling_factor, - window_stride, - merged_tokens=None, -): - """ - Merge per-chunk character-level timestamps into a single global timeline. - - This function stitches together character timestamp dictionaries coming from - consecutive chunks of the same audio. It shifts each chunk's offsets into a - global frame-of-reference and converts subsampled frame offsets to seconds. - - Args: - hypotheses: List of hypotheses. - chunk_offsets: List of raw-frame offsets (one per chunk) used for shifting. - subsampling_factor: Encoder subsampling factor (int). Number of raw - frames per one subsampled step. - window_stride: Time (in seconds) per raw input frame (float). - merged_tokens: Optional list of global token ids. If provided, only - characters whose `token_id` matches the next id in this list are - retained; leading overlapped characters within a chunk are trimmed. - - Returns: - List[dict]: Character timestamp dicts placed on a global timeline - """ - char_timestamps = [] - cumulative_offset = 0 # raw (pre-subsampling) frames already emitted - j_token = 0 # cursor in merged_tokens - - subsamp = subsampling_factor - stride = window_stride # sec per raw frame - for i, h in enumerate(hypotheses): - chunk_frame_offset = chunk_offsets[i] // subsamp - cumulative_offset += chunk_frame_offset - - # 1) figure out how much of the *front* of this chunk we will drop - for char in h.timestamp['char']: - if not char: - continue - keep = merged_tokens is None or ( - j_token < len(merged_tokens) and char['token_id'] == merged_tokens[j_token] - ) - if not keep: - continue - # adjust offsets: chunk start + global chunk shift − total removed - upd = dict(char) - if char['start_offset'] != -1: - upd['start_offset'] = char['start_offset'] + cumulative_offset # place chunk globally - if char['end_offset'] != -1: - upd['end_offset'] = char['end_offset'] + cumulative_offset - - if char_timestamps: - if upd['start_offset'] != -1 and upd['start_offset'] < char_timestamps[-1]['end_offset']: - upd['start_offset'] = char_timestamps[-1]['end_offset'] - upd['end_offset'] = char_timestamps[-1]['end_offset'] - # convert to seconds - upd['start'] = -1 if upd['start_offset'] == -1 else upd['start_offset'] * stride * subsamp - upd['end'] = -1 if upd['end_offset'] == -1 else upd['end_offset'] * stride * subsamp - - char_timestamps.append(upd) - j_token += 1 - - return char_timestamps - - -def _normalize_hypothesis_group_id(hypothesis_id: str) -> str: - """ - Normalize hypothesis IDs so that segmented continuations share the same group ID. - - IDs ending with `_cut_segmented` represent continuations of the chunk whose ID - shares the same prefix but ends with `-0`. Only the substring after the final - `-` is replaced so prefixes containing additional dashes remain unchanged. - """ - if not isinstance(hypothesis_id, str): - return hypothesis_id - if 'cut_segmented' not in hypothesis_id: - return hypothesis_id - - base_id = hypothesis_id.split('_cut_segmented', 1)[0] - if '-' not in base_id: - return base_id - - prefix, _ = base_id.rsplit('-', 1) - if not prefix: - return base_id - - return f'{prefix}-0' - - -def merge_all_hypotheses(hypotheses_list, timestamps, subsampling_factor, chunk_duration_seconds=3600): - """ - Group hypotheses by ID and merge each group into a single hypothesis. - - Args: - hypotheses_list: List of hypothesis objects with 'id' attributes - timestamps: True if timestamps generation is enabled - subsampling_factor: Subsampling factor of the encoder - chunk_duration_seconds: Duration of each chunk in seconds (default: 3600) - - Returns: - List[Hypothesis]: List of merged hypotheses, one per unique ID - """ - same_audio_hypotheses = [] - all_merged_hypotheses = [] - prev_id = None - for h in hypotheses_list: - # This will form the current ids of the same audio file - current_id = _normalize_hypothesis_group_id(h.id) - - # If this is a new ID (different from previous), process the accumulated hypotheses - if prev_id is not None and current_id != prev_id: - if same_audio_hypotheses: # Only merge if we have hypotheses to merge - - all_merged_hypotheses.append( - merge_hypotheses_of_same_audio( - same_audio_hypotheses, timestamps, subsampling_factor, chunk_duration_seconds - ) - ) - same_audio_hypotheses = [] - - # Add current hypothesis to the group - same_audio_hypotheses.append(h) - prev_id = current_id - - # Process the final group of hypotheses - if same_audio_hypotheses: - all_merged_hypotheses.append( - merge_hypotheses_of_same_audio( - same_audio_hypotheses, timestamps, subsampling_factor, chunk_duration_seconds - ) - ) - return all_merged_hypotheses - - -def merge_hypotheses_of_same_audio(hypotheses_list, timestamps, subsampling_factor, chunk_duration_seconds=3600): - """ - Merge hypotheses from the same audio source into a single hypothesis. - Used for combining results when long audio is split into hour-long segments - processed as separate batches. - - Args: - hypotheses_list: List of hypothesis objects from time chunks - timestamps: True if timestamps generation is enabled - subsampling_factor: Subsampling factor of the encoder - chunk_duration_seconds: Duration of each chunk in seconds (default: 3600) - - Returns: - Hypothesis: Single merged hypothesis - """ - - # Create merged hypothesis with empty initial values - merged_hypothesis = Hypothesis( - score=0.0, - y_sequence=torch.tensor([]), - timestamp=([] if not timestamps else {'word': [], 'segment': []}), - ) - - merged_hypothesis.y_sequence = torch.cat([h.y_sequence for h in hypotheses_list]) - - # Merge confidence values from all hypotheses - merged_hypothesis = join_confidence_values(merged_hypothesis, hypotheses_list) - - # Create final text by joining text from all hypotheses - text_parts = [] - for hyp in hypotheses_list: - if hyp.text: - text_parts.append(hyp.text.strip()) - merged_hypothesis.text = ' '.join(text_parts) - - # Handle timestamps with proper time offsets (word and segment only) - if timestamps and len(hypotheses_list) > 0 and getattr(hypotheses_list[0], "timestamp", {}): - # Calculate time offsets for each chunk (in seconds) - merged_word_timestamps = [] - merged_segment_timestamps = [] - - for chunk_idx, hyp in enumerate(hypotheses_list): - if not hasattr(hyp, 'timestamp') or not hyp.timestamp: - continue - - # Time offset for this chunk - time_offset = chunk_idx * chunk_duration_seconds - # Frame offset for this chunk (convert time to frames) - frame_offset = int(time_offset * 1000 / subsampling_factor) - - # Merge word timestamps with offset - if 'word' in hyp.timestamp and hyp.timestamp['word']: - for word_info in hyp.timestamp['word']: - if isinstance(word_info, dict): - adjusted_word = word_info.copy() - # Adjust start and end times - if ( - 'start' in adjusted_word - and adjusted_word['start'] is not None - and adjusted_word['start'] != -1 - ): - adjusted_word['start'] += time_offset - if 'end' in adjusted_word and adjusted_word['end'] is not None and adjusted_word['end'] != -1: - adjusted_word['end'] += time_offset - # Adjust start and end offsets (frame counts) - if ( - 'start_offset' in adjusted_word - and adjusted_word['start_offset'] is not None - and adjusted_word['start_offset'] != -1 - ): - adjusted_word['start_offset'] += frame_offset - if ( - 'end_offset' in adjusted_word - and adjusted_word['end_offset'] is not None - and adjusted_word['end_offset'] != -1 - ): - adjusted_word['end_offset'] += frame_offset - merged_word_timestamps.append(adjusted_word) - else: - merged_word_timestamps.append(word_info) - - # Merge segment timestamps with offset - if 'segment' in hyp.timestamp and hyp.timestamp['segment']: - for segment_info in hyp.timestamp['segment']: - if isinstance(segment_info, dict): - adjusted_segment = segment_info.copy() - # Adjust start and end times - if ( - 'start' in adjusted_segment - and adjusted_segment['start'] is not None - and adjusted_segment['start'] != -1 - ): - adjusted_segment['start'] += time_offset - if ( - 'end' in adjusted_segment - and adjusted_segment['end'] is not None - and adjusted_segment['end'] != -1 - ): - adjusted_segment['end'] += time_offset - # Adjust start and end offsets (frame counts) - if ( - 'start_offset' in adjusted_segment - and adjusted_segment['start_offset'] is not None - and adjusted_segment['start_offset'] != -1 - ): - adjusted_segment['start_offset'] += frame_offset - if ( - 'end_offset' in adjusted_segment - and adjusted_segment['end_offset'] is not None - and adjusted_segment['end_offset'] != -1 - ): - adjusted_segment['end_offset'] += frame_offset - merged_segment_timestamps.append(adjusted_segment) - else: - merged_segment_timestamps.append(segment_info) - - # Set the merged timestamps - merged_hypothesis.timestamp = { - 'word': merged_word_timestamps, - 'segment': merged_segment_timestamps, - } - elif len(hypotheses_list) == 1 and timestamps: - merged_hypothesis.timestamp = { - 'word': hypotheses_list[0].timestamp['word'], - 'segment': hypotheses_list[0].timestamp['segment'], - } - - return merged_hypothesis diff --git a/nemo/collections/asr/parts/utils/confidence_metrics.py b/nemo/collections/asr/parts/utils/confidence_metrics.py deleted file mode 100644 index 7d793c9df607c922c3f5f4ec941f2052ae259c61..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/confidence_metrics.py +++ /dev/null @@ -1,266 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import math -import os -from pathlib import Path -from typing import List, Optional, Tuple, Union - -import matplotlib.pyplot as plt -import numpy as np -from sklearn.metrics import ( - PrecisionRecallDisplay, - RocCurveDisplay, - average_precision_score, - log_loss, - precision_recall_curve, - roc_auc_score, - roc_curve, -) - - -def auc_roc(y_true: Union[List[int], np.ndarray], y_score: Union[List[float], np.ndarray]) -> float: - """Compute Area Under the Receiver Operating Characteristic Curve (ROC AUC) from prediction scores. - - Note: If only one class is present in y_true, 0.5 is returned. - """ - y_true = np.array(y_true) - y_score = np.array(y_score) - assert len(y_true) == len(y_score) - assert np.all(y_true >= 0) and np.all(y_true <= 1) - if np.all(y_true == 0) or np.all(y_true == 1): - return 0.5 - return roc_auc_score(y_true, y_score) - - -def auc_pr(y_true: Union[List[int], np.ndarray], y_score: Union[List[float], np.ndarray]) -> float: - """Compute Area Under the Precision-Recall Curve (PR AUC) from prediction scores. - - Note: If only regatives are present in y_true, 0.0 is returned. - """ - y_true = np.array(y_true) - y_score = np.array(y_score) - assert len(y_true) == len(y_score) - assert np.all(y_true >= 0) and np.all(y_true <= 1) - if np.all(y_true == 0): - return 0.0 - return average_precision_score(y_true, y_score) - - -def auc_nt(y_true: Union[List[int], np.ndarray], y_score: Union[List[float], np.ndarray]) -> float: - """Compute Area Under the Negative Predictive Value vs. True Negative Rate Curve (NT AUC) from prediction scores. - - This metric can be thought of as a PR AUC in which errors are treated as positives. - - Note: If only positives are present in y_true, 0.0 is returned. - """ - y_true = np.array(y_true) - y_score = np.array(y_score) - assert len(y_true) == len(y_score) - assert np.all(y_true >= 0) and np.all(y_true <= 1) - if np.all(y_true == 1): - return 0.0 - return average_precision_score(1 - y_true, 1 - y_score) - - -def nce(y_true: Union[List[int], np.ndarray], y_score: Union[List[float], np.ndarray]) -> float: - """Compute Normalized Cross Entropy (NCE) from prediction scores. Also known as the Normalized Mutual Information. - - NCE measures how close the correct prediction scores are to one and the incorrect prediction scores are to zero. - Negative NCE values indicate that the classifier performs worse than the setting all prediction scores - as the proportion of correct predictions. - - Note: If only one class is present in y_true, 0.5 is returned. - """ - y_true = np.array(y_true) - y_score = np.array(y_score) - assert len(y_true) == len(y_score) - assert np.all(y_true >= 0) and np.all(y_true <= 1) - if np.all(y_true == 0) or np.all(y_true == 1): - return -math.inf - p = y_true.mean() - eps = 1e-15 - Hp = -(math.log(p + eps) * p + math.log(1 - p + eps) * (1 - p)) - return (Hp - log_loss(y_true, y_score)) / Hp - - -def ece( - y_true: Union[List[int], np.ndarray], - y_score: Union[List[float], np.ndarray], - n_bins: int = 100, - return_curve: bool = False, -) -> Union[float, Tuple[float, Tuple[List[int], List[float]]]]: - """Compute Expected Calibration Error (ECE) from prediction scores. - - ECE measures how close the correct prediction scores are to one and the incorrect prediction scores are to zero. - ECE ranges from zero to one with the best value zero (the lower the value, the better). - """ - y_true = np.array(y_true) - y_score = np.array(y_score) - assert len(y_true) == len(y_score) - assert np.all(y_true >= 0) and np.all(y_true <= 1) - py = np.array([1 - y_score, y_score]).T - acc, conf = np.zeros(n_bins), np.zeros(n_bins) - Bm = np.zeros(n_bins) - ece_curve = [] - thresholds = [] - for m in range(n_bins): - a, b = m / n_bins, (m + 1) / n_bins - threshold = (a + b) / 2 - thresholds.append(threshold) - py_index = (py.T[1] >= threshold).astype(int) - py_value = py[np.arange(len(py_index)), py_index] - bin_range = ((py_value > a) & (py_value <= b)).nonzero()[0] - Bm[m] = len(bin_range) - if Bm[m] > 0: - acc[m] = (py_index[bin_range] == y_true[bin_range]).sum() / Bm[m] - conf[m] = py_value[bin_range].sum() / Bm[m] - ece_curve.append(Bm[m] * np.abs(acc[m] - conf[m])) - ece = sum(ece_curve) / sum(Bm) - if return_curve: - return ece, (thresholds, ece_curve) - else: - return ece - - -def auc_yc( - y_true: Union[List[int], np.ndarray], - y_score: Union[List[float], np.ndarray], - n_bins: int = 100, - return_std_maximum: bool = False, - return_curve: bool = False, -) -> Union[ - float, - Tuple[float, Tuple[List[int], List[float]]], - Tuple[float, float, float], - Tuple[float, float, float, Tuple[List[int], List[float]]], -]: - """Compute Area Under the Youden's Curve (YC AUC) from prediction scores. - - YC AUC represents the rate of the effective threshold range. - - If return_std_maximum is set to True, std and maximum values of the Youden's Curve are returned with the AUC. - - Note: If only one class is present in y_true, zeroes are returned for every entity. - """ - y_true = np.array(y_true) - y_score = np.array(y_score) - thresholds = np.linspace(0, 1, n_bins + 1) - assert len(y_true) == len(y_score) - assert np.all(y_true >= 0) and np.all(y_true <= 1) - if np.all(y_true == 0) or np.all(y_true == 1): - if return_std_maximum and return_curve: - return 0.0, 0.0, 0.0, (thresholds, np.zeros(len(thresholds))) - elif return_std_maximum: - return 0.0, 0.0, 0.0 - elif return_curve: - return 0.0, (thresholds, np.zeros(len(thresholds))) - else: - return 0.0 - mask_correct = y_true == 1 - count_correct = max(len(mask_correct.nonzero()[0]), 1) - count_incorrect = max(len(y_true) - count_correct, 1) - y_score_correct = y_score[mask_correct] - y_score_incorrect = y_score[~mask_correct] - yc = [] - for threshold in thresholds: - tnr = len((y_score_incorrect < threshold).nonzero()[0]) / count_incorrect - fnr = len((y_score_correct < threshold).nonzero()[0]) / count_correct - yc.append(abs(tnr - fnr)) - yc = np.array(yc) - if return_std_maximum and return_curve: - return yc.mean(), yc.std(), yc.max(), (thresholds, yc) - elif return_std_maximum: - return yc.mean(), yc.std(), yc.max() - elif return_curve: - return yc.mean(), (thresholds, yc) - else: - return yc.mean() - - -def save_confidence_hist(y_score: Union[List[float], np.ndarray], plot_dir: Union[str, Path], name: str = "hist"): - os.makedirs(plot_dir, exist_ok=True) - plt.hist(np.array(y_score), 50, range=(0, 1)) - plt.title(name) - plt.xlabel("Confidence score") - plt.ylabel("Count") - plt.savefig(Path(plot_dir) / Path(name + ".png"), dpi=300) - plt.clf() - - -def save_roc_curve( - y_true: Union[List[int], np.ndarray], - y_score: Union[List[float], np.ndarray], - plot_dir: Union[str, Path], - name: str = "roc", -): - assert len(y_true) == len(y_score) - os.makedirs(plot_dir, exist_ok=True) - fpr, tpr, _ = roc_curve(1 - np.array(y_true), 1 - np.array(y_score)) - RocCurveDisplay(fpr=fpr, tpr=tpr).plot() - plt.title(name) - plt.savefig(Path(plot_dir) / Path(name + ".png"), dpi=300) - plt.clf() - - -def save_pr_curve( - y_true: Union[List[int], np.ndarray], - y_score: Union[List[float], np.ndarray], - plot_dir: Union[str, Path], - name: str = "pr", -): - assert len(y_true) == len(y_score) - os.makedirs(plot_dir, exist_ok=True) - precision, recall, _ = precision_recall_curve(np.array(y_true), np.array(y_score)) - PrecisionRecallDisplay(precision=precision, recall=recall).plot() - plt.title(name) - plt.savefig(Path(plot_dir) / Path(name + ".png"), dpi=300) - plt.clf() - - -def save_nt_curve( - y_true: Union[List[int], np.ndarray], - y_score: Union[List[float], np.ndarray], - plot_dir: Union[str, Path], - name: str = "nt", -): - assert len(y_true) == len(y_score) - os.makedirs(plot_dir, exist_ok=True) - precision, recall, _ = precision_recall_curve(1 - np.array(y_true), 1 - np.array(y_score)) - PrecisionRecallDisplay(precision=precision, recall=recall).plot() - plt.title(name) - plt.savefig(Path(plot_dir) / Path(name + ".png"), dpi=300) - plt.clf() - - -def save_custom_confidence_curve( - thresholds: Union[List[float], np.ndarray], - values: Union[List[float], np.ndarray], - plot_dir: Union[str, Path], - name: str = "my_awesome_curve", - xlabel: Optional[str] = None, - ylabel: Optional[str] = None, -): - assert len(thresholds) == len(values) - os.makedirs(plot_dir, exist_ok=True) - plt.plot(thresholds, values) - plt.xlim([0, 1]) - plt.ylim([0, 1]) - plt.title(name) - if xlabel is not None: - plt.xlabel(xlabel) - if ylabel is not None: - plt.ylabel(ylabel) - plt.savefig(Path(plot_dir) / Path(name + ".png"), dpi=300) - plt.clf() diff --git a/nemo/collections/asr/parts/utils/data_simulation_utils.py b/nemo/collections/asr/parts/utils/data_simulation_utils.py deleted file mode 100644 index 14a853bcb6a387a2bc345e347d91741423d67905..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/data_simulation_utils.py +++ /dev/null @@ -1,1274 +0,0 @@ -# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import copy -import os -import shutil -from collections import defaultdict -from typing import Dict, List, Optional, Tuple - -import numpy as np -import torch -from scipy.stats import beta, gamma -from tqdm import tqdm - -from nemo.collections.asr.parts.preprocessing.perturb import AudioAugmentor -from nemo.collections.asr.parts.preprocessing.segment import AudioSegment -from nemo.collections.asr.parts.utils.manifest_utils import ( - get_ctm_line, - read_manifest, - write_ctm, - write_manifest, - write_text, -) -from nemo.collections.asr.parts.utils.speaker_utils import labels_to_rttmfile -from nemo.utils import logging - - -def get_cleaned_base_path(output_dir: str, overwrite_output: bool = True) -> str: - """ - Delete output directory if it exists or throw warning. - - Args: - output_dir (str): Path to output directory - overwrite_output (bool): If True, delete output directory if it exists - - Returns: - basepath (str): Path to base-path directory for writing output files - """ - if os.path.isdir(output_dir) and os.listdir(output_dir): - if overwrite_output: - if os.path.exists(output_dir): - shutil.rmtree(output_dir) - os.mkdir(output_dir) - else: - raise Exception("Output directory is nonempty and overwrite_output = false") - elif not os.path.isdir(output_dir): - os.makedirs(output_dir) - - # only add root if paths are relative - if not os.path.isabs(output_dir): - ROOT = os.getcwd() - basepath = os.path.join(ROOT, output_dir) - else: - basepath = output_dir - return basepath - - -def binary_search_alignments( - inds: List[int], - max_audio_read_sec: float, - min_alignment_count: int, - alignments: List[float], -) -> int: - """ - Binary search to find the index of the alignment that satisfies the maximum audio read duration, - `max_audio_read_sec`. This is used to avoid reading the short audio files. - NOTE: `offset_max` should be at least 1 to avoid feeding max=0 to random sampling function. - - Args: - inds (list): List of indices to search from - max_audio_read_sec (float): Maximum audio read duration - min_alignment_count (int): Minimum number of alignments to read - audio_manifest (dict): Dictionary containing the audio file's alignments - - Returns: - offset_max (int) Index of the alignment that satisfies the maximum audio read duration - """ - # Start from the left end (at index 0) and -1 * min_alignment_count for the right end - left, right = 0, len(inds) - 1 - min_alignment_count - while left < right: - mid = left + (right - left) // 2 - dur_left = alignments[-1 * min_alignment_count] - alignments[inds[mid]] - if dur_left < max_audio_read_sec: - right = mid - 1 - elif dur_left > max_audio_read_sec: - left = mid + 1 - else: - break - mid_out = left + (right - left) // 2 - # If mid_out is on the boundary, move it to the left. - if alignments[-1 * min_alignment_count] - alignments[inds[mid_out]] < max_audio_read_sec: - mid_out -= 1 - offset_max = max(mid_out, 1) - return offset_max - - -def get_subset_of_audio_manifest( - audio_manifest: dict, - offset_index: int, - max_audio_read_sec: float, - min_alignment_count: int, -) -> dict: - """ - Get a subset of `audio_manifest` for faster audio-file reading. - - Args: - audio_manifest (dict): Audio manifest dictionary. - keys: 'offset', 'duration', 'alignments', 'words' - offset_index (int): Index of the offset. - max_audio_read_sec (float): Maximum audio read duration. - min_alignment_count (int): Minimum number of alignments to read. - - Returns: - audio_manifest (dict): Subset of `audio_manifest` is returned for `words` and `alignments` keys. - """ - alignment_array = np.array(audio_manifest['alignments']) - alignment_array_pr = np.array(alignment_array[offset_index:]) - alignment_array[offset_index] - subset_alignments = alignment_array_pr[alignment_array_pr < max_audio_read_sec] - if len(subset_alignments) < min_alignment_count: - # Cases where the word next to the offset is longer than the max_audio_read_sec. - logging.warning( - f"subset_alignments of {audio_manifest['audio_filepath']} \n" - f"has subset alignment length:{len(subset_alignments)} at offset_index:{offset_index}, " - f"word:{audio_manifest['words'][offset_index:offset_index+min_alignment_count]}, " - f"alignments:{alignment_array_pr[:min_alignment_count]} which is longer than _max_audio_read_sec:{[0, max_audio_read_sec]}." - " Truncating the alignements." - ) - # Attach the `_max_audio_read_sec` to the `subset_alignments` to truncate the alignment timestamp. - subset_alignments = np.concatenate([subset_alignments, np.array([max_audio_read_sec])]) - audio_manifest['offset'], audio_manifest['duration'] = ( - alignment_array[offset_index], - subset_alignments[-1] - subset_alignments[0], - ) - audio_manifest['alignments'] = subset_alignments.tolist() - audio_manifest['words'] = audio_manifest['words'][offset_index : offset_index + len(subset_alignments)] - return audio_manifest - - -def read_audio_from_buffer( - audio_manifest: dict, - buffer_dict: dict, - offset_index: int, - device: torch.device, - max_audio_read_sec: float = 2.5, - min_alignment_count: int = 2, - read_subset: bool = True, -) -> Tuple[torch.Tensor, int, dict]: - """ - Read from the provided file path while maintaining a hash-table that saves loading time. - Also, this function only reads a subset of the audio file if `read_subset` is True for faster audio-file reading. - - Args: - audio_manifest (dict): Audio manifest dictionary. - keys: 'audio_filepath', 'duration', 'alignments', 'words' - buffer_dict (dict): Hash-table that saves loaded audio files. - offset_index (int): Index of the offset for the audio file. - device (torch.device): Device to load the audio file. - max_audio_read_sec (float): Maximum audio read duration. - min_alignment_count (int): Minimum number of alignments to read. - read_subset (bool): If True, read a subset of the audio file. - To control the length of the audio file, use data_simulator.session_params.max_audio_read_sec. - Note that using large value (greater than 3~4 sec) for `max_audio_read_sec` will slow down the generation process. - If False, read the entire audio file. - - Returns: - audio_file (torch.Tensor): Time-series audio data in a tensor. - sr (int): Sample rate of the audio file. - audio_manifest (dict): (modified) audio manifest dictionary. - """ - audio_file_id = f"{audio_manifest['audio_filepath']}#{offset_index}" - if audio_file_id in buffer_dict: - audio_file, sr, audio_manifest = buffer_dict[audio_file_id] - else: - if read_subset: - audio_manifest = get_subset_of_audio_manifest( - audio_manifest=audio_manifest, - offset_index=offset_index, - max_audio_read_sec=max_audio_read_sec, - min_alignment_count=min_alignment_count, - ) - segment = AudioSegment.from_file( - audio_file=audio_manifest['audio_filepath'], - offset=audio_manifest['offset'], - duration=audio_manifest['duration'], - ) - else: - segment = AudioSegment.from_file(audio_file=audio_manifest['audio_filepath']) - audio_file, sr = torch.from_numpy(segment.samples).to(device), segment.sample_rate - if read_subset and segment.duration < (audio_manifest['alignments'][-1] - audio_manifest['alignments'][0]): - audio_manifest['alignments'][-1] = min(segment.duration, audio_manifest['alignments'][-1]) - if audio_file.ndim > 1: - audio_file = torch.mean(audio_file, 1, False).to(device) - buffer_dict[audio_file_id] = (audio_file, sr, audio_manifest) - return audio_file, sr, audio_manifest - - -def perturb_audio( - audio: torch.Tensor, sr: int, augmentor: Optional[AudioAugmentor] = None, device: Optional[torch.device] = None -) -> torch.Tensor: - """ - Perturb the audio (segment or session) using audio augmentor. - - Args: - audio (torch.Tensor): Time-series signal of the segment - sr (int): Sample rate of the original audio file - augmentor (AudioAugmentor): Audio augmentor to use - device (torch.device): Device to load the audio file - - Returns: - audio (torch.Tensor): Perturbed audio (time-series signal) of the segment - """ - if augmentor is None: - return audio - device = device if device is not None else torch.device('cpu') - if isinstance(audio, torch.Tensor): - audio = audio.cpu().numpy() - audio_segment = AudioSegment(audio, sample_rate=sr) - augmentor.perturb(audio_segment) - audio_segment = torch.from_numpy(audio_segment.samples).to(device) - return audio_segment - - -def normalize_audio(array: torch.Tensor) -> torch.Tensor: - """ - Normalize the audio signal to avoid clipping. - - Args: - array (torch.Tensor): Time-series audio data in a tensor. - - Returns: - (torch.Tensor): Normalized audio signal. - """ - return array / (1.0 * torch.max(torch.abs(array))) - - -def get_power_of_audio_file(audio_file: str, end_audio_file: int, running_len_samples: int, device: torch.device): - """ - Calculate the power of the audio signal. - - Args: - audio_file (torch.Tensor): Time-series audio data in a tensor. - end_audio_file (int): End index of the audio file. - running_len_samples (int): Running length of the audio file. - device (torch.device): Device to use. - - Returns: - (float): Power of the audio signal. - """ - return torch.mean(audio_file[: end_audio_file - running_len_samples] ** 2).to(device) - - -def get_scaled_audio_signal( - audio_file: torch.Tensor, - end_audio_file: int, - running_len_samples: int, - desired_avg_power_noise: float, - device: torch.device, -): - """ - Scale the audio signal to the desired average power. - - Args: - audio_file (torch.Tensor): Time-series audio data in a tensor. - end_audio_file (int): End index of the audio file. - running_len_samples (int): Running length of the audio file. - desired_avg_power_noise (float): Desired average power of the audio file. - device (torch.device): Device to use. - - Returns: - scaled_audio_file (torch.Tensor): Scaled audio signal. - """ - pow_audio_file = get_power_of_audio_file( - audio_file=audio_file, end_audio_file=end_audio_file, running_len_samples=running_len_samples, device=device - ) - scaled_audio_file = audio_file[: end_audio_file - running_len_samples] * torch.sqrt( - desired_avg_power_noise / pow_audio_file - ).to(device) - return scaled_audio_file - - -def get_desired_avg_power_noise( - power_array: float, - snr_min: float, - snr_max: float, - background_noise_snr: float, -): - """ - Calculate the desired average power of the noise. - - Args: - power_array (float): Power of the audio signal. - snr_min (float): Minimum SNR. - snr_max (float): Maximum SNR. - background_noise_snr (float): SNR of the background noise. - - Returns: - desired_avg_power_noise (float): Desired average power of the noise. - """ - if (snr_min is not None) and (snr_max is not None) and (snr_min <= snr_max): - desired_snr = np.random.uniform(snr_min, snr_max) - else: - desired_snr = background_noise_snr - ratio = 10 ** (desired_snr / 20) - desired_avg_power_noise = power_array / ratio - return desired_avg_power_noise, desired_snr - - -def get_background_noise( - len_array: int, - power_array: float, - noise_samples: list, - audio_read_buffer_dict: dict, - snr_min: float, - snr_max: float, - background_noise_snr: float, - seed: int, - device: torch.device, - sr: float = 16000, -): - """ - Augment with background noise (inserting ambient background noise up to the desired SNR for the full clip). - - Args: - len_array (int): Length of background noise required. - power_array (float): Power of the audio signal. - noise_samples (list): List of noise samples. - audio_read_buffer_dict (dict): Dictionary containing audio read buffer. - snr_min (float): Minimum SNR. - snr_max (float): Maximum SNR. - background_noise_snr (float): SNR of the background noise. - seed (int): Seed for random number generator. - device (torch.device): Device to use. - - Returns: - bg_array (tensor): Tensor containing background noise. - desired_snr (float): Desired SNR for adding background noise. - """ - np.random.seed(seed) - bg_array = torch.zeros(len_array).to(device) - desired_avg_power_noise, desired_snr = get_desired_avg_power_noise( - power_array=power_array, snr_min=snr_min, snr_max=snr_max, background_noise_snr=background_noise_snr - ) - running_len_samples = 0 - noise_segment_list = [] - - last_mixed_cut_offset = 0 - file_id = np.random.randint(len(noise_samples)) - while running_len_samples < len_array: # build background audio stream (the same length as the full file) - audio_file, sr, audio_manifest = read_audio_from_buffer( - audio_manifest=noise_samples[file_id], - buffer_dict=audio_read_buffer_dict, - offset_index=0, - device=device, - read_subset=False, - ) - # noise_segment_list.append( - noise_manifest_dict = copy.deepcopy(audio_manifest) - noise_manifest_dict['duration'] = float(min(len(audio_file), len_array - running_len_samples - 1) / sr) - noise_manifest_dict['offset'] = 0 - noise_manifest_dict['volume'] = 1.0 - noise_manifest_dict['mixed_cut_offset'] = last_mixed_cut_offset - last_mixed_cut_offset += noise_manifest_dict['duration'] - - noise_segment_list.append(noise_manifest_dict) - - if running_len_samples + len(audio_file) < len_array: - end_audio_file = running_len_samples + len(audio_file) - else: - end_audio_file = len_array - scaled_audio_file = get_scaled_audio_signal( - audio_file=audio_file, - end_audio_file=end_audio_file, - running_len_samples=running_len_samples, - desired_avg_power_noise=desired_avg_power_noise, - device=device, - ) - - bg_array[running_len_samples:end_audio_file] = scaled_audio_file - running_len_samples = end_audio_file - - return bg_array, desired_snr, noise_segment_list - - -def get_random_offset_index( - audio_manifest: dict, - audio_read_buffer_dict: dict, - offset_min: int = 0, - max_audio_read_sec: float = 2.5, - min_alignment_count: int = 2, -) -> int: - """ - Get an index for randomly accessing the silence in alignment timestamps. - - Args: - audio_manifest (dict): Audio manifest dictionary. - keys: 'audio_filepath', 'duration', 'alignments', 'words' - audio_read_buffer_dict (dict): Dictionary containing audio read buffer. - offset_min (int): Minimum offset index. (Default: 0) - max_audio_read_sec (float): Maximum audio read duration in seconds. (Default: 2.5) - min_alignment_count (int): Minimum number of alignment timestamps. (Default: 2) - - Returns: - (int): Random offset index smaller than `offset_count`. - """ - if len(audio_manifest['alignments']) <= min_alignment_count: - raise ValueError( - f"Audio file {audio_manifest['audio_filepath']} has less than {min_alignment_count} alignment timestamps." - ) - index_file_id = f"{audio_manifest['audio_filepath']}#index" - - # Avoid multiple indexings of the same audio file by using a hash-table. - if index_file_id in audio_read_buffer_dict: - (sil_inds, offset_max) = audio_read_buffer_dict[index_file_id] - else: - # Find all silence indices - sil_inds = np.where((np.array(audio_manifest['words']) == '') == True)[0] - if audio_manifest['alignments'][-1] - audio_manifest['alignments'][0] < max_audio_read_sec: - # The total duration is already short, therefore skip range search. - offset_max = 1 - else: - # Find the range that satisfies `max_audio_read_sec` duration. - offset_max = binary_search_alignments( - inds=sil_inds, - max_audio_read_sec=max_audio_read_sec, - min_alignment_count=min_alignment_count, - alignments=audio_manifest['alignments'], - ) - - audio_read_buffer_dict[index_file_id] = (sil_inds, offset_max) - - # If the audio file is shorter than the max_audio_read_sec, then we don't need to read a subset of the audio file. - if ( - len(sil_inds) <= min_alignment_count - or (audio_manifest['alignments'][-1] - audio_manifest['alignments'][0]) < max_audio_read_sec - ): - return offset_min - else: - offset_index = np.random.randint(offset_min, offset_max) - return sil_inds[offset_index] - - -def get_speaker_ids(sess_idx: int, speaker_samples: dict, permutated_speaker_inds: list) -> List[str]: - """ - Randomly select speaker IDs from the loaded manifest file. - - Args: - sess_idx (int): Session index in integer. - speaker_samples (dict): Dictionary mapping speaker ID to their list of samples. - permutated_speaker_inds (list): List of permutated speaker indices. - - Returns: - speaker_ids (list): List of speaker IDs - """ - all_speaker_ids = list(speaker_samples.keys()) - # Measure the length of permutated_speaker_inds and mod the sess_idx number so that - # sess_idx is always less than the length of permutated_speaker_inds - sess_idx_circular = sess_idx % permutated_speaker_inds.shape[0] - idx_list = permutated_speaker_inds[sess_idx_circular, :] - speaker_ids = [all_speaker_ids[i] for i in idx_list] - return speaker_ids - - -def build_speaker_samples_map(manifest: dict, tqdm_bar: bool = False) -> dict: - """ - Build a dictionary for mapping speaker ID to their list of samples - - Returns: - speaker_samples (Dict[list]): - Dictionary mapping speaker ID to their list of samples - """ - speaker_samples = defaultdict(list) - # logging.info("Building speaker to samples map...") - for sample in tqdm(manifest, total=len(manifest), disable=not tqdm_bar): - # for sample in manifest: - speaker_id = sample['speaker_id'] - speaker_samples[speaker_id].append(sample) - return speaker_samples - - -def read_noise_manifest(add_bg: bool, background_manifest: str): - """ - Read the noise manifest file and sample the noise manifest. - - Args: - add_bg (bool): Whether to add background noise. - background_manifest (str): Path to the background noise manifest file. - - Returns: - noise_manifest (list): List of the entire noise source samples. - """ - noise_manifest = [] - if add_bg is True: - if background_manifest is not None: - background_manifest_list = background_manifest - if isinstance(background_manifest_list, str): - background_manifest_list = [background_manifest_list] - for background_manifest in background_manifest_list: - if os.path.exists(background_manifest): - noise_manifest += read_manifest(background_manifest) - else: - raise FileNotFoundError(f"Noise manifest file: {background_manifest} file not found.") - else: - raise FileNotFoundError( - f"Noise manifest file is {background_manifest}. Please provide a valid noise manifest file/list if add_bg=True." - ) - return noise_manifest - - -def read_rir_manifest(rir_manifest: str): - """ - Read the rir manifest file and sample the rir manifest. - """ - - rir_manifest_list = [rir_manifest] - rir_loaded_list = [] - for manifest_file in rir_manifest_list: - if os.path.exists(manifest_file): - rir_loaded_list.extend(read_manifest(manifest_file)) - - return rir_loaded_list - - -def get_speaker_samples(speaker_ids: List[str], speaker_samples: dict) -> Dict[str, list]: - """ - Get a list of the samples for each of the specified speakers. - - Args: - speaker_ids (list): LibriSpeech speaker IDs for each speaker in the current session. - speaker_samples (dict): Dictionary mapping speaker ID to their list of samples. - - Returns: - speaker_wav_align_map (dict): Dictionary containing speaker IDs and their corresponding wav filepath and alignments. - """ - speaker_wav_align_map = defaultdict(list) - for sid in speaker_ids: - speaker_wav_align_map[sid] = speaker_samples[sid] - return speaker_wav_align_map - - -def add_silence_to_alignments(audio_manifest: dict): - """ - Add silence to the beginning of the alignments and words. - - Args: - audio_manifest (dict): Audio manifest dictionary. - keys: 'audio_filepath', 'duration', 'alignments', 'words' - - Returns: - audio_manifest (dict): Audio manifest dictionary with silence added to the beginning. - """ - if type(audio_manifest['words'][0]) == str and len(audio_manifest['words'][0]) > 0: - audio_manifest['words'].insert(0, "") - audio_manifest['alignments'].insert(0, 0.0) - return audio_manifest - - -def load_speaker_sample( - speaker_wav_align_map: List[dict], - speaker_ids: List[str], - speaker_turn: int, - min_alignment_count: int, -) -> str: - """ - Load a sample for the selected speaker ID. - The first alignment and word must be silence that determines the start of the alignments. - - Args: - speaker_wav_align_map (dict): Dictionary containing speaker IDs and their corresponding wav filepath and alignments. - speaker_ids (list): LibriSpeech speaker IDs for each speaker in the current session. - speaker_turn (int): Current speaker turn. - output_precision (int): Precision of the output alignments in integer. - min_alignment_count (int): Minimum number of alignments in the audio file. - - Returns: - audio_manifest (dict): Audio manifest dictionary containing the wav filepath, words and alignments. - """ - speaker_id = speaker_ids[speaker_turn] - file_id = np.random.randint(0, max(len(speaker_wav_align_map[str(speaker_id)]) - 1, 1)) - audio_manifest = speaker_wav_align_map[str(speaker_id)][file_id] - - # Check if the alignment file has at least 2 words. - if len(audio_manifest['alignments']) < min_alignment_count: - raise ValueError( - f"Alignment file {audio_manifest['audio_filepath']} has an inappropriate length of {len(audio_manifest['alignments'])} < 2." - ) - - # Check whether the first word is silence and insert a silence token if the first token is not silence. - if audio_manifest['words'][0] != "": - audio_manifest = add_silence_to_alignments(audio_manifest) - - audio_manifest = copy.deepcopy(audio_manifest) - return audio_manifest - - -def get_split_points_in_alignments( - words: List[str], - alignments: List[float], - split_buffer: float, - sr: int, - sentence_audio_len: int, - new_start: float = 0, -): - """ - Collect split points in the alignment based on silence. - Silence is defined as a blank symbol between two words that is longer than 2 * split_buffer. - - Args: - words (List[str]): List of words in the sentence. - alignments (List[float]): List of alignment timestamps in the sentence. - split_buffer (float): Buffer length in seconds. - sr (int): Sample rate of the audio. - sentence_audio_len (int): Length of the sentence audio in samples. - new_start (float): Start of the sentence audio in seconds. - - Returns: - splits (List[List[int]]): List of integer split points in the sentence audio. - """ - splits = [] - for i in range(len(words)): - if words[i] == "" and i != 0 and i != len(words) - 1: - # if words[i] == "" and i != 0 and i != len(words) - 1: - silence_length = alignments[i] - alignments[i - 1] - if silence_length > 2 * split_buffer: # split utterance on silence - new_end = alignments[i - 1] + split_buffer - splits.append( - [ - int(new_start * sr), - int(new_end * sr), - ] - ) - new_start = alignments[i] - split_buffer - # The last split point should be added - splits.append([int(new_start * sr), sentence_audio_len]) - return splits - - -def per_speaker_normalize( - sentence_audio: torch.Tensor, splits: List[List[int]], speaker_turn: int, volume: List[float], device: torch.device -) -> torch.Tensor: - """ - Normalize time-series audio signal per speaker. - - Args: - sentence_audio (torch.Tensor): Time-series audio signal. - splits (List[List[int]]): List of integer split points in the sentence audio. - speaker_turn (int): Speaker ID of the current speaker. - volume (List[float]): List of volume levels for each speaker. - device (torch.device): Device to use for computations. - - Returns: - sentence_audio (torch.Tensor): Normalized time-series audio signal. - """ - split_length = torch.tensor(0).to(device).double() - split_sum = torch.tensor(0).to(device).double() - for split in splits: - split_length += len(sentence_audio[split[0] : split[1]]) - split_sum += torch.sum(sentence_audio[split[0] : split[1]] ** 2) - average_rms = torch.sqrt(split_sum * 1.0 / split_length) - sentence_audio = sentence_audio / (1.0 * average_rms) * volume[speaker_turn] - return sentence_audio - - -class DataAnnotator(object): - """ - Class containing the functions that create RTTM, CTM, JSON files. - - Arguments in config: - - data_simulator: - session_config: - num_speakers (int): Number of unique speakers per multispeaker audio session - session_params: - split_buffer (float): Split RTTM labels if greater than twice this amount of silence (to avoid long gaps between - utterances as being labelled as speech) - outputs: - output_dir (str): Output directory for audio sessions and corresponding label files - output_filename (str): Output filename for the wav and RTTM files - overwrite_output (bool): If true, delete the output directory if it exists - output_precision (int): Number of decimal places in output files - """ - - def __init__(self, cfg): - """ - Args: - cfg: OmegaConf configuration loaded from yaml file. - """ - self._params = cfg - self._files = {} - self._init_file_write() - self._init_filelist_lists() - - def _init_file_write(self): - """ - Initialize file writing arguments - """ - self._file_base_str = "synthetic" - self._file_types = ["wav", "rttm", "json", "noise", "ctm", "txt", "meta"] - self._annotation_types = ["rttm", "json", "ctm"] - - def _init_filelist_lists(self): - """ - Initialize lists to store the filelists for each file type - """ - self.annote_lists = {} - for file_type in self._file_types: - self.annote_lists[f"{file_type}_list"] = [] - - def init_annotation_lists(self): - """ - Initialize lists to store the annotations for each file type - """ - for file_type in self._file_types: - self.annote_lists[file_type] = [] - - def create_new_rttm_entry( - self, - words: List[str], - alignments: List[float], - start: int, - end: int, - speaker_id: int, - add_split_buffer: bool = False, - ) -> List[str]: - """ - Create new RTTM entries (to write to output rttm file) - - Args: - words (list): List of words in the current audio file. - alignments (list): List of alignments (timestamps) for the current audio file. - start (int): Current start of the audio file being inserted. - end (int): End of the audio file being inserted. - speaker_id (int): LibriSpeech speaker ID for the current entry. - - Returns: - rttm_list (list): List of rttm entries - """ - rttm_list = [] - new_start = start - # look for split locations - for i in range(len(words)): - if words[i] == "" and i != 0 and i != len(words) - 1: - silence_length = alignments[i] - alignments[i - 1] - if ( - silence_length > 2 * self._params.data_simulator.session_params.split_buffer - ): # split utterance on silence - new_end = start + alignments[i - 1] - - # new_end = start + alignments[i - 1] + self._params.data_simulator.session_params.split_buffer - - # import ipdb; ipdb.set_trace() - # if add_split_buffer: # add split buffer if specified in config - # new_end += self._params.data_simulator.session_params.split_buffer - t_stt = round(float(new_start), self._params.data_simulator.outputs.output_precision) - t_end = round(float(new_end), self._params.data_simulator.outputs.output_precision) - rttm_list.append(f"{t_stt} {t_end} {speaker_id}") - new_start = start + alignments[i] - # new_start = start + alignments[i] - self._params.data_simulator.session_params.split_buffer - - t_stt = round(float(new_start), self._params.data_simulator.outputs.output_precision) - t_end = round(float(end), self._params.data_simulator.outputs.output_precision) - rttm_list.append(f"{t_stt} {t_end} {speaker_id}") - return rttm_list - - def create_new_json_entry( - self, - text: List[str], - wav_filename: str, - start: float, - length: float, - speaker_id: int, - rttm_filepath: str, - ctm_filepath: str, - ) -> dict: - """ - Create new JSON entries (to write to output json file). - - Args: - text (list): string of text for the current entry. - wav_filename (str): Filename of the wav file. - start (float): Start time of the current entry. - length (float): Length of the current entry. - speaker_id (int): speaker ID for the current entry. - rttm_filepath (str): Path to the RTTM file. - ctm_filepath (str): Path to the CTM file. - - Returns: - meta (dict): JSON entry dictionary. - """ - start = round(float(start), self._params.data_simulator.outputs.output_precision) - length = round(float(length), self._params.data_simulator.outputs.output_precision) - meta = { - "audio_filepath": wav_filename, - "offset": start, - "duration": length, - "label": speaker_id, - "text": text, - "num_speakers": self._params.data_simulator.session_config.num_speakers, - "rttm_filepath": rttm_filepath, - "ctm_filepath": ctm_filepath, - "uem_filepath": None, - } - return meta - - def create_ctm_entry_from_segment_list( - self, source_segment_list, session_name: str, speaker_id: int, start: int - ) -> List[str]: - """ - Create new CTM entry (to write to output ctm file) - - Args: - words (list): List of words in the current audio file. - alignments (list): List of alignments (timestamps) for the current audio file. - session_name (str): Current session name. - speaker_id (int): LibriSpeech speaker ID for the current entry. - start (int): Current start of the audio file being inserted. - - Returns: - arr (list): List of ctm entries - """ - arr = [] - start = float(round(start, self._params.data_simulator.outputs.output_precision)) - - for seg_dict in source_segment_list: - words = seg_dict["words"] - alignments = seg_dict["alignments"] - start_offset = seg_dict["mixed_cut_offset"] - alignment_offset = alignments[0] - for i in range(len(words)): - word = words[i] - if ( - word != "" - ): # note that using the current alignments the first word is always empty, so there is no error from indexing the array with i-1 - # prev_align = 0 if i == 0 else alignments[i - 1] - # align1 = round(float(prev_align + start), self._params.data_simulator.outputs.output_precision) - align1 = round( - float(start_offset + alignments[i] - alignment_offset), - self._params.data_simulator.outputs.output_precision, - ) - align2 = round( - float(start_offset + alignments[i + 1] - alignment_offset - align1), - self._params.data_simulator.outputs.output_precision, - ) - text = get_ctm_line( - source=session_name, - channel=1, - start_time=align1, - duration=align2, - token=word, - conf=None, - type_of_token='lex', - speaker=speaker_id, - ) - arr.append((align1, text)) - return arr - - def create_new_ctm_entry( - self, - words: List[str], - alignments: List[float], - session_name: str, - speaker_id: int, - start: int, - ) -> List[str]: - """ - Create new CTM entry (to write to output ctm file) - - Args: - words (list): List of words in the current audio file. - alignments (list): List of alignments (timestamps) for the current audio file. - session_name (str): Current session name. - speaker_id (int): LibriSpeech speaker ID for the current entry. - start (int): Current start of the audio file being inserted. - - Returns: - arr (list): List of ctm entries - """ - arr, word_and_ts_list = [], [] - start = float(round(start, self._params.data_simulator.outputs.output_precision)) - - for i in range(len(words)): - word = words[i] - if ( - word != "" - ): # note that using the current alignments the first word is always empty, so there is no error from indexing the array with i-1 - prev_align = 0 if i == 0 else alignments[i - 1] - align1 = round(float(prev_align + start), self._params.data_simulator.outputs.output_precision) - align2 = round(float(alignments[i] - prev_align), self._params.data_simulator.outputs.output_precision) - end_time = round(align1 + align2, self._params.data_simulator.outputs.output_precision) - text = get_ctm_line( - source=session_name, - channel=1, - start_time=align1, - duration=align2, - token=word, - conf=None, - type_of_token='lex', - speaker=speaker_id, - output_precision=self._params.data_simulator.outputs.output_precision, - ) - word_and_ts_list.append((word, align1, end_time)) - arr.append((align1, text)) - return arr, word_and_ts_list - - def add_to_filename_lists(self, basepath: str, filename: str): - """ - Add the current filename to the list of filenames for each file type. - - Args: - basepath (str): Basepath for output files. - filename (str): Base filename for all output files. - """ - full_base_filepath = os.path.join(basepath, filename) - for file_type in self._file_types: - self.annote_lists[f"{file_type}_list"].append(f"{full_base_filepath}.{file_type}") - - def write_filelist_files(self, basepath): - """ - Write all filelist files. - - Args: - basepath (str): Basepath for output files. - """ - for file_type in self._file_types: - with open(f"{basepath}/{self._file_base_str}_{file_type}.list", "w") as list_file: - list_file.write("\n".join(self.annote_lists[f"{file_type}_list"])) - list_file.close() - - def write_annotation_files(self, basepath: str, filename: str, meta_data: dict): - """ - Write all annotation files: RTTM, JSON, CTM, TXT, and META. - - Args: - basepath (str): Basepath for output files. - filename (str): Base filename for all output files. - meta_data (dict): Metadata for the current session. - rttm_list (list): List of RTTM entries. - json_list (list): List of JSON entries. - ctm_list (list): List of CTM entries. - """ - labels_to_rttmfile(self.annote_lists['rttm'], filename, self._params.data_simulator.outputs.output_dir) - write_manifest(os.path.join(basepath, filename + '.json'), self.annote_lists['json']) - write_ctm(os.path.join(basepath, filename + '.ctm'), self.annote_lists['ctm']) - write_text(os.path.join(basepath, filename + '.txt'), self.annote_lists['ctm']) - write_manifest(os.path.join(basepath, filename + '.meta'), [meta_data]) - - def write_annotation_rttm_and_ctm(self, basepath: str, filename: str): - """ - Write all annotation files: RTTM, JSON, CTM, TXT, and META. - - Args: - basepath (str): Basepath for output files. - filename (str): Base filename for all output files. - meta_data (dict): Metadata for the current session. - rttm_list (list): List of RTTM entries. - json_list (list): List of JSON entries. - ctm_list (list): List of CTM entries. - """ - labels_to_rttmfile( - self.annote_lists['rttm'], os.path.join(basepath, filename), self._params.data_simulator.outputs.output_dir - ) - write_ctm(os.path.join(basepath, filename + '.ctm'), self.annote_lists['ctm']) - - -class SpeechSampler(object): - """ - Class for sampling speech samples for Multispeaker Audio Session Simulator - - Args: - cfg: OmegaConf configuration loaded from yaml file. - - Variables for sampling speech: - self.running_speech_len_samples (int): Running total of speech samples in the current audio session. - self.running_silence_len_samples (int): Running total of silence samples in the current audio session. - self.running_overlap_len_samples (int): Running total of overlap samples in the current audio session. - - self.sess_silence_mean (int) : Targeted mean number of silence samples in the current audio session. - self.per_silence_min_len (int): Minimum number of silence samples in the silence segment. - self.per_silence_max_len (int): Maximum number of silence samples in the silence segment. - - self.sess_overlap_mean (int): Targeted mean number of overlap samples in the current audio session. - self.per_overlap_min_len (int): Minimum number of overlap samples in the overlap segment. - self.per_overlap_max_len (int): Maximum number of overlap samples in the overlap segment. - - data_simulator: - session_params: - mean_silence (float): Mean proportion of silence to speaking time in the audio session. Should be in range [0, 1). - mean_silence_var (float): Variance for mean silence in all audio sessions. - This value should be 0 <= mean_silence_var < mean_silence * (1 - mean_silence). - per_silence_var (float): Variance for each silence in an audio session, set large values (e.g., 20) for de-correlation. - per_silence_min (float): Minimum duration for each silence, default to 0. - per_silence_max (float): Maximum duration for each silence, default to -1 for no maximum. - - mean_overlap (float): Mean proportion of overlap in the overall non-silence duration. Should be in range [0, 1) and - recommend [0, 0.15] range for accurate results. - mean_overlap_var (float): Variance for mean overlap in all audio sessions. - This value should be 0 <= mean_overlap_var < mean_overlap * (1 - mean_overlap). - per_overlap_var (float): Variance for per overlap in each session, set large values to de-correlate silence lengths - with the latest speech segment lengths - per_overlap_min (float): Minimum per overlap duration in seconds - per_overlap_max (float): Maximum per overlap duration in seconds, set -1 for no maximum - """ - - def __init__(self, cfg): - """ - Args: - cfg: OmegaConf configuration loaded from yaml file. - """ - self._params = cfg - - self.running_speech_len_samples = 0 - self.running_silence_len_samples = 0 - self.running_overlap_len_samples = 0 - - self.sess_silence_mean = None - self.per_silence_min_len = 0 - self.per_silence_max_len = 0 - - self.sess_overlap_mean = None - self.per_overlap_min_len = 0 - self.per_overlap_max_len = 0 - - self.mean_overlap = float(self._params.data_simulator.session_params.mean_overlap) - self.mean_overlap_var = float(self._params.data_simulator.session_params.mean_overlap_var) - - self.mean_silence = float(self._params.data_simulator.session_params.mean_silence) - self.mean_silence_var = float(self._params.data_simulator.session_params.mean_silence_var) - - self.per_silence_var = float(self._params.data_simulator.session_params.per_silence_var) - self.per_overlap_var = float(self._params.data_simulator.session_params.per_overlap_var) - - self.num_noise_files = int(self._params.data_simulator.background_noise.num_noise_files) - - def _mean_var_to_a_and_b(self, mean: float, var: float) -> Tuple[float, float]: - """ - Convert mean and variance to a and b parameters for beta distribution. - - Args: - mean (float): Mean of the beta distribution. - var (float): Variance of the beta distribution. - - Returns: - Tuple[float, float]: a and b parameters for beta distribution. - """ - a = mean**2 * (1 - mean) / var - mean - b = mean * (1 - mean) ** 2 / var - (1 - mean) - return a, b - - def _init_silence_params(self): - """ - Initialize parameters for silence insertion in the current session. - """ - self.running_speech_len_samples = 0 - self.running_silence_len_samples = 0 - - self.per_silence_min_len = int( - max(0, self._params.data_simulator.session_params.per_silence_min) * self._params.data_simulator.sr - ) - if self._params.data_simulator.session_params.per_silence_max > 0: - self.per_silence_max_len = int( - self._params.data_simulator.session_params.per_silence_max * self._params.data_simulator.sr - ) - else: - self.per_silence_max_len = int( - self._params.data_simulator.session_config.session_length * self._params.data_simulator.sr - ) - - def _init_overlap_params(self): - """ - Initialize parameters for overlap insertion in the current session. - """ - self.running_overlap_len_samples = 0 - - self.per_overlap_min_len = int( - max(0, self._params.data_simulator.session_params.per_overlap_min) * self._params.data_simulator.sr - ) - if self._params.data_simulator.session_params.per_overlap_max > 0: - self.per_overlap_max_len = int( - self._params.data_simulator.session_params.per_overlap_max * self._params.data_simulator.sr - ) - else: - self.per_overlap_max_len = int( - self._params.data_simulator.session_config.session_length * self._params.data_simulator.sr - ) - - def silence_vs_overlap_selector(self, running_len_samples: int, non_silence_len_samples: int) -> bool: - """ - Compare the current silence ratio to the current overlap ratio. Switch to either silence or overlap mode according - to the amount of the gap between current ratio and session mean in config. - - Args: - running_len_samples (int): Length of the current session in samples. - non_silence_len_samples (int): Length of the signal that is not silence in samples. - - Returns: - add_overlap (bool): True if the current silence ratio is less than the current overlap ratio, False otherwise. - """ - if running_len_samples > 0: - self.current_silence_ratio = (running_len_samples - self.running_speech_len_samples) / running_len_samples - self.current_overlap_ratio = self.running_overlap_len_samples / non_silence_len_samples - else: - self.current_silence_ratio, self.current_overlap_ratio = 0, 0 - - # self.silence_discrepancy = max(0, self.sess_silence_mean - self.current_silence_ratio) - # self.overlap_discrepancy = max(0, self.sess_overlap_mean - self.current_overlap_ratio) - # threshold = self.silence_discrepancy / (self.overlap_discrepancy + self.silence_discrepancy + 1e-10) - # add_overlap = np.random.rand() > threshold - self.silence_discrepancy = self.current_silence_ratio - self.sess_silence_mean - self.overlap_discrepancy = self.current_overlap_ratio - self.sess_overlap_mean - add_overlap = bool(self.overlap_discrepancy < self.silence_discrepancy) - return add_overlap - - def get_session_silence_mean(self): - """ - Get the target mean silence for current session using re-parameterized Beta distribution. - The following constraints are applied to make a > 0 and b > 0: - - 0 < mean_silence < 1 - 0 < mean_silence_var < mean_silence * (1 - mean_silence) - - Args: - silence_mean (float): - Target mean silence for the current session - """ - self._init_silence_params() - mean, var = self.mean_silence, self.mean_silence_var - if var > 0: - a, b = self._mean_var_to_a_and_b(mean, var) - if a < 0 or b < 0: - raise ValueError( - f"Beta(a, b), a = {a:.3f} and b = {b:.3f} should be both greater than 0. " - f"Invalid `mean_silence_var` value {var} for sampling from Beta distribution. " - f"`mean_silence_var` should be less than `mean_silence * (1 - mean_silence)`. " - f"Please check `mean_silence_var` and try again." - ) - self.sess_silence_mean = beta(a, b).rvs() - else: - self.sess_silence_mean = mean - return self.sess_silence_mean - - def get_session_overlap_mean(self): - """ - Get the target mean overlap for current session using re-parameterized Beta distribution. - The following constraints are applied to make a > 0 and b > 0: - - 0 < mean_overlap < 1 - 0 < mean_overlap_var < mean_overlap * (1 - mean_overlap) - - Returns: - overlap_mean (float): - Target mean overlap for the current session - """ - self._init_overlap_params() - mean, var = self.mean_overlap, self.mean_overlap_var - if var > 0: - a, b = self._mean_var_to_a_and_b(mean, var) - if a < 0 or b < 0: - raise ValueError( - f"Beta(a, b), a = {a:.3f} and b = {b:.3f} should be both greater than 0. " - f"Invalid `mean_overlap_var` value {var} for sampling from Beta distribution. " - f"`mean_overlap_var` should be less than `mean_overlap * (1 - mean_overlap)`. " - f"Please check `mean_overlap_var` and try again." - ) - self.sess_overlap_mean = beta(a, b).rvs() - else: - self.sess_overlap_mean = mean - return self.sess_overlap_mean - - def sample_from_silence_model(self, running_len_samples: int) -> int: - """ - Sample from the silence model to determine the amount of silence to add between sentences. - Gamma distribution is employed for modeling the highly skewed distribution of silence length distribution. - When we add silence between sentences, we want to ensure that the proportion of silence meets the `sess_silence_mean`. - Thus, [Session Silence Mean] = [Total Running Silence Time] / [Total Running Session Time] equation holds. We employ the following - formula to determine the amount of silence to add, which is `silence_mean`: - - self.sess_silence_mean = (silence_mean + self.running_silence_len_samples) / (silence_mean + running_len_samples) - - The above equation is setting `silence_mean` to yield the desired silence ratio `self.sess_silence_mean`. - We use the above `silence_mean` value to sample silence-length for each silence occurrence. - - Args: - running_len_samples (int): - Running length of the session (in terms of number of samples). - session_len_samples (int): - Targeted total session length (in terms of number of samples). - - Returns: - silence_amount (int): Amount of silence to add between sentences (in terms of number of samples). - """ - silence_mean = ((self.sess_silence_mean * running_len_samples) - self.running_silence_len_samples) / ( - 1 - self.sess_silence_mean - ) - silence_mean = max(self.per_silence_min_len, min(silence_mean, self.per_silence_max_len)) - if silence_mean > 0: - self.per_silence_var = self._params.data_simulator.session_params.per_silence_var - silence_amount = ( - int(gamma(a=(silence_mean**2) / self.per_silence_var, scale=self.per_silence_var / silence_mean).rvs()) - if self.per_silence_var > 0 - else int(silence_mean) - ) - silence_amount = max(self.per_silence_min_len, min(silence_amount, self.per_silence_max_len)) - else: - silence_amount = 0 - return silence_amount - - def sample_from_overlap_model(self, non_silence_len_samples: int): - """ - Sample from the overlap model to determine the amount of overlap between segments. - Gamma distribution is employed for modeling the highly skewed distribution of overlap length distribution. - When we add an overlap occurrence, we want to meet the desired overlap ratio defined by `self.sess_overlap_mean`. - Thus, [Session Overlap Mean] = [Total Running Overlap Speech Time] / [Total Running Non-Silence Speech Time]. - Let `overlap_mean` be the desired overlap amount, then the mean and variance of the gamma distribution is given by: - - self.sess_overlap_mean = (overlap_mean + self.running_overlap_len_samples) / (non_silence_len_samples - overlap_mean) - - The above equation is setting `overlap_mean` to yield the desired overlap ratio `self.sess_overlap_mean`. - We use the above `overlap_mean` value to sample overlap-length for each overlap occurrence. - - Args: - non_silence_len_samples (int): - The total amount of non-silence (speech) region regardless of overlap status - - Returns: - desired_overlap_amount (int): - Amount of overlap between segments (in terms of number of samples). - """ - overlap_mean = ((self.sess_overlap_mean * non_silence_len_samples) - self.running_overlap_len_samples) / ( - 1 + self.sess_overlap_mean - ) - overlap_mean = max(self.per_overlap_min_len, min(max(0, overlap_mean), self.per_overlap_max_len)) - - if overlap_mean > 0: - desired_overlap_amount = ( - int(gamma(a=overlap_mean**2 / self.per_overlap_var, scale=self.per_overlap_var / overlap_mean).rvs()) - if self.per_overlap_var > 0 - else int(overlap_mean) - ) - desired_overlap_amount = max( - self.per_overlap_min_len, min(desired_overlap_amount, self.per_overlap_max_len) - ) - else: - desired_overlap_amount = 0 - return desired_overlap_amount - - def sample_noise_manifest(self, noise_manifest: dict) -> list: - """ - Sample noise manifest to a specified count `num_noise_files` for the current simulated audio session. - - Args: - noise_manifest (list): - List of noise source samples to be sampled from. - - Returns: - sampled_noise_manifest (list): - List of noise samples to be used for the current session. - """ - num_noise_files = min(len(noise_manifest), self.num_noise_files) - sampled_noise_manifest = [] - if num_noise_files > 0: - selected_noise_ids = np.random.choice(range(len(noise_manifest)), num_noise_files, replace=False) - for k in selected_noise_ids: - sampled_noise_manifest.append(noise_manifest[k]) - return sampled_noise_manifest diff --git a/nemo/collections/asr/parts/utils/decoder_timestamps_utils.py b/nemo/collections/asr/parts/utils/decoder_timestamps_utils.py deleted file mode 100644 index 59e050c5f6560579da51f5a1a2f4761056267fab..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/decoder_timestamps_utils.py +++ /dev/null @@ -1,806 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import copy -import math -from typing import Dict, List, Tuple, Type, Union - -import numpy as np -import torch -from omegaconf import OmegaConf - -import nemo.collections.asr as nemo_asr -from nemo.collections.asr.metrics.wer import WER -from nemo.collections.asr.models import EncDecCTCModel, EncDecCTCModelBPE -from nemo.collections.asr.parts.preprocessing.segment import get_samples -from nemo.collections.asr.parts.submodules.ctc_decoding import ( - CTCBPEDecoding, - CTCBPEDecodingConfig, - CTCDecoding, - CTCDecodingConfig, -) -from nemo.collections.asr.parts.utils.speaker_utils import audio_rttm_map, get_uniqname_from_filepath -from nemo.collections.asr.parts.utils.streaming_utils import AudioFeatureIterator, FrameBatchASR -from nemo.collections.common.tokenizers.tokenizer_spec import TokenizerSpec -from nemo.utils import logging - -__all__ = ['ASRDecoderTimeStamps'] - -try: - from pyctcdecode import build_ctcdecoder - - PYCTCDECODE = True -except ImportError: - PYCTCDECODE = False - - -def if_none_get_default(param, default_value): - return (param, default_value)[param is None] - - -class WERBPE_TS(WER): - """ - This is WERBPE_TS class that is modified for generating word_timestamps with logits. - The functions in WER class is modified to save the word_timestamps whenever BPE token - is being saved into a list. - This class is designed to support ASR models based on CTC and BPE. - Please refer to the definition of WERBPE class for more information. - """ - - def __init__( - self, - tokenizer: TokenizerSpec, - batch_dim_index=0, - use_cer=False, - ctc_decode=None, - log_prediction=True, - dist_sync_on_step=False, - ): - if ctc_decode is not None: - logging.warning(f'`ctc_decode` was set to {ctc_decode}. Note that this is ignored.') - - decoding_cfg = CTCBPEDecodingConfig(batch_dim_index=batch_dim_index) - decoding = CTCBPEDecoding(decoding_cfg, tokenizer=tokenizer) - super().__init__(decoding, use_cer, log_prediction, dist_sync_on_step) - - def ctc_decoder_predictions_tensor_with_ts( - self, time_stride, predictions: torch.Tensor, predictions_len: torch.Tensor = None - ) -> List[str]: - hypotheses, timestamps, word_timestamps = [], [], [] - # '⁇' string should be removed since it causes error during string split. - unk = '⁇' - prediction_cpu_tensor = predictions.long().cpu() - # iterate over batch - self.time_stride = time_stride - for ind in range(prediction_cpu_tensor.shape[self.decoding.batch_dim_index]): - prediction = prediction_cpu_tensor[ind].detach().numpy().tolist() - if predictions_len is not None: - prediction = prediction[: predictions_len[ind]] - # CTC decoding procedure - decoded_prediction, char_ts, timestamp_list = [], [], [] - previous = self.decoding.blank_id - for pdx, p in enumerate(prediction): - if (p != previous or previous == self.decoding.blank_id) and p != self.decoding.blank_id: - decoded_prediction.append(p) - char_ts.append(round(pdx * self.time_stride, 2)) - timestamp_list.append(round(pdx * self.time_stride, 2)) - - previous = p - - hypothesis = self.decode_tokens_to_str_with_ts(decoded_prediction) - hypothesis = hypothesis.replace(unk, '') - word_ts, word_seq = self.get_ts_from_decoded_prediction(decoded_prediction, hypothesis, char_ts) - - hypotheses.append(" ".join(word_seq)) - timestamps.append(timestamp_list) - word_timestamps.append(word_ts) - return hypotheses, timestamps, word_timestamps - - def decode_tokens_to_str_with_ts(self, tokens: List[int]) -> str: - hypothesis = self.decoding.tokenizer.ids_to_text(tokens) - return hypothesis - - def decode_ids_to_tokens_with_ts(self, tokens: List[int]) -> List[str]: - token_list = self.decoding.tokenizer.ids_to_tokens(tokens) - return token_list - - def get_ts_from_decoded_prediction( - self, decoded_prediction: List[str], hypothesis: str, char_ts: List[str] - ) -> Tuple[List[List[float]], List[str]]: - decoded_char_list = self.decoding.tokenizer.ids_to_tokens(decoded_prediction) - stt_idx, end_idx = 0, len(decoded_char_list) - 1 - stt_ch_idx, end_ch_idx = 0, 0 - space = '▁' - word_ts, word_seq = [], [] - word_open_flag = False - for idx, ch in enumerate(decoded_char_list): - - # If the symbol is space and not an end of the utterance, move on - if idx != end_idx and (space == ch and space in decoded_char_list[idx + 1]): - continue - - # If the word does not containg space (the start of the word token), keep counting - if (idx == stt_idx or space == decoded_char_list[idx - 1] or (space in ch and len(ch) > 1)) and ( - ch != space - ): - _stt = char_ts[idx] - stt_ch_idx = idx - word_open_flag = True - - # If this char has `word_open_flag=True` and meets any of one of the following condition: - # (1) last word (2) unknown word (3) start symbol in the following word, - # close the `word_open_flag` and add the word to the `word_seq` list. - close_cond = idx == end_idx or ch in [''] or space in decoded_char_list[idx + 1] - if (word_open_flag and ch != space) and close_cond: - _end = round(char_ts[idx] + self.time_stride, 2) - end_ch_idx = idx - word_open_flag = False - word_ts.append([_stt, _end]) - stitched_word = ''.join(decoded_char_list[stt_ch_idx : end_ch_idx + 1]).replace(space, '') - word_seq.append(stitched_word) - - assert len(word_ts) == len(hypothesis.split()), "Text hypothesis does not match word timestamps." - return word_ts, word_seq - - -class WER_TS(WER): - """ - This is WER class that is modified for generating timestamps with logits. - The functions in WER class is modified to save the timestamps whenever character - is being saved into a list. - This class is designed to support ASR models based on CTC and Character-level tokens. - Please refer to the definition of WER class for more information. - """ - - def __init__( - self, - vocabulary, - batch_dim_index=0, - use_cer=False, - ctc_decode=None, - log_prediction=True, - dist_sync_on_step=False, - ): - if ctc_decode is not None: - logging.warning(f'`ctc_decode` was set to {ctc_decode}. Note that this is ignored.') - - decoding_cfg = CTCDecodingConfig(batch_dim_index=batch_dim_index) - decoding = CTCDecoding(decoding_cfg, vocabulary=vocabulary) - super().__init__(decoding, use_cer, log_prediction, dist_sync_on_step) - - def decode_tokens_to_str_with_ts(self, tokens: List[int], timestamps: List[int]) -> str: - """ - Take frame-level tokens and timestamp list and collect the timestamps for - start and end of each word. - """ - token_list, timestamp_list = self.decode_ids_to_tokens_with_ts(tokens, timestamps) - hypothesis = ''.join(self.decoding.decode_ids_to_tokens(tokens)) - return hypothesis, timestamp_list - - def decode_ids_to_tokens_with_ts(self, tokens: List[int], timestamps: List[int]) -> List[str]: - token_list, timestamp_list = [], [] - for i, c in enumerate(tokens): - if c != self.decoding.blank_id: - token_list.append(self.decoding.labels_map[c]) - timestamp_list.append(timestamps[i]) - return token_list, timestamp_list - - def ctc_decoder_predictions_tensor_with_ts( - self, - predictions: torch.Tensor, - predictions_len: torch.Tensor = None, - ) -> List[str]: - """ - A shortened version of the original function ctc_decoder_predictions_tensor(). - Replaced decode_tokens_to_str() function with decode_tokens_to_str_with_ts(). - """ - hypotheses, timestamps = [], [] - prediction_cpu_tensor = predictions.long().cpu() - for ind in range(prediction_cpu_tensor.shape[self.decoding.batch_dim_index]): - prediction = prediction_cpu_tensor[ind].detach().numpy().tolist() - if predictions_len is not None: - prediction = prediction[: predictions_len[ind]] - - # CTC decoding procedure with timestamps - decoded_prediction, decoded_timing_list = [], [] - previous = self.decoding.blank_id - for pdx, p in enumerate(prediction): - if (p != previous or previous == self.decoding.blank_id) and p != self.decoding.blank_id: - decoded_prediction.append(p) - decoded_timing_list.append(pdx) - previous = p - - text, timestamp_list = self.decode_tokens_to_str_with_ts(decoded_prediction, decoded_timing_list) - hypotheses.append(text) - timestamps.append(timestamp_list) - - return hypotheses, timestamps - - -def get_wer_feat_logit(audio_file_path, asr, frame_len, tokens_per_chunk, delay, model_stride_in_secs): - """ - Create a preprocessor to convert audio samples into raw features, - Normalization will be done per buffer in frame_bufferer. - """ - asr.reset() - asr.read_audio_file_and_return(audio_file_path, delay, model_stride_in_secs) - hyp, tokens, log_prob = asr.transcribe_with_ts(tokens_per_chunk, delay) - return hyp, tokens, log_prob - - -class FrameBatchASRLogits(FrameBatchASR): - """ - A class for streaming frame-based ASR. - Inherits from FrameBatchASR and adds new capability of returning the logit output. - Please refer to FrameBatchASR for more detailed information. - """ - - def __init__( - self, - asr_model: Type[EncDecCTCModelBPE], - frame_len: float = 1.6, - total_buffer: float = 4.0, - batch_size: int = 4, - ): - super().__init__(asr_model, frame_len, total_buffer, batch_size) - self.all_logprobs = [] - - def clear_buffer(self): - self.all_logprobs = [] - self.all_preds = [] - - def read_audio_file_and_return(self, audio_filepath: str, delay: float, model_stride_in_secs: float): - samples = get_samples(audio_filepath) - samples = np.pad(samples, (0, int(delay * model_stride_in_secs * self.asr_model._cfg.sample_rate))) - frame_reader = AudioFeatureIterator(samples, self.frame_len, self.raw_preprocessor, self.asr_model.device) - self.set_frame_reader(frame_reader) - - @torch.no_grad() - def _get_batch_preds(self, keep_logits): - device = self.asr_model.device - for batch in iter(self.data_loader): - feat_signal, feat_signal_len = batch - feat_signal, feat_signal_len = feat_signal.to(device), feat_signal_len.to(device) - log_probs, encoded_len, predictions = self.asr_model( - processed_signal=feat_signal, processed_signal_length=feat_signal_len - ) - preds = torch.unbind(predictions) - for pred in preds: - self.all_preds.append(pred.cpu().numpy()) - # Always keep logits in FrameBatchASRLogits - _ = keep_logits - log_probs_tup = torch.unbind(log_probs) - for log_prob in log_probs_tup: - self.all_logprobs.append(log_prob) - del log_probs, log_probs_tup - del encoded_len - del predictions - - def transcribe_with_ts( - self, - tokens_per_chunk: int, - delay: int, - ): - self.infer_logits() - self.unmerged = [] - self.part_logprobs = [] - for idx, pred in enumerate(self.all_preds): - decoded = pred.tolist() - _stt, _end = len(decoded) - 1 - delay, len(decoded) - 1 - delay + tokens_per_chunk - self.unmerged += decoded[len(decoded) - 1 - delay : len(decoded) - 1 - delay + tokens_per_chunk] - self.part_logprobs.append(self.all_logprobs[idx][_stt:_end, :]) - self.unmerged_logprobs = torch.cat(self.part_logprobs, 0) - assert ( - len(self.unmerged) == self.unmerged_logprobs.shape[0] - ), "Unmerged decoded result and log prob lengths are different." - return self.greedy_merge(self.unmerged), self.unmerged, self.unmerged_logprobs - - -class ASRDecoderTimeStamps: - """ - A class designed for extracting word timestamps while the ASR decoding process. - This class contains a few setups for a slew of NeMo ASR models such as QuartzNet, CitriNet and ConformerCTC models. - """ - - def __init__(self, cfg_diarizer): - self.manifest_filepath = cfg_diarizer.manifest_filepath - self.params = cfg_diarizer.asr.parameters - self.ctc_decoder_params = cfg_diarizer.asr.ctc_decoder_parameters - self.ASR_model_name = cfg_diarizer.asr.model_path - self.nonspeech_threshold = self.params.asr_based_vad_threshold - self.root_path = None - self.run_ASR = None - self.encdec_class = None - self.AUDIO_RTTM_MAP = audio_rttm_map(self.manifest_filepath) - self.audio_file_list = [value['audio_filepath'] for _, value in self.AUDIO_RTTM_MAP.items()] - - def set_asr_model(self): - """ - Initialize the parameters for the given ASR model. - Currently, the following NGC models are supported: - - stt_en_quartznet15x5, - stt_en_citrinet*, - stt_en_conformer_ctc* - - To assign a proper decoding function for generating timestamp output, - the name of .nemo file should include the architecture name such as: - 'quartznet', 'conformer', and 'citrinet'. - - decoder_delay_in_sec is the amount of delay that is compensated during the word timestamp extraction. - word_ts_anchor_offset is the reference point for a word and used for matching the word with diarization labels. - Each ASR model has a different optimal decoder delay and word timestamp anchor offset. - To obtain an optimized diarization result with ASR, decoder_delay_in_sec and word_ts_anchor_offset - need to be searched on a development set. - """ - if 'quartznet' in self.ASR_model_name.lower(): - self.run_ASR = self.run_ASR_QuartzNet_CTC - self.encdec_class = EncDecCTCModel - self.decoder_delay_in_sec = if_none_get_default(self.params['decoder_delay_in_sec'], 0.04) - self.word_ts_anchor_offset = if_none_get_default(self.params['word_ts_anchor_offset'], 0.12) - self.asr_batch_size = if_none_get_default(self.params['asr_batch_size'], 4) - self.model_stride_in_secs = 0.02 - - elif 'fastconformer' in self.ASR_model_name.lower(): - self.run_ASR = self.run_ASR_BPE_CTC - self.encdec_class = EncDecCTCModelBPE - self.decoder_delay_in_sec = if_none_get_default(self.params['decoder_delay_in_sec'], 0.08) - self.word_ts_anchor_offset = if_none_get_default(self.params['word_ts_anchor_offset'], 0.12) - self.asr_batch_size = if_none_get_default(self.params['asr_batch_size'], 16) - self.model_stride_in_secs = 0.08 - # FastConformer requires buffered inference and the parameters for buffered processing. - self.chunk_len_in_sec = 15 - self.total_buffer_in_secs = 30 - - elif 'conformer' in self.ASR_model_name.lower(): - self.run_ASR = self.run_ASR_BPE_CTC - self.encdec_class = EncDecCTCModelBPE - self.decoder_delay_in_sec = if_none_get_default(self.params['decoder_delay_in_sec'], 0.08) - self.word_ts_anchor_offset = if_none_get_default(self.params['word_ts_anchor_offset'], 0.12) - self.asr_batch_size = if_none_get_default(self.params['asr_batch_size'], 16) - self.model_stride_in_secs = 0.04 - # Conformer requires buffered inference and the parameters for buffered processing. - self.chunk_len_in_sec = 5 - self.total_buffer_in_secs = 25 - - elif 'citrinet' in self.ASR_model_name.lower(): - self.run_ASR = self.run_ASR_CitriNet_CTC - self.encdec_class = EncDecCTCModelBPE - self.decoder_delay_in_sec = if_none_get_default(self.params['decoder_delay_in_sec'], 0.16) - self.word_ts_anchor_offset = if_none_get_default(self.params['word_ts_anchor_offset'], 0.2) - self.asr_batch_size = if_none_get_default(self.params['asr_batch_size'], 4) - self.model_stride_in_secs = 0.08 - - else: - raise ValueError(f"Cannot find the ASR model class for: {self.params['self.ASR_model_name']}") - - if self.ASR_model_name.endswith('.nemo'): - asr_model = self.encdec_class.restore_from(restore_path=self.ASR_model_name) - else: - asr_model = self.encdec_class.from_pretrained(model_name=self.ASR_model_name, strict=False) - - if self.ctc_decoder_params['pretrained_language_model']: - if not PYCTCDECODE: - raise ImportError( - 'LM for beam search decoding is provided but pyctcdecode is not installed. Install pyctcdecode using PyPI: pip install pyctcdecode' - ) - self.beam_search_decoder = self.load_LM_for_CTC_decoder(asr_model) - else: - self.beam_search_decoder = None - - asr_model.eval() - return asr_model - - def load_LM_for_CTC_decoder(self, asr_model: Type[Union[EncDecCTCModel, EncDecCTCModelBPE]]): - """ - Load a language model for CTC decoder (pyctcdecode). - Note that only EncDecCTCModel and EncDecCTCModelBPE models can use pyctcdecode. - """ - kenlm_model = self.ctc_decoder_params['pretrained_language_model'] - logging.info(f"Loading language model : {self.ctc_decoder_params['pretrained_language_model']}") - - if 'EncDecCTCModelBPE' in str(type(asr_model)): - vocab = asr_model.tokenizer.tokenizer.get_vocab() - labels = list(vocab.keys()) - labels[0] = "" - elif 'EncDecCTCModel' in str(type(asr_model)): - labels = asr_model.decoder.vocabulary - else: - raise ValueError(f"Cannot find a vocabulary or tokenizer for: {self.params['self.ASR_model_name']}") - - decoder = build_ctcdecoder( - labels, kenlm_model, alpha=self.ctc_decoder_params['alpha'], beta=self.ctc_decoder_params['beta'] - ) - return decoder - - def run_ASR_QuartzNet_CTC(self, asr_model: Type[EncDecCTCModel]) -> Tuple[Dict, Dict]: - """ - Launch QuartzNet ASR model and collect logit, timestamps and text output. - - Args: - asr_model (class): - The loaded NeMo ASR model. - - Returns: - words_dict (dict): - Dictionary containing the sequence of words from hypothesis. - word_ts_dict (dict): - Dictionary containing the time-stamps of words. - """ - words_dict, word_ts_dict = {}, {} - - wer_ts = WER_TS( - vocabulary=asr_model.decoder.vocabulary, - batch_dim_index=0, - use_cer=asr_model._cfg.get('use_cer', False), - ctc_decode=True, - dist_sync_on_step=True, - log_prediction=asr_model._cfg.get("log_prediction", False), - ) - - with torch.amp.autocast(asr_model.device.type): - transcript_hyps_list = asr_model.transcribe( - self.audio_file_list, batch_size=self.asr_batch_size, return_hypotheses=True - ) # type: List[nemo_asr.parts.Hypothesis] - transcript_logits_list = [hyp.alignments for hyp in transcript_hyps_list] - for idx, logit_np in enumerate(transcript_logits_list): - logit_np = logit_np.cpu().numpy() - uniq_id = get_uniqname_from_filepath(self.audio_file_list[idx]) - if self.beam_search_decoder: - logging.info( - f"Running beam-search decoder on {uniq_id} with LM {self.ctc_decoder_params['pretrained_language_model']}" - ) - hyp_words, word_ts = self.run_pyctcdecode(logit_np) - else: - log_prob = torch.from_numpy(logit_np) - logits_len = torch.from_numpy(np.array([log_prob.shape[0]])) - greedy_predictions = log_prob.argmax(dim=-1, keepdim=False).unsqueeze(0) - text, char_ts = wer_ts.ctc_decoder_predictions_tensor_with_ts( - greedy_predictions, predictions_len=logits_len - ) - trans, char_ts_in_feature_frame_idx = self.clean_trans_and_TS(text[0], char_ts[0]) - spaces_in_sec, hyp_words = self._get_spaces( - trans, char_ts_in_feature_frame_idx, self.model_stride_in_secs - ) - word_ts = self.get_word_ts_from_spaces( - char_ts_in_feature_frame_idx, spaces_in_sec, end_stamp=logit_np.shape[0] - ) - word_ts = self.align_decoder_delay(word_ts, self.decoder_delay_in_sec) - assert len(hyp_words) == len(word_ts), "Words and word timestamp list length does not match." - words_dict[uniq_id] = hyp_words - word_ts_dict[uniq_id] = word_ts - - return words_dict, word_ts_dict - - @staticmethod - def clean_trans_and_TS(trans: str, char_ts: List[str]) -> Tuple[str, List[str]]: - """ - Remove the spaces in the beginning and the end. - The char_ts need to be changed and synced accordingly. - - Args: - trans (list): - List containing the character output (str). - char_ts (list): - List containing the timestamps (int) for each character. - - Returns: - trans (list): - List containing the cleaned character output. - char_ts (list): - List containing the cleaned timestamps for each character. - """ - assert (len(trans) > 0) and (len(char_ts) > 0) - assert len(trans) == len(char_ts) - - trans = trans.lstrip() - diff_L = len(char_ts) - len(trans) - char_ts = char_ts[diff_L:] - - trans = trans.rstrip() - diff_R = len(char_ts) - len(trans) - if diff_R > 0: - char_ts = char_ts[: -1 * diff_R] - return trans, char_ts - - def _get_spaces(self, trans: str, char_ts: List[str], time_stride: float) -> Tuple[float, List[str]]: - """ - Collect the space symbols with a list of words. - - Args: - trans (list): - List containing the character output (str). - char_ts (list): - List containing the timestamps of the characters. - time_stride (float): - The size of stride of the model in second. - - Returns: - spaces_in_sec (list): - List containing the ranges of spaces - word_list (list): - List containing the words from ASR inference. - """ - blank = ' ' - spaces_in_sec, word_list = [], [] - stt_idx = 0 - assert (len(trans) > 0) and (len(char_ts) > 0), "Transcript and char_ts length should not be 0." - assert len(trans) == len(char_ts), "Transcript and timestamp lengths do not match." - - # If there is a blank, update the time stamps of the space and the word. - for k, s in enumerate(trans): - if s == blank: - spaces_in_sec.append( - [round(char_ts[k] * time_stride, 2), round((char_ts[k + 1] - 1) * time_stride, 2)] - ) - word_list.append(trans[stt_idx:k]) - stt_idx = k + 1 - - # Add the last word - if len(trans) > stt_idx and trans[stt_idx] != blank: - word_list.append(trans[stt_idx:]) - return spaces_in_sec, word_list - - def run_ASR_CitriNet_CTC(self, asr_model: Type[EncDecCTCModelBPE]) -> Tuple[Dict, Dict]: - """ - Launch CitriNet ASR model and collect logit, timestamps and text output. - - Args: - asr_model (class): - The loaded NeMo ASR model. - - Returns: - words_dict (dict): - Dictionary containing the sequence of words from hypothesis. - word_ts_dict (dict): - Dictionary containing the timestamps of hypothesis words. - """ - words_dict, word_ts_dict = {}, {} - - werbpe_ts = WERBPE_TS( - tokenizer=asr_model.tokenizer, - batch_dim_index=0, - use_cer=asr_model._cfg.get('use_cer', False), - ctc_decode=True, - dist_sync_on_step=True, - log_prediction=asr_model._cfg.get("log_prediction", False), - ) - - with torch.amp.autocast(asr_model.device.type): - transcript_hyps_list = asr_model.transcribe( - self.audio_file_list, batch_size=self.asr_batch_size, return_hypotheses=True - ) # type: List[nemo_asr.parts.Hypothesis] - transcript_logits_list = [hyp.alignments for hyp in transcript_hyps_list] - for idx, logit_np in enumerate(transcript_logits_list): - log_prob = logit_np.cpu().numpy() - uniq_id = get_uniqname_from_filepath(self.audio_file_list[idx]) - if self.beam_search_decoder: - logging.info( - f"Running beam-search decoder with LM {self.ctc_decoder_params['pretrained_language_model']}" - ) - hyp_words, word_ts = self.run_pyctcdecode(logit_np) - else: - log_prob = torch.from_numpy(logit_np) - greedy_predictions = log_prob.argmax(dim=-1, keepdim=False).unsqueeze(0) - logits_len = torch.from_numpy(np.array([log_prob.shape[0]])) - text, char_ts, word_ts = werbpe_ts.ctc_decoder_predictions_tensor_with_ts( - self.model_stride_in_secs, greedy_predictions, predictions_len=logits_len - ) - hyp_words, word_ts = text[0].split(), word_ts[0] - word_ts = self.align_decoder_delay(word_ts, self.decoder_delay_in_sec) - assert len(hyp_words) == len(word_ts), "Words and word timestamp list length does not match." - words_dict[uniq_id] = hyp_words - word_ts_dict[uniq_id] = word_ts - - return words_dict, word_ts_dict - - def set_buffered_infer_params(self, asr_model: Type[EncDecCTCModelBPE]) -> Tuple[float, float, float]: - """ - Prepare the parameters for the buffered inference. - """ - cfg = copy.deepcopy(asr_model._cfg) - OmegaConf.set_struct(cfg.preprocessor, False) - - # some changes for streaming scenario - cfg.preprocessor.dither = 0.0 - cfg.preprocessor.pad_to = 0 - cfg.preprocessor.normalize = "None" - - preprocessor = nemo_asr.models.EncDecCTCModelBPE.from_config_dict(cfg.preprocessor) - preprocessor.to(asr_model.device) - - # Disable config overwriting - OmegaConf.set_struct(cfg.preprocessor, True) - - onset_delay = ( - math.ceil(((self.total_buffer_in_secs - self.chunk_len_in_sec) / 2) / self.model_stride_in_secs) + 1 - ) - mid_delay = math.ceil( - (self.chunk_len_in_sec + (self.total_buffer_in_secs - self.chunk_len_in_sec) / 2) - / self.model_stride_in_secs - ) - tokens_per_chunk = math.ceil(self.chunk_len_in_sec / self.model_stride_in_secs) - - return onset_delay, mid_delay, tokens_per_chunk - - def run_ASR_BPE_CTC(self, asr_model: Type[EncDecCTCModelBPE]) -> Tuple[Dict, Dict]: - """ - Launch CTC-BPE based ASR model and collect logit, timestamps and text output. - - Args: - asr_model (class): - The loaded NeMo ASR model. - - Returns: - words_dict (dict): - Dictionary containing the sequence of words from hypothesis. - word_ts_dict (dict): - Dictionary containing the time-stamps of words. - """ - torch.manual_seed(0) - torch.set_grad_enabled(False) - words_dict, word_ts_dict = {}, {} - - werbpe_ts = WERBPE_TS( - tokenizer=asr_model.tokenizer, - batch_dim_index=0, - use_cer=asr_model._cfg.get('use_cer', False), - ctc_decode=True, - dist_sync_on_step=True, - log_prediction=asr_model._cfg.get("log_prediction", False), - ) - - frame_asr = FrameBatchASRLogits( - asr_model=asr_model, - frame_len=self.chunk_len_in_sec, - total_buffer=self.total_buffer_in_secs, - batch_size=self.asr_batch_size, - ) - - onset_delay, mid_delay, tokens_per_chunk = self.set_buffered_infer_params(asr_model) - onset_delay_in_sec = round(onset_delay * self.model_stride_in_secs, 2) - - with torch.amp.autocast(asr_model.device.type): - logging.info(f"Running ASR model {self.ASR_model_name}") - - for idx, audio_file_path in enumerate(self.audio_file_list): - uniq_id = get_uniqname_from_filepath(audio_file_path) - logging.info(f"[{idx+1}/{len(self.audio_file_list)}] FrameBatchASR: {audio_file_path}") - frame_asr.clear_buffer() - - hyp, greedy_predictions_list, log_prob = get_wer_feat_logit( - audio_file_path, - frame_asr, - self.chunk_len_in_sec, - tokens_per_chunk, - mid_delay, - self.model_stride_in_secs, - ) - if self.beam_search_decoder: - logging.info( - f"Running beam-search decoder with LM {self.ctc_decoder_params['pretrained_language_model']}" - ) - log_prob = log_prob.unsqueeze(0).cpu().numpy()[0] - hyp_words, word_ts = self.run_pyctcdecode(log_prob, onset_delay_in_sec=onset_delay_in_sec) - else: - logits_len = torch.from_numpy(np.array([len(greedy_predictions_list)])) - greedy_predictions_list = greedy_predictions_list[onset_delay:] - greedy_predictions = torch.from_numpy(np.array(greedy_predictions_list)).unsqueeze(0) - text, char_ts, word_ts = werbpe_ts.ctc_decoder_predictions_tensor_with_ts( - self.model_stride_in_secs, greedy_predictions, predictions_len=logits_len - ) - hyp_words, word_ts = text[0].split(), word_ts[0] - - word_ts = self.align_decoder_delay(word_ts, self.decoder_delay_in_sec) - assert len(hyp_words) == len(word_ts), "Words and word timestamp list length does not match." - words_dict[uniq_id] = hyp_words - word_ts_dict[uniq_id] = word_ts - - return words_dict, word_ts_dict - - def get_word_ts_from_spaces(self, char_ts: List[float], spaces_in_sec: List[float], end_stamp: float) -> List[str]: - """ - Take word timestamps from the spaces from the decoded prediction. - - Args: - char_ts (list): - List containing the timestamp for each character. - spaces_in_sec (list): - List containing the start and the end time of each space token. - end_stamp (float): - The end time of the session in sec. - - Returns: - word_timestamps (list): - List containing the timestamps for the resulting words. - """ - end_stamp = min(end_stamp, (char_ts[-1] + 2)) - start_stamp_in_sec = round(char_ts[0] * self.model_stride_in_secs, 2) - end_stamp_in_sec = round(end_stamp * self.model_stride_in_secs, 2) - - # In case of one word output with no space information. - if len(spaces_in_sec) == 0: - word_timestamps = [[start_stamp_in_sec, end_stamp_in_sec]] - elif len(spaces_in_sec) > 0: - # word_timetamps_middle should be an empty list if len(spaces_in_sec) == 1. - word_timetamps_middle = [ - [ - round(spaces_in_sec[k][1], 2), - round(spaces_in_sec[k + 1][0], 2), - ] - for k in range(len(spaces_in_sec) - 1) - ] - word_timestamps = ( - [[start_stamp_in_sec, round(spaces_in_sec[0][0], 2)]] - + word_timetamps_middle - + [[round(spaces_in_sec[-1][1], 2), end_stamp_in_sec]] - ) - return word_timestamps - - def run_pyctcdecode( - self, logprob: np.ndarray, onset_delay_in_sec: float = 0, beam_width: int = 32 - ) -> Tuple[List[str], List[str]]: - """ - Launch pyctcdecode with the loaded pretrained language model. - - Args: - logprob (np.ndarray): - The log probability from the ASR model inference in numpy array format. - onset_delay_in_sec (float): - The amount of delay that needs to be compensated for the timestamp outputs froM pyctcdecode. - beam_width (int): - The beam width parameter for beam search decodring. - Returns: - hyp_words (list): - List containing the words in the hypothesis. - word_ts (list): - List containing the word timestamps from the decoder. - """ - beams = self.beam_search_decoder.decode_beams(logprob, beam_width=self.ctc_decoder_params['beam_width']) - word_ts_beam, words_beam = [], [] - for idx, (word, _) in enumerate(beams[0][2]): - ts = self.get_word_ts_from_wordframes(idx, beams[0][2], self.model_stride_in_secs, onset_delay_in_sec) - word_ts_beam.append(ts) - words_beam.append(word) - hyp_words, word_ts = words_beam, word_ts_beam - return hyp_words, word_ts - - @staticmethod - def get_word_ts_from_wordframes( - idx, word_frames: List[List[float]], frame_duration: float, onset_delay: float, word_block_delay: float = 2.25 - ): - """ - Extract word timestamps from word frames generated from pyctcdecode. - """ - offset = -1 * word_block_delay * frame_duration - onset_delay - frame_begin = word_frames[idx][1][0] - if frame_begin == -1: - frame_begin = word_frames[idx - 1][1][1] if idx != 0 else 0 - frame_end = word_frames[idx][1][1] - return [ - round(max(frame_begin * frame_duration + offset, 0), 2), - round(max(frame_end * frame_duration + offset, 0), 2), - ] - - @staticmethod - def align_decoder_delay(word_ts, decoder_delay_in_sec: float): - """ - Subtract decoder_delay_in_sec from the word timestamp output. - """ - for k in range(len(word_ts)): - word_ts[k] = [ - round(word_ts[k][0] - decoder_delay_in_sec, 2), - round(word_ts[k][1] - decoder_delay_in_sec, 2), - ] - return word_ts diff --git a/nemo/collections/asr/parts/utils/diarization_utils.py b/nemo/collections/asr/parts/utils/diarization_utils.py deleted file mode 100644 index a99f86d6a634709d45a05ea6a828412e4ec852bb..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/diarization_utils.py +++ /dev/null @@ -1,1626 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import copy -import csv -import json -import os -import string -from collections import OrderedDict as od -from collections import defaultdict -from datetime import datetime -from typing import Dict, List, Optional, Tuple - -import numpy as np -from pyannote.metrics.diarization import DiarizationErrorRate - -from nemo.collections.asr.metrics.der import calculate_session_cpWER, concat_perm_word_error_rate -from nemo.collections.asr.metrics.wer import word_error_rate -from nemo.collections.asr.models import ClusteringDiarizer -from nemo.collections.asr.parts.utils.speaker_utils import ( - audio_rttm_map, - get_uniqname_from_filepath, - labels_to_rttmfile, - rttm_to_labels, - write_rttm2manifest, -) -from nemo.utils import logging - -try: - import arpa - - ARPA = True -except ImportError: - ARPA = False - -__all__ = ['OfflineDiarWithASR'] - - -def get_color_palette() -> Dict[str, str]: - return { - 'speaker_0': '\033[1;32m', - 'speaker_1': '\033[1;34m', - 'speaker_2': '\033[1;36m', - 'speaker_3': '\033[1;31m', - 'speaker_4': '\033[1;35m', - 'speaker_5': '\033[1;30m', - 'speaker_6': '\033[1;37m', - 'speaker_7': '\033[1;30m', - 'speaker_8': '\033[1;33m', - 'speaker_9': '\033[0;34m', - 'white': '\033[0;37m', - 'black': '\033[0;30m', - } - - -def dump_json_to_file(file_path: str, session_trans_dict: dict): - """ - Write a json file from the session_trans_dict dictionary. - - Args: - file_path (str): - Target filepath where json file is saved - session_trans_dict (dict): - Dictionary containing transcript, speaker labels and timestamps - """ - with open(file_path, "w") as outfile: - json.dump(session_trans_dict, outfile, indent=4) - - -def write_txt(w_path: str, val: str): - """ - Write a text file from the string input. - - Args: - w_path (str): - Target path for saving a file - val (str): - String variable to be written - """ - with open(w_path, "w") as output: - output.write(val + '\n') - - -def init_session_trans_dict(uniq_id: str, n_spk: int): - """ - Initialize json (in dictionary variable) formats for session level result and Gecko style json. - - Returns: - (dict): Session level result dictionary variable - """ - return od( - { - 'status': 'initialized', - 'session_id': uniq_id, - 'transcription': '', - 'speaker_count': n_spk, - 'words': [], - 'sentences': [], - } - ) - - -def init_session_gecko_dict(): - """ - Initialize a dictionary format for Gecko style json. - - Returns: - (dict): - Gecko style json dictionary. - """ - return od({'schemaVersion': 2.0, 'monologues': []}) - - -def convert_ctm_to_text(ctm_file_path: str) -> Tuple[List[str], str]: - """ - Convert ctm file into a list containing transcription (space seperated string) per each speaker. - - Args: - ctm_file_path (str): - Filepath to the reference CTM files. - - Returns: - spk_reference (list): - List containing the reference transcripts for each speaker. - - Example: - >>> spk_reference = ["hi how are you well that's nice", "i'm good yeah how is your sister"] - - mix_reference (str): - Reference transcript from CTM file. This transcript has word sequence in temporal order. - - Example: - >>> mix_reference = "hi how are you i'm good well that's nice yeah how is your sister" - """ - mix_reference, per_spk_ref_trans_dict = [], {} - ctm_content = open(ctm_file_path).readlines() - for ctm_line in ctm_content: - ctm_split = ctm_line.split() - spk = ctm_split[1] - if spk not in per_spk_ref_trans_dict: - per_spk_ref_trans_dict[spk] = [] - per_spk_ref_trans_dict[spk].append(ctm_split[4]) - mix_reference.append(ctm_split[4]) - spk_reference = [" ".join(word_list) for word_list in per_spk_ref_trans_dict.values()] - mix_reference = " ".join(mix_reference) - return spk_reference, mix_reference - - -def convert_word_dict_seq_to_text(word_dict_seq_list: List[Dict[str, float]]) -> Tuple[List[str], str]: - """ - Convert word_dict_seq_list into a list containing transcription (space seperated string) per each speaker. - - Args: - word_dict_seq_list (list): - List containing words and corresponding word timestamps in dictionary format. - - Example: - >>> word_dict_seq_list = \ - >>> [{'word': 'right', 'start_time': 0.0, 'end_time': 0.04, 'speaker': 'speaker_0'}, - {'word': 'and', 'start_time': 0.64, 'end_time': 0.68, 'speaker': 'speaker_1'}, - ...], - - Returns: - spk_hypothesis (list): - Dictionary containing the hypothesis transcript for each speaker. A list containing the sequence - of words is assigned for each speaker. - - Example: - >>> spk_hypothesis= ["hi how are you well that's nice", "i'm good yeah how is your sister"] - - mix_hypothesis (str): - Hypothesis transcript from ASR output. This transcript has word sequence in temporal order. - - Example: - >>> mix_hypothesis = "hi how are you i'm good well that's nice yeah how is your sister" - """ - mix_hypothesis, per_spk_hyp_trans_dict = [], {} - for word_dict in word_dict_seq_list: - spk = word_dict['speaker'] - if spk not in per_spk_hyp_trans_dict: - per_spk_hyp_trans_dict[spk] = [] - per_spk_hyp_trans_dict[spk].append(word_dict['word']) - mix_hypothesis.append(word_dict['word']) - - # Create a list containing string formatted transcript - spk_hypothesis = [" ".join(word_list) for word_list in per_spk_hyp_trans_dict.values()] - mix_hypothesis = " ".join(mix_hypothesis) - return spk_hypothesis, mix_hypothesis - - -def convert_word_dict_seq_to_ctm( - word_dict_seq_list: List[Dict[str, float]], uniq_id: str = 'null', decimals: int = 3 -) -> Tuple[List[str], str]: - """ - Convert word_dict_seq_list into a list containing transcription in CTM format. - - Args: - word_dict_seq_list (list): - List containing words and corresponding word timestamps in dictionary format. - - Example: - >>> word_dict_seq_list = \ - >>> [{'word': 'right', 'start_time': 0.0, 'end_time': 0.34, 'speaker': 'speaker_0'}, - {'word': 'and', 'start_time': 0.64, 'end_time': 0.81, 'speaker': 'speaker_1'}, - ...], - - Returns: - ctm_lines_list (list): - List containing the hypothesis transcript in CTM format. - - Example: - >>> ctm_lines_list= ["my_audio_01 speaker_0 0.0 0.34 right 0", - my_audio_01 speaker_0 0.64 0.81 and 0", - - - """ - ctm_lines = [] - confidence = 0 - for word_dict in word_dict_seq_list: - spk = word_dict['speaker'] - stt = word_dict['start_time'] - dur = round(word_dict['end_time'] - word_dict['start_time'], decimals) - word = word_dict['word'] - ctm_line_str = f"{uniq_id} {spk} {stt} {dur} {word} {confidence}" - ctm_lines.append(ctm_line_str) - return ctm_lines - - -def get_total_result_dict( - der_results: Dict[str, Dict[str, float]], - wer_results: Dict[str, Dict[str, float]], - csv_columns: List[str], -): - """ - Merge WER results and DER results into a single dictionary variable. - - Args: - der_results (dict): - Dictionary containing FA, MISS, CER and DER values for both aggregated amount and - each session. - wer_results (dict): - Dictionary containing session-by-session WER and cpWER. `wer_results` only - exists when CTM files are provided. - - Returns: - total_result_dict (dict): - Dictionary containing both DER and WER results. This dictionary contains unique-IDs of - each session and `total` key that includes average (cp)WER and DER/CER/Miss/FA values. - """ - total_result_dict = {} - for uniq_id in der_results.keys(): - if uniq_id == 'total': - continue - total_result_dict[uniq_id] = {x: "-" for x in csv_columns} - total_result_dict[uniq_id]["uniq_id"] = uniq_id - if uniq_id in der_results: - total_result_dict[uniq_id].update(der_results[uniq_id]) - if uniq_id in wer_results: - total_result_dict[uniq_id].update(wer_results[uniq_id]) - total_result_jsons = list(total_result_dict.values()) - return total_result_jsons - - -def get_audacity_label(word: str, stt_sec: float, end_sec: float, speaker: str) -> str: - """ - Get a string formatted line for Audacity label. - - Args: - word (str): - A decoded word - stt_sec (float): - Start timestamp of the word - end_sec (float): - End timestamp of the word - - Returns: - speaker (str): - Speaker label in string type - """ - spk = speaker.split('_')[-1] - return f'{stt_sec}\t{end_sec}\t[{spk}] {word}' - - -def get_num_of_spk_from_labels(labels: List[str]) -> int: - """ - Count the number of speakers in a segment label list. - Args: - labels (list): - List containing segment start and end timestamp and speaker labels. - - Example: - >>> labels = ["15.25 21.82 speaker_0", "21.18 29.51 speaker_1", ... ] - - Returns: - n_spk (int): - The number of speakers in the list `labels` - - """ - spk_set = [x.split(' ')[-1].strip() for x in labels] - return len(set(spk_set)) - - -def convert_seglst(seglst, all_speakers): - ''' - convert the seglst to a format that can be used for scoring - - Args: - seglst (list): list of seglst dictionaries - all_speakers (list): list of all active speakers - Returns: - timestamps: (list of list) - [ - [[st1, et1], [st2, et2]], # timestamps list for speaker 1 - [[st1, et1], ...], # timestamps list for speaker 2 - ...] - words (list[[s1], [s2], [s3], [s4]]): list of words for each speaker 1 to 4 - ''' - - timestamps = [[] for _ in all_speakers] - words = ['' for _ in all_speakers] - - spk2id = {spk: idx for idx, spk in enumerate(all_speakers)} - seglst = sorted(seglst, key=lambda x: (x['start_time'], x['end_time'])) - for seg in seglst: - timestamps[spk2id[seg['speaker']]].append((seg['start_time'], seg['end_time'])) - words[spk2id[seg['speaker']]] += seg['words'] + ' ' - - return timestamps, words - - -def get_session_trans_dict(uniq_id: str, word_dict_seq_list: List[Dict[str, float]], diar_labels: List[str]): - """ - Get the session transcription dictionary. - - Args: - uniq_id (str): the unique id of the session - word_dict_seq_list (list): list of word dictionaries - diar_labels (list): list of diarization labels - - Returns: - session_trans_dict (dict): the session transcription dictionary - gecko_dict (dict): the gecko dictionary - audacity_label_words (list): the audacity label words - sentences (list): the sentences - """ - n_spk = get_num_of_spk_from_labels(diar_labels) - session_trans_dict = init_session_trans_dict(uniq_id=uniq_id, n_spk=n_spk) - gecko_dict = init_session_gecko_dict() - word_seq_list, audacity_label_words = [], [] - start_point, end_point, speaker = diar_labels[0].split() - prev_speaker = speaker - - sentences, terms_list = [], [] - sentence = {'speaker': speaker, 'start_time': start_point, 'end_time': end_point, 'text': ''} - - for k, word_dict in enumerate(word_dict_seq_list): - word, speaker = word_dict['word'], word_dict['speaker'] - word_seq_list.append(word) - start_point, end_point = word_dict['start_time'], word_dict['end_time'] - if speaker != prev_speaker: - if len(terms_list) != 0: - gecko_dict['monologues'].append({'speaker': {'name': None, 'id': prev_speaker}, 'terms': terms_list}) - terms_list = [] - - # remove trailing space in text - sentence['text'] = sentence['text'].strip() - - # store last sentence - sentences.append(sentence) - - # start construction of a new sentence - sentence = {'speaker': speaker, 'start_time': start_point, 'end_time': end_point, 'text': ''} - else: - # correct the ending time - sentence['end_time'] = end_point - - stt_sec, end_sec = start_point, end_point - terms_list.append({'start': stt_sec, 'end': end_sec, 'text': word, 'type': 'WORD'}) - - # add current word to sentence - sentence['text'] += word.strip() + ' ' - - audacity_label_words.append(get_audacity_label(word, stt_sec, end_sec, speaker)) - prev_speaker = speaker - - session_trans_dict['words'] = word_dict_seq_list - - # note that we need to add the very last sentence. - sentence['text'] = sentence['text'].strip() - sentences.append(sentence) - - # Speaker independent transcription - session_trans_dict['transcription'] = ' '.join(word_seq_list) - # add sentences to transcription information dict - session_trans_dict['sentences'] = sentences - gecko_dict['monologues'].append({'speaker': {'name': None, 'id': speaker}, 'terms': terms_list}) - return session_trans_dict, gecko_dict, audacity_label_words, sentences - - -def print_sentences(sentences: List[Dict[str, float]], color_palette: Dict[str, str], params: Dict[str, bool]) -> None: - """ - Print a transcript with speaker labels and timestamps. - - Args: - sentences (list): - List containing sentence-level dictionaries. - - Returns: - string_out (str): - String variable containing transcript and the corresponding speaker label. - """ - # init output - string_out = '' - # time_color = color_palette.get('black', '\033[0;30m') - time_color = color_palette.get('white', '\033[0;30m') - - for sentence in sentences: - # extract info - speaker = sentence['speaker'] - start_point = sentence['start_time'] - end_point = sentence['end_time'] - if 'text' in sentence: - text = sentence['text'] - elif 'words' in sentence: - text = sentence['words'] - else: - raise ValueError(f"text or words not in sentence: {sentence}") - - if params.get('colored_text', False): - color = color_palette.get(speaker, '\033[0;37m') - else: - color = '' - - # cast timestamp to the correct format - datetime_offset = 16 * 3600 - if float(start_point) > 3600: - time_str = '%H:%M:%S.%f' - else: - time_str = '%M:%S.%f' - start_point, end_point = max(float(start_point), 0), max(float(end_point), 0) - start_point_str = datetime.fromtimestamp(start_point - datetime_offset).strftime(time_str)[:-4] - end_point_str = datetime.fromtimestamp(end_point - datetime_offset).strftime(time_str)[:-4] - - if params.get('print_time', False): - time_str = f'[{start_point_str}-{end_point_str}] ' - else: - time_str = '' - - # string out concatenation - speaker = speaker.replace("speaker_", "[ Speaker-") + " ]" - string_out += f'{time_color}{time_str}{color}{speaker} {text}\n' - - return string_out - - -def read_seglst(seglst_filepath, round_digits=3, return_rttm=False, sort_by_start_time=False, sort_by_end_time=False): - """ - Read a seglst file and return the speaker & text information dictionary. - - Args: - seglst_filepath: path to the seglst file - seglst format: - [ - { - "session_id": "Bed008", - "words": "alright so i'm i should read all of these numbers", - "speaker": "me045", - "start_time": "53.814", - "end_time": "56.753" - } - ] - round_digits (int): number of digits to round the timestamps - return_rttm (bool): Whether to return RTTM lines - - Returns: - seglst_dict (dict): - A dictionary containing speaker and text information for each segment. - rttm_lines (list): - A list containing RTTM lines. - """ - rttm_lines = [] - seglst = [] - with open(seglst_filepath, 'r') as f: - seglst_lines = json.loads(f.read()) - - for idx, line in enumerate(seglst_lines): - spk, start, end = line['speaker'], float(line['start_time']), float(line['end_time']) - dur = round(end - start, round_digits) - - if return_rttm: - rttm_line_str = f'SPEAKER {line["session_id"]} 1 {start:.3f} {end-start:.3f} {spk} ' - rttm_lines.append(rttm_line_str) - seglst.append( - { - 'session_id': line['session_id'], - 'speaker': spk, - 'words': line['words'], - 'start_time': start, - 'end_time': end, - 'duration': dur, - } - ) - if sort_by_start_time and sort_by_end_time: - raise ValueError("Cannot sort by both start and end time") - if sort_by_start_time: - seglst = sorted(seglst, key=lambda x: (x['start_time'], x['end_time'])) - if sort_by_end_time: - seglst = sorted(seglst, key=lambda x: (x['end_time'], x['start_time'])) - if return_rttm: - return seglst, rttm_lines - return seglst - - -def chunk_seglst(seglst: List[Dict], chunk_size: float = 10.0): - ''' - Get chunked timestamps and words for each speaker - - Args: - seglst (list): list of seglst dictionaries - chunk_size (float): chunk size in seconds - - Returns: - chunk_id2timestamps (dict): dictionary of chunk_id to list of timestamps - speakers (set): set of all speakers - session_id (str): session id - ''' - chunk_id2timestamps = defaultdict(list) - speakers = set() - session_ids = set() - - for segment in seglst: - session_id = segment['session_id'] - start_time = segment['start_time'] - end_time = segment['end_time'] - - # Determine interval bounds - chunk_start = int(start_time // chunk_size) - chunk_end = int(end_time // chunk_size) - - # Split and assign the segment across overlapping intervals - words = segment['words'] - for chunk_idx in range(chunk_start, chunk_end + 1): - chunk_start_time = chunk_idx * chunk_size - chunk_end_time = (chunk_idx + 1) * chunk_size - - # Calculate the adjusted start and end times for the split segment - segment_start = max(start_time, chunk_start_time) - segment_end = min(end_time, chunk_end_time) - - # Create a split segment and add it to the corresponding interval - split_segment = { - 'session_id': session_id, - 'speaker': segment['speaker'], - 'words': words, - 'start_time': segment_start, - 'end_time': segment_end, - 'duration': segment_end - segment_start, - } - words = "" - chunk_id2timestamps[chunk_idx].append(split_segment) - speakers.add(segment['speaker']) - session_ids.add(session_id) - - assert len(session_ids) <= 1, "All segments should belong to the same session" - - if len(session_ids) == 0: - session_id = None - else: - session_id = session_ids.pop() - - return chunk_id2timestamps, speakers, session_id - - -class OnlineEvaluation: - """ - A class designed for performing online evaluation of diarization and ASR. - - Attributes: - ref_seglst (list): - List of reference seglst dictionaries - hyp_seglst (list): - List of hypothesis seglst dictionaries - collar (float): - Collar for DER calculation - ignore_overlap (bool): - Whether to ignore overlapping segments - verbose (bool): - Whether to print verbose output - """ - - def __init__( - self, - ref_seglst: List[Dict], - ref_rttm_labels: List[str], - hyp_seglst: Optional[List[Dict]] = None, - collar: float = 0.25, - ignore_overlap: bool = False, - verbose: bool = True, - ): - self.ref_seglst = ref_seglst - self.ref_rttm_labels = ref_rttm_labels - self.hyp_seglst = hyp_seglst - self.collar = collar - self.ignore_overlap = ignore_overlap - self.verbose = verbose - self.der_list = [] - self.cpwer_list = [] - # current index of the reference seglst - self.current_idx = 0 - - def evaluate_inloop(self, hyp_seglst, end_step_time=0.0): - """ - Evaluate the diarization and ASR performance at each step. - - Args: - hyp_seglst (list): list of hypothesis seglst dictionaries from start to end_step_time - end_step_time (float): end time of the current step - """ - is_update = False - if end_step_time > self.ref_seglst[self.current_idx]['end_time']: - self.current_idx += 1 - is_update = True - ref_seglst = self.ref_seglst[: self.current_idx] - der_cumul, cpwer_cumul = self.evaluate(ref_seglst, hyp_seglst, chunk_size=-1, verbose=False) - der, cpwer = der_cumul[-1], cpwer_cumul[-1] - if self.verbose: - logging.info(f"Session ID: {self.ref_seglst[0]['session_id']} from 0.0s to {end_step_time:.3f}s") - logging.info(f"DER: {der:.2f}%, cpWER: {cpwer:.2f}%") - self.der_list.append(der) - self.cpwer_list.append(cpwer) - else: - is_update = False - if len(self.der_list) > 0 and len(self.cpwer_list) > 0: - der, cpwer = self.der_list[-1], self.cpwer_list[-1] - else: - der, cpwer = 400.0, 100.0 - return der, cpwer, is_update - - def evaluate_outofloop(self, chunk_size=10.0): - """ - Evaluate the diarization and ASR performance for the entire session. - - Args: - chunk_size (float): chunk size in seconds, will report DER and cpWER from start and end of each chunk - """ - return self.evaluate(self.ref_seglst, self.hyp_seglst, chunk_size=chunk_size) - - def evaluate(self, ref_seglst, hyp_seglst, chunk_size=10.0, verbose=True): - max_duration = max([seg['end_time'] for seg in ref_seglst + hyp_seglst]) - if chunk_size == -1: - chunk_size = max_duration + 1 - max_idx = int(max_duration // chunk_size) + 1 - - chunked_ref_seglst, ref_speakers, ref_session_id = chunk_seglst(ref_seglst, chunk_size=chunk_size) - chunked_hyp_seglst, hyp_speakers, hyp_session_id = chunk_seglst(hyp_seglst, chunk_size=chunk_size) - - if hyp_session_id is None: - hyp_session_id = ref_session_id - - assert ref_session_id == hyp_session_id, "Session IDs of reference and hypothesis should match" - - # Only care about the sessions in reference only - session_id = ref_session_id - ref_speaker_words = defaultdict(list) - hyp_speaker_words = defaultdict(list) - - der_metric = DiarizationErrorRate(collar=2 * self.collar, skip_overlap=self.ignore_overlap) - cpwer_metric = calculate_session_cpWER - der_list, cpwer_list = [], [] - for chunk_idx in range(max_idx): - ref_seglst = chunked_ref_seglst[chunk_idx] - hyp_seglst = chunked_hyp_seglst[chunk_idx] - - if len(ref_speaker_words) == 0: - ref_speaker_words = ['' for _ in ref_speakers] - if len(hyp_speaker_words) == 0: - hyp_speaker_words = ['' for _ in hyp_speakers] - hyp_speaker_timestamps, hyp_speaker_word = convert_seglst(hyp_seglst, hyp_speakers) - ref_speaker_timestamps, ref_speaker_word = convert_seglst(ref_seglst, ref_speakers) - - for idx, speaker in enumerate(ref_speakers): - ref_speaker_words[idx] += ref_speaker_word[idx] - for idx, speaker in enumerate(hyp_speakers): - hyp_speaker_words[idx] += hyp_speaker_word[idx] - - # Normalize the text - for spk_idx in range(len(hyp_speaker_words)): - hyp_speaker_words[spk_idx] = ( - hyp_speaker_words[spk_idx].translate(str.maketrans('', '', string.punctuation)).lower() - ) - cpWER, min_perm_hyp_trans, ref_trans = cpwer_metric(ref_speaker_words, hyp_speaker_words) - - if verbose: - logging.info( - f"Session ID: {session_id} Chunk ID: {chunk_idx} from 0.0s to {(chunk_idx+1)*chunk_size}s" - ) - logging.info(f"DER: {abs(der_metric)*100:.2f}%, cpWER: {cpWER*100:.2f}%") - - der_list.append(abs(der_metric) * 100) - cpwer_list.append(cpWER * 100) - - return der_list, cpwer_list - - -class OfflineDiarWithASR: - """ - A class designed for performing ASR and diarization together. - - Attributes: - cfg_diarizer (OmegaConf): - Hydra config for diarizer key - params (OmegaConf): - Parameters config in diarizer.asr - ctc_decoder_params (OmegaConf) - Hydra config for beam search decoder - realigning_lm_params (OmegaConf): - Hydra config for realigning language model - manifest_filepath (str): - Path to the input manifest path - nonspeech_threshold (float): - Threshold for VAD logits that are used for creating speech segments - fix_word_ts_with_VAD (bool): - Choose whether to fix word timestamps by using VAD results - root_path (str): - Path to the folder where diarization results are saved - vad_threshold_for_word_ts (float): - Threshold used for compensating word timestamps with VAD output - max_word_ts_length_in_sec (float): - Maximum limit for the duration of each word timestamp - word_ts_anchor_offset (float): - Offset for word timestamps from ASR decoders - run_ASR: - Placeholder variable for an ASR launcher function - realigning_lm: - Placeholder variable for a loaded ARPA Language model - ctm_exists (bool): - Boolean that indicates whether all files have the corresponding reference CTM file - frame_VAD (dict): - Dictionary containing frame-level VAD logits - AUDIO_RTTM_MAP: - Dictionary containing the input manifest information - color_palette (dict): - Dictionary containing the ANSI color escape codes for each speaker label (speaker index) - """ - - def __init__(self, cfg_diarizer): - self.cfg_diarizer = cfg_diarizer - self.params = cfg_diarizer.asr.parameters - self.ctc_decoder_params = cfg_diarizer.asr.ctc_decoder_parameters - self.realigning_lm_params = cfg_diarizer.asr.realigning_lm_parameters - self.manifest_filepath = cfg_diarizer.manifest_filepath - self.nonspeech_threshold = self.params.asr_based_vad_threshold - self.fix_word_ts_with_VAD = self.params.fix_word_ts_with_VAD - self.root_path = cfg_diarizer.out_dir - - self.vad_threshold_for_word_ts = 0.7 - self.max_word_ts_length_in_sec = 0.6 - self.word_ts_anchor_offset = 0.0 - self.run_ASR = None - self.realigning_lm = None - self.ctm_exists = False - self.frame_VAD = {} - - self.make_file_lists() - - self.color_palette = get_color_palette() - self.csv_columns = self.get_csv_columns() - - @staticmethod - def get_csv_columns() -> List[str]: - return [ - 'uniq_id', - 'DER', - 'CER', - 'FA', - 'MISS', - 'est_n_spk', - 'ref_n_spk', - 'cpWER', - 'WER', - 'mapping', - ] - - def make_file_lists(self): - """ - Create lists containing the filepaths of audio clips and CTM files. - """ - self.AUDIO_RTTM_MAP = audio_rttm_map(self.manifest_filepath) - self.audio_file_list = [value['audio_filepath'] for _, value in self.AUDIO_RTTM_MAP.items()] - - self.ctm_file_list = [] - for k, audio_file_path in enumerate(self.audio_file_list): - uniq_id = get_uniqname_from_filepath(audio_file_path) - if ( - 'ctm_filepath' in self.AUDIO_RTTM_MAP[uniq_id] - and self.AUDIO_RTTM_MAP[uniq_id]['ctm_filepath'] is not None - and uniq_id in self.AUDIO_RTTM_MAP[uniq_id]['ctm_filepath'] - ): - self.ctm_file_list.append(self.AUDIO_RTTM_MAP[uniq_id]['ctm_filepath']) - - # check if all unique IDs have CTM files - if len(self.audio_file_list) == len(self.ctm_file_list): - self.ctm_exists = True - - def _load_realigning_LM(self): - """ - Load ARPA language model for realigning speaker labels for words. - """ - self.N_range = ( - self.realigning_lm_params['min_number_of_words'], - self.realigning_lm_params['max_number_of_words'], - ) - self.stt_end_tokens = ['', ''] - logging.info(f"Loading LM for realigning: {self.realigning_lm_params['arpa_language_model']}") - return arpa.loadf(self.realigning_lm_params['arpa_language_model'])[0] - - def _save_VAD_labels_list(self, word_ts_dict: Dict[str, Dict[str, List[float]]]): - """ - Take the non_speech labels from logit output. The logit output is obtained from - `run_ASR` function. - - Args: - word_ts_dict (dict): - Dictionary containing word timestamps. - """ - self.VAD_RTTM_MAP = {} - for idx, (uniq_id, word_timestamps) in enumerate(word_ts_dict.items()): - speech_labels_float = self.get_speech_labels_from_decoded_prediction( - word_timestamps, self.nonspeech_threshold - ) - speech_labels = self.get_str_speech_labels(speech_labels_float) - output_path = os.path.join(self.root_path, 'pred_rttms') - if not os.path.exists(output_path): - os.makedirs(output_path) - filename = labels_to_rttmfile(speech_labels, uniq_id, output_path) - self.VAD_RTTM_MAP[uniq_id] = {'audio_filepath': self.audio_file_list[idx], 'rttm_filepath': filename} - - @staticmethod - def get_speech_labels_from_decoded_prediction( - input_word_ts: List[float], - nonspeech_threshold: float, - ) -> List[float]: - """ - Extract speech labels from the ASR output (decoded predictions) - - Args: - input_word_ts (list): - List containing word timestamps. - - Returns: - word_ts (list): - The ranges of the speech segments, which are merged ranges of input_word_ts. - """ - speech_labels = [] - word_ts = copy.deepcopy(input_word_ts) - if word_ts == []: - return speech_labels - else: - count = len(word_ts) - 1 - while count > 0: - if len(word_ts) > 1: - if word_ts[count][0] - word_ts[count - 1][1] <= nonspeech_threshold: - trangeB = word_ts.pop(count) - trangeA = word_ts.pop(count - 1) - word_ts.insert(count - 1, [trangeA[0], trangeB[1]]) - count -= 1 - return word_ts - - def run_diarization(self, diar_model_config, word_timestamps) -> Dict[str, List[str]]: - """ - Launch the diarization process using the given VAD timestamp (oracle_manifest). - - Args: - diar_model_config (OmegaConf): - Hydra configurations for speaker diarization - word_and_timestamps (list): - List containing words and word timestamps - - Returns: - diar_hyp (dict): - A dictionary containing rttm results which are indexed by a unique ID. - score Tuple[pyannote object, dict]: - A tuple containing pyannote metric instance and mapping dictionary between - speakers in hypotheses and speakers in reference RTTM files. - """ - - if diar_model_config.diarizer.asr.parameters.asr_based_vad: - self._save_VAD_labels_list(word_timestamps) - oracle_manifest = os.path.join(self.root_path, 'asr_vad_manifest.json') - oracle_manifest = write_rttm2manifest(self.VAD_RTTM_MAP, oracle_manifest) - diar_model_config.diarizer.vad.model_path = None - diar_model_config.diarizer.vad.external_vad_manifest = oracle_manifest - - diar_model = ClusteringDiarizer(cfg=diar_model_config) - score = diar_model.diarize() - if diar_model_config.diarizer.vad.model_path is not None and not diar_model_config.diarizer.oracle_vad: - self._get_frame_level_VAD( - vad_processing_dir=diar_model.vad_pred_dir, - smoothing_type=diar_model_config.diarizer.vad.parameters.smoothing, - ) - - diar_hyp = {} - for k, audio_file_path in enumerate(self.audio_file_list): - uniq_id = get_uniqname_from_filepath(audio_file_path) - pred_rttm = os.path.join(self.root_path, 'pred_rttms', uniq_id + '.rttm') - diar_hyp[uniq_id] = rttm_to_labels(pred_rttm) - return diar_hyp, score - - def _get_frame_level_VAD(self, vad_processing_dir, smoothing_type=False): - """ - Read frame-level VAD outputs. - - Args: - vad_processing_dir (str): - Path to the directory where the VAD results are saved. - smoothing_type (bool or str): [False, median, mean] - type of smoothing applied softmax logits to smooth the predictions. - """ - if isinstance(smoothing_type, bool) and not smoothing_type: - ext_type = 'frame' - else: - ext_type = smoothing_type - - for uniq_id in self.AUDIO_RTTM_MAP: - frame_vad = os.path.join(vad_processing_dir, uniq_id + '.' + ext_type) - frame_vad_float_list = [] - with open(frame_vad, 'r') as fp: - for line in fp.readlines(): - frame_vad_float_list.append(float(line.strip())) - self.frame_VAD[uniq_id] = frame_vad_float_list - - @staticmethod - def gather_eval_results( - diar_score, - audio_rttm_map_dict: Dict[str, Dict[str, str]], - trans_info_dict: Dict[str, Dict[str, float]], - root_path: str, - decimals: int = 4, - ) -> Dict[str, Dict[str, float]]: - """ - Gather diarization evaluation results from pyannote DiarizationErrorRate metric object. - - Args: - metric (DiarizationErrorRate metric): - DiarizationErrorRate metric pyannote object - trans_info_dict (dict): - Dictionary containing word timestamps, speaker labels and words from all sessions. - Each session is indexed by unique ID as a key. - mapping_dict (dict): - Dictionary containing speaker mapping labels for each audio file with key as unique name - decimals (int): - The number of rounding decimals for DER value - - Returns: - der_results (dict): - Dictionary containing scores for each audio file along with aggregated results - """ - metric, mapping_dict, _ = diar_score - results = metric.results_ - der_results = {} - count_correct_spk_counting = 0 - for result in results: - key, score = result - if 'hyp_rttm_filepath' in audio_rttm_map_dict[key]: - pred_rttm = audio_rttm_map_dict[key]['hyp_rttm_filepath'] - else: - pred_rttm = os.path.join(root_path, 'pred_rttms', key + '.rttm') - pred_labels = rttm_to_labels(pred_rttm) - - ref_rttm = audio_rttm_map_dict[key]['rttm_filepath'] - ref_labels = rttm_to_labels(ref_rttm) - ref_n_spk = get_num_of_spk_from_labels(ref_labels) - est_n_spk = get_num_of_spk_from_labels(pred_labels) - - _DER, _CER, _FA, _MISS = ( - (score['confusion'] + score['false alarm'] + score['missed detection']) / score['total'], - score['confusion'] / score['total'], - score['false alarm'] / score['total'], - score['missed detection'] / score['total'], - ) - - der_results[key] = { - "DER": round(_DER, decimals), - "CER": round(_CER, decimals), - "FA": round(_FA, decimals), - "MISS": round(_MISS, decimals), - "est_n_spk": est_n_spk, - "ref_n_spk": ref_n_spk, - "mapping": mapping_dict[key], - } - count_correct_spk_counting += int(est_n_spk == ref_n_spk) - - DER, CER, FA, MISS = ( - abs(metric), - metric['confusion'] / metric['total'], - metric['false alarm'] / metric['total'], - metric['missed detection'] / metric['total'], - ) - der_results["total"] = { - "DER": DER, - "CER": CER, - "FA": FA, - "MISS": MISS, - "spk_counting_acc": count_correct_spk_counting / len(metric.results_), - } - - return der_results - - def _get_the_closest_silence_start( - self, vad_index_word_end: float, vad_frames: np.ndarray, offset: int = 10 - ) -> float: - """ - Find the closest silence frame from the given starting position. - - Args: - vad_index_word_end (float): - The timestamp of the end of the current word. - vad_frames (numpy.array): - The numpy array containing frame-level VAD probability. - params (dict): - Contains the parameters for diarization and ASR decoding. - - Returns: - cursor (float): - A timestamp of the earliest start of a silence region from - the given time point, vad_index_word_end. - """ - - cursor = vad_index_word_end + offset - limit = int(100 * self.max_word_ts_length_in_sec + vad_index_word_end) - while cursor < len(vad_frames): - if vad_frames[cursor] < self.vad_threshold_for_word_ts: - break - else: - cursor += 1 - if cursor > limit: - break - cursor = min(len(vad_frames) - 1, cursor) - cursor = round(cursor / 100.0, 2) - return cursor - - def _compensate_word_ts_list( - self, - audio_file_list: List[str], - word_ts_dict: Dict[str, List[float]], - ) -> Dict[str, List[List[float]]]: - """ - Compensate the word timestamps based on the VAD output. - The length of each word is capped by self.max_word_ts_length_in_sec. - - Args: - audio_file_list (list): - List containing audio file paths. - word_ts_dict (dict): - Dictionary containing timestamps of words. - - Returns: - enhanced_word_ts_dict (dict): - Dictionary containing the enhanced word timestamp values indexed by unique-IDs. - """ - enhanced_word_ts_dict = {} - for idx, (uniq_id, word_ts_seq_list) in enumerate(word_ts_dict.items()): - N = len(word_ts_seq_list) - enhanced_word_ts_buffer = [] - for k, word_ts in enumerate(word_ts_seq_list): - if k < N - 1: - word_len = round(word_ts[1] - word_ts[0], 2) - len_to_next_word = round(word_ts_seq_list[k + 1][0] - word_ts[0] - 0.01, 2) - if uniq_id in self.frame_VAD: - vad_index_word_end = int(100 * word_ts[1]) - closest_sil_stt = self._get_the_closest_silence_start( - vad_index_word_end, self.frame_VAD[uniq_id] - ) - vad_est_len = round(closest_sil_stt - word_ts[0], 2) - else: - vad_est_len = len_to_next_word - min_candidate = min(vad_est_len, len_to_next_word) - fixed_word_len = max(min(self.max_word_ts_length_in_sec, min_candidate), word_len) - enhanced_word_ts_buffer.append([word_ts[0], word_ts[0] + fixed_word_len]) - else: - enhanced_word_ts_buffer.append([word_ts[0], word_ts[1]]) - - enhanced_word_ts_dict[uniq_id] = enhanced_word_ts_buffer - return enhanced_word_ts_dict - - def get_transcript_with_speaker_labels( - self, diar_hyp: Dict[str, List[str]], word_hyp: Dict[str, List[str]], word_ts_hyp: Dict[str, List[float]] - ) -> Dict[str, Dict[str, float]]: - """ - Match the diarization result with the ASR output. - The words and the timestamps for the corresponding words are matched in a for loop. - - Args: - diar_hyp (dict): - Dictionary of the Diarization output labels in str. Indexed by unique IDs. - - Example: - >>> diar_hyp['my_audio_01'] = ['0.0 4.375 speaker_1', '4.375 5.125 speaker_0', ...] - - word_hyp (dict): - Dictionary of words from ASR inference. Indexed by unique IDs. - - Example: - >>> word_hyp['my_audio_01'] = ['hi', 'how', 'are', ...] - - word_ts_hyp (dict): - Dictionary containing the start time and the end time of each word. - Indexed by unique IDs. - - Example: - >>> word_ts_hyp['my_audio_01'] = [[0.0, 0.04], [0.64, 0.68], [0.84, 0.88], ...] - - Returns: - trans_info_dict (dict): - Dictionary containing word timestamps, speaker labels and words from all sessions. - Each session is indexed by a unique ID. - """ - trans_info_dict = {} - if self.fix_word_ts_with_VAD: - if self.frame_VAD == {}: - logging.warning( - "VAD timestamps are not provided. Fixing word timestamps without VAD. Please check the hydra configurations." - ) - word_ts_refined = self._compensate_word_ts_list(self.audio_file_list, word_ts_hyp) - else: - word_ts_refined = word_ts_hyp - - if self.realigning_lm_params['arpa_language_model']: - if not ARPA: - raise ImportError( - 'LM for realigning is provided but arpa is not installed. Install arpa using PyPI: pip install arpa' - ) - else: - self.realigning_lm = self._load_realigning_LM() - - word_dict_seq_list = [] - for k, audio_file_path in enumerate(self.audio_file_list): - uniq_id = get_uniqname_from_filepath(audio_file_path) - words, diar_labels = word_hyp[uniq_id], diar_hyp[uniq_id] - word_ts, word_rfnd_ts = word_ts_hyp[uniq_id], word_ts_refined[uniq_id] - - # Assign speaker labels to words - word_dict_seq_list = self.get_word_level_json_list( - words=words, word_ts=word_ts, word_rfnd_ts=word_rfnd_ts, diar_labels=diar_labels - ) - if self.realigning_lm: - word_dict_seq_list = self.realign_words_with_lm(word_dict_seq_list) - - # Create a transscript information json dictionary from the output variables - trans_info_dict[uniq_id] = self._make_json_output(uniq_id, diar_labels, word_dict_seq_list) - logging.info(f"Diarization with ASR output files are saved in: {self.root_path}/pred_rttms") - return trans_info_dict - - def get_word_level_json_list( - self, - words: List[str], - diar_labels: List[str], - word_ts: List[List[float]], - word_rfnd_ts: List[List[float]] = None, - decimals: int = 2, - ) -> Dict[str, Dict[str, str]]: - """ - Assign speaker labels to each word and save the hypothesis words and speaker labels to - a dictionary variable for future use. - - Args: - uniq_id (str): - A unique ID (key) that identifies each input audio file. - diar_labels (list): - List containing the Diarization output labels in str. Indexed by unique IDs. - - Example: - >>> diar_labels = ['0.0 4.375 speaker_1', '4.375 5.125 speaker_0', ...] - - words (list): - Dictionary of words from ASR inference. Indexed by unique IDs. - - Example: - >>> words = ['hi', 'how', 'are', ...] - - word_ts (list): - Dictionary containing the start time and the end time of each word. - Indexed by unique IDs. - - Example: - >>> word_ts = [[0.0, 0.04], [0.64, 0.68], [0.84, 0.88], ...] - - word_ts_refined (list): - Dictionary containing the refined (end point fixed) word timestamps based on hypothesis - word timestamps. Indexed by unique IDs. - - Example: - >>> word_rfnd_ts = [[0.0, 0.60], [0.64, 0.80], [0.84, 0.92], ...] - - Returns: - word_dict_seq_list (list): - List containing word by word dictionary containing word, timestamps and speaker labels. - - Example: - >>> [{'word': 'right', 'start_time': 0.0, 'end_time': 0.04, 'speaker': 'speaker_0'}, - {'word': 'and', 'start_time': 0.64, 'end_time': 0.68, 'speaker': 'speaker_1'}, - {'word': 'i', 'start_time': 0.84, 'end_time': 0.88, 'speaker': 'speaker_1'}, - ...] - """ - if word_rfnd_ts is None: - word_rfnd_ts = word_ts - start_point, end_point, speaker = diar_labels[0].split() - word_pos, turn_idx = 0, 0 - word_dict_seq_list = [] - for word_idx, (word, word_ts_stt_end, refined_word_ts_stt_end) in enumerate(zip(words, word_ts, word_rfnd_ts)): - word_pos = self._get_word_timestamp_anchor(word_ts_stt_end) - if word_pos > float(end_point): - turn_idx += 1 - turn_idx = min(turn_idx, len(diar_labels) - 1) - start_point, end_point, speaker = diar_labels[turn_idx].split() - stt_sec = round(refined_word_ts_stt_end[0], decimals) - end_sec = round(refined_word_ts_stt_end[1], decimals) - word_dict_seq_list.append({'word': word, 'start_time': stt_sec, 'end_time': end_sec, 'speaker': speaker}) - return word_dict_seq_list - - def _make_json_output( - self, - uniq_id: str, - diar_labels: List[str], - word_dict_seq_list: List[Dict[str, float]], - ) -> Dict[str, Dict[str, str]]: - """ - Generate json output files and transcripts from the ASR and diarization results. - - Args: - uniq_id (str): - A unique ID (key) that identifies each input audio file. - diar_labels (list): - List containing the diarization hypothesis timestamps - - Example: - >>> diar_hyp['my_audio_01'] = ['0.0 4.375 speaker_1', '4.375 5.125 speaker_0', ...] - - word_dict_seq_list (list): - List containing words and corresponding word timestamps in dictionary format. - - Example: - >>> [{'word': 'right', 'start_time': 0.0, 'end_time': 0.04, 'speaker': 'speaker_0'}, - {'word': 'and', 'start_time': 0.64, 'end_time': 0.68, 'speaker': 'speaker_1'}, - {'word': 'i', 'start_time': 0.84, 'end_time': 0.88, 'speaker': 'speaker_1'}, - ...] - - Returns: - session_result_dict (dict): - A dictionary containing overall results of diarization and ASR inference. - `session_result_dict` has following keys: `status`, `session_id`, `transcription`, `speaker_count`, - `words`, `sentences`. - - Example: - >>> session_trans_dict = \ - { - 'status': 'Success', - 'session_id': 'my_audio_01', - 'transcription': 'right and i really think ...', - 'speaker_count': 2, - 'words': [{'word': 'right', 'start_time': 0.0, 'end_time': 0.04, 'speaker': 'speaker_0'}, - {'word': 'and', 'start_time': 0.64, 'end_time': 0.68, 'speaker': 'speaker_1'}, - {'word': 'i', 'start_time': 0.84, 'end_time': 0.88, 'speaker': 'speaker_1'}, - ... - ] - 'sentences': [{'sentence': 'right', 'start_time': 0.0, 'end_time': 0.04, 'speaker': 'speaker_0'}, - {'sentence': 'and i really think ...', - 'start_time': 0.92, 'end_time': 4.12, 'speaker': 'speaker_0'}, - ... - ] - } - """ - logging.info(f"Creating results for Session: {uniq_id}") - session_trans_dict, gecko_dict, audacity_label_words, sentences = get_session_trans_dict( - uniq_id, word_dict_seq_list, diar_labels - ) - self._write_and_log(uniq_id, session_trans_dict, audacity_label_words, gecko_dict, sentences) - return session_trans_dict - - def _get_realignment_ranges(self, k: int, word_seq_len: int) -> Tuple[int, int]: - """ - Calculate word ranges for realignment operation. - N1, N2 are calculated to not exceed the start and end of the input word sequence. - - Args: - k (int): - Index of the current word - word_seq_len (int): - Length of the sentence - - Returns: - N1 (int): - Start index of the word sequence - N2 (int): - End index of the word sequence - """ - if k < self.N_range[1]: - N1 = max(k, self.N_range[0]) - N2 = min(word_seq_len - k, self.N_range[1]) - elif k > (word_seq_len - self.N_range[1]): - N1 = min(k, self.N_range[1]) - N2 = max(word_seq_len - k, self.N_range[0]) - else: - N1, N2 = self.N_range[1], self.N_range[1] - return N1, N2 - - def _get_word_timestamp_anchor(self, word_ts_stt_end: List[float]) -> float: - """ - Determine a reference point to match a word with the diarization results. - word_ts_anchor_pos determines the position of a word in relation to the given diarization labels: - - 'start' uses the beginning of the word - - 'end' uses the end of the word - - 'mid' uses the mean of start and end of the word - - word_ts_anchor_offset determines how much offset we want to add to the anchor position. - It is recommended to use the default value. - - Args: - word_ts_stt_end (list): - List containing start and end of the decoded word. - - Returns: - word_pos (float): - Floating point number that indicates temporal location of the word. - """ - if self.params['word_ts_anchor_pos'] == 'start': - word_pos = word_ts_stt_end[0] - elif self.params['word_ts_anchor_pos'] == 'end': - word_pos = word_ts_stt_end[1] - elif self.params['word_ts_anchor_pos'] == 'mid': - word_pos = (word_ts_stt_end[0] + word_ts_stt_end[1]) / 2 - else: - logging.info( - f"word_ts_anchor_pos: {self.params['word_ts_anchor']} is not a supported option. Using the default 'start' option." - ) - word_pos = word_ts_stt_end[0] - - word_pos = word_pos + self.word_ts_anchor_offset - return word_pos - - def realign_words_with_lm(self, word_dict_seq_list: List[Dict[str, float]]) -> List[Dict[str, float]]: - """ - Realign the mapping between speaker labels and words using a language model. - The realigning process calculates the probability of the certain range around the words, - especially at the boundary between two hypothetical sentences spoken by different speakers. - - Example: - k-th word: "but" - - hyp_former: - since i think like tuesday but he's coming back to albuquerque - hyp_latter: - since i think like tuesday but he's coming back to albuquerque - - The joint probabilities of words in the sentence are computed for these two hypotheses. In addition, - logprob_diff_threshold parameter is used for reducing the false positive realigning. - - Args: - word_dict_seq_list (list): - List containing words and corresponding word timestamps in dictionary format. - - Returns: - realigned_list (list): - List of dictionaries containing words, word timestamps and speaker labels. - """ - word_seq_len = len(word_dict_seq_list) - hyp_w_dict_list, spk_list = [], [] - for k, line_dict in enumerate(word_dict_seq_list): - word, spk_label = line_dict['word'], line_dict['speaker'] - hyp_w_dict_list.append(word) - spk_list.append(spk_label) - - realigned_list = [] - org_spk_list = copy.deepcopy(spk_list) - for k, line_dict in enumerate(word_dict_seq_list): - if self.N_range[0] < k < (word_seq_len - self.N_range[0]) and ( - spk_list[k] != org_spk_list[k + 1] or spk_list[k] != org_spk_list[k - 1] - ): - N1, N2 = self._get_realignment_ranges(k, word_seq_len) - hyp_former = self.realigning_lm.log_s( - ' '.join(hyp_w_dict_list[k - N1 : k] + self.stt_end_tokens + hyp_w_dict_list[k : k + N2]) - ) - hyp_latter = self.realigning_lm.log_s( - ' '.join(hyp_w_dict_list[k - N1 : k + 1] + self.stt_end_tokens + hyp_w_dict_list[k + 1 : k + N2]) - ) - log_p = [hyp_former, hyp_latter] - p_order = np.argsort(log_p)[::-1] - if log_p[p_order[0]] > log_p[p_order[1]] + self.realigning_lm_params['logprob_diff_threshold']: - if p_order[0] == 0: - spk_list[k] = org_spk_list[k + 1] - line_dict['speaker'] = spk_list[k] - realigned_list.append(line_dict) - return realigned_list - - @staticmethod - def evaluate( - audio_file_list: List[str], - hyp_trans_info_dict: Dict[str, Dict[str, float]], - hyp_ctm_file_list: List[str] = None, - ref_ctm_file_list: List[str] = None, - ) -> Dict[str, Dict[str, float]]: - """ - Evaluate the result transcripts based on the provided CTM file. WER and cpWER are calculated to assess - the performance of ASR system and diarization at the same time. - - Args: - audio_file_list (list): - List containing file path to the input audio files. - hyp_trans_info_dict (dict): - Dictionary containing the hypothesis transcriptions for all sessions. - hyp_ctm_file_list (list): - List containing file paths of the hypothesis transcriptions in CTM format for all sessions. - ref_ctm_file_list (list): - List containing file paths of the reference transcriptions in CTM format for all sessions. - - Note: Either `hyp_trans_info_dict` or `hyp_ctm_file_list` should be provided. - - Returns: - wer_results (dict): - Session-by-session results including DER, miss rate, false alarm rate, WER and cpWER - """ - wer_results = {} - - if ref_ctm_file_list is not None: - spk_hypotheses, spk_references = [], [] - mix_hypotheses, mix_references = [], [] - WER_values, uniq_id_list = [], [] - - for k, (audio_file_path, ctm_file_path) in enumerate(zip(audio_file_list, ref_ctm_file_list)): - uniq_id = get_uniqname_from_filepath(audio_file_path) - uniq_id_list.append(uniq_id) - if uniq_id != get_uniqname_from_filepath(ctm_file_path): - raise ValueError("audio_file_list has mismatch in uniq_id with ctm_file_path") - - # Either hypothesis CTM file or hyp_trans_info_dict should be provided - if hyp_ctm_file_list is not None: - if uniq_id == get_uniqname_from_filepath(hyp_ctm_file_list[k]): - spk_hypothesis, mix_hypothesis = convert_ctm_to_text(hyp_ctm_file_list[k]) - else: - raise ValueError("Hypothesis CTM files are provided but uniq_id is mismatched") - elif hyp_trans_info_dict is not None and uniq_id in hyp_trans_info_dict: - spk_hypothesis, mix_hypothesis = convert_word_dict_seq_to_text( - hyp_trans_info_dict[uniq_id]['words'] - ) - else: - raise ValueError("Hypothesis information is not provided in the correct format.") - - spk_reference, mix_reference = convert_ctm_to_text(ctm_file_path) - - spk_hypotheses.append(spk_hypothesis) - spk_references.append(spk_reference) - mix_hypotheses.append(mix_hypothesis) - mix_references.append(mix_reference) - - # Calculate session by session WER value - WER_values.append(word_error_rate([mix_hypothesis], [mix_reference])) - - cpWER_values, hyps_spk, refs_spk = concat_perm_word_error_rate(spk_hypotheses, spk_references) - - # Take an average of cpWER and regular WER value on all sessions - wer_results['total'] = {} - wer_results['total']['average_cpWER'] = word_error_rate(hypotheses=hyps_spk, references=refs_spk) - wer_results['total']['average_WER'] = word_error_rate(hypotheses=mix_hypotheses, references=mix_references) - - for uniq_id, cpWER, WER in zip(uniq_id_list, cpWER_values, WER_values): - # Save session-level cpWER and WER values - wer_results[uniq_id] = {} - wer_results[uniq_id]['cpWER'] = cpWER - wer_results[uniq_id]['WER'] = WER - - return wer_results - - @staticmethod - def get_str_speech_labels(speech_labels_float: List[List[float]]) -> List[str]: - """ - Convert floating point speech labels list to a list containing string values. - - Args: - speech_labels_float (list): - List containing start and end timestamps of the speech segments in floating point type - speech_labels (list): - List containing start and end timestamps of the speech segments in string format - """ - speech_labels = [] - for start, end in speech_labels_float: - speech_labels.append("{:.3f} {:.3f} speech".format(start, end)) - return speech_labels - - @staticmethod - def write_session_level_result_in_csv( - der_results: Dict[str, Dict[str, float]], - wer_results: Dict[str, Dict[str, float]], - root_path: str, - csv_columns: List[str], - csv_file_name: str = "ctm_eval.csv", - ): - """ - This function is for development use when a CTM file is provided. - Saves the session-level diarization and ASR result into a csv file. - - Args: - wer_results (dict): - Dictionary containing session-by-session results of ASR and diarization in terms of - WER and cpWER. - """ - target_path = f"{root_path}/pred_rttms" - os.makedirs(target_path, exist_ok=True) - logging.info(f"Writing {target_path}/{csv_file_name}") - total_result_jsons = get_total_result_dict(der_results, wer_results, csv_columns) - try: - with open(f"{target_path}/{csv_file_name}", 'w') as csvfile: - writer = csv.DictWriter(csvfile, fieldnames=csv_columns) - writer.writeheader() - for data in total_result_jsons: - writer.writerow(data) - except IOError: - logging.info("I/O error has occurred while writing a csv file.") - - def _write_and_log( - self, - uniq_id: str, - session_trans_dict: Dict[str, Dict[str, float]], - audacity_label_words: List[str], - gecko_dict: Dict[str, Dict[str, float]], - sentences: List[Dict[str, float]], - ): - """ - Write output files and display logging messages. - - Args: - uniq_id (str): - A unique ID (key) that identifies each input audio file - session_trans_dict (dict): - Dictionary containing the transcription output for a session - audacity_label_words (list): - List containing word and word timestamp information in Audacity label format - gecko_dict (dict): - Dictionary formatted to be opened in Gecko software - sentences (list): - List containing sentence dictionary - """ - # print the sentences in the .txt output - string_out = print_sentences(sentences, color_palette=self.color_palette, params=self.params) - if self.params['break_lines']: - string_out = self.break_transcript_lines(string_out, params=self.params) - - session_trans_dict["status"] = "success" - ctm_lines_list = convert_word_dict_seq_to_ctm(session_trans_dict['words']) - - dump_json_to_file(f'{self.root_path}/pred_rttms/{uniq_id}.json', session_trans_dict) - dump_json_to_file(f'{self.root_path}/pred_rttms/{uniq_id}_gecko.json', gecko_dict) - write_txt(f'{self.root_path}/pred_rttms/{uniq_id}.ctm', '\n'.join(ctm_lines_list)) - write_txt(f'{self.root_path}/pred_rttms/{uniq_id}.txt', string_out.strip()) - write_txt(f'{self.root_path}/pred_rttms/{uniq_id}.w.label', '\n'.join(audacity_label_words)) - - def break_transcript_lines(self, string_out: str, params: Dict[str, str], max_chars_in_line: int = 90) -> str: - """ - Break the lines in the transcript. - - Args: - string_out (str): - Input transcript with speaker labels - params (dict): - Parameters dictionary - max_chars_in_line (int): - Maximum characters in each line - - Returns: - return_string_out (str): - String variable containing line breaking - """ - color_str_len = len('\033[1;00m') if self.params['colored_text'] else 0 - split_string_out = string_out.split('\n') - return_string_out = [] - for org_chunk in split_string_out: - buffer = [] - if len(org_chunk) - color_str_len > max_chars_in_line: - color_str = org_chunk[:color_str_len] if color_str_len > 0 else '' - for i in range(color_str_len, len(org_chunk), max_chars_in_line): - trans_str = org_chunk[i : i + max_chars_in_line] - if len(trans_str.strip()) > 0: - c_trans_str = color_str + trans_str - buffer.append(c_trans_str) - return_string_out.extend(buffer) - else: - return_string_out.append(org_chunk) - return_string_out = '\n'.join(return_string_out) - return return_string_out - - @staticmethod - def print_errors(der_results: Dict[str, Dict[str, float]], wer_results: Dict[str, Dict[str, float]]): - """ - Print a slew of error metrics for ASR and Diarization. - - Args: - der_results (dict): - Dictionary containing FA, MISS, CER and DER values for both aggregated amount and - each session. - wer_results (dict): - Dictionary containing session-by-session WER and cpWER. `wer_results` only - exists when CTM files are provided. - """ - DER_info = f"\nDER : {der_results['total']['DER']:.4f} \ - \nFA : {der_results['total']['FA']:.4f} \ - \nMISS : {der_results['total']['MISS']:.4f} \ - \nCER : {der_results['total']['CER']:.4f} \ - \nSpk. counting acc. : {der_results['total']['spk_counting_acc']:.4f}" - if wer_results is not None and len(wer_results) > 0: - logging.info( - DER_info - + f"\ncpWER : {wer_results['total']['average_cpWER']:.4f} \ - \nWER : {wer_results['total']['average_WER']:.4f}" - ) - else: - logging.info(DER_info) diff --git a/nemo/collections/asr/parts/utils/eou_utils.py b/nemo/collections/asr/parts/utils/eou_utils.py deleted file mode 100644 index 478fc44df3a93648a1a4cb8b4a2d2e0181212a7f..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/eou_utils.py +++ /dev/null @@ -1,289 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from dataclasses import dataclass -from typing import Dict, List - -import numpy as np - - -@dataclass -class EOUResult: - """ - A dataclass to store the EOU results. - Args: - latency: List of latencies in seconds. - early_cutoff: List of early cutoffs in seconds. - true_positives: Number of true positives. - false_negatives: Number of false negatives. - false_positives: Number of false positives. - num_utterances: Number of utterances. - num_predictions: Number of predictions. - missing: Number of missing predictions. - """ - - latency: list - early_cutoff: list - true_positives: int - false_negatives: int - false_positives: int - num_utterances: int - num_predictions: int - missing: int - - def to_dict(self) -> Dict[str, float]: - """ - Convert the EOUResult dataclass to a dictionary. - Returns: - Dict: A dictionary representation of the EOUResult. - """ - return { - 'latency': self.latency, - 'early_cutoff': self.early_cutoff, - 'true_positives': self.true_positives, - 'false_negatives': self.false_negatives, - 'false_positives': self.false_positives, - 'num_utterances': self.num_utterances, - 'num_predictions': self.num_predictions, - 'missing': self.missing, - } - - -def flatten_nested_list(nested_list: List[List[float]]) -> List[float]: - """ - Flatten a nested list into a single list. - Args: - nested_list (List[List]): A nested list to be flattened. - Returns: - List: A flattened list. - """ - return [item for sublist in nested_list for item in sublist] - - -def evaluate_eou( - *, prediction: List[dict], reference: List[dict], threshold: float, collar: float, do_sorting: bool = True -) -> EOUResult: - """ - Evaluate end of utterance predictions against reference labels. - Each item in predicition/reference is a dictionary in SegLST containing: - { - "session_id": str, - "start_time": float, # start time in seconds - "end_time": float, # end time in seconds - "words": str, # transcription of the utterance - "audio_filepath": str, # only in prediction - "eou_prob": float, # only in prediction, probability of EOU in range [0.1] - "eou_pred": bool, # only in prediction - "full_text": str, # only in prediction, which is the full transcription up to the end_time - } - - Args: - predictions (List[dict]): List of dictionaries containing predictions. - references (List[dict]): List of dictionaries containing reference labels. - threshold (float): Threshold for considering a prediction as EOU. - collar (float): Collar time in seconds for matching predictions to references. - do_sorting (bool): Whether to sort the predictions and references by start time. - Returns: - EOUResult: A dataclass containing the evaluation results. - """ - - latency = [] - early_cutoff = [] - true_positives = 0 - false_negatives = 0 - false_positives = 0 - num_utterances = len(reference) - num_predictions = len(prediction) - missing = 0 - earlycut_ids = set() - predicted_eou = prediction - if threshold is not None and threshold > 0: - predicted_eou = [p for p in prediction if p["eou_prob"] > threshold] - elif all([hasattr(p, "eou_pred") for p in prediction]): - # If eou_pred is available, use it - predicted_eou = [p for p in prediction if p["eou_pred"]] - - if do_sorting: - predicted_eou = sorted(predicted_eou, key=lambda x: x["start_time"]) - reference = sorted(reference, key=lambda x: x["start_time"]) - - p_idx = 0 - r_idx = 0 - for p_idx in range(len(predicted_eou)): - p = predicted_eou[p_idx] - p_start = p["start_time"] - p_end = p["end_time"] - - while r_idx < len(reference) and reference[r_idx]["end_time"] < p_start: - # Current reference ends before the current predicted utterance starts, find the next reference - r_idx += 1 - - if r_idx >= len(reference): - # No more references to compare against - false_positives += 1 - continue - - r = reference[r_idx] - r_start = r["start_time"] - r_end = r["end_time"] - - if np.abs(p_end - r_end) <= collar: - # Correctly predicted EOU - true_positives += 1 - latency.append(p_end - r_end) - if r_idx in earlycut_ids: - # If this reference was already missed due to early cutoff, we do not count it again - earlycut_ids.remove(r_idx) - r_idx += 1 - elif r_start <= p_end < r_end - collar: - # Early cutoff - # current predicted EOU is within the current reference utterance - false_positives += 1 - early_cutoff.append(r_end - p_end) - earlycut_ids.add(r_idx) - elif r_end + collar < p_end: - # Late EOU - # Current predicted EOU is after the current reference ends - false_negatives += 1 - latency.append(p_end - r_end) - if r_idx in earlycut_ids: - # If this reference was already missed due to early cutoff, we do not count it again - earlycut_ids.remove(r_idx) - r_idx += 1 - else: - # p_end <= r_start - # Current predicted EOU is before the current reference starts - false_positives += 1 - - if r_idx < len(reference): - # There are remaining references that were not matched - false_negatives += len(reference) - r_idx - missing += len(reference) - r_idx - - missing -= len(earlycut_ids) # Remove the references that were missed due to early cutoff - false_negatives -= len(earlycut_ids) # Remove the references that were missed due to early cutoff - return EOUResult( - latency=latency, - early_cutoff=early_cutoff, - true_positives=true_positives, - false_negatives=false_negatives, - false_positives=false_positives, - num_utterances=num_utterances, - num_predictions=num_predictions, - missing=missing, - ) - - -def get_SegLST_from_frame_labels(frame_labels: List[int], frame_len_in_secs: float = 0.08) -> List[dict]: - """ - Convert frame labels to SegLST format. - Args: - frame_labels (List[int]): List of frame labels. - frame_len_in_secs (float): Length of each frame in seconds. - Returns: - List[dict]: List of dictionaries in SegLST format. - """ - seg_lst = [] - start_time = 0.0 - for i, label in enumerate(frame_labels): - if label > 0: - end_time = start_time + frame_len_in_secs * i - seg_lst.append({"start_time": start_time, "end_time": end_time, "eou_prob": label}) - start_time = end_time - return seg_lst - - -def cal_eou_metrics_from_frame_labels( - *, - prediction: List[float], - reference: List[float], - threshold: float = 0.5, - collar: float = 0, - frame_len_in_secs: float = 0.08, -) -> EOUResult: - """ - Calculate EOU metrics from lists of predictions and references. - Args: - prediction (List): List of floats containing predicted EOU probabilities. - reference (List): List of binary floats containing reference EOU probabilities. - threshold (float): Threshold for considering a prediction as EOU. - collar (float): Collar time in seconds for matching predictions to references. - frame_len_in_secs (float): Length of each frame in seconds. - """ - - if len(prediction) != len(reference): - raise ValueError( - f"Prediction ({len(prediction)}) and reference ({len(reference)}) lists must have the same length." - ) - - pred_seg_lst = get_SegLST_from_frame_labels(prediction, frame_len_in_secs) - ref_seg_lst = get_SegLST_from_frame_labels(reference, frame_len_in_secs) - eou_metrics = evaluate_eou( - prediction=pred_seg_lst, reference=ref_seg_lst, threshold=threshold, collar=collar, do_sorting=False - ) - return eou_metrics - - -def get_percentiles(values: List[float], percentiles: List[float], tag: str = "") -> Dict[str, float]: - """ - Get the percentiles of a list of values. - Args: - values: list of values - percentiles: list of percentiles - Returns: - metrics: Dict of percentiles - """ - if len(values) == 0: - return [0.0] * len(percentiles) - results = np.percentile(values, percentiles).tolist() - metrics = {} - if tag: - tag += "_" - for i, p in enumerate(percentiles): - metrics[f'{tag}p{int(p)}'] = float(results[i]) - return metrics - - -def aggregate_eou_metrics(eou_metrics: List[EOUResult], target_percentiles: List = [50, 90, 95]) -> Dict[str, float]: - """ - Aggregate EOU metrics to produce metrics for logging. - Args: - eou_metrics: List of EOUResult objects. - target_percentiles: List of target percentiles. - Returns: - Dict: A dictionary containing the aggregated EOU metrics. - """ - num_eou_utterances = sum([x.num_utterances for x in eou_metrics]) - eou_latency = flatten_nested_list([x.latency for x in eou_metrics]) - eou_early_cutoff = flatten_nested_list([x.early_cutoff for x in eou_metrics]) - - eou_avg_num_early_cutoff = len(eou_early_cutoff) / num_eou_utterances if num_eou_utterances > 0 else 0.0 - if len(eou_latency) == 0: - eou_latency = [0.0] - if len(eou_early_cutoff) == 0: - eou_early_cutoff = [0.0] - - eou_missing = [x.missing for x in eou_metrics] - - metrics = {} - eou_latency_metrics = get_percentiles(eou_latency, target_percentiles, tag='latency') - eou_early_cutoff_metrics = get_percentiles(eou_early_cutoff, target_percentiles, tag='early_cutoff') - - metrics.update(eou_latency_metrics) - metrics.update(eou_early_cutoff_metrics) - - metrics['early_cutoff_rate'] = eou_avg_num_early_cutoff - metrics['miss_rate'] = sum(eou_missing) / num_eou_utterances if num_eou_utterances > 0 else 0.0 - - return metrics diff --git a/nemo/collections/asr/parts/utils/eval_utils.py b/nemo/collections/asr/parts/utils/eval_utils.py deleted file mode 100644 index c7d23a214bbca3bd2ef51e311927bee63d7dd91d..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/eval_utils.py +++ /dev/null @@ -1,345 +0,0 @@ -# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import json -import re -from typing import Optional, Tuple, Union - -from torchmetrics.text import SacreBLEUScore -from torchmetrics.text.rouge import ROUGEScore - -from nemo.collections.asr.metrics.wer import word_error_rate_detail -from nemo.utils import logging -from nemo.utils.nemo_logging import LogMode - -TEXT_METRICS_MAPPING = { - 'bleu': SacreBLEUScore, - 'rouge': ROUGEScore, -} - -from omegaconf import DictConfig - - -def flatten_dict_config(config: DictConfig, parent_key='', sep='.', join='\n') -> str: - """ - Flatten a DictConfig object into a string of parameter names and their values. - - Args: - config (DictConfig): The input DictConfig object. - parent_key (str): The parent key for nested configurations. - sep (str): Separator between keys. - - Returns: - str: Flattened string of parameter names and their values. - """ - items = [] - for k, v in config.items(): - new_key = f"{parent_key}{sep}{k}" if parent_key else k - if isinstance(v, DictConfig): - items.extend(flatten_dict_config(v, new_key, sep=sep, join=join).split(join)) - else: - items.append(f"{new_key}={v}") - return join.join(items) - - -def get_hydra_override_from_config(config: Optional[DictConfig] = None, exclude_keys: Optional[list] = None) -> str: - """ - Flatten a DictConfig object into a string of hydra overrides for commandline, for example: - >>> config = OmegaConf.create({"foo": {"bar": 1, "baz": 2}}) - >>> get_hydra_override_from_config(config) - "++foo.bar=1 ++foo.baz=2" - """ - if not config: - return "" - join = '\n' - overrides = flatten_dict_config(config, join=join).split(join) - if exclude_keys: - overrides = [x for x in overrides if not any([y == x.split("=")[0] for y in exclude_keys])] - param_str = " ".join([f"++{x}" for x in overrides]) - return param_str - - -def strip_spaces_before_punctuations(text: str) -> str: - """ - Remove spaces before punctuations, e.g. "hello , world" -> "hello, world" - """ - result = re.sub(r'(\w)\s+([.,;!?])', r'\1\2', text) - return result - - -def remove_punctuations(text: str, punctuations: Optional[Union[list, str]] = None) -> str: - """ - Remove punctuations from a string - """ - if not punctuations: - punctuations = [char for char in '!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~'] - - for punctuation in punctuations: - text = text.replace(punctuation, '') - return text - - -def clean_label(_str: str, num_to_words: bool = True, langid="en") -> str: - """ - Remove unauthorized characters in a string, lower it and remove unneeded spaces - """ - replace_with_space = [char for char in '/?*\",.:=?_{|}~¨«·»¡¿„…‧‹›≪≫!:;ː→'] - replace_with_blank = [char for char in '`¨´‘’“”`ʻ‘’“"‘”'] - replace_with_apos = [char for char in '‘’ʻ‘’‘'] - _str = _str.strip() - _str = _str.lower() - for i in replace_with_blank: - _str = _str.replace(i, "") - for i in replace_with_space: - _str = _str.replace(i, " ") - for i in replace_with_apos: - _str = _str.replace(i, "'") - if num_to_words: - if langid == "en": - _str = convert_num_to_words(_str, langid="en") - else: - logging.warning( - "Currently support basic num_to_words in English only. Please use Text Normalization to convert other languages! Skipping!", - mode=LogMode.ONCE, - ) - - ret = " ".join(_str.split()) - return ret - - -def convert_num_to_words(_str: str, langid: str = "en") -> str: - """ - Convert digits to corresponding words. Note this is a naive approach and could be replaced with text normalization. - """ - if langid == "en": - num_to_words = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] - _str = _str.strip() - words = _str.split() - out_str = "" - num_word = [] - for word in words: - if word.isdigit(): - num = int(word) - while num: - digit = num % 10 - digit_word = num_to_words[digit] - num_word.append(digit_word) - num = int(num / 10) - if not (num): - num_str = "" - num_word = num_word[::-1] - for ele in num_word: - num_str += ele + " " - out_str += num_str + " " - num_word.clear() - else: - out_str += word + " " - out_str = out_str.strip() - else: - logging.warning( - "Currently support basic num_to_words in English only. Please use Text Normalization to convert other languages!", - mode=LogMode.ONCE, - ) - return out_str - - -def cal_write_wer( - pred_manifest: str = None, - gt_text_attr_name: str = "text", - pred_text_attr_name: str = "pred_text", - clean_groundtruth_text: bool = False, - langid: str = 'en', - use_cer: bool = False, - output_filename: str = None, - ignore_capitalization: bool = False, - ignore_punctuation: bool = False, - punctuations: Optional[list] = None, - strip_punc_space: bool = False, -) -> Tuple[str, dict, str]: - """ - Calculate wer, inserion, deletion and substitution rate based on groundtruth text and pred_text_attr_name (pred_text) - We use WER in function name as a convention, but Error Rate (ER) currently support Word Error Rate (WER) and Character Error Rate (CER) - """ - samples = [] - hyps = [] - refs = [] - eval_metric = "cer" if use_cer else "wer" - - with open(pred_manifest, 'r') as fp: - for line in fp.readlines(): - line = line.strip() - if not line: - continue - sample = json.loads(line) - - if gt_text_attr_name not in sample: - if "text" in sample: - gt_text_attr_name = "text" - else: - logging.info( - f"ground-truth text attribute {gt_text_attr_name} is not present in manifest! Cannot calculate WER. Returning!" - ) - return None, None, eval_metric - - hyp = sample[pred_text_attr_name].strip() - ref = sample[gt_text_attr_name].strip() - - if clean_groundtruth_text: - ref = clean_label(ref, langid=langid) - - if ignore_punctuation: - ref = remove_punctuations(ref, punctuations=punctuations) - hyp = remove_punctuations(hyp, punctuations=punctuations) - elif strip_punc_space: - ref = strip_spaces_before_punctuations(ref) - hyp = strip_spaces_before_punctuations(hyp) - - if ignore_capitalization: - ref = ref.lower() - hyp = hyp.lower() - - wer, tokens, ins_rate, del_rate, sub_rate = word_error_rate_detail( - hypotheses=[hyp], references=[ref], use_cer=use_cer - ) - sample[eval_metric] = wer # evaluatin metric, could be word error rate of character error rate - sample['tokens'] = tokens # number of word/characters/tokens - sample['ins_rate'] = ins_rate # insertion error rate - sample['del_rate'] = del_rate # deletion error rate - sample['sub_rate'] = sub_rate # substitution error rate - - samples.append(sample) - hyps.append(hyp) - refs.append(ref) - - total_wer, total_tokens, total_ins_rate, total_del_rate, total_sub_rate = word_error_rate_detail( - hypotheses=hyps, references=refs, use_cer=use_cer - ) - - if not output_filename: - output_manifest_w_wer = pred_manifest - else: - output_manifest_w_wer = output_filename - - with open(output_manifest_w_wer, 'w') as fout: - for sample in samples: - json.dump(sample, fout) - fout.write('\n') - fout.flush() - - total_res = { - "samples": len(samples), - "tokens": total_tokens, - eval_metric: total_wer, - "ins_rate": total_ins_rate, - "del_rate": total_del_rate, - "sub_rate": total_sub_rate, - } - return output_manifest_w_wer, total_res, eval_metric - - -def cal_write_text_metric( - pred_manifest: str = None, - gt_text_attr_name: str = "text", - pred_text_attr_name: str = "pred_text", - output_filename: str = None, - ignore_capitalization: bool = False, - ignore_punctuation: bool = False, - punctuations: Optional[list] = None, - metric: str = 'bleu', - metric_args: Optional[dict] = None, - strip_punc_space: bool = False, -): - samples = [] - hyps = [] - refs = [] - - if metric not in TEXT_METRICS_MAPPING: - raise ValueError(f"metric {metric} is not supported! Please choose from {TEXT_METRICS_MAPPING.keys()}") - - metric_calculator = TEXT_METRICS_MAPPING[metric](**metric_args) if metric_args else TEXT_METRICS_MAPPING[metric]() - with open(pred_manifest, 'r') as fp: - for line in fp.readlines(): - line = line.strip() - if not line: - continue - sample = json.loads(line) - - if gt_text_attr_name not in sample: - if "text" in sample: - gt_text_attr_name = "text" - else: - logging.info( - f"ground-truth text attribute {gt_text_attr_name} is not present in manifest! Cannot calculate {metric}. Returning!" - ) - return None, None, metric - - hyp = sample[pred_text_attr_name].strip() - ref = sample[gt_text_attr_name].strip() - - if ignore_punctuation: - ref = remove_punctuations(ref, punctuations=punctuations) - hyp = remove_punctuations(hyp, punctuations=punctuations) - elif strip_punc_space: - ref = strip_spaces_before_punctuations(ref) - hyp = strip_spaces_before_punctuations(hyp) - - if ignore_capitalization: - ref = ref.lower() - hyp = hyp.lower() - - if metric == 'bleu': - score = metric_calculator([hyp], [[ref]]).item() - else: - score = metric_calculator(hyp, ref).item() - sample[metric] = score # evaluatin metric, could be word error rate of character error rate - - samples.append(sample) - hyps.append(hyp) - refs.append(ref) - - if metric == 'bleu': - refs = [[ref] for ref in refs] - total_score = metric_calculator(hyps, refs).item() - - if not output_filename: - output_manifest_w_wer = pred_manifest - else: - output_manifest_w_wer = output_filename - - with open(output_manifest_w_wer, 'w') as fout: - for sample in samples: - json.dump(sample, fout) - fout.write('\n') - fout.flush() - - total_res = { - "samples": len(samples), - metric: total_score, - } - return output_manifest_w_wer, total_res, metric - - -def compute_laal(delays, source_length, target_length): - if delays[0] > source_length: - return delays[0] - LAAL = 0 - gamma = max(len(delays), target_length) / source_length - tau = 0 - for t_minus_1, d in enumerate(delays): - LAAL += d - t_minus_1 / gamma - tau = t_minus_1 + 1 - if d >= source_length: - break - LAAL /= tau - return LAAL diff --git a/nemo/collections/asr/parts/utils/longform_clustering.py b/nemo/collections/asr/parts/utils/longform_clustering.py deleted file mode 100644 index 171c074d9e10bdc05a734d4fa9ff0a720a3afa1e..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/longform_clustering.py +++ /dev/null @@ -1,422 +0,0 @@ -# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import Dict, List, Tuple -import torch -from tqdm import tqdm -from nemo.collections.asr.parts.utils.offline_clustering import ( - SpeakerClustering, - get_scale_interpolated_embs, - getCosAffinityMatrix, - split_input_data, -) -from nemo.collections.asr.parts.utils.online_clustering import get_merge_quantity, run_reducer - - -class LongFormSpeakerClustering(torch.nn.Module): - def __init__(self, cuda: bool = False): - """ - Initializes a speaker clustering class tailored for long-form audio, leveraging methods from the `SpeakerClustering` class. - The clustering algorithm for long-form content is executed via the `forward_infer` function (not shown here). Input embedding - vectors are divided into chunks, each of size `embeddings_per_chunk`. Within every chunk, the clustering algorithm aims - to identify `chunk_cluster_count` distinct clusters. The resulting clustering labels are then expanded to match the original - length of the input embeddings. - - NOTE: torch.jit.script currently does not support inherited methods with a `super()` call. - - Args: - cuda (bool): - Flag indicating whether CUDA is available for computation. - """ - super().__init__() - self.speaker_clustering = SpeakerClustering(cuda=cuda) - self.embeddings_in_scales: List[torch.Tensor] = [torch.tensor([0])] - self.timestamps_in_scales: List[torch.Tensor] = [torch.tensor([0])] - self.cuda = cuda - self.device = torch.device("cuda") if self.cuda else torch.device("cpu") - - def check_input(self, embeddings_per_chunk: int, chunk_cluster_count: int, max_num_speakers: int) -> None: - """ - Checks the validity of the input parameters. - - Args: - embeddings_per_chunk (int): - The size of the windows in which the algorithm aims to identify `chunk_cluster_count` clusters. - chunk_cluster_count (int): - The target number of clusters to identify within each window. - max_num_speakers (int): - The maximum number of speakers to be detected in the audio. - """ - if chunk_cluster_count is None or embeddings_per_chunk is None: - raise ValueError( - f"chunk_cluster_count ({chunk_cluster_count}) and embeddings_per_chunk ({embeddings_per_chunk}) should be set." - ) - elif ( - all(v is not None for v in [chunk_cluster_count, embeddings_per_chunk]) - and chunk_cluster_count >= embeddings_per_chunk - ): - raise ValueError( - f"chunk_cluster_count ({chunk_cluster_count}) should be smaller than embeddings_per_chunk ({embeddings_per_chunk})." - ) - - if chunk_cluster_count <= max_num_speakers: - raise ValueError( - f"chunk_cluster_count ({chunk_cluster_count}) should be larger than max_num_speakers ({max_num_speakers})." - ) - - def unpack_labels( - self, - Y_aggr: torch.Tensor, - window_range_list: List[List[int]], - absolute_merge_mapping: List[List[torch.Tensor]], - org_len: int, - ) -> torch.LongTensor: - """ - Unpack the labels from the aggregated labels to the original labels. - - Args: - Y_aggr (Tensor): - Aggregated label vector from the merged segments. - window_range_list (List[List[int]]): - List of window ranges for each of the merged segments. - absolute_merge_mapping (List[List[torch.Tensor]]): - List of absolute mappings for each of the merged segments. Each list element contains two tensors: - - The first tensor represents the absolute index of the bypassed segment (segments that remain unchanged). - - The second tensor represents the absolute index of the merged segment (segments that have had their indexes changed). - org_len (int): - Original length of the labels. In most cases, this is a fairly large number (on the order of 10^5). - - Returns: - Y_unpack (Tensor): - Unpacked labels derived from the aggregated labels. - """ - Y_unpack = torch.zeros((org_len,)).long().to(Y_aggr.device) - for (win_rng, abs_mapping) in zip(window_range_list, absolute_merge_mapping): - inferred_merged_embs = Y_aggr[win_rng[0] : win_rng[1]] - if len(abs_mapping[1]) > 0: - Y_unpack[abs_mapping[1]] = inferred_merged_embs[-1].clone() # Merged - if len(abs_mapping[0]) > 0: - Y_unpack[abs_mapping[0]] = inferred_merged_embs[:-1].clone() # Bypass - else: - if len(abs_mapping[0]) > 0: - Y_unpack[abs_mapping[0]] = inferred_merged_embs.clone() - return Y_unpack - - def split_embs_to_windows( - self, index: int, emb: torch.Tensor, embeddings_per_chunk: int, - ) -> Tuple[torch.Tensor, int]: - """ - Splits the embedding tensor into smaller window-sized tensors based on a given index. - - Args: - index (int): The index of the desired window. This determines the starting point - of the window using the formula: - start = embeddings_per_chunk * index - emb (Tensor): The embedding tensor which needs to be split. - embeddings_per_chunk (int): - The size of the windows in which the algorithm aims to identify `chunk_cluster_count` clusters. - - Returns: - emb_part (Tensor): - The window-sized tensor, which is a portion of the `emb`. - offset_index (int): - The starting position of the window in the `emb` tensor. - """ - if embeddings_per_chunk * (index + 1) > emb.shape[0]: - emb_part = emb[-1 * embeddings_per_chunk :] - offset_index = emb.shape[0] - embeddings_per_chunk - else: - emb_part = emb[embeddings_per_chunk * index : embeddings_per_chunk * (index + 1)] - offset_index = embeddings_per_chunk * index - return emb_part, offset_index - - def forward(self, param_dict: Dict[str, torch.Tensor]) -> torch.LongTensor: - """ - A function wrapper designed for performing inference using an exported script format. - - Note: - A dictionary is used to facilitate inference with the exported jit model in the Triton server. - This is done using an easy-to-understand naming convention. - See https://github.com/triton-inference-server/server/blob/main/docs/user_guide/model_configuration.md#special-conventions-for-pytorch-backend - - Args: - param_dict (dict): - Dictionary containing the arguments for speaker clustering. - See `forward_infer` function for the argument information. - - Returns: - (LongTensor): Speaker labels for the segments in the given input embeddings. - """ - embeddings_in_scales = param_dict['embeddings'] - timestamps_in_scales = param_dict['timestamps'] - multiscale_segment_counts = param_dict['multiscale_segment_counts'] - multiscale_weights = param_dict['multiscale_weights'] - oracle_num_speakers = int(param_dict['oracle_num_speakers'].item()) - max_num_speakers = int(param_dict['max_num_speakers'].item()) - enhanced_count_thres = int(param_dict['enhanced_count_thres'].item()) - sparse_search_volume = int(param_dict['sparse_search_volume'].item()) - max_rp_threshold = float(param_dict['max_rp_threshold'].item()) - fixed_thres = float(param_dict['fixed_thres'].item()) - return self.forward_infer( - embeddings_in_scales=embeddings_in_scales, - timestamps_in_scales=timestamps_in_scales, - multiscale_segment_counts=multiscale_segment_counts, - multiscale_weights=multiscale_weights, - oracle_num_speakers=oracle_num_speakers, - max_rp_threshold=max_rp_threshold, - max_num_speakers=max_num_speakers, - enhanced_count_thres=enhanced_count_thres, - sparse_search_volume=sparse_search_volume, - fixed_thres=fixed_thres, - ) - - def get_div_ceil_count(self, numer: int, denomin: int) -> int: - """ - Calculates the ceiling of the division of two integers. - - Args: - numer (int): Numerator, the number of segments or clusters, for example. - denomin (int): Denominator, the number of speakers or clusters, for example. - - Returns: - (int): The ceiling of the division of the two integers (number of chunks). - """ - return int(torch.ceil(torch.tensor(numer / denomin)).item()) - - def long_forward_infer( - self, - embeddings_in_scales: torch.Tensor, - timestamps_in_scales: torch.Tensor, - multiscale_segment_counts: torch.LongTensor, - multiscale_weights: torch.Tensor, - oracle_num_speakers: int, - max_rp_threshold: float, - max_num_speakers: int, - sparse_search_volume: int, - fixed_thres: float, - chunk_cluster_count: int, - embeddings_per_chunk: int, - ) -> torch.LongTensor: - """ - This is forward function for long-form speaker clustering. - Please refer to `SpeakerClustering` class for the original argument information. - - In the `LongFormSpeakerClustering` process: - Step-1: Input embeddings are divided into smaller windows of size `embeddings_per_chunk`. - Step-2: Each window undergoes overclustering, resulting in `chunk_cluster_count` fine-grained clusters. - Step-3: These fine-grained clusters are merged to form the aggregated clustering labels `Y_aggr`. - Step-4: The `unpack_labels` function is then employed to map the aggregated labels `Y_aggr` back to the - original labels for all `org_len` input embeddings: `Y_unpack`. - - Args: - embeddings_in_scales (Tensor): - List containing concatenated Torch tensor embeddings across multiple scales. - The length of the list is equal to the number of scales. - Each tensor has dimensions of (Number of base segments) x (Embedding Dimension). - timestamps_in_scales (Tensor): - List containing concatenated Torch tensor timestamps across multiple scales. - The length of the list is equal to the number of scales. - Each tensor has dimensions of (Total number of segments across all scales) x 2. - Example: - >>> timestamps_in_scales[0] = \ - torch.Tensor([[0.4, 1.4], [0.9, 1.9], [1.4, 2.4], ... [121.2, 122.2]]) - multiscale_segment_counts (LongTensor): - A Torch tensor containing the number of segments for each scale. - The tensor has dimensions of (Number of scales). - Example: - >>> multiscale_segment_counts = torch.LongTensor([31, 52, 84, 105, 120]) - multiscale_weights (Tensor): - Multi-scale weights used when merging affinity scores. - Example: - >>> multiscale_weights = torch.tensor([1.4, 1.3, 1.2, 1.1, 1.0]) - oracle_num_speakers (int): - The number of speakers in a session as given by the reference transcript. - max_num_speakers (int): - The upper bound for the number of speakers in each session. - max_rp_threshold (float): - Limits the range of parameter search. - The clustering performance can vary based on this range. - The default value is 0.15. - enhanced_count_thres (int): - For shorter audio recordings, the clustering algorithm might not accumulate enough speaker profiles for each cluster. - Thus, the function `getEnhancedSpeakerCount` uses anchor embeddings (dummy representations) to mitigate the effects of cluster sparsity. - A value of 80 is recommended for `enhanced_count_thres`. - sparse_search_volume (int): - The number of p_values considered during NME analysis. - The default is 30. Lower values speed up the NME-analysis but might lead to poorer parameter estimations. Values below 20 are not recommended. - fixed_thres (float): - If a `fixed_thres` value is provided, the NME-analysis process will be skipped. - This value should be optimized on a development set for best results. - By default, it is set to -1.0, and the function performs NME-analysis to estimate the threshold. - kmeans_random_trials (int): - The number of random trials for initializing k-means clustering. More trials can result in more stable clustering. The default is 1. - chunk_cluster_count (int): - The target number of clusters to identify within each chunk. - embeddings_per_chunk (int): - The size of the chunks in which the algorithm aims to identify `chunk_cluster_count` clusters. - - Returns: - Y_unpack (LongTensor): - Speaker labels for the segments in the provided input embeddings. - """ - self.check_input(embeddings_per_chunk, chunk_cluster_count, max_num_speakers) - - self.embeddings_in_scales, self.timestamps_in_scales = split_input_data( - embeddings_in_scales, timestamps_in_scales, multiscale_segment_counts - ) - emb, _ = get_scale_interpolated_embs( - multiscale_weights, self.embeddings_in_scales, self.timestamps_in_scales, self.device - ) - offset_index: int = 0 - window_offset: int = 0 - total_emb: List[torch.Tensor] = [] - window_range_list: List[List[int]] = [] - absolute_merge_mapping: List[List[torch.Tensor]] = [] - total_window_count = self.get_div_ceil_count(numer=emb.shape[0], denomin=embeddings_per_chunk) - - if not torch.jit.is_scripting(): - pbar = tqdm(range(total_window_count), desc="Clustering Sub-Windows", leave=True, unit="window") - else: - pbar = range(total_window_count) - - for win_index in pbar: - # Step-1: Split the embeddings into smaller chunks - emb_part, offset_index = self.split_embs_to_windows( - index=win_index, emb=emb, embeddings_per_chunk=embeddings_per_chunk - ) - - # Step-2: Perform overclustering on the chunks to identify `chunk_cluster_count` clusters - if emb_part.shape[0] == 1: - Y_part = torch.zeros((1,), dtype=torch.int64) - else: - mat = getCosAffinityMatrix(emb_part) - overcluster_count = min(chunk_cluster_count, mat.shape[0]) - Y_part = self.speaker_clustering.forward_unit_infer( - mat=mat, - oracle_num_speakers=overcluster_count, - max_rp_threshold=max_rp_threshold, - max_num_speakers=chunk_cluster_count, - sparse_search_volume=sparse_search_volume, - ) - - # Step-3: Merge the clusters to form the aggregated clustering labels `Y_aggr` - num_to_be_merged = int(min(embeddings_per_chunk, emb_part.shape[0]) - chunk_cluster_count) - min_count_per_cluster = self.get_div_ceil_count( - numer=chunk_cluster_count, denomin=len(torch.unique(Y_part)) - ) - - # We want only one embedding vector for each cluster, so we calculate the number of embedding vectors to be removed - class_target_vol = get_merge_quantity( - num_to_be_removed=num_to_be_merged, - pre_clus_labels=Y_part, - min_count_per_cluster=min_count_per_cluster, - ) - if not torch.jit.is_scripting(): - pbar.update(1) - - # `class_target_vol` is a list of cluster-indices from overclustering - for spk_idx, merge_quantity in enumerate(list(class_target_vol)): - merged_embs, merged_clus_labels, index_mapping = run_reducer( - pre_embs=emb_part, target_spk_idx=spk_idx, merge_quantity=merge_quantity, pre_clus_labels=Y_part, - ) - total_emb.append(merged_embs) - absolute_index_mapping = [x + offset_index for x in index_mapping] - absolute_merge_mapping.append(absolute_index_mapping) - window_range_list.append([window_offset, window_offset + merged_embs.shape[0]]) - window_offset += merged_embs.shape[0] - - if not torch.jit.is_scripting(): - pbar.close() - - # Concatenate the reduced embeddings then perform high-level clustering - reduced_embs = torch.cat(total_emb) - reduced_mat = getCosAffinityMatrix(reduced_embs) - - # Step-4: Map the aggregated labels `Y_aggr` back to the original labels for all `org_len` input embeddings: `Y_unpack` - Y_aggr = self.speaker_clustering.forward_unit_infer( - mat=reduced_mat, - oracle_num_speakers=oracle_num_speakers, - max_rp_threshold=max_rp_threshold, - max_num_speakers=max_num_speakers, - sparse_search_volume=sparse_search_volume, - fixed_thres=fixed_thres, - ) - if reduced_embs.shape[0] != Y_aggr.shape[0]: - raise ValueError( - f"The number of embeddings ({reduced_embs.shape[0]}) and the number of clustered labels ({Y_aggr.shape[0]}) do not match." - ) - - # Reassign the labels to the original embeddings - Y_unpack = self.unpack_labels( - Y_aggr=Y_aggr, - window_range_list=window_range_list, - absolute_merge_mapping=absolute_merge_mapping, - org_len=emb.shape[0], - ) - if Y_unpack.shape[0] != emb.shape[0]: - raise ValueError( - f"The number of raw input embeddings ({emb.shape[0]}) and the number of clustered labels ({Y_unpack.shape[0]}) do not match." - ) - return Y_unpack - - def forward_infer( - self, - embeddings_in_scales: torch.Tensor, - timestamps_in_scales: torch.Tensor, - multiscale_segment_counts: torch.LongTensor, - multiscale_weights: torch.Tensor, - oracle_num_speakers: int = -1, - max_rp_threshold: float = 0.15, - max_num_speakers: int = 8, - enhanced_count_thres: int = 80, - sparse_search_volume: int = 30, - fixed_thres: float = -1.0, - chunk_cluster_count: int = 50, - embeddings_per_chunk: int = 10000, - ) -> torch.LongTensor: - """ - This function is a wrapper designed for toggling between long-form and short-form speaker clustering. - The details of short-form clustering is in `SpeakerClustering` class. - NOTE: `torch.jit.script` currently does not support `**kwargs` in the function signature therefore, - we need to use a wrapper function to handle the arguments. - """ - if embeddings_per_chunk is not None and torch.max(multiscale_segment_counts) > embeddings_per_chunk: - return self.long_forward_infer( - embeddings_in_scales=embeddings_in_scales, - timestamps_in_scales=timestamps_in_scales, - multiscale_segment_counts=multiscale_segment_counts, - multiscale_weights=multiscale_weights, - oracle_num_speakers=oracle_num_speakers, - max_rp_threshold=max_rp_threshold, - max_num_speakers=max_num_speakers, - sparse_search_volume=sparse_search_volume, - fixed_thres=fixed_thres, - chunk_cluster_count=chunk_cluster_count, - embeddings_per_chunk=embeddings_per_chunk, - ) - else: - cluster_labels = self.speaker_clustering.forward_infer( - embeddings_in_scales=embeddings_in_scales, - timestamps_in_scales=timestamps_in_scales, - multiscale_segment_counts=multiscale_segment_counts, - multiscale_weights=multiscale_weights, - oracle_num_speakers=oracle_num_speakers, - max_rp_threshold=max_rp_threshold, - max_num_speakers=max_num_speakers, - enhanced_count_thres=enhanced_count_thres, - sparse_search_volume=sparse_search_volume, - fixed_thres=fixed_thres, - ) - self.timestamps_in_scales = self.speaker_clustering.timestamps_in_scales - return cluster_labels diff --git a/nemo/collections/asr/parts/utils/manifest_utils.py b/nemo/collections/asr/parts/utils/manifest_utils.py deleted file mode 100644 index 6cd53136046e8fdead63dee696a42be567e2846d..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/manifest_utils.py +++ /dev/null @@ -1,574 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import json -import os -from collections import Counter -from collections import OrderedDict as od -from pathlib import Path -from typing import Dict, List, Union - -import librosa -import numpy as np - -from nemo.collections.asr.parts.utils.speaker_utils import ( - audio_rttm_map, - get_subsegments_scriptable, - get_uniqname_from_filepath, - rttm_to_labels, - segments_manifest_to_subsegments_manifest, - write_rttm2manifest, -) -from nemo.utils import logging -from nemo.utils.data_utils import DataStoreObject - - -def get_rounded_str_float(num: float, output_precision: int, min_precision=1, max_precision=3) -> str: - """ - Get a string of a float number with rounded precision. - - Args: - num (float): float number to round - output_precision (int): precision of the output floating point number - min_precision (int, optional): Minimum precision of the output floating point number. Defaults to 1. - max_precision (int, optional): Maximum precision of the output floating point number. Defaults to 3. - - Returns: - (str): Return a string of a float number with rounded precision. - """ - output_precision = min(max_precision, max(min_precision, output_precision)) - return f"{num:.{output_precision}f}" - - -def get_ctm_line( - source: str, - channel: int, - start_time: float, - duration: float, - token: str, - conf: float, - type_of_token: str, - speaker: str, - NA_token: str = 'NA', - UNK: str = 'unknown', - default_channel: str = '1', - output_precision: int = 2, -) -> str: - """ - Get a line in Conversation Time Mark (CTM) format. Following CTM format appeared in - `Rich Transcription Meeting Eval Plan: RT09` document. - - CTM Format: - - - Reference: - https://web.archive.org/web/20170119114252/ - http://www.itl.nist.gov/iad/mig/tests/rt/2009/docs/rt09-meeting-eval-plan-v2.pdf - - Args: - source (str): is name of the source file, session name or utterance ID - channel (int): is channel number defaults to 1 - start_time (float): is the begin time of the word, which we refer to as `start_time` in NeMo. - duration (float): is duration of the word - token (str): Token or word for the current entry - conf (float): is a floating point number between 0 (no confidence) and 1 (certainty). - A value of “NA” is used (in CTM format data) - when no confidence is computed and in the reference data. - type_of_token (str): is the token type. The legal values of are - “lex”, “frag”, “fp”, “un-lex”, “for-lex”, “non-lex”, “misc”, or “noscore” - speaker (str): is a string identifier for the speaker who uttered the token. - This should be “null” for non-speech tokens and “unknown” when - the speaker has not been determined. - NA_token (str, optional): A token for . Defaults to ''. - output_precision (int, optional): The precision of the output floating point number. Defaults to 3. - - Returns: - str: Return a line in CTM format filled with the given information. - """ - VALID_TOKEN_TYPES = ["lex", "frag", "fp", "un-lex", "for-lex", "non-lex", "misc", "noscore"] - - if type(start_time) == str and start_time.replace('.', '', 1).isdigit(): - start_time = float(start_time) - elif type(start_time) != float: - raise ValueError(f"`start_time` must be a float or str containing float, but got {type(start_time)}") - - if type(duration) == str and duration.replace('.', '', 1).isdigit(): - duration = float(duration) - elif type(duration) != float: - raise ValueError(f"`duration` must be a float or str containing float, but got {type(duration)}") - - if type(conf) == str and conf.replace('.', '', 1).isdigit(): - conf = float(conf) - elif conf is None: - conf = NA_token - elif type(conf) != float: - raise ValueError(f"`conf` must be a float or str containing float, but got {type(conf)}") - - if channel is not None and type(channel) != int: - channel = str(channel) - if conf is not None and type(conf) == float and not (0 <= conf <= 1): - raise ValueError(f"`conf` must be between 0 and 1, but got {conf}") - if type_of_token is not None and type(type_of_token) != str: - raise ValueError(f"`type` must be a string, but got {type(type_of_token)} type {type_of_token}") - if type_of_token is not None and type_of_token not in VALID_TOKEN_TYPES: - raise ValueError(f"`type` must be one of {VALID_TOKEN_TYPES}, but got {type_of_token} type {type_of_token}") - if speaker is not None and type(speaker) != str: - raise ValueError(f"`speaker` must be a string, but got {type(speaker)}") - - channel = default_channel if channel is None else channel - conf = NA_token if conf is None else conf - speaker = NA_token if speaker is None else speaker - type_of_token = UNK if type_of_token is None else type_of_token - start_time = get_rounded_str_float(start_time, output_precision) - duration = get_rounded_str_float(duration, output_precision) - conf = get_rounded_str_float(conf, output_precision) if conf != NA_token else conf - return f"{source} {channel} {start_time} {duration} {token} {conf} {type_of_token} {speaker}\n" - - -def rreplace(s: str, old: str, new: str) -> str: - """ - Replace end of string. - - Args: - s (str): string to operate on - old (str): ending of string to replace - new (str): replacement for ending of string - Returns: - new.join(li) (string): new string with end replaced - """ - li = s.rsplit(old, 1) - return new.join(li) - - -def get_uniq_id_with_period(path: str) -> str: - """ - Get uniq_id from path string with period in it. - - Args: - path (str): path to audio file - Returns: - uniq_id (str): unique speaker ID - """ - split_path = os.path.basename(path).split('.')[:-1] - uniq_id = '.'.join(split_path) if len(split_path) > 1 else split_path[0] - return uniq_id - - -def get_subsegment_dict(subsegments_manifest_file: str, window: float, shift: float, deci: int) -> Dict[str, dict]: - """ - Get subsegment dictionary from manifest file. - - Args: - subsegments_manifest_file (str): Path to subsegment manifest file - window (float): Window length for segmentation - shift (float): Shift length for segmentation - deci (int): Rounding number of decimal places - Returns: - _subsegment_dict (dict): Subsegment dictionary - """ - _subsegment_dict = {} - with open(subsegments_manifest_file, 'r') as subsegments_manifest: - segments = subsegments_manifest.readlines() - for segment in segments: - segment = segment.strip() - dic = json.loads(segment) - audio, offset, duration = dic['audio_filepath'], dic['offset'], dic['duration'] - subsegments = get_subsegments_scriptable(offset=offset, window=window, shift=shift, duration=duration) - if dic['uniq_id'] is not None: - uniq_id = dic['uniq_id'] - else: - uniq_id = get_uniq_id_with_period(audio) - if uniq_id not in _subsegment_dict: - _subsegment_dict[uniq_id] = {'ts': [], 'json_dic': []} - for subsegment in subsegments: - start, dur = subsegment - _subsegment_dict[uniq_id]['ts'].append([round(start, deci), round(start + dur, deci)]) - _subsegment_dict[uniq_id]['json_dic'].append(dic) - return _subsegment_dict - - -def get_input_manifest_dict(input_manifest_path: str) -> Dict[str, dict]: - """ - Get dictionary from manifest file. - - Args: - input_manifest_path (str): Path to manifest file - Returns: - input_manifest_dict (dict): Dictionary from manifest file - """ - input_manifest_dict = {} - with open(input_manifest_path, 'r') as input_manifest_fp: - json_lines = input_manifest_fp.readlines() - for json_line in json_lines: - dic = json.loads(json_line) - dic["text"] = "-" - uniq_id = get_uniqname_from_filepath(dic["audio_filepath"]) - input_manifest_dict[uniq_id] = dic - return input_manifest_dict - - -def write_truncated_subsegments( - input_manifest_dict: Dict[str, dict], - _subsegment_dict: Dict[str, dict], - output_manifest_path: str, - step_count: int, - deci: int, -): - """ - Write subsegments to manifest filepath. - - Args: - input_manifest_dict (dict): Input manifest dictionary - _subsegment_dict (dict): Input subsegment dictionary - output_manifest_path (str): Path to output manifest file - step_count (int): Number of the unit segments you want to create per utterance - deci (int): Rounding number of decimal places - """ - with open(output_manifest_path, 'w') as output_manifest_fp: - for uniq_id, subseg_dict in _subsegment_dict.items(): - subseg_array = np.array(subseg_dict['ts']) - subseg_array_idx = np.argsort(subseg_array, axis=0) - chunked_set_count = subseg_array_idx.shape[0] // step_count - - for idx in range(chunked_set_count - 1): - chunk_index_stt = subseg_array_idx[:, 0][idx * step_count] - chunk_index_end = subseg_array_idx[:, 1][(idx + 1) * step_count] - offset_sec = subseg_array[chunk_index_stt, 0] - end_sec = subseg_array[chunk_index_end, 1] - dur = round(end_sec - offset_sec, deci) - meta = input_manifest_dict[uniq_id] - meta['offset'] = offset_sec - meta['duration'] = dur - json.dump(meta, output_manifest_fp) - output_manifest_fp.write("\n") - - -def write_file(name: str, lines: List[dict], idx: int): - """ - Write json lines to file. - - Args: - name (str): Output file path - lines (list): List of json lines - idx (int): Indices to dump to the file - """ - with open(name, 'w') as fout: - for i in idx: - dic = lines[i] - json.dump(dic, fout) - fout.write('\n') - - -def read_file(pathlist: str) -> List[str]: - """ - Read list of lines from target file. - - Args: - pathlist (str): Input file path - Returns: - sorted(pathlist) (list): List of lines - """ - with open(pathlist, 'r') as f: - pathlist = f.readlines() - return sorted(pathlist) - - -def get_dict_from_wavlist(pathlist: List[str]) -> Dict[str, str]: - """ - Read dictionaries from list of lines - - Args: - pathlist (list): List of file paths - Returns: - path_dict (dict): Dictionary containing dictionaries read from files - """ - path_dict = od() - pathlist = sorted(pathlist) - for line_path in pathlist: - uniq_id = os.path.basename(line_path).split('.')[0] - path_dict[uniq_id] = line_path - return path_dict - - -def get_dict_from_list(data_pathlist: List[str], uniqids: List[str]) -> Dict[str, str]: - """ - Create dictionaries from list of lines - - Args: - data_pathlist (list): List of file paths - uniqids (list): List of file IDs - Returns: - path_dict (dict): Dictionary containing file paths - """ - path_dict = {} - for line_path in data_pathlist: - uniq_id = os.path.basename(line_path).split('.')[0] - if uniq_id in uniqids: - path_dict[uniq_id] = line_path - else: - raise ValueError(f'uniq id {uniq_id} is not in wav filelist') - return path_dict - - -def get_path_dict(data_path: str, uniqids: List[str], len_wavs: int = None) -> Dict[str, str]: - """ - Create dictionary from list of lines (using the get_dict_from_list function) - - Args: - data_path (str): Path to file containing list of files - uniqids (list): List of file IDs - len_wavs (int): Length of file list - Returns: - data_pathdict (dict): Dictionary containing file paths - """ - if data_path is not None: - data_pathlist = read_file(data_path) - if len_wavs is not None: - assert len(data_pathlist) == len_wavs - data_pathdict = get_dict_from_list(data_pathlist, uniqids) - elif len_wavs is not None: - data_pathdict = {uniq_id: None for uniq_id in uniqids} - return data_pathdict - - -def create_segment_manifest( - input_manifest_path: str, output_manifest_path: str, window: float, shift: float, step_count: int, deci: int -): - """ - Create segmented manifest file from base manifest file - - Args: - input_manifest_path (str): Path to input manifest file - output_manifest_path (str): Path to output manifest file - window (float): Window length for segmentation - shift (float): Shift length for segmentation - step_count (int): Number of the unit segments you want to create per utterance - deci (int): Rounding number of decimal places - """ - if '.json' not in input_manifest_path: - raise ValueError("input_manifest_path file should be .json file format") - if output_manifest_path and '.json' not in output_manifest_path: - raise ValueError("output_manifest_path file should be .json file format") - elif not output_manifest_path: - output_manifest_path = rreplace(input_manifest_path, '.json', f'_{step_count}seg.json') - - input_manifest_dict = get_input_manifest_dict(input_manifest_path) - segment_manifest_path = rreplace(input_manifest_path, '.json', '_seg.json') - subsegment_manifest_path = rreplace(input_manifest_path, '.json', '_subseg.json') - min_subsegment_duration = 0.05 - step_count = int(step_count) - - AUDIO_RTTM_MAP = audio_rttm_map(input_manifest_path) - segments_manifest_file = write_rttm2manifest(AUDIO_RTTM_MAP, segment_manifest_path, deci) - subsegments_manifest_file = subsegment_manifest_path - segments_manifest_to_subsegments_manifest( - segments_manifest_file, - subsegments_manifest_file, - window, - shift, - min_subsegment_duration, - ) - subsegments_dict = get_subsegment_dict(subsegments_manifest_file, window, shift, deci) - write_truncated_subsegments(input_manifest_dict, subsegments_dict, output_manifest_path, step_count, deci) - os.remove(segment_manifest_path) - os.remove(subsegment_manifest_path) - - -def create_manifest( - wav_path: str, - manifest_filepath: str, - text_path: str = None, - rttm_path: str = None, - uem_path: str = None, - ctm_path: str = None, - add_duration: bool = False, -): - """ - Create base manifest file - - Args: - wav_path (str): Path to list of wav files - manifest_filepath (str): Path to output manifest file - text_path (str): Path to list of text files - rttm_path (str): Path to list of rttm files - uem_path (str): Path to list of uem files - ctm_path (str): Path to list of ctm files - add_duration (bool): Whether to add durations to the manifest file - """ - if os.path.exists(manifest_filepath): - os.remove(manifest_filepath) - wav_pathlist = read_file(wav_path) - wav_pathdict = get_dict_from_wavlist(wav_pathlist) - len_wavs = len(wav_pathlist) - uniqids = sorted(wav_pathdict.keys()) - - text_pathdict = get_path_dict(text_path, uniqids, len_wavs) - rttm_pathdict = get_path_dict(rttm_path, uniqids, len_wavs) - uem_pathdict = get_path_dict(uem_path, uniqids, len_wavs) - ctm_pathdict = get_path_dict(ctm_path, uniqids, len_wavs) - - lines = [] - for uid in uniqids: - wav, text, rttm, uem, ctm = ( - wav_pathdict[uid], - text_pathdict[uid], - rttm_pathdict[uid], - uem_pathdict[uid], - ctm_pathdict[uid], - ) - - audio_line = wav.strip() - if rttm is not None: - rttm = rttm.strip() - labels = rttm_to_labels(rttm) - num_speakers = Counter([label.split()[-1] for label in labels]).keys().__len__() - else: - num_speakers = None - - if uem is not None: - uem = uem.strip() - - if text is not None: - with open(text.strip()) as f: - text = f.readlines()[0].strip() - else: - text = "-" - - if ctm is not None: - ctm = ctm.strip() - - duration = None - if add_duration: - y, sr = librosa.load(audio_line, sr=None) - duration = librosa.get_duration(y=y, sr=sr) - meta = [ - { - "audio_filepath": audio_line, - "offset": 0, - "duration": duration, - "label": "infer", - "text": text, - "num_speakers": num_speakers, - "rttm_filepath": rttm, - "uem_filepath": uem, - "ctm_filepath": ctm, - } - ] - lines.extend(meta) - - write_file(manifest_filepath, lines, range(len(lines))) - - -def read_manifest(manifest: Union[Path, str]) -> List[dict]: - """ - Read manifest file - - Args: - manifest (str or Path): Path to manifest file - Returns: - data (list): List of JSON items - """ - manifest = DataStoreObject(str(manifest)) - - data = [] - try: - f = open(manifest.get(), 'r', encoding='utf-8') - except: - raise Exception(f"Manifest file could not be opened: {manifest}") - - errors = [] - for line in f.readlines(): - line = line.strip() - if not line: - continue - try: - item = json.loads(line) - except json.JSONDecodeError: - errors.append(line) - continue - data.append(item) - f.close() - if errors: - logging.error(f"{len(errors)} Errors encountered while reading manifest file: {manifest}") - for error in errors: - logging.error(f"-- Failed to parse line: `{error}`") - raise RuntimeError(f"Errors encountered while reading manifest file: {manifest}") - return data - - -def write_manifest(output_path: Union[Path, str], target_manifest: List[dict], ensure_ascii: bool = True): - """ - Write to manifest file - - Args: - output_path (str or Path): Path to output manifest file - target_manifest (list): List of manifest file entries - ensure_ascii (bool): default is True, meaning the output is guaranteed to have all incoming - non-ASCII characters escaped. If ensure_ascii is false, these characters - will be output as-is. - """ - with open(output_path, "w", encoding="utf-8") as outfile: - for tgt in target_manifest: - json.dump(tgt, outfile, ensure_ascii=ensure_ascii) - outfile.write('\n') - - -def write_ctm(output_path: str, target_ctm: Dict[str, dict]): - """ - Write ctm entries from diarization session to a .ctm file. - - Args: - output_path (str): target file path - target_ctm (dict): list of ctm entries - """ - target_ctm.sort(key=lambda y: y[0]) - with open(output_path, "w") as outfile: - for pair in target_ctm: - tgt = pair[1] - outfile.write(tgt) - - -def write_text(output_path: str, target_ctm: Dict[str, dict]): - """ - Write text from diarization session to a .txt file - - Args: - output_path (str): target file path - target_ctm (dict): list of ctm entries - """ - target_ctm.sort(key=lambda y: y[0]) - with open(output_path, "w") as outfile: - for pair in target_ctm: - tgt = pair[1] - word = tgt.split(' ')[4] - outfile.write(word + ' ') - outfile.write('\n') - - -def filepath_to_absolute(filepath: str | Path, base_path: Path) -> Path: - """ - Return absolute path to an audio file. - - Check if a file exists at `filepath`. - If not, assume that the path is relative to `base_path`. - - Args: - filepath (str or Path): path to file - base_path (Path): base path to resolve relative path - """ - filepath = Path(filepath).expanduser() - - if not filepath.is_file() and not filepath.is_absolute(): - filepath = (base_path / filepath).absolute() - return filepath diff --git a/nemo/collections/asr/parts/utils/multispk_transcribe_utils.py b/nemo/collections/asr/parts/utils/multispk_transcribe_utils.py deleted file mode 100644 index 291705a54f1e84de2f3990064876ab51d4159fc6..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/multispk_transcribe_utils.py +++ /dev/null @@ -1,1921 +0,0 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import itertools -import json -import math -import os -import time -from collections import OrderedDict -from copy import deepcopy -from functools import wraps -from typing import Any, Dict, List, Optional, Tuple - -import torch -from lhotse.dataset.collation import collate_matrices -from omegaconf import DictConfig - -from nemo.collections.asr.data.audio_to_diar_label import extract_frame_info_from_rttm, get_frame_targets_from_rttm -from nemo.collections.asr.models.sortformer_diar_models import SortformerEncLabelModel -from nemo.collections.asr.modules.sortformer_modules import StreamingSortformerState -from nemo.collections.asr.parts.utils.diarization_utils import get_color_palette, print_sentences, write_txt -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis -from nemo.collections.asr.parts.utils.speaker_utils import audio_rttm_map as get_audio_rttm_map -from nemo.collections.asr.parts.utils.speaker_utils import get_uniqname_from_filepath -from nemo.utils import logging - - -def measure_eta(func): - """ - Measure the time taken to execute the function and print the ETA. - - Args: - func (callable): The function to measure the ETA of. - - Returns: - callable: The wrapped function. - """ - - @wraps(func) - def wrapper(*args, **kwargs): - start_time = time.time() # Record the start time - result = func(*args, **kwargs) # Execute the function - end_time = time.time() # Record the end time - eta = end_time - start_time # Calculate the elapsed time - logging.info(f"[ Step-{kwargs['step_num']} ] for '{func.__name__}': {eta:.4f} seconds") # Print the ETA - return result # Return the original function's result - - return wrapper - - -def format_time(seconds: float) -> str: - """ - Format the time in minutes and seconds. - - Args: - seconds (float): The time in seconds. - - Returns: - str: The time in minutes and seconds. - """ - minutes = math.floor(seconds / 60) - sec = seconds % 60 - return f"{minutes}:{sec:05.2f}" - - -def add_delay_for_real_time( - cfg: Any, - chunk_audio: torch.Tensor, - session_start_time: float, - feat_frame_count: int, - loop_end_time: float, - loop_start_time: float, -): - """ - Add artificial delay for real-time mode by calculating the time difference between - the current time and the session start time.. - - Args: - cfg (Any): The configuration object containing the parameters for the delay calculation. - chunk_audio (torch.Tensor): The chunk audio tensor containing time-series audio data. - session_start_time (float): The session start time in seconds. - feat_frame_count (int): The number of features per second. - loop_end_time (float): The loop end time in seconds. - loop_start_time (float): The loop start time in seconds. - """ - time_diff = max(0, (time.time() - session_start_time) - feat_frame_count * cfg.get("feat_len_sec", 0.01)) - eta_min_sec = format_time(time.time() - session_start_time) - logging.info( - f"[ REAL TIME MODE ] min:sec - {eta_min_sec} " - f"Time difference for real-time mode: {time_diff:.4f} seconds" - ) - time.sleep( - max( - 0, - (chunk_audio.shape[-1] - cfg.get("discarded_frames", 8)) * cfg.get("feat_len_sec", 0.01) - - (loop_end_time - loop_start_time) - - time_diff * cfg.get("finetune_realtime_ratio", 0.01), - ) - ) - - -def write_seglst_file(seglst_dict_list: List[Dict[str, Any]], output_path: str): - """ - Write a seglst file from the seglst dictionary list. - - Args: - seglst_dict_list (List[Dict[str, Any]]): The list of seglst dictionaries. - Example: - [ - { - "session_id": "session_001", - "speaker": "speaker_1", - "words": "Write this to a SegLST file.", - "start_time": 12.34, - "end_time": 23.45, - }, ... - ] - output_path (str): The path to the output file. - """ - if len(seglst_dict_list) == 0: - raise ValueError("seglst_dict_list is empty. No transcriptions were generated.") - with open(output_path, 'w', encoding='utf-8') as f: - f.write(json.dumps(seglst_dict_list, indent=4) + '\n') - logging.info(f"Saved the transcriptions of the streaming inference in\n:{output_path}") - - -def get_multi_talker_samples_from_manifest(cfg, manifest_file: str, feat_per_sec: float, max_spks: int): - """ - Get the multi-talker samples from the manifest file and save it to a list named 'samples'. - Also, save the rttm mask matrix to a list named 'rttms_mask_mats'. - - Args: - cfg (DictConfig): The configuration object. - manifest_file (str): The path to the manifest file. - feat_per_sec (float): The number of features per second. - max_spks (int): The maximum number of speakers. - - Returns: - samples (list): The list of samples. - rttms_mask_mats (list): The list of rttm mask matrices. - """ - samples, rttms_mask_mats = [], [] - with open(manifest_file, 'r', encoding='utf-8') as f: - for line_num, line in enumerate(f): - item = json.loads(line) - if 'audio_filepath' not in item: - raise KeyError(f"Line {line_num}: 'audio_filepath' missing") - if 'duration' not in item: - raise KeyError(f"Line {line_num}: 'duration' missing") - samples.append(item) - if cfg.get("spk_supervision", "diar") == "rttm": - rttm_path = samples[-1]['rttm_filepath'] - if not rttm_path: - raise ValueError(f"Line {line_num}: rttm_filepath required when spk_supervision='rttm'") - if not os.path.exists(rttm_path): - raise FileNotFoundError(f"Line {line_num}: RTTM file not found: {rttm_path}") - - with open(rttm_path, 'r', encoding='utf-8') as f: - rttm_lines = f.readlines() - rttm_timestamps, _ = extract_frame_info_from_rttm(0, samples[-1]['duration'], rttm_lines) - rttm_mat = get_frame_targets_from_rttm( - rttm_timestamps=rttm_timestamps, - offset=0, - duration=samples[-1]['duration'], - round_digits=3, - feat_per_sec=round(float(1 / feat_per_sec), 2), - max_spks=max_spks, - ) - rttms_mask_mats.append(rttm_mat) - samples[-1]['duration'] = None - if 'offset' not in item: - samples[-1]['offset'] = 0 - - if len(rttms_mask_mats) > 0: - rttms_mask_mats = collate_matrices(rttms_mask_mats) - else: - rttms_mask_mats = None - return samples, rttms_mask_mats - - -def setup_diarization_model(cfg: DictConfig, map_location: Optional[str] = None) -> SortformerEncLabelModel: - """Setup model from cfg and return diarization model and model name for next step""" - if cfg.diar_model_path.endswith(".ckpt"): - diar_model = SortformerEncLabelModel.load_from_checkpoint( - checkpoint_path=cfg.diar_model_path, map_location=map_location, strict=False - ) - model_name = os.path.splitext(os.path.basename(cfg.diar_model_path))[0] - elif cfg.diar_model_path.endswith(".nemo"): - diar_model = SortformerEncLabelModel.restore_from(restore_path=cfg.diar_model_path, map_location=map_location) - model_name = os.path.splitext(os.path.basename(cfg.diar_model_path))[0] - elif cfg.diar_pretrained_name.startswith("nvidia/"): - diar_model = SortformerEncLabelModel.from_pretrained(cfg.diar_pretrained_name) - model_name = os.path.splitext(os.path.basename(cfg.diar_pretrained_name))[0] - else: - raise ValueError("cfg.diar_model_path must end with.ckpt or.nemo!") - return diar_model, model_name - - -def write_seglst(output_filepath: str, seglst_list: list) -> None: - """ - Write the segmentation list to a file. - - Args: - output_filepath (str): The path to the output file. - seglst_list (list): The list of segmentation lists. - """ - with open(output_filepath, "w", encoding="utf-8") as f: - f.write(json.dumps(seglst_list, indent=2) + "\n") - - -def get_new_sentence_dict( - speaker: str, - start_time: float, - end_time: float, - text: str, - session_id: Optional[str] = None, - decimal: int = 3, -) -> dict: - """ - Get a new SegLST style sentence dictionary variable. - - Args: - speaker (str): The speaker of the sentence. - start_time (float): The start time of the sentence. - end_time (float): The end time of the sentence. - text (str): The text of the sentence. - session_id (Optional[str]): The session id of the sentence. - - Returns: - Dict[str, Any]: A new SegLST style sentence dictionary variable. - """ - # If start_time or end_time is a torch tensor, convert it to a float and round it to 3 decimal places - if isinstance(start_time, torch.Tensor): - start_time = start_time.item() - if isinstance(end_time, torch.Tensor): - end_time = end_time.item() - return { - 'speaker': speaker, - 'start_time': round(start_time, decimal), - 'end_time': round(end_time, decimal), - 'words': text.lstrip(), - 'session_id': session_id, - } - - -def fix_frame_time_step(cfg: Any, new_tokens: List[str], new_words: List[str], frame_inds_seq: List[int]) -> List[int]: - """ - Adjust the frame indices sequence to match the length of new tokens. - - This function handles mismatches between the number of tokens and the frame indices sequence. - It adjusts the frame_inds_seq to ensure it has the same length as new_tokens. - - Args: - cfg (Any): Configuration object containing logging settings. - new_tokens (List[str]): List of new tokens. - new_words (List[str]): List of new words. - frame_inds_seq (List[int]): List of frame indices. - - Returns: - List[int]: Adjusted frame indices sequence. - """ - if len(new_tokens) != len(frame_inds_seq): - # Sometimes there is a mismatch in the number of tokens between the new tokens and the frame indices sequence. - if len(frame_inds_seq) > len(new_words): - # Get unique frame indices sequence - frame_inds_seq = list(OrderedDict.fromkeys(frame_inds_seq)) - if len(frame_inds_seq) < len(new_tokens): - deficit = len(new_tokens) - len(frame_inds_seq) - frame_inds_seq = [frame_inds_seq[0]] * deficit + frame_inds_seq - elif len(frame_inds_seq) > len(new_tokens): - deficit = len(frame_inds_seq) - len(new_tokens) - frame_inds_seq = frame_inds_seq[deficit:] - - elif len(frame_inds_seq) < len(new_tokens): - deficit = len(new_tokens) - len(frame_inds_seq) - frame_inds_seq = [frame_inds_seq[0]] * deficit + frame_inds_seq - if cfg.get("log", True): - logging.warning( - f"Length of new token sequence ({len(new_tokens)}) does not match" - f"the length of frame indices sequence ({len(frame_inds_seq)}). Skipping this chunk." - ) - return frame_inds_seq - - -def get_simulated_softmax(cfg, speaker_sigmoid: torch.Tensor) -> torch.Tensor: - """ - Simulate the softmax operation for speaker diarization. - - Args: - cfg (Any): Configuration object containing diarization settings. - speaker_sigmoid (torch.Tensor): Speaker sigmoid values. - - Returns: - speaker_softmax (torch.Tensor): Speaker softmax values. - """ - if speaker_sigmoid.ndim != 1: - raise ValueError(f"Expected 1D tensor for speaker_sigmoid, got shape {speaker_sigmoid.shape}") - if speaker_sigmoid.shape[0] < cfg.get("max_num_of_spks", 4): - raise ValueError( - f"speaker_sigmoid size {speaker_sigmoid.shape[0]} < max_num_of_spks {cfg.get('max_num_of_spks', 4)}" - ) - - speaker_sigmoid = torch.clamp(speaker_sigmoid, min=cfg.get("min_sigmoid_val", 1e-2), max=1) - sigmoid_sum = speaker_sigmoid.sum() - if sigmoid_sum == 0: - logging.warning("speaker_sigmoid sum is zero, returning uniform distribution") - speaker_softmax = torch.ones_like(speaker_sigmoid) / speaker_sigmoid.shape[0] - else: - speaker_softmax = speaker_sigmoid / sigmoid_sum - speaker_softmax = speaker_softmax.cpu() - speaker_softmax[cfg.get("max_num_of_spks", 4) :] = 0.0 - return speaker_softmax - - -def get_word_dict_content_offline( - cfg: Any, - word: str, - word_index: int, - diar_pred_out: torch.Tensor, - time_stt_end_tuple: Tuple[int], - frame_len: float = 0.08, -) -> Dict[str, Any]: - """ - Generate a dictionary containing word information and speaker diarization results. - - This function processes a single word and its associated tokens to determine - the start and end frames, speaker, and other relevant information. - - Args: - cfg (Any): Configuration object containing diarization settings. - word (str): The word being processed. - word_index (int): Index of the word in the sequence. - diar_pred_out (torch.Tensor): Diarization prediction output stream. - time_stt_end_tuple (int): Local time step offset. - - frame_len (float, optional): Length of each frame in seconds. Defaults to 0.08. - - Returns: - Dict[str, Any]: A dictionary containing word information and diarization results. - """ - frame_stt, frame_end = time_stt_end_tuple - - # Edge Cases: Sometimes, repeated token indexs can lead to incorrect frame and speaker assignment. - if frame_stt == frame_end: - if frame_stt >= diar_pred_out.shape[0] - 1: - frame_stt, frame_end = (diar_pred_out.shape[1] - 1, diar_pred_out.shape[0]) - else: - frame_end = frame_stt + 1 - - # Get the speaker based on the frame-wise softmax probabilities. - stt_p, end_p = max((frame_stt + cfg.get("left_frame_shift", -1)), 0), (frame_end + cfg.get("right_frame_shift", 0)) - speaker_sigmoid = diar_pred_out[stt_p:end_p, :].mean(dim=0) - speaker_softmax = get_simulated_softmax(cfg, speaker_sigmoid) - - speaker_softmax[cfg.get("max_num_of_spks", 4) :] = 0.0 - spk_id = speaker_softmax.argmax().item() - stt_sec, end_sec = frame_stt * frame_len, frame_end * frame_len - word_dict = { - "word": word, - "word_index": word_index, - 'frame_stt': frame_stt, - 'frame_end': frame_end, - 'start_time': round(stt_sec, 3), - 'end_time': round(end_sec, 3), - 'speaker': f"speaker_{spk_id}", - 'speaker_softmax': speaker_softmax, - } - return word_dict - - -def get_word_dict_content_online( - cfg: Any, - word: str, - word_index: int, - diar_pred_out_stream: torch.Tensor, - token_group: List[str], - frame_inds_seq: List[int], - time_step_local_offset: int, - frame_len: float = 0.08, -) -> Dict[str, Any]: - """ - Generate a dictionary containing word information and speaker diarization results. - - This function processes a single word and its associated tokens to determine - the start and end frames, speaker, and other relevant information. - - Args: - cfg (Any): Configuration object containing diarization settings. - word (str): The word being processed. - word_index (int): Index of the word in the sequence. - diar_pred_out_stream (torch.Tensor): Diarization prediction output stream. - Dimensions: (num_frames, max_num_of_spks) - token_group (List[str]): Group of tokens associated with the word. - frame_inds_seq (List[int]): Sequence of frame indices. - time_step_local_offset (int): Local time step offset. - frame_len (float, optional): Length of each frame in seconds. Defaults to 0.08. - - Returns: - Dict[str, Any]: A dictionary containing word information and diarization results. - """ - _stt, _end = time_step_local_offset, time_step_local_offset + len(token_group) - 1 - if len(token_group) == 1: - frame_stt, frame_end = frame_inds_seq[_stt], frame_inds_seq[_stt] + 1 - else: - try: - frame_stt, frame_end = frame_inds_seq[_stt], frame_inds_seq[_end] - except IndexError: - frame_stt, frame_end = frame_inds_seq[_stt], frame_inds_seq[_stt] + 1 - - # Edge Cases: Sometimes, repeated token indexs can lead to incorrect frame and speaker assignment. - if frame_stt == frame_end: - if frame_stt >= diar_pred_out_stream.shape[0] - 1: - frame_stt, frame_end = (diar_pred_out_stream.shape[0] - 1, diar_pred_out_stream.shape[0]) - else: - frame_end = frame_stt + 1 - - # Get the speaker based on the frame-wise softmax probabilities. - stt_p, end_p = max((frame_stt + cfg.get("left_frame_shift", -1)), 0), (frame_end + cfg.get("right_frame_shift", 0)) - speaker_sigmoid = diar_pred_out_stream[stt_p:end_p, :].mean(dim=0) - speaker_softmax = get_simulated_softmax(cfg, speaker_sigmoid) - - speaker_softmax[cfg.get("max_num_of_spks", 4) :] = 0.0 - spk_id = speaker_softmax.argmax().item() - stt_sec, end_sec = frame_stt * frame_len, frame_end * frame_len - word_dict = { - "word": word, - "word_index": word_index, - 'frame_stt': frame_stt, - 'frame_end': frame_end, - 'start_time': round(stt_sec, 3), - 'end_time': round(end_sec, 3), - 'speaker': f"speaker_{spk_id}", - 'speaker_softmax': speaker_softmax, - } - return word_dict - - -def get_multitoken_words( - cfg, word_and_ts_seq: Dict[str, List], word_seq: List[str], new_words: List[str], fix_prev_words_count: int = 5 -) -> Dict[str, List]: - """ - Fix multi-token words that were not fully captured by the previous chunk window. - - This function compares the words in the current sequence with the previously processed words, - and updates any multi-token words that may have been truncated in earlier processing. - - Args: - cfg (DiarizationConfig): Configuration object containing verbose setting. - word_and_ts_seq (Dict[str, List]): Dictionary containing word sequences and timestamps. - word_seq (List[str]): List of all words processed so far. - new_words (List[str]): List of new words in the current chunk. - fix_prev_words_count (int, optional): Number of previous words to check. Defaults to 5. - - Returns: - Dict[str, List]: Updated word_and_ts_seq with fixed multi-token words. - """ - prev_start = max(0, len(word_seq) - fix_prev_words_count - len(new_words)) - prev_end = max(0, len(word_seq) - len(new_words)) - for ct, prev_word in enumerate(word_seq[prev_start:prev_end]): - if len(word_and_ts_seq["words"]) > fix_prev_words_count - ct: - saved_word = word_and_ts_seq["words"][-fix_prev_words_count + ct]["word"] - if len(prev_word) > len(saved_word): - if cfg.verbose: - logging.info(f"[Replacing Multi-token Word]: {saved_word} with {prev_word}") - word_and_ts_seq["words"][-fix_prev_words_count + ct]["word"] = prev_word - return word_and_ts_seq - - -def append_word_and_ts_seq( - cfg: Any, word_idx_offset: int, word_and_ts_seq: Dict[str, Any], word_dict: Dict[str, Any] -) -> tuple[int, Dict[str, Any]]: - """ - Append the word dictionary to the word and time-stamp sequence. - - This function updates the word_and_ts_seq dictionary by appending new word information - and managing the buffered words and speaker count. - - Args: - cfg (Any): Configuration object containing parameters like word_window. - word_idx_offset (int): The current word index offset. - word_and_ts_seq (Dict[str, Any]): Dictionary containing word sequences and related information. - word_dict (Dict[str, Any]): Dictionary containing information about the current word. - - Returns: - tuple[int, Dict[str, Any]]: A tuple containing the updated word_idx_offset and word_and_ts_seq. - """ - word_and_ts_seq["words"].append(word_dict) - word_and_ts_seq["buffered_words"].append(word_dict) - word_and_ts_seq["speaker_count_buffer"].append(word_dict["speaker"]) - word_and_ts_seq["word_window_seq"].append(word_dict['word']) - - if len(word_and_ts_seq["words"]) >= cfg.word_window + 1: - word_and_ts_seq["buffered_words"].pop(0) - word_and_ts_seq["word_window_seq"].pop(0) - word_idx_offset = 0 - - word_and_ts_seq["speaker_count"] = len(set(word_and_ts_seq["speaker_count_buffer"])) - return word_idx_offset, word_and_ts_seq - - -class SpeakerTaggedASR: - def __init__( - self, - cfg, - asr_model, - diar_model, - ): - # Required configs, models and datasets for inference - self.cfg = cfg - if not self.cfg.get("deploy_mode", False): - if self.cfg.manifest_file: - self.test_manifest_dict = get_audio_rttm_map(self.cfg.manifest_file) - elif self.cfg.audio_file is not None: - uniq_id = get_uniqname_from_filepath(filepath=self.cfg.audio_file) - self.test_manifest_dict = { - uniq_id: {'audio_filepath': self.cfg.audio_file, 'seglst_filepath': None, 'rttm_filepath': None} - } - else: - raise ValueError("One of the audio_file and manifest_file should be non-empty!") - else: - self.test_manifest_dict = { - "streaming_session": { - 'audio_filepath': 'streaming_session.wav', - 'seglst_filepath': None, - 'rttm_filepath': None, - } - } - self.transcribed_speaker_texts = [None] * len(self.test_manifest_dict) - - self.asr_model = asr_model - self.diar_model = diar_model - - # ASR speaker tagging configs - self._fix_prev_words_count = cfg.fix_prev_words_count - self._sentence_render_length = int(self._fix_prev_words_count + cfg.update_prev_words_sentence) - self._frame_len_sec = 0.08 - self._initial_steps = cfg.ignored_initial_frame_steps - self._word_and_ts_seq = {} - self._stt_words = [] - self._frame_hop_length = self.asr_model.encoder.streaming_cfg.valid_out_len - self._init_transcript_sessions() - - # Multi-instance configs - self._max_num_of_spks = cfg.get("max_num_of_spks", 4) - self._offset_chunk_start_time = 0.0 - self._sent_break_sec = cfg.get("sent_break_sec", 5.0) - - self._att_context_size = cfg.att_context_size - self._nframes_per_chunk = self._att_context_size[1] + 1 - self._cache_gating = cfg.get("cache_gating", False) - self._cache_gating_buffer_size = cfg.get("cache_gating_buffer_size", 2) - self._binary_diar_preds = cfg.binary_diar_preds - - self._masked_asr = cfg.get("masked_asr", True) - self._use_mask_preencode = cfg.get("mask_preencode", False) - self._single_speaker_mode = cfg.get("single_speaker_mode", False) - - self.instance_manager = MultiTalkerInstanceManager( - asr_model=self.asr_model, - diar_model=self.diar_model, - max_num_of_spks=self.diar_model._cfg.max_num_of_spks, - batch_size=cfg.batch_size, - sent_break_sec=self._sent_break_sec, - ) - self.n_active_speakers_per_stream = self.cfg.max_num_of_spks - - def _init_transcript_sessions(self): - """ - Initialize the word and time-stamp sequence for each session. - """ - for uniq_id in self.test_manifest_dict.keys(): - uniq_id = uniq_id.split(".")[0] # Make sure there is no "." in the uniq_id - self._word_and_ts_seq[uniq_id] = { - "words": [], - "buffered_words": [], - "token_frame_index": [], - "offset_count": 0, - "status": "success", - "sentences": None, - "last_word_index": 0, - "speaker_count": None, - "transcription": None, - "max_spk_probs": [], - "word_window_seq": [], - "speaker_count_buffer": [], - "sentence_memory": {}, - } - - def _get_offset_sentence(self, session_trans_dict: Dict[str, Any], offset: int) -> Dict[str, Any]: - """ - For the very first word in a session, get the offset sentence. - - Args: - session_trans_dict (dict): Dictionary containing session-related information. - offset (int): Index of the word for which the offset sentence is needed. - - Returns: - (Dict): Dictionary containing offset sentence information. - """ - word_dict = session_trans_dict['words'][offset] - return { - 'session_id': session_trans_dict['uniq_id'], - 'speaker': word_dict['speaker'], - 'start_time': word_dict['start_time'], - 'end_time': word_dict['end_time'], - 'words': f"{word_dict['word']} ", - } - - def _get_sentence(self, word_dict: Dict[str, Any]) -> Dict[str, Any]: - """ - Get the sentence for a given word. - - Args: - word_dict (Dict[str, Any]): Dictionary containing word-related information. - """ - return { - 'speaker': word_dict['speaker'], - 'start_time': word_dict['start_time'], - 'end_time': word_dict['end_time'], - 'words': '', - } - - def get_sentences_values(self, session_trans_dict: dict, sentence_render_length: int): - """ - Get sentences (speaker-turn-level text) for a given session and sentence render length. - - Args: - session_trans_dict (Dict[str, Any]): Dictionary containing session-related information. - sentence_render_length (int): Length of the sentences to be generated. - - Returns: - sentences (List[Dict[str, Any]]): List of sentences in the session. - """ - stt_word_index = max(0, session_trans_dict['last_word_index'] - sentence_render_length) - if session_trans_dict['sentences'] is None: - sentence = self._get_offset_sentence(session_trans_dict=session_trans_dict, offset=0) - sentences = [] - session_trans_dict['last_word_index'] = stt_word_index - session_trans_dict['sentence_memory'].update( - {stt_word_index: (deepcopy(sentences), deepcopy(sentence), sentence['speaker'])} - ) - prev_speaker = session_trans_dict['words'][stt_word_index]['speaker'] - else: - (_sentences, _sentence, prev_speaker) = session_trans_dict['sentence_memory'][stt_word_index] - sentences, sentence = deepcopy(_sentences), deepcopy(_sentence) - - for word_idx in range(stt_word_index + 1, len(session_trans_dict['words'])): - word_dict = session_trans_dict['words'][word_idx] - word, end_point = word_dict['word'], word_dict['end_time'] - if word_dict['speaker'] != prev_speaker: - sentence['words'] = sentence['words'].strip() - sentences.append(sentence) - sentence = self._get_sentence(word_dict=session_trans_dict['words'][word_idx]) - else: - sentence['end_time'] = end_point - sentence['words'] += word.strip() + ' ' - sentence['words'] = sentence['words'] - sentence['session_id'] = session_trans_dict['uniq_id'] - session_trans_dict['last_word_index'] = word_idx - prev_speaker = word_dict['speaker'] - session_trans_dict['sentence_memory'][word_idx] = (deepcopy(sentences), deepcopy(sentence), prev_speaker) - sentence['words'] = sentence['words'].strip() - sentences.append(sentence) - session_trans_dict['sentences'] = sentences - return session_trans_dict - - def merge_transcript_and_speakers( - self, test_manifest_dict: dict, asr_hypotheses: List[Hypothesis], diar_pred_out: torch.Tensor - ) -> Tuple[List[str], Dict[str, Dict[str, Any]]]: - """ - Merge the transcript and speakers and generate real-time scripts if the config is set. - - Args: - test_manifest_dict (Dict): Dictionary containing test manifest data. - asr_hypotheses (List[Hypothesis]): List of ASR hypotheses. - diar_pred_out (torch.Tensor): Diarization prediction output stream. - - Returns: - transcribed_speaker_texts (List[str]): List of transcribed speaker texts. - self._word_and_ts_seq (Dict[str, Dict[str, Any]]): Dictionary of word-level dictionaries with uniq_id as key. - """ - - for idx, (uniq_id, _) in enumerate(test_manifest_dict.items()): - uniq_id = uniq_id.split(".")[0] # Make sure there is no "." in the uniq_id - if not len(asr_hypotheses[idx].text) == 0: - # Get the word-level dictionaries for each word in the chunk - self._word_and_ts_seq[uniq_id] = self.get_frame_and_words_offline( - uniq_id=uniq_id, - diar_pred_out=diar_pred_out[idx].squeeze(0), - asr_hypothesis=asr_hypotheses[idx], - word_and_ts_seq=self._word_and_ts_seq[uniq_id], - ) - if len(self._word_and_ts_seq[uniq_id]["words"]) > 0: - self._word_and_ts_seq[uniq_id] = self.get_sentences_values( - session_trans_dict=self._word_and_ts_seq[uniq_id], - sentence_render_length=self._sentence_render_length, - ) - if self.cfg.generate_realtime_scripts: - self.transcribed_speaker_texts[idx] = print_sentences( - sentences=self._word_and_ts_seq[uniq_id]["sentences"], - color_palette=get_color_palette(), - params=self.cfg, - ) - if not self.cfg.get("deploy_mode", False): - write_txt( - f'{self.cfg.print_path}'.replace(".sh", f"_{idx}.sh"), - self.transcribed_speaker_texts[idx].strip(), - ) - return self.transcribed_speaker_texts, self._word_and_ts_seq - - def get_frame_and_words_offline( - self, - uniq_id: str, - diar_pred_out: torch.Tensor, - asr_hypothesis: Hypothesis, - word_and_ts_seq: Dict[str, Any], - ): - """ - Get the frame and words for each word in the chunk. - - Args: - uniq_id (str): The unique id of the chunk. - diar_pred_out (torch.Tensor): Diarization prediction output stream. - asr_hypothesis (Hypothesis): ASR hypothesis. - word_and_ts_seq (Dict[str, Any]): Pre-existing word-level dictionaries. - - Returns: - word_and_ts_seq (Dict[str, Any]): The updated word-level dictionaries with new words. - """ - word_and_ts_seq['uniq_id'] = uniq_id - - for word_index, hyp_word_dict in enumerate(asr_hypothesis.timestamp['word']): - time_stt_end_tuple = (hyp_word_dict['start_offset'], hyp_word_dict['end_offset']) - word_dict = get_word_dict_content_offline( - cfg=self.cfg, - word=hyp_word_dict['word'], - word_index=word_index, - diar_pred_out=diar_pred_out, - time_stt_end_tuple=time_stt_end_tuple, - frame_len=self._frame_len_sec, - ) - word_and_ts_seq["words"].append(word_dict) - word_and_ts_seq["speaker_count_buffer"].append(word_dict["speaker"]) - word_and_ts_seq["word_window_seq"].append(word_dict['word']) - - word_and_ts_seq["buffered_words"] = word_and_ts_seq["words"] - word_and_ts_seq["speaker_count"] = len(set(word_and_ts_seq["speaker_count_buffer"])) - return word_and_ts_seq - - def get_frame_and_words_online( - self, - uniq_id: str, - step_num: int, - diar_pred_out_stream: torch.Tensor, - previous_hypothesis: Hypothesis, - word_and_ts_seq: Dict[str, Any], - ): - """ - Get the frame and words for each word object in the chunk during streaming inference. - - Args: - uniq_id (str): The unique id of the chunk. - step_num (int): The step number of the chunk. - diar_pred_out_stream (torch.Tensor): The diarization prediction output stream. - previous_hypothesis (Hypothesis): The previous hypothesis. - word_and_ts_seq (Dict[str, Any]): The word and timestamp sequence. - - Returns: - word_and_ts_seq (Dict[str, Any]): The word and timestamp sequence. - """ - offset = step_num * self._frame_hop_length - word_seq = previous_hypothesis.text.split() - new_words = word_seq[word_and_ts_seq["offset_count"] :] - new_token_group = self.asr_model.tokenizer.text_to_tokens(new_words) - new_tokens = list(itertools.chain(*new_token_group)) - frame_inds_seq = (torch.tensor(previous_hypothesis.timestamp) + offset).tolist() - frame_inds_seq = fix_frame_time_step(self.cfg, new_tokens, new_words, frame_inds_seq) - word_and_ts_seq['uniq_id'] = uniq_id - - min_len = min(len(new_words), len(frame_inds_seq)) - for idx in range(min_len): - word_and_ts_seq["token_frame_index"].append((new_tokens[idx], frame_inds_seq[idx])) - word_and_ts_seq["offset_count"] += 1 - - time_step_local_offset, word_idx_offset = 0, 0 - word_and_ts_seq = get_multitoken_words( - cfg=self.cfg, - word_and_ts_seq=word_and_ts_seq, - word_seq=word_seq, - new_words=new_words, - fix_prev_words_count=self._fix_prev_words_count, - ) - - # Get the FIFO queue preds to word_and_ts_seq - for local_idx, (token_group, word) in enumerate(zip(new_token_group, new_words)): - word_dict = get_word_dict_content_online( - cfg=self.cfg, - word=word, - word_index=(len(word_and_ts_seq["words"]) + local_idx), - diar_pred_out_stream=diar_pred_out_stream, - token_group=token_group, - frame_inds_seq=frame_inds_seq, - time_step_local_offset=time_step_local_offset, - frame_len=self._frame_len_sec, - ) - # Count the number of speakers in the word window - time_step_local_offset += len(token_group) - word_idx_offset, word_and_ts_seq = append_word_and_ts_seq( - cfg=self.cfg, word_idx_offset=word_idx_offset, word_and_ts_seq=word_and_ts_seq, word_dict=word_dict - ) - return word_and_ts_seq - - def _add_speaker_transcriptions( - self, - transcriptions: list, - speaker_transcriptions: List[str], - word_and_ts_seq: Dict[str, Dict[str, Any]], - test_manifest_dict: dict, - ) -> Tuple[List[Hypothesis], List[Hypothesis]]: - """ - Add speaker tagging into the transcriptions generated from an ASR model. - - Args: - transcriptions (Tuple[List[Hypothesis], List[Hypothesis]]): - Tuple containing the transcriptions and n-best transcriptions. - speaker_transcriptions (List[str]): - List of speaker transcriptions. - word_and_ts_seq (Dict[str, Dict[str, Any]]): - Dictionary of word-level dictionaries with uniq_id as key. - test_manifest_dict (dict): - Dictionary containing test manifest data. - - Returns: - Tuple[List[Hypothesis], List[Hypothesis]]: Tuple containing the updated transcriptions with speaker tags. - """ - trans_hyp, _ = transcriptions - for sess_idx, (uniq_id, _) in enumerate(test_manifest_dict.items()): - uniq_id = uniq_id.split(".")[0] # Make sure there is no "." in the uniq_id - if speaker_transcriptions[sess_idx] is not None: - trans_hyp[sess_idx].text = speaker_transcriptions[sess_idx] - speaker_added_word_dicts = [] - for word_idx, trans_wdict in enumerate(trans_hyp[0].timestamp['word']): - trans_wdict_copy = deepcopy(trans_wdict) - trans_wdict_copy['speaker'] = word_and_ts_seq[uniq_id]['words'][word_idx]['speaker'] - speaker_added_word_dicts.append(trans_wdict_copy) - trans_hyp[sess_idx].timestamp['word'] = speaker_added_word_dicts - w_count, segment_list = 0, [] - for word_idx, trans_segdict in enumerate(trans_hyp[0].timestamp['segment']): - words = trans_segdict['segment'].split() - spk_vote_pool = [] - for word in words: - if word.lower() != word_and_ts_seq[uniq_id]['words'][w_count]['word'].lower(): - raise ValueError( - f"Word mismatch: '{word.lower()}' != '{word_and_ts_seq[uniq_id]['words'][w_count]['word'].lower()}' " - f"at session {sess_idx}, word count {w_count}." - ) - spk_int = int(word_and_ts_seq[uniq_id]['words'][w_count]['speaker'].split('_')[-1]) - spk_vote_pool.append(spk_int) - w_count += 1 - trans_segdict['speaker'] = f"speaker_{torch.mode(torch.tensor(spk_vote_pool), dim=0).values.item()}" - segment_list.append(trans_segdict) - trans_hyp[sess_idx].timestamp['segment'] = segment_list - transcriptions = (trans_hyp, trans_hyp) - return transcriptions - - def perform_offline_stt_spk(self, override_cfg: Dict[str, Any]): - """ - Perform offline STT and speaker diarization on the provided manifest file. - - Args: - override_cfg (dict): Override configuration parameters. - - Returns: - transcriptions (Tuple): Tuple containing the speaker-tagged transcripts. - """ - transcriptions = self.asr_model.transcribe( - audio=self.cfg.dataset_manifest, - override_config=override_cfg, - ) - best_hyp, _ = transcriptions - _, pred_tensors = self.diar_model.diarize(audio=self.cfg.manifest_file, include_tensor_outputs=True) - speaker_transcriptions, word_and_ts_seq = self.merge_transcript_and_speakers( - test_manifest_dict=self.diar_model._diarize_audio_rttm_map, - asr_hypotheses=best_hyp, - diar_pred_out=pred_tensors, - ) - transcriptions = self._add_speaker_transcriptions( - transcriptions=transcriptions, - speaker_transcriptions=speaker_transcriptions, - word_and_ts_seq=word_and_ts_seq, - test_manifest_dict=self.diar_model._diarize_audio_rttm_map, - ) - return transcriptions - - def generate_seglst_dicts_from_serial_streaming(self, samples: List[Dict[str, Any]]): - """ - Generate the seglst dictionary for SegLST format from serial streaming. - For SegLST format, the session_id is the name of the audio file - should not contain "." in the name. - - Args: - samples (List[Dict[str, Any]]): List of samples. - """ - for sample in samples: - uniq_id = get_uniqname_from_filepath(sample['audio_filepath']).split('.')[0] - word_ts_and_seq_dict = self._word_and_ts_seq[uniq_id] - for sentence_dict in word_ts_and_seq_dict['sentences']: - session_id = word_ts_and_seq_dict['uniq_id'].split('.')[0] - seglst_dict = get_new_sentence_dict( - speaker=sentence_dict['speaker'], - start_time=float(sentence_dict['start_time']), - end_time=float(sentence_dict['end_time']), - text=sentence_dict["words"], - session_id=session_id, - ) - if seglst_dict['words'].strip() != "": - self.instance_manager.seglst_dict_list.append(seglst_dict) - return self.instance_manager.seglst_dict_list - - def generate_seglst_dicts_from_parallel_streaming(self, samples: List[Dict[str, Any]]): - """ - Generate the seglst dictionary for SegLST format from parallel streaming. - For SegLST format, the session_id is the name of the audio file - should not contain "." in the name. - - Args: - samples (List[Dict[str, Any]]): List of samples. - """ - self.instance_manager.previous_asr_states.extend(self.instance_manager.batch_asr_states) - for sample, asr_state in zip(samples, self.instance_manager.previous_asr_states): - audio_filepath = sample["audio_filepath"] - uniq_id = os.path.basename(audio_filepath).split('.')[0] - seglsts = [] - for seg in asr_state.seglsts: - a_seg_dict = get_new_sentence_dict( - speaker=seg['speaker'], - start_time=seg['start_time'], - end_time=seg['end_time'], - text=seg['words'], - session_id=uniq_id, - ) - if a_seg_dict['words'].strip() != "": - seglsts.append(a_seg_dict) - seglsts = sorted(seglsts, key=lambda x: x['start_time']) - self.instance_manager.seglst_dict_list.extend(seglsts) - return self.instance_manager.seglst_dict_list - - def _find_active_speakers(self, diar_preds: torch.Tensor, n_active_speakers_per_stream: int) -> List[List[int]]: - """ - Find the active speakers from the diar prediction output. - - Args: - diar_preds (torch.Tensor): The diar prediction output. - n_active_speakers_per_stream (int): The number of active speakers per stream. - - Returns: - speaker_ids_list (List[List[int]]): The list of active speakers for each stream. - """ - if diar_preds.ndim != 3: - raise ValueError(f"diar_preds must be 3D (B, T, N), got shape {diar_preds.shape}") - if n_active_speakers_per_stream > diar_preds.shape[2]: - raise ValueError( - f"n_active_speakers_per_stream ({n_active_speakers_per_stream}) " - f"> available speakers ({diar_preds.shape[2]})" - ) - max_probs = torch.max(diar_preds, dim=1).values # (B, T, N) --> (B, N) - top_values, top_indices = torch.topk(max_probs, k=n_active_speakers_per_stream, dim=1) - masks = top_values > 0.5 - - speaker_ids_list = [] - for speaker_ids, mask in zip(top_indices, masks): - speaker_ids_list.append(sorted(speaker_ids[mask].tolist())) - return speaker_ids_list - - def forward_pre_encoded( - self, audio_signal: torch.Tensor, length: torch.Tensor, drop_extra_pre_encoded: int = 0 - ) -> None: - """ - Forward the pre-encoded features through the ASR model. - - Args: - audio_signal (torch.Tensor): The audio signal. - length (torch.Tensor): The length of the audio signal. - drop_extra_pre_encoded (int): The number of extra pre-encoded tokens to drop. - - Returns: - audio_signal (torch.Tensor): The pre-encoded audio signal. - length (torch.Tensor): The length of the pre-encoded audio signal. - """ - audio_signal = torch.transpose(audio_signal, 1, 2) # (B, T, D) -> (B, D, T) - - audio_signal, length = self.asr_model.encoder.pre_encode(x=audio_signal, lengths=length) - length = length.to(torch.int64) - # `self.streaming_cfg` is set by setup_streaming_cfg(), called in the init - if drop_extra_pre_encoded: - audio_signal = audio_signal[:, drop_extra_pre_encoded:, :] - length = (length - drop_extra_pre_encoded).clamp(min=0) - return audio_signal, length - - def mask_features( - self, chunk_audio: torch.Tensor, mask: torch.Tensor, threshold: float = 0.5, mask_value: float = -16.6355 - ) -> torch.Tensor: - """ - Mask the features of the chunk audio. - - Args: - chunk_audio (torch.Tensor): The chunk audio. - mask (torch.Tensor): The mask. - threshold (float): The threshold for the mask. - mask_value (float): The value for the masked audio. - - Returns: - masked_chunk_audio (torch.Tensor): The masked chunk audio. - """ - if chunk_audio.ndim != 3: - raise ValueError( - f"chunk_audio must be 3D (B, C, T), got {chunk_audio.ndim}D with shape {chunk_audio.shape}" - ) - if mask.ndim != 2: - raise ValueError(f"mask must be 2D (B, T), got {mask.ndim}D with shape {mask.shape}") - if chunk_audio.shape[0] != mask.shape[0]: - raise ValueError(f"Batch size mismatch: chunk_audio={chunk_audio.shape[0]}, mask={mask.shape[0]}") - mask = (mask > threshold).float() - mask = mask.unsqueeze(-1).repeat(1, 1, 8).flatten(1, 2) - - if mask.shape[1] > chunk_audio.shape[2]: - if self.cfg.get("log", False): - logging.warning(f"Mask shape {mask.shape} is greater than chunk_audio shape {chunk_audio.shape}") - mask = mask[:, : chunk_audio.shape[2]] - elif mask.shape[1] < chunk_audio.shape[2]: - if self.cfg.get("log", False): - logging.warning(f"Mask shape {mask.shape} is less than chunk_audio shape {chunk_audio.shape}") - mask = torch.nn.functional.pad(mask, (chunk_audio.shape[2] - mask.shape[1], 0), mode='constant', value=0) - - masked_chunk_audio = chunk_audio * mask.unsqueeze(1) - masked_chunk_audio[torch.where(chunk_audio == 0)] = mask_value - - return masked_chunk_audio - - def mask_preencode(self, chunk_audio: torch.Tensor, mask: torch.Tensor, threshold: float = 0.5) -> torch.Tensor: - """ - Mask the pre-encoded features of the chunk audio. - - Args: - chunk_audio (torch.Tensor): The chunk audio. - mask (torch.Tensor): The mask. - threshold (float): The threshold for the mask. - - Returns: - masked_chunk_audio (torch.Tensor): The masked chunk audio. - """ - mask = (mask > threshold).float() - - if mask.shape[1] > chunk_audio.shape[1]: - logging.warning(f"Mask shape {mask.shape} is greater than chunk_audio shape {chunk_audio.shape}") - mask = mask[:, : chunk_audio.shape[1]] - elif mask.shape[1] < chunk_audio.shape[1]: - logging.warning(f"Mask shape {mask.shape} is less than chunk_audio shape {chunk_audio.shape}") - mask = torch.nn.functional.pad(mask, (chunk_audio.shape[1] - mask.shape[1], 0), mode='constant', value=0) - - masked_chunk_audio = chunk_audio * mask.unsqueeze(-1) - - return masked_chunk_audio - - def get_diar_pred_out_stream(self, step_num): - """ - Get the diar prediction output stream for the given step number. - - Args: - step_num (int): the step number - - Returns: - new_diar_pred_out_stream (torch.Tensor): the diar prediction output stream for the given step number - new_chunk_preds (torch.Tensor): the diar prediction output stream for the given step number - """ - start_frame_idx = step_num * self._nframes_per_chunk - end_frame_idx = start_frame_idx + self._nframes_per_chunk - new_diar_pred_out_stream = self.diar_model.rttms_mask_mats[:, :end_frame_idx] - new_chunk_preds = new_diar_pred_out_stream[:, start_frame_idx:end_frame_idx] - return new_diar_pred_out_stream, new_chunk_preds - - @measure_eta - def perform_serial_streaming_stt_spk( - self, - step_num: int, - chunk_audio: torch.Tensor, - chunk_lengths: torch.Tensor, - is_buffer_empty: bool, - drop_extra_pre_encoded: int, - ): - """ - Perform the serial streaming inference. - Serial streaming inference deploys a single ASR model instance to transcribe multiple speakers in a chunk. - All the updates are done to the instance manager in a `SpeakerTaggedASR` class instance. - - Args: - step_num (int): The step number of the chunk. - chunk_audio (torch.Tensor): The chunk audio. - chunk_lengths (torch.Tensor): The length of the chunk audio. - is_buffer_empty (bool): Whether the buffer is empty. - drop_extra_pre_encoded (int): The number of extra pre-encoded tokens to drop. - """ - # Initialize the instance manager with the batch size of the chunk audio. - if step_num == 0: - self.instance_manager.reset(batch_size=chunk_audio.shape[0]) - self.instance_manager.to(chunk_audio.device) - - # This part exists for compatibility with the parallel streaming inference. - self.instance_manager.get_active_speakers_info( - active_speakers=[[0] for _ in range(chunk_audio.shape[0])], - chunk_audio=chunk_audio, - chunk_lengths=chunk_lengths, - ) - - ( - asr_pred_out_stream, - _, - cache_last_channel, - cache_last_time, - cache_last_channel_len, - previous_hypotheses, - ) = self.asr_model.conformer_stream_step( - processed_signal=chunk_audio, - processed_signal_length=chunk_lengths, - cache_last_channel=self.instance_manager.active_cache_last_channel, - cache_last_time=self.instance_manager.active_cache_last_time, - cache_last_channel_len=self.instance_manager.active_cache_last_channel_len, - previous_hypotheses=self.instance_manager.active_previous_hypotheses, - previous_pred_out=self.instance_manager.active_asr_pred_out_stream, - keep_all_outputs=is_buffer_empty, - drop_extra_pre_encoded=drop_extra_pre_encoded, - return_transcription=True, - ) - - if self.diar_model.rttms_mask_mats is None: - - new_streaming_state, diar_pred_out_stream = self.diar_model.forward_streaming_step( - processed_signal=chunk_audio.transpose(1, 2), - processed_signal_length=chunk_lengths, - streaming_state=self.instance_manager.diar_states.streaming_state, - total_preds=self.instance_manager.diar_states.diar_pred_out_stream, - drop_extra_pre_encoded=drop_extra_pre_encoded, - ) - self.instance_manager.update_diar_state( - diar_pred_out_stream=diar_pred_out_stream, - previous_chunk_preds=diar_pred_out_stream[:, -self._nframes_per_chunk :], - diar_streaming_state=new_streaming_state, - ) - else: - _, new_chunk_preds = self.get_diar_pred_out_stream(step_num) - diar_pred_out_stream = new_chunk_preds - - # Apply max number of speakers - diar_pred_out_stream[:, :, self._max_num_of_spks :] = 0.0 - - for idx, (uniq_id, _) in enumerate(self.test_manifest_dict.items()): - if not (len(previous_hypotheses[idx].text) == 0 and step_num <= self._initial_steps): - # Get the word-level dictionaries for each word in the chunk - self._word_and_ts_seq[uniq_id] = self.get_frame_and_words_online( - uniq_id=uniq_id, - step_num=step_num, - diar_pred_out_stream=diar_pred_out_stream[idx, :, :], - previous_hypothesis=previous_hypotheses[idx], - word_and_ts_seq=self._word_and_ts_seq[uniq_id], - ) - if len(self._word_and_ts_seq[uniq_id]["words"]) > 0: - self._word_and_ts_seq[uniq_id] = self.get_sentences_values( - session_trans_dict=self._word_and_ts_seq[uniq_id], - sentence_render_length=self._sentence_render_length, - ) - if self.cfg.get("generate_realtime_scripts", True): - self.transcribed_speaker_texts[idx] = print_sentences( - sentences=self._word_and_ts_seq[uniq_id]["sentences"], - color_palette=get_color_palette(), - params=self.cfg, - ) - if not self.cfg.get("deploy_mode", False): - write_txt( - f'{self.cfg.get("print_path", "./print_script.sh")}'.replace(".sh", f"_{idx}.sh"), - self.transcribed_speaker_texts[idx].strip(), - ) - - for batch_idx in range(chunk_audio.shape[0]): - self.instance_manager.update_asr_state( - batch_idx, - speaker_id=0, - cache_last_channel=cache_last_channel[:, batch_idx], - cache_last_time=cache_last_time[:, batch_idx], - cache_last_channel_len=cache_last_channel_len[batch_idx], - previous_hypotheses=previous_hypotheses[batch_idx], - previous_pred_out=asr_pred_out_stream[batch_idx], - ) - return self.transcribed_speaker_texts - - @measure_eta - def perform_parallel_streaming_stt_spk( - self, - step_num, - chunk_audio, - chunk_lengths, - is_buffer_empty, - drop_extra_pre_encoded, - ): - """ - Perform the parallel streaming inference. - Parallel streaming inference deploys multiple ASR model instances to transcribe multiple speakers in a chunk. - All the updates are done to the instance manager in a `SpeakerTaggedASR` class instance. - - Args: - step_num (int): The step number of the chunk. - chunk_audio (torch.Tensor): The chunk audio. - chunk_lengths (torch.Tensor): The length of the chunk audio. - is_buffer_empty (bool): Whether the buffer is empty. - drop_extra_pre_encoded (int): The number of extra pre-encoded tokens to drop. - """ - # Initialize the instance manager with the batch size of the chunk audio. - if step_num == 0: - self._offset_chunk_start_time = 0 - self.instance_manager.reset(batch_size=chunk_audio.shape[0]) - self.instance_manager.to(chunk_audio.device) - - # Step 2: diarize or get GT rttms - if self.diar_model.rttms_mask_mats is None: - new_streaming_state, new_diar_pred_out_stream = self.diar_model.forward_streaming_step( - processed_signal=chunk_audio.transpose(1, 2), - processed_signal_length=chunk_lengths, - streaming_state=self.instance_manager.diar_states.streaming_state, - total_preds=self.instance_manager.diar_states.diar_pred_out_stream, - drop_extra_pre_encoded=drop_extra_pre_encoded, - ) - new_chunk_preds = new_diar_pred_out_stream[:, -self._nframes_per_chunk :] - - else: - new_diar_pred_out_stream, new_chunk_preds = self.get_diar_pred_out_stream(step_num) - new_streaming_state = self.instance_manager.diar_states.streaming_state - - # Apply max number of speakers - new_diar_pred_out_stream[:, :, self._max_num_of_spks :] = 0.0 - - # Step 3: update diar states - self.instance_manager.update_diar_state( - diar_pred_out_stream=new_diar_pred_out_stream, - previous_chunk_preds=new_chunk_preds, - diar_streaming_state=new_streaming_state, - ) - - # For a session, if no second speaker is detected, - # the spk_targets will be set to all ones in the single speaker mode - if self._single_speaker_mode: - if self._max_num_of_spks == 1: - is_single_speaker = [True] * chunk_audio.shape[0] - else: - is_single_speaker = (new_diar_pred_out_stream > 0.5).any(1).sum(-1) <= 1.0 - for i in range(chunk_audio.shape[0]): - if is_single_speaker[i]: - new_diar_pred_out_stream[i, :, 0] = 1.0 - new_diar_pred_out_stream[i, :, 1:] = 0.0 - - # Step 4: find active speakers - diar_chunk_preds = new_diar_pred_out_stream[:, -self._nframes_per_chunk * self._cache_gating_buffer_size :] - if self._cache_gating: - active_speakers = self._find_active_speakers( - diar_chunk_preds, n_active_speakers_per_stream=self.n_active_speakers_per_stream - ) - else: - active_speakers = [list(range(self.n_active_speakers_per_stream)) for _ in range(chunk_audio.shape[0])] - - if (self._masked_asr and self._use_mask_preencode) or not self._masked_asr: - chunk_audio, chunk_lengths = self.forward_pre_encoded(chunk_audio, chunk_lengths, drop_extra_pre_encoded) - bypass_pre_encode = True - else: - bypass_pre_encode = False - - # Step 5: generate instance for active speakers - ( - active_chunk_audio, - active_chunk_lengths, - active_speaker_targets, - inactive_speaker_targets, - ) = self.instance_manager.get_active_speakers_info( - active_speakers=active_speakers, - chunk_audio=chunk_audio, - chunk_lengths=chunk_lengths, - ) - - # skip current chunk if no active speakers are found - if active_chunk_audio is None: - return - - # Step 6: - # 1) mask the non-active speakers for masked ASR; or - # 2) set speaker targets for multitalker ASR - if self._masked_asr: - if self._use_mask_preencode: - active_chunk_audio = self.mask_preencode(chunk_audio=active_chunk_audio, mask=active_speaker_targets) - else: - active_chunk_audio = self.mask_features(chunk_audio=active_chunk_audio, mask=active_speaker_targets) - else: - if self._binary_diar_preds: - active_speaker_targets = (active_speaker_targets > 0.5).float() - inactive_speaker_targets = (inactive_speaker_targets > 0.5).float() - self.asr_model.set_speaker_targets(active_speaker_targets, inactive_speaker_targets) - - # Step 7: ASR forward pass for active speakers - ( - pred_out_stream, - _, - cache_last_channel, - cache_last_time, - cache_last_channel_len, - previous_hypotheses, - ) = self.asr_model.conformer_stream_step( - processed_signal=active_chunk_audio, - processed_signal_length=active_chunk_lengths, - cache_last_channel=self.instance_manager.active_cache_last_channel, - cache_last_time=self.instance_manager.active_cache_last_time, - cache_last_channel_len=self.instance_manager.active_cache_last_channel_len, - keep_all_outputs=is_buffer_empty, - previous_hypotheses=self.instance_manager.active_previous_hypotheses, - previous_pred_out=self.instance_manager.active_asr_pred_out_stream, - drop_extra_pre_encoded=drop_extra_pre_encoded, - return_transcription=True, - bypass_pre_encode=bypass_pre_encode, - ) - - # Step 8: update ASR states - active_id = 0 - for batch_idx, speaker_ids in enumerate(active_speakers): - for speaker_id in speaker_ids: - self.instance_manager.update_asr_state( - batch_idx, - speaker_id, - cache_last_channel[:, active_id], - cache_last_time[:, active_id], - cache_last_channel_len[active_id], - previous_hypotheses[active_id], - pred_out_stream[active_id], - ) - active_id += 1 - - # Step 9: update seglsts with timestamps - self.instance_manager.update_seglsts(offset=self._offset_chunk_start_time) - self._offset_chunk_start_time += self._nframes_per_chunk * self._frame_len_sec - - if self.cfg.get("generate_realtime_scripts", True): - for session_idx in self.cfg.get("print_sample_indices", [0]): - asr_state = self.instance_manager.batch_asr_states[session_idx] - self.transcribed_speaker_texts[session_idx] = print_sentences( - sentences=asr_state.seglsts, color_palette=get_color_palette(), params=self.cfg - ) - if not self.cfg.get("deploy_mode", False): - write_txt( - f'{self.cfg.get("print_path", "./print_script.sh").replace(".sh", f"_{session_idx}.sh")}', - self.transcribed_speaker_texts[session_idx].strip(), - ) - return self.transcribed_speaker_texts - - -class MultiTalkerInstanceManager: - """ - For multi-talker inference, we need to manage the information per speaker. - Each sample in a batch can be considered as a multi-talker instance, - and each instance may contain multiple speakers, which is the real - batch size for inference. If there are at most N speakers and the batch - size is B, then the real batch size for inference is at most B * N. - """ - - class ASRState: - """ - ASR state for each instance. - 1. In parallel mode, each instance handles each potential speaker. - 2. In serial mode, each instance handles one session. - - The goal of ASR-State class is to handle the ASR cache state between streaming steps. - The ASR-states required to perform streaming inference are all included in this class. - """ - - def __init__( - self, - max_num_of_spks: int = 4, - frame_len_sec: float = 0.08, - sent_break_sec: float = 5.0, - uppercase_first_letter: bool = True, - ): - """ - Initialize the ASR-State class with the initial parameters. - - Args: - max_num_of_spks (int): The maximum number of speakers. - frame_len_sec (float): The length of the frame in seconds. - sent_break_sec (float): The minimum time gap between two sentences in seconds. - """ - # Initialize the ASR state with the initial parameters. - self.speakers: Optional[List[str]] = None - self.cache_last_channel = None - self.cache_last_time = None - self.cache_last_channel_len = None - self.previous_hypothesis = None - self.previous_pred_out = None - - self.max_num_of_spks = max_num_of_spks - - self._frame_len_sec = frame_len_sec - self._sent_break_sec = sent_break_sec - self._uppercase_first_letter = uppercase_first_letter - self._speaker_wise_sentences = {} - self._prev_history_speaker_texts = ["" for _ in range(self.max_num_of_spks)] - - self.seglsts = [] - - def _reset_speaker_wise_sentences(self): - """ - Reset the speaker-wise sentences which will be used to generate the SegLST transcription outputs. - """ - self._speaker_wise_sentences = {} - self._prev_history_speaker_texts = ["" for _ in range(self.max_num_of_spks)] - - def reset(self, asr_cache_state: Tuple[torch.Tensor, torch.Tensor, torch.Tensor]): - """ - Reset the ASR state. - - Args: - asr_cache_state (Tuple[torch.Tensor, torch.Tensor, torch.Tensor]): The ASR cache state. - - cache_last_channel (torch.Tensor): The cache last channel. - - cache_last_time (torch.Tensor): The cache last time. - - cache_last_channel_len (torch.Tensor): The cache last channel length. - """ - self.speakers = [0] - self.cache_last_channel, self.cache_last_time, self.cache_last_channel_len = asr_cache_state - self.previous_hypothesis = [None] - self.previous_pred_out = [None] - self.seglsts = [] - self._speaker_wise_sentences = {} - self._prev_history_speaker_texts = ["" for _ in range(self.max_num_of_spks)] - - def update_asr_state( - self, - speaker_id, - cache_last_channel, - cache_last_time, - cache_last_channel_len, - previous_hypothesis, - previous_pred_out, - ): - """ - Update the ASR state with the new ASR cache state. - This function should be called at every streaming step to update the ASR cache state. - - Args: - speaker_id (int): The speaker id. - cache_last_channel (torch.Tensor): The cache last channel. - cache_last_time (torch.Tensor): The cache last time. - cache_last_channel_len (torch.Tensor): The cache last channel length. - previous_hypothesis (Hypothesis): The previous hypothesis. - previous_pred_out (torch.Tensor): The previous prediction output. - """ - self.cache_last_channel[:, speaker_id] = cache_last_channel - self.cache_last_time[:, speaker_id] = cache_last_time - self.cache_last_channel_len[speaker_id] = cache_last_channel_len - self.previous_hypothesis[speaker_id] = previous_hypothesis - self.previous_pred_out[speaker_id] = previous_pred_out - - def to(self, device): - """ - Override the to method to move the ASR state to the device. - - Args: - device (torch.device): The device to move the ASR state to. - """ - self.cache_last_channel = self.cache_last_channel.to(device) - self.cache_last_time = self.cache_last_time.to(device) - self.cache_last_channel_len = self.cache_last_channel_len.to(device) - - def get_speakers(self): - """ - Get the speaker ids (int) for each instance. - This function is used for serial streaming mode. - """ - return self.speakers - - def add_speaker(self, speaker_id: int, asr_cache_state: Tuple[torch.Tensor, torch.Tensor, torch.Tensor]): - """ - Add a speaker index and its initial cache state to the ASR state. - - Args: - speaker_id (int): The speaker id. - asr_cache_state (Tuple[torch.Tensor, torch.Tensor, torch.Tensor]): The ASR cache state. - """ - self.speakers.append(speaker_id) - cache_last_channel, cache_last_time, cache_last_channel_len = asr_cache_state - self.cache_last_channel = torch.cat([self.cache_last_channel, cache_last_channel], dim=1) - self.cache_last_time = torch.cat([self.cache_last_time, cache_last_time], dim=1) - self.cache_last_channel_len = torch.cat([self.cache_last_channel_len, cache_last_channel_len], dim=0) - self.previous_hypothesis.append(None) - self.previous_pred_out.append(None) - - def _update_last_sentence(self, spk_idx: int, end_time: float, diff_text: str): - """ - Update the end time of the last sentence for a speaker. - - Args: - spk_idx (int): The speaker id. - end_time (float): The end time of the last sentence. - diff_text (str): The difference text. - """ - if end_time is not None: - self._speaker_wise_sentences[spk_idx][-1]['end_time'] = end_time - new_words = self._speaker_wise_sentences[spk_idx][-1]['words'] + diff_text - self._speaker_wise_sentences[spk_idx][-1]['words'] = new_words.strip() - - def _is_new_text(self, spk_idx: int, text: str): - """ - Check if the text is new for a speaker. - - Args: - spk_idx (int): The speaker id. - text (str): The text. - """ - if text is None or text == self._prev_history_speaker_texts[spk_idx]: - return None - else: - # Get the difference between the current text and the previous text - if self._prev_history_speaker_texts[spk_idx] in text: - return text.replace(self._prev_history_speaker_texts[spk_idx], "") - else: - return text.strip() - - def _compute_hypothesis_timestamps(self, hypothesis: Hypothesis, offset: float) -> Tuple[float, float, bool]: - """ - Compute start and end timestamps for a hypothesis based on available timing information. - - This method calculates the temporal boundaries of a speech hypothesis, prioritizing - frame-level timestamps when available. When timestamps are not available, it falls - back to computing timing based on the hypothesis length. - - Args: - hypothesis (Hypothesis): The ASR hypothesis object containing either frame-level - offset (float): The time offset (in seconds) to add to the computed timestamps, - typically representing the start time of the current audio chunk. - - Returns: - Tuple[float, float, bool]: A tuple containing: - - start_time (float): The absolute start time of the hypothesis in seconds - - end_time (float): The absolute end time of the hypothesis in seconds - - sep_flag (bool): A flag indicating whether timing was computed from length - rather than timestamps. - - Note: - The end_time calculation from timestamps adds 1 to the last timestamp to account - for the full duration of the final frame. - """ - sep_flag = False - if len(hypothesis.timestamp) > 0: - start_time = offset + (hypothesis.timestamp[0]) * self._frame_len_sec - end_time = offset + (hypothesis.timestamp[-1] + 1) * self._frame_len_sec - else: - start_time = offset - end_time = offset + hypothesis.length.item() * self._frame_len_sec - sep_flag = True - - return start_time, end_time, sep_flag - - def update_sessionwise_seglsts_for_parallel(self, offset: float): - """ - Update the seglsts for the parallel mode streaming. - Note that this function is NOT used for serial mode streaming. - - Args: - offset (float): The offset in seconds. - This is usally the start time of the current audio chunk. - """ - valid_speakers = set() - for spk_idx in self.get_speakers(): - hypothesis = self.previous_hypothesis[spk_idx] - if hypothesis is None: - continue - valid_speakers.add(spk_idx) - - if spk_idx not in self._speaker_wise_sentences: - self._speaker_wise_sentences[spk_idx] = [] - - diff_text = self._is_new_text(spk_idx=spk_idx, text=hypothesis.text) - if diff_text is not None: - - start_time, end_time, sep_flag = self._compute_hypothesis_timestamps( - hypothesis=hypothesis, offset=offset - ) - - # Get the last end time of the previous sentence or None if no sentences are present - if len(self._speaker_wise_sentences[spk_idx]) > 0: - last_end_time = self._speaker_wise_sentences[spk_idx][-1]['end_time'] - else: - last_end_time = 0.0 - - # Case 1 - If start_tiime is greater than end_time + sent_break_sec, then we need to add the sentence - if sep_flag or (last_end_time == 0.0 or start_time > last_end_time + self._sent_break_sec): - stripped_text = diff_text.strip() - if len(stripped_text) > 0 and stripped_text[0] in ['.', ',', '?', '!']: - # This handles the case where the first character should be assigned to the previous sentence. - the_first_char, diff_text = stripped_text[0], stripped_text[1:] - self._update_last_sentence(spk_idx=spk_idx, end_time=None, diff_text=the_first_char) - - # Add the sentence to the speaker-wise sentences only if the text is not empty. - a_seg_dict = get_new_sentence_dict( - speaker=f"speaker_{spk_idx}", start_time=start_time, end_time=end_time, text=diff_text - ) - if a_seg_dict['words'].strip() != "": - if self._uppercase_first_letter: - split_words = a_seg_dict['words'].split() - split_words[0] = split_words[0].capitalize() - a_seg_dict['words'] = ' '.join(split_words) - self._speaker_wise_sentences[spk_idx].append(a_seg_dict) - # Case 2 - If start_time is less than end_time + sent_break_sec, then we need to update the end_time - else: - self._update_last_sentence(spk_idx=spk_idx, end_time=end_time, diff_text=diff_text) - - # Update the previous history of the speaker text - if hypothesis.text is not None: - self._prev_history_speaker_texts[spk_idx] = hypothesis.text - - self.seglsts = [] - - # Merge all sentences for each speaker but sort by start_time - for spk_idx in valid_speakers: - self.seglsts.extend(self._speaker_wise_sentences[spk_idx]) - - # Finally, sort the seglsts by start_time - self.seglsts = sorted(self.seglsts, key=lambda x: x['start_time']) - - class DiarState: - """ - Diar state for each diarization instance. - There is no difference between serial and parallel mode for the diarization state. - The goal of Diar-State class is to handle the diarization cache state between streaming steps. - """ - - def __init__(self, batch_size: int = 1, max_num_of_spks: int = 4): - """ - Initialize the Diar-State class with the initial parameters. - - Args: - batch_size (int): The batch size. - max_num_of_spks (int): The maximum number of speakers. - """ - self.batch_size = batch_size - self.max_num_of_spks = max_num_of_spks - self.diar_pred_out_stream = None - self.previous_chunk_preds = None - self.streaming_state = None - - def reset(self, diar_streaming_state: StreamingSortformerState): - self.diar_pred_out_stream = torch.zeros((self.batch_size, 0, self.max_num_of_spks)) - self.previous_chunk_preds = torch.zeros((self.batch_size, 0, self.max_num_of_spks)) - self.streaming_state = diar_streaming_state - - def to(self, device): - self.diar_pred_out_stream = self.diar_pred_out_stream.to(device) - self.previous_chunk_preds = self.previous_chunk_preds.to(device) - self.streaming_state.to(device) - - def __init__( - self, - asr_model=None, - diar_model=None, - batch_size: int = 1, - max_num_of_spks: int = 4, - sent_break_sec: float = 5.0, - ): - """ - Initialize the MultiTalkerInstanceManager class with the initial parameters. - - Args: - asr_model: The ASR model. - diar_model: The diarization model. - batch_size (int): The batch size for ASR. - 1. For parallel mode, this is the number of potential speakers - multiplied by the session counts. - 2. For serial mode, this is the number of sessions. - max_num_of_spks (int): The maximum number of speakers. - """ - self.asr_model = asr_model - self.diar_model = diar_model - - self.batch_size = batch_size - self.max_num_of_spks = max_num_of_spks - self._sent_break_sec = sent_break_sec - - # ASR state bank - self.batch_asr_states = [] - self.previous_asr_states = [] - - # Diar states - self.diar_states = None - - # SegLST output list - self.seglst_dict_list = [] - - # Active speaker buffer lists - self._active_chunk_audio: List[torch.Tensor] = [] - self._active_chunk_lengths: List[torch.Tensor] = [] - self._active_speaker_targets: List[torch.Tensor] = [] - self._inactive_speaker_targets: List[torch.Tensor] = [] - self._active_previous_hypotheses: List[Hypothesis] = [] - self._active_asr_pred_out_stream: List[torch.Tensor] = [] - self._active_cache_last_channel: List[torch.Tensor] = [] - self._active_cache_last_time: List[torch.Tensor] = [] - self._active_cache_last_channel_len: List[torch.Tensor] = [] - - # Active speaker attributes - self.active_previous_hypotheses: Optional[List[Hypothesis]] = None - self.active_asr_pred_out_stream: Optional[List[torch.Tensor]] = None - self.active_cache_last_channel: Optional[torch.Tensor] = None - self.active_cache_last_time: Optional[torch.Tensor] = None - self.active_cache_last_channel_len: Optional[torch.Tensor] = None - - def _reset_active_speaker_buffers(self): - """ - Reset the active speaker buffers need to update the active speaker information. - """ - self._active_chunk_audio = [] - self._active_chunk_lengths = [] - self._active_speaker_targets = [] - self._inactive_speaker_targets = [] - self._active_previous_hypotheses = [] - - self._active_asr_pred_out_stream = [] - self._active_cache_last_channel = [] - self._active_cache_last_time = [] - self._active_cache_last_channel_len = [] - - def reset(self, batch_size: Optional[int] = None, max_num_of_spks: Optional[int] = None): - """ - Reset the active speaker buffers need to update the active speaker information. - - Args: - batch_size (Optional[int]): The batch size. - max_num_of_spks (Optional[int]): The maximum number of speakers. - """ - if batch_size is not None: - self.batch_size = batch_size - if max_num_of_spks is not None: - self.max_num_of_spks = max_num_of_spks - - if len(self.batch_asr_states) > 0: - self.previous_asr_states.extend(deepcopy(self.batch_asr_states)) - self.batch_asr_states = [ - self.ASRState(self.max_num_of_spks, sent_break_sec=self._sent_break_sec) for _ in range(self.batch_size) - ] - - for i in range(self.batch_size): - self.batch_asr_states[i].reset(self.asr_model.encoder.get_initial_cache_state(batch_size=1)) - - self.diar_states = self.DiarState(batch_size=self.batch_size, max_num_of_spks=self.max_num_of_spks) - self.diar_states.reset(self.diar_model.sortformer_modules.init_streaming_state(batch_size=self.batch_size)) - - self.seglst_dict_list = [] - - def add_speaker(self, batch_idx: int, speaker_id: int): - """ - Add a speaker index and its initial cache state to the ASR state. - - Args: - batch_idx (int): The batch index. - speaker_id (int): The speaker id. - """ - speakers = self.batch_asr_states[batch_idx].get_speakers() - for speaker_index in range(0, speaker_id + 1): - if speaker_index not in speakers: - self.batch_asr_states[batch_idx].add_speaker( - speaker_id=speaker_index, - asr_cache_state=self.asr_model.encoder.get_initial_cache_state(batch_size=1), - ) - - def get_speakers(self, batch_idx: int): - """ - Get the speaker ids (int) for each instance. - - Args: - batch_idx (int): The batch index. - """ - return self.batch_asr_states[batch_idx].get_speakers() - - def to(self, device: torch.device): - """ - Override the to method to move the ASR and Diar states to the device. - - Args: - device (torch.device): The device to move the ASR and Diar states to. - """ - for batch_idx in range(len(self.batch_asr_states)): - self.batch_asr_states[batch_idx].to(device) - self.diar_states.to(device) - - def update_diar_state( - self, - diar_pred_out_stream: torch.Tensor, - previous_chunk_preds: torch.Tensor, - diar_streaming_state: StreamingSortformerState, - ): - """ - Update the diarization state from the diarization step. - The diarization results are updated as a form of torch.Tensor. - - Args: - diar_pred_out_stream (torch.Tensor): The diarization prediction output stream. - previous_chunk_preds (torch.Tensor): The previous chunk prediction output. - diar_streaming_state (StreamingSortformerState): The diarization streaming state. - """ - self.diar_states.diar_pred_out_stream = diar_pred_out_stream - self.diar_states.previous_chunk_preds = previous_chunk_preds - self.diar_states.streaming_state = diar_streaming_state - - def update_asr_state( - self, - batch_idx, - speaker_id, - cache_last_channel, - cache_last_time, - cache_last_channel_len, - previous_hypotheses, - previous_pred_out, - ): - """ - A function to update the ASR state with the new ASR cache state. - This function should be called at every streaming step to update the ASR cache state. - - Args: - batch_idx (int): The batch index. - If parallel mode, this is the index of the potential speaker. - If serial mode, this is the index of the session. - speaker_id (int): The speaker id in the given session. - -- Cache aware ASR related parameters -- - cache_last_channel (torch.Tensor) - cache_last_time (torch.Tensor) - cache_last_channel_len (torch.Tensor) - previous_hypotheses (Hypothesis) - previous_pred_out (torch.Tensor) The previous prediction output. - """ - self.batch_asr_states[batch_idx].update_asr_state( - speaker_id, - cache_last_channel, - cache_last_time, - cache_last_channel_len, - previous_hypotheses, - previous_pred_out, - ) - - def get_active_speakers_info(self, active_speakers, chunk_audio, chunk_lengths): - """ - Collect the active speaker information for the next streaming step and - update the active speaker buffers. - - Args: - active_speakers (List[List[int]]): The active speakers for each chunk. - chunk_audio (torch.Tensor): The chunk audio. - chunk_lengths (torch.Tensor): The chunk lengths. - """ - # Reset the active speaker buffers - self._reset_active_speaker_buffers() - - # Loop through the active speakers and update the active speaker buffers - for batch_idx, speaker_ids in enumerate(active_speakers): - for speaker_id in speaker_ids: - self._active_chunk_audio.append(chunk_audio[batch_idx, :]) - self._active_chunk_lengths.append(chunk_lengths[batch_idx]) - self._active_speaker_targets.append(self.diar_states.previous_chunk_preds[batch_idx, :, speaker_id]) - inactive_speaker_ids = [i for i in range(len(speaker_ids)) if i != speaker_id] - self._inactive_speaker_targets.append( - (self.diar_states.previous_chunk_preds[batch_idx, :, inactive_speaker_ids] > 0.5).sum(dim=-1) > 0 - ) - if speaker_id not in self.batch_asr_states[batch_idx].get_speakers(): - self.add_speaker(batch_idx, speaker_id) - - self._active_previous_hypotheses.append( - self.batch_asr_states[batch_idx].previous_hypothesis[speaker_id] - ) - self._active_asr_pred_out_stream.append(self.batch_asr_states[batch_idx].previous_pred_out[speaker_id]) - self._active_cache_last_channel.append( - self.batch_asr_states[batch_idx].cache_last_channel[:, speaker_id] - ) - self._active_cache_last_time.append(self.batch_asr_states[batch_idx].cache_last_time[:, speaker_id]) - self._active_cache_last_channel_len.append( - self.batch_asr_states[batch_idx].cache_last_channel_len[speaker_id] - ) - if len(self._active_chunk_audio) == 0: - return None, None, None, None - - # Convert chunk audio and target info to tensors - active_chunk_audio = torch.stack(self._active_chunk_audio) - active_chunk_lengths = torch.stack(self._active_chunk_lengths) - active_speaker_targets = torch.stack(self._active_speaker_targets) - inactive_speaker_targets = torch.stack(self._inactive_speaker_targets) - - # Update active speaker attributes - self.active_previous_hypotheses = deepcopy(self._active_previous_hypotheses) - self.active_asr_pred_out_stream = deepcopy(self._active_asr_pred_out_stream) - self.active_cache_last_channel = torch.stack(self._active_cache_last_channel).transpose(0, 1) - self.active_cache_last_time = torch.stack(self._active_cache_last_time).transpose(0, 1) - self.active_cache_last_channel_len = torch.stack(self._active_cache_last_channel_len) - return active_chunk_audio, active_chunk_lengths, active_speaker_targets, inactive_speaker_targets - - def update_seglsts(self, offset: int): - """ - Take the ASR states and update the seglsts. - - Args: - offset (int): The offset of the chunk. - """ - for asr_state in self.batch_asr_states: - asr_state.update_sessionwise_seglsts_for_parallel(offset=offset) diff --git a/nemo/collections/asr/parts/utils/numba_utils.py b/nemo/collections/asr/parts/utils/numba_utils.py deleted file mode 100644 index 867ecf59521b1c04ada1dfd9324b921a898d135f..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/numba_utils.py +++ /dev/null @@ -1,88 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import numpy as np -from numba import jit - - -def phase_vocoder(D: np.ndarray, rate: float, phi_advance: np.ndarray, scale_buffer: np.ndarray): - """ - Optimized implementation of phase vocoder from Librosa. - Reference implementation: - - https://librosa.github.io/librosa/generated/librosa.core.phase_vocoder.html - Args: - D: Complex spectograms of shape [d, t, complex=2]. - rate: Speed rate, must be float greater than 0. - phi_advance: Precomputed phase advance buffer array of length [n_fft + 1] - scale_buffer: Precomputed numpy buffer array of length [n_fft + 1] - Returns: - Complex64 ndarray of shape [d, t / rate, complex=2] - """ - time_steps = np.arange(0, D.shape[1], rate, dtype=np.float64) - - # Create an empty output array - d_stretch = np.zeros((D.shape[0], len(time_steps)), D.dtype, order='F') - - # Phase accumulator; initialize to the first sample - phase_acc = np.angle(D[:, 0]) - - # Pad 0 columns to simplify boundary logic - D = np.pad(D, [(0, 0), (0, 2)], mode='constant') - - d_stretch = _phase_vocoder_kernel(D, time_steps, phi_advance, d_stretch, phase_acc, scale_buffer) - - return d_stretch - - -@jit(nopython=True, nogil=True) -def _phase_vocoder_kernel(D, time_steps, phi_advance, d_stretch, phase_acc, scale_buffer): - """ - Numba optimized kernel to compute the phase vocoder step. - Args: - D: Complex spectograms of shape [d, t, complex=2]. - rate: Speed rate, must be float greater than 0. - time_steps: Numpy ndarray of linearly spaced time steps, shape = [t] - phi_advance: Precomputed phase advance buffer array of length [n_fft + 1] - d_stretch: Output complex matrix of shape [d, t / rate, complex=2] - phase_acc: Phase accumulator initialized to first sample of shape [d, complex=2] - scale_buffer: Precomputed numpy buffer array of length [n_fft + 1] - Returns: - Complex64 ndarray of shape [d, t / rate, complex=2] - """ - two_pi = 2.0 * np.pi - - for (t, step) in enumerate(time_steps): - columns = D[:, int(step) : int(step + 2)] - columns_0 = columns[:, 0] - columns_1 = columns[:, 1] - - # Weighting for linear magnitude interpolation - alpha = np.mod(step, 1.0) - mag = (1.0 - alpha) * np.abs(columns_0) + alpha * np.abs(columns_1) - - # Store to output array - d_stretch[:, t] = mag * np.exp(1.0j * phase_acc) - - # Compute phase advance - dphase = np.angle(columns_1) - np.angle(columns_0) - phi_advance - - # Wrap to -pi:pi range - scale = dphase / two_pi - np.round(scale, 0, scale_buffer) - - dphase = dphase - two_pi * scale_buffer - - # Accumulate phase - phase_acc += phi_advance + dphase - - return d_stretch diff --git a/nemo/collections/asr/parts/utils/offline_clustering.py b/nemo/collections/asr/parts/utils/offline_clustering.py deleted file mode 100644 index 3f6c90d945efc3723f302fff0fc17ae7541c2286..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/offline_clustering.py +++ /dev/null @@ -1,1387 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Copyright (c) 2007-2020 The scikit-learn developers. - -# BSD 3-Clause License - -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -# NME-SC clustering is based on the implementation from the paper -# https://arxiv.org/pdf/2003.02405.pdf and the implementation from -# https://github.com/tango4j/Auto-Tuning-Spectral-Clustering. - -from typing import Dict, List, Tuple - -import torch -from torch.linalg import eigh, eigvalsh - - -def cos_similarity(emb_a: torch.Tensor, emb_b: torch.Tensor, eps=torch.tensor(3.5e-4)) -> torch.Tensor: - """ - Calculate cosine similarities of the given two set of tensors. The output is an N by N - matrix where N is the number of feature vectors. - - Args: - a (Tensor): - Matrix containing speaker representation vectors. (N x embedding_dim) - b (Tensor): - Matrix containing speaker representation vectors. (N x embedding_dim) - - Returns: - res (Tensor): - N by N matrix containing the cosine similarities of the values. - """ - # If number of embedding count is 1, it creates nan values - if emb_a.shape[0] == 1 or emb_b.shape[0] == 1: - raise ValueError(f"Number of feature vectors should be greater than 1 but got {emb_a.shape} and {emb_b.shape}") - a_norm = emb_a / (torch.norm(emb_a, dim=1).unsqueeze(1) + eps) - b_norm = emb_b / (torch.norm(emb_b, dim=1).unsqueeze(1) + eps) - res = torch.mm(a_norm, b_norm.transpose(0, 1)) - res.fill_diagonal_(1) - return res - - -def ScalerMinMax(X: torch.Tensor) -> torch.Tensor: - """ - Min-max scale the input affinity matrix X, which will lead to a dynamic range of [0, 1]. - - Args: - X (Tensor): - Matrix containing cosine similarity values among embedding vectors (N x N) - - Returns: - v_norm (Tensor): - Min-max normalized value of X. - """ - v_min, v_max = X.min(), X.max() - v_norm = (X - v_min) / (v_max - v_min) - return v_norm - - -def getEuclideanDistance( - specEmbA: torch.Tensor, specEmbB: torch.Tensor, device: torch.device = torch.device('cpu') -) -> torch.Tensor: - """ - Calculate Euclidean distances from the given feature tensors. - - Args: - specEmbA (Tensor): - Matrix containing spectral embedding vectors from eigenvalue decomposition (N x embedding_dim). - specEmbB (Tensor): - Matrix containing spectral embedding vectors from eigenvalue decomposition (N x embedding_dim). - - Returns: - dis (Tensor): - Euclidean distance values of the two sets of spectral embedding vectors. - """ - specEmbA, specEmbB = specEmbA.to(device), specEmbB.to(device) - A, B = specEmbA.unsqueeze(dim=1), specEmbB.unsqueeze(dim=0) - dis = (A - B) ** 2.0 - dis = dis.sum(dim=-1).squeeze() - return dis - - -def kmeans_plusplus_torch( - X: torch.Tensor, - n_clusters: int, - random_state: int, - n_local_trials: int = 30, - device: torch.device = torch.device('cpu'), -): - """ - Choose initial centroids for initializing k-means algorithm. The performance of - k-means algorithm can vary significantly by the initial centroids. To alleviate - this problem, k-means++ algorithm chooses initial centroids based on the probability - proportional to the distance from the formally chosen centroids. The centroids - selected by k-means++ algorithm improve the chance of getting more accurate and - stable clustering results. The overall implementation of k-means++ algorithm is - inspired by the numpy based k-means++ implementation in: - https://github.com/scikit-learn/scikit-learn - - Originally, the implementation of the k-means++ algorithm in scikit-learn is based - on the following research article: - Arthur, David, and Sergei Vassilvitskii. k-means++: The advantages of careful - seeding. Proceedings of the eighteenth annual ACM-SIAM symposium on Discrete - algorithms, Society for Industrial and Applied Mathematics (2007) - - Args: - X (Tensor): - Matrix containing cosine similarity values among embedding vectors (N x N) - n_clusters (int): - Maximum number of speakers for estimating number of speakers. - Shows stable performance under 20. - random_state (int): - Seed variable for setting up a random state. - n_local_trials (int): - Number of trials for creating initial values of the center points. - device (torch.device) - Torch device variable. - - Returns: - centers (Tensor): - The coordinates for center points that are used for initializing k-means algorithm. - indices (Tensor): - The indices of the best candidate center points. - """ - torch.manual_seed(random_state) - X = X.to(device) - n_samples, n_features = X.shape - - centers = torch.zeros(n_clusters, n_features, dtype=X.dtype) - center_id = torch.randint(0, n_samples, (1,)).long() - indices = torch.full([n_clusters,], -1, dtype=torch.int) - - centers[0] = X[center_id].squeeze(0) - indices[0] = center_id.squeeze(0) - - centers = centers.to(device) - closest_dist_diff = centers[0, None].repeat(1, X.shape[0]).view(X.shape[0], -1) - X - closest_dist_sq = closest_dist_diff.pow(2).sum(dim=1).unsqueeze(dim=0) - current_pot = closest_dist_sq.sum() - - for c in range(1, n_clusters): - rand_vals = torch.rand(n_local_trials) * current_pot.item() - - if len(closest_dist_sq.shape) > 1: - torch_cumsum = torch.cumsum(closest_dist_sq, dim=1)[0] - else: - torch_cumsum = torch.cumsum(closest_dist_sq, dim=0) - - candidate_ids = torch.searchsorted(torch_cumsum, rand_vals.to(device)) - - N_ci = candidate_ids.shape[0] - distance_diff = X[candidate_ids].repeat(1, X.shape[0]).view(X.shape[0] * N_ci, -1) - X.repeat(N_ci, 1) - distance = distance_diff.pow(2).sum(dim=1).view(N_ci, -1) - distance_to_candidates = torch.minimum(closest_dist_sq, distance) - candidates_pot = distance_to_candidates.sum(dim=1) - - best_candidate = torch.argmin(candidates_pot) - current_pot = candidates_pot[best_candidate] - closest_dist_sq = distance_to_candidates[best_candidate] - best_candidate = candidate_ids[best_candidate] - - centers[c] = X[best_candidate] - indices[c] = best_candidate - return centers, indices - - -def kmeans_torch( - X: torch.Tensor, - num_clusters: int, - threshold: float = 1e-4, - iter_limit: int = 15, - random_state: int = 0, - device: torch.device = torch.device('cpu'), -) -> torch.Tensor: - """ - Run k-means algorithm on the given set of spectral embeddings in X. The threshold - and iter_limit variables are set to show the best performance on speaker diarization - tasks. The overall implementation of k-means algorithm is inspired by the k-means - algorithm implemented in https://github.com/scikit-learn/scikit-learn. - - References: - Arthur, David, and Sergei Vassilvitskii. k-means++: The advantages of careful - seeding. Proceedings of the eighteenth annual ACM-SIAM symposium on Discrete - algorithms, Society for Industrial and Applied Mathematics (2007). - - Args: - X (Tensor): - Cosine similarity matrix calculated from speaker embeddings - num_clusters (int): - The estimated number of speakers. - threshold (float): - This threshold limits the change of center values. If the square of - the center shift values are bigger than this threshold, the iteration stops. - iter_limit (int): - The maximum number of iterations that is allowed by the k-means algorithm. - device (torch.device): - Torch device variable - - Returns: - selected_cluster_indices (Tensor): - The assigned cluster labels from the k-means clustering. - """ - # Convert tensor type to float - X = X.float().to(device) - input_size = X.shape[0] - - # Initialize the cluster centers with kmeans_plusplus algorithm. - plusplus_init_states = kmeans_plusplus_torch(X, n_clusters=num_clusters, random_state=random_state, device=device) - centers = plusplus_init_states[0] - - selected_cluster_indices = torch.zeros(input_size).long() - - for iter_count in range(iter_limit): - euc_dist = getEuclideanDistance(X, centers, device=device) - - if len(euc_dist.shape) <= 1: - break - else: - selected_cluster_indices = torch.argmin(euc_dist, dim=1) - - center_inits = centers.clone() - - for index in range(num_clusters): - selected_cluster = torch.nonzero(selected_cluster_indices == index).squeeze().to(device) - chosen_indices = torch.index_select(X, 0, selected_cluster) - - if chosen_indices.shape[0] == 0: - chosen_indices = X[torch.randint(len(X), (1,))] - - centers[index] = chosen_indices.mean(dim=0) - - # Calculate the delta from center_inits to centers - center_delta_pow = torch.pow((centers - center_inits), 2) - center_shift_pow = torch.pow(torch.sum(torch.sqrt(torch.sum(center_delta_pow, dim=1))), 2) - - # If the cluster centers are not changing significantly, stop the loop. - if center_shift_pow < threshold: - break - - return selected_cluster_indices - - -def getTheLargestComponent(affinity_mat: torch.Tensor, seg_index: int, device: torch.device) -> torch.Tensor: - """ - Find the largest affinity_mat connected components for each given node. - This is for checking whether the affinity_mat is fully connected. - - Args: - affinity_mat (Tensor): - A square matrix (tensor) containing normalized cosine distance values - seg_index (int): - The segment index that is targeted to be explored. - - Returns: - connected_nodes (Tensor): - A tensor containing booleans that indicate whether the node is connected. - """ - num_of_segments = affinity_mat.shape[0] - - connected_nodes = torch.zeros(num_of_segments, dtype=torch.bool).to(device) - nodes_to_explore = torch.zeros(num_of_segments, dtype=torch.bool).to(device) - - nodes_to_explore[seg_index] = True - nodes_to_explore = nodes_to_explore.to(device) - for k in range(num_of_segments): - last_num_component = connected_nodes.sum() - torch.logical_or(connected_nodes, nodes_to_explore, out=connected_nodes) - if last_num_component >= connected_nodes.sum(): - break - - indices = (nodes_to_explore == torch.tensor(True)).nonzero().t().squeeze() - if len(indices.size()) == 0: - indices = indices.unsqueeze(0) - for i in indices: - neighbors = affinity_mat[i].to(device) - torch.logical_or(nodes_to_explore, neighbors.squeeze(0), out=nodes_to_explore) - return connected_nodes - - -def isGraphFullyConnected(affinity_mat: torch.Tensor, device: torch.device) -> torch.Tensor: - """ - Check whether the given affinity matrix is a fully connected graph. - """ - return getTheLargestComponent(affinity_mat, 0, device).sum() == affinity_mat.shape[0] - - -def getKneighborsConnections(affinity_mat: torch.Tensor, p_value: int, mask_method: str = 'binary') -> torch.Tensor: - """ - Binarize top-p values for each row from the given affinity matrix. - - Args: - affinity_mat (Tensor): - A square matrix (tensor) containing normalized cosine similarity values - p_value (int): - The number of top values that are selected from each row. - mask_method (str): - The method that is used to manipulate the affinity matrix. The default method is 'binary'. - - Returns: - binarized_affinity_mat (Tensor): - A binarized affinity matrix based on the given mask method. - """ - dim = affinity_mat.shape - binarized_affinity_mat = torch.zeros_like(affinity_mat).half() - sorted_matrix = torch.argsort(affinity_mat, dim=1, descending=True)[:, :p_value] - binarized_affinity_mat[sorted_matrix.T, torch.arange(affinity_mat.shape[0])] = ( - torch.ones(1).to(affinity_mat.device).half() - ) - indices_row = sorted_matrix[:, :p_value].flatten() - indices_col = torch.arange(dim[1]).repeat(p_value, 1).T.flatten() - if mask_method == 'binary' or mask_method is None: - binarized_affinity_mat[indices_row, indices_col] = ( - torch.ones(indices_row.shape[0]).to(affinity_mat.device).half() - ) - elif mask_method == 'drop': - binarized_affinity_mat[indices_row, indices_col] = affinity_mat[indices_row, indices_col].half() - elif mask_method == 'sigmoid': - binarized_affinity_mat[indices_row, indices_col] = torch.sigmoid(affinity_mat[indices_row, indices_col]).half() - else: - raise ValueError(f'Unknown mask method: {mask_method}') - return binarized_affinity_mat - - -def getAffinityGraphMat(affinity_mat_raw: torch.Tensor, p_value: int) -> torch.Tensor: - """ - Calculate a binarized graph matrix and - symmetrize the binarized graph matrix. - """ - X = affinity_mat_raw if p_value <= 0 else getKneighborsConnections(affinity_mat_raw, p_value) - symm_affinity_mat = 0.5 * (X + X.T) - return symm_affinity_mat - - -def getMinimumConnection( - mat: torch.Tensor, max_N: torch.Tensor, n_list: torch.Tensor, device: torch.device -) -> Tuple[torch.Tensor, torch.Tensor]: - """ - Generate connections until fully connect all the nodes in the graph. - If the graph is not fully connected, it might generate inaccurate results. - """ - p_value = torch.tensor(1) - affinity_mat = getAffinityGraphMat(mat, p_value) - for i, p_value in enumerate(n_list): - fully_connected = isGraphFullyConnected(affinity_mat, device) - affinity_mat = getAffinityGraphMat(mat, p_value) - if fully_connected or p_value > max_N: - break - - return affinity_mat, p_value - - -def getRepeatedList(mapping_argmat: torch.Tensor, score_mat_size: torch.Tensor) -> torch.Tensor: - """ - Count the numbers in the mapping dictionary and create lists that contain - repeated indices that will be used for creating a repeated affinity matrix. - This repeated matrix is then used for fusing multiple affinity values. - """ - repeat_list = torch.zeros(score_mat_size, dtype=torch.int32).to(mapping_argmat.device) - idxs, counts = torch.unique(mapping_argmat, return_counts=True) - repeat_list[idxs] = counts.int().to(mapping_argmat.device) - return repeat_list - - -def get_argmin_mat(timestamps_in_scales: List[torch.Tensor]) -> List[torch.Tensor]: - """ - Calculate the mapping between the base scale and other scales. A segment from a longer scale is - repeatedly mapped to a segment from a shorter scale or the base scale. - - Args: - timestamps_in_scales (list): - List containing timestamp tensors for each scale. - Each tensor has dimensions of (Number of base segments) x 2. - - Returns: - session_scale_mapping_list (list): - List containing argmin arrays indexed by scale index. - """ - scale_list = list(range(len(timestamps_in_scales))) - segment_anchor_list = [] - for scale_idx in scale_list: - time_stamps_float = timestamps_in_scales[scale_idx] - segment_anchor_list.append(torch.mean(time_stamps_float, dim=1)) - base_scale_idx = max(scale_list) - base_scale_anchor = segment_anchor_list[base_scale_idx] - session_scale_mapping_list = [] - for scale_idx in scale_list: - curr_scale_anchor = segment_anchor_list[scale_idx] - curr_mat = torch.tile(curr_scale_anchor, (base_scale_anchor.shape[0], 1)) - base_mat = torch.tile(base_scale_anchor, (curr_scale_anchor.shape[0], 1)).t() - argmin_mat = torch.argmin(torch.abs(curr_mat - base_mat), dim=1) - session_scale_mapping_list.append(argmin_mat) - return session_scale_mapping_list - - -def getCosAffinityMatrix(emb: torch.Tensor) -> torch.Tensor: - """ - Calculate cosine similarity values among speaker embeddings then min-max normalize - the affinity matrix. - - Args: - emb (Tensor): - Matrix containing embedding vectors. emb variable should be float(FP32) type to make the data-type - compatible with torch.mm operation for both CPU and GPU(CUDA). - dimension: (Number of embedding vectors) x (embedding dimension) - - Returns: - sim_d (Tensor): - Matrix containing cosine similarity values among the given embedding vectors. - dimension: (Number of embedding vectors) x (Number of embedding vectors) - """ - if emb.shape[0] == 1: - sim_d = torch.tensor([[1]]).to(emb.device) - else: - emb = emb.float() - sim_d = cos_similarity(emb, emb) - sim_d = ScalerMinMax(sim_d) - return sim_d - - -def get_scale_interpolated_embs( - multiscale_weights: torch.Tensor, - embeddings_in_scales: List[torch.Tensor], - timestamps_in_scales: List[torch.Tensor], - device: torch.device = torch.device('cpu'), -) -> Tuple[torch.Tensor, List[torch.Tensor]]: - """ - Generate a scale-interpolated single embedding vector by calculating the weighted sum - of the multiple embedding vectors from different scales. The output is a set of embedding - vectors corresponding to the base-scale segments. - - Args: - multiscale_weights (Tensor): - Tensor containing Multiscale weights - Dimensions: (Number of scales) x 1 - embeddings_in_scales (list): - List containing split embedding tensors by each scale - timestamps_in_scales (list): - List containing split timestamps tensors by each scale - device (torch.device): - Torch device variable - - Returns: - context_emb (Tensor): - A set of scale-interpolated embedding vectors. - Dimensions: (Number of base-scale segments) x (Dimensions of embedding vector) - session_scale_mapping_list (list): - List containing argmin arrays indexed by scale index. - """ - rep_mat_list = [] - multiscale_weights = multiscale_weights.to(device) - session_scale_mapping_list = get_argmin_mat(timestamps_in_scales) - scale_list = list(range(len(timestamps_in_scales))) - for scale_idx in scale_list: - mapping_argmat = session_scale_mapping_list[scale_idx] - emb_t = embeddings_in_scales[scale_idx].to(device) - mapping_argmat = mapping_argmat.to(device) - repeat_list = getRepeatedList(mapping_argmat, torch.tensor(emb_t.shape[0])).to(device) - rep_emb_t = torch.repeat_interleave(emb_t, repeats=repeat_list, dim=0) - rep_mat_list.append(rep_emb_t) - stacked_scale_embs = torch.stack(rep_mat_list) - context_emb = torch.matmul(stacked_scale_embs.permute(2, 1, 0), multiscale_weights.t()).squeeze().t() - if len(context_emb.shape) < 2: - context_emb = context_emb.unsqueeze(0) - context_emb = context_emb.to(device) - return context_emb, session_scale_mapping_list - - -def getMultiScaleCosAffinityMatrix( - multiscale_weights: torch.Tensor, - embeddings_in_scales: List[torch.Tensor], - timestamps_in_scales: List[torch.Tensor], - device: torch.device = torch.device('cpu'), -) -> torch.Tensor: - """ - Calculate cosine similarity values among speaker embeddings for each scale then - apply multiscale weights to calculate the fused similarity matrix. - NOTE: Due to CUDA memory limit, the embedding vectors in embeddings_in_scales are stored in `cpu` device. - - Args: - multiscale_weights (Tensor): - Tensor containing multiscale weights - Dimensions: (Number of scales) x 1 - embeddings_in_scales (list): - List containing split embedding tensors by each scale - timestamps_in_scales (list): - List containing split timestamps tensors by each scale - device (torch.device): - Torch device variable - - Returns: - fused_sim_d (Tensor): - An affinity matrix that is obtained by calculating the weighted sum of - the multiple affinity matrices from the different scales. - """ - multiscale_weights = torch.squeeze(multiscale_weights, dim=0).to(device) - session_scale_mapping_list = get_argmin_mat(timestamps_in_scales) - scale_list = list(range(len(timestamps_in_scales))) - fused_sim_d = torch.zeros(len(timestamps_in_scales[-1]), len(timestamps_in_scales[-1])).to(device) - for scale_idx in scale_list: - mapping_argmat = session_scale_mapping_list[scale_idx] - emb_t = embeddings_in_scales[scale_idx].half().to(device) - score_mat_torch = getCosAffinityMatrix(emb_t) - repeat_list = getRepeatedList(mapping_argmat, torch.tensor(score_mat_torch.shape[0])).to(device) - repeated_tensor_0 = torch.repeat_interleave(score_mat_torch, repeats=repeat_list, dim=0).to(device) - repeated_tensor_1 = torch.repeat_interleave(repeated_tensor_0, repeats=repeat_list, dim=1).to(device) - fused_sim_d += multiscale_weights[scale_idx] * repeated_tensor_1 - return fused_sim_d - - -def getLaplacian(X: torch.Tensor) -> torch.Tensor: - """ - Calculate a laplacian matrix from an affinity matrix X. - """ - X.fill_diagonal_(0) - D = torch.sum(torch.abs(X), dim=1) - D = torch.diag_embed(D) - L = D - X - return L - - -def eigDecompose(laplacian: torch.Tensor, cuda: bool, device: torch.device) -> Tuple[torch.Tensor, torch.Tensor]: - """ - Calculate eigenvalues and eigenvectors from the Laplacian matrix. - """ - if cuda: - if device is None: - device = torch.cuda.current_device() - laplacian = laplacian.float().to(device) - else: - laplacian = laplacian.float().to(torch.device('cpu')) - lambdas, diffusion_map = eigh(laplacian) - return lambdas, diffusion_map - - -def eigValueSh(laplacian: torch.Tensor, cuda: bool, device: torch.device) -> torch.Tensor: - """ - Calculate only eigenvalues from the Laplacian matrix. - """ - if cuda: - if device is None: - device = torch.cuda.current_device() - laplacian = laplacian.float().to(device) - else: - laplacian = laplacian.float().to(torch.device('cpu')) - lambdas = eigvalsh(laplacian) - return lambdas - - -def getLamdaGaplist(lambdas: torch.Tensor) -> torch.Tensor: - """ - Calculate the gaps between lambda values. - """ - if torch.is_complex(lambdas): - lambdas = torch.real(lambdas) - return lambdas[1:] - lambdas[:-1] - - -def addAnchorEmb(emb: torch.Tensor, anchor_sample_n: int, anchor_spk_n: int, sigma: float) -> torch.Tensor: - """ - Add randomly generated synthetic embeddings to make eigenanalysis more stable. - We refer to these embeddings as anchor embeddings. - - emb (Tensor): - The input embedding from the embedding extractor. - anchor_sample_n (int): - Number of embedding samples per speaker. - anchor_sample_n = 10 is recommended. - anchor_spk_n (int): - Number of speakers for synthetic embedding. - anchor_spk_n = 3 is recommended. - sigma (int): - The amplitude of synthetic noise for each embedding vector. - If the sigma value is too small, under-counting could happen. - If the sigma value is too large, over-counting could happen. - sigma = 50 is recommended. - """ - emb_dim = emb.shape[1] - std_org = torch.std(emb, dim=0) - sigma = torch.tensor(sigma).to(emb.device) - new_emb_list = [] - for _ in range(anchor_spk_n): - emb_m = torch.tile(torch.randn(1, emb_dim), (anchor_sample_n, 1)).to(emb.device) - emb_noise = torch.randn(anchor_sample_n, emb_dim).T.to(emb.device) - emb_noise = torch.matmul( - torch.diag(std_org), emb_noise / torch.max(torch.abs(emb_noise), dim=0)[0].unsqueeze(0) - ).T - emb_gen = emb_m + sigma * emb_noise - new_emb_list.append(emb_gen) - - new_emb_list.append(emb) - new_emb_np = torch.vstack(new_emb_list) - return new_emb_np - - -def getEnhancedSpeakerCount( - emb: torch.Tensor, - random_test_count: int = 5, - anchor_spk_n: int = 3, - anchor_sample_n: int = 10, - sigma: float = 50, - cuda: bool = False, -) -> torch.Tensor: - """ - Calculate the number of speakers using NME analysis with anchor embeddings. Add dummy speaker - embedding vectors and run speaker counting multiple times to enhance the speaker counting accuracy - for the short audio samples. - - Args: - emb (Tensor): - The input embedding from the embedding extractor. - cuda (bool): - Use cuda for the operations if cuda==True. - random_test_count (int): - Number of trials of the enhanced counting with randomness. - The higher the count, the more accurate the enhanced counting is. - anchor_spk_n (int): - Number of speakers for synthetic embedding. - anchor_spk_n = 3 is recommended. - anchor_sample_n (int): - Number of embedding samples per speaker. - anchor_sample_n = 10 is recommended. - sigma (float): - The amplitude of synthetic noise for each embedding vector. - If the sigma value is too small, under-counting could happen. - If the sigma value is too large, over-counting could happen. - sigma = 50 is recommended. - - Returns: - comp_est_num_of_spk (Tensor): - The estimated number of speakers. `anchor_spk_n` is subtracted from the estimated - number of speakers to factor out the dummy speaker embedding vectors. - """ - est_num_of_spk_list: List[int] = [] - for seed in range(random_test_count): - torch.manual_seed(seed) - emb_aug = addAnchorEmb(emb, anchor_sample_n, anchor_spk_n, sigma) - mat = getCosAffinityMatrix(emb_aug) - nmesc = NMESC( - mat, - max_num_speakers=emb.shape[0], - max_rp_threshold=0.15, - sparse_search=True, - sparse_search_volume=10, - fixed_thres=-1.0, - nme_mat_size=300, - cuda=cuda, - ) - est_num_of_spk, _ = nmesc.forward() - est_num_of_spk_list.append(est_num_of_spk.item()) - comp_est_num_of_spk = torch.tensor(max(torch.mode(torch.tensor(est_num_of_spk_list))[0].item() - anchor_spk_n, 1)) - return comp_est_num_of_spk - - -def split_input_data( - embeddings_in_scales: torch.Tensor, - timestamps_in_scales: torch.Tensor, - multiscale_segment_counts: torch.LongTensor, -) -> Tuple[List[torch.Tensor], List[torch.Tensor]]: - """ - Split multiscale embeddings and multiscale timestamps and put split scale-wise data into python lists. - This formatting function is needed to make the input type as `torch.Tensor`. - - Args: - embeddings_in_scales (Tensor): - Concatenated Torch tensor containing embeddings in multiple scales - timestamps_in_scales (Tensor): - Concatenated Torch tensor containing timestamps in multiple scales - multiscale_segment_counts (LongTensor): - Concatenated Torch LongTensor containing number of segments per each scale - - Returns: - embeddings_in_scales (list): - List containing split embedding tensors by each scale - timestamps_in_scales (list): - List containing split timestamps tensors by each scale - """ - if len(embeddings_in_scales.shape) != 2: - raise ValueError( - f"embeddings_in_scales Tensor should have 2 dimensions, but got {len(embeddings_in_scales.shape)}." - ) - elif len(timestamps_in_scales.shape) != 2: - raise ValueError( - f"timestamps_in_scales Tensor should have 2 dimensions, but got {len(timestamps_in_scales.shape)}." - ) - elif not (torch.sum(multiscale_segment_counts) == embeddings_in_scales.shape[0] == timestamps_in_scales.shape[0]): - raise ValueError( - f"multiscale_segment_counts, embeddings_in_scales, and timestamps_in_scales should have the same length, \ - but got {multiscale_segment_counts.shape[0]}, {embeddings_in_scales.shape[0]}, and {timestamps_in_scales.shape[0]} respectively." - ) - split_index: List[int] = multiscale_segment_counts.tolist() - embeddings_in_scales = torch.split(embeddings_in_scales, split_index, dim=0) - timestamps_in_scales = torch.split(timestamps_in_scales, split_index, dim=0) - embeddings_in_scales, timestamps_in_scales = list(embeddings_in_scales), list(timestamps_in_scales) - return embeddings_in_scales, timestamps_in_scales - - -def estimateNumofSpeakers( - affinity_mat: torch.Tensor, max_num_speakers: int, cuda: bool = False -) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: - """ - Estimate the number of speakers using eigendecomposition on the Laplacian Matrix. - - Args: - affinity_mat (Tensor): - N by N affinity matrix - max_num_speakers (int): - Maximum number of clusters to consider for each session - cuda (bool): - If cuda available eigendecomposition is computed on GPUs. - - Returns: - num_of_spk (Tensor): - The estimated number of speakers - lambdas (Tensor): - The lambda values from eigendecomposition - lambda_gap (Tensor): - The gap between the lambda values from eigendecomposition - """ - laplacian = getLaplacian(affinity_mat) - lambdas = eigValueSh(laplacian, cuda=cuda, device=affinity_mat.device) - lambdas = torch.sort(lambdas)[0] - lambda_gap = getLamdaGaplist(lambdas) - num_of_spk = torch.argmax(lambda_gap[: min(max_num_speakers, lambda_gap.shape[0])]) + 1 - return num_of_spk, lambdas, lambda_gap - - -class SpectralClustering: - """ - Perform spectral clustering by calculating spectral embeddings then run k-means clustering - algorithm on the spectral embeddings. - """ - - def __init__( - self, - n_clusters: int = 8, - random_state: int = 0, - n_random_trials: int = 1, - cuda: bool = False, - device: torch.device = torch.device('cpu'), - ): - """ - Initialize the variables needed for spectral clustering and k-means++. - - Args: - n_clusters (int): - Number of the estimated (or oracle) number of speakers - random_state (int): - Random seed that determines a random state of k-means initialization. - n_random_trials (int): - Number of trials with different random seeds for k-means initialization. - k-means++ algorithm is executed for multiple times then the final result - is obtained by taking a majority vote. - cuda (bool): - if cuda=True, spectral clustering is done on GPU. - device (torch.device): - Torch device variable - """ - self.n_clusters = n_clusters - self.random_state = random_state - self.n_random_trials = max(n_random_trials, 1) - self.cuda = cuda - self.device = device - - def forward(self, X) -> torch.Tensor: - """ - Call self.clusterSpectralEmbeddings() function to predict cluster labels. - - Args: - X (Tensor): - Affinity matrix input - - Returns: - labels (Tensor): - Clustering label output - """ - if X.shape[0] != X.shape[1]: - raise ValueError("The affinity matrix is not a square matrix.") - labels = self.clusterSpectralEmbeddings(X, cuda=self.cuda, device=self.device) - return labels - - def clusterSpectralEmbeddings( - self, affinity: torch.Tensor, cuda: bool = False, device: torch.device = torch.device('cpu') - ) -> torch.Tensor: - """ - Perform k-means clustering on spectral embeddings. To alleviate the effect of randomness, - k-means clustering is performed for (self.n_random_trials) times then the final labels are obtained - by taking a majority vote. If speed is the major concern, self.n_random_trials should be set to 1. - n_random_trials=30 is recommended to see an improved result. - - Args: - affinity (Tensor): - Affinity matrix input - cuda (torch.bool): - Use cuda for spectral clustering if cuda=True - device (torch.device): - Torch device variable - - Returns: - labels (Tensor): - clustering label output - - """ - spectral_emb = self.getSpectralEmbeddings(affinity, n_spks=self.n_clusters, cuda=cuda) - labels_set = [] - - for random_state_seed in range(self.random_state, self.random_state + self.n_random_trials): - _labels = kmeans_torch( - X=spectral_emb, num_clusters=self.n_clusters, random_state=random_state_seed, device=device - ) - labels_set.append(_labels) - stacked_labels = torch.stack(labels_set) - label_index = torch.mode(torch.mode(stacked_labels, 0)[1])[0] - labels = stacked_labels[label_index] - return labels - - def getSpectralEmbeddings(self, affinity_mat: torch.Tensor, n_spks: int = 8, cuda: bool = False) -> torch.Tensor: - """ - Calculate eigenvalues and eigenvectors to extract spectral embeddings. - - Args: - affinity (Tensor): - Affinity matrix input - cuda (torch.bool): - Use cuda for spectral clustering if cuda=True - device (torch.device): - Torch device variable - - Returns: - labels (Tensor): - clustering label output - """ - laplacian = getLaplacian(affinity_mat) - _, diffusion_map_ = eigDecompose(laplacian, cuda=cuda, device=affinity_mat.device) - diffusion_map = diffusion_map_[:, :n_spks] - inv_idx = torch.arange(diffusion_map.size(1) - 1, -1, -1).long() - embedding = diffusion_map.T[inv_idx, :] - return embedding[:n_spks].T - - -class NMESC: - """ - Normalized Maximum Eigengap based Spectral Clustering (NME-SC) - uses Eigengap analysis to get an estimated p-value for - affinity binarization and an estimated number of speakers. - - p_value (also referred to as p_neighbors) is for taking - top p number of affinity values and convert those to 1 while - convert the rest of values to 0. - - p_value can be also tuned on a development set without performing - NME-analysis. Fixing p_value brings about significantly faster clustering - speed, but the performance is limited to the development set. - - References: - Tae Jin Park et al., Auto-Tuning Spectral Clustering for Speaker Diarization - Using Normalized Maximum Eigengap, IEEE Signal Processing Letters 27 (2019), - https://arxiv.org/abs/2003.02405 - - Args: - Please refer to def __init__(). - - Methods: - NMEanalysis(): - Performs NME-analysis to estimate p_value and the number of speakers - subsampleAffinityMat(nme_mat_size): - Subsamples the number of speakers to reduce the computational load - getPvalueList(): - Generates a list containing p-values that need to be examined. - getEigRatio(p_neighbors): - Calculates g_p, which is a ratio between p_neighbors and the maximum eigengap - getLamdaGaplist(lambdas): - Calculates lambda gap values from an array contains lambda values - estimateNumofSpeakers(affinity_mat): - Estimates the number of speakers using lambda gap list - """ - - def __init__( - self, - mat: torch.Tensor, - max_num_speakers: int = 10, - max_rp_threshold: float = 0.15, - sparse_search: bool = True, - sparse_search_volume: int = 30, - nme_mat_size: int = 512, - use_subsampling_for_nme: bool = True, - fixed_thres: float = -1.0, - maj_vote_spk_count: bool = False, - parallelism: bool = True, - cuda: bool = False, - device: torch.device = torch.device('cpu'), - ): - """ - Args: - mat (Tensor): - Cosine similarity matrix calculated from the provided speaker embeddings. - max_num_speakers (int): - Maximum number of speakers for estimating number of speakers. - Shows stable performance under 20. - max_rp_threshold (float): - Limits the range of parameter search. - Clustering performance can vary depending on this range. - Default is 0.25. - sparse_search (bool): - To increase the speed of parameter estimation, sparse_search=True - limits the number of p_values we search. - sparse_search_volume (int): - Number of p_values we search during NME analysis. - Default is 30. The lower the value, the faster NME-analysis becomes. - However, a value lower than 20 might cause a poor parameter estimation. - nme_mat_size (int): - Targeted size of matrix for NME analysis. - use_subsampling_for_nme (bool): - Use subsampling to reduce the calculational complexity. - Default is True. - fixed_thres (float or None): - A fixed threshold which can be used instead of estimating the - threshold with NME analysis. If fixed_thres is float, - it skips the NME analysis part. - maj_vote_spk_count (bool): - If True, take a majority vote on all p-values in the given range to estimate the number of speakers. - The majority voting may contribute to surpress overcounting of the speakers and improve speaker - counting accuracy. - parallelism (bool): - If True, turn on parallelism based on torch.jit.script library. - cuda (bool): - Use cuda for Eigen decomposition if cuda=True. - device (torch.device): - Torch device variable - """ - self.max_num_speakers: int = max_num_speakers - self.max_rp_threshold: float = max_rp_threshold - self.use_subsampling_for_nme: bool = use_subsampling_for_nme - self.nme_mat_size: int = nme_mat_size - self.sparse_search: bool = sparse_search - self.sparse_search_volume: int = sparse_search_volume - self.min_p_value = torch.tensor(2) - self.fixed_thres: float = fixed_thres - self.eps = 1e-10 - self.max_N = torch.tensor(0) - self.mat: torch.Tensor = mat - self.p_value_list: torch.Tensor = self.min_p_value.unsqueeze(0) - self.cuda: bool = cuda - self.device: torch.device = device - self.maj_vote_spk_count: bool = maj_vote_spk_count - self.parallelism: bool = parallelism - - def forward(self) -> Tuple[torch.Tensor, torch.Tensor]: - """ - Subsample the input matrix to reduce the computational load. - - Returns: - est_num_of_spk (Tensor): - Estimated number of speakers from NMESC approach - p_hat_value (Tensor): - Estimated p-value (determines how many neighboring values to be selected) - """ - if self.use_subsampling_for_nme: - subsample_ratio = self.subsampleAffinityMat(self.nme_mat_size) - else: - subsample_ratio = torch.tensor(1) - - # Scans p_values and find a p_value that generates the smallest g_p value. - results: List[torch.Tensor] = [] - est_spk_n_dict: Dict[int, torch.Tensor] = {} - self.p_value_list = self.getPvalueList() - p_volume = self.p_value_list.shape[0] - eig_ratio_list = torch.zeros(p_volume,) - est_num_of_spk_list = torch.zeros(p_volume,) - - if self.parallelism: - futures: List[torch.jit.Future[torch.Tensor]] = [] - for p_idx, p_value in enumerate(self.p_value_list): - futures.append(torch.jit.fork(self.getEigRatio, p_value)) - for future in futures: - results.append(torch.jit.wait(future)) - - else: - for p_idx, p_value in enumerate(self.p_value_list): - results.append(self.getEigRatio(p_value)) - - # Retrieve the eigen analysis results - for p_idx, p_value in enumerate(self.p_value_list): - output = results[p_idx] - g_p, est_num_of_spk = output[0], output[1].int() - eig_ratio_list[p_idx] = g_p - est_spk_n_dict[p_value.item()] = est_num_of_spk - est_num_of_spk_list[p_idx] = est_num_of_spk - - index_nn = torch.argmin(eig_ratio_list) - rp_p_value = self.p_value_list[index_nn] - affinity_mat = getAffinityGraphMat(self.mat, rp_p_value) - - # Checks whether the affinity graph is fully connected. - # If not, it adds a minimum number of connections to make it fully connected. - if not isGraphFullyConnected(affinity_mat, device=self.device): - affinity_mat, rp_p_value = getMinimumConnection( - self.mat, self.max_N, self.p_value_list, device=self.device - ) - - p_hat_value = (subsample_ratio * rp_p_value).type(torch.int) - if self.maj_vote_spk_count: - est_num_of_spk = torch.mode(torch.tensor(est_num_of_spk_list))[0] - else: - est_num_of_spk = est_spk_n_dict[rp_p_value.item()] - return est_num_of_spk, p_hat_value - - def subsampleAffinityMat(self, nme_mat_size: int) -> torch.Tensor: - """ - Perform subsampling of affinity matrix. - This subsampling is for calculational complexity, not for performance. - The smaller nme_mat_size is, - - the bigger the chance of missing a speaker. - - the faster p-value estimation speed (based on eigen decomposition). - - The recommended nme_mat_size is 250~750. - However, if there are speakers who speak for very short period of time in the recording, - this subsampling might make the system miss underrepresented speakers. - Use this variable with caution. - - Args: - nme_mat_size (int): - The targeted matrix size - - Returns: - subsample_ratio (float): - The ratio between nme_mat_size and the original matrix size - """ - subsample_ratio = torch.max(torch.tensor(1), torch.tensor(self.mat.shape[0] / nme_mat_size)).type(torch.int) - self.mat = self.mat[:: subsample_ratio.item(), :: subsample_ratio.item()] - return subsample_ratio - - def getEigRatio(self, p_neighbors: int) -> torch.Tensor: - """ - For a given p_neighbors value, calculate g_p, which is a ratio between p_neighbors and the - maximum eigengap values. - References: - Tae Jin Park et al., Auto-Tuning Spectral Clustering for Speaker Diarization Using - Normalized Maximum Eigengap, IEEE Signal Processing Letters 27 (2019), - https://arxiv.org/abs/2003.02405 - - Args: - p_neighbors (int): - Determines how many binary graph connections we want to keep for each row. - - Returns: - est_num_of_spk (int): - Estimated number of speakers - g_p (float): - The ratio between p_neighbors value and the maximum eigen gap value. - """ - affinity_mat = getAffinityGraphMat(self.mat, p_neighbors) - est_num_of_spk, lambdas, lambda_gap_list = estimateNumofSpeakers( - affinity_mat, self.max_num_speakers, self.cuda - ) - arg_sorted_idx = torch.argsort(lambda_gap_list[: self.max_num_speakers], descending=True) - max_key = arg_sorted_idx[0] - max_eig_gap = lambda_gap_list[max_key] / (torch.max(lambdas).item() + self.eps) - g_p = (p_neighbors / self.mat.shape[0]) / (max_eig_gap + self.eps) - return torch.stack([g_p, est_num_of_spk]) - - def getPvalueList(self) -> torch.Tensor: - """ - Generates a p-value (p_neighbour) list for searching. p_value_list must include 2 (min_p_value) - since at least one neighboring segment should be selected other than itself. - - If fixed_thres value is specified, then only one p-value is specified. - If fixed_thres is not provided, multiple p-values are searched. - If sparse_search is True: - - Limit the number of p-values to be searched to sparse_search_volume. - - N should be at least 2 to include a number greater than 1. - If sparse_search is False: - - Scan all the p_values from 1 to max_N - - If sparse_search is False, NMESC analysis could take more time compared to sparse_search = True. - - Returns: - p_value_list (Tensor): - Tensor containing the p_values to be searched. - """ - if self.fixed_thres is not None and self.fixed_thres > 0.0: - self.max_N = torch.max( - torch.floor(torch.tensor(self.mat.shape[0] * self.fixed_thres)).type(torch.int), self.min_p_value - ) - p_value_list = self.max_N.unsqueeze(0).int() - else: - self.max_N = torch.max( - torch.floor(torch.tensor(self.mat.shape[0] * self.max_rp_threshold)).type(torch.int), self.min_p_value - ) - if self.sparse_search: - search_volume = torch.min(self.max_N, torch.tensor(self.sparse_search_volume).type(torch.int)) - # search at least two values - N = torch.max(search_volume, torch.tensor(2)) - # avoid repeating values by limiting the step size - steps = min(self.max_N, N) - p_value_list = torch.linspace(start=1, end=self.max_N, steps=steps).type(torch.int) - else: - p_value_list = torch.arange(1, self.max_N + 1) - if p_value_list.shape[0] == 0: - raise ValueError("p_value_list should not be empty.") - return p_value_list - - -class SpeakerClustering(torch.nn.Module): - def __init__( - self, - min_samples_for_nmesc: int = 6, - nme_mat_size: int = 512, - sparse_search: bool = True, - maj_vote_spk_count: bool = False, - parallelism: bool = False, - cuda: bool = False, - ): - """ - Clustering method for speaker diarization based on cosine similarity. - NME-SC part is converted to torch.tensor based operations in NeMo 1.9. - - Args: - min_samples_for_nmesc (int): - The minimum number of samples required for NME clustering. This avoids - zero p_neighbour_lists. If the input has fewer segments than min_samples, - it is directed to the enhanced speaker counting mode. - nme_mat_size (int): - The targeted matrix size for NME analysis. - sparse_search (bool): - Toggle sparse search mode. If True, limit the size of p_value_list to sparse_search_volume. - maj_vote_spk_count (bool): - If True, take a majority vote on all p-values in the given range to estimate the number of speakers. - The majority voting may contribute to surpress overcounting of the speakers and improve speaker - counting accuracy. - parallelism (bool): - Use dynamic parallelism feature in torch.jit compiler to accelerate the p-value search. - cuda (bool): - Boolean variable for toggling cuda availability. - """ - super().__init__() - self.min_samples_for_nmesc: int = min_samples_for_nmesc - self.nme_mat_size: int = nme_mat_size - self.sparse_search: bool = sparse_search - self.parallelism: bool = parallelism - self.cuda: bool = cuda - self.maj_vote_spk_count: bool = maj_vote_spk_count - self.embeddings_in_scales: List[torch.Tensor] = [torch.Tensor(0)] - self.timestamps_in_scales: List[torch.Tensor] = [torch.Tensor(0)] - self.device = torch.device("cuda") if self.cuda else torch.device("cpu") - - def forward_unit_infer( - self, - mat: torch.Tensor, - oracle_num_speakers: int = -1, - max_num_speakers: int = 8, - max_rp_threshold: float = 0.15, - sparse_search_volume: int = 30, - est_num_of_spk_enhanced: torch.Tensor = torch.tensor(-1), - fixed_thres: float = -1.0, - kmeans_random_trials: int = 1, - ) -> torch.LongTensor: - """ - This function takes a cosine similarity matrix `mat` and returns the speaker labels for the segments - in the given input embeddings. - - Args: - mat (Tensor): - Cosine similarity matrix (affinity matrix) calculated from the provided speaker embeddings. - oracle_num_speakers (int): - The number of speakers in a session, as specified by the reference transcript. - Can be used as `chunk_cluster_count` in long-form clustering mode. - max_num_speakers (int): - The upper bound for the number of speakers in each session. - max_rp_threshold (float): - Limits the range of parameter search. - The clustering performance can vary based on this range. - The default value is 0.15. - sparse_search_volume (int): - The number of p_values considered during NME analysis. - The default is 30. Lower values speed up the NME-analysis but might lead to poorer parameter estimations. Values below 20 are not recommended. - est_num_of_spk_enhanced (int): - The number of speakers estimated from enhanced speaker counting. - If the value is -1, the enhanced speaker counting is skipped. - fixed_thres (float): - If a `fixed_thres` value is provided, the NME-analysis process will be skipped. - This value should be optimized on a development set for best results. - By default, it is set to -1.0, and the function performs NME-analysis to estimate the threshold. - kmeans_random_trials (int): - The number of random trials for initializing k-means clustering. More trials can result in more stable clustering. The default is 1. - - Returns: - Y (LongTensor): - Speaker labels (clustering output) in integer format for the segments in the given input embeddings. - """ - nmesc = NMESC( - mat, - max_num_speakers=max_num_speakers, - max_rp_threshold=max_rp_threshold, - sparse_search=self.sparse_search, - sparse_search_volume=sparse_search_volume, - fixed_thres=fixed_thres, - nme_mat_size=self.nme_mat_size, - maj_vote_spk_count=self.maj_vote_spk_count, - parallelism=self.parallelism, - cuda=self.cuda, - device=self.device, - ) - # If there are less than `min_samples_for_nmesc` segments, est_num_of_spk is 1. - if mat.shape[0] > self.min_samples_for_nmesc: - est_num_of_spk, p_hat_value = nmesc.forward() - affinity_mat = getAffinityGraphMat(mat, p_hat_value) - else: - nmesc.fixed_thres = max_rp_threshold - est_num_of_spk, p_hat_value = nmesc.forward() - affinity_mat = mat - - # `n_clusters` is number of speakers estimated from spectral clustering. - if oracle_num_speakers > 0: - n_clusters = int(oracle_num_speakers) - elif est_num_of_spk_enhanced > 0: - n_clusters = int(est_num_of_spk_enhanced.item()) - else: - n_clusters = int(est_num_of_spk.item()) - - spectral_model = SpectralClustering( - n_clusters=n_clusters, n_random_trials=kmeans_random_trials, cuda=self.cuda, device=self.device - ) - Y = spectral_model.forward(affinity_mat) - return Y - - def forward(self, param_dict: Dict[str, torch.Tensor]) -> torch.LongTensor: - """ - A function wrapper designed for inference in exported script format. - - Note: - Dict is used to allow easy inference of the exported jit model in Triton server using easy to understand - naming convention. - See https://github.com/triton-inference-server/server/blob/main/docs/user_guide/model_configuration.md#special-conventions-for-pytorch-backend - - Args: - param_dict (dict): - Dictionary containing the arguments for speaker clustering. - See `forward_infer` function for the argument information. - - Returns: - (LongTensor): Speaker labels for the segments in the given input embeddings. - """ - embeddings_in_scales = param_dict['embeddings'] - timestamps_in_scales = param_dict['timestamps'] - multiscale_segment_counts = param_dict['multiscale_segment_counts'] - multiscale_weights = param_dict['multiscale_weights'] - oracle_num_speakers = int(param_dict['oracle_num_speakers'].item()) - max_num_speakers = int(param_dict['max_num_speakers'].item()) - enhanced_count_thres = int(param_dict['enhanced_count_thres'].item()) - sparse_search_volume = int(param_dict['sparse_search_volume'].item()) - max_rp_threshold = float(param_dict['max_rp_threshold'].item()) - fixed_thres = float(param_dict['fixed_thres'].item()) - return self.forward_infer( - embeddings_in_scales=embeddings_in_scales, - timestamps_in_scales=timestamps_in_scales, - multiscale_segment_counts=multiscale_segment_counts, - multiscale_weights=multiscale_weights, - oracle_num_speakers=oracle_num_speakers, - max_rp_threshold=max_rp_threshold, - max_num_speakers=max_num_speakers, - enhanced_count_thres=enhanced_count_thres, - sparse_search_volume=sparse_search_volume, - fixed_thres=fixed_thres, - ) - - def forward_infer( - self, - embeddings_in_scales: torch.Tensor, - timestamps_in_scales: torch.Tensor, - multiscale_segment_counts: torch.LongTensor, - multiscale_weights: torch.Tensor, - oracle_num_speakers: int = -1, - max_num_speakers: int = 8, - max_rp_threshold: float = 0.15, - enhanced_count_thres: int = 40, - sparse_search_volume: int = 30, - fixed_thres: float = -1.0, - kmeans_random_trials: int = 1, - ) -> torch.LongTensor: - """ - Calculate the affinity matrix using timestamps and speaker embeddings, run NME analysis to estimate the best - p-value, and perform spectral clustering based on the estimated p-value and the calculated affinity matrix. - - Caution: - For compatibility with libtorch, python boolean `False` has been replaced with `torch.LongTensor(-1)`. - - Args: - embeddings_in_scales (Tensor): - List containing concatenated Torch tensor embeddings across multiple scales. - The length of the list is equal to the number of scales. - Each tensor has dimensions of (Number of base segments) x (Embedding Dimension). - timestamps_in_scales (Tensor): - List containing concatenated Torch tensor timestamps across multiple scales. - The length of the list is equal to the number of scales. - Each tensor has dimensions of (Total number of segments across all scales) x 2. - Example: - >>> timestamps_in_scales[0] = \ - torch.Tensor([[0.4, 1.4], [0.9, 1.9], [1.4, 2.4], ... [121.2, 122.2]]) - multiscale_segment_counts (LongTensor): - A Torch tensor containing the number of segments for each scale. - The tensor has dimensions of (Number of scales). - Example: - >>> multiscale_segment_counts = torch.LongTensor([31, 52, 84, 105, 120]) - multiscale_weights (Tensor): - Multi-scale weights used when merging affinity scores. - Example: - >>> multiscale_weights = torch.tensor([1.4, 1.3, 1.2, 1.1, 1.0]) - oracle_num_speakers (int): - The number of speakers in a session as given by the reference transcript. - max_num_speakers (int): - The upper bound for the number of speakers in each session. - max_rp_threshold (float): - Limits the range of parameter search. - The clustering performance can vary based on this range. - The default value is 0.15. - enhanced_count_thres (int): - For shorter audio recordings, the clustering algorithm might not accumulate enough speaker profiles for each cluster. - Thus, the function `getEnhancedSpeakerCount` uses anchor embeddings (dummy representations) to mitigate the effects of cluster sparsity. - A value of 80 is recommended for `enhanced_count_thres`. - sparse_search_volume (int): - The number of p_values considered during NME analysis. - The default is 30. Lower values speed up the NME-analysis but might lead to poorer parameter estimations. Values below 20 are not recommended. - fixed_thres (float): - If a `fixed_thres` value is provided, the NME-analysis process will be skipped. - This value should be optimized on a development set for best results. - By default, it is set to -1.0, and the function performs NME-analysis to estimate the threshold. - kmeans_random_trials (int): - The number of random trials for initializing k-means clustering. More trials can result in more stable clustering. The default is 1. - - Returns: - (LongTensor): Speaker labels for the segments in the provided input embeddings. - """ - self.embeddings_in_scales, self.timestamps_in_scales = split_input_data( - embeddings_in_scales, timestamps_in_scales, multiscale_segment_counts - ) - # Last slot is the base scale embeddings - emb = self.embeddings_in_scales[-1] - - # Cases for extreamly short sessions - if emb.shape[0] == 1: - return torch.zeros((1,), dtype=torch.int64) - elif emb.shape[0] <= max(enhanced_count_thres, self.min_samples_for_nmesc) and oracle_num_speakers < 0: - est_num_of_spk_enhanced = getEnhancedSpeakerCount(emb=emb, cuda=self.cuda) - else: - est_num_of_spk_enhanced = torch.tensor(-1) - - if oracle_num_speakers > 0: - max_num_speakers = oracle_num_speakers - - mat = getMultiScaleCosAffinityMatrix( - multiscale_weights=multiscale_weights, - embeddings_in_scales=self.embeddings_in_scales, - timestamps_in_scales=self.timestamps_in_scales, - device=self.device, - ) - - return self.forward_unit_infer( - mat=mat, - oracle_num_speakers=oracle_num_speakers, - max_rp_threshold=max_rp_threshold, - max_num_speakers=max_num_speakers, - sparse_search_volume=sparse_search_volume, - est_num_of_spk_enhanced=est_num_of_spk_enhanced, - kmeans_random_trials=kmeans_random_trials, - fixed_thres=fixed_thres, - ) diff --git a/nemo/collections/asr/parts/utils/online_clustering.py b/nemo/collections/asr/parts/utils/online_clustering.py deleted file mode 100644 index 23ebe6c6dbbfe9b43c0ae8e271ca761416c6684e..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/online_clustering.py +++ /dev/null @@ -1,1195 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Copyright (c) 2007-2020 The scikit-learn developers. - -# BSD 3-Clause License - -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -# NME-SC clustering is based on the implementation from the paper -# https://arxiv.org/pdf/2003.02405.pdf and the implementation from -# https://github.com/tango4j/Auto-Tuning-Spectral-Clustering. - -from typing import List, Tuple -import torch - -from nemo.collections.asr.parts.utils.offline_clustering import ( - NMESC, - SpeakerClustering, - SpectralClustering, - get_scale_interpolated_embs, - getAffinityGraphMat, - getCosAffinityMatrix, - split_input_data, -) -from nemo.collections.asr.parts.utils.optimization_utils import linear_sum_assignment - - -def get_lsa_speaker_mapping( - U_set: torch.Tensor, cmm_P: torch.Tensor, cmm_Q: torch.Tensor, PandQ: torch.Tensor -) -> torch.Tensor: - """ - Find a mapping that minimizes the matching cost between the label P and Q. - One-hot encodding is employed to represent sequence and calculate the cost. - - Args: - U_set (list): - Whole set of the estimated speakers - cmm_P (Tensor): - Length-matched old sequence - cmm_Q (Tensor): - Length-matched new sequence - PandQ (Tensor): - Tensor containing the indices of the speakers that are in both old and new sequences - - Returns: - mapping_array (np.array): - Mapped labels that minimizes the cost - """ - all_spks_labels = [[x] for x in range(len(U_set))] - common_inds: List[int] = [int(x.item()) for x in PandQ] - - # Create tensors for one-hot encoding - enc_P = torch.zeros((len(cmm_P), len(all_spks_labels))).to(cmm_P.device) - enc_Q = torch.zeros((len(cmm_Q), len(all_spks_labels))).to(cmm_Q.device) - - # Create one-hot encoding - enc_P[torch.arange(len(cmm_P)), cmm_P] = 1 - enc_Q[torch.arange(len(cmm_Q)), cmm_Q] = 1 - - # Cost matrix from one-hot encoding vectors - cost = -1 * torch.matmul(enc_P.T, enc_Q).T.to(PandQ.device) - _, col_ind = linear_sum_assignment(cost) - - # If number of are speakers in each vector is not the same - mapping_array = torch.arange(0, len(U_set)).to(PandQ.device) - for x in range(col_ind.shape[0]): - if x not in common_inds: - mapping_array[x] = x - else: - mapping_array[x] = col_ind[x] - return mapping_array - - -def get_minimal_indices(Y_new: torch.Tensor) -> torch.Tensor: - """ - Force the unique indices of the labels to use the lowest numbers. - - Example: - >>> Y_new = [3, 3, 3, 4, 4, 5] - >>> get_minimal_indices(Y_new) - Return: - [0, 0, 0, 1, 1, 2] - - Args: - Y_new (Tensor): - Tensor containing cluster labels - - Returns: - (Tensor): Newly mapped cluster labels that has minimized indicies - """ - device = Y_new.device - Y_new_enlisted = torch.unique(Y_new).sort()[0].to(torch.long).to(device) - sequence = torch.arange(torch.max(Y_new_enlisted) + 1).to(device) - sequence[Y_new_enlisted] = torch.arange(len(Y_new_enlisted)).to(device) - return sequence[Y_new] - - -@torch.jit.script -def stitch_cluster_labels(Y_old: torch.Tensor, Y_new: torch.Tensor) -> torch.Tensor: - """ - Run Hungarian (linear sum assignment) algorithm to find the best permutation mapping between - the cumulated labels in history and the new clustering output labels. - - Args: - Y_old (Tensor): - Cumulated diarization labels. This will be concatenated with history embedding speaker label - then compared with the predicted label Y_new. - Y_new (Tensor): - Contains predicted labels for reduced history embeddings concatenated with the predicted label. - Permutation is not matched yet. - - Returns: - mapping_array[Y] (Tensor): - An output numpy array where the input Y_new is mapped with mapping_array. - """ - Y_new = get_minimal_indices(Y_new) - if len(Y_old) == 0: - matched_output = Y_new - else: - P_raw, Q_raw = Y_old.to(Y_new.device), Y_new - U_set = torch.unique(torch.cat([P_raw, Q_raw])) - PQ = torch.cat([P_raw, Q_raw]) - a_cat_b, counts = torch.unique(PQ, return_counts=True) - # Get a union set of old P and new Q labels - PandQ = a_cat_b[torch.where(counts.gt(1))[0]] - min_len = min(P_raw.shape[0], Q_raw.shape[0]) - P, Q = P_raw[:min_len], Q_raw[:min_len] - - if len(U_set) == 1: - # When two speaker vectors are exactly the same: No need to encode. - mapping_array = torch.tensor([0, 0]).to(Y_new.device) - else: - # Run Hungarian algorithm if there are more than one speaker in universal set U. - mapping_array = get_lsa_speaker_mapping(U_set=U_set, cmm_P=P, cmm_Q=Q, PandQ=PandQ) - matched_output = mapping_array[Y_new] - matched_output = get_minimal_indices(matched_output) - return matched_output - - -def calculate_removable_counts(removable_counts_mat: torch.Tensor, remain_count: int, num_clus: int) -> torch.Tensor: - """ - Calculate removable counts based on the arguments and calculate how many counts should be - removed from the each cluster. This function has `O(N)` (N = num_clus) time complexity to - return the desired `removable_counts_mat`. - - Example: - - The original input to `get_merge_quantity` function: - >>> pre_clus_labels = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2] - >>> num_to_be_removed = 3 - >>> min_count_per_cluster = 2 - - Histogram: (`min_count_per_cluster`=2 is removed) - 0 |***** - 1 |*** - 2 |* - - Inputs: - >>> removable_counts_mat = [5, 3, 1] - >>> remain_count = 6 - >>> num_clus = 3 - - Interim results: - >>> diff_counts - [1, 2, 2] - >>> gradual_counts - [3, 4, 2] - >>> cumsum_counts - [3, 7, 9] - - Return: - >>> removable_counts_mat - [2, 1, 0] - - Args: - removable_counts_mat (Tensor): - Tensor containing how many vectors could be removed from each cluster - remain_count (int): - Integer value that indicates the number of vectors removed from the total set - num_clus (int): - Number of clusters in the given label sequence (cardinality of a label set) - - Returns: - removable_counts_mat (Tensor): - Tensor containing the number of vectors should be removed from each cluster - """ - device = removable_counts_mat.device - zero_padded_counts = torch.cat( - [torch.tensor([0]).to(device), removable_counts_mat.sort()[0], torch.tensor([0]).to(device)], dim=0 - ) - removable_count_args = removable_counts_mat.sort(descending=True)[1] - - # Calculate the size difference between clusters - diff_counts = (zero_padded_counts[1:] - zero_padded_counts[:-1])[:num_clus] - gradual_counts = torch.arange(num_clus, 0, -1).to(device) * diff_counts - cumsum_counts = torch.cumsum(gradual_counts, dim=0) - remain_count_rem = remain_count - - # Find how many remaining counts we can use - ind: int = 0 - for ind, num in enumerate(cumsum_counts): - if remain_count < num: - break - - # Subtract the common values step by step - if ind > 0: - for knd in range(ind): - removable_counts_mat[removable_count_args[: num_clus - knd]] -= diff_counts[knd] - remain_count_rem -= int(diff_counts[knd].item()) * (num_clus - knd) - assert remain_count >= 0, "remain_count should never be negative." - - # Add remaining values - num_labels = remain_count_rem // (num_clus - ind) - rem_labels = remain_count_rem % (num_clus - ind) - removable_counts_mat[removable_count_args[: (num_clus - ind)]] -= num_labels - removable_counts_mat[removable_count_args[:rem_labels]] -= 1 - return removable_counts_mat.int() - - -def get_merge_quantity( - num_to_be_removed: int, pre_clus_labels: torch.Tensor, min_count_per_cluster: int, -) -> torch.Tensor: - """ - Determine which embeddings we need to reduce or merge in history buffer. - We want to merge or remove the embedding in the bigger cluster first. - At the same time, we keep the minimum number of embedding per cluster - with the variable named min_count_per_cluster. - - Constraint: - - Each cluster should keep the number of vectors over `min_count_per_cluster`. - - In total, `num_to_be_removed` of vectors should be removed from the total buffer. - - While merging embeddings, minimize the gap between quantities between clusters. - - Example: - >>> num_to_be_removed = 3 - >>> pre_clus_labels = [0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2] - >>> min_count_per_cluster = 2 - >>> get_merge_quantity(num_to_be_removed, pre_clus_labels, min_count_per_cluster) - Return: - torch.tensor([2, 1, 0]) - >>> # Sum should be equal to `num_to_be_removed` which is 3 - - Args: - num_to_be_removed: (int) - the quantity of the newly obtained embedding from the new stream of input. - pre_clus_labels: (Tensor) - the speaker labels of (the history_embedding_buffer_emb) + (the new embeddings to be added) - min_count_per_cluster: (int) - Minimum vector quantity for each cluster - - Returns: - removable_counts_mat: (Tensor) - Tensor containing the number of vectors should be removed from each cluster - """ - if num_to_be_removed > pre_clus_labels.shape[0] - 1: - raise ValueError(f"num_to_be_removed: {num_to_be_removed} should be less than pre_clus_labels length - 1") - remain_count = pre_clus_labels.shape[0] - num_to_be_removed - spk_freq_count = torch.bincount(pre_clus_labels) - num_clus = len(torch.unique(pre_clus_labels)) - if remain_count < min_count_per_cluster * num_clus: - raise ValueError(f"The remaining embedding vectors should be more than { min_count_per_cluster * num_clus }") - - # Minimum vector counts should be excluded from the removable amount - min_seg_count = torch.tensor([min_count_per_cluster] * len(spk_freq_count)).to(pre_clus_labels.device) - min_seg_count_mat = torch.stack((min_seg_count, spk_freq_count)).min(0)[0] - - # Exclude minimum quantities from the removable count matrix - remain_count -= int(torch.sum(min_seg_count_mat)) - removable_counts_mat = spk_freq_count - min_seg_count_mat - - # Calculate removable counts from `remain_count` variable - removable_counts_mat = calculate_removable_counts(removable_counts_mat, remain_count, num_clus) - if int(removable_counts_mat.sum()) != num_to_be_removed: - raise ValueError("Sum of `removable_counts_mat` is not equal to `num_to_be_removed` variable.") - if not torch.all(removable_counts_mat >= 0) or not torch.all(spk_freq_count - min_seg_count_mat >= 0): - raise ValueError( - f"Every value in `removable_counts_mat` should be always non-negative value but got {removable_counts_mat}" - ) - return removable_counts_mat - - -def merge_vectors( - selected_inds: torch.Tensor, emb_ndx: torch.Tensor, pre_cluster_labels: torch.Tensor -) -> Tuple[torch.Tensor, torch.Tensor]: - """ - Merge feature (embedding) vectors estimated to be the same cluster label. - - Args: - selected_inds (Tensor): - Selected indices for merging - emb_ndx (Tensor): - Feature (embedding) vectors - Dimension: (original vector counts) x (feature dimension) - pre_cluster_labels (Tensor): - Original cluster labels before merging - - Returns: - merged_vecs (Tensor): - Merged feature vectors that are concatenated - Dimension: (merged vector counts) x (feature dimension) - merged_clus_labels (Tensor): - Cluster labels for the merged feature vectors - Dimension: (merged vector counts) - """ - if emb_ndx.shape[0] != pre_cluster_labels.shape[0]: - raise ValueError("pre_cluster_labels and emb_ndx have mismatch in dimension") - avg_emb = torch.mean(emb_ndx[selected_inds, :], dim=0) - merged_clus_labels = pre_cluster_labels[selected_inds] - selected_inds_list: List[int] = selected_inds.tolist() - bypass_inds_list: List[int] = [] - for k in range(emb_ndx.shape[0]): - if k not in selected_inds_list: - bypass_inds_list.append(k) - bypass_inds = torch.tensor(bypass_inds_list) - selected_inds = torch.tensor(selected_inds_list) - if bypass_inds.shape[0] == 0: - merged_vecs = avg_emb.unsqueeze(0) - merged_clus_labels = merged_clus_labels.unsqueeze(0) - else: - merged_vecs = torch.vstack((emb_ndx[bypass_inds], avg_emb)) - merged_clus_labels = torch.hstack((pre_cluster_labels[bypass_inds], merged_clus_labels[0])) - return merged_vecs, merged_clus_labels - - -def get_closest_embeddings(affinity_mat: torch.Tensor, n_closest: int) -> Tuple[torch.Tensor, torch.Tensor]: - """ - Get the indices of the embedding vectors we want to merge. - - Example: - >>> n_closest = 2 - >>> affinity_mat = [[1.0, 0.2, 0.8], - [0.2, 1.0, 0.4], - [0.8, 0.4, 1.0]] - >>> affinity_mat.sum(0) - [2.0, 1.6, 2.2] - - # The closest two embedding vectors are at index 0 and 2. - - Args: - affinity_mat: (Tensor) - Symmetric affinity matrix of the given embedding vector set. - n_closest (int): - The amount of vector counts that are expected to be removed from the set - Example: - Input: 10 vectors in a set - n_closest = 5 - (5+1) vectors are merged into 1 vector - Output: 5 vectors in a set - - Returns: - idx_aff_sum (torch.Tensor): - Indices of the closest `n_closest` embedding vectors - rest_inds (torch.Tensor): - Indices of the complementary set of the indices in `idx_aff_sum` - """ - comb_limit = int(affinity_mat.shape[0] - 1) - if n_closest > comb_limit: - raise ValueError(f"Got n_closest of {n_closest}: {n_closest} is bigger than comb_limit {comb_limit}") - - # Take summed values over one axis - sum_cmat = affinity_mat.sum(0) - - # `n_closest + 1` will become 1 embedding vector after merging - idx_aff_sum = torch.argsort(sum_cmat, descending=True)[: (n_closest + 1)] - rest_inds = torch.argsort(sum_cmat, descending=True)[(n_closest + 1) :] - return idx_aff_sum, rest_inds - - -def run_reducer( - pre_embs: torch.Tensor, target_spk_idx: int, merge_quantity: int, pre_clus_labels: torch.Tensor, -): - """ - Reduce the number of embedding vectors by merging the closest embedding vectors. - - This merging algorithm is based on the assumption that the closest embeddings - are the most redundant embedding vectors. - - The closest embedding vectors are chosen by selecting the highest top-N sum of - each column in a given affinity matrix. - - If merge_quantity is N, we choose (N+1) vectors into 1 embedding vector. - Thus, we reduce N embeddings in the original embedding vector set. - - Example: - >>> merge_quantity = 1 # We merge 1+1 = 2 embedding vectors - >>> affinity_mat = [[1.0, 0.2, 0.8], - [0.2, 1.0, 0.4], - [0.8, 0.4, 1.0]] - >>> affinity_mat.sum(0) - [2.0, 1.6, 2.2] - - The first and the third embedding vectors are merged into one embedding vector. - >>> index_mapping # (bypassed indices, merged indices) - ([1], [0, 2]) - - Args: - pre_embs (Tensor): - Potential Embedding vectors to be merged - affinity_mat (Tensor): - The affinity matrix of the `pre_embs` - target_spk_idx (int): - The targeted speaker index for merging - merge_quantity (int): - The count of embeddings to be reduced - pre_clus_labels (list) - The original cluster (speaker) index - - Returns: - merged_embs (torch.Tensor): - The merged embedding vectors. - merged_clus_labels (torch.Tensor): - The cluster (speaker) indices for the merged embedding vectors. - index_mapping (Tuple[torch.Tensor, torch.Tensor]): - A tuple containing the indices of the original embeddings that were not merged (`bypassed indices`) - and the indices of the new merged embeddings (`merged indices`). - """ - if pre_embs.shape[0] != pre_clus_labels.shape[0]: - raise ValueError("Dimension mismatch between `pre_embs` and `pre_clus_labels`.") - - target_emb_index = torch.where(pre_clus_labels == target_spk_idx)[0] - org_size = target_emb_index.shape[0] - if merge_quantity > 0: - if merge_quantity > (target_emb_index.shape[0] - 1): - raise ValueError( - f"merge_quantity {merge_quantity} should not be larger than target_emb_index length: {target_emb_index.shape[0]-1}" - ) - total_affinity_mat = getCosAffinityMatrix(pre_embs) - - # Get the lower triangle of the affinity_mat array - affinity_mat = total_affinity_mat[:, target_emb_index][target_emb_index, :] - if affinity_mat.shape[0] != target_emb_index.shape[0]: - raise ValueError( - "Dimension mismatch between targeted speaker affinity `affinity_mat` and targeted speaker index `target_emb_index`." - ) - # Get the indices of the closest embedding vectors - selected_inds, rest_inds = get_closest_embeddings(affinity_mat, merge_quantity) - spk_cluster_labels, selected_embs = pre_clus_labels[target_emb_index], pre_embs[target_emb_index] - - # Note that we need to return the indices of speaker-specific indices from `target_emb_index`. - index_mapping = (target_emb_index[rest_inds.sort()[0]], target_emb_index[selected_inds]) - - # Merge the embeddings targeted by the 2-dim indices `index_2d` - merged_embs, merged_clus_labels = merge_vectors(selected_inds, selected_embs, spk_cluster_labels) - - if (org_size - merge_quantity) != merged_embs.shape[0]: - raise ValueError( - f"Reducer output {merged_embs.shape[0]} is not matched to the target quantity {org_size - merge_quantity}." - ) - - else: - merged_embs = pre_embs[target_emb_index] - merged_clus_labels = pre_clus_labels[target_emb_index] - index_mapping = (target_emb_index, torch.arange(0)) - return merged_embs, merged_clus_labels, index_mapping - - -def get_first_arg_index(mat: torch.Tensor, label: int) -> int: - """ - Get the index of the first element are specified by `index` variable. - - Args: - mat (Tensor): - Source matrix filled with indices - label (int): - Label which we want to find the first occuring index - - Returns: - (int): The first index of the given label - """ - return int(torch.where(mat == label)[0][0]) - - -class OnlineSpeakerClustering(torch.nn.Module): - """ - Online clustering method for speaker diarization based on cosine similarity. - - Regular Clustering Attributes: - - max_num_speakers (int): - The upper bound for the number of speakers in each session - max_rp_threshold (float): - Limits the range of parameter search. - Clustering performance can vary depending on this range. - Default is 0.15. - enhanced_count_thres (int): - For the short audio recordings, clustering algorithm cannot - accumulate enough amount of speaker profile for each cluster. - Thus, function `getEnhancedSpeakerCount` employs anchor embeddings - (dummy representations) to mitigate the effect of cluster sparsity. - enhanced_count_thres = 40 is recommended. - sparse_search_volume (int): - Number of p_values we search during NME analysis. - Default is 30. The lower the value, the faster NME-analysis becomes. - Lower than 20 might cause a poor parameter estimation. - fixed_thres (float): - A fixed threshold for finding p-closest neighbors in affinity matrix for clustering. - If fixed_thres value is provided, NME-analysis process will be skipped. - This value should be optimized on a development set to obtain a quality result. - Default is None and performs NME-analysis to estimate the threshold. - min_samples_for_nmesc (int): - The minimum number of samples required for NME clustering. This avoids - zero p_neighbour_lists. If the input has fewer segments than min_samples, - it is directed to the enhanced speaker counting mode. - sparse_search (bool): - Toggle sparse search mode. If True, limit the size of p_value_list to sparse_search_volume. - cuda (bool): - Use cuda for Eigen decomposition if cuda=True. - - Additional Online Processing Attributes: - - history_buffer_size (int): - - This is a buffer where diarization history is saved in the form of averaged speaker embedding vector. - - The values in [50, 200] range is recommended while the system requires bigger buffer size for - sessions with larger number of speakers. - current_buffer_size (int): - - This is a buffer which process the most recent speaker embedding vector inputs. - current-buffer is first-in-first-out (FIFO) queue where the embeddings accepted earlier - get to merged and saved to history buffer. - - In general, [50, 200] range is recommended and the performance can be sensitive on this buffer size. - min_spk_counting_buffer_size (int): - Integer number for speaker counting buffer. Number of speakers are estimated through a small buffer - and the number is obtained by taking majority vote. - min_frame_per_spk (int): - Below this number, the system considers the whole input segments as a single speaker. - p_update_freq (int): - Frequency (interval) of updating p_value for NMESC algorithm. - p_value_skip_frame_thres (int): - After `frame_index` passes this number, `p_value` estimation is skipped for inference speed - p_value_queue_size (int): - `p_value` buffer for major voting - use_temporal_label_major_vote (bool): - Boolean that determines whether to use temporal majorvoting for the final speaker labels - temporal_label_major_vote_buffer_size (int): - Buffer size for major-voting the - num_spk_stat (list): - List of number of speakers for major voting. Number of speakers are estimated through - majority voting of `self.num_spk_stat` list. - p_value_hist (list): - List of p_values for major voting. - To save the computation time, p_value is estimated every `p_update_freq` frames and - saved to `self.p_value_hist`. - - Attributes for counters and buffers in streaming system: - - is_online (bool): - - If self.is_online is False: - FIFO queue does not push out any speaker embedding vector - - If self.is_online is True: - FIFO queue starts push out speaker embedding vectors and saving them into - history buffer. - max_embed_count (int): - The maximum number of segments the streaming system has ever seen. - This value keeps increasing as the system processes more and more segments. - memory_margin (int): - The margin that is added to keep the segmentation data in the streaming system - minimum_segments_per_buffer (int): - Maximum number of embedding vectors kept in history buffer per speaker. - Example: - history_buffer_size (history_n) = 100 - max_num_speakers = 4 - minimum_segments_per_buffer = 25 - history_buffer_seg_end (int): - Index that indicates the boundary between history embedding sets and current processing buffer - when history embedding vectors and current input embedding vectors are concatenated into a - single matrix. - - Attributes for history buffer: - - history_embedding_buffer_emb (Tensor) - Tensor containing speaker embedding vectors for saving the history of the previous - speaker profile in the given audio session - history_embedding_buffer_label (Tensor) - Speaker label (cluster label) for embedding vectors saved in the history buffer - Y_fullhist (Tensor) - Tensor containing the speaker label hypothesis from start to current frame - """ - - def __init__( - self, - max_num_speakers: int = 8, - max_rp_threshold: float = 0.15, - enhanced_count_thres: float = 40, - fixed_thres: float = -1.0, - sparse_search_volume: int = 10, - history_buffer_size: int = 150, - current_buffer_size: int = 150, - min_spk_counting_buffer_size: int = 3, - min_frame_per_spk: int = 15, - p_update_freq: int = 5, - p_value_skip_frame_thres: int = 50, - p_value_queue_size: int = 3, - use_temporal_label_major_vote: bool = False, - temporal_label_major_vote_buffer_size: int = 11, - cuda: bool = False, - ): - super().__init__() - self.max_num_speakers = max_num_speakers - self.max_rp_threshold = max_rp_threshold - self.enhanced_count_thres = enhanced_count_thres - self.sparse_search_volume = sparse_search_volume - self.fixed_thres = fixed_thres - self.history_n = history_buffer_size - self.current_n = current_buffer_size - self.min_spk_counting_buffer_size = min_spk_counting_buffer_size - self.min_frame_per_spk = min_frame_per_spk - self.p_update_freq = p_update_freq - self.p_value_skip_frame_thres = p_value_skip_frame_thres - self.p_value_queue_size = p_value_queue_size - self.use_temporal_label_major_vote = use_temporal_label_major_vote - self.temporal_label_major_vote_buffer_size = temporal_label_major_vote_buffer_size - self.cuda = cuda - self.num_spk_stat: List[torch.Tensor] = [torch.tensor(1)] - self.p_value_hist: List[torch.Tensor] = [torch.tensor(2)] - - # Initialize the counters and buffers in streaming system - self.is_online = False - self.max_embed_count = 0 - self.memory_margin = 0 - self.minimum_segments_per_buffer = int(self.history_n / self.max_num_speakers) - self.history_buffer_seg_end = 0 - - # Initialize the streaming buffer tensors - self.history_embedding_buffer_emb = torch.tensor([]) - self.history_embedding_buffer_label = torch.tensor([]) - self.Y_fullhist = torch.tensor([]) - - def onlineNMEanalysis(self, mat_in: torch.Tensor, frame_index: int) -> Tuple[int, int]: - """ - To save the running time, the p-value is only estimated in the beginning of the session. - After switching to online mode, the system uses the most common estimated p-value. - Estimating p-value requires a plenty of computational resource. The less frequent estimation of - p-value can speed up the clustering algorithm by a huge margin. - - Args: - mat_in (Tensor): - Tensor containing the affinity matrix for the current segments - frame_index (int): - Unique index for each segment and embedding vector - - Returns: - est_num_of_spk: (int) - The estimated number of speakers. - p_hat_value: (int) - The estimated p-value from NMESC method. - """ - nmesc = NMESC( - mat_in, - max_num_speakers=self.max_num_speakers, - max_rp_threshold=self.max_rp_threshold, - sparse_search=True, - maj_vote_spk_count=False, - sparse_search_volume=self.sparse_search_volume, - fixed_thres=self.fixed_thres, - nme_mat_size=256, - parallelism=False, - device=mat_in.device, - cuda=self.cuda, - ) - if len(self.p_value_hist) == 0 or ( - frame_index < self.p_value_skip_frame_thres and frame_index % self.p_update_freq == 0 - ): - est_num_of_spk, p_hat_value = nmesc.forward() - self.p_value_hist.append(p_hat_value) - if len(self.p_value_hist) > self.p_value_queue_size: - self.p_value_hist.pop(0) - p_hat_int_list: List[int] = [int(p) for p in self.p_value_hist] - p_hat_value = torch.mode(torch.tensor(p_hat_int_list))[0].item() - output = nmesc.getEigRatio(p_hat_value) - g_p, est_num_of_spk = output[0], output[1].int() - return est_num_of_spk, p_hat_value - - def speaker_counter_buffer(self, est_num_of_spk: int) -> torch.Tensor: - """ - Use a queue to avoid unstable speaker counting results. - - Args: - est_num_of_spk (int): - Estimated number of speakers - - Returns: - est_num_of_spk (torch.Tensor): - Estimated number of speakers from the speaker counting buffer. - """ - est_num_of_spk = torch.tensor(est_num_of_spk) - self.num_spk_stat.append(est_num_of_spk) - if len(self.num_spk_stat) > self.min_spk_counting_buffer_size: - self.num_spk_stat.pop(0) - num_spk_stat_tensor = torch.tensor([int(s) for s in self.num_spk_stat]) - num_spks_bincount = torch.bincount(num_spk_stat_tensor) - est_num_of_spk = torch.argmax(num_spks_bincount) - return est_num_of_spk - - def limit_frames_per_speaker(self, frame_index: int, est_num_of_spk: int) -> int: - """ - Limit the estimated number of speakers in proportion to the number of speakers. - - Args: - frame_index (int): - Unique index for each segment and embedding vector - est_num_of_spk (int): - Estimated number of speakers - - Returns: - (int) Estimated number of speakers capped by `self.min_frame_per_spk` - """ - return min(est_num_of_spk, int(1 + frame_index // self.min_frame_per_spk)) - - def online_spk_num_estimation(self, mat_in: torch.Tensor, frame_index: int) -> Tuple[int, torch.Tensor]: - """ - Online version of speaker estimation involves speaker counting buffer and application of per-speaker - frame count limit. - - Args: - mat_in (Tensor): - Raw affinity matrix containing similarity values of each pair of segments - frame_index (int) - Unique frame index of online processing pipeline - - Returns: - est_num_of_spk (int): - Estimated number of speakers - affinity_mat (Tensor): - Affinity matrix after applying the affinity threshold with `p_hat_value` - """ - est_num_of_spk, p_hat_value = self.onlineNMEanalysis(mat_in, frame_index) - affinity_mat = getAffinityGraphMat(mat_in, p_hat_value) - raw_est_num_of_spk = self.speaker_counter_buffer(est_num_of_spk) - est_num_of_spk = self.limit_frames_per_speaker(frame_index, raw_est_num_of_spk.item()) - return est_num_of_spk, affinity_mat - - def prepare_embedding_update( - self, emb_in: torch.Tensor, segment_indexes_matrix: torch.Tensor - ) -> Tuple[bool, int, torch.Tensor, torch.Tensor]: - """ - This function performs the following tasks: - 1. Decide whether to extract more embeddings or not (by setting `is_update`) - (Only if we need update): - 2. Calculate how many embeddings should be updated (set `new_emb_n` variable) - 3. Update history embedding vectors and save it to `pre_embs`. - - We only save the index and clustering label of each embedding. - - - Case-1: The very first step - This else statement is for the very first diarization loop. - This is the very first reduction frame. - - - Case-2: Number of embedding vectors is increased, therefore we need to update. - Since there are new embeddings, we push the same amount (new_emb_n) - of old embeddings to the history buffer. - We should also update self.history_buffer_seg_end which is a pointer. - update to history emb: emb_in[emb_idx_stt:emb_idx_end] - update to history label: self.Y_fullhist[label_stt:_end] - - - Case-3: Number of embedding vectors is decreased - If the number of embeddings is decreased compared to the last trial, - then skip embedding merging. - - Variables: - hist_curr_boundary (int): - The current boundary of between history buffer and current buffer. - This is the new history-current buffer boundary while self.history_buffer_seg_end is the old one. - Thus, the new set of embedding vectors are collected from - `label_stt=self.hist_buffer_seg_end` to `label_end=hist_curr_boundary`. - total_segments_processed_count (int): - The number of segments that are processed so far in integer format. - - Args: - emb_in (Tensor): - Tensor containing embedding vectors - Dimensions: (number of embedding vectors) x (embedding dimension) - segment_indexes_matrix (Tensor): - Tensor containing unique segment (embedding vector) index - - Returns: - is_update (bool): - Boolean indicates whether to update speaker embedding vectors. - new_emb_n (int): - The amount of embedding vectors that are exceeding FIFO queue size. - new_emb_n is also an amount of embedding vectors that needs to be merged in history buffer. - pre_embs (Tensor): - Embedding vector matrix before merging. - The subset of `pre_embs` embedding vectors will be merged. - Dimensions: (number of embedding vectors) x (embedding dimension) - pre_clus_labels (Tensor): - A set of clustering labels for each embedding vector in `pre_embs`. - """ - total_segments_processed_count = int(segment_indexes_matrix[-1] + 1) - hist_curr_boundary = int(total_segments_processed_count - self.current_n) - new_emb_n: int = 0 - pre_embs: torch.Tensor = torch.empty(0) - pre_clus_labels: torch.Tensor = torch.empty(0) - is_update = True - - if total_segments_processed_count > self.max_embed_count: - # Case-1: The very first step - if len(self.history_embedding_buffer_emb) == 0: - new_emb_n = total_segments_processed_count - (self.current_n + self.history_n) - hist_curr_boundary_emb_idx = get_first_arg_index(segment_indexes_matrix, hist_curr_boundary) - pre_embs = emb_in[:hist_curr_boundary_emb_idx] - pre_clus_labels = self.Y_fullhist[:hist_curr_boundary] - - # Case-2: Number of embedding vectors is increased, need to update history and its label - else: - # Calculate the number of new embedding vectors: `new_emb_n` - label_stt, label_end = self.history_buffer_seg_end, hist_curr_boundary - new_emb_n = label_end - label_stt - # Add embedding vectors to `pre_embs` so that we can merge it with reducer function. - emb_idx_stt = int(get_first_arg_index(segment_indexes_matrix, label_stt)) - emb_idx_end = int(get_first_arg_index(segment_indexes_matrix, label_end)) - pre_embs = torch.vstack((self.history_embedding_buffer_emb, emb_in[emb_idx_stt:emb_idx_end])) - # Update labels for `pre_embs` - pre_clus_labels = torch.hstack( - (self.history_embedding_buffer_label, self.Y_fullhist[label_stt:label_end]) - ) - - if new_emb_n > self.current_n: - raise ValueError( - "new_emb_n should be less than or equal to current buffer size (self.current_n)." - f" Getting too many segments: {new_emb_n} for the given current buffer size {self.current_n}." - " Please either (1) increase buffer size or (2) use longer segment lengths to get less number of segments." - ) - elif new_emb_n <= 0: - raise ValueError("Segment counting error. `new_emb_n` should be a positve integer number.") - if pre_embs.shape[0] != pre_clus_labels.shape[0]: - raise ValueError( - "`pre_embs` and `pre_clus_labels` should have the same length, " - f"but got {pre_embs.shape[0]} and {pre_clus_labels.shape[0]} respectively." - ) - - # Case-3: Number of embedding vectors is not increased. - else: - # There will be no embedding update, so new_emb_n is 0, pre_embs and pre_clus_labels are empty. - is_update = False - - # Update the history buffer index for the next step - self.history_buffer_seg_end = hist_curr_boundary - self.max_embed_count = max(total_segments_processed_count, self.max_embed_count) - return is_update, new_emb_n, pre_embs, pre_clus_labels - - def make_constant_length_emb(self, emb_in: torch.Tensor, base_segment_indexes: torch.Tensor) -> torch.Tensor: - """ - This function deals with edge cases when the number of segments decreases and the number of embedding falls - short for the labels. - - - ASR decoder occasionally returns less number of words compared to the previous frame. - - In this case, we obtain fewer embedding vectors for the short period of time. To match the pre-defined - length, the last embedding vector is repeated to fill the voidness. - - The repeated embedding will be soon replaced by the actual embeddings once the system takes new frames. - - Args: - emb_in (Tensor): - If self.is_online is False: - `pre_embs` contains only current speaker embedding inputs, which is FIFO queue - If self.is_online is True: - `pre_embs` contains history buffer and FIFO queue - base_segment_indexes (Tensor): - Tensor containing unique segment (embedding vector) index - - Returns: - emb_curr (Tensor): - Length preserved speaker embedding vectors - """ - curr_clustered_segments = torch.where(base_segment_indexes >= self.history_buffer_seg_end)[0] - - # Check if the current buffer result is falling short compared to `self.current_n`. - if emb_in[curr_clustered_segments].shape[0] < self.current_n: - delta_count = self.current_n - emb_in[curr_clustered_segments].shape[0] - fill_in_emb = torch.tile(emb_in[curr_clustered_segments][-1], (delta_count, 1)) - emb_curr = torch.vstack((emb_in[curr_clustered_segments], fill_in_emb)) - else: - emb_curr = emb_in[curr_clustered_segments] - return emb_curr - - def update_speaker_history_buffer( - self, emb_in: torch.Tensor, base_segment_indexes: torch.Tensor - ) -> Tuple[torch.Tensor, bool]: - """ - Merge the given embedding vectors based on the calculate affinity matrix. - if `is_update` is True, update the history buffer . - - Args: - emb_in (Tensor): - If self.is_online is False: - `emb` contains only current speaker embedding inputs, which is FIFO queue - If self.is_online is True: - `emb` contains history buffer and FIFO queue - base_segment_indexes (Tensor): - Tensor containing unique segment (embedding vector) index - - Returns: - history_embedding_buffer_emb (Tensor): - Matrix containing merged embedding vectors of the previous frames. - This matrix is referred to as "history buffer" in this class. - is_update (bool): - Boolean indicates whether to update speaker - - Example: - - at the frame index where `is_online` turns to True: - - |------hist-buffer------|-----FIFO-queue-----| - - self.history_n = 20 - self.current_n = 10 - - Step (1) - |-----------------------|ABCDEF--------------| - - If we get two more segments, "NN" as in the description: - history buffer = 20 - current buffer = 12 - - Step (2) - |-----------------------|ABCDEF--------------XY| - |---------emb_in-------| - - The newly accepted embeddings go through a FIFO queue (first come, first merge) - history buffer = 22 - current buffer = 10 - - Step (3) - |-----------------------AB|CDEF--------------XY| - |---------pre_embs--------| - - After merging (reducing) the embedding set gets back to the original size: - history buffer = 20 - current buffer = 10 - - Step (4) - |======================|CDEF--------------XY| - |-----hist_emb_buff----| - - After clustering, `self.Y_fullhist` is updated as: - - |0000000000011111111111|11110000110010010011| - - The dimension of `self.Y_fullhist` is (`history_n + current_n`) x 1 - - self.history_buffer_seg_end (int): - The total number of segments that have been merged from the beginning of the session. - (=`hist_curr_boundary`) - """ - is_update, new_emb_n, pre_embs, pre_clus_labels = self.prepare_embedding_update(emb_in, base_segment_indexes) - - # Update the history/current_buffer boundary cursor - total_emb, total_cluster_labels = [], [] - - if is_update: - # Calculate how many embedding vectors should be reduced per speaker - class_target_vol = get_merge_quantity( - num_to_be_removed=new_emb_n, - pre_clus_labels=pre_clus_labels, - min_count_per_cluster=self.minimum_segments_per_buffer, - ) - - # Merge the segments in the history buffer - for spk_idx, sub_cluster_num in enumerate(list(class_target_vol)): - merged_embs, merged_clus_labels, _ = run_reducer( - pre_embs=pre_embs, - target_spk_idx=spk_idx, - merge_quantity=sub_cluster_num.item(), - pre_clus_labels=pre_clus_labels, - ) - total_emb.append(merged_embs) - total_cluster_labels.append(merged_clus_labels) - - # Update the speaker history buffer - self.history_embedding_buffer_emb = torch.vstack(total_emb) - self.history_embedding_buffer_label = torch.hstack(total_cluster_labels) - if self.history_embedding_buffer_emb.shape[0] != self.history_n: - raise ValueError("History embedding size is not maintained correctly.") - if len(self.history_embedding_buffer_label) != self.history_n: - raise ValueError("History label size is not maintained correctly.") - - else: - total_emb.append(self.history_embedding_buffer_emb) - total_cluster_labels.append(self.history_embedding_buffer_label) - - # `emb_curr` is the incumbent set of embeddings which is the the latest. - emb_curr = self.make_constant_length_emb(emb_in, base_segment_indexes) - total_emb.append(emb_curr) - - # Before perform clustering, we attach the current_n number of estimated speaker labels - # from the previous clustering result. - total_cluster_labels.append(self.Y_fullhist[-self.current_n :]) - - history_and_current_emb = torch.vstack(total_emb) - history_and_current_labels = torch.hstack(total_cluster_labels) - if history_and_current_emb.shape[0] != len(history_and_current_labels): - raise ValueError("`history_and_current_emb` has a mismatch in length with `history_and_current_labels`.") - return history_and_current_emb, is_update - - def get_reduced_mat(self, emb_in: torch.Tensor, base_segment_indexes: torch.Tensor) -> Tuple[torch.Tensor, bool]: - """ - Choose whether we want to add embeddings to the memory or not. - The processing buffer has size of (self.current_n + self.history_n). - - Case-1: If margin_seg_n > 0, this means we have more embedding vectors than we can hold in the processing buffer. - - `is_online` should be `True` - - reduce the number of embedding vectors by merging the closest ones. - call `update_speaker_history_buffer` function - - Case-2: If margin_seg_n <= 0, this means that we can accept more embedding vectors and yet to fill the processing buffer. - - `is_online` should be `False` - - Replace `merged_emb` variable with the raw input `emb_in`. - - `add_new` is `True`, since we are adding more embedding vectors to `merged_emb` variable. - - Args: - emb_in (Tensor): - If self.is_online is False: - `emb` contains only current speaker embedding inputs - base_segment_indexes (Tensor): - Tensor containing unique segment (embedding vector) index - - Returns: - merged_emb (Tensor): - Matrix containing merged embedding vectors of the previous frames. - This matrix is referred to as "history buffer" in this class. - If self.is_online is False: - `merged_emb` contains only current speaker embedding inputs - If self.is_online is True: - `merged_emb` is a concatenated matrix with history embedding and current embedding inputs - add_new (bool): - Boolean that indicates whether there is a new set of segments. Depending on the VAD timestamps, - the number of subsegments can be ocassionally decreased. If `add_new=True`, then it adds the newly - acquired cluster labels. - """ - margin_seg_n = emb_in.shape[0] - (self.current_n + self.history_n) - if len(self.Y_fullhist) == 0 and margin_seg_n > 0: - raise ValueError( - "The number of incoming embedding vectors is larger than the total processing buffer size." - "Please either (1) increase the history and current buffer size (2) or use longer segment lengths to reduce number of segments." - ) - if margin_seg_n > 0: - self.is_online = True - merged_emb, add_new = self.update_speaker_history_buffer( - emb_in=emb_in, base_segment_indexes=base_segment_indexes - ) - else: - self.is_online = False - merged_emb = emb_in - add_new = True - return merged_emb, add_new - - def match_labels(self, Y_merged: torch.Tensor, add_new: bool) -> torch.Tensor: - """ - This function matches the newly generated clustering label sequence with the existing speaker labels in the history buffer. - `self.history_buffer_seg_end` is an integer index that tells to which point is history embedding contains from `self.Y_fullhist`. - - If embedding reducing is done correctly, we should discard (0, self.history_n) amount and take - (self.history_n, len(Y_merged)) from the new clustering output `Y_merged`. - - Args: - Y_merged (Tensor): - The newly generated clustering label sequence that may have different permutations with the existing - speaker labels in the history buffer. - add_new (bool): - This variable indicates whether there is a new set of segments. Depending on the VAD timestamps, - the number of subsegments can be occasionally decreased. If `add_new=True`, then it adds the newly - acquired cluster labels. - - Returns: - Y_out (Tensor): - Permutation-matched speaker labels based on history buffer - """ - if self.is_online: - # Online clustering mode with history buffer - Y_old = torch.hstack((self.history_embedding_buffer_label, self.Y_fullhist[self.history_buffer_seg_end :])) - - # Stitch the old history and new cluster labels - Y_matched = stitch_cluster_labels(Y_old=Y_old, Y_new=Y_merged).to(Y_merged.device) - if add_new: - if Y_matched[self.history_n :].shape[0] != self.current_n: - raise ValueError("Update point sync is not correct.") - # Concatenate the newly generated speaker labels - Y_out = torch.hstack((self.Y_fullhist[: self.history_buffer_seg_end], Y_matched[self.history_n :])) - self.Y_fullhist = Y_out - else: - # Do not update cumulative labels since there are no new segments. - Y_out = self.Y_fullhist - else: - # If no memory is used, offline clustering is applied. - Y_out = stitch_cluster_labels(Y_old=self.Y_fullhist, Y_new=Y_merged).to(Y_merged.device) - self.Y_fullhist = Y_out - return Y_out - - def forward( - self, - curr_emb, - base_segment_indexes, - max_num_speakers: int, - max_rp_threshold: float, - enhanced_count_thres: int, - sparse_search_volume: int, - frame_index: int, - cuda: bool = False, - ) -> torch.Tensor: - """ - Wrapper function for torch.jit.script compatibility. - NOTE: jit scripted classes only contain the methods which are included in the computation graph in the forward pass. - """ - Y = self.forward_infer( - curr_emb=curr_emb, - base_segment_indexes=base_segment_indexes, - max_num_speakers=max_num_speakers, - max_rp_threshold=max_rp_threshold, - enhanced_count_thres=enhanced_count_thres, - sparse_search_volume=sparse_search_volume, - frame_index=frame_index, - cuda=cuda, - ) - return Y - - def forward_infer( - self, - curr_emb: torch.Tensor, - base_segment_indexes: torch.Tensor, - max_num_speakers: int = 4, - max_rp_threshold: float = 0.15, - enhanced_count_thres: int = 40, - sparse_search_volume: int = 10, - fixed_thres: float = -1.0, - frame_index: int = 0, - cuda: bool = False, - ) -> torch.Tensor: - """ - Perform speaker clustering in online mode. Embedding vector set `emb` is expected to be containing - history embeddings to count the number of speakers. - - Args: - curr_emb (Tensor): - Current embedding vector input. - base_segment_indexes (Tensor): - Tensor containing unique segment (embedding vector) index - max_num_speakers (int): - Maximum number of speakers to be detected during online diarization session - max_rp_threshold (float): - Limits the range of parameter search. - Clustering performance can vary depending on this range. - Default is 0.25. - max_rp_threshold (float): - Limits the range of parameter search. - Clustering performance can vary depending on this range. - Default is 0.15. - frame_index (int): - Unique index for each segment (also each embedding vector) - cuda (bool): - Boolean that determines whether cuda is used or not - device (torch.device): - `torch.device` variable - - Returns: - Y (Tensor): - Speaker labels for history embeddings and current embedding inputs - """ - self.max_num_speakers = max_num_speakers - self.max_rp_threshold = max_rp_threshold - self.enhanced_count_thres = enhanced_count_thres - self.sparse_search_volume = sparse_search_volume - self.fixed_thres = fixed_thres - - # Merge the closest embeddings and reduce the size of the embedding count. - if cuda and (curr_emb.device == torch.device("cpu") or base_segment_indexes.device == torch.device("cpu")): - raise ValueError(f"CUDA is enabled but the input {curr_emb} or {base_segment_indexes} is not on the GPU.") - - merged_embs, add_new = self.get_reduced_mat(emb_in=curr_emb, base_segment_indexes=base_segment_indexes,) - # Perform clustering on the embedding matrix containing history and current FIFO buffer merged_embeddings - if merged_embs.shape[0] == 1: - Y = torch.zeros((1,), dtype=torch.int32) - else: - mat = getCosAffinityMatrix(merged_embs) - est_num_of_spk, affinity_mat = self.online_spk_num_estimation(mat, frame_index) - spectral_model = SpectralClustering(n_clusters=est_num_of_spk, cuda=cuda, device=merged_embs.device) - Y = spectral_model.forward(affinity_mat).to(merged_embs.device) - # Match the permutation of the newly obtained speaker labels and the previous labels - merged_clus_labels = self.match_labels(Y_merged=Y, add_new=add_new) - return merged_clus_labels diff --git a/nemo/collections/asr/parts/utils/optimization_utils.py b/nemo/collections/asr/parts/utils/optimization_utils.py deleted file mode 100644 index f947007e59b41b4723b0adfd131c679dbc3c179e..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/optimization_utils.py +++ /dev/null @@ -1,343 +0,0 @@ -# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# The original code of Linear Sum Assignment solver is -# from: https://github.com/scipy/scipy/blob/v0.18.1/scipy/optimize/_hungarian.py -# The following is the full text of the license: - -# Hungarian algorithm (Kuhn-Munkres) for solving the linear sum assignment -# problem. Taken from scikit-learn. Based on original code by Brian Clapper, -# adapted to NumPy by Gael Varoquaux. -# Further improvements by Ben Root, Vlad Niculae and Lars Buitinck. -# Copyright (c) 2008 Brian M. Clapper , Gael Varoquaux -# Author: Brian M. Clapper, Gael Varoquaux -# License: 3-clause BSD - -import torch - - -@torch.jit.script -def unravel_index(index: int, shape: torch.Tensor): - """ - Unravel the index input to fit the given shape. - This function is needed for torch.jit.script compatibility. - - Args: - index (int): The index to unravel. - shape (Tesnor): The shape to unravel the index to. - - Returns: - Tensor: The unraveled index. - """ - out = [] - shape = torch.flip(shape, dims=(0,)) - for dim in shape: - out.append(index % dim) - index = index // dim - out = torch.tensor([int(x.item()) for x in out]) - return torch.flip(out, dims=(0,)) - - -@torch.jit.script -class LinearSumAssignmentSolver(object): - """ - A Solver class for the linear sum assignment (LSA) problem. - Designed for torch.jit.script compatibility in NeMo. - - The LSA problem is also referred to as bipartite matching problem. An LSA problem is described - by a matrix `cost_mat`, where each cost_mat[i,j] is the cost of matching vertex i of the first partite - set (e.g. a "worker") and vertex j of the second set (e.g. a "job"). - - Thus, the goal of LSA-solver is to find a complete assignment of column element to row element with - the minimal cost. Note that the solution may not be unique and there could be multiple solutions that - yield the same minimal cost. - - LSA problem solver is needed for the following tasks in NeMo: - - Permutation Invariant Loss (PIL) for diarization model training - - Label permutation matching for online speaker diarzation - - Concatenated minimum-permutation Word Error Rate (cp-WER) calculation - - This implementation is based on the LAP solver from scipy: - https://github.com/scipy/scipy/blob/v0.18.1/scipy/optimize/_hungarian.py - The scipy implementation comes with the following license: - - Copyright (c) 2008 Brian M. Clapper , Gael Varoquaux - Author: Brian M. Clapper, Gael Varoquaux - License: 3-clause BSD - - References - 1. http://csclab.murraystate.edu/bob.pilgrim/445/munkres.html - 2. https://en.wikipedia.org/wiki/Hungarian_algorithm - 3. https://github.com/scipy/scipy/blob/v0.18.1/scipy/optimize/_hungarian.py - - - Attributes: - cost_mat (Tensor): 2D matrix containing cost matrix. Number of columns must be larger than number of rows. - row_uncovered (Tensor): 1D matrix containing boolean values indicating whether a row is covered. - col_uncovered (Tensor): 1D matrix containing boolean values indicating whether a column is covered. - zero_row (Tensor): 1D matrix containing the row index of the last zero found. - zero_col (Tensor): 1D matrix containing the column index of the last zero found. - path (Tensor): 2D matrix containing the path taken through the matrix. - marked (Tensor): 2D matrix containing the marked zeros. - """ - - def __init__(self, cost_matrix: torch.Tensor): - # The main cost matrix - self.cost_mat = cost_matrix - row_len, col_len = self.cost_mat.shape - - # Initialize the solver state - self.zero_row = torch.tensor(0, dtype=torch.long).to(cost_matrix.device) - self.zero_col = torch.tensor(0, dtype=torch.long).to(cost_matrix.device) - - # Initialize the covered matrices - self.row_uncovered = torch.ones(row_len, dtype=torch.bool).to(cost_matrix.device) - self.col_uncovered = torch.ones(col_len, dtype=torch.bool).to(cost_matrix.device) - - # Initialize the path matrix and the mark matrix - self.path = torch.zeros((row_len + col_len, 2), dtype=torch.long).to(cost_matrix.device) - self.marked = torch.zeros((row_len, col_len), dtype=torch.long).to(cost_matrix.device) - - def _reset_uncovered_mat(self): - """ - Clear all covered matrix cells and assign `True` to all uncovered elements. - """ - self.row_uncovered[:] = True - self.col_uncovered[:] = True - - def _step1(self): - """ - Step 1 - - Goal: Subtract the smallest element of each row from its elements. - - All elements of the matrix are now non-negative. - - Therefore, an assignment of total cost 0 is the minimum cost assignment. - - This operation leads to at least one zero in each row. - - Procedure: - - For each row of the matrix, find the smallest element and subtract it from every element in its row. - - Go to Step 2. - """ - self.cost_mat -= torch.min(self.cost_mat, dim=1)[0].unsqueeze(1) - return 2 - - def _step2(self): - """ - Step 2 - - Goal: Make sure assignment with cost sum 0 is feasible. - - Procedure: - - Find a zero in the resulting cost matrix. - - If there are no marked zeros in its row or column, mark the zero. - - Repeat for each element in the matrix. - - Go to step 3. - """ - ind_out = torch.where(self.cost_mat == 0) - ind, val = list(ind_out[0]), list(ind_out[1]) - for i, j in zip(ind, val): - if self.col_uncovered[j] and self.row_uncovered[i]: - self.marked[i, j] = 1 - self.col_uncovered[j] = False - self.row_uncovered[i] = False - - self._reset_uncovered_mat() - return 3 - - def _step3(self) -> int: - """ - Step 3 - - Goal: All zeros in the matrix must be covered by marking with the least numbers of rows and columns. - - Procedure: - - Cover each column containing a marked zero. - - If n columns are covered, the marked zeros describe a complete set of unique assignments. - In this case, Go to Step 0 (Done state) - - Otherwise, Go to Step 4. - """ - marked = self.marked == 1 - self.col_uncovered[torch.any(marked, dim=0)] = False - if marked.sum() < self.cost_mat.shape[0]: - return 4 # Go to step 4 - else: - return 0 # Go to step 0 (Done state) - - def _step4(self, bypass: bool = False) -> int: - """ - Step 4 - - Goal: Cover all columns containing a marked zero. - - Procedure: - - Find a non-covered zero and put a prime mark on it. - - If there is no marked zero in the row containing this primed zero, Go to Step 5. - - Otherwise, cover this row and uncover the column containing the marked zero. - - Continue in this manner until there are no uncovered zeros left. - - Save the smallest uncovered value. - - Go to Step 6. - """ - # We convert to int as numpy operations are faster on int - cost_mat = (self.cost_mat == 0).int() - covered_cost_mat = cost_mat * self.row_uncovered.unsqueeze(1) - covered_cost_mat *= self.col_uncovered.long() - row_len, col_len = self.cost_mat.shape - if not bypass: - while True: - urv = unravel_index(torch.argmax(covered_cost_mat).item(), torch.tensor([col_len, row_len])) - row, col = int(urv[0].item()), int(urv[1].item()) - if covered_cost_mat[row, col] == 0: - return 6 - else: - self.marked[row, col] = 2 # Find the first marked element in the row - mark_col = torch.argmax((self.marked[row] == 1).int()) - if self.marked[row, mark_col] != 1: # No marked element in the row - self.zero_row = torch.tensor(row) - self.zero_col = torch.tensor(col) - return 5 - else: - col = mark_col - self.row_uncovered[row] = False - self.col_uncovered[col] = True - covered_cost_mat[:, col] = cost_mat[:, col] * self.row_uncovered - covered_cost_mat[row] = 0 - return 0 - - def _step5(self) -> int: - """ - Step 5 - - Goal: Construct a series of alternating primed and marked zeros as follows. - - Procedure: - - Let Z0 represent the uncovered primed zero found in Step 4. - - Let Z1 denote the marked zero in the column of Z0 (if any). - - Let Z2 denote the primed zero in the row of Z1 (there will always be one). - - Continue until the series terminates at a primed zero that has no marked zero in its column. - - Unmark each marked zero of the series. - - Mark each primed zero of the series. - - Erase all primes and uncover every line in the matrix. - - Return to Step 3 - """ - count = torch.tensor(0) - path = self.path - path[count, 0] = self.zero_row.long() - path[count, 1] = self.zero_col.long() - - while True: # Unmark each marked zero of the series - # Find the first marked element in the col defined by the path (= `val`) - row = torch.argmax((self.marked[:, path[count, 1]] == 1).int()) - - if self.marked[row, path[count, 1]] != 1: - # Could not find one - break - else: - count += 1 - path[count, 0] = row - path[count, 1] = path[count - 1, 1] - - # Find the first prime element in the row defined by the first path step - col = int(torch.argmax((self.marked[path[count, 0]] == 2).int())) - if self.marked[row, col] != 2: - col = -1 - count += 1 - path[count, 0] = path[count - 1, 0] - path[count, 1] = col - - # Convert paths - for i in range(int(count.item()) + 1): - if self.marked[path[i, 0], path[i, 1]] == 1: - self.marked[path[i, 0], path[i, 1]] = 0 - else: - self.marked[path[i, 0], path[i, 1]] = 1 - - self._reset_uncovered_mat() - - # Remove all prime markings in marked matrix - self.marked[self.marked == 2] = 0 - return 3 - - def _step6(self) -> int: - """ - Step 6 - - Goal: Prepare for another iteration by modifying the cost matrix. - - Procedure: - - Add the value found in Step 4 to every element of each covered row. - - Subtract it from every element of each uncovered column. - - Return to Step 4 without altering any marks, primes, or covered lines. - """ - if torch.any(self.row_uncovered) and torch.any(self.col_uncovered): - row_minval = torch.min(self.cost_mat[self.row_uncovered], dim=0)[0] - minval = torch.min(row_minval[self.col_uncovered]) - self.cost_mat[~self.row_uncovered] += minval - self.cost_mat[:, self.col_uncovered] -= minval - return 4 - - -@torch.jit.script -def linear_sum_assignment(cost_matrix: torch.Tensor, max_size: int = 100): - """ - Launch the linear sum assignment algorithm on a cost matrix. - - Args: - cost_matrix (Tensor): The cost matrix of shape (N, M) where M should be larger than N. - - Returns: - row_index (Tensor): The row indices of the optimal assignments. - col_index (Tensor): The column indices of the optimal assignments. - """ - cost_matrix = cost_matrix.clone().detach() - - if len(cost_matrix.shape) != 2: - raise ValueError(f"2-d tensor is expected but got a {cost_matrix.shape} tensor") - if max(cost_matrix.shape) > max_size: - raise ValueError( - f"Cost matrix size {cost_matrix.shape} is too large. The maximum supported size is {max_size}x{max_size}." - ) - - # The algorithm expects more columns than rows in the cost matrix. - if cost_matrix.shape[1] < cost_matrix.shape[0]: - cost_matrix = cost_matrix.T - transposed = True - else: - transposed = False - - lap_solver = LinearSumAssignmentSolver(cost_matrix) - f_int: int = 0 if 0 in cost_matrix.shape else 1 - - # while step is not Done (step 0): - # NOTE: torch.jit.scipt does not support getattr with string argument. - # Do not use getattr(lap_solver, f"_step{f_int}")() - while f_int != 0: - if f_int == 1: - f_int = lap_solver._step1() - elif f_int == 2: - f_int = lap_solver._step2() - elif f_int == 3: - f_int = lap_solver._step3() - elif f_int == 4: - f_int = lap_solver._step4() - elif f_int == 5: - f_int = lap_solver._step5() - elif f_int == 6: - f_int = lap_solver._step6() - - if transposed: - marked = lap_solver.marked.T - else: - marked = lap_solver.marked - row_index, col_index = torch.where(marked == 1) - return row_index, col_index diff --git a/nemo/collections/asr/parts/utils/regularization_utils.py b/nemo/collections/asr/parts/utils/regularization_utils.py deleted file mode 100644 index 871b4889ad68c6338514add9313fd8778910d55d..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/regularization_utils.py +++ /dev/null @@ -1,64 +0,0 @@ -# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import List - - -def compute_stochastic_depth_drop_probs( - num_layers: int, - stochastic_depth_drop_prob: float = 0.0, - stochastic_depth_mode: str = "linear", - stochastic_depth_start_layer: int = 1, -) -> List[float]: - """Computes drop probabilities for stochastic depth regularization technique. - The first layer is never dropped and the starting layer needs to be greater - or equal to 1. - - Args: - num_layers (int): number of layers in the network. - stochastic_depth_drop_prob (float): if non-zero, will randomly drop - layers during training. The higher this value, the more often layers - are dropped. Defaults to 0.0. - stochastic_depth_mode (str): can be either "linear" or "uniform". If - set to "uniform", all layers have the same probability of drop. If - set to "linear", the drop probability grows linearly from 0 for the - first layer to the desired value for the final layer. Defaults to - "linear". - stochastic_depth_start_layer (int): starting layer for stochastic depth. - All layers before this will never be dropped. Note that drop - probability will be adjusted accordingly if mode is "linear" when - start layer is > 1. Defaults to 1. - Returns: - List[float]: list of drop probabilities for all layers - """ - if not (0 <= stochastic_depth_drop_prob < 1.0): - raise ValueError("stochastic_depth_drop_prob has to be in [0, 1).") - if not (1 <= stochastic_depth_start_layer <= num_layers): - raise ValueError("stochastic_depth_start_layer has to be in [1, num layers].") - - # Layers before `stochastic_depth_start_layer` are never dropped - layer_drop_probs = [0.0] * stochastic_depth_start_layer - - # Layers starting with `stochastic_depth_start_layer` may be dropped - if (L := num_layers - stochastic_depth_start_layer) > 0: - if stochastic_depth_mode == "linear": - # we start with 1/L * drop_prob and and end with the desired drop probability. - layer_drop_probs += [l / L * stochastic_depth_drop_prob for l in range(1, L + 1)] - elif stochastic_depth_mode == "uniform": - layer_drop_probs += [stochastic_depth_drop_prob] * L - else: - raise ValueError( - f'stochastic_depth_mode has to be one of ["linear", "uniform"]. Current value: {stochastic_depth_mode}' - ) - return layer_drop_probs diff --git a/nemo/collections/asr/parts/utils/rnnt_utils.py b/nemo/collections/asr/parts/utils/rnnt_utils.py deleted file mode 100644 index 1765a493ced9cfa60567170e390fd9c2480520ab..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/rnnt_utils.py +++ /dev/null @@ -1,845 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Copyright 2017 Johns Hopkins University (Shinji Watanabe) -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from dataclasses import dataclass, field -from typing import Any, Dict, List, Optional, Tuple, Union - -import torch - -from nemo.collections.asr.parts.context_biasing.biasing_multi_model import BiasingRequestItemConfig - - -@dataclass -class Hypothesis: - """Hypothesis class for beam search algorithms. - - score: A float score obtained from an AbstractRNNTDecoder module's score_hypothesis method. - - y_sequence: Either a sequence of integer ids pointing to some vocabulary, or a packed torch.Tensor - behaving in the same manner. dtype must be torch.Long in the latter case. - - dec_state: A list (or list of list) of LSTM-RNN decoder states. Can be None. - - text: (Optional) A decoded string after processing via CTC / RNN-T decoding (removing the CTC/RNNT - `blank` tokens, and optionally merging word-pieces). Should be used as decoded string for - Word Error Rate calculation. - - timestamp: (Optional) A list of integer indices representing at which index in the decoding - process did the token appear. Should be of same length as the number of non-blank tokens. - - alignments: (Optional) Represents the CTC / RNNT token alignments as integer tokens along an axis of - time T (for CTC) or Time x Target (TxU). - For CTC, represented as a single list of integer indices. - For RNNT, represented as a dangling list of list of integer indices. - Outer list represents Time dimension (T), inner list represents Target dimension (U). - The set of valid indices **includes** the CTC / RNNT blank token in order to represent alignments. - - frame_confidence: (Optional) Represents the CTC / RNNT per-frame confidence scores as token probabilities - along an axis of time T (for CTC) or Time x Target (TxU). - For CTC, represented as a single list of float indices. - For RNNT, represented as a dangling list of list of float indices. - Outer list represents Time dimension (T), inner list represents Target dimension (U). - - token_confidence: (Optional) Represents the CTC / RNNT per-token confidence scores as token probabilities - along an axis of Target U. - Represented as a single list of float indices. - - word_confidence: (Optional) Represents the CTC / RNNT per-word confidence scores as token probabilities - along an axis of Target U. - Represented as a single list of float indices. - - length: Represents the length of the sequence (the original length without padding), otherwise - defaults to 0. - - y: (Unused) A list of torch.Tensors representing the list of hypotheses. - - lm_state: (Unused) A dictionary state cache used by an external Language Model. - - lm_scores: (Unused) Score of the external Language Model. - - ngram_lm_state: (Optional) State of the external n-gram Language Model. - - tokens: (Optional) A list of decoded tokens (can be characters or word-pieces. - - last_token (Optional): A token or batch of tokens which was predicted in the last step. - - last_frame (Optional): Index of the last decoding step hypothesis was updated including blank token prediction. - - xatt_scores (Optional): List of cross-attention scores for each decoder layer. Each element of the list is a - Tensor of shape num heads x decoder input len x encoder output len (HxUxT). This is useful only for AED models. - """ - - score: float - y_sequence: Union[List[int], torch.Tensor] - text: Optional[str] = None - dec_out: Optional[List[torch.Tensor]] = None - dec_state: Optional[Union[List[List[torch.Tensor]], List[torch.Tensor]]] = None - timestamp: Union[List[int], torch.Tensor] = field(default_factory=list) - alignments: Optional[Union[List[int], List[List[int]]]] = None - frame_confidence: Optional[Union[List[float], List[List[float]]]] = None - token_confidence: Optional[List[float]] = None - word_confidence: Optional[List[float]] = None - length: Union[int, torch.Tensor] = 0 - y: List[torch.tensor] = None - lm_state: Optional[Union[Dict[str, Any], List[Any]]] = None - lm_scores: Optional[torch.Tensor] = None - ngram_lm_state: Optional[Union[Dict[str, Any], List[Any]]] = None - tokens: Optional[Union[List[int], torch.Tensor]] = None - last_token: Optional[torch.Tensor] = None - token_duration: Optional[torch.Tensor] = None - last_frame: Optional[int] = None - biasing_cfg: BiasingRequestItemConfig | None = None - xatt_scores: Optional[List[torch.Tensor]] = None - - @property - def non_blank_frame_confidence(self) -> List[float]: - """Get per-frame confidence for non-blank tokens according to self.timestamp - - Returns: - List with confidence scores. The length of the list is the same as `timestamp`. - """ - non_blank_frame_confidence = [] - # self.timestamp can be a dict for RNNT - timestamp = self.timestamp['timestep'] if isinstance(self.timestamp, dict) else self.timestamp - if len(timestamp) != 0 and self.frame_confidence is not None: - if any(isinstance(i, list) for i in self.frame_confidence): # rnnt - t_prev = -1 - offset = 0 - for t in timestamp: - if t != t_prev: - t_prev = t - offset = 0 - else: - offset += 1 - non_blank_frame_confidence.append(self.frame_confidence[t][offset]) - else: # ctc - non_blank_frame_confidence = [self.frame_confidence[t] for t in timestamp] - return non_blank_frame_confidence - - @property - def words(self) -> List[str]: - """Get words from self.text - - Returns: - List with words (str). - """ - return [] if self.text is None else self.text.split() - - def merge_(self, other: "Hypothesis") -> "Hypothesis": - """Merge (inplace) current hypothesis with another one.""" - self.score += other.score - if self.y_sequence is None: - self.y_sequence = other.y_sequence - elif isinstance(self.y_sequence, torch.Tensor): - self.y_sequence = torch.cat((self.y_sequence, other.y_sequence), dim=0) - else: - self.y_sequence.extend(other.y_sequence) - self.dec_state = other.dec_state - if self.timestamp is None: - self.timestamp = other.timestamp - elif isinstance(self.timestamp, torch.Tensor): - self.timestamp = torch.cat((self.timestamp, other.timestamp), dim=0) - else: - self.timestamp.extend(other.timestamp) - self.length += other.length - self.last_token = other.last_token - if self.alignments is None: - self.alignments = other.alignments - else: - self.alignments.extend(other.alignments) - if self.frame_confidence is None: - self.frame_confidence = other.frame_confidence - else: - self.frame_confidence.extend(other.frame_confidence) - # Invalidated. Need to rerun decode_hypothesis here. - self.text = None - self.biasing_cfg = other.biasing_cfg or self.biasing_cfg - return self - - def clean_decoding_state_(self): - """Clean the decoding state to save memory.""" - self.dec_state = None - - def has_biasing_request(self) -> bool: - """Return True if contains non-empty biasing request""" - return self.biasing_cfg is not None and (not self.biasing_cfg.is_empty()) - - @classmethod - def empty_with_biasing_cfg(cls, biasing_cfg: BiasingRequestItemConfig): - """Constructor of empty hypothesis with biasing request""" - return cls(y_sequence=[], score=0.0, biasing_cfg=biasing_cfg) - - -@dataclass -class NBestHypotheses: - """List of N best hypotheses""" - - n_best_hypotheses: Optional[List[Hypothesis]] - - -@dataclass -class HATJointOutput: - """HATJoint outputs for beam search decoding - - hat_logprobs: standard HATJoint outputs as for RNNTJoint - - ilm_logprobs: internal language model probabilities (for ILM subtraction) - """ - - hat_logprobs: Optional[torch.Tensor] = None - ilm_logprobs: Optional[torch.Tensor] = None - - -def is_prefix(x: List[int], pref: List[int]) -> bool: - """ - Obtained from https://github.com/espnet/espnet. - - Check if pref is a prefix of x. - - Args: - x: Label ID sequence. - pref: Prefix label ID sequence. - - Returns: - : Whether pref is a prefix of x. - """ - if len(pref) >= len(x): - return False - - for i in range(len(pref)): - if pref[i] != x[i]: - return False - - return True - - -def select_k_expansions( - hyps: List[Hypothesis], - topk_idxs: torch.Tensor, - topk_logps: torch.Tensor, - gamma: float, - beta: int, -) -> List[Tuple[int, Hypothesis]]: - """ - Obtained from https://github.com/espnet/espnet - - Return K hypotheses candidates for expansion from a list of hypothesis. - K candidates are selected according to the extended hypotheses probabilities - and a prune-by-value method. Where K is equal to beam_size + beta. - - Args: - hyps: Hypotheses. - topk_idxs: Indices of candidates hypothesis. Shape = [B, num_candidates] - topk_logps: Log-probabilities for hypotheses expansions. Shape = [B, V + 1] - gamma: Allowed logp difference for prune-by-value method. - beta: Number of additional candidates to store. - - Return: - k_expansions: Best K expansion hypotheses candidates. - """ - k_expansions = [] - - for i, hyp in enumerate(hyps): - hyp_i = [(int(k), hyp.score + float(v)) for k, v in zip(topk_idxs[i], topk_logps[i])] - k_best_exp_val = max(hyp_i, key=lambda x: x[1]) - - k_best_exp_idx = k_best_exp_val[0] - k_best_exp = k_best_exp_val[1] - - expansions = sorted( - filter(lambda x: (k_best_exp - gamma) <= x[1], hyp_i), - key=lambda x: x[1], - ) - - if len(expansions) > 0: - k_expansions.append(expansions) - else: - k_expansions.append([(k_best_exp_idx, k_best_exp)]) - - return k_expansions - - -class BatchedHyps: - """Class to store batched hypotheses (labels, time_indices, scores) for efficient RNNT decoding""" - - def __init__( - self, - batch_size: int, - init_length: int, - device: Optional[torch.device] = None, - float_dtype: Optional[torch.dtype] = None, - is_with_durations: bool = False, - ): - """ - - Args: - batch_size: batch size for hypotheses - init_length: initial estimate for the length of hypotheses (if the real length is higher, - tensors will be reallocated) - device: device for storing hypotheses - float_dtype: float type for scores - """ - if init_length <= 0: - raise ValueError(f"init_length must be > 0, got {init_length}") - if batch_size <= 0: - raise ValueError(f"batch_size must be > 0, got {batch_size}") - self._max_length = init_length - self.batch_size = batch_size - self.device = device - self.float_dtype = float_dtype - self.is_with_durations = is_with_durations - - # batch of current lengths of hypotheses and correspoinding timestamps - self.current_lengths = torch.zeros(batch_size, device=device, dtype=torch.long) - # tensor for storing transcripts - self.transcript = torch.zeros((batch_size, self._max_length), device=device, dtype=torch.long) - # tensor for storing timestamps corresponding to transcripts - self.timestamps = torch.zeros((batch_size, self._max_length), device=device, dtype=torch.long) - # tensor for storing durations corresponding to transcripts tokens - if is_with_durations: - self.token_durations = torch.zeros((batch_size, self._max_length), device=device, dtype=torch.long) - # accumulated scores for hypotheses - self.scores = torch.zeros(batch_size, device=device, dtype=float_dtype) - - # tracking last timestamp of each hyp to avoid infinite looping (when max symbols per frame is restricted) - # last observed timestamp (with label) for each hypothesis - self.last_timestamp = torch.full((batch_size,), -1, device=device, dtype=torch.long) - # number of labels for the last timestamp - self.last_timestamp_lasts = torch.zeros(batch_size, device=device, dtype=torch.long) - self._batch_indices = torch.arange(batch_size, device=device) - self._ones_batch = torch.ones_like(self._batch_indices) - - def clear_(self): - """ - Clears batched hypotheses state. - """ - self.current_lengths.fill_(0) - self.transcript.fill_(0) - self.timestamps.fill_(0) - self.scores.fill_(0.0) - self.last_timestamp.fill_(-1) - self.last_timestamp_lasts.fill_(0) - - if self.is_with_durations: - self.token_durations.fill_(0) - - def _allocate_more(self): - """ - Allocate 2x space for tensors, similar to common C++ std::vector implementations - to maintain O(1) insertion time complexity - """ - self.transcript = torch.cat((self.transcript, torch.zeros_like(self.transcript)), dim=-1) - self.timestamps = torch.cat((self.timestamps, torch.zeros_like(self.timestamps)), dim=-1) - if self.is_with_durations: - self.token_durations = torch.cat((self.token_durations, torch.zeros_like(self.token_durations)), dim=-1) - self._max_length *= 2 - - def add_results_( - self, - active_indices: torch.Tensor, - labels: torch.Tensor, - time_indices: torch.Tensor, - scores: torch.Tensor, - token_durations: Optional[torch.Tensor] = None, - ): - """ - Add results (inplace) from a decoding step to the batched hypotheses. - We assume that all tensors have the same first dimension, and labels are non-blanks. - Args: - active_indices: tensor with indices of active hypotheses (indices should be within the original batch_size) - labels: non-blank labels to add - time_indices: tensor of time index for each label - scores: label scores - """ - if active_indices.shape[0] == 0: - return # nothing to add - # if needed - increase storage - if self.current_lengths.max().item() >= self._max_length: - self._allocate_more() - - self.add_results_no_checks_( - active_indices=active_indices, - labels=labels, - time_indices=time_indices, - scores=scores, - token_durations=token_durations if self.is_with_durations else None, - ) - - def add_results_no_checks_( - self, - active_indices: torch.Tensor, - labels: torch.Tensor, - time_indices: torch.Tensor, - scores: torch.Tensor, - token_durations: Optional[torch.Tensor] = None, - ): - """ - Add results (inplace) from a decoding step to the batched hypotheses without checks. - We assume that all tensors have the same first dimension, and labels are non-blanks. - Useful if all the memory is pre-allocated, especially with cuda graphs - (otherwise prefer a more safe `add_results_`) - Args: - active_indices: tensor with indices of active hypotheses (indices should be within the original batch_size) - labels: non-blank labels to add - time_indices: tensor of time index for each label - scores: label scores - token_durations: predicted durations for each token by TDT head - """ - # accumulate scores - self.scores[active_indices] += scores - - # store transcript and timestamps - active_lengths = self.current_lengths[active_indices] - self.transcript[active_indices, active_lengths] = labels - self.timestamps[active_indices, active_lengths] = time_indices - if token_durations is not None: - self.token_durations[active_indices, active_lengths] = token_durations - # store last observed timestamp + number of observation for the current timestamp - self.last_timestamp_lasts[active_indices] = torch.where( - self.last_timestamp[active_indices] == time_indices, self.last_timestamp_lasts[active_indices] + 1, 1 - ) - self.last_timestamp[active_indices] = time_indices - # increase lengths - self.current_lengths[active_indices] += 1 - - def add_results_masked_( - self, - active_mask: torch.Tensor, - labels: torch.Tensor, - time_indices: torch.Tensor, - scores: torch.Tensor, - token_durations: Optional[torch.Tensor] = None, - ): - """ - Add results (inplace) from a decoding step to the batched hypotheses. - We assume that all tensors have the same first dimension, and labels are non-blanks. - Args: - active_mask: tensor with mask for active hypotheses (of batch_size) - labels: non-blank labels to add - time_indices: tensor of time index for each label - scores: label scores - token_durations: token durations for TDT - """ - if (self.current_lengths + active_mask).max() >= self._max_length: - self._allocate_more() - self.add_results_masked_no_checks_( - active_mask=active_mask, - labels=labels, - time_indices=time_indices, - scores=scores, - token_durations=token_durations if self.is_with_durations else None, - ) - - def add_results_masked_no_checks_( - self, - active_mask: torch.Tensor, - labels: torch.Tensor, - time_indices: torch.Tensor, - scores: torch.Tensor, - token_durations: Optional[torch.Tensor] = None, - ): - """ - Add results (inplace) from a decoding step to the batched hypotheses without checks. - We assume that all tensors have the same first dimension, and labels are non-blanks. - Useful if all the memory is pre-allocated, especially with cuda graphs - (otherwise prefer a more safe `add_results_`) - Args: - active_mask: tensor with mask for active hypotheses (of batch_size) - labels: non-blank labels to add - time_indices: tensor of time index for each label - scores: label scores - token_durations: token durations for TDT - """ - # accumulate scores - # same as self.scores[active_mask] += scores[active_mask], but non-blocking - torch.where(active_mask, self.scores + scores, self.scores, out=self.scores) - - # store transcript and timestamps - self.transcript[self._batch_indices, self.current_lengths] = labels - self.timestamps[self._batch_indices, self.current_lengths] = time_indices - if self.is_with_durations: - self.token_durations[self._batch_indices, self.current_lengths] = token_durations - # store last observed timestamp + number of observation for the current timestamp - # if last_timestamp == time_indices, increase; else set to 1 - torch.where( - torch.logical_and(active_mask, self.last_timestamp == time_indices), - self.last_timestamp_lasts + 1, - self.last_timestamp_lasts, - out=self.last_timestamp_lasts, - ) - torch.where( - torch.logical_and(active_mask, self.last_timestamp != time_indices), - self._ones_batch, - self.last_timestamp_lasts, - out=self.last_timestamp_lasts, - ) - # same as: self.last_timestamp[active_mask] = time_indices[active_mask], but non-blocking - torch.where(active_mask, time_indices, self.last_timestamp, out=self.last_timestamp) - # increase lengths - self.current_lengths += active_mask - - def get_last_labels(self, pad_id: int = -1): - """Get last labels. For elements without labels use pad_id""" - return torch.where( - self.current_lengths > 0, self.transcript[self._batch_indices, self.current_lengths - 1], pad_id - ) - - def clone(self) -> "BatchedHyps": - """Return a copy of self""" - batched_hyps = BatchedHyps( - batch_size=self.batch_size, - init_length=self._max_length, - device=self.device, - float_dtype=self.float_dtype, - is_with_durations=self.is_with_durations, - ) - batched_hyps.current_lengths.copy_(self.current_lengths) - batched_hyps.transcript.copy_(self.transcript) - batched_hyps.timestamps.copy_(self.timestamps) - if self.is_with_durations: - batched_hyps.token_durations.copy_(self.token_durations) - batched_hyps.scores.copy_(self.scores) - batched_hyps.last_timestamp.copy_(self.last_timestamp) - batched_hyps.last_timestamp_lasts.copy_(self.last_timestamp_lasts) - return batched_hyps - - def merge_(self, other: "BatchedHyps") -> "BatchedHyps": - """ - Merge two batched hypotheses structures. - NB: this will reallocate memory - - Args: - other: BatchedHyps - """ - cur_len = self.current_lengths.max().item() - other_len = other.current_lengths.max().item() - if cur_len + other_len >= self._max_length: - add_len = cur_len + other_len - self._max_length + 1 - device = self.transcript.device - add_shape = [self.batch_size, add_len] - self.transcript = torch.cat( - (self.transcript, torch.zeros(add_shape, dtype=torch.long, device=device)), dim=-1 - ) - self.timestamps = torch.cat( - (self.timestamps, torch.zeros(add_shape, dtype=torch.long, device=device)), dim=-1 - ) - if self.is_with_durations: - self.token_durations = torch.cat( - (self.token_durations, torch.zeros(add_shape, dtype=torch.long, device=device)), dim=-1 - ) - self._max_length += add_len - - indices = torch.arange(other_len, device=self.current_lengths.device) - shifted_indices = self.current_lengths[:, None] + indices[None, :] - self.transcript.scatter_(dim=1, index=shifted_indices, src=other.transcript) - self.timestamps.scatter_(dim=1, index=shifted_indices, src=other.timestamps) - if self.is_with_durations: - self.token_durations.scatter_(dim=1, index=shifted_indices, src=other.token_durations) - - self.current_lengths += other.current_lengths - self.scores += other.scores - self.last_timestamp.copy_(other.last_timestamp) - self.last_timestamp_lasts.copy_(other.last_timestamp_lasts) - - return self - - -class BatchedAlignments: - """ - Class to store batched alignments (logits, labels, frame_confidence). - Size is different from hypotheses, since blank outputs are preserved - """ - - def __init__( - self, - batch_size: int, - logits_dim: int, - init_length: int, - device: Optional[torch.device] = None, - float_dtype: Optional[torch.dtype] = None, - store_alignments: bool = True, - store_frame_confidence: bool = False, - with_duration_confidence: bool = False, - ): - """ - - Args: - batch_size: batch size for hypotheses - logits_dim: dimension for logits - init_length: initial estimate for the lengths of flatten alignments - device: device for storing data - float_dtype: expected logits/confidence data type - store_alignments: if alignments should be stored - store_frame_confidence: if frame confidence should be stored - """ - if init_length <= 0: - raise ValueError(f"init_length must be > 0, got {init_length}") - if batch_size <= 0: - raise ValueError(f"batch_size must be > 0, got {batch_size}") - self.batch_size = batch_size - self.logits_dim = logits_dim - self.device = device - self.float_dtype = float_dtype - self.with_frame_confidence = store_frame_confidence - self.with_duration_confidence = with_duration_confidence - self.with_alignments = store_alignments - self._max_length = init_length - - # tensor to store observed timestamps (for alignments / confidence scores) - self.timestamps = torch.zeros((batch_size, self._max_length), device=device, dtype=torch.long) - # current lengths of the utterances (alignments) - self.current_lengths = torch.zeros(batch_size, device=device, dtype=torch.long) - - # empty tensors instead of None to make torch.jit.script happy - self.logits = torch.zeros(0, device=device, dtype=float_dtype) - self.labels = torch.zeros(0, device=device, dtype=torch.long) - if self.with_alignments: - # logits and labels; labels can contain , different from BatchedHyps - self.logits = torch.zeros((batch_size, self._max_length, logits_dim), device=device, dtype=float_dtype) - self.labels = torch.zeros((batch_size, self._max_length), device=device, dtype=torch.long) - - # empty tensor instead of None to make torch.jit.script happy - self.frame_confidence = torch.zeros(0, device=device, dtype=float_dtype) - if self.with_frame_confidence: - # tensor to store frame confidence - self.frame_confidence = torch.zeros( - [batch_size, self._max_length, 2] if self.with_duration_confidence else [batch_size, self._max_length], - device=device, - dtype=float_dtype, - ) - self._batch_indices = torch.arange(batch_size, device=device) - - def clear_(self): - """ - Clears batched hypotheses state. - """ - self.current_lengths.fill_(0) - self.timestamps.fill_(0) - self.logits.fill_(0.0) - self.labels.fill_(0) - self.frame_confidence.fill_(0) - - def _allocate_more(self): - """ - Allocate 2x space for tensors, similar to common C++ std::vector implementations - to maintain O(1) insertion time complexity - """ - self.timestamps = torch.cat((self.timestamps, torch.zeros_like(self.timestamps)), dim=-1) - if self.with_alignments: - self.logits = torch.cat((self.logits, torch.zeros_like(self.logits)), dim=1) - self.labels = torch.cat((self.labels, torch.zeros_like(self.labels)), dim=-1) - if self.with_frame_confidence: - self.frame_confidence = torch.cat((self.frame_confidence, torch.zeros_like(self.frame_confidence)), dim=1) - self._max_length *= 2 - - def add_results_( - self, - active_indices: torch.Tensor, - time_indices: torch.Tensor, - logits: Optional[torch.Tensor] = None, - labels: Optional[torch.Tensor] = None, - confidence: Optional[torch.Tensor] = None, - ): - """ - Add results (inplace) from a decoding step to the batched hypotheses. - All tensors must use the same fixed batch dimension. - Args: - active_mask: tensor with mask for active hypotheses (of batch_size) - logits: tensor with raw network outputs - labels: tensor with decoded labels (can contain blank) - time_indices: tensor of time index for each label - confidence: optional tensor with confidence for each item in batch - """ - # we assume that all tensors have the same first dimension - if active_indices.shape[0] == 0: - return # nothing to add - - # if needed - increase storage - if self.current_lengths.max().item() >= self._max_length: - self._allocate_more() - - active_lengths = self.current_lengths[active_indices] - # store timestamps - same for alignments / confidence - self.timestamps[active_indices, active_lengths] = time_indices - - if self.with_alignments and logits is not None and labels is not None: - self.logits[active_indices, active_lengths] = logits - self.labels[active_indices, active_lengths] = labels - - if self.with_frame_confidence and confidence is not None: - self.frame_confidence[active_indices, active_lengths] = confidence - # increase lengths - self.current_lengths[active_indices] += 1 - - def add_results_masked_( - self, - active_mask: torch.Tensor, - time_indices: torch.Tensor, - logits: Optional[torch.Tensor] = None, - labels: Optional[torch.Tensor] = None, - confidence: Optional[torch.Tensor] = None, - ): - """ - Add results (inplace) from a decoding step to the batched hypotheses. - All tensors must use the same fixed batch dimension. - Args: - active_mask: tensor with indices of active hypotheses (indices should be within the original batch_size) - time_indices: tensor of time index for each label - logits: tensor with raw network outputs - labels: tensor with decoded labels (can contain blank) - confidence: optional tensor with confidence for each item in batch - """ - if (self.current_lengths + active_mask).max() >= self._max_length: - self._allocate_more() - self.add_results_masked_no_checks_( - active_mask=active_mask, time_indices=time_indices, logits=logits, labels=labels, confidence=confidence - ) - - def add_results_masked_no_checks_( - self, - active_mask: torch.Tensor, - time_indices: torch.Tensor, - logits: Optional[torch.Tensor] = None, - labels: Optional[torch.Tensor] = None, - confidence: Optional[torch.Tensor] = None, - ): - """ - Add results (inplace) from a decoding step to the batched hypotheses. - All tensors must use the same fixed batch dimension. - Useful if all the memory is pre-allocated, especially with cuda graphs - (otherwise prefer a more safe `add_results_masked_`) - Args: - active_mask: tensor with indices of active hypotheses (indices should be within the original batch_size) - time_indices: tensor of time index for each label - logits: tensor with raw network outputs - labels: tensor with decoded labels (can contain blank) - confidence: optional tensor with confidence for each item in batch - """ - # store timestamps - same for alignments / confidence - self.timestamps[self._batch_indices, self.current_lengths] = time_indices - - if self.with_alignments and logits is not None and labels is not None: - self.timestamps[self._batch_indices, self.current_lengths] = time_indices - self.logits[self._batch_indices, self.current_lengths] = logits - self.labels[self._batch_indices, self.current_lengths] = labels - - if self.with_frame_confidence and confidence is not None: - self.frame_confidence[self._batch_indices, self.current_lengths] = confidence - # increase lengths - self.current_lengths += active_mask - - def clone(self) -> "BatchedAlignments": - """Return a copy of self""" - batched_alignments = BatchedAlignments( - batch_size=self.batch_size, - logits_dim=self.logits_dim, - init_length=self._max_length, - device=self.device, - float_dtype=self.float_dtype, - store_alignments=self.with_alignments, - store_frame_confidence=self.with_frame_confidence, - with_duration_confidence=self.with_duration_confidence, - ) - batched_alignments.current_lengths.copy_(self.current_lengths) - batched_alignments.timestamps.copy_(self.timestamps) - batched_alignments.logits.copy_(self.logits) - batched_alignments.labels.copy_(self.labels) - batched_alignments.frame_confidence.copy_(self.frame_confidence) - return batched_alignments - - -def batched_hyps_to_hypotheses( - batched_hyps: BatchedHyps, alignments: Optional[BatchedAlignments] = None, batch_size=None -) -> List[Hypothesis]: - """ - Convert batched hypotheses to a list of Hypothesis objects. - Keep this function separate to allow for jit compilation for BatchedHyps class (see tests) - - Args: - batched_hyps: BatchedHyps object - alignments: BatchedAlignments object, optional; must correspond to BatchedHyps if present - batch_size: Batch Size to retrieve hypotheses. When working with CUDA graphs the batch size for all tensors - is constant, thus we need here the real batch size to return only necessary hypotheses - - Returns: - list of Hypothesis objects - """ - assert batch_size is None or batch_size <= batched_hyps.scores.shape[0] - num_hyps = batched_hyps.scores.shape[0] if batch_size is None else batch_size - # NB: clone is not necessary anymore, since CUDA graph decoder always returns an independent copy - scores = batched_hyps.scores.cpu() - current_lengths = batched_hyps.current_lengths.cpu() - transcript = batched_hyps.transcript.cpu() - timestamps = batched_hyps.timestamps.cpu() - hypotheses = [ - Hypothesis( - score=scores[i].item(), - y_sequence=transcript[i, : current_lengths[i]], - timestamp=timestamps[i, : batched_hyps.current_lengths[i]], - token_duration=( - batched_hyps.token_durations[i, : batched_hyps.current_lengths[i]] - if batched_hyps.is_with_durations - else torch.empty(0) - ), - alignments=None, - dec_state=None, - ) - for i in range(num_hyps) - ] - if alignments is not None: - # move all data to cpu to avoid overhead with moving data by chunks - alignment_lengths = alignments.current_lengths.cpu().tolist() - if alignments.with_alignments: - alignment_logits = alignments.logits.cpu() - alignment_labels = alignments.labels.cpu() - if alignments.with_frame_confidence: - frame_confidence = alignments.frame_confidence.cpu() - - # for each hypothesis - aggregate alignment using unique_consecutive for time indices (~itertools.groupby) - for i in range(len(hypotheses)): - hypotheses[i].alignments = [] - if alignments.with_frame_confidence: - hypotheses[i].frame_confidence = [] - _, grouped_counts = torch.unique_consecutive( - alignments.timestamps[i, : alignment_lengths[i]], return_counts=True - ) - start = 0 - for timestamp_cnt in grouped_counts.tolist(): - if alignments.with_alignments: - hypotheses[i].alignments.append( - [ - (alignment_logits[i, start + j], alignment_labels[i, start + j]) - for j in range(timestamp_cnt) - ] - ) - if alignments.with_frame_confidence: - hypotheses[i].frame_confidence.append( - [frame_confidence[i, start + j] for j in range(timestamp_cnt)] - ) - start += timestamp_cnt - return hypotheses diff --git a/nemo/collections/asr/parts/utils/slu_utils.py b/nemo/collections/asr/parts/utils/slu_utils.py deleted file mode 100644 index 47b2881143297cfa48510b0823c8dcaad8bfaddd..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/slu_utils.py +++ /dev/null @@ -1,205 +0,0 @@ -# ! /usr/bin/python -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from dataclasses import dataclass -from typing import List, Optional - -import torch -from omegaconf import DictConfig - -from nemo.collections.asr.modules.transformer import ( - BeamSearchSequenceGenerator, - GreedySequenceGenerator, - TopKSequenceGenerator, -) -from nemo.collections.common.tokenizers.tokenizer_spec import TokenizerSpec -from nemo.core.classes.module import NeuralModule - - -@dataclass -class SequenceGeneratorConfig: - type: str = "greedy" # choices=[greedy, topk, beam] - max_sequence_length: int = 512 - max_delta_length: int = -1 - temperature: float = 1.0 # for top-k sampling - beam_size: int = 1 # K for top-k sampling, N for beam search - len_pen: float = 0.0 # for beam-search - - -class SequenceGenerator: - """ - Wrapper class for sequence generators for NeMo transformers. - """ - - TYPE_GREEDY = "greedy" - TYPE_TOPK = "topk" - TYPE_BEAM = "beam" - SEARCHER_TYPES = [TYPE_GREEDY, TYPE_TOPK, TYPE_BEAM] - - def __init__( - self, - cfg: DictConfig, - embedding: NeuralModule, - decoder: NeuralModule, - log_softmax: NeuralModule, - tokenizer: TokenizerSpec, - ) -> None: - super().__init__() - - self._type = cfg.get("type", "greedy") - self.tokenizer = tokenizer - self.pad_id = getattr(tokenizer, "pad_id", 0) - self.eos_id = getattr(tokenizer, "eos_id", -1) - self.bos_id = getattr(tokenizer, "bos_id", -1) - common_args = { - "pad": self.pad_id, - "bos": self.bos_id, - "eos": self.eos_id, - "max_sequence_length": cfg.get("max_sequence_length", 512), - "max_delta_length": cfg.get("max_delta_length", -1), - "batch_size": cfg.get("batch_size", 1), - } - if self._type == self.TYPE_GREEDY: - self.generator = GreedySequenceGenerator(embedding, decoder, log_softmax, **common_args) - elif self._type == self.TYPE_TOPK: - beam_size = cfg.get("beam_size", 1) - temperature = cfg.get("temperature", 1.0) - self.generator = TopKSequenceGenerator( - embedding, decoder, log_softmax, beam_size, temperature, **common_args - ) - elif self._type == self.TYPE_BEAM: - beam_size = cfg.get("beam_size", 1) - len_pen = cfg.get("len_pen", 0.0) - self.generator = BeamSearchSequenceGenerator( - embedding, decoder, log_softmax, beam_size, len_pen, **common_args - ) - else: - raise ValueError( - f"Sequence Generator only supports one of {self.SEARCH_TYPES}, but got {self._type} instead." - ) - - def __call__( - self, - encoder_states: torch.Tensor, - encoder_input_mask: torch.Tensor = None, - return_beam_scores: bool = False, - pad_max_len: Optional[int] = None, - return_length: bool = False, - ): - """ - Generate sequence tokens given the input encoder states and masks. - Params: - - encoder_states: a torch Tensor of shape BxTxD - - encoder_input_mask: a binary tensor of shape BxTxD - - return_beam_scores: whether to return beam scores - - pad_max_len: optional int, set it to pad all sequence to the same length - - return_length: whether to return the lengths for generated sequences (shape B) - Returns: - - generated tokens tensor of shape BxT - """ - predictions = self.generator( - encoder_hidden_states=encoder_states, - encoder_input_mask=encoder_input_mask, - return_beam_scores=return_beam_scores, - ) - - if pad_max_len: - predictions = pad_sequence(predictions, pad_max_len, self.pad_id) - - if return_length: - return predictions, self.get_seq_length(predictions) - - return predictions - - def get_seq_length(self, seq: torch.Tensor) -> torch.Tensor: - """ - Get sequence length. - Params: - - seq: batched sequence tensor of shape BxTxD - Returns: - - tensor of shape B, where each element is the length of the sequence - """ - lengths = seq.size(1) * torch.ones(seq.size(0), device=seq.device).long() - pos = (seq == self.eos_id).long().nonzero() - seq_lengths = torch.scatter(lengths, dim=0, index=pos[:, 0], src=pos[:, 1]) - return seq_lengths - - def decode_semantics_from_tokens(self, seq_tokens: torch.Tensor) -> List[str]: - """ - Decode tokens into strings - Rarams: - - seq_tokens: integer tensor of shape BxT - Returns: - - list of strings - """ - semantics_list = [] - # Drop sequence tokens to CPU - seq_tokens = seq_tokens.detach().long().cpu() - seq_lengths = self.get_seq_length(seq_tokens) - # iterate over batch - for ind in range(seq_tokens.shape[0]): - tokens = seq_tokens[ind].numpy().tolist() - length = seq_lengths[ind].long().cpu().item() - tokens = tokens[:length] - text = "".join(self.tokenizer.tokenizer.decode_ids(tokens)) - semantics_list.append(text) - return semantics_list - - -def get_seq_length(seq: torch.Tensor, eos_id: int) -> torch.Tensor: - """ - Get sequence length. - Params: - - seq: batched sequence tensor of shape BxTxD - - eos_id: integer representing the end of sentence - Returns: - - tensor of shape B, where each element is the length of the sequence - """ - lengths = seq.size(1) * torch.ones(seq.size(0), device=seq.device).long() - pos = (seq == eos_id).long().nonzero() - seq_lengths = torch.scatter(lengths, dim=0, index=pos[:, 0], src=pos[:, 1]) - return seq_lengths - - -def pad_sequence(seq: torch.Tensor, max_len: int, pad_token: int = 0) -> torch.Tensor: - """ - Params: - - seq: integer token sequences of shape BxT - - max_len: integer for max sequence length - - pad_token: integer token for padding - Returns: - - padded sequence of shape B x max_len - """ - batch = seq.size(0) - curr_len = seq.size(1) - if curr_len >= max_len: - return seq - - padding = torch.zeros(batch, max_len - curr_len, dtype=seq.dtype, device=seq.device).fill_(pad_token) - return torch.cat([seq, padding], dim=1) - - -def get_seq_mask(seq: torch.Tensor, seq_lens: torch.Tensor) -> torch.Tensor: - """ - Get the sequence mask based on the actual length of each sequence - Params: - - seq: tensor of shape [BxLxD] - - seq_len: tensor of shape [B] - Returns: - - binary mask of shape [BxL] - """ - mask = torch.arange(seq.size(1))[None, :].to(seq.device) < seq_lens[:, None] - return mask.to(seq.device, dtype=bool) diff --git a/nemo/collections/asr/parts/utils/speaker_utils.py b/nemo/collections/asr/parts/utils/speaker_utils.py deleted file mode 100644 index 99bd29760ffc0a39d9caf1232f5afc648068d6ef..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/speaker_utils.py +++ /dev/null @@ -1,1582 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import gc -import json -import math -import os -from copy import deepcopy -from typing import Dict, List, Tuple - -import numpy as np -import soundfile as sf -import torch -from omegaconf.listconfig import ListConfig -from pyannote.core import Annotation, Segment, Timeline -from tqdm import tqdm - -from nemo.collections.asr.data.audio_to_label import repeat_signal -from nemo.collections.asr.parts.utils.longform_clustering import LongFormSpeakerClustering -from nemo.utils import logging - - -def get_uniqname_from_filepath(filepath): - """ - Return base name from provided filepath - """ - if type(filepath) is str: - uniq_id = os.path.splitext(os.path.basename(filepath))[0] - return uniq_id - else: - raise TypeError("input must be filepath string") - - -def get_uniq_id_from_manifest_line(line: str) -> str: - """ - Retrieve `uniq_id` from the `audio_filepath` in a manifest line. - """ - dic = json.loads(line.strip()) - uniq_id = get_uniqname_from_filepath(dic['audio_filepath']) - return uniq_id - - -def get_uniq_id_with_dur(meta, decimals=3): - """ - Return basename with offset and end time labels - """ - # bare_uniq_id = get_uniqname_from_filepath(meta['audio_filepath']) - bare_uniq_id = get_uniqname_from_filepath(meta['rttm_filepath']) - if meta['offset'] is None and meta['duration'] is None: - return bare_uniq_id - if meta['offset']: - offset = str(int(round(meta['offset'], decimals) * pow(10, decimals))) - else: - offset = 0 - if meta['duration']: - endtime = str(int(round(meta['offset'] + meta['duration'], decimals) * pow(10, decimals))) - else: - endtime = 'NULL' - uniq_id = f"{bare_uniq_id}_{offset}_{endtime}" - return uniq_id - - -def audio_rttm_map(manifest, attach_dur=False): - """ - This function creates AUDIO_RTTM_MAP which is used by all diarization components to extract embeddings, - cluster and unify time stamps - - Args: - manifest (str): Path to the manifest file - attach_dur (bool, optional): If True, attach duration information to the unique name. Defaults to False. - - Returns: - AUDIO_RTTM_MAP (dict) : Dictionary with unique names as keys and corresponding metadata as values. - """ - - AUDIO_RTTM_MAP = {} - with open(manifest, 'r') as inp_file: - lines = inp_file.readlines() - logging.info("Number of files to diarize: {}".format(len(lines))) - for line in lines: - line = line.strip() - dic = json.loads(line) - - meta = { - 'audio_filepath': dic['audio_filepath'], - 'rttm_filepath': dic.get('rttm_filepath', None), - 'offset': dic.get('offset', None), - 'duration': dic.get('duration', None), - 'text': dic.get('text', None), - 'num_speakers': dic.get('num_speakers', None), - 'uem_filepath': dic.get('uem_filepath', None), - 'ctm_filepath': dic.get('ctm_filepath', None), - } - if attach_dur: - uniqname = get_uniq_id_with_dur(meta) - else: - if "uniq_id" in dic.keys(): - uniqname = dic['uniq_id'] - else: - uniqname = get_uniqname_from_filepath(filepath=meta['audio_filepath']) - - if uniqname not in AUDIO_RTTM_MAP: - AUDIO_RTTM_MAP[uniqname] = meta - else: - raise KeyError( - f"file {meta['audio_filepath']} is already part of AUDIO_RTTM_MAP, it might be duplicated, " - "Note: file basename must be unique" - ) - - return AUDIO_RTTM_MAP - - -def parse_scale_configs(window_lengths_in_sec, shift_lengths_in_sec, multiscale_weights): - """ - Check whether multiscale parameters are provided correctly. window_lengths_in_sec, shift_lengfhs_in_sec and - multiscale_weights should be all provided in omegaconf.listconfig.ListConfig type. In addition, the scales - should be provided in descending order, from the longest scale to the base scale (the shortest). - - Example: - Single-scale setting: - parameters.window_length_in_sec=1.5 - parameters.shift_length_in_sec=0.75 - parameters.multiscale_weights=null - - Multiscale setting (base scale - window_length 0.5 s and shift_length 0.25): - parameters.window_length_in_sec=[1.5,1.0,0.5] - parameters.shift_length_in_sec=[0.75,0.5,0.25] - parameters.multiscale_weights=[1,1,1] - - In addition, you can also specify session-by-session multiscale weight. In this case, each dictionary key - points to different weights. - """ - check_float_config = [isinstance(var, float) for var in (window_lengths_in_sec, shift_lengths_in_sec)] - check_list_config = [ - isinstance(var, (ListConfig, list, tuple)) - for var in (window_lengths_in_sec, shift_lengths_in_sec, multiscale_weights) - ] - if all(check_list_config) or all(check_float_config): - - # If bare floating numbers are provided, convert them to list format. - if all(check_float_config): - window_lengths, shift_lengths, multiscale_weights = ( - [window_lengths_in_sec], - [shift_lengths_in_sec], - [1.0], - ) - else: - window_lengths, shift_lengths, multiscale_weights = ( - window_lengths_in_sec, - shift_lengths_in_sec, - multiscale_weights, - ) - - length_check = ( - len(set([len(window_lengths), len(shift_lengths), len(multiscale_weights)])) == 1 - and len(multiscale_weights) > 0 - ) - scale_order_check = ( - list(window_lengths) == sorted(window_lengths)[::-1] and list(shift_lengths) == sorted(shift_lengths)[::-1] - ) - - # Check whether window lengths are longer than shift lengths - if len(window_lengths) > 1: - shift_length_check = all([w > s for w, s in zip(window_lengths, shift_lengths)]) - else: - shift_length_check = window_lengths[0] > shift_lengths[0] - - multiscale_args_dict = {'use_single_scale_clustering': False} - if all([length_check, scale_order_check, shift_length_check]): - if len(window_lengths) > 1: - multiscale_args_dict['scale_dict'] = { - k: (w, s) for k, (w, s) in enumerate(zip(window_lengths, shift_lengths)) - } - else: - multiscale_args_dict['scale_dict'] = {0: (window_lengths[0], shift_lengths[0])} - multiscale_args_dict['multiscale_weights'] = multiscale_weights - return multiscale_args_dict - else: - raise ValueError('Multiscale parameters are not properly setup.') - - elif any(check_list_config): - raise ValueError( - 'You must provide a list config for all three parameters: window, shift and multiscale weights.' - ) - else: - return None - - -def get_embs_and_timestamps(multiscale_embeddings_and_timestamps, multiscale_args_dict): - """ - The embeddings and timestamps in multiscale_embeddings_and_timestamps dictionary are - indexed by scale index. This function rearranges the extracted speaker embedding and - timestamps by unique ID to make the further processing more convenient. - - Args: - multiscale_embeddings_and_timestamps (dict): - Dictionary of embeddings and timestamps for each scale. - multiscale_args_dict (dict): - Dictionary of scale information: window, shift and multiscale weights. - - Returns: - embs_and_timestamps (dict) - A dictionary containing embeddings and timestamps of each scale, indexed by unique ID. - """ - embs_and_timestamps = {uniq_id: {} for uniq_id in multiscale_embeddings_and_timestamps[0][0].keys()} - if multiscale_args_dict['use_single_scale_clustering']: - _multiscale_args_dict = deepcopy(multiscale_args_dict) - _multiscale_args_dict['scale_dict'] = {0: multiscale_args_dict['scale_dict'][0]} - _multiscale_args_dict['multiscale_weights'] = multiscale_args_dict['multiscale_weights'][:1] - else: - _multiscale_args_dict = multiscale_args_dict - - embeddings, timestamps = multiscale_embeddings_and_timestamps[0] - for uniq_id in embeddings.keys(): - embeddings_list, time_stamps_list, segment_index_list = [], [], [] - for scale_idx in sorted(_multiscale_args_dict['scale_dict'].keys()): - embeddings, timestamps = multiscale_embeddings_and_timestamps[scale_idx] - if len(embeddings[uniq_id]) != len(timestamps[uniq_id]): - raise ValueError("Mismatch of counts between embedding vectors and timestamps") - time_stamps_tensor = torch.tensor(timestamps[uniq_id]) - embeddings_list.append(embeddings[uniq_id]) - segment_index_list.append(embeddings[uniq_id].shape[0]) - time_stamps_list.append(time_stamps_tensor) - - embs_and_timestamps[uniq_id]['multiscale_weights'] = ( - torch.tensor(_multiscale_args_dict['multiscale_weights']).unsqueeze(0).float() - ) - embs_and_timestamps[uniq_id]['embeddings'] = torch.cat(embeddings_list, dim=0) - embs_and_timestamps[uniq_id]['timestamps'] = torch.cat(time_stamps_list, dim=0) - embs_and_timestamps[uniq_id]['multiscale_segment_counts'] = torch.tensor(segment_index_list) - - return embs_and_timestamps - - -def get_timestamps(multiscale_timestamps, multiscale_args_dict): - """ - The timestamps in `multiscale_timestamps` dictionary are indexed by scale index. - This function rearranges the extracted speaker embedding and timestamps by unique ID - to make the further processing more convenient. - - Args: - multiscale_timestamps (dict): - Dictionary of timestamps for each scale. - multiscale_args_dict (dict): - Dictionary of scale information: window, shift and multiscale weights. - - Returns: - timestamps_dict (dict) - A dictionary containing embeddings and timestamps of each scale, indexed by unique ID. - """ - timestamps_dict = {uniq_id: {'scale_dict': {}} for uniq_id in multiscale_timestamps[0].keys()} - for scale_idx in sorted(multiscale_args_dict['scale_dict'].keys()): - time_stamps = multiscale_timestamps[scale_idx] - for uniq_id in time_stamps.keys(): - timestamps_dict[uniq_id]['scale_dict'][scale_idx] = { - 'time_stamps': time_stamps[uniq_id], - } - - return timestamps_dict - - -def get_contiguous_stamps(stamps): - """ - Return contiguous time stamps - """ - lines = deepcopy(stamps) - contiguous_stamps = [] - for i in range(len(lines) - 1): - start, end, speaker = lines[i].split() - next_start, next_end, next_speaker = lines[i + 1].split() - if float(end) > float(next_start): - avg = str((float(next_start) + float(end)) / 2.0) - lines[i + 1] = ' '.join([avg, next_end, next_speaker]) - contiguous_stamps.append(start + " " + avg + " " + speaker) - else: - contiguous_stamps.append(start + " " + end + " " + speaker) - start, end, speaker = lines[-1].split() - contiguous_stamps.append(start + " " + end + " " + speaker) - return contiguous_stamps - - -def merge_stamps(lines): - """ - Merge time stamps of the same speaker. - """ - stamps = deepcopy(lines) - overlap_stamps = [] - for i in range(len(stamps) - 1): - start, end, speaker = stamps[i].split() - next_start, next_end, next_speaker = stamps[i + 1].split() - if float(end) == float(next_start) and speaker == next_speaker: - stamps[i + 1] = ' '.join([start, next_end, next_speaker]) - else: - overlap_stamps.append(start + " " + end + " " + speaker) - - start, end, speaker = stamps[-1].split() - overlap_stamps.append(start + " " + end + " " + speaker) - - return overlap_stamps - - -def labels_to_pyannote_object(labels, uniq_name=''): - """ - Convert the given labels to pyannote object to calculate DER and for visualization - """ - annotation = Annotation(uri=uniq_name) - for label in labels: - start, end, speaker = label.strip().split() - start, end = float(start), float(end) - annotation[Segment(start, end)] = speaker - - return annotation - - -def labels_to_rttmfile(labels, uniq_id, out_rttm_dir): - """ - Write rttm file with uniq_id name in out_rttm_dir with timestamps in labels - """ - filename = os.path.join(out_rttm_dir, uniq_id + '.rttm') - with open(filename, 'w') as f: - for line in labels: - line = line.strip() - start, end, speaker = line.split() - duration = float(end) - float(start) - start = float(start) - log = 'SPEAKER {} 1 {:.3f} {:.3f} {} \n'.format(uniq_id, start, duration, speaker) - f.write(log) - - return filename - - -def string_to_float(x, round_digits): - """ - Convert string to float then round the number. - """ - return round(float(x), round_digits) - - -def convert_rttm_line(rttm_line, round_digits=3): - """ - Convert a line in RTTM file to speaker label, start and end timestamps. - - Args: - rttm_line (str): - A line in RTTM formatted file containing offset and duration of each segment. - round_digits (int): - Number of digits to be rounded. - - Returns: - start (float) - Start timestamp in floating point number. - end (float): - End timestamp in floating point number. - speaker (str): - speaker string in RTTM lines. - """ - rttm = rttm_line.strip().split() - start = string_to_float(rttm[3], round_digits) - end = string_to_float(rttm[4], round_digits) + string_to_float(rttm[3], round_digits) - speaker = rttm[7] - return start, end, speaker - - -def rttm_to_labels(rttm_filename): - """ - Prepare time stamps label list from rttm file - """ - labels = [] - with open(rttm_filename, 'r') as f: - for line in f.readlines(): - start, end, speaker = convert_rttm_line(line, round_digits=3) - labels.append('{} {} {}'.format(start, end, speaker)) - return labels - - -def write_cluster_labels(base_scale_idx, lines_cluster_labels, out_rttm_dir): - """ - Write cluster labels that are generated from clustering into a file. - Args: - base_scale_idx (int): The base scale index which is the highest scale index. - lines_cluster_labels (list): The start and end time-stamps of each segment with the predicted cluster label. - out_rttm_dir (str): The path where output rttm files are saved. - """ - out_label_name = os.path.join( - out_rttm_dir, '../speaker_outputs', f'subsegments_scale{base_scale_idx}_cluster.label' - ) - with open(out_label_name, 'w') as f: - for clus_label_line in lines_cluster_labels: - f.write(clus_label_line) - - -def generate_cluster_labels(segment_ranges: List[str], cluster_labels: List[int]): - """ - Generate cluster (speaker labels) from the segment_range list and cluster label list. - - Args: - segment_ranges (list): - List containing intervals (start and end timestapms, ranges) of each segment - cluster_labels (list): - List containing a cluster label sequence - - Returns: - diar_hyp (list): - List containing merged speaker-turn-level timestamps and labels in string format - Example: - >>> diar_hyp = ['0.0 4.375 speaker_1', '4.375 5.125 speaker_0', ...] - - lines (list) - List containing raw segment-level timestamps and labels in raw digits - >>> diar_hyp = ['0.0 0.25 speaker_1', '0.25 0.5 speaker_1', ..., '4.125 4.375 speaker_1'] - """ - lines = [] - for idx, label in enumerate(cluster_labels): - tag = 'speaker_' + str(label) - stt, end = segment_ranges[idx] - lines.append(f"{stt} {end} {tag}") - cont_lines = get_contiguous_stamps(lines) - diar_hyp = merge_stamps(cont_lines) - return diar_hyp, lines - - -def perform_clustering( - embs_and_timestamps, AUDIO_RTTM_MAP, out_rttm_dir, clustering_params, device, verbose: bool = True -): - """ - Performs spectral clustering on embeddings with time stamps generated from VAD output - - Args: - embs_and_timestamps (dict): This dictionary contains the following items indexed by unique IDs. - 'embeddings' : Tensor containing embeddings. Dimensions:(# of embs) x (emb. dimension) - 'timestamps' : Tensor containing ime stamps list for each audio recording - 'multiscale_segment_counts' : Tensor containing the number of segments for each scale - AUDIO_RTTM_MAP (dict): - AUDIO_RTTM_MAP for mapping unique id with audio file path and rttm path - out_rttm_dir (str): - Path to write predicted rttms - clustering_params (dict): - Clustering parameters provided through config that contains max_num_speakers (int), - oracle_num_speakers (bool), max_rp_threshold(float), sparse_search_volume(int) - and enhance_count_threshold (int). - use_torch_script (bool): - Boolean that determines whether to use torch.jit.script for speaker clustering - device (torch.device): - Device we are running on ('cpu', 'cuda'). - verbose (bool): - Enable TQDM progress bar. - - Returns: - all_reference (list[uniq_name,Annotation]): reference annotations for score calculation - all_hypothesis (list[uniq_name,Annotation]): hypothesis annotations for score calculation - - """ - all_hypothesis = [] - all_reference = [] - no_references = False - lines_cluster_labels = [] - - cuda = True - if device.type != 'cuda': - logging.warning("cuda=False, using CPU for eigen decomposition. This might slow down the clustering process.") - cuda = False - - speaker_clustering = LongFormSpeakerClustering(cuda=cuda) - - if clustering_params.get('export_script_module', False): - speaker_clustering = torch.jit.script(speaker_clustering) - torch.jit.save(speaker_clustering, 'speaker_clustering_script.pt') - - for uniq_id, audio_rttm_values in tqdm(AUDIO_RTTM_MAP.items(), desc='clustering', leave=True, disable=not verbose): - uniq_embs_and_timestamps = embs_and_timestamps[uniq_id] - - if clustering_params.oracle_num_speakers: - num_speakers = audio_rttm_values.get('num_speakers', None) - if num_speakers is None: - raise ValueError("Provided option as oracle num of speakers but num_speakers in manifest is null") - else: - num_speakers = -1 - - base_scale_idx = uniq_embs_and_timestamps['multiscale_segment_counts'].shape[0] - 1 - - cluster_labels = speaker_clustering.forward_infer( - embeddings_in_scales=uniq_embs_and_timestamps['embeddings'], - timestamps_in_scales=uniq_embs_and_timestamps['timestamps'], - multiscale_segment_counts=uniq_embs_and_timestamps['multiscale_segment_counts'], - multiscale_weights=uniq_embs_and_timestamps['multiscale_weights'], - oracle_num_speakers=int(num_speakers), - max_num_speakers=int(clustering_params.max_num_speakers), - max_rp_threshold=float(clustering_params.max_rp_threshold), - sparse_search_volume=int(clustering_params.sparse_search_volume), - chunk_cluster_count=clustering_params.get('chunk_cluster_count', None), - embeddings_per_chunk=clustering_params.get('embeddings_per_chunk', None), - ) - - del uniq_embs_and_timestamps - if cuda: - torch.cuda.empty_cache() - else: - gc.collect() - timestamps = speaker_clustering.timestamps_in_scales[base_scale_idx] - - cluster_labels = cluster_labels.cpu().numpy() - if len(cluster_labels) != timestamps.shape[0]: - raise ValueError("Mismatch of length between cluster_labels and timestamps.") - - labels, lines = generate_cluster_labels(timestamps, cluster_labels) - - if out_rttm_dir: - labels_to_rttmfile(labels, uniq_id, out_rttm_dir) - lines_cluster_labels.extend([f'{uniq_id} {seg_line}\n' for seg_line in lines]) - hypothesis = labels_to_pyannote_object(labels, uniq_name=uniq_id) - all_hypothesis.append([uniq_id, hypothesis]) - - rttm_file = audio_rttm_values.get('rttm_filepath', None) - if rttm_file is not None and os.path.exists(rttm_file) and not no_references: - ref_labels = rttm_to_labels(rttm_file) - reference = labels_to_pyannote_object(ref_labels, uniq_name=uniq_id) - all_reference.append([uniq_id, reference]) - else: - no_references = True - all_reference = [] - - if out_rttm_dir: - write_cluster_labels(base_scale_idx, lines_cluster_labels, out_rttm_dir) - - return all_reference, all_hypothesis - - -def get_vad_out_from_rttm_line(rttm_line): - """ - Extract VAD timestamp from the given RTTM lines. - """ - vad_out = rttm_line.strip().split() - if len(vad_out) > 3: - start, dur, _ = float(vad_out[3]), float(vad_out[4]), vad_out[7] - else: - start, dur, _ = float(vad_out[0]), float(vad_out[1]), vad_out[2] - return start, dur - - -def get_offset_and_duration(AUDIO_RTTM_MAP, uniq_id, decimals=5): - """ - Extract offset and duration information from AUDIO_RTTM_MAP dictionary. - If duration information is not specified, a duration value is extracted from the audio file directly. - - Args: - AUDIO_RTTM_MAP (dict): - Dictionary containing RTTM file information, which is indexed by unique file id. - uniq_id (str): - Unique file id - Returns: - offset (float): - The offset value that determines the beginning of the audio stream. - duration (float): - The length of audio stream that is expected to be used. - """ - audio_path = AUDIO_RTTM_MAP[uniq_id]['audio_filepath'] - if AUDIO_RTTM_MAP[uniq_id].get('duration', None): - duration = round(AUDIO_RTTM_MAP[uniq_id]['duration'], decimals) - offset = round(AUDIO_RTTM_MAP[uniq_id]['offset'], decimals) - else: - sound = sf.SoundFile(audio_path) - duration = sound.frames / sound.samplerate - offset = 0.0 - return offset, duration - - -def write_overlap_segments(outfile, AUDIO_RTTM_MAP, uniq_id, overlap_range_list, decimals=5): - """ - Write the json dictionary into the specified manifest file. - - Args: - outfile: - File pointer that indicates output file path. - AUDIO_RTTM_MAP (dict): - Dictionary containing the input manifest information - uniq_id (str): - Unique file id - overlap_range_list (list): - List containing overlapping ranges between target and source. - decimals (int): - Number of decimals to round the offset and duration values. - """ - audio_path = AUDIO_RTTM_MAP[uniq_id]['audio_filepath'] - for stt, end in overlap_range_list: - meta = { - "audio_filepath": audio_path, - "offset": round(stt, decimals), - "duration": round(end - stt, decimals), - "label": 'UNK', - "uniq_id": uniq_id, - } - json.dump(meta, outfile) - outfile.write("\n") - - -def read_rttm_lines(rttm_file_path): - """ - Read rttm files and return the rttm information lines. - - Args: - rttm_file_path (str): - An absolute path to an RTTM file - - Returns: - lines (list): - List containing the strings from the RTTM file. - """ - if rttm_file_path and os.path.exists(rttm_file_path): - with open(rttm_file_path, 'r') as f: - lines = f.readlines() - else: - raise FileNotFoundError( - "Requested to construct manifest from rttm with oracle VAD option " - f"or from NeMo VAD but received filename as {rttm_file_path}" - ) - return lines - - -def validate_vad_manifest(AUDIO_RTTM_MAP, vad_manifest): - """ - This function will check the valid speech segments in the manifest file which is either - generated from NeMo voice activity detection(VAD) or oracle VAD. - If an audio file does not contain any valid speech segments, we ignore the audio file - (indexed by uniq_id) for the rest of the processing steps. - """ - vad_uniq_ids = set() - with open(vad_manifest, 'r') as vad_file: - for line in vad_file: - line = line.strip() - dic = json.loads(line) - if dic['duration'] > 0: - vad_uniq_ids.add(dic['uniq_id']) - - provided_uniq_ids = set(AUDIO_RTTM_MAP.keys()) - silence_ids = provided_uniq_ids - vad_uniq_ids - for uniq_id in silence_ids: - del AUDIO_RTTM_MAP[uniq_id] - logging.warning(f"{uniq_id} is ignored since the file does not contain any speech signal to be processed.") - - if len(AUDIO_RTTM_MAP) == 0: - raise ValueError("All files present in manifest contains silence, aborting next steps") - - -def is_overlap(rangeA: List[float], rangeB: List[float]) -> bool: - """ - Check whether two ranges have overlap. - - Args: - rangeA (list, tuple): - List or tuple containing start and end value in float. - rangeB (list, tuple): - List or tuple containing start and end value in float. - Returns: - (bool): - Boolean that indicates whether the input ranges have overlap. - """ - start1, end1 = rangeA[0], rangeA[1] - start2, end2 = rangeB[0], rangeB[1] - return end1 > start2 and end2 > start1 - - -def get_overlap_range(rangeA: List[float], rangeB: List[float]): - """ - Calculate the overlapping range between rangeA and rangeB. - - Args: - rangeA (list, tuple): - List or tuple containing start and end value in float. - rangeB (list, tuple): - List or tuple containing start and end value in float. - - Returns: - (list): - List containing the overlapping range between rangeA and rangeB. - """ - assert is_overlap(rangeA, rangeB), f"There is no overlap between rangeA:{rangeA} and rangeB:{rangeB}" - return [max(rangeA[0], rangeB[0]), min(rangeA[1], rangeB[1])] - - -def merge_int_intervals(intervals_in: List[List[int]]) -> List[List[int]]: - """ - Interval merging algorithm which has `O(N*logN)` time complexity. (N is number of intervals) - Merge the range pairs if there is overlap exists between the given ranges. - This algorithm needs a sorted range list in terms of the start time. - Note that neighboring numbers lead to a merged range. - - Example: - input: [(1, 10), (11, 20)] - output: [(1, 20)] - - Refer to the original code at https://stackoverflow.com/a/59378428 - - Args: - intervals_in (list): - List containing ranges. - Example: - >>> intervals_in - [(102, 103), (104, 109), (107, 120)] - - Returns: - merged_list (list): - List containing the combined ranges. - Example: - >>> merged_list - [(102, 120)] - """ - num_intervals = len(intervals_in) - if num_intervals == 0: - return [] - elif num_intervals == 1: - return intervals_in - else: - merged_list: List[List[int]] = [] - stt2: int = 0 - end2: int = 0 - - intervals_in = [[int(x[0]), int(x[1])] for x in intervals_in] - interval_tensor: torch.Tensor = torch.tensor(intervals_in) - _sorted, _ = torch.sort(interval_tensor, dim=0) - _sorted_int: List[List[int]] = [[int(x[0]), int(x[1])] for x in _sorted.cpu()] - intervals: List[List[int]] = _sorted_int - - start, end = intervals[0][0], intervals[0][1] - for i in range(1, num_intervals): - stt2, end2 = intervals[i][0], intervals[i][1] - if end >= stt2: - end = max(end2, end) - else: - start, end = int(start), int(end) - merged_list.append([start, end]) - start = stt2 - end = max(end2, end) - - start, end = int(start), int(end) - merged_list.append([start, end]) - return merged_list - - -def fl2int(x: float, decimals: int = 3) -> int: - """ - Convert floating point number to integer. - """ - return torch.round(torch.tensor([x * (10**decimals)]), decimals=0).int().item() - - -def int2fl(x: int, decimals: int = 3) -> float: - """ - Convert integer to floating point number. - """ - return torch.round(torch.tensor([x / (10**decimals)]), decimals=decimals).item() - - -def merge_float_intervals(ranges: List[List[float]], decimals: int = 5, margin: int = 2) -> List[List[float]]: - """ - Combine overlaps with floating point numbers. Since neighboring integers are considered as continuous range, - we need to add margin to the starting range before merging then subtract margin from the result range. - - Args: - ranges (list): - List containing ranges. - Example: [(10.2, 10.83), (10.42, 10.91), (10.45, 12.09)] - decimals (int): - Number of rounding decimals - margin (int): - margin for determining overlap of the two ranges when ranges are converted to integer ranges. - Default is margin=2 which follows the python index convention. - - Examples: - If margin is 0: - [(1, 10), (10, 20)] -> [(1, 20)] - [(1, 10), (11, 20)] -> [(1, 20)] - If margin is 1: - [(1, 10), (10, 20)] -> [(1, 20)] - [(1, 10), (11, 20)] -> [(1, 10), (11, 20)] - If margin is 2: - [(1, 10), (10, 20)] -> [(1, 10), (10, 20)] - [(1, 10), (11, 20)] -> [(1, 10), (11, 20)] - - Returns: - merged_list (list): - List containing the combined ranges. - Example: [(10.2, 12.09)] - """ - ranges_int: List[List[int]] = [] - merged_ranges_int: List[List[int]] = [] - for x in ranges: - stt, end = int(fl2int(x[0], decimals) + margin), int(fl2int(x[1], decimals)) - if stt < end: - ranges_int.append([stt, end]) - merged_ranges_int = merge_int_intervals(ranges_int) - merged_ranges_float: List[List[float]] = [] - merged_ranges_float = [[int2fl(x[0] - margin, decimals), int2fl(x[1], decimals)] for x in merged_ranges_int] - return merged_ranges_float - - -def get_sub_range_list(target_range: List[float], source_range_list: List[List[float]]) -> List[List[float]]: - """ - Get the ranges that has overlaps with the target range from the source_range_list. - - Example: - source range: - |===--======---=====---====--| - target range: - |--------================----| - out_range: - |--------===---=====---==----| - - Args: - target_range (list): - A range (a start and end value pair) that defines the target range we want to select. - target_range = [(start, end)] - source_range_list (list): - List containing the subranges that need to be selected. - source_range = [(start0, end0), (start1, end1), ...] - Returns: - out_range (list): - List containing the overlap between target_range and - source_range_list. - """ - if len(target_range) == 0: - return [] - else: - out_range: List[List[float]] = [] - for s_range in source_range_list: - if is_overlap(s_range, target_range): - ovl_range = get_overlap_range(s_range, target_range) - out_range.append(ovl_range) - return out_range - - -def write_rttm2manifest( - AUDIO_RTTM_MAP: str, manifest_file: str, include_uniq_id: bool = False, decimals: int = 5 -) -> str: - """ - Write manifest file based on rttm files (or vad table out files). This manifest file would be used by - speaker diarizer to compute embeddings and cluster them. This function takes care of overlapping VAD timestamps - and trimmed with the given offset and duration value. - - Args: - AUDIO_RTTM_MAP (dict): - Dictionary containing keys to unique names, that contains audio filepath and rttm_filepath as its contents, - these are used to extract oracle vad timestamps. - manifest (str): - The path to the output manifest file. - - Returns: - manifest (str): - The path to the output manifest file. - """ - with open(manifest_file, 'w') as outfile: - for uniq_id in AUDIO_RTTM_MAP: - rttm_file_path = AUDIO_RTTM_MAP[uniq_id]['rttm_filepath'] - rttm_lines = read_rttm_lines(rttm_file_path) - offset, duration = get_offset_and_duration(AUDIO_RTTM_MAP, uniq_id, decimals) - vad_start_end_list_raw = [] - for line in rttm_lines: - start, dur = get_vad_out_from_rttm_line(line) - vad_start_end_list_raw.append([start, start + dur]) - vad_start_end_list = merge_float_intervals(vad_start_end_list_raw, decimals) - if len(vad_start_end_list) == 0: - logging.warning(f"File ID: {uniq_id}: The VAD label is not containing any speech segments.") - elif duration <= 0: - logging.warning(f"File ID: {uniq_id}: The audio file has negative or zero duration.") - else: - overlap_range_list = get_sub_range_list( - source_range_list=vad_start_end_list, target_range=[offset, offset + duration] - ) - write_overlap_segments(outfile, AUDIO_RTTM_MAP, uniq_id, overlap_range_list, decimals) - return manifest_file - - -def segments_manifest_to_subsegments_manifest( - segments_manifest_file: str, - subsegments_manifest_file: str = None, - window: float = 1.5, - shift: float = 0.75, - min_subsegment_duration: float = 0.05, - include_uniq_id: bool = False, -): - """ - Generate subsegments manifest from segments manifest file - Args: - segments_manifest file (str): path to segments manifest file, typically from VAD output - subsegments_manifest_file (str): path to output subsegments manifest file - (default (None) : writes to current working directory) - window (float): window length for segments to subsegments length - shift (float): hop length for subsegments shift - min_subsegments_duration (float): exclude subsegments smaller than this duration value - - Returns: - returns path to subsegment manifest file - """ - if subsegments_manifest_file is None: - pwd = os.getcwd() - subsegments_manifest_file = os.path.join(pwd, 'subsegments.json') - - with ( - open(segments_manifest_file, 'r') as segments_manifest, - open(subsegments_manifest_file, 'w') as subsegments_manifest, - ): - segments = segments_manifest.readlines() - for segment in segments: - segment = segment.strip() - dic = json.loads(segment) - audio, offset, duration, label = dic['audio_filepath'], dic['offset'], dic['duration'], dic['label'] - subsegments = get_subsegments_scriptable(offset=offset, window=window, shift=shift, duration=duration) - if include_uniq_id and 'uniq_id' in dic: - uniq_id = dic['uniq_id'] - else: - uniq_id = None - for subsegment in subsegments: - start, dur = subsegment - if dur > min_subsegment_duration: - meta = { - "audio_filepath": audio, - "offset": start, - "duration": dur, - "label": label, - "uniq_id": uniq_id, - } - - json.dump(meta, subsegments_manifest) - subsegments_manifest.write("\n") - - return subsegments_manifest_file - - -def get_subsegments( - offset: float, - window: float, - shift: float, - duration: float, - min_subsegment_duration: float = 0.01, - decimals: int = 2, - use_asr_style_frame_count: bool = False, - sample_rate: int = 16000, - feat_per_sec: int = 100, -) -> List[List[float]]: - """ - Return subsegments from a segment of audio file. - - Example: - (window, shift) = 1.5, 0.75 - Segment: [12.05, 14.45] - Subsegments: [[12.05, 13.55], [12.8, 14.3], [13.55, 14.45], [14.3, 14.45]] - - Args: - offset (float): Start time of audio segment - window (float): Window length for segments to subsegments length - shift (float): Hop length for subsegments shift - duration (float): Duration of segment - min_subsegment_duration (float): Exclude subsegments smaller than this duration value - decimals (int): Number of decimal places to round to - use_asr_style_frame_count (bool): If True, use asr style frame count to generate subsegments. - For example, if duration is 10 secs and frame_shift is 0.08 secs, - it results in (10/0.08)+1 = 125 + 1 frames. - - Returns: - subsegments (List[tuple[float, float]]): subsegments generated for the segments as - list of tuple of start and duration of each subsegment - """ - subsegments: List[List[float]] = [] - start = offset - slice_end = start + duration - if min_subsegment_duration <= duration <= shift: - slices = 1 - elif use_asr_style_frame_count is True: - num_feat_frames = np.ceil((1 + duration * sample_rate) / int(sample_rate / feat_per_sec)).astype(int) - slices = np.ceil(num_feat_frames / int(feat_per_sec * shift)).astype(int) - slice_end = start + shift * slices - else: - slices = np.ceil(1 + (duration - window) / shift).astype(int) - if slices == 1: - if min(duration, window) >= min_subsegment_duration: - subsegments.append([start, min(duration, window)]) - elif slices > 0: # What if slcies = 0 ? - start_col = torch.arange(offset, slice_end, shift)[:slices] - dur_col_raw = torch.min( - slice_end * torch.ones_like(start_col) - start_col, window * torch.ones_like(start_col) - ) - dur_col = torch.round(dur_col_raw, decimals=decimals) - valid_mask = dur_col >= min_subsegment_duration - valid_subsegments = torch.stack([start_col[valid_mask], dur_col[valid_mask]], dim=1) - subsegments = valid_subsegments.tolist() - return subsegments - - -def get_subsegments_scriptable(offset: float, window: float, shift: float, duration: float) -> List[List[float]]: - """ - This function returns subsegments from a segment of an audio file. - Although this implementation is inefficient due to the use of a for-loop for segmentation, - it is designed to be torch-jit-scriptable. - Use `get_subsegments` for a more efficient implementation. - - Args: - offset (float): start time of audio segment - window (float): window length for segments to subsegments length - shift (float): hop length for subsegments shift - duration (float): duration of segment - Returns: - subsegments (List[tuple[float, float]]): subsegments generated for the segments - as list of tuple of start and duration of - each subsegment - """ - subsegments: List[List[float]] = [] - start = offset - slice_end = start + duration - base = math.ceil((duration - window) / shift) - slices = 1 if base < 0 else base + 1 - for slice_id in range(slices): - end = start + window - if end > slice_end: - end = slice_end - subsegments.append([start, end - start]) - start = offset + (slice_id + 1) * shift - return subsegments - - -def get_target_sig( - sig, - start_sec: float, - end_sec: float, - slice_length: int, - sample_rate: int, -) -> torch.Tensor: - """ - Extract time-series signal from the given audio buffer based on the start and end - timestamps. - - Args: - start_sec (float): - Start of the targeted segments in second - end_sec (float): - Start of the targeted segments in second - slice_length (int): - Length of the entire audio segment that the samples are extracted from - sample_rate (int): - Sampling rate of the time-series audio signal - - Returns: - (Tensor) Trimmed ime-series audio signal samples - """ - start_idx = int(start_sec * sample_rate) - end_idx = min(int(end_sec * sample_rate), int(slice_length + start_idx)) - return sig[start_idx:end_idx] - - -def check_ranges(range_tensor): - """ - Check whether the range list has any faulty timestamp order. - - Args: - range_tensor (list): - List containing the start and end time of the segments. - Example: - >>> range_tensor = [[0.5, 3.12], [3.51, 7.26], ... ] - """ - for k in range(range_tensor.shape[0]): - range_tup = range_tensor[k] - if range_tup[1] < range_tup[0]: - raise ValueError("Range start time should be preceding the end time but we got: {range_tup}") - return True - - -def tensor_to_list(range_tensor: torch.Tensor) -> List[List[float]]: - """ - For online segmentation. Force the list elements to be float type. - """ - return [[float(range_tensor[k][0]), float(range_tensor[k][1])] for k in range(range_tensor.shape[0])] - - -def generate_diarization_output_lines(speaker_timestamps: List[List[float]], model_spk_num: int) -> List[str]: - """ - Generate diarization output lines list from the speaker timestamps list by merging overlapping intervals. - - Args: - speaker_timestamps (list): - List containing the start and end time of the speech intervals for each speaker. - Example: - >>> speaker_timestamps = [[0.5, 3.12], [3.51, 7.26],... ] - model_spk_num (int): - Number of speakers in the model. - - Returns: - speaker_lines_total (list): - List containing the diarization output lines in the format: - "start_time end_time speaker_id" - Example: - >>> speaker_lines_total = ["0.5 3.12 speaker_0", "3.51 7.26 speaker_1",...] - """ - speaker_lines_total = [] - for spk_idx in range(model_spk_num): - ts_invervals = speaker_timestamps[spk_idx] - merged_ts_intervals = merge_float_intervals(ts_invervals) - for ts_interval in merged_ts_intervals: - speaker_lines_total.extend([f"{ts_interval[0]:.3f} {ts_interval[1]:.3f} speaker_{int(spk_idx)}"]) - return speaker_lines_total - - -def get_speech_labels_for_update( - frame_start: float, - buffer_end: float, - vad_timestamps: torch.Tensor, - cumulative_speech_labels: torch.Tensor, - cursor_for_old_segments: float, -) -> Tuple[torch.Tensor, torch.Tensor]: - """ - Bring the new speech labels from the current buffer. Followingly: - - 1. Concatenate the old speech labels from self.cumulative_speech_labels for the overlapped region. - - This goes to new_speech_labels. - 2. Update the new 1 sec of speech label (speech_label_for_new_segments) to self.cumulative_speech_labels. - 3. Return the speech label from cursor_for_old_segments to buffer end. - - Args: - frame_start (float): - Start of the middle audio chunk in the audio buffer - buffer_end (float): - End of the audio buffer - vad_timestamps (Tensor): - Tensor containing VAD intervals (start and end timestamps) - cumulative_speech_labels (torch.Tensor): - Cumulative speech/non-speech timestamps (equivalent to VAD timestamps) - cursor_for_old_segments (float): - Floating point number that indicates the point where new segments should replace - the old segments - - Returns: - speech_label_for_new_segments (Tensor): - The intervals (start and end) timestamps where the new incoming speech segments should - be collected from - cumulative_speech_labels (Tensor): - Cumulative speech/non-speech timestamps (equivalent to VAD timestamps) with newly added - speech/non-speech timestamps from the `vad_timestamps` input - """ - update_overlap_range: List[float] = [] - if cursor_for_old_segments < frame_start: - update_overlap_range = [float(cursor_for_old_segments), float(frame_start)] - - # Get VAD timestamps that are in (frame_start, buffer_end) range - vad_timestamps = tensor_to_list(vad_timestamps) - cumulative_speech_labels = tensor_to_list(cumulative_speech_labels) - new_incoming_speech_labels = get_sub_range_list( - target_range=[float(frame_start), float(buffer_end)], source_range_list=vad_timestamps - ) - - # Update the speech label by including overlapping region with the previous output - update_overlap_speech_labels = get_sub_range_list( - target_range=update_overlap_range, source_range_list=cumulative_speech_labels - ) - - # Speech segments for embedding extractions - speech_label_for_new_segments = merge_float_intervals( - update_overlap_speech_labels + new_incoming_speech_labels, margin=0 - ) - - # Keep cumulative VAD labels for the future use - cumulative_speech_labels = merge_float_intervals(cumulative_speech_labels + new_incoming_speech_labels, margin=0) - - # Convert the lists back to type torch.Tensor - speech_label_for_new_segments = torch.tensor(speech_label_for_new_segments) - cumulative_speech_labels = torch.tensor(cumulative_speech_labels) - - return speech_label_for_new_segments, cumulative_speech_labels - - -def get_new_cursor_for_update( - frame_start: float, - segment_range_ts: List[List[float]], -) -> Tuple[float, int]: - """ - Function for updating a cursor online speaker diarization. - Remove the old segments that overlap with the new frame (self.frame_start) - cursor_for_old_segments is set to the onset of the t_range popped lastly. - - - Args: - frame_start (float): - Start of streaming pipeline frame - segment_range_ts (float): - Interval (start and end timestamps) of the targeted segments - - Returns: - cursor_for_old_segments (float): - Floating point number that indicates the point where new segments should replace - the old segments - cursor_index (int): - The index of the first newly accepted segments - """ - cursor_for_old_segments = frame_start - cursor_index: int = len(segment_range_ts) - count = 0 - while True and len(segment_range_ts) > 0: - t_range = segment_range_ts[-1 * (count + 1)] - if frame_start <= t_range[1]: - count += 1 - cursor_for_old_segments = t_range[0] - else: - break - cursor_index = len(segment_range_ts) - count - return cursor_for_old_segments, cursor_index - - -def get_online_segments_from_slices( - sig: torch.Tensor, - buffer_start: float, - buffer_end: float, - subsegments: List[List[float]], - ind_offset: int, - window: float, - sample_rate: int, -) -> Tuple[int, List[torch.Tensor], List[List[float]], List[int]]: - """ - Create short speech segments from slices for online processing purpose. - - Args: - sig (Tensor): - Tensor containing the raw time-series signal - buffer_start (float): - Start point of the time-series signal buffer - buffer_end (float): - End point of the time-series signal buffer - subsegments (list): - List containing the interval information (start and duration) of each segment - ind_offset (int): - Offset for index that compensates the point of the current position in the streaming session - window (float): - Window length in second - shift (float): - Shift length in second - - Returns: - sigs_list (list): - list of sliced input signal - audio_lengths (list): - list of audio sample lengths - """ - sig_rangel_list: List[List[float]] = [] - sig_indexes: List[int] = [] - sigs_list: List[torch.Tensor] = [] - slice_length: int = int(window * sample_rate) - end_sec: float = 0.0 - for subseg in subsegments: - start_sec, dur = subseg[0], subseg[1] - - if start_sec > buffer_end: - continue - ind_offset += 1 - - buffer_len = buffer_end - buffer_start - end_sec = float(start_sec + dur) - - if end_sec > buffer_len: - end_sec = float(min(end_sec, buffer_len)) - - signal = get_target_sig(sig, start_sec, end_sec, slice_length, sample_rate) - - if len(signal) == 0: - raise ValueError("len(signal) is zero. Signal length should not be zero.") - if len(signal) < slice_length: - signal = repeat_signal(signal, len(signal), slice_length) - - start_abs_sec = buffer_start + start_sec - end_abs_sec = buffer_start + end_sec - - sigs_list.append(signal) - sig_rangel_list.append([start_abs_sec, end_abs_sec]) - sig_indexes.append(ind_offset) - - if not len(sigs_list) == len(sig_rangel_list) == len(sig_indexes): - raise ValueError("Signal information lists have a mismatch.") - - return ind_offset, sigs_list, sig_rangel_list, sig_indexes - - -def get_online_subsegments_from_buffer( - buffer_start: float, - buffer_end: float, - sample_rate: int, - speech_labels_for_update: torch.Tensor, - audio_buffer: torch.Tensor, - segment_indexes: List[int], - window: float, - shift: float, -) -> Tuple[List[torch.Tensor], List[List[float]], List[int]]: - """ - Generate subsegments for online processing from the given segment information. - This function extracts subsegments (embedding vector level) time-series from the - raw time-series buffer based on the segment interval (start and end timestamps) information. - - Args: - buffer_start (float): - Start point of the time-series signal buffer - buffer_end (float): - End point of the time-series signal buffer - sample_rate (int): - Sampling rate of the audio input - speech_labels_for_update (Tensor): - Tensor containing intervals (start and end timestamps) of the speech segments - audio_buffer (Tensor): - Tensor containing the raw time-series signal - segment_indexes (list): - List containing the unique indices of segments - window (float): - Window length in second - shift (float): - Shift length in second - - Returns: - sigs_list (list): - List containing the tensors of the old and the newly added time-series signals - sig_rangel_list (list): - List containing the old and the newly added intervals (timestamps) of the speech segments - sig_indexes (list): - List containing the old and the newly added unique indices of segments - """ - sigs_list: List[torch.Tensor] = [] - sig_rangel_list: List[List[float]] = [] - sig_indexes: List[int] = [] - if len(segment_indexes) > 0: - ind_offset = segment_indexes[-1] - else: - ind_offset = -1 - - for idx, range_spl in enumerate(speech_labels_for_update): - range_offs = [float(range_spl[0].item() - buffer_start), float(range_spl[1].item() - buffer_start)] - range_t = [max(0, range_offs[0]), range_offs[1]] - - subsegments = get_subsegments_scriptable( - offset=range_t[0], - window=window, - shift=shift, - duration=(range_t[1] - range_t[0]), - ) - ind_offset, sigs, ranges, inds = get_online_segments_from_slices( - sig=audio_buffer, - buffer_start=buffer_start, - buffer_end=buffer_end, - subsegments=subsegments, - window=window, - ind_offset=ind_offset, - sample_rate=sample_rate, - ) - - sigs_list.extend(sigs) - sig_rangel_list.extend(ranges) - sig_indexes.extend(inds) - - assert len(sigs_list) == len(sig_rangel_list) == len(sig_indexes) - return sigs_list, sig_rangel_list, sig_indexes - - -def timestamps_to_pyannote_object( - speaker_timestamps: List[Tuple[float, float]], - uniq_id: str, - audio_rttm_values: Dict[str, str], - all_hypothesis: List[Tuple[str, Timeline]], - all_reference: List[Tuple[str, Timeline]], - all_uems: List[Tuple[str, Timeline]], - out_rttm_dir: str | None, -): - """ - Convert speaker timestamps to pyannote.core.Timeline object. - - Args: - speaker_timestamps (List[Tuple[float, float]]): - Timestamps of each speaker: start time and end time of each speaker. - uniq_id (str): - Unique ID of each speaker. - audio_rttm_values (Dict[str, str]): - Dictionary of manifest values. - all_hypothesis (List[Tuple[str, pyannote.core.Timeline]]): - List of hypothesis in pyannote.core.Timeline object. - all_reference (List[Tuple[str, pyannote.core.Timeline]]): - List of reference in pyannote.core.Timeline object. - all_uems (List[Tuple[str, pyannote.core.Timeline]]): - List of uems in pyannote.core.Timeline object. - out_rttm_dir (str | None): - Directory to save RTTMs - - Returns: - all_hypothesis (List[Tuple[str, pyannote.core.Timeline]]): - List of hypothesis in pyannote.core.Timeline object with an added Timeline object. - all_reference (List[Tuple[str, pyannote.core.Timeline]]): - List of reference in pyannote.core.Timeline object with an added Timeline object. - all_uems (List[Tuple[str, pyannote.core.Timeline]]): - List of uems in pyannote.core.Timeline object with an added Timeline object. - """ - offset, dur = float(audio_rttm_values.get('offset', None)), float(audio_rttm_values.get('duration', None)) - hyp_labels = generate_diarization_output_lines( - speaker_timestamps=speaker_timestamps, model_spk_num=len(speaker_timestamps) - ) - hypothesis = labels_to_pyannote_object(hyp_labels, uniq_name=uniq_id) - if out_rttm_dir is not None and os.path.exists(out_rttm_dir): - with open(f'{out_rttm_dir}/{uniq_id}.rttm', 'w') as f: - hypothesis.write_rttm(f) - all_hypothesis.append([uniq_id, hypothesis]) - rttm_file = audio_rttm_values.get('rttm_filepath', None) - if rttm_file is not None and os.path.exists(rttm_file): - uem_lines = [[offset, dur + offset]] - org_ref_labels = rttm_to_labels(rttm_file) - ref_labels = org_ref_labels - reference = labels_to_pyannote_object(ref_labels, uniq_name=uniq_id) - uem_obj = get_uem_object(uem_lines, uniq_id=uniq_id) - all_uems.append(uem_obj) - all_reference.append([uniq_id, reference]) - return all_hypothesis, all_reference, all_uems - - -def get_uem_object(uem_lines: List[List[float]], uniq_id: str): - """ - Generate pyannote timeline segments for uem file. - - file format - UNIQ_SPEAKER_ID CHANNEL START_TIME END_TIME - - Args: - uem_lines (list): list of session ID and start, end times. - Example: - [[0.0, 30.41], [60.04, 165.83]] - uniq_id (str): Unique session ID. - - Returns: - timeline (pyannote.core.Timeline): pyannote timeline object. - """ - timeline = Timeline(uri=uniq_id) - for uem_stt_end in uem_lines: - start_time, end_time = uem_stt_end - timeline.add(Segment(float(start_time), float(end_time))) - return timeline - - -def embedding_normalize(embs, use_std=False, eps=1e-10): - """ - Mean and l2 length normalize the input speaker embeddings - - Args: - embs: embeddings of shape (Batch,emb_size) - Returns: - embs: normalized embeddings of shape (Batch,emb_size) - """ - embs = embs - embs.mean(axis=0) - if use_std: - embs = embs / (embs.std(axis=0) + eps) - embs_l2_norm = np.expand_dims(np.linalg.norm(embs, ord=2, axis=-1), axis=1) - embs = embs / embs_l2_norm - - return embs - - -class OnlineSegmentor: - """ - Online Segmentor for online (streaming) diarizer. - - The class instances created by this class takes time-series signal from the audio buffer and - creates subsegments for embedding extraction. - - Since online segmentation is based on a short audio buffer, the methods in this class extracts - a few subsegments from the given intervals for the raw time-series signal. - - Attributes: - frame_start (float): - Start of the middle chunk - buffer_start (float): - Start of the entire buffer - buffer_end (float): - End of the entire buffer - sample_rate (int): - Sampling rate of the input time-series signal - cumulative_speech_labels (Tensor): - Torch tensor matrix containing culmulative VAD (speech activity) timestamps - """ - - def __init__(self, sample_rate: int): - self.frame_start: float = 0.0 - self.buffer_start: float = 0.0 - self.buffer_end: float = 0.0 - self.sample_rate: int = sample_rate - self.cumulative_speech_labels: torch.Tensor = torch.tensor([]) - - def run_online_segmentation( - self, - audio_buffer: torch.Tensor, - vad_timestamps: torch.Tensor, - segment_raw_audio: List[torch.Tensor], - segment_range_ts: List[List[float]], - segment_indexes: List[int], - window: float, - shift: float, - ) -> Tuple[List[torch.Tensor], List[List[float]], List[int]]: - """ - Remove the old segments that overlap with the new frame (self.frame_start) - cursor_for_old_segments is pointing at the onset of the t_range popped most recently. - - Frame is in the middle of the buffer. - - |___Buffer___[___________]____________| - |____________[ Frame ]____________| - - | <- buffer start - |____________| <- frame start - - - Args: - audio_buffer (Tensor): - Tensor containing raw time-series signal - vad_timestamps (Tensor): - Tensor containing VAD intervals (start and end timestamps) - segment_raw_audio (list): - List containing the previously added tensors of the raw time-series signal segments - segment_range_ts (list): - List containing the previously added intervals (start and end timestamps) of each segment - segment_indexes (list): - List containing the previously added global integer indicies of the segments from - start to current cursor - window (float): - Window length in second - shift (float): - Shift length in second - - Returns: - segment_raw_audio (list): - List containing the newly added tensors of the raw time-series signal - segment_range_ts (list): - List containing the newly added interval (start and end timestamps) of each segment - segment_indexes (list): - List containing the newly added global integer indicies of the segments from - start to current cursor - """ - if self.buffer_start >= 0: - # Check if this is the very first step - if len(segment_raw_audio) == 0 and vad_timestamps.shape[0] > 0: - vad_timestamps[0][0] = max(vad_timestamps[0][0], 0.0) - speech_labels_for_update = vad_timestamps - self.cumulative_speech_labels = speech_labels_for_update - else: - # Calculate a cursor for the update point - cursor_for_old_segments, cursor_index = get_new_cursor_for_update(self.frame_start, segment_range_ts) - - segment_range_ts = segment_range_ts[:cursor_index] - segment_raw_audio = segment_raw_audio[:cursor_index] - segment_indexes = segment_indexes[:cursor_index] - - if not len(segment_raw_audio) == len(segment_range_ts) == len(segment_indexes): - raise ValueError("Scale-wise segment information has a mismatch in length.") - - speech_labels_for_update, self.cumulative_speech_labels = get_speech_labels_for_update( - self.frame_start, - self.buffer_end, - self.cumulative_speech_labels, - vad_timestamps, - cursor_for_old_segments, - ) - - # Collect the timeseries signal from the buffer - sigs_list, sig_rangel_list, sig_indexes = get_online_subsegments_from_buffer( - buffer_start=self.buffer_start, - buffer_end=self.buffer_end, - sample_rate=self.sample_rate, - speech_labels_for_update=speech_labels_for_update, - audio_buffer=audio_buffer, - segment_indexes=segment_indexes, - window=window, - shift=shift, - ) - - segment_raw_audio.extend(sigs_list) - segment_range_ts.extend(sig_rangel_list) - segment_indexes.extend(sig_indexes) - - if not len(segment_raw_audio) == len(segment_range_ts) == len(segment_indexes): - raise ValueError("Segment information has a mismatch in length.") - return segment_raw_audio, segment_range_ts, segment_indexes diff --git a/nemo/collections/asr/parts/utils/streaming_utils.py b/nemo/collections/asr/parts/utils/streaming_utils.py deleted file mode 100644 index d657c56a67b6da3150357bfb59d973d449f16173..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/streaming_utils.py +++ /dev/null @@ -1,2394 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import copy -import logging -import math -import os -from dataclasses import dataclass -from pathlib import Path -from typing import NamedTuple, Optional - -import librosa -import numpy as np -import torch -from omegaconf import OmegaConf -from torch.nn.utils.rnn import pad_sequence -from torch.utils.data import DataLoader, Dataset - -from nemo.collections.asr.data.audio_to_text_lhotse_prompted import PromptedAudioToTextMiniBatch -from nemo.collections.asr.models import ASRModel -from nemo.collections.asr.parts.context_biasing.biasing_multi_model import BiasingRequestItemConfig -from nemo.collections.asr.parts.mixins.streaming import StreamingEncoder -from nemo.collections.asr.parts.preprocessing.features import normalize_batch -from nemo.collections.asr.parts.preprocessing.segment import get_samples -from nemo.collections.asr.parts.utils import rnnt_utils -from nemo.collections.asr.parts.utils.timestamp_utils import get_forced_aligned_timestamps_with_external_model -from nemo.collections.common.tokenizers.canary_tokenizer import CanaryBPETokenizer -from nemo.core.classes import IterableDataset -from nemo.core.neural_types import LengthsType, MelSpectrogramType, NeuralType - -# Minimum number of tokens required to assign a LCS merge step, otherwise ignore and -# select all i-1 and ith buffer tokens to merge. -MIN_MERGE_SUBSEQUENCE_LEN = 1 - - -def print_alignment(alignment): - """ - Print an alignment matrix of the shape (m + 1, n + 1) - - Args: - alignment: An integer alignment matrix of shape (m + 1, n + 1) - """ - m = len(alignment) - if m > 0: - n = len(alignment[0]) - for i in range(m): - for j in range(n): - if j == 0: - print(f"{i:4d} |", end=" ") - print(f"{alignment[i][j]}", end=" ") - print() - - -def write_lcs_alignment_to_pickle(alignment, filepath, extras=None): - """ - Writes out the LCS alignment to a file, along with any extras provided. - - Args: - alignment: An alignment matrix of shape [m + 1, n + 1] - filepath: str filepath - extras: Optional dictionary of items to preserve. - """ - if extras is None: - extras = {} - - extras['alignment'] = alignment - torch.save(extras, filepath) - - -def longest_common_subsequence_merge(X, Y, filepath=None): - """ - Longest Common Subsequence merge algorithm for aligning two consecutive buffers. - - Base alignment construction algorithm is Longest Common Subsequence (reffered to as LCS hear after) - - LCS Merge algorithm looks at two chunks i-1 and i, determins the aligned overlap at the - end of i-1 and beginning of ith chunk, and then clips the subsegment of the ith chunk. - - Assumption is that the two chunks are consecutive chunks, and there exists at least small overlap acoustically. - - It is a sub-word token merge algorithm, operating on the abstract notion of integer ids representing - the subword ids. It is independent of text or character encoding. - - Since the algorithm is merge based, and depends on consecutive buffers, the very first buffer is processes using - the "middle tokens" algorithm. - - It requires a delay of some number of tokens such that: - lcs_delay = math.floor(((total_buffer_in_secs - chunk_len_in_sec)) / model_stride_in_secs) - - Total cost of the model is O(m_{i-1} * n_{i}) where (m, n) represents the number of subword ids of the buffer. - - Args: - X: The subset of the previous chunk i-1, sliced such X = X[-(lcs_delay * max_steps_per_timestep):] - Therefore there can be at most lcs_delay * max_steps_per_timestep symbols for X, preserving computation. - Y: The entire current chunk i. - filepath: Optional filepath to save the LCS alignment matrix for later introspection. - - Returns: - A tuple containing - - - i: Start index of alignment along the i-1 chunk. - - j: Start index of alignment along the ith chunk. - - slice_len: number of tokens to slice off from the ith chunk. - The LCS alignment matrix itself (shape m + 1, n + 1) - """ - # LCSuff is the table with zero - # value initially in each cell - m = len(X) - n = len(Y) - LCSuff = [[0 for _ in range(n + 1)] for _ in range(m + 1)] - - # To store the length of - # longest common substring - result = 0 - result_idx = [0, 0, 0] # Contains (i, j, slice_len) - - # Following steps to build - # LCSuff[m+1][n+1] in bottom up fashion - for i in range(m + 1): - for j in range(n + 1): - if i == 0 or j == 0: - LCSuff[i][j] = 0 - elif X[i - 1] == Y[j - 1]: - LCSuff[i][j] = LCSuff[i - 1][j - 1] + 1 - - if result <= LCSuff[i][j]: - result = LCSuff[i][j] # max(result, LCSuff[i][j]) - result_idx = [i, j, result] - - else: - LCSuff[i][j] = 0 - - # Check if perfect alignment was found or not - # Perfect alignment is found if : - # Longest common subsequence extends to the final row of of the old buffer - # This means that there exists a diagonal LCS backtracking to the beginning of the new buffer - i, j = result_idx[0:2] - is_complete_merge = i == m - - # Perfect alignment was found, slice eagerly - if is_complete_merge: - length = result_idx[-1] - - # In case the LCS was incomplete - missing a few tokens at the beginning - # Perform backtrack to find the origin point of the slice (j) and how many tokens should be sliced - while length >= 0 and i > 0 and j > 0: - # Alignment exists at the required diagonal - if LCSuff[i - 1][j - 1] > 0: - length -= 1 - i, j = i - 1, j - 1 - - else: - # End of longest alignment - i, j, length = i - 1, j - 1, length - 1 - break - - else: - # Expand hypothesis to catch partial mismatch - - # There are 3 steps for partial mismatch in alignment - # 1) Backward search for leftmost LCS - # 2) Greedy expansion of leftmost LCS to the right - # 3) Backtrack final leftmost expanded LCS to find origin point of slice - - # (1) Backward search for Leftmost LCS - # This is required for cases where multiple common subsequences exist - # We only need to select the leftmost one - since that corresponds - # to the last potential subsequence that matched with the new buffer. - # If we just chose the LCS (and not the leftmost LCS), then we can potentially - # slice off major sections of text which are repeated between two overlapping buffers. - - # backward linear search for leftmost j with longest subsequence - max_j = 0 - max_j_idx = n - - i_partial = m # Starting index of i for partial merge - j_partial = -1 # Index holder of j for partial merge - j_skip = 0 # Number of tokens that were skipped along the diagonal - slice_count = 0 # Number of tokens that should be sliced - - # Select leftmost LCS - for i_idx in range(m, -1, -1): # start from last timestep of old buffer - for j_idx in range(0, n + 1): # start from first token from new buffer - # Select the longest LCSuff, while minimizing the index of j (token index for new buffer) - if LCSuff[i_idx][j_idx] > max_j and j_idx <= max_j_idx: - max_j = LCSuff[i_idx][j_idx] - max_j_idx = j_idx - - # Update the starting indices of the partial merge - i_partial = i_idx - j_partial = j_idx - - # EARLY EXIT (if max subsequence length <= MIN merge length) - # Important case where there is long silence - # The end of one buffer will have many blank tokens, the beginning of new buffer may have many blank tokens - # As such, LCS will potentially be from the region of actual tokens. - # This can be detected as the max length of the suffix in LCS - # If this max length of the leftmost suffix is less than some margin, avoid slicing all together. - if max_j <= MIN_MERGE_SUBSEQUENCE_LEN: - # If the number of partiial tokens to be deleted are less than the minimum, - # dont delete any tokens at all. - - i = i_partial - j = 0 - result_idx[-1] = 0 - - else: - # Some valid long partial alignment was found - # (2) Expand this alignment along the diagonal *downwards* towards the end of the old buffer - # such that i_partial = m + 1. - # This is a common case where due to LSTM state or reduced buffer size, the alignment breaks - # in the middle but there are common subsequences between old and new buffers towards the end - # We can expand the current leftmost LCS in a diagonal manner downwards to include such potential - # merge regions. - - # Expand current partial subsequence with co-located tokens - i_temp = i_partial + 1 # diagonal next i - j_temp = j_partial + 1 # diagonal next j - - j_exp = 0 # number of tokens to expand along the diagonal - j_skip = 0 # how many diagonals didnt have the token. Incremented by 1 for every row i - - for i_idx in range(i_temp, m + 1): # walk from i_partial + 1 => m + 1 - j_any_skip = 0 # If the diagonal element at this location is not found, set to 1 - # j_any_skip expands the search space one place to the right - # This allows 1 diagonal misalignment per timestep i (and expands the search for the next timestep) - - # walk along the diagonal corresponding to i_idx, plus allowing diagonal skips to occur - # diagonal elements may not be aligned due to ASR model predicting - # incorrect token in between correct tokens - for j_idx in range(j_temp, j_temp + j_skip + 1): - if j_idx < n + 1: - if LCSuff[i_idx][j_idx] == 0: - j_any_skip = 1 - else: - j_exp = 1 + j_skip + j_any_skip - - # If the diagonal element existed, dont expand the search space, - # otherwise expand the search space 1 token to the right - j_skip += j_any_skip - - # Move one step to the right for the next diagonal j corresponding to i - j_temp += 1 - - # reset j_skip, augment j_partial with expansions - j_skip = 0 - j_partial += j_exp - - # (3) Given new leftmost j_partial with expansions, backtrack the partial alignments - # counting how many diagonal skips occured to compute slice length - # as well as starting point of slice. - - # Partial backward trace to find start of slice - while i_partial > 0 and j_partial > 0: - if LCSuff[i_partial][j_partial] == 0: - # diagonal skip occured, move j to left 1 extra time - j_partial -= 1 - j_skip += 1 - - if j_partial > 0: - # If there are more steps to be taken to the left, slice off the current j - # Then loop for next (i, j) diagonal to the upper left - slice_count += 1 - i_partial -= 1 - j_partial -= 1 - - # Recompute total slice length as slice count along diagonal - # plus the number of diagonal skips - i = max(0, i_partial) - j = max(0, j_partial) - result_idx[-1] = slice_count + j_skip - - # Set the value of i and j - result_idx[0] = i - result_idx[1] = j - - if filepath is not None: - extras = { - "is_complete_merge": is_complete_merge, - "X": X, - "Y": Y, - "slice_idx": result_idx, - } - write_lcs_alignment_to_pickle(LCSuff, filepath=filepath, extras=extras) - print("Wrote alignemnt to :", filepath) - - return result_idx, LCSuff - - -def lcs_alignment_merge_buffer( - buffer, - data, - delay, - model, - max_steps_per_timestep: int = 5, - filepath: str = None, - min_lcs_length: int = 1, - parallel_chunking: bool = False, -): - """ - Merges the new text from the current frame with the previous text contained in the buffer. - - The alignment is based on a Longest Common Subsequence algorithm, with some additional heuristics leveraging - the notion that the chunk size is >= the context window. In case this assumption is violated, the results of the - merge will be incorrect (or at least obtain worse WER overall). - - If the LCS found is shorter than min_lcs_length, no deduplication is performed. - - Args: - buffer: The existing buffer of tokens - data: New data to merge with buffer - delay: Number of delay timesteps - model: The ASR model - max_steps_per_timestep: Maximum steps per timestep - filepath: Optional filepath for debugging - min_lcs_length: Minimum LCS length for deduplication - parallel_chunking: If True, remove the LCS from the buffer as well, then concatenate with data; if False, make changes only to the data - """ - if delay < 1 or len(buffer) == 0: - buffer += data - return buffer - - search_size = int(delay * max_steps_per_timestep) - buffer_slice = buffer[-search_size:] - - lcs_idx, lcs_alignment = longest_common_subsequence_merge(buffer_slice, data, filepath=filepath) - i_rel, j_rel, length = lcs_idx - - if length < min_lcs_length: - return buffer + data - - if parallel_chunking: - base = len(buffer) - len(buffer_slice) - i_abs_start = base + i_rel - i_abs_end = i_abs_start + length # end position (exclusive) in `buffer` - j_after = j_rel + length # first index after LCS in `data` - - merged = buffer[:i_abs_end] + data[j_after:] - return merged - else: - # Slice off new data based on LCS and concatenate - slice_idx = j_rel + length - data = data[slice_idx:] - buffer += data - return buffer - - -def inplace_buffer_merge(buffer, data, timesteps, model): - """ - Merges the new text from the current frame with the previous text contained in the buffer. - - The alignment is based on a Longest Common Subsequence algorithm, with some additional heuristics leveraging - the notion that the chunk size is >= the context window. In case this assumptio is violated, the results of - the merge will be incorrect (or at least obtain worse WER overall). - """ - # If delay timesteps is 0, that means no future context was used. Simply concatenate the buffer with new data. - if timesteps < 1: - buffer += data - return buffer - - # If buffer is empty, simply concatenate the buffer and data. - if len(buffer) == 0: - buffer += data - return buffer - - # Concat data to buffer - buffer += data - return buffer - - -class StreamingFeatureBufferer: - """ - Class to append each feature frame to a buffer and return an array of buffers. - This class is designed to perform a real-life streaming decoding where only a single chunk - is provided at each step of a streaming pipeline. - """ - - def __init__(self, asr_model, chunk_size, buffer_size): - ''' - Args: - asr_model: - Reference to the asr model instance for which the feature needs to be created - chunk_size (float): - Duration of the new chunk of audio - buffer_size (float): - Size of the total audio in seconds maintained in the buffer - ''' - - self.NORM_CONSTANT = 1e-5 - if hasattr(asr_model.preprocessor, 'log') and asr_model.preprocessor.log: - self.ZERO_LEVEL_SPEC_DB_VAL = -16.635 # Log-Melspectrogram value for zero signal - else: - self.ZERO_LEVEL_SPEC_DB_VAL = 0.0 - self.asr_model = asr_model - self.sr = asr_model.cfg.sample_rate - self.model_normalize_type = asr_model.cfg.preprocessor.normalize - self.chunk_size = chunk_size - timestep_duration = asr_model.cfg.preprocessor.window_stride - - self.n_chunk_look_back = int(timestep_duration * self.sr) - self.n_chunk_samples = int(chunk_size * self.sr) - self.buffer_size = buffer_size - total_buffer_len = int(buffer_size / timestep_duration) - self.n_feat = asr_model.cfg.preprocessor.features - self.sample_buffer = torch.zeros(int(self.buffer_size * self.sr)) - self.buffer = torch.ones([self.n_feat, total_buffer_len], dtype=torch.float32) * self.ZERO_LEVEL_SPEC_DB_VAL - self.feature_chunk_len = int(chunk_size / timestep_duration) - self.feature_buffer_len = total_buffer_len - - self.reset() - cfg = copy.deepcopy(asr_model.cfg) - OmegaConf.set_struct(cfg.preprocessor, False) - - cfg.preprocessor.dither = 0.0 - cfg.preprocessor.pad_to = 0 - cfg.preprocessor.normalize = "None" - self.raw_preprocessor = ASRModel.from_config_dict(cfg.preprocessor) - self.raw_preprocessor.to(asr_model.device) - - def reset(self): - ''' - Reset frame_history and decoder's state - ''' - self.buffer = torch.ones(self.buffer.shape, dtype=torch.float32) * self.ZERO_LEVEL_SPEC_DB_VAL - self.frame_buffers = [] - self.sample_buffer = torch.zeros(int(self.buffer_size * self.sr)) - self.feature_buffer = ( - torch.ones([self.n_feat, self.feature_buffer_len], dtype=torch.float32) * self.ZERO_LEVEL_SPEC_DB_VAL - ) - - def _add_chunk_to_buffer(self, chunk): - """ - Add time-series audio signal to `sample_buffer` - - Args: - chunk (Tensor): - Tensor filled with time-series audio signal - """ - self.sample_buffer[: -self.n_chunk_samples] = self.sample_buffer[self.n_chunk_samples :].clone() - self.sample_buffer[-self.n_chunk_samples :] = chunk.clone() - - def _update_feature_buffer(self, feat_chunk): - """ - Add an extracted feature to `feature_buffer` - """ - self.feature_buffer[:, : -self.feature_chunk_len] = self.feature_buffer[:, self.feature_chunk_len :].clone() - self.feature_buffer[:, -self.feature_chunk_len :] = feat_chunk.clone() - - def get_raw_feature_buffer(self): - return self.feature_buffer - - def get_normalized_feature_buffer(self): - normalized_buffer, _, _ = normalize_batch( - x=self.feature_buffer.unsqueeze(0), - seq_len=torch.tensor([len(self.feature_buffer)]), - normalize_type=self.model_normalize_type, - ) - return normalized_buffer.squeeze(0) - - def _convert_buffer_to_features(self): - """ - Extract features from the time-series audio buffer `sample_buffer`. - """ - # samples for conversion to features. - # Add look_back to have context for the first feature - samples = self.sample_buffer[: -(self.n_chunk_samples + self.n_chunk_look_back)] - device = self.asr_model.device - audio_signal = samples.unsqueeze_(0).to(device) - audio_signal_len = torch.Tensor([samples.shape[1]]).to(device) - features, features_len = self.raw_preprocessor( - input_signal=audio_signal, - length=audio_signal_len, - ) - features = features.squeeze() - self._update_feature_buffer(features[:, -self.feature_chunk_len :]) - - def update_feature_buffer(self, chunk): - """ - Update time-series signal `chunk` to the buffer then generate features out of the - signal in the audio buffer. - - Args: - chunk (Tensor): - Tensor filled with time-series audio signal - """ - if len(chunk) > self.n_chunk_samples: - raise ValueError(f"chunk should be of length {self.n_chunk_samples} or less") - if len(chunk) < self.n_chunk_samples: - temp_chunk = torch.zeros(self.n_chunk_samples, dtype=torch.float32) - temp_chunk[: chunk.shape[0]] = chunk - chunk = temp_chunk - self._add_chunk_to_buffer(chunk) - self._convert_buffer_to_features() - - -class AudioFeatureIterator(IterableDataset): - def __init__(self, samples, frame_len, preprocessor, device, pad_to_frame_len=True): - self._samples = samples - self._frame_len = frame_len - self._start = 0 - self.output = True - self.count = 0 - self.pad_to_frame_len = pad_to_frame_len - timestep_duration = preprocessor._cfg['window_stride'] - self._feature_frame_len = frame_len / timestep_duration - audio_signal = torch.from_numpy(self._samples).unsqueeze_(0).to(device) - audio_signal_len = torch.Tensor([self._samples.shape[0]]).to(device) - self._features, self._features_len = preprocessor( - input_signal=audio_signal, - length=audio_signal_len, - ) - self._features = self._features.squeeze() - - def __iter__(self): - return self - - def __next__(self): - if not self.output: - raise StopIteration - last = int(self._start + self._feature_frame_len) - if last <= self._features_len[0]: - frame = self._features[:, self._start : last].cpu() - self._start = last - else: - if not self.pad_to_frame_len: - frame = self._features[:, self._start : self._features_len[0]].cpu() - else: - frame = np.zeros([self._features.shape[0], int(self._feature_frame_len)], dtype='float32') - segment = self._features[:, self._start : self._features_len[0]].cpu() - frame[:, : segment.shape[1]] = segment - self.output = False - self.count += 1 - return frame - - -def speech_collate_fn(batch): - """collate batch of audio sig, audio len, tokens, tokens len - Args: - batch (Optional[FloatTensor], Optional[LongTensor], LongTensor, - LongTensor): A tuple of tuples of signal, signal lengths, - encoded tokens, and encoded tokens length. This collate func - assumes the signals are 1d torch tensors (i.e. mono audio). - """ - _, audio_lengths = zip(*batch) - max_audio_len = 0 - has_audio = audio_lengths[0] is not None - if has_audio: - max_audio_len = max(audio_lengths).item() - - audio_signal = [] - for sig, sig_len in batch: - if has_audio: - sig_len = sig_len.item() - if sig_len < max_audio_len: - pad = (0, max_audio_len - sig_len) - sig = torch.nn.functional.pad(sig, pad) - audio_signal.append(sig) - - if has_audio: - audio_signal = torch.stack(audio_signal) - audio_lengths = torch.stack(audio_lengths) - else: - audio_signal, audio_lengths = None, None - - return audio_signal, audio_lengths - - -# simple data layer to pass buffered frames of audio samples -class AudioBuffersDataLayer(IterableDataset): - @property - def output_types(self): - return { - "processed_signal": NeuralType(('B', 'D', 'T'), MelSpectrogramType()), - "processed_length": NeuralType(tuple('B'), LengthsType()), - } - - def __init__(self): - super().__init__() - - def __iter__(self): - return self - - def __next__(self): - if self._buf_count == len(self.signal): - raise StopIteration - self._buf_count += 1 - return ( - torch.as_tensor(self.signal[self._buf_count - 1], dtype=torch.float32), - torch.as_tensor(self.signal[self._buf_count - 1].shape[1], dtype=torch.int64), - ) - - def set_signal(self, signals): - self.signal = signals - self.signal_shape = self.signal[0].shape - self._buf_count = 0 - - def __len__(self): - return 1 - - -class FeatureFrameBufferer: - """ - Class to append each feature frame to a buffer and return - an array of buffers. - """ - - def __init__(self, asr_model, frame_len=1.6, batch_size=4, total_buffer=4.0, pad_to_buffer_len=True): - ''' - Args: - frame_len: frame's duration, seconds - frame_overlap: duration of overlaps before and after current frame, seconds - offset: number of symbols to drop for smooth streaming - ''' - if hasattr(asr_model.preprocessor, 'log') and asr_model.preprocessor.log: - self.ZERO_LEVEL_SPEC_DB_VAL = -16.635 # Log-Melspectrogram value for zero signal - else: - self.ZERO_LEVEL_SPEC_DB_VAL = 0.0 - self.asr_model = asr_model - self.sr = asr_model._cfg.sample_rate - self.frame_len = frame_len - timestep_duration = asr_model._cfg.preprocessor.window_stride - self.n_frame_len = int(frame_len / timestep_duration) - - total_buffer_len = int(total_buffer / timestep_duration) - self.n_feat = asr_model._cfg.preprocessor.features - self.buffer = np.ones([self.n_feat, total_buffer_len], dtype=np.float32) * self.ZERO_LEVEL_SPEC_DB_VAL - self.pad_to_buffer_len = pad_to_buffer_len - self.batch_size = batch_size - - self.signal_end = False - self.frame_reader = None - self.feature_buffer_len = total_buffer_len - - self.feature_buffer = ( - np.ones([self.n_feat, self.feature_buffer_len], dtype=np.float32) * self.ZERO_LEVEL_SPEC_DB_VAL - ) - self.frame_buffers = [] - self.buffered_features_size = 0 - self.reset() - self.buffered_len = 0 - - def reset(self): - ''' - Reset frame_history and decoder's state - ''' - self.buffer = np.ones(shape=self.buffer.shape, dtype=np.float32) * self.ZERO_LEVEL_SPEC_DB_VAL - self.prev_char = '' - self.unmerged = [] - self.frame_buffers = [] - self.buffered_len = 0 - self.feature_buffer = ( - np.ones([self.n_feat, self.feature_buffer_len], dtype=np.float32) * self.ZERO_LEVEL_SPEC_DB_VAL - ) - - def get_batch_frames(self): - if self.signal_end: - return [] - batch_frames = [] - for frame in self.frame_reader: - batch_frames.append(np.copy(frame)) - if len(batch_frames) == self.batch_size: - return batch_frames - self.signal_end = True - - return batch_frames - - def get_frame_buffers(self, frames): - # Build buffers for each frame - self.frame_buffers = [] - for frame in frames: - curr_frame_len = frame.shape[1] - self.buffered_len += curr_frame_len - if curr_frame_len < self.feature_buffer_len and not self.pad_to_buffer_len: - self.frame_buffers.append(np.copy(frame)) - continue - self.buffer[:, :-curr_frame_len] = self.buffer[:, curr_frame_len:] - self.buffer[:, -self.n_frame_len :] = frame - self.frame_buffers.append(np.copy(self.buffer)) - return self.frame_buffers - - def set_frame_reader(self, frame_reader): - self.frame_reader = frame_reader - self.signal_end = False - - def _update_feature_buffer(self, feat_frame): - curr_frame_len = feat_frame.shape[1] - if curr_frame_len < self.feature_buffer_len and not self.pad_to_buffer_len: - self.feature_buffer = np.copy(feat_frame) # assume that only the last frame is less than the buffer length - else: - self.feature_buffer[:, : -feat_frame.shape[1]] = self.feature_buffer[:, feat_frame.shape[1] :] - self.feature_buffer[:, -feat_frame.shape[1] :] = feat_frame - self.buffered_features_size += feat_frame.shape[1] - - def get_norm_consts_per_frame(self, batch_frames): - norm_consts = [] - for i, frame in enumerate(batch_frames): - self._update_feature_buffer(frame) - mean_from_buffer = np.mean(self.feature_buffer, axis=1) - stdev_from_buffer = np.std(self.feature_buffer, axis=1) - norm_consts.append((mean_from_buffer.reshape(self.n_feat, 1), stdev_from_buffer.reshape(self.n_feat, 1))) - return norm_consts - - def normalize_frame_buffers(self, frame_buffers, norm_consts): - CONSTANT = 1e-5 - for i, frame_buffer in enumerate(frame_buffers): - frame_buffers[i] = (frame_buffer - norm_consts[i][0]) / (norm_consts[i][1] + CONSTANT) - - def get_buffers_batch(self): - batch_frames = self.get_batch_frames() - - while len(batch_frames) > 0: - - frame_buffers = self.get_frame_buffers(batch_frames) - norm_consts = self.get_norm_consts_per_frame(batch_frames) - if len(frame_buffers) == 0: - continue - self.normalize_frame_buffers(frame_buffers, norm_consts) - return frame_buffers - return [] - - -# class for streaming frame-based ASR -# 1) use reset() method to reset FrameASR's state -# 2) call transcribe(frame) to do ASR on -# contiguous signal's frames -class FrameBatchASR: - """ - class for streaming frame-based ASR use reset() method to reset FrameASR's - state call transcribe(frame) to do ASR on contiguous signal's frames - """ - - def __init__( - self, - asr_model, - frame_len=1.6, - total_buffer=4.0, - batch_size=4, - pad_to_buffer_len=True, - ): - ''' - Args: - frame_len: frame's duration, seconds - frame_overlap: duration of overlaps before and after current frame, seconds - offset: number of symbols to drop for smooth streaming - ''' - self.frame_bufferer = FeatureFrameBufferer( - asr_model=asr_model, - frame_len=frame_len, - batch_size=batch_size, - total_buffer=total_buffer, - pad_to_buffer_len=pad_to_buffer_len, - ) - - self.asr_model = asr_model - self.decoder = getattr(asr_model, "decoder", None) - - self.batch_size = batch_size - self.all_logits = [] - self.all_preds = [] - - self.unmerged = [] - - if self.decoder is None: - if isinstance(asr_model.tokenizer, CanaryBPETokenizer): - self.blank_id = asr_model.tokenizer.vocab_size - else: - self.blank_id = len(asr_model.tokenizer.vocabulary) - elif hasattr(asr_model.decoder, "vocabulary"): - self.blank_id = len(asr_model.decoder.vocabulary) - else: - self.blank_id = len(asr_model.joint.vocabulary) - self.tokenizer = asr_model.tokenizer - self.toks_unmerged = [] - self.frame_buffers = [] - self.reset() - cfg = copy.deepcopy(asr_model._cfg) - self.cfg = cfg - self.frame_len = frame_len - OmegaConf.set_struct(cfg.preprocessor, False) - - # some changes for streaming scenario - cfg.preprocessor.dither = 0.0 - cfg.preprocessor.pad_to = 0 - cfg.preprocessor.normalize = "None" - self.raw_preprocessor = ASRModel.from_config_dict(cfg.preprocessor) - self.raw_preprocessor.to(asr_model.device) - self.preprocessor = self.raw_preprocessor - - def reset(self): - """ - Reset frame_history and decoder's state - """ - self.prev_char = '' - self.unmerged = [] - self.data_layer = AudioBuffersDataLayer() - self.data_loader = DataLoader(self.data_layer, batch_size=self.batch_size, collate_fn=speech_collate_fn) - self.all_logits = [] - self.all_preds = [] - self.toks_unmerged = [] - self.frame_buffers = [] - self.frame_bufferer.reset() - - def read_audio_file(self, audio_filepath: str, delay, model_stride_in_secs): - samples = get_samples(audio_filepath) - samples = np.pad(samples, (0, int(delay * model_stride_in_secs * self.asr_model._cfg.sample_rate))) - frame_reader = AudioFeatureIterator(samples, self.frame_len, self.raw_preprocessor, self.asr_model.device) - self.set_frame_reader(frame_reader) - - def set_frame_reader(self, frame_reader): - self.frame_bufferer.set_frame_reader(frame_reader) - - @torch.no_grad() - def infer_logits(self, keep_logits=False): - frame_buffers = self.frame_bufferer.get_buffers_batch() - - while len(frame_buffers) > 0: - self.frame_buffers += frame_buffers[:] - self.data_layer.set_signal(frame_buffers[:]) - self._get_batch_preds(keep_logits) - frame_buffers = self.frame_bufferer.get_buffers_batch() - - @torch.no_grad() - def _get_batch_preds(self, keep_logits=False): - device = self.asr_model.device - for batch in iter(self.data_loader): - - feat_signal, feat_signal_len = batch - feat_signal, feat_signal_len = feat_signal.to(device), feat_signal_len.to(device) - forward_outs = self.asr_model(processed_signal=feat_signal, processed_signal_length=feat_signal_len) - - if len(forward_outs) == 2: # hybrid ctc rnnt model - encoded, encoded_len = forward_outs - log_probs = self.asr_model.ctc_decoder(encoder_output=encoded) - predictions = log_probs.argmax(dim=-1, keepdim=False) - else: - log_probs, encoded_len, predictions = forward_outs - - preds = torch.unbind(predictions) - for pred in preds: - self.all_preds.append(pred.cpu().numpy()) - if keep_logits: - log_probs = torch.unbind(log_probs) - for log_prob in log_probs: - self.all_logits.append(log_prob.cpu()) - else: - del log_probs - del encoded_len - del predictions - - def transcribe(self, tokens_per_chunk: int, delay: int, keep_logits: bool = False): - self.infer_logits(keep_logits) - self.unmerged = [] - for pred in self.all_preds: - decoded = pred.tolist() - self.unmerged += decoded[len(decoded) - 1 - delay : len(decoded) - 1 - delay + tokens_per_chunk] - hypothesis = self.greedy_merge(self.unmerged) - if not keep_logits: - return hypothesis - - all_logits = [] - for log_prob in self.all_logits: - T = log_prob.shape[0] - log_prob = log_prob[T - 1 - delay : T - 1 - delay + tokens_per_chunk, :] - all_logits.append(log_prob) - all_logits = torch.concat(all_logits, 0) - return hypothesis, all_logits - - def greedy_merge(self, preds): - decoded_prediction = [] - previous = self.blank_id - for p in preds: - if (p != previous or previous == self.blank_id) and p != self.blank_id: - decoded_prediction.append(p) - previous = p - hypothesis = self.tokenizer.ids_to_text(decoded_prediction) - return hypothesis - - -class BatchedFeatureFrameBufferer(FeatureFrameBufferer): - """ - Batched variant of FeatureFrameBufferer where batch dimension is the independent audio samples. - """ - - def __init__(self, asr_model, frame_len=1.6, batch_size=4, total_buffer=4.0): - ''' - Args: - frame_len: frame's duration, seconds - frame_overlap: duration of overlaps before and after current frame, seconds - offset: number of symbols to drop for smooth streaming - ''' - super().__init__(asr_model, frame_len=frame_len, batch_size=batch_size, total_buffer=total_buffer) - - # OVERRIDES OF BASE CLASS - timestep_duration = asr_model._cfg.preprocessor.window_stride - total_buffer_len = int(total_buffer / timestep_duration) - self.buffer = ( - np.ones([batch_size, self.n_feat, total_buffer_len], dtype=np.float32) * self.ZERO_LEVEL_SPEC_DB_VAL - ) - - # Preserve list of buffers and indices, one for every sample - self.all_frame_reader = [None for _ in range(self.batch_size)] - self.signal_end = [False for _ in range(self.batch_size)] - self.signal_end_index = [None for _ in range(self.batch_size)] - self.buffer_number = 0 # preserve number of buffers returned since reset. - - self.reset() - del self.buffered_len - del self.buffered_features_size - - def reset(self): - ''' - Reset frame_history and decoder's state - ''' - super().reset() - self.feature_buffer = ( - np.ones([self.batch_size, self.n_feat, self.feature_buffer_len], dtype=np.float32) - * self.ZERO_LEVEL_SPEC_DB_VAL - ) - self.all_frame_reader = [None for _ in range(self.batch_size)] - self.signal_end = [False for _ in range(self.batch_size)] - self.signal_end_index = [None for _ in range(self.batch_size)] - self.buffer_number = 0 - - def get_batch_frames(self): - # Exit if all buffers of all samples have been processed - if all(self.signal_end): - return [] - - # Otherwise sequentially process frames of each sample one by one. - batch_frames = [] - for idx, frame_reader in enumerate(self.all_frame_reader): - try: - frame = next(frame_reader) - frame = np.copy(frame) - - batch_frames.append(frame) - except StopIteration: - # If this sample has finished all of its buffers - # Set its signal_end flag, and assign it the id of which buffer index - # did it finish the sample (if not previously set) - # This will let the alignment module know which sample in the batch finished - # at which index. - batch_frames.append(None) - self.signal_end[idx] = True - - if self.signal_end_index[idx] is None: - self.signal_end_index[idx] = self.buffer_number - - self.buffer_number += 1 - return batch_frames - - def get_frame_buffers(self, frames): - # Build buffers for each frame - self.frame_buffers = [] - # Loop over all buffers of all samples - for idx in range(self.batch_size): - frame = frames[idx] - # If the sample has a buffer, then process it as usual - if frame is not None: - self.buffer[idx, :, : -self.n_frame_len] = self.buffer[idx, :, self.n_frame_len :] - self.buffer[idx, :, -self.n_frame_len :] = frame - # self.buffered_len += frame.shape[1] - # WRAP the buffer at index idx into a outer list - self.frame_buffers.append([np.copy(self.buffer[idx])]) - else: - # If the buffer does not exist, the sample has finished processing - # set the entire buffer for that sample to 0 - self.buffer[idx, :, :] *= 0.0 - self.frame_buffers.append([np.copy(self.buffer[idx])]) - - return self.frame_buffers - - def set_frame_reader(self, frame_reader, idx): - self.all_frame_reader[idx] = frame_reader - self.signal_end[idx] = False - self.signal_end_index[idx] = None - - def _update_feature_buffer(self, feat_frame, idx): - # Update the feature buffer for given sample, or reset if the sample has finished processing - if feat_frame is not None: - self.feature_buffer[idx, :, : -feat_frame.shape[1]] = self.feature_buffer[idx, :, feat_frame.shape[1] :] - self.feature_buffer[idx, :, -feat_frame.shape[1] :] = feat_frame - # self.buffered_features_size += feat_frame.shape[1] - else: - self.feature_buffer[idx, :, :] *= 0.0 - - def get_norm_consts_per_frame(self, batch_frames): - for idx, frame in enumerate(batch_frames): - self._update_feature_buffer(frame, idx) - - mean_from_buffer = np.mean(self.feature_buffer, axis=2, keepdims=True) # [B, self.n_feat, 1] - stdev_from_buffer = np.std(self.feature_buffer, axis=2, keepdims=True) # [B, self.n_feat, 1] - - return (mean_from_buffer, stdev_from_buffer) - - def normalize_frame_buffers(self, frame_buffers, norm_consts): - CONSTANT = 1e-8 - for i in range(len(frame_buffers)): - frame_buffers[i] = (frame_buffers[i] - norm_consts[0][i]) / (norm_consts[1][i] + CONSTANT) - - def get_buffers_batch(self): - batch_frames = self.get_batch_frames() - - while len(batch_frames) > 0: - # while there exists at least one sample that has not been processed yet - frame_buffers = self.get_frame_buffers(batch_frames) - norm_consts = self.get_norm_consts_per_frame(batch_frames) - - self.normalize_frame_buffers(frame_buffers, norm_consts) - return frame_buffers - return [] - - -class BatchedFrameASRRNNT(FrameBatchASR): - """ - Batched implementation of FrameBatchASR for RNNT models, where the batch dimension is independent audio samples. - """ - - def __init__( - self, - asr_model, - frame_len=1.6, - total_buffer=4.0, - batch_size=32, - max_steps_per_timestep: int = 5, - stateful_decoding: bool = False, - target_lang_id=None, - ): - ''' - Args: - asr_model: An RNNT model. - frame_len: frame's duration, seconds. - total_buffer: duration of total audio chunk size, in seconds. - batch_size: Number of independent audio samples to process at each step. - max_steps_per_timestep: Maximum number of tokens (u) to process per acoustic timestep (t). - stateful_decoding: Boolean whether to enable stateful decoding for preservation of state across buffers. - target_lang_id: Optional target language ID for multilingual AST models. - ''' - super().__init__(asr_model, frame_len=frame_len, total_buffer=total_buffer, batch_size=batch_size) - - # OVERRIDES OF THE BASE CLASS - self.max_steps_per_timestep = max_steps_per_timestep - self.stateful_decoding = stateful_decoding - self.target_lang_id = target_lang_id - - self.all_alignments = [[] for _ in range(self.batch_size)] - self.all_preds = [[] for _ in range(self.batch_size)] - self.all_timestamps = [[] for _ in range(self.batch_size)] - self.previous_hypotheses = None - self.batch_index_map = { - idx: idx for idx in range(self.batch_size) - } # pointer from global batch id : local sub-batch id - - try: - self.eos_id = self.asr_model.tokenizer.eos_id - except Exception: - self.eos_id = -1 - - print("Performing Stateful decoding :", self.stateful_decoding) - - if self.target_lang_id is not None: - logging.info("Using target language ID") - # OVERRIDES - self.frame_bufferer = BatchedFeatureFrameBufferer( - asr_model=asr_model, frame_len=frame_len, batch_size=batch_size, total_buffer=total_buffer - ) - - self.reset() - - def set_target_lang_id(self, target_lang_id): - """Set the target language ID for multilingual models.""" - self.target_lang_id = target_lang_id - - def reset(self): - """ - Reset frame_history and decoder's state - """ - super().reset() - - self.all_alignments = [[] for _ in range(self.batch_size)] - self.all_preds = [[] for _ in range(self.batch_size)] - self.all_timestamps = [[] for _ in range(self.batch_size)] - self.previous_hypotheses = None - self.batch_index_map = {idx: idx for idx in range(self.batch_size)} - - self.data_layer = [AudioBuffersDataLayer() for _ in range(self.batch_size)] - self.data_loader = [ - DataLoader(self.data_layer[idx], batch_size=1, collate_fn=speech_collate_fn) - for idx in range(self.batch_size) - ] - - def read_audio_file(self, audio_filepath: list, delay, model_stride_in_secs): - assert len(audio_filepath) == self.batch_size - - # Read in a batch of audio files, one by one - for idx in range(self.batch_size): - samples = get_samples(audio_filepath[idx]) - samples = np.pad(samples, (0, int(delay * model_stride_in_secs * self.asr_model._cfg.sample_rate))) - frame_reader = AudioFeatureIterator(samples, self.frame_len, self.raw_preprocessor, self.asr_model.device) - self.set_frame_reader(frame_reader, idx) - - def set_frame_reader(self, frame_reader, idx): - self.frame_bufferer.set_frame_reader(frame_reader, idx) - - @torch.no_grad() - def infer_logits(self): - frame_buffers = self.frame_bufferer.get_buffers_batch() - - while len(frame_buffers) > 0: - # While at least 1 sample has a buffer left to process - self.frame_buffers += frame_buffers[:] - - for idx, buffer in enumerate(frame_buffers): - self.data_layer[idx].set_signal(buffer[:]) - - self._get_batch_preds() - frame_buffers = self.frame_bufferer.get_buffers_batch() - - @torch.no_grad() - def _get_batch_preds(self): - """ - Perform dynamic batch size decoding of frame buffers of all samples. - - Steps: - - Load all data loaders of every sample - - For all samples, determine if signal has finished. - - If so, skip calculation of mel-specs. - - If not, compute mel spec and length - - Perform Encoder forward over this sub-batch of samples. Maintain the indices of samples that - were processed. - - If performing stateful decoding, prior to decoder forward, remove the states of samples that - were not processed. - - Perform Decoder + Joint forward for samples that were processed. - - For all output RNNT alignment matrix of the joint do: - - If signal has ended previously (this was last buffer of padding), skip alignment - - Otherwise, recalculate global index of this sample from the sub-batch index, and preserve - alignment. - - Same for preds - - Update indices of sub-batch with global index map. - - Redo steps until all samples were processed (sub-batch size == 0). - """ - device = self.asr_model.device - - data_iters = [iter(data_loader) for data_loader in self.data_loader] - - feat_signals = [] - feat_signal_lens = [] - - new_batch_keys = [] - # while not all(self.frame_bufferer.signal_end): - for idx in range(self.batch_size): - if self.frame_bufferer.signal_end[idx]: - continue - - batch = next(data_iters[idx]) - feat_signal, feat_signal_len = batch - feat_signal, feat_signal_len = feat_signal.to(device), feat_signal_len.to(device) - - feat_signals.append(feat_signal) - feat_signal_lens.append(feat_signal_len) - - # preserve batch indices - new_batch_keys.append(idx) - - if len(feat_signals) == 0: - return - - feat_signal = torch.cat(feat_signals, 0) - feat_signal_len = torch.cat(feat_signal_lens, 0) - - del feat_signals, feat_signal_lens - - # Handle prompt if needed - check if model supports prompts - prompt_tensor = None - if hasattr(self.asr_model, 'num_prompts') or hasattr(self.asr_model, 'prompt_kernel'): - # Get prompt dictionary from model config - prompt_dict = getattr(self.asr_model._cfg, 'model_defaults', {}).get('prompt_dictionary', {}) - if not prompt_dict: - logging.ValueError("Prompt dictionary is empty in model config") - - # Get prompt index from dictionary or default to 0 - prompt_idx = 0 # Default value - if self.target_lang_id is not None and isinstance(self.target_lang_id, str): - prompt_idx = prompt_dict.get(self.target_lang_id, 0) - if prompt_idx == 0 and self.target_lang_id not in prompt_dict: - logging.ValueError(f"Prompt ID '{self.target_lang_id}' not found in prompt dictionary") - - # Create target prompt tensor with calculated time dimension - time_length = feat_signal.shape[2] - hidden_length = math.ceil(time_length / 8) - - # Get number of prompts from model - if hasattr(self.asr_model, 'num_prompts'): - num_prompts = self.asr_model.num_prompts - else: - # Fallback: get from config or use default - num_prompts = getattr(self.asr_model._cfg, 'model_defaults', {}).get('num_prompts', 128) - - prompt_tensor = torch.zeros( - [feat_signal.size(0), hidden_length, num_prompts], dtype=feat_signal.dtype, device=device - ) - - # Set the target language - for i in range(prompt_tensor.size(0)): - prompt_tensor[i, :, prompt_idx] = 1 - - # Call model forward with or without prompt - if prompt_tensor is not None: - encoded, encoded_len = self.asr_model.forward( - processed_signal=feat_signal, - processed_signal_length=feat_signal_len, - prompt=prompt_tensor, - ) - else: - encoded, encoded_len = self.asr_model.forward( - processed_signal=feat_signal, processed_signal_length=feat_signal_len - ) - - # filter out partial hypotheses from older batch subset - if self.stateful_decoding and self.previous_hypotheses is not None: - new_prev_hypothesis = [] - for new_batch_idx, global_index_key in enumerate(new_batch_keys): - old_pos = self.batch_index_map[global_index_key] - new_prev_hypothesis.append(self.previous_hypotheses[old_pos]) - self.previous_hypotheses = new_prev_hypothesis - - best_hyp = self.asr_model.decoding.rnnt_decoder_predictions_tensor( - encoded, encoded_len, return_hypotheses=True, partial_hypotheses=self.previous_hypotheses - ) - - if self.stateful_decoding: - # preserve last state from hypothesis of new batch indices - self.previous_hypotheses = best_hyp - - for idx, hyp in enumerate(best_hyp): - global_index_key = new_batch_keys[idx] # get index of this sample in the global batch - - has_signal_ended = self.frame_bufferer.signal_end[global_index_key] - if not has_signal_ended: - self.all_alignments[global_index_key].append(hyp.alignments) - - preds = [hyp.y_sequence for hyp in best_hyp] - for idx, pred in enumerate(preds): - global_index_key = new_batch_keys[idx] # get index of this sample in the global batch - - has_signal_ended = self.frame_bufferer.signal_end[global_index_key] - if not has_signal_ended: - self.all_preds[global_index_key].append(pred.cpu().numpy()) - - timestamps = [hyp.timestamp for hyp in best_hyp] - for idx, timestamp in enumerate(timestamps): - global_index_key = new_batch_keys[idx] # get index of this sample in the global batch - - has_signal_ended = self.frame_bufferer.signal_end[global_index_key] - if not has_signal_ended: - self.all_timestamps[global_index_key].append(timestamp) - - if self.stateful_decoding: - # State resetting is being done on sub-batch only, global index information is not being updated - reset_states = self.asr_model.decoder.initialize_state(encoded) - - for idx, pred in enumerate(preds): - if len(pred) > 0 and pred[-1] == self.eos_id: - # reset states : - self.previous_hypotheses[idx].y_sequence = self.previous_hypotheses[idx].y_sequence[:-1] - self.previous_hypotheses[idx].dec_state = self.asr_model.decoder.batch_select_state( - reset_states, idx - ) - - # Position map update - if len(new_batch_keys) != len(self.batch_index_map): - for new_batch_idx, global_index_key in enumerate(new_batch_keys): - self.batch_index_map[global_index_key] = new_batch_idx # let index point from global pos -> local pos - - del encoded, encoded_len - del best_hyp, pred - - def transcribe( - self, - tokens_per_chunk: int, - delay: int, - ): - """ - Performs "middle token" alignment prediction using the buffered audio chunk. - """ - self.infer_logits() - - self.unmerged = [[] for _ in range(self.batch_size)] - for idx, alignments in enumerate(self.all_alignments): - - signal_end_idx = self.frame_bufferer.signal_end_index[idx] - if signal_end_idx is None: - raise ValueError("Signal did not end") - - for a_idx, alignment in enumerate(alignments): - if delay == len(alignment): # chunk size = buffer size - offset = 0 - else: # all other cases - offset = 1 - - alignment = alignment[ - len(alignment) - offset - delay : len(alignment) - offset - delay + tokens_per_chunk - ] - - ids, toks = self._alignment_decoder(alignment, self.asr_model.tokenizer, self.blank_id) - - if len(ids) > 0 and a_idx < signal_end_idx: - self.unmerged[idx] = inplace_buffer_merge( - self.unmerged[idx], - ids, - delay, - model=self.asr_model, - ) - - output = [] - for idx in range(self.batch_size): - output.append(self.greedy_merge(self.unmerged[idx])) - return output - - def _alignment_decoder(self, alignments, tokenizer, blank_id): - s = [] - ids = [] - - for t in range(len(alignments)): - for u in range(len(alignments[t])): - _, token_id = alignments[t][u] # (logprob, token_id) - token_id = int(token_id) - if token_id != blank_id: - token = tokenizer.ids_to_tokens([token_id])[0] - s.append(token) - ids.append(token_id) - - else: - # blank token - pass - - return ids, s - - def greedy_merge(self, preds): - decoded_prediction = [p for p in preds] - hypothesis = self.asr_model.tokenizer.ids_to_text(decoded_prediction) - return hypothesis - - -class BatchedFrameASRTDT(BatchedFrameASRRNNT): - """ - Batched implementation of FrameBatchASR for TDT models, where the batch dimension is independent audio samples. - It's mostly similar to BatchedFrameASRRNNT with special handling of boundary cases due to the frame-skipping - resulted by TDT models. - """ - - def __init__( - self, - asr_model, - frame_len=1.6, - total_buffer=4.0, - batch_size=32, - max_steps_per_timestep: int = 5, - stateful_decoding: bool = False, - tdt_search_boundary: int = 4, - ): - ''' - Args: - asr_model: An RNNT model. - frame_len: frame's duration, seconds. - total_buffer: duration of total audio chunk size, in seconds. - batch_size: Number of independent audio samples to process at each step. - max_steps_per_timestep: Maximum number of tokens (u) to process per acoustic timestep (t). - stateful_decoding: Boolean whether to enable stateful decoding for preservation of state across buffers. - tdt_search_boundary: The max number of frames that we search between chunks to match the token at boundary. - ''' - super().__init__(asr_model, frame_len=frame_len, total_buffer=total_buffer, batch_size=batch_size) - self.tdt_search_boundary = tdt_search_boundary - - def transcribe( - self, - tokens_per_chunk: int, - delay: int, - ): - """ - Performs "middle token" alignment prediction using the buffered audio chunk. - """ - self.infer_logits() - - self.unmerged = [[] for _ in range(self.batch_size)] - for idx, alignments in enumerate(self.all_alignments): - - signal_end_idx = self.frame_bufferer.signal_end_index[idx] - if signal_end_idx is None: - raise ValueError("Signal did not end") - - for a_idx, alignment in enumerate(alignments): - if delay == len(alignment): # chunk size = buffer size - offset = 0 - else: # all other cases - offset = 1 - - longer_alignment = alignment[ - len(alignment) - - offset - - delay - - self.tdt_search_boundary : len(alignment) - - offset - - delay - + tokens_per_chunk - ] - - alignment = alignment[ - len(alignment) - offset - delay : len(alignment) - offset - delay + tokens_per_chunk - ] - - longer_ids, longer_toks = self._alignment_decoder( - longer_alignment, self.asr_model.tokenizer, self.blank_id - ) - ids, _ = self._alignment_decoder(alignment, self.asr_model.tokenizer, self.blank_id) - - if len(longer_ids) > 0 and a_idx < signal_end_idx: - if a_idx == 0 or len(self.unmerged[idx]) == 0: - self.unmerged[idx] = inplace_buffer_merge( - self.unmerged[idx], - ids, - delay, - model=self.asr_model, - ) - elif len(self.unmerged[idx]) > 0 and len(longer_toks) > 1: - id_to_match = self.unmerged[idx][-1] - start = min(len(longer_ids) - len(ids), len(longer_ids) - 1) - end = -1 - for i in range(start, end, -1): - if longer_ids[i] == id_to_match: - ids = longer_ids[i + 1 :] - break - - self.unmerged[idx] = inplace_buffer_merge( - self.unmerged[idx], - ids, - delay, - model=self.asr_model, - ) - - output = [] - for idx in range(self.batch_size): - output.append(self.greedy_merge(self.unmerged[idx])) - return output - - -class LongestCommonSubsequenceBatchedFrameASRRNNT(BatchedFrameASRRNNT): - """ - Implements a token alignment algorithm for text alignment instead of middle token alignment. - - For more detail, read the docstring of longest_common_subsequence_merge(). - """ - - def __init__( - self, - asr_model, - frame_len=1.6, - total_buffer=4.0, - batch_size=4, - max_steps_per_timestep: int = 5, - stateful_decoding: bool = False, - alignment_basepath: str = None, - ): - ''' - Args: - asr_model: An RNNT model. - frame_len: frame's duration, seconds. - total_buffer: duration of total audio chunk size, in seconds. - batch_size: Number of independent audio samples to process at each step. - max_steps_per_timestep: Maximum number of tokens (u) to process per acoustic timestep (t). - stateful_decoding: Boolean whether to enable stateful decoding for preservation of state across buffers. - alignment_basepath: Str path to a directory where alignments from LCS will be preserved for later analysis. - ''' - super().__init__(asr_model, frame_len, total_buffer, batch_size, max_steps_per_timestep, stateful_decoding) - self.sample_offset = 0 - self.lcs_delay = -1 - - self.alignment_basepath = alignment_basepath - - def transcribe( - self, - tokens_per_chunk: int, - delay: int, - ): - if self.lcs_delay < 0: - raise ValueError( - "Please set LCS Delay valus as `(buffer_duration - chunk_duration) / model_stride_in_secs`" - ) - - self.infer_logits() - - self.unmerged = [[] for _ in range(self.batch_size)] - for idx, alignments in enumerate(self.all_alignments): - - signal_end_idx = self.frame_bufferer.signal_end_index[idx] - if signal_end_idx is None: - raise ValueError("Signal did not end") - - for a_idx, alignment in enumerate(alignments): - - # Middle token first chunk - if a_idx == 0: - # len(alignment) - 1 - delay + tokens_per_chunk - alignment = alignment[len(alignment) - 1 - delay :] - ids, toks = self._alignment_decoder(alignment, self.asr_model.tokenizer, self.blank_id) - - if len(ids) > 0: - self.unmerged[idx] = inplace_buffer_merge( - self.unmerged[idx], - ids, - delay, - model=self.asr_model, - ) - - else: - ids, toks = self._alignment_decoder(alignment, self.asr_model.tokenizer, self.blank_id) - if len(ids) > 0 and a_idx < signal_end_idx: - - if self.alignment_basepath is not None: - basepath = self.alignment_basepath - sample_offset = self.sample_offset + idx - alignment_offset = a_idx - path = os.path.join(basepath, str(sample_offset)) - - os.makedirs(path, exist_ok=True) - path = os.path.join(path, "alignment_" + str(alignment_offset) + '.pt') - - filepath = path - else: - filepath = None - - self.unmerged[idx] = lcs_alignment_merge_buffer( - self.unmerged[idx], - ids, - self.lcs_delay, - model=self.asr_model, - max_steps_per_timestep=self.max_steps_per_timestep, - filepath=filepath, - ) - - output = [] - for idx in range(self.batch_size): - output.append(self.greedy_merge(self.unmerged[idx])) - return output - - -class CacheAwareStreamingAudioBuffer: - """ - A buffer to be used for cache-aware streaming. It can load a single or multiple audio - files/processed signals, split them in chunks and return one on one. It can be used to - simulate streaming audio or audios. - """ - - def __init__(self, model, online_normalization=None, pad_and_drop_preencoded=False): - ''' - Args: - model: An ASR model. - online_normalization (bool): whether to perform online normalization per chunk or - normalize the whole audio before chunking - pad_and_drop_preencoded (bool): if true pad first audio chunk and always drop preencoded - ''' - self.model = model - self.buffer = None - self.buffer_idx = 0 - self.streams_length = None - self.step = 0 - self.pad_and_drop_preencoded = pad_and_drop_preencoded - - self.online_normalization = online_normalization - if not isinstance(model.encoder, StreamingEncoder): - raise ValueError( - "The model's encoder is not inherited from StreamingEncoder, and likely not to support streaming!" - ) - if model.encoder.streaming_cfg is None: - model.encoder.setup_streaming_params() - self.streaming_cfg = model.encoder.streaming_cfg - - self.input_features = model.encoder._feat_in - - self.preprocessor = self.extract_preprocessor() - - if hasattr(model.encoder, "pre_encode") and hasattr(model.encoder.pre_encode, "get_sampling_frames"): - self.sampling_frames = model.encoder.pre_encode.get_sampling_frames() - else: - self.sampling_frames = None - - def __iter__(self): - while True: - if self.buffer_idx >= self.buffer.size(-1): - return - - if self.buffer_idx == 0 and isinstance(self.streaming_cfg.chunk_size, list): - if self.pad_and_drop_preencoded: - chunk_size = self.streaming_cfg.chunk_size[1] - else: - chunk_size = self.streaming_cfg.chunk_size[0] - else: - chunk_size = ( - self.streaming_cfg.chunk_size[1] - if isinstance(self.streaming_cfg.chunk_size, list) - else self.streaming_cfg.chunk_size - ) - - if self.buffer_idx == 0 and isinstance(self.streaming_cfg.shift_size, list): - if self.pad_and_drop_preencoded: - shift_size = self.streaming_cfg.shift_size[1] - else: - shift_size = self.streaming_cfg.shift_size[0] - else: - shift_size = ( - self.streaming_cfg.shift_size[1] - if isinstance(self.streaming_cfg.shift_size, list) - else self.streaming_cfg.shift_size - ) - - audio_chunk = self.buffer[:, :, self.buffer_idx : self.buffer_idx + chunk_size] - - if self.sampling_frames is not None: - # checking to make sure the audio chunk has enough frames to produce at least one output after - # downsampling - if self.buffer_idx == 0 and isinstance(self.sampling_frames, list): - cur_sampling_frames = self.sampling_frames[0] - else: - cur_sampling_frames = ( - self.sampling_frames[1] if isinstance(self.sampling_frames, list) else self.sampling_frames - ) - if audio_chunk.size(-1) < cur_sampling_frames: - return - - # Adding the cache needed for the pre-encoder part of the model to the chunk - # if there is not enough frames to be used as the pre-encoding cache, zeros would be added - zeros_pads = None - if self.buffer_idx == 0 and isinstance(self.streaming_cfg.pre_encode_cache_size, list): - if self.pad_and_drop_preencoded: - cache_pre_encode_num_frames = self.streaming_cfg.pre_encode_cache_size[1] - else: - cache_pre_encode_num_frames = self.streaming_cfg.pre_encode_cache_size[0] - cache_pre_encode = torch.zeros( - (audio_chunk.size(0), self.input_features, cache_pre_encode_num_frames), - device=audio_chunk.device, - dtype=audio_chunk.dtype, - ) - else: - if isinstance(self.streaming_cfg.pre_encode_cache_size, list): - pre_encode_cache_size = self.streaming_cfg.pre_encode_cache_size[1] - else: - pre_encode_cache_size = self.streaming_cfg.pre_encode_cache_size - - start_pre_encode_cache = self.buffer_idx - pre_encode_cache_size - if start_pre_encode_cache < 0: - start_pre_encode_cache = 0 - cache_pre_encode = self.buffer[:, :, start_pre_encode_cache : self.buffer_idx] - if cache_pre_encode.size(-1) < pre_encode_cache_size: - zeros_pads = torch.zeros( - ( - audio_chunk.size(0), - audio_chunk.size(-2), - pre_encode_cache_size - cache_pre_encode.size(-1), - ), - device=audio_chunk.device, - dtype=audio_chunk.dtype, - ) - - added_len = cache_pre_encode.size(-1) - audio_chunk = torch.cat((cache_pre_encode, audio_chunk), dim=-1) - - if self.online_normalization: - audio_chunk, x_mean, x_std = normalize_batch( - x=audio_chunk, - seq_len=torch.tensor([audio_chunk.size(-1)] * audio_chunk.size(0)), - normalize_type=self.model_normalize_type, - ) - - if zeros_pads is not None: - # TODO: check here when zero_pads is not None and added_len is already non-zero - audio_chunk = torch.cat((zeros_pads, audio_chunk), dim=-1) - added_len += zeros_pads.size(-1) - - max_chunk_lengths = self.streams_length - self.buffer_idx - max_chunk_lengths = max_chunk_lengths + added_len - chunk_lengths = torch.clamp(max_chunk_lengths, min=0, max=audio_chunk.size(-1)) - - self.buffer_idx += shift_size - self.step += 1 - yield audio_chunk, chunk_lengths - - def is_buffer_empty(self): - if self.buffer_idx >= self.buffer.size(-1): - return True - else: - return False - - def __len__(self): - return len(self.buffer) - - def reset_buffer(self): - self.buffer = None - self.buffer_idx = 0 - self.streams_length = None - self.step = 0 - - def reset_buffer_pointer(self): - self.buffer_idx = 0 - self.step = 0 - - def extract_preprocessor(self): - cfg = copy.deepcopy(self.model._cfg) - self.model_normalize_type = cfg.preprocessor.normalize - OmegaConf.set_struct(cfg.preprocessor, False) - cfg.preprocessor.dither = 0.0 - cfg.preprocessor.pad_to = 0 - if self.online_normalization: - cfg.preprocessor.normalize = "None" - - preprocessor = self.model.from_config_dict(cfg.preprocessor) - return preprocessor.to(self.get_model_device()) - - def append_audio_file(self, audio_filepath, stream_id=-1): - audio = get_samples(audio_filepath) - processed_signal, processed_signal_length, stream_id = self.append_audio(audio, stream_id) - return processed_signal, processed_signal_length, stream_id - - def append_audio(self, audio, stream_id=-1): - processed_signal, processed_signal_length = self.preprocess_audio(audio) - processed_signal, processed_signal_length, stream_id = self.append_processed_signal( - processed_signal, stream_id - ) - return processed_signal, processed_signal_length, stream_id - - def append_processed_signal(self, processed_signal, stream_id=-1): - processed_signal_length = torch.tensor(processed_signal.size(-1), device=processed_signal.device) - if stream_id >= 0 and (self.streams_length is not None and stream_id >= len(self.streams_length)): - raise ValueError("Not valid stream_id!") - if self.buffer is None: - if stream_id >= 0: - raise ValueError("stream_id can not be specified when there is no stream.") - self.buffer = processed_signal - self.streams_length = torch.tensor([processed_signal_length], device=processed_signal.device) - else: - if self.buffer.size(1) != processed_signal.size(1): - raise ValueError("Buffer and the processed signal have different dimensions!") - if stream_id < 0: - self.buffer = torch.nn.functional.pad(self.buffer, pad=(0, 0, 0, 0, 0, 1)) - self.streams_length = torch.cat( - (self.streams_length, torch.tensor([0], device=self.streams_length.device)), dim=-1 - ) - stream_id = len(self.streams_length) - 1 - needed_len = self.streams_length[stream_id] + processed_signal_length - if needed_len > self.buffer.size(-1): - self.buffer = torch.nn.functional.pad(self.buffer, pad=(0, needed_len - self.buffer.size(-1))) - - self.buffer[ - stream_id, :, self.streams_length[stream_id] : self.streams_length[stream_id] + processed_signal_length - ] = processed_signal - self.streams_length[stream_id] = self.streams_length[stream_id] + processed_signal.size(-1) - - if self.online_normalization: - processed_signal, x_mean, x_std = normalize_batch( - x=processed_signal, - seq_len=torch.tensor([processed_signal_length]), - normalize_type=self.model_normalize_type, - ) - return processed_signal, processed_signal_length, stream_id - - def get_model_device(self): - return self.model.device - - def preprocess_audio(self, audio, device=None): - if device is None: - device = self.get_model_device() - audio_signal = torch.from_numpy(audio).unsqueeze_(0).to(device) - audio_signal_len = torch.Tensor([audio.shape[0]]).to(device) - processed_signal, processed_signal_length = self.preprocessor( - input_signal=audio_signal, length=audio_signal_len - ) - return processed_signal, processed_signal_length - - def get_all_audios(self): - processed_signal = self.buffer - if self.online_normalization: - processed_signal, x_mean, x_std = normalize_batch( - x=processed_signal, - seq_len=torch.tensor(self.streams_length), - normalize_type=self.model_normalize_type, - ) - return processed_signal, self.streams_length - - -class FrameBatchMultiTaskAED(FrameBatchASR): - def __init__(self, asr_model, frame_len=4, total_buffer=4, batch_size=4): - - self.timestamps_asr_model = asr_model.timestamps_asr_model - if self.timestamps_asr_model is not None: - self.timestamps_frame_asr = FrameBatchASR( - asr_model=self.timestamps_asr_model, - frame_len=frame_len, - total_buffer=total_buffer, - batch_size=batch_size, - ) - - super().__init__(asr_model, frame_len, total_buffer, batch_size, pad_to_buffer_len=False) - self.window_stride = asr_model._cfg.preprocessor.window_stride - self.subsampling_factor = asr_model._cfg.encoder.subsampling_factor - self.chunk_offsets = [ - 0, - ] # chunk offsets in terms of num frames before subsampling - - def reset(self): - super().reset() - self.chunk_offsets = [ - 0, - ] - - if self.timestamps_asr_model is not None: - self.timestamps_frame_asr.reset() - - @torch.no_grad() - def infer_logits(self, keep_logits=False, timestamps=False): - frame_buffers = self.frame_bufferer.get_buffers_batch() - - while len(frame_buffers) > 0: - self.frame_buffers += frame_buffers[:] - self.data_layer.set_signal(frame_buffers[:]) - self._get_batch_preds(keep_logits=keep_logits, timestamps=timestamps) - frame_buffers = self.frame_bufferer.get_buffers_batch() - - def get_input_tokens(self, sample: dict): - if self.asr_model.prompt_format == "canary": - expected_slots = {"source_lang", "target_lang", "taskname", "pnc"} - default_slot_values = {} - elif self.asr_model.prompt_format == "canary2": - expected_slots = {"source_lang", "target_lang"} - default_slot_values = { - "decodercontext": "", - "emotion": "<|emo:undefined|>", - "itn": "<|noitn|>", - "timestamp": "<|notimestamp|>", - "diarize": "<|nodiarize|>", - "pnc": "<|pnc|>", # consistent with canary1 - } - else: - raise ValueError(f"Unknown prompt format: {self.asr_model.prompt_format}") - - missing_keys = [k for k in expected_slots if k not in sample] - if missing_keys: - raise RuntimeError( - f"We found sample that is missing the following keys: {missing_keys}" - f"Please ensure that every utterance in the input manifests contains these keys. Sample: {sample}" - ) - - # fill optional slots - for k, v in default_slot_values.items(): - sample[k] = sample.get(k, v) - if k == 'timestamp' and self.timestamps_asr_model is not None: - sample[k] = "<|notimestamp|>" - - tokens = self.asr_model.prompt.encode_dialog( - turns=[ - { - "role": "user", - "slots": { - **sample, - self.asr_model.prompt.PROMPT_LANGUAGE_SLOT: "spl_tokens", - }, - } - ] - )["context_ids"] - - return torch.tensor(tokens, dtype=torch.long, device=self.asr_model.device).unsqueeze(0) # [1, T] - - def read_audio_file(self, audio_filepath: str, delay, model_stride_in_secs, meta_data): - timestamps = meta_data.get('timestamp', False) == "yes" - self.input_tokens = self.get_input_tokens(meta_data) - samples = get_samples(audio_filepath) - padded_samples = np.pad(samples, (0, int(delay * model_stride_in_secs * self.asr_model._cfg.sample_rate))) - - frame_reader = AudioFeatureIterator( - padded_samples, self.frame_len, self.raw_preprocessor, self.asr_model.device, pad_to_frame_len=False - ) - self.set_frame_reader(frame_reader) - if timestamps and self.timestamps_asr_model is not None: - ts_model_feature_stride = self.timestamps_asr_model._cfg.preprocessor['window_stride'] - ts_model_stride_in_secs = ts_model_feature_stride * self.timestamps_asr_model.encoder.subsampling_factor - - ts_model_padded_samples = np.pad( - samples, (0, int(delay * ts_model_stride_in_secs * self.timestamps_asr_model._cfg.sample_rate)) - ) - - ts_model_frame_reader = AudioFeatureIterator( - ts_model_padded_samples, - self.frame_len, - self.timestamps_frame_asr.raw_preprocessor, - self.timestamps_frame_asr.asr_model.device, - ) - self.timestamps_frame_asr.set_frame_reader(ts_model_frame_reader) - - @torch.no_grad() - def _get_batch_preds(self, keep_logits=False, timestamps=False): - device = self.asr_model.device - for batch in iter(self.data_loader): - feat_signal, feat_signal_len = batch - # keep track of chunk offsets - self.chunk_offsets.extend(feat_signal_len.tolist()) - feat_signal, feat_signal_len = feat_signal.to(device), feat_signal_len.to(device) - tokens = self.input_tokens.to(device).repeat(feat_signal.size(0), 1) - tokens_len = torch.tensor([tokens.size(1)] * tokens.size(0), device=device).long() - - batch_input = PromptedAudioToTextMiniBatch( - audio=feat_signal, - audio_lens=feat_signal_len, - transcript=None, - transcript_lens=None, - prompt=tokens, - prompt_lens=tokens_len, - prompted_transcript=None, - prompted_transcript_lens=None, - ) - predictions = self.asr_model.predict_step(batch_input, has_processed_signal=True, timestamps=timestamps) - - self.all_preds.extend(predictions) - del predictions - - def transcribe( - self, - tokens_per_chunk: Optional[int] = None, - delay: Optional[int] = None, - keep_logits: bool = False, - timestamps: bool = False, - ): - """ - unsued params are for keeping the same signature as the parent class - """ - self.infer_logits(keep_logits=keep_logits, timestamps=timestamps) - if timestamps and self.timestamps_asr_model is not None: - self.timestamps_frame_asr.infer_logits(keep_logits=True) - timestamps_model_hypotheses = [ - rnnt_utils.Hypothesis(y_sequence=logits, score=0.0) for logits in self.timestamps_frame_asr.all_logits - ] - self.all_preds = get_forced_aligned_timestamps_with_external_model( - audio=timestamps_model_hypotheses, - external_ctc_model=self.timestamps_asr_model, - main_model_predictions=self.all_preds, - batch_size=self.batch_size, - timestamp_type=['word', 'segment'], - viterbi_device=self.timestamps_frame_asr.asr_model.device, - has_hypotheses=True, - ) - - # join hypotheses - hypothesis = self._join_hypotheses(self.all_preds, timestamps=timestamps) - - if not keep_logits: - return hypothesis - - print("keep_logits=True is not supported for MultiTaskAEDFrameBatchInfer. Returning empty logits.") - return hypothesis, [] - - def _join_hypotheses(self, hypotheses, timestamps=False): - if len(hypotheses) == 1: - return hypotheses[0] - - # initialize a new hypothesis - merged_hypthesis = rnnt_utils.Hypothesis( - score=0.0, - y_sequence=torch.tensor([]), - ) - - # join - merged_hypthesis = self._join_text(merged_hypthesis, hypotheses) - - merged_hypthesis = self._join_y_sequence(merged_hypthesis, hypotheses) - - if timestamps: - merged_hypthesis.timestamp = { - 'char': [], - 'word': [], - 'segment': [], - } - merged_hypthesis = self._join_timestamp(merged_hypthesis, hypotheses) - - return merged_hypthesis - - def _join_text(self, merged_hypothesis, hypotheses): - merged_hypothesis.text = " ".join([h.text for h in hypotheses]) - return merged_hypothesis - - def _join_y_sequence(self, merged_hypothesis, hypotheses): - merged_hypothesis.y_sequence = torch.cat([h.y_sequence for h in hypotheses]) - return merged_hypothesis - - def _join_timestamp(self, merged_hypothesis, hypotheses): - # word level - cumulative_offset = 0 - for i, h in enumerate(hypotheses): - cumulative_offset += self.chunk_offsets[i] # self.chunk_offsets starts with 0, - - # update frame numbers - updated_timestamps = [ - { - **word, - 'start_offset': word['start_offset'] - + cumulative_offset - // self.subsampling_factor, # dividing here to avoid error accumulation over long audios - 'end_offset': word['end_offset'] + cumulative_offset // self.subsampling_factor, - } - for word in h.timestamp['word'] - ] - - # update times - updated_timestamps = [ - { - **word, - 'start': word['start_offset'] * self.window_stride * self.subsampling_factor, - 'end': word['end_offset'] * self.window_stride * self.subsampling_factor, - } - for word in updated_timestamps - ] - - merged_hypothesis.timestamp['word'].extend(updated_timestamps) - - # segment level - cumulative_offset = 0 - for i, h in enumerate(hypotheses): - cumulative_offset += self.chunk_offsets[i] - - # update frame numbers - updated_timestamps = [ - { - **segment, - 'start_offset': segment['start_offset'] + cumulative_offset // self.subsampling_factor, - 'end_offset': segment['end_offset'] + cumulative_offset // self.subsampling_factor, - } - for segment in h.timestamp['segment'] - ] - - # update times - updated_timestamps = [ - { - **segment, - 'start': segment['start_offset'] * self.window_stride * self.subsampling_factor, - 'end': segment['end_offset'] * self.window_stride * self.subsampling_factor, - } - for segment in updated_timestamps - ] - - merged_hypothesis.timestamp['segment'].extend(updated_timestamps) - - return merged_hypothesis - - -class FrameBatchChunkedRNNT(FrameBatchASR): - def __init__(self, asr_model, frame_len=4, total_buffer=4, batch_size=4): - super().__init__(asr_model, frame_len, total_buffer, batch_size, pad_to_buffer_len=False) - - def read_audio_file(self, audio_filepath: str, delay, model_stride_in_secs): - samples = get_samples(audio_filepath) - samples = np.pad(samples, (0, int(delay * model_stride_in_secs * self.asr_model._cfg.sample_rate))) - frame_reader = AudioFeatureIterator( - samples, self.frame_len, self.raw_preprocessor, self.asr_model.device, pad_to_frame_len=False - ) - self.set_frame_reader(frame_reader) - - @torch.no_grad() - def _get_batch_preds(self, keep_logits=False): - device = self.asr_model.device - for batch in iter(self.data_loader): - feat_signal, feat_signal_len = batch - feat_signal, feat_signal_len = feat_signal.to(device), feat_signal_len.to(device) - - encoded, encoded_len = self.asr_model( - processed_signal=feat_signal, processed_signal_length=feat_signal_len - ) - - best_hyp_text, all_hyp_text = self.asr_model.decoding.rnnt_decoder_predictions_tensor( - encoder_output=encoded, encoded_lengths=encoded_len, return_hypotheses=False - ) - self.all_preds.extend(best_hyp_text) - del best_hyp_text - del all_hyp_text - del encoded - del encoded_len - - def transcribe( - self, tokens_per_chunk: Optional[int] = None, delay: Optional[int] = None, keep_logits: bool = False - ): - """ - unsued params are for keeping the same signature as the parent class - """ - self.infer_logits(keep_logits) - - hypothesis = " ".join(self.all_preds) - if not keep_logits: - return hypothesis - - print("keep_logits=True is not supported for FrameBatchChunkedRNNT. Returning empty logits.") - return hypothesis, [] - - -class FrameBatchChunkedCTC(FrameBatchASR): - def __init__(self, asr_model, frame_len=4, total_buffer=4, batch_size=4): - super().__init__(asr_model, frame_len, total_buffer, batch_size, pad_to_buffer_len=False) - - def read_audio_file(self, audio_filepath: str, delay, model_stride_in_secs): - samples = get_samples(audio_filepath) - samples = np.pad(samples, (0, int(delay * model_stride_in_secs * self.asr_model._cfg.sample_rate))) - frame_reader = AudioFeatureIterator( - samples, self.frame_len, self.raw_preprocessor, self.asr_model.device, pad_to_frame_len=False - ) - self.set_frame_reader(frame_reader) - - @torch.no_grad() - def _get_batch_preds(self, keep_logits=False): - device = self.asr_model.device - for batch in iter(self.data_loader): - feat_signal, feat_signal_len = batch - feat_signal, feat_signal_len = feat_signal.to(device), feat_signal_len.to(device) - - results = self.asr_model(processed_signal=feat_signal, processed_signal_length=feat_signal_len) - if len(results) == 2: # hybrid model - encoded, encoded_len = results - log_probs = self.asr_model.ctc_decoder(encoder_output=encoded) - transcribed_texts, _ = self.asr_model.ctc_decoding.ctc_decoder_predictions_tensor( - decoder_outputs=log_probs, - decoder_lengths=encoded_len, - return_hypotheses=False, - ) - else: - log_probs, encoded_len, predictions = results - transcribed_texts, _ = self.asr_model.decoding.ctc_decoder_predictions_tensor( - decoder_outputs=log_probs, - decoder_lengths=encoded_len, - return_hypotheses=False, - ) - - self.all_preds.extend(transcribed_texts) - del log_probs - del encoded_len - del predictions - - def transcribe( - self, tokens_per_chunk: Optional[int] = None, delay: Optional[int] = None, keep_logits: bool = False - ): - """ - unsued params are for keeping the same signature as the parent class - """ - self.infer_logits(keep_logits) - - hypothesis = " ".join(self.all_preds) - if not keep_logits: - return hypothesis - - print("keep_logits=True is not supported for FrameBatchChunkedCTC. Returning empty logits.") - return hypothesis, [] - - -@dataclass -class ContextSize: - left: int - chunk: int - right: int - - def total(self) -> int: - """Total context size""" - return self.left + self.chunk + self.right - - def subsample(self, factor: int) -> "ContextSize": - """ - Subsample context size by factor - - Args: - factor: subsampling factor - """ - return ContextSize( - left=self.left // factor, - chunk=self.chunk // factor, - right=self.right // factor, - ) - - def add_frames_get_removed_(self, num_frames: int, is_last_chunk: bool, expected_context: "ContextSize") -> int: - """ - Add frames to context size - Args: - num_frames: number of frames to add - is_last_chunk: if last chunk - - Returns: - number of frames removed from the left side - """ - if num_frames > expected_context.chunk + expected_context.right: - raise ValueError( - f"Added chunk length {num_frames} is larger " - f"than expected chunk with right context {expected_context}" - ) - # consider first everything is moved to right/left context, then move to chunk - self.left += self.chunk - self.chunk = 0 - self.right += num_frames - if is_last_chunk: - # move all samples to chunk, empty right part - self.chunk = self.right - self.right = 0 - else: - self.chunk = expected_context.chunk - self.right -= expected_context.chunk - extra_samples = max(self.total() - expected_context.total(), 0) - self.left -= extra_samples - if not is_last_chunk: - assert self.right == expected_context.right - return extra_samples - - def __str__(self): - return f"Left {self.left} - Chunk {self.chunk} - Right {self.right}" - - -@dataclass -class ContextSizeBatch: - """Batched context size""" - - left: torch.Tensor - chunk: torch.Tensor - right: torch.Tensor - - def total(self) -> torch.Tensor: - """Total context size""" - return self.left + self.chunk + self.right - - def subsample(self, factor: int) -> "ContextSizeBatch": - """ - Subsample context size by factor - - Args: - factor: subsampling factor - """ - return ContextSizeBatch( - left=torch.div(self.left, factor, rounding_mode="floor"), - chunk=torch.div(self.chunk, factor, rounding_mode="floor"), - right=torch.div(self.right, factor, rounding_mode="floor"), - ) - - def add_frames_( - self, num_frames_batch: torch.Tensor, is_last_chunk_batch: torch.Tensor, expected_context: "ContextSize" - ): - """ - Add frames to context size - Args: - num_frames_batch: number of frames to add - is_last_chunk_batch: if last chunk - - Returns: - number of frames removed from the left side - """ - self.left += self.chunk - self.chunk.fill_(0) - self.right += num_frames_batch - - self.chunk = torch.where(is_last_chunk_batch, self.right, expected_context.chunk) - self.right = torch.where(is_last_chunk_batch, 0, self.right - expected_context.chunk) - - # fix left context - self.left = torch.where(self.chunk > 0, self.left, 0) - - extra_samples = torch.maximum(self.total() - expected_context.total(), torch.zeros_like(self.left)) - self.left -= extra_samples - self.left = torch.where(self.left < 0, torch.zeros_like(self.left), self.left) - - -class StreamingBatchedAudioBuffer: - """Batched audio buffer with strict context management for streaming inference without left padding.""" - - def __init__(self, batch_size: int, context_samples: ContextSize, dtype: torch.dtype, device: torch.device | str): - """ - Init batched audio buffer for streaming inference - Args: - batch_size: batch size - context_samples: context size - dtype: buffer dtype - device: device for buffer - """ - self.batch_size = batch_size - self.expected_context = context_samples - self.samples = torch.zeros([batch_size, 0], dtype=dtype, device=device) - self.context_size = ContextSize(left=0, chunk=0, right=0) - self.context_size_batch = ContextSizeBatch( - left=torch.zeros([batch_size], dtype=torch.long, device=device), - chunk=torch.zeros([batch_size], dtype=torch.long, device=device), - right=torch.zeros([batch_size], dtype=torch.long, device=device), - ) - - def add_audio_batch_( - self, - audio_batch: torch.Tensor, - audio_lengths: torch.Tensor, - is_last_chunk: bool, - is_last_chunk_batch: torch.Tensor, - ): - """ - Add audio batch to buffer - - Args: - audio_batch: chunk with audio - audio_lengths: length of audio - is_last_chunk: if last chunk - is_last_chunk_batch: if last chunk for each audio utterance - """ - added_chunk_length = audio_batch.shape[1] - - # concat new chunk with buffer, remove extra samples - self.samples = torch.cat((self.samples, audio_batch), dim=1) - extra_samples_in_buffer = self.context_size.add_frames_get_removed_( - added_chunk_length, is_last_chunk=is_last_chunk, expected_context=self.expected_context - ) - self.context_size_batch.add_frames_( - num_frames_batch=audio_lengths, - is_last_chunk_batch=is_last_chunk_batch, - expected_context=self.expected_context, - ) - # leave only full_ctx_audio_samples in buffer - if extra_samples_in_buffer > 0: - self.samples = self.samples[:, extra_samples_in_buffer:] - - -def load_audio(file_path: str | Path, sample_rate: int = 16000) -> tuple[torch.Tensor, int]: - """Load audio from file""" - audio, sr = librosa.load(file_path, sr=sample_rate) - return torch.tensor(audio, dtype=torch.float32), sr - - -class AudioItem(NamedTuple): - audio_signal: torch.Tensor - biasing_request: BiasingRequestItemConfig | None - - -class AudioBatch(NamedTuple): - audio_signals: torch.Tensor - audio_signal_lengths: torch.Tensor - biasing_requests: list[BiasingRequestItemConfig | None] | None - - @staticmethod - def collate_fn( - audio_batch: list[AudioItem], - ) -> "AudioBatch": - """ - Collate audio signals to batch - """ - audio_signals = pad_sequence( - [audio_item.audio_signal for audio_item in audio_batch], batch_first=True, padding_value=0.0 - ) - audio_signal_lengths = torch.tensor([audio_item.audio_signal.shape[0] for audio_item in audio_batch]).long() - biasing_requests = [audio_item.biasing_request for audio_item in audio_batch] - - return AudioBatch( - audio_signals=audio_signals, - audio_signal_lengths=audio_signal_lengths, - biasing_requests=None if all([request is None for request in biasing_requests]) else biasing_requests, - ) - - -class SimpleAudioDataset(Dataset): - """Dataset constructed from audio filenames. Each item - audio""" - - def __init__( - self, - audio_filenames: list[str | Path], - sample_rate: int = 16000, - biasing_requests: list[BiasingRequestItemConfig | None] | None = None, - ): - super().__init__() - self.audio_filenames = audio_filenames - self.sample_rate = sample_rate - self.biasing_requests = ( - biasing_requests if biasing_requests is not None else [None for _ in range(len(self.audio_filenames))] - ) - if len(self.biasing_requests) != len(self.audio_filenames): - raise ValueError( - f"Length of biasing requests {len(self.biasing_requests)} " - "expected to be equal to the length of audio filenames {len(self.audio_filenames)}" - ) - - def __getitem__(self, item: int) -> AudioItem: - audio, _ = load_audio(self.audio_filenames[item], sample_rate=self.sample_rate) - return AudioItem(audio_signal=audio, biasing_request=self.biasing_requests[item]) - - def __len__(self): - return len(self.audio_filenames) diff --git a/nemo/collections/asr/parts/utils/timestamp_utils.py b/nemo/collections/asr/parts/utils/timestamp_utils.py deleted file mode 100644 index e4ce4eef8baaae6432dc330a8cd5193ead47b880..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/timestamp_utils.py +++ /dev/null @@ -1,670 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import re -from typing import Callable, Dict, List, Optional, Set, Union - -import numpy as np -import torch -from torch.utils.data import DataLoader - -from nemo.collections.asr.parts.utils.aligner_utils import ( - BLANK_TOKEN, - Segment, - Word, - add_t_start_end_to_utt_obj, - get_batch_variables, - viterbi_decoding, -) -from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis -from nemo.utils import logging, logging_mode - - -def flatten_char_offsets(char_offsets: List[Dict[str, Union[int, float]]]) -> List[Dict[str, Union[int, float]]]: - """ - Flatten the char offsets to contain only one char and one token per offset. - This is needed for RNNT decoding, as they return a list of strings for offset['char']. - """ - if not char_offsets: - return char_offsets - - flattened_char_offsets = [] - for char_offset in char_offsets: - if isinstance(char_offset['char'], list): - for char in char_offset['char']: - sub_char_offset = char_offset.copy() - sub_char_offset['char'] = char - flattened_char_offsets.append(sub_char_offset) - else: - flattened_char_offsets.append(char_offset) - return flattened_char_offsets - - -def get_words_offsets( - char_offsets: List[Dict[str, Union[int, float]]], - encoded_char_offsets: List[Dict[str, Union[int, float]]], - decode_tokens_to_str: Callable[[List[int]], str], - word_delimiter_char: str = " ", - tokenizer_type: str = "bpe", - supported_punctuation: Optional[Set] = None, -) -> List[Dict[str, Union[int, float]]]: - """ - Utility method which constructs word time stamps out of sub-word time stamps. - - Args: - char_offsets: A list of dictionaries, each containing "char", "start_offset" and "end_offset", - where "char" is decoded with the tokenizer. - encoded_char_offsets: A list of dictionaries, each containing "char", "start_offset" and "end_offset", - where "char" is the original id/ids from the hypotheses (not decoded with the tokenizer). - This is needed for subword tokenization models. - word_delimiter_char: Character token that represents the word delimiter. By default, " ". - supported_punctuation: Set containing punctuation marks in the vocabulary. - - Returns: - A list of dictionaries containing the word offsets. Each item contains "word", "start_offset" and - "end_offset". - """ - - def define_word_start_condition() -> Callable[[str, str], bool]: - """ - Define the word start condition based on the tokenizer type and word delimiter character. - """ - if tokenizer_type in ["bpe", "wpe"] and word_delimiter_char == " ": - if tokenizer_type == "wpe": - return ( - lambda token, token_text, next_non_delimeter_token: token_text - and not token_text.startswith("##") - or (token_text == word_delimiter_char and next_non_delimeter_token not in supported_punctuation) - ) - return lambda token, token_text, next_non_delimeter_token: token != token_text or ( - token_text == word_delimiter_char and next_non_delimeter_token not in supported_punctuation - ) - elif word_delimiter_char == " ": - return ( - lambda token, token_text, next_non_delimeter_token: token_text == word_delimiter_char - and next_non_delimeter_token not in supported_punctuation - ) - else: - return lambda token, token_text, next_non_delimeter_token: token_text == word_delimiter_char - - char_offsets = flatten_char_offsets(char_offsets) - encoded_char_offsets = flatten_char_offsets(encoded_char_offsets) - - if encoded_char_offsets is None: - encoded_char_offsets = char_offsets - - word_offsets = [] - previous_token_index = 0 - - # Built tokens should be list here as when dealing with wpe tokenizer, - # ids should be decoded together to ensure tokens starting with ## are not split - built_tokens = [] - condition_for_word_start = define_word_start_condition() - - # For every collapsed sub-word token - for i, (char_offset, char_token_offset) in enumerate(zip(char_offsets, encoded_char_offsets)): - - char_text = char_offset['char'] - char_token = char_token_offset['char'] - - curr_punctuation = ( - supported_punctuation and char_text in supported_punctuation and char_text != word_delimiter_char - ) - next_non_delimeter_token = None - next_non_delimeter_token_index = i - while not next_non_delimeter_token and next_non_delimeter_token_index < len(char_offsets) - 1: - next_non_delimeter_token_index += 1 - next_non_delimeter_token = char_offsets[next_non_delimeter_token_index]['char'] - next_non_delimeter_token = ( - next_non_delimeter_token if next_non_delimeter_token != word_delimiter_char else None - ) - # It is a sub-word token, or contains an identifier at the beginning such as _ or ## that was stripped - # after forcing partial text conversion of the token. - # AND it is not a supported punctuation mark, which needs to be added to the built word regardless of its identifier. - - if condition_for_word_start(char_token, char_text, next_non_delimeter_token) and not curr_punctuation: - # If there are any partially or fully built sub-word token ids, construct to text. - # Note: This is "old" subword, that occurs *after* current sub-word has started. - - if built_tokens: - word_offsets.append( - { - "word": decode_tokens_to_str(built_tokens), - "start_offset": char_offsets[previous_token_index]["start_offset"], - "end_offset": char_offsets[i - 1]["end_offset"], - } - ) - - if "start" in char_offset: - word_offsets[-1]["start"] = char_offsets[previous_token_index]["start"] - if "end" in char_offset: - word_offsets[-1]["end"] = char_offsets[i - 1]["end"] - - # Prepare new built_tokens - built_tokens = [] - - if char_text != word_delimiter_char: - built_tokens.append(char_token) - previous_token_index = i - - # If the token is a punctuation mark and there is no built word, then the previous word is complete - # and lacks the punctuation mark. We need to add the punctuation mark to the previous formed word. - elif curr_punctuation and not built_tokens and word_offsets: - last_built_word = word_offsets[-1] - last_built_word['end_offset'] = char_offset['end_offset'] - if last_built_word['word'][-1] == ' ': - last_built_word['word'] = last_built_word['word'][:-1] - last_built_word['word'] += char_text - # If the token is a punctuation mark and there is a built word, - # then we need to add the punctuation mark to the built word and remove preceding space. - elif curr_punctuation and built_tokens: - if built_tokens[-1] in [' ', "_", "▁"]: - built_tokens = built_tokens[:-1] - built_tokens.append(char_token) - else: - # If the token does not contain any sub-word start mark, then the sub-word has not completed yet - # Append to current built word. - # If this token is the first in the built_tokens, we should save its index as the previous token index - # because it will be used to calculate the start offset of the word. - if not built_tokens: - previous_token_index = i - built_tokens.append(char_token) - - # Inject the start offset of the first token to word offsets - # This is because we always skip the delay the injection of the first sub-word due to the loop - # condition and check whether built token is ready or not. - # Therefore without this forced injection, the start_offset appears as off by 1. - if len(word_offsets) == 0: - # alaptev: sometimes word_offsets can be empty - if built_tokens: - word_offsets.append( - { - "word": decode_tokens_to_str(built_tokens), - "start_offset": char_offsets[0]["start_offset"], - "end_offset": char_offsets[-1]["end_offset"], - } - ) - if "start" in char_offsets[0]: - word_offsets[0]["start"] = char_offsets[0]["start"] - if "end" in char_offsets[-1]: - word_offsets[-1]["end"] = char_offsets[-1]["end"] - else: - word_offsets[0]["start_offset"] = char_offsets[0]["start_offset"] - - if "start" in char_offsets[0]: - word_offsets[0]["start"] = char_offsets[0]["start"] - - # If there are any remaining tokens left, inject them all into the final word offset. - # Note: The start offset of this token is the start time of the first token inside build_token. - # Note: The end offset of this token is the end time of the last token inside build_token - if built_tokens: - word_offsets.append( - { - "word": decode_tokens_to_str(built_tokens), - "start_offset": char_offsets[previous_token_index]["start_offset"], - "end_offset": char_offsets[-1]["end_offset"], - } - ) - if "start" in char_offset: - word_offsets[-1]["start"] = char_offsets[previous_token_index]["start"] - if "end" in char_offset: - word_offsets[-1]["end"] = char_offsets[-1]["end"] - - return word_offsets - - -def get_segment_offsets( - word_offsets: List[Dict[str, Union[str, float]]], - segment_delimiter_tokens: List[str], - supported_punctuation: Optional[Set] = None, - segment_gap_threshold: Optional[int] = None, -) -> List[Dict[str, Union[str, float]]]: - """ - Utility method which constructs segment time stamps out of word time stamps. - - Args: - offsets: A list of dictionaries, each containing "word", "start_offset" and "end_offset". - segments_delimiter_tokens: List containing tokens representing the seperator(s) between segments. - supported_punctuation: Set containing punctuation marks in the vocabulary. - segment_gap_threshold: Number of frames between 2 consecutive words necessary to form segments out of plain text. - - Returns: - A list of dictionaries containing the segment offsets. Each item contains "segment", "start_offset" and - "end_offset". - """ - if ( - supported_punctuation - and not set(segment_delimiter_tokens).intersection(supported_punctuation) - and not segment_gap_threshold - ): - logging.warning( - f"Specified segment seperators are not in supported punctuation {supported_punctuation}. " - "If the seperators are not punctuation marks, ignore this warning. " - "Otherwise, specify 'segment_gap_threshold' parameter in decoding config to form segments.", - mode=logging_mode.ONCE, - ) - - segment_offsets = [] - segment_words = [] - previous_word_index = 0 - - # For every offset word - for i, offset in enumerate(word_offsets): - - word = offset['word'] - if segment_gap_threshold and segment_words: - gap_between_words = offset['start_offset'] - word_offsets[i - 1]['end_offset'] - - if gap_between_words >= segment_gap_threshold: - segment_offsets.append( - { - "segment": ' '.join(segment_words), - "start_offset": word_offsets[previous_word_index]["start_offset"], - "end_offset": word_offsets[i - 1]["end_offset"], - } - ) - - if "start" in word_offsets[previous_word_index]: - segment_offsets[-1]["start"] = word_offsets[previous_word_index]["start"] - if "end" in word_offsets[i - 1]: - segment_offsets[-1]["end"] = word_offsets[i - 1]["end"] - - segment_words = [word] - previous_word_index = i - continue - - # check if the word ends with any delimeter token or the word itself is a delimeter - elif word and (word[-1] in segment_delimiter_tokens or word in segment_delimiter_tokens): - segment_words.append(word) - if segment_words: - segment_offsets.append( - { - "segment": ' '.join(segment_words), - "start_offset": word_offsets[previous_word_index]["start_offset"], - "end_offset": offset["end_offset"], - } - ) - - if "start" in word_offsets[previous_word_index]: - segment_offsets[-1]["start"] = word_offsets[previous_word_index]["start"] - if "end" in offset: - segment_offsets[-1]["end"] = offset["end"] - - segment_words = [] - previous_word_index = i + 1 - continue - - segment_words.append(word) - - if segment_words: - start_offset = word_offsets[previous_word_index]["start_offset"] - segment_offsets.append( - { - "segment": ' '.join(segment_words), - "start_offset": start_offset, - "end_offset": word_offsets[-1]["end_offset"], - } - ) - - if "start" in word_offsets[previous_word_index]: - segment_offsets[-1]["start"] = word_offsets[previous_word_index]["start"] - if "end" in word_offsets[-1]: - segment_offsets[-1]["end"] = word_offsets[-1]["end"] - - segment_words.clear() - - return segment_offsets - - -def process_aed_timestamp_outputs(outputs, subsampling_factor: int = 1, window_stride: float = 0.01): - """ - Processes AED timestamp outputs and extracts word-level timestamps. - Args: - outputs (Hypothesis, list of Hypotesis or list of list of Hypotesis): The hypothesis outputs to process. Can be a single Hypothesis object or a list of Hypothesis objects. - subsampling_factor (int, optional): The subsampling factor used in the model. Default is 1. - window_stride (float, optional): The window stride used in the model. Default is 0.01. - Returns: - list of list of Hypotesis: The processed hypothesis outputs with word-level timestamps added. - """ - - def extract_words_with_timestamps(text, subsampling_factor: int = 1, window_stride: float = 0.01): - text = text.strip() # remove leading and trailing whitespaces - training data artifact - - if not re.search(r'<\|\d+\|>.*?<\|\d+\|>', text): - return None, text - - # Find words that directly have start and end timestamps - pattern = r'<\|(\d+)\|>(.*?)<\|(\d+)\|>' - - matches = [] - text_without_timestamps = [] - for match in re.finditer(pattern, text): - start_offset = int(match.group(1)) - content = match.group(2) - end_offset = int(match.group(3)) - start_time = start_offset * window_stride * subsampling_factor - end_time = end_offset * window_stride * subsampling_factor - - # Only include if there's actual content - if content.strip(): - sample = { - 'word': content.strip(), - 'start_offset': start_offset, - 'end_offset': end_offset, - 'start': start_time, - 'end': end_time, - } - matches.append(sample) - text_without_timestamps.append(content.strip()) - - text_without_timestamps = ' '.join(text_without_timestamps) - return matches, text_without_timestamps - - def segments_offset_to_time(segments, window_stride, subsampling_factor): - for segment in segments: - segment['start'] = segment['start_offset'] * window_stride * subsampling_factor - segment['end'] = segment['end_offset'] * window_stride * subsampling_factor - return segments - - def process_hypothesis(hyp, subsampling_factor: int, window_stride: float): - """ - Processes a single Hypothesis object to extract timestamps. - """ - timestamp, text = extract_words_with_timestamps(hyp.text, subsampling_factor, window_stride) - hyp.text = text - if timestamp is not None: - if len(hyp.timestamp) == 0: - hyp.timestamp = {} - - hyp.timestamp.update( - { - 'word': timestamp, - 'segment': [], - 'char': [], # not supported for AED - } - ) - - segments = get_segment_offsets(timestamp, segment_delimiter_tokens=['.', '?', '!']) - hyp.timestamp['segment'] = segments_offset_to_time(segments, window_stride, subsampling_factor) - else: - hyp.timestamp = { - 'word': [], - 'segment': [], - 'char': [], - } - - return hyp - - if outputs is None: - return outputs - - if isinstance(outputs, Hypothesis): - return [process_hypothesis(outputs, subsampling_factor, window_stride)] - elif isinstance(outputs, list) and isinstance(outputs[0], Hypothesis): - # list of Hypothesis - return [process_hypothesis(hyp, subsampling_factor, window_stride) for hyp in outputs] - elif isinstance(outputs, list) and isinstance(outputs[0], list) and isinstance(outputs[0][0], Hypothesis): - # list of list of Hypothesis (for beam decoding) - return [ - [process_hypothesis(hyp, subsampling_factor, window_stride) for hyp in hyps_list] for hyps_list in outputs - ] - else: - raise ValueError( - f"Expected Hypothesis, list of Hypothesis or list of list of Hypothesis object, got {type(outputs)}" - ) - - -def process_timestamp_outputs(outputs, subsampling_factor: int = 1, window_stride: float = 0.01): - """ - Process the timestamps from list of hypothesis to user friendly format. - Converts the start and end duration from frames to seconds. - Args: - outputs: List of Hypothesis objects. - subsampling_factor: int, Subsampling factor used in the model. - window_stride: float, Window stride used in the model. (sometimes referred to as hop length/shift) - Returns: - List of Hypothesis objects with processed timestamps - """ - - if outputs is None: - return outputs - - if isinstance(outputs, Hypothesis): - outputs = [outputs] - - if not isinstance(outputs[0], Hypothesis): - raise ValueError(f"Expected Hypothesis object, got {type(outputs[0])}") - - def process_timestamp(timestamp, subsampling_factor, window_stride): - """ - Process the timestamp for a single hypothesis. - return the start and end duration in seconds. - """ - for idx, val in enumerate(timestamp): - start_offset = val['start_offset'] - end_offset = val['end_offset'] - start = start_offset * window_stride * subsampling_factor - end = end_offset * window_stride * subsampling_factor - val['start'] = start - val['end'] = end - - return timestamp - - for idx, hyp in enumerate(outputs): - if not hasattr(hyp, 'timestamp'): - raise ValueError( - f"Expected Hypothesis object to have 'timestamp' attribute, when compute_timestamps is \ - enabled but got {hyp}" - ) - timestamp = hyp.timestamp - if 'word' in timestamp: - outputs[idx].timestamp['word'] = process_timestamp(timestamp['word'], subsampling_factor, window_stride) - if 'char' in timestamp: - outputs[idx].timestamp['char'] = process_timestamp(timestamp['char'], subsampling_factor, window_stride) - if 'segment' in timestamp: - outputs[idx].timestamp['segment'] = process_timestamp( - timestamp['segment'], subsampling_factor, window_stride - ) - return outputs - - -def get_forced_aligned_timestamps_with_external_model( - audio: Union[str, List[str], np.ndarray, DataLoader], - external_ctc_model, - main_model_predictions: List[Hypothesis], - batch_size: int = 4, - viterbi_device: Optional[torch.device] = None, - segment_separators: Optional[Union[str, List[str]]] = ['.', '?', '!', '...'], - word_separator: Optional[str] = " ", - supported_punctuation: Optional[Union[Set, List[str]]] = {',', '.', '!', '?'}, - timestamp_type: Optional[Union[str, List[str]]] = "all", - has_hypotheses: bool = False, - verbose: bool = True, -) -> List[Hypothesis]: - """ - Extracts the word, segment and char timestamps by aligning the audio with the external ASR model and adds them to the provided Hypothesis objects. - Args: - audio: The audio to align. - external_ctc_model: The external ASR CTC model to use for alignment. - main_model_predictions: The predictions from the main model the pred_texts of which will be used for alignment. - batch_size: The batch size to use for alignment (this is used both for CTC model inference and viterbi decoding). - viterbi_device: The device to use for viterbi decoding. Batch variables got with get_batch_variables() are moved to this device before viterbi decoding. - segment_separators: The segment separators to use for splitting the pred_text into segments. Default is ['.', '?', '!', '...'] - word_separator: The word separator to use for splitting the pred_text into words. Default is " ". - supported_punctuation: The supported punctuation is punctuation marks in the vocabulary of the main model. - This is used for refining the timestamps extracted with the external ASR model. - As sometimes punctuation marks can be assigned to multiple audio frames, which is not correct, so we should neutralize these cases. - Default is {',', '.', '!', '?'}. - timestamp_type: The type of timestamps to return. Default is "all". Can be "segment", "word", "char" or "all", or a list of these. - has_hypotheses: Whether `audio` is a list of Hypothesis objects resulted from the external ASR CTC model inference. - This is used in external alignment generation script, e.g. `examples/asr/asr_chunked_inference/aed/speech_to_text_aed_chunked_infer.py`. - If True, `audio` will be used as a list of Hypothesis objects and the inference to the external ASR CTC model will be skipped. - - Returns: - List of provided Hypothesis objects with processed timestamps - """ - - def process_timestamps(utt_obj, output_timestep_duration, timestamp_type): - if isinstance(timestamp_type, str): - assert timestamp_type in [ - "segment", - "word", - "char", - "all", - ], "Invalid timestamp type must be one of: segment, word, char, all" - timestamp_type = [timestamp_type] if timestamp_type != "all" else ["segment", "word", "char"] - elif isinstance(timestamp_type, list): - assert all( - t in ["segment", "word", "char", "all"] for t in timestamp_type - ), "Invalid timestamp type must be one of: segment, word, char, all" - else: - raise ValueError("Invalid timestamp type must be one of: segment, word, char, all") - - timestamps = {t: [] for t in timestamp_type} - - for segment in utt_obj.segments_and_tokens: - - if not isinstance(segment, Segment): - continue - - if "segment" in timestamp_type: - timestamps["segment"].append( - { - "segment": segment.text, - "start_offset": ( - int(segment.t_start / output_timestep_duration) if segment.t_start != -1 else -1 - ), - "end_offset": int(segment.t_end / output_timestep_duration) if segment.t_end != -1 else -1, - "start": round(segment.t_start, 2), - "end": round(segment.t_end, 2), - } - ) - - for word in segment.words_and_tokens: - - if not isinstance(word, Word): - continue - - if "word" in timestamp_type: - timestamps["word"].append( - { - "word": word.text, - "start_offset": int(word.t_start / output_timestep_duration) if word.t_start != -1 else -1, - "end_offset": int(word.t_end / output_timestep_duration) if word.t_end != -1 else -1, - "start": round(word.t_start, 2), - "end": round(word.t_end, 2), - } - ) - - for i, token in enumerate(word.tokens): - if token.text == BLANK_TOKEN: - continue - - if token.text in supported_punctuation: - - previous_non_blank_token_idx = i - 1 - previous_non_blank_token = ( - word.tokens[previous_non_blank_token_idx] if previous_non_blank_token_idx >= 0 else None - ) - - while previous_non_blank_token is not None and previous_non_blank_token.text == BLANK_TOKEN: - previous_non_blank_token_idx -= 1 - previous_non_blank_token = ( - word.tokens[previous_non_blank_token_idx] - if previous_non_blank_token_idx >= 0 - else None - ) - - previous_token_end = ( - round(previous_non_blank_token.t_end, 2) - if previous_non_blank_token is not None - else round(token.t_start, 2) - ) - - if "segment" in timestamp_type: - if segment.t_end == word.t_end: - timestamps["segment"][-1]["end"] = previous_token_end - timestamps["segment"][-1]["end_offset"] = ( - int(previous_token_end / output_timestep_duration) - if previous_token_end != -1 - else -1 - ) - - if "word" in timestamp_type: - if word.t_end == token.t_end: - timestamps["word"][-1]["end"] = previous_token_end - timestamps["word"][-1]["end_offset"] = ( - int(previous_token_end / output_timestep_duration) - if previous_token_end != -1 - else -1 - ) - - token.t_end = token.t_start = previous_token_end - - if "char" in timestamp_type: - timestamps["char"].append( - { - "char": external_ctc_model.tokenizer.ids_to_text([token.token_id]), - "token_id": token.token_id, - "token": token.text, - "start_offset": ( - int(token.t_start / output_timestep_duration) if token.t_start != -1 else -1 - ), - "end_offset": int(token.t_end / output_timestep_duration) if token.t_end != -1 else -1, - "start": round(token.t_start, 2), - "end": round(token.t_end, 2), - } - ) - - return timestamps - - if viterbi_device is None: - viterbi_device = external_ctc_model.device - - if timestamp_type == "char": - segment_separators = None - word_separator = None - elif timestamp_type == "word": - segment_separators = None - - for start_idx in range(0, len(audio), batch_size): - end_idx = start_idx + batch_size - - audio_batch = audio[start_idx:end_idx] - - log_probs_batch, y_batch, T_batch, U_batch, utt_obj_batch, output_timestep_duration = get_batch_variables( - audio=audio_batch, - model=external_ctc_model, - segment_separators=segment_separators, - word_separator=word_separator, - gt_text_batch=[hyp.text for hyp in main_model_predictions[start_idx:end_idx]], - has_hypotheses=has_hypotheses, - verbose=verbose, - ) - - alignments_batch = viterbi_decoding( - log_probs_batch, - y_batch, - T_batch, - U_batch, - viterbi_device=viterbi_device, - ) - - for i, (utt_obj, alignment_utt) in enumerate(zip(utt_obj_batch, alignments_batch)): - utt_obj = add_t_start_end_to_utt_obj(utt_obj, alignment_utt, output_timestep_duration) - main_model_predictions[start_idx + i].timestamp = process_timestamps( - utt_obj, output_timestep_duration, timestamp_type - ) - - return main_model_predictions diff --git a/nemo/collections/asr/parts/utils/tokenizer_utils.py b/nemo/collections/asr/parts/utils/tokenizer_utils.py deleted file mode 100644 index d4f15f5123de57e760bb84b5e6dd3bf3b11cb3c1..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/tokenizer_utils.py +++ /dev/null @@ -1,71 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import re -import unicodedata -from typing import List, Set - - -def extract_punctuation_from_vocab(vocab: List[str]) -> Set[str]: - """ - Extract punctuation marks from vocabulary. - - Args: - vocab: List of vocabulary tokens - - Returns: - Set of punctuation marks found in the vocabulary - """ - special_token_patterns = [ - re.compile(r'^\[.*\]$'), - re.compile(r'^<.*>$'), - re.compile(r'^##'), - re.compile(r'^▁'), - re.compile(r'^\s*$'), - ] - - def is_special_token(token): - return any(pattern.match(token) for pattern in special_token_patterns) - - punctuation = { - char - for token in vocab - for char in token - if unicodedata.category(char).startswith('P') and not is_special_token(token) - } - - return punctuation - - -def extract_capitalized_tokens_from_vocab(vocab: List[str]) -> Set[str]: - """ - Extract capitalized tokens from vocabulary. - - Args: - vocab: List of vocabulary tokens - - Returns: - Set of capitalized tokens found in the vocabulary - """ - capitalized_tokens = {token.strip() for token in vocab if any(char.isupper() for char in token)} - return capitalized_tokens - - -def define_spe_tokenizer_type(vocabulary: List[str]) -> str: - """ - Define the tokenizer type based on the vocabulary. - """ - if any(token.startswith("##") for token in vocabulary): - return "wpe" - return "bpe" diff --git a/nemo/collections/asr/parts/utils/transcribe_utils.py b/nemo/collections/asr/parts/utils/transcribe_utils.py deleted file mode 100644 index 9c576ce3c09349c7129e16939806d82433efd877..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/transcribe_utils.py +++ /dev/null @@ -1,684 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import glob -import json -import os -import re -from dataclasses import dataclass -from pathlib import Path -from tempfile import NamedTemporaryFile -from typing import List, Optional, Tuple, Union - -import torch -from omegaconf import DictConfig -from tqdm.auto import tqdm - -from nemo.collections.asr.metrics.wer import word_error_rate -from nemo.collections.asr.models import ASRModel, EncDecMultiTaskModel -from nemo.collections.asr.parts.utils import manifest_utils, rnnt_utils -from nemo.collections.asr.parts.utils.streaming_utils import FrameBatchASR, FrameBatchMultiTaskAED -from nemo.collections.common.metrics.punct_er import OccurancePunctuationErrorRate -from nemo.collections.common.parts.preprocessing.manifest import get_full_path -from nemo.utils import logging, model_utils - -_MPS_WARNING_TEXT = ( - "MPS device (Apple Silicon M-series GPU) support is experimental." - " Env variable `PYTORCH_ENABLE_MPS_FALLBACK=1` should be set in most cases to avoid failures." -) - - -def get_auto_inference_device(allow_mps: bool = True) -> torch.device: - """Get best available inference device. Preference: CUDA -> MPS -> CPU""" - cuda_available = torch.cuda.is_available() - mps_available = hasattr(torch.backends, "mps") and torch.backends.mps.is_available() - if cuda_available: - device = torch.device('cuda:0') # use 0th CUDA device - elif allow_mps and mps_available: - logging.warning(_MPS_WARNING_TEXT) - device = torch.device('mps') - else: - device = torch.device('cpu') - return device - - -def get_inference_device(cuda: int | None = None, allow_mps: bool = True) -> torch.device: - """ - Get the best available device for model inference - - Args: - cuda: CUDA (GPU) device ID; negative value = GPU is not allowed; if None, select device automatically. - allow_mps: allow to select MPS device (Apple Silicon) - - Returns: - device: torch.device - """ - mps_available = hasattr(torch.backends, "mps") and torch.backends.mps.is_available() - cuda_available = torch.cuda.is_available() - if cuda is None: - return get_auto_inference_device(allow_mps=allow_mps) - elif cuda < 0: - # negative number => inference on CPU or MPS - if allow_mps and mps_available: - logging.warning(_MPS_WARNING_TEXT) - device = torch.device('mps') - else: - device = torch.device('cpu') - else: - if cuda_available: - device = torch.device(f'cuda:{cuda}') - else: - raise ValueError(f"CUDA device {cuda} requested, but unavailable") - return device - - -def get_auto_inference_dtype(device: torch.device) -> torch.dtype: - """Get inference dtype automatically. Preference: bfloat16 -> float32""" - can_use_bfloat16 = device.type == "cuda" and torch.cuda.is_bf16_supported() - if can_use_bfloat16: - return torch.bfloat16 - return torch.float32 - - -def get_inference_dtype(compute_dtype: str | None, device: torch.device) -> torch.dtype: - """Get dtype for model inference. If compute_dtype is None, the best available option is selected""" - dtype: torch.dtype - if compute_dtype is None: - return get_auto_inference_dtype(device=device) - assert compute_dtype in {"float32", "bfloat16", "float16"} - dtype = getattr(torch, compute_dtype) - return dtype - - -def get_buffered_pred_feat_rnnt( - asr: FrameBatchASR, - tokens_per_chunk: int, - delay: int, - model_stride_in_secs: int, - batch_size: int, - manifest: str = None, - filepaths: List[list] = None, - target_lang_id: str = None, - accelerator: Optional[str] = 'cpu', -) -> List[rnnt_utils.Hypothesis]: - """ - Moved from examples/asr/asr_chunked_inference/rnnt/speech_to_text_buffered_infer_rnnt.py - Write all information presented in input manifest to output manifest and removed WER calculation. - """ - hyps = [] - refs = [] - lang_ids = [] - - if filepaths and manifest: - raise ValueError("Please select either filepaths or manifest") - if filepaths is None and manifest is None: - raise ValueError("Either filepaths or manifest shoud not be None") - - if manifest: - filepaths = [] - with open(manifest, "r", encoding='utf_8') as mfst_f: - print("Parsing manifest files...") - for L in mfst_f: - L = L.strip() - if not L: - continue - row = json.loads(L) - audio_file = get_full_path(audio_file=row['audio_filepath'], manifest_file=manifest) - filepaths.append(audio_file) - if 'text' in row: - refs.append(row['text']) - - # Extract language from manifest - if 'target_lang' in row: - lang_ids.append(row['target_lang']) - elif 'lang' in row: - lang_ids.append(row['lang']) - else: - # Use target_lang_id as fallback - lang_ids.append(target_lang_id) - else: - # If filepaths are provided directly, use lang_id from config for all - lang_ids = [target_lang_id] * len(filepaths) - logging.info(f"filepaths are provided directly and target_lang_id: {target_lang_id}") - with torch.inference_mode(): - with torch.amp.autocast('cpu' if accelerator == 'cpu' else 'cuda'): - batch = [] - batch_lang_ids = [] - asr.sample_offset = 0 - for idx in tqdm(range(len(filepaths)), desc='Sample:', total=len(filepaths)): - batch.append(filepaths[idx]) - batch_lang_ids.append(lang_ids[idx]) - - if len(batch) == batch_size: - audio_files = [sample for sample in batch] - - # Reset ASR for new batch - asr.reset() - - # Set the language ID if any valid language ID exists - if any(lid is not None for lid in batch_lang_ids): - # Find the first non-None language ID to use - lang_id = next((lid for lid in batch_lang_ids if lid is not None), None) - if lang_id is not None: - asr.set_target_lang_id(lang_id) - - asr.read_audio_file(audio_files, delay, model_stride_in_secs) - hyp_list = asr.transcribe(tokens_per_chunk, delay) - hyps.extend(hyp_list) - - batch.clear() - batch_lang_ids.clear() - asr.sample_offset += batch_size - - if len(batch) > 0: - asr.batch_size = len(batch) - asr.frame_bufferer.batch_size = len(batch) - asr.reset() - - # Set the language ID for the remaining batch - if any(lid is not None for lid in batch_lang_ids): - lang_id = next((lid for lid in batch_lang_ids if lid is not None), None) - if lang_id is not None: - asr.set_target_lang_id(lang_id) - - audio_files = [sample for sample in batch] - asr.read_audio_file(audio_files, delay, model_stride_in_secs) - hyp_list = asr.transcribe(tokens_per_chunk, delay) - hyps.extend(hyp_list) - - batch.clear() - batch_lang_ids.clear() - asr.sample_offset += len(batch) - - if os.environ.get('DEBUG', '0') in ('1', 'y', 't'): - if len(refs) == 0: - print("ground-truth text does not present!") - for hyp in hyps: - print("hyp:", hyp) - else: - for hyp, ref in zip(hyps, refs): - print("hyp:", hyp) - print("ref:", ref) - - wrapped_hyps = wrap_transcription(hyps) - return wrapped_hyps - - -def get_buffered_pred_feat_multitaskAED( - asr: FrameBatchMultiTaskAED, - preprocessor_cfg: DictConfig, - model_stride_in_secs: int, - device: Union[List[int], int], - manifest: str = None, - filepaths: List[list] = None, - delay: float = 0.0, - timestamps: bool = False, -) -> List[rnnt_utils.Hypothesis]: - # Create a preprocessor to convert audio samples into raw features, - # Normalization will be done per buffer in frame_bufferer - # Do not normalize whatever the model's preprocessor setting is - preprocessor_cfg.normalize = "None" - preprocessor = EncDecMultiTaskModel.from_config_dict(preprocessor_cfg) - preprocessor.to(device) - hyps = [] - refs = [] - - if filepaths and manifest: - raise ValueError("Please select either filepaths or manifest") - if filepaths is None and manifest is None: - raise ValueError("Either filepaths or manifest shoud not be None") - - if filepaths: - logging.info( - "Deteced audio files as input, default to English ASR with Punctuation and Capitalization output. \ - Please use manifest input for other options." - ) - for audio_file in tqdm(filepaths, desc="Transcribing:", total=len(filepaths), ncols=80): - meta = { - 'audio_filepath': audio_file, - 'duration': 100000, - 'source_lang': 'en', - 'taskname': 'asr', - 'target_lang': 'en', - 'pnc': 'yes', - 'answer': 'nothing', - 'timestamp': 'yes' if timestamps else 'no', - } - asr.reset() - asr.read_audio_file(audio_file, delay, model_stride_in_secs, meta_data=meta) - hyp = asr.transcribe(timestamps=timestamps) - hyps.append(hyp) - else: - with open(manifest, "r", encoding='utf_8') as fin: - lines = list(fin.readlines()) - for line in tqdm(lines, desc="Transcribing:", total=len(lines), ncols=80): - asr.reset() - line = line.strip() - if not line: - continue - sample = json.loads(line) - if timestamps: - # user convenience so that they don't need to make another manifest with timestamp field or modify the existing one - sample['timestamp'] = 'yes' - if 'text' in sample: - refs.append(sample['text']) - audio_file = get_full_path(audio_file=sample['audio_filepath'], manifest_file=manifest) - # do not support partial audio - asr.read_audio_file(audio_file, delay, model_stride_in_secs, meta_data=sample) - hyp = asr.transcribe(timestamps=timestamps) - hyps.append(hyp) - - wrapped_hyps = wrap_transcription(hyps) - return wrapped_hyps - - -def wrap_transcription(hyps: List[str]) -> List[rnnt_utils.Hypothesis]: - """Wrap transcription to the expected format in func write_transcription""" - if isinstance(hyps[0], rnnt_utils.Hypothesis): - return hyps - - wrapped_hyps = [] - for hyp in hyps: - hypothesis = rnnt_utils.Hypothesis(score=0.0, y_sequence=[], text=hyp) - wrapped_hyps.append(hypothesis) - return wrapped_hyps - - -def setup_model(cfg: DictConfig, map_location: torch.device) -> Tuple[ASRModel, str]: - """Setup model from cfg and return model and model name for next step""" - if cfg.model_path is not None and cfg.model_path != "None": - # restore model from .nemo file path - model_cfg = ASRModel.restore_from(restore_path=cfg.model_path, return_config=True) - classpath = model_cfg.target # original class path - imported_class = model_utils.import_class_by_path(classpath) # type: ASRModel - logging.info(f"Restoring model : {imported_class.__name__}") - asr_model = imported_class.restore_from( - restore_path=cfg.model_path, - map_location=map_location, - ) # type: ASRModel - model_name = os.path.splitext(os.path.basename(cfg.model_path))[0] - else: - # restore model by name - asr_model = ASRModel.from_pretrained( - model_name=cfg.pretrained_name, - map_location=map_location, - ) # type: ASRModel - model_name = cfg.pretrained_name - - if hasattr(cfg, "model_change") and hasattr(asr_model, "change_attention_model"): - asr_model.change_attention_model( - self_attention_model=cfg.model_change.conformer.get("self_attention_model", None), - att_context_size=cfg.model_change.conformer.get("att_context_size", None), - ) - - return asr_model, model_name - - -def prepare_audio_data(cfg: DictConfig) -> Tuple[List[str], bool]: - """ - Prepare audio data for transcription. - Args: - cfg (DictConfig): Configuration dictionary containing the following parameters: - - audio_dir (str): Path to the directory containing audio files. - - append_pred (bool): Flag indicating whether to append predictions to an existing dataset. - - audio_type (str): Type of audio files to consider. - - dataset_manifest (str): Path to the dataset manifest file. - - audio_key (str, optional): Key in the manifest file specifying the audio file path. - Defaults to 'audio_filepath'. - - presort_manifest (bool, optional): Flag indicating whether to presort the manifest file. - Defaults to True. - Returns: - Tuple[List[str], bool]: A tuple containing the following: - - filepaths (List[str]): List of filepaths to the audio files if path to the directory - containing audio files is provided. - - sorted_manifest_path (bool): Path to the sorted manifest file if path to the dataset - manifest file is provided. - """ - - filepaths = None - sorted_manifest_path = None - - if cfg.audio_dir is not None and not cfg.append_pred: - filepaths = list(glob.glob(os.path.join(cfg.audio_dir, f"**/*.{cfg.audio_type}"), recursive=True)) - else: - filepaths = [] - if os.stat(cfg.dataset_manifest).st_size == 0: - logging.error(f"The input dataset_manifest {cfg.dataset_manifest} is empty. Exiting!") - return None - - audio_key = cfg.get('audio_key', 'audio_filepath') - - with open(cfg.dataset_manifest, "rt") as fh: - for line in fh: - line = line.strip() - if not line: - continue - item = json.loads(line) - item[audio_key] = get_full_path(item[audio_key], cfg.dataset_manifest) - if item.get("duration") is None and cfg.presort_manifest: - raise ValueError( - f"Requested presort_manifest=True, but line {line} in manifest {cfg.dataset_manifest} \ - lacks a 'duration' field." - ) - - with NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f: - for item in read_and_maybe_sort_manifest(cfg.dataset_manifest, try_sort=cfg.presort_manifest): - audio_file = get_full_path(audio_file=item[audio_key], manifest_file=cfg.dataset_manifest) - item['audio_filepath'] = audio_file - filepaths.append(audio_file) - f.write(json.dumps(item) + "\n") - sorted_manifest_path = f.name - - return filepaths, sorted_manifest_path - - -def read_and_maybe_sort_manifest(path: str, try_sort: bool = False) -> List[dict]: - """Sorts the manifest if duration key is available for every utterance.""" - items = manifest_utils.read_manifest(path) - if try_sort and all("duration" in item and item["duration"] is not None for item in items): - items = sorted(items, reverse=True, key=lambda item: item["duration"]) - return items - - -def restore_transcription_order(manifest_path: str, transcriptions: list) -> list: - with open(manifest_path, encoding='utf-8') as f: - items = [(idx, json.loads(l)) for idx, l in enumerate(f) if l.strip() != ""] - if not all("duration" in item[1] and item[1]["duration"] is not None for item in items): - return transcriptions - new2old = [item[0] for item in sorted(items, reverse=True, key=lambda it: it[1]["duration"])] - del items # free up some memory - is_list = isinstance(transcriptions[0], list) - if is_list: - transcriptions = list(zip(*transcriptions)) - reordered = [None] * len(transcriptions) - for new, old in enumerate(new2old): - reordered[old] = transcriptions[new] - - if is_list: - reordered = tuple(map(list, zip(*reordered))) - return reordered - - -def compute_output_filename(cfg: DictConfig, model_name: str) -> DictConfig: - """Compute filename of output manifest and update cfg""" - if cfg.output_filename is None: - # create default output filename - if cfg.audio_dir is not None: - cfg.output_filename = os.path.dirname(os.path.join(cfg.audio_dir, '.')) + '.json' - elif cfg.pred_name_postfix is not None: - cfg.output_filename = cfg.dataset_manifest.replace('.json', f'_{cfg.pred_name_postfix}.json') - else: - cfg.output_filename = cfg.dataset_manifest.replace('.json', f'_{model_name}.json') - return cfg - - -def normalize_timestamp_output(timestamps: dict): - """ - Normalize the dictionary of timestamp values to JSON serializable values. - Expects the following keys to exist - - "start_offset": int-like object that represents the starting index of the token - in the full audio after downsampling. - "end_offset": int-like object that represents the ending index of the token - in the full audio after downsampling. - - Args: - timestamps: Nested dict. - - Returns: - Normalized `timestamps` dictionary (in-place normalized) - """ - for val_idx in range(len(timestamps)): - timestamps[val_idx]['start_offset'] = int(timestamps[val_idx]['start_offset']) - timestamps[val_idx]['end_offset'] = int(timestamps[val_idx]['end_offset']) - return timestamps - - -def write_transcription( - transcriptions: Union[List[rnnt_utils.Hypothesis], List[List[rnnt_utils.Hypothesis]], List[str]], - cfg: DictConfig, - model_name: str, - filepaths: List[str] = None, - compute_langs: bool = False, - timestamps: bool = False, -) -> Tuple[str, str]: - """Write generated transcription to output file.""" - if cfg.append_pred: - logging.info(f'Transcripts will be written in "{cfg.output_filename}" file') - if cfg.pred_name_postfix is not None: - pred_by_model_name = cfg.pred_name_postfix - else: - pred_by_model_name = model_name - pred_text_attr_name = 'pred_text_' + pred_by_model_name - else: - pred_text_attr_name = 'pred_text' - - return_hypotheses = True - if isinstance(transcriptions[0], str): # List[str]: - best_hyps = transcriptions - return_hypotheses = False - elif isinstance(transcriptions[0], rnnt_utils.Hypothesis): # List[rnnt_utils.Hypothesis] - best_hyps = transcriptions - assert cfg.decoding.beam.return_best_hypothesis, "Works only with return_best_hypothesis=true" - elif isinstance(transcriptions[0], list) and isinstance( - transcriptions[0][0], rnnt_utils.Hypothesis - ): # List[List[rnnt_utils.Hypothesis]] NBestHypothesis - best_hyps, beams = [], [] - for hyps in transcriptions: - best_hyps.append(hyps[0]) - if not cfg.decoding.beam.return_best_hypothesis: - beam = [] - for hyp in hyps: - score = hyp.score.numpy().item() if isinstance(hyp.score, torch.Tensor) else hyp.score - beam.append((hyp.text, score)) - beams.append(beam) - else: - raise TypeError - - # create output dir if not exists - Path(cfg.output_filename).parent.mkdir(parents=True, exist_ok=True) - with open(cfg.output_filename, 'w', encoding='utf-8', newline='\n') as f: - if cfg.audio_dir is not None: - for idx, transcription in enumerate(best_hyps): # type: rnnt_utils.Hypothesis or str - if not return_hypotheses: # transcription is str - item = {'audio_filepath': filepaths[idx], pred_text_attr_name: transcription} - else: # transcription is Hypothesis - item = {'audio_filepath': filepaths[idx], pred_text_attr_name: transcription.text} - - if timestamps: - timestamps = transcription.timestamp - if timestamps is not None and isinstance(timestamps, dict): - timestamps.pop( - 'timestep', None - ) # Pytorch tensor calculating index of each token, not needed. - for key in timestamps.keys(): - values = normalize_timestamp_output(timestamps[key]) - item[f'{key}'] = values - - if compute_langs: - item['pred_lang'] = transcription.langs - item['pred_lang_chars'] = transcription.langs_chars - if not cfg.decoding.beam.return_best_hypothesis: - item['beams'] = beams[idx] - f.write(json.dumps(item) + "\n") - else: - with open(cfg.dataset_manifest, 'r', encoding='utf-8') as fr: - for idx, line in enumerate(fr): - line = line.strip() - if not line: - continue - item = json.loads(line) - if not return_hypotheses: # transcription is str - item[pred_text_attr_name] = best_hyps[idx] - else: # transcription is Hypothesis - item[pred_text_attr_name] = best_hyps[idx].text - - if timestamps: - timestamps = best_hyps[idx].timestamp - if timestamps is not None and isinstance(timestamps, dict): - timestamps.pop( - 'timestep', None - ) # Pytorch tensor calculating index of each token, not needed. - for key in timestamps.keys(): - values = normalize_timestamp_output(timestamps[key]) - item[f'{key}'] = values - - if compute_langs: - item['pred_lang'] = best_hyps[idx].langs - item['pred_lang_chars'] = best_hyps[idx].langs_chars - - if not cfg.decoding.beam.return_best_hypothesis: - item['beams'] = beams[idx] - f.write(json.dumps(item) + "\n") - - return cfg.output_filename, pred_text_attr_name - - -def compute_metrics_per_sample( - manifest_path: str, - reference_field: str = "text", - hypothesis_field: str = "pred_text", - metrics: List[str] = ["wer"], - punctuation_marks: List[str] = [".", ",", "?"], - output_manifest_path: str = None, -) -> dict: - ''' - Computes metrics per sample for given manifest - - Args: - manifest_path: str, Required - path to dataset JSON manifest file (in NeMo format) - reference_field: str, Optional - name of field in .json manifest with the reference text - ("text" by default). - hypothesis_field: str, Optional - name of field in .json manifest with the hypothesis text - ("pred_text" by default). - metrics: list[str], Optional - list of metrics to be computed - (currently supported "wer", "cer", "punct_er") - punctuation_marks: list[str], Optional - list of punctuation marks for computing - punctuation error rate ([".", ",", "?"] by default). - output_manifest_path: str, Optional - path where .json manifest with calculated metrics will be saved. - - Returns: - samples: dict - Dict of samples with calculated metrics - ''' - - supported_metrics = ["wer", "cer", "punct_er"] - - if len(metrics) == 0: - raise AssertionError( - f"'metrics' list is empty. \ - Select the metrics from the supported: {supported_metrics}." - ) - - for metric in metrics: - if metric not in supported_metrics: - raise AssertionError( - f"'{metric}' metric is not supported. \ - Currently supported metrics are {supported_metrics}." - ) - - if "punct_er" in metrics: - if len(punctuation_marks) == 0: - raise AssertionError("punctuation_marks list can't be empty when 'punct_er' metric is enabled.") - else: - oper_obj = OccurancePunctuationErrorRate(punctuation_marks=punctuation_marks) - - use_wer = "wer" in metrics - use_cer = "cer" in metrics - use_punct_er = "punct_er" in metrics - - with open(manifest_path, 'r') as manifest: - lines = manifest.readlines() - samples = [json.loads(line) for line in lines if line.strip() != ""] - samples_with_metrics = [] - - logging.info(f"Computing {', '.join(metrics)} per sample") - - for sample in tqdm(samples): - reference = sample[reference_field] - hypothesis = sample[hypothesis_field] - - if use_wer: - sample_wer = word_error_rate(hypotheses=[hypothesis], references=[reference], use_cer=False) - sample["wer"] = round(100 * sample_wer, 2) - - if use_cer: - sample_cer = word_error_rate(hypotheses=[hypothesis], references=[reference], use_cer=True) - sample["cer"] = round(100 * sample_cer, 2) - - if use_punct_er: - operation_amounts, substitution_amounts, punctuation_rates = oper_obj.compute( - reference=reference, hypothesis=hypothesis - ) - sample["punct_correct_rate"] = round(100 * punctuation_rates.correct_rate, 2) - sample["punct_deletions_rate"] = round(100 * punctuation_rates.deletions_rate, 2) - sample["punct_insertions_rate"] = round(100 * punctuation_rates.insertions_rate, 2) - sample["punct_substitutions_rate"] = round(100 * punctuation_rates.substitutions_rate, 2) - sample["punct_error_rate"] = round(100 * punctuation_rates.punct_er, 2) - - samples_with_metrics.append(sample) - - if output_manifest_path is not None: - with open(output_manifest_path, 'w') as output: - for sample in samples_with_metrics: - line = json.dumps(sample) - output.writelines(f'{line}\n') - logging.info(f'Output manifest saved: {output_manifest_path}') - - return samples_with_metrics - - -class PunctuationCapitalization: - def __init__(self, punctuation_marks: str): - """ - Class for text processing with punctuation and capitalization. Can be used with class TextProcessingConfig. - - Args: - punctuation_marks (str): String with punctuation marks to process. - Example: punctuation_marks = '.,?' - """ - if punctuation_marks: - self.regex_punctuation = re.compile(fr"([{''.join(punctuation_marks)}])") - self.regex_extra_space = re.compile(r'\s{2,}') - else: - self.regex_punctuation = None - - def separate_punctuation(self, lines: List[str]) -> List[str]: - if self.regex_punctuation is not None: - return [ - self.regex_extra_space.sub(' ', self.regex_punctuation.sub(r' \1 ', line)).strip() for line in lines - ] - else: - return lines - - def do_lowercase(self, lines: List[str]) -> List[str]: - return [line.lower() for line in lines] - - def rm_punctuation(self, lines: List[str]) -> List[str]: - if self.regex_punctuation is not None: - return [self.regex_extra_space.sub(' ', self.regex_punctuation.sub(' ', line)).strip() for line in lines] - else: - return lines - - -@dataclass -class TextProcessingConfig: - # Punctuation marks to process. Example: ".,?" - punctuation_marks: str = "" - - # Whether to apply lower case conversion on the training text. - do_lowercase: bool = False - - # Whether to remove punctuation marks from text. - rm_punctuation: bool = False - - # Whether to separate punctuation with the previouse word by space. - separate_punctuation: bool = True diff --git a/nemo/collections/asr/parts/utils/vad_utils.py b/nemo/collections/asr/parts/utils/vad_utils.py deleted file mode 100644 index 0848a4f9c3f1a991aa309a11ac653034c22d0ad9..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/vad_utils.py +++ /dev/null @@ -1,1895 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import glob -import json -import math -import multiprocessing -import os -import shutil -from dataclasses import dataclass -from itertools import repeat -from math import ceil, floor -from pathlib import Path -from typing import Dict, List, Optional, Tuple, Union - -import IPython.display as ipd -import librosa -import matplotlib.pyplot as plt -import numpy as np -import pandas as pd -import torch -import yaml -from omegaconf import DictConfig, OmegaConf -from pyannote.core import Annotation, Segment -from pyannote.metrics import detection -from sklearn.metrics import roc_auc_score -from sklearn.model_selection import ParameterGrid -from tqdm import tqdm -from nemo.collections.asr.models import EncDecClassificationModel, EncDecFrameClassificationModel -from nemo.collections.common.parts.preprocessing.manifest import get_full_path -from nemo.utils import logging - -""" -This file contains all the utility functions required for voice activity detection. -""" - - -@dataclass -class PostProcessingParams: - """ - Postprocessing parameters for end-to-end speaker diarization models. - These parameters can significantly affect DER performance depending on the evaluation style and the dataset. - It is recommended to tune these parameters based on the evaluation style and the dataset - to achieve the desired DER performance. - """ - - onset: float = 0.5 # Onset threshold for detecting the beginning and end of a speech - offset: float = 0.5 # Offset threshold for detecting the end of a speech - pad_onset: float = 0.0 # Adding durations before each speech segment - pad_offset: float = 0.0 # Adding durations after each speech segment - min_duration_on: float = 0.0 # Threshold for short speech segment deletion - min_duration_off: float = 0.0 # Threshold for small non-speech deletion - - -def load_postprocessing_from_yaml(postprocessing_yaml: str = None) -> PostProcessingParams: - """ - Load postprocessing parameters from a YAML file. - - Args: - postprocessing_yaml (str): - Path to a YAML file for postprocessing configurations. - - Returns: - postprocessing_params (dataclass): - Postprocessing parameters loaded from the YAML file. - """ - # Add PostProcessingParams as a field - postprocessing_params = OmegaConf.structured(PostProcessingParams()) - if postprocessing_yaml is None: - logging.info( - f"No postprocessing YAML file has been provided. Default postprocessing configurations will be applied." - ) - else: - # Load postprocessing params from the provided YAML file - with open(postprocessing_yaml, 'r') as file: - yaml_params = yaml.safe_load(file)['parameters'] - # Update the postprocessing_params with the loaded values - logging.info(f"Postprocessing YAML file '{postprocessing_yaml}' has been loaded.") - for key, value in yaml_params.items(): - if hasattr(postprocessing_params, key): - setattr(postprocessing_params, key, value) - return postprocessing_params - - -def prepare_manifest(config: dict) -> str: - """ - Perform VAD on long audio snippet might cause CUDA out of memory issue. - Automatically split manifest entry by split_duration to avoid the potential memory issue. - """ - if 'prepared_manifest_vad_input' in config and config['prepared_manifest_vad_input']: - manifest_vad_input = config['prepared_manifest_vad_input'] - else: - default_path = "manifest_vad_input.json" - manifest_vad_input = os.path.join(config["out_dir"], default_path) if "out_dir" in config else default_path - - # input_list is a list of variable ['audio_filepath': i, "offset": xxx, "duration": xxx]) - if type(config['input']) == str: - input_list = [] - with open(config['input'], 'r', encoding='utf-8') as manifest: - for line in manifest.readlines(): - input_list.append(json.loads(line.strip())) - elif type(config['input']) == list: - input_list = config['input'] - else: - raise ValueError( - "The input for manifest preparation would either be a string of the filepath to manifest " - "or a list of {'audio_filepath': i, 'offset': 0, 'duration': null}." - ) - - args_func = { - 'label': 'infer', - 'split_duration': config['split_duration'], - 'window_length_in_sec': config['window_length_in_sec'], - 'manifest_dir': Path(config['input']).parent if type(config['input']) == str else '', - } - - if config.get('num_workers') is not None and config['num_workers'] > 1: - with multiprocessing.Pool(processes=config['num_workers']) as p: - inputs = zip(input_list, repeat(args_func)) - results = list( - tqdm( - p.imap(write_vad_infer_manifest_star, inputs), - total=len(input_list), - desc='splitting manifest', - leave=True, - ) - ) - else: - results = [ - write_vad_infer_manifest(input_el, args_func) - for input_el in tqdm(input_list, desc='splitting manifest', leave=True) - ] - - if os.path.exists(manifest_vad_input): - logging.info("The prepared manifest file exists. Overwriting!") - os.remove(manifest_vad_input) - - with open(manifest_vad_input, 'a', encoding='utf-8') as fout: - for res in results: - for r in res: - json.dump(r, fout) - fout.write('\n') - fout.flush() - return manifest_vad_input - - -def write_vad_infer_manifest_star(args): - """ - A workaround for tqdm with starmap of multiprocessing - """ - return write_vad_infer_manifest(*args) - - -def write_vad_infer_manifest(file: dict, args_func: dict) -> list: - """ - Used by prepare_manifest. - Given a list of files, split them with maximum split_duration and write them to the manifest. - Args: - files (dict) : file to be processed - args_func: - label (str): label for audio snippet.y - split_duration (float): max duration of each audio clip (each line in json) - window_length_in_sec (float) : length of window for generating the frame. Used for taking care of joint. - Returns: - res (list) : list of generated metadata line of json for file - """ - res = [] - label = args_func['label'] - split_duration = args_func['split_duration'] - window_length_in_sec = args_func['window_length_in_sec'] - filepath = file['audio_filepath'] - in_duration = file.get('duration', None) - in_offset = file.get('offset', 0) - - # if filepath is not found, try to find it in the dir of manifest - if not Path(filepath).is_file(): - new_filepath = Path(args_func['manifest_dir']) / filepath - if new_filepath.is_file(): - filepath = new_filepath.absolute().as_posix() - - try: - sr = 16000 - x, _sr = librosa.load(filepath, sr=sr, offset=in_offset, duration=in_duration) - duration = librosa.get_duration(y=x, sr=sr) - left = duration - current_offset = in_offset - - status = 'single' - while left > 0: - if left <= split_duration: - if status == 'single': - write_duration = left - current_offset = 0 - else: - status = 'end' - write_duration = left + window_length_in_sec - current_offset -= window_length_in_sec - offset_inc = left - left = 0 - else: - if status == 'start' or status == 'next': - status = 'next' - else: - status = 'start' - - if status == 'start': - write_duration = split_duration - offset_inc = split_duration - else: - write_duration = split_duration + window_length_in_sec - current_offset -= window_length_in_sec - offset_inc = split_duration + window_length_in_sec - - left -= split_duration - - metadata = { - 'audio_filepath': filepath, - 'duration': write_duration, - 'label': label, - 'text': '_', - 'offset': current_offset, - } - res.append(metadata) - - current_offset += offset_inc - - except Exception as e: - err_file = "error.log" - with open(err_file, 'w', encoding='utf-8') as fout: - fout.write(filepath + ":" + str(e)) - return res - - -def get_vad_stream_status(data: list) -> list: - """ - Generate a list of status for each snippet in manifest. A snippet should be in single, start, next or end status. - Used for concatenating to full audio file. - Args: - data (list): list of filepath of audio snippet - Returns: - status (list): list of status of each snippet. - """ - if len(data) == 1: - return ['single'] - - status = [None] * len(data) - for i in range(len(data)): - if i == 0: - status[i] = 'start' if data[i] == data[i + 1] else 'single' - elif i == len(data) - 1: - status[i] = 'end' if data[i] == data[i - 1] else 'single' - else: - if data[i] != data[i - 1] and data[i] == data[i + 1]: - status[i] = 'start' - elif data[i] == data[i - 1] and data[i] == data[i + 1]: - status[i] = 'next' - elif data[i] == data[i - 1] and data[i] != data[i + 1]: - status[i] = 'end' - else: - status[i] = 'single' - return status - - -def load_tensor_from_file(filepath: str) -> Tuple[torch.Tensor, str]: - """ - Load torch.Tensor and the name from file - """ - frame = [] - with open(filepath, "r", encoding='utf-8') as f: - for line in f.readlines(): - frame.append(float(line)) - - name = Path(filepath).stem - return torch.tensor(frame), name - - -def generate_overlap_vad_seq( - frame_pred_dir: str, - smoothing_method: str, - overlap: float, - window_length_in_sec: float, - shift_length_in_sec: float, - num_workers: int, - out_dir: str = None, -) -> str: - """ - Generate predictions with overlapping input windows/segments. - Then a smoothing filter is applied to decide the label for a frame spanned by multiple windows. - Two common smoothing filters are supported: majority vote (median) and average (mean). - This function uses multiprocessing to speed up. - Args: - frame_pred_dir (str): Directory of frame prediction file to be processed. - smoothing_method (str): median or mean smoothing filter. - overlap (float): amounts of overlap of adjacent windows. - window_length_in_sec (float): length of window for generating the frame. - shift_length_in_sec (float): amount of shift of window for generating the frame. - out_dir (str): directory of generated predictions. - num_workers(float): number of process for multiprocessing - Returns: - overlap_out_dir(str): directory of the generated predictions. - """ - - frame_filepathlist = glob.glob(frame_pred_dir + "/*.frame") - if out_dir: - overlap_out_dir = out_dir - else: - overlap_out_dir = os.path.join( - frame_pred_dir, "overlap_smoothing_output" + "_" + smoothing_method + "_" + str(overlap) - ) - - if not os.path.exists(overlap_out_dir): - os.mkdir(overlap_out_dir) - - per_args = { - "overlap": overlap, - "window_length_in_sec": window_length_in_sec, - "shift_length_in_sec": shift_length_in_sec, - "out_dir": overlap_out_dir, - "smoothing_method": smoothing_method, - } - if num_workers is not None and num_workers > 1: - with multiprocessing.Pool(processes=num_workers) as p: - inputs = zip(frame_filepathlist, repeat(per_args)) - results = list( - tqdm( - p.imap(generate_overlap_vad_seq_per_file_star, inputs), - total=len(frame_filepathlist), - desc='generating preds', - leave=True, - ) - ) - - else: - for frame_filepath in tqdm(frame_filepathlist, desc='generating preds', leave=False): - generate_overlap_vad_seq_per_file(frame_filepath, per_args) - - return overlap_out_dir - - -def generate_overlap_vad_seq_per_file_star(args): - """ - A workaround for tqdm with starmap of multiprocessing - """ - return generate_overlap_vad_seq_per_file(*args) - - -@torch.jit.script -def generate_overlap_vad_seq_per_tensor( - frame: torch.Tensor, per_args: Dict[str, float], smoothing_method: str -) -> torch.Tensor: - """ - Use generated frame prediction (generated by shifting window of shift_length_in_sec (10ms)) to generate - prediction with overlapping input window/segments. See description in generate_overlap_vad_seq. - Use this for single instance pipeline. - """ - # This function will be refactor for vectorization but this is okay for now - - overlap = per_args['overlap'] - window_length_in_sec = per_args['window_length_in_sec'] - shift_length_in_sec = per_args['shift_length_in_sec'] - frame_len = per_args.get('frame_len', 0.01) - - shift = int(shift_length_in_sec / frame_len) # number of units of shift - seg = int((window_length_in_sec / frame_len + 1)) # number of units of each window/segment - - jump_on_target = int(seg * (1 - overlap)) # jump on target generated sequence - jump_on_frame = int(jump_on_target / shift) # jump on input frame sequence - - if jump_on_frame < 1: - raise ValueError( - f"Note we jump over frame sequence to generate overlapping input segments. \n \ - Your input makes jump_on_frame={jump_on_frame} < 1 which is invalid because it cannot jump and will stuck.\n \ - Please try different window_length_in_sec, shift_length_in_sec and overlap choices. \n \ - jump_on_target = int(seg * (1 - overlap)) \n \ - jump_on_frame = int(jump_on_frame/shift) " - ) - - target_len = int(len(frame) * shift) - - if smoothing_method == 'mean': - preds = torch.zeros(target_len) - pred_count = torch.zeros(target_len) - - for i, og_pred in enumerate(frame): - if i % jump_on_frame != 0: - continue - start = i * shift - end = start + seg - preds[start:end] = preds[start:end] + og_pred - pred_count[start:end] = pred_count[start:end] + 1 - - preds = preds / pred_count - last_non_zero_pred = preds[pred_count != 0][-1] - preds[pred_count == 0] = last_non_zero_pred - - elif smoothing_method == 'median': - preds = [torch.empty(0) for _ in range(target_len)] - for i, og_pred in enumerate(frame): - if i % jump_on_frame != 0: - continue - - start = i * shift - end = start + seg - for j in range(start, end): - if j <= target_len - 1: - preds[j] = torch.cat((preds[j], og_pred.unsqueeze(0)), 0) - - preds = torch.stack([torch.nanquantile(l, q=0.5) for l in preds]) - nan_idx = torch.isnan(preds) - last_non_nan_pred = preds[~nan_idx][-1] - preds[nan_idx] = last_non_nan_pred - - else: - raise ValueError("smoothing_method should be either mean or median") - - return preds - - -def generate_overlap_vad_seq_per_file(frame_filepath: str, per_args: dict) -> str: - """ - A wrapper for generate_overlap_vad_seq_per_tensor. - """ - - out_dir = per_args['out_dir'] - smoothing_method = per_args['smoothing_method'] - frame, name = load_tensor_from_file(frame_filepath) - - per_args_float: Dict[str, float] = {} - for i in per_args: - if type(per_args[i]) == float or type(per_args[i]) == int: - per_args_float[i] = per_args[i] - - preds = generate_overlap_vad_seq_per_tensor(frame, per_args_float, smoothing_method) - - overlap_filepath = os.path.join(out_dir, name + "." + smoothing_method) - with open(overlap_filepath, "w", encoding='utf-8') as f: - for pred in preds: - f.write(f"{pred:.4f}\n") - - return overlap_filepath - - -@torch.jit.script -def merge_overlap_segment(segments: torch.Tensor) -> torch.Tensor: - """ - Merged the given overlapped segments. - For example: - torch.Tensor([[0, 1.5], [1, 3.5]]) -> torch.Tensor([0, 3.5]) - """ - if ( - segments.shape == torch.Size([0]) - or segments.shape == torch.Size([0, 2]) - or segments.shape == torch.Size([1, 2]) - ): - return segments - - segments = segments[segments[:, 0].sort()[1]] - merge_boundary = segments[:-1, 1] >= segments[1:, 0] - head_padded = torch.nn.functional.pad(merge_boundary, [1, 0], mode='constant', value=0.0) - head = segments[~head_padded, 0] - tail_padded = torch.nn.functional.pad(merge_boundary, [0, 1], mode='constant', value=0.0) - tail = segments[~tail_padded, 1] - merged = torch.stack((head, tail), dim=1) - return merged - - -@torch.jit.script -def filter_short_segments(segments: torch.Tensor, threshold: float) -> torch.Tensor: - """ - Remove segments which duration is smaller than a threshold. - For example, - torch.Tensor([[0, 1.5], [1, 3.5], [4, 7]]) and threshold = 2.0 - -> - torch.Tensor([[1, 3.5], [4, 7]]) - """ - return segments[segments[:, 1] - segments[:, 0] >= threshold] - - -def percentile(data: torch.Tensor, perc: int) -> float: - """ - Calculate percentile given data - """ - size = len(data) - return float(sorted(data)[int(math.ceil((size * perc) / 100)) - 1]) - - -def cal_vad_onset_offset( - scale: str, onset: float, offset: float, sequence: torch.Tensor = None -) -> Tuple[float, float]: - """ - Calculate onset and offset threshold given different scale. - """ - if scale == "absolute": - mini = 0 - maxi = 1 - elif scale == "relative": - mini = min(sequence) - maxi = max(sequence) - elif scale == "percentile": - mini = percentile(sequence, 1) - maxi = percentile(sequence, 99) - - onset = mini + onset * (maxi - mini) - offset = mini + offset * (maxi - mini) - return float(onset), float(offset) - - -@torch.jit.script -def binarization(sequence: torch.Tensor, per_args: Dict[str, float]) -> torch.Tensor: - """ - Binarize predictions to speech and non-speech - - Reference - Paper: Gregory Gelly and Jean-Luc Gauvain. "Minimum Word Error Training of RNN-based Voice - Activity Detection", InterSpeech 2015. - Implementation: https://github.com/pyannote/pyannote-audio/blob/master/pyannote/audio/utils/signal.py - - Args: - sequence (torch.Tensor) : A tensor of frame level predictions. - per_args: - onset (float): onset threshold for detecting the beginning and end of a speech - offset (float): offset threshold for detecting the end of a speech. - pad_onset (float): adding durations before each speech segment - pad_offset (float): adding durations after each speech segment; - frame_length_in_sec (float): length of frame. - - Returns: - speech_segments(torch.Tensor): A tensor of speech segment in the form of: - `torch.Tensor([[start1, end1], [start2, end2]])`. - """ - frame_length_in_sec = per_args.get('frame_length_in_sec', 0.01) - - onset = per_args.get('onset', 0.5) - offset = per_args.get('offset', 0.5) - pad_onset = per_args.get('pad_onset', 0.0) - pad_offset = per_args.get('pad_offset', 0.0) - - speech = False - start = 0.0 - i = 0 - - speech_segments = torch.empty(0) - - for i in range(0, len(sequence)): - # Current frame is speech - if speech: - # Switch from speech to non-speech - if sequence[i] < offset: - if i * frame_length_in_sec + pad_offset > max(0, start - pad_onset): - new_seg = torch.tensor( - [max(0, start - pad_onset), i * frame_length_in_sec + pad_offset] - ).unsqueeze(0) - speech_segments = torch.cat((speech_segments, new_seg), 0) - - start = i * frame_length_in_sec - speech = False - - # Current frame is non-speech - else: - # Switch from non-speech to speech - if sequence[i] > onset: - start = i * frame_length_in_sec - speech = True - - # if it's speech at the end, add final segment - if speech: - new_seg = torch.tensor([max(0, start - pad_onset), i * frame_length_in_sec + pad_offset]).unsqueeze(0) - speech_segments = torch.cat((speech_segments, new_seg), 0) - - # Merge the overlapped speech segments due to padding - speech_segments = merge_overlap_segment(speech_segments) # not sorted - return speech_segments - - -@torch.jit.script -def remove_segments(original_segments: torch.Tensor, to_be_removed_segments: torch.Tensor) -> torch.Tensor: - """ - Remove speech segments list in to_be_removed_segments from original_segments. - (Example) Remove torch.Tensor([[start2, end2],[start4, end4]]) - from torch.Tensor([[start1, end1],[start2, end2],[start3, end3], [start4, end4]]), - -> - torch.Tensor([[start1, end1],[start3, end3]]) - """ - for y in to_be_removed_segments: - original_segments = original_segments[original_segments.eq(y).all(dim=1).logical_not()] - return original_segments - - -@torch.jit.script -def get_gap_segments(segments: torch.Tensor) -> torch.Tensor: - """ - Get the gap segments. - For example, - torch.Tensor([[start1, end1], [start2, end2], [start3, end3]]) -> torch.Tensor([[end1, start2], [end2, start3]]) - """ - segments = segments[segments[:, 0].sort()[1]] - return torch.column_stack((segments[:-1, 1], segments[1:, 0])) - - -@torch.jit.script -def filtering(speech_segments: torch.Tensor, per_args: Dict[str, float]) -> torch.Tensor: - """ - Filter out short non-speech and speech segments. - - Reference: - Paper: Gregory Gelly and Jean-Luc Gauvain. "Minimum Word Error Training of RNN-based Voice - Activity Detection", InterSpeech 2015. - Implementation: - https://github.com/pyannote/pyannote-audio/blob/master/pyannote/audio/utils/signal.py - - Args: - speech_segments (torch.Tensor): - A tensor of speech segments in the format - torch.Tensor([[start1, end1], [start2, end2]]). - per_args: - min_duration_on (float): - Threshold for short speech segment deletion. - min_duration_off (float): - Threshold for small non-speech deletion. - filter_speech_first (float): - Whether to perform short speech segment deletion first. Use 1.0 to represent True. - - Returns: - speech_segments (torch.Tensor): - A tensor of filtered speech segments in the format - torch.Tensor([[start1, end1], [start2, end2]]). - """ - if speech_segments.shape == torch.Size([0]): - return speech_segments - - min_duration_on = per_args.get('min_duration_on', 0.0) - min_duration_off = per_args.get('min_duration_off', 0.0) - filter_speech_first = per_args.get('filter_speech_first', 1.0) - - if filter_speech_first == 1.0: - # Filter out the shorter speech segments - if min_duration_on > 0.0: - speech_segments = filter_short_segments(speech_segments, min_duration_on) - # Filter out the shorter non-speech segments and return to be as speech segments - if min_duration_off > 0.0: - # Find non-speech segments - non_speech_segments = get_gap_segments(speech_segments) - # Find shorter non-speech segments - short_non_speech_segments = remove_segments( - non_speech_segments, filter_short_segments(non_speech_segments, min_duration_off) - ) - # Return shorter non-speech segments to be as speech segments - speech_segments = torch.cat((speech_segments, short_non_speech_segments), 0) - - # Merge the overlapped speech segments - speech_segments = merge_overlap_segment(speech_segments) - else: - if min_duration_off > 0.0: - # Find non-speech segments - non_speech_segments = get_gap_segments(speech_segments) - # Find shorter non-speech segments - short_non_speech_segments = remove_segments( - non_speech_segments, filter_short_segments(non_speech_segments, min_duration_off) - ) - - speech_segments = torch.cat((speech_segments, short_non_speech_segments), 0) - - # Merge the overlapped speech segments - speech_segments = merge_overlap_segment(speech_segments) - if min_duration_on > 0.0: - speech_segments = filter_short_segments(speech_segments, min_duration_on) - - return speech_segments - - -def prepare_gen_segment_table(sequence: torch.Tensor, per_args: dict) -> Tuple[str, dict]: - """ - Preparing for generating segment table. - """ - out_dir = per_args.get('out_dir', None) - - # calculate onset offset based on scale selection - per_args['onset'], per_args['offset'] = cal_vad_onset_offset( - per_args.get('scale', 'absolute'), per_args['onset'], per_args['offset'], sequence - ) - - # cast 'filter_speech_first' for torch.jit.script - if 'filter_speech_first' in per_args: - if per_args['filter_speech_first']: - per_args['filter_speech_first'] = 1.0 - else: - per_args['filter_speech_first'] = 0.0 - - per_args_float: Dict[str, float] = {} - for i in per_args: - if type(per_args[i]) == float or type(per_args[i]) == int: - per_args_float[i] = per_args[i] - - return out_dir, per_args_float - - -@torch.jit.script -def generate_vad_segment_table_per_tensor(sequence: torch.Tensor, per_args: Dict[str, float]) -> torch.Tensor: - """ - See description in generate_overlap_vad_seq. - Use this for single instance pipeline. - """ - UNIT_FRAME_LEN = 0.01 - - speech_segments = binarization(sequence, per_args) - speech_segments = filtering(speech_segments, per_args) - - if speech_segments.shape == torch.Size([0]): - return speech_segments - - speech_segments, _ = torch.sort(speech_segments, 0) - - dur = speech_segments[:, 1:2] - speech_segments[:, 0:1] + UNIT_FRAME_LEN - speech_segments = torch.column_stack((speech_segments, dur)) - - return speech_segments - - -def generate_vad_segment_table_per_file(pred_filepath: str, per_args: dict) -> str: - """ - A wrapper for generate_vad_segment_table_per_tensor - """ - sequence, name = load_tensor_from_file(pred_filepath) - out_dir, per_args_float = prepare_gen_segment_table(sequence, per_args) - - preds = generate_vad_segment_table_per_tensor(sequence, per_args_float) - ext = ".rttm" if per_args.get("use_rttm", False) else ".txt" - save_name = name + ext - save_path = os.path.join(out_dir, save_name) - - if preds.shape[0] == 0: - with open(save_path, "w", encoding='utf-8') as fp: - if per_args.get("use_rttm", False): - fp.write(f"SPEAKER 1 0 0 speech \n") - else: - fp.write(f"0 0 speech\n") - else: - with open(save_path, "w", encoding='utf-8') as fp: - for i in preds: - if per_args.get("use_rttm", False): - fp.write(f"SPEAKER {name} 1 {i[0]:.4f} {i[2]:.4f} speech \n") - else: - fp.write(f"{i[0]:.4f} {i[2]:.4f} speech\n") - - return save_path - - -def generate_vad_segment_table( - vad_pred_dir: str, - postprocessing_params: dict, - frame_length_in_sec: float, - num_workers: int, - out_dir: str = None, - use_rttm: bool = False, -) -> str: - """ - Convert frame level prediction to speech segment in start and end times format. - And save to csv file in rttm-like format - 0, 10, speech - 17,18, speech - Args: - vad_pred_dir (str): directory of prediction files to be processed. - postprocessing_params (dict): dictionary of thresholds for prediction score. - See details in binarization and filtering. - frame_length_in_sec (float): frame length. - out_dir (str): output dir of generated table/csv file. - num_workers(float): number of process for multiprocessing - Returns: - out_dir(str): directory of the generated table. - """ - - suffixes = ("frame", "mean", "median") - vad_pred_filepath_list = [os.path.join(vad_pred_dir, x) for x in os.listdir(vad_pred_dir) if x.endswith(suffixes)] - - if not out_dir: - out_dir_name = "seg_output" - for key in postprocessing_params: - out_dir_name = out_dir_name + "-" + str(key) + str(postprocessing_params[key]) - - out_dir = os.path.join(vad_pred_dir, out_dir_name) - - if not os.path.exists(out_dir): - os.mkdir(out_dir) - - per_args = { - "frame_length_in_sec": frame_length_in_sec, - "out_dir": out_dir, - "use_rttm": use_rttm, - } - per_args = {**per_args, **postprocessing_params} - num_workers = None - if num_workers is not None and num_workers > 1: - with multiprocessing.Pool(num_workers) as p: - inputs = zip(vad_pred_filepath_list, repeat(per_args)) - list( - tqdm( - p.imap(generate_vad_segment_table_per_file_star, inputs), - total=len(vad_pred_filepath_list), - desc='creating speech segments', - leave=True, - ) - ) - else: - for vad_pred_filepath in tqdm(vad_pred_filepath_list, desc='creating speech segments', leave=True): - generate_vad_segment_table_per_file(vad_pred_filepath, per_args) - - return out_dir - - -def generate_vad_segment_table_per_file_star(args): - """ - A workaround for tqdm with starmap of multiprocessing - """ - return generate_vad_segment_table_per_file(*args) - - -def vad_construct_pyannote_object_per_file( - vad_table_filepath: str, groundtruth_RTTM_file: str -) -> Tuple[Annotation, Annotation]: - """ - Construct a Pyannote object for evaluation. - Args: - vad_table_filepath(str) : path of vad rttm-like table. - groundtruth_RTTM_file(str): path of groundtruth rttm file. - Returns: - reference(pyannote.Annotation): groundtruth - hypothesis(pyannote.Annotation): prediction - """ - - pred = pd.read_csv(vad_table_filepath, sep=" ", header=None) - label = pd.read_csv(groundtruth_RTTM_file, sep=" ", delimiter=None, header=None) - label = label.rename(columns={3: "start", 4: "dur", 7: "speaker"}) - - # construct reference - reference = Annotation() - for index, row in label.iterrows(): - reference[Segment(row['start'], row['start'] + row['dur'])] = row['speaker'] - - # construct hypothsis - hypothesis = Annotation() - for index, row in pred.iterrows(): - hypothesis[Segment(float(row[0]), float(row[0]) + float(row[1]))] = 'Speech' - return reference, hypothesis - - -def get_parameter_grid(params: dict) -> list: - """ - Get the parameter grid given a dictionary of parameters. - """ - has_filter_speech_first = False - if 'filter_speech_first' in params: - filter_speech_first = params['filter_speech_first'] - has_filter_speech_first = True - params.pop("filter_speech_first") - - params_grid = list(ParameterGrid(params)) - - if has_filter_speech_first: - for i in params_grid: - i['filter_speech_first'] = filter_speech_first - return params_grid - - -def vad_tune_threshold_on_dev( - params: dict, - vad_pred: str, - groundtruth_RTTM: str, - result_file: str = "res", - vad_pred_method: str = "frame", - focus_metric: str = "DetER", - frame_length_in_sec: float = 0.01, - num_workers: int = 20, -) -> Tuple[dict, dict]: - """ - Tune thresholds on dev set. Return best thresholds which gives the lowest - detection error rate (DetER) in thresholds. - - Args: - params (dict): dictionary of parameters to be tuned on. - vad_pred_method (str): suffix of prediction file. Use to locate file. - Should be either in "frame", "mean" or "median". - groundtruth_RTTM_dir (str): Directory of ground-truth rttm files or a file contains the paths of them. - focus_metric (str): Metrics we care most when tuning threshold. Should be either in "DetER", "FA", "MISS" - frame_length_in_sec (float): Frame length. - num_workers (int): Number of workers. - Returns: - best_threshold (float): Threshold that gives lowest DetER. - """ - min_score = 100 - all_perf = {} - try: - check_if_param_valid(params) - except: - raise ValueError("Please check if the parameters are valid") - - paired_filenames, groundtruth_RTTM_dict, vad_pred_dict = pred_rttm_map(vad_pred, groundtruth_RTTM, vad_pred_method) - metric = detection.DetectionErrorRate() - params_grid = get_parameter_grid(params) - - for param in params_grid: - for i in param: - if type(param[i]) == np.float64 or type(param[i]) == np.int64: - param[i] = float(param[i]) - try: - # Generate speech segments by performing binarization on the VAD prediction according to param. - # Filter speech segments according to param and write the result to rttm-like table. - vad_table_dir = generate_vad_segment_table( - vad_pred, param, frame_length_in_sec=frame_length_in_sec, num_workers=num_workers - ) - # add reference and hypothesis to metrics - for filename in paired_filenames: - groundtruth_RTTM_file = groundtruth_RTTM_dict[filename] - vad_table_filepath = os.path.join(vad_table_dir, filename + ".txt") - reference, hypothesis = vad_construct_pyannote_object_per_file( - vad_table_filepath, groundtruth_RTTM_file - ) - metric(reference, hypothesis) # accumulation - - # delete tmp table files - shutil.rmtree(vad_table_dir, ignore_errors=True) - - report = metric.report(display=False) - DetER = report.iloc[[-1]][('detection error rate', '%')].item() - FA = report.iloc[[-1]][('false alarm', '%')].item() - MISS = report.iloc[[-1]][('miss', '%')].item() - - assert ( - focus_metric == "DetER" or focus_metric == "FA" or focus_metric == "MISS" - ), "Metric we care most should be only in 'DetER', 'FA' or 'MISS'!" - all_perf[str(param)] = {'DetER (%)': DetER, 'FA (%)': FA, 'MISS (%)': MISS} - logging.info(f"parameter {param}, {all_perf[str(param)] }") - - score = all_perf[str(param)][focus_metric + ' (%)'] - - del report - metric.reset() # reset internal accumulator - - # save results for analysis - with open(result_file + ".txt", "a", encoding='utf-8') as fp: - fp.write(f"{param}, {all_perf[str(param)] }\n") - - if score < min_score: - best_threshold = param - optimal_scores = all_perf[str(param)] - min_score = score - print("Current best", best_threshold, optimal_scores) - - except RuntimeError as e: - print(f"Pass {param}, with error {e}") - except pd.errors.EmptyDataError as e1: - print(f"Pass {param}, with error {e1}") - - return best_threshold, optimal_scores - - -def check_if_param_valid(params: dict) -> bool: - """ - Check if the parameters are valid. - """ - for i in params: - if i == "filter_speech_first": - if not type(params["filter_speech_first"]) == bool: - raise ValueError("Invalid inputs! filter_speech_first should be either True or False!") - elif i == "pad_onset": - continue - elif i == "pad_offset": - continue - else: - for j in params[i]: - if not j >= 0: - raise ValueError( - "Invalid inputs! All float parameters except pad_onset and pad_offset should be larger than 0!" - ) - - if not (all(i <= 1 for i in params['onset']) and all(i <= 1 for i in params['offset'])): - raise ValueError("Invalid inputs! The onset and offset thresholds should be in range [0, 1]!") - - return True - - -def pred_rttm_map(vad_pred: str, groundtruth_RTTM: str, vad_pred_method: str = "frame") -> Tuple[set, dict, dict]: - """ - Find paired files in vad_pred and groundtruth_RTTM - """ - groundtruth_RTTM_dict = {} - if os.path.isfile(groundtruth_RTTM): - with open(groundtruth_RTTM, "r", encoding='utf-8') as fp: - groundtruth_RTTM_files = fp.read().splitlines() - elif os.path.isdir(groundtruth_RTTM): - groundtruth_RTTM_files = glob.glob(os.path.join(groundtruth_RTTM, "*.rttm")) - else: - raise ValueError( - "groundtruth_RTTM should either be a directory contains rttm files or a file contains paths to them!" - ) - for f in groundtruth_RTTM_files: - filename = os.path.basename(f).rsplit(".", 1)[0] - groundtruth_RTTM_dict[filename] = f - - vad_pred_dict = {} - if os.path.isfile(vad_pred): - with open(vad_pred, "r", encoding='utf-8') as fp: - vad_pred_files = fp.read().splitlines() - elif os.path.isdir(vad_pred): - vad_pred_files = glob.glob(os.path.join(vad_pred, "*." + vad_pred_method)) - else: - raise ValueError( - "vad_pred should either be a directory containing vad pred files or a file contains paths to them!" - ) - for f in vad_pred_files: - filename = os.path.basename(f).rsplit(".", 1)[0] - vad_pred_dict[filename] = f - - paired_filenames = groundtruth_RTTM_dict.keys() & vad_pred_dict.keys() - return paired_filenames, groundtruth_RTTM_dict, vad_pred_dict - - -def plot( - path2audio_file: str, - path2_vad_pred: Optional[str] = None, - path2groundtruth_rttm: Optional[str] = None, - groundtruth_labels: Optional[str] = None, - sample_rate: int = 16000, - offset: float = 0, - duration: float = None, - threshold: float = None, - per_args: dict = None, - unit_frame_len: float = 0.01, - label_repeat: int = 1, - xticks_step: int = 5, -) -> ipd.Audio: - """ - Plot Audio and/or VAD output and/or groundtruth labels for visualization - Args: - path2audio_file (str): path to audio file. - path2_vad_pred (str): path to vad prediction file, - path2groundtruth_rttm(str): path to groundtruth RTTM file. - ground_truth_labels(str): a list of groundtruth label. - sample_rate (int): sample rate of audio file. - offset (float): offset in seconds. - duration (float): duration in seconds. - threshold (float): threshold for prediction score (from 0 to 1). - per_args(dict): a dict that stores the thresholds for postprocessing. - unit_frame_len (float): unit frame length in seconds for VAD predictions. - label_repeat (int): repeat the label for this number of times to match different - frame lengths in preds and labels. - xticks_step (int): step size for xticks. - """ - plt.figure(figsize=[20, 2]) - - audio, sample_rate = librosa.load( - path=path2audio_file, sr=sample_rate, mono=True, offset=offset, duration=duration - ) - dur = librosa.get_duration(y=audio, sr=sample_rate) - - time = np.arange(offset, offset + dur, unit_frame_len) - len_pred = int(dur / unit_frame_len) + 1 - - frame_snippet = None - if path2_vad_pred: - frame, _ = load_tensor_from_file(path2_vad_pred) - frame_snippet = frame[int(offset / unit_frame_len) : int((offset + dur) / unit_frame_len)] - len_pred = len(frame_snippet) - - ax1 = plt.subplot() - ax1.plot(np.arange(audio.size) / sample_rate, audio, 'gray') - ax1.set_xlim([0, int(dur) + 1]) - ax1.tick_params(axis='y', labelcolor='b') - ax1.set_ylabel('Signal') - ax1.set_ylim([-1, 1]) - ax2 = ax1.twinx() - - if threshold and per_args: - raise ValueError("threshold and per_args cannot be used at same time!") - if not threshold and not per_args: - raise ValueError("One and only one of threshold and per_args must have been used!") - - if threshold and frame_snippet is not None: - pred_snippet = np.where(frame_snippet >= threshold, 1, 0) - elif per_args and frame_snippet is not None: - _, per_args_float = prepare_gen_segment_table( - frame, per_args - ) # take whole frame here for calculating onset and offset - speech_segments = generate_vad_segment_table_per_tensor(frame, per_args_float) - pred = gen_pred_from_speech_segments(speech_segments, frame) - pred_snippet = pred[int(offset / unit_frame_len) : int((offset + dur) / unit_frame_len)] - else: - pred_snippet = None - - if path2groundtruth_rttm and path2groundtruth_rttm.endswith('.rttm'): - label = extract_labels(path2groundtruth_rttm, time) - elif groundtruth_labels: - label = [float(x) for x in groundtruth_labels] - if label_repeat > 1: - label = np.repeat(label, label_repeat) - label = label[int(offset / unit_frame_len) : int((offset + dur) / unit_frame_len)] - else: - label = None - - if label is not None: - ax2.plot(np.arange(len_pred) * unit_frame_len, label, 'r', label='label') - if pred_snippet is not None: - ax2.plot(np.arange(len_pred) * unit_frame_len, pred_snippet, 'b', label='pred') - if frame_snippet is not None: - ax2.plot(np.arange(len_pred) * unit_frame_len, frame_snippet, 'g--', label='speech prob') - - ax2.tick_params(axis='y', labelcolor='r') - ax2.legend(loc='lower right', shadow=True) - ax2.set_ylabel('Preds and Probas') - ax2.set_ylim([-0.1, 1.1]) - ax2.set_xticks(np.arange(0, int(dur) + 1, xticks_step)) - return ipd.Audio(audio, rate=sample_rate) - - -def gen_pred_from_speech_segments( - speech_segments: torch.Tensor, prob: float, shift_length_in_sec: float = 0.01 -) -> np.array: - """ - Generate prediction arrays like 000111000... from speech segments {[0,1][2,4]} - """ - pred = np.zeros(prob.shape) - speech_segments = [list(i) for i in speech_segments] - speech_segments.sort(key=lambda x: x[0]) - - for seg in speech_segments: - start = int(seg[0] / shift_length_in_sec) - end = int(seg[1] / shift_length_in_sec) - pred[start:end] = 1 - return pred - - -def extract_labels(path2ground_truth_label: str, time: list) -> list: - """ - Extract ground-truth label for given time period. - path2ground_truth_label (str): path of groundtruth RTTM file - time (list) : a list of array representing time period. - """ - - data = pd.read_csv(path2ground_truth_label, sep=r"\s+", delimiter=None, header=None) - data = data.rename(columns={3: "start", 4: "dur", 7: "speaker"}) - labels = [] - for pos in time: - line = data[(data["start"] <= pos) & (data["start"] + data["dur"] > pos)] - if len(line) >= 1: - labels.append(1) - else: - labels.append(0) - return labels - - -def generate_vad_frame_pred( - vad_model, - window_length_in_sec: float, - shift_length_in_sec: float, - manifest_vad_input: str, - out_dir: str, - use_feat: bool = False, -) -> str: - """ - Generate VAD frame level prediction and write to out_dir - """ - time_unit = int(window_length_in_sec / shift_length_in_sec) - trunc = int(time_unit / 2) - trunc_l = time_unit - trunc - all_len = 0 - - data = [] - with open(manifest_vad_input, 'r', encoding='utf-8') as f: - for line in f: - file = json.loads(line)['audio_filepath'].split("/")[-1] - data.append(file.split(".wav")[0]) - logging.info(f"Inference on {len(data)} audio files/json lines!") - - status = get_vad_stream_status(data) - for i, test_batch in enumerate(tqdm(vad_model.test_dataloader(), total=len(vad_model.test_dataloader()))): - test_batch = [x.to(vad_model.device) for x in test_batch] - with torch.amp.autocast(vad_model.device.type): - if use_feat: - log_probs = vad_model(processed_signal=test_batch[0], processed_signal_length=test_batch[1]) - else: - log_probs = vad_model(input_signal=test_batch[0], input_signal_length=test_batch[1]) - probs = torch.softmax(log_probs, dim=-1) - if len(probs.shape) == 3 and probs.shape[0] == 1: - # squeeze the batch dimension, since batch size is 1 for frame-VAD - probs = probs.squeeze(0) # [1,T,C] -> [T,C] - pred = probs[:, 1] - - if window_length_in_sec == 0: - to_save = pred - elif status[i] == 'start': - to_save = pred[:-trunc] - elif status[i] == 'next': - to_save = pred[trunc:-trunc_l] - elif status[i] == 'end': - to_save = pred[trunc_l:] - else: - to_save = pred - - to_save = to_save.cpu().tolist() - all_len += len(to_save) - outpath = os.path.join(out_dir, data[i] + ".frame") - with open(outpath, "a", encoding='utf-8') as fout: - for f in range(len(to_save)): - fout.write('{0:0.4f}\n'.format(to_save[f])) - - del test_batch - if status[i] == 'end' or status[i] == 'single': - logging.debug(f"Overall length of prediction of {data[i]} is {all_len}!") - all_len = 0 - return out_dir - - -def init_vad_model(model_path: str): - """ - Initiate VAD model with model path - """ - if model_path.endswith('.nemo'): - logging.info(f"Using local VAD model from {model_path}") - vad_model = EncDecClassificationModel.restore_from(restore_path=model_path) - elif model_path.endswith('.ckpt'): - vad_model = EncDecClassificationModel.load_from_checkpoint(checkpoint_path=model_path) - else: - logging.info(f"Using NGC cloud VAD model {model_path}") - vad_model = EncDecClassificationModel.from_pretrained(model_name=model_path) - return vad_model - - -def init_frame_vad_model(model_path: str): - """ - Initiate VAD model with model path - """ - if model_path.endswith('.nemo'): - logging.info(f"Using local VAD model from {model_path}") - vad_model = EncDecFrameClassificationModel.restore_from(restore_path=model_path) - elif model_path.endswith('.ckpt'): - vad_model = EncDecFrameClassificationModel.load_from_checkpoint(checkpoint_path=model_path) - else: - logging.info(f"Using NGC cloud VAD model {model_path}") - vad_model = EncDecFrameClassificationModel.from_pretrained(model_name=model_path) - return vad_model - - -def stitch_segmented_asr_output( - segmented_output_manifest: str, - speech_segments_tensor_dir: str = "speech_segments", - stitched_output_manifest: str = "asr_stitched_output_manifest.json", -) -> str: - """ - Stitch the prediction of speech segments. - """ - if not os.path.exists(speech_segments_tensor_dir): - os.mkdir(speech_segments_tensor_dir) - - segmented_output = [] - with open(segmented_output_manifest, 'r', encoding='utf-8') as f: - for line in f: - file = json.loads(line) - segmented_output.append(file) - - with open(stitched_output_manifest, 'w', encoding='utf-8') as fout: - speech_segments = torch.Tensor() - all_pred_text = "" - if len(segmented_output) > 1: - for i in range(1, len(segmented_output)): - start, end = ( - segmented_output[i - 1]['offset'], - segmented_output[i - 1]['offset'] + segmented_output[i - 1]['duration'], - ) - new_seg = torch.tensor([start, end]).unsqueeze(0) - speech_segments = torch.cat((speech_segments, new_seg), 0) - pred_text = segmented_output[i - 1]['pred_text'] - all_pred_text += pred_text - name = segmented_output[i - 1]['audio_filepath'].split("/")[-1].rsplit(".", 1)[0] - - if segmented_output[i - 1]['audio_filepath'] != segmented_output[i]['audio_filepath']: - - speech_segments_tensor_path = os.path.join(speech_segments_tensor_dir, name + '.pt') - torch.save(speech_segments, speech_segments_tensor_path) - meta = { - 'audio_filepath': segmented_output[i - 1]['audio_filepath'], - 'speech_segments_filepath': speech_segments_tensor_path, - 'pred_text': all_pred_text, - } - - json.dump(meta, fout) - fout.write('\n') - fout.flush() - speech_segments = torch.Tensor() - all_pred_text = "" - else: - all_pred_text += " " - else: - i = -1 - - start, end = segmented_output[i]['offset'], segmented_output[i]['offset'] + segmented_output[i]['duration'] - new_seg = torch.tensor([start, end]).unsqueeze(0) - speech_segments = torch.cat((speech_segments, new_seg), 0) - pred_text = segmented_output[i]['pred_text'] - all_pred_text += pred_text - name = segmented_output[i]['audio_filepath'].split("/")[-1].rsplit(".", 1)[0] - speech_segments_tensor_path = os.path.join(speech_segments_tensor_dir, name + '.pt') - torch.save(speech_segments, speech_segments_tensor_path) - - meta = { - 'audio_filepath': segmented_output[i]['audio_filepath'], - 'speech_segments_filepath': speech_segments_tensor_path, - 'pred_text': all_pred_text, - } - json.dump(meta, fout) - fout.write('\n') - fout.flush() - - logging.info( - f"Finish stitch segmented ASR output to {stitched_output_manifest}, " - f"the speech segments info has been stored in directory {speech_segments_tensor_dir}" - ) - return stitched_output_manifest - - -def construct_manifest_eval( - input_manifest: str, stitched_output_manifest: str, aligned_vad_asr_output_manifest: str = "vad_asr_out.json" -) -> str: - """ - Generate aligned manifest for evaluation. - Because some pure noise samples might not appear in stitched_output_manifest. - """ - stitched_output = dict() - with open(stitched_output_manifest, 'r', encoding='utf-8') as f: - for line in f: - file = json.loads(line) - stitched_output[file["audio_filepath"]] = file - - out = [] - with open(input_manifest, 'r', encoding='utf-8') as f: - for line in f: - file = json.loads(line) - sample = file["audio_filepath"] - if sample in stitched_output: - file["pred_text"] = stitched_output[sample]["pred_text"] - file["speech_segments_filepath"] = stitched_output[sample]["speech_segments_filepath"] - else: - file["pred_text"] = "" - file["speech_segments_filepath"] = "" - - out.append(file) - - with open(aligned_vad_asr_output_manifest, 'w', encoding='utf-8') as fout: - for i in out: - json.dump(i, fout) - fout.write('\n') - fout.flush() - - return aligned_vad_asr_output_manifest - - -def load_rttm_file(filepath: str) -> pd.DataFrame: - """ - Load rttm file and extract speech segments - """ - if not Path(filepath).exists(): - raise ValueError(f"File not found: {filepath}") - data = pd.read_csv(filepath, sep=r"\s+", delimiter=None, header=None) - data = data.rename(columns={3: "start", 4: "dur", 7: "speaker"}) - - data['start'] = data['start'].astype(float) - data['dur'] = data['dur'].astype(float) - data['end'] = data['start'] + data['dur'] - - data = data.sort_values(by=['start']) - data['segment'] = list(zip(data['start'], data['end'])) - - return data - - -def merge_intervals(intervals: List[List[float]]) -> List[List[float]]: - """ - Merge speech segments into non-overlapping segments - """ - intervals.sort(key=lambda x: x[0]) - merged = [] - for interval in intervals: - # if the list of merged intervals is empty or if the current - # interval does not overlap with the previous, simply append it. - if not merged or merged[-1][1] < interval[0]: - merged.append(interval) - else: - # otherwise, there is overlap, so we merge the current and previous - # intervals. - merged[-1][1] = max(merged[-1][1], interval[1]) - return merged - - -def load_speech_segments_from_rttm(rttm_file: str) -> List[List[float]]: - """ - load speech segments from rttm file, where each segment is represented - as [start, end] interval - """ - speech_segments = list(load_rttm_file(rttm_file)['segment']) - speech_segments = [list(x) for x in speech_segments] - speech_segments = merge_intervals(speech_segments) - return speech_segments - - -def load_speech_overlap_segments_from_rttm(rttm_file: str) -> Tuple[List[List[float]], List[List[float]]]: - """ - Load speech segments from RTTM file, merge and extract possible overlaps - - Args: - rttm_file (str): Path to RTTM file - - Returns: - merged (List[List[float]]): merged speech intervals without overlaps - overlaps (List[List[float]]): intervals with overlap speech - """ - speech_segments = list(load_rttm_file(rttm_file)['segment']) - speech_segments = [list(x) for x in speech_segments] - speech_segments.sort(key=lambda x: x[0]) # sort by start time - merged = [] - overlaps = [] - for interval in speech_segments: - # if the list of merged intervals is empty or if the current - # interval does not overlap with the previous, simply append it. - if not merged or merged[-1][1] < interval[0]: - merged.append(interval) - else: - # otherwise, there is overlap, so we merge the current and previous - # intervals. - overlaps.append([interval[0], min(merged[-1][1], interval[1])]) - merged[-1][1] = max(merged[-1][1], interval[1]) - return merged, overlaps - - -def get_nonspeech_segments( - speech_segments: List[List[float]], max_duration: Optional[float] = None -) -> List[List[float]]: - """ - Get non-speech segments from given speech segments and maximum duration - - Args: - speech_segments (List[List[float]]): speech segment intervals loaded by load_speech_segments() - max_duration (Optional[float]): maximum duration of the audio, used to calculate the last silence segment - - Returns: - nonspeech_segments (List[List[float]]): intervals of non-speech segments - """ - nonspeech_segments = [] - start = 0.0 - for sp_seg in speech_segments: - end = sp_seg[0] - nonspeech_segments.append([start, end]) - start = sp_seg[1] - - if max_duration is not None and start < max_duration: - nonspeech_segments.append([start, max_duration]) - - return nonspeech_segments - - -def get_frame_labels( - segments: List[List[float]], frame_length: float, offset: float, duration: float, as_str: bool = True -) -> str: - """ - Generate frame-level binary labels for audio, '0' for non-speech and '1' for speech - - Args: - segments (List[List[float]]): speech segments loaded by load_speech_segments_from_rttm - frame_length (float): frame length in seconds, e.g. 0.01 for 10ms frames - offset (float): Offset of the audio clip - duration (float): duration of the audio clip - """ - labels = [] - n_frames = int(np.ceil(duration / frame_length)) - sid = 0 - for i in range(n_frames): - t = offset + i * frame_length - while sid < len(segments) - 1 and segments[sid][1] < t: - sid += 1 - if segments[sid][1] != 0 and segments[sid][0] <= t <= segments[sid][1]: - labels.append(1) - else: - labels.append(0) - if as_str: - return ' '.join([str(x) for x in labels]) - return [float(x) for x in labels] - - -def plot_sample_from_rttm( - audio_file: str, - rttm_file: str, - max_duration: Optional[float] = None, - save_path: str = "", - show: bool = True, - offset: float = 0.0, - unit_frame_len: float = 0.01, -): - """ - Plot audio signal and frame-level labels from RTTM file - """ - plt.figure(figsize=[20, 2]) - - audio, sample_rate = librosa.load(path=audio_file, sr=16000, mono=True, offset=offset, duration=max_duration) - dur = librosa.get_duration(y=audio, sr=sample_rate) - - segments = load_speech_segments_from_rttm(rttm_file) - labels = get_frame_labels(segments, unit_frame_len, offset, dur) - labels = [float(x) for x in labels.split()] - - length = len(labels) - ax1 = plt.subplot() - ax1.set_title(audio_file) - ax1.plot(np.arange(audio.size) / sample_rate, audio, 'gray') - ax1.set_xlim([0, int(dur) + 1]) - ax1.tick_params(axis='y', labelcolor='b') - ax1.set_ylabel('Signal') - ax1.set_ylim([-1, 1]) - ax2 = ax1.twinx() - - ax2.plot(np.arange(length) * unit_frame_len, labels, 'r', label='label') - ax2.tick_params(axis='y', labelcolor='r') - ax2.legend(loc='lower right', shadow=True) - ax2.set_ylabel('Labels') - ax2.set_ylim([-0.1, 1.1]) - if show: - plt.show() - if save_path: - plt.savefig(save_path) - return ipd.Audio(audio, rate=16000) - - -def align_labels_to_frames(probs, labels, threshold=0.2): - """ - Aligns labels to frames when the frame length (e.g., 10ms) is different from the label length - (e.g., 20ms). The threshold 0.2 is not critical, as the actual ratio will always be close to an - integer unless using frame/label lengths that are not multiples of each other (e.g., 15ms frame - length and 20ms label length), which is not valid. The value 0.2 is chosen for easier unit testing. - - Args: - probs (List[float]): - List of probabilities. - labels (List[int]): - List of labels. - threshold (float): - Threshold for rounding the ratio to an integer. - - Returns: - labels (List[int]): - List of labels aligned to frames. - """ - frames_len = len(probs) - labels_len = len(labels) - probs = torch.tensor(probs).float() - labels = torch.tensor(labels).long() - - if frames_len < labels_len: - # pad labels with zeros until labels_len is a multiple of frames_len - ratio = labels_len / frames_len - res = labels_len % frames_len - if ( - ceil(ratio) - ratio < threshold - ): # e.g., ratio = 2.9, ceil(ratio) = 3, then we pad labels to make it a multiple of 3 - # pad labels with zeros until labels_max_len is a multiple of logits_max_len - labels = labels.tolist() - if len(labels) % ceil(ratio) != 0: - labels += [0] * (ceil(ratio) - len(labels) % ceil(ratio)) - labels = torch.tensor(labels).long() - labels = labels.view(-1, ceil(ratio)).amax(1) - return align_labels_to_frames(probs.tolist(), labels.long().tolist()) - # otherwise, truncate additional labels until labels_max_len is a multiple of logits_max_len - if res > 0: - labels = labels[:-res] - labels = labels.view(-1, floor(ratio)).amax(1) - return labels.long().tolist() - elif frames_len > labels_len: - # repeat labels until labels_len is a multiple of frames_len - ratio = frames_len / labels_len - res = frames_len % labels_len - if ceil(ratio) - ratio < threshold: - # e.g., ratio is 1.83, ceil(ratio) = 2, then we repeat labels - # to make it a multiple of 2, and discard the redundant labels - labels = labels.repeat_interleave(ceil(ratio), dim=0).long().tolist() - labels = labels[:frames_len] - else: - # e.g., ratio is 2.02, floor(ratio) = 2, then we repeat labels - # to make it a multiple of 2 and add additional labels - labels = labels.repeat_interleave(floor(ratio), dim=0).long().tolist() - if res > 0: - labels += labels[-res:] - return labels - else: - return labels.long().tolist() - - -def read_rttm_as_pyannote_object(rttm_file: str, speaker_override: Optional[str] = None) -> Annotation: - """ - Read rttm file and construct a Pyannote object. - Args: - rttm_file(str) : path of rttm file. - speaker_override(str) : if not None, all speakers will be replaced by this value. - Returns: - annotation(pyannote.Annotation): annotation object - """ - annotation = Annotation() - data = pd.read_csv(rttm_file, sep=r"\s+", delimiter=None, header=None) - data = data.rename(columns={3: "start", 4: "dur", 7: "speaker"}) - for index, row in data.iterrows(): - if speaker_override is not None: - annotation[Segment(row['start'], row['start'] + row['dur'])] = speaker_override - else: - annotation[Segment(row['start'], row['start'] + row['dur'])] = row['speaker'] - return annotation - - -def convert_labels_to_speech_segments(labels: List[float], frame_length_in_sec: float = 0.01): - """ - Convert a list of labels to a list of speech segments. - Args: - labels (List[float]): list of labels - frame_length_in_sec (float): frame length in seconds - Returns: - segments (List[Tuple[float, float]]): list of speech segments - """ - segments = [] - start = -1 - for i, label in enumerate(labels): - if label == 1: - if start == -1: - start = i * frame_length_in_sec - else: - if start > -1: - segments.append([start, (i - 1) * frame_length_in_sec]) - start = -1 - if start != -1: - segments.append([start, (len(labels) - 1) * frame_length_in_sec]) - return segments - - -def frame_vad_construct_pyannote_object_per_file( - prediction: Union[str, List[float]], groundtruth: Union[str, List[float]], frame_length_in_sec: float = 0.01 -) -> Tuple[Annotation, Annotation]: - """ - Construct a Pyannote object for evaluation. - Args: - prediction (str) : path of VAD predictions stored as RTTM or CSV-like txt. - groundtruth (str): path of groundtruth rttm file. - frame_length_in_sec(float): frame length in seconds - Returns: - reference(pyannote.Annotation): groundtruth - hypothesis(pyannote.Annotation): prediction - """ - - hypothesis = Annotation() - if isinstance(groundtruth, str) and prediction.endswith('.rttm'): - hypothesis = read_rttm_as_pyannote_object(prediction, speaker_override='speech') - elif isinstance(groundtruth, str) and prediction.endswith('.txt'): - pred = pd.read_csv(prediction, sep=" ", header=None) - for index, row in pred.iterrows(): - hypothesis[Segment(float(row[0]), float(row[0]) + float(row[1]))] = 'speech' - elif isinstance(groundtruth, list): - segments = convert_labels_to_speech_segments(prediction, frame_length_in_sec) - for segment in segments: - hypothesis[Segment(segment[0], segment[1])] = 'speech' - else: - raise ValueError('prediction must be a path to rttm file or a list of frame labels.') - - reference = Annotation() - if isinstance(groundtruth, str) and groundtruth.endswith('.rttm'): - reference = read_rttm_as_pyannote_object(groundtruth, speaker_override='speech') - elif isinstance(groundtruth, list): - segments = convert_labels_to_speech_segments(groundtruth, frame_length_in_sec) - for segment in segments: - reference[Segment(segment[0], segment[1])] = 'speech' - else: - raise ValueError('groundtruth must be a path to rttm file or a list of frame labels.') - return reference, hypothesis - - -def frame_vad_infer_load_manifest(cfg: DictConfig): - """ - Load manifest file and prepare label/rttm mapping - Args: - cfg: DictConfig object - Returns: - manifest_orig (List[Dict]): original manifest data - key_labels_map (Dict): mapping from unique_audio_name to its labels - key_rttm_map (Dict): mapping from unique_audio_name to its rttm file - """ - unique_audio_names = set() - key_labels_map = {} - key_rttm_map = {} - manifest_orig = [] - manifest_file = Path(cfg.input_manifest).absolute().as_posix() - with open(manifest_file, 'r') as fin: - for line in fin.readlines(): - entry = json.loads(line.strip()) - audio_filepath = get_full_path(audio_file=entry['audio_filepath'], manifest_file=manifest_file) - entry['audio_filepath'] = str(audio_filepath) - uniq_audio_name = Path(audio_filepath).stem - - if uniq_audio_name in unique_audio_names: - raise ValueError("Please make sure each line is with different audio_filepath! ") - else: - unique_audio_names.add(uniq_audio_name) - - manifest_orig.append(entry) - - if cfg.evaluate: - # always prefer RTTM labels if exist - rttm_key = "rttm_filepath" if "rttm_filepath" in entry else "rttm_file" - rttm_file = entry.get(rttm_key, None) - if rttm_file: - rttm_file = get_full_path(audio_file=rttm_file, manifest_file=manifest_file) - segments = load_speech_segments_from_rttm(rttm_file) - label_str = get_frame_labels( - segments=segments, - frame_length=cfg.vad.parameters.shift_length_in_sec, - duration=entry['duration'], - offset=entry['offset'], - ) - key_rttm_map[uniq_audio_name] = entry[rttm_key] - key_labels_map[uniq_audio_name] = [float(x) for x in label_str.split()] - elif entry.get("label", None) is not None: - key_labels_map[uniq_audio_name] = [float(x) for x in entry["label"].split()] - else: - raise ValueError("Must have either `label` or `rttm_filepath` in manifest when evaluate=True") - - return manifest_orig, key_labels_map, key_rttm_map - - -def frame_vad_eval_detection_error( - pred_dir: str, key_labels_map: dict, key_rttm_map: dict, key_pred_rttm_map: dict, frame_length_in_sec: float -): - """ - Perform evaluation on frame-VAD results - Args: - pred_dir: directory of frame-VAD prediction files with in `.frame` format - key_labels_map: dictionary of mapping each to its labels - key_rttm_map: dictionary of mapping each to its GROUNDTRUTH rttm file - key_pred_rttm_map: dictionary of mapping each to its PREDICTED rttm file - frame_length_in_sec: frame length in seconds, e.g. 0.02s - Returns: - auroc: AUROC score in 0~100% - report: Pyannote detection.DetectionErrorRate() report - """ - all_probs = [] - all_labels = [] - metric = detection.DetectionErrorRate() - key_probs_map = {} - predictions_list = list(Path(pred_dir).glob("*.frame")) - for frame_pred in tqdm(predictions_list, desc="Evaluating VAD results", total=len(predictions_list)): - pred_probs = [] - with frame_pred.open("r") as fin: - for line in fin.readlines(): - line = line.strip() - if not line: - continue - pred_probs.append(float(line)) - key = frame_pred.stem - key_probs_map[key] = pred_probs - key_labels_map[key] = align_labels_to_frames(probs=pred_probs, labels=key_labels_map[key]) - all_probs.extend(key_probs_map[key]) - all_labels.extend(key_labels_map[key]) - - if key in key_rttm_map: - groundtruth = key_rttm_map[key] - else: - groundtruth = key_labels_map[key] - - reference, hypothesis = frame_vad_construct_pyannote_object_per_file( - prediction=key_pred_rttm_map[key], - groundtruth=groundtruth, - frame_length_in_sec=frame_length_in_sec, - ) - metric(reference, hypothesis) - - auroc = roc_auc_score(y_true=all_labels, y_score=all_probs) - report = metric.report(display=False) - return auroc, report - - -def ts_vad_post_processing( - ts_vad_binary_vec: torch.Tensor, - cfg_vad_params: OmegaConf, - unit_10ms_frame_count: int = 8, - bypass_postprocessing: bool = False, -): - """ - Post-processing on diarization results using VAD style post-processing methods. - These post-processing methods are inspired by the following paper: - Medennikov, Ivan, et al. "Target-Speaker Voice Activity Detection: - a Novel Approach for Multi-Speaker Diarization in a Dinner Party Scenario." (2020). - - Args: - ts_vad_binary_vec (Tensor): - Sigmoid values of each frame and each speaker. - Dimension: (num_frames,) - cfg_vad_params (OmegaConf): - Configuration (omega config) of VAD parameters. - unit_10ms_frame_count (int, optional): - an integer indicating the number of 10ms frames in a unit. - For example, if unit_10ms_frame_count is 8, then each frame is 0.08 seconds. - bypass_postprocessing (bool, optional): - If True, diarization post-processing will be bypassed. - - Returns: - speech_segments (Tensor): - start and end of each speech segment. - Dimension: (num_segments, 2) - - Example: - tensor([[ 0.0000, 3.0400], - [ 6.0000, 6.0800], - ... - [587.3600, 591.0400], - [591.1200, 597.7600]]) - """ - ts_vad_binary_frames = torch.repeat_interleave(ts_vad_binary_vec, unit_10ms_frame_count) - if not bypass_postprocessing: - speech_segments = binarization(ts_vad_binary_frames, cfg_vad_params) - speech_segments = filtering(speech_segments, cfg_vad_params) - else: - cfg_vad_params.onset = 0.5 - cfg_vad_params.offset = 0.5 - cfg_vad_params.pad_onset = 0.0 - cfg_vad_params.pad_offset = 0.0 - speech_segments = binarization(ts_vad_binary_frames, cfg_vad_params) - return speech_segments - - -def predlist_to_timestamps( - batch_preds_list: List[torch.Tensor], - audio_rttm_map_dict: Dict[str, Dict[str, Union[float, int]]], - cfg_vad_params: OmegaConf, - unit_10ms_frame_count: int, - bypass_postprocessing: bool = False, - precision: int = 2, -) -> List[List[float]]: - """ - Converts floating point number tensor diarization results to timestamps using VAD style - post-processing methods. - - Args: - batch_preds_list (List[Tensor]): - Tensor diarization results for each sample. - Dimension: [(num_frames, num_speakers), ...] - audio_rttm_map_dict (Dict[str, Dict[str, Union[float, int]]]): - Dictionary mapping unique audio file names to their rttm file entries. - cfg_vad_params (OmegaConf): - Configuration (omega config) of VAD parameters. - unit_10ms_frame_count (int): - an integer indicating the number of 10ms frames in a unit. - For example, if unit_10ms_frame_count is 8, then each frame is 0.08 seconds. - bypass_postprocessing (bool, optional): - If True, diarization post-processing will be bypassed. - precision (int, optional): - The number of decimal places to round the timestamps. Defaults to 2. - - Returns: - total_speaker_timestamps (List[List[List[float]]]): - A list of lists of timestamp tensors for each session (utterance) - Levels: - - Session-level (uniq_id) [session1_list, session2_list,...] - - Segment-level: [[start1, end1], [start2, end2],...]] - - List of start and end timestamp [start, end] - """ - total_speaker_timestamps = [] - pp_message = "Binarization" if bypass_postprocessing else "Post-processing" - for sample_idx, (uniq_id, audio_rttm_values) in tqdm( - enumerate(audio_rttm_map_dict.items()), total=len(audio_rttm_map_dict), desc=pp_message - ): - offset = audio_rttm_values['offset'] - speaker_assign_mat = batch_preds_list[sample_idx].squeeze(dim=0) - speaker_timestamps = [[] for _ in range(speaker_assign_mat.shape[-1])] - for spk_id in range(speaker_assign_mat.shape[-1]): - ts_mat = ts_vad_post_processing( - speaker_assign_mat[:, spk_id], - cfg_vad_params=cfg_vad_params, - unit_10ms_frame_count=unit_10ms_frame_count, - bypass_postprocessing=bypass_postprocessing, - ) - ts_mat = ts_mat + offset - ts_seg_raw_list = ts_mat.tolist() - ts_seg_list = [[round(stt, precision), round(end, precision)] for (stt, end) in ts_seg_raw_list] - speaker_timestamps[spk_id].extend(ts_seg_list) - total_speaker_timestamps.append(speaker_timestamps) - return total_speaker_timestamps diff --git a/nemo/collections/asr/parts/utils/wfst_utils.py b/nemo/collections/asr/parts/utils/wfst_utils.py deleted file mode 100644 index d06493783ccca47cab357ab428f78513acfa761d..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/utils/wfst_utils.py +++ /dev/null @@ -1,1447 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os -import re -import tempfile -from abc import ABC, abstractmethod, abstractproperty -from collections import defaultdict, namedtuple -from dataclasses import dataclass -from enum import Enum -from pathlib import Path -from typing import Any, Dict, List, NamedTuple, Optional, Tuple, Union - -from nemo.utils import logging - - -TW_BREAK = "‡" - - -try: - import kaldifst - - # check that kaldifst package is not empty - # Note: lightning.pytorch.utilities.imports.package_available may not help here - kaldifst.StdVectorFst() - _KALDIFST_AVAILABLE = True -except (ImportError, ModuleNotFoundError, AttributeError): - _KALDIFST_AVAILABLE = False - - -try: - import graphviz - - _GRAPHVIZ_AVAILABLE = True -except (ImportError, ModuleNotFoundError): - _GRAPHVIZ_AVAILABLE = False - - -try: - import kaldilm - - _KALDILM_AVAILABLE = True -except (ImportError, ModuleNotFoundError): - _KALDILM_AVAILABLE = False - - -KALDIFST_INSTALLATION_MESSAGE = ( - "kaldifst is not installed or is installed incorrectly.\n" - "please run `pip install kaldifst` or `bash scripts/installers/install_riva_decoder.sh` to install." -) - - -GRAPHVIZ_INSTALLATION_MESSAGE = ( - "graphviz is not installed.\n" "please run `bash scripts/installers/install_graphviz.sh` to install." -) - - -KALDILM_INSTALLATION_MESSAGE = ( - "kaldilm is not installed.\n" - "please run `pip install kaldilm` or `bash scripts/installers/install_riva_decoder.sh` to install." -) - - -def _kaldifst_maybe_raise(): - if _KALDIFST_AVAILABLE is False: - raise ImportError(KALDIFST_INSTALLATION_MESSAGE) - - -def kaldifst_importer(): - """Import helper function that returns kaldifst package or raises ImportError exception.""" - _kaldifst_maybe_raise() - return kaldifst - - -def _graphviz_maybe_raise(): - if _GRAPHVIZ_AVAILABLE is False: - raise ImportError(GRAPHVIZ_INSTALLATION_MESSAGE) - - -def graphviz_importer(): - """Import helper function that returns graphviz package or raises ImportError exception.""" - _graphviz_maybe_raise() - return graphviz - - -def _kaldilm_maybe_raise(): - if _KALDILM_AVAILABLE is False: - raise ImportError(KALDILM_INSTALLATION_MESSAGE) - - -def kaldilm_importer(): - """Import helper function that returns kaldifst package or raises ImportError exception.""" - _kaldilm_maybe_raise() - return kaldilm - - -@dataclass -class LexiconUnit: - """A dataclass encapsulating the name of the language unit (e.g. wordpiece) and its mark (e.g. word begin).""" - - name: str - mark: str = "" - - -class Lexicon: - def __init__( - self, - wordid2tokenid: Dict[int, List[List[int]]], - id2word: Union[Dict[int, str], Dict[int, LexiconUnit]], - id2token: Union[Dict[int, str], Dict[int, LexiconUnit]], - disambig_pattern: str = re.compile(r"^#\d+$"), - ): - """ - Lexicon class which contains word-to-token-sequence, word-to-id, and token-to-id mappings. - - Args: - wordid2tokenid: - Lexicon. - Mapping from word_id to token1_id token2_id ... tokenN_id. - - id2word: - Word index. - Mapping from word_id to word_str. - - id2token: - Token index. - Mapping from token_id to token_str. - - disambig_pattern: - Pattern for disambiguation symbols. - """ - is_id2token_str = not isinstance(list(id2token.values())[0], LexiconUnit) - self.id2token = {k: LexiconUnit(v) for k, v in id2token.items()} if is_id2token_str else id2token - self.token2id = {v.name: k for k, v in self.id2token.items()} - is_id2word_str = not isinstance(list(id2word.values())[0], LexiconUnit) - self.id2word = {k: LexiconUnit(v) for k, v in id2word.items()} if is_id2word_str else id2word - self.word2id = {v.name: k for k, v in self.id2word.items()} - self.wordid2tokenid = wordid2tokenid - word2tokens = defaultdict(list) - for k, v in self.wordid2tokenid.items(): - word2tokens[self.id2word[k].name] += [[self.id2token[i].name for i in vp] for vp in v] - self.word2tokens = word2tokens - self.disambig_pattern = disambig_pattern - - max_disambig_id = -1 - num_disambigs = 0 - self.has_epsilon = False - self._default_disambig_mark = "disambig" - self._default_epsilon_mark = "epsilon" - self._default_epsilon_name = "" - for i, s in self.id2token.items(): - if self.disambig_pattern.match(s.name): - if is_id2token_str or not s.mark.startswith(self._default_disambig_mark): - s.mark = self._default_disambig_mark - if i > max_disambig_id: - max_disambig_id = i - num_disambigs += 1 - if s.name == self._default_epsilon_name or s.mark == self._default_epsilon_mark: - assert i == 0 - self.has_epsilon = True - self.max_disambig_id = max_disambig_id - self.num_disambigs = num_disambigs - - if is_id2word_str: - for i, s in self.id2word.items(): - if self.disambig_pattern.match(s.name): - s.mark = self._default_disambig_mark - elif s.name == self._default_epsilon_name: - s.mark == self._default_epsilon_mark - - def __iter__(self) -> Tuple[str, List[str]]: - for wordid, tokenid_list in self.wordid2tokenid.items(): - for tokenids in tokenid_list: - yield wordid, tokenids - - def __str__(self): - return str(self.word2tokens) - - @property - def token_ids(self) -> List[int]: - """Return a list of token IDs excluding those from - disambiguation symbols. - """ - ans = [] - for i, s in self.id2token.items(): - if not s.mark.startswith(self._default_epsilon_mark) and (not self.has_epsilon or i != 0): - ans.append(i) - ans.sort() - return ans - - -def arpa2fst(lm_path: str, attach_symbol_table: bool = True) -> 'kaldifst.StdVectorFst': - """ - Compiles an ARPA LM file into a grammar WFST (G.fst). - - Args: - lm_path: - Path to the ARPA LM file. - - attach_symbol_table: - Whether to attach the words for indices of the returned WFST. - - Returns: - Kaldi-type grammar WFST. - """ - _kaldifst_maybe_raise() - _kaldilm_maybe_raise() - - with tempfile.TemporaryDirectory() as tempdirname: - output_fst = os.path.join(tempdirname, "output.fst") - words_txt = os.path.join(tempdirname, "words.txt") - # with suppress_stdout_stderr(): - kaldilm.arpa2fst( - input_arpa=lm_path, - output_fst=output_fst, - disambig_symbol="#0", - write_symbol_table=words_txt, - ) - - G = kaldifst.StdVectorFst.read(output_fst) - - if attach_symbol_table: - osym = kaldifst.SymbolTable() - with open(words_txt, encoding="utf-8") as f: - for line in f: - w, i = line.strip().split() - osym.add_symbol(symbol=w, key=int(i)) - G.output_symbols = osym - - kaldifst.arcsort(G, sort_type="ilabel") - return G - - -def add_tokenwords_( - g_fst: 'kaldifst.StdVectorFst', - tokens: List[str], - word_weight: float = 2.0, - token_unigram_weight: float = 4.0, - token_oov: str = "", -) -> int: - """ - Adds special words representing individual tokens (tokenwords). - In-place operation. - - Args: - g_fst: - Kaldi-type grammar WFST. - Will be augmented with the tokenwords. - - tokens: - Token vocabulary. - - word_weight: - The weight of an Out Of Vocabulary (OOV) word emission. - - token_unigram_weight: - The weight of a tokenword emission. - - token_oov: - OOV token. - - Returns: - The id of the tokenword disambiguation token. - """ - _kaldifst_maybe_raise() - - unigram_state = 0 - # check if 0 is the unigram state (has no outgoing epsilon arcs) - assert kaldifst.ArcIterator(g_fst, unigram_state).value.ilabel not in (0, g_fst.output_symbols.find("#0")) - - # we put tokenword self-loops in a separate state wrapped with a tokenword_disambig token - tokenword_disambig_id = g_fst.output_symbols.available_key() - tokenword_disambig = "#1" - g_fst.output_symbols.add_symbol(tokenword_disambig, tokenword_disambig_id) - tokenword_state = g_fst.add_state() - # we keep olabel !=0 to mark tokenword segments in the recognition results - g_fst.add_arc( - state=unigram_state, - arc=kaldifst.StdArc( - ilabel=tokenword_disambig_id, - olabel=tokenword_disambig_id, - weight=word_weight, - nextstate=tokenword_state, - ), - ) - g_fst.add_arc( - state=tokenword_state, - arc=kaldifst.StdArc( - ilabel=tokenword_disambig_id, - olabel=tokenword_disambig_id, - weight=0.0, - nextstate=unigram_state, - ), - ) - label = tokenword_disambig_id + 1 - for t in tokens: - if t != token_oov: - g_fst.add_arc( - state=tokenword_state, - arc=kaldifst.StdArc( - ilabel=label, - olabel=label, - weight=token_unigram_weight, - nextstate=tokenword_state, - ), - ) - g_fst.output_symbols.add_symbol(f"{t}{TW_BREAK}{tokenword_disambig}", label) - label += 1 - - return tokenword_disambig_id - - -def generate_lexicon_sentencepiece( - tokenizer: 'TokenizerSpec', - id2word: Dict[int, str], - oov: str = "", - add_epsilon: bool = False, - first_tokenword_id: int = -1, - disambig_pattern: str = re.compile(r"^#\d+$"), -) -> Lexicon: - """ - Generate a Lexicon using a SentencePiece tokenizer. - - Args: - tokenizer: - NeMo SentencePiece tokenizer. - - id2word: - Word index. - Mapping from word_id to word_str. - - oov: - Out Of Vocabulary word in lexicon. - - Returns: - Lexicon object. - """ - word2id = {v: k for k, v in id2word.items()} - backoff_disambig = "#0" - tokenword_disambig = "#1" - word_begin_mark = "▁" - - tokenword_mode = first_tokenword_id != -1 - if tokenword_mode: - words, tokenwords = [], [] - for k, v in id2word.items(): - if disambig_pattern.match(v): - continue - words.append(v) if k < first_tokenword_id else tokenwords.append(v) - else: - words, tokenwords = [v for v in id2word.values() if not disambig_pattern.match(v)], [] - - # Use encode to avoid OOV tokens - words_piece_ids = tokenizer.encode(words, out_type=int) - - # tokenizer.get_vocab() gives indices starting with 1 - maybe_add_one = int(add_epsilon) - maybe_subtract_one = int(not add_epsilon) - vocab = tokenizer.get_vocab() - id2token = { - v - maybe_subtract_one: LexiconUnit(k, "begin" if k.startswith(word_begin_mark) else "") - for k, v in vocab.items() - } - - # Introduce unk, blank, and the first disambig ids - unk_id = tokenizer.piece_to_id(oov) + maybe_add_one - id2token[unk_id] = LexiconUnit(oov, "unk") - # We assume blank to have the last output id of the neural network output - max_token_id = max(id2token.keys()) - id2token[max_token_id + 1] = LexiconUnit("", "blank") - id2token[max_token_id + 2] = LexiconUnit(backoff_disambig, "disambig_backoff") - if tokenword_mode: - id2token[max_token_id + 3] = LexiconUnit(tokenword_disambig, "disambig_tokenword") - if add_epsilon: - # insert first - id2token[0] = LexiconUnit("", "epsilon") - id2token = {k: v for k, v in sorted(id2token.items(), key=lambda item: item[0])} - - if tokenword_mode: - words += tokenwords - words_piece_ids += [[vocab[tw.rstrip(f"{TW_BREAK}{tokenword_disambig}")] - maybe_add_one] for tw in tokenwords] - - wordid2tokenid = defaultdict(list) - - for word, piece_ids in zip(words, words_piece_ids): - if word.startswith("<") and word != "": # not a real word, probably some tag - continue - elif word == "": # we do not need to tokelize - continue - else: - wordid2tokenid[word2id[word]].append([p + maybe_add_one for p in piece_ids]) - - lexicon = Lexicon(wordid2tokenid, id2word, id2token) - # state disambig purpose explicitly for further use - lexicon.id2word[lexicon.word2id[backoff_disambig]].mark = "disambig_backoff" - if tokenword_mode: - lexicon.id2word[lexicon.word2id[tokenword_disambig]].mark = "disambig_tokenword" - for tw in tokenwords: - lexicon.id2word[lexicon.word2id[tw]].mark = "tokenword" - return lexicon - - -def add_disambig_symbols(lexicon: Lexicon) -> Lexicon: - """ - Adds pseudo-token disambiguation symbols #1, #2 and so on - at the ends of tokens to ensure that all pronunciations are different, - and that none is a prefix of another. - - See also add_lex_disambig.pl from kaldi. - - Args: - lexicon: - Lexicon object. - - Returns: - Return Lexicon augmented with subseqence disambiguation symbols. - """ - - tokenword_mode = "#1" in lexicon.word2id - if tokenword_mode: - first_tokenword_id = lexicon.word2id["#1"] + 1 - last_used_disambig_id = lexicon.token2id["#1"] - else: - last_used_disambig_id = lexicon.token2id["#0"] - - # (1) Work out the count of each token-sequence in the lexicon. - count = defaultdict(int) - for _, token_ids in lexicon: - count[tuple(token_ids)] += 1 - - # (2) For each left sub-sequence of each token-sequence, note down - # that it exists (for identifying prefixes of longer strings). - issubseq = defaultdict(int) - for word_id, token_ids in lexicon: - if tokenword_mode and word_id >= first_tokenword_id: - continue - token_ids = token_ids.copy() - token_ids.pop() - while token_ids: - issubseq[tuple(token_ids)] = 1 - token_ids.pop() - - # (3) For each entry in the lexicon: - # if the token sequence is unique and is not a - # prefix of another word, no disambig symbol. - # Else output #1, or #2, #3, ... if the same token-seq - # has already been assigned a disambig symbol. - wordid2tokenid = defaultdict(list) - id2token = lexicon.id2token.copy() - - first_allowed_disambig = lexicon.num_disambigs - first_allowed_disambig_id = last_used_disambig_id + 1 - max_disambig = first_allowed_disambig - 1 - last_used_disambig_id_of = defaultdict(int) - - for word_id, token_ids in lexicon: - token_key = tuple(token_ids) - assert len(token_key) > 0 - if issubseq[token_key] == 0 and count[token_key] == 1 or tokenword_mode and word_id >= first_tokenword_id: - wordid2tokenid[word_id].append(token_ids) - continue - - cur_disambig_id = last_used_disambig_id_of[token_key] - if cur_disambig_id == 0: - cur_disambig = first_allowed_disambig - cur_disambig_id = first_allowed_disambig_id - else: - cur_disambig = int(id2token[cur_disambig_id].name.lstrip("#")) + 1 - - if cur_disambig > max_disambig: - max_disambig = cur_disambig - cur_disambig_id = max(id2token.keys()) + 1 - id2token[cur_disambig_id] = LexiconUnit(f"#{max_disambig}", "disambig_subsequence") - last_used_disambig_id_of[token_key] = cur_disambig_id - wordid2tokenid[word_id].append(token_ids + [cur_disambig_id]) - return Lexicon(wordid2tokenid, lexicon.id2word, id2token) - - -def make_lexicon_fst_no_silence( - lexicon: Lexicon, - attach_symbol_table: bool = True, -) -> 'kaldifst.StdVectorFst': - """ - Compiles a Lexicon into a lexicon WFST (L.fst). - - See also make_lexicon_fst.py from kaldi. - - Args: - lexicon: - Lexicon object. - - Returns: - Kaldi-type lexicon WFST. - """ - _kaldifst_maybe_raise() - - backoff_disambig = "#0" - tokenword_disambig = "#1" - tokenword_mode = tokenword_disambig in lexicon.word2id - if tokenword_mode: - first_tokenword_id = lexicon.word2id[tokenword_disambig] + 1 - - fst = kaldifst.StdVectorFst() - start_state = fst.add_state() - fst.start = start_state - fst.set_final(state=start_state, weight=0) - fst.add_arc( - state=start_state, - arc=kaldifst.StdArc( - ilabel=lexicon.token2id[backoff_disambig], - olabel=lexicon.word2id[backoff_disambig], - weight=0, - nextstate=start_state, - ), - ) - if tokenword_mode: - tokenword_state_begin = fst.add_state() - fst.add_arc( - state=start_state, - arc=kaldifst.StdArc( - ilabel=lexicon.token2id[tokenword_disambig], - olabel=lexicon.word2id[tokenword_disambig], - weight=0, - nextstate=tokenword_state_begin, - ), - ) - - for word_id, token_ids in lexicon: - cur_state = start_state - - if not tokenword_mode or word_id < first_tokenword_id - 1: - for i, token_id in enumerate(token_ids[:-1]): - next_state = fst.add_state() - fst.add_arc( - state=cur_state, - arc=kaldifst.StdArc( - ilabel=token_id, - olabel=word_id if i == 0 else 0, - weight=0, - nextstate=next_state, - ), - ) - cur_state = next_state - i = len(token_ids) - 1 # note: i == -1 if tokens is empty. - fst.add_arc( - state=cur_state, - arc=kaldifst.StdArc( - ilabel=token_ids[-1] if i >= 0 else 0, - olabel=word_id if i <= 0 else 0, - weight=0, - nextstate=start_state, - ), - ) - if tokenword_mode: - tokenword_begin, tokenword_other = [], [] - for word_id in range(first_tokenword_id, max(lexicon.id2word) + 1): - token_id = lexicon.token2id[lexicon.id2word[word_id].name.rstrip(f"{TW_BREAK}{tokenword_disambig}")] - token_unit = lexicon.id2token[token_id] - if token_unit.mark.startswith("begin"): - tokenword_begin.append((token_id, word_id)) - elif token_unit.mark == "": - tokenword_other.append((token_id, word_id)) - else: - raise RuntimeError(f"Unexpected mark `{token_unit.mark}` for tokenword `{token_unit.name}`") - - tokenword_state_main = fst.add_state() - for token_id, word_id in tokenword_begin: - fst.add_arc( - state=tokenword_state_begin, - arc=kaldifst.StdArc( - ilabel=token_id, - olabel=word_id, - weight=0, - nextstate=tokenword_state_main, - ), - ) - tokenword_state_end = fst.add_state() - for token_id, word_id in tokenword_other: - fst.add_arc( - state=tokenword_state_main, - arc=kaldifst.StdArc( - ilabel=token_id, - olabel=word_id, - weight=0, - nextstate=tokenword_state_main, - ), - ) - fst.add_arc( - state=tokenword_state_main, - arc=kaldifst.StdArc( - ilabel=token_id, - olabel=word_id, - weight=0, - nextstate=tokenword_state_end, - ), - ) - fst.add_arc( - state=tokenword_state_end, - arc=kaldifst.StdArc( - ilabel=lexicon.token2id[tokenword_disambig], - olabel=lexicon.word2id[tokenword_disambig], - weight=0, - nextstate=start_state, - ), - ) - - if attach_symbol_table: - isym = kaldifst.SymbolTable() - for p, i in lexicon.token2id.items(): - isym.add_symbol(symbol=p, key=i) - fst.input_symbols = isym - - osym = kaldifst.SymbolTable() - for w, i in lexicon.word2id.items(): - osym.add_symbol(symbol=w, key=i) - fst.output_symbols = osym - - kaldifst.arcsort(fst, sort_type="ilabel") - return fst - - -def build_topo( - name: str, token2id: Dict[str, int], with_self_loops: bool = True, attach_symbol_table: bool = True -) -> 'kaldifst.StdVectorFst': - """Helper function to build a topology WFST (T.fst). - - Args: - name: - Topology name. Choices: default, compact, minimal - - token2id: - Token index. - Mapping from token_str to token_id. - - with_self_loops: - Whether to add token-to-epsilon self-loops to the topology. - - attach_symbol_table: - Whether to attach the token names for indices of the returned WFST. - - Returns: - Kaldi-type topology WFST. - """ - _kaldifst_maybe_raise() - - if name == "default": - fst = build_default_topo(token2id, with_self_loops) - elif name == "compact": - fst = build_compact_topo(token2id, with_self_loops) - elif name == "minimal": - fst = build_minimal_topo(token2id) - else: - raise ValueError(f"Unknown topo name: {name}") - - if attach_symbol_table: - isym = kaldifst.SymbolTable() - for t, i in token2id.items(): - isym.add_symbol(symbol=t, key=i) - fst.input_symbols = isym - fst.output_symbols = fst.input_symbols.copy() - return fst - - -def build_default_topo(token2id: Dict[str, int], with_self_loops: bool = True) -> 'kaldifst.StdVectorFst': - """Build the default (correct) CTC topology.""" - _kaldifst_maybe_raise() - - disambig_pattern = re.compile(r"^#\d+$") - blank_id = token2id[""] - fst = kaldifst.StdVectorFst() - start_state = fst.add_state() - fst.start = start_state - fst.set_final(state=start_state, weight=0) - fst.add_arc( - state=start_state, - arc=kaldifst.StdArc( - ilabel=blank_id, - olabel=0, - weight=0, - nextstate=start_state, # token2id[""] is always 0 - ), - ) - - disambig_ids = [] - token_ids = {} - for s, i in token2id.items(): - if s == "" or s == "": - continue - elif disambig_pattern.match(s): - disambig_ids.append(i) - else: - state = fst.add_state() - fst.set_final(state=state, weight=0) - token_ids[state] = i - fst.add_arc( - state=start_state, - arc=kaldifst.StdArc( - ilabel=i, - olabel=i, - weight=0, - nextstate=state, - ), - ) - if with_self_loops: - fst.add_arc( - state=state, - arc=kaldifst.StdArc( - ilabel=i, - olabel=0, - weight=0, - nextstate=state, # token2id[""] is always 0 - ), - ) - fst.add_arc( - state=state, - arc=kaldifst.StdArc( - ilabel=blank_id, - olabel=0, - weight=0, - nextstate=start_state, # token2id[""] is always 0 - ), - ) - - for istate in kaldifst.StateIterator(fst): - if istate > 0: - for ostate in kaldifst.StateIterator(fst): - if ostate > 0 and istate != ostate: - label = token_ids[ostate] - fst.add_arc( - state=istate, - arc=kaldifst.StdArc( - ilabel=label, - olabel=label, - weight=0, - nextstate=ostate, - ), - ) - for disambig_id in disambig_ids: - fst.add_arc( - state=istate, - arc=kaldifst.StdArc( - ilabel=0, - olabel=disambig_id, - weight=0, - nextstate=istate, # token2id[""] is always 0 - ), - ) - - return fst - - -def build_compact_topo(token2id: Dict[str, int], with_self_loops: bool = True) -> 'kaldifst.StdVectorFst': - """Build the Compact CTC topology.""" - _kaldifst_maybe_raise() - - disambig_pattern = re.compile(r"^#\d+$") - blank_id = token2id[""] - fst = kaldifst.StdVectorFst() - start_state = fst.add_state() - fst.start = start_state - fst.set_final(state=start_state, weight=0) - fst.add_arc( - state=start_state, - arc=kaldifst.StdArc( - ilabel=blank_id, - olabel=0, - weight=0, - nextstate=start_state, # token2id[""] is always 0 - ), - ) - - for s, i in token2id.items(): - if s == "" or s == "": - continue - elif disambig_pattern.match(s): - fst.add_arc( - state=start_state, - arc=kaldifst.StdArc( - ilabel=0, - olabel=i, - weight=0, - nextstate=start_state, # token2id[""] is always 0 - ), - ) - else: - state = fst.add_state() - fst.add_arc( - state=start_state, - arc=kaldifst.StdArc( - ilabel=i, - olabel=i, - weight=0, - nextstate=state, - ), - ) - if with_self_loops: - fst.add_arc( - state=state, - arc=kaldifst.StdArc( - ilabel=i, - olabel=0, - weight=0, - nextstate=state, # token2id[""] is always 0 - ), - ) - fst.add_arc( - state=state, - arc=kaldifst.StdArc( - ilabel=0, # token2id[""] is always 0 - olabel=0, # token2id[""] is always 0 - weight=0, - nextstate=start_state, - ), - ) - - return fst - - -def build_minimal_topo(token2id: Dict[str, int]) -> 'kaldifst.StdVectorFst': - """Build the Minimal CTC topology.""" - _kaldifst_maybe_raise() - - disambig_pattern = re.compile(r"^#\d+$") - blank_id = token2id[""] - fst = kaldifst.StdVectorFst() - start_state = fst.add_state() - fst.start = start_state - fst.set_final(state=start_state, weight=0) - fst.add_arc( - state=start_state, - arc=kaldifst.StdArc( - ilabel=blank_id, - olabel=0, - weight=0, - nextstate=start_state, # token2id[""] is always 0 - ), - ) - - for s, i in token2id.items(): - if s == "" or s == "": - continue - elif disambig_pattern.match(s): - fst.add_arc( - state=start_state, - arc=kaldifst.StdArc( - ilabel=0, - olabel=i, - weight=0, - nextstate=start_state, # token2id[""] is always 0 - ), - ) - else: - fst.add_arc( - state=start_state, - arc=kaldifst.StdArc( - ilabel=i, - olabel=i, - weight=0, - nextstate=start_state, - ), - ) - - return fst - - -def mkgraph_ctc_ov( - tokenizer: 'TokenizerSpec', - lm_path: Union[Path, str], - topology_name: str = "default", - write_tlg_path: Optional[Union[Path, str]] = None, - open_vocabulary: bool = False, - open_vocabulary_weights: Tuple[float, float] = (2.0, 4.0), - target: str = "kaldi", -) -> Tuple['kaldifst.StdVectorFst', int]: - """ - Builds a decoding WFST (TLG.fst or TLG.pt). - - See also mkgraph.sh from kaldi. - - Args: - tokenizer: - NeMo SentencePiece tokenizer. - - lm_path: - Path to the ARPA LM file. - - topology_name: - Topology name. Choices: default, compact, minimal. - - write_tlg_path: - Where to buffer the TLG. - - open_vocabulary: - Whether to build a decoding WFST suitable for the open vocabulary decoding. - - open_vocabulary_weights: - Pair of weights (oov_word_weight, token_unigram_weight). - - target: - What type to build the WFST for. Choices: kaldi. - - Returns: - A pair of kaldi-type decoding WFST and its id of the tokenword disambiguation token. - """ - _kaldifst_maybe_raise() - - logging.info("Compiling G.fst ...") - G = arpa2fst(lm_path) - if open_vocabulary: - # in-place for g_fst - tokenword_disambig_id = add_tokenwords_( - g_fst=G, - tokens=tokenizer.tokenizer.get_vocab().keys(), - word_weight=open_vocabulary_weights[0], - token_unigram_weight=open_vocabulary_weights[1], - ) - else: - tokenword_disambig_id = -1 - - logging.info("Building L.fst ...") - id2word = {int(line.split("\t")[1]): line.split("\t")[0] for line in str(G.output_symbols).strip().split("\n")} - lexicon = generate_lexicon_sentencepiece( - tokenizer.tokenizer, id2word, add_epsilon=True, first_tokenword_id=tokenword_disambig_id - ) - lexicon_disambig = add_disambig_symbols(lexicon) - - L = make_lexicon_fst_no_silence(lexicon_disambig) - kaldifst.arcsort(L, sort_type="olabel") - - logging.info("Building LG.fst ...") - LG = kaldifst.compose(L, G) - kaldifst.determinize_star(LG) - kaldifst.minimize_encoded(LG) - kaldifst.arcsort(LG, sort_type="ilabel") - - logging.info("Building TLG.fst ...") - T = build_topo(topology_name, lexicon_disambig.token2id) - kaldifst.arcsort(T, sort_type="olabel") - TLG = kaldifst.compose(T, LG) - - if target == "kaldi": - if write_tlg_path: - logging.info(f"Buffering TLG.fst into {write_tlg_path} ...") - TLG.write(write_tlg_path) - else: - raise ValueError(f"Unsupported target: `{target}`") - - return TLG, tokenword_disambig_id - - -class KaldiFstMask(Enum): - Acceptor = 65536 - Error = 4 - TopSorted = 274877906944 - Acyclic = 34359738368 - IlabelSorted = 268435456 - OlabelSorted = 1073741824 - IlabelDeterministic = 262144 - OlabelDeterministic = 1048576 - HasEpsilons = 4194304 - HasIEpsilons = 16777216 - Accessible = 1099511627776 - Coaccessible = 4398046511104 - Weighted = 4294967296 - - -class LatticeProperties(NamedTuple): - Acceptor: bool - Valid: bool - Nonempty: bool - TopSorted: bool - Acyclic: bool - ArcSorted: bool - Deterministic: bool - EpsilonFree: bool - InputEpsilonFree: bool - Connected: bool - Weighted: bool - - -class AbstractLattice(ABC): - """A lattice wrapper with high-level capabilities.""" - - def __init__(self, lattice: Any): - self._lattice = lattice - self._properties = None - - @abstractmethod - def as_tensor(self) -> 'torch.Tensor': - """Represents the lattice as a tensor. - - Returns: - torch.Tensor - """ - pass - - @abstractmethod - def draw( - self, filename: Optional[Union[Path, str]] = None, title: Optional[Union[Path, str]] = None, zoom: float = 1.0 - ) -> Union['graphviz.Digraph', 'IPython.display.HTML']: - """Render FSA as an image via graphviz, and return the Digraph object; and optionally save to file filename. - filename must have a suffix that graphviz understands, such as pdf, svg or png. - - Note: - You need to install graphviz to use this function:: - - ./scripts/installers/install_graphviz.sh - - Args: - filename: - Filename to (optionally) save to, e.g. ‘foo.png’, ‘foo.svg’, ‘foo.png’. - - title: - Title to be displayed in image, e.g. ‘A simple lattice example’. - - zoom: - Zoom-in lattice in IPython notebook (needed for large lattices). - - Returns: - graphviz.Digraph or IPython.display.HTML - """ - pass - - @abstractmethod - def edit_distance(self, reference_sequence: List[int]) -> int: - """Get the edit distance from a reference sequence to the lattice. - - Args: - reference_sequence: - List of word- or token-ids. - - Returns: - Number of edits. - """ - - @property - def lattice(self): - self._properties = None - return self._lattice - - @abstractproperty - def properties(self) -> LatticeProperties: - pass - - @abstractproperty - def symbol_table(self) -> Optional[Dict[int, str]]: - pass - - @abstractproperty - def auxiliary_tables(self) -> Optional[Tuple[Any]]: - pass - - -class KaldiWordLattice(AbstractLattice): - """A Kaldi lattice wrapper with high-level capabilities.""" - - def __init__( - self, - lattice: 'kaldifst.Lattice', - symbol_table: Optional[Dict[int, str]] = None, - auxiliary_tables: Optional[Dict[str, Any]] = None, - ): - _kaldifst_maybe_raise() - - if not isinstance(lattice, kaldifst.Lattice): - raise ValueError(f"Wrong lattice type: `{type(lattice)}`") - super().__init__(lattice) - - kaldi_symbols2dict = lambda symbols: { - int(line.split("\t")[1]): line.split("\t")[0] for line in str(symbols).strip().split("\n") - } - self._symbol_table = None - # most likely lattice will have empty input_symbols - if symbol_table is not None: - self._symbol_table = symbol_table - elif self._lattice.output_symbols is not None: - # we suppose that lattice.input_symbols will not be changed - self._symbol_table = kaldi_symbols2dict(self._lattice.output_symbols) - - self._auxiliary_tables = None - if auxiliary_tables is not None: - attributes, values = list(auxiliary_tables.keys()), list(auxiliary_tables.values()) - if "input_symbols" not in attributes and self._lattice.input_symbols is not None: - # rare but possible case - attributes.append("input_symbols") - values.append(kaldi_symbols2dict(self._lattice.input_symbols)) - self._auxiliary_tables = namedtuple("KaldiAuxiliaryTables", attributes)(*values) - elif self._lattice.input_symbols is not None: - self._auxiliary_tables = namedtuple("KaldiAuxiliaryTables", "input_symbols")( - kaldi_symbols2dict(self._lattice.input_symbols) - ) - - @property - def properties(self) -> LatticeProperties: - if self._properties is None: - acceptor = self._lattice.properties(KaldiFstMask.Acceptor.value, True) == KaldiFstMask.Acceptor.value - valid = self._lattice.properties(KaldiFstMask.Error.value, True) != KaldiFstMask.Error.value - nonempty = self._lattice.num_states > 0 - top_sorted = self._lattice.properties(KaldiFstMask.TopSorted.value, True) == KaldiFstMask.TopSorted.value - acyclic = self._lattice.properties(KaldiFstMask.Acyclic.value, True) == KaldiFstMask.Acyclic.value - arc_sorted = ( - self._lattice.properties(KaldiFstMask.IlabelSorted.value, True) == KaldiFstMask.IlabelSorted.value - and self._lattice.properties(KaldiFstMask.OlabelSorted.value, True) == KaldiFstMask.OlabelSorted.value - ) - deterministic = ( - self._lattice.properties(KaldiFstMask.IlabelDeterministic.value, True) - == KaldiFstMask.IlabelDeterministic.value - and self._lattice.properties(KaldiFstMask.OlabelDeterministic.value, True) - == KaldiFstMask.OlabelDeterministic.value - ) - epsilon_free = ( - self._lattice.properties(KaldiFstMask.HasEpsilons.value, True) != KaldiFstMask.HasEpsilons.value - ) - input_epsilon_free = ( - self._lattice.properties(KaldiFstMask.HasIEpsilons.value, True) != KaldiFstMask.HasIEpsilons.value - ) - connected = ( - self._lattice.properties(KaldiFstMask.Accessible.value, True) == KaldiFstMask.Accessible.value - and self._lattice.properties(KaldiFstMask.Coaccessible.value, True) == KaldiFstMask.Coaccessible.value - ) - weighted = self._lattice.properties(KaldiFstMask.Weighted.value, True) == KaldiFstMask.Weighted.value - self._properties = LatticeProperties( - Acceptor=acceptor, - Valid=valid, - Nonempty=nonempty, - TopSorted=top_sorted, - Acyclic=acyclic, - ArcSorted=arc_sorted, - Deterministic=deterministic, - EpsilonFree=epsilon_free, - InputEpsilonFree=input_epsilon_free, - Connected=connected, - Weighted=weighted, - ) - return self._properties - - @property - def symbol_table(self) -> Optional[Dict[int, str]]: - return self._symbol_table - - @property - def auxiliary_tables(self) -> Optional[Tuple[Any]]: - return self._auxiliary_tables - - def as_tensor(self) -> 'torch.Tensor': - """Represents the lattice as a tensor. - - Returns: - torch.Tensor - """ - raise NotImplementedError("Tensor representation is not supported yet.") - - def edit_distance(self, reference_sequence: List[int]) -> int: - """Get the edit distance from a reference sequence to the lattice. - - Args: - reference_sequence: - List of word- or token-ids. - - Returns: - Number of edits. - """ - _kaldifst_maybe_raise() - - if not self.properties.InputEpsilonFree: - logging.warning(f"Lattice contains input epsilons. Edit distance calculations may not be accurate.") - if not all(reference_sequence): - raise ValueError(f"reference_sequence contains zeros, which is not allowed.") - ref = levenshtein_graph_kaldi(kaldifst.make_linear_acceptor(reference_sequence)) - hyp = levenshtein_graph_kaldi(self._lattice) - kaldifst.invert(hyp) - ali_fst = kaldifst.compose(hyp, ref) - succeeded, _, _, total_weight = kaldifst.get_linear_symbol_sequence(kaldifst.shortest_path(ali_fst)) - if not succeeded: - raise RuntimeError("Something went wrong while calculating edit_distance. Please check input manually.") - return round(total_weight.value) - - def draw( - self, filename: Optional[Union[Path, str]] = None, title: Optional[Union[Path, str]] = None, zoom: float = 1.0 - ) -> Union['graphviz.Digraph', 'IPython.display.HTML']: - """Render FSA as an image via graphviz, and return the Digraph object; and optionally save to file filename. - filename must have a suffix that graphviz understands, such as pdf, svg or png. - - Note: - You need to install graphviz to use this function:: - - ./scripts/installers/install_graphviz.sh - - Args: - filename: - Filename to (optionally) save to, e.g. ‘foo.png’, ‘foo.svg’, ‘foo.png’. - - title: - Title to be displayed in image, e.g. ‘A simple lattice example’. - - zoom: - Zoom-in lattice in IPython notebook (needed for large lattices). - - Returns: - graphviz.Digraph or IPython.display.HTML - """ - _kaldifst_maybe_raise() - _graphviz_maybe_raise() - - isym, osym = None, None - if self._symbol_table: - osym = kaldifst.SymbolTable() - for i, w in self._symbol_table.items(): - osym.add_symbol(symbol=w, key=i) - - if ( - self._auxiliary_tables - and hasattr(self._auxiliary_tables, "input_symbols") - and self._auxiliary_tables.input_symbols - ): - isym = kaldifst.SymbolTable() - for i, t in self._auxiliary_tables.input_symbols.items(): - isym.add_symbol(symbol=t, key=i) - - fst_dot = kaldifst.draw( - self._lattice, acceptor=False, portrait=True, isymbols=isym, osymbols=osym, show_weight_one=True - ) - source = graphviz.Source(fst_dot) - source_lines = str(source).splitlines() - # Remove 'digraph tree {' - source_lines.pop(0) - # Remove the closing brackets '}' - source_lines.pop(-1) - graph_attr = { - 'rankdir': 'LR', - 'size': '8.5,11', - 'center': '1', - 'orientation': 'Portrait', - 'ranksep': '0.4', - 'nodesep': '0.25', - 'margin': '0.0', - } - if title is not None: - graph_attr['label'] = title - digraph = graphviz.Digraph(graph_attr=graph_attr) - digraph.body += source_lines - if filename: - _, extension = os.path.splitext(filename) - if extension == '' or extension[0] != '.': - raise ValueError(f"Filename needs to have a suffix like .png, .pdf, .svg, or .gv: `{filename}`") - with tempfile.TemporaryDirectory() as tmp_dir: - temp_fn = digraph.render(filename='temp', directory=tmp_dir, format=extension[1:], cleanup=True) - - shutil.move(temp_fn, filename) - if _is_notebook(): - import warnings - - from IPython.display import HTML - - with tempfile.TemporaryDirectory() as tmp_dir: - temp_fn = digraph.render(filename='temp', directory=tmp_dir, format="svg", cleanup=True) - svg, (width, height) = _svg_srcdoc_resize(temp_fn, zoom) - # IFrame requires src file to be present when rendering - # so we use HTML with iframe srcdoc instead - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - return HTML( - f"""""" - ) - return digraph - - -def _is_notebook() -> bool: - try: - shell = get_ipython().__class__.__name__ - if shell == 'ZMQInteractiveShell' or 'Shell': - return True # Jupyter notebook, Google Colab notebook, or qtconsole - elif shell == 'TerminalInteractiveShell': - return False # Terminal running IPython - else: - return False # Other type - except NameError: - return False # Probably standard Python interpreter - - -def _svg_srcdoc_resize(filename: Union[Path, str], zoom: float) -> Tuple[str, Tuple[int, int]]: - with open(filename, "rt", encoding="utf-8") as f: - line = f.readline() - while not line.startswith(" 'kaldifst.StdFst': - """Construct the levenshtein graph from a kaldi-type WFST or a lattice. - - See also levenshtein_graph from k2. - - Args: - fst: - Kaldi-type source WFST or lattice. - - ins_del_score: - Insertion and deletion penalty. - Should be more than 0.5 for substitutions to be preferred over insertions/deletions, or less otherwise. - - Returns: - Kaldi-type levenshtein WFST. - """ - _kaldifst_maybe_raise() - - if fst.properties(KaldiFstMask.Acceptor.value, True) != KaldiFstMask.Acceptor.value: - logging.warning( - "Levenshtein graph construction is not safe for WFSTs with different input and output symbols." - ) - if fst.properties(KaldiFstMask.Acyclic.value, True) != KaldiFstMask.Acyclic.value: - raise ValueError("Levenshtein graph is not defined for WFSTs with cycles.") - if isinstance(fst, kaldifst.StdFst): - lfst = fst.copy(safe=True) - elif isinstance(fst, kaldifst.Lattice): - # dropping lattice weights - lfst = kaldifst.compile(re.sub(r"[-\d.]+,[-\d.]+", "0", fst.to_str(show_weight_one=True))) - else: - raise ValueError(f"Levenshtein graph building is not supported for the type `{type(fst)}`.") - sub_score = 0.5 - eps = 0 - for state in kaldifst.StateIterator(lfst): - # epsilon self-loop for insertions and deletions - arcs_to_add = [ - kaldifst.StdArc( - ilabel=eps, - olabel=eps, - weight=ins_del_score, - nextstate=state, - ) - ] - for arc in kaldifst.ArcIterator(lfst, state): - # epsilon-to-ilabel arc for substitutions - arcs_to_add.append( - kaldifst.StdArc( - ilabel=eps, - olabel=arc.ilabel, - weight=sub_score, - nextstate=arc.nextstate, - ) - ) - # zero weight for correct ids (redundant for lattices) - arc.weight = 0.0 - for arc in arcs_to_add: - lfst.add_arc(state=state, arc=arc) - kaldifst.arcsort(lfst) - return lfst - - -def load_word_lattice( - lat_filename: Union[Path, str], id2word: Optional[Dict[int, str]] = None, id2token: Optional[Dict[int, str]] = None -) -> Dict[str, KaldiWordLattice]: - """Helper function to load riva-decoder recognition lattices. - - Args: - lat_filename: - Path to the riva-decoder recognition lattice file. - - id2word: - Word index. - Mapping from word_id to word_str. - - id2token: - Token index. - Mapping from token_id to token_str. - - Returns: - Dictionary with lattice names and corresponding lattices in KaldiWordLattice format. - """ - _kaldifst_maybe_raise() - - lattice_dict = {} - lattice = None - max_state = 0 - token_seq_list = [] - with open(lat_filename, "rt") as f: - for line in f.readlines(): - line_items = line.strip().split() - line_len = len(line_items) - if line_len == 0: # end of lattice - token_seq_list = [] - lattice = None - max_state = 0 - elif line_len == 1: # lattice identifier - assert lattice is None - assert max_state == 0 - assert len(token_seq_list) == 0 - lat_id = line_items[0] - lattice = kaldifst.Lattice() - lattice_dict[lat_id] = KaldiWordLattice( - lattice=lattice, - symbol_table=id2word, - auxiliary_tables={"token_seq_list": token_seq_list, "input_symbols": id2token}, - ) - start = lattice.add_state() - lattice.start = start - max_state += 1 - elif line_len in (3, 4): # arc - if line_len == 4: # regular arc - state, next_state, label = [int(i) for i in line_items[:-1]] - trunk = line_items[-1].split(',') - graph_cost, acoustic_cost = [float(i) for i in trunk[:-1]] - else: # arc without weight - logging.warning( - f"""An arc without weight is detected for lattice `{lat_id}`. - Weights and token sequences will be set trivially.""" - ) - state, next_state, label = [int(i) for i in line_items] - trunk = [""] - graph_cost, acoustic_cost = 0.0, 0.0 - if next_state >= max_state: - for i in range(max_state, next_state + 1): - lattice.add_state() - max_state = next_state + 1 - ark = kaldifst.LatticeArc( - ilabel=label, - olabel=label, - weight=kaldifst.LatticeWeight(graph_cost=graph_cost, acoustic_cost=acoustic_cost), - nextstate=next_state, - ) - lattice.add_arc(state=state, arc=ark) - token_seq_list.append((ark, [int(i) for i in trunk[-1].split(TW_BREAK)] if trunk[-1] != "" else [])) - elif line_len == 2: # final state - state = int(line_items[0]) - trunk = line_items[-1].split(',') - graph_cost, acoustic_cost = [float(i) for i in trunk[:-1]] - lattice.set_final( - state=state, weight=kaldifst.LatticeWeight(graph_cost=graph_cost, acoustic_cost=acoustic_cost) - ) - else: - raise RuntimeError(f"Broken line: `{line}`") - return lattice_dict diff --git a/nemo/collections/audio/README.md b/nemo/collections/audio/README.md deleted file mode 100644 index 9dd6215c554c255f5f2651a190775a4e1c9f0909..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# Audio processing collection - -The NeMo Audio Collection supports a range of models tailored for audio processing tasks, including single- and multi-channel speech enhancement and restoration. - -* Mask-based speech processing: single-channel masking and guided source separation (GSS) -* Predictive speech processing: NCSN++ -* Score-based generative models: SGMSE+ -* Schrödinger bridge-based models -* Flow-matching-based models -* Multi-channel audio processing: mask-based beamforming (MVDR) and dereverberation (WPE) - -More details can be found in [NeMo documentation](https://docs.nvidia.com/nemo-framework/user-guide/latest/index.html). diff --git a/nemo/collections/audio/__init__.py b/nemo/collections/audio/__init__.py deleted file mode 100644 index b53a75b366428110a9e1fb523007a92b519e7625..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/__init__.py +++ /dev/null @@ -1,25 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.audio import data, losses, metrics, models, modules -from nemo.package_info import __version__ - -# Set collection version equal to NeMo version. -__version = __version__ - -# Authorship. -__author__ = "NVIDIA Corporation" - -# Set collection name. -__description__ = "Audio Processing collection" diff --git a/nemo/collections/audio/data/__init__.py b/nemo/collections/audio/data/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/data/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/audio/data/audio_to_audio.py b/nemo/collections/audio/data/audio_to_audio.py deleted file mode 100644 index bb56b89d64c3c6d97ee0514d7af87f559fb3ca9e..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/data/audio_to_audio.py +++ /dev/null @@ -1,1170 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import abc -import math -import random -from collections import OrderedDict, namedtuple -from dataclasses import dataclass -from typing import Callable, Dict, List, Optional, Tuple, Type, Union - -import librosa -import numpy as np -import torch - -from nemo.collections.asr.parts.preprocessing.segment import AudioSegment, ChannelSelectorType -from nemo.collections.common.parts.preprocessing import collections -from nemo.collections.common.parts.utils import flatten -from nemo.core.classes import Dataset -from nemo.core.neural_types import AudioSignal, EncodedRepresentation, LengthsType, NeuralType -from nemo.utils import logging - -__all__ = [ - 'AudioToTargetDataset', - 'AudioToTargetWithReferenceDataset', - 'AudioToTargetWithEmbeddingDataset', -] - - -def _audio_collate_fn(batch: List[dict]) -> Tuple[torch.Tensor]: - """Collate a batch of items returned by __getitem__. - Examples for each signal are zero padded to the same length - (batch_length), which is determined by the longest example. - Lengths of the original signals are returned in the output. - - Args: - batch: List of dictionaries. Each element of the list - has the following format - ``` - { - 'signal_0': 1D or 2D tensor, - 'signal_1': 1D or 2D tensor, - ... - 'signal_N': 1D or 2D tensor, - } - ``` - 1D tensors have shape (num_samples,) and 2D tensors - have shape (num_channels, num_samples) - - Returns: - A tuple containing signal tensor and signal length tensor (in samples) - for each signal. - The output has the following format: - ``` - (signal_0, signal_0_length, signal_1, signal_1_length, ..., signal_N, signal_N_length) - ``` - Note that the output format is obtained by interleaving signals and their length. - """ - signals = batch[0].keys() - - batched = tuple() - - for signal in signals: - signal_length = [b[signal].shape[-1] for b in batch] - # Batch length is determined by the longest signal in the batch - batch_length = max(signal_length) - b_signal = [] - for s_len, b in zip(signal_length, batch): - # check if padding is necessary - if s_len < batch_length: - if b[signal].ndim == 1: - # single-channel signal - pad = (0, batch_length - s_len) - elif b[signal].ndim == 2: - # multi-channel signal - pad = (0, batch_length - s_len, 0, 0) - else: - raise RuntimeError( - f'Signal {signal} has unsuported dimensions {signal.shape}. Currently, only 1D and 2D arrays are supported.' - ) - b[signal] = torch.nn.functional.pad(b[signal], pad) - # append the current padded signal - b_signal.append(b[signal]) - # (signal_batched, signal_length) - batched += (torch.stack(b_signal), torch.tensor(signal_length, dtype=torch.int32)) - - # Currently, outputs are expected to be in a tuple, where each element must correspond - # to the output type in the OrderedDict returned by output_types. - # - # Therefore, we return batched signals by interleaving signals and their length: - # (signal_0, signal_0_length, signal_1, signal_1_length, ...) - return batched - - -@dataclass -class SignalSetup: - signals: List[str] # signal names - duration: Optional[Union[float, list]] = None # duration for each signal - channel_selectors: Optional[List[ChannelSelectorType]] = None # channel selector for loading each signal - - -class ASRAudioProcessor: - """Class that processes an example from Audio collection and returns - a dictionary with prepared signals. - - For example, the output dictionary may be the following - ``` - { - 'input_signal': input_signal_tensor, - 'target_signal': target_signal_tensor, - 'reference_signal': reference_signal_tensor, - 'embedding_vector': embedding_vector - } - ``` - Keys in the output dictionary are ordered with synchronous signals given first, - followed by asynchronous signals and embedding. - - Args: - sample_rate: sample rate used for all audio signals - random_offset: If `True`, offset will be randomized when loading a subsegment - from a file. - normalization_signal: Normalize all audio with a factor that ensures the signal - `example[normalization_signal]` in `process` is in range [-1, 1]. - All other audio signals are scaled by the same factor. Default is - `None`, corresponding to no normalization. - """ - - def __init__( - self, - sample_rate: float, - random_offset: bool, - normalization_signal: Optional[str] = None, - eps: float = 1e-8, - ): - self.sample_rate = sample_rate - self.random_offset = random_offset - self.normalization_signal = normalization_signal - self.eps = eps - - self.sync_setup = None - self.async_setup = None - self.embedding_setup = None - - @property - def sample_rate(self) -> float: - return self._sample_rate - - @sample_rate.setter - def sample_rate(self, value: float): - if value <= 0: - raise ValueError(f'Sample rate must be positive, received {value}') - - self._sample_rate = value - - @property - def random_offset(self) -> bool: - return self._random_offset - - @random_offset.setter - def random_offset(self, value: bool): - self._random_offset = value - - @property - def sync_setup(self) -> SignalSetup: - """Return the current setup for synchronous signals. - - Returns: - A dataclass containing the list of signals, their - duration and channel selectors. - """ - return self._sync_setup - - @sync_setup.setter - def sync_setup(self, value: Optional[SignalSetup]): - """Setup signals to be loaded synchronously. - - Args: - value: An instance of SignalSetup with the following fields - - signals: list of signals (keys of example.audio_signals) which will be loaded - synchronously with the same start time and duration. - - duration: Duration for each signal to be loaded. - If duration is set to None, the whole file will be loaded. - - channel_selectors: A list of channel selector for each signal. If channel selector - is None, all channels in the audio file will be loaded. - """ - if value is None or isinstance(value, SignalSetup): - self._sync_setup = value - else: - raise ValueError(f'Unexpected type {type(value)} for value {value}.') - - @property - def async_setup(self) -> SignalSetup: - """Return the current setup for asynchronous signals. - - Returns: - A dataclass containing the list of signals, their - duration and channel selectors. - """ - return self._async_setup - - @async_setup.setter - def async_setup(self, value: Optional[SignalSetup]): - """Setup signals to be loaded asynchronously. - - Args: - Args: - value: An instance of SignalSetup with the following fields - - signals: list of signals (keys of example.audio_signals) which will be loaded - asynchronously with signals possibly having different start and duration - - duration: Duration for each signal to be loaded. - If duration is set to None, the whole file will be loaded. - - channel_selectors: A list of channel selector for each signal. If channel selector - is None, all channels in the audio file will be loaded. - """ - if value is None or isinstance(value, SignalSetup): - self._async_setup = value - else: - raise ValueError(f'Unexpected type {type(value)} for value {value}.') - - @property - def embedding_setup(self) -> SignalSetup: - """Setup signals corresponding to an embedding vector.""" - return self._embedding_setup - - @embedding_setup.setter - def embedding_setup(self, value: SignalSetup): - """Setup signals corresponding to an embedding vector. - - Args: - value: An instance of SignalSetup with the following fields - - signals: list of signals (keys of example.audio_signals) which will be loaded - as embedding vectors. - """ - if value is None or isinstance(value, SignalSetup): - self._embedding_setup = value - else: - raise ValueError(f'Unexpected type {type(value)} for value {value}.') - - def process(self, example: collections.Audio.OUTPUT_TYPE) -> Dict[str, torch.Tensor]: - """Process an example from a collection of audio examples. - - Args: - example: an example from Audio collection. - - Returns: - An ordered dictionary of signals and their tensors. - For example, the output dictionary may be the following - ``` - { - 'input_signal': input_signal_tensor, - 'target_signal': target_signal_tensor, - 'reference_signal': reference_signal_tensor, - 'embedding_vector': embedding_vector - } - ``` - Keys in the output dictionary are ordered with synchronous signals given first, - followed by asynchronous signals and embedding. - """ - audio = self.load_audio(example=example) - audio = self.process_audio(audio=audio) - return audio - - def load_audio(self, example: collections.Audio.OUTPUT_TYPE) -> Dict[str, torch.Tensor]: - """Given an example, load audio from `example.audio_files` and prepare - the output dictionary. - - Args: - example: An example from an audio collection - - Returns: - An ordered dictionary of signals and their tensors. - For example, the output dictionary may be the following - ``` - { - 'input_signal': input_signal_tensor, - 'target_signal': target_signal_tensor, - 'reference_signal': reference_signal_tensor, - 'embedding_vector': embedding_vector - } - ``` - Keys in the output dictionary are ordered with synchronous signals given first, - followed by asynchronous signals and embedding. - """ - output = OrderedDict() - - if self.sync_setup is not None: - # Load all signals with the same start and duration - sync_signals = self.load_sync_signals(example) - output.update(sync_signals) - - if self.async_setup is not None: - # Load each signal independently - async_signals = self.load_async_signals(example) - output.update(async_signals) - - # Load embedding vector - if self.embedding_setup is not None: - embedding = self.load_embedding(example) - output.update(embedding) - - if not output: - raise RuntimeError('Output dictionary is empty. Please use `_setup` methods to setup signals to be loaded') - - return output - - def process_audio(self, audio: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: - """Process audio signals available in the input dictionary. - - Args: - audio: A dictionary containing loaded signals `signal: tensor` - - Returns: - An ordered dictionary of signals and their tensors. - """ - if self.normalization_signal: - # Normalize all audio with a factor that ensures the normalization signal is in range [-1, 1]. - norm_scale = audio[self.normalization_signal].abs().max() - - # Do not normalize embeddings - skip_signals = self.embedding_setup.signals if self.embedding_setup is not None else [] - - # Normalize audio signals - for signal in audio: - if signal not in skip_signals: - # All audio signals are scaled by the same factor. - # This ensures that the relative level between signals is preserved. - audio[signal] = audio[signal] / (norm_scale + self.eps) - - return audio - - def load_sync_signals(self, example: collections.Audio.OUTPUT_TYPE) -> Dict[str, torch.Tensor]: - """Load signals with the same start and duration. - - Args: - example: an example from audio collection - - Returns: - An ordered dictionary of signals and their tensors. - """ - output = OrderedDict() - sync_audio_files = [example.audio_files[s] for s in self.sync_setup.signals] - - sync_samples = self.get_samples_synchronized( - audio_files=sync_audio_files, - channel_selectors=self.sync_setup.channel_selectors, - sample_rate=self.sample_rate, - duration=self.sync_setup.duration, - fixed_offset=example.offset, - random_offset=self.random_offset, - ) - - for signal, samples in zip(self.sync_setup.signals, sync_samples): - output[signal] = torch.tensor(samples) - - return output - - def load_async_signals(self, example: collections.Audio.OUTPUT_TYPE) -> Dict[str, torch.Tensor]: - """Load each async signal independently, no constraints on starting - from the same time. - - Args: - example: an example from audio collection - - Returns: - An ordered dictionary of signals and their tensors. - """ - output = OrderedDict() - for idx, signal in enumerate(self.async_setup.signals): - samples = self.get_samples( - audio_file=example.audio_files[signal], - sample_rate=self.sample_rate, - duration=self.async_setup.duration[idx], - channel_selector=self.async_setup.channel_selectors[idx], - fixed_offset=example.offset, - random_offset=self.random_offset, - ) - output[signal] = torch.tensor(samples) - return output - - @classmethod - def get_samples( - cls, - audio_file: str, - sample_rate: int, - duration: Optional[float] = None, - channel_selector: ChannelSelectorType = None, - fixed_offset: float = 0, - random_offset: bool = False, - ) -> np.ndarray: - """Get samples from an audio file. - For a single-channel signal, the output is shape (num_samples,). - For a multi-channel signal, the output is shape (num_samples, num_channels). - - Args: - audio_file: path to an audio file - sample_rate: desired sample rate for output samples - duration: Optional desired duration of output samples. - If `None`, the complete file will be loaded. - If set, a segment of `duration` seconds will be loaded. - channel_selector: Optional channel selector, for selecting a subset of channels. - fixed_offset: Optional fixed offset when loading samples. - random_offset: If `True`, offset will be randomized when loading a short segment - from a file. The value is randomized between fixed_offset and - max_offset (set depending on the duration and fixed_offset). - - Returns: - Numpy array with samples from audio file. - The array has shape (num_samples,) for a single-channel signal - or (num_channels, num_samples) for a multi-channel signal. - """ - output = cls.get_samples_synchronized( - audio_files=[audio_file], - sample_rate=sample_rate, - duration=duration, - channel_selectors=[channel_selector], - fixed_offset=fixed_offset, - random_offset=random_offset, - ) - - return output[0] - - @classmethod - def get_samples_synchronized( - cls, - audio_files: List[str], - sample_rate: int, - duration: Optional[float] = None, - channel_selectors: Optional[List[ChannelSelectorType]] = None, - fixed_offset: float = 0, - random_offset: bool = False, - ) -> List[np.ndarray]: - """Get samples from multiple files with the same start and end point. - - Args: - audio_files: list of paths to audio files - sample_rate: desired sample rate for output samples - duration: Optional desired duration of output samples. - If `None`, the complete files will be loaded. - If set, a segment of `duration` seconds will be loaded from - all files. Segment is synchronized across files, so that - start and end points are the same. - channel_selectors: Optional channel selector for each signal, for selecting - a subset of channels. - fixed_offset: Optional fixed offset when loading samples. - random_offset: If `True`, offset will be randomized when loading a short segment - from a file. The value is randomized between fixed_offset and - max_offset (set depending on the duration and fixed_offset). - - Returns: - List with the same size as `audio_files` but containing numpy arrays - with samples from each audio file. - Each array has shape (num_samples,) or (num_channels, num_samples), for single- - or multi-channel signal, respectively. - For example, if `audio_files = [path/to/file_1.wav, path/to/file_2.wav]`, - the output will be a list `output = [samples_file_1, samples_file_2]`. - """ - if channel_selectors is None: - channel_selectors = [None] * len(audio_files) - - if duration is None: - # Load complete files starting from a fixed offset - offset = fixed_offset # fixed offset - num_samples = None # no constrain on the number of samples - - else: - # Fixed duration of the output - audio_durations = cls.get_duration(audio_files) - min_audio_duration = min(audio_durations) - available_duration = min_audio_duration - fixed_offset - - if available_duration <= 0: - raise ValueError(f'Fixed offset {fixed_offset}s is larger than shortest file {min_audio_duration}s.') - - if duration + fixed_offset > min_audio_duration: - # The shortest file is shorter than the requested duration - logging.debug( - f'Shortest file ({min_audio_duration}s) is less than the desired duration {duration}s + fixed offset {fixed_offset}s. Returned signals will be shortened to {available_duration} seconds.' - ) - offset = fixed_offset - duration = available_duration - elif random_offset: - # Randomize offset based on the shortest file - max_offset = min_audio_duration - duration - offset = random.uniform(fixed_offset, max_offset) - else: - # Fixed offset - offset = fixed_offset - - # Fixed number of samples - num_samples = math.floor(duration * sample_rate) - - output = [] - - # Prepare segments - for idx, audio_file in enumerate(audio_files): - segment_samples = cls.get_samples_from_file( - audio_file=audio_file, - sample_rate=sample_rate, - offset=offset, - num_samples=num_samples, - channel_selector=channel_selectors[idx], - ) - output.append(segment_samples) - - return output - - @classmethod - def get_samples_from_file( - cls, - audio_file: Union[str, List[str]], - sample_rate: int, - offset: float, - num_samples: Optional[int] = None, - channel_selector: Optional[ChannelSelectorType] = None, - ) -> np.ndarray: - """Get samples from a single or multiple files. - If loading samples from multiple files, they will - be concatenated along the channel dimension. - - Args: - audio_file: path or a list of paths. - sample_rate: sample rate of the loaded samples - offset: fixed offset in seconds - num_samples: Optional, number of samples to load. - If `None`, all available samples will be loaded. - channel_selector: Select a subset of available channels. - - Returns: - An array with shape (samples,) or (channels, samples) - """ - if isinstance(audio_file, str): - # Load samples from a single file - segment_samples = cls.get_segment_from_file( - audio_file=audio_file, - sample_rate=sample_rate, - offset=offset, - num_samples=num_samples, - channel_selector=channel_selector, - ) - elif isinstance(audio_file, list): - # Load samples from multiple files and form a multi-channel signal - segment_samples = [] - for a_file in audio_file: - a_file_samples = cls.get_segment_from_file( - audio_file=a_file, - sample_rate=sample_rate, - offset=offset, - num_samples=num_samples, - channel_selector=channel_selector, - ) - segment_samples.append(a_file_samples) - segment_samples = cls.list_to_multichannel(segment_samples) - elif audio_file is None: - # Support for inference, when the target signal is `None` - segment_samples = [] - else: - raise RuntimeError(f'Unexpected audio_file type {type(audio_file)}') - return segment_samples - - @staticmethod - def get_segment_from_file( - audio_file: str, - sample_rate: int, - offset: float, - num_samples: Optional[int] = None, - channel_selector: Optional[ChannelSelectorType] = None, - ) -> np.ndarray: - """Get a segment of samples from a single audio file. - - Args: - audio_file: path to an audio file - sample_rate: sample rate of the loaded samples - offset: fixed offset in seconds - num_samples: Optional, number of samples to load. - If `None`, all available samples will be loaded. - channel_selector: Select a subset of available channels. - - Returns: - An array with shape (samples,) or (channels, samples) - """ - if num_samples is None: - segment = AudioSegment.from_file( - audio_file=audio_file, - target_sr=sample_rate, - offset=offset, - channel_selector=channel_selector, - ) - - else: - segment = AudioSegment.segment_from_file( - audio_file=audio_file, - target_sr=sample_rate, - n_segments=num_samples, - offset=offset, - channel_selector=channel_selector, - ) - - if segment.samples.ndim == 1: - # Single-channel signal - return segment.samples - elif segment.samples.ndim == 2: - # Use multi-channel format as (channels, samples) - return segment.samples.T - else: - raise RuntimeError(f'Unexpected samples shape: {segment.samples.shape}') - - @staticmethod - def list_to_multichannel(signal: Union[np.ndarray, List[np.ndarray]]) -> np.ndarray: - """Convert a list of signals into a multi-channel signal by concatenating - the elements of the list along the channel dimension. - - If input is not a list, it is returned unmodified. - - Args: - signal: list of arrays - - Returns: - Numpy array obtained by concatenating the elements of the list - along the channel dimension (axis=0). - """ - if not isinstance(signal, list): - # Nothing to do there - return signal - elif len(signal) == 0: - # Nothing to do, return as is - return signal - elif len(signal) == 1: - # Nothing to concatenate, return the original format - return signal[0] - - # If multiple signals are provided in a list, we concatenate them along the channel dimension - if signal[0].ndim == 1: - # Single-channel individual files - mc_signal = np.stack(signal, axis=0) - elif signal[0].ndim == 2: - # Multi-channel individual files - mc_signal = np.concatenate(signal, axis=0) - else: - raise RuntimeError(f'Unexpected target with {signal[0].ndim} dimensions.') - - return mc_signal - - @staticmethod - def get_duration(audio_files: List[str]) -> List[float]: - """Get duration for each audio file in `audio_files`. - - Args: - audio_files: list of paths to audio files - - Returns: - List of durations in seconds. - """ - duration = [librosa.get_duration(path=f) for f in flatten(audio_files)] - return duration - - def load_embedding(self, example: collections.Audio.OUTPUT_TYPE) -> Dict[str, torch.Tensor]: - """Given an example, load embedding from `example.audio_files[embedding]` - and return it in a dictionary. - - Args: - example: An example from audio collection - - Returns: - An dictionary of embedding keys and their tensors. - """ - output = OrderedDict() - for idx, signal in enumerate(self.embedding_setup.signals): - embedding_file = example.audio_files[signal] - embedding = self.load_embedding_vector(embedding_file) - output[signal] = torch.tensor(embedding) - return output - - @staticmethod - def load_embedding_vector(filepath: str) -> np.ndarray: - """Load an embedding vector from a file. - - Args: - filepath: path to a file storing a vector. - Currently, it is assumed the file is a npy file. - - Returns: - Array loaded from filepath. - """ - if filepath.endswith('.npy'): - with open(filepath, 'rb') as f: - embedding = np.load(f) - else: - raise RuntimeError(f'Unknown embedding file format in file: {filepath}') - - return embedding - - -class BaseAudioDataset(Dataset): - """Base class of audio datasets, providing common functionality - for other audio datasets. - - Args: - collection: Collection of audio examples prepared from manifest files. - audio_processor: Used to process every example from the collection. - A callable with `process` method. For reference, - please check ASRAudioProcessor. - """ - - @property - @abc.abstractmethod - def output_types(self) -> Optional[Dict[str, NeuralType]]: - """Returns definitions of module output ports.""" - - def __init__(self, collection: collections.Audio, audio_processor: Callable, output_type: Type[namedtuple]): - """Instantiates an audio dataset.""" - super().__init__() - - self.collection = collection - self.audio_processor = audio_processor - self.output_type = output_type - - def num_channels(self, signal_key) -> int: - """Returns the number of channels for a particular signal in - items prepared by this dictionary. - - More specifically, this will get the tensor from the first - item in the dataset, check if it's a one- or two-dimensional - tensor, and return the number of channels based on the size - of the first axis (shape[0]). - - NOTE: - This assumes that all examples have the same number of channels. - - Args: - signal_key: string, used to select a signal from the dictionary - output by __getitem__ - - Returns: - Number of channels for the selected signal. - """ - # Assumption: whole dataset has the same number of channels - item = self.__getitem__(0) - - if item[signal_key].ndim == 1: - return 1 - elif item[signal_key].ndim == 2: - return item[signal_key].shape[0] - else: - raise RuntimeError( - f'Unexpected number of dimension for signal {signal_key} with shape {item[signal_key].shape}' - ) - - def __getitem__(self, index: int) -> Dict[str, torch.Tensor]: - """Return a single example from the dataset. - - Args: - index: integer index of an example in the collection - - Returns: - Dictionary providing mapping from signal to its tensor. - For example: - ``` - { - 'input_signal': input_signal_tensor, - 'target_signal': target_signal_tensor, - } - ``` - """ - example = self.collection[index] - output = self.audio_processor.process(example=example) - - return output - - def __len__(self) -> int: - """Return the number of examples in the dataset.""" - return len(self.collection) - - def _collate_fn(self, batch) -> Tuple[torch.Tensor]: - """Collate items in a batch.""" - return self.output_type(*_audio_collate_fn(batch)) - - -AudioToTargetExample = namedtuple( - typename='AudioToTargetExample', field_names='input_signal input_length target_signal target_length' -) - - -class AudioToTargetDataset(BaseAudioDataset): - """A dataset for audio-to-audio tasks where the goal is to use - an input signal to recover the corresponding target signal. - - Each line of the manifest file is expected to have the following format: - - .. code-block:: json - - {"input_key": "path/to/input.wav", "target_key": "path/to/target.wav", "duration": "duration_in_seconds"} - - Additionally, multiple audio files may be provided for each key in the manifest, for example, - - .. code-block:: json - - {"input_key": "path/to/input.wav", "target_key": ["path/to/path_to_target_ch0.wav", "path/to/path_to_target_ch1.wav"], "duration": "duration_in_seconds"} - - Keys for input and target signals can be configured in the constructor (`input_key` and `target_key`). - - Args: - manifest_filepath: Path to manifest file in a format described above. - sample_rate: Sample rate for loaded audio signals. - input_key: Key pointing to input audio files in the manifest - target_key: Key pointing to target audio files in manifest - audio_duration: Optional duration of each item returned by __getitem__. - If `None`, complete audio will be loaded. - If set, a random subsegment will be loaded synchronously from - target and audio, i.e., with the same start and end point. - random_offset: If `True`, offset will be randomized when loading a subsegment - from a file. - max_duration: If audio exceeds this length, do not include in dataset. - min_duration: If audio is less than this length, do not include in dataset. - max_utts: Limit number of utterances. - input_channel_selector: Optional, select subset of channels from each input audio file. - If `None`, all channels will be loaded. - target_channel_selector: Optional, select subset of channels from each input audio file. - If `None`, all channels will be loaded. - normalization_signal: Normalize audio signals with a scale that ensures the normalization signal is in range [-1, 1]. - All audio signals are scaled by the same factor. Supported values are `None` (no normalization), - 'input_signal', 'target_signal'. - """ - - def __init__( - self, - manifest_filepath: str, - sample_rate: int, - input_key: str, - target_key: str, - audio_duration: Optional[float] = None, - random_offset: bool = False, - max_duration: Optional[float] = None, - min_duration: Optional[float] = None, - max_utts: Optional[int] = None, - input_channel_selector: Optional[int] = None, - target_channel_selector: Optional[int] = None, - normalization_signal: Optional[str] = None, - ): - audio_to_manifest_key = { - 'input_signal': input_key, - 'target_signal': target_key, - } - - collection = collections.AudioCollection( - manifest_files=manifest_filepath, - audio_to_manifest_key=audio_to_manifest_key, - min_duration=min_duration, - max_duration=max_duration, - max_number=max_utts, - ) - - audio_processor = ASRAudioProcessor( - sample_rate=sample_rate, - random_offset=random_offset, - normalization_signal=normalization_signal, - ) - audio_processor.sync_setup = SignalSetup( - signals=['input_signal', 'target_signal'], - duration=audio_duration, - channel_selectors=[input_channel_selector, target_channel_selector], - ) - - super().__init__(collection=collection, audio_processor=audio_processor, output_type=AudioToTargetExample) - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - """Returns definitions of module output ports. - - Returns: - OrderedDict: Dictionary containing the following items: - input_signal: - Batched single- or multi-channel input audio signal - input_length: - Batched original length of each input signal - target_signal: - Batched single- or multi-channel target audio signal - target_length: - Batched original length of each target signal - """ - sc_audio_type = NeuralType(('B', 'T'), AudioSignal()) - mc_audio_type = NeuralType(('B', 'C', 'T'), AudioSignal()) - - return OrderedDict( - input_signal=sc_audio_type if self.num_channels('input_signal') == 1 else mc_audio_type, - input_length=NeuralType(('B',), LengthsType()), - target_signal=sc_audio_type if self.num_channels('target_signal') == 1 else mc_audio_type, - target_length=NeuralType(('B',), LengthsType()), - ) - - -AudioToTargetWithReferenceExample = namedtuple( - typename='AudioToTargetWithReferenceExample', - field_names='input_signal input_length target_signal target_length reference_signal reference_length', -) - - -class AudioToTargetWithReferenceDataset(BaseAudioDataset): - """A dataset for audio-to-audio tasks where the goal is to use - an input signal to recover the corresponding target signal and an - additional reference signal is available. - - This can be used, for example, when a reference signal is - available from - - enrollment utterance for the target signal - - echo reference from playback - - reference from another sensor that correlates with the target signal - - Each line of the manifest file is expected to have the following format - - .. code-block:: json - - {"input_key": "path/to/input.wav", "target_key": "path/to/path_to_target.wav", "reference_key": "path/to/path_to_reference.wav", "duration": "duration_in_seconds"} - - Keys for input, target and reference signals can be configured in the constructor. - - Args: - manifest_filepath: Path to manifest file in a format described above. - sample_rate: Sample rate for loaded audio signals. - input_key: Key pointing to input audio files in the manifest - target_key: Key pointing to target audio files in manifest - reference_key: Key pointing to reference audio files in manifest - audio_duration: Optional duration of each item returned by __getitem__. - If `None`, complete audio will be loaded. - If set, a random subsegment will be loaded synchronously from - target and audio, i.e., with the same start and end point. - random_offset: If `True`, offset will be randomized when loading a subsegment - from a file. - max_duration: If audio exceeds this length, do not include in dataset. - min_duration: If audio is less than this length, do not include in dataset. - max_utts: Limit number of utterances. - input_channel_selector: Optional, select subset of channels from each input audio file. - If `None`, all channels will be loaded. - target_channel_selector: Optional, select subset of channels from each input audio file. - If `None`, all channels will be loaded. - reference_channel_selector: Optional, select subset of channels from each input audio file. - If `None`, all channels will be loaded. - reference_is_synchronized: If True, it is assumed that the reference signal is synchronized - with the input signal, so the same subsegment will be loaded as for - input and target. If False, reference signal will be loaded independently - from input and target. - reference_duration: Optional, can be used to set a fixed duration of the reference utterance. If `None`, - complete audio file will be loaded. - normalization_signal: Normalize audio signals with a scale that ensures the normalization signal is in range [-1, 1]. - All audio signals are scaled by the same factor. Supported values are `None` (no normalization), - 'input_signal', 'target_signal', 'reference_signal'. - """ - - def __init__( - self, - manifest_filepath: str, - sample_rate: int, - input_key: str, - target_key: str, - reference_key: str, - audio_duration: Optional[float] = None, - random_offset: bool = False, - max_duration: Optional[float] = None, - min_duration: Optional[float] = None, - max_utts: Optional[int] = None, - input_channel_selector: Optional[int] = None, - target_channel_selector: Optional[int] = None, - reference_channel_selector: Optional[int] = None, - reference_is_synchronized: bool = True, - reference_duration: Optional[float] = None, - normalization_signal: Optional[str] = None, - ): - audio_to_manifest_key = { - 'input_signal': input_key, - 'target_signal': target_key, - 'reference_signal': reference_key, - } - - collection = collections.AudioCollection( - manifest_files=manifest_filepath, - audio_to_manifest_key=audio_to_manifest_key, - min_duration=min_duration, - max_duration=max_duration, - max_number=max_utts, - ) - - audio_processor = ASRAudioProcessor( - sample_rate=sample_rate, - random_offset=random_offset, - normalization_signal=normalization_signal, - ) - - if reference_is_synchronized: - audio_processor.sync_setup = SignalSetup( - signals=['input_signal', 'target_signal', 'reference_signal'], - duration=audio_duration, - channel_selectors=[input_channel_selector, target_channel_selector, reference_channel_selector], - ) - else: - audio_processor.sync_setup = SignalSetup( - signals=['input_signal', 'target_signal'], - duration=audio_duration, - channel_selectors=[input_channel_selector, target_channel_selector], - ) - audio_processor.async_setup = SignalSetup( - signals=['reference_signal'], - duration=[reference_duration], - channel_selectors=[reference_channel_selector], - ) - - super().__init__( - collection=collection, audio_processor=audio_processor, output_type=AudioToTargetWithReferenceExample - ) - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - """Returns definitions of module output ports. - - Returns: - OrderedDict: Dictionary containing the following items: - input_signal: - Batched single- or multi-channel input audio signal - input_length: - Batched original length of each input signal - target_signal: - Batched single- or multi-channel target audio signal - target_length: - Batched original length of each target signal - reference_signal: - Batched single- or multi-channel reference audio signal - reference_length: - Batched original length of each reference signal - """ - sc_audio_type = NeuralType(('B', 'T'), AudioSignal()) - mc_audio_type = NeuralType(('B', 'C', 'T'), AudioSignal()) - - return OrderedDict( - input_signal=sc_audio_type if self.num_channels('input_signal') == 1 else mc_audio_type, - input_length=NeuralType(('B',), LengthsType()), - target_signal=sc_audio_type if self.num_channels('target_signal') == 1 else mc_audio_type, - target_length=NeuralType(('B',), LengthsType()), - reference_signal=sc_audio_type if self.num_channels('reference_signal') == 1 else mc_audio_type, - reference_length=NeuralType(('B',), LengthsType()), - ) - - -AudioToTargetWithEmbeddingExample = namedtuple( - typename='AudioToTargetWithEmbeddingExample', - field_names='input_signal input_length target_signal target_length embedding_vector embedding_length', -) - - -class AudioToTargetWithEmbeddingDataset(BaseAudioDataset): - """A dataset for audio-to-audio tasks where the goal is to use - an input signal to recover the corresponding target signal and an - additional embedding signal. It is assumed that the embedding - is in a form of a vector. - - Each line of the manifest file is expected to have the following format - - .. code-block:: json - - {"input_key": "path/to/input.wav", "target_key": "path/to/path_to_target.wav", "embedding_key": "path/to/path_to_reference.npy", "duration": "duration_in_seconds"} - - Keys for input, target and embedding signals can be configured in the constructor. - - Args: - manifest_filepath: Path to manifest file in a format described above. - sample_rate: Sample rate for loaded audio signals. - input_key: Key pointing to input audio files in the manifest - target_key: Key pointing to target audio files in manifest - embedding_key: Key pointing to embedding files in manifest - audio_duration: Optional duration of each item returned by __getitem__. - If `None`, complete audio will be loaded. - If set, a random subsegment will be loaded synchronously from - target and audio, i.e., with the same start and end point. - random_offset: If `True`, offset will be randomized when loading a subsegment - from a file. - max_duration: If audio exceeds this length, do not include in dataset. - min_duration: If audio is less than this length, do not include in dataset. - max_utts: Limit number of utterances. - input_channel_selector: Optional, select subset of channels from each input audio file. - If `None`, all channels will be loaded. - target_channel_selector: Optional, select subset of channels from each input audio file. - If `None`, all channels will be loaded. - normalization_signal: Normalize audio signals with a scale that ensures the normalization signal is in range [-1, 1]. - All audio signals are scaled by the same factor. Supported values are `None` (no normalization), - 'input_signal', 'target_signal'. - """ - - def __init__( - self, - manifest_filepath: str, - sample_rate: int, - input_key: str, - target_key: str, - embedding_key: str, - audio_duration: Optional[float] = None, - random_offset: bool = False, - max_duration: Optional[float] = None, - min_duration: Optional[float] = None, - max_utts: Optional[int] = None, - input_channel_selector: Optional[int] = None, - target_channel_selector: Optional[int] = None, - normalization_signal: Optional[str] = None, - ): - audio_to_manifest_key = { - 'input_signal': input_key, - 'target_signal': target_key, - 'embedding_vector': embedding_key, - } - - collection = collections.AudioCollection( - manifest_files=manifest_filepath, - audio_to_manifest_key=audio_to_manifest_key, - min_duration=min_duration, - max_duration=max_duration, - max_number=max_utts, - ) - - audio_processor = ASRAudioProcessor( - sample_rate=sample_rate, - random_offset=random_offset, - normalization_signal=normalization_signal, - ) - audio_processor.sync_setup = SignalSetup( - signals=['input_signal', 'target_signal'], - duration=audio_duration, - channel_selectors=[input_channel_selector, target_channel_selector], - ) - audio_processor.embedding_setup = SignalSetup(signals=['embedding_vector']) - - super().__init__( - collection=collection, audio_processor=audio_processor, output_type=AudioToTargetWithEmbeddingExample - ) - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - """Returns definitions of module output ports. - - Returns: - OrderedDict: Dictionary containing the following items: - input_signal: - Batched single- or multi-channel input audio signal - input_length: - Batched original length of each input signal - target_signal: - Batched single- or multi-channel target audio signal - target_length: - Batched original length of each target signal - embedding_vector: - Batched embedded vector format - embedding_length: - Batched original length of each embedding vector - """ - sc_audio_type = NeuralType(('B', 'T'), AudioSignal()) - mc_audio_type = NeuralType(('B', 'C', 'T'), AudioSignal()) - - return OrderedDict( - input_signal=sc_audio_type if self.num_channels('input_signal') == 1 else mc_audio_type, - input_length=NeuralType(('B',), LengthsType()), - target_signal=sc_audio_type if self.num_channels('target_signal') == 1 else mc_audio_type, - target_length=NeuralType(('B',), LengthsType()), - embedding_vector=NeuralType(('B', 'D'), EncodedRepresentation()), - embedding_length=NeuralType(('B',), LengthsType()), - ) diff --git a/nemo/collections/audio/data/audio_to_audio_dataset.py b/nemo/collections/audio/data/audio_to_audio_dataset.py deleted file mode 100644 index 38ea5ef9cd39e58ad7f5d2a288e1a83320c20cd9..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/data/audio_to_audio_dataset.py +++ /dev/null @@ -1,98 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.audio.data import audio_to_audio - - -def get_audio_to_target_dataset(config: dict) -> audio_to_audio.AudioToTargetDataset: - """Instantiates an audio-to-audio dataset. - - Args: - config: Config of AudioToTargetDataset. - - Returns: - An instance of AudioToTargetDataset - """ - dataset = audio_to_audio.AudioToTargetDataset( - manifest_filepath=config['manifest_filepath'], - sample_rate=config['sample_rate'], - input_key=config['input_key'], - target_key=config['target_key'], - audio_duration=config.get('audio_duration', None), - random_offset=config.get('random_offset', False), - max_duration=config.get('max_duration', None), - min_duration=config.get('min_duration', None), - max_utts=config.get('max_utts', 0), - input_channel_selector=config.get('input_channel_selector', None), - target_channel_selector=config.get('target_channel_selector', None), - normalization_signal=config.get('normalization_signal', None), - ) - return dataset - - -def get_audio_to_target_with_reference_dataset(config: dict) -> audio_to_audio.AudioToTargetWithReferenceDataset: - """Instantiates an audio-to-audio dataset. - - Args: - config: Config of AudioToTargetWithReferenceDataset. - - Returns: - An instance of AudioToTargetWithReferenceDataset - """ - dataset = audio_to_audio.AudioToTargetWithReferenceDataset( - manifest_filepath=config['manifest_filepath'], - sample_rate=config['sample_rate'], - input_key=config['input_key'], - target_key=config['target_key'], - reference_key=config['reference_key'], - audio_duration=config.get('audio_duration', None), - random_offset=config.get('random_offset', False), - max_duration=config.get('max_duration', None), - min_duration=config.get('min_duration', None), - max_utts=config.get('max_utts', 0), - input_channel_selector=config.get('input_channel_selector', None), - target_channel_selector=config.get('target_channel_selector', None), - reference_channel_selector=config.get('reference_channel_selector', None), - reference_is_synchronized=config.get('reference_is_synchronized', True), - reference_duration=config.get('reference_duration', None), - normalization_signal=config.get('normalization_signal', None), - ) - return dataset - - -def get_audio_to_target_with_embedding_dataset(config: dict) -> audio_to_audio.AudioToTargetWithEmbeddingDataset: - """Instantiates an audio-to-audio dataset. - - Args: - config: Config of AudioToTargetWithEmbeddingDataset. - - Returns: - An instance of AudioToTargetWithEmbeddingDataset - """ - dataset = audio_to_audio.AudioToTargetWithEmbeddingDataset( - manifest_filepath=config['manifest_filepath'], - sample_rate=config['sample_rate'], - input_key=config['input_key'], - target_key=config['target_key'], - embedding_key=config['embedding_key'], - audio_duration=config.get('audio_duration', None), - random_offset=config.get('random_offset', False), - max_duration=config.get('max_duration', None), - min_duration=config.get('min_duration', None), - max_utts=config.get('max_utts', 0), - input_channel_selector=config.get('input_channel_selector', None), - target_channel_selector=config.get('target_channel_selector', None), - normalization_signal=config.get('normalization_signal', None), - ) - return dataset diff --git a/nemo/collections/audio/data/audio_to_audio_lhotse.py b/nemo/collections/audio/data/audio_to_audio_lhotse.py deleted file mode 100644 index aca86787b44eff2b2479bc47189248f9a9fc23ae..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/data/audio_to_audio_lhotse.py +++ /dev/null @@ -1,229 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import os - -import numpy as np -import torch -from lhotse import AudioSource, CutSet, Recording -from lhotse.array import Array -from lhotse.audio import info -from lhotse.cut import MixedCut -from lhotse.dataset.collation import collate_audio, collate_custom_field -from lhotse.serialization import load_jsonl - -from nemo.collections.common.parts.preprocessing.manifest import get_full_path - -INPUT_CHANNEL_SELECTOR = "input_channel_selector" -TARGET_CHANNEL_SELECTOR = "target_channel_selector" -REFERENCE_CHANNEL_SELECTOR = "reference_channel_selector" -LHOTSE_TARGET_CHANNEL_SELECTOR = "target_recording_channel_selector" -LHOTSE_REFERENCE_CHANNEL_SELECTOR = "reference_recording_channel_selector" - - -class LhotseAudioToTargetDataset(torch.utils.data.Dataset): - """ - A dataset for audio-to-audio tasks where the goal is to use - an input signal to recover the corresponding target signal. - - .. note:: This is a Lhotse variant of :class:`nemo.collections.asr.data.audio_to_audio.AudioToTargetDataset`. - """ - - TARGET_KEY = "target_recording" - REFERENCE_KEY = "reference_recording" - EMBEDDING_KEY = "embedding_vector" - - def __getitem__(self, cuts: CutSet) -> dict[str, torch.Tensor]: - # In the rare case, the collate_audio function would raise the FileSeek error when loading .flac (https://github.com/bastibe/python-soundfile/issues/274) - # A workaround is to use fault_tolerant and skip failed data, resulting in a smaller batch size for the few problematic cases. - src_audio, src_audio_lens, retained_padded_cuts = collate_audio(cuts, fault_tolerant=True) - ans = { - "input_signal": src_audio, - "input_length": src_audio_lens, - } - # keep only the first non-padding cuts - retained_cuts = [ - cut._first_non_padding_cut if isinstance(cut, MixedCut) else cut for cut in retained_padded_cuts - ] - - # if online augmentation is applied, some retained cuts still may be MixedCuts (including the original speech, noise, and augmentation) - # get the first non-padding cut from there, which is supposed to be the clean speech signal - for n, cut in enumerate(retained_cuts): - if isinstance(cut, MixedCut): - retained_cuts[n] = cut._first_non_padding_cut - # create cutset - retained_cuts = CutSet.from_cuts(retained_cuts) - - if _key_available(retained_cuts, self.TARGET_KEY): - # TODO: use fault_tolerant=True for robust loading of target - tgt_audio, tgt_audio_lens = collate_audio(retained_cuts, recording_field=self.TARGET_KEY) - ans.update(target_signal=tgt_audio, target_length=tgt_audio_lens) - if _key_available(retained_cuts, self.REFERENCE_KEY): - # TODO: use fault_tolerant=True for robust loading of target - ref_audio, ref_audio_lens = collate_audio(retained_cuts, recording_field=self.REFERENCE_KEY) - ans.update(reference_signal=ref_audio, reference_length=ref_audio_lens) - if _key_available(cuts, self.EMBEDDING_KEY): - emb = collate_custom_field(retained_cuts, field=self.EMBEDDING_KEY) - ans.update(embedding_signal=emb) - return ans - - -def _key_available(cuts: CutSet, key: str) -> bool: - for cut in cuts: - if isinstance(cut, MixedCut): - cut = cut._first_non_padding_cut - if cut.custom is not None and key in cut.custom: - continue - else: - return False - return True - - -def create_recording(path_or_paths: str | list[str]) -> Recording: - if isinstance(path_or_paths, list): - cur_channel_idx = 0 - sources = [] - infos = [] - for p in path_or_paths: - i = info(p) - infos.append(i) - sources.append( - AudioSource(type="file", channels=list(range(cur_channel_idx, cur_channel_idx + i.channels)), source=p) - ) - cur_channel_idx += i.channels - assert all( - i.samplerate == infos[0].samplerate for i in infos[1:] - ), f"Mismatched sampling rates for individual audio files in: {path_or_paths}" - recording = Recording( - id=path_or_paths[0], - sources=sources, - sampling_rate=infos[0].samplerate, - num_samples=infos[0].frames, - duration=infos[0].duration, - channel_ids=list(range(0, cur_channel_idx)), - ) - else: - recording = Recording.from_file(path_or_paths) - return recording - - -def create_array(path: str) -> Array: - assert path.endswith(".npy"), f"Currently only conversion of numpy files is supported (got: {path})" - arr = np.load(path) - parent, path = os.path.split(path) - return Array( - storage_type="numpy_files", - storage_path=parent, - storage_key=path, - shape=list(arr.shape), - ) - - -def convert_manifest_nemo_to_lhotse( - input_manifest: str, - output_manifest: str, - input_key: str = 'input_filepath', - target_key: str = 'target_filepath', - reference_key: str = 'reference_filepath', - embedding_key: str = 'embedding_filepath', - force_absolute_paths: bool = False, -): - """ - Convert an audio-to-audio manifest from NeMo format to Lhotse format. - - Args: - input_manifest: Path to the input NeMo manifest. - output_manifest: Path where we'll write the output Lhotse manifest (supported extensions: .jsonl.gz and .jsonl). - input_key: Key of the input recording, mapped to Lhotse's 'Cut.recording'. - target_key: Key of the target recording, mapped to Lhotse's 'Cut.target_recording'. - reference_key: Key of the reference recording, mapped to Lhotse's 'Cut.reference_recording'. - embedding_key: Key of the embedding, mapped to Lhotse's 'Cut.embedding_vector'. - force_absolute_paths: If True, the paths in the output manifest will be absolute. - """ - with CutSet.open_writer(output_manifest) as writer: - for item in load_jsonl(input_manifest): - - # Create Lhotse recording and cut object, apply offset and duration slicing if present. - item_input_key = item.pop(input_key) - recording = create_recording(get_full_path(audio_file=item_input_key, manifest_file=input_manifest)) - cut = recording.to_cut().truncate(duration=item.pop("duration"), offset=item.pop("offset", 0.0)) - - _as_relative(cut.recording, item_input_key, enabled=not force_absolute_paths) - - if (channels := item.pop(INPUT_CHANNEL_SELECTOR, None)) is not None: - if cut.num_channels == 1: - assert ( - len(channels) == 1 and channels[0] == 0 - ), f"The input recording has only a single channel, but manifest specified {INPUT_CHANNEL_SELECTOR}={channels}" - else: - cut = cut.with_channels(channels) - - if target_key in item: - item_target_key = item.pop(target_key) - cut.target_recording = create_recording( - get_full_path(audio_file=item_target_key, manifest_file=input_manifest) - ) - - _as_relative(cut.target_recording, item_target_key, enabled=not force_absolute_paths) - - if (channels := item.pop(TARGET_CHANNEL_SELECTOR, None)) is not None: - if cut.target_recording.num_channels == 1: - assert ( - len(channels) == 1 and channels[0] == 0 - ), f"The target recording has only a single channel, but manifest specified {TARGET_CHANNEL_SELECTOR}={channels}" - else: - cut = cut.with_custom(LHOTSE_TARGET_CHANNEL_SELECTOR, channels) - - if reference_key in item: - item_reference_key = item.pop(reference_key) - cut.reference_recording = create_recording( - get_full_path(audio_file=item_reference_key, manifest_file=input_manifest) - ) - - _as_relative(cut.reference_recording, item_target_key, enabled=not force_absolute_paths) - - if (channels := item.pop(REFERENCE_CHANNEL_SELECTOR, None)) is not None: - if cut.reference_recording.num_channels == 1: - assert ( - len(channels) == 1 and channels[0] == 0 - ), f"The reference recording has only a single channel, but manifest specified {REFERENCE_CHANNEL_SELECTOR}={channels}" - else: - cut = cut.with_custom(LHOTSE_REFERENCE_CHANNEL_SELECTOR, channels) - - if embedding_key in item: - item_embedding_key = item.pop(embedding_key) - cut.embedding_vector = create_array( - get_full_path(audio_file=item_embedding_key, manifest_file=input_manifest) - ) - - if not force_absolute_paths: - # Use the same format for paths as in the original manifest - cut.embedding_vector.storage_path = "" - cut.embedding_vector.storage_key = item_embedding_key - - if item: - cut.custom.update(item) # any field that's still left goes to custom fields - - writer.write(cut) - - -def _as_relative(recording: Recording, paths: list[str] | str, enabled: bool) -> None: - if not enabled: - return - if isinstance(paths, str): - paths = [paths] - assert len(recording.sources) == len( - paths - ), f"Mismatched number of sources for lhotse Recording and the override list. Got {recording=} and {paths=}" - for source, path in zip(recording.sources, paths): - source.source = path diff --git a/nemo/collections/audio/data/data_simulation.py b/nemo/collections/audio/data/data_simulation.py deleted file mode 100644 index f70b34fe83ed02faa9a172e16280a2b6cf62d63a..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/data/data_simulation.py +++ /dev/null @@ -1,2395 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import itertools -import multiprocessing -import os -import random -from typing import Dict, Iterable, List, Optional, Tuple, Union - -import librosa -import matplotlib.pyplot as plt -import numpy as np -import soundfile as sf -from numpy.random import default_rng -from omegaconf import DictConfig, OmegaConf -from scipy.signal import convolve -from scipy.spatial.transform import Rotation -from tqdm import tqdm - -from nemo.collections.asr.parts.preprocessing.segment import AudioSegment -from nemo.collections.asr.parts.utils.manifest_utils import read_manifest, write_manifest -from nemo.collections.audio.parts.utils.audio import db2mag, generate_approximate_noise_field, mag2db, pow2db, rms -from nemo.utils import logging - -try: - import pyroomacoustics as pra - - PRA = True -except ImportError: - PRA = False - -try: - import h5py - - HAS_H5PY = True -except ImportError: - HAS_H5PY = False - - -def check_angle(key: str, val: Union[float, Iterable[float]]) -> bool: - """Check if the angle value is within the expected range. Input - values are in degrees. - - Note: - azimuth: angle between a projection on the horizontal (xy) plane and - positive x axis. Increases counter-clockwise. Range: [-180, 180]. - elevation: angle between a vector an its projection on the horizontal (xy) plane. - Positive above, negative below, i.e., north=+90, south=-90. Range: [-90, 90] - yaw: rotation around the z axis. Defined accoding to right-hand rule. - Range: [-180, 180] - pitch: rotation around the yʹ axis. Defined accoding to right-hand rule. - Range: [-90, 90] - roll: rotation around the xʺ axis. Defined accoding to right-hand rule. - Range: [-180, 180] - - Args: - key: angle type - val: values in degrees - - Returns: - True if all values are within the expected range. - """ - if np.isscalar(val): - min_val = max_val = val - else: - min_val = min(val) - max_val = max(val) - - if key == 'azimuth' and -180 <= min_val <= max_val <= 180: - return True - if key == 'elevation' and -90 <= min_val <= max_val <= 90: - return True - if key == 'yaw' and -180 <= min_val <= max_val <= 180: - return True - if key == 'pitch' and -90 <= min_val <= max_val <= 90: - return True - if key == 'roll' and -180 <= min_val <= max_val <= 180: - return True - - raise ValueError(f'Invalid value for angle {key} = {val}') - - -def wrap_to_180(angle: float) -> float: - """Wrap an angle to range ±180 degrees. - - Args: - angle: angle in degrees - - Returns: - Angle in degrees wrapped to ±180 degrees. - """ - return angle - np.floor(angle / 360 + 1 / 2) * 360 - - -class ArrayGeometry(object): - """A class to simplify handling of array geometry. - - Supports translation and rotation of the array and calculation of - spherical coordinates of a given point relative to the internal - coordinate system of the array. - - Args: - mic_positions: 3D coordinates, with shape (num_mics, 3) - center: optional position of the center of the array. Defaults to the average of the coordinates. - internal_cs: internal coordinate system for the array relative to the global coordinate system. - Defaults to (x, y, z), and is rotated with the array. - """ - - def __init__( - self, - mic_positions: Union[np.ndarray, List], - center: Optional[np.ndarray] = None, - internal_cs: Optional[np.ndarray] = None, - ): - if isinstance(mic_positions, Iterable): - mic_positions = np.array(mic_positions) - - if not mic_positions.ndim == 2: - raise ValueError( - f'Expecting a 2D array specifying mic positions, but received {mic_positions.ndim}-dim array' - ) - - if not mic_positions.shape[1] == 3: - raise ValueError(f'Expecting 3D positions, but received {mic_positions.shape[1]}-dim positions') - - mic_positions_center = np.mean(mic_positions, axis=0) - self.centered_positions = mic_positions - mic_positions_center - self.center = mic_positions_center if center is None else center - - # Internal coordinate system - if internal_cs is None: - # Initially aligned with the global - self.internal_cs = np.eye(3) - else: - self.internal_cs = internal_cs - - @property - def num_mics(self): - """Return the number of microphones for the current array.""" - return self.centered_positions.shape[0] - - @property - def positions(self): - """Absolute positions of the microphones.""" - return self.centered_positions + self.center - - @property - def internal_positions(self): - """Positions in the internal coordinate system.""" - return np.matmul(self.centered_positions, self.internal_cs.T) - - @property - def radius(self): - """Radius of the array, relative to the center.""" - return max(np.linalg.norm(self.centered_positions, axis=1)) - - @staticmethod - def get_rotation(yaw: float = 0, pitch: float = 0, roll: float = 0) -> Rotation: - """Get a Rotation object for given angles. - - All angles are defined according to the right-hand rule. - - Args: - yaw: rotation around the z axis - pitch: rotation around the yʹ axis - roll: rotation around the xʺ axis - - Returns: - A rotation object constructed using the provided angles. - """ - check_angle('yaw', yaw) - check_angle('pitch', pitch) - check_angle('roll', roll) - - return Rotation.from_euler('ZYX', [yaw, pitch, roll], degrees=True) - - def translate(self, to: np.ndarray): - """Translate the array center to a new point. - - Translation does not change the centered positions or the internal coordinate system. - - Args: - to: 3D point, shape (3,) - """ - self.center = to - - def rotate(self, yaw: float = 0, pitch: float = 0, roll: float = 0): - """Apply rotation on the mic array. - - This rotates the centered microphone positions and the internal - coordinate system, it doesn't change the center of the array. - - All angles are defined according to the right-hand rule. - For example, this means that a positive pitch will result in a rotation from z - to x axis, which will result in a reduced elevation with respect to the global - horizontal plane. - - Args: - yaw: rotation around the z axis - pitch: rotation around the yʹ axis - roll: rotation around the xʺ axis - """ - # construct rotation using TB angles - rotation = self.get_rotation(yaw=yaw, pitch=pitch, roll=roll) - - # rotate centered positions - self.centered_positions = rotation.apply(self.centered_positions) - - # apply the same transformation on the internal coordinate system - self.internal_cs = rotation.apply(self.internal_cs) - - def new_rotated_array(self, yaw: float = 0, pitch: float = 0, roll: float = 0): - """Create a new array by rotating this array. - - Args: - yaw: rotation around the z axis - pitch: rotation around the yʹ axis - roll: rotation around the xʺ axis - - Returns: - A new ArrayGeometry object constructed using the provided angles. - """ - new_array = ArrayGeometry(mic_positions=self.positions, center=self.center, internal_cs=self.internal_cs) - new_array.rotate(yaw=yaw, pitch=pitch, roll=roll) - return new_array - - def spherical_relative_to_array( - self, point: np.ndarray, use_internal_cs: bool = True - ) -> Tuple[float, float, float]: - """Return spherical coordinates of a point relative to the internal coordinate system. - - Args: - point: 3D coordinate, shape (3,) - use_internal_cs: Calculate position relative to the internal coordinate system. - If `False`, the positions will be calculated relative to the - external coordinate system centered at `self.center`. - - Returns: - A tuple (distance, azimuth, elevation) relative to the mic array. - """ - rel_position = point - self.center - distance = np.linalg.norm(rel_position) - - if use_internal_cs: - # transform from the absolute coordinate system to the internal coordinate system - rel_position = np.matmul(self.internal_cs, rel_position) - - # get azimuth - azimuth = np.arctan2(rel_position[1], rel_position[0]) / np.pi * 180 - # get elevation - elevation = np.arcsin(rel_position[2] / distance) / np.pi * 180 - - return distance, azimuth, elevation - - def __str__(self): - with np.printoptions(precision=3, suppress=True): - desc = f"{type(self)}:\ncenter =\n{self.center}\ncentered positions =\n{self.centered_positions}\nradius = \n{self.radius:.3}\nabsolute positions =\n{self.positions}\ninternal coordinate system =\n{self.internal_cs}\n\n" - return desc - - def plot(self, elev=30, azim=-55, mic_size=25): - """Plot microphone positions. - - Args: - elev: elevation for the view of the plot - azim: azimuth for the view of the plot - mic_size: size of the microphone marker in the plot - """ - fig = plt.figure() - ax = fig.add_subplot(projection='3d') - - # show mic positions - for m in range(self.num_mics): - # show mic - ax.scatter( - self.positions[m, 0], - self.positions[m, 1], - self.positions[m, 2], - marker='o', - c='black', - s=mic_size, - depthshade=False, - ) - # add label - ax.text(self.positions[m, 0], self.positions[m, 1], self.positions[m, 2], str(m), c='red', zorder=10) - - # show the internal coordinate system - ax.quiver( - self.center[0], - self.center[1], - self.center[2], - self.internal_cs[:, 0], - self.internal_cs[:, 1], - self.internal_cs[:, 2], - length=self.radius, - label='internal cs', - normalize=False, - linestyle=':', - linewidth=1.0, - ) - for dim, label in enumerate(['x′', 'y′', 'z′']): - label_pos = self.center + self.radius * self.internal_cs[dim] - ax.text(label_pos[0], label_pos[1], label_pos[2], label, tuple(self.internal_cs[dim]), c='blue') - try: - # Unfortunately, equal aspect ratio has been added very recently to Axes3D - ax.set_aspect('equal') - except NotImplementedError: - logging.warning('Equal aspect ratio not supported by Axes3D') - # Set view - ax.view_init(elev=elev, azim=azim) - # Set reasonable limits for all axes, even for the case of an unequal aspect ratio - ax.set_xlim([self.center[0] - self.radius, self.center[0] + self.radius]) - ax.set_ylim([self.center[1] - self.radius, self.center[1] + self.radius]) - ax.set_zlim([self.center[2] - self.radius, self.center[2] + self.radius]) - - ax.set_xlabel('x/m') - ax.set_ylabel('y/m') - ax.set_zlabel('z/m') - ax.set_title('Microphone positions') - ax.legend() - plt.show() - - -def convert_placement_to_range( - placement: dict, room_dim: Iterable[float], object_radius: float = 0 -) -> List[List[float]]: - """Given a placement dictionary, return ranges for each dimension. - - Args: - placement: dictionary containing x, y, height, and min_to_wall - room_dim: dimensions of the room, shape (3,) - object_radius: radius of the object to be placed - - Returns - List with a range of values for each dimensions. - """ - if not np.all(np.array(room_dim) > 0): - raise ValueError(f'Room dimensions must be positive: {room_dim}') - - if object_radius < 0: - raise ValueError(f'Object radius must be non-negative: {object_radius}') - - placement_range = [None] * 3 - min_to_wall = placement.get('min_to_wall', 0) - - if min_to_wall < 0: - raise ValueError(f'Min distance to wall must be positive: {min_to_wall}') - - for idx, key in enumerate(['x', 'y', 'height']): - # Room dimension - dim = room_dim[idx] - # Construct the range - val = placement.get(key) - if val is None: - # No constrained specified on the coordinate of the mic center - min_val, max_val = 0, dim - elif np.isscalar(val): - min_val = max_val = val - else: - if len(val) != 2: - raise ValueError(f'Invalid value for placement for dim {idx}/{key}: {str(placement)}') - min_val, max_val = val - - # Make sure the array is not too close to a wall - min_val = max(min_val, min_to_wall + object_radius) - max_val = min(max_val, dim - min_to_wall - object_radius) - - if min_val > max_val or min(min_val, max_val) < 0: - raise ValueError(f'Invalid range dim {idx}/{key}: min={min_val}, max={max_val}') - - placement_range[idx] = [min_val, max_val] - - return placement_range - - -class RIRCorpusGenerator(object): - """Creates a corpus of RIRs based on a defined configuration of rooms and microphone array. - - RIRs are generated using `generate` method. - """ - - def __init__(self, cfg: DictConfig): - """ - Args: - cfg: dictionary with parameters of the simulation - """ - logging.info("Initialize RIRCorpusGenerator") - self._cfg = cfg - self.check_cfg() - - @property - def cfg(self): - """Property holding the internal config of the object. - - Note: - Changes to this config are not reflected in the state of the object. - Please create a new model with the updated config. - """ - return self._cfg - - @property - def sample_rate(self): - return self._cfg.sample_rate - - @cfg.setter - def cfg(self, cfg): - """Property holding the internal config of the object. - - Note: - Changes to this config are not reflected in the state of the object. - Please create a new model with the updated config. - """ - self._cfg = cfg - - def check_cfg(self): - """ - Checks provided configuration to ensure it has the minimal required - configuration the values are in a reasonable range. - """ - # sample rate - sample_rate = self.cfg.get('sample_rate') - if sample_rate is None: - raise ValueError('Sample rate not provided.') - elif sample_rate < 0: - raise ValueError(f'Sample rate must to be positive: {sample_rate}') - - # room configuration - room_cfg = self.cfg.get('room') - if room_cfg is None: - raise ValueError('Room configuration not provided') - - if room_cfg.get('num') is None: - raise ValueError('Number of rooms per subset not provided') - - if room_cfg.get('dim') is None: - raise ValueError('Room dimensions not provided') - - for idx, key in enumerate(['width', 'length', 'height']): - dim = room_cfg.dim.get(key) - - if dim is None: - # not provided - raise ValueError(f'Room {key} needs to be a scalar or a range, currently it is None') - elif np.isscalar(dim) and dim <= 0: - # fixed dimension - raise ValueError(f'A fixed dimension must be positive for {key}: {dim}') - elif len(dim) != 2 or not 0 < dim[0] < dim[1]: - # not a valid range - raise ValueError(f'Range must be specified with two positive increasing elements for {key}: {dim}') - - rt60 = room_cfg.get('rt60') - if rt60 is None: - # not provided - raise ValueError('RT60 needs to be a scalar or a range, currently it is None') - elif np.isscalar(rt60) and rt60 <= 0: - # fixed dimension - raise ValueError(f'RT60 must be positive: {rt60}') - elif len(rt60) != 2 or not 0 < rt60[0] < rt60[1]: - # not a valid range - raise ValueError(f'RT60 range must be specified with two positive increasing elements: {rt60}') - - # mic array - mic_cfg = self.cfg.get('mic_array') - if mic_cfg is None: - raise ValueError('Mic configuration not provided') - - if mic_cfg.get('positions') == 'random': - # Only num_mics and placement are required - mic_cfg_keys = ['num_mics', 'placement'] - else: - mic_cfg_keys = ['positions', 'placement', 'orientation'] - - for key in mic_cfg_keys: - if key not in mic_cfg: - raise ValueError(f'Mic array {key} not provided') - - # source - source_cfg = self.cfg.get('source') - if source_cfg is None: - raise ValueError('Source configuration not provided') - - if source_cfg.get('num') is None: - raise ValueError('Number of sources per room not provided') - elif source_cfg.num <= 0: - raise ValueError(f'Number of sources must be positive: {source_cfg.num}') - - if 'placement' not in source_cfg: - raise ValueError('Source placement dictionary not provided') - - # anechoic - if self.cfg.get('anechoic') is None: - raise ValueError('Anechoic configuratio not provided.') - - def generate_room_params(self) -> dict: - """Generate randomized room parameters based on the provided - configuration. - """ - # Prepare room sim parameters - if not PRA: - raise ImportError('pyroomacoustics is required for room simulation') - - room_cfg = self.cfg.room - - # Prepare rt60 - if room_cfg.rt60 is None: - raise ValueError('Room RT60 needs to be a scalar or a range, currently it is None') - - if np.isscalar(room_cfg.rt60): - assert room_cfg.rt60 > 0, f'RT60 should be positive: {room_cfg.rt60}' - rt60 = room_cfg.rt60 - elif len(room_cfg.rt60) == 2: - assert ( - 0 < room_cfg.rt60[0] <= room_cfg.rt60[1] - ), f'Expecting two non-decreasing values for RT60, received {room_cfg.rt60}' - rt60 = self.random.uniform(low=room_cfg.rt60[0], high=room_cfg.rt60[1]) - else: - raise ValueError(f'Unexpected value for RT60: {room_cfg.rt60}') - - # Generate a room with random dimensions - num_retries = self.cfg.get('num_retries', 20) - - for n in range(num_retries): - - # width, length, height - room_dim = np.zeros(3) - - # prepare dimensions - for idx, key in enumerate(['width', 'length', 'height']): - # get configured dimension - dim = room_cfg.dim[key] - - # set a value - if dim is None: - raise ValueError(f'Room {key} needs to be a scalar or a range, currently it is None') - elif np.isscalar(dim): - assert dim > 0, f'Dimension should be positive for {key}: {dim}' - room_dim[idx] = dim - elif len(dim) == 2: - assert 0 < dim[0] <= dim[1], f'Expecting two non-decreasing values for {key}, received {dim}' - # Reduce dimension if the previous attempt failed - room_dim[idx] = self.random.uniform(low=dim[0], high=dim[1] - n * (dim[1] - dim[0]) / num_retries) - else: - raise ValueError(f'Unexpected value for {key}: {dim}') - - try: - # Get parameters from size and RT60 - room_absorption, room_max_order = pra.inverse_sabine(rt60, room_dim) - break - except Exception as e: - logging.debug('Inverse sabine failed: %s', str(e)) - # Inverse sabine may fail if the room is too large for the selected RT60. - # Try again by generate a smaller room. - room_absorption = room_max_order = None - continue - - if room_absorption is None or room_max_order is None: - raise RuntimeError(f'Evaluation of parameters failed for RT60 {rt60}s and room size {room_dim}.') - - # Return the required values - room_params = { - 'dim': room_dim, - 'absorption': room_absorption, - 'max_order': room_max_order, - 'rt60_theoretical': rt60, - 'anechoic_absorption': self.cfg.anechoic.absorption, - 'anechoic_max_order': self.cfg.anechoic.max_order, - 'sample_rate': self.cfg.sample_rate, - } - return room_params - - def generate_array(self, room_dim: Iterable[float]) -> ArrayGeometry: - """Generate array placement for the current room and config. - - Args: - room_dim: dimensions of the room, [width, length, height] - - Returns: - Randomly placed microphone array. - """ - mic_cfg = self.cfg.mic_array - - if mic_cfg.positions == 'random': - # Create a radom set of microphones - num_mics = mic_cfg.num_mics - mic_positions = [] - - # Each microphone is placed individually - placement_range = convert_placement_to_range( - placement=mic_cfg.placement, room_dim=room_dim, object_radius=0 - ) - - # Randomize mic placement - for m in range(num_mics): - position_m = [None] * 3 - for idx in range(3): - position_m[idx] = self.random.uniform(low=placement_range[idx][0], high=placement_range[idx][1]) - mic_positions.append(position_m) - - mic_array = ArrayGeometry(mic_positions) - - else: - mic_array = ArrayGeometry(mic_cfg.positions) - - # Randomize center placement - center = np.zeros(3) - placement_range = convert_placement_to_range( - placement=mic_cfg.placement, room_dim=room_dim, object_radius=mic_array.radius - ) - - for idx in range(len(center)): - center[idx] = self.random.uniform(low=placement_range[idx][0], high=placement_range[idx][1]) - - # Place the array at the configured center point - mic_array.translate(to=center) - - # Randomize orientation - orientation = dict() - for key in ['yaw', 'roll', 'pitch']: - # angle for current orientation - angle = mic_cfg.orientation[key] - - if angle is None: - raise ValueError(f'Mic array {key} should be a scalar or a range, currently it is set to None.') - - # check it's within the expected range - check_angle(key, angle) - - if np.isscalar(angle): - orientation[key] = angle - elif len(angle) == 2: - assert angle[0] <= angle[1], f"Expecting two non-decreasing values for {key}, received {angle}" - # generate integer values, for easier bucketing, if necessary - orientation[key] = self.random.uniform(low=angle[0], high=angle[1]) - else: - raise ValueError(f'Unexpected value for orientation {key}: {angle}') - - # Rotate the array to match the selected orientation - mic_array.rotate(**orientation) - - return mic_array - - def generate_source_position(self, room_dim: Iterable[float]) -> List[List[float]]: - """Generate position for all sources in a room. - - Args: - room_dim: dimensions of a 3D shoebox room - - Returns: - List of source positions, with each position characterized with a 3D coordinate - """ - source_cfg = self.cfg.source - placement_range = convert_placement_to_range(placement=source_cfg.placement, room_dim=room_dim) - source_position = [] - - for n in range(source_cfg.num): - # generate a random point withing the range - s_pos = [None] * 3 - for idx in range(len(s_pos)): - s_pos[idx] = self.random.uniform(low=placement_range[idx][0], high=placement_range[idx][1]) - source_position.append(s_pos) - - return source_position - - def generate(self): - """Generate RIR corpus. - - This method will prepare randomized examples based on the current configuration, - run room simulations and save results to output_dir. - """ - logging.info("Generate RIR corpus") - - # Initialize - self.random = default_rng(seed=self.cfg.random_seed) - - # Prepare output dir - output_dir = self.cfg.output_dir - if output_dir.endswith('.yaml'): - output_dir = output_dir[:-5] - - # Create absolute path - logging.info('Output dir set to: %s', output_dir) - - # Generate all cases - for subset, num_rooms in self.cfg.room.num.items(): - - output_dir_subset = os.path.join(output_dir, subset) - examples = [] - - if not os.path.exists(output_dir_subset): - logging.info('Creating output directory: %s', output_dir_subset) - os.makedirs(output_dir_subset) - elif os.path.isdir(output_dir_subset) and len(os.listdir(output_dir_subset)) > 0: - raise RuntimeError(f'Output directory {output_dir_subset} is not empty.') - - # Generate examples - for n_room in range(num_rooms): - - # room info - room_params = self.generate_room_params() - - # array placement - mic_array = self.generate_array(room_params['dim']) - - # source placement - source_position = self.generate_source_position(room_params['dim']) - - # file name for the file - room_filepath = os.path.join(output_dir_subset, f'{subset}_room_{n_room:06d}.h5') - - # prepare example - example = { - 'room_params': room_params, - 'mic_array': mic_array, - 'source_position': source_position, - 'room_filepath': room_filepath, - } - examples.append(example) - - # Simulation - if (num_workers := self.cfg.get('num_workers')) is None: - num_workers = os.cpu_count() - 1 - - if num_workers > 1: - logging.info(f'Simulate using {num_workers} workers') - with multiprocessing.Pool(processes=num_workers) as pool: - metadata = list(tqdm(pool.imap(simulate_room_kwargs, examples), total=len(examples))) - - else: - logging.info('Simulate using a single worker') - metadata = [] - for example in tqdm(examples, total=len(examples)): - metadata.append(simulate_room(**example)) - - # Save manifest - manifest_filepath = os.path.join(output_dir, f'{subset}_manifest.json') - - if os.path.exists(manifest_filepath) and os.path.isfile(manifest_filepath): - raise RuntimeError(f'Manifest config file exists: {manifest_filepath}') - - # Make all paths in the manifest relative to the output dir - for data in metadata: - data['room_filepath'] = os.path.relpath(data['room_filepath'], start=output_dir) - - write_manifest(manifest_filepath, metadata) - - # Generate plots with information about generated data - plot_filepath = os.path.join(output_dir, f'{subset}_info.png') - - if os.path.exists(plot_filepath) and os.path.isfile(plot_filepath): - raise RuntimeError(f'Plot file exists: {plot_filepath}') - - plot_rir_manifest_info(manifest_filepath, plot_filepath=plot_filepath) - - # Save used configuration for reference - config_filepath = os.path.join(output_dir, 'config.yaml') - if os.path.exists(config_filepath) and os.path.isfile(config_filepath): - raise RuntimeError(f'Output config file exists: {config_filepath}') - - OmegaConf.save(self.cfg, config_filepath, resolve=True) - - -def simulate_room_kwargs(kwargs: dict) -> dict: - """Wrapper around `simulate_room` to handle kwargs. - - `pool.map(simulate_room_kwargs, examples)` would be - equivalent to `pool.starstarmap(simulate_room, examples)` - if `starstarmap` would exist. - - Args: - kwargs: kwargs that are forwarded to `simulate_room` - - Returns: - Dictionary with metadata, see `simulate_room` - """ - return simulate_room(**kwargs) - - -def simulate_room( - room_params: dict, - mic_array: ArrayGeometry, - source_position: Iterable[Iterable[float]], - room_filepath: str, -) -> dict: - """Simulate room - - Args: - room_params: parameters of the room to be simulated - mic_array: defines positions of the microphones - source_positions: positions for all sources to be simulated - room_filepath: results are saved to this path - - Returns: - Dictionary with metadata based on simulation setup - and simulation results. Used to create the corresponding - manifest file. - """ - # room with the selected parameters - room_sim = pra.ShoeBox( - room_params['dim'], - fs=room_params['sample_rate'], - materials=pra.Material(room_params['absorption']), - max_order=room_params['max_order'], - ) - - # same geometry for generating anechoic responses - room_anechoic = pra.ShoeBox( - room_params['dim'], - fs=room_params['sample_rate'], - materials=pra.Material(room_params['anechoic_absorption']), - max_order=room_params['anechoic_max_order'], - ) - - # Compute RIRs - for room in [room_sim, room_anechoic]: - # place the array - room.add_microphone_array(mic_array.positions.T) - - # place the sources - for s_pos in source_position: - room.add_source(s_pos) - - # generate RIRs - room.compute_rir() - - # Get metadata for sources - source_distance = [] - source_azimuth = [] - source_elevation = [] - for s_pos in source_position: - distance, azimuth, elevation = mic_array.spherical_relative_to_array(s_pos) - source_distance.append(distance) - source_azimuth.append(azimuth) - source_elevation.append(elevation) - - # RIRs - rir_dataset = { - 'rir': convert_rir_to_multichannel(room_sim.rir), - 'anechoic': convert_rir_to_multichannel(room_anechoic.rir), - } - - # Prepare metadata dict and return - metadata = { - 'room_filepath': room_filepath, - 'sample_rate': room_params['sample_rate'], - 'dim': room_params['dim'], - 'rir_absorption': room_params['absorption'], - 'rir_max_order': room_params['max_order'], - 'rir_rt60_theory': room_sim.rt60_theory(), - 'rir_rt60_measured': room_sim.measure_rt60().mean(axis=0), # average across mics for each source - 'anechoic_rt60_theory': room_anechoic.rt60_theory(), - 'anechoic_rt60_measured': room_anechoic.measure_rt60().mean(axis=0), # average across mics for each source - 'anechoic_absorption': room_params['anechoic_absorption'], - 'anechoic_max_order': room_params['anechoic_max_order'], - 'mic_positions': mic_array.positions, - 'mic_center': mic_array.center, - 'source_position': source_position, - 'source_distance': source_distance, - 'source_azimuth': source_azimuth, - 'source_elevation': source_elevation, - 'num_sources': len(source_position), - } - - # Save simulated RIR - save_rir_simulation(room_filepath, rir_dataset, metadata) - - return convert_numpy_to_serializable(metadata) - - -def save_rir_simulation(filepath: str, rir_dataset: Dict[str, List[np.array]], metadata: dict): - """Save simulated RIRs and metadata. - - Args: - filepath: Path to the file where the data will be saved. - rir_dataset: Dictionary with RIR data. Each item is a set of multi-channel RIRs. - metadata: Dictionary with related metadata. - """ - if not HAS_H5PY: - raise ImportError("Install h5py to use save_rir_simulation") - if os.path.exists(filepath): - raise RuntimeError(f'Output file exists: {filepath}') - - num_sources = metadata['num_sources'] - - with h5py.File(filepath, 'w') as h5f: - # Save RIRs, each RIR set in a separate group - for rir_key, rir_value in rir_dataset.items(): - if len(rir_value) != num_sources: - raise ValueError( - f'Each RIR dataset should have exactly {num_sources} elements. Current RIR {rir_key} has {len(rir_value)} elements' - ) - - rir_group = h5f.create_group(rir_key) - - # RIRs for different sources are saved under [group]['idx'] - for idx, rir in enumerate(rir_value): - rir_group.create_dataset(f'{idx}', data=rir_value[idx]) - - # Save metadata - metadata_group = h5f.create_group('metadata') - for key, value in metadata.items(): - metadata_group.create_dataset(key, data=value) - - -def load_rir_simulation(filepath: str, source: int = 0, rir_key: str = 'rir') -> Tuple[np.ndarray, float]: - """Load simulated RIRs and metadata. - - Args: - filepath: Path to simulated RIR data - source: Index of a source. - rir_key: String to denote which RIR to load, if there are multiple available. - - Returns: - Multichannel RIR as ndarray with shape (num_samples, num_channels) and scalar sample rate. - """ - if not HAS_H5PY: - raise ImportError("Install h5py to use load_rir_simulation") - with h5py.File(filepath, 'r') as h5f: - # Load RIR - rir = h5f[rir_key][f'{source}'][:] - - # Load metadata - sample_rate = h5f['metadata']['sample_rate'][()] - - return rir, sample_rate - - -def convert_numpy_to_serializable(data: Union[dict, float, np.ndarray]) -> Union[dict, float, np.ndarray]: - """Convert all numpy estries to list. - Can be used to preprocess data before writing to a JSON file. - - Args: - data: Dictionary, array or scalar. - - Returns: - The same structure, but converted to list if - the input is np.ndarray, so `data` can be seralized. - """ - if isinstance(data, dict): - for key, val in data.items(): - data[key] = convert_numpy_to_serializable(val) - elif isinstance(data, list): - data = [convert_numpy_to_serializable(d) for d in data] - elif isinstance(data, np.ndarray): - data = data.tolist() - elif isinstance(data, np.integer): - data = int(data) - elif isinstance(data, np.floating): - data = float(data) - elif isinstance(data, np.generic): - data = data.item() - - return data - - -def convert_rir_to_multichannel(rir: List[List[np.ndarray]]) -> List[np.ndarray]: - """Convert RIR to a list of arrays. - - Args: - rir: list of lists, each element is a single-channel RIR - - Returns: - List of multichannel RIRs - """ - num_mics = len(rir) - num_sources = len(rir[0]) - - mc_rir = [None] * num_sources - - for n_source in range(num_sources): - rir_len = [len(rir[m][n_source]) for m in range(num_mics)] - max_len = max(rir_len) - mc_rir[n_source] = np.zeros((max_len, num_mics)) - for n_mic, len_mic in enumerate(rir_len): - mc_rir[n_source][:len_mic, n_mic] = rir[n_mic][n_source] - - return mc_rir - - -def plot_rir_manifest_info(filepath: str, plot_filepath: str = None): - """Plot distribution of parameters from manifest file. - - Args: - filepath: path to a RIR corpus manifest file - plot_filepath: path to save the plot at - """ - metadata = read_manifest(filepath) - - # source placement - source_distance = [] - source_azimuth = [] - source_elevation = [] - source_height = [] - - # room config - rir_rt60_theory = [] - rir_rt60_measured = [] - anechoic_rt60_theory = [] - anechoic_rt60_measured = [] - - # get the required data - for data in metadata: - # source config - source_distance += data['source_distance'] - source_azimuth += data['source_azimuth'] - source_elevation += data['source_elevation'] - source_height += [s_pos[2] for s_pos in data['source_position']] - - # room config - rir_rt60_theory.append(data['rir_rt60_theory']) - rir_rt60_measured += data['rir_rt60_measured'] - anechoic_rt60_theory.append(data['anechoic_rt60_theory']) - anechoic_rt60_measured += data['anechoic_rt60_measured'] - - # plot - plt.figure(figsize=(12, 6)) - - plt.subplot(2, 4, 1) - plt.hist(source_distance, label='distance') - plt.xlabel('distance / m') - plt.ylabel('# examples') - plt.title('Source-to-array center distance') - - plt.subplot(2, 4, 2) - plt.hist(source_azimuth, label='azimuth') - plt.xlabel('azimuth / deg') - plt.ylabel('# examples') - plt.title('Source-to-array center azimuth') - - plt.subplot(2, 4, 3) - plt.hist(source_elevation, label='elevation') - plt.xlabel('elevation / deg') - plt.ylabel('# examples') - plt.title('Source-to-array center elevation') - - plt.subplot(2, 4, 4) - plt.hist(source_height, label='source height') - plt.xlabel('height / m') - plt.ylabel('# examples') - plt.title('Source height') - - plt.subplot(2, 4, 5) - plt.hist(rir_rt60_theory, label='theory') - plt.xlabel('RT60 / s') - plt.ylabel('# examples') - plt.title('RT60 theory') - - plt.subplot(2, 4, 6) - plt.hist(rir_rt60_measured, label='measured') - plt.xlabel('RT60 / s') - plt.ylabel('# examples') - plt.title('RT60 measured') - - plt.subplot(2, 4, 7) - plt.hist(anechoic_rt60_theory, label='theory') - plt.xlabel('RT60 / s') - plt.ylabel('# examples') - plt.title('RT60 theory (anechoic)') - - plt.subplot(2, 4, 8) - plt.hist(anechoic_rt60_measured, label='measured') - plt.xlabel('RT60 / s') - plt.ylabel('# examples') - plt.title('RT60 measured (anechoic)') - - for n in range(8): - plt.subplot(2, 4, n + 1) - plt.grid() - plt.legend(loc='lower left') - - plt.tight_layout() - - if plot_filepath is not None: - plt.savefig(plot_filepath) - plt.close() - logging.info('Plot saved at %s', plot_filepath) - - -class RIRMixGenerator(object): - """Creates a dataset of mixed signals at the microphone - by combining target speech, background noise and interference. - - Correspnding signals are are generated and saved - using the `generate` method. - - Input configuration is expexted to have the following structure - ``` - sample_rate: sample rate used for simulation - room: - subset: manifest for RIR data - target: - subset: manifest for target source data - noise: - subset: manifest for noise data - interference: - subset: manifest for interference data - interference_probability: probability that interference is present - max_num_interferers: max number of interferers, randomly selected between 0 and max - mix: - subset: - num: number of examples to generate - rsnr: range of RSNR - rsir: range of RSIR - ref_mic: reference microphone - ref_mic_rms: desired RMS at ref_mic - ``` - """ - - def __init__(self, cfg: DictConfig): - """ - Instantiate a RIRMixGenerator object. - - Args: - cfg: generator configuration defining data for room, - target signal, noise, interference and mixture - """ - logging.info("Initialize RIRMixGenerator") - self._cfg = cfg - self.check_cfg() - - self.subsets = self.cfg.room.keys() - logging.info('Initialized with %d subsets: %s', len(self.subsets), str(self.subsets)) - - # load manifests - self.metadata = dict() - for subset in self.subsets: - subset_data = dict() - - logging.info('Loading data for %s', subset) - for key in ['room', 'target', 'noise', 'interference']: - try: - subset_data[key] = read_manifest(self.cfg[key][subset]) - logging.info('\t%-*s: \t%d files', 15, key, len(subset_data[key])) - except Exception as e: - subset_data[key] = None - logging.info('\t%-*s: \t0 files', 15, key) - logging.warning('\t\tManifest data not loaded. Exception: %s', str(e)) - - self.metadata[subset] = subset_data - - logging.info('Loaded all manifests') - - self.num_retries = self.cfg.get('num_retries', 5) - - @property - def cfg(self): - """Property holding the internal config of the object. - - Note: - Changes to this config are not reflected in the state of the object. - Please create a new model with the updated config. - """ - return self._cfg - - @property - def sample_rate(self): - return self._cfg.sample_rate - - @cfg.setter - def cfg(self, cfg): - """Property holding the internal config of the object. - - Note: - Changes to this config are not reflected in the state of the object. - Please create a new model with the updated config. - """ - self._cfg = cfg - - def check_cfg(self): - """ - Checks provided configuration to ensure it has the minimal required - configuration the values are in a reasonable range. - """ - # sample rate - sample_rate = self.cfg.get('sample_rate') - if sample_rate is None: - raise ValueError('Sample rate not provided.') - elif sample_rate < 0: - raise ValueError(f'Sample rate must be positive: {sample_rate}') - - # room configuration - room_cfg = self.cfg.get('room') - if not room_cfg: - raise ValueError( - 'Room configuration not provided. Expecting RIR manifests in format {subset: path_to_manifest}' - ) - - # target configuration - target_cfg = self.cfg.get('target') - if not target_cfg: - raise ValueError( - 'Target configuration not provided. Expecting audio manifests in format {subset: path_to_manifest}' - ) - - for key in ['azimuth', 'elevation', 'distance']: - value = target_cfg.get(key) - - if value is None or np.isscalar(value): - # no constraint or a fixed dimension is ok - pass - elif len(value) != 2 or not value[0] < value[1]: - # not a valid range - raise ValueError(f'Range must be specified with two positive increasing elements for {key}: {value}') - - # noise configuration - noise_cfg = self.cfg.get('noise') - if not noise_cfg: - raise ValueError( - 'Noise configuration not provided. Expecting audio manifests in format {subset: path_to_manifest}' - ) - - # interference configuration - interference_cfg = self.cfg.get('interference') - if not interference_cfg: - logging.info('Interference configuration not provided.') - else: - interference_probability = interference_cfg.get('interference_probability', 0) - max_num_interferers = interference_cfg.get('max_num_interferers', 0) - min_azimuth_to_target = interference_cfg.get('min_azimuth_to_target', 0) - if interference_probability is not None: - if interference_probability < 0: - raise ValueError( - f'Interference probability must be non-negative. Current value: {interference_probability}' - ) - elif interference_probability > 0: - assert ( - max_num_interferers is not None and max_num_interferers > 0 - ), f'Max number of interferers must be positive. Current value: {max_num_interferers}' - assert ( - min_azimuth_to_target is not None and min_azimuth_to_target >= 0 - ), 'Min azimuth to target must be non-negative' - - # mix configuration - mix_cfg = self.cfg.get('mix') - if not mix_cfg: - raise ValueError('Mix configuration not provided. Expecting configuration for each subset.') - if 'ref_mic' not in mix_cfg: - raise ValueError('Reference microphone not defined.') - if 'ref_mic_rms' not in mix_cfg: - raise ValueError('Reference microphone RMS not defined.') - - def generate_target(self, subset: str) -> dict: - """ - Prepare a dictionary with target configuration. - - The output dictionary contains the following information - ``` - room_index: index of the selected room from the RIR corpus - room_filepath: path to the room simulation file - source: index of the selected source for the target - rt60: reverberation time of the selected room - num_mics: number of microphones - azimuth: azimuth of the target source, relative to the microphone array - elevation: elevation of the target source, relative to the microphone array - distance: distance of the target source, relative to the microphone array - audio_filepath: path to the audio file for the target source - text: text for the target source audio signal, if available - duration: duration of the target source audio signal - ``` - - Args: - subset: string denoting a subset which will be used to selected target - audio and room parameters. - - Returns: - Dictionary with target configuration, including room, source index, and audio information. - """ - - # Utility function - def select_target_source(room_metadata, room_indices): - """Find a room and a source that satisfies the constraints.""" - for room_index in room_indices: - # Select room - room_data = room_metadata[room_index] - - # Candidate sources - sources = self.random.choice(room_data['num_sources'], size=self.num_retries, replace=False) - - # Select target source in this room - for source in sources: - # Check constraints - constraints_met = [] - for constraint in ['azimuth', 'elevation', 'distance']: - if self.cfg.target.get(constraint) is not None: - # Check that the selected source is in the range - source_value = room_data[f'source_{constraint}'][source] - if self.cfg.target[constraint][0] <= source_value <= self.cfg.target[constraint][1]: - constraints_met.append(True) - else: - constraints_met.append(False) - # No need to check the remaining constraints - break - - # Check if a feasible source is found - if all(constraints_met): - # A feasible source has been found - return source, room_index - - return None, None - - # Prepare room & source position - room_metadata = self.metadata[subset]['room'] - room_indices = self.random.choice(len(room_metadata), size=self.num_retries, replace=False) - source, room_index = select_target_source(room_metadata, room_indices) - - if source is None: - raise RuntimeError(f'Could not find a feasible source given target constraints {self.cfg.target}') - - room_data = room_metadata[room_index] - - # Optional: select subset of channels - num_available_mics = len(room_data['mic_positions']) - if 'mic_array' in self.cfg: - num_mics = self.cfg.mic_array['num_mics'] - mic_selection = self.cfg.mic_array['selection'] - - if mic_selection == 'random': - logging.debug('Randomly selecting %d mics', num_mics) - selected_mics = self.random.choice(num_available_mics, size=num_mics, replace=False) - elif isinstance(mic_selection, Iterable): - logging.debug('Using explicitly selected mics: %s', str(mic_selection)) - assert ( - 0 <= min(mic_selection) < num_available_mics - ), f'Expecting mic_selection in range [0,{num_available_mics}), current value: {mic_selection}' - selected_mics = np.array(mic_selection) - else: - raise ValueError(f'Unexpected value for mic_selection: {mic_selection}') - else: - logging.debug('Using all %d available mics', num_available_mics) - num_mics = num_available_mics - selected_mics = np.arange(num_mics) - - # Double-check the number of mics is as expected - assert ( - len(selected_mics) == num_mics - ), f'Expecting {num_mics} mics, but received {len(selected_mics)} mics: {selected_mics}' - logging.debug('Selected mics: %s', str(selected_mics)) - - # Calculate distance from the source to each microphone - mic_positions = np.array(room_data['mic_positions'])[selected_mics] - source_position = np.array(room_data['source_position'][source]) - distance_source_to_mic = np.linalg.norm(mic_positions - source_position, axis=1) - - # Handle relative paths - room_filepath = room_data['room_filepath'] - if not os.path.isabs(room_filepath): - manifest_dir = os.path.dirname(self.cfg.room[subset]) - room_filepath = os.path.join(manifest_dir, room_filepath) - - target_cfg = { - 'room_index': int(room_index), - 'room_filepath': room_filepath, - 'source': source, - 'rt60': room_data['rir_rt60_measured'][source], - 'selected_mics': selected_mics.tolist(), - # Positions - 'source_position': source_position.tolist(), - 'mic_positions': mic_positions.tolist(), - # Relative to center of the array - 'azimuth': room_data['source_azimuth'][source], - 'elevation': room_data['source_elevation'][source], - 'distance': room_data['source_distance'][source], - # Relative to mics - 'distance_source_to_mic': distance_source_to_mic, - } - - return target_cfg - - def generate_interference(self, subset: str, target_cfg: dict) -> List[dict]: - """ - Prepare a list of dictionaries with interference configuration. - - Args: - subset: string denoting a subset which will be used to select interference audio. - target_cfg: dictionary with target configuration. This is used to determine - the minimal required duration for the noise signal. - - Returns: - List of dictionary with interference configuration, including source index and audio information - for one or more interference sources. - """ - if self.metadata[subset]['interference'] is None: - # No interference to be configured - return None - - # Configure interfering sources - max_num_sources = self.cfg.interference.get('max_num_interferers', 0) - interference_probability = self.cfg.interference.get('interference_probability', 0) - - if ( - max_num_sources >= 1 - and interference_probability > 0 - and self.random.uniform(low=0.0, high=1.0) < interference_probability - ): - # interference present - num_interferers = self.random.integers(low=1, high=max_num_sources + 1) - else: - # interference not present - return None - - # Room setup: same room as target - room_index = target_cfg['room_index'] - room_data = self.metadata[subset]['room'][room_index] - feasible_sources = list(range(room_data['num_sources'])) - # target source is not eligible - feasible_sources.remove(target_cfg['source']) - - # Constraints for interfering sources - min_azimuth_to_target = self.cfg.interference.get('min_azimuth_to_target', 0) - - # Prepare interference configuration - interference_cfg = [] - for n in range(num_interferers): - - # Select a source - source = None - while len(feasible_sources) > 0 and source is None: - - # Select a potential source for the target - source = self.random.choice(feasible_sources) - feasible_sources.remove(source) - - # Check azimuth separation - if min_azimuth_to_target > 0: - source_azimuth = room_data['source_azimuth'][source] - azimuth_diff = wrap_to_180(source_azimuth - target_cfg['azimuth']) - if abs(azimuth_diff) < min_azimuth_to_target: - # Try again - source = None - continue - - if source is None: - logging.warning('Could not select a feasible interference source %d of %s', n, num_interferers) - - # Return what we have for now or None - return interference_cfg if interference_cfg else None - - # Current source setup - interfering_source = { - 'source': source, - 'selected_mics': target_cfg['selected_mics'], - 'position': room_data['source_position'][source], - 'azimuth': room_data['source_azimuth'][source], - 'elevation': room_data['source_elevation'][source], - 'distance': room_data['source_distance'][source], - } - - # Done with interference for this source - interference_cfg.append(interfering_source) - - return interference_cfg - - def generate_mix(self, subset: str, target_cfg: dict) -> dict: - """Generate scaling parameters for mixing - the target speech at the microphone, background noise - and interference signal at the microphone. - - The output dictionary contains the following information - ``` - rsnr: reverberant signal-to-noise ratio - rsir: reverberant signal-to-interference ratio - ref_mic: reference microphone for calculating the metrics - ref_mic_rms: RMS of the signal at the reference microphone - ``` - - Args: - subset: string denoting the subset of configuration - target_cfg: dictionary with target configuration - - Returns: - Dictionary containing configured RSNR, RSIR, ref_mic - and RMS on ref_mic. - """ - mix_cfg = dict() - - for key in ['rsnr', 'rsir', 'ref_mic', 'ref_mic_rms', 'min_duration']: - if key in self.cfg.mix[subset]: - # Take the value from subset config - value = self.cfg.mix[subset].get(key) - else: - # Take the global value - value = self.cfg.mix.get(key) - - if value is None: - mix_cfg[key] = None - elif np.isscalar(value): - mix_cfg[key] = value - elif len(value) == 2: - # Select from the given range, including the upper bound - mix_cfg[key] = self.random.integers(low=value[0], high=value[1] + 1) - else: - # Select one of the multiple values - mix_cfg[key] = self.random.choice(value) - - if mix_cfg['ref_mic'] == 'closest': - # Select the closest mic as the reference - mix_cfg['ref_mic'] = np.argmin(target_cfg['distance_source_to_mic']) - - # Configuration for saving individual components - mix_cfg['save'] = OmegaConf.to_object(self.cfg.mix['save']) if 'save' in self.cfg.mix else {} - - return mix_cfg - - def generate(self): - """Generate a corpus of microphone signals by mixing target, background noise - and interference signals. - - This method will prepare randomized examples based on the current configuration, - run simulations and save results to output_dir. - """ - logging.info('Generate mixed signals') - - # Initialize - self.random = default_rng(seed=self.cfg.random_seed) - - # Prepare output dir - output_dir = self.cfg.output_dir - if output_dir.endswith('.yaml'): - output_dir = output_dir[:-5] - - # Create absolute path - logging.info('Output dir set to: %s', output_dir) - - # Generate all cases - for subset in self.subsets: - - output_dir_subset = os.path.join(output_dir, subset) - examples = [] - - if not os.path.exists(output_dir_subset): - logging.info('Creating output directory: %s', output_dir_subset) - os.makedirs(output_dir_subset) - elif os.path.isdir(output_dir_subset) and len(os.listdir(output_dir_subset)) > 0: - raise RuntimeError(f'Output directory {output_dir_subset} is not empty.') - - num_examples = self.cfg.mix[subset].num - logging.info('Preparing %d examples for subset %s', num_examples, subset) - - # Generate examples - for n_example in tqdm(range(num_examples), total=num_examples, desc=f'Preparing {subset}'): - # prepare configuration - target_cfg = self.generate_target(subset) - interference_cfg = self.generate_interference(subset, target_cfg) - mix_cfg = self.generate_mix(subset, target_cfg) - - # base file name - base_output_filepath = os.path.join(output_dir_subset, f'{subset}_example_{n_example:09d}') - - # prepare example - example = { - 'sample_rate': self.sample_rate, - 'target_cfg': target_cfg, - 'interference_cfg': interference_cfg, - 'mix_cfg': mix_cfg, - 'base_output_filepath': base_output_filepath, - } - - examples.append(example) - - # Audio data - audio_metadata = { - 'target': self.metadata[subset]['target'], - 'target_dir': os.path.dirname(self.cfg.target[subset]), # manifest_dir - 'noise': self.metadata[subset]['noise'], - 'noise_dir': os.path.dirname(self.cfg.noise[subset]), # manifest_dir - } - - if interference_cfg is not None: - audio_metadata.update( - { - 'interference': self.metadata[subset]['interference'], - 'interference_dir': os.path.dirname(self.cfg.interference[subset]), # manifest_dir - } - ) - - # Simulation - if (num_workers := self.cfg.get('num_workers')) is None: - num_workers = os.cpu_count() - 1 - - if num_workers is not None and num_workers > 1: - logging.info(f'Simulate using {num_workers} workers') - examples_and_audio_metadata = zip(examples, itertools.repeat(audio_metadata, len(examples))) - with multiprocessing.Pool(processes=num_workers) as pool: - metadata = list( - tqdm( - pool.imap(simulate_room_mix_helper, examples_and_audio_metadata), - total=len(examples), - desc=f'Simulating {subset}', - ) - ) - else: - logging.info('Simulate using a single worker') - metadata = [] - for example in tqdm(examples, total=len(examples), desc=f'Simulating {subset}'): - metadata.append(simulate_room_mix(**example, audio_metadata=audio_metadata)) - - # Save manifest - manifest_filepath = os.path.join(output_dir, f'{os.path.basename(output_dir)}_{subset}.json') - - if os.path.exists(manifest_filepath) and os.path.isfile(manifest_filepath): - raise RuntimeError(f'Manifest config file exists: {manifest_filepath}') - - # Make all paths in the manifest relative to the output dir - for data in tqdm(metadata, total=len(metadata), desc=f'Making filepaths relative {subset}'): - for key, val in data.items(): - if key.endswith('_filepath') and val is not None: - data[key] = os.path.relpath(val, start=output_dir) - - write_manifest(manifest_filepath, metadata) - - # Generate plots with information about generated data - plot_filepath = os.path.join(output_dir, f'{os.path.basename(output_dir)}_{subset}_info.png') - - if os.path.exists(plot_filepath) and os.path.isfile(plot_filepath): - raise RuntimeError(f'Plot file exists: {plot_filepath}') - - plot_mix_manifest_info(manifest_filepath, plot_filepath=plot_filepath) - - # Save used configuration for reference - config_filepath = os.path.join(output_dir, 'config.yaml') - if os.path.exists(config_filepath) and os.path.isfile(config_filepath): - raise RuntimeError(f'Output config file exists: {config_filepath}') - - OmegaConf.save(self.cfg, config_filepath, resolve=True) - - -def convolve_rir(signal: np.ndarray, rir: np.ndarray) -> np.ndarray: - """Convolve signal with a possibly multichannel IR in rir, i.e., - calculate the following for each channel m: - - signal_m = rir_m \ast signal - - Args: - signal: single-channel signal (samples,) - rir: single- or multi-channel IR, (samples,) or (samples, channels) - - Returns: - out: same length as signal, same number of channels as rir, shape (samples, channels) - """ - num_samples = len(signal) - if rir.ndim == 1: - # convolve and trim to length - out = convolve(signal, rir)[:num_samples] - elif rir.ndim == 2: - num_channels = rir.shape[1] - out = np.zeros((num_samples, num_channels)) - for m in range(num_channels): - out[:, m] = convolve(signal, rir[:, m])[:num_samples] - - else: - raise RuntimeError(f'RIR with {rir.ndim} not supported') - - return out - - -def calculate_drr(rir: np.ndarray, sample_rate: float, n_direct: List[int], n_0_ms=2.5) -> List[float]: - """Calculate direct-to-reverberant ratio (DRR) from the measured RIR. - - Calculation is done as in eq. (3) from [1]. - - Args: - rir: room impulse response, shape (num_samples, num_channels) - sample_rate: sample rate for the impulse response - n_direct: direct path delay - n_0_ms: window around n_direct for calculating the direct path energy - - Returns: - Calculated DRR for each channel of the input RIR. - - References: - [1] Eaton et al, The ACE challenge: Corpus description and performance evaluation, WASPAA 2015 - """ - # Define a window around the direct path delay - n_0 = int(n_0_ms * sample_rate / 1000) - - len_rir, num_channels = rir.shape - drr = [None] * num_channels - for m in range(num_channels): - - # Window around the direct path - dir_start = max(n_direct[m] - n_0, 0) - dir_end = n_direct[m] + n_0 - - # Power of the direct component - pow_dir = np.sum(np.abs(rir[dir_start:dir_end, m]) ** 2) / len_rir - - # Power of the reverberant component - pow_reverberant = (np.sum(np.abs(rir[0:dir_start, m]) ** 2) + np.sum(np.abs(rir[dir_end:, m]) ** 2)) / len_rir - - # DRR in dB - drr[m] = pow2db(pow_dir / pow_reverberant) - - return drr - - -def normalize_max(x: np.ndarray, max_db: float = 0, eps: float = 1e-16) -> np.ndarray: - """Normalize max input value to max_db full scale (±1). - - Args: - x: input signal - max_db: desired max magnitude compared to full scale - eps: small regularization constant - - Returns: - Normalized signal with max absolute value max_db. - """ - max_val = db2mag(max_db) - return max_val * x / (np.max(np.abs(x)) + eps) - - -def simultaneously_active_rms( - x: np.ndarray, - y: np.ndarray, - sample_rate: float, - rms_threshold_db: float = -60, - window_len_ms: float = 200, - min_active_duration: float = 0.5, -) -> Tuple[float, float]: - """Calculate RMS over segments where both input signals are active. - - Args: - x: first input signal - y: second input signal - sample_rate: sample rate for input signals in Hz - rms_threshold_db: threshold for determining activity of the signal, relative - to max absolute value - window_len_ms: window length in milliseconds, used for calculating segmental RMS - min_active_duration: minimal duration of the active segments - - Returns: - RMS value over active segments for x and y. - """ - if len(x) != len(y): - raise RuntimeError(f'Expecting signals of same length: len(x)={len(x)}, len(y)={len(y)}') - window_len = int(window_len_ms * sample_rate / 1000) - rms_threshold = db2mag(rms_threshold_db) # linear scale - - x_normalized = normalize_max(x) - y_normalized = normalize_max(y) - - x_active_power = y_active_power = active_len = 0 - for start in range(0, len(x) - window_len, window_len): - window = slice(start, start + window_len) - - # check activity on the scaled signal - x_window_rms = rms(x_normalized[window]) - y_window_rms = rms(y_normalized[window]) - - if x_window_rms > rms_threshold and y_window_rms > rms_threshold: - # sum the power of the original non-scaled signal - x_active_power += np.sum(np.abs(x[window]) ** 2) - y_active_power += np.sum(np.abs(y[window]) ** 2) - active_len += window_len - - if active_len < int(min_active_duration * sample_rate): - raise RuntimeError( - f'Signals are simultaneously active less than {min_active_duration} s: only {active_len/sample_rate} s' - ) - - # normalize - x_active_power /= active_len - y_active_power /= active_len - - return np.sqrt(x_active_power), np.sqrt(y_active_power) - - -def scaled_disturbance( - signal: np.ndarray, - disturbance: np.ndarray, - sdr: float, - sample_rate: float = None, - ref_channel: int = 0, - eps: float = 1e-16, -) -> np.ndarray: - """ - Args: - signal: numpy array, shape (num_samples, num_channels) - disturbance: numpy array, same shape as signal - sdr: desired signal-to-disturbance ration - sample_rate: sample rate of the input signals - ref_channel: ref mic used to calculate RMS - eps: regularization constant - - Returns: - Scaled disturbance, so that signal-to-disturbance ratio at ref_channel - is approximately equal to input SDR during simultaneously active - segment of signal and disturbance. - """ - if signal.shape != disturbance.shape: - raise ValueError(f'Signal and disturbance shapes do not match: {signal.shape} != {disturbance.shape}') - - # set scaling based on RMS at ref_mic - signal_rms, disturbance_rms = simultaneously_active_rms( - signal[:, ref_channel], disturbance[:, ref_channel], sample_rate=sample_rate - ) - disturbance_gain = db2mag(-sdr) * signal_rms / (disturbance_rms + eps) - # scale disturbance - scaled_disturbance = disturbance_gain * disturbance - return scaled_disturbance - - -def prepare_source_signal( - signal_type: str, - sample_rate: int, - audio_data: List[dict], - audio_dir: Optional[str] = None, - min_duration: Optional[int] = None, - ref_signal: Optional[np.ndarray] = None, - mic_positions: Optional[np.ndarray] = None, - num_retries: int = 10, -) -> tuple: - """Prepare an audio signal for a source. - - Args: - signal_type: 'point' or 'diffuse' - sample_rate: Sampling rate for the signal - audio_data: List of audio items, each is a dictionary with audio_filepath, duration, offset and optionally text - audio_dir: Base directory for resolving paths, e.g., manifest basedir - min_duration: Minimal duration to be loaded if ref_signal is not provided, in seconds - ref_signal: Optional, used to determine the length of the signal - mic_positions: Optional, used to prepare approximately diffuse signal - num_retries: Number of retries when selecting the source files - - Returns: - (audio_signal, metadata), where audio_signal is an ndarray and metadata is a dictionary - with audio filepaths, durations and offsets - """ - if signal_type not in ['point', 'diffuse']: - raise ValueError(f'Unexpected signal type {signal_type}.') - - if audio_data is None: - # No data to load - return None - - metadata = {} - - if ref_signal is None: - audio_signal = None - # load at least one sample if min_duration is not provided - samples_to_load = int(min_duration * sample_rate) if min_duration is not None else 1 - source_signals_metadata = {'audio_filepath': [], 'duration': [], 'offset': [], 'text': []} - - while samples_to_load > 0: - # Select a random item and load the audio - item = random.choice(audio_data) - - audio_filepath = item['audio_filepath'] - if not os.path.isabs(audio_filepath) and audio_dir is not None: - audio_filepath = os.path.join(audio_dir, audio_filepath) - - # Load audio - check_min_sample_rate(audio_filepath, sample_rate) - audio_segment = AudioSegment.from_file( - audio_file=audio_filepath, - target_sr=sample_rate, - duration=item['duration'], - offset=item.get('offset', 0), - ) - - if signal_type == 'point': - if audio_segment.num_channels > 1: - raise RuntimeError( - f'Expecting single-channel source signal, but received {audio_segment.num_channels}. File: {audio_filepath}' - ) - else: - raise ValueError(f'Unexpected signal type {signal_type}.') - - source_signals_metadata['audio_filepath'].append(audio_filepath) - source_signals_metadata['duration'].append(item['duration']) - source_signals_metadata['duration'].append(item.get('offset', 0)) - source_signals_metadata['text'].append(item.get('text')) - - # not perfect, since different files may have different distributions - segment_samples = normalize_max(audio_segment.samples) - # concatenate - audio_signal = ( - np.concatenate((audio_signal, segment_samples)) if audio_signal is not None else segment_samples - ) - # remaining samples - samples_to_load -= len(segment_samples) - - # Finally, we need only the metadata for the complete signal - metadata = { - 'duration': sum(source_signals_metadata['duration']), - 'offset': 0, - } - - # Add text only if all source signals have text - if all([isinstance(tt, str) for tt in source_signals_metadata['text']]): - metadata['text'] = ' '.join(source_signals_metadata['text']) - else: - # Load a signal with total_len samples and ensure it has enough simultaneous activity/overlap with ref_signal - # Concatenate multiple files if necessary - total_len = len(ref_signal) - - for n in range(num_retries): - - audio_signal = None - source_signals_metadata = {'audio_filepath': [], 'duration': [], 'offset': []} - - if signal_type == 'point': - samples_to_load = total_len - elif signal_type == 'diffuse': - # Load longer signal so it can be reshaped into (samples, mics) and - # used to generate approximately diffuse noise field - num_mics = len(mic_positions) - samples_to_load = num_mics * total_len - - while samples_to_load > 0: - # Select an audio file - item = random.choice(audio_data) - - audio_filepath = item['audio_filepath'] - if not os.path.isabs(audio_filepath) and audio_dir is not None: - audio_filepath = os.path.join(audio_dir, audio_filepath) - - # Load audio signal - check_min_sample_rate(audio_filepath, sample_rate) - - if (max_offset := item['duration'] - np.ceil(samples_to_load / sample_rate)) > 0: - # Load with a random offset if the example is longer than samples_to_load - offset = random.uniform(0, max_offset) - duration = -1 - else: - # Load the whole file - offset, duration = 0, item['duration'] - audio_segment = AudioSegment.from_file( - audio_file=audio_filepath, target_sr=sample_rate, duration=duration, offset=offset - ) - - # Prepare a single-channel signal - if audio_segment.num_channels == 1: - # Take all samples - segment_samples = audio_segment.samples - else: - # Take a random channel - selected_channel = random.choice(range(audio_segment.num_channels)) - segment_samples = audio_segment.samples[:, selected_channel] - - source_signals_metadata['audio_filepath'].append(audio_filepath) - source_signals_metadata['duration'].append(len(segment_samples) / sample_rate) - source_signals_metadata['offset'].append(offset) - - # not perfect, since different files may have different distributions - segment_samples = normalize_max(segment_samples) - # concatenate - audio_signal = ( - np.concatenate((audio_signal, segment_samples)) if audio_signal is not None else segment_samples - ) - # remaining samples - samples_to_load -= len(segment_samples) - - if signal_type == 'diffuse' and num_mics > 1: - try: - # Trim and reshape to num_mics to prepare num_mics source signals - audio_signal = audio_signal[: num_mics * total_len].reshape(num_mics, -1).T - - # Make spherically diffuse noise - audio_signal = generate_approximate_noise_field( - mic_positions=np.array(mic_positions), noise_signal=audio_signal, sample_rate=sample_rate - ) - except Exception as e: - logging.info('Failed to generate approximate noise field: %s', str(e)) - logging.info('Try again.') - # Try again - audio_signal, source_signals_metadata = None, {} - continue - - # Trim to length - audio_signal = audio_signal[:total_len, ...] - - # Include the channel dimension if the reference includes it - if ref_signal.ndim == 2 and audio_signal.ndim == 1: - audio_signal = audio_signal[:, None] - - try: - # Signal and ref_signal should be simultaneously active - simultaneously_active_rms(ref_signal, audio_signal, sample_rate=sample_rate) - # We have enough overlap - break - except Exception as e: - # Signal and ref_signal are not overlapping, try again - logging.info('Exception: %s', str(e)) - logging.info('Signals are not overlapping, try again.') - audio_signal, source_signals_metadata = None, {} - continue - - if audio_signal is None: - logging.warning('Audio signal not set: %s.', signal_type) - - metadata['source_signals'] = source_signals_metadata - - return audio_signal, metadata - - -def check_min_sample_rate(filepath: str, sample_rate: float): - """Make sure the file's sample rate is at least sample_rate. - This will make sure that we have only downsampling if loading - this file, while upsampling is not permitted. - - Args: - filepath: path to a file - sample_rate: desired sample rate - """ - file_sample_rate = librosa.get_samplerate(path=filepath) - if file_sample_rate < sample_rate: - raise RuntimeError( - f'Sample rate ({file_sample_rate}) is lower than the desired sample rate ({sample_rate}). File: {filepath}.' - ) - - -def simulate_room_mix( - sample_rate: int, - target_cfg: dict, - interference_cfg: dict, - mix_cfg: dict, - audio_metadata: dict, - base_output_filepath: str, - max_amplitude: float = 0.999, - eps: float = 1e-16, -) -> dict: - """Simulate mixture signal at the microphone, including target, noise and - interference signals and mixed at specific RSNR and RSIR. - - Args: - sample_rate: Sample rate for all signals - target_cfg: Dictionary with configuration of the target. Includes - room_filepath, source index, audio_filepath, duration - noise_cfg: List of dictionaries, where each item includes audio_filepath, - offset and duration. - interference_cfg: List of dictionaries, where each item contains source - index - mix_cfg: Dictionary with the mixture configuration. Includes RSNR, RSIR, - ref_mic and ref_mic_rms. - audio_metadata: Dictionary with a list of files for target, noise and interference - base_output_filepath: All output audio files will be saved with this prefix by - adding a diffierent suffix for each component, e.g., _mic.wav. - max_amplitude: Maximum amplitude of the mic signal, used to prevent clipping. - eps: Small regularization constant. - - Returns: - Dictionary with metadata based on the mixture setup and - simulation results. This corresponds to a line of the - output manifest file. - """ - - # Local utilities - def load_rir( - room_filepath: str, source: int, selected_mics: list, sample_rate: float, rir_key: str = 'rir' - ) -> np.ndarray: - """Load a RIR and check that the sample rate is matching the desired sample rate - - Args: - room_filepath: Path to a room simulation in an h5 file - source: Index of the desired source - sample_rate: Sample rate of the simulation - rir_key: Key of the RIR to load from the simulation. - - Returns: - Numpy array with shape (num_samples, num_channels) - """ - rir, rir_sample_rate = load_rir_simulation(room_filepath, source=source, rir_key=rir_key) - if rir_sample_rate != sample_rate: - raise RuntimeError( - f'RIR sample rate ({sample_rate}) is not matching the expected sample rate ({sample_rate}). File: {room_filepath}' - ) - return rir[:, selected_mics] - - def get_early_rir( - rir: np.ndarray, rir_anechoic: np.ndarray, sample_rate: int, early_duration: float = 0.050 - ) -> np.ndarray: - """Return only the early part of the RIR.""" - early_len = int(early_duration * sample_rate) - direct_path_delay = np.min(np.argmax(rir_anechoic, axis=0)) - rir_early = rir.copy() - rir_early[direct_path_delay + early_len :, :] = 0 - return rir_early - - def save_audio( - base_path: str, - tag: str, - audio_signal: Optional[np.ndarray], - sample_rate: int, - save: str = 'all', - ref_mic: Optional[int] = None, - format: str = 'wav', - subtype: str = 'float', - ): - """Save audio signal and return filepath.""" - if (audio_signal is None) or (not save): - return None - - if save == 'ref_mic': - # save only ref_mic - audio_signal = audio_signal[:, ref_mic] - - audio_filepath = base_path + f'_{tag}.{format}' - sf.write(audio_filepath, audio_signal, sample_rate, subtype) - - return audio_filepath - - # Target RIRs - target_rir = load_rir( - target_cfg['room_filepath'], - source=target_cfg['source'], - selected_mics=target_cfg['selected_mics'], - sample_rate=sample_rate, - ) - target_rir_anechoic = load_rir( - target_cfg['room_filepath'], - source=target_cfg['source'], - sample_rate=sample_rate, - selected_mics=target_cfg['selected_mics'], - rir_key='anechoic', - ) - target_rir_early = get_early_rir(rir=target_rir, rir_anechoic=target_rir_anechoic, sample_rate=sample_rate) - - # Target signals - target_signal, target_metadata = prepare_source_signal( - signal_type='point', - sample_rate=sample_rate, - audio_data=audio_metadata['target'], - audio_dir=audio_metadata['target_dir'], - min_duration=mix_cfg['min_duration'], - ) - source_signals_metadata = {'target': target_metadata['source_signals']} - - # Convolve target - target_reverberant = convolve_rir(target_signal, target_rir) - target_anechoic = convolve_rir(target_signal, target_rir_anechoic) - target_early = convolve_rir(target_signal, target_rir_early) - - # Prepare noise signal - noise, noise_metadata = prepare_source_signal( - signal_type='diffuse', - sample_rate=sample_rate, - mic_positions=target_cfg['mic_positions'], - audio_data=audio_metadata['noise'], - audio_dir=audio_metadata['noise_dir'], - ref_signal=target_reverberant, - ) - source_signals_metadata['noise'] = noise_metadata['source_signals'] - - # Prepare interference signal - if interference_cfg is None: - interference = None - else: - # Load interference signals - interference = 0 - source_signals_metadata['interference'] = [] - for i_cfg in interference_cfg: - # Load single-channel signal for directional interference - i_signal, i_metadata = prepare_source_signal( - signal_type='point', - sample_rate=sample_rate, - audio_data=audio_metadata['interference'], - audio_dir=audio_metadata['interference_dir'], - ref_signal=target_signal, - ) - source_signals_metadata['interference'].append(i_metadata['source_signals']) - # Load RIR from the same room as the target, but a difference source - i_rir = load_rir( - target_cfg['room_filepath'], - source=i_cfg['source'], - selected_mics=i_cfg['selected_mics'], - sample_rate=sample_rate, - ) - # Convolve interference - i_reverberant = convolve_rir(i_signal, i_rir) - # Sum - interference += i_reverberant - - # Scale and add components of the signal - mic = target_reverberant.copy() - - if noise is not None: - noise = scaled_disturbance( - signal=target_reverberant, - disturbance=noise, - sdr=mix_cfg['rsnr'], - sample_rate=sample_rate, - ref_channel=mix_cfg['ref_mic'], - ) - # Update mic signal - mic += noise - - if interference is not None: - interference = scaled_disturbance( - signal=target_reverberant, - disturbance=interference, - sdr=mix_cfg['rsir'], - sample_rate=sample_rate, - ref_channel=mix_cfg['ref_mic'], - ) - # Update mic signal - mic += interference - - # Set the final mic signal level - mic_rms = rms(mic[:, mix_cfg['ref_mic']]) - global_gain = db2mag(mix_cfg['ref_mic_rms']) / (mic_rms + eps) - mic_max = np.max(np.abs(mic)) - if (clipped_max := mic_max * global_gain) > max_amplitude: - # Downscale the global gain to prevent clipping + adjust ref_mic_rms accordingly - clipping_prevention_gain = max_amplitude / clipped_max - global_gain *= clipping_prevention_gain - mix_cfg['ref_mic_rms'] += mag2db(clipping_prevention_gain) - - logging.debug( - 'Clipping prevented for example %s (protection gain: %.2f dB)', - base_output_filepath, - mag2db(clipping_prevention_gain), - ) - - # save signals - signals = { - 'mic': mic, - 'target_reverberant': target_reverberant, - 'target_anechoic': target_anechoic, - 'target_early': target_early, - 'noise': noise, - 'interference': interference, - } - - metadata = {} - - for tag, signal in signals.items(): - - if signal is not None: - # scale all signal components with the global gain - signal = global_gain * signal - - audio_filepath = save_audio( - base_path=base_output_filepath, - tag=tag, - audio_signal=signal, - sample_rate=sample_rate, - save=mix_cfg['save'].get(tag, 'all'), - ref_mic=mix_cfg['ref_mic'], - format=mix_cfg['save'].get('format', 'wav'), - subtype=mix_cfg['save'].get('subtype', 'float'), - ) - - if tag == 'mic': - metadata['audio_filepath'] = audio_filepath - else: - metadata[tag + '_filepath'] = audio_filepath - - # Add metadata - metadata.update( - { - 'text': target_metadata.get('text'), - 'duration': target_metadata['duration'], - 'target_cfg': target_cfg, - 'interference_cfg': interference_cfg, - 'mix_cfg': mix_cfg, - 'ref_channel': mix_cfg.get('ref_mic'), - 'rt60': target_cfg.get('rt60'), - 'drr': calculate_drr(target_rir, sample_rate, n_direct=np.argmax(target_rir_anechoic, axis=0)), - 'rsnr': None if noise is None else mix_cfg['rsnr'], - 'rsir': None if interference is None else mix_cfg['rsir'], - 'source_signals': source_signals_metadata, - } - ) - - return convert_numpy_to_serializable(metadata) - - -def simulate_room_mix_helper(example_and_audio_metadata: tuple) -> dict: - """Wrapper around `simulate_room_mix` for pool.imap. - - Args: - args: example and audio_metadata that are forwarded to `simulate_room_mix` - - Returns: - Dictionary with metadata, see `simulate_room_mix` - """ - example, audio_metadata = example_and_audio_metadata - return simulate_room_mix(**example, audio_metadata=audio_metadata) - - -def plot_mix_manifest_info(filepath: str, plot_filepath: str = None): - """Plot distribution of parameters from the manifest file. - - Args: - filepath: path to a RIR corpus manifest file - plot_filepath: path to save the plot at - """ - metadata = read_manifest(filepath) - - # target info - target_distance = [] - target_azimuth = [] - target_elevation = [] - target_duration = [] - - # room config - rt60 = [] - drr = [] - - # noise - rsnr = [] - rsir = [] - - # get the required data - for data in metadata: - # target info - target_distance.append(data['target_cfg']['distance']) - target_azimuth.append(data['target_cfg']['azimuth']) - target_elevation.append(data['target_cfg']['elevation']) - target_duration.append(data['duration']) - - # room config - rt60.append(data['rt60']) - drr += data['drr'] # average DRR across all mics - - # noise - if data['rsnr'] is not None: - rsnr.append(data['rsnr']) - - if data['rsir'] is not None: - rsir.append(data['rsir']) - - # plot - plt.figure(figsize=(12, 6)) - - plt.subplot(2, 4, 1) - plt.hist(target_distance, label='distance') - plt.xlabel('distance / m') - plt.ylabel('# examples') - plt.title('Target-to-array distance') - - plt.subplot(2, 4, 2) - plt.hist(target_azimuth, label='azimuth') - plt.xlabel('azimuth / deg') - plt.ylabel('# examples') - plt.title('Target-to-array azimuth') - - plt.subplot(2, 4, 3) - plt.hist(target_elevation, label='elevation') - plt.xlabel('elevation / deg') - plt.ylabel('# examples') - plt.title('Target-to-array elevation') - - plt.subplot(2, 4, 4) - plt.hist(target_duration, label='duration') - plt.xlabel('time / s') - plt.ylabel('# examples') - plt.title('Target duration') - - plt.subplot(2, 4, 5) - plt.hist(rt60, label='RT60') - plt.xlabel('RT60 / s') - plt.ylabel('# examples') - plt.title('RT60') - - plt.subplot(2, 4, 6) - plt.hist(drr, label='DRR') - plt.xlabel('DRR / dB') - plt.ylabel('# examples') - plt.title('DRR [avg over mics]') - - if len(rsnr) > 0: - plt.subplot(2, 4, 7) - plt.hist(rsnr, label='RSNR') - plt.xlabel('RSNR / dB') - plt.ylabel('# examples') - plt.title(f'RSNR [{100 * len(rsnr) / len(rt60):.0f}% ex]') - - if len(rsir): - plt.subplot(2, 4, 8) - plt.hist(rsir, label='RSIR') - plt.xlabel('RSIR / dB') - plt.ylabel('# examples') - plt.title(f'RSIR [{100 * len(rsir) / len(rt60):.0f}% ex]') - - for n in range(8): - plt.subplot(2, 4, n + 1) - plt.grid() - plt.legend(loc='lower left') - - plt.tight_layout() - - if plot_filepath is not None: - plt.savefig(plot_filepath) - plt.close() - logging.info('Plot saved at %s', plot_filepath) diff --git a/nemo/collections/audio/losses/__init__.py b/nemo/collections/audio/losses/__init__.py deleted file mode 100644 index 154f14f0228d3f3b63c58aa748af912fe6e65e2c..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/losses/__init__.py +++ /dev/null @@ -1,17 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.audio.losses.audio import MAELoss, MSELoss, SDRLoss - -__all__ = ["MAELoss", "MSELoss", "SDRLoss"] diff --git a/nemo/collections/audio/losses/audio.py b/nemo/collections/audio/losses/audio.py deleted file mode 100644 index 04f55ea463e3377ee203e8f47e6c2980b8852b46..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/losses/audio.py +++ /dev/null @@ -1,742 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import math -from typing import List, Optional, Tuple, Union - -import numpy as np -import torch - -from nemo.collections.asr.parts.preprocessing.features import make_seq_mask_like -from nemo.collections.audio.parts.utils.audio import toeplitz -from nemo.core.classes import Loss, Typing, typecheck -from nemo.core.neural_types import AudioSignal, LengthsType, LossType, MaskType, NeuralType, VoidType -from nemo.utils import logging - -__all__ = ['SDRLoss', 'MSELoss'] - - -def calculate_mean( - input: torch.Tensor, - input_length: Optional[torch.Tensor] = None, - mask: Optional[torch.Tensor] = None, - dim: Union[int, Tuple[int]] = -1, - keepdim: bool = False, - eps: float = 1e-10, -) -> torch.Tensor: - """Calculate mean along dimension `dim` with optionally - averaging only over valid samples (based on the input length). - - Args: - input: signal, for example (B, C, T) or (B, C, D, T) - input_length: Optional, length of each example in the batch, shape (B,) - mask: Optional, temporal mask for each example in the batch, same shape as the input signal - dim: dimension or dimensions to reduce - keepdim: Whether to keep the temporal dimension - eps: Regularization to avoid division by zero - - Returns: - Mean over dimensions `dim`. - """ - if input_length is not None: - if mask is not None: - raise RuntimeError( - 'Argument `input_length` is mutually exclusive with `mask`. Both cannot be used at the same time.' - ) - # Construct a binary mask - mask = make_seq_mask_like(lengths=input_length, like=input, time_dim=-1, valid_ones=True) - mask = mask.expand_as(input) - - if mask is None: - # No length information, assume all samples are valid - mean = torch.mean(input, dim=dim, keepdim=keepdim) - else: - # Average using temporal mask - mean = mask * input - mean = torch.sum(mean, dim=dim, keepdim=keepdim) - normalization = torch.sum(mask, dim=dim, keepdim=keepdim) - mean = mean / (normalization + eps) - - return mean - - -def scale_invariant_target( - estimate: torch.Tensor, - target: torch.Tensor, - input_length: Optional[torch.Tensor] = None, - mask: Optional[torch.Tensor] = None, - eps: float = 1e-10, -) -> torch.Tensor: - """Calculate optimal scale-invariant target. - Assumes time dimension is the last dimension in the array. - - Calculate scaled target obtained by solving - - min_scale || scale * target - estimate ||^2 - - for each example in batch and each channel (b, c). - - Args: - estimate: tensor, shape (B, C, T) - target: tensor, shape (B, C, T) - input_length: optional, length of valid samples, shape (B,) - mask: optional, mask for input samples, shape (B, T) - eps: regularization constant - - Returns: - Scaled target, shape (B, C, T) - """ - if input_length is not None: - if mask is not None: - raise RuntimeError( - 'Argument `input_length` is mutually exclusive with `mask`. Both cannot be used at the same time.' - ) - - # Construct a binary mask - mask = make_seq_mask_like(lengths=input_length, like=estimate, time_dim=-1, valid_ones=True) - mask = mask.expand_as(estimate) - - estimate_dot_target = calculate_mean(estimate * target, mask=mask, dim=-1, keepdim=True, eps=eps) - target_pow = calculate_mean(torch.abs(target) ** 2, mask=mask, dim=-1, keepdim=True, eps=eps) - scale = estimate_dot_target / (target_pow + eps) - target_scaled = scale * target - - # Mask to keep only the valid samples - if mask is not None: - target_scaled = mask * target_scaled - - return target_scaled - - -def convolution_invariant_target( - estimate: torch.Tensor, - target: torch.Tensor, - input_length: Optional[torch.Tensor] = None, - mask: Optional[torch.Tensor] = None, - filter_length: int = 512, - diag_reg: float = 1e-6, - eps: float = 1e-8, -) -> torch.Tensor: - """Calculate optimal convolution-invariant target for a given estimate. - Assumes time dimension is the last dimension in the array. - - Calculate target filtered with a linear f obtained by solving - - min_filter || conv(filter, target) - estimate ||^2 - - for each example in batch and each channel (b, c). - - Args: - estimate: tensor, shape (B, C, T) - target: tensor, shape (B, C, T) - input_length: optional, length of valid samples, shape (B,) - mask: optional, mask for input samples, shape (B, T) - filter_length: length of the (convolutional) filter for target - diag_reg: relative diagonal regularization for the linear system - eps: absolute regularization for the diagonal - - Returns: - Filtered target, shape (B, C, T) - - Reference: - C. Boeddeker et al., Convolutive Transfer Function Invariant SDR training criteria for Multi-Channel Reverberant Speech Separation, 2021 - """ - if input_length is not None: - if mask is not None: - raise RuntimeError( - 'Argument `input_length` is mutually exclusive with `mask`. Both cannot be used at the same time.' - ) - - if torch.min(input_length) < filter_length: - logging.warning( - 'Current min input_length (%d) is smaller than filter_length (%d). This will result in a singular linear system.', - torch.min(input_length), - filter_length, - ) - - # Construct a binary mask - mask = make_seq_mask_like(lengths=input_length, like=estimate, time_dim=-1, valid_ones=True) - mask = mask.expand_as(estimate) - - # Apply a mask, if available - if mask is not None: - estimate = mask * estimate - target = mask * target - - # Calculate filtered target - input_shape = estimate.shape - estimate = estimate.view(-1, input_shape[-1]) - target = target.view(-1, input_shape[-1]) - - n_fft = 2 ** math.ceil(math.log2(2 * input_shape[-1] - 1)) - - T = torch.fft.rfft(target, n=n_fft) - E = torch.fft.rfft(estimate, n=n_fft) - - # Target autocorrelation - tt_corr = torch.fft.irfft(torch.abs(T) ** 2, n=n_fft) - # Target-estimate crosscorrelation - te_corr = torch.fft.irfft(T.conj() * E, n=n_fft) - - # Use only filter_length - tt_corr = tt_corr[..., :filter_length] - te_corr = te_corr[..., :filter_length] - - # Diagonal regularization - if diag_reg is not None: - tt_corr[..., 0] += diag_reg * tt_corr[..., 0] + eps - - # Construct the Toeplitz system matrix - TT = toeplitz(tt_corr) - - # Solve the linear system for the optimal filter - filt = torch.linalg.solve(TT, te_corr) - - # Calculate filtered target - T_filt = T * torch.fft.rfft(filt, n=n_fft) - target_filt = torch.fft.irfft(T_filt, n=n_fft) - - # Reshape to the original format - target_filt = target_filt[..., : input_shape[-1]].view(*input_shape) - - # Mask to keep only the valid samples - if mask is not None: - target_filt = mask * target_filt - - return target_filt - - -def calculate_sdr_batch( - estimate: torch.Tensor, - target: torch.Tensor, - input_length: Optional[torch.Tensor] = None, - mask: Optional[torch.Tensor] = None, - scale_invariant: bool = False, - convolution_invariant: bool = False, - convolution_filter_length: Optional[int] = 512, - remove_mean: bool = True, - sdr_max: Optional[float] = None, - eps: float = 1e-8, -) -> torch.Tensor: - """Calculate signal-to-distortion ratio per channel. - - SDR = 10 * log10( ||t||_2^2 / (||e-t||_2^2 + alpha * ||t||^2) - - where - alpha = 10^(-sdr_max/10) - - Optionally, use scale- or convolution- invariant target signal. - - Args: - estimate: estimated signal, shape (B, C, T) - target: target signal, shape (B, C, T) - input_length: Optional, length of valid samples, shape (B,) - mask: Optional, temporal mask, shape (B, T) - scale_invariant: Use scale invariant SDR - convolution_invariant: Use convolution invariant SDR - convolution_filter_length: Filter length for convolution invariant SDR - remove_mean: If True, mean will be removed before calculating SDR - eps: Small regularization constant - - Returns: - SDR in dB for each channel, shape (B, C) - """ - if scale_invariant and convolution_invariant: - raise ValueError('Arguments scale_invariant and convolution_invariant cannot be used simultaneously.') - - assert ( - estimate.shape == target.shape - ), f'Estimate shape ({estimate.shape}) not matching target shape ({target.shape})' - - if input_length is not None: - if mask is not None: - raise RuntimeError( - 'Argument `input_length` is mutually exclusive with `mask`. Both cannot be used at the same time.' - ) - - # Construct a binary mask - mask = make_seq_mask_like(lengths=input_length, like=estimate, time_dim=-1, valid_ones=True) - mask = mask.expand_as(estimate) - - if remove_mean: - estimate = estimate - calculate_mean(estimate, mask=mask, dim=-1, keepdim=True, eps=eps) - target = target - calculate_mean(target, mask=mask, dim=-1, keepdim=True, eps=eps) - - if scale_invariant or (convolution_invariant and convolution_filter_length == 1): - target = scale_invariant_target(estimate=estimate, target=target, mask=mask, eps=eps) - elif convolution_invariant: - target = convolution_invariant_target( - estimate=estimate, - target=target, - mask=mask, - filter_length=convolution_filter_length, - eps=eps, - ) - - distortion = estimate - target - - target_pow = calculate_mean(torch.abs(target) ** 2, mask=mask, dim=-1, eps=eps) - distortion_pow = calculate_mean(torch.abs(distortion) ** 2, mask=mask, dim=-1, eps=eps) - - if sdr_max is not None: - distortion_pow = distortion_pow + 10 ** (-sdr_max / 10) * target_pow - - sdr = target_pow / (distortion_pow + eps) - sdr = 10 * torch.log10(sdr + eps) - - return sdr - - -class SDRLoss(Loss, Typing): - """ - Computes signal-to-distortion ratio (SDR) loss with weighted average across channels. - - Args: - weight: weight for SDR of each output channel, used for averaging the loss across channels. Defaults to `None` (averaging). - reduction: batch reduction. Defaults to `mean` over the batch. - scale_invariant: If `True`, use scale-invariant SDR. Defaults to `False`. - remove_mean: Remove mean before calculating the loss. Defaults to `True`. - sdr_max: Soft thresholding of the loss to SDR_max. - eps: Small value for regularization. - """ - - def __init__( - self, - weight: Optional[List[float]] = None, - reduction: str = 'mean', - scale_invariant: bool = False, - convolution_invariant: bool = False, - convolution_filter_length: Optional[int] = 512, - remove_mean: bool = True, - sdr_max: Optional[float] = None, - eps: float = 1e-8, - ): - super().__init__() - - # SDR weight buffer - if weight is not None: - if any([w <= 0 for w in weight]): - raise ValueError(f'Weight must be positive! Current value: {weight}') - elif not np.isclose(sum(weight), 1, atol=1e-6): - raise ValueError(f'Weight should add to one, current weight: {weight}') - weight = torch.tensor(weight).reshape(1, -1) - logging.info('Channel weight set to %s', weight) - self.register_buffer('weight', weight) - self.weight: Optional[torch.Tensor] - - # Batch reduction - self.reduction = reduction - if reduction == 'mean': - self.reduce = torch.mean - else: - raise ValueError(f'Unexpected reduction mode {reduction}.') - - # SDR calculation setup - if scale_invariant and convolution_invariant: - raise ValueError( - f'{self.__class__.__name__}: arguments scale_invariant and convolution_invariant cannot be used simultaneously.' - ) - self.scale_invariant = scale_invariant - self.convolution_invariant = convolution_invariant - self.convolution_filter_length = convolution_filter_length - self.remove_mean = remove_mean - self.sdr_max = sdr_max - self.eps = eps - - @property - def input_types(self): - """Input types definitions for SDRLoss.""" - signal_shape = ('B', 'C', 'T') - return { - "estimate": NeuralType(signal_shape, AudioSignal()), - "target": NeuralType(signal_shape, AudioSignal()), - "input_length": NeuralType(tuple('B'), LengthsType(), optional=True), - "mask": NeuralType(('B', 'C', 'T'), MaskType(), optional=True), - } - - @property - def output_types(self): - """Output types definitions for SDRLoss.""" - return {"loss": NeuralType(elements_type=LossType())} - - @typecheck() - def forward( - self, - estimate: torch.Tensor, - target: torch.Tensor, - input_length: Optional[torch.Tensor] = None, - mask: Optional[torch.Tensor] = None, - ) -> torch.Tensor: - """For input batch of multi-channel signals, calculate SDR between estimate and target for each channel, - perform averaging across channels (weighting optional), and apply reduction across the batch. - - Args: - estimate: Batch of signals, shape (B, C, T) - target: Batch of signals, shape (B, C, T) - input_length: Batch of lengths, shape (B,) - mask: Batch of temporal masks for each channel, shape (B, C, T) - - Returns: - Scalar loss. - """ - - sdr = calculate_sdr_batch( - estimate=estimate, - target=target, - input_length=input_length, - mask=mask, - scale_invariant=self.scale_invariant, - convolution_invariant=self.convolution_invariant, - convolution_filter_length=self.convolution_filter_length, - remove_mean=self.remove_mean, - sdr_max=self.sdr_max, - eps=self.eps, - ) - - # channel averaging - if self.weight is None: - sdr = torch.mean(sdr, dim=1) - else: - # weighting across channels - sdr = sdr * self.weight - sdr = torch.sum(sdr, dim=1) - - # reduction - sdr = self.reduce(sdr) - - return -sdr - - -def calculate_mse_batch( - estimate: torch.Tensor, - target: torch.Tensor, - input_length: Optional[torch.Tensor] = None, - mask: Optional[torch.Tensor] = None, -) -> torch.Tensor: - """Calculate MSE per channel. - - MSE = ||estimate - target||_2^2 / input_length - - Args: - estimate: estimated signal, shape (B, C, T) or (B, C, D, T) - target: target signal, shape (B, C, T) or (B, C, D, T) - input_length: Optional, length of valid samples, shape (B,) - mask: Optional, temporal mask, same shape as signals - - Returns: - MSE for each channel, shape (B, C) - """ - assert ( - estimate.shape == target.shape - ), f'Estimate shape ({estimate.shape}) not matching target shape ({target.shape})' - - if input_length is not None: - if mask is not None: - raise RuntimeError( - 'Argument `input_length` is mutually exclusive with `mask`. Both cannot be used at the same time.' - ) - - # Construct a binary mask - mask = make_seq_mask_like(lengths=input_length, like=estimate, time_dim=-1, valid_ones=True) - mask = mask.expand_as(estimate) - - # error - err = estimate - target - - # dimensions for averaging - if estimate.ndim == 3: - # average across time - dim = -1 - elif estimate.ndim == 4: - # average across time and features - dim = (-2, -1) - else: - raise RuntimeError(f'Unexpected dimension of the input: {estimate.shape}') - - # calculate masked mean - mse = calculate_mean(torch.abs(err) ** 2, mask=mask, dim=dim) - - return mse - - -class MSELoss(Loss, Typing): - """ - Computes MSE loss with weighted average across channels. - - Args: - weight: weight for loss of each output channel, used for averaging the loss across channels. Defaults to `None` (averaging). - reduction: batch reduction. Defaults to `mean` over the batch. - ndim: Number of dimensions for the input signal - """ - - def __init__( - self, - weight: Optional[List[float]] = None, - reduction: str = 'mean', - ndim: int = 3, - ): - super().__init__() - - # weight buffer - if weight is not None: - if any([w <= 0 for w in weight]): - raise ValueError(f'Weight must be positive! Current value: {weight}') - elif not np.isclose(sum(weight), 1, atol=1e-6): - raise ValueError(f'Weight should add to one, current weight: {weight}') - weight = torch.tensor(weight).reshape(1, -1) - logging.info('Channel weight set to %s', weight) - self.register_buffer('weight', weight) - self.weight: Optional[torch.Tensor] - - # Batch reduction - self.reduction = reduction - if reduction == 'mean': - self.reduce = torch.mean - else: - raise ValueError(f'Unexpected reduction mode {reduction}.') - - # Input dimension - self.ndim = ndim - - if self.ndim == 3: - # Time-domain input - self.signal_shape = ('B', 'C', 'T') - elif self.ndim == 4: - # Spectral-domain input - self.signal_shape = ('B', 'C', 'D', 'T') - else: - raise ValueError(f'Unexpected input dimension: {self.ndim}') - - logging.debug('Initialized %s with', self.__class__.__name__) - logging.debug('\tweight: %s', self.weight) - logging.debug('\treduction: %s', self.reduction) - logging.debug('\tndim: %s', self.ndim) - logging.debug('\tsignal_shape: %s', self.signal_shape) - - @property - def input_types(self): - """Input types definitions for SDRLoss.""" - return { - "estimate": NeuralType(self.signal_shape, VoidType()), - "target": NeuralType(self.signal_shape, VoidType()), - "input_length": NeuralType(tuple('B'), LengthsType(), optional=True), - "mask": NeuralType(self.signal_shape, MaskType(), optional=True), - } - - @property - def output_types(self): - """Output types definitions for MSELoss.""" - return {"loss": NeuralType(elements_type=LossType())} - - @typecheck() - def forward( - self, - estimate: torch.Tensor, - target: torch.Tensor, - input_length: Optional[torch.Tensor] = None, - mask: Optional[torch.Tensor] = None, - ) -> torch.Tensor: - """For input batch of multi-channel signals, calculate SDR between estimate and target for each channel, - perform averaging across channels (weighting optional), and apply reduction across the batch. - - Args: - estimate: Estimate of the target signal - target: Target signal - input_length: Length of each example in the batch - mask: Mask for each signal - - Returns: - Scalar loss. - """ - mse = calculate_mse_batch( - estimate=estimate, - target=target, - input_length=input_length, - mask=mask, - ) - - # channel averaging - if self.weight is None: - mse = torch.mean(mse, dim=1) - else: - # weighting across channels - mse = mse * self.weight - mse = torch.sum(mse, dim=1) - - # reduction - mse = self.reduce(mse) - - return mse - - -def calculate_mae_batch( - estimate: torch.Tensor, - target: torch.Tensor, - input_length: Optional[torch.Tensor] = None, - mask: Optional[torch.Tensor] = None, -) -> torch.Tensor: - """Calculate mean absolute error (MAE) per channel. - - MAE = ||estimate - target||_1 / input_length - - Args: - estimate: estimated signal, shape (B, C, T) or (B, C, D, T) - target: target signal, shape (B, C, T) or (B, C, D, T) - input_length: Optional, length of valid samples, shape (B,) - mask: Optional, temporal mask, same shape as signals - - Returns: - MAE for each channel, shape (B, C) - """ - assert ( - estimate.shape == target.shape - ), f'Estimate shape ({estimate.shape}) not matching target shape ({target.shape})' - - if input_length is not None: - if mask is not None: - raise RuntimeError( - 'Argument `input_length` is mutually exclusive with `mask`. Both cannot be used at the same time.' - ) - - # Construct a binary mask - mask = make_seq_mask_like(lengths=input_length, like=estimate, time_dim=-1, valid_ones=True) - mask = mask.expand_as(estimate) - - # error - err = estimate - target - - # dimensions for averaging - if estimate.ndim == 3: - # average across time - dim = -1 - elif estimate.ndim == 4: - # average across time and features - dim = (-2, -1) - else: - raise RuntimeError(f'Unexpected dimension of the input: {estimate.shape}') - - # calculate masked mean - mse = calculate_mean(torch.abs(err), mask=mask, dim=dim) - - return mse - - -class MAELoss(Loss, Typing): - """ - Computes the mean absolute error (MAE) loss with weighted average across channels. - - Args: - weight: weight for loss of each output channel, used for averaging the loss across channels. Defaults to `None` (averaging). - reduction: batch reduction. Defaults to `mean` over the batch. - ndim: Number of dimensions for the input signal - """ - - def __init__( - self, - weight: Optional[List[float]] = None, - reduction: str = 'mean', - ndim: int = 3, - ): - super().__init__() - - # weight buffer - if weight is not None: - if any([w <= 0 for w in weight]): - raise ValueError(f'Weight must be positive! Current value: {weight}') - elif not np.isclose(sum(weight), 1, atol=1e-6): - raise ValueError(f'Weight should add to one, current weight: {weight}') - weight = torch.tensor(weight).reshape(1, -1) - logging.info('Channel weight set to %s', weight) - self.register_buffer('weight', weight) - self.weight: Optional[torch.Tensor] - - # Batch reduction - self.reduction = reduction - if reduction == 'mean': - self.reduce = torch.mean - else: - raise ValueError(f'Unexpected reduction mode {reduction}.') - - # Input dimension - self.ndim = ndim - - if self.ndim == 3: - # Time-domain input - self.signal_shape = ('B', 'C', 'T') - elif self.ndim == 4: - # Spectral-domain input - self.signal_shape = ('B', 'C', 'D', 'T') - else: - raise ValueError(f'Unexpected input dimension: {self.ndim}') - - logging.debug('Initialized %s with', self.__class__.__name__) - logging.debug('\tweight: %s', self.weight) - logging.debug('\treduction: %s', self.reduction) - logging.debug('\tndim: %s', self.ndim) - logging.debug('\tsignal_shape: %s', self.signal_shape) - - @property - def input_types(self): - """Input types definitions for MAELoss.""" - return { - "estimate": NeuralType(self.signal_shape, VoidType()), - "target": NeuralType(self.signal_shape, VoidType()), - "input_length": NeuralType(tuple('B'), LengthsType(), optional=True), - "mask": NeuralType(self.signal_shape, MaskType(), optional=True), - } - - @property - def output_types(self): - """Output types definitions for MAELoss.""" - return {"loss": NeuralType(elements_type=LossType())} - - @typecheck() - def forward( - self, - estimate: torch.Tensor, - target: torch.Tensor, - input_length: Optional[torch.Tensor] = None, - mask: Optional[torch.Tensor] = None, - ) -> torch.Tensor: - """For input batch of multi-channel signals, calculate MAE between estimate and target for each channel, - perform averaging across channels (weighting optional), and apply reduction across the batch. - - Args: - estimate: Estimate of the target signal - target: Target signal - input_length: Length of each example in the batch - mask: Mask for each signal - - Returns: - Scalar loss. - """ - mae = calculate_mae_batch( - estimate=estimate, - target=target, - input_length=input_length, - mask=mask, - ) - - # channel averaging - if self.weight is None: - mae = torch.mean(mae, dim=1) - else: - # weighting across channels - mae = mae * self.weight - mae = torch.sum(mae, dim=1) - - # reduction - mae = self.reduce(mae) - - return mae diff --git a/nemo/collections/audio/losses/maxine/__init__.py b/nemo/collections/audio/losses/maxine/__init__.py deleted file mode 100644 index 6fcdfe815c0dde793570a1722625382e53a8c56c..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/losses/maxine/__init__.py +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.audio.losses.maxine.losses_combined import CombinedLoss - -__all__ = [ - 'CombinedLoss', -] diff --git a/nemo/collections/audio/losses/maxine/losses_combined.py b/nemo/collections/audio/losses/maxine/losses_combined.py deleted file mode 100644 index 95d95fe64ae82f615bd8866031db8e9f04b97b18..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/losses/maxine/losses_combined.py +++ /dev/null @@ -1,205 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import hashlib -from pathlib import Path -from typing import Optional - -import torch - -from nemo.collections.asr.models.asr_model import ASRModel -from nemo.collections.audio.parts.utils.transforms import MelSpectrogram, resample -from nemo.core import Loss, Typing, typecheck -from nemo.core.neural_types import LengthsType, LossType, NeuralType, VoidType -from nemo.utils import logging -from nemo.utils.cloud import maybe_download_from_cloud -from nemo.utils.data_utils import resolve_cache_dir - -from .sisnr_loss import sisnr_loss - -# ASR model used for loss -# Note: Currently only this model is supported -STT_EN_CONFORMER_CTC_SMALL_v1_6_0 = 'https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_conformer_ctc_small/versions/1.6.0/files/stt_en_conformer_ctc_small.nemo' - - -def restore_asr_model_from_cloud(location: str, refresh_cache: bool = False) -> ASRModel: - """Restore an ASR model from the cloud. - - Args: - location (str): The URL of the model in the cloud. - refresh_cache (bool): Whether to force re-download of the model. - - Returns: - nemo_asr.models.ASRModel: The restored model. - """ - logging.debug('Restoring model from cloud location: %s', location) - - # Split into filename and base URL - filename = location.split('/')[-1] - url = location.replace(filename, '') - - # Get local cache dir - cache_dir = Path.joinpath(resolve_cache_dir(), f'{filename[:-5]}') - - # If location in the cloud changes, this will force re-download - cache_subfolder = hashlib.md5(location.encode('utf-8')).hexdigest() - - nemo_model_file_in_cache = maybe_download_from_cloud( - url=url, filename=filename, cache_dir=cache_dir, subfolder=cache_subfolder, refresh_cache=refresh_cache - ) - - logging.debug('Model file in cache: %s', nemo_model_file_in_cache) - - # Restore model from local cache - model = ASRModel.restore_from(nemo_model_file_in_cache) - - return model - - -class CombinedLoss(Loss, Typing): - """ - Combination of three losses (signal quality/spectral+cepstral features/acoustic error) - See https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=1083798 - """ - - def __init__( - self, - sample_rate: int, - hop_length: int, - num_mels: int, - fft_length: int, - sisnr_loss_weight: float, - spectral_loss_weight: float, - asr_loss_weight: float, - use_asr_loss: bool = True, - use_mel_spec: bool = True, - conformer_model=STT_EN_CONFORMER_CTC_SMALL_v1_6_0, - epsilon=float(5.9604644775390625e-8), - ): - - super().__init__() - self.sample_rate = sample_rate - - window = torch.hann_window(fft_length) - self.register_buffer("window", window) - epsilon = torch.tensor(epsilon) - self.register_buffer("epsilon", epsilon, persistent=False) - self.source_lengths = None - self.source_value = sample_rate * sample_rate - if use_asr_loss: - self.asr_model = restore_asr_model_from_cloud(conformer_model) - self.asr_model.eval() - self.asr_model.freeze() - - self.mel_transform = MelSpectrogram( - sample_rate=sample_rate, - n_fft=fft_length, - hop_length=hop_length, - n_mels=num_mels, - center=False, - ) - self.mae_loss = torch.nn.L1Loss() - self.use_mel_spec = use_mel_spec - self.use_asr_loss = use_asr_loss - - self.sisnr_loss_weight = sisnr_loss_weight - self.spectral_loss_weight = spectral_loss_weight - self.asr_loss_weight = asr_loss_weight - - def spectral_loss(self, predicted_audio: torch.Tensor, primary_audio: torch.Tensor) -> torch.Tensor: - loss = 0 - if self.use_mel_spec: - primary_mel_spec = self.mel_transform(primary_audio) - predicted_mel_spec = self.mel_transform(predicted_audio) - melLoss = self.mae_loss(predicted_mel_spec, primary_mel_spec) - loss += melLoss - - log_pred = 2 * torch.log10(torch.clamp(predicted_mel_spec, min=self.epsilon)) - log_prim = 2 * torch.log10(torch.clamp(primary_mel_spec, min=self.epsilon)) - logMelLoss = self.mae_loss(log_pred, log_prim) - loss += logMelLoss - return loss - - def asr_loss(self, predicted_audio: torch.Tensor, primary_audio: torch.Tensor) -> torch.Tensor: - primary_audio_ = torch.squeeze(primary_audio, dim=1).to(next(self.parameters()).device) - predicted_audio_ = torch.squeeze(predicted_audio, dim=1).to(next(self.parameters()).device) - - input_len = torch.full([primary_audio_.size(dim=0)], primary_audio_.size(dim=-1)).to( - next(self.parameters()).device - ) - - asr_sample_rate = self.asr_model.cfg.sample_rate - if self.sample_rate != asr_sample_rate: - # Resample to 16kHz - primary_audio_ = resample(primary_audio_, self.sample_rate, asr_sample_rate) - predicted_audio_ = resample(predicted_audio_, self.sample_rate, asr_sample_rate) - - primary_log, _, _ = self.asr_model(input_signal=primary_audio_, input_signal_length=input_len) - predicted_log, _, _ = self.asr_model(input_signal=predicted_audio_, input_signal_length=input_len) - - primary_prob = 10**primary_log - predicted_prob = 10**predicted_log - - loss_fn = torch.nn.CrossEntropyLoss() - loss = loss_fn(predicted_prob, primary_prob) - return loss - - @property - def input_types(self): - """Input types definitions for CombinedLoss.""" - signal_shape = ('B', 'C', 'T') - return { - "estimate": NeuralType(signal_shape, VoidType()), - "target": NeuralType(signal_shape, VoidType()), - "input_length": NeuralType(tuple('B'), LengthsType(), optional=True), - } - - @property - def output_types(self): - """Output types definitions for CombinedLoss. - loss: - NeuralType(None) - """ - return {"loss": NeuralType(elements_type=LossType())} - - @typecheck() - def forward( - self, estimate: torch.Tensor, target: torch.Tensor, input_length: Optional[torch.Tensor] = None - ) -> torch.Tensor: - device = next(self.parameters()).device - if self.source_lengths is None: - batch = estimate.shape[0] - self.source_lengths = torch.full((batch,), self.source_value).to(device) - # Clip at min_len - min_len = int(torch.min(torch.tensor([estimate.size(-1), target.size(-1)]))) - if input_length is None: - input_length = torch.full((estimate.shape[0],), estimate.shape[1]).to(device) - source_lengths_l = torch.where(input_length > min_len, min_len, input_length) - primary_audio = estimate[..., :min_len] - predicted_audio = target[..., :min_len] - - loss_total = torch.tensor([0.0]).to(device) - - # SiSNR loss - loss_total += self.sisnr_loss_weight * sisnr_loss(primary_audio, predicted_audio, source_lengths_l) - - # Spectral Loss - loss = self.spectral_loss(predicted_audio, primary_audio) - loss_total += self.spectral_loss_weight * loss - - # ASR loss - if self.use_asr_loss: - loss_total += self.asr_loss_weight * self.asr_loss(predicted_audio, primary_audio) - - return loss_total diff --git a/nemo/collections/audio/losses/maxine/sisnr_loss.py b/nemo/collections/audio/losses/maxine/sisnr_loss.py deleted file mode 100644 index 89c20e5cd0a3130515f7e42d47ff2de8e8f5f0ed..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/losses/maxine/sisnr_loss.py +++ /dev/null @@ -1,149 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# The following piece of code was adapted from https://github.com/kaituoxu/Conv-TasNet -# released under the MIT License. -# Author: Kaituo XU -# Created on 2018/12 -# -# Copyright (c) 2018 Kaituo XU -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in all -# copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - -from itertools import permutations - -import torch - -EPS = 1e-8 - - -def sisnr_loss(source: torch.Tensor, estimate_source: torch.Tensor, source_lengths: torch.Tensor) -> float: - """ - Args: - source: [B, C, T], B is batch size - estimate_source: [B, C, T] - source_lengths: [B] - """ - max_snr, perms, max_snr_idx, snr_set = cal_si_snr_with_pit(source, estimate_source, source_lengths) - loss = 0 - torch.mean(max_snr) - - return loss - - -def cal_si_snr_with_pit(source, estimate_source, source_lengths): - """Calculate SI-SNR with PIT training. - Args: - source: [B, C, T], B is batch size - estimate_source: [B, C, T] - source_lengths: [B], each item is between [0, T] - """ - assert source.size() == estimate_source.size() - B, C, T = source.size() - # mask padding position along T - mask = get_mask(source, source_lengths) - estimate_source = estimate_source * mask - - # Step 1. Zero-mean norm - num_samples = source_lengths.view(-1, 1, 1).float() # [B, 1, 1] - mean_target = torch.sum(source, dim=2, keepdim=True) / num_samples - mean_estimate = torch.sum(estimate_source, dim=2, keepdim=True) / num_samples - zero_mean_target = source - mean_target - zero_mean_estimate = estimate_source - mean_estimate - # mask padding position along T - zero_mean_target *= mask - zero_mean_estimate *= mask - - # Step 2. SI-SNR with PIT - # reshape to use broadcast - s_target = torch.unsqueeze(zero_mean_target, dim=1) # [B, 1, C, T] - s_estimate = torch.unsqueeze(zero_mean_estimate, dim=2) # [B, C, 1, T] - # s_target = s / ||s||^2 - pair_wise_dot = torch.sum(s_estimate * s_target, dim=3, keepdim=True) # [B, C, C, 1] - s_target_energy = torch.sum(s_target**2, dim=3, keepdim=True) + EPS # [B, 1, C, 1] - pair_wise_proj = pair_wise_dot * s_target / s_target_energy # [B, C, C, T] - # e_noise = s' - s_target - e_noise = s_estimate - pair_wise_proj # [B, C, C, T] - # SI-SNR = 10 * log_10(||s_target||^2 / ||e_noise||^2) - pair_wise_si_snr = torch.sum(pair_wise_proj**2, dim=3) / (torch.sum(e_noise**2, dim=3) + EPS) - pair_wise_si_snr = 10 * torch.log10(pair_wise_si_snr + EPS) # [B, C, C] - pair_wise_si_snr = torch.transpose(pair_wise_si_snr, 1, 2) - - # Get max_snr of each utterance - # permutations, [C!, C] - perms = source.new_tensor(list(permutations(range(C))), dtype=torch.long) - # one-hot, [C!, C, C] - index = torch.unsqueeze(perms, 2) - perms_one_hot = source.new_zeros((*perms.size(), C)).scatter_(2, index, 1) - # [B, C!] <- [B, C, C] einsum [C!, C, C], SI-SNR sum of each permutation - snr_set = torch.einsum('bij,pij->bp', [pair_wise_si_snr, perms_one_hot]) - max_snr_idx = torch.argmax(snr_set, dim=1) # [B] - # max_snr = torch.gather(snr_set, 1, max_snr_idx.view(-1, 1)) # [B, 1] - max_snr, _ = torch.max(snr_set, dim=1, keepdim=True) - max_snr /= C - return max_snr, perms, max_snr_idx, snr_set / C - - -def reorder_source(source, perms, max_snr_idx): - """ - Args: - source: [B, C, T] - perms: [C!, C], permutations - max_snr_idx: [B], each item is between [0, C!) - Returns: - reorder_source: [B, C, T] - """ - B, C, *_ = source.size() - # [B, C], permutation whose SI-SNR is max of each utterance - # for each utterance, reorder estimate source according this permutation - max_snr_perm = torch.index_select(perms, dim=0, index=max_snr_idx) - # print('max_snr_perm', max_snr_perm) - # maybe use torch.gather()/index_select()/scatter() to impl this? - reorder_source = torch.zeros_like(source) - for b in range(B): - for c in range(C): - reorder_source[b, c] = source[b, max_snr_perm[b][c]] - return reorder_source - - -def get_mask(source, source_lengths): - """ - Args: - source: [B, C, T] - source_lengths: [B] - Returns: - mask: [B, 1, T] - """ - B, _, T = source.size() - '''print("B", B) - print("source_lengths", source_lengths.shape)''' - mask = source.new_ones((B, 1, T)) - for i in range(B): - mask[i, :, source_lengths[i] :] = 0 - return mask diff --git a/nemo/collections/audio/metrics/__init__.py b/nemo/collections/audio/metrics/__init__.py deleted file mode 100644 index 7a3c234cedf824860d49bc126ceaf51b7ee76f16..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/metrics/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.audio.metrics.audio import AudioMetricWrapper -from nemo.collections.audio.metrics.squim import SquimMOSMetric, SquimObjectiveMetric diff --git a/nemo/collections/audio/metrics/audio.py b/nemo/collections/audio/metrics/audio.py deleted file mode 100644 index 0f8b5bee0fd2355a4acfbf7816f751ea9762b436..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/metrics/audio.py +++ /dev/null @@ -1,201 +0,0 @@ -# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import Callable, Iterable, List, Optional, Tuple - -import torch -from torchmetrics import Metric -from torchmetrics.audio.pesq import PerceptualEvaluationSpeechQuality -from torchmetrics.audio.pit import PermutationInvariantTraining -from torchmetrics.audio.sdr import ScaleInvariantSignalDistortionRatio, SignalDistortionRatio -from torchmetrics.audio.snr import ScaleInvariantSignalNoiseRatio, SignalNoiseRatio -from torchmetrics.audio.stoi import ShortTimeObjectiveIntelligibility -from nemo.collections.audio.metrics.squim import SquimMOSMetric, SquimObjectiveMetric - -from nemo.utils import logging - -__all__ = ['AudioMetricWrapper'] - -__VERIFIED_METRICS__ = [ - PermutationInvariantTraining, - ScaleInvariantSignalDistortionRatio, - SignalDistortionRatio, - ScaleInvariantSignalNoiseRatio, - SignalNoiseRatio, - PerceptualEvaluationSpeechQuality, - ShortTimeObjectiveIntelligibility, - SquimMOSMetric, - SquimObjectiveMetric, -] - - -class AudioMetricWrapper(Metric): - """A wrapper around an audio metric enabling selection of a specific channel - and handling of examples in a batch with varying valid input length. - - Note: - This class assumes that the underlying metric uses averaging to calculate the - value over a batch. This assumption is only used by `forward` and does not - impact other methods, such as `update` and `compute`. - - Args: - metric: base metric that should be wrapped. It is assumed that calculation - of the metric over a batch is done by averaging. - channel: Optional, for selecting a channel from `preds` and `target` signals. - If None, all channels are used. - metric_using_batch_averaging: Optional, used to denote that the base metric - is using averaging to calculate the metric value - for a batch. - """ - - full_state_update: bool = False - num_examples: torch.Tensor - - def __init__( - self, metric: Metric, channel: Optional[int] = None, metric_using_batch_averaging: Optional[bool] = None - ): - super().__init__() - if not isinstance(metric, Metric): - raise ValueError(f"Expected argument `metric` to be an instance of `torchmetrics.Metric` but got {metric}") - - if not metric_using_batch_averaging and type(metric) not in __VERIFIED_METRICS__: - raise ValueError( - f'Metric {metric} is not in verified metrics. {self.__class__.__name__} assumes reduction over batch is calculated using averaging. \n' - 'This should not affect the final results, but values for a single batch obtained using `forward` may be inaccurate if using `input_length`. \n' - 'To suppress this message, please confirm the used metric is using batch averaging and set "metric_using_batch_averaging = True"' - ) - - self._metric = metric - self._channel = channel - self.add_state('num_examples', default=torch.tensor(0), dist_reduce_fx='sum') - logging.debug('Setup metric %s, channel %s', metric, str(channel)) - - def _select_channel(self, preds: torch.Tensor, target: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: - """Select a single channel from input signals. - - Args: - preds: tensor with shape (B, C, T) - target: tensor with shape (B, C, T) - - Returns: - Original tensors if self.channel is None, shape (B, C, T). - A single channel from input tensors if self.channel is set, shape (B, T) - """ - if self._channel is None: - return preds, target - else: - return preds[:, self._channel, ...], target[:, self._channel, ...] - - @staticmethod - def _trim_inputs( - preds: torch.Tensor, target: torch.Tensor, input_length: torch.Tensor - ) -> Iterable[Tuple[torch.Tensor, torch.Tensor]]: - """Trim input tensors to input_length samples. - - Args: - preds: tensor with shape (B, C, T) - target: tensor with shape (B, C, T) - - Returns: - An iterable with tuples of (preds, target) with - the correct length. - """ - # Each example has a different length - for b_idx, b_len in enumerate(input_length): - b_preds = preds[b_idx, ..., :b_len] - b_target = target[b_idx, ..., :b_len] - - yield b_preds, b_target - - @staticmethod - def _batch_reduction(batch_values: List[torch.Tensor]) -> torch.Tensor: - """Reduce metric values for each example in a batch to a single - value for the whole batch. - - Args: - batch_values: list of metric values for each example in a batch - - Returns: - Average metric value over the batch. - """ - return sum(batch_values) / len(batch_values) - - def update(self, preds: torch.Tensor, target: torch.Tensor, input_length: Optional[torch.Tensor] = None) -> None: - """Update the underlying metric by taking into account channel selector and input length. - - Args: - preds: tensor with predictions, shape (B, C, T) - target: tensor with target signals, shape (B, C, T) - input_length: Optional, input tensor with length (in samples) of each signal in the batch, shape (B,). - If not provided, it is assumed that all samples are valid. - """ - preds, target = self._select_channel(preds=preds, target=target) - - if input_length is None: - self._metric.update(preds=preds, target=target) - else: - # Each example in this batch has a different length - for b_preds, b_target in self._trim_inputs(preds=preds, target=target, input_length=input_length): - self._metric.update(preds=b_preds, target=b_target) - - self.num_examples += preds.size(0) - - def compute(self) -> torch.Tensor: - """Compute the underlying metric.""" - return self._metric.compute() - - def forward( - self, preds: torch.Tensor, target: torch.Tensor, input_length: Optional[torch.Tensor] = None - ) -> torch.Tensor: - """Call underlying forward method to add the batch statistics to the accumulated metric state - and return the result for the current batch. - - Args: - preds: tensor with predictions, shape (B, C, T) - target: tensor with target signals, shape (B, C, T) - input_length: Optional, input tensor with length (in samples) of each signal in the batch, shape (B,). - If not provided, it is assumed that all samples are valid. - - Returns: - Underlying metric averaged on the current batch. - """ - preds, target = self._select_channel(preds=preds, target=target) - - if input_length is None: - return self._metric(preds=preds, target=target) - else: - # Each example in this batch has a different length - batch_values = [] - for b_preds, b_target in self._trim_inputs(preds=preds, target=target, input_length=input_length): - batch_values.append(self._metric(preds=b_preds, target=b_target)) - # Average over the batch - return self._batch_reduction(batch_values) - - def reset(self) -> None: - """Reset the underlying metric.""" - # reset the internal states - super().reset() - # reset the underlying metric - self._metric.reset() - - def __repr__(self) -> str: - """Return string representation of the object.""" - _op_metric = f"(metric: {repr(self._metric)}, channel: {self._channel})" - repr_str = self.__class__.__name__ + _op_metric - - return repr_str - - def _wrap_compute(self, compute: Callable) -> Callable: - """Overwrite to do nothing, as in CompositionalMetric.""" - return compute diff --git a/nemo/collections/audio/metrics/squim.py b/nemo/collections/audio/metrics/squim.py deleted file mode 100644 index 58f42f86d03709f92d2d6a4b8569848a84dcd77a..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/metrics/squim.py +++ /dev/null @@ -1,197 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import Any - -import torch -from torchmetrics import Metric -from nemo.utils import logging - -try: - import torchaudio - - HAVE_TORCHAUDIO = True -except ModuleNotFoundError: - HAVE_TORCHAUDIO = False - - -class SquimMOSMetric(Metric): - """A metric calculating the average Torchaudio Squim MOS. - - Args: - fs: sampling rate of the input signals - """ - - sample_rate: int = 16000 # sample rate of the model - mos_sum: torch.Tensor - num_examples: torch.Tensor - higher_is_better: bool = True - - def __init__(self, fs: int, **kwargs: Any): - super().__init__(**kwargs) - - if not HAVE_TORCHAUDIO: - raise ModuleNotFoundError(f"{self.__class__.__name__} metric needs `torchaudio`.") - - if fs != self.sample_rate: - # Resampler: kaiser_best - self._squim_mos_metric_resampler = torchaudio.transforms.Resample( - orig_freq=fs, - new_freq=self.sample_rate, - lowpass_filter_width=64, - rolloff=0.9475937167399596, - resampling_method='sinc_interp_kaiser', - beta=14.769656459379492, - ) - logging.warning('Input signals will be resampled from fs=%d to %d Hz', fs, self.sample_rate) - self.fs = fs - - # MOS model - self._squim_mos_metric_model = torchaudio.pipelines.SQUIM_SUBJECTIVE.get_model() - - self.add_state('mos_sum', default=torch.tensor(0.0), dist_reduce_fx='sum') - self.add_state('num_examples', default=torch.tensor(0), dist_reduce_fx='sum') - logging.debug('Setup metric %s with input fs=%s', self.__class__.__name__, self.fs) - - def update(self, preds: torch.Tensor, target: torch.Tensor) -> None: - """Update the metric by calculating the MOS score for the current batch. - - Args: - preds: tensor with predictions, shape (B, T) - target: tensor with target signals, shape (B, T). Target can be a non-matching reference. - """ - if self.fs != self.sample_rate: - preds = self._squim_mos_metric_resampler(preds) - target = self._squim_mos_metric_resampler(target) - - if preds.ndim == 1: - # Unsqueeze batch dimension - preds = preds.unsqueeze(0) - target = target.unsqueeze(0) - elif preds.ndim > 2: - raise ValueError(f'Expected 1D or 2D signals, got {preds.ndim}D signals') - - mos_batch = self._squim_mos_metric_model(preds, target) - - self.mos_sum += mos_batch.sum() - self.num_examples += mos_batch.numel() - - def compute(self) -> torch.Tensor: - """Compute the underlying metric.""" - return self.mos_sum / self.num_examples - - def state_dict(self, *args, **kwargs): - """Do not save the MOS model and resampler in the state dict.""" - state_dict = super().state_dict(*args, **kwargs) - # Do not include resampler or mos_model in the state dict - remove_keys = [ - key - for key in state_dict.keys() - if '_squim_mos_metric_resampler' in key or '_squim_mos_metric_model' in key - ] - for key in remove_keys: - del state_dict[key] - return state_dict - - -class SquimObjectiveMetric(Metric): - """A metric calculating the average Torchaudio Squim objective metric. - - Args: - fs: sampling rate of the input signals - metric: the objective metric to calculate. One of 'stoi', 'pesq', 'si_sdr' - """ - - sample_rate: int = 16000 # sample rate of the model - metric_sum: torch.Tensor - num_examples: torch.Tensor - higher_is_better: bool = True - - def __init__(self, fs: int, metric: str, **kwargs: Any): - super().__init__(**kwargs) - - if not HAVE_TORCHAUDIO: - raise ModuleNotFoundError(f"{self.__class__.__name__} needs `torchaudio`.") - - if fs != self.sample_rate: - # Resampler: kaiser_best - self._squim_objective_metric_resampler = torchaudio.transforms.Resample( - orig_freq=fs, - new_freq=self.sample_rate, - lowpass_filter_width=64, - rolloff=0.9475937167399596, - resampling_method='sinc_interp_kaiser', - beta=14.769656459379492, - ) - logging.warning('Input signals will be resampled from fs=%d to %d Hz', fs, self.sample_rate) - self.fs = fs - - if metric not in ['stoi', 'pesq', 'si_sdr']: - raise ValueError(f'Unsupported metric {metric}. Supported metrics are "stoi", "pesq", "si_sdr".') - - self.metric = metric - - # Objective model - self._squim_objective_metric_model = torchaudio.pipelines.SQUIM_OBJECTIVE.get_model() - - self.add_state('metric_sum', default=torch.tensor(0.0), dist_reduce_fx='sum') - self.add_state('num_examples', default=torch.tensor(0), dist_reduce_fx='sum') - logging.debug('Setup %s with metric=%s, input fs=%s', self.__class__.__name__, self.metric, self.fs) - - def update(self, preds: torch.Tensor, target: Any = None) -> None: - """Update the metric by calculating the selected metric score for the current batch. - - Args: - preds: tensor with predictions, shape (B, T) - target: None, not used. Keeping for interfacfe compatibility with other metrics. - """ - if self.fs != self.sample_rate: - preds = self._squim_objective_metric_resampler(preds) - - if preds.ndim == 1: - # Unsqueeze batch dimension - preds = preds.unsqueeze(0) - elif preds.ndim > 2: - raise ValueError(f'Expected 1D or 2D signals, got {preds.ndim}D signals') - - stoi_batch, pesq_batch, si_sdr_batch = self._squim_objective_metric_model(preds) - - if self.metric == 'stoi': - metric_batch = stoi_batch - elif self.metric == 'pesq': - metric_batch = pesq_batch - elif self.metric == 'si_sdr': - metric_batch = si_sdr_batch - else: - raise ValueError(f'Unknown metric {self.metric}') - - self.metric_sum += metric_batch.sum() - self.num_examples += metric_batch.numel() - - def compute(self) -> torch.Tensor: - """Compute the underlying metric.""" - return self.metric_sum / self.num_examples - - def state_dict(self, *args, **kwargs): - """Do not save the MOS model and resampler in the state dict.""" - state_dict = super().state_dict(*args, **kwargs) - # Do not include resampler or mos_model in the state dict - remove_keys = [ - key - for key in state_dict.keys() - if '_squim_objective_metric_resampler' in key or '_squim_objective_metric_model' in key - ] - for key in remove_keys: - del state_dict[key] - return state_dict diff --git a/nemo/collections/audio/models/__init__.py b/nemo/collections/audio/models/__init__.py deleted file mode 100644 index 28845859872c5c81fc48461b3c96d4734a7b7c5d..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/models/__init__.py +++ /dev/null @@ -1,31 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.audio.models.audio_to_audio import AudioToAudioModel -from nemo.collections.audio.models.enhancement import ( - EncMaskDecAudioToAudioModel, - FlowMatchingAudioToAudioModel, - PredictiveAudioToAudioModel, - SchroedingerBridgeAudioToAudioModel, - ScoreBasedGenerativeAudioToAudioModel, -) - -__all__ = [ - "AudioToAudioModel", - "EncMaskDecAudioToAudioModel", - "FlowMatchingAudioToAudioModel", - "PredictiveAudioToAudioModel", - "SchroedingerBridgeAudioToAudioModel", - "ScoreBasedGenerativeAudioToAudioModel", -] diff --git a/nemo/collections/audio/models/audio_to_audio.py b/nemo/collections/audio/models/audio_to_audio.py deleted file mode 100644 index 28109f27b7f2d7c2b353137ba46102560625cc8a..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/models/audio_to_audio.py +++ /dev/null @@ -1,535 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import json -import os -import tempfile -from abc import ABC, abstractmethod -from typing import Dict, List, Optional, Union - -import hydra -import librosa -import soundfile as sf -import torch -from lightning.pytorch import Trainer -from omegaconf import DictConfig, OmegaConf -from tqdm import tqdm - -from nemo.collections.asr.data.audio_to_text_dataset import inject_dataloader_value_from_model_config -from nemo.collections.asr.parts.preprocessing.segment import ChannelSelectorType -from nemo.collections.audio.data import audio_to_audio_dataset -from nemo.collections.audio.data.audio_to_audio_lhotse import LhotseAudioToTargetDataset -from nemo.collections.audio.metrics.audio import AudioMetricWrapper -from nemo.collections.common.data.lhotse import get_lhotse_dataloader_from_config -from nemo.core.classes import ModelPT -from nemo.core.classes.common import PretrainedModelInfo -from nemo.utils import logging, model_utils - -__all__ = ['AudioToAudioModel'] - - -class AudioToAudioModel(ModelPT, ABC): - """Base class for audio-to-audio models. - - Args: - cfg: A DictConfig object with the configuration parameters. - trainer: A Trainer object to be used for training. - """ - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - super().__init__(cfg=cfg, trainer=trainer) - - self._setup_loss() - - def _setup_loss(self): - """Setup loss for this model.""" - if 'loss' in self._cfg: - self.loss = AudioToAudioModel.from_config_dict(self._cfg.loss) - else: - logging.warning('No loss function is defined in the config.') - self.loss = None - - def _get_num_dataloaders(self, tag: str = 'val'): - if tag == 'val': - num_dataloaders = len(self._validation_dl) if isinstance(self._validation_dl, List) else 1 - elif tag == 'test': - num_dataloaders = len(self._test_dl) if isinstance(self._test_dl, List) else 1 - else: - raise ValueError(f'Unexpected tag {tag}.') - - return num_dataloaders - - def _setup_metrics(self, tag: str = 'val'): - """Setup metrics for this model for all available dataloaders. - - When using multiple DataLoaders, it is recommended to initialize separate modular - metric instances for each DataLoader and use them separately. - - Reference: - - https://torchmetrics.readthedocs.io/en/stable/pages/lightning.html#common-pitfalls - """ - # Number of currently configured dataloaders - num_dataloaders = self._get_num_dataloaders(tag) - logging.debug('Found %d dataloaders for %s', num_dataloaders, tag) - - if hasattr(self, 'metrics'): - if tag in self.metrics and len(self.metrics[tag]) == num_dataloaders: - # Exact number of metrics have already been configured, nothing else to do - logging.debug('Found %d metrics for tag %s, not necesary to initialize again', num_dataloaders, tag) - return - - if self.cfg.get('metrics') is None: - # Metrics are not available in the configuration, nothing to do - logging.debug('No metrics configured in model.metrics') - return - - if (metrics_cfg := self.cfg['metrics'].get(tag)) is None: - # Metrics configuration is not available in the configuration, nothing to do - logging.debug('No metrics configured for %s in model.metrics', tag) - return - - if 'loss' in metrics_cfg: - raise ValueError( - f'Loss is automatically included in the metrics, it should not be specified in model.metrics.{tag}.' - ) - - # Initialize metrics - if not hasattr(self, 'metrics'): - self.metrics = torch.nn.ModuleDict() - - # Setup metrics for each dataloader - self.metrics[tag] = torch.nn.ModuleList() - for dataloader_idx in range(num_dataloaders): - metrics_dataloader_idx = {} - for name, cfg in metrics_cfg.items(): - logging.debug('Initialize %s for dataloader_idx %s', name, dataloader_idx) - cfg_dict = OmegaConf.to_container(cfg) - cfg_channel = cfg_dict.pop('channel', None) - cfg_batch_averaging = cfg_dict.pop('metric_using_batch_averaging', None) - metrics_dataloader_idx[name] = AudioMetricWrapper( - metric=hydra.utils.instantiate(cfg_dict), - channel=cfg_channel, - metric_using_batch_averaging=cfg_batch_averaging, - ) - - metrics_dataloader_idx = torch.nn.ModuleDict(metrics_dataloader_idx) - self.metrics[tag].append(metrics_dataloader_idx.to(self.device)) - - logging.info( - 'Setup metrics for %s, dataloader %d: %s', tag, dataloader_idx, ', '.join(metrics_dataloader_idx) - ) - - @abstractmethod - def evaluation_step(self, batch, batch_idx, dataloader_idx: int = 0, tag: str = 'val'): - pass - - def on_validation_start(self): - self._setup_metrics('val') - return super().on_validation_start() - - def on_test_start(self): - self._setup_metrics('test') - return super().on_test_start() - - def validation_step(self, batch, batch_idx, dataloader_idx: int = 0): - output_dict = self.evaluation_step(batch, batch_idx, dataloader_idx, 'val') - if isinstance(self.trainer.val_dataloaders, (list, tuple)) and len(self.trainer.val_dataloaders) > 1: - self.validation_step_outputs[dataloader_idx].append(output_dict) - else: - self.validation_step_outputs.append(output_dict) - return output_dict - - def test_step(self, batch, batch_idx, dataloader_idx=0): - output_dict = self.evaluation_step(batch, batch_idx, dataloader_idx, 'test') - if isinstance(self.trainer.test_dataloaders, (list, tuple)) and len(self.trainer.test_dataloaders) > 1: - self.test_step_outputs[dataloader_idx].append(output_dict) - else: - self.test_step_outputs.append(output_dict) - return output_dict - - def multi_evaluation_epoch_end(self, outputs, dataloader_idx: int = 0, tag: str = 'val'): - # Handle loss - loss_mean = torch.stack([x[f'{tag}_loss'] for x in outputs]).mean() - tensorboard_logs = {f'{tag}_loss': loss_mean} - - # Handle metrics for this tag and dataloader_idx - if hasattr(self, 'metrics') and tag in self.metrics: - for name, metric in self.metrics[tag][dataloader_idx].items(): - # Compute & reset the metric - value = metric.compute() - metric.reset() - # Store for logs - tensorboard_logs[f'{tag}_{name}'] = value - - return {f'{tag}_loss': loss_mean, 'log': tensorboard_logs} - - def multi_validation_epoch_end(self, outputs, dataloader_idx: int = 0): - return self.multi_evaluation_epoch_end(outputs, dataloader_idx, 'val') - - def multi_test_epoch_end(self, outputs, dataloader_idx: int = 0): - return self.multi_evaluation_epoch_end(outputs, dataloader_idx, 'test') - - def _setup_dataloader_from_config(self, config: Optional[Dict]): - # TODO: Consider moving `inject` from `audio_to_text_dataset` to a utility module? - # Automatically inject args from model config to dataloader config - inject_dataloader_value_from_model_config(self.cfg, config, key='sample_rate') - - if config.get("use_lhotse", False): - return get_lhotse_dataloader_from_config( - config, global_rank=self.global_rank, world_size=self.world_size, dataset=LhotseAudioToTargetDataset() - ) - - is_concat = config.get('is_concat', False) - if is_concat: - raise NotImplementedError('Concat not implemented') - - # Instantiate tarred dataset loader or normal dataset loader - if config.get('is_tarred', False): - raise NotImplementedError('Tarred datasets not supported') - - if 'manifest_filepath' in config and config['manifest_filepath'] is None: - logging.warning(f"Could not load dataset as `manifest_filepath` was None. Provided config : {config}") - return None - - dataset = audio_to_audio_dataset.get_audio_to_target_dataset(config=config) - - if hasattr(dataset, 'collate_fn'): - collate_fn = dataset.collate_fn - elif hasattr(dataset.datasets[0], 'collate_fn'): - # support datasets that are lists of entries - collate_fn = dataset.datasets[0].collate_fn - else: - # support datasets that are lists of lists - collate_fn = dataset.datasets[0].datasets[0].collate_fn - - return torch.utils.data.DataLoader( - dataset=dataset, - batch_size=config['batch_size'], - collate_fn=collate_fn, - drop_last=config.get('drop_last', False), - shuffle=config['shuffle'], - num_workers=config.get('num_workers', 0), - pin_memory=config.get('pin_memory', False), - ) - - def setup_training_data(self, train_data_config: Optional[Union[DictConfig, Dict]]): - """ - Sets up the training data loader via a Dict-like object. - - Args: - train_data_config: A config that contains the information regarding construction - of a training dataset. - - Supported Datasets: - - :class:`~nemo.collections.asr.data.audio_to_audio.AudioToTargetDataset` - """ - if 'shuffle' not in train_data_config: - train_data_config['shuffle'] = True - - # preserve config - self._update_dataset_config(dataset_name='train', config=train_data_config) - - self._train_dl = self._setup_dataloader_from_config(config=train_data_config) - - if 'is_tarred' in train_data_config and train_data_config['is_tarred']: - raise NotImplementedError('Tarred datasets not supported') - - def setup_validation_data(self, val_data_config: Optional[Union[DictConfig, Dict]]): - """ - Sets up the validation data loader via a Dict-like object. - - Args: - val_data_config: A config that contains the information regarding construction - of a validation dataset. - - Supported Datasets: - - :class:`~nemo.collections.asr.data.audio_to_audio.AudioToTargetDataset` - """ - if 'shuffle' not in val_data_config: - val_data_config['shuffle'] = False - - # preserve config - self._update_dataset_config(dataset_name='validation', config=val_data_config) - - self._validation_dl = self._setup_dataloader_from_config(config=val_data_config) - - def setup_test_data(self, test_data_config: Optional[Union[DictConfig, Dict]]): - """ - Sets up the test data loader via a Dict-like object. - - Args: - test_data_config: A config that contains the information regarding construction - of a test dataset. - - Supported Datasets: - - :class:`~nemo.collections.asr.data.audio_to_audio.AudioToTargetDataset` - """ - if 'shuffle' not in test_data_config: - test_data_config['shuffle'] = False - - # preserve config - self._update_dataset_config(dataset_name='test', config=test_data_config) - - self._test_dl = self._setup_dataloader_from_config(config=test_data_config) - - def _setup_process_dataloader(self, config: Dict) -> 'torch.utils.data.DataLoader': - """Prepare a dataloader for processing files. - - Args: - config: A python dictionary which contains the following keys: - manifest_filepath: path to a manifest file - input_key: key with audio filepaths in the manifest - input_channel_selector: Optional, used to select a subset of channels from input audio files - batch_size: batch size for the dataloader - num_workers: number of workers for the dataloader - - Returns: - A pytorch DataLoader for the given manifest filepath. - """ - dl_config = { - 'manifest_filepath': config['manifest_filepath'], - 'sample_rate': self.sample_rate, - 'input_key': config['input_key'], - 'input_channel_selector': config.get('input_channel_selector', None), - 'target_key': None, - 'target_channel_selector': None, - 'batch_size': config['batch_size'], - 'shuffle': False, - 'num_workers': config.get('num_workers', min(config['batch_size'], os.cpu_count() - 1)), - 'pin_memory': True, - } - - temporary_dataloader = self._setup_dataloader_from_config(config=DictConfig(dl_config)) - return temporary_dataloader - - @staticmethod - def match_batch_length(input: torch.Tensor, batch_length: int) -> torch.Tensor: - """Trim or pad the output to match the batch length. - - Args: - input: tensor with shape (B, C, T) - batch_length: int - - Returns: - Tensor with shape (B, C, T), where T matches the - batch length. - """ - input_length = input.size(-1) - pad_length = batch_length - input_length - pad = (0, pad_length) - # pad with zeros or crop - return torch.nn.functional.pad(input, pad, 'constant', 0) - - @torch.no_grad() - def process( - self, - paths2audio_files: List[str], - output_dir: str, - batch_size: int = 1, - num_workers: Optional[int] = None, - input_channel_selector: Optional[ChannelSelectorType] = None, - input_dir: Optional[str] = None, - ) -> List[str]: - """ - Takes paths to audio files and returns a list of paths to processed - audios. - - Args: - paths2audio_files: paths to audio files to be processed - output_dir: directory to save the processed files - batch_size: (int) batch size to use during inference. - num_workers: Number of workers for the dataloader - input_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`. - input_dir: Optional, directory that contains the input files. If provided, the output directory will mirror the input directory structure. - - Returns: - Paths to processed audio signals. - """ - if paths2audio_files is None or len(paths2audio_files) == 0: - return {} - - if num_workers is None: - num_workers = min(batch_size, os.cpu_count() - 1) - - # Output - paths2processed_files = [] - - # Model's mode and device - mode = self.training - device = next(self.parameters()).device - - try: - # Switch model to evaluation mode - self.eval() - # Freeze weights - self.freeze() - - logging_level = logging.get_verbosity() - logging.set_verbosity(logging.WARNING) - - # Processing - with tempfile.TemporaryDirectory() as tmpdir: - # Save temporary manifest - temporary_manifest_filepath = os.path.join(tmpdir, 'manifest.json') - with open(temporary_manifest_filepath, 'w', encoding='utf-8') as fp: - for audio_file in paths2audio_files: - entry = {'input_filepath': audio_file, 'duration': librosa.get_duration(path=audio_file)} - fp.write(json.dumps(entry) + '\n') - - config = { - 'manifest_filepath': temporary_manifest_filepath, - 'input_key': 'input_filepath', - 'input_channel_selector': input_channel_selector, - 'batch_size': min(batch_size, len(paths2audio_files)), - 'num_workers': num_workers, - } - - # Create output dir if necessary - if not os.path.isdir(output_dir): - os.makedirs(output_dir) - - # DataLoader for the input files - temporary_dataloader = self._setup_process_dataloader(config) - - # Indexing of the original files, used to form the output file name - file_idx = 0 - - # Process batches - for test_batch in tqdm(temporary_dataloader, desc="Processing"): - input_signal = test_batch[0] - input_length = test_batch[1] - - # Expand channel dimension, if necessary - # For consistency, the model uses multi-channel format, even if the channel dimension is 1 - if input_signal.ndim == 2: - input_signal = input_signal.unsqueeze(1) - - processed_batch, _ = self.forward( - input_signal=input_signal.to(device), input_length=input_length.to(device) - ) - - for example_idx in range(processed_batch.size(0)): - # This assumes the data loader is not shuffling files - if input_dir is not None: - # Make sure the output has the same directory structure as the input - filepath_relative = os.path.relpath(paths2audio_files[file_idx], start=input_dir) - else: - # Input dir is not provided, save files in the output directory - filepath_relative = os.path.basename(paths2audio_files[file_idx]) - # Prepare output file - output_file = os.path.join(output_dir, filepath_relative) - # Create output dir if necessary - if not os.path.isdir(os.path.dirname(output_file)): - os.makedirs(os.path.dirname(output_file)) - # Crop the output signal to the actual length - output_signal = processed_batch[example_idx, :, : input_length[example_idx]].cpu().numpy() - # Write audio - sf.write(output_file, output_signal.T, self.sample_rate, 'float') - # Update the file counter - file_idx += 1 - # Save processed file - paths2processed_files.append(output_file) - - del test_batch - del processed_batch - - finally: - # set mode back to its original value - self.train(mode=mode) - if mode is True: - self.unfreeze() - logging.set_verbosity(logging_level) - - return paths2processed_files - - @classmethod - def list_available_models(cls) -> 'List[PretrainedModelInfo]': - """ - This method returns a list of pre-trained model which can be instantiated directly from NVIDIA's NGC cloud. - - Returns: - List of available pre-trained models. - """ - # recursively walk the subclasses to generate pretrained model info - list_of_models = model_utils.resolve_subclass_pretrained_model_info(cls) - return list_of_models - - def setup_optimization_flags(self): - """ - Utility method that must be explicitly called by the subclass in order to support optional optimization flags. - This method is the only valid place to access self.cfg prior to DDP training occurs. - - The subclass may chose not to support this method, therefore all variables here must be checked via hasattr() - """ - # Skip update if nan/inf grads appear on any rank. - self._skip_nan_grad = False - if "skip_nan_grad" in self._cfg and self._cfg["skip_nan_grad"]: - self._skip_nan_grad = self._cfg["skip_nan_grad"] - - def on_after_backward(self): - """ - zero-out the gradients which any of them is NAN or INF - """ - super().on_after_backward() - - if hasattr(self, '_skip_nan_grad') and self._skip_nan_grad: - device = next(self.parameters()).device - valid_gradients = torch.tensor([1], device=device, dtype=torch.float32) - - # valid_gradients = True - for param_name, param in self.named_parameters(): - if param.grad is not None: - is_not_nan_or_inf = not (torch.isnan(param.grad).any() or torch.isinf(param.grad).any()) - if not is_not_nan_or_inf: - valid_gradients = valid_gradients * 0 - break - - if torch.distributed.is_initialized(): - torch.distributed.all_reduce(valid_gradients, op=torch.distributed.ReduceOp.MIN) - - if valid_gradients < 1: - logging.warning('detected inf or nan values in gradients! Setting gradients to zero.') - self.zero_grad(set_to_none=False) - - def configure_callbacks(self): - """ - Create an callback to add audio/spectrogram into tensorboard & wandb. - """ - self.log_config = self.cfg.get("log_config", None) - if not self.log_config: - return [] - - log_callbacks = [] - from nemo.collections.audio.parts.utils.callbacks import SpeechEnhancementLoggingCallback - - if isinstance(self._validation_dl, List): - data_loaders = self._validation_dl - else: - data_loaders = [self._validation_dl] - - for data_loader_idx, data_loader in enumerate(data_loaders): - log_callbacks.append( - SpeechEnhancementLoggingCallback( - data_loader=data_loader, - data_loader_idx=data_loader_idx, - loggers=self.trainer.loggers, - log_tensorboard=self.log_config.log_tensorboard, - log_wandb=self.log_config.log_wandb, - sample_rate=self.sample_rate, - max_utts=self.log_config.get("max_utts", None), - ) - ) - - return log_callbacks diff --git a/nemo/collections/audio/models/enhancement.py b/nemo/collections/audio/models/enhancement.py deleted file mode 100644 index 02c449a5b2b824ec57ae5662e5f8b0c999255a5e..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/models/enhancement.py +++ /dev/null @@ -1,1294 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import Dict, Optional - -import einops -import hydra -import torch -from lightning.pytorch import Trainer -from omegaconf import DictConfig - -from nemo.collections.audio.models.audio_to_audio import AudioToAudioModel -from nemo.core.classes.common import PretrainedModelInfo, typecheck -from nemo.core.neural_types import AudioSignal, LengthsType, LossType, NeuralType -from nemo.utils import logging - -__all__ = [ - 'EncMaskDecAudioToAudioModel', - 'ScoreBasedGenerativeAudioToAudioModel', - 'PredictiveAudioToAudioModel', - 'SchroedingerBridgeAudioToAudioModel', - 'FlowMatchingAudioToAudioModel', -] - - -class EncMaskDecAudioToAudioModel(AudioToAudioModel): - """Class for encoder-mask-decoder audio processing models. - - The model consists of the following blocks: - - encoder: transforms input multi-channel audio signal into an encoded representation (analysis transform) - - mask_estimator: estimates a mask used by signal processor - - mask_processor: mask-based signal processor, combines the encoded input and the estimated mask - - decoder: transforms processor output into the time domain (synthesis transform) - """ - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - # Get global rank and total number of GPU workers for IterableDataset partitioning, if applicable - # Global_rank and local_rank is set by LightningModule in Lightning 1.2.0 - self.world_size = 1 - if trainer is not None: - self.world_size = trainer.world_size - - super().__init__(cfg=cfg, trainer=trainer) - self.sample_rate = self._cfg.sample_rate - - # Setup processing modules - self.encoder = EncMaskDecAudioToAudioModel.from_config_dict(self._cfg.encoder) - self.mask_estimator = EncMaskDecAudioToAudioModel.from_config_dict(self._cfg.mask_estimator) - self.mask_processor = EncMaskDecAudioToAudioModel.from_config_dict(self._cfg.mask_processor) - self.decoder = EncMaskDecAudioToAudioModel.from_config_dict(self._cfg.decoder) - - if 'mixture_consistency' in self._cfg: - logging.debug('Using mixture consistency') - self.mixture_consistency = EncMaskDecAudioToAudioModel.from_config_dict(self._cfg.mixture_consistency) - else: - logging.debug('Mixture consistency not used') - self.mixture_consistency = None - - # Setup augmentation - if hasattr(self.cfg, 'channel_augment') and self.cfg.channel_augment is not None: - logging.debug('Using channel augmentation') - self.channel_augmentation = EncMaskDecAudioToAudioModel.from_config_dict(self.cfg.channel_augment) - else: - logging.debug('Channel augmentation not used') - self.channel_augmentation = None - - # Setup optional Optimization flags - self.setup_optimization_flags() - - @property - def input_types(self) -> Dict[str, NeuralType]: - return { - "input_signal": NeuralType( - ('B', 'C', 'T'), AudioSignal(freq=self.sample_rate) - ), # multi-channel format, channel dimension can be 1 for single-channel audio - "input_length": NeuralType(tuple('B'), LengthsType(), optional=True), - } - - @property - def output_types(self) -> Dict[str, NeuralType]: - return { - "output_signal": NeuralType( - ('B', 'C', 'T'), AudioSignal(freq=self.sample_rate) - ), # multi-channel format, channel dimension can be 1 for single-channel audio - "output_length": NeuralType(tuple('B'), LengthsType(), optional=True), - } - - @typecheck() - def forward(self, input_signal, input_length=None): - """ - Forward pass of the model. - - Args: - input_signal: Tensor that represents a batch of raw audio signals, - of shape [B, T] or [B, T, C]. T here represents timesteps, with 1 second of audio represented as - `self.sample_rate` number of floating point values. - input_signal_length: Vector of length B, that contains the individual lengths of the audio - sequences. - - Returns: - Output signal `output` in the time domain and the length of the output signal `output_length`. - """ - batch_length = input_signal.size(-1) - - # Encoder - encoded, encoded_length = self.encoder(input=input_signal, input_length=input_length) - - # Mask estimator - mask, _ = self.mask_estimator(input=encoded, input_length=encoded_length) - - # Mask-based processor in the encoded domain - processed, processed_length = self.mask_processor(input=encoded, input_length=encoded_length, mask=mask) - - # Mixture consistency - if self.mixture_consistency is not None: - processed = self.mixture_consistency(mixture=encoded, estimate=processed) - - # Decoder - processed, processed_length = self.decoder(input=processed, input_length=processed_length) - - # Trim or pad the estimated signal to match input length - processed = self.match_batch_length(input=processed, batch_length=batch_length) - return processed, processed_length - - # PTL-specific methods - def training_step(self, batch, batch_idx): - - if isinstance(batch, dict): - # lhotse batches are dictionaries - input_signal = batch['input_signal'] - input_length = batch['input_length'] - target_signal = batch['target_signal'] - else: - input_signal, input_length, target_signal, _ = batch - - # For consistency, the model uses multi-channel format, even if the channel dimension is 1 - if input_signal.ndim == 2: - input_signal = einops.rearrange(input_signal, 'B T -> B 1 T') - if target_signal.ndim == 2: - target_signal = einops.rearrange(target_signal, 'B T -> B 1 T') - - # Apply channel augmentation - if self.training and self.channel_augmentation is not None: - input_signal = self.channel_augmentation(input=input_signal) - - # Process input - processed_signal, _ = self.forward(input_signal=input_signal, input_length=input_length) - - # Calculate the loss - loss = self.loss(estimate=processed_signal, target=target_signal, input_length=input_length) - - # Logs - self.log('train_loss', loss) - self.log('learning_rate', self._optimizer.param_groups[0]['lr']) - self.log('global_step', torch.tensor(self.trainer.global_step, dtype=torch.float32)) - - # Return loss - return loss - - def evaluation_step(self, batch, batch_idx, dataloader_idx: int = 0, tag: str = 'val'): - - if isinstance(batch, dict): - # lhotse batches are dictionaries - input_signal = batch['input_signal'] - input_length = batch['input_length'] - target_signal = batch['target_signal'] - else: - input_signal, input_length, target_signal, _ = batch - - # For consistency, the model uses multi-channel format, even if the channel dimension is 1 - if input_signal.ndim == 2: - input_signal = einops.rearrange(input_signal, 'B T -> B 1 T') - if target_signal.ndim == 2: - target_signal = einops.rearrange(target_signal, 'B T -> B 1 T') - - # Process input - processed_signal, _ = self.forward(input_signal=input_signal, input_length=input_length) - - # Calculate the loss - loss = self.loss(estimate=processed_signal, target=target_signal, input_length=input_length) - - # Update metrics - if hasattr(self, 'metrics') and tag in self.metrics: - # Update metrics for this (tag, dataloader_idx) - for name, metric in self.metrics[tag][dataloader_idx].items(): - metric.update(preds=processed_signal, target=target_signal, input_length=input_length) - - # Log global step - self.log('global_step', torch.tensor(self.trainer.global_step, dtype=torch.float32)) - - # Return loss - return {f'{tag}_loss': loss} - - @classmethod - def list_available_models(cls) -> Optional[PretrainedModelInfo]: - """ - This method returns a list of pre-trained model which can be instantiated directly from NVIDIA's NGC cloud. - - Returns: - List of available pre-trained models. - """ - results = [] - - return results - - -class PredictiveAudioToAudioModel(AudioToAudioModel): - """This models aims to directly estimate the coefficients - in the encoded domain by applying a neural model. - """ - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - super().__init__(cfg=cfg, trainer=trainer) - self.sample_rate = self._cfg.sample_rate - - # Setup processing modules - self.encoder = self.from_config_dict(self._cfg.encoder) - self.decoder = self.from_config_dict(self._cfg.decoder) - - # Neural estimator - self.estimator = self.from_config_dict(self._cfg.estimator) - - # Normalization - self.normalize_input = self._cfg.get('normalize_input', False) - - # Term added to the denominator to improve numerical stability - self.eps = self._cfg.get('eps', 1e-8) - - # Setup optional Optimization flags - self.setup_optimization_flags() - - logging.debug('Initialized %s', self.__class__.__name__) - logging.debug('\tnormalize_input: %s', self.normalize_input) - logging.debug('\teps: %s', self.eps) - - @property - def input_types(self) -> Dict[str, NeuralType]: - return { - "input_signal": NeuralType(('B', 'C', 'T'), AudioSignal(freq=self.sample_rate)), - "input_length": NeuralType(tuple('B'), LengthsType(), optional=True), - } - - @property - def output_types(self) -> Dict[str, NeuralType]: - return { - "output_signal": NeuralType(('B', 'C', 'T'), AudioSignal(freq=self.sample_rate)), - "output_length": NeuralType(tuple('B'), LengthsType(), optional=True), - } - - @typecheck() - def forward(self, input_signal, input_length=None): - """Forward pass of the model. - - Args: - input_signal: time-domain signal - input_length: valid length of each example in the batch - - Returns: - Output signal `output` in the time domain and the length of the output signal `output_length`. - """ - batch_length = input_signal.size(-1) - - if self.normalize_input: - # max for each example in the batch - norm_scale = torch.amax(input_signal.abs(), dim=(-1, -2), keepdim=True) - # scale input signal - input_signal = input_signal / (norm_scale + self.eps) - - # Encoder - encoded, encoded_length = self.encoder(input=input_signal, input_length=input_length) - - # Backbone - estimated, estimated_length = self.estimator(input=encoded, input_length=encoded_length) - - # Decoder - output, output_length = self.decoder(input=estimated, input_length=estimated_length) - - if self.normalize_input: - # rescale to the original scale - output = output * norm_scale - - # Trim or pad the estimated signal to match input length - output = self.match_batch_length(input=output, batch_length=batch_length) - return output, output_length - - # PTL-specific methods - def training_step(self, batch, batch_idx): - - if isinstance(batch, dict): - # lhotse batches are dictionaries - input_signal = batch['input_signal'] - input_length = batch['input_length'] - target_signal = batch['target_signal'] - else: - input_signal, input_length, target_signal, _ = batch - - # For consistency, the model uses multi-channel format, even if the channel dimension is 1 - if input_signal.ndim == 2: - input_signal = einops.rearrange(input_signal, 'B T -> B 1 T') - if target_signal.ndim == 2: - target_signal = einops.rearrange(target_signal, 'B T -> B 1 T') - - # Estimate the signal - output_signal, _ = self.forward(input_signal=input_signal, input_length=input_length) - - # Calculate the loss - loss = self.loss(estimate=output_signal, target=target_signal, input_length=input_length) - - # Logs - self.log('train_loss', loss) - self.log('learning_rate', self._optimizer.param_groups[0]['lr']) - self.log('global_step', torch.tensor(self.trainer.global_step, dtype=torch.float32)) - - return loss - - def evaluation_step(self, batch, batch_idx, dataloader_idx: int = 0, tag: str = 'val'): - - if isinstance(batch, dict): - # lhotse batches are dictionaries - input_signal = batch['input_signal'] - input_length = batch['input_length'] - target_signal = batch['target_signal'] - else: - input_signal, input_length, target_signal, _ = batch - - # For consistency, the model uses multi-channel format, even if the channel dimension is 1 - if input_signal.ndim == 2: - input_signal = einops.rearrange(input_signal, 'B T -> B 1 T') - if target_signal.ndim == 2: - target_signal = einops.rearrange(target_signal, 'B T -> B 1 T') - - # Estimate the signal - output_signal, _ = self.forward(input_signal=input_signal, input_length=input_length) - - # Prepare output - loss = self.loss(estimate=output_signal, target=target_signal, input_length=input_length) - - # Update metrics - if hasattr(self, 'metrics') and tag in self.metrics: - # Update metrics for this (tag, dataloader_idx) - for name, metric in self.metrics[tag][dataloader_idx].items(): - metric.update(preds=output_signal, target=target_signal, input_length=input_length) - - # Log global step - self.log('global_step', torch.tensor(self.trainer.global_step, dtype=torch.float32)) - - return {f'{tag}_loss': loss} - - -class ScoreBasedGenerativeAudioToAudioModel(AudioToAudioModel): - """This models is using a score-based diffusion process to generate - an encoded representation of the enhanced signal. - - The model consists of the following blocks: - - encoder: transforms input multi-channel audio signal into an encoded representation (analysis transform) - - estimator: neural model, estimates a score for the diffusion process - - sde: stochastic differential equation (SDE) defining the forward and reverse diffusion process - - sampler: sampler for the reverse diffusion process, estimates coefficients of the target signal - - decoder: transforms sampler output into the time domain (synthesis transform) - """ - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - super().__init__(cfg=cfg, trainer=trainer) - self.sample_rate = self._cfg.sample_rate - - # Setup processing modules - self.encoder = self.from_config_dict(self._cfg.encoder) - self.decoder = self.from_config_dict(self._cfg.decoder) - - # Neural score estimator - self.estimator = self.from_config_dict(self._cfg.estimator) - - # SDE - self.sde = self.from_config_dict(self._cfg.sde) - - # Sampler - if 'sde' in self._cfg.sampler: - raise ValueError('SDE should be defined in the model config, not in the sampler config') - if 'score_estimator' in self._cfg.sampler: - raise ValueError('Score estimator should be defined in the model config, not in the sampler config') - - self.sampler = hydra.utils.instantiate(self._cfg.sampler, sde=self.sde, score_estimator=self.estimator) - - # Normalization - self.normalize_input = self._cfg.get('normalize_input', False) - - # Metric evaluation - self.max_utts_evaluation_metrics = self._cfg.get('max_utts_evaluation_metrics') - - if self.max_utts_evaluation_metrics is not None: - logging.warning( - 'Metrics will be evaluated on first %d examples of the evaluation datasets.', - self.max_utts_evaluation_metrics, - ) - - # Term added to the denominator to improve numerical stability - self.eps = self._cfg.get('eps', 1e-8) - - # Setup optional Optimization flags - self.setup_optimization_flags() - - logging.debug('Initialized %s', self.__class__.__name__) - logging.debug('\tnormalize_input: %s', self.normalize_input) - logging.debug('\teps: %s', self.eps) - - @property - def input_types(self) -> Dict[str, NeuralType]: - return { - "input_signal": NeuralType(('B', 'C', 'T'), AudioSignal(freq=self.sample_rate)), - "input_length": NeuralType(tuple('B'), LengthsType(), optional=True), - } - - @property - def output_types(self) -> Dict[str, NeuralType]: - return { - "output_signal": NeuralType(('B', 'C', 'T'), AudioSignal(freq=self.sample_rate)), - "output_length": NeuralType(tuple('B'), LengthsType(), optional=True), - } - - @typecheck() - @torch.inference_mode() - def forward(self, input_signal, input_length=None): - """Forward pass of the model. - - Forward pass of the model aplies the following steps: - - encoder to obtain the encoded representation of the input signal - - sampler to generate the estimated coefficients of the target signal - - decoder to transform the sampler output into the time domain - - Args: - input_signal: Tensor that represents a batch of time-domain audio signals, - of shape [B, C, T]. T here represents timesteps, with 1 second of audio represented as - `self.sample_rate` number of floating point values. - input_signal_length: Vector of length B, contains the individual lengths of the audio sequences. - - Returns: - Output `output_signal` in the time domain and the length of the output signal `output_length`. - """ - batch_length = input_signal.size(-1) - - if self.normalize_input: - # max for each example in the batch - norm_scale = torch.amax(input_signal.abs(), dim=(-1, -2), keepdim=True) - # scale input signal - input_signal = input_signal / (norm_scale + self.eps) - - # Encoder - encoded, encoded_length = self.encoder(input=input_signal, input_length=input_length) - - # Sampler - generated, generated_length = self.sampler( - prior_mean=encoded, score_condition=encoded, state_length=encoded_length - ) - - # Decoder - output, output_length = self.decoder(input=generated, input_length=generated_length) - - if self.normalize_input: - # rescale to the original scale - output = output * norm_scale - - # Trim or pad the estimated signal to match input length - output = self.match_batch_length(input=output, batch_length=batch_length) - return output, output_length - - @typecheck( - input_types={ - "target_signal": NeuralType(('B', 'C', 'T'), AudioSignal()), - "input_signal": NeuralType(('B', 'C', 'T'), AudioSignal()), - "input_length": NeuralType(tuple('B'), LengthsType()), - }, - output_types={ - "loss": NeuralType(None, LossType()), - }, - ) - def _step(self, target_signal, input_signal, input_length=None): - """Randomly generate a time step for each example in the batch, estimate - the score and calculate the loss value. - - Note that this step does not include sampler. - """ - batch_size = target_signal.size(0) - - if self.normalize_input: - # max for each example in the batch - norm_scale = torch.amax(input_signal.abs(), dim=(-1, -2), keepdim=True) - # scale input signal - input_signal = input_signal / (norm_scale + self.eps) - # scale the target signal - target_signal = target_signal / (norm_scale + self.eps) - - # Apply encoder to both target and the input - input_enc, input_enc_len = self.encoder(input=input_signal, input_length=input_length) - target_enc, _ = self.encoder(input=target_signal, input_length=input_length) - - # Generate random time steps - sde_time = self.sde.generate_time(size=batch_size, device=input_enc.device) - - # Get the mean and the variance of the perturbation kernel - pk_mean, pk_std = self.sde.perturb_kernel_params(state=target_enc, prior_mean=input_enc, time=sde_time) - - # Generate a random sample from a standard normal distribution - z_norm = torch.randn_like(input_enc) - - # Prepare perturbed data - perturbed_enc = pk_mean + pk_std * z_norm - - # Score is conditioned on the perturbed data and the input - estimator_input = torch.cat([perturbed_enc, input_enc], dim=-3) - - # Estimate the score using the neural estimator - # SDE time is used to inform the estimator about the current time step - # Note: - # - some implementations use `score = -self._raw_dnn_output(x, t, y)` - # - this seems to be unimportant, and is an artifact of transfering code from the original Song's repo - score_est, score_len = self.estimator(input=estimator_input, input_length=input_enc_len, condition=sde_time) - - # Score loss weighting as in Section 4.2 in http://arxiv.org/abs/1907.05600 - score_est = score_est * pk_std - score_ref = -z_norm - - # Score matching loss on the normalized scores - loss = self.loss(estimate=score_est, target=score_ref, input_length=score_len) - - return loss - - # PTL-specific methods - def training_step(self, batch, batch_idx): - - if isinstance(batch, dict): - # lhotse batches are dictionaries - input_signal = batch['input_signal'] - input_length = batch['input_length'] - target_signal = batch['target_signal'] - else: - input_signal, input_length, target_signal, _ = batch - - # For consistency, the model uses multi-channel format, even if the channel dimension is 1 - if input_signal.ndim == 2: - input_signal = einops.rearrange(input_signal, 'B T -> B 1 T') - if target_signal.ndim == 2: - target_signal = einops.rearrange(target_signal, 'B T -> B 1 T') - - # Calculate the loss - loss = self._step(target_signal=target_signal, input_signal=input_signal, input_length=input_length) - - # Logs - self.log('train_loss', loss) - self.log('learning_rate', self._optimizer.param_groups[0]['lr']) - self.log('global_step', torch.tensor(self.trainer.global_step, dtype=torch.float32)) - - return loss - - def evaluation_step(self, batch, batch_idx, dataloader_idx: int = 0, tag: str = 'val'): - - if isinstance(batch, dict): - # lhotse batches are dictionaries - input_signal = batch['input_signal'] - input_length = batch['input_length'] - target_signal = batch['target_signal'] - else: - input_signal, input_length, target_signal, _ = batch - - # For consistency, the model uses multi-channel format, even if the channel dimension is 1 - if input_signal.ndim == 2: - input_signal = einops.rearrange(input_signal, 'B T -> B 1 T') - if target_signal.ndim == 2: - target_signal = einops.rearrange(target_signal, 'B T -> B 1 T') - - # Calculate loss - loss = self._step(target_signal=target_signal, input_signal=input_signal, input_length=input_length) - - # Update metrics - update_metrics = False - if self.max_utts_evaluation_metrics is None: - # Always update if max is not configured - update_metrics = True - # Number of examples to process - num_examples = input_signal.size(0) # batch size - else: - # Check how many examples have been used for metric calculation - first_metric_name = next(iter(self.metrics[tag][dataloader_idx])) - num_examples_evaluated = self.metrics[tag][dataloader_idx][first_metric_name].num_examples - # Update metrics if some examples were not processed - update_metrics = num_examples_evaluated < self.max_utts_evaluation_metrics - # Number of examples to process - num_examples = min(self.max_utts_evaluation_metrics - num_examples_evaluated, input_signal.size(0)) - - if update_metrics: - # Generate output signal - output_signal, _ = self.forward( - input_signal=input_signal[:num_examples, ...], input_length=input_length[:num_examples] - ) - - # Update metrics - if hasattr(self, 'metrics') and tag in self.metrics: - # Update metrics for this (tag, dataloader_idx) - for name, metric in self.metrics[tag][dataloader_idx].items(): - metric.update( - preds=output_signal, - target=target_signal[:num_examples, ...], - input_length=input_length[:num_examples], - ) - - # Log global step - self.log('global_step', torch.tensor(self.trainer.global_step, dtype=torch.float32)) - - return {f'{tag}_loss': loss} - - -class FlowMatchingAudioToAudioModel(AudioToAudioModel): - """This models uses a flow matching process to generate - an encoded representation of the enhanced signal. - - The model consists of the following blocks: - - encoder: transforms input multi-channel audio signal into an encoded representation (analysis transform) - - estimator: neural model, estimates a score for the diffusion process - - flow: ordinary differential equation (ODE) defining a flow and a vector field. - - sampler: sampler for the inference process, estimates coefficients of the target signal - - decoder: transforms sampler output into the time domain (synthesis transform) - - ssl_pretrain_masking: if it is defined, perform the ssl pretrain masking for self reconstruction in the training process - """ - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - super().__init__(cfg=cfg, trainer=trainer) - self.sample_rate = self._cfg.sample_rate - - # Setup processing modules - self.encoder = self.from_config_dict(self._cfg.encoder) - self.decoder = self.from_config_dict(self._cfg.decoder) - - # Neural estimator - self.estimator = self.from_config_dict(self._cfg.estimator) - - self.estimator_target = self._cfg.get('estimator_target', 'conditional_vector_field') - - # Flow - self.flow = self.from_config_dict(self._cfg.flow) - - # Sampler - self.sampler = hydra.utils.instantiate(self._cfg.sampler, estimator=self.estimator, flow=self.flow) - - # probability that the conditional input will be feed into the - # estimator in the training stage - self.p_cond = self._cfg.get('p_cond', 1.0) - - # Self-Supervised Pretraining - if self._cfg.get('ssl_pretrain_masking') is not None: - logging.debug('SSL-pretrain_masking is found and will be initialized') - self.ssl_pretrain_masking = self.from_config_dict(self._cfg.ssl_pretrain_masking) - else: - self.ssl_pretrain_masking = None - - # Normalization - self.normalize_input = self._cfg.get('normalize_input', False) - - # Metric evaluation - self.max_utts_evaluation_metrics = self._cfg.get('max_utts_evaluation_metrics') - - if self.max_utts_evaluation_metrics is not None: - logging.warning( - 'Metrics will be evaluated on first %d examples of the evaluation datasets.', - self.max_utts_evaluation_metrics, - ) - - # Regularization - self.eps = self._cfg.get('eps', 1e-8) - - # Setup optional Optimization flags - self.setup_optimization_flags() - - logging.debug('Initialized %s', self.__class__.__name__) - logging.debug('\tdoing SSL-pretraining: %s', (self.ssl_pretrain_masking is not None)) - logging.debug('\tp_cond: %s', self.p_cond) - logging.debug('\tnormalize_input: %s', self.normalize_input) - logging.debug('\tloss: %s', self.loss) - logging.debug('\teps: %s', self.eps) - - @property - def input_types(self) -> Dict[str, NeuralType]: - return { - "input_signal": NeuralType(('B', 'C', 'T'), AudioSignal(freq=self.sample_rate)), - "input_length": NeuralType(tuple('B'), LengthsType(), optional=True), - } - - @property - def output_types(self) -> Dict[str, NeuralType]: - return { - "output_signal": NeuralType(('B', 'C', 'T'), AudioSignal(freq=self.sample_rate)), - "output_length": NeuralType(tuple('B'), LengthsType(), optional=True), - } - - @typecheck() - @torch.inference_mode() - def forward(self, input_signal, input_length=None): - """Forward pass of the model to generate samples from the target distribution. - This is used for inference mode only, and it explicitly disables SSL masking to the input. - - Args: - input_signal: Tensor that represents a batch of raw audio signals, - of shape [B, T] or [B, T, C]. T here represents timesteps, with 1 second of audio represented as - `self.sample_rate` number of floating point values. - input_signal_length: Vector of length B, that contains the individual lengths of the audio - sequences. - - Returns: - Output signal `output` in the time domain and the length of the output signal `output_length`. - """ - return self.forward_internal(input_signal=input_signal, input_length=input_length, enable_ssl_masking=False) - - @typecheck( - input_types={ - "input_signal": NeuralType(('B', 'C', 'T'), AudioSignal()), - "input_length": NeuralType(tuple('B'), LengthsType(), optional=True), - }, - output_types={ - "output_signal": NeuralType(('B', 'C', 'T'), AudioSignal()), - "output_length": NeuralType(tuple('B'), LengthsType(), optional=True), - }, - ) - @torch.inference_mode() - def forward_eval(self, input_signal, input_length=None): - """Forward pass of the model to generate samples from the target distribution. - This is used for eval mode only, and it enables SSL masking to the input. - - Args: - input_signal: Tensor that represents a batch of raw audio signals, - of shape [B, T] or [B, T, C]. T here represents timesteps, with 1 second of audio represented as - `self.sample_rate` number of floating point values. - input_signal_length: Vector of length B, that contains the individual lengths of the audio - sequences. - - Returns: - Output signal `output` in the time domain and the length of the output signal `output_length`. - """ - return self.forward_internal(input_signal=input_signal, input_length=input_length, enable_ssl_masking=True) - - @torch.inference_mode() - def forward_internal(self, input_signal, input_length=None, enable_ssl_masking=False): - """Internal forward pass of the model. - - Args: - input_signal: Tensor that represents a batch of raw audio signals, - of shape [B, T] or [B, T, C]. T here represents timesteps, with 1 second of audio represented as - `self.sample_rate` number of floating point values. - input_signal_length: Vector of length B, that contains the individual lengths of the audio - sequences. - enable_ssl_masking: Whether to enable SSL masking of the input. If using SSL pretraining, masking - is applied to the input signal. If not using SSL pretraining, masking is not applied. - - Returns: - Output signal `output` in the time domain and the length of the output signal `output_length`. - """ - batch_length = input_signal.size(-1) - - if self.normalize_input: - # max for each example in the batch - norm_scale = torch.amax(input_signal.abs(), dim=(-1, -2), keepdim=True) - # scale input signal - input_signal = input_signal / (norm_scale + self.eps) - - # Encoder - encoded, encoded_length = self.encoder(input=input_signal, input_length=input_length) - - # Conditional input - if self.p_cond == 0: - # The model is trained without the conditional input - encoded = torch.zeros_like(encoded) - elif enable_ssl_masking and self.ssl_pretrain_masking is not None: - # Masking for self-supervised pretraining - encoded = self.ssl_pretrain_masking(input_spec=encoded, length=encoded_length) - - # Initial process state - init_state = torch.randn_like(encoded) * self.flow.sigma_start - - # Sampler - generated, generated_length = self.sampler( - state=init_state, estimator_condition=encoded, state_length=encoded_length - ) - - # Decoder - output, output_length = self.decoder(input=generated, input_length=generated_length) - - if self.normalize_input: - # rescale to the original scale - output = output * norm_scale - - # Trim or pad the estimated signal to match input length - output = self.match_batch_length(input=output, batch_length=batch_length) - - return output, output_length - - @typecheck( - input_types={ - "target_signal": NeuralType(('B', 'C', 'T'), AudioSignal()), - "input_signal": NeuralType(('B', 'C', 'T'), AudioSignal()), - "input_length": NeuralType(tuple('B'), LengthsType()), - }, - output_types={ - "loss": NeuralType(None, LossType()), - }, - ) - def _step(self, target_signal, input_signal, input_length=None): - batch_size = target_signal.size(0) - - if self.normalize_input: - # max for each example in the batch - norm_scale = torch.amax(input_signal.abs(), dim=(-1, -2), keepdim=True) - # scale input signal - input_signal = input_signal / (norm_scale + self.eps) - # scale the target signal - target_signal = target_signal / (norm_scale + self.eps) - - # Apply encoder to both target and the input - input_enc, input_enc_len = self.encoder(input=input_signal, input_length=input_length) - target_enc, _ = self.encoder(input=target_signal, input_length=input_length) - - # Self-Supervised Pretraining - if self.ssl_pretrain_masking is not None: - input_enc = self.ssl_pretrain_masking(input_spec=input_enc, length=input_enc_len) - - # Drop off conditional inputs (input_enc) with (1 - p_cond) probability. - # The dropped conditions will be set to zeros - keep_conditions = einops.rearrange((torch.rand(batch_size) < self.p_cond).float(), 'B -> B 1 1 1') - input_enc = input_enc * keep_conditions.to(input_enc.device) - - x_start = torch.zeros_like(input_enc) - - time = self.flow.generate_time(batch_size=batch_size).to(device=input_enc.device) - sample = self.flow.sample(time=time, x_start=x_start, x_end=target_enc) - - # we want to get a vector field estimate given current state - # at training time, current state is sampled from the conditional path - # the vector field model is also conditioned on input signal - estimator_input = torch.cat([sample, input_enc], dim=-3) - - # Estimate the vector using the neural estimator - estimate, estimate_len = self.estimator(input=estimator_input, input_length=input_enc_len, condition=time) - - if self.estimator_target == 'conditional_vector_field': - loss_target = self.flow.vector_field(time=time, x_start=x_start, x_end=target_enc, point=sample) - elif self.estimator_target == 'data': - loss_target = target_enc - else: - raise ValueError(f'Invalid estimator target: {self.estimator_target}') - - return self.loss(estimate=estimate, target=loss_target, input_length=input_enc_len) - - # PTL-specific methods - def training_step(self, batch, batch_idx): - if isinstance(batch, dict): - # lhotse batches are dictionaries - input_signal = batch['input_signal'] - input_length = batch['input_length'] - target_signal = batch.get('target_signal', input_signal.clone()) - else: - input_signal, input_length, target_signal, _ = batch - - # For consistency, the model uses multi-channel format, even if the channel dimension is 1 - if input_signal.ndim == 2: - input_signal = einops.rearrange(input_signal, "B T -> B 1 T") - if target_signal.ndim == 2: - target_signal = einops.rearrange(target_signal, "B T -> B 1 T") - - # Calculate the loss - loss = self._step(target_signal=target_signal, input_signal=input_signal, input_length=input_length) - - # Logs - self.log('train_loss', loss) - self.log('learning_rate', self._optimizer.param_groups[0]['lr']) - self.log('global_step', torch.tensor(self.trainer.global_step, dtype=torch.float32)) - - return loss - - def evaluation_step(self, batch, batch_idx, dataloader_idx: int = 0, tag: str = 'val'): - - if isinstance(batch, dict): - # lhotse batches are dictionaries - input_signal = batch['input_signal'] - input_length = batch['input_length'] - target_signal = batch.get('target_signal', input_signal.clone()) - else: - input_signal, input_length, target_signal, _ = batch - - # For consistency, the model uses multi-channel format, even if the channel dimension is 1 - if input_signal.ndim == 2: - input_signal = einops.rearrange(input_signal, 'B T -> B 1 T') - if target_signal.ndim == 2: - target_signal = einops.rearrange(target_signal, 'B T -> B 1 T') - - # Calculate loss - loss = self._step( - target_signal=target_signal, - input_signal=input_signal, - input_length=input_length, - ) - - # Update metrics - update_metrics = False - if self.max_utts_evaluation_metrics is None: - # Always update if max is not configured - update_metrics = True - # Number of examples to process - num_examples = input_signal.size(0) # batch size - else: - # Check how many examples have been used for metric calculation - first_metric_name = next(iter(self.metrics[tag][dataloader_idx])) - num_examples_evaluated = self.metrics[tag][dataloader_idx][first_metric_name].num_examples - # Update metrics if some examples were not processed - update_metrics = num_examples_evaluated < self.max_utts_evaluation_metrics - # Number of examples to process - num_examples = min(self.max_utts_evaluation_metrics - num_examples_evaluated, input_signal.size(0)) - - if update_metrics: - # Generate output signal - output_signal, _ = self.forward_eval( - input_signal=input_signal[:num_examples, ...], input_length=input_length[:num_examples] - ) - - # Update metrics - if hasattr(self, 'metrics') and tag in self.metrics: - # Update metrics for this (tag, dataloader_idx) - for name, metric in self.metrics[tag][dataloader_idx].items(): - metric.update( - preds=output_signal, - target=target_signal[:num_examples, ...], - input_length=input_length[:num_examples], - ) - - # Log global step - self.log('global_step', torch.tensor(self.trainer.global_step, dtype=torch.float32)) - - return {f'{tag}_loss': loss} - - -class SchroedingerBridgeAudioToAudioModel(AudioToAudioModel): - """This models is using a Schrödinger Bridge process to generate - an encoded representation of the enhanced signal. - - The model consists of the following blocks: - - encoder: transforms input audio signal into an encoded representation (analysis transform) - - estimator: neural model, estimates the coefficients for the SB process - - noise_schedule: defines the path between the clean and noisy signals - - sampler: sampler for the reverse process, estimates coefficients of the target signal - - decoder: transforms sampler output into the time domain (synthesis transform) - - References: - Schrödinger Bridge for Generative Speech Enhancement, https://arxiv.org/abs/2407.16074 - """ - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - super().__init__(cfg=cfg, trainer=trainer) - self.sample_rate = self._cfg.sample_rate - - # Setup processing modules - self.encoder = self.from_config_dict(self._cfg.encoder) - self.decoder = self.from_config_dict(self._cfg.decoder) - - # Neural estimator - self.estimator = self.from_config_dict(self._cfg.estimator) - self.estimator_output = self._cfg.estimator_output - - # Noise schedule - self.noise_schedule = self.from_config_dict(self._cfg.noise_schedule) - - # Sampler - self.sampler = hydra.utils.instantiate( - self._cfg.sampler, - noise_schedule=self.noise_schedule, - estimator=self.estimator, - estimator_output=self.estimator_output, - ) - - # Normalization - self.normalize_input = self._cfg.get('normalize_input', False) - - # Metric evaluation - self.max_utts_evaluation_metrics = self._cfg.get('max_utts_evaluation_metrics') - - if self.max_utts_evaluation_metrics is not None: - logging.warning( - 'Metrics will be evaluated on first %d examples of the evaluation datasets.', - self.max_utts_evaluation_metrics, - ) - - # Loss in the encoded domain - if 'loss_encoded' in self._cfg: - self.loss_encoded = self.from_config_dict(self._cfg.loss_encoded) - self.loss_encoded_weight = self._cfg.get('loss_encoded_weight', 1.0) - else: - self.loss_encoded = None - self.loss_encoded_weight = 0.0 - - # Loss in the time domain - if 'loss_time' in self._cfg: - self.loss_time = self.from_config_dict(self._cfg.loss_time) - self.loss_time_weight = self._cfg.get('loss_time_weight', 1.0) - else: - self.loss_time = None - self.loss_time_weight = 0.0 - - if self.loss is not None and (self.loss_encoded is not None or self.loss_time is not None): - raise ValueError('Either ``loss`` or ``loss_encoded`` and ``loss_time`` should be defined, not both.') - - # Term added to the denominator to improve numerical stability - self.eps = self._cfg.get('eps', 1e-8) - - # Setup optional optimization flags - self.setup_optimization_flags() - - logging.debug('Initialized %s', self.__class__.__name__) - logging.debug('\testimator_output: %s', self.estimator_output) - logging.debug('\tnormalize_input: %s', self.normalize_input) - logging.debug('\tloss: %s', self.loss) - logging.debug('\tloss_encoded: %s', self.loss_encoded) - logging.debug('\tloss_encoded_weight: %s', self.loss_encoded_weight) - logging.debug('\tloss_time: %s', self.loss_time) - logging.debug('\tloss_time_weight: %s', self.loss_time_weight) - logging.debug('\teps: %s', self.eps) - - @property - def input_types(self) -> Dict[str, NeuralType]: - # time-domain input - return { - "input_signal": NeuralType(('B', 'C', 'T'), AudioSignal(freq=self.sample_rate)), - "input_length": NeuralType(tuple('B'), LengthsType(), optional=True), - } - - @property - def output_types(self) -> Dict[str, NeuralType]: - # time-domain output - return { - "output_signal": NeuralType(('B', 'C', 'T'), AudioSignal(freq=self.sample_rate)), - "output_length": NeuralType(tuple('B'), LengthsType(), optional=True), - } - - @typecheck() - @torch.inference_mode() - def forward(self, input_signal, input_length=None): - """Forward pass of the model. - - Forward pass of the model consists of the following steps - - encoder to obtain the encoded representation of the input signal - - sampler to generate the estimated coefficients of the target signal - - decoder to transform the estimated output into the time domain - - Args: - input_signal: Tensor that represents a batch of time-domain audio signals, - of shape [B, C, T]. T here represents timesteps, with 1 second of audio represented as - `self.sample_rate` number of floating point values. - input_signal_length: Vector of length B, contains the individual lengths of the audio sequences. - - Returns: - Output `output_signal` in the time domain and the length of the output signal `output_length`. - """ - batch_length = input_signal.size(-1) - - if self.normalize_input: - # max for each example in the batch - norm_scale = torch.amax(input_signal.abs(), dim=(-1, -2), keepdim=True) - # scale input signal - input_signal = input_signal / (norm_scale + self.eps) - - # Encoder - encoded, encoded_length = self.encoder(input=input_signal, input_length=input_length) - - # Sampler - generated, generated_length = self.sampler( - prior_mean=encoded, estimator_condition=encoded, state_length=encoded_length - ) - - # Decoder - output, output_length = self.decoder(input=generated, input_length=generated_length) - - if self.normalize_input: - # rescale to the original scale - output = output * norm_scale - - # Trim or pad the estimated signal to match input length - output = self.match_batch_length(input=output, batch_length=batch_length) - - return output, output_length - - @typecheck( - input_types={ - "target_signal": NeuralType(('B', 'C', 'T'), AudioSignal()), - "input_signal": NeuralType(('B', 'C', 'T'), AudioSignal()), - "input_length": NeuralType(tuple('B'), LengthsType()), - }, - output_types={ - "loss": NeuralType(None, LossType()), - "loss_encoded": NeuralType(None, LossType()), - "loss_time": NeuralType(None, LossType()), - }, - ) - def _step(self, target_signal, input_signal, input_length=None): - """Randomly generate time step for each example in the batch, run neural estimator - to estimate the target and calculate the loss. - """ - batch_size = target_signal.size(0) - - if self.normalize_input: - # max for each example in the batch - norm_scale = torch.amax(input_signal.abs(), dim=(-1, -2), keepdim=True) - # scale input signal - input_signal = input_signal / (norm_scale + self.eps) - # scale the target signal - target_signal = target_signal / (norm_scale + self.eps) - - # Apply encoder to both target and the input - # For example, if the encoder is STFT, then _enc is the complex-valued STFT of the corresponding signal - input_enc, input_enc_len = self.encoder(input=input_signal, input_length=input_length) - target_enc, _ = self.encoder(input=target_signal, input_length=input_length) - - # Generate random time steps - process_time = self.noise_schedule.generate_time(size=batch_size, device=input_enc.device) - - # Prepare necessary info from the noise schedule - alpha_t, alpha_bar_t, alpha_t_max = self.noise_schedule.get_alphas(time=process_time) - sigma_t, sigma_bar_t, sigma_t_max = self.noise_schedule.get_sigmas(time=process_time) - - # Marginal distribution - weight_target = alpha_t * sigma_bar_t**2 / (sigma_t_max**2 + self.eps) - weight_input = alpha_bar_t * sigma_t**2 / (sigma_t_max**2 + self.eps) - # view weights as [B, C, D, T] - weight_target = weight_target.view(-1, 1, 1, 1) - weight_input = weight_input.view(-1, 1, 1, 1) - # mean - mean_x = weight_target * target_enc + weight_input * input_enc - # standard deviation - std_x = alpha_t * sigma_bar_t * sigma_t / (sigma_t_max + self.eps) - # view as [B, C, D, T] - std_x = std_x.view(-1, 1, 1, 1) - - # Generate a random sample from a standard normal distribution - z_norm = torch.randn_like(input_enc) - - # Generate a random sample from the marginal distribution - x_t = mean_x + std_x * z_norm - - # Estimator is conditioned on the generated sample and the original input (prior) - estimator_input = torch.cat([x_t, input_enc], dim=-3) - - # Neural estimator - # Estimator input is the same data type as the encoder output - # For example, if the encoder is STFT, then the estimator input and output are complex-valued coefficients - estimate, estimate_len = self.estimator( - input=estimator_input, input_length=input_enc_len, condition=process_time - ) - - # Prepare output target and calculate loss - if self.estimator_output == 'data_prediction': - if self.loss is not None: - # Single loss in the encoded domain - loss = self.loss(estimate=estimate, target=target_enc, input_length=estimate_len) - loss_encoded = loss_time = None - else: - # Weighted loss between encoded and time domain - loss = 0.0 - - # Loss in the encoded domain - if self.loss_encoded is not None: - # Loss between the estimate and the target in the encoded domain - loss_encoded = self.loss_encoded(estimate=estimate, target=target_enc, input_length=estimate_len) - # Weighting - loss += self.loss_encoded_weight * loss_encoded - else: - loss_encoded = None - - # Loss in the time domain - if self.loss_time is not None: - # Convert the estimate to the time domain - with typecheck.disable_checks(): - # Note: stimate is FloatType, decoder requires SpectrogramType - estimate_signal, _ = self.decoder(input=estimate, input_length=estimate_len) - - # Match estimate length - batch_length = input_signal.size(-1) - estimate_signal = self.match_batch_length(input=estimate_signal, batch_length=batch_length) - - # Loss between the estimate and the target in the time domain - loss_time = self.loss_time( - estimate=estimate_signal, target=target_signal, input_length=input_length - ) - # Weighting - loss += self.loss_time_weight * loss_time - else: - loss_time = None - else: - raise NotImplementedError(f'Output type {self.estimator_output} is not implemented') - - return loss, loss_encoded, loss_time - - # PTL-specific methods - def training_step(self, batch, batch_idx): - - if isinstance(batch, dict): - # lhotse batches are dictionaries - input_signal = batch['input_signal'] - input_length = batch['input_length'] - target_signal = batch['target_signal'] - else: - input_signal, input_length, target_signal, _ = batch - - # For consistency, the model uses multi-channel format, even if the channel dimension is 1 - if input_signal.ndim == 2: - input_signal = einops.rearrange(input_signal, 'B T -> B 1 T') - if target_signal.ndim == 2: - target_signal = einops.rearrange(target_signal, 'B T -> B 1 T') - - # Calculate the loss - loss, loss_encoded, loss_time = self._step( - target_signal=target_signal, input_signal=input_signal, input_length=input_length - ) - - # Logs - self.log('train_loss', loss) - self.log('learning_rate', self._optimizer.param_groups[0]['lr']) - self.log('global_step', torch.tensor(self.trainer.global_step, dtype=torch.float32)) - - if loss_encoded is not None: - self.log('train_loss_encoded', loss_encoded) - - if loss_time is not None: - self.log('train_loss_time', loss_time) - - return loss - - def evaluation_step(self, batch, batch_idx, dataloader_idx: int = 0, tag: str = 'val'): - - if isinstance(batch, dict): - # lhotse batches are dictionaries - input_signal = batch['input_signal'] - input_length = batch['input_length'] - target_signal = batch['target_signal'] - else: - input_signal, input_length, target_signal, _ = batch - - # For consistency, the model uses multi-channel format, even if the channel dimension is 1 - if input_signal.ndim == 2: - input_signal = einops.rearrange(input_signal, 'B T -> B 1 T') - if target_signal.ndim == 2: - target_signal = einops.rearrange(target_signal, 'B T -> B 1 T') - - # Calculate loss - loss, *_ = self._step(target_signal=target_signal, input_signal=input_signal, input_length=input_length) - - # Update metrics - update_metrics = False - if self.max_utts_evaluation_metrics is None: - # Always update if max is not configured - update_metrics = True - # Number of examples to process - num_examples = input_signal.size(0) # batch size - else: - # Check how many examples have been used for metric calculation - first_metric_name = next(iter(self.metrics[tag][dataloader_idx])) - num_examples_evaluated = self.metrics[tag][dataloader_idx][first_metric_name].num_examples - # Update metrics if some examples were not processed - update_metrics = num_examples_evaluated < self.max_utts_evaluation_metrics - # Number of examples to process - num_examples = min(self.max_utts_evaluation_metrics - num_examples_evaluated, input_signal.size(0)) - - if update_metrics: - # Generate output signal - output_signal, _ = self.forward( - input_signal=input_signal[:num_examples, ...], input_length=input_length[:num_examples] - ) - - # Update metrics - if hasattr(self, 'metrics') and tag in self.metrics: - # Update metrics for this (tag, dataloader_idx) - for name, metric in self.metrics[tag][dataloader_idx].items(): - metric.update( - preds=output_signal, - target=target_signal[:num_examples, ...], - input_length=input_length[:num_examples], - ) - - # Log global step - self.log('global_step', torch.tensor(self.trainer.global_step, dtype=torch.float32)) - - return {f'{tag}_loss': loss} diff --git a/nemo/collections/audio/models/maxine/__init__.py b/nemo/collections/audio/models/maxine/__init__.py deleted file mode 100644 index 125cc06253f029c98214fbe0dd6ed5ae73e62149..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/models/maxine/__init__.py +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.audio.models.maxine.bnr import BNR2 - -__all__ = [ - 'BNR2', -] diff --git a/nemo/collections/audio/models/maxine/bnr.py b/nemo/collections/audio/models/maxine/bnr.py deleted file mode 100644 index 6cff8ead9c87d0189b290eec19b1778f98beafba..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/models/maxine/bnr.py +++ /dev/null @@ -1,294 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -""" -Implementation of Maxine BNR2 denoising network - -Maxine Background Noise Removal (BNR) 2.0 is an audio background noise removal -model from NVIDIA. This is the second generation of BNR from -Maxine Audio Effects SDK. BNR 2.0 removes unwanted noises from audio improving -speech intelligibility and also improving the speech recognition accuracy of -various ASR systems under noisy environments. - -BNR 2.0 uses the SEASR architecture described in https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=10837982 -""" - -from typing import Dict, Optional - -import einops -import lightning.pytorch as plt -import torch -import torch.nn as nn -import torch.nn.functional as F -from lightning.pytorch import Trainer -from omegaconf import DictConfig - -from nemo.collections.audio.models.audio_to_audio import AudioToAudioModel -from nemo.collections.audio.parts.utils.maxine import apply_weight_norm_lstm, remove_weight_norm_lstm -from nemo.core.classes.common import PretrainedModelInfo, typecheck -from nemo.core.neural_types import AudioSignal, NeuralType - -SUPPORTED_SAMPLE_RATE = 16000 -SUPPORTED_INPUT_ALIGN_MS = 10 -SUPPORTED_INPUT_ALIGN_SAMPLES = SUPPORTED_INPUT_ALIGN_MS * (SUPPORTED_SAMPLE_RATE // 1000) - - -class _Seasr(plt.LightningModule): - """Internal implementation of the model class""" - - def __init__( - self, sample_rate, hidden_nodes=128, streaming=False, kernel_size=320, f1=1024, f2=512, stride=160, dropout=0.5 - ): - - if sample_rate != SUPPORTED_SAMPLE_RATE: - raise AssertionError("Currently only 16k is supported") - - super().__init__() - self.f1 = f1 - self.f2 = f2 - self.f3 = hidden_nodes * 2 - self.gru_nodes = self.f1 - padding = 0 if streaming else 'same' - - self.conv1d = nn.Conv1d(1, self.f1, kernel_size=kernel_size, stride=stride, bias=False) - self.bn0 = nn.BatchNorm1d(self.f1, eps=0.001) - self.feature_gru0 = nn.GRU(self.f1, self.f3, num_layers=1, batch_first=True) - - self.conv1d_out1 = nn.Conv1d(self.f1, self.f2, kernel_size=3, padding=padding) - self.bn1 = nn.BatchNorm1d(self.f2, eps=0.001) - self.feature_gru1 = nn.GRU(self.f2, self.f3, num_layers=1, batch_first=True) - - self.conv1d_out2 = nn.Conv1d(self.f2, self.f2, kernel_size=3, padding=padding) - self.bn2 = nn.BatchNorm1d(self.f2, eps=0.001) - self.feature_gru2 = nn.GRU(self.f2, self.f3, num_layers=1, batch_first=True) - - self.conv1d_out3 = nn.Conv1d(self.f2, self.f2, kernel_size=3, padding=padding) - self.bn3 = nn.BatchNorm1d(self.f2, eps=0.001) - - self.denoise_gru = nn.GRU(3 * self.f3 + self.f2, self.gru_nodes, batch_first=True, dropout=dropout) - self.denoise_gru_1 = nn.GRU(self.gru_nodes, self.gru_nodes, num_layers=1, batch_first=True, dropout=dropout) - self.denoise_gru_2 = nn.GRU(self.gru_nodes, self.gru_nodes, num_layers=1, batch_first=True, dropout=dropout) - self.denoise_gru_3 = nn.GRU(self.gru_nodes, self.gru_nodes, batch_first=True) - - self.denoise_mask = nn.Linear(self.gru_nodes, self.f1) - self.mask_act = nn.Sigmoid() - - self.inv_conv = nn.ConvTranspose1d(self.f1, 1, kernel_size=kernel_size, stride=stride) - self.inv_conv_activation = nn.Tanh() - - def forward(self, **kwargs): - x0 = kwargs.get('x0') - x0 = F.relu(self.conv1d(x0)) - xc0 = self.bn0(x0) - - xc1 = F.leaky_relu(self.conv1d_out1(xc0)) - xc1 = self.bn1(xc1) - fg1, _ = self.feature_gru1(xc1.permute(0, 2, 1)) - - xc2 = F.leaky_relu(self.conv1d_out2(xc1)) - xc2 = self.bn2(xc2) - fg2, _ = self.feature_gru2(xc2.permute(0, 2, 1)) - - xc3 = F.leaky_relu(self.conv1d_out3(xc2)) - xc3 = self.bn3(xc3) - - xc3 = xc3.permute(0, 2, 1) - - xc0 = xc0.permute(0, 2, 1) - fg0, _ = self.feature_gru0(xc0) - - xi = torch.cat((fg0, fg1, fg2, xc3), 2) - xi, _ = self.denoise_gru(xi) - xi = xi + xc0 - xi1, _ = self.denoise_gru_1(xi) - xi1 = xi1 + xi - xi2, _ = self.denoise_gru_2(xi1) - xi = xi1 + xi2 - - xi, _ = self.denoise_gru_3(xi) - - mask = self.mask_act(self.denoise_mask(xi)) - mask = mask.permute(0, 2, 1) - xi = x0 * mask - - xi = self.inv_conv(xi) - xi = self.inv_conv_activation(xi) - - return xi - - def apply_weight_norm(self): - """Apply weight normalization module from all layers.""" - - def _apply_weight_norm(m): - if isinstance(m, (torch.nn.Conv1d, torch.nn.Linear)): - torch.nn.utils.weight_norm(m) - elif isinstance(m, (torch.nn.LSTM, torch.nn.GRU)): - apply_weight_norm_lstm(m) - - self.apply(_apply_weight_norm) - - def remove_weight_norm(self): - """Remove weight normalization module from all layers.""" - - def _remove_weight_norm(m): - try: - if isinstance(m, (torch.nn.Conv1d, torch.nn.Linear)): - torch.nn.utils.remove_weight_norm(m) - elif isinstance(m, (torch.nn.LSTM, torch.nn.GRU)): - remove_weight_norm_lstm(m) - except ValueError: # this module didn't have weight norm - return - - self.apply(_remove_weight_norm) - - -class BNR2(AudioToAudioModel): - """Implementation of the BNR 2 model""" - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - self.world_size = 1 - if trainer is not None: - self.world_size = trainer.world_size - - super().__init__(cfg=cfg, trainer=trainer) - self.sample_rate = self._cfg.sample_rate - - # Setup optional Optimization flags - self.setup_optimization_flags() - - self.seasr = _Seasr(self.sample_rate) - if ( - hasattr(self._cfg, "train") - and hasattr(self._cfg.train, "enable_weight_norm") - and self._cfg.train.enable_weight_norm - ): - self.seasr.apply_weight_norm() - - @property - def input_types(self) -> Dict[str, NeuralType]: - return { - "input_signal": NeuralType( - ('B', 'C', 'T'), AudioSignal(freq=self.sample_rate) - ) # multi-channel format, only channel dimension of 1 supported currently - } - - @property - def output_types(self) -> Dict[str, NeuralType]: - return { - "output_signal": NeuralType( - ('B', 'C', 'T'), AudioSignal(freq=self.sample_rate) - ) # multi-channel format, channel dimension can be 1 for single-channel audio - } - - @typecheck() - def forward(self, input_signal): - """ - Forward pass of the model. - - Args: - input_signal: Tensor that represents a batch of raw audio signals, - of shape [B, T] or [B, T, C]. T here represents timesteps, with 1 second of audio represented as - `self.sample_rate` number of floating point values. - - Returns: - Output signal `output` in the time domain and the length of the output signal `output_length`. - """ - if input_signal.ndim == 3: - if input_signal.shape[1] != 1: - raise ValueError("This network currently only supports single channel audio signals.") - elif input_signal.ndim != 2: - raise ValueError( - "Invalid shape for input signal (received {}, supported [B, 1, T] or [B, T])".format( - input_signal.shape - ) - ) - - # Pad input to nearest multiple of SUPPORTED_INPUT_ALIGN_SAMPLES - original_length = input_signal.shape[-1] - remainder = original_length % SUPPORTED_INPUT_ALIGN_SAMPLES - if remainder != 0: - pad_length = SUPPORTED_INPUT_ALIGN_SAMPLES - remainder - input_signal = F.pad(input_signal, (0, pad_length)) - output = self.seasr.forward(x0=input_signal) - - # Trim output back to original length - if remainder != 0: - output = output[..., :original_length] - - return output - - def training_step(self, batch, batch_idx): - if isinstance(batch, dict): - input_signal = batch['input_signal'] - input_length = batch['input_length'] - target_signal = batch['target_signal'] - else: - input_signal, input_length, target_signal, _ = batch - - if input_signal.ndim == 2: - input_signal = einops.rearrange(input_signal, 'B T -> B 1 T') - if target_signal.ndim == 2: - target_signal = einops.rearrange(target_signal, 'B T -> B 1 T') - - predicted_audio = self.forward(input_signal=input_signal) - - loss = self.loss(target=target_signal, estimate=predicted_audio, input_length=input_length) - - self.log('train_loss', loss) - self.log('learning_rate', self._optimizer.param_groups[0]['lr']) - self.log('global_step', torch.tensor(self.trainer.global_step, dtype=torch.float32)) - - return loss - - def evaluation_step(self, batch, batch_idx, dataloader_idx: int = 0, tag: str = 'val'): - if isinstance(batch, dict): - input_signal = batch['input_signal'] - input_length = batch['input_length'] - target_signal = batch['target_signal'] - else: - input_signal, input_length, target_signal, _ = batch - - if input_signal.ndim == 2: - input_signal = einops.rearrange(input_signal, 'B T -> B 1 T') - if target_signal.ndim == 2: - target_signal = einops.rearrange(target_signal, 'B T -> B 1 T') - - # Process input - processed_signal = self(input_signal=input_signal) - - # Calculate the loss - loss = self.loss(target=target_signal, estimate=processed_signal, input_length=input_length) - - # Update metrics - if hasattr(self, 'metrics') and tag in self.metrics: - # Update metrics for this (tag, dataloader_idx) - for name, metric in self.metrics[tag][dataloader_idx].items(): - metric.update(preds=processed_signal, target=target_signal, input_length=input_length) - - # Log global step - self.log('global_step', torch.tensor(self.trainer.global_step, dtype=torch.float32)) - - # Return loss - return {f'{tag}_loss': loss} - - @classmethod - def list_available_models(cls) -> Optional[PretrainedModelInfo]: - """ - This method returns a list of pre-trained model which can be instantiated directly from NVIDIA's NGC cloud. - - Returns: - List of available pre-trained models. - """ - - return None diff --git a/nemo/collections/audio/modules/__init__.py b/nemo/collections/audio/modules/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/modules/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/audio/modules/features.py b/nemo/collections/audio/modules/features.py deleted file mode 100644 index b20670850de5edca9c5a72434c337a01c7c9bcb2..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/modules/features.py +++ /dev/null @@ -1,286 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import Dict, Optional - -import torch - -from nemo.collections.audio.losses.audio import calculate_mean -from nemo.collections.audio.parts.utils.audio import wrap_to_pi -from nemo.core.classes import NeuralModule, typecheck -from nemo.core.neural_types import LengthsType, NeuralType, SpectrogramType -from nemo.utils import logging - - -class SpectrogramToMultichannelFeatures(NeuralModule): - """Convert a complex-valued multi-channel spectrogram to - multichannel features. - - Args: - num_subbands: Expected number of subbands in the input signal - num_input_channels: Optional, provides the number of channels - of the input signal. Used to infer the number - of output channels. - mag_reduction: Reduction across channels. Default `None`, will calculate - magnitude of each channel. - mag_power: Optional, apply power on the magnitude. - use_ipd: Use inter-channel phase difference (IPD). - mag_normalization: Normalization for magnitude features - ipd_normalization: Normalization for IPD features - eps: Small regularization constant. - """ - - def __init__( - self, - num_subbands: int, - num_input_channels: Optional[int] = None, - mag_reduction: Optional[str] = None, - mag_power: Optional[float] = None, - use_ipd: bool = False, - mag_normalization: Optional[str] = None, - ipd_normalization: Optional[str] = None, - eps: float = 1e-8, - ): - super().__init__() - self.mag_reduction = mag_reduction - self.mag_power = mag_power - self.use_ipd = use_ipd - - if mag_normalization not in [None, 'mean', 'mean_var']: - raise NotImplementedError(f'Unknown magnitude normalization {mag_normalization}') - self.mag_normalization = mag_normalization - - if ipd_normalization not in [None, 'mean', 'mean_var']: - raise NotImplementedError(f'Unknown ipd normalization {ipd_normalization}') - self.ipd_normalization = ipd_normalization - - if self.use_ipd: - self._num_features = 2 * num_subbands - self._num_channels = num_input_channels - else: - self._num_features = num_subbands - self._num_channels = num_input_channels if self.mag_reduction is None else 1 - - self.eps = eps - - logging.debug('Initialized %s with', self.__class__.__name__) - logging.debug('\tnum_subbands: %d', num_subbands) - logging.debug('\tmag_reduction: %s', self.mag_reduction) - logging.debug('\tmag_power: %s', self.mag_power) - logging.debug('\tuse_ipd: %s', self.use_ipd) - logging.debug('\tmag_normalization: %s', self.mag_normalization) - logging.debug('\tipd_normalization: %s', self.ipd_normalization) - logging.debug('\teps: %f', self.eps) - logging.debug('\t_num_features: %s', self._num_features) - logging.debug('\t_num_channels: %s', self._num_channels) - - @property - def input_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "input": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "input_length": NeuralType(('B',), LengthsType()), - } - - @property - def output_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "output": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "output_length": NeuralType(('B',), LengthsType()), - } - - @property - def num_features(self) -> int: - """Configured number of features""" - return self._num_features - - @property - def num_channels(self) -> int: - """Configured number of channels""" - if self._num_channels is not None: - return self._num_channels - else: - raise ValueError( - 'Num channels is not configured. To configure this, `num_input_channels` ' - 'must be provided when constructing the object.' - ) - - @staticmethod - def get_mean_time_channel(input: torch.Tensor, input_length: Optional[torch.Tensor] = None) -> torch.Tensor: - """Calculate mean across time and channel dimensions. - - Args: - input: tensor with shape (B, C, F, T) - input_length: tensor with shape (B,) - - Returns: - Mean of `input` calculated across time and channel dimension - with shape (B, 1, F, 1) - """ - assert input.ndim == 4, f'Expected input to have 4 dimensions, got {input.ndim}' - - if input_length is None: - mean = torch.mean(input, dim=(-1, -3), keepdim=True) - else: - # temporal mean - mean = calculate_mean(input, input_length, dim=-1, keepdim=True) - # channel mean - mean = torch.mean(mean, dim=-3, keepdim=True) - - return mean - - @classmethod - def get_mean_std_time_channel( - cls, input: torch.Tensor, input_length: Optional[torch.Tensor] = None, eps: float = 1e-10 - ) -> torch.Tensor: - """Calculate mean and standard deviation across time and channel dimensions. - - Args: - input: tensor with shape (B, C, F, T) - input_length: tensor with shape (B,) - - Returns: - Mean and standard deviation of the `input` calculated across time and - channel dimension, each with shape (B, 1, F, 1). - """ - assert input.ndim == 4, f'Expected input to have 4 dimensions, got {input.ndim}' - - if input_length is None: - std, mean = torch.std_mean(input, dim=(-1, -3), unbiased=False, keepdim=True) - else: - mean = cls.get_mean_time_channel(input, input_length) - std = (input - mean).pow(2) - # temporal mean - std = calculate_mean(std, input_length, dim=-1, keepdim=True) - # channel mean - std = torch.mean(std, dim=-3, keepdim=True) - # final value - std = torch.sqrt(std.clamp(eps)) - - return mean, std - - @typecheck( - input_types={ - 'input': NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - 'input_length': NeuralType(tuple('B'), LengthsType()), - }, - output_types={ - 'output': NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - }, - ) - def normalize_mean(self, input: torch.Tensor, input_length: torch.Tensor) -> torch.Tensor: - """Mean normalization for the input tensor. - - Args: - input: input tensor - input_length: valid length for each example - - Returns: - Mean normalized input. - """ - mean = self.get_mean_time_channel(input=input, input_length=input_length) - output = input - mean - return output - - @typecheck( - input_types={ - 'input': NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - 'input_length': NeuralType(tuple('B'), LengthsType()), - }, - output_types={ - 'output': NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - }, - ) - def normalize_mean_var(self, input: torch.Tensor, input_length: torch.Tensor) -> torch.Tensor: - """Mean and variance normalization for the input tensor. - - Args: - input: input tensor - input_length: valid length for each example - - Returns: - Mean and variance normalized input. - """ - mean, std = self.get_mean_std_time_channel(input=input, input_length=input_length, eps=self.eps) - output = (input - mean) / std - return output - - @typecheck() - def forward(self, input: torch.Tensor, input_length: torch.Tensor) -> torch.Tensor: - """Convert input batch of C-channel spectrograms into - a batch of time-frequency features with dimension num_feat. - The output number of channels may be the same as input, or - reduced to 1, e.g., if averaging over magnitude and not appending individual IPDs. - - Args: - input: Spectrogram for C channels with F subbands and N time frames, (B, C, F, N) - input_length: Length of valid entries along the time dimension, shape (B,) - - Returns: - num_feat_channels channels with num_feat features, shape (B, num_feat_channels, num_feat, N) - """ - num_input_channels = input.size(1) - - # Magnitude spectrum - if self.mag_reduction is None: - mag = torch.abs(input) - elif self.mag_reduction == 'abs_mean': - mag = torch.abs(torch.mean(input, axis=1, keepdim=True)) - elif self.mag_reduction == 'mean_abs': - mag = torch.mean(torch.abs(input), axis=1, keepdim=True) - elif self.mag_reduction == 'rms': - mag = torch.sqrt(torch.mean(torch.abs(input) ** 2, axis=1, keepdim=True)) - else: - raise ValueError(f'Unexpected magnitude reduction {self.mag_reduction}') - - if self.mag_power is not None: - mag = torch.pow(mag, self.mag_power) - - if self.mag_normalization == 'mean': - # normalize mean across channels and time steps - mag = self.normalize_mean(input=mag, input_length=input_length) - elif self.mag_normalization == 'mean_var': - # normalize mean and variance across channels and time steps - mag = self.normalize_mean_var(input=mag, input_length=input_length) - - features = mag - - if self.use_ipd: - if num_input_channels == 1: - # no IPD for single-channel input - ipd = torch.zeros_like(input, dtype=features.dtype, device=features.device) - else: - # Calculate IPD relative to the average spec - spec_mean = torch.mean(input, axis=1, keepdim=True) # channel average - ipd = torch.angle(input) - torch.angle(spec_mean) - # Modulo to [-pi, pi] - ipd = wrap_to_pi(ipd) - - if self.ipd_normalization == 'mean': - # normalize mean across channels and time steps - # mean across time - ipd = self.normalize_mean(input=ipd, input_length=input_length) - elif self.ipd_normalization == 'mean_var': - ipd = self.normalize_mean_var(input=ipd, input_length=input_length) - - # Concatenate to existing features - features = torch.cat([features.expand(ipd.shape), ipd], axis=2) - - if self._num_channels is not None and features.size(1) != self._num_channels: - raise RuntimeError( - f'Number of channels in features {features.size(1)} is different than the configured number of channels {self._num_channels}' - ) - - return features, input_length diff --git a/nemo/collections/audio/modules/masking.py b/nemo/collections/audio/modules/masking.py deleted file mode 100644 index 3f0380dccb5d6e9f81742d36574b7b65d49d64d2..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/modules/masking.py +++ /dev/null @@ -1,1063 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import Dict, List, Optional, Tuple - -import torch - -from nemo.collections.asr.modules.conformer_encoder import ConformerEncoder -from nemo.collections.asr.parts.preprocessing.features import make_seq_mask_like -from nemo.collections.audio.modules.features import SpectrogramToMultichannelFeatures -from nemo.collections.audio.parts.submodules.multichannel import ( - ChannelAttentionPool, - ChannelAveragePool, - ParametricMultichannelWienerFilter, - TransformAttendConcatenate, - TransformAverageConcatenate, - WPEFilter, -) -from nemo.collections.audio.parts.utils.audio import db2mag -from nemo.core.classes import NeuralModule, typecheck -from nemo.core.neural_types import FloatType, LengthsType, NeuralType, SpectrogramType -from nemo.utils import logging - - -class MaskEstimatorRNN(NeuralModule): - """Estimate `num_outputs` masks from the input spectrogram - using stacked RNNs and projections. - - The module is structured as follows: - input --> spatial features --> input projection --> - --> stacked RNNs --> output projection for each output --> sigmoid - - Reference: - Multi-microphone neural speech separation for far-field multi-talker - speech recognition (https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=8462081) - - Args: - num_outputs: Number of output masks to estimate - num_subbands: Number of subbands of the input spectrogram - num_features: Number of features after the input projections - num_layers: Number of RNN layers - num_hidden_features: Number of hidden features in RNN layers - num_input_channels: Number of input channels - dropout: If non-zero, introduces dropout on the outputs of each RNN layer except the last layer, with dropout - probability equal to `dropout`. Default: 0 - bidirectional: If `True`, use bidirectional RNN. - rnn_type: Type of RNN, either `lstm` or `gru`. Default: `lstm` - mag_reduction: Channel-wise reduction for magnitude features - use_ipd: Use inter-channel phase difference (IPD) features - """ - - def __init__( - self, - num_outputs: int, - num_subbands: int, - num_features: int = 1024, - num_layers: int = 3, - num_hidden_features: Optional[int] = None, - num_input_channels: Optional[int] = None, - dropout: float = 0, - bidirectional=True, - rnn_type: str = 'lstm', - mag_reduction: str = 'rms', - use_ipd: bool = None, - ): - super().__init__() - if num_hidden_features is None: - num_hidden_features = num_features - - self.features = SpectrogramToMultichannelFeatures( - num_subbands=num_subbands, - num_input_channels=num_input_channels, - mag_reduction=mag_reduction, - use_ipd=use_ipd, - ) - - self.input_projection = torch.nn.Linear( - in_features=self.features.num_features * self.features.num_channels, out_features=num_features - ) - - if rnn_type == 'lstm': - self.rnn = torch.nn.LSTM( - input_size=num_features, - hidden_size=num_hidden_features, - num_layers=num_layers, - batch_first=True, - dropout=dropout, - bidirectional=bidirectional, - ) - elif rnn_type == 'gru': - self.rnn = torch.nn.GRU( - input_size=num_features, - hidden_size=num_hidden_features, - num_layers=num_layers, - batch_first=True, - dropout=dropout, - bidirectional=bidirectional, - ) - else: - raise ValueError(f'Unknown rnn_type: {rnn_type}') - - self.fc = torch.nn.Linear( - in_features=2 * num_features if bidirectional else num_features, out_features=num_features - ) - self.norm = torch.nn.LayerNorm(num_features) - - # Each output shares the RNN and has a separate projection - self.output_projections = torch.nn.ModuleList( - [torch.nn.Linear(in_features=num_features, out_features=num_subbands) for _ in range(num_outputs)] - ) - self.output_nonlinearity = torch.nn.Sigmoid() - - @property - def input_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "input": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "input_length": NeuralType(('B',), LengthsType()), - } - - @property - def output_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "output": NeuralType(('B', 'C', 'D', 'T'), FloatType()), - "output_length": NeuralType(('B',), LengthsType()), - } - - @typecheck() - def forward(self, input: torch.Tensor, input_length: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: - """Estimate `num_outputs` masks from the input spectrogram. - - Args: - input: C-channel input, shape (B, C, F, N) - input_length: Length of valid entries along the time dimension, shape (B,) - - Returns: - Returns `num_outputs` masks in a tensor, shape (B, num_outputs, F, N), - and output length with shape (B,) - """ - input, _ = self.features(input=input, input_length=input_length) - B, num_feature_channels, num_features, N = input.shape - - # (B, num_feat_channels, num_feat, N) -> (B, N, num_feat_channels, num_feat) - input = input.permute(0, 3, 1, 2) - - # (B, N, num_feat_channels, num_feat) -> (B, N, num_feat_channels * num_features) - input = input.view(B, N, -1) - - # Apply projection on num_feat - input = self.input_projection(input) - - # Apply RNN on the input sequence - input_packed = torch.nn.utils.rnn.pack_padded_sequence( - input, input_length.cpu(), batch_first=True, enforce_sorted=False - ).to(input.device) - self.rnn.flatten_parameters() - input_packed, _ = self.rnn(input_packed) - output, output_length = torch.nn.utils.rnn.pad_packed_sequence(input_packed, batch_first=True) - output_length = output_length.to(input.device) - - # Layer normalization and skip connection - output = self.norm(self.fc(output)) + input - - # Create `num_outputs` masks - masks = [] - for output_projection in self.output_projections: - # Output projection - mask = output_projection(output) - mask = self.output_nonlinearity(mask) - - # Back to the original format - # (B, N, F) -> (B, F, N) - mask = mask.transpose(2, 1) - - # Append to the output - masks.append(mask) - - # Stack along channel dimension to get (B, M, F, N) - masks = torch.stack(masks, axis=1) - - # Mask frames beyond output length - length_mask: torch.Tensor = make_seq_mask_like( - lengths=output_length, like=masks, time_dim=-1, valid_ones=False - ) - masks = masks.masked_fill(length_mask, 0.0) - - return masks, output_length - - -class MaskEstimatorFlexChannels(NeuralModule): - """Estimate `num_outputs` masks from the input spectrogram - using stacked channel-wise and temporal layers. - - This model is using interlaved channel blocks and temporal blocks, and - it can process arbitrary number of input channels. - Default channel block is the transform-average-concatenate layer. - Default temporal block is the Conformer encoder. - Reduction from multichannel signal to single-channel signal is performed - after `channel_reduction_position` blocks. Only temporal blocks are used afterwards. - After the sequence of blocks, the output mask is computed using an additional - output temporal layer and a nonlinearity. - - References: - - Yoshioka et al, VarArray: Array-Geometry-Agnostic Continuous Speech Separation, 2022 - - Jukić et al, Flexible multichannel speech enhancement for noise-robust frontend, 2023 - - Args: - num_outputs: Number of output masks. - num_subbands: Number of subbands on the input spectrogram. - num_blocks: Number of blocks in the model. - channel_reduction_position: After this block, the signal will be reduced across channels. - channel_reduction_type: Reduction across channels: 'average' or 'attention' - channel_block_type: Block for channel processing: 'transform_average_concatenate' or 'transform_attend_concatenate' - temporal_block_type: Block for temporal processing: 'conformer_encoder' - temporal_block_num_layers: Number of layers for the temporal block - temporal_block_num_heads: Number of heads for the temporal block - temporal_block_dimension: The hidden size of the model - temporal_block_self_attention_model: Self attention model for the temporal block - temporal_block_att_context_size: Attention context size for the temporal block - mag_reduction: Channel-wise reduction for magnitude features - mag_power: Power to apply on magnitude features - use_ipd: Use inter-channel phase difference (IPD) features - mag_normalization: Normalize using mean ('mean') or mean and variance ('mean_var') - ipd_normalization: Normalize using mean ('mean') or mean and variance ('mean_var') - """ - - def __init__( - self, - num_outputs: int, - num_subbands: int, - num_blocks: int, - channel_reduction_position: int = -1, # if 0, apply before block 0, if -1 apply at the end - channel_reduction_type: str = 'attention', - channel_block_type: str = 'transform_attend_concatenate', - temporal_block_type: str = 'conformer_encoder', - temporal_block_num_layers: int = 5, - temporal_block_num_heads: int = 4, - temporal_block_dimension: int = 128, - temporal_block_self_attention_model: str = 'rel_pos', - temporal_block_att_context_size: Optional[List[int]] = None, - num_input_channels: Optional[int] = None, - mag_reduction: str = 'abs_mean', - mag_power: Optional[float] = None, - use_ipd: bool = True, - mag_normalization: Optional[str] = None, - ipd_normalization: Optional[str] = None, - ): - super().__init__() - - self.features = SpectrogramToMultichannelFeatures( - num_subbands=num_subbands, - num_input_channels=num_input_channels, - mag_reduction=mag_reduction, - mag_power=mag_power, - use_ipd=use_ipd, - mag_normalization=mag_normalization, - ipd_normalization=ipd_normalization, - ) - self.num_blocks = num_blocks - logging.debug('Total number of blocks: %d', self.num_blocks) - - # Channel reduction - if channel_reduction_position == -1: - # Apply reduction after the last layer - channel_reduction_position = num_blocks - - if channel_reduction_position > num_blocks: - raise ValueError( - f'Channel reduction position {channel_reduction_position} exceeds the number of blocks {num_blocks}' - ) - self.channel_reduction_position = channel_reduction_position - logging.debug('Channel reduction will be applied before block %d', self.channel_reduction_position) - - # Prepare processing blocks - self.channel_blocks = torch.nn.ModuleList() - self.temporal_blocks = torch.nn.ModuleList() - - for n in range(num_blocks): - logging.debug('Prepare block %d', n) - - # Setup channel block - if n < channel_reduction_position: - # Number of input features is either the number of input channels or the number of temporal block features - channel_in_features = self.features.num_features if n == 0 else temporal_block_dimension - logging.debug( - 'Setup channel block %s with %d input features and %d output features', - channel_block_type, - channel_in_features, - temporal_block_dimension, - ) - - # Instantiante the channel block - if channel_block_type == 'transform_average_concatenate': - channel_block = TransformAverageConcatenate( - in_features=channel_in_features, out_features=temporal_block_dimension - ) - elif channel_block_type == 'transform_attend_concatenate': - channel_block = TransformAttendConcatenate( - in_features=channel_in_features, out_features=temporal_block_dimension - ) - else: - raise ValueError(f'Unknown channel layer type: {channel_block_type}') - self.channel_blocks.append(channel_block) - - # Setup temporal block - temporal_in_features = ( - self.features.num_features if n == self.channel_reduction_position == 0 else temporal_block_dimension - ) - logging.debug('Setup temporal block %s', temporal_block_type) - if temporal_block_type == 'conformer_encoder': - temporal_block = ConformerEncoder( - feat_in=temporal_in_features, - n_layers=temporal_block_num_layers, - d_model=temporal_block_dimension, - subsampling_factor=1, - self_attention_model=temporal_block_self_attention_model, - att_context_size=temporal_block_att_context_size, - n_heads=temporal_block_num_heads, - ) - else: - raise ValueError(f'Unknown temporal block {temporal_block}.') - - self.temporal_blocks.append(temporal_block) - - logging.debug('Setup channel reduction %s', channel_reduction_type) - if channel_reduction_type == 'average': - # Mean across channel dimension - self.channel_reduction = ChannelAveragePool() - elif channel_reduction_type == 'attention': - # Number of input features is either the number of input channels or the number of temporal block features - channel_reduction_in_features = ( - self.features.num_features if self.channel_reduction_position == 0 else temporal_block_dimension - ) - # Attention across channel dimension - self.channel_reduction = ChannelAttentionPool(in_features=channel_reduction_in_features) - else: - raise ValueError(f'Unknown channel reduction type: {channel_reduction_type}') - - logging.debug('Setup %d output layers', num_outputs) - self.output_layers = torch.nn.ModuleList( - [ - ConformerEncoder( - feat_in=temporal_block_dimension, - n_layers=1, - d_model=temporal_block_dimension, - feat_out=num_subbands, - subsampling_factor=1, - self_attention_model=temporal_block_self_attention_model, - att_context_size=temporal_block_att_context_size, - n_heads=temporal_block_num_heads, - ) - for _ in range(num_outputs) - ] - ) - - # Output nonlinearity - self.output_nonlinearity = torch.nn.Sigmoid() - - @property - def input_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "input": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "input_length": NeuralType(('B',), LengthsType()), - } - - @property - def output_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "output": NeuralType(('B', 'C', 'D', 'T'), FloatType()), - "output_length": NeuralType(('B',), LengthsType()), - } - - @typecheck() - def forward(self, input: torch.Tensor, input_length: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: - """Estimate `num_outputs` masks from the input spectrogram.""" - # get input features from a complex-valued spectrogram, (B, C, F, T) - output, output_length = self.features(input=input, input_length=input_length) - - # batch and num channels - B, M = input.size(0), input.size(1) - - # process all blocks - for n in range(self.num_blocks): - if n < self.channel_reduction_position: - # apply multichannel block - output = self.channel_blocks[n](input=output) - # change to a single-stream format - F, T = output.size(-2), output.size(-1) - # (B, M, F, T) -> (B * M, F, T) - output = output.reshape(-1, F, T) - if M > 1: - # adjust the lengths accordingly - output_length = output_length.repeat_interleave(M) - - elif n == self.channel_reduction_position: - # apply channel reduction - # (B, M, F, T) -> (B, F, T) - output = self.channel_reduction(input=output) - - # apply temporal model on each channel independently - with typecheck.disable_checks(): - # output is AcousticEncodedRepresentation, conformer encoder requires SpectrogramType - output, output_length = self.temporal_blocks[n](audio_signal=output, length=output_length) - - # if channel reduction has not been applied yet, go back to multichannel layout - if n < self.channel_reduction_position: - # back to multi-channel format with possibly a different number of features - T = output.size(-1) - # (B * M, F, T) -> (B, M, F, T) - output = output.reshape(B, M, -1, T) - if M > 1: - # convert lengths from single-stream format to original multichannel - output_length = output_length[0:-1:M] - - if self.channel_reduction_position == self.num_blocks: - # apply channel reduction after the last layer - # (B, M, F, T) -> (B, F, T) - output = self.channel_reduction(input=output) - - # final mask for each output - masks = [] - for output_layer in self.output_layers: - # calculate mask - with typecheck.disable_checks(): - # output is AcousticEncodedRepresentation, conformer encoder requires SpectrogramType - mask, mask_length = output_layer(audio_signal=output, length=output_length) - mask = self.output_nonlinearity(mask) - # append to all masks - masks.append(mask) - - # stack masks along channel dimensions - masks = torch.stack(masks, dim=1) - - return masks, mask_length - - -class MaskEstimatorGSS(NeuralModule): - """Estimate masks using guided source separation with a complex - angular Central Gaussian Mixture Model (cACGMM) [1]. - - This module corresponds to `GSS` in Fig. 2 in [2]. - - Notation is approximately following [1], where `gamma` denotes - the time-frequency mask, `alpha` denotes the mixture weights, - and `BM` denotes the shape matrix. Additionally, the provided - source activity is denoted as `activity`. - - Args: - num_iterations: Number of iterations for the EM algorithm - eps: Small value for regularization - dtype: Data type for internal computations (default `torch.cdouble`) - - References: - [1] Ito et al., Complex Angular Central Gaussian Mixture Model for Directional Statistics in Mask-Based Microphone Array Signal Processing, 2016 - [2] Boeddeker et al., Front-End Processing for the CHiME-5 Dinner Party Scenario, 2018 - """ - - def __init__(self, num_iterations: int = 3, eps: float = 1e-8, dtype: torch.dtype = torch.cdouble): - super().__init__() - - if num_iterations <= 0: - raise ValueError(f'Number of iterations must be positive, got {num_iterations}') - - # number of iterations for the EM algorithm - self.num_iterations = num_iterations - - if eps <= 0: - raise ValueError(f'eps must be positive, got {eps}') - - # small regularization constant - self.eps = eps - - # internal calculations - if dtype not in [torch.cfloat, torch.cdouble]: - raise ValueError(f'Unsupported dtype {dtype}, expecting cfloat or cdouble') - self.dtype = dtype - - logging.debug('Initialized %s', self.__class__.__name__) - logging.debug('\tnum_iterations: %s', self.num_iterations) - logging.debug('\teps: %g', self.eps) - logging.debug('\tdtype: %s', self.dtype) - - def normalize(self, x: torch.Tensor, dim: int = 1) -> torch.Tensor: - """Normalize input to have a unit L2-norm across `dim`. - By default, normalizes across the input channels. - - Args: - x: C-channel input signal, shape (B, C, F, T) - dim: Dimension for normalization, defaults to -3 to normalize over channels - - Returns: - Normalized signal, shape (B, C, F, T) - """ - norm_x = torch.linalg.vector_norm(x, ord=2, dim=dim, keepdim=True) - x = x / (norm_x + self.eps) - return x - - @typecheck( - input_types={ - 'alpha': NeuralType(('B', 'C', 'D')), - 'activity': NeuralType(('B', 'C', 'T')), - 'log_pdf': NeuralType(('B', 'C', 'D', 'T')), - }, - output_types={ - 'gamma': NeuralType(('B', 'C', 'D', 'T')), - }, - ) - def update_masks(self, alpha: torch.Tensor, activity: torch.Tensor, log_pdf: torch.Tensor) -> torch.Tensor: - """Update masks for the cACGMM. - - Args: - alpha: component weights, shape (B, num_outputs, F) - activity: temporal activity for the components, shape (B, num_outputs, T) - log_pdf: logarithm of the PDF, shape (B, num_outputs, F, T) - - Returns: - Masks for the components of the model, shape (B, num_outputs, F, T) - """ - # (B, num_outputs, F) - # normalize across outputs in the log domain - log_gamma = log_pdf - torch.max(log_pdf, axis=-3, keepdim=True)[0] - - gamma = torch.exp(log_gamma) - - # calculate the mask using weight, pdf and source activity - gamma = alpha[..., None] * gamma * activity[..., None, :] - - # normalize across components/output channels - gamma = gamma / (torch.sum(gamma, dim=-3, keepdim=True) + self.eps) - - return gamma - - @typecheck( - input_types={ - 'gamma': NeuralType(('B', 'C', 'D', 'T')), - }, - output_types={ - 'alpha': NeuralType(('B', 'C', 'D')), - }, - ) - def update_weights(self, gamma: torch.Tensor) -> torch.Tensor: - """Update weights for the individual components - in the mixture model. - - Args: - gamma: masks, shape (B, num_outputs, F, T) - - Returns: - Component weights, shape (B, num_outputs, F) - """ - alpha = torch.mean(gamma, dim=-1) - return alpha - - @typecheck( - input_types={ - 'z': NeuralType(('B', 'C', 'D', 'T')), - 'gamma': NeuralType(('B', 'C', 'D', 'T')), - 'zH_invBM_z': NeuralType(('B', 'C', 'D', 'T')), - }, - output_types={ - 'log_pdf': NeuralType(('B', 'C', 'D', 'T')), - 'zH_invBM_z': NeuralType(('B', 'C', 'D', 'T')), - }, - ) - def update_pdf( - self, z: torch.Tensor, gamma: torch.Tensor, zH_invBM_z: torch.Tensor - ) -> Tuple[torch.Tensor, torch.Tensor]: - """Update PDF of the cACGMM. - - Args: - z: directional statistics, shape (B, num_inputs, F, T) - gamma: masks, shape (B, num_outputs, F, T) - zH_invBM_z: energy weighted by shape matrices, shape (B, num_outputs, F, T) - - Returns: - Logarithm of the PDF, shape (B, num_outputs, F, T), the energy term, shape (B, num_outputs, F, T) - """ - num_inputs = z.size(-3) - - # shape (B, num_outputs, F, T) - scale = gamma / (zH_invBM_z + self.eps) - - # scale outer product and sum over time - # shape (B, num_outputs, F, num_inputs, num_inputs) - BM = num_inputs * torch.einsum('bmft,bift,bjft->bmfij', scale.to(z.dtype), z, z.conj()) - - # normalize across time - denom = torch.sum(gamma, dim=-1) - BM = BM / (denom[..., None, None] + self.eps) - - # make sure the matrix is Hermitian - BM = (BM + BM.conj().transpose(-1, -2)) / 2 - - # use eigenvalue decomposition to calculate the log determinant - # and the inverse-weighted energy term - L, Q = torch.linalg.eigh(BM) - - # BM is positive definite, so all eigenvalues should be positive - # However, small negative values may occur due to a limited precision - L = torch.clamp(L.real, min=self.eps) - - # PDF is invariant to scaling of the shape matrix [1], so - # eignevalues can be normalized (across num_inputs) - L = L / (torch.max(L, axis=-1, keepdim=True)[0] + self.eps) - - # small regularization to avoid numerical issues - L = L + self.eps - - # calculate the log determinant using the eigenvalues - log_detBM = torch.sum(torch.log(L), dim=-1) - - # calculate the energy term using the inverse eigenvalues - # NOTE: keeping an alternative implementation for reference (slower) - # zH_invBM_z = torch.einsum('bift,bmfij,bmfj,bmfkj,bkft->bmft', z.conj(), Q, (1 / L).to(Q.dtype), Q.conj(), z) - # zH_invBM_z = zH_invBM_z.abs() + self.eps # small regularization - - # calc sqrt(L) * Q^H * z - zH_invBM_z = torch.einsum('bmfj,bmfkj,bkft->bmftj', (1 / L.sqrt()).to(Q.dtype), Q.conj(), z) - # calc squared norm - zH_invBM_z = zH_invBM_z.abs().pow(2).sum(-1) - # small regularization - zH_invBM_z = zH_invBM_z + self.eps - - # final log PDF - log_pdf = -num_inputs * torch.log(zH_invBM_z) - log_detBM[..., None] - - return log_pdf, zH_invBM_z - - @property - def input_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "input": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "activity": NeuralType(('B', 'C', 'T')), - } - - @property - def output_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "gamma": NeuralType(('B', 'C', 'D', 'T')), - } - - @typecheck() - def forward(self, input: torch.Tensor, activity: torch.Tensor) -> torch.Tensor: - """Apply GSS to estimate the time-frequency masks for each output source. - - Args: - input: batched C-channel input signal, shape (B, num_inputs, F, T) - activity: batched frame-wise activity for each output source, shape (B, num_outputs, T) - - Returns: - Masks for the components of the model, shape (B, num_outputs, F, T) - """ - B, num_inputs, F, T = input.shape - num_outputs = activity.size(1) - device = input.device.type - - if activity.size(0) != B: - raise ValueError(f'Batch dimension mismatch: activity {activity.shape} vs input {input.shape}') - - if activity.size(-1) != T: - raise ValueError(f'Time dimension mismatch: activity {activity.shape} vs input {input.shape}') - - if num_outputs == 1: - raise ValueError(f'Expecting multiple outputs, got {num_outputs}') - - with torch.amp.autocast(device, enabled=False): - input = input.to(dtype=self.dtype) - - assert input.is_complex(), f'Expecting complex input, got {input.dtype}' - - # convert input to directional statistics by normalizing across channels - z = self.normalize(input, dim=-3) - - # initialize masks - gamma = torch.clamp(activity, min=self.eps) - # normalize across channels - gamma = gamma / torch.sum(gamma, dim=-2, keepdim=True) - # expand to input shape - gamma = gamma.unsqueeze(2).expand(-1, -1, F, -1) - - # initialize the energy term - zH_invBM_z = torch.ones(B, num_outputs, F, T, dtype=input.dtype, device=input.device) - - # EM iterations - for it in range(self.num_iterations): - alpha = self.update_weights(gamma=gamma) - log_pdf, zH_invBM_z = self.update_pdf(z=z, gamma=gamma, zH_invBM_z=zH_invBM_z) - gamma = self.update_masks(alpha=alpha, activity=activity, log_pdf=log_pdf) - - if torch.any(torch.isnan(gamma)): - raise RuntimeError(f'gamma contains NaNs: {gamma}') - - return gamma - - -class MaskReferenceChannel(NeuralModule): - """A simple mask processor which applies mask - on ref_channel of the input signal. - - Args: - ref_channel: Index of the reference channel. - mask_min_db: Threshold mask to a minimal value before applying it, defaults to -200dB - mask_max_db: Threshold mask to a maximal value before applying it, defaults to 0dB - """ - - def __init__(self, ref_channel: int = 0, mask_min_db: float = -200, mask_max_db: float = 0): - super().__init__() - self.ref_channel = ref_channel - # Mask thresholding - self.mask_min = db2mag(mask_min_db) - self.mask_max = db2mag(mask_max_db) - - logging.debug('Initialized %s with', self.__class__.__name__) - logging.debug('\tref_channel: %d', self.ref_channel) - logging.debug('\tmask_min: %f', self.mask_min) - logging.debug('\tmask_max: %f', self.mask_max) - - @property - def input_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "input": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "input_length": NeuralType(('B',), LengthsType()), - "mask": NeuralType(('B', 'C', 'D', 'T'), FloatType()), - } - - @property - def output_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "output": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "output_length": NeuralType(('B',), LengthsType()), - } - - @typecheck() - def forward( - self, - input: torch.Tensor, - input_length: torch.Tensor, - mask: torch.Tensor, - ) -> Tuple[torch.Tensor, torch.Tensor]: - """Apply mask on `ref_channel` of the input signal. - This can be used to generate multi-channel output. - If `mask` has `M` channels, the output will have `M` channels as well. - - Args: - input: Input signal complex-valued spectrogram, shape (B, C, F, N) - input_length: Length of valid entries along the time dimension, shape (B,) - mask: Mask for M outputs, shape (B, M, F, N) - - Returns: - M-channel output complex-valed spectrogram with shape (B, M, F, N) - """ - # Apply thresholds - mask = torch.clamp(mask, min=self.mask_min, max=self.mask_max) - - # Apply each output mask on the ref channel - output = mask * input[:, self.ref_channel : self.ref_channel + 1, ...] - return output, input_length - - -class MaskBasedBeamformer(NeuralModule): - """Multi-channel processor using masks to estimate signal statistics. - - Args: - filter_type: string denoting the type of the filter. Defaults to `mvdr` - filter_beta: Parameter of the parameteric multichannel Wiener filter - filter_rank: Parameter of the parametric multichannel Wiener filter - filter_postfilter: Optional, postprocessing of the filter - ref_channel: Optional, reference channel. If None, it will be estimated automatically - ref_hard: If true, hard (one-hot) reference. If false, a soft reference - ref_hard_use_grad: If true, use straight-through gradient when using the hard reference - ref_subband_weighting: If true, use subband weighting when estimating reference channel - num_subbands: Optional, used to determine the parameter size for reference estimation - mask_min_db: Threshold mask to a minimal value before applying it, defaults to -200dB - mask_max_db: Threshold mask to a maximal value before applying it, defaults to 0dB - diag_reg: Optional, diagonal regularization for the multichannel filter - eps: Small regularization constant to avoid division by zero - """ - - def __init__( - self, - filter_type: str = 'mvdr_souden', - filter_beta: float = 0.0, - filter_rank: str = 'one', - filter_postfilter: Optional[str] = None, - ref_channel: Optional[int] = 0, - ref_hard: bool = True, - ref_hard_use_grad: bool = False, - ref_subband_weighting: bool = False, - num_subbands: Optional[int] = None, - mask_min_db: float = -200, - mask_max_db: float = 0, - postmask_min_db: float = 0, - postmask_max_db: float = 0, - diag_reg: Optional[float] = 1e-6, - eps: float = 1e-8, - ): - super().__init__() - if filter_type not in ['pmwf', 'mvdr_souden']: - raise ValueError(f'Unknown filter type {filter_type}') - - self.filter_type = filter_type - if self.filter_type == 'mvdr_souden' and filter_beta != 0: - logging.warning( - 'Using filter type %s: beta will be automatically set to zero (current beta %f) and rank to one (current rank %s).', - self.filter_type, - filter_beta, - filter_rank, - ) - filter_beta = 0.0 - filter_rank = 'one' - # Prepare filter - self.filter = ParametricMultichannelWienerFilter( - beta=filter_beta, - rank=filter_rank, - postfilter=filter_postfilter, - ref_channel=ref_channel, - ref_hard=ref_hard, - ref_hard_use_grad=ref_hard_use_grad, - ref_subband_weighting=ref_subband_weighting, - num_subbands=num_subbands, - diag_reg=diag_reg, - eps=eps, - ) - # Mask thresholding - if mask_min_db >= mask_max_db: - raise ValueError( - f'Lower bound for the mask {mask_min_db}dB must be smaller than the upper bound {mask_max_db}dB' - ) - self.mask_min = db2mag(mask_min_db) - self.mask_max = db2mag(mask_max_db) - # Postmask thresholding - if postmask_min_db > postmask_max_db: - raise ValueError( - f'Lower bound for the postmask {postmask_min_db}dB must be smaller or equal to the upper bound {postmask_max_db}dB' - ) - self.postmask_min = db2mag(postmask_min_db) - self.postmask_max = db2mag(postmask_max_db) - - logging.debug('Initialized %s', self.__class__.__name__) - logging.debug('\tfilter_type: %s', self.filter_type) - logging.debug('\tmask_min: %e', self.mask_min) - logging.debug('\tmask_max: %e', self.mask_max) - logging.debug('\tpostmask_min: %e', self.postmask_min) - logging.debug('\tpostmask_max: %e', self.postmask_max) - - @property - def input_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "input": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "mask": NeuralType(('B', 'C', 'D', 'T'), FloatType()), - "mask_undesired": NeuralType(('B', 'C', 'D', 'T'), FloatType(), optional=True), - "input_length": NeuralType(('B',), LengthsType(), optional=True), - } - - @property - def output_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "output": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "output_length": NeuralType(('B',), LengthsType(), optional=True), - } - - @typecheck() - def forward( - self, - input: torch.Tensor, - mask: torch.Tensor, - mask_undesired: Optional[torch.Tensor] = None, - input_length: Optional[torch.Tensor] = None, - ) -> torch.Tensor: - """Apply a mask-based beamformer to the input spectrogram. - This can be used to generate multi-channel output. - If `mask` has multiple channels, a multichannel filter is created for each mask, - and the output is concatenation of individual outputs along the channel dimension. - The total number of outputs is `num_masks * M`, where `M` is the number of channels - at the filter output. - - Args: - input: Input signal complex-valued spectrogram, shape (B, C, F, N) - mask: Mask for M output signals, shape (B, num_masks, F, N) - input_length: Length of valid entries along the time dimension, shape (B,) - - Returns: - Multichannel output signal complex-valued spectrogram, shape (B, num_masks * M, F, N) - """ - # Length mask - if input_length is not None: - length_mask: torch.Tensor = make_seq_mask_like( - lengths=input_length, like=mask[:, 0, ...], time_dim=-1, valid_ones=False - ) - - # Use each mask to generate an output - output, num_masks = [], mask.size(1) - for m in range(num_masks): - # Desired signal mask - mask_d = mask[:, m, ...] - # Undesired signal mask - if mask_undesired is not None: - mask_u = mask_undesired[:, m, ...] - elif num_masks == 1: - # If a single mask is estimated, use the complement - mask_u = 1 - mask_d - else: - # Use sum of all other sources - mask_u = torch.sum(mask, dim=1) - mask_d - - # Threshold masks - mask_d = torch.clamp(mask_d, min=self.mask_min, max=self.mask_max) - mask_u = torch.clamp(mask_u, min=self.mask_min, max=self.mask_max) - - if input_length is not None: - mask_d = mask_d.masked_fill(length_mask, 0.0) - mask_u = mask_u.masked_fill(length_mask, 0.0) - - # Apply filter - output_m = self.filter(input=input, mask_s=mask_d, mask_n=mask_u) - - # Optional: apply a postmask with min and max thresholds - if self.postmask_min < self.postmask_max: - postmask_m = torch.clamp(mask[:, m, ...], min=self.postmask_min, max=self.postmask_max) - output_m = output_m * postmask_m.unsqueeze(1) - - # Save the current output (B, M, F, T) - output.append(output_m) - - # Combine outputs along the channel dimension - # Each output is (B, M, F, T) - output = torch.concatenate(output, axis=1) - - # Apply masking - if input_length is not None: - output = output.masked_fill(length_mask[:, None, ...], 0.0) - - return output, input_length - - -class MaskBasedDereverbWPE(NeuralModule): - """Multi-channel linear prediction-based dereverberation using - weighted prediction error for filter estimation. - - An optional mask to estimate the signal power can be provided. - If a time-frequency mask is not provided, the algorithm corresponds - to the conventional WPE algorithm. - - Args: - filter_length: Length of the convolutional filter for each channel in frames. - prediction_delay: Delay of the input signal for multi-channel linear prediction in frames. - num_iterations: Number of iterations for reweighting - mask_min_db: Threshold mask to a minimal value before applying it, defaults to -200dB - mask_max_db: Threshold mask to a minimal value before applying it, defaults to 0dB - diag_reg: Diagonal regularization for WPE - eps: Small regularization constant - dtype: Data type for internal computations - - References: - - Kinoshita et al, Neural network-based spectrum estimation for online WPE dereverberation, 2017 - - Yoshioka and Nakatani, Generalization of Multi-Channel Linear Prediction Methods for Blind MIMO Impulse Response Shortening, 2012 - """ - - def __init__( - self, - filter_length: int, - prediction_delay: int, - num_iterations: int = 1, - mask_min_db: float = -200, - mask_max_db: float = 0, - diag_reg: Optional[float] = 1e-6, - eps: float = 1e-8, - dtype: torch.dtype = torch.cdouble, - ): - super().__init__() - # Filter setup - self.filter = WPEFilter( - filter_length=filter_length, prediction_delay=prediction_delay, diag_reg=diag_reg, eps=eps - ) - self.num_iterations = num_iterations - # Mask thresholding - self.mask_min = db2mag(mask_min_db) - self.mask_max = db2mag(mask_max_db) - # Internal calculations - if dtype not in [torch.cfloat, torch.cdouble]: - raise ValueError(f'Unsupported dtype {dtype}, expecting torch.cfloat or torch.cdouble') - self.dtype = dtype - - logging.debug('Initialized %s', self.__class__.__name__) - logging.debug('\tnum_iterations: %s', self.num_iterations) - logging.debug('\tmask_min: %g', self.mask_min) - logging.debug('\tmask_max: %g', self.mask_max) - logging.debug('\tdtype: %s', self.dtype) - - @property - def input_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "input": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "input_length": NeuralType(('B',), LengthsType(), optional=True), - "mask": NeuralType(('B', 'C', 'D', 'T'), FloatType(), optional=True), - } - - @property - def output_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "output": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "output_length": NeuralType(('B',), LengthsType(), optional=True), - } - - @typecheck() - def forward( - self, input: torch.Tensor, input_length: Optional[torch.Tensor] = None, mask: Optional[torch.Tensor] = None - ) -> torch.Tensor: - """Given an input signal `input`, apply the WPE dereverberation algoritm. - - Args: - input: C-channel complex-valued spectrogram, shape (B, C, F, T) - input_length: Optional length for each signal in the batch, shape (B,) - mask: Optional mask, shape (B, 1, F, N) or (B, C, F, T) - - Returns: - Processed tensor with the same number of channels as the input, - shape (B, C, F, T). - """ - io_dtype = input.dtype - device = input.device.type - - with torch.amp.autocast(device, enabled=False): - output = input.to(dtype=self.dtype) - - if not output.is_complex(): - raise RuntimeError(f'Expecting complex input, got {output.dtype}') - - for i in range(self.num_iterations): - magnitude = torch.abs(output) - if i == 0 and mask is not None: - # Apply thresholds - mask = torch.clamp(mask, min=self.mask_min, max=self.mask_max) - # Mask magnitude - magnitude = mask * magnitude - # Calculate power - power = magnitude**2 - # Apply filter - output, output_length = self.filter(input=output, input_length=input_length, power=power) - - return output.to(io_dtype), output_length diff --git a/nemo/collections/audio/modules/projections.py b/nemo/collections/audio/modules/projections.py deleted file mode 100644 index 8dcc8a69d26a8c8d65329c0608029b6d8aec804d..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/modules/projections.py +++ /dev/null @@ -1,90 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import Dict, Optional - -import torch - -from nemo.core.classes import NeuralModule, typecheck -from nemo.core.neural_types import NeuralType, SpectrogramType - - -class MixtureConsistencyProjection(NeuralModule): - """Ensure estimated sources are consistent with the input mixture. - Note that the input mixture is assume to be a single-channel signal. - - Args: - weighting: Optional weighting mode for the consistency constraint. - If `None`, use uniform weighting. If `power`, use the power of the - estimated source as the weight. - eps: Small positive value for regularization - - Reference: - Wisdom et al, Differentiable consistency constraints for improved deep speech enhancement, 2018 - """ - - def __init__(self, weighting: Optional[str] = None, eps: float = 1e-8): - super().__init__() - self.weighting = weighting - self.eps = eps - - if self.weighting not in [None, 'power']: - raise NotImplementedError(f'Weighting mode {self.weighting} not implemented') - - @property - def input_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "mixture": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "estimate": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - } - - @property - def output_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "output": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - } - - @typecheck() - def forward(self, mixture: torch.Tensor, estimate: torch.Tensor) -> torch.Tensor: - """Enforce mixture consistency on the estimated sources. - Args: - mixture: Single-channel mixture, shape (B, 1, F, N) - estimate: M estimated sources, shape (B, M, F, N) - - Returns: - Source estimates consistent with the mixture, shape (B, M, F, N) - """ - if mixture.size(-3) != 1: - raise ValueError(f'Mixture must have a single channel, got shape {mixture.shape}') - - # number of sources - M = estimate.size(-3) - # estimated mixture based on the estimated sources - estimated_mixture = torch.sum(estimate, dim=-3, keepdim=True) - - # weighting - if self.weighting is None: - weight = 1 / M - elif self.weighting == 'power': - weight = estimate.abs().pow(2) - weight = weight / (weight.sum(dim=-3, keepdim=True) + self.eps) - else: - raise NotImplementedError(f'Weighting mode {self.weighting} not implemented') - - # consistent estimate - consistent_estimate = estimate + weight * (mixture - estimated_mixture) - - return consistent_estimate diff --git a/nemo/collections/audio/modules/ssl_pretrain_masking.py b/nemo/collections/audio/modules/ssl_pretrain_masking.py deleted file mode 100644 index 66883b60df31c1650155010d63dbc67de24c1bc6..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/modules/ssl_pretrain_masking.py +++ /dev/null @@ -1,112 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import random - -import einops -import torch - -from nemo.core.classes import NeuralModule, typecheck -from nemo.core.neural_types import LengthsType, NeuralType, SpectrogramType - -__all__ = ['SSLPretrainWithMaskedPatch'] - - -class SSLPretrainWithMaskedPatch(NeuralModule): - """ - Zeroes out fixed size time patches of the spectrogram. - All samples in batch are guaranteed to have the same amount of masked time steps. - Note that this may be problematic when we do pretraining on a unbalanced dataset. - - For example, say a batch contains two spectrograms of length 87 and 276. - With mask_fraction=0.7 and patch_size=10, we'll obrain mask_patches=7. - Each of the two data will then have 7 patches of 10-frame mask. - - Args: - patch_size (int): up to how many time steps does one patch consist of. - Defaults to 10. - mask_fraction (float): how much fraction in each sample to be masked (number of patches is rounded up). - Range from 0.0 to 1.0. Defaults to 0.7. - """ - - @property - def input_types(self): - """Returns definitions of module input types""" - return { - "input_spec": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "length": NeuralType(tuple('B'), LengthsType()), - } - - @property - def output_types(self): - """Returns definitions of module output types""" - return {"augmented_spec": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType())} - - def __init__( - self, - patch_size: int = 10, - mask_fraction: float = 0.7, - ): - super().__init__() - if patch_size <= 0: - raise ValueError(f'patch_size must be positive, got patch_size={patch_size}') - - if mask_fraction > 1.0 or mask_fraction < 0.0: - raise ValueError(f'mask_fraction must be in the range [0.0, 1.0], got mask_fraction={mask_fraction}') - - self.patch_size = patch_size - self.mask_fraction = mask_fraction - - @typecheck() - def forward(self, input_spec, length): - """ - Apply Patched masking on the input_spec. - - - During the training stage, the mask is generated randomly, with - approximately `self.mask_fraction` of the time frames being masked out. - - In the validation stage, the masking pattern is fixed to ensure - consistent evaluation of checkpoints and to prevent overfitting. Note - that the same masking pattern is applied to all data, regardless of - their lengths. On average, approximately `self.mask_fraction` of the - time frames will be masked out. - - """ - augmented_spec = input_spec - - if self.training: - for idx, cur_len in enumerate(length.tolist()): - # patch indices - patches = range(cur_len // self.patch_size) - # fraction of samples to mask - len_fraction = int(cur_len * self.mask_fraction) - # number of patches to mask - mask_patches = len_fraction // self.patch_size + int(len_fraction % self.patch_size != 0) - # if the number of patches to mask is greater than the number of patches, reduce the number of patches to mask - if cur_len < self.patch_size * mask_patches: - mask_patches = cur_len // self.patch_size - # sample random patches to mask - masked_patches = random.sample(patches, mask_patches) - # mask the sampled patches - for mp in masked_patches: - augmented_spec[idx, :, :, mp * self.patch_size : (mp + 1) * self.patch_size] = 0.0 - else: - chunk_length = self.patch_size // self.mask_fraction - mask = torch.arange(augmented_spec.size(-1), device=augmented_spec.device) - mask = (mask % chunk_length) >= self.patch_size - mask = einops.rearrange(mask, 'T -> 1 1 1 T').float() - augmented_spec = augmented_spec * mask - - return augmented_spec diff --git a/nemo/collections/audio/modules/transforms.py b/nemo/collections/audio/modules/transforms.py deleted file mode 100644 index 2970601f24e297cc82a4844063a2519db2fc23fc..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/modules/transforms.py +++ /dev/null @@ -1,487 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -from typing import Dict, Optional, Tuple - -import torch -from einops import rearrange - -from nemo.collections.asr.parts.preprocessing.features import make_seq_mask_like -from nemo.core.classes import NeuralModule, typecheck -from nemo.core.neural_types import AudioSignal, LengthsType, NeuralType, SpectrogramType -from nemo.utils import logging - - -class AudioToSpectrogram(NeuralModule): - """Transform a batch of input multi-channel signals into a batch of - STFT-based spectrograms. - - Args: - fft_length: length of FFT - hop_length: length of hops/shifts of the sliding window - power: exponent for magnitude spectrogram. Default `None` will - return a complex-valued spectrogram - magnitude_power: Transform magnitude of the spectrogram as x^magnitude_power. - scale: Positive scaling of the spectrogram. - """ - - def __init__( - self, fft_length: int, hop_length: int, magnitude_power: float = 1.0, scale: float = 1.0, center: bool = True - ): - super().__init__() - - # For now, assume FFT length is divisible by two - if fft_length % 2 != 0: - raise ValueError(f'fft_length = {fft_length} must be divisible by 2') - - self.fft_length = fft_length - self.hop_length = hop_length - self.pad_mode = 'constant' - window = torch.hann_window(self.win_length) - self.register_buffer('window', window) - - self.num_subbands = fft_length // 2 + 1 - - if magnitude_power <= 0: - raise ValueError(f'Magnitude power needs to be positive: current value {magnitude_power}') - self.magnitude_power = magnitude_power - - if scale <= 0: - raise ValueError(f'Scale needs to be positive: current value {scale}') - self.scale = scale - self.center = center - logging.debug('Initialized %s with:', self.__class__.__name__) - logging.debug('\tfft_length: %s', fft_length) - logging.debug('\thop_length: %s', hop_length) - logging.debug('\tmagnitude_power: %s', magnitude_power) - logging.debug('\tscale: %s', scale) - - @property - def win_length(self) -> int: - return self.fft_length - - def stft(self, x: torch.Tensor): - """Apply STFT as in torchaudio.transforms.Spectrogram(power=None) - - Args: - x_spec: Input time-domain signal, shape (..., T) - - Returns: - Time-domain signal ``x_spec = STFT(x)``, shape (..., F, N). - """ - # pack batch - B, C, T = x.size() - x = rearrange(x, 'B C T -> (B C) T') - - x_spec = torch.stft( - input=x, - n_fft=self.fft_length, - hop_length=self.hop_length, - win_length=self.win_length, - window=self.window, - center=self.center, - pad_mode=self.pad_mode, - normalized=False, - onesided=True, - return_complex=True, - ) - - # unpack batch - x_spec = rearrange(x_spec, '(B C) F N -> B C F N', B=B, C=C) - - return x_spec - - @property - def input_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "input": NeuralType(('B', 'C', 'T'), AudioSignal()), - "input_length": NeuralType(('B',), LengthsType(), optional=True), - } - - @property - def output_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "output": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "output_length": NeuralType(('B',), LengthsType()), - } - - @typecheck() - def forward( - self, input: torch.Tensor, input_length: Optional[torch.Tensor] = None - ) -> Tuple[torch.Tensor, torch.Tensor]: - """Convert a batch of C-channel input signals - into a batch of complex-valued spectrograms. - - Args: - input: Time-domain input signal with C channels, shape (B, C, T) - input_length: Length of valid entries along the time dimension, shape (B,) - - Returns: - Output spectrogram with F subbands and N time frames, shape (B, C, F, N) - and output length with shape (B,). - """ - B, T = input.size(0), input.size(-1) - input = input.view(B, -1, T) - - # STFT output (B, C, F, N) - with torch.amp.autocast(input.device.type, enabled=False): - output = self.stft(input.float()) - - if self.magnitude_power != 1: - # apply power on the magnitude - output = torch.pow(output.abs(), self.magnitude_power) * torch.exp(1j * output.angle()) - - if self.scale != 1: - # apply scaling of the coefficients - output = self.scale * output - - if input_length is not None: - # Mask padded frames - output_length = self.get_output_length(input_length=input_length) - - length_mask: torch.Tensor = make_seq_mask_like( - lengths=output_length, like=output, time_dim=-1, valid_ones=False - ) - output = output.masked_fill(length_mask, 0.0) - else: - # Assume all frames are valid for all examples in the batch - output_length = output.size(-1) * torch.ones(B, device=output.device).long() - - return output, output_length - - def get_output_length(self, input_length: torch.Tensor) -> torch.Tensor: - """Get length of valid frames for the output. - - Args: - input_length: number of valid samples, shape (B,) - - Returns: - Number of valid frames, shape (B,) - """ - # centered STFT results in (T // hop_length + 1) frames for T samples (cf. torch.stft) - output_length = input_length.div(self.hop_length, rounding_mode='floor').add(1).long() - return output_length - - -class SpectrogramToAudio(NeuralModule): - """Transform a batch of input multi-channel spectrograms into a batch of - time-domain multi-channel signals. - - Args: - fft_length: length of FFT - hop_length: length of hops/shifts of the sliding window - magnitude_power: Transform magnitude of the spectrogram as x^(1/magnitude_power). - scale: Spectrogram will be scaled with 1/scale before the inverse transform. - - Streaming usage (``center=False``):: - - # analysis should use the same window and center=False - # Prefer hamming for center=False (see note below) - window = torch.hamming_window(fft_length) - spec2audio = SpectrogramToAudio(fft_length=fft_length, hop_length=hop_length, center=False) - spec2audio.window = window - spec2audio.use_streaming = True - spec2audio.reset_streaming() - - parts = [] - for t in range(0, N, K): - frames = spec[..., t : t + K] # (B, C, F, K), complex - out, _ = spec2audio(input=frames) - parts.append(out) - tail = spec2audio.stream_finalize() - x_stream = torch.cat(parts + [tail], dim=-1) - - Notes: ``window`` must match analysis; call ``reset_streaming()`` before a new stream; - ``stream_finalize()`` flushes the tail (empty if ``hop_length == win_length``). - With ``center=False``, certain windows (e.g., Hann) may error in - some PyTorch versions; Hamming works reliably. See - `PyTorch issue #91309 `_. - """ - - def __init__( - self, fft_length: int, hop_length: int, magnitude_power: float = 1.0, scale: float = 1.0, center: bool = True - ): - super().__init__() - - # For now, assume FFT length is divisible by two - if fft_length % 2 != 0: - raise ValueError(f'fft_length = {fft_length} must be divisible by 2') - - self.fft_length = fft_length - self.hop_length = hop_length - window = torch.hann_window(self.win_length) - self.register_buffer('window', window) - - self.num_subbands = fft_length // 2 + 1 - - if magnitude_power <= 0: - raise ValueError(f'Magnitude power needs to be positive: current value {magnitude_power}') - self.magnitude_power = magnitude_power - self.center = center - if scale <= 0: - raise ValueError(f'Scale needs to be positive: current value {scale}') - self.scale = scale - - logging.debug('Initialized %s with:', self.__class__.__name__) - logging.debug('\tfft_length: %s', fft_length) - logging.debug('\thop_length: %s', hop_length) - logging.debug('\tmagnitude_power: %s', magnitude_power) - logging.debug('\tscale: %s', scale) - - # --- Streaming state (initialized lazily) --- - # Time-domain overlap-add buffers (initialized lazily) - self._ola_accum: Optional[torch.Tensor] = None - self._ola_weight: Optional[torch.Tensor] = None - # Kept for backward compatibility; not used in OLA implementation - self.use_streaming: bool = False - - @property - def win_length(self) -> int: - return self.fft_length - - def istft(self, x_spec: torch.Tensor): - """Apply iSTFT as in torchaudio.transforms.InverseSpectrogram - - Args: - x_spec: Input complex-valued spectrogram, shape (..., F, N) - - Returns: - Time-domain signal ``x = iSTFT(x_spec)``, shape (..., T). - """ - # pack batch - B, C, F, N = x_spec.size() - x_spec = rearrange(x_spec, 'B C F N -> (B C) F N') - - x = torch.istft( - input=x_spec, - n_fft=self.fft_length, - hop_length=self.hop_length, - win_length=self.win_length, - window=self.window, - center=self.center, - normalized=False, - onesided=True, - length=None, - return_complex=False, - ) - - # unpack batch - x = rearrange(x, '(B C) T -> B C T', B=B, C=C) - - return x - - @property - def input_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "input": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "input_length": NeuralType(('B',), LengthsType(), optional=True), - } - - @property - def output_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "output": NeuralType(('B', 'C', 'T'), AudioSignal()), - "output_length": NeuralType(('B',), LengthsType()), - } - - @typecheck() - def forward(self, input: torch.Tensor, input_length: Optional[torch.Tensor] = None) -> torch.Tensor: - """Convert input complex-valued spectrogram to a time-domain - signal. Multi-channel IO is supported. - - Offline mode (default): processes the entire input spectrogram at once. - Streaming mode: expects one or more frames (N>=1) and returns hop_length * N samples per call. - - Args: - input: Input spectrogram for C channels, shape (B, C, F, N) - input_length: Length of valid entries along the time dimension, shape (B,) - - Returns: - - Offline: (B, C, T_total), lengths (B,) - - Streaming (N=1): (B, C, hop_length), lengths (B,) filled with hop_length - """ - B, F, N = input.size(0), input.size(-2), input.size(-1) - assert F == self.num_subbands, f'Number of subbands F={F} not matching self.num_subbands={self.num_subbands}' - input = input.view(B, -1, F, N) - - if not input.is_complex(): - raise ValueError("Expected `input` to be complex dtype.") - - # iSTFT output (B, C, T) - with torch.amp.autocast(input.device.type, enabled=False): - output = input.cfloat() - - if self.scale != 1: - # apply 1/scale on the coefficients - output = output / self.scale - - if self.magnitude_power != 1: - # apply 1/power on the magnitude - output = torch.pow(output.abs(), 1 / self.magnitude_power) * torch.exp(1j * output.angle()) - - # --- Streaming mode --- - if self.use_streaming: - # Streaming expects a single frame at a time to avoid internal iteration. - out_stream = self.stream_update(output) # (B, C, <= hop_length) - out_len = torch.full((B,), out_stream.size(-1), dtype=torch.long, device=out_stream.device) - return out_stream, out_len - - output = self.istft(output) - - if input_length is not None: - # Mask padded samples - output_length = self.get_output_length(input_length=input_length) - - length_mask: torch.Tensor = make_seq_mask_like( - lengths=output_length, like=output, time_dim=-1, valid_ones=False - ) - output = output.masked_fill(length_mask, 0.0) - else: - # Assume all frames are valid for all examples in the batch - output_length = output.size(-1) * torch.ones(B, device=output.device).long() - - return output, output_length - - def get_output_length(self, input_length: torch.Tensor) -> torch.Tensor: - """Get length of valid samples for the output. - - Args: - input_length: number of valid frames, shape (B,) - - Returns: - Number of valid samples, shape (B,) - """ - # centered STFT results in ((N-1) * hop_length) time samples for N frames (cf. torch.istft) - output_length = input_length.sub(1).mul(self.hop_length).long() - return output_length - - @property - def _stream_initialized(self) -> bool: - """Return True if streaming buffers are initialized.""" - return (self._ola_accum is not None) and (self._ola_weight is not None) - - @property - def _eps(self) -> float: - """Machine epsilon for the active streaming dtype.""" - dtype = self._ola_weight.dtype if self._ola_weight is not None else self.window.dtype - return torch.finfo(dtype).eps - - # ------------------------------------------------------------------ - # Streaming iSTFT API (frame-by-frame with overlap-add buffering) - # ------------------------------------------------------------------ - def _init_stream_buffers(self, shape_like: torch.Tensor) -> None: - """Initialize streaming buffers based on an input tensor.""" - if self._stream_initialized: - return - if shape_like.dim() != 4: - raise ValueError("Expected input of shape (B, C, F, N_frames) for streaming.") - B, C = shape_like.size(0), shape_like.size(1) - device = shape_like.device - # Real-valued buffers for accumulated time-domain samples and weights - dtype = torch.float32 if shape_like.dtype == torch.complex64 else torch.float64 - self._ola_accum = torch.zeros(B, C, self.win_length, device=device, dtype=dtype) - self._ola_weight = torch.zeros(B, C, self.win_length, device=device, dtype=dtype) - - def reset_streaming(self) -> None: - """Reset the internal streaming buffers. - - Re-initialization happens lazily on the next call to `stream_update`. - """ - self._ola_accum = None - self._ola_weight = None - - def _shift_left_inplace(self, buffer: torch.Tensor) -> None: - """Shift buffer left by hop length and zero-fill the tail in-place.""" - hop = self.hop_length - buffer[..., :-hop] = buffer[..., hop:].clone() - buffer[..., -hop:] = 0.0 - - @torch.no_grad() - def stream_update(self, input: torch.Tensor) -> torch.Tensor: - """Consume one or more spectrogram frames (N>=1) and return hop_length * N samples via OLA. - - Steps per frame: - - inverse FFT - - apply synthesis window - - overlap-add into accumulation buffer - - emit first hop_length samples normalized by window-sum-square - - shift buffers left by hop_length - """ - if not input.is_complex(): - raise ValueError("Expected `input` to be complex dtype for streaming.") - - if self.center: - raise ValueError("Streaming iSTFT requires center=False.") - - # Lazily initialize buffers - self._init_stream_buffers(input) - - B, C, F, num_frames = input.size() - assert F == self.num_subbands, f"Number of subbands F={F} not matching self.num_subbands={self.num_subbands}" - - # Vectorized inverse FFT over frequency bins (dim=-2), yields (B, C, T, N) - frames_time = torch.fft.irfft(input, n=self.fft_length, dim=-2) - - # Prepare window and ensure buffers are on correct device/dtype - hop = self.hop_length - emitted_parts = [] - # Window shaped for broadcasting over frames - win = self.window.to(frames_time.device, dtype=frames_time.dtype).view(1, 1, self.win_length, 1) - win_sq = win[..., 0].squeeze(-1).pow(2) # (1, 1, T) - frames_time_windowed = frames_time * win # (B, C, T, N) - - # Ensure buffers on correct device/dtype - self._ola_accum = self._ola_accum.to(frames_time_windowed.device, dtype=frames_time_windowed.dtype) - self._ola_weight = self._ola_weight.to(frames_time_windowed.device, dtype=frames_time_windowed.dtype) - - # Iterate over frames for OLA - for t in range(num_frames): - frame_t = frames_time_windowed[..., t] # (B, C, T) - - # Overlap-add accumulation and window-sum-square weights - self._ola_accum.add_(frame_t) - self._ola_weight.add_(win_sq) - - # Emit first hop_length samples with normalization - denom = torch.clamp(self._ola_weight[..., :hop], min=self._eps) - emitted = self._ola_accum[..., :hop] / denom - emitted_parts.append(emitted) - - # Shift buffers left by hop_length - self._shift_left_inplace(self._ola_accum) - self._shift_left_inplace(self._ola_weight) - - return torch.cat(emitted_parts, dim=-1) - - @torch.no_grad() - def stream_finalize(self) -> torch.Tensor: - """Flush the remaining buffered samples (final tail for center=False). - - After processing the last frame, the streaming loop has emitted N*hop - samples. The remaining tail corresponds to the last (win_length - hop) - samples, which we return after proper window-sum-square normalization. - """ - if not self._stream_initialized: - return torch.tensor((), device=self.window.device) - - tail_len = self.win_length - self.hop_length - if tail_len <= 0: - return torch.tensor((), device=self.window.device) - - denom_tail = torch.clamp(self._ola_weight[..., :tail_len], min=self._eps) - tail = self._ola_accum[..., :tail_len] / denom_tail - return tail diff --git a/nemo/collections/audio/parts/__init__.py b/nemo/collections/audio/parts/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/parts/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/audio/parts/submodules/__init__.py b/nemo/collections/audio/parts/submodules/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/parts/submodules/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/audio/parts/submodules/conformer.py b/nemo/collections/audio/parts/submodules/conformer.py deleted file mode 100644 index 6f9ccae5daa03ca356479789b5f0e6f0147ee4eb..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/parts/submodules/conformer.py +++ /dev/null @@ -1,171 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import Dict - -import einops -import torch - -from nemo.collections.asr.modules.conformer_encoder import ConformerEncoder -from nemo.core.classes import NeuralModule, typecheck -from nemo.core.neural_types import ChannelType, LengthsType, NeuralType, SpectrogramType -from nemo.utils import logging - -__all__ = ['SpectrogramConformer'] - - -class SpectrogramConformer(NeuralModule): - """A Conformer-based model for processing complex-valued spectrograms. - - This model processes complex-valued inputs by stacking real and imaginary components - along the channel dimension. The stacked tensor is processed using Conformer layers, - and the output is projected back to generate real and imaginary components of the - output channels. - - Args: - in_channels: number of input complex-valued channels - out_channels: number of output complex-valued channels - kwargs: additional arguments for ConformerEncoder - """ - - def __init__(self, in_channels: int = 1, out_channels: int = 1, **kwargs): - super().__init__() - - # Number of input channels for this estimator - if in_channels < 1: - raise ValueError( - f'Number of input channels needs to be larger or equal to one, current value {in_channels}' - ) - - self.in_channels = in_channels - - # Number of output channels for this estimator - if out_channels < 1: - raise ValueError( - f'Number of output channels needs to be larger or equal to one, current value {out_channels}' - ) - - self.out_channels = out_channels - - # Conformer-based estimator - conformer_params = kwargs.copy() - conformer_params['feat_in'] = conformer_params['feat_out'] = ( - 2 * self.in_channels * kwargs['feat_in'] - ) # stack real and imag - logging.debug('Conformer params: %s', conformer_params) - self.conformer = ConformerEncoder(**conformer_params) - - # Output projection to generate real and imaginary components of the output channels - self.output_projection = torch.nn.Conv2d( - in_channels=2 * self.in_channels, out_channels=2 * self.out_channels, kernel_size=1 - ) - - logging.debug('Initialized %s with', self.__class__.__name__) - logging.debug('\tin_channels: %s', self.in_channels) - logging.debug('\tout_channels: %s', self.out_channels) - - @property - def context_size(self): - """Returns the attention context size used by the conformer encoder. - - The context size is a list of two integers [left_context, right_context] that defines - how many frames to the left and right each frame can attend to in the self-attention - layers. - - Returns: - List[int]: The attention context size [left_context, right_context] - """ - return self.conformer.att_context_size - - @context_size.setter - def context_size(self, value): - """Sets the attention context size used by the conformer encoder. - - The context size is a list of two integers [left_context, right_context] that defines - how many frames to the left and right each frame can attend to in the self-attention - layers. - - Args: - value (List[int]): The attention context size [left_context, right_context] - """ - self.conformer.set_default_att_context_size(value) - - @property - def input_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "input": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "input_length": NeuralType(('B',), LengthsType(), optional=True), - # convolutional context - "cache_last_channel": NeuralType(('D', 'B', 'T', 'D'), ChannelType(), optional=True), - "cache_last_time": NeuralType(('D', 'B', 'D', 'T'), ChannelType(), optional=True), - "cache_last_channel_len": NeuralType(tuple('B'), LengthsType(), optional=True), - } - - @property - def output_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "output": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "output_length": NeuralType(('B',), LengthsType(), optional=True), - # convolutional context - "cache_last_channel_next": NeuralType(('D', 'B', 'T', 'D'), ChannelType(), optional=True), - "cache_last_time_next": NeuralType(('D', 'B', 'D', 'T'), ChannelType(), optional=True), - "cache_last_channel_next_len": NeuralType(tuple('B'), LengthsType(), optional=True), - } - - @typecheck() - def forward( - self, input, input_length=None, cache_last_channel=None, cache_last_time=None, cache_last_channel_len=None - ): - """Forward pass for the SpectrogramConformer model. - - This method processes complex-valued inputs by stacking real and imaginary components, - passing the stacked tensor through Conformer layers, and projecting back to generate - real and imaginary components of the output channels. - """ - B, C_in, D, T = input.shape - if C_in != self.in_channels: - raise RuntimeError(f'Unexpected input channel size {C_in}, expected {self.in_channels}') - - # Stack real and imaginary components - input_real_imag = torch.stack([input.real, input.imag], dim=2) - input = einops.rearrange(input_real_imag, 'B C RI D T -> B (C RI D) T') - - # Conformer - if cache_last_channel is None: - # Not using caching mode - output, output_length = self.conformer(audio_signal=input, length=input_length) - else: - # Using caching mode - output, output_length, cache_last_channel, cache_last_time, cache_last_channel_len = self.conformer( - audio_signal=input, - length=input_length, - cache_last_channel=cache_last_channel, - cache_last_time=cache_last_time, - cache_last_channel_len=cache_last_channel_len, - ) - - # Output projection - output = einops.rearrange(output, 'B (C RI D) T -> B (C RI) D T', C=self.in_channels, RI=2, D=D) - output = self.output_projection(output) - - # Convert to complex-valued signal - output = einops.rearrange(output, 'B (C RI) D T -> B C D T RI', C=self.out_channels, RI=2, D=D) - output = torch.view_as_complex(output.contiguous()) - - if cache_last_channel is None: - return output, output_length - else: - return output, output_length, cache_last_channel, cache_last_time, cache_last_channel_len diff --git a/nemo/collections/audio/parts/submodules/conformer_unet.py b/nemo/collections/audio/parts/submodules/conformer_unet.py deleted file mode 100644 index 75573b2783930b176fe315a4caead78374abb332..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/parts/submodules/conformer_unet.py +++ /dev/null @@ -1,418 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import random -from typing import Dict - -import einops -import torch -import torch.nn as nn - -from nemo.collections.asr.modules.conformer_encoder import ConformerEncoder -from nemo.core.classes.common import typecheck - -from nemo.core.classes.module import NeuralModule -from nemo.core.neural_types import ChannelType, LengthsType, NeuralType, SpectrogramType -from nemo.utils import logging - -__all__ = ['SpectrogramConformerUNet', 'ConformerEncoderUNet'] - - -class ConformerEncoderUNet(ConformerEncoder): - """ - ConformerEncoder with U-Net-style skip connections for enhanced audio processing. - - Inherits all functionality from ConformerEncoder and adds U-Net skip connections - where the first encoder layer connects to the last layer, the second to the - second-last, and so on — but without any time-domain subsampling. - - Based on: - 'Conformer: Convolution-augmented Transformer for Speech Recognition' by Anmol Gulati et al. - https://arxiv.org/abs/2005.08100 - - U-Net skip connections inspired by: - Le et al., Voicebox: Text-Guided Multilingual Universal Speech Generation at Scale, 2023 - - Args: - n_layers (int): Number of ConformerBlock layers. Must be even (divisible by 2) when - use_unet_skip_connection=True to enable symmetric skip connections between - the first and second halves of the encoder. - use_unet_skip_connection (bool): Enable U-Net style skip connections between encoder layers. - When True, creates skip connections from the first half of layers to the second half. - Defaults to True. - skip_connect_scale (float, optional): Scaling factor applied to skip connections before - concatenation with the main signal. If None, defaults to 2^(-0.5) ≈ 0.707. - Defaults to None. - **kwargs: All other arguments are passed to the parent ConformerEncoder class. - See :class:`~nemo.collections.asr.modules.conformer_encoder.ConformerEncoder` - for complete documentation of all available parameters including: - - Model architecture (feat_in, n_layers, d_model, etc.) - - Attention settings (self_attention_model, att_context_size, etc.) - - Subsampling and reduction options - - Dropout and regularization parameters - - Streaming and caching configurations - - """ - - def __init__( - self, - *args, - use_unet_skip_connection: bool = True, - skip_connect_scale: float | None = None, - **kwargs, - ): - super().__init__(*args, **kwargs) - - self.use_unet_skip_connection = use_unet_skip_connection - self.skip_connect_scale = 2**-0.5 if skip_connect_scale is None else skip_connect_scale - - if not use_unet_skip_connection: - logging.warning('Skip connections are disabled in the ConformerEncoderUNet.') - return - - # Validate that n_layers is even for symmetric U-Net skip connections - if self.n_layers % 2 != 0: - raise ValueError( - f"For U-Net skip connections, n_layers must be even (divisible by 2), " - f"but got n_layers={self.n_layers}. This ensures symmetric skip connections " - f"between the first and second halves of the encoder." - ) - - new_layers = nn.ModuleList() - mid = len(self.layers) // 2 - for idx, layer in enumerate(self.layers): - has_skip = idx >= mid - combiner = nn.Linear(self.d_model * 2, self.d_model) if has_skip else None - new_layers.append(nn.ModuleList([combiner, layer])) - self.layers = new_layers - - def forward_internal( - self, - audio_signal, - length, - cache_last_channel=None, - cache_last_time=None, - cache_last_channel_len=None, - bypass_pre_encode=None, - ): - """ - Forward pass for the ConformerEncoderUNet model with U-Net-style skip connections. - - This method processes the input audio signal through the Conformer layers with optional - caching and U-Net-style skip connections. - - Main Changes Compared to Original Conformer: - - Incorporates U-Net-style skip connections between encoder layers. - """ - if length is None: - length = audio_signal.new_full( - (audio_signal.size(0),), audio_signal.size(-1), dtype=torch.int64, device=audio_signal.device - ) - - # select a random att_context_size with the distribution specified by att_context_probs during training - # for non-validation cases like test, validation or inference, it uses the first mode in self.att_context_size - if self.training and len(self.att_context_size_all) > 1: - cur_att_context_size = random.choices(self.att_context_size_all, weights=self.att_context_probs)[0] - else: - cur_att_context_size = self.att_context_size - - audio_signal = torch.transpose(audio_signal, 1, 2) - - if isinstance(self.pre_encode, nn.Linear): - audio_signal = self.pre_encode(audio_signal) - else: - audio_signal, length = self.pre_encode(x=audio_signal, lengths=length) - length = length.to(torch.int64) - # self.streaming_cfg is set by setup_streaming_cfg(), called in the init - if self.streaming_cfg.drop_extra_pre_encoded > 0 and cache_last_channel is not None: - audio_signal = audio_signal[:, self.streaming_cfg.drop_extra_pre_encoded :, :] - length = (length - self.streaming_cfg.drop_extra_pre_encoded).clamp(min=0) - - if self.reduction_position is not None and cache_last_channel is not None: - raise ValueError("Caching with reduction feature is not supported yet!") - - max_audio_length = audio_signal.size(1) - if cache_last_channel is not None: - cache_len = self.streaming_cfg.last_channel_cache_size - cache_keep_size = max_audio_length - self.streaming_cfg.cache_drop_size - max_audio_length = max_audio_length + cache_len - padding_length = length + cache_len - offset = torch.neg(cache_last_channel_len) + cache_len - else: - padding_length = length - cache_last_channel_next = None - cache_len = 0 - offset = None - - audio_signal, pos_emb = self.pos_enc(x=audio_signal, cache_len=cache_len) - - # Create the self-attention and padding masks - pad_mask, att_mask = self._create_masks( - att_context_size=cur_att_context_size, - padding_length=padding_length, - max_audio_length=max_audio_length, - offset=offset, - device=audio_signal.device, - ) - - if cache_last_channel is not None: - pad_mask = pad_mask[:, cache_len:] - if att_mask is not None: - att_mask = att_mask[:, cache_len:] - # Convert caches from the tensor to list - cache_last_time_next = [] - cache_last_channel_next = [] - - skip_connects = [] - - for lth, (drop_prob, (skip_combiner, layer)) in enumerate(zip(self.layer_drop_probs, self.layers)): - - if skip_combiner is None: - skip_connects.append(audio_signal) - else: - skip_connect = skip_connects.pop() * self.skip_connect_scale - audio_signal = torch.cat((audio_signal, skip_connect), dim=-1) - audio_signal = skip_combiner(audio_signal) - - original_signal = audio_signal - if cache_last_channel is not None: - cache_last_channel_cur = cache_last_channel[lth] - cache_last_time_cur = cache_last_time[lth] - else: - cache_last_channel_cur = None - cache_last_time_cur = None - - audio_signal = layer( - x=audio_signal, - att_mask=att_mask, - pos_emb=pos_emb, - pad_mask=pad_mask, - cache_last_channel=cache_last_channel_cur, - cache_last_time=cache_last_time_cur, - ) - - if cache_last_channel_cur is not None: - (audio_signal, cache_last_channel_cur, cache_last_time_cur) = audio_signal - cache_last_channel_next.append(cache_last_channel_cur) - cache_last_time_next.append(cache_last_time_cur) - - # applying stochastic depth logic from https://arxiv.org/abs/2102.03216 - if self.training and drop_prob > 0.0: - should_drop = torch.rand(1) < drop_prob - # adjusting to match expectation - if should_drop: - # that's not efficient, but it's hard to implement distributed - # version of dropping layers without deadlock or random seed meddling - # so multiplying the signal by 0 to ensure all weights get gradients - audio_signal = audio_signal * 0.0 + original_signal - else: - # not doing this operation if drop prob is 0 as it's identity in that case - audio_signal = (audio_signal - original_signal) / (1.0 - drop_prob) + original_signal - - if self.reduction_position == lth: - audio_signal, length = self.reduction_subsampling(x=audio_signal, lengths=length) - max_audio_length = audio_signal.size(1) - # Don't update the audio_signal here because then it will again scale the audio_signal - # and cause an increase in the WER - _, pos_emb = self.pos_enc(x=audio_signal, cache_len=cache_len) - pad_mask, att_mask = self._create_masks( - att_context_size=cur_att_context_size, - padding_length=length, - max_audio_length=max_audio_length, - offset=offset, - device=audio_signal.device, - ) - - # saving tensors if required for interctc loss - if self.is_access_enabled(getattr(self, "model_guid", None)): - if self.interctc_capture_at_layers is None: - self.interctc_capture_at_layers = self.access_cfg.get('interctc', {}).get('capture_layers', []) - if lth in self.interctc_capture_at_layers: - lth_audio_signal = audio_signal - if self.out_proj is not None: - lth_audio_signal = self.out_proj(audio_signal) - # shape is the same as the shape of audio_signal output, i.e. [B, D, T] - self.register_accessible_tensor( - name=f'interctc/layer_output_{lth}', tensor=torch.transpose(lth_audio_signal, 1, 2) - ) - self.register_accessible_tensor(name=f'interctc/layer_length_{lth}', tensor=length) - - if self.out_proj is not None: - audio_signal = self.out_proj(audio_signal) - - # Reduction - if self.reduction_position == -1: - audio_signal, length = self.reduction_subsampling(x=audio_signal, lengths=length) - - audio_signal = torch.transpose(audio_signal, 1, 2) - length = length.to(dtype=torch.int64) - - if cache_last_channel is not None: - cache_last_channel_next = torch.stack(cache_last_channel_next, dim=0) - cache_last_time_next = torch.stack(cache_last_time_next, dim=0) - return ( - audio_signal, - length, - cache_last_channel_next, - cache_last_time_next, - torch.clamp(cache_last_channel_len + cache_keep_size, max=cache_len), - ) - else: - return audio_signal, length - - -class SpectrogramConformerUNet(NeuralModule): - """A Conformer-based model for processing complex-valued spectrograms. - - This model processes complex-valued inputs by stacking real and imaginary components - along the channel dimension. The stacked tensor is processed using Conformer layers, - and the output is projected back to generate real and imaginary components of the - output channels. - - Args: - in_channels: number of input complex-valued channels - out_channels: number of output complex-valued channels - kwargs: additional arguments for ConformerEncoderUNet - """ - - def __init__(self, in_channels: int = 1, out_channels: int = 1, **kwargs): - super().__init__() - - # Number of input channels for this estimator - if in_channels < 1: - raise ValueError( - f'Number of input channels needs to be larger or equal to one, current value {in_channels}' - ) - - self.in_channels = in_channels - - # Number of output channels for this estimator - if out_channels < 1: - raise ValueError( - f'Number of output channels needs to be larger or equal to one, current value {out_channels}' - ) - - self.out_channels = out_channels - - # Conformer-based estimator - conformer_params = kwargs.copy() - conformer_params['feat_in'] = conformer_params['feat_out'] = ( - 2 * self.in_channels * kwargs['feat_in'] - ) # stack real and imag - logging.info('Conformer params: %s', conformer_params) - self.conformer = ConformerEncoderUNet(**conformer_params) - # logging.info(self.conformer) - - # Output projection to generate real and imaginary components of the output channels - self.output_projection = torch.nn.Conv2d( - in_channels=2 * self.in_channels, out_channels=2 * self.out_channels, kernel_size=1 - ) - - logging.debug('Initialized %s with', self.__class__.__name__) - logging.debug('\tin_channels: %s', self.in_channels) - logging.debug('\tout_channels: %s', self.out_channels) - - @property - def context_size(self): - """Returns the attention context size used by the conformer encoder. - - The context size is a list of two integers [left_context, right_context] that defines - how many frames to the left and right each frame can attend to in the self-attention - layers. - - Returns: - List[int]: The attention context size [left_context, right_context] - """ - return self.conformer.att_context_size - - @context_size.setter - def context_size(self, value): - """Sets the attention context size used by the conformer encoder. - - The context size is a list of two integers [left_context, right_context] that defines - how many frames to the left and right each frame can attend to in the self-attention - layers. - - Args: - value (List[int]): The attention context size [left_context, right_context] - """ - self.conformer.set_default_att_context_size(value) - - @property - def input_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "input": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "input_length": NeuralType(('B',), LengthsType(), optional=True), - # convolutional context - "cache_last_channel": NeuralType(('D', 'B', 'T', 'D'), ChannelType(), optional=True), - "cache_last_time": NeuralType(('D', 'B', 'D', 'T'), ChannelType(), optional=True), - "cache_last_channel_len": NeuralType(tuple('B'), LengthsType(), optional=True), - } - - @property - def output_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "output": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "output_length": NeuralType(('B',), LengthsType(), optional=True), - # convolutional context - "cache_last_channel_next": NeuralType(('D', 'B', 'T', 'D'), ChannelType(), optional=True), - "cache_last_time_next": NeuralType(('D', 'B', 'D', 'T'), ChannelType(), optional=True), - "cache_last_channel_next_len": NeuralType(tuple('B'), LengthsType(), optional=True), - } - - @typecheck() - def forward( - self, input, input_length=None, cache_last_channel=None, cache_last_time=None, cache_last_channel_len=None - ): - - # Stack real and imaginary components - B, C_in, D, T = input.shape - if C_in != self.in_channels: - raise RuntimeError(f'Unexpected input channel size {C_in}, expected {self.in_channels}') - - input_real_imag = torch.stack([input.real, input.imag], dim=2) - input = einops.rearrange(input_real_imag, 'B C RI D T -> B (C RI D) T') - - # Conformer - if cache_last_channel is None: - # Not using caching mode - output, output_length = self.conformer(audio_signal=input, length=input_length) - else: - # Using caching mode - output, output_length, cache_last_channel, cache_last_time, cache_last_channel_len = self.conformer( - audio_signal=input, - length=input_length, - cache_last_channel=cache_last_channel, - cache_last_time=cache_last_time, - cache_last_channel_len=cache_last_channel_len, - ) - - # Output projection - output = einops.rearrange(output, 'B (C RI D) T -> B (C RI) D T', C=self.in_channels, RI=2, D=D) - output = self.output_projection(output) - - # Convert to complex-valued signal - output = einops.rearrange(output, 'B (C RI) D T -> B C D T RI', C=self.out_channels, RI=2, D=D) - - # torch.view_as_complex doesn't support BFloat16, convert to float32 if needed - if output.dtype == torch.bfloat16: - output = output.float() - - output = torch.view_as_complex(output.contiguous()) - - if cache_last_channel is None: - return output, output_length - else: - return output, output_length, cache_last_channel, cache_last_time, cache_last_channel_len diff --git a/nemo/collections/audio/parts/submodules/diffusion.py b/nemo/collections/audio/parts/submodules/diffusion.py deleted file mode 100644 index 7a75943de686828b3df83abba442875c70a20982..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/parts/submodules/diffusion.py +++ /dev/null @@ -1,819 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from abc import ABC, abstractmethod -from typing import Optional, Tuple, Type - -import numpy as np -import torch - -from nemo.collections.common.parts.utils import mask_sequence_tensor -from nemo.core.classes import NeuralModule, typecheck -from nemo.core.neural_types import FloatType, LengthsType, NeuralType, SpectrogramType, VoidType -from nemo.utils import logging - - -class StochasticDifferentialEquation(NeuralModule, ABC): - """Base class for stochastic differential equations.""" - - def __init__(self, time_min: float, time_max: float, num_steps: int): - super().__init__() - - # min and max time - if time_min <= 0: - raise ValueError(f'time_min should be positive, current value {time_min}') - - if time_max <= time_min: - raise ValueError(f'time_max should be larger than time_min, current max {time_max} and min {time_min}') - - self.time_min = time_min - self.time_max = time_max - - # number of steps - if num_steps <= 0: - raise ValueError(f'num_steps needs to be positive: current value {num_steps}') - - self.num_steps = num_steps - - @property - def dt(self) -> float: - """Time step for this SDE. - This denotes the step size between `0` and `self.time_max` when using `self.num_steps`. - """ - return self.time_max / self.num_steps - - @property - def time_delta(self) -> float: - """Time range for this SDE.""" - return self.time_max - self.time_min - - def generate_time(self, size: int, device: torch.device) -> torch.Tensor: - """Generate random time steps in the valid range. - - Time steps are generated between `self.time_min` and `self.time_max`. - - Args: - size: number of samples - device: device to use - - Returns: - A tensor of floats with shape (size,) - """ - time = torch.rand(size, device=device) * self.time_delta + self.time_min - return time - - @abstractmethod - def coefficients(self, state: torch.Tensor, time: torch.Tensor, **kwargs) -> Tuple[torch.Tensor, torch.Tensor]: - """ - Args: - state: tensor of shape (B, C, D, T) - time: tensor of shape (B,) - - Returns: - Tuple with drift and diffusion coefficients. - """ - pass - - @typecheck( - input_types={ - "prior_mean": NeuralType(('B', 'C', 'D', 'T'), VoidType()), - }, - output_types={ - "sample": NeuralType(('B', 'C', 'D', 'T'), VoidType()), - }, - ) - @abstractmethod - def prior_sampling(self, prior_mean: torch.Tensor) -> torch.Tensor: - """Generate a sample from the prior distribution p_T. - - Args: - prior_mean: Mean of the prior distribution - - Returns: - A sample from the prior distribution. - """ - pass - - def discretize( - self, *, state: torch.Tensor, time: torch.Tensor, state_length: Optional[torch.Tensor] = None, **kwargs - ) -> Tuple[torch.Tensor, torch.Tensor]: - """Assume we have the following SDE: - - dx = drift(x, t) * dt + diffusion(x, t) * dwt - - where `wt` is the standard Wiener process. - - We assume the following discretization: - - new_state = current_state + total_drift + total_diffusion * z_norm - - where `z_norm` is sampled from normal distribution with zero mean and unit variance. - - Args: - state: current state of the process, shape (B, C, D, T) - time: current time of the process, shape (B,) - state_length: length of the valid time steps for each example in the batch, shape (B,) - **kwargs: other parameters - - Returns: - Drift and diffusion. - """ - # Get coefficients - drift_coefficient, diffusion_coefficient = self.coefficients( - state=state, time=time, state_length=state_length, **kwargs - ) - - # Discretized drift - drift = drift_coefficient * self.dt - - # Note: - # Scale with sqrt(dt) because z_norm is sampled from a normal distribution with zero mean and - # unit variance and dwt is normally distributed with zero mean and variance dt - diffusion = diffusion_coefficient * np.sqrt(self.dt) - - return drift, diffusion - - @abstractmethod - def copy(self): - """Create a copy of this SDE.""" - pass - - def __repr__(self): - desc = f'{self.__class__.__name__}(time_min={self.time_min}, time_max={self.time_max}, num_steps={self.num_steps})' - desc += f'\n\tdt: {self.dt}' - desc += f'\n\ttime_delta: {self.time_delta}' - return desc - - -class OrnsteinUhlenbeckVarianceExplodingSDE(StochasticDifferentialEquation): - """This class implements the Ornstein-Uhlenbeck SDE with variance exploding noise schedule. - - The SDE is given by: - - dx = theta * (y - x) dt + g(t) dw - - where `theta` is the stiffness parameter and `g(t)` is the diffusion coefficient: - - g(t) = std_min * (std_max/std_min)^t * sqrt(2 * log(std_max/std_min)) - - References: - Richter et al., Speech Enhancement and Dereverberation with Diffusion-based Generative Models, Tr. ASLP 2023 - """ - - def __init__( - self, - stiffness: float, - std_min: float, - std_max: float, - num_steps: int = 100, - time_min: float = 3e-2, - time_max: float = 1.0, - eps: float = 1e-8, - ): - super().__init__(time_min=time_min, time_max=time_max, num_steps=num_steps) - - # Small regularization - if eps <= 0: - raise ValueError(f'eps should be positive, current value {eps}') - self.eps = eps - - # stifness - self.stiffness = stiffness - - # noise schedule - if std_min <= 0: - raise ValueError(f'std_min should be positive, current value {std_min}') - - if std_max <= std_min: - raise ValueError(f'std_max should be larger than std_min, current max {std_max} and min {std_min}') - - self.std_min = std_min - self.std_max = std_max - - logging.debug('Initialized %s with', self.__class__.__name__) - logging.debug('\tstiffness: %s', self.stiffness) - logging.debug('\tstd_min: %s', self.std_min) - logging.debug('\tstd_max: %s', self.std_max) - logging.debug('\tnum_steps: %s', self.num_steps) - logging.debug('\ttime_min: %s', self.time_min) - logging.debug('\ttime_max: %s', self.time_max) - logging.debug('\teps: %s', self.eps) - - @property - def std_ratio(self) -> float: - return self.std_max / (self.std_min + self.eps) - - @property - def log_std_ratio(self) -> float: - return np.log(self.std_ratio + self.eps) - - @typecheck( - input_types={ - "state": NeuralType(('B', 'C', 'D', 'T'), VoidType()), - "prior_mean": NeuralType(('B', 'C', 'D', 'T'), VoidType()), - "time": NeuralType(tuple('B'), FloatType()), - }, - output_types={ - "mean": NeuralType(('B', 'C', 'D', 'T'), FloatType()), - }, - ) - def perturb_kernel_mean(self, state: torch.Tensor, prior_mean: torch.Tensor, time: torch.Tensor) -> torch.Tensor: - """Return the mean of the perturbation kernel for this SDE. - - Args: - state: current state of the process, shape (B, C, D, T) - prior_mean: mean of the prior distribution - time: current time of the process, shape (B,) - - Returns: - A tensor of shape (B, C, D, T) - """ - # exponential weighting - weight = torch.exp(-self.stiffness * time) - - # view as [B, C, D, T] - weight = weight.view(-1, 1, 1, 1) - - # closed-form mean - mean = weight * state + (1 - weight) * prior_mean - - return mean - - @typecheck( - input_types={ - "time": NeuralType(tuple('B'), FloatType()), - }, - output_types={ - "std": NeuralType(tuple('B'), FloatType()), - }, - ) - def perturb_kernel_std(self, time: torch.Tensor) -> torch.Tensor: - """Return the standard deviation of the perturbation kernel for this SDE. - - Note that the standard deviation depends on the time and the noise schedule, - which is parametrized using `self.stiffness`, `self.std_min` and `self.std_max`. - - Args: - time: current time of the process, shape (B,) - - Returns: - A tensor of shape (B,) - """ - var = (self.std_min**2) * self.log_std_ratio - var *= torch.pow(self.std_ratio, 2 * time) - torch.exp(-2 * self.stiffness * time) - var /= self.stiffness + self.log_std_ratio - std = torch.sqrt(var) - return std - - @typecheck( - input_types={ - "state": NeuralType(('B', 'C', 'D', 'T'), VoidType()), - "prior_mean": NeuralType(('B', 'C', 'D', 'T'), VoidType()), - "time": NeuralType(tuple('B'), FloatType()), - }, - output_types={ - "mean": NeuralType(('B', 'C', 'D', 'T'), FloatType()), - "std": NeuralType(('B', 'C', 'D', 'T'), FloatType()), - }, - ) - def perturb_kernel_params(self, state: torch.Tensor, prior_mean: torch.Tensor, time: torch.Tensor) -> torch.Tensor: - """Return the mean and standard deviation of the perturbation kernel for this SDE. - - Args: - state: current state of the process, shape (B, C, D, T) - prior_mean: mean of the prior distribution - time: current time of the process, shape (B,) - """ - assert torch.all(time <= self.time_max) - assert torch.all(time >= self.time_min) - - # compute the mean - mean = self.perturb_kernel_mean(state=state, prior_mean=prior_mean, time=time) - - # compute the standard deviation - std = self.perturb_kernel_std(time=time) - # view as [B, C, D, T] - std = std.view(-1, 1, 1, 1) - - return mean, std - - @typecheck( - input_types={ - "state": NeuralType(('B', 'C', 'D', 'T'), VoidType()), - "time": NeuralType(tuple('B'), VoidType()), - "prior_mean": NeuralType(('B', 'C', 'D', 'T'), VoidType()), - "state_length": NeuralType(tuple('B'), LengthsType(), optional=True), - }, - output_types={ - "drift_coefficient": NeuralType(('B', 'C', 'D', 'T'), FloatType()), - "diffusion_coefficient": NeuralType(('B', 'C', 'D', 'T'), FloatType()), - }, - ) - def coefficients( - self, - state: torch.Tensor, - time: torch.Tensor, - prior_mean: torch.Tensor, - state_length: Optional[torch.Tensor] = None, - ) -> Tuple[torch.Tensor, torch.Tensor]: - """Compute drift and diffusion coefficients for this SDE. - - Args: - state: current state of the process, shape (B, C, D, T) - time: current time of the process, shape (B,) - prior_mean: mean of the prior distribution - state_length: length of the valid time steps for each example in the batch - - Returns: - Drift and diffusion coefficients. - """ - # Drift coefficient - drift_coefficient = self.stiffness * (prior_mean - state) - - # Diffusion coefficient - diffusion_coefficient = self.std_min * torch.pow(self.std_ratio, time) * np.sqrt(2 * self.log_std_ratio) - # View in the same shape as the state - diffusion_coefficient = diffusion_coefficient.view(-1, *([1] * (state.dim() - 1))) - - if state_length is not None: - drift_coefficient = mask_sequence_tensor(drift_coefficient, state_length) - diffusion_coefficient = mask_sequence_tensor(diffusion_coefficient, state_length) - - return drift_coefficient, diffusion_coefficient - - def prior_sampling(self, prior_mean: torch.Tensor) -> torch.Tensor: - """Generate a sample from the prior distribution p_T. - - Args: - prior_mean: Mean of the prior distribution - """ - # Final time step for all samples in the batch - time = self.time_max * torch.ones(prior_mean.shape[0], device=prior_mean.device) - - # Compute the std of the prior distribution - std = self.perturb_kernel_std(time=time) - - # view as [B, C, D, T] - std = std.view(-1, 1, 1, 1) - - # Generate a sample from a normal distribution centered at prior_mean - sample = prior_mean + torch.randn_like(prior_mean) * std - - return sample - - def copy(self): - return OrnsteinUhlenbeckVarianceExplodingSDE( - stiffness=self.stiffness, - std_min=self.std_min, - std_max=self.std_max, - num_steps=self.num_steps, - time_min=self.time_min, - time_max=self.time_max, - eps=self.eps, - ) - - def __repr__(self): - desc = f'{self.__class__.__name__}(stiffness={self.stiffness}, std_min={self.std_min}, std_max={self.std_max}, num_steps={self.num_steps}, time_min={self.time_min}, time_max={self.time_max}, eps={self.eps})' - desc += f'\n\tdt: {self.dt}' - desc += f'\n\ttime_delta: {self.time_delta}' - desc += f'\n\tstd_ratio: {self.std_ratio}' - desc += f'\n\tlog_std_ratio: {self.log_std_ratio}' - - return desc - - -class ReverseStochasticDifferentialEquation(StochasticDifferentialEquation): - def __init__(self, *, sde: Type[StochasticDifferentialEquation], score_estimator: Type[NeuralModule]): - """Use the forward SDE and a score estimator to define the reverse SDE. - - Args: - sde: forward SDE - score_estimator: neural score estimator - """ - super().__init__(time_min=sde.time_min, time_max=sde.time_max, num_steps=sde.num_steps) - self.score_estimator = score_estimator - self.forward_sde = sde - - logging.debug('Initialized %s', self.__class__.__name__) - - def coefficients( - self, - state: torch.Tensor, - time: torch.Tensor, - score_condition: Optional[torch.Tensor] = None, - state_length: Optional[torch.Tensor] = None, - **kwargs, - ) -> Tuple[torch.Tensor, torch.Tensor]: - """Compute drift and diffusion coefficients for the reverse SDE. - - Args: - state: current state of the process, shape (B, C, D, T) - time: current time of the process, shape (B,) - """ - raise NotImplementedError('Coefficients not necessary for the reverse SDE.') - - def prior_sampling(self, shape: torch.Size, device: torch.device) -> torch.Tensor: - """Prior sampling is not necessary for the reverse SDE.""" - raise NotImplementedError('Prior sampling not necessary for the reverse SDE.') - - def discretize( - self, - *, - state: torch.Tensor, - time: torch.Tensor, - score_condition: Optional[torch.Tensor] = None, - state_length: Optional[torch.Tensor] = None, - **kwargs, - ) -> Tuple[torch.Tensor, torch.Tensor]: - """Discretize the reverse SDE. - - Args: - state: current state of the process, shape (B, C, D, T) - time: current time of the process, shape (B,) - score_condition: condition for the score estimator - state_length: length of the valid time steps for each example in the batch - **kwargs: other parameters for discretization of the forward SDE - """ - # Drift and diffusion from the forward SDE - forward_drift, forward_diffusion = self.forward_sde.discretize(state=state, time=time, **kwargs) - - # For input for the score estimator: - # - if no condition is provided, use the state - # - if a condition is provided, concatenate the state and the condition along the channel dimension - score_input = state if score_condition is None else torch.cat([state, score_condition], dim=1) - - # Estimate score - score, _ = self.score_estimator(input=score_input, input_length=state_length, condition=time) - - # Adjust drift - drift = forward_drift - forward_diffusion.pow(2) * score - - # Adjust diffusion - diffusion = forward_diffusion - - if state_length is not None: - drift = mask_sequence_tensor(drift, state_length) - diffusion = mask_sequence_tensor(diffusion, state_length) - - return drift, diffusion - - def copy(self): - return ReverseStochasticDifferentialEquation(sde=self.forward_sde.copy(), score_estimator=self.score_estimator) - - def __repr__(self): - desc = f'{self.__class__.__name__}(sde={self.forward_sde}, score_estimator={self.score_estimator})' - return desc - - -class PredictorCorrectorSampler(NeuralModule): - """Predictor-Corrector sampler for the reverse SDE. - - Args: - sde: forward SDE - score_estimator: neural score estimator - predictor: predictor for the reverse process - corrector: corrector for the reverse process - num_steps: number of time steps for the reverse process - num_corrector_steps: number of corrector steps - time_max: maximum time - time_min: minimum time - snr: SNR for Annealed Langevin Dynamics - output_type: type of the output ('state' for the final state, or 'mean' for the mean of the final state) - - References: - - Song et al., Score-based generative modeling through stochastic differential equations, 2021 - """ - - def __init__( - self, - sde, - score_estimator, - predictor: str = 'reverse_diffusion', - corrector: str = 'annealed_langevin_dynamics', - num_steps: int = 50, - num_corrector_steps: int = 1, - time_max: Optional[float] = None, - time_min: Optional[float] = None, - snr: float = 0.5, - output_type: str = 'mean', - ): - super().__init__() - # Create a copy of SDE - self.sde = sde.copy() - - # Update SDE parameters for sampling - if time_max is not None: - self.sde.time_max = time_max - logging.info('sde.time_max set to: %s', self.sde.time_max) - - if time_min is not None: - self.sde.time_min = time_min - logging.info('sde.time_min set to: %s', self.sde.time_min) - - self.sde.num_steps = num_steps - logging.info('sde.num_steps set to: %s', self.sde.num_steps) - - # Update local values - self.time_max = self.sde.time_max - self.time_min = self.sde.time_min - self.num_steps = self.sde.num_steps - - # Predictor setup - if predictor == 'reverse_diffusion': - self.predictor = ReverseDiffusionPredictor(sde=self.sde, score_estimator=score_estimator) - else: - raise RuntimeError(f'Unexpected predictor: {predictor}') - - # Corrector setup - if corrector == 'annealed_langevin_dynamics': - self.corrector = AnnealedLangevinDynamics( - sde=self.sde, score_estimator=score_estimator, snr=snr, num_steps=num_corrector_steps - ) - else: - raise RuntimeError(f'Unexpected corrector: {corrector}') - - if output_type not in ['mean', 'state']: - raise ValueError(f'Unexpected output type: {output_type}') - self.output_type = output_type - - logging.debug('Initialized %s with', self.__class__.__name__) - logging.debug('\tpredictor: %s', predictor) - logging.debug('\tcorrector: %s', corrector) - logging.debug('\tnum_steps: %s', self.num_steps) - logging.debug('\ttime_min: %s', self.time_min) - logging.debug('\ttime_max: %s', self.time_max) - logging.debug('\tnum_corrector_steps: %s', num_corrector_steps) - logging.debug('\tsnr: %s', snr) - logging.debug('\toutput_type: %s', self.output_type) - - @typecheck( - input_types={ - "prior_mean": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "score_condition": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType(), optional=True), - "state_length": NeuralType(tuple('B'), LengthsType(), optional=True), - }, - output_types={ - "sample": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "state_length": NeuralType(tuple('B'), LengthsType(), optional=True), - }, - ) - @torch.inference_mode() - def forward( - self, prior_mean: torch.Tensor, score_condition: torch.Tensor, state_length: Optional[torch.Tensor] = None - ) -> torch.Tensor: - """Takes prior (noisy) mean and generates a sample by solving the reverse SDE. - - Args: - prior_mean: mean for the prior distribution, e.g., noisy observation - score_condition: conditioning for the score estimator - state_length: length of the valid time steps for each example in the batch - - Returns: - Generated `sample` and the corresponding `sample_length`. - """ - # Sample from the prior distribution - state = self.sde.prior_sampling(prior_mean=prior_mean) - - if state_length is not None: - state = mask_sequence_tensor(state, state_length) - - # Time steps for evaluation - time_steps = torch.linspace(self.time_max, self.time_min, self.num_steps, device=state.device) - - # Sampling - for t in time_steps: - # time steps for the whole batch - time = t * torch.ones(state.shape[0], device=state.device) - - # corrector step - state, _ = self.corrector( - state=state, time=time, score_condition=score_condition, state_length=state_length - ) - - # predictor step - state, state_mean = self.predictor( - state=state, - time=time, - score_condition=score_condition, - prior_mean=prior_mean, - state_length=state_length, - ) - - # Final output - if self.output_type == 'state': - sample = state - elif self.output_type == 'mean': - sample = state_mean - else: - raise RuntimeError(f'Unexpected output type: {self.output_type}') - - if state_length is not None: - sample = mask_sequence_tensor(sample, state_length) - - return sample, state_length - - -class Predictor(torch.nn.Module, ABC): - """Predictor for the reverse process. - - Args: - sde: forward SDE - score_estimator: neural score estimator - """ - - def __init__(self, sde, score_estimator): - super().__init__() - self.reverse_sde = ReverseStochasticDifferentialEquation(sde=sde, score_estimator=score_estimator) - - @abstractmethod - @torch.inference_mode() - def forward( - self, - *, - state: torch.Tensor, - time: torch.Tensor, - score_condition: Optional[torch.Tensor] = None, - state_length: Optional[torch.Tensor] = None, - **kwargs, - ): - """Predict the next state of the reverse process. - - Args: - state: current state of the process, shape (B, C, D, T) - time: current time of the process, shape (B,) - score_condition: conditioning for the score estimator - state_length: length of the valid time steps for each example in the batch - - Returns: - New state and mean. - """ - pass - - -class ReverseDiffusionPredictor(Predictor): - """Predict the next state of the reverse process using the reverse diffusion process. - - Args: - sde: forward SDE - score_estimator: neural score estimator - """ - - def __init__(self, sde, score_estimator): - super().__init__(sde=sde, score_estimator=score_estimator) - - @torch.inference_mode() - def forward(self, *, state, time, score_condition=None, state_length=None, **kwargs): - """Predict the next state of the reverse process using the reverse diffusion process. - - Args: - state: current state of the process, shape (B, C, D, T) - time: current time of the process, shape (B,) - score_condition: conditioning for the score estimator - state_length: length of the valid time steps for each example in the batch - - Returns: - New state and mean of the diffusion process. - """ - drift, diffusion = self.reverse_sde.discretize( - state=state, time=time, score_condition=score_condition, state_length=state_length, **kwargs - ) - - # Generate a random sample from a standard normal distribution - z_norm = torch.randn_like(state) - - # Compute the mean of the next state - mean = state - drift - - # Compute new state by sampling - new_state = mean + diffusion * z_norm - - if state_length is not None: - new_state = mask_sequence_tensor(new_state, state_length) - mean = mask_sequence_tensor(mean, state_length) - - return new_state, mean - - -class Corrector(NeuralModule, ABC): - """Corrector for the reverse process. - - Args: - sde: forward SDE - score_estimator: neural score estimator - snr: SNR for Annealed Langevin Dynamics - num_steps: number of steps for the corrector - """ - - def __init__( - self, - sde: Type[StochasticDifferentialEquation], - score_estimator: Type[NeuralModule], - snr: float, - num_steps: int, - ): - super().__init__() - self.sde = sde - self.score_estimator = score_estimator - self.snr = snr - self.num_steps = num_steps - - logging.debug('Initialized %s with', self.__class__.__name__) - logging.debug('\tsnr: %s', snr) - logging.debug('\tnum_steps: %s', num_steps) - - @abstractmethod - @typecheck( - input_types={ - "state": NeuralType(('B', 'C', 'D', 'T'), VoidType()), - "time": NeuralType(tuple('B'), FloatType()), - "score_condition": NeuralType(('B', 'C', 'D', 'T'), VoidType(), optional=True), - "state_length": NeuralType(tuple('B'), LengthsType(), optional=True), - }, - output_types={ - "state": NeuralType(('B', 'C', 'D', 'T'), VoidType()), - }, - ) - @torch.inference_mode() - def forward(self, state, time, score_condition=None, state_length=None): - """ - Args: - state: current state of the process, shape (B, C, D, T) - time: current time of the process, shape (B,) - score_condition: conditioning for the score estimator - state_length: length of the valid time steps for each example in the batch - - Returns: - New state and mean. - """ - pass - - -class AnnealedLangevinDynamics(Corrector): - """Annealed Langevin Dynamics for the reverse process. - - References: - - Song et al., Score-based generative modeling through stochastic differential equations, 2021 - """ - - def __init__(self, sde, **kwargs): - if not isinstance(sde, OrnsteinUhlenbeckVarianceExplodingSDE): - raise ValueError(f'Expected an instance of OrnsteinUhlenbeckVarianceExplodingSDE, got {type(sde)}') - super().__init__(sde=sde, **kwargs) - - @torch.inference_mode() - def forward(self, state, time, score_condition=None, state_length=None): - """Correct the state using Annealed Langevin Dynamics. - - Args: - state: current state of the process, shape (B, C, D, T) - time: current time of the process, shape (B,) - score_condition: conditioning for the score estimator - state_length: length of the valid time steps for each example in the batch - - Returns: - New state and mean of the diffusion process. - - References: - Alg. 4 in http://arxiv.org/abs/2011.13456 - """ - # Compute the standard deviation of the diffusion process - std = self.sde.perturb_kernel_std(time=time) - # View as [B, 1, 1, 1] - std = std.view(-1, *([1] * (state.dim() - 1))) - - for i in range(self.num_steps): - # prepare input for the score estimator, concatenate conditioning along the channel dimension - score_input = state if score_condition is None else torch.cat([state, score_condition], dim=1) - - # calculate the score - score, _ = self.score_estimator(input=score_input, input_length=state_length, condition=time) - - # generate a sample from a standard normal distribution - z_norm = torch.randn_like(state) - - # compute the step size - # note: this is slightly different than in the paper, where std = ||z_norm||_2 / ||score||_2 - step_size = 2 * (self.snr * std).pow(2) - - # update the mean - mean = state + step_size * score - - # update the state - state = mean + z_norm * torch.sqrt(step_size * 2) - - if state_length is not None: - state = mask_sequence_tensor(state, state_length) - mean = mask_sequence_tensor(mean, state_length) - - return state, mean diff --git a/nemo/collections/audio/parts/submodules/flow.py b/nemo/collections/audio/parts/submodules/flow.py deleted file mode 100644 index 924bfd06667f815071a9ad26fa7c18eb3d270b99..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/parts/submodules/flow.py +++ /dev/null @@ -1,269 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -from abc import ABC, abstractmethod -from typing import Literal, Tuple - -import einops -import torch - -from nemo.collections.common.parts.utils import mask_sequence_tensor -from nemo.utils import logging - -ESTIMATOR_TARGET = Literal['conditional_vector_field', 'data'] - - -class ConditionalFlow(ABC): - """ - Abstract class for different conditional flow-matching (CFM) classes - - Time horizon is [time_min, time_max (should be 1)] - - every path is "conditioned" on endpoints of the path - endpoints are just our paired data samples - subclasses need to implement mean, std, and vector_field - - """ - - def __init__(self, time_min: float = 1e-8, time_max: float = 1.0): - self.time_min = time_min - self.time_max = time_max - - @abstractmethod - def mean(self, *, time: torch.Tensor, x_start: torch.Tensor, x_end: torch.Tensor) -> torch.Tensor: - """ - Return the mean of p_t(x | x_start, x_end) at time t - """ - pass - - @abstractmethod - def std(self, *, time: torch.Tensor, x_start: torch.Tensor, x_end: torch.Tensor) -> torch.Tensor: - """ - Return the standard deviation of p_t(x | x_start, x_end) at time t - """ - pass - - @abstractmethod - def vector_field( - self, *, time: torch.Tensor, x_start: torch.Tensor, x_end: torch.Tensor, point: torch.Tensor - ) -> torch.Tensor: - """ - Compute the conditional vector field v_t( point | x_start, x_end) - """ - pass - - @staticmethod - def _broadcast_time(time: torch.Tensor, n_dim: int) -> torch.Tensor: - """ - Broadcast time tensor to the desired number of dimensions - """ - if time.ndim == 1: - target_shape = ' '.join(['B'] + ['1'] * (n_dim - 1)) - time = einops.rearrange(time, f'B -> {target_shape}') - - return time - - def generate_time(self, batch_size: int, rng: torch.random.Generator = None) -> torch.Tensor: - """ - Randomly sample a batchsize of time_steps from U[self.time_min, self.time_max] - Supports an external random number generator for better reproducibility - """ - return torch.rand((batch_size,), generator=rng) * (self.time_max - self.time_min) + self.time_min - - def sample(self, *, time: torch.Tensor, x_start: torch.Tensor, x_end: torch.Tensor) -> torch.Tensor: - """ - Generate a sample from p_t(x | x_start, x_end) at time t. - Note that this implementation assumes all path marginals are normally distributed. - """ - time = self._broadcast_time(time, n_dim=x_start.ndim) - - mean = self.mean(time=time, x_start=x_start, x_end=x_end) - std = self.std(time=time, x_start=x_start, x_end=x_end) - return mean + std * torch.randn_like(mean) - - def flow( - self, *, time: torch.Tensor, x_start: torch.Tensor, x_end: torch.Tensor, point: torch.Tensor - ) -> torch.Tensor: - """ - Compute the conditional flow phi_t( point | x_start, x_end). - This is an affine flow. - """ - mean = self.mean(time=time, x_start=x_start, x_end=x_end) - std = self.std(time=time, x_start=x_start, x_end=x_end) - return mean + std * (point - x_start) - - -class OptimalTransportFlow(ConditionalFlow): - """The OT-CFM model from [Lipman et at, 2023] - - Every conditional path the following holds: - p_0 = N(x_start, sigma_start) - p_1 = N(x_end, sigma_end), - - mean(x, t) = (time_max - t) * x_start + t * x_end - (linear interpolation between x_start and x_end) - - std(x, t) = (time_max - t) * sigma_start + t * sigma_end - - Every conditional path is optimal transport map from p_0(x_start, x_end) to p_1(x_start, x_end) - Marginal path is not guaranteed to be an optimal transport map from p_0 to p_1 - - To get the OT-CFM model from [Lipman et at, 2023] just pass zeroes for x_start - To get the I-CFM model, set sigma_min=sigma_max - To get the rectified flow model, set sigma_min=sigma_max=0 - - Args: - time_min: minimum time value used in the process - time_max: maximum time value used in the process - sigma_start: the standard deviation of the initial distribution - sigma_end: the standard deviation of the target distribution - """ - - def __init__( - self, time_min: float = 1e-8, time_max: float = 1.0, sigma_start: float = 1.0, sigma_end: float = 1e-4 - ): - super().__init__(time_min=time_min, time_max=time_max) - self.sigma_start = sigma_start - self.sigma_end = sigma_end - - logging.debug('Initialized %s with', self.__class__.__name__) - logging.debug('\ttime_min: %s', self.time_min) - logging.debug('\ttime_max: %s', self.time_max) - logging.debug('\tsgima_start: %s', self.sigma_start) - logging.debug('\tsigma_end: %s', self.sigma_end) - - def mean(self, *, x_start: torch.Tensor, x_end: torch.Tensor, time: torch.Tensor) -> torch.Tensor: - return (self.time_max - time) * x_start + time * x_end - - def std(self, *, x_start: torch.Tensor, x_end: torch.Tensor, time: torch.Tensor) -> torch.Tensor: - return (self.time_max - time) * self.sigma_start + time * self.sigma_end - - def vector_field( - self, - *, - x_start: torch.Tensor, - x_end: torch.Tensor, - time: torch.Tensor, - point: torch.Tensor, - eps: float = 1e-6, - ) -> torch.Tensor: - time = self._broadcast_time(time, n_dim=x_start.ndim) - - if self.sigma_start == self.sigma_end: - return x_end - x_start - - num = self.sigma_end * (point - x_start) - self.sigma_start * (point - x_end) - denom = (1 - time) * self.sigma_start + time * self.sigma_end - return num / (denom + eps) - - -class ConditionalFlowMatchingSampler(ABC): - """ - Abstract class for different sampler to solve the ODE in CFM - - Args: - estimator: the NN-based conditional vector field estimator - num_steps: How many time steps to iterate in the process - time_min: minimum time value used in the process - time_max: maximum time value used in the process - - """ - - def __init__( - self, - estimator: torch.nn.Module, - num_steps: int = 5, - time_min: float = 1e-8, - time_max: float = 1.0, - ): - self.estimator = estimator - self.num_steps = num_steps - self.time_min = time_min - self.time_max = time_max - - @property - def time_step(self): - return (self.time_max - self.time_min) / self.num_steps - - @abstractmethod - def forward( - self, state: torch.Tensor, estimator_condition: torch.Tensor, state_length: torch.Tensor - ) -> Tuple[torch.Tensor, torch.Tensor]: - pass - - -class ConditionalFlowMatchingEulerSampler(ConditionalFlowMatchingSampler): - """ - The Euler Sampler for solving the ODE in CFM on a uniform time grid - """ - - def __init__( - self, - estimator: torch.nn.Module, - num_steps: int = 5, - time_min: float = 1e-8, - time_max: float = 1.0, - estimator_target: ESTIMATOR_TARGET = 'conditional_vector_field', - flow: ConditionalFlow = None, - ): - super().__init__( - estimator=estimator, - num_steps=num_steps, - time_min=time_min, - time_max=time_max, - ) - self.estimator_target = estimator_target - if self.estimator_target == 'data' and flow is None: - raise ValueError('Flow is required for estimator_target=data') - self.flow = flow - - logging.debug('Initialized %s with', self.__class__.__name__) - logging.debug('\tnum_steps: %s', self.num_steps) - logging.debug('\ttime_min: %s', self.time_min) - logging.debug('\ttime_max: %s', self.time_max) - logging.debug('\testimator_target: %s', self.estimator_target) - logging.debug('\tflow: %s', self.flow) - - def __call__(self, *args, **kwargs): - return self.forward(*args, **kwargs) - - @torch.inference_mode() - def forward( - self, state: torch.Tensor, estimator_condition: torch.Tensor, state_length: torch.Tensor - ) -> Tuple[torch.Tensor, torch.Tensor]: - time_steps = torch.linspace(self.time_min, self.time_max, self.num_steps + 1) - - if state_length is not None: - state = mask_sequence_tensor(state, state_length) - - init_state = state.clone() - for t in time_steps[:-1]: - time = t * torch.ones(state.shape[0], device=state.device) - - if estimator_condition is None: - estimator_input = state - else: - estimator_input = torch.cat([state, estimator_condition], dim=1) - - if self.estimator_target == 'conditional_vector_field': - vector_field, _ = self.estimator(input=estimator_input, input_length=state_length, condition=time) - state = state + vector_field * self.time_step - elif self.estimator_target == 'data': - endpoint, _ = self.estimator(input=estimator_input, input_length=state_length, condition=time) - vector_field = self.flow.vector_field(time=time, x_start=init_state, x_end=endpoint, point=state) - state = state + vector_field * self.time_step - - if state_length is not None: - state = mask_sequence_tensor(state, state_length) - - return state, state_length diff --git a/nemo/collections/audio/parts/submodules/multichannel.py b/nemo/collections/audio/parts/submodules/multichannel.py deleted file mode 100644 index 407e9a3fe03db6ebc3ccaf525280cbdc761e0350..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/parts/submodules/multichannel.py +++ /dev/null @@ -1,1034 +0,0 @@ -# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import random -from typing import Callable, Dict, Optional, Tuple - -import numpy as np -import torch - -from nemo.collections.asr.parts.preprocessing.features import make_seq_mask_like -from nemo.collections.asr.parts.submodules.multi_head_attention import MultiHeadAttention -from nemo.collections.audio.parts.utils.audio import covariance_matrix -from nemo.core.classes import NeuralModule, typecheck -from nemo.core.neural_types import AudioSignal, FloatType, LengthsType, NeuralType, SpectrogramType -from nemo.utils import logging - - -class ChannelAugment(NeuralModule): - """Randomly permute and selects a subset of channels. - - Args: - permute_channels (bool): Apply a random permutation of channels. - num_channels_min (int): Minimum number of channels to select. - num_channels_max (int): Max number of channels to select. - rng: Optional, random generator. - seed: Optional, seed for the generator. - """ - - def __init__( - self, - permute_channels: bool = True, - num_channels_min: int = 1, - num_channels_max: Optional[int] = None, - rng: Optional[Callable] = None, - seed: Optional[int] = None, - ): - super().__init__() - - self._rng = random.Random(seed) if rng is None else rng - self.permute_channels = permute_channels - self.num_channels_min = num_channels_min - self.num_channels_max = num_channels_max - - if num_channels_max is not None and num_channels_min > num_channels_max: - raise ValueError( - f'Min number of channels {num_channels_min} cannot be greater than max number of channels {num_channels_max}' - ) - - logging.debug('Initialized %s with', self.__class__.__name__) - logging.debug('\tpermute_channels: %s', self.permute_channels) - logging.debug('\tnum_channels_min: %s', self.num_channels_min) - logging.debug('\tnum_channels_max: %s', self.num_channels_max) - - @property - def input_types(self): - """Returns definitions of module input types""" - return { - 'input': NeuralType(('B', 'C', 'T'), AudioSignal()), - } - - @property - def output_types(self): - """Returns definitions of module output types""" - return { - 'output': NeuralType(('B', 'C', 'T'), AudioSignal()), - } - - @typecheck() - @torch.no_grad() - def forward(self, input: torch.Tensor) -> torch.Tensor: - # Expecting (B, C, T) - assert input.ndim == 3, 'Expecting input with shape (B, C, T)' - num_channels_in = input.size(1) - - if num_channels_in < self.num_channels_min: - raise RuntimeError( - f'Number of input channels ({num_channels_in}) is smaller than the min number of output channels ({self.num_channels_min})' - ) - - num_channels_max = num_channels_in if self.num_channels_max is None else self.num_channels_max - num_channels_out = self._rng.randint(self.num_channels_min, num_channels_max) - - channels = list(range(num_channels_in)) - - if self.permute_channels: - self._rng.shuffle(channels) - - channels = channels[:num_channels_out] - - return input[:, channels, :] - - -class TransformAverageConcatenate(NeuralModule): - """Apply transform-average-concatenate across channels. - We're using a version from [2]. - - Args: - in_features: Number of input features - out_features: Number of output features - - References: - [1] Luo et al, End-to-end Microphone Permutation and Number Invariant Multi-channel Speech Separation, 2019 - [2] Yoshioka et al, VarArray: Array-Geometry-Agnostic Continuous Speech Separation, 2022 - """ - - def __init__(self, in_features: int, out_features: Optional[int] = None): - super().__init__() - - if out_features is None: - out_features = in_features - - # Parametrize with the total number of features (needs to be divisible by two due to stacking) - if out_features % 2 != 0: - raise ValueError(f'Number of output features should be divisible by two, currently set to {out_features}') - - self.transform_channel = torch.nn.Sequential( - torch.nn.Linear(in_features, out_features // 2, bias=False), torch.nn.ReLU() - ) - self.transform_average = torch.nn.Sequential( - torch.nn.Linear(in_features, out_features // 2, bias=False), torch.nn.ReLU() - ) - - logging.debug('Initialized %s with', self.__class__.__name__) - logging.debug('\tin_features: %d', in_features) - logging.debug('\tout_features: %d', out_features) - - @property - def input_types(self): - """Returns definitions of module input types""" - return { - 'input': NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - } - - @property - def output_types(self): - """Returns definitions of module output types""" - return { - 'output': NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - } - - @typecheck() - def forward(self, input: torch.Tensor) -> torch.Tensor: - """ - Args: - input: shape (B, M, in_features, T) - - Returns: - Output tensor with shape shape (B, M, out_features, T) - """ - B, M, F, T = input.shape - - # (B, M, F, T) -> (B, T, M, F) - input = input.permute(0, 3, 1, 2) - - # transform and average across channels - average = self.transform_average(input) - average = torch.mean(average, dim=-2, keepdim=True) - # view with the number of channels expanded to M - average = average.expand(-1, -1, M, -1) - - # transform each channel - transform = self.transform_channel(input) - - # concatenate along feature dimension - output = torch.cat([transform, average], dim=-1) - - # Return to the original layout - # (B, T, M, F) -> (B, M, F, T) - output = output.permute(0, 2, 3, 1) - - return output - - -class TransformAttendConcatenate(NeuralModule): - """Apply transform-attend-concatenate across channels. - The output is a concatenation of transformed channel and MHA - over channels. - - Args: - in_features: Number of input features - out_features: Number of output features - n_head: Number of heads for the MHA module - dropout_rate: Dropout rate for the MHA module - - References: - - Jukić et al, Flexible multichannel speech enhancement for noise-robust frontend, 2023 - """ - - def __init__(self, in_features: int, out_features: Optional[int] = None, n_head: int = 4, dropout_rate: float = 0): - super().__init__() - - if out_features is None: - out_features = in_features - - # Parametrize with the total number of features (needs to be divisible by two due to stacking) - if out_features % 2 != 0: - raise ValueError(f'Number of output features should be divisible by two, currently set to {out_features}') - - self.transform_channel = torch.nn.Sequential( - torch.nn.Linear(in_features, out_features // 2, bias=False), torch.nn.ReLU() - ) - self.transform_attend = torch.nn.Sequential( - torch.nn.Linear(in_features, out_features // 2, bias=False), torch.nn.ReLU() - ) - self.attention = MultiHeadAttention(n_head=n_head, n_feat=out_features // 2, dropout_rate=dropout_rate) - - logging.debug('Initialized %s with', self.__class__.__name__) - logging.debug('\tin_features: %d', in_features) - logging.debug('\tout_features: %d', out_features) - logging.debug('\tn_head: %d', n_head) - logging.debug('\tdropout_rate: %f', dropout_rate) - - @property - def input_types(self): - """Returns definitions of module input types""" - return { - 'input': NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - } - - @property - def output_types(self): - """Returns definitions of module output types""" - return { - 'output': NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - } - - @typecheck() - def forward(self, input: torch.Tensor) -> torch.Tensor: - """ - Args: - input: shape (B, M, in_features, T) - - Returns: - Output tensor with shape shape (B, M, out_features, T) - """ - B, M, F, T = input.shape - - # (B, M, F, T) -> (B, T, M, F) - input = input.permute(0, 3, 1, 2) - input = input.reshape(B * T, M, F) - - # transform each channel - transform = self.transform_channel(input) - - # attend - attend = self.transform_attend(input) - # attention across channels - attend = self.attention(query=attend, key=attend, value=attend, mask=None) - - # concatenate along feature dimension - output = torch.cat([transform, attend], dim=-1) - - # return to the original layout - output = output.view(B, T, M, -1) - - # (B, T, M, num_features) -> (B, M, num_features, T) - output = output.permute(0, 2, 3, 1) - - return output - - -class ChannelAveragePool(NeuralModule): - """Apply average pooling across channels.""" - - def __init__(self): - super().__init__() - logging.debug('Initialized %s', self.__class__.__name__) - - @property - def input_types(self): - """Returns definitions of module input types""" - return { - 'input': NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - } - - @property - def output_types(self): - """Returns definitions of module output types""" - return { - 'output': NeuralType(('B', 'D', 'T'), SpectrogramType()), - } - - @typecheck() - def forward(self, input: torch.Tensor) -> torch.Tensor: - """ - Args: - input: shape (B, M, F, T) - - Returns: - Output tensor with shape shape (B, F, T) - """ - return torch.mean(input, dim=-3) - - -class ChannelAttentionPool(NeuralModule): - """Use attention pooling to aggregate information across channels. - First apply MHA across channels and then apply averaging. - - Args: - in_features: Number of input features - out_features: Number of output features - n_head: Number of heads for the MHA module - dropout_rate: Dropout rate for the MHA module - - References: - - Wang et al, Neural speech separation using sparially distributed microphones, 2020 - - Jukić et al, Flexible multichannel speech enhancement for noise-robust frontend, 2023 - """ - - def __init__(self, in_features: int, n_head: int = 1, dropout_rate: float = 0): - super().__init__() - self.in_features = in_features - self.attention = MultiHeadAttention(n_head=n_head, n_feat=in_features, dropout_rate=dropout_rate) - - logging.debug('Initialized %s with', self.__class__.__name__) - logging.debug('\tin_features: %d', in_features) - logging.debug('\tnum_heads: %d', n_head) - logging.debug('\tdropout_rate: %d', dropout_rate) - - @property - def input_types(self): - """Returns definitions of module input types""" - return { - 'input': NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - } - - @property - def output_types(self): - """Returns definitions of module output types""" - return { - 'output': NeuralType(('B', 'D', 'T'), SpectrogramType()), - } - - @typecheck() - def forward(self, input: torch.Tensor) -> torch.Tensor: - """ - Args: - input: shape (B, M, F, T) - - Returns: - Output tensor with shape shape (B, F, T) - """ - B, M, F, T = input.shape - - # (B, M, F, T) -> (B, T, M, F) - input = input.permute(0, 3, 1, 2) - input = input.reshape(B * T, M, F) - - # attention across channels - output = self.attention(query=input, key=input, value=input, mask=None) - - # return to the original layout - output = output.view(B, T, M, -1) - - # (B, T, M, num_features) -> (B, M, out_features, T) - output = output.permute(0, 2, 3, 1) - - # average across channels - output = torch.mean(output, axis=-3) - - return output - - -class ParametricMultichannelWienerFilter(NeuralModule): - """Parametric multichannel Wiener filter, with an adjustable - tradeoff between noise reduction and speech distortion. - It supports automatic reference channel selection based - on the estimated output SNR. - - Args: - beta: Parameter of the parameteric filter, tradeoff between noise reduction - and speech distortion (0: MVDR, 1: MWF). - rank: Rank assumption for the speech covariance matrix. - postfilter: Optional postfilter. If None, no postfilter is applied. - ref_channel: Optional, reference channel. If None, it will be estimated automatically. - ref_hard: If true, estimate a hard (one-hot) reference. If false, a soft reference. - ref_hard_use_grad: If true, use straight-through gradient when using the hard reference - ref_subband_weighting: If true, use subband weighting when estimating reference channel - num_subbands: Optional, used to determine the parameter size for reference estimation - diag_reg: Optional, diagonal regularization for the multichannel filter - eps: Small regularization constant to avoid division by zero - - References: - - Souden et al, On Optimal Frequency-Domain Multichannel Linear Filtering for Noise Reduction, 2010 - """ - - def __init__( - self, - beta: float = 1.0, - rank: str = 'one', - postfilter: Optional[str] = None, - ref_channel: Optional[int] = None, - ref_hard: bool = True, - ref_hard_use_grad: bool = True, - ref_subband_weighting: bool = False, - num_subbands: Optional[int] = None, - diag_reg: Optional[float] = 1e-6, - eps: float = 1e-8, - ): - super().__init__() - - # Parametric filter - # 0=MVDR, 1=MWF - self.beta = beta - - # Rank - # Assumed rank for the signal covariance matrix (psd_s) - self.rank = rank - - if self.rank == 'full' and self.beta == 0: - raise ValueError(f'Rank {self.rank} is not compatible with beta {self.beta}.') - - # Postfilter, applied on the output of the multichannel filter - if postfilter not in [None, 'ban']: - raise ValueError(f'Postfilter {postfilter} is not supported.') - self.postfilter = postfilter - - # Regularization - if diag_reg is not None and diag_reg < 0: - raise ValueError(f'Diagonal regularization {diag_reg} must be positive.') - self.diag_reg = diag_reg - - if eps <= 0: - raise ValueError(f'Epsilon {eps} must be positive.') - self.eps = eps - - # Reference channel - self.ref_channel = ref_channel - if self.ref_channel == 'max_snr': - self.ref_estimator = ReferenceChannelEstimatorSNR( - hard=ref_hard, - hard_use_grad=ref_hard_use_grad, - subband_weighting=ref_subband_weighting, - num_subbands=num_subbands, - eps=eps, - ) - else: - self.ref_estimator = None - # Flag to determine if the filter is MISO or MIMO - self.is_mimo = self.ref_channel is None - - logging.debug('Initialized %s', self.__class__.__name__) - logging.debug('\tbeta: %f', self.beta) - logging.debug('\trank: %s', self.rank) - logging.debug('\tpostfilter: %s', self.postfilter) - logging.debug('\tdiag_reg: %g', self.diag_reg) - logging.debug('\teps: %g', self.eps) - logging.debug('\tref_channel: %s', self.ref_channel) - logging.debug('\tis_mimo: %s', self.is_mimo) - - @staticmethod - def trace(x: torch.Tensor, keepdim: bool = False) -> torch.Tensor: - """Calculate trace of matrix slices over the last - two dimensions in the input tensor. - - Args: - x: tensor, shape (..., C, C) - - Returns: - Trace for each (C, C) matrix. shape (...) - """ - trace = torch.diagonal(x, dim1=-2, dim2=-1).sum(-1) - if keepdim: - trace = trace.unsqueeze(-1).unsqueeze(-1) - return trace - - def apply_diag_reg(self, psd: torch.Tensor) -> torch.Tensor: - """Apply diagonal regularization on psd. - - Args: - psd: tensor, shape (..., C, C) - - Returns: - Tensor, same shape as input. - """ - # Regularization: diag_reg * trace(psd) + eps - diag_reg = self.diag_reg * self.trace(psd).real + self.eps - - # Apply regularization - psd = psd + torch.diag_embed(diag_reg.unsqueeze(-1) * torch.ones(psd.shape[-1], device=psd.device)) - - return psd - - def apply_filter(self, input: torch.Tensor, filter: torch.Tensor) -> torch.Tensor: - """Apply the MIMO filter on the input. - - Args: - input: batch with C input channels, shape (B, C, F, T) - filter: batch of C-input, M-output filters, shape (B, F, C, M) - - Returns: - M-channel filter output, shape (B, M, F, T) - """ - if not filter.is_complex(): - raise TypeError(f'Expecting complex-valued filter, found {filter.dtype}') - - if not input.is_complex(): - raise TypeError(f'Expecting complex-valued input, found {input.dtype}') - - if filter.ndim != 4 or filter.size(-2) != input.size(-3) or filter.size(-3) != input.size(-2): - raise ValueError(f'Filter shape {filter.shape}, not compatible with input shape {input.shape}') - - output = torch.einsum('bfcm,bcft->bmft', filter.conj(), input) - - return output - - def apply_ban(self, input: torch.Tensor, filter: torch.Tensor, psd_n: torch.Tensor) -> torch.Tensor: - """Apply blind analytic normalization postfilter. Note that this normalization has been - derived for the GEV beamformer in [1]. More specifically, the BAN postfilter aims to scale GEV - to satisfy the distortionless constraint and the final analytical expression is derived using - an assumption on the norm of the transfer function. - However, this may still be useful in some instances. - - Args: - input: batch with M output channels (B, M, F, T) - filter: batch of C-input, M-output filters, shape (B, F, C, M) - psd_n: batch of noise PSDs, shape (B, F, C, C) - - Returns: - Filtere input, shape (B, M, F, T) - - References: - - Warsitz and Haeb-Umbach, Blind Acoustic Beamforming Based on Generalized Eigenvalue Decomposition, 2007 - """ - # number of input channel, used to normalize the numerator - num_inputs = filter.size(-2) - numerator = torch.einsum('bfcm,bfci,bfij,bfjm->bmf', filter.conj(), psd_n, psd_n, filter) - numerator = torch.sqrt(numerator.abs() / num_inputs) - - denominator = torch.einsum('bfcm,bfci,bfim->bmf', filter.conj(), psd_n, filter) - denominator = denominator.abs() - - # Scalar filter per output channel, frequency and batch - # shape (B, M, F) - ban = numerator / (denominator + self.eps) - - input = ban[..., None] * input - - return input - - @property - def input_types(self): - """Returns definitions of module input types""" - return { - 'input': NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - 'mask_s': NeuralType(('B', 'D', 'T'), FloatType()), - 'mask_n': NeuralType(('B', 'D', 'T'), FloatType()), - } - - @property - def output_types(self): - """Returns definitions of module output types""" - return { - 'output': NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - } - - @typecheck() - def forward(self, input: torch.Tensor, mask_s: torch.Tensor, mask_n: torch.Tensor) -> torch.Tensor: - """Return processed signal. - The output has either one channel (M=1) if a ref_channel is selected, - or the same number of channels as the input (M=C) if ref_channel is None. - - Args: - input: Input signal, complex tensor with shape (B, C, F, T) - mask_s: Mask for the desired signal, shape (B, F, T) - mask_n: Mask for the undesired noise, shape (B, F, T) - - Returns: - Processed signal, shape (B, M, F, T) - """ - iodtype = input.dtype - - with torch.amp.autocast(input.device.type, enabled=False): - # Convert to double - input = input.cdouble() - mask_s = mask_s.double() - mask_n = mask_n.double() - - # Calculate signal statistics - psd_s = covariance_matrix(x=input, mask=mask_s) - psd_n = covariance_matrix(x=input, mask=mask_n) - - if self.rank == 'one': - # Calculate filter W using (18) in [1] - # Diagonal regularization - if self.diag_reg: - psd_n = self.apply_diag_reg(psd_n) - - # MIMO filter - # (B, F, C, C) - W = torch.linalg.solve(psd_n, psd_s) - lam = self.trace(W, keepdim=True).real - W = W / (self.beta + lam + self.eps) - elif self.rank == 'full': - # Calculate filter W using (15) in [1] - psd_sn = psd_s + self.beta * psd_n - - if self.diag_reg: - psd_sn = self.apply_diag_reg(psd_sn) - - # MIMO filter - # (B, F, C, C) - W = torch.linalg.solve(psd_sn, psd_s) - else: - raise RuntimeError(f'Unexpected rank {self.rank}') - - if torch.jit.isinstance(self.ref_channel, int): - # Fixed ref channel - # (B, F, C, 1) - W = W[..., self.ref_channel].unsqueeze(-1) - elif self.ref_estimator is not None: - # Estimate ref channel tensor (one-hot or soft across C) - # (B, C) - ref_channel_tensor = self.ref_estimator(W=W, psd_s=psd_s, psd_n=psd_n).to(W.dtype) - # Weighting across channels - # (B, F, C, 1) - W = torch.sum(W * ref_channel_tensor[:, None, None, :], dim=-1, keepdim=True) - - output = self.apply_filter(input=input, filter=W) - - # Optional: postfilter - if self.postfilter == 'ban': - output = self.apply_ban(input=output, filter=W, psd_n=psd_n) - - return output.to(iodtype) - - -class ReferenceChannelEstimatorSNR(NeuralModule): - """Estimate a reference channel by selecting the reference - that maximizes the output SNR. It returns one-hot encoded - vector or a soft reference. - - A straight-through estimator is used for gradient when using - hard reference. - - Args: - hard: If true, use hard estimate of ref channel. - If false, use a soft estimate across channels. - hard_use_grad: Use straight-through estimator for - the gradient. - subband_weighting: If true, use subband weighting when - adding across subband SNRs. If false, use average - across subbands. - - References: - Boeddeker et al, Front-End Processing for the CHiME-5 Dinner Party Scenario, 2018 - """ - - def __init__( - self, - hard: bool = True, - hard_use_grad: bool = True, - subband_weighting: bool = False, - num_subbands: Optional[int] = None, - eps: float = 1e-8, - ): - super().__init__() - - self.hard = hard - self.hard_use_grad = hard_use_grad - self.subband_weighting = subband_weighting - self.eps = eps - - if subband_weighting and num_subbands is None: - raise ValueError(f'Number of subbands must be provided when using subband_weighting={subband_weighting}.') - # Subband weighting - self.weight_s = torch.nn.Parameter(torch.ones(num_subbands)) if subband_weighting else None - self.weight_n = torch.nn.Parameter(torch.ones(num_subbands)) if subband_weighting else None - - logging.debug('Initialized %s', self.__class__.__name__) - logging.debug('\thard: %d', self.hard) - logging.debug('\thard_use_grad: %d', self.hard_use_grad) - logging.debug('\tsubband_weighting: %d', self.subband_weighting) - logging.debug('\tnum_subbands: %s', num_subbands) - logging.debug('\teps: %e', self.eps) - - @property - def input_types(self): - """Returns definitions of module input types""" - return { - 'W': NeuralType(('B', 'D', 'C', 'C'), SpectrogramType()), - 'psd_s': NeuralType(('B', 'D', 'C', 'C'), SpectrogramType()), - 'psd_n': NeuralType(('B', 'D', 'C', 'C'), SpectrogramType()), - } - - @property - def output_types(self): - """Returns definitions of module output types""" - return { - 'output': NeuralType(('B', 'C'), FloatType()), - } - - @typecheck() - def forward(self, W: torch.Tensor, psd_s: torch.Tensor, psd_n: torch.Tensor) -> torch.Tensor: - """ - Args: - W: Multichannel input multichannel output filter, shape (B, F, C, M), where - C is the number of input channels and M is the number of output channels - psd_s: Covariance for the signal, shape (B, F, C, C) - psd_n: Covariance for the noise, shape (B, F, C, C) - - Returns: - One-hot or soft reference channel, shape (B, M) - """ - if self.subband_weighting: - # (B, F, M) - pow_s = torch.einsum('...jm,...jk,...km->...m', W.conj(), psd_s, W).abs() - pow_n = torch.einsum('...jm,...jk,...km->...m', W.conj(), psd_n, W).abs() - - # Subband-weighting - # (B, F, M) -> (B, M) - pow_s = torch.sum(pow_s * self.weight_s.softmax(dim=0).unsqueeze(1), dim=-2) - pow_n = torch.sum(pow_n * self.weight_n.softmax(dim=0).unsqueeze(1), dim=-2) - else: - # Sum across f as well - # (B, F, C, M), (B, F, C, C), (B, F, C, M) -> (B, M) - pow_s = torch.einsum('...fjm,...fjk,...fkm->...m', W.conj(), psd_s, W).abs() - pow_n = torch.einsum('...fjm,...fjk,...fkm->...m', W.conj(), psd_n, W).abs() - - # Estimated SNR per channel (B, C) - snr = pow_s / (pow_n + self.eps) - snr = 10 * torch.log10(snr + self.eps) - - # Soft reference - ref_soft = snr.softmax(dim=-1) - - if self.hard: - _, idx = ref_soft.max(dim=-1, keepdim=True) - ref_hard = torch.zeros_like(snr).scatter(-1, idx, 1.0) - if self.hard_use_grad: - # Straight-through for gradient - # Propagate ref_soft gradient, as if thresholding is identity - ref = ref_hard - ref_soft.detach() + ref_soft - else: - # No gradient - ref = ref_hard - else: - ref = ref_soft - - return ref - - -class WPEFilter(NeuralModule): - """A weighted prediction error filter. - Given input signal, and expected power of the desired signal, this - class estimates a multiple-input multiple-output prediction filter - and returns the filtered signal. Currently, estimation of statistics - and processing is performed in batch mode. - - Args: - filter_length: Length of the prediction filter in frames, per channel - prediction_delay: Prediction delay in frames - diag_reg: Diagonal regularization for the correlation matrix Q, applied as diag_reg * trace(Q) + eps - eps: Small positive constant for regularization - - References: - - Yoshioka and Nakatani, Generalization of Multi-Channel Linear Prediction - Methods for Blind MIMO Impulse Response Shortening, 2012 - - Jukić et al, Group sparsity for MIMO speech dereverberation, 2015 - """ - - def __init__(self, filter_length: int, prediction_delay: int, diag_reg: Optional[float] = 1e-6, eps: float = 1e-8): - super().__init__() - self.filter_length = filter_length - self.prediction_delay = prediction_delay - self.diag_reg = diag_reg - self.eps = eps - - logging.debug('Initialized %s', self.__class__.__name__) - logging.debug('\tfilter_length: %d', self.filter_length) - logging.debug('\tprediction_delay: %d', self.prediction_delay) - logging.debug('\tdiag_reg: %g', self.diag_reg) - logging.debug('\teps: %g', self.eps) - - @property - def input_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "input": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "power": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "input_length": NeuralType(('B',), LengthsType(), optional=True), - } - - @property - def output_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "output": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "output_length": NeuralType(('B',), LengthsType(), optional=True), - } - - @typecheck() - def forward( - self, input: torch.Tensor, power: torch.Tensor, input_length: Optional[torch.Tensor] = None - ) -> torch.Tensor: - """Given input and the predicted power for the desired signal, estimate - the WPE filter and return the processed signal. - - Args: - input: Input signal, shape (B, C, F, N) - power: Predicted power of the desired signal, shape (B, C, F, N) - input_length: Optional, length of valid frames in `input`. Defaults to `None` - - Returns: - Tuple of (processed_signal, output_length). Processed signal has the same - shape as the input signal (B, C, F, N), and the output length is the same - as the input length. - """ - # Temporal weighting: average power over channels, output shape (B, F, N) - weight = torch.mean(power, dim=1) - # Use inverse power as the weight - weight = 1 / (weight + self.eps) - - # Multi-channel convolution matrix for each subband - tilde_input = self.convtensor(input, filter_length=self.filter_length, delay=self.prediction_delay) - - # Estimate correlation matrices - Q, R = self.estimate_correlations( - input=input, weight=weight, tilde_input=tilde_input, input_length=input_length - ) - - # Estimate prediction filter - G = self.estimate_filter(Q=Q, R=R) - - # Apply prediction filter - undesired_signal = self.apply_filter(filter=G, tilde_input=tilde_input) - - # Dereverberation - desired_signal = input - undesired_signal - - if input_length is not None: - # Mask padded frames - length_mask: torch.Tensor = make_seq_mask_like( - lengths=input_length, like=desired_signal, time_dim=-1, valid_ones=False - ) - desired_signal = desired_signal.masked_fill(length_mask, 0.0) - - return desired_signal, input_length - - @classmethod - def convtensor( - cls, x: torch.Tensor, filter_length: int, delay: int = 0, n_steps: Optional[int] = None - ) -> torch.Tensor: - """Create a tensor equivalent of convmtx_mc for each example in the batch. - The input signal tensor `x` has shape (B, C, F, N). - Convtensor returns a view of the input signal `x`. - - Note: We avoid reshaping the output to collapse channels and filter taps into - a single dimension, e.g., (B, F, N, -1). In this way, the output is a view of the input, - while an additional reshape would result in a contiguous array and more memory use. - - Args: - x: input tensor, shape (B, C, F, N) - filter_length: length of the filter, determines the shape of the convolution tensor - delay: delay to add to the input signal `x` before constructing the convolution tensor - n_steps: Optional, number of time steps to keep in the out. Defaults to the number of - time steps in the input tensor. - - Returns: - Return a convolutional tensor with shape (B, C, F, n_steps, filter_length) - """ - if x.ndim != 4: - raise RuntimeError(f'Expecting a 4-D input. Received input with shape {x.shape}') - - B, C, F, N = x.shape - - if n_steps is None: - # Keep the same length as the input signal - n_steps = N - - # Pad temporal dimension - x = torch.nn.functional.pad(x, (filter_length - 1 + delay, 0)) - - # Build Toeplitz-like matrix view by unfolding across time - tilde_X = x.unfold(-1, filter_length, 1) - - # Trim to the set number of time steps - tilde_X = tilde_X[:, :, :, :n_steps, :] - - return tilde_X - - @classmethod - def permute_convtensor(cls, x: torch.Tensor) -> torch.Tensor: - """Reshape and permute columns to convert the result of - convtensor to be equal to convmtx_mc. This is used for verification - purposes and it is not required to use the filter. - - Args: - x: output of self.convtensor, shape (B, C, F, N, filter_length) - - Returns: - Output has shape (B, F, N, C*filter_length) that corresponds to - the layout of convmtx_mc. - """ - B, C, F, N, filter_length = x.shape - - # .view will not work, so a copy will have to be created with .reshape - # That will result in more memory use, since we don't use a view of the original - # multi-channel signal - x = x.permute(0, 2, 3, 1, 4) - x = x.reshape(B, F, N, C * filter_length) - - permute = [] - for m in range(C): - permute[m * filter_length : (m + 1) * filter_length] = m * filter_length + np.flip( - np.arange(filter_length) - ) - return x[..., permute] - - def estimate_correlations( - self, - input: torch.Tensor, - weight: torch.Tensor, - tilde_input: torch.Tensor, - input_length: Optional[torch.Tensor] = None, - ) -> Tuple[torch.Tensor]: - """ - Args: - input: Input signal, shape (B, C, F, N) - weight: Time-frequency weight, shape (B, F, N) - tilde_input: Multi-channel convolution tensor, shape (B, C, F, N, filter_length) - input_length: Length of each input example, shape (B) - - Returns: - Returns a tuple of correlation matrices for each batch. - - Let `X` denote the input signal in a single subband, - `tilde{X}` the corresponding multi-channel correlation matrix, - and `w` the vector of weights. - - The first output is Q = tilde{X}^H * diag(w) * tilde{X}, for each (b, f). - The matrix Q has shape (C * filter_length, C * filter_length) - The output is returned in a tensor with shape (B, F, C, filter_length, C, filter_length). - - The second output is R = tilde{X}^H * diag(w) * X, for each (b, f). - The matrix R has shape (C * filter_length, C) - The output is returned in a tensor with shape (B, F, C, filter_length, C). The last - dimension corresponds to output channels. - """ - if input_length is not None: - # Take only valid samples into account - length_mask: torch.Tensor = make_seq_mask_like( - lengths=input_length, like=weight, time_dim=-1, valid_ones=False - ) - weight = weight.masked_fill(length_mask, 0.0) - - # Calculate (1) - # result: (B, F, C, filter_length, C, filter_length) - Q = torch.einsum('bjfik,bmfin->bfjkmn', tilde_input.conj(), weight[:, None, :, :, None] * tilde_input) - - # Calculate (2) - # result: (B, F, C, filter_length, C) - R = torch.einsum('bjfik,bmfi->bfjkm', tilde_input.conj(), weight[:, None, :, :] * input) - - return Q, R - - def estimate_filter(self, Q: torch.Tensor, R: torch.Tensor) -> torch.Tensor: - r"""Estimate the MIMO prediction filter as G(b,f) = Q(b,f) \ R(b,f) - for each subband in each example in the batch (b, f). - - Args: - Q: shape (B, F, C, filter_length, C, filter_length) - R: shape (B, F, C, filter_length, C) - - Returns: - Complex-valued prediction filter, shape (B, C, F, C, filter_length) - """ - B, F, C, filter_length, _, _ = Q.shape - assert ( - filter_length == self.filter_length - ), f'Shape of Q {Q.shape} is not matching filter length {self.filter_length}' - - # Reshape to analytical dimensions for each (b, f) - Q = Q.reshape(B, F, C * self.filter_length, C * filter_length) - R = R.reshape(B, F, C * self.filter_length, C) - - # Diagonal regularization - if self.diag_reg: - # Regularization: diag_reg * trace(Q) + eps - diag_reg = self.diag_reg * torch.diagonal(Q, dim1=-2, dim2=-1).sum(-1).real + self.eps - # Apply regularization on Q - Q = Q + torch.diag_embed(diag_reg.unsqueeze(-1) * torch.ones(Q.shape[-1], device=Q.device)) - - # Solve for the filter - G = torch.linalg.solve(Q, R) - - # Reshape to desired representation: (B, F, input channels, filter_length, output channels) - G = G.reshape(B, F, C, filter_length, C) - # Move output channels to front: (B, output channels, F, input channels, filter_length) - G = G.permute(0, 4, 1, 2, 3) - - return G - - def apply_filter( - self, filter: torch.Tensor, input: Optional[torch.Tensor] = None, tilde_input: Optional[torch.Tensor] = None - ) -> torch.Tensor: - """Apply a prediction filter `filter` on the input `input` as - - output(b,f) = tilde{input(b,f)} * filter(b,f) - - If available, directly use the convolution matrix `tilde_input`. - - Args: - input: Input signal, shape (B, C, F, N) - tilde_input: Convolution matrix for the input signal, shape (B, C, F, N, filter_length) - filter: Prediction filter, shape (B, C, F, C, filter_length) - - Returns: - Multi-channel signal obtained by applying the prediction filter on - the input signal, same shape as input (B, C, F, N) - """ - if input is None and tilde_input is None: - raise RuntimeError('Both inputs cannot be None simultaneously.') - if input is not None and tilde_input is not None: - raise RuntimeError('Both inputs cannot be provided simultaneously.') - - if tilde_input is None: - tilde_input = self.convtensor(input, filter_length=self.filter_length, delay=self.prediction_delay) - - # For each (batch, output channel, f, time step), sum across (input channel, filter tap) - output = torch.einsum('bjfik,bmfjk->bmfi', tilde_input, filter) - - return output diff --git a/nemo/collections/audio/parts/submodules/ncsnpp.py b/nemo/collections/audio/parts/submodules/ncsnpp.py deleted file mode 100644 index 01f36537af95610e1d4755411a4376fd44636364..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/parts/submodules/ncsnpp.py +++ /dev/null @@ -1,510 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import math -from typing import Dict, Optional, Sequence - -import einops -import einops.layers.torch -import torch -import torch.nn.functional as F - -from nemo.collections.common.parts.utils import activation_registry, mask_sequence_tensor -from nemo.core.classes import NeuralModule, typecheck -from nemo.core.neural_types import FloatType, LengthsType, NeuralType, SpectrogramType, VoidType -from nemo.utils import logging - - -class SpectrogramNoiseConditionalScoreNetworkPlusPlus(NeuralModule): - """This model handles complex-valued inputs by stacking real and imaginary components. - Stacked tensor is processed using NCSN++ and the output is projected to generate real - and imaginary components of the output channels. - - Args: - in_channels: number of input complex-valued channels - out_channels: number of output complex-valued channels - """ - - def __init__(self, *, in_channels: int = 1, out_channels: int = 1, **kwargs): - super().__init__() - - # Number of input signals for this estimator - if in_channels < 1: - raise ValueError( - f'Number of input channels needs to be larger or equal to one, current value {in_channels}' - ) - - self.in_channels = in_channels - - # Number of output signals for this estimator - if out_channels < 1: - raise ValueError( - f'Number of output channels needs to be larger or equal to one, current value {out_channels}' - ) - - self.out_channels = out_channels - - # Instantiate noise conditional score network NCSN++ - ncsnpp_params = kwargs.copy() - ncsnpp_params['in_channels'] = ncsnpp_params['out_channels'] = 2 * self.in_channels # stack real and imag - self.ncsnpp = NoiseConditionalScoreNetworkPlusPlus(**ncsnpp_params) - - # Output projection to generate real and imaginary components of the output channels - self.output_projection = torch.nn.Conv2d( - in_channels=2 * self.in_channels, out_channels=2 * self.out_channels, kernel_size=1 - ) - - logging.debug('Initialized %s with', self.__class__.__name__) - logging.debug('\tin_channels: %s', self.in_channels) - logging.debug('\tout_channels: %s', self.out_channels) - - @property - def input_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "input": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "input_length": NeuralType(('B',), LengthsType(), optional=True), - "condition": NeuralType(('B',), FloatType(), optional=True), - } - - @property - def output_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "output": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "output_length": NeuralType(('B',), LengthsType(), optional=True), - } - - @typecheck() - def forward(self, input, input_length=None, condition=None): - # Stack real and imaginary components - B, C_in, D, T = input.shape - - if C_in != self.in_channels: - raise RuntimeError(f'Unexpected input channel size {C_in}, expected {self.in_channels}') - - # Stack real and imaginary parts - input_real_imag = torch.stack([input.real, input.imag], dim=2) - input = einops.rearrange(input_real_imag, 'B C RI F T -> B (C RI) F T') - - # Process using NCSN++ - output, output_length = self.ncsnpp(input=input, input_length=input_length, condition=condition) - - # Output projection - output = self.output_projection(output) - - # Convert to complex-valued signal - output = output.reshape(B, 2, self.out_channels, D, T) - # Move real/imag dimension to the end - output = output.permute(0, 2, 3, 4, 1) - output = torch.view_as_complex(output.contiguous()) - - return output, output_length - - -class NoiseConditionalScoreNetworkPlusPlus(NeuralModule): - """Implementation of Noise Conditional Score Network (NCSN++) architecture. - - References: - - Song et al., Score-Based Generative Modeling through Stochastic Differential Equations, NeurIPS 2021 - - Brock et al., Large scale GAN training for high fidelity natural image synthesis, ICLR 2018 - """ - - def __init__( - self, - nonlinearity: str = "swish", - in_channels: int = 2, # number of channels in the input image - out_channels: int = 2, # number of channels in the output image - channels: Sequence[int] = (128, 128, 256, 256, 256), # number of channels at start + at every resolution - num_res_blocks: int = 2, - num_resolutions: int = 4, - init_scale: float = 1e-5, - conditioned_on_time: bool = False, - fourier_embedding_scale: float = 16.0, - dropout_rate: float = 0.0, - pad_time_to: Optional[int] = None, - pad_dimension_to: Optional[int] = None, - **_, - ): - # Network topology is a flavor of UNet, example chart for num_resolutions=4 - # - # 1: Image → Image/2 → Image/4 → Image/8 - # ↓ ↓ ↓ ↓ - # 2: Hidden → Hidden/2 → Hidden/4 → Hidden/8 - # ↓ ↓ ↓ ↓ - # 3: Hidden ← Hidden/2 ← Hidden/4 ← Hidden/8 - # ↓ ↓ ↓ ↓ - # 4: Image ← Image/2 ← Image/4 ← Image/8 - - # Horizontal arrows in (1) are downsampling - # Vertical arrows from (1) to (2) are channel upconversions - # - # Horizontal arrows in (2) are blocks with downsampling where necessary - # Horizontal arrows in (3) are blocks with upsampling where necessary - # - # Vertical arrows from (1) to (2) are downsampling and channel upconversioins - # Vertical arrows from (2) to (3) are sums connections (also with / sqrt(2)) - # Vertical arrows from (3) to (4) are channel downconversions - # Horizontal arrows in (4) are upsampling and addition - super().__init__() - - # same nonlinearity is used throughout the whole network - self.activation: torch.nn.Module = activation_registry[nonlinearity]() - self.init_scale: float = init_scale - - self.downsample = torch.nn.Upsample(scale_factor=0.5, mode="bilinear") - self.upsample = torch.nn.Upsample(scale_factor=2, mode="bilinear") - - self.in_channels = in_channels - self.out_channels = out_channels - self.channels = channels - self.num_res_blocks = num_res_blocks - self.num_resolutions = num_resolutions - self.conditioned_on_time = conditioned_on_time - - # padding setup - self.pad_time_to = pad_time_to or 2**self.num_resolutions - self.pad_dimension_to = pad_dimension_to or 2**self.num_resolutions - - if self.conditioned_on_time: - self.time_embedding = torch.nn.Sequential( - GaussianFourierProjection(embedding_size=self.channels[0], scale=fourier_embedding_scale), - torch.nn.Linear(self.channels[0] * 2, self.channels[0] * 4), - self.activation, - torch.nn.Linear(self.channels[0] * 4, self.channels[0] * 4), - ) - - self.input_pyramid = torch.nn.ModuleList() - for ch in self.channels[:-1]: - self.input_pyramid.append(torch.nn.Conv2d(in_channels=self.in_channels, out_channels=ch, kernel_size=1)) - - # each block takes an image and outputs an image - # possibly changes number of channels - # output blocks ("reverse" path of the unet) reuse outputs of input blocks ("forward" path) - # so great care must be taken to in/out channels of each block - # resolutions are handled in `forward` - block_params = { - "activation": self.activation, - "dropout_rate": dropout_rate, - "init_scale": self.init_scale, - "diffusion_step_embedding_dim": channels[0] * 4 if self.conditioned_on_time else None, - } - self.input_blocks = torch.nn.ModuleList() - for in_ch, out_ch in zip(self.channels[:-1], self.channels[1:]): - for n in range(num_res_blocks): - block = ResnetBlockBigGANPlusPlus(in_ch=in_ch if n == 0 else out_ch, out_ch=out_ch, **block_params) - self.input_blocks.append(block) - - self.output_blocks = torch.nn.ModuleList() - for in_ch, out_ch in zip(reversed(self.channels[1:]), reversed(self.channels[:-1])): - for n in reversed(range(num_res_blocks)): - block = ResnetBlockBigGANPlusPlus(in_ch=in_ch, out_ch=out_ch if n == 0 else in_ch, **block_params) - self.output_blocks.append(block) - - self.projection_blocks = torch.nn.ModuleList() - for ch in self.channels[:-1]: - self.projection_blocks.append(torch.nn.Conv2d(ch, out_channels, kernel_size=1)) - - assert len(self.input_pyramid) == self.num_resolutions - assert len(self.input_blocks) == self.num_resolutions * self.num_res_blocks - assert len(self.output_blocks) == self.num_resolutions * self.num_res_blocks - assert len(self.projection_blocks) == self.num_resolutions - - self.init_weights_() - - logging.debug('Initialized %s with', self.__class__.__name__) - logging.debug('\tin_channels: %s', self.in_channels) - logging.debug('\tout_channels: %s', self.out_channels) - logging.debug('\tchannels: %s', self.channels) - logging.debug('\tnum_res_blocks: %s', self.num_res_blocks) - logging.debug('\tnum_resolutions: %s', self.num_resolutions) - logging.debug('\tconditioned_on_time: %s', self.conditioned_on_time) - logging.debug('\tpad_time_to: %s', self.pad_time_to) - logging.debug('\tpad_dimension_to: %s', self.pad_dimension_to) - - def init_weights_(self): - for module in self.modules(): - if isinstance(module, (torch.nn.Linear, torch.nn.Conv2d)): - torch.nn.init.xavier_uniform_(module.weight) - if module.bias is not None: - torch.nn.init.zeros_(module.bias) - - # torch.nn submodules with scaled init - for module in self.projection_blocks: - torch.nn.init.xavier_uniform_(module.weight, gain=self.init_scale) - - # non-torch.nn submodules can have their own init schemes - for module in self.modules(): - if module is self: - continue - - if hasattr(module, "init_weights_"): - module.init_weights_() - - @typecheck( - input_types={ - "input": NeuralType(('B', 'C', 'D', 'T')), - }, - output_types={ - "output": NeuralType(('B', 'C', 'D', 'T')), - }, - ) - def pad_input(self, input: torch.Tensor) -> torch.Tensor: - """Pad input tensor to match the required dimensions across `T` and `D`.""" - *_, D, T = input.shape - output = input - - # padding across time - if T % self.pad_time_to != 0: - output = F.pad(output, (0, self.pad_time_to - T % self.pad_time_to)) - - # padding across dimension - if D % self.pad_dimension_to != 0: - output = F.pad(output, (0, 0, 0, self.pad_dimension_to - D % self.pad_dimension_to)) - - return output - - @property - def input_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "input": NeuralType(('B', 'C', 'D', 'T'), VoidType()), - "input_length": NeuralType(('B',), LengthsType(), optional=True), - "condition": NeuralType(('B',), FloatType(), optional=True), - } - - @property - def output_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "output": NeuralType(('B', 'C', 'D', 'T'), VoidType()), - "output_length": NeuralType(('B',), LengthsType(), optional=True), - } - - @typecheck() - def forward( - self, *, input: torch.Tensor, input_length: Optional[torch.Tensor], condition: Optional[torch.Tensor] = None - ): - """Forward pass of the model. - - Args: - input: input tensor, shjae (B, C, D, T) - input_length: length of the valid time steps for each example in the batch, shape (B,) - condition: scalar condition (time) for the model, will be embedded using `self.time_embedding` - """ - assert input.shape[1] == self.in_channels - - # apply padding at the input - *_, D, T = input.shape - input = self.pad_input(input=input) - - if input_length is None: - # assume all time frames are valid - input_length = torch.LongTensor([input.shape[-1]] * input.shape[0]).to(input.device) - - lengths = input_length - - if condition is not None: - if len(condition.shape) != 1: - raise ValueError( - f"Expected conditon to be a 1-dim tensor, got a {len(condition.shape)}-dim tensor of shape {tuple(condition.shape)}" - ) - if condition.shape[0] != input.shape[0]: - raise ValueError( - f"Condition {tuple(condition.shape)} and input {tuple(input.shape)} should match along the batch dimension" - ) - - condition = self.time_embedding(torch.log(condition)) - - # downsample and project input image to add later in the downsampling path - pyramid = [input] - for resolution_num in range(self.num_resolutions - 1): - pyramid.append(self.downsample(pyramid[-1])) - pyramid = [block(image) for image, block in zip(pyramid, self.input_pyramid)] - - # downsampling path - history = [] - hidden = torch.zeros_like(pyramid[0]) - input_blocks = iter(self.input_blocks) - for resolution_num, image in enumerate(pyramid): - hidden = (hidden + image) / math.sqrt(2.0) - hidden = mask_sequence_tensor(hidden, lengths) - - for _ in range(self.num_res_blocks): - hidden = next(input_blocks)(hidden, condition) - hidden = mask_sequence_tensor(hidden, lengths) - history.append(hidden) - - final_resolution = resolution_num == self.num_resolutions - 1 - if not final_resolution: - hidden = self.downsample(hidden) - lengths = (lengths / 2).ceil().long() - - # upsampling path - to_project = [] - for residual, block in zip(reversed(history), self.output_blocks): - if hidden.shape != residual.shape: - to_project.append(hidden) - hidden = self.upsample(hidden) - lengths = (lengths * 2).long() - - hidden = (hidden + residual) / math.sqrt(2.0) - hidden = block(hidden, condition) - hidden = mask_sequence_tensor(hidden, lengths) - - to_project.append(hidden) - - # projecting to images - images = [] - for tensor, projection in zip(to_project, reversed(self.projection_blocks)): - image = projection(tensor) - images.append(F.interpolate(image, size=input.shape[-2:])) # TODO write this loop using self.upsample - - result = sum(images) - - assert result.shape[-2:] == input.shape[-2:] - - # remove padding - result = result[:, :, :D, :T] - return result, input_length - - -class GaussianFourierProjection(NeuralModule): - """Gaussian Fourier embeddings for input scalars. - - The input scalars are typically time or noise levels. - """ - - def __init__(self, embedding_size: int = 256, scale: float = 1.0): - super().__init__() - self.W = torch.nn.Parameter(torch.randn(embedding_size) * scale, requires_grad=False) - - @property - def input_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "input": NeuralType(('B',), FloatType()), - } - - @property - def output_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "output": NeuralType(('B', 'D'), VoidType()), - } - - def forward(self, input): - x_proj = input[:, None] * self.W[None, :] * 2 * math.pi - return torch.cat([torch.sin(x_proj), torch.cos(x_proj)], dim=-1) - - -class ResnetBlockBigGANPlusPlus(torch.nn.Module): - """Implementation of a ResNet block for the BigGAN model. - - References: - - Song et al., Score-Based Generative Modeling through Stochastic Differential Equations, NeurIPS 2021 - - Brock et al., Large scale GAN training for high fidelity natural image synthesis, ICLR 2018 - """ - - def __init__( - self, - activation: torch.nn.Module, - in_ch: int, - out_ch: int, - diffusion_step_embedding_dim: Optional[int] = None, - init_scale: float = 1e-5, - dropout_rate: float = 0.1, - in_num_groups: Optional[int] = None, - out_num_groups: Optional[int] = None, - eps: float = 1e-6, - ): - """ - Args: - activation (torch.nn.Module): activation layer (ReLU, SiLU, etc) - in_ch (int): number of channels in the input image - out_ch (int, optional): number of channels in the output image - diffusion_step_embedding_dim (int, optional): dimension of diffusion timestep embedding. Defaults to None (no embedding). - dropout_rate (float, optional): dropout rate. Defaults to 0.1. - init_scale (float, optional): scaling for weight initialization. Defaults to 0.0. - in_num_groups (int, optional): num_groups in the first GroupNorm. Defaults to min(in_ch // 4, 32) - out_num_groups (int, optional): num_groups in the second GroupNorm. Defaults to min(out_ch // 4, 32) - eps (float, optional): eps parameter of GroupNorms. Defaults to 1e-6. - """ - super().__init__() - in_num_groups = in_num_groups or min(in_ch // 4, 32) - out_num_groups = out_num_groups or min(out_ch // 4, 32) - - self.init_scale = init_scale - - self.input_block = torch.nn.Sequential( - torch.nn.GroupNorm(num_groups=in_num_groups, num_channels=in_ch, eps=eps), - activation, - ) - - self.middle_conv = torch.nn.Conv2d(in_channels=in_ch, out_channels=out_ch, kernel_size=3, padding=1) - if diffusion_step_embedding_dim is not None: - self.diffusion_step_projection = torch.nn.Sequential( - activation, - torch.nn.Linear(diffusion_step_embedding_dim, out_ch), - einops.layers.torch.Rearrange("batch dim -> batch dim 1 1"), - ) - - self.output_block = torch.nn.Sequential( - torch.nn.GroupNorm(num_groups=out_num_groups, num_channels=out_ch, eps=eps), - activation, - torch.nn.Dropout(dropout_rate), - torch.nn.Conv2d(in_channels=out_ch, out_channels=out_ch, kernel_size=3, padding=1), - ) - - if in_ch != out_ch: - self.residual_projection = torch.nn.Conv2d(in_channels=in_ch, out_channels=out_ch, kernel_size=1) - - self.act = activation - self.in_ch = in_ch - self.out_ch = out_ch - - self.init_weights_() - - def init_weights_(self): - """Weight initialization""" - for module in self.modules(): - if isinstance(module, (torch.nn.Conv2d, torch.nn.Linear)): - torch.nn.init.xavier_uniform_(module.weight) - if module.bias is not None: - torch.nn.init.zeros_(module.bias) - - # a single Conv2d is initialized with gain - torch.nn.init.xavier_uniform_(self.output_block[-1].weight, gain=self.init_scale) - - def forward(self, x: torch.Tensor, diffusion_time_embedding: Optional[torch.Tensor] = None): - """Forward pass of the model. - - Args: - x: input tensor - diffusion_time_embedding: embedding of the diffusion time step - - Returns: - Output tensor - """ - h = self.input_block(x) - h = self.middle_conv(h) - - if diffusion_time_embedding is not None: - h = h + self.diffusion_step_projection(diffusion_time_embedding) - - h = self.output_block(h) - - if x.shape != h.shape: # matching number of channels - x = self.residual_projection(x) - return (x + h) / math.sqrt(2.0) diff --git a/nemo/collections/audio/parts/submodules/schroedinger_bridge.py b/nemo/collections/audio/parts/submodules/schroedinger_bridge.py deleted file mode 100644 index 77a971ed89231f22957108eec9d5b7aacafeb1f4..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/parts/submodules/schroedinger_bridge.py +++ /dev/null @@ -1,607 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import math -from abc import ABC, abstractmethod -from typing import Optional - -import torch - -from nemo.collections.common.parts.utils import mask_sequence_tensor -from nemo.core.classes import NeuralModule, typecheck -from nemo.core.neural_types import LengthsType, NeuralType, SpectrogramType -from nemo.utils import logging - - -class SBNoiseSchedule(NeuralModule, ABC): - """Noise schedule for the Schrödinger Bridge - - Args: - time_min: minimum time for the process - time_max: maximum time for the process - num_steps: number of steps for the process - eps: small regularization - - References: - Schrödinger Bridge for Generative Speech Enhancement, https://arxiv.org/abs/2407.16074 - """ - - def __init__( - self, - time_min: float = 0.0, - time_max: float = 1.0, - num_steps: int = 100, - eps: float = 1e-8, - ): - super().__init__() - - # min and max time - if time_min < 0: - raise ValueError(f'time_min should be non-negative, current value {time_min}') - - if time_max <= time_min: - raise ValueError(f'time_max should be larger than time_min, current max {time_max} and min {time_min}') - - self.time_min = time_min - self.time_max = time_max - - if num_steps <= 0: - raise ValueError(f'Expected num_steps > 0, got {num_steps}') - - self.num_steps = num_steps - - if eps <= 0: - raise ValueError(f'Expected eps > 0, got {eps}') - - self.eps = eps - - logging.debug('Initialized %s with', self.__class__.__name__) - logging.debug('\ttime_min: %s', self.time_min) - logging.debug('\ttime_max: %s', self.time_max) - logging.debug('\tnum_steps: %s', self.num_steps) - logging.debug('\teps: %s', self.eps) - - @property - def dt(self) -> float: - """Time step for the process.""" - return self.time_max / self.num_steps - - @property - def time_delta(self) -> float: - """Time range for the process.""" - return self.time_max - self.time_min - - def generate_time(self, size: int, device: torch.device) -> torch.Tensor: - """Generate random time steps in the valid range.""" - time = torch.rand(size, device=device) * self.time_delta + self.time_min - return time - - @property - def alpha_t_max(self): - """Return alpha_t at t_max.""" - t_max = torch.tensor([self.time_max], device=alpha.device) - return self.alpha(t_max) - - @property - def sigma_t_max(self): - """Return sigma_t at t_max.""" - t_max = torch.tensor([self.time_max], device=alpha.device) - return self.sigma(t_max) - - @abstractmethod - def f(self, time: torch.Tensor) -> torch.Tensor: - """Drift scaling f(t). - - Args: - time: tensor with time steps - - Returns: - Tensor the same size as time, representing drift scaling. - """ - pass - - @abstractmethod - def g(self, time: torch.Tensor) -> torch.Tensor: - """Diffusion scaling g(t). - - Args: - time: tensor with time steps - - Returns: - Tensor the same size as time, representing diffusion scaling. - """ - pass - - @abstractmethod - def alpha(self, time: torch.Tensor) -> torch.Tensor: - """Return alpha for SB noise schedule. - - alpha_t = exp( int_0^s f(s) ds ) - - Args: - time: tensor with time steps - - Returns: - Tensor the same size as time, representing alpha for each time. - """ - pass - - def alpha_bar_from_alpha(self, alpha: torch.Tensor) -> (torch.Tensor, torch.Tensor): - """Return alpha_bar for SB. - - alpha_bar = alpha_t / alpha_t_max - - Args: - alpha: tensor with alpha values - - Returns: - Tensors the same size as alpha, representing alpha_bar and alpha_t_max. - """ - alpha_t_max = self.alpha(torch.tensor([self.time_max], device=alpha.device)) - alpha_bar = alpha / (alpha_t_max + self.eps) - return alpha_bar, alpha_t_max - - def get_alphas(self, time: torch.Tensor) -> (torch.Tensor, torch.Tensor, torch.Tensor): - """Return alpha, alpha_bar and alpha_t_max for SB. - - Args: - time: tensor with time steps - - Returns: - Tuple of tensors with alpha, alpha_bar and alpha_t_max. - """ - alpha = self.alpha(time) - alpha_bar, alpha_t_max = self.alpha_bar_from_alpha(alpha) - return alpha, alpha_bar, alpha_t_max - - @abstractmethod - def sigma(self, time: torch.Tensor) -> torch.Tensor: - """Return sigma_t for SB. - - sigma_t^2 = int_0^s g^2(s) / alpha_s^2 ds - - Args: - time: tensor with time steps - - Returns: - Tensor the same size as time, representing sigma for each time. - """ - pass - - def sigma_bar_from_sigma(self, sigma: torch.Tensor) -> (torch.Tensor, torch.Tensor): - """Return sigma_bar_t for SB. - - sigma_bar_t^2 = sigma_t_max^2 - sigma_t^2 - - Args: - sigma: tensor with sigma values - - Returns: - Tensors the same size as sigma, representing sigma_bar and sigma_t_max. - """ - sigma_t_max = self.sigma(torch.tensor([self.time_max], device=sigma.device)) - sigma_bar_sq = sigma_t_max**2 - sigma**2 - return torch.sqrt(sigma_bar_sq + self.eps), sigma_t_max - - def get_sigmas(self, time: torch.Tensor) -> (torch.Tensor, torch.Tensor, torch.Tensor): - """Return sigma, sigma_bar and sigma_t_max for SB. - - Args: - time: tensor with time steps - - Returns: - Tuple of tensors with sigma, sigma_bar and sigma_t_max. - """ - sigma = self.sigma(time) - sigma_bar, sigma_t_max = self.sigma_bar_from_sigma(sigma) - return sigma, sigma_bar, sigma_t_max - - @abstractmethod - def copy(self): - """Return a copy of the noise schedule.""" - pass - - def __repr__(self): - desc = f'{self.__class__.__name__}(time_min={self.time_min}, time_max={self.time_max}, num_steps={self.num_steps})' - desc += f'\n\tdt: {self.dt}' - desc += f'\n\ttime_delta: {self.time_delta}' - return desc - - -class SBNoiseScheduleVE(SBNoiseSchedule): - """Variance exploding noise schedule for the Schrödinger Bridge. - - Args: - k: defines the base for the exponential diffusion coefficient - c: scaling for the diffusion coefficient - time_min: minimum time for the process - time_max: maximum time for the process - num_steps: number of steps for the process - eps: small regularization - - References: - Schrödinger Bridge for Generative Speech Enhancement, https://arxiv.org/abs/2407.16074 - """ - - def __init__( - self, - k: float, - c: float, - time_min: float = 0.0, - time_max: float = 1.0, - num_steps: int = 100, - eps: float = 1e-8, - ): - super().__init__(time_min=time_min, time_max=time_max, num_steps=num_steps, eps=eps) - - # Shape parameters - if k <= 1: - raise ValueError(f'Expected k > 1, got {k}') - - if c <= 0: - raise ValueError(f'Expected c > 0, got {c}') - - self.c = c - self.k = k - - logging.debug('Initialized %s with', self.__class__.__name__) - logging.debug('\tk: %s', self.k) - logging.debug('\tc: %s', self.c) - logging.debug('\ttime_min: %s', self.time_min) - logging.debug('\ttime_max: %s', self.time_max) - logging.debug('\tnum_steps: %s', self.num_steps) - logging.debug('\teps: %s', self.eps) - - def f(self, time: torch.Tensor) -> torch.Tensor: - return torch.zeros_like(time) - - def g(self, time: torch.Tensor) -> torch.Tensor: - return torch.sqrt(self.c) * self.k**self.time - - def alpha(self, time: torch.Tensor) -> torch.Tensor: - return torch.ones_like(time) - - def sigma(self, time: torch.Tensor) -> torch.Tensor: - sigma_sq = self.c * (self.k ** (2 * time) - 1) / (2 * math.log(self.k) + self.eps) - return torch.sqrt(sigma_sq) - - def copy(self): - return SBNoiseScheduleVE( - k=self.k, - c=self.c, - time_min=self.time_min, - time_max=self.time_max, - num_steps=self.num_steps, - eps=self.eps, - ) - - def __repr__(self): - desc = super().__repr__() - desc += f'\n\tk: {self.k}' - desc += f'\n\tc: {self.c}' - return desc - - -class SBNoiseScheduleVP(SBNoiseSchedule): - """Variance preserving noise schedule for the Schrödinger Bridge. - - Args: - beta_0: defines the lower bound for diffusion coefficient - beta_1: defines upper bound for diffusion coefficient - c: scaling for the diffusion coefficient - time_min: minimum time for the process - time_max: maximum time for the process - num_steps: number of steps for the process - eps: small regularization - """ - - def __init__( - self, - beta_0: float, - beta_1: float, - c: float = 1.0, - time_min: float = 0.0, - time_max: float = 1.0, - num_steps: int = 100, - eps: float = 1e-8, - ): - super().__init__(time_min=time_min, time_max=time_max, num_steps=num_steps, eps=eps) - - # Shape parameters - if beta_0 < 0: - raise ValueError(f'Expected beta_0 >= 0, got {beta_0}') - - if beta_1 < 0: - raise ValueError(f'Expected beta_1 >= 0, got {beta_1}') - - if beta_0 >= beta_1: - raise ValueError(f'Expected beta_0 < beta_1, got beta_0={beta_0} and beta_1={beta_1}') - - if c <= 0: - raise ValueError(f'Expected c > 0, got {c}') - - self.beta_0 = beta_0 - self.beta_1 = beta_1 - self.c = c - - logging.debug('Initialized %s with', self.__class__.__name__) - logging.debug('\tbeta_0: %s', self.beta_0) - logging.debug('\tbeta_1: %s', self.beta_1) - logging.debug('\tc: %s', self.c) - logging.debug('\ttime_min: %s', self.time_min) - logging.debug('\ttime_max: %s', self.time_max) - logging.debug('\tnum_steps: %s', self.num_steps) - logging.debug('\teps: %s', self.eps) - - def f(self, time: torch.Tensor) -> torch.Tensor: - return -0.5 * (self.beta_0 + time * (self.beta_1 - self.beta_0)) - - def g(self, time: torch.Tensor) -> torch.Tensor: - g_sq = self.c * (self.beta_0 + time * (self.beta_1 - self.beta_0)) - return torch.sqrt(g_sq) - - def alpha(self, time: torch.Tensor) -> torch.Tensor: - tmp = self.beta_0 * time + (self.beta_1 - self.beta_0) / 2 * time**2 - return torch.exp(-0.5 * tmp) - - def sigma(self, time: torch.Tensor) -> torch.Tensor: - sigma_sq = self.beta_0 * time + (self.beta_1 - self.beta_0) / 2 * time**2 - sigma_sq = torch.exp(sigma_sq) - 1 - sigma_sq = self.c * sigma_sq - return torch.sqrt(sigma_sq) - - def copy(self): - return SBNoiseScheduleVP( - beta_0=self.beta_0, - beta_1=self.beta_1, - c=self.c, - time_min=self.time_min, - time_max=self.time_max, - num_steps=self.num_steps, - eps=self.eps, - ) - - def __repr__(self): - desc = super().__repr__() - desc += f'\n\tbeta_0: {self.beta_0}' - desc += f'\n\tbeta_1: {self.beta_1}' - desc += f'\n\tc: {self.c}' - return desc - - -class SBSampler(NeuralModule): - """Schrödinger Bridge sampler. - - Args: - noise_schedule: noise schedule for the bridge - estimator: neural estimator - estimator_output: defines the output of the estimator, e.g., data_prediction - estimator_time: time for conditioning the estimator, e.g., 'current' - or 'previous'. Default is 'previous'. - process: defines the process, e.g., sde or ode - time_max: maximum time for the process - time_min: minimum time for the process - num_steps: number of steps for the process - eps: small regularization to prevent division by zero - - References: - Schrödinger Bridge for Generative Speech Enhancement, https://arxiv.org/abs/2407.16074 - Schrodinger Bridges Beat Diffusion Models on Text-to-Speech Synthesis, https://arxiv.org/abs/2312.03491 - """ - - def __init__( - self, - noise_schedule: SBNoiseSchedule, - estimator: NeuralModule, # neural estimator - estimator_output: str, - estimator_time: str = 'previous', # time for the estimator - process: str = 'sde', - time_max: Optional[float] = None, - time_min: Optional[float] = None, - num_steps: int = 50, - eps: float = 1e-8, - ): - super().__init__() - # Create a copy of the noise schedule - self.noise_schedule = noise_schedule.copy() - - # Update sampling parameters - if time_max is not None: - self.noise_schedule.time_max = time_max - logging.info('noise_schedule.time_max set to: %s', self.noise_schedule.time_max) - - if time_min is not None: - self.noise_schedule.time_min = time_min - logging.info('noise_schedule.time_min set to: %s', self.noise_schedule.time_min) - - self.noise_schedule.num_steps = num_steps - logging.info('noise_schedule.num_steps set to: %s', self.noise_schedule.num_steps) - - # Estimator - self.estimator = estimator - self.estimator_output = estimator_output - self.estimator_time = estimator_time - - # Sampling process - self.process = process - - # Small regularization - if eps <= 0: - raise ValueError(f'Expected eps > 0, got {eps}') - self.eps = eps - - logging.debug('Initialized %s with', self.__class__.__name__) - logging.debug('\testimator_output: %s', self.estimator_output) - logging.debug('\testimator_time: %s', self.estimator_time) - logging.debug('\tprocess: %s', self.process) - logging.debug('\ttime_min: %s', self.time_min) - logging.debug('\ttime_max: %s', self.time_max) - logging.debug('\tnum_steps: %s', self.num_steps) - logging.debug('\teps: %s', self.eps) - - @property - def time_max(self): - return self.noise_schedule.time_max - - @time_max.setter - def time_max(self, value: float): - self.noise_schedule.time_max = value - logging.debug('noise_schedule.time_max set to: %s', self.noise_schedule.time_max) - - @property - def time_min(self): - return self.noise_schedule.time_min - - @time_min.setter - def time_min(self, value: float): - self.noise_schedule.time_min = value - logging.debug('noise_schedule.time_min set to: %s', self.noise_schedule.time_min) - - @property - def num_steps(self): - return self.noise_schedule.num_steps - - @num_steps.setter - def num_steps(self, value: int): - self.noise_schedule.num_steps = value - logging.debug('noise_schedule.num_steps set to: %s', self.noise_schedule.num_steps) - - @property - def process(self): - return self._process - - @process.setter - def process(self, value: str): - if value not in ['sde', 'ode']: - raise ValueError(f'Unexpected process: {value}') - self._process = value - logging.info('process set to: %s', self._process) - - @property - def estimator_time(self): - return self._estimator_time - - @estimator_time.setter - def estimator_time(self, value: str): - if value not in ['current', 'previous']: - raise ValueError(f'Unexpected estimator time: {value}') - self._estimator_time = value - logging.info('estimator time set to: %s', self._estimator_time) - - @typecheck( - input_types={ - "prior_mean": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "estimator_condition": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType(), optional=True), - "state_length": NeuralType(tuple('B'), LengthsType(), optional=True), - }, - output_types={ - "sample": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "state_length": NeuralType(tuple('B'), LengthsType(), optional=True), - }, - ) - @torch.inference_mode() - def forward( - self, prior_mean: torch.Tensor, estimator_condition: torch.Tensor, state_length: Optional[torch.Tensor] = None - ) -> torch.Tensor: - """Takes prior mean and generates a sample.""" - # SB starts from the prior mean - state = prior_mean - - if state_length is not None: - state = mask_sequence_tensor(state, state_length) - - # Time steps for sampling - time_steps = torch.linspace(self.time_max, self.time_min, self.num_steps + 1, device=state.device) - - # Initial values - time_prev = time_steps[0] * torch.ones(state.shape[0], device=state.device) - alpha_prev, _, alpha_t_max = self.noise_schedule.get_alphas(time_prev) - sigma_prev, sigma_bar_prev, sigma_t_max = self.noise_schedule.get_sigmas(time_prev) - - # Sampling - # Sample at the initial time step (`self.time_max`) is exactly the prior_mean. - # We do not need to estimate it, but we need to pass it to the next time step. - # We iterate through the following time steps to generate the sample at the final time (`self.time_min`). - for t in time_steps[1:]: - - # Prepare time steps for the whole batch - time = t * torch.ones(state.shape[0], device=state.device) - - # Prepare input for estimator, concatenate conditioning along the channel dimension - estimator_input = state if estimator_condition is None else torch.cat([state, estimator_condition], dim=1) - estimator_time = time if self.estimator_time == 'current' else time_prev - - # Estimator - if self.estimator_output == 'data_prediction': - current_estimate, _ = self.estimator( - input=estimator_input, input_length=state_length, condition=estimator_time - ) - else: - raise NotImplementedError(f'Unexpected estimator output: {self.estimator_output}') - - # Get noise schedule for current time - alpha_t, alpha_bar_t, _ = self.noise_schedule.get_alphas(time) - sigma_t, sigma_bar_t, _ = self.noise_schedule.get_sigmas(time) - - if self.process == 'sde': - # Calculate scaling for the first-order discretization from the paper - weight_prev = alpha_t * sigma_t**2 / (alpha_prev * sigma_prev**2 + self.eps) - tmp = 1 - sigma_t**2 / (sigma_prev**2 + self.eps) - weight_estimate = alpha_t * tmp - weight_z = alpha_t * sigma_t * torch.sqrt(tmp) - - # View as [B, C, D, T] - weight_prev = weight_prev.view(-1, 1, 1, 1) - weight_estimate = weight_estimate.view(-1, 1, 1, 1) - weight_z = weight_z.view(-1, 1, 1, 1) - - # Random sample - z_norm = torch.randn_like(state) - - # Update state: weighted sum of previous state, current estimate and noise - state = weight_prev * state + weight_estimate * current_estimate + weight_z * z_norm - elif self.process == 'ode': - # Calculate scaling for the first-order discretization from the paper - weight_prev = alpha_t * sigma_t * sigma_bar_t / (alpha_prev * sigma_prev * sigma_bar_prev + self.eps) - weight_estimate = ( - alpha_t - / (sigma_t_max**2 + self.eps) - * (sigma_bar_t**2 - sigma_bar_prev * sigma_t * sigma_bar_t / (sigma_prev + self.eps)) - ) - weight_prior_mean = ( - alpha_t - / (alpha_t_max * sigma_t_max**2 + self.eps) - * (sigma_t**2 - sigma_prev * sigma_t * sigma_bar_t / (sigma_bar_prev + self.eps)) - ) - - # View as [B, C, D, T] - weight_prev = weight_prev.view(-1, 1, 1, 1) - weight_estimate = weight_estimate.view(-1, 1, 1, 1) - weight_prior_mean = weight_prior_mean.view(-1, 1, 1, 1) - - # Update state: weighted sum of previous state, current estimate and prior - state = weight_prev * state + weight_estimate * current_estimate + weight_prior_mean * prior_mean - else: - raise RuntimeError(f'Unexpected process: {self.process}') - - # Save previous values - time_prev = time - alpha_prev = alpha_t - sigma_prev = sigma_t - sigma_bar_prev = sigma_bar_t - - # Final output - if state_length is not None: - state = mask_sequence_tensor(state, state_length) - - return state, state_length diff --git a/nemo/collections/audio/parts/submodules/transformerunet.py b/nemo/collections/audio/parts/submodules/transformerunet.py deleted file mode 100644 index 89d8bcc275df0812e42eef4c5b0d6bb1b0d445f0..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/parts/submodules/transformerunet.py +++ /dev/null @@ -1,513 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# MIT License -# -# Copyright (c) 2023 Phil Wang -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in all -# copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - -import math -from functools import partial -from typing import Dict, Optional - -import einops -import torch -import torch.nn.functional as F -from torch import nn -from torch.nn import Module - -from nemo.core.classes import NeuralModule, typecheck -from nemo.core.neural_types import BoolType, FloatType, LengthsType, NeuralType, SpectrogramType -from nemo.utils import logging - -__all__ = ['TransformerUNet'] - - -class LearnedSinusoidalPosEmb(Module): - """The sinusoidal Embedding to encode time conditional information""" - - def __init__(self, dim: int): - super().__init__() - if (dim % 2) != 0: - raise ValueError(f"Input dimension {dim} is not divisible by 2!") - half_dim = dim // 2 - self.weights = nn.Parameter(torch.randn(half_dim)) - - def forward(self, t: torch.Tensor) -> torch.Tensor: - """ - Args: - t: input time tensor, shape (B) - - Return: - fouriered: the encoded time conditional embedding, shape (B, D) - """ - t = einops.rearrange(t, 'b -> b 1') - freqs = t * einops.rearrange(self.weights, 'd -> 1 d') * 2 * math.pi - fouriered = torch.cat((freqs.sin(), freqs.cos()), dim=-1) - return fouriered - - -class ConvPositionEmbed(Module): - """The Convolutional Embedding to encode time information of each frame""" - - def __init__(self, dim: int, kernel_size: int, groups: Optional[int] = None): - super().__init__() - if (kernel_size % 2) == 0: - raise ValueError(f"Kernel size {kernel_size} is divisible by 2!") - - if groups is None: - groups = dim - - self.dw_conv1d = nn.Sequential( - nn.Conv1d(dim, dim, kernel_size, groups=groups, padding=kernel_size // 2), nn.GELU() - ) - - def forward(self, x, mask=None): - """ - Args: - x: input tensor, shape (B, T, D) - - Return: - out: output tensor with the same shape (B, T, D) - """ - - if mask is not None: - mask = mask[..., None] - x = x.masked_fill(mask, 0.0) - - x = einops.rearrange(x, 'b n c -> b c n') - x = self.dw_conv1d(x) - out = einops.rearrange(x, 'b c n -> b n c') - - if mask is not None: - out = out.masked_fill(mask, 0.0) - - return out - - -class RMSNorm(Module): - """The Root Mean Square Layer Normalization - - References: - - Zhang et al., Root Mean Square Layer Normalization, 2019 - """ - - def __init__(self, dim): - super().__init__() - self.scale = dim**0.5 - self.gamma = nn.Parameter(torch.ones(dim)) - - def forward(self, x: torch.Tensor): - return F.normalize(x, dim=-1) * self.scale * self.gamma - - -class AdaptiveRMSNorm(Module): - """ - Adaptive Root Mean Square Layer Normalization given a conditional embedding. - This enables the model to consider the conditional input during normalization. - """ - - def __init__(self, dim: int, cond_dim: Optional[int] = None): - super().__init__() - if cond_dim is None: - cond_dim = dim - self.scale = dim**0.5 - - self.to_gamma = nn.Linear(cond_dim, dim) - self.to_beta = nn.Linear(cond_dim, dim) - - # init adaptive normalization to identity - - nn.init.zeros_(self.to_gamma.weight) - nn.init.ones_(self.to_gamma.bias) - - nn.init.zeros_(self.to_beta.weight) - nn.init.zeros_(self.to_beta.bias) - - def forward(self, x: torch.Tensor, cond: torch.Tensor): - normed = F.normalize(x, dim=-1) * self.scale - - gamma, beta = self.to_gamma(cond), self.to_beta(cond) - gamma = einops.rearrange(gamma, 'B D -> B 1 D') - beta = einops.rearrange(beta, 'B D -> B 1 D') - - return normed * gamma + beta - - -class GEGLU(Module): - """The GeGLU activation implementation""" - - def forward(self, x: torch.Tensor): - x, gate = x.chunk(2, dim=-1) - return F.gelu(gate) * x - - -def get_feedforward_layer(dim: int, mult: int = 4, dropout: float = 0.0): - """ - Return a Feed-Forward layer for the Transformer Layer. - GeGLU activation is used in this FF layer - """ - dim_inner = int(dim * mult * 2 / 3) - return nn.Sequential(nn.Linear(dim, dim_inner * 2), GEGLU(), nn.Dropout(dropout), nn.Linear(dim_inner, dim)) - - -class TransformerUNet(NeuralModule): - """ - Implementation of the transformer Encoder Model with U-Net structure used in - VoiceBox and AudioBox - - References: - Le et al., Voicebox: Text-Guided Multilingual Universal Speech Generation at Scale, 2023 - Vyas et al., Audiobox: Unified Audio Generation with Natural Language Prompts, 2023 - """ - - def __init__( - self, - dim: int, - depth: int, - heads: int = 8, - ff_mult: int = 4, - attn_dropout: float = 0.0, - ff_dropout: float = 0.0, - max_positions: int = 6000, - adaptive_rmsnorm: bool = False, - adaptive_rmsnorm_cond_dim_in: Optional[int] = None, - use_unet_skip_connection: bool = True, - skip_connect_scale: Optional[int] = None, - ): - """ - Args: - dim: Embedding dimension - depth: Number of Transformer Encoder Layers - heads: Number of heads in MHA - ff_mult: The multiplier for the feedforward dimension (ff_dim = ff_mult * dim) - attn_dropout: dropout rate for the MHA layer - ff_dropout: droupout rate for the feedforward layer - max_positions: The maximum time length of the input during training and inference - adaptive_rmsnorm: Whether to use AdaptiveRMS layer. - Set to True if the model has a conditional embedding in forward() - adaptive_rms_cond_dim_in: Dimension of the conditional embedding - use_unet_skip_connection: Whether to use U-Net or not - skip_connect_scale: The scale of the U-Net connection. - """ - super().__init__() - if (depth % 2) != 0: - raise ValueError(f"Number of layers {depth} is not divisible by 2!") - self.layers = nn.ModuleList([]) - self.init_alibi(max_positions=max_positions, heads=heads) - - if adaptive_rmsnorm and adaptive_rmsnorm_cond_dim_in is None: - raise ValueError("adaptive_rmsnorm_cond_dim_in must be provided if adaptive_rmsnorm is True") - self.adaptive_rmsnorm = adaptive_rmsnorm - self.adaptive_rmsnorm_cond_dim_in = adaptive_rmsnorm_cond_dim_in - - if self.adaptive_rmsnorm: - rmsnorm_class = partial(AdaptiveRMSNorm, cond_dim=adaptive_rmsnorm_cond_dim_in) - else: - rmsnorm_class = RMSNorm - - if skip_connect_scale is None: - self.skip_connect_scale = 2**-0.5 - else: - self.skip_connect_scale = skip_connect_scale - - for ind in range(depth): - layer = ind + 1 - has_skip = use_unet_skip_connection and layer > (depth // 2) - - self.layers.append( - nn.ModuleList( - [ - nn.Linear(dim * 2, dim) if has_skip else None, - rmsnorm_class(dim=dim), - nn.MultiheadAttention( - embed_dim=dim, - num_heads=heads, - dropout=attn_dropout, - batch_first=True, - ), - rmsnorm_class(dim=dim), - get_feedforward_layer(dim=dim, mult=ff_mult, dropout=ff_dropout), - ] - ) - ) - - self.final_norm = RMSNorm(dim) - - logging.debug('Initialized %s with', self.__class__.__name__) - logging.debug('\tembedding dim: %s', dim) - logging.debug('\tNumber of Layer: %s', depth) - logging.debug('\tfeedforward dim: %s', dim * ff_mult) - logging.debug('\tnumber of heads: %s', heads) - logging.debug('\tDropout rate of MHA: %s', attn_dropout) - logging.debug('\tDropout rate of FF: %s', ff_dropout) - logging.debug('\tnumber of heads: %s', heads) - logging.debug('\tmaximun time length: %s', max_positions) - logging.debug('\tuse AdaptiveRMS: %s', adaptive_rmsnorm) - logging.debug('\tConditional dim: %s', adaptive_rmsnorm_cond_dim_in) - logging.debug('\tUse UNet connection: %s', use_unet_skip_connection) - logging.debug('\tskip connect scale: %s', self.skip_connect_scale) - - def init_alibi( - self, - max_positions: int, - heads: int, - ): - """Initialize the Alibi bias parameters - - References: - - Press et al., Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation, 2021 - """ - - def get_slopes(n): - ratio = 2 ** (-8 / n) - return ratio ** torch.arange(1, n + 1) - - if not math.log2(heads).is_integer(): - logging.warning( - "It is recommend to set number of attention heads to be the power of 2 for the Alibi bias!" - ) - logging.warning(f"Current value of heads: {heads}") - - self.slopes = nn.Parameter(einops.rearrange(get_slopes(heads), "B -> B 1 1")) - - pos_matrix = ( - -1 * torch.abs(torch.arange(max_positions).unsqueeze(0) - torch.arange(max_positions).unsqueeze(1)).float() - ) - pos_matrix = einops.rearrange(pos_matrix, "T1 T2 -> 1 T1 T2") - self.register_buffer('pos_matrix', pos_matrix, persistent=False) - - @property - def input_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "x": NeuralType(('B', 'T', 'D'), FloatType()), - "key_padding_mask": NeuralType(('B', 'T'), BoolType(), optional=True), - "adaptive_rmsnorm_cond": NeuralType(('B', 'D'), FloatType(), optional=True), - } - - @property - def output_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "output": NeuralType(('B', 'T', 'D'), FloatType()), - } - - @typecheck() - def forward(self, x, key_padding_mask: Optional[torch.Tensor] = None, adaptive_rmsnorm_cond=None): - """Forward pass of the model. - - Args: - input: input tensor, shape (B, C, D, T) - key_padding_mask: mask tensor indicating the padding parts, shape (B, T) - adaptive_rmsnorm_cond: conditional input for the model, shape (B, D) - """ - batch_size, seq_len, *_ = x.shape - skip_connects = [] - alibi_bias = self.get_alibi_bias(batch_size=batch_size, seq_len=seq_len) - - rmsnorm_kwargs = dict() - if adaptive_rmsnorm_cond is not None: - rmsnorm_kwargs = dict(cond=adaptive_rmsnorm_cond) - - for skip_combiner, attn_prenorm, attn, ff_prenorm, ff in self.layers: - - if skip_combiner is None: - skip_connects.append(x) - else: - skip_connect = skip_connects.pop() * self.skip_connect_scale - x = torch.cat((x, skip_connect), dim=-1) - x = skip_combiner(x) - - attn_input = attn_prenorm(x, **rmsnorm_kwargs) - if key_padding_mask is not None: - # Since Alibi_bias is a float-type attn_mask, the padding_mask need to be float-type. - float_key_padding_mask = key_padding_mask.float() - float_key_padding_mask = float_key_padding_mask.masked_fill(key_padding_mask, float('-inf')) - else: - float_key_padding_mask = None - - attn_output, _ = attn( - query=attn_input, - key=attn_input, - value=attn_input, - key_padding_mask=float_key_padding_mask, - need_weights=False, - attn_mask=alibi_bias, - ) - x = x + attn_output - - ff_input = ff_prenorm(x, **rmsnorm_kwargs) - x = ff(ff_input) + x - - return self.final_norm(x) - - def get_alibi_bias(self, batch_size: int, seq_len: int): - """ - Return the alibi_bias given batch size and seqence length - """ - pos_matrix = self.pos_matrix[:, :seq_len, :seq_len] - alibi_bias = pos_matrix * self.slopes - alibi_bias = alibi_bias.repeat(batch_size, 1, 1) - - return alibi_bias - - -class SpectrogramTransformerUNet(NeuralModule): - """This model handles complex-valued inputs by stacking real and imaginary components. - Stacked tensor is processed using TransformerUNet and the output is projected to generate real - and imaginary components of the output channels. - - Convolutional Positional Embedding is applied for the input sequence - """ - - def __init__( - self, - in_channels: int = 1, - out_channels: int = 1, - freq_dim: int = 256, - dim: int = 1024, - depth: int = 24, - heads: int = 16, - ff_mult: int = 4, - ff_dropout: float = 0.0, - attn_dropout: float = 0.0, - max_positions: int = 6000, - time_hidden_dim: Optional[int] = None, - conv_pos_embed_kernel_size: int = 31, - conv_pos_embed_groups: Optional[int] = None, - adaptive_rmsnorm: Optional[bool] = True, - ): - super().__init__() - self.in_channels = in_channels - self.out_channels = out_channels - dim_in = freq_dim * in_channels * 2 - - if time_hidden_dim is None: - time_hidden_dim = dim * 4 - - self.proj_in = nn.Linear(dim_in, dim) - if adaptive_rmsnorm: - self.sinu_pos_emb = nn.Sequential(LearnedSinusoidalPosEmb(dim), nn.Linear(dim, time_hidden_dim), nn.SiLU()) - - self.conv_embed = ConvPositionEmbed( - dim=dim, kernel_size=conv_pos_embed_kernel_size, groups=conv_pos_embed_groups - ) - - self.transformerunet = TransformerUNet( - dim=dim, - depth=depth, - heads=heads, - ff_mult=ff_mult, - ff_dropout=ff_dropout, - attn_dropout=attn_dropout, - max_positions=max_positions, - adaptive_rmsnorm=adaptive_rmsnorm, - adaptive_rmsnorm_cond_dim_in=time_hidden_dim, - use_unet_skip_connection=True, - ) - - # 2x the frequency dimension as the model operates in the complex-value domain - dim_out = freq_dim * out_channels * 2 - - self.proj_out = nn.Linear(dim, dim_out) - - logging.debug('Initialized %s with', self.__class__.__name__) - logging.debug('\tin_channels: %s', self.in_channels) - logging.debug('\tout_channels: %s', self.out_channels) - logging.debug('\tInput frequency dimension: %s', freq_dim) - - @property - def input_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "input": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "input_length": NeuralType(('B',), LengthsType(), optional=True), - "condition": NeuralType(('B',), FloatType(), optional=True), - } - - @property - def output_types(self) -> Dict[str, NeuralType]: - """Returns definitions of module output ports.""" - return { - "output": NeuralType(('B', 'C', 'D', 'T'), SpectrogramType()), - "output_length": NeuralType(('B',), LengthsType(), optional=True), - } - - @staticmethod - def _get_key_padding_mask(input_length: torch.Tensor, max_length: int): - """ - Return the self_attention masking according to the input length. - 0 indicates the frame is in the valid range, while 1 indicates the frame is a padding frame. - Args: - input_length: shape (B) - max_length (int): The maximum length of the input sequence - - return: - key_padding_mask: shape (B, T) - """ - key_padding_mask = torch.arange(max_length).expand(len(input_length), max_length).to(input_length.device) - key_padding_mask = key_padding_mask >= input_length.unsqueeze(1) - return key_padding_mask - - @typecheck() - def forward(self, input, input_length=None, condition=None): - """Forward pass of the model. - - Args: - input: input tensor, shape (B, C, D, T) - input_length: length of the valid time steps for each example in the batch, shape (B,) - condition: scalar condition (time) for the model, will be embedded using `self.time_embedding` - """ - # Stack real and imaginary components - B, C_in, D, T = input.shape - if C_in != self.in_channels: - raise RuntimeError(f'Unexpected input channel size {C_in}, expected {self.in_channels}') - - input_real_imag = torch.stack([input.real, input.imag], dim=2) - input = einops.rearrange(input_real_imag, 'B C RI D T -> B T (C RI D)') - - x = self.proj_in(input) - key_padding_mask = self._get_key_padding_mask(input_length, max_length=T) - x = self.conv_embed(x, mask=key_padding_mask) + x - - if condition is None: - time_emb = None - else: - time_emb = self.sinu_pos_emb(condition) - - x = self.transformerunet(x=x, key_padding_mask=key_padding_mask, adaptive_rmsnorm_cond=time_emb) - - output = self.proj_out(x) - output = einops.rearrange(output, "B T (C RI D) -> B C D T RI", C=self.out_channels, RI=2, D=D) - output = torch.view_as_complex(output.contiguous()) - - return output, input_length diff --git a/nemo/collections/audio/parts/utils/__init__.py b/nemo/collections/audio/parts/utils/__init__.py deleted file mode 100644 index 341a77c5bc66dee5d2ba0edf888f91e5bf225e3c..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/parts/utils/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/nemo/collections/audio/parts/utils/audio.py b/nemo/collections/audio/parts/utils/audio.py deleted file mode 100644 index 9019f3ee2945de38110ef09b1257b1d48ecb57cd..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/parts/utils/audio.py +++ /dev/null @@ -1,575 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import math -from typing import Optional - -import librosa -import numpy as np -import numpy.typing as npt -import scipy -import torch -from einops import rearrange, reduce -from scipy.spatial.distance import pdist, squareform - -SOUND_VELOCITY = 343.0 # m/s - - -def sinc_unnormalized(x: float) -> float: - """Unnormalized sinc. - - Args: - x: input value - - Returns: - Calculates sin(x)/x - """ - return np.sinc(x / np.pi) - - -def theoretical_coherence( - mic_positions: npt.NDArray, - sample_rate: float, - field: str = 'spherical', - fft_length: int = 512, - sound_velocity: float = SOUND_VELOCITY, -) -> npt.NDArray: - """Calculate a theoretical coherence matrix for given mic positions and field type. - - Args: - mic_positions: 3D Cartesian coordinates of microphone positions, shape (num_mics, 3) - field: string denoting the type of the soundfield - sample_rate: sampling rate of the input signal in Hz - fft_length: length of the fft in samples - sound_velocity: speed of sound in m/s - - Returns: - Calculated coherence with shape (num_subbands, num_mics, num_mics) - """ - assert mic_positions.shape[1] == 3, "Expecting 3D microphone positions" - num_mics = mic_positions.shape[0] - - if num_mics < 2: - raise ValueError(f'Expecting at least 2 microphones, received {num_mics}') - - num_subbands = fft_length // 2 + 1 - angular_freq = 2 * np.pi * sample_rate * np.arange(0, num_subbands) / fft_length - desired_coherence = np.zeros((num_subbands, num_mics, num_mics)) - - mic_distance = squareform(pdist(mic_positions)) - - for p in range(num_mics): - desired_coherence[:, p, p] = 1.0 - for q in range(p + 1, num_mics): - dist_pq = mic_distance[p, q] - if field == 'spherical': - desired_coherence[:, p, q] = sinc_unnormalized(angular_freq * dist_pq / sound_velocity) - else: - raise ValueError(f'Unknown noise field {field}.') - # symmetry - desired_coherence[:, q, p] = desired_coherence[:, p, q] - - return desired_coherence - - -def estimated_coherence(S: npt.NDArray, eps: float = 1e-16) -> npt.NDArray: - """Estimate complex-valued coherence for the input STFT-domain signal. - - Args: - S: STFT of the signal with shape (num_subbands, num_frames, num_channels) - eps: small regularization constant - - Returns: - Estimated coherence with shape (num_subbands, num_channels, num_channels) - """ - if S.ndim != 3: - raise RuntimeError('Expecting the input STFT to be a 3D array') - - num_subbands, num_frames, num_channels = S.shape - - if num_channels < 2: - raise ValueError('Expecting at least 2 microphones') - - psd = np.mean(np.abs(S) ** 2, axis=1) - estimated_coherence = np.zeros((num_subbands, num_channels, num_channels), dtype=complex) - - for p in range(num_channels): - estimated_coherence[:, p, p] = 1.0 - for q in range(p + 1, num_channels): - cross_psd = np.mean(S[:, :, p] * np.conjugate(S[:, :, q]), axis=1) - estimated_coherence[:, p, q] = cross_psd / np.sqrt(psd[:, p] * psd[:, q] + eps) - # symmetry - estimated_coherence[:, q, p] = np.conjugate(estimated_coherence[:, p, q]) - - return estimated_coherence - - -def generate_approximate_noise_field( - mic_positions: npt.NDArray, - noise_signal: npt.NDArray, - sample_rate: float, - field: str = 'spherical', - fft_length: int = 512, - method: str = 'cholesky', - sound_velocity: float = SOUND_VELOCITY, -): - """ - Args: - mic_positions: 3D microphone positions, shape (num_mics, 3) - noise_signal: signal used to generate the approximate noise field, shape (num_samples, num_mics). - Different channels need to be independent. - sample_rate: sampling rate of the input signal - field: string denoting the type of the soundfield - fft_length: length of the fft in samples - method: coherence decomposition method - sound_velocity: speed of sound in m/s - - Returns: - Signal with coherence approximately matching the desired coherence, shape (num_samples, num_channels) - - References: - E.A.P. Habets, I. Cohen and S. Gannot, 'Generating nonstationary multisensor - signals under a spatial coherence constraint', Journal of the Acoustical Society - of America, Vol. 124, Issue 5, pp. 2911-2917, Nov. 2008. - """ - assert fft_length % 2 == 0 - num_mics = mic_positions.shape[0] - - if num_mics < 2: - raise ValueError('Expecting at least 2 microphones') - - desired_coherence = theoretical_coherence( - mic_positions=mic_positions, - field=field, - sample_rate=sample_rate, - fft_length=fft_length, - sound_velocity=sound_velocity, - ) - - return transform_to_match_coherence(signal=noise_signal, desired_coherence=desired_coherence, method=method) - - -def transform_to_match_coherence( - signal: npt.NDArray, - desired_coherence: npt.NDArray, - method: str = 'cholesky', - ref_channel: int = 0, - corrcoef_threshold: float = 0.2, -) -> npt.NDArray: - """Transform the input multichannel signal to match the desired coherence. - - Note: It's assumed that channels are independent. - - Args: - signal: independent noise signals with shape (num_samples, num_channels) - desired_coherence: desired coherence with shape (num_subbands, num_channels, num_channels) - method: decomposition method used to construct the transformation matrix - ref_channel: reference channel for power normalization of the input signal - corrcoef_threshold: used to detect input signals with high correlation between channels - - Returns: - Signal with coherence approximately matching the desired coherence, shape (num_samples, num_channels) - - References: - E.A.P. Habets, I. Cohen and S. Gannot, 'Generating nonstationary multisensor - signals under a spatial coherence constraint', Journal of the Acoustical Society - of America, Vol. 124, Issue 5, pp. 2911-2917, Nov. 2008. - """ - num_channels = signal.shape[1] - num_subbands = desired_coherence.shape[0] - assert desired_coherence.shape[1] == num_channels - assert desired_coherence.shape[2] == num_channels - - fft_length = 2 * (num_subbands - 1) - - # remove DC component - signal = signal - np.mean(signal, axis=0) - - # channels needs to have equal power, so normalize with the ref mic - signal_power = np.mean(np.abs(signal) ** 2, axis=0) - signal = signal * np.sqrt(signal_power[ref_channel]) / np.sqrt(signal_power) - - # input channels should be uncorrelated - # here, we just check for high correlation coefficients between channels to detect ill-constructed inputs - corrcoef_matrix = np.corrcoef(signal.transpose()) - # mask the diagonal elements - np.fill_diagonal(corrcoef_matrix, 0.0) - if np.any(np.abs(corrcoef_matrix) > corrcoef_threshold): - raise RuntimeError( - f'Input channels are correlated above the threshold {corrcoef_threshold}. Max abs off-diagonal element of the coefficient matrix: {np.abs(corrcoef_matrix).max()}.' - ) - - # analysis transform - S = librosa.stft(signal.transpose(), n_fft=fft_length) - # (channel, subband, frame) -> (subband, frame, channel) - S = S.transpose(1, 2, 0) - - # generate output signal for each subband - X = np.zeros_like(S) - - # factorize the desired coherence (skip the DC component) - if method == 'cholesky': - L = np.linalg.cholesky(desired_coherence[1:]) - A = L.swapaxes(1, 2) - elif method == 'evd': - w, V = np.linalg.eig(desired_coherence[1:]) - # scale eigenvectors - A = np.sqrt(w)[:, None, :] * V - # prepare transform matrix - A = A.swapaxes(1, 2) - else: - raise ValueError(f'Unknown method {method}') - - # transform vectors at each time step: - # x_t = A^T * s_t - # or in matrix notation: X = S * A - X[1:, ...] = np.matmul(S[1:, ...], A) - - # synthesis transform - # transpose X from (subband, frame, channel) to (channel, subband, frame) - x = librosa.istft(X.transpose(2, 0, 1), length=len(signal)) - # (channel, sample) -> (sample, channel) - x = x.transpose() - - return x - - -def rms(x: np.ndarray) -> float: - """Calculate RMS value for the input signal. - - Args: - x: input signal - - Returns: - RMS of the input signal. - """ - return np.sqrt(np.mean(np.abs(x) ** 2)) - - -def mag2db(mag: float, eps: Optional[float] = 1e-16) -> float: - """Convert magnitude ratio from linear scale to dB. - - Args: - mag: linear magnitude value - eps: small regularization constant - - Returns: - Value in dB. - """ - return 20 * np.log10(mag + eps) - - -def db2mag(db: float) -> float: - """Convert value in dB to linear magnitude ratio. - - Args: - db: magnitude ratio in dB - - Returns: - Magnitude ratio in linear scale. - """ - return 10 ** (db / 20) - - -def pow2db(power: float, eps: Optional[float] = 1e-16) -> float: - """Convert power ratio from linear scale to dB. - - Args: - power: power ratio in linear scale - eps: small regularization constant - - Returns: - Power in dB. - """ - return 10 * np.log10(power + eps) - - -def get_segment_start(signal: np.ndarray, segment: np.ndarray) -> int: - """Get starting point of `segment` in `signal`. - We assume that `segment` is a sub-segment of `signal`. - For example, `signal` may be a 10 second audio signal, - and `segment` could be the signal between 2 seconds and - 5 seconds. This function will then return the index of - the sample where `segment` starts (at 2 seconds). - - Args: - signal: numpy array with shape (num_samples,) - segment: numpy array with shape (num_samples,) - - Returns: - Index of the start of `segment` in `signal`. - """ - if len(signal) <= len(segment): - raise ValueError( - f'segment must be shorter than signal: len(segment) = {len(segment)}, len(signal) = {len(signal)}' - ) - cc = scipy.signal.correlate(signal, segment, mode='valid') - return np.argmax(cc) - - -def calculate_sdr_numpy( - estimate: np.ndarray, - target: np.ndarray, - scale_invariant: bool = False, - convolution_invariant: bool = False, - convolution_filter_length: Optional[int] = None, - remove_mean: bool = True, - sdr_max: Optional[float] = None, - eps: float = 1e-8, -) -> float: - """Calculate signal-to-distortion ratio. - - SDR = 10 * log10( ||t||_2^2 / (||e-t||_2^2 + alpha * ||t||^2) - - where - alpha = 10^(-sdr_max/10) - - Optionally, apply scale-invariant scaling to target signal. - - Args: - estimate: estimated signal - target: target signal - - Returns: - SDR in dB. - """ - if scale_invariant and convolution_invariant: - raise ValueError('Arguments scale_invariant and convolution_invariant cannot be used simultaneously.') - - if remove_mean: - estimate = estimate - np.mean(estimate) - target = target - np.mean(target) - - if scale_invariant or (convolution_invariant and convolution_filter_length == 1): - target = scale_invariant_target_numpy(estimate=estimate, target=target, eps=eps) - elif convolution_invariant: - target = convolution_invariant_target_numpy( - estimate=estimate, target=target, filter_length=convolution_filter_length, eps=eps - ) - - target_pow = np.mean(np.abs(target) ** 2) - distortion_pow = np.mean(np.abs(estimate - target) ** 2) - - if sdr_max is not None: - distortion_pow = distortion_pow + 10 ** (-sdr_max / 10) * target_pow - - sdr = 10 * np.log10(target_pow / (distortion_pow + eps) + eps) - return sdr - - -def wrap_to_pi(x: torch.Tensor) -> torch.Tensor: - """Wrap angle in radians to [-pi, pi] - - Args: - x: angle in radians - - Returns: - Angle in radians wrapped to [-pi, pi] - """ - pi = torch.tensor(math.pi, device=x.device) - return torch.remainder(x + pi, 2 * pi) - pi - - -def convmtx_numpy(x: np.ndarray, filter_length: int, delay: int = 0, n_steps: Optional[int] = None) -> np.ndarray: - """Construct a causal convolutional matrix from x delayed by `delay` samples. - - Args: - x: input signal, shape (N,) - filter_length: length of the filter in samples - delay: delay the signal by a number of samples - n_steps: total number of time steps (rows) for the output matrix - - Returns: - Convolutional matrix, shape (n_steps, filter_length) - """ - if x.ndim != 1: - raise ValueError(f'Expecting one-dimensional signal. Received signal with shape {x.shape}') - - if n_steps is None: - # Keep the same length as the input signal - n_steps = len(x) - - # pad as necessary - x_pad = np.hstack([np.zeros(delay), x]) - if (pad_len := n_steps - len(x_pad)) > 0: - x_pad = np.hstack([x_pad, np.zeros(pad_len)]) - else: - x_pad = x_pad[:n_steps] - - return scipy.linalg.toeplitz(x_pad, np.hstack([x_pad[0], np.zeros(filter_length - 1)])) - - -def convmtx_mc_numpy(x: np.ndarray, filter_length: int, delay: int = 0, n_steps: Optional[int] = None) -> np.ndarray: - """Construct a causal multi-channel convolutional matrix from `x` delayed by `delay` samples. - - Args: - x: input signal, shape (N, M) - filter_length: length of the filter in samples - delay: delay the signal by a number of samples - n_steps: total number of time steps (rows) for the output matrix - - Returns: - Multi-channel convolutional matrix, shape (n_steps, M * filter_length) - """ - if x.ndim != 2: - raise ValueError(f'Expecting two-dimensional signal. Received signal with shape {x.shape}') - - mc_mtx = [] - - for m in range(x.shape[1]): - mc_mtx.append(convmtx_numpy(x[:, m], filter_length=filter_length, delay=delay, n_steps=n_steps)) - - return np.hstack(mc_mtx) - - -def scale_invariant_target_numpy(estimate: np.ndarray, target: np.ndarray, eps: float = 1e-8) -> np.ndarray: - """Calculate convolution-invariant target for a given estimated signal. - - Calculate scaled target obtained by solving - - min_scale || scale * target - estimate ||^2 - - Args: - estimate: one-dimensional estimated signal, shape (T,) - target: one-dimensional target signal, shape (T,) - eps: regularization constans - - Returns: - Scaled target signal, shape (T,) - """ - assert target.ndim == estimate.ndim == 1, 'Only one-dimensional inputs supported' - - estimate_dot_target = np.mean(estimate * target) - target_pow = np.mean(np.abs(target) ** 2) - scale = estimate_dot_target / (target_pow + eps) - return scale * target - - -def convolution_invariant_target_numpy( - estimate: np.ndarray, target: np.ndarray, filter_length, diag_reg: float = 1e-6, eps: float = 1e-8 -) -> np.ndarray: - """Calculate convolution-invariant target for a given estimated signal. - - Calculate target filtered with a linear f obtained by solving - - min_filter || conv(filter, target) - estimate ||^2 - - Args: - estimate: one-dimensional estimated signal - target: one-dimensional target signal - filter_length: length of the (convolutive) filter - diag_reg: multiplicative factor for relative diagonal loading - eps: absolute diagonal loading - """ - assert target.ndim == estimate.ndim == 1, 'Only one-dimensional inputs supported' - - n_fft = 2 ** math.ceil(math.log2(len(target) + len(estimate) - 1)) - - T = np.fft.rfft(target, n=n_fft) - E = np.fft.rfft(estimate, n=n_fft) - - # target autocorrelation - tt_corr = np.fft.irfft(np.abs(T) ** 2, n=n_fft) - # target-estimate crosscorrelation - te_corr = np.fft.irfft(T.conj() * E, n=n_fft) - - # Use only filter_length - tt_corr = tt_corr[:filter_length] - te_corr = te_corr[:filter_length] - - if diag_reg is not None: - tt_corr[0] += diag_reg * tt_corr[0] + eps - - # Construct the Toeplitz system matrix - TT = scipy.linalg.toeplitz(tt_corr) - - # Solve the linear system for the optimal filter - filt = np.linalg.solve(TT, te_corr) - - # Calculate filtered target - T_filt = T * np.fft.rfft(filt, n=n_fft) - target_filt = np.fft.irfft(T_filt, n=n_fft) - - return target_filt[: len(target)] - - -def toeplitz(x: torch.Tensor) -> torch.Tensor: - """Create Toeplitz matrix for one-dimensional signals along the last dimension. - - Args: - x: tensor with shape (..., T) - - Returns: - Tensor with shape (..., T, T) - """ - length = x.size(-1) - x = torch.cat([x[..., 1:].flip(dims=(-1,)), x], dim=-1) - return x.unfold(-1, length, 1).flip(dims=(-1,)) - - -def covariance_matrix( - x: torch.Tensor, mask: Optional[torch.Tensor] = None, normalize_mask: bool = True, eps: float = 1e-8 -) -> torch.Tensor: - """Calculate covariance matrix of the input signal. - - If a mask is provided, the covariance matrix is calculated by weighting by the provided time-frequency mask and summing over the time dimension. The mask is normalized by default. If a mask is not provided, the covariance matrix is calculated by averaging over the time dimension. - - The provided mask can be real-valued or complex-valued, or a binary or boolean mask. - - Args: - x: input signal with shape `(..., channel, freq, time)` - mask: Time-frequency mask with shape `(..., freq, time)`. Default is `None`. - normalize_mask: if `True`, normalize the mask by dividing by the sum of the mask across time. Default is `True`. - eps: regularization constant. Default is `1e-10`. - - Returns: - Covariance matrix with shape (..., freq, channel, channel) - """ - # Check dimensions of the input signal - if x.ndim < 3: - raise ValueError(f"Input signal must have at least 3 dimensions. Input signal shape: {x.shape}") - - # Permute dimensions to (..., freq, time, channel) - x = rearrange(x, '... c f t -> ... f t c') - - # For each time-step, calculate the outer product p_xx(t) = x(t) x(t)^H - p_xx = torch.einsum('...tm,...tn->...tmn', x, x.conj()) - - # Weighting across time - if mask is None: - # Average over the time dimension - # Note: reduce(..., 'mean') is not supported for complex-valued tensors - p_xx = p_xx.mean(dim=-3) - else: - # Check dimensions of the mask - if mask.ndim != x.ndim - 1: - raise ValueError( - f"Mask must have the same number of dimensions as the input signal, excluding the channel dimension. Input signal shape: {x.shape}, mask shape: {mask.shape}" - ) - - if mask.shape != x.shape[:-1]: - raise ValueError( - f"Mask must have the same shape as the input signal, excluding the channel dimension. Input signal shape: {x.shape}, mask shape: {mask.shape}" - ) - # Normalize the mask - if normalize_mask: - mask = mask / (mask.sum(dim=-1, keepdim=True) + eps) - - # Apply the mask to the input signal - p_xx = mask[..., None, None] * p_xx - - # Aggregate over the time dimension - p_xx = reduce(p_xx, '... f t m n -> ... f m n', 'sum') - - return p_xx diff --git a/nemo/collections/audio/parts/utils/callbacks.py b/nemo/collections/audio/parts/utils/callbacks.py deleted file mode 100644 index b78cc30445787bd2d833cee73b203ceb42b6a1dc..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/parts/utils/callbacks.py +++ /dev/null @@ -1,177 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import List, Optional, Type - -import einops -import torch -from lightning.pytorch import Callback, LightningModule, Trainer -from lightning.pytorch.loggers import TensorBoardLogger -from lightning.pytorch.loggers.logger import Logger -from lightning.pytorch.loggers.wandb import WandbLogger - -from nemo.utils import logging -from nemo.utils.decorators import experimental - -HAVE_WANDB = True -try: - import wandb -except ModuleNotFoundError: - HAVE_WANDB = False - - -def _get_logger(loggers: List[Logger], logger_type: Type[Logger]): - for logger in loggers: - if isinstance(logger, logger_type): - if hasattr(logger, "experiment"): - return logger.experiment - else: - return logger - raise ValueError(f"Could not find {logger_type} logger in {loggers}.") - - -@experimental -class SpeechEnhancementLoggingCallback(Callback): - """ - Callback which can log artifacts (eg. model predictions, graphs) to local disk, Tensorboard, and/or WandB. - - Args: - data_loader: Data to log artifacts for. - output_dir: Optional local directory. If provided, artifacts will be saved in output_dir. - loggers: Optional list of loggers to use if logging to tensorboard or wandb. - log_tensorboard: Whether to log artifacts to tensorboard. - log_wandb: Whether to log artifacts to WandB. - """ - - def __init__( - self, - data_loader, - data_loader_idx: int, - loggers: Optional[List[Logger]] = None, - log_tensorboard: bool = False, - log_wandb: bool = False, - sample_rate: int = 16000, - max_utts: Optional[int] = None, - ): - self.data_loader = data_loader - self.data_loader_idx = data_loader_idx - self.loggers = loggers if loggers else [] - self.log_tensorboard = log_tensorboard - self.log_wandb = log_wandb - self.sample_rate = sample_rate - self.max_utts = max_utts - - if log_tensorboard: - logging.info('Creating tensorboard logger') - self.tensorboard_logger = _get_logger(self.loggers, TensorBoardLogger) - else: - logging.debug('Not using tensorbord logger') - self.tensorboard_logger = None - - if log_wandb: - if not HAVE_WANDB: - raise ValueError("Wandb not installed.") - logging.info('Creating wandb logger') - self.wandb_logger = _get_logger(self.loggers, WandbLogger) - else: - logging.debug('Not using wandb logger') - self.wandb_logger = None - - logging.debug('Initialized %s with', self.__class__.__name__) - logging.debug('\tlog_tensorboard: %s', self.log_tensorboard) - logging.debug('\tlog_wandb: %s', self.log_wandb) - - def _log_audio(self, audios: torch.Tensor, lengths: torch.Tensor, step: int, label: str = "input"): - - num_utts = audios.size(0) - for audio_idx in range(num_utts): - length = lengths[audio_idx] - if self.tensorboard_logger: - self.tensorboard_logger.add_audio( - tag=f"{label}_{audio_idx}", - snd_tensor=audios[audio_idx, :length], - global_step=step, - sample_rate=self.sample_rate, - ) - - if self.wandb_logger: - wandb_audio = ( - wandb.Audio(audios[audio_idx], sample_rate=self.sample_rate, caption=f"{label}_{audio_idx}"), - ) - self.wandb_logger.log({f"{label}_{audio_idx}": wandb_audio}) - - def on_validation_epoch_end(self, trainer: Trainer, model: LightningModule): - """Log artifacts at the end of an epoch.""" - epoch = 1 + model.current_epoch - output_signal_list = [] - output_length_list = [] - num_examples_uploaded = 0 - - logging.info(f"Logging processed speech for validation dataset {self.data_loader_idx}...") - for batch in self.data_loader: - if isinstance(batch, dict): - # lhotse batches are dictionaries - input_signal = batch['input_signal'] - input_length = batch['input_length'] - target_signal = batch.get('target_signal', input_signal.clone()) - else: - input_signal, input_length, target_signal, _ = batch - - if self.max_utts is None: - num_examples = input_signal.size(0) # batch size - do_upload = True - else: - do_upload = num_examples_uploaded < self.max_utts - num_examples = min(self.max_utts - num_examples_uploaded, input_signal.size(0)) - num_examples_uploaded += num_examples - - if do_upload: - # Only pick the required numbers of speech to the logger - input_signal = input_signal[:num_examples, ...] - target_signal = target_signal[:num_examples, ...] - input_length = input_length[:num_examples] - - # For consistency, the model uses multi-channel format, even if the channel dimension is 1 - if input_signal.ndim == 2: - input_signal = einops.rearrange(input_signal, 'B T -> B 1 T') - if target_signal.ndim == 2: - target_signal = einops.rearrange(target_signal, 'B T -> B 1 T') - - input_signal = input_signal.to(model.device) - input_length = input_length.to(model.device) - - output_signal, output_length = model(input_signal=input_signal, input_length=input_length) - output_signal_list.append(output_signal.to(target_signal.device)) - output_length_list.append(output_length.to(target_signal.device)) - - if len(output_signal_list) == 0: - logging.debug('List are empty, no artifacts to log at epoch %d.', epoch) - return - - output_signals = torch.concat(output_signal_list, dim=0) - output_lengths = torch.concat(output_length_list, dim=0) - if output_signals.size(1) != 1: - logging.error( - f"Currently only supports single-channel audio! Current output shape: {output_signals.shape}" - ) - raise NotImplementedError - - output_signals = einops.rearrange(output_signals, "B 1 T -> B T") - - self._log_audio( - audios=output_signals, - lengths=output_lengths, - step=model.global_step, - label=f"dataloader_{self.data_loader_idx}_processed", - ) diff --git a/nemo/collections/audio/parts/utils/maxine.py b/nemo/collections/audio/parts/utils/maxine.py deleted file mode 100644 index 01f0daa5cb5bb8d13e22750ac02809cadb5e11fa..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/parts/utils/maxine.py +++ /dev/null @@ -1,35 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from torch.nn.utils import remove_weight_norm, weight_norm - - -def apply_weight_norm_lstm(lstm_module): - bidirectional = lstm_module.bidirectional - lstm_wn = weight_norm(lstm_module, name='weight_ih_l0') - lstm_wn = weight_norm(lstm_wn, name='weight_hh_l0') - if bidirectional: - lstm_wn = weight_norm(lstm_wn, name='weight_ih_l0_reverse') - lstm_wn = weight_norm(lstm_wn, name='weight_hh_l0_reverse') - return lstm_wn - - -def remove_weight_norm_lstm(lstm_module): - bidirectional = lstm_module.bidirectional - lstm = remove_weight_norm(lstm_module, name='weight_ih_l0') - lstm = remove_weight_norm(lstm, name='weight_hh_l0') - if bidirectional: - lstm = remove_weight_norm(lstm, name='weight_ih_l0_reverse') - lstm = remove_weight_norm(lstm, name='weight_hh_l0_reverse') - return lstm diff --git a/nemo/collections/audio/parts/utils/transforms.py b/nemo/collections/audio/parts/utils/transforms.py deleted file mode 100644 index 6f7f914799044d031781c4b9e50cb45a8cc731ad..0000000000000000000000000000000000000000 --- a/nemo/collections/audio/parts/utils/transforms.py +++ /dev/null @@ -1,1105 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# NOTE: The code below originates from torchaudio repository, version 2.9. -# It can be found under: https://github.com/pytorch/audio/tree/release/2.9 -# The modifications applied are mostly cosmetic. -# The inclusion of this code in NeMo allows us to avoid -# a dependency with a problematic build process. -# This code is licensed under the BSD 2-Clause License, -# included verbatim from the torchaudio repository below: -# -# BSD 2-Clause License -# -# Copyright (c) 2017 Facebook Inc. (Soumith Chintala), -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# * Redistributions of source code must retain the above copyright notice, this -# list of conditions and the following disclaimer. -# -# * Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -import math -import warnings -from typing import Callable, Optional, Union - -import torch -from torch import Tensor - -__all__ = ["Spectrogram", "MelSpectrogram", "MFCC", "Resample"] - - -class Spectrogram(torch.nn.Module): - r"""Create a spectrogram from a audio signal. - - .. devices:: CPU CUDA - - .. properties:: Autograd TorchScript - - Args: - n_fft (int, optional): Size of FFT, creates ``n_fft // 2 + 1`` bins. (Default: ``400``) - win_length (int or None, optional): Window size. (Default: ``n_fft``) - hop_length (int or None, optional): Length of hop between STFT windows. (Default: ``win_length // 2``) - pad (int, optional): Two sided padding of signal. (Default: ``0``) - window_fn (Callable[..., Tensor], optional): A function to create a window tensor - that is applied/multiplied to each frame/window. (Default: ``torch.hann_window``) - power (float or None, optional): Exponent for the magnitude spectrogram, - (must be > 0) e.g., 1 for magnitude, 2 for power, etc. - If None, then the complex spectrum is returned instead. (Default: ``2``) - normalized (bool or str, optional): Whether to normalize by magnitude after stft. If input is str, choices are - ``"window"`` and ``"frame_length"``, if specific normalization type is desirable. ``True`` maps to - ``"window"``. (Default: ``False``) - wkwargs (dict or None, optional): Arguments for window function. (Default: ``None``) - center (bool, optional): whether to pad :attr:`waveform` on both sides so - that the :math:`t`-th frame is centered at time :math:`t \times \text{hop\_length}`. - (Default: ``True``) - pad_mode (string, optional): controls the padding method used when - :attr:`center` is ``True``. (Default: ``"reflect"``) - onesided (bool, optional): controls whether to return half of results to - avoid redundancy (Default: ``True``) - return_complex (bool, optional): - Deprecated and not used. - - Example - >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True) - >>> transform = torchaudio.transforms.Spectrogram(n_fft=800) - >>> spectrogram = transform(waveform) - - """ - - __constants__ = ["n_fft", "win_length", "hop_length", "pad", "power", "normalized"] - - def __init__( - self, - n_fft: int = 400, - win_length: Optional[int] = None, - hop_length: Optional[int] = None, - pad: int = 0, - window_fn: Callable[..., Tensor] = torch.hann_window, - power: Optional[float] = 2.0, - normalized: Union[bool, str] = False, - wkwargs: Optional[dict] = None, - center: bool = True, - pad_mode: str = "reflect", - onesided: bool = True, - return_complex: Optional[bool] = None, - ) -> None: - super().__init__() - self.n_fft = n_fft - # number of FFT bins. the returned STFT result will have n_fft // 2 + 1 - # number of frequencies due to onesided=True in torch.stft - self.win_length = win_length if win_length is not None else n_fft - self.hop_length = hop_length if hop_length is not None else self.win_length // 2 - window = window_fn(self.win_length) if wkwargs is None else window_fn(self.win_length, **wkwargs) - self.register_buffer("window", window) - self.pad = pad - self.power = power - self.normalized = normalized - self.center = center - self.pad_mode = pad_mode - self.onesided = onesided - if return_complex is not None: - warnings.warn( - "`return_complex` argument is now deprecated and is not effective." - "`torchaudio.transforms.Spectrogram(power=None)` always returns a tensor with " - "complex dtype. Please remove the argument in the function call." - ) - - def forward(self, waveform: Tensor) -> Tensor: - r""" - Args: - waveform (Tensor): Tensor of audio of dimension (..., time). - - Returns: - Tensor: Dimension (..., freq, time), where freq is - ``n_fft // 2 + 1`` where ``n_fft`` is the number of - Fourier bins, and time is the number of window hops (n_frame). - """ - return spectrogram( - waveform, - self.pad, - self.window, - self.n_fft, - self.hop_length, - self.win_length, - self.power, - self.normalized, - self.center, - self.pad_mode, - self.onesided, - ) - - -class MelSpectrogram(torch.nn.Module): - r"""Create MelSpectrogram for a raw audio signal. - - .. devices:: CPU CUDA - - .. properties:: Autograd TorchScript - - This is a composition of :py:func:`torchaudio.transforms.Spectrogram` - and :py:func:`torchaudio.transforms.MelScale`. - - Sources - * https://gist.github.com/kastnerkyle/179d6e9a88202ab0a2fe - * https://timsainb.github.io/spectrograms-mfccs-and-inversion-in-python.html - * http://haythamfayek.com/2016/04/21/speech-processing-for-machine-learning.html - - Args: - sample_rate (int, optional): Sample rate of audio signal. (Default: ``16000``) - n_fft (int, optional): Size of FFT, creates ``n_fft // 2 + 1`` bins. (Default: ``400``) - win_length (int or None, optional): Window size. (Default: ``n_fft``) - hop_length (int or None, optional): Length of hop between STFT windows. (Default: ``win_length // 2``) - f_min (float, optional): Minimum frequency. (Default: ``0.``) - f_max (float or None, optional): Maximum frequency. (Default: ``None``) - pad (int, optional): Two sided padding of signal. (Default: ``0``) - n_mels (int, optional): Number of mel filterbanks. (Default: ``128``) - window_fn (Callable[..., Tensor], optional): A function to create a window tensor - that is applied/multiplied to each frame/window. (Default: ``torch.hann_window``) - power (float, optional): Exponent for the magnitude spectrogram, - (must be > 0) e.g., 1 for magnitude, 2 for power, etc. (Default: ``2``) - normalized (bool, optional): Whether to normalize by magnitude after stft. (Default: ``False``) - wkwargs (Dict[..., ...] or None, optional): Arguments for window function. (Default: ``None``) - center (bool, optional): whether to pad :attr:`waveform` on both sides so - that the :math:`t`-th frame is centered at time :math:`t \times \text{hop\_length}`. - (Default: ``True``) - pad_mode (string, optional): controls the padding method used when - :attr:`center` is ``True``. (Default: ``"reflect"``) - onesided: Deprecated and unused. - norm (str or None, optional): If "slaney", divide the triangular mel weights by the width of the mel band - (area normalization). (Default: ``None``) - mel_scale (str, optional): Scale to use: ``htk`` or ``slaney``. (Default: ``htk``) - - Example - >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True) - >>> transform = transforms.MelSpectrogram(sample_rate) - >>> mel_specgram = transform(waveform) # (channel, n_mels, time) - - See also: - :py:func:`torchaudio.functional.melscale_fbanks` - The function used to - generate the filter banks. - """ - - __constants__ = ["sample_rate", "n_fft", "win_length", "hop_length", "pad", "n_mels", "f_min"] - - def __init__( - self, - sample_rate: int = 16000, - n_fft: int = 400, - win_length: Optional[int] = None, - hop_length: Optional[int] = None, - f_min: float = 0.0, - f_max: Optional[float] = None, - pad: int = 0, - n_mels: int = 128, - window_fn: Callable[..., Tensor] = torch.hann_window, - power: float = 2.0, - normalized: bool = False, - wkwargs: Optional[dict] = None, - center: bool = True, - pad_mode: str = "reflect", - onesided: Optional[bool] = None, - norm: Optional[str] = None, - mel_scale: str = "htk", - ) -> None: - super(MelSpectrogram, self).__init__() - - if onesided is not None: - warnings.warn( - "Argument 'onesided' has been deprecated and has no influence on the behavior of this module." - ) - - self.sample_rate = sample_rate - self.n_fft = n_fft - self.win_length = win_length if win_length is not None else n_fft - self.hop_length = hop_length if hop_length is not None else self.win_length // 2 - self.pad = pad - self.power = power - self.normalized = normalized - self.n_mels = n_mels # number of mel frequency bins - self.f_max = f_max - self.f_min = f_min - self.spectrogram = Spectrogram( - n_fft=self.n_fft, - win_length=self.win_length, - hop_length=self.hop_length, - pad=self.pad, - window_fn=window_fn, - power=self.power, - normalized=self.normalized, - wkwargs=wkwargs, - center=center, - pad_mode=pad_mode, - onesided=True, - ) - self.mel_scale = MelScale( - self.n_mels, self.sample_rate, self.f_min, self.f_max, self.n_fft // 2 + 1, norm, mel_scale - ) - - def forward(self, waveform: Tensor) -> Tensor: - r""" - Args: - waveform (Tensor): Tensor of audio of dimension (..., time). - - Returns: - Tensor: Mel frequency spectrogram of size (..., ``n_mels``, time). - """ - specgram = self.spectrogram(waveform) - mel_specgram = self.mel_scale(specgram) - return mel_specgram - - -class MFCC(torch.nn.Module): - r"""Create the Mel-frequency cepstrum coefficients from an audio signal. - - .. devices:: CPU CUDA - - .. properties:: Autograd TorchScript - - By default, this calculates the MFCC on the DB-scaled Mel spectrogram. - This is not the textbook implementation, but is implemented here to - give consistency with librosa. - - This output depends on the maximum value in the input spectrogram, and so - may return different values for an audio clip split into snippets vs. a - a full clip. - - Args: - sample_rate (int, optional): Sample rate of audio signal. (Default: ``16000``) - n_mfcc (int, optional): Number of mfc coefficients to retain. (Default: ``40``) - dct_type (int, optional): type of DCT (discrete cosine transform) to use. (Default: ``2``) - norm (str, optional): norm to use. (Default: ``"ortho"``) - log_mels (bool, optional): whether to use log-mel spectrograms instead of db-scaled. (Default: ``False``) - melkwargs (dict or None, optional): arguments for MelSpectrogram. (Default: ``None``) - - Example - >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True) - >>> transform = transforms.MFCC( - >>> sample_rate=sample_rate, - >>> n_mfcc=13, - >>> melkwargs={"n_fft": 400, "hop_length": 160, "n_mels": 23, "center": False}, - >>> ) - >>> mfcc = transform(waveform) - - See also: - :py:func:`torchaudio.functional.melscale_fbanks` - The function used to - generate the filter banks. - """ - - __constants__ = ["sample_rate", "n_mfcc", "dct_type", "top_db", "log_mels"] - - def __init__( - self, - sample_rate: int = 16000, - n_mfcc: int = 40, - dct_type: int = 2, - norm: str = "ortho", - log_mels: bool = False, - melkwargs: Optional[dict] = None, - ) -> None: - super(MFCC, self).__init__() - supported_dct_types = [2] - if dct_type not in supported_dct_types: - raise ValueError("DCT type not supported: {}".format(dct_type)) - self.sample_rate = sample_rate - self.n_mfcc = n_mfcc - self.dct_type = dct_type - self.norm = norm - self.top_db = 80.0 - self.amplitude_to_DB = AmplitudeToDB("power", self.top_db) - - melkwargs = melkwargs or {} - self.MelSpectrogram = MelSpectrogram(sample_rate=self.sample_rate, **melkwargs) - - if self.n_mfcc > self.MelSpectrogram.n_mels: - raise ValueError("Cannot select more MFCC coefficients than # mel bins") - dct_mat = create_dct(self.n_mfcc, self.MelSpectrogram.n_mels, self.norm) - self.register_buffer("dct_mat", dct_mat) - self.log_mels = log_mels - - def forward(self, waveform: Tensor) -> Tensor: - r""" - Args: - waveform (Tensor): Tensor of audio of dimension (..., time). - - Returns: - Tensor: specgram_mel_db of size (..., ``n_mfcc``, time). - """ - mel_specgram = self.MelSpectrogram(waveform) - if self.log_mels: - log_offset = 1e-6 - mel_specgram = torch.log(mel_specgram + log_offset) - else: - mel_specgram = self.amplitude_to_DB(mel_specgram) - - # (..., time, n_mels) dot (n_mels, n_mfcc) -> (..., n_nfcc, time) - mfcc = torch.matmul(mel_specgram.transpose(-1, -2), self.dct_mat).transpose(-1, -2) - return mfcc - - -class Resample(torch.nn.Module): - r"""Resample a signal from one frequency to another. A resampling method can be given. - - .. devices:: CPU CUDA - - .. properties:: Autograd TorchScript - - Note: - If resampling on waveforms of higher precision than float32, there may be a small loss of precision - because the kernel is cached once as float32. If high precision resampling is important for your application, - the functional form will retain higher precision, but run slower because it does not cache the kernel. - Alternatively, you could rewrite a transform that caches a higher precision kernel. - - Args: - orig_freq (int, optional): The original frequency of the signal. (Default: ``16000``) - new_freq (int, optional): The desired frequency. (Default: ``16000``) - resampling_method (str, optional): The resampling method to use. - Options: [``sinc_interp_hann``, ``sinc_interp_kaiser``] (Default: ``"sinc_interp_hann"``) - lowpass_filter_width (int, optional): Controls the sharpness of the filter, more == sharper - but less efficient. (Default: ``6``) - rolloff (float, optional): The roll-off frequency of the filter, as a fraction of the Nyquist. - Lower values reduce anti-aliasing, but also reduce some of the highest frequencies. (Default: ``0.99``) - beta (float or None, optional): The shape parameter used for kaiser window. - dtype (torch.device, optional): - Determnines the precision that resampling kernel is pre-computed and cached. If not provided, - kernel is computed with ``torch.float64`` then cached as ``torch.float32``. - If you need higher precision, provide ``torch.float64``, and the pre-computed kernel is computed and - cached as ``torch.float64``. If you use resample with lower precision, then instead of providing this - providing this argument, please use ``Resample.to(dtype)``, so that the kernel generation is still - carried out on ``torch.float64``. - - Example - >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True) - >>> transform = transforms.Resample(sample_rate, sample_rate/10) - >>> waveform = transform(waveform) - """ - - def __init__( - self, - orig_freq: int = 16000, - new_freq: int = 16000, - resampling_method: str = "sinc_interp_hann", - lowpass_filter_width: int = 6, - rolloff: float = 0.99, - beta: Optional[float] = None, - *, - dtype: Optional[torch.dtype] = None, - ) -> None: - super().__init__() - - self.orig_freq = orig_freq - self.new_freq = new_freq - self.gcd = math.gcd(int(self.orig_freq), int(self.new_freq)) - self.resampling_method = resampling_method - self.lowpass_filter_width = lowpass_filter_width - self.rolloff = rolloff - self.beta = beta - - if self.orig_freq != self.new_freq: - kernel, self.width = _get_sinc_resample_kernel( - self.orig_freq, - self.new_freq, - self.gcd, - self.lowpass_filter_width, - self.rolloff, - self.resampling_method, - beta, - dtype=dtype, - ) - self.register_buffer("kernel", kernel) - - def forward(self, waveform: Tensor) -> Tensor: - r""" - Args: - waveform (Tensor): Tensor of audio of dimension (..., time). - - Returns: - Tensor: Output signal of dimension (..., time). - """ - if self.orig_freq == self.new_freq: - return waveform - return _apply_sinc_resample_kernel(waveform, self.orig_freq, self.new_freq, self.gcd, self.kernel, self.width) - - -class MelScale(torch.nn.Module): - r"""Turn a normal STFT into a mel frequency STFT with triangular filter banks. - - .. devices:: CPU CUDA - - .. properties:: Autograd TorchScript - - Args: - n_mels (int, optional): Number of mel filterbanks. (Default: ``128``) - sample_rate (int, optional): Sample rate of audio signal. (Default: ``16000``) - f_min (float, optional): Minimum frequency. (Default: ``0.``) - f_max (float or None, optional): Maximum frequency. (Default: ``sample_rate // 2``) - n_stft (int, optional): Number of bins in STFT. See ``n_fft`` in :class:`Spectrogram`. (Default: ``201``) - norm (str or None, optional): If ``"slaney"``, divide the triangular mel weights by the width of the mel band - (area normalization). (Default: ``None``) - mel_scale (str, optional): Scale to use: ``htk`` or ``slaney``. (Default: ``htk``) - - Example - >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True) - >>> spectrogram_transform = transforms.Spectrogram(n_fft=1024) - >>> spectrogram = spectrogram_transform(waveform) - >>> melscale_transform = transforms.MelScale(sample_rate=sample_rate, n_stft=1024 // 2 + 1) - >>> melscale_spectrogram = melscale_transform(spectrogram) - - See also: - :py:func:`torchaudio.functional.melscale_fbanks` - The function used to - generate the filter banks. - """ - - __constants__ = ["n_mels", "sample_rate", "f_min", "f_max"] - - def __init__( - self, - n_mels: int = 128, - sample_rate: int = 16000, - f_min: float = 0.0, - f_max: Optional[float] = None, - n_stft: int = 201, - norm: Optional[str] = None, - mel_scale: str = "htk", - ) -> None: - super(MelScale, self).__init__() - self.n_mels = n_mels - self.sample_rate = sample_rate - self.f_max = f_max if f_max is not None else float(sample_rate // 2) - self.f_min = f_min - self.norm = norm - self.mel_scale = mel_scale - - if f_min > self.f_max: - raise ValueError("Require f_min: {} <= f_max: {}".format(f_min, self.f_max)) - - fb = melscale_fbanks(n_stft, self.f_min, self.f_max, self.n_mels, self.sample_rate, self.norm, self.mel_scale) - self.register_buffer("fb", fb) - - def forward(self, specgram: Tensor) -> Tensor: - r""" - Args: - specgram (Tensor): A spectrogram STFT of dimension (..., freq, time). - - Returns: - Tensor: Mel frequency spectrogram of size (..., ``n_mels``, time). - """ - - # (..., time, freq) dot (freq, n_mels) -> (..., n_mels, time) - mel_specgram = torch.matmul(specgram.transpose(-1, -2), self.fb).transpose(-1, -2) - - return mel_specgram - - -class AmplitudeToDB(torch.nn.Module): - r"""Turn a tensor from the power/amplitude scale to the decibel scale. - - .. devices:: CPU CUDA - - .. properties:: Autograd TorchScript - - This output depends on the maximum value in the input tensor, and so - may return different values for an audio clip split into snippets vs. a - a full clip. - - Args: - stype (str, optional): scale of input tensor (``"power"`` or ``"magnitude"``). The - power being the elementwise square of the magnitude. (Default: ``"power"``) - top_db (float or None, optional): minimum negative cut-off in decibels. A reasonable - number is 80. (Default: ``None``) - - Example - >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True) - >>> transform = transforms.AmplitudeToDB(stype="amplitude", top_db=80) - >>> waveform_db = transform(waveform) - """ - - __constants__ = ["multiplier", "amin", "ref_value", "db_multiplier"] - - def __init__(self, stype: str = "power", top_db: Optional[float] = None) -> None: - super(AmplitudeToDB, self).__init__() - self.stype = stype - if top_db is not None and top_db < 0: - raise ValueError("top_db must be positive value") - self.top_db = top_db - self.multiplier = 10.0 if stype == "power" else 20.0 - self.amin = 1e-10 - self.ref_value = 1.0 - self.db_multiplier = math.log10(max(self.amin, self.ref_value)) - - def forward(self, x: Tensor) -> Tensor: - r"""Numerically stable implementation from Librosa. - - https://librosa.org/doc/latest/generated/librosa.amplitude_to_db.html - - Args: - x (Tensor): Input tensor before being converted to decibel scale. - - Returns: - Tensor: Output tensor in decibel scale. - """ - return amplitude_to_DB(x, self.multiplier, self.amin, self.db_multiplier, self.top_db) - - -def resample( - waveform: Tensor, - orig_freq: int, - new_freq: int, - lowpass_filter_width: int = 6, - rolloff: float = 0.99, - resampling_method: str = "sinc_interp_hann", - beta: Optional[float] = None, -) -> Tensor: - r"""Resamples the waveform at the new frequency using bandlimited interpolation. :cite:`RESAMPLE`. - - .. devices:: CPU CUDA - - .. properties:: Autograd TorchScript - - Note: - ``transforms.Resample`` precomputes and reuses the resampling kernel, so using it will result in - more efficient computation if resampling multiple waveforms with the same resampling parameters. - - Args: - waveform (Tensor): The input signal of dimension `(..., time)` - orig_freq (int): The original frequency of the signal - new_freq (int): The desired frequency - lowpass_filter_width (int, optional): Controls the sharpness of the filter, more == sharper - but less efficient. (Default: ``6``) - rolloff (float, optional): The roll-off frequency of the filter, as a fraction of the Nyquist. - Lower values reduce anti-aliasing, but also reduce some of the highest frequencies. (Default: ``0.99``) - resampling_method (str, optional): The resampling method to use. - Options: [``"sinc_interp_hann"``, ``"sinc_interp_kaiser"``] (Default: ``"sinc_interp_hann"``) - beta (float or None, optional): The shape parameter used for kaiser window. - - Returns: - Tensor: The waveform at the new frequency of dimension `(..., time).` - """ - - if orig_freq <= 0.0 or new_freq <= 0.0: - raise ValueError("Original frequency and desired frequecy should be positive") - - if orig_freq == new_freq: - return waveform - - gcd = math.gcd(int(orig_freq), int(new_freq)) - - kernel, width = _get_sinc_resample_kernel( - orig_freq, - new_freq, - gcd, - lowpass_filter_width, - rolloff, - resampling_method, - beta, - waveform.device, - waveform.dtype, - ) - resampled = _apply_sinc_resample_kernel(waveform, orig_freq, new_freq, gcd, kernel, width) - return resampled - - -def _get_sinc_resample_kernel( - orig_freq: int, - new_freq: int, - gcd: int, - lowpass_filter_width: int = 6, - rolloff: float = 0.99, - resampling_method: str = "sinc_interp_hann", - beta: Optional[float] = None, - device: torch.device = "cpu", - dtype: Optional[torch.dtype] = None, -): - if not (int(orig_freq) == orig_freq and int(new_freq) == new_freq): - raise Exception( - "Frequencies must be of integer type to ensure quality resampling computation. " - "To work around this, manually convert both frequencies to integer values " - "that maintain their resampling rate ratio before passing them into the function. " - "Example: To downsample a 44100 hz waveform by a factor of 8, use " - "`orig_freq=8` and `new_freq=1` instead of `orig_freq=44100` and `new_freq=5512.5`. " - "For more information, please refer to https://github.com/pytorch/audio/issues/1487." - ) - - if resampling_method not in ["sinc_interp_hann", "sinc_interp_kaiser"]: - raise ValueError("Invalid resampling method: {}".format(resampling_method)) - - orig_freq = int(orig_freq) // gcd - new_freq = int(new_freq) // gcd - - if lowpass_filter_width <= 0: - raise ValueError("Low pass filter width should be positive.") - base_freq = min(orig_freq, new_freq) - # This will perform antialiasing filtering by removing the highest frequencies. - # At first I thought I only needed this when downsampling, but when upsampling - # you will get edge artifacts without this, as the edge is equivalent to zero padding, - # which will add high freq artifacts. - base_freq *= rolloff - - # The key idea of the algorithm is that x(t) can be exactly reconstructed from x[i] (tensor) - # using the sinc interpolation formula: - # x(t) = sum_i x[i] sinc(pi * orig_freq * (i / orig_freq - t)) - # We can then sample the function x(t) with a different sample rate: - # y[j] = x(j / new_freq) - # or, - # y[j] = sum_i x[i] sinc(pi * orig_freq * (i / orig_freq - j / new_freq)) - - # We see here that y[j] is the convolution of x[i] with a specific filter, for which - # we take an FIR approximation, stopping when we see at least `lowpass_filter_width` zeros crossing. - # But y[j+1] is going to have a different set of weights and so on, until y[j + new_freq]. - # Indeed: - # y[j + new_freq] = sum_i x[i] sinc(pi * orig_freq * ((i / orig_freq - (j + new_freq) / new_freq)) - # = sum_i x[i] sinc(pi * orig_freq * ((i - orig_freq) / orig_freq - j / new_freq)) - # = sum_i x[i + orig_freq] sinc(pi * orig_freq * (i / orig_freq - j / new_freq)) - # so y[j+new_freq] uses the same filter as y[j], but on a shifted version of x by `orig_freq`. - # This will explain the F.conv1d after, with a stride of orig_freq. - width = math.ceil(lowpass_filter_width * orig_freq / base_freq) - # If orig_freq is still big after GCD reduction, most filters will be very unbalanced, i.e., - # they will have a lot of almost zero values to the left or to the right... - # There is probably a way to evaluate those filters more efficiently, but this is kept for - # future work. - idx_dtype = dtype if dtype is not None else torch.float64 - - idx = torch.arange(-width, width + orig_freq, dtype=idx_dtype, device=device)[None, None] / orig_freq - - t = torch.arange(0, -new_freq, -1, dtype=dtype, device=device)[:, None, None] / new_freq + idx - t *= base_freq - t = t.clamp_(-lowpass_filter_width, lowpass_filter_width) - - # we do not use built in torch windows here as we need to evaluate the window - # at specific positions, not over a regular grid. - if resampling_method == "sinc_interp_hann": - window = torch.cos(t * math.pi / lowpass_filter_width / 2) ** 2 - else: - # sinc_interp_kaiser - if beta is None: - beta = 14.769656459379492 - beta_tensor = torch.tensor(float(beta)) - window = torch.i0(beta_tensor * torch.sqrt(1 - (t / lowpass_filter_width) ** 2)) / torch.i0(beta_tensor) - - t *= math.pi - - scale = base_freq / orig_freq - kernels = torch.where(t == 0, torch.tensor(1.0).to(t), t.sin() / t) - kernels *= window * scale - - if dtype is None: - kernels = kernels.to(dtype=torch.float32) - - return kernels, width - - -def _apply_sinc_resample_kernel( - waveform: Tensor, - orig_freq: int, - new_freq: int, - gcd: int, - kernel: Tensor, - width: int, -): - if not waveform.is_floating_point(): - raise TypeError(f"Expected floating point type for waveform tensor, but received {waveform.dtype}.") - - orig_freq = int(orig_freq) // gcd - new_freq = int(new_freq) // gcd - - # pack batch - shape = waveform.size() - waveform = waveform.view(-1, shape[-1]) - - num_wavs, length = waveform.shape - waveform = torch.nn.functional.pad(waveform, (width, width + orig_freq)) - resampled = torch.nn.functional.conv1d(waveform[:, None], kernel, stride=orig_freq) - resampled = resampled.transpose(1, 2).reshape(num_wavs, -1) - target_length = torch.ceil(torch.as_tensor(new_freq * length / orig_freq)).long() - resampled = resampled[..., :target_length] - - # unpack batch - resampled = resampled.view(shape[:-1] + resampled.shape[-1:]) - return resampled - - -def spectrogram( - waveform: Tensor, - pad: int, - window: Tensor, - n_fft: int, - hop_length: int, - win_length: int, - power: Optional[float], - normalized: Union[bool, str], - center: bool = True, - pad_mode: str = "reflect", - onesided: bool = True, - return_complex: Optional[bool] = None, -) -> Tensor: - r"""Create a spectrogram or a batch of spectrograms from a raw audio signal. - The spectrogram can be either magnitude-only or complex. - - .. devices:: CPU CUDA - - .. properties:: Autograd TorchScript - - Args: - waveform (Tensor): Tensor of audio of dimension `(..., time)` - pad (int): Two sided padding of signal - window (Tensor): Window tensor that is applied/multiplied to each frame/window - n_fft (int): Size of FFT - hop_length (int): Length of hop between STFT windows - win_length (int): Window size - power (float or None): Exponent for the magnitude spectrogram, - (must be > 0) e.g., 1 for magnitude, 2 for power, etc. - If None, then the complex spectrum is returned instead. - normalized (bool or str): Whether to normalize by magnitude after stft. If input is str, choices are - ``"window"`` and ``"frame_length"``, if specific normalization type is desirable. ``True`` maps to - ``"window"``. When normalized on ``"window"``, waveform is normalized upon the window's L2 energy. If - normalized on ``"frame_length"``, waveform is normalized by dividing by - :math:`(\text{frame\_length})^{0.5}`. - center (bool, optional): whether to pad :attr:`waveform` on both sides so - that the :math:`t`-th frame is centered at time :math:`t \times \text{hop\_length}`. - Default: ``True`` - pad_mode (string, optional): controls the padding method used when - :attr:`center` is ``True``. Default: ``"reflect"`` - onesided (bool, optional): controls whether to return half of results to - avoid redundancy. Default: ``True`` - return_complex (bool, optional): - Deprecated and not used. - - Returns: - Tensor: Dimension `(..., freq, time)`, freq is - ``n_fft // 2 + 1`` and ``n_fft`` is the number of - Fourier bins, and time is the number of window hops (n_frame). - """ - if return_complex is not None: - warnings.warn( - "`return_complex` argument is now deprecated and is not effective." - "`torchaudio.functional.spectrogram(power=None)` always returns a tensor with " - "complex dtype. Please remove the argument in the function call." - ) - - if pad > 0: - # TODO add "with torch.no_grad():" back when JIT supports it - waveform = torch.nn.functional.pad(waveform, (pad, pad), "constant") - - frame_length_norm, window_norm = _get_spec_norms(normalized) - - # pack batch - shape = waveform.size() - waveform = waveform.reshape(-1, shape[-1]) - - # default values are consistent with librosa.core.spectrum._spectrogram - spec_f = torch.stft( - input=waveform, - n_fft=n_fft, - hop_length=hop_length, - win_length=win_length, - window=window, - center=center, - pad_mode=pad_mode, - normalized=frame_length_norm, - onesided=onesided, - return_complex=True, - ) - - # unpack batch - spec_f = spec_f.reshape(shape[:-1] + spec_f.shape[-2:]) - - if window_norm: - spec_f /= window.pow(2.0).sum().sqrt() - if power is not None: - if power == 1.0: - return spec_f.abs() - return spec_f.abs().pow(power) - return spec_f - - -def _get_spec_norms(normalized: Union[str, bool]): - frame_length_norm, window_norm = False, False - if torch.jit.isinstance(normalized, str): - if normalized not in ["frame_length", "window"]: - raise ValueError("Invalid normalized parameter: {}".format(normalized)) - if normalized == "frame_length": - frame_length_norm = True - elif normalized == "window": - window_norm = True - elif torch.jit.isinstance(normalized, bool): - if normalized: - window_norm = True - else: - raise TypeError("Input type not supported") - return frame_length_norm, window_norm - - -def amplitude_to_DB( - x: Tensor, multiplier: float, amin: float, db_multiplier: float, top_db: Optional[float] = None -) -> Tensor: - r"""Turn a spectrogram from the power/amplitude scale to the decibel scale. - - .. devices:: CPU CUDA - - .. properties:: Autograd TorchScript - - The output of each tensor in a batch depends on the maximum value of that tensor, - and so may return different values for an audio clip split into snippets vs. a full clip. - - Args: - - x (Tensor): Input spectrogram(s) before being converted to decibel scale. - The expected shapes are ``(freq, time)``, ``(channel, freq, time)`` or - ``(..., batch, channel, freq, time)``. - - .. note:: - - When ``top_db`` is specified, cut-off values are computed for each audio - in the batch. Therefore if the input shape is 4D (or larger), different - cut-off values are used for audio data in the batch. - If the input shape is 2D or 3D, a single cutoff value is used. - - multiplier (float): Use 10. for power and 20. for amplitude - amin (float): Number to clamp ``x`` - db_multiplier (float): Log10(max(reference value and amin)) - top_db (float or None, optional): Minimum negative cut-off in decibels. A reasonable number - is 80. (Default: ``None``) - - Returns: - Tensor: Output tensor in decibel scale - """ - x_db = multiplier * torch.log10(torch.clamp(x, min=amin)) - x_db -= multiplier * db_multiplier - - if top_db is not None: - # Expand batch - shape = x_db.size() - packed_channels = shape[-3] if x_db.dim() > 2 else 1 - x_db = x_db.reshape(-1, packed_channels, shape[-2], shape[-1]) - - x_db = torch.max(x_db, (x_db.amax(dim=(-3, -2, -1)) - top_db).view(-1, 1, 1, 1)) - - # Repack batch - x_db = x_db.reshape(shape) - - return x_db - - -def create_dct(n_mfcc: int, n_mels: int, norm: Optional[str]) -> Tensor: - r"""Create a DCT transformation matrix with shape (``n_mels``, ``n_mfcc``), - normalized depending on norm. - - .. devices:: CPU - - .. properties:: TorchScript - - Args: - n_mfcc (int): Number of mfc coefficients to retain - n_mels (int): Number of mel filterbanks - norm (str or None): Norm to use (either "ortho" or None) - - Returns: - Tensor: The transformation matrix, to be right-multiplied to - row-wise data of size (``n_mels``, ``n_mfcc``). - """ - - if norm is not None and norm != "ortho": - raise ValueError('norm must be either "ortho" or None') - - # http://en.wikipedia.org/wiki/Discrete_cosine_transform#DCT-II - n = torch.arange(float(n_mels)) - k = torch.arange(float(n_mfcc)).unsqueeze(1) - dct = torch.cos(math.pi / float(n_mels) * (n + 0.5) * k) # size (n_mfcc, n_mels) - - if norm is None: - dct *= 2.0 - else: - dct[0] *= 1.0 / math.sqrt(2.0) - dct *= math.sqrt(2.0 / float(n_mels)) - return dct.t() - - -def melscale_fbanks( - n_freqs: int, - f_min: float, - f_max: float, - n_mels: int, - sample_rate: int, - norm: Optional[str] = None, - mel_scale: str = "htk", -) -> Tensor: - r"""Create a frequency bin conversion matrix. - - .. devices:: CPU - - .. properties:: TorchScript - - Note: - For the sake of the numerical compatibility with librosa, not all the coefficients - in the resulting filter bank has magnitude of 1. - - .. image:: https://download.pytorch.org/torchaudio/doc-assets/mel_fbanks.png - :alt: Visualization of generated filter bank - - Args: - n_freqs (int): Number of frequencies to highlight/apply - f_min (float): Minimum frequency (Hz) - f_max (float): Maximum frequency (Hz) - n_mels (int): Number of mel filterbanks - sample_rate (int): Sample rate of the audio waveform - norm (str or None, optional): If "slaney", divide the triangular mel weights by the width of the mel band - (area normalization). (Default: ``None``) - mel_scale (str, optional): Scale to use: ``htk`` or ``slaney``. (Default: ``htk``) - - Returns: - Tensor: Triangular filter banks (fb matrix) of size (``n_freqs``, ``n_mels``) - meaning number of frequencies to highlight/apply to x the number of filterbanks. - Each column is a filterbank so that assuming there is a matrix A of - size (..., ``n_freqs``), the applied result would be - ``A @ melscale_fbanks(A.size(-1), ...)``. - - """ - - if norm is not None and norm != "slaney": - raise ValueError('norm must be one of None or "slaney"') - - # freq bins - all_freqs = torch.linspace(0, sample_rate // 2, n_freqs) - - # calculate mel freq bins - m_min = _hz_to_mel(f_min, mel_scale=mel_scale) - m_max = _hz_to_mel(f_max, mel_scale=mel_scale) - - m_pts = torch.linspace(m_min, m_max, n_mels + 2) - f_pts = _mel_to_hz(m_pts, mel_scale=mel_scale) - - # create filterbank - fb = _create_triangular_filterbank(all_freqs, f_pts) - - if norm is not None and norm == "slaney": - # Slaney-style mel is scaled to be approx constant energy per channel - enorm = 2.0 / (f_pts[2 : n_mels + 2] - f_pts[:n_mels]) - fb *= enorm.unsqueeze(0) - - if (fb.max(dim=0).values == 0.0).any(): - warnings.warn( - "At least one mel filterbank has all zero values. " - f"The value for `n_mels` ({n_mels}) may be set too high. " - f"Or, the value for `n_freqs` ({n_freqs}) may be set too low." - ) - - return fb - - -def _hz_to_mel(freq: float, mel_scale: str = "htk") -> float: - r"""Convert Hz to Mels. - - Args: - freqs (float): Frequencies in Hz - mel_scale (str, optional): Scale to use: ``htk`` or ``slaney``. (Default: ``htk``) - - Returns: - mels (float): Frequency in Mels - """ - - if mel_scale not in ["slaney", "htk"]: - raise ValueError('mel_scale should be one of "htk" or "slaney".') - - if mel_scale == "htk": - return 2595.0 * math.log10(1.0 + (freq / 700.0)) - - # Fill in the linear part - f_min = 0.0 - f_sp = 200.0 / 3 - - mels = (freq - f_min) / f_sp - - # Fill in the log-scale part - min_log_hz = 1000.0 - min_log_mel = (min_log_hz - f_min) / f_sp - logstep = math.log(6.4) / 27.0 - - if freq >= min_log_hz: - mels = min_log_mel + math.log(freq / min_log_hz) / logstep - - return mels - - -def _mel_to_hz(mels: Tensor, mel_scale: str = "htk") -> Tensor: - """Convert mel bin numbers to frequencies. - - Args: - mels (Tensor): Mel frequencies - mel_scale (str, optional): Scale to use: ``htk`` or ``slaney``. (Default: ``htk``) - - Returns: - freqs (Tensor): Mels converted in Hz - """ - - if mel_scale not in ["slaney", "htk"]: - raise ValueError('mel_scale should be one of "htk" or "slaney".') - - if mel_scale == "htk": - return 700.0 * (10.0 ** (mels / 2595.0) - 1.0) - - # Fill in the linear scale - f_min = 0.0 - f_sp = 200.0 / 3 - freqs = f_min + f_sp * mels - - # And now the nonlinear scale - min_log_hz = 1000.0 - min_log_mel = (min_log_hz - f_min) / f_sp - logstep = math.log(6.4) / 27.0 - - log_t = mels >= min_log_mel - freqs[log_t] = min_log_hz * torch.exp(logstep * (mels[log_t] - min_log_mel)) - - return freqs - - -def _create_triangular_filterbank( - all_freqs: Tensor, - f_pts: Tensor, -) -> Tensor: - """Create a triangular filter bank. - - Args: - all_freqs (Tensor): STFT freq points of size (`n_freqs`). - f_pts (Tensor): Filter mid points of size (`n_filter`). - - Returns: - fb (Tensor): The filter bank of size (`n_freqs`, `n_filter`). - """ - # Adopted from Librosa - # calculate the difference between each filter mid point and each stft freq point in hertz - f_diff = f_pts[1:] - f_pts[:-1] # (n_filter + 1) - slopes = f_pts.unsqueeze(0) - all_freqs.unsqueeze(1) # (n_freqs, n_filter + 2) - # create overlapping triangles - zero = torch.zeros(1) - down_slopes = (-1.0 * slopes[:, :-2]) / f_diff[:-1] # (n_freqs, n_filter) - up_slopes = slopes[:, 2:] / f_diff[1:] # (n_freqs, n_filter) - fb = torch.max(zero, torch.min(down_slopes, up_slopes)) - - return fb diff --git a/nemo/collections/common/__init__.py b/nemo/collections/common/__init__.py deleted file mode 100644 index 9c203622104b054550ec59232bdfad328f147e13..0000000000000000000000000000000000000000 --- a/nemo/collections/common/__init__.py +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import nemo.collections.common.callbacks -from nemo.collections.common import data, losses, parts, tokenizers -from nemo.package_info import __version__ - -# Set collection version equal to NeMo version. -__version = __version__ - -# Authorship. -__author__ = "NVIDIA Corporation" - -# Set collection name. -__description__ = "Common collection" diff --git a/nemo/collections/common/callbacks/__init__.py b/nemo/collections/common/callbacks/__init__.py deleted file mode 100644 index 0cf495d946960af72276cde51d1f546385356a1d..0000000000000000000000000000000000000000 --- a/nemo/collections/common/callbacks/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.common.callbacks.callbacks import LogEpochTimeCallback -from nemo.collections.common.callbacks.ema import EMA diff --git a/nemo/collections/common/callbacks/callbacks.py b/nemo/collections/common/callbacks/callbacks.py deleted file mode 100644 index 754b33726faf948c5f7927f4d8106bb531ac2805..0000000000000000000000000000000000000000 --- a/nemo/collections/common/callbacks/callbacks.py +++ /dev/null @@ -1,95 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import time - -from lightning.pytorch.callbacks import Callback -from lightning.pytorch.utilities import rank_zero_only - -# from sacrebleu import corpus_bleu - - -class LogEpochTimeCallback(Callback): - """Simple callback that logs how long each epoch takes, in seconds, to a pytorch lightning log""" - - @rank_zero_only - def on_train_epoch_start(self, trainer, pl_module): - self.epoch_start = time.time() - - @rank_zero_only - def on_train_epoch_end(self, trainer, pl_module): - curr_time = time.time() - duration = curr_time - self.epoch_start - trainer.logger.log_metrics({"epoch_time": duration}, step=trainer.global_step) - - -# class MachineTranslationLogEvalCallback(Callback): -# def _on_eval_end(self, trainer, pl_module, mode): -# counts = np.array(self._non_pad_tokens) -# eval_loss = np.sum(np.array(self._losses) * counts) / np.sum(counts) -# sacre_bleu = corpus_bleu(self._translations, [self._ground_truths], tokenize="13a") -# print(f"{mode} results for process with global rank {pl_module.global_rank}".upper()) -# for i in range(pl_module.num_examples[mode]): -# print('\u0332'.join(f"EXAMPLE {i}:")) # Underline output -# sent_id = np.random.randint(len(self._translations)) -# print(f"Ground truth: {self._ground_truths[sent_id]}\n") -# print(f"Translation: {self._translations[sent_id]}\n") -# print() -# print("-" * 50) -# print(f"loss: {eval_loss:.3f}") -# print(f"SacreBLEU: {sacre_bleu}") -# print("-" * 50) - -# @rank_zero_only -# def on_test_end(self, trainer, pl_module): -# self._on_eval_end(trainer, pl_module, "test") - -# @rank_zero_only -# def on_validation_end(self, trainer, pl_module): -# self._on_eval_end(trainer, pl_module, "val") - -# @rank_zero_only -# def on_sanity_check_end(self, trainer, pl_module): -# self._on_eval_end(trainer, pl_module, "val") - -# def _on_eval_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx, mode): -# self._translations.extend(outputs['translations']) -# self._ground_truths.extend(outputs['ground_truths']) -# self._non_pad_tokens.append(outputs['num_non_pad_tokens']) -# self._losses.append(outputs[f'{mode}_loss']) - -# @rank_zero_only -# def on_test_batch_end(self, trainer, pl_module, batch, outputs, batch_idx, dataloader_idx): -# self._on_eval_batch_end(trainer, pl_module, batch, outputs, batch_idx, dataloader_idx, 'test') - -# @rank_zero_only -# def on_validation_batch_end(self, trainer, pl_module, batch, outputs, batch_idx, dataloader_idx): -# self._on_eval_batch_end(trainer, pl_module, batch, outputs, batch_idx, dataloader_idx, 'val') - -# def _on_eval_start(self, trainer, pl_module): -# self._translations = [] -# self._ground_truths = [] -# self._losses = [] -# self._non_pad_tokens = [] - -# @rank_zero_only -# def on_test_start(self, trainer, pl_module): -# self._on_eval_start(trainer, pl_module) - -# @rank_zero_only -# def on_validation_start(self, trainer, pl_module): -# self._on_eval_start(trainer, pl_module) - -# @rank_zero_only -# def on_sanity_check_start(self, trainer, pl_module): -# self._on_eval_start(trainer, pl_module) diff --git a/nemo/collections/common/callbacks/ema.py b/nemo/collections/common/callbacks/ema.py deleted file mode 100644 index dee125be54ef16f8588ba0e4c17b4e2258d6e64f..0000000000000000000000000000000000000000 --- a/nemo/collections/common/callbacks/ema.py +++ /dev/null @@ -1,360 +0,0 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import contextlib -import copy -import os -import threading -from typing import Any, Dict, Iterable - -import lightning.pytorch as pl -import torch -from lightning.pytorch import Callback -from lightning.pytorch.utilities.exceptions import MisconfigurationException -from lightning.pytorch.utilities.rank_zero import rank_zero_info - - -class EMA(Callback): - """ - Implements Exponential Moving Averaging (EMA). - - When training a model, this callback will maintain moving averages of the trained parameters. - When evaluating, we use the moving averages copy of the trained parameters. - When saving, we save an additional set of parameters with the prefix `ema`. - - Args: - decay: The exponential decay used when calculating the moving average. Has to be between 0-1. - validate_original_weights: Validate the original weights, as apposed to the EMA weights. - every_n_steps: Apply EMA every N steps. - cpu_offload: Offload weights to CPU. - """ - - def __init__( - self, - decay: float, - validate_original_weights: bool = False, - every_n_steps: int = 1, - cpu_offload: bool = False, - ): - if not (0 <= decay <= 1): - raise MisconfigurationException("EMA decay value must be between 0 and 1") - self.decay = decay - self.validate_original_weights = validate_original_weights - self.every_n_steps = every_n_steps - self.cpu_offload = cpu_offload - - def on_fit_start(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None: - device = pl_module.device if not self.cpu_offload else torch.device('cpu') - trainer.optimizers = [ - EMAOptimizer( - optim, - device=device, - decay=self.decay, - every_n_steps=self.every_n_steps, - current_step=trainer.global_step, - ) - for optim in trainer.optimizers - if not isinstance(optim, EMAOptimizer) - ] - - def on_validation_start(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None: - if self._should_validate_ema_weights(trainer): - self.swap_model_weights(trainer) - - def on_validation_end(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None: - if self._should_validate_ema_weights(trainer): - self.swap_model_weights(trainer) - - def on_test_start(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None: - if self._should_validate_ema_weights(trainer): - self.swap_model_weights(trainer) - - def on_test_end(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None: - if self._should_validate_ema_weights(trainer): - self.swap_model_weights(trainer) - - def _should_validate_ema_weights(self, trainer: "pl.Trainer") -> bool: - return not self.validate_original_weights and self._ema_initialized(trainer) - - def _ema_initialized(self, trainer: "pl.Trainer") -> bool: - return any(isinstance(optimizer, EMAOptimizer) for optimizer in trainer.optimizers) - - def swap_model_weights(self, trainer: "pl.Trainer", saving_ema_model: bool = False): - for optimizer in trainer.optimizers: - assert isinstance(optimizer, EMAOptimizer) - optimizer.switch_main_parameter_weights(saving_ema_model) - - @contextlib.contextmanager - def save_ema_model(self, trainer: "pl.Trainer"): - """ - Saves an EMA copy of the model + EMA optimizer states for resume. - """ - self.swap_model_weights(trainer, saving_ema_model=True) - try: - yield - finally: - self.swap_model_weights(trainer, saving_ema_model=False) - - @contextlib.contextmanager - def save_original_optimizer_state(self, trainer: "pl.Trainer"): - for optimizer in trainer.optimizers: - assert isinstance(optimizer, EMAOptimizer) - optimizer.save_original_optimizer_state = True - try: - yield - finally: - for optimizer in trainer.optimizers: - optimizer.save_original_optimizer_state = False - - def on_load_checkpoint( - self, trainer: "pl.Trainer", pl_module: "pl.LightningModule", checkpoint: Dict[str, Any] - ) -> None: - checkpoint_callback = trainer.checkpoint_callback - - # Replace connector._ckpt_path with below to avoid calling into lightning's protected API - ckpt_path = trainer.ckpt_path - - if ckpt_path and checkpoint_callback is not None and 'NeMo' in type(checkpoint_callback).__name__: - ext = checkpoint_callback.FILE_EXTENSION - if ckpt_path.endswith(f'-EMA{ext}'): - rank_zero_info( - "loading EMA based weights. " - "The callback will treat the loaded EMA weights as the main weights" - " and create a new EMA copy when training." - ) - return - ema_path = ckpt_path.replace(ext, f'-EMA{ext}') - if os.path.exists(ema_path): - ema_state_dict = torch.load(ema_path, map_location=torch.device('cpu')) - - checkpoint['optimizer_states'] = ema_state_dict['optimizer_states'] - del ema_state_dict - rank_zero_info("EMA state has been restored.") - else: - raise MisconfigurationException( - "Unable to find the associated EMA weights when re-loading, " - f"training will start with new EMA weights. Expected them to be at: {ema_path}", - ) - - -@torch.no_grad() -def ema_update(ema_model_tuple, current_model_tuple, decay): - torch._foreach_mul_(ema_model_tuple, decay) - torch._foreach_add_( - ema_model_tuple, - current_model_tuple, - alpha=(1.0 - decay), - ) - - -def run_ema_update_cpu(ema_model_tuple, current_model_tuple, decay, pre_sync_stream=None): - if pre_sync_stream is not None: - pre_sync_stream.synchronize() - - ema_update(ema_model_tuple, current_model_tuple, decay) - - -class EMAOptimizer(torch.optim.Optimizer): - r""" - EMAOptimizer is a wrapper for torch.optim.Optimizer that computes - Exponential Moving Average of parameters registered in the optimizer. - - EMA parameters are automatically updated after every step of the optimizer - with the following formula: - - ema_weight = decay * ema_weight + (1 - decay) * training_weight - - To access EMA parameters, use ``swap_ema_weights()`` context manager to - perform a temporary in-place swap of regular parameters with EMA - parameters. - - Notes: - - EMAOptimizer is not compatible with APEX AMP O2. - - Args: - optimizer (torch.optim.Optimizer): optimizer to wrap - device (torch.device): device for EMA parameters - decay (float): decay factor - - Returns: - returns an instance of torch.optim.Optimizer that computes EMA of - parameters - - Example: - model = Model().to(device) - opt = torch.optim.Adam(model.parameters()) - - opt = EMAOptimizer(opt, device, 0.9999) - - for epoch in range(epochs): - training_loop(model, opt) - - regular_eval_accuracy = evaluate(model) - - with opt.swap_ema_weights(): - ema_eval_accuracy = evaluate(model) - """ - - def __init__( - self, - optimizer: torch.optim.Optimizer, - device: torch.device, - decay: float = 0.9999, - every_n_steps: int = 1, - current_step: int = 0, - ): - self.optimizer = optimizer - self.decay = decay - self.device = device - self.current_step = current_step - self.every_n_steps = every_n_steps - self.save_original_optimizer_state = False - - self.first_iteration = True - self.rebuild_ema_params = True - self.stream = None - self.thread = None - - self.ema_params = () - self.in_saving_ema_model_context = False - - def all_parameters(self) -> Iterable[torch.Tensor]: - return (param for group in self.param_groups for param in group['params']) - - def step(self, closure=None, grad_scaler=None, **kwargs): - self.join() - - if self.first_iteration: - if any(p.is_cuda for p in self.all_parameters()): - self.stream = torch.cuda.Stream() - - self.first_iteration = False - - if self.rebuild_ema_params: - opt_params = list(self.all_parameters()) - - self.ema_params += tuple( - copy.deepcopy(param.data.detach()).to(self.device) for param in opt_params[len(self.ema_params) :] - ) - self.rebuild_ema_params = False - - if getattr(self.optimizer, "_step_supports_amp_scaling", False) and grad_scaler is not None: - loss = self.optimizer.step(closure=closure, grad_scaler=grad_scaler) - else: - loss = self.optimizer.step(closure) - - if self._should_update_at_step(): - self.update() - self.current_step += 1 - return loss - - def _should_update_at_step(self) -> bool: - return self.current_step % self.every_n_steps == 0 - - @torch.no_grad() - def update(self): - if self.stream is not None: - self.stream.wait_stream(torch.cuda.current_stream()) - - with torch.cuda.stream(self.stream): - current_model_state = tuple( - param.data.to(self.device, non_blocking=True) for param in self.all_parameters() - ) - - if self.device.type == 'cuda': - ema_update(self.ema_params, current_model_state, self.decay) - - if self.device.type == 'cpu': - self.thread = threading.Thread( - target=run_ema_update_cpu, - args=( - self.ema_params, - current_model_state, - self.decay, - self.stream, - ), - ) - self.thread.start() - - def swap_tensors(self, tensor1, tensor2): - tmp = torch.empty_like(tensor1) - tmp.copy_(tensor1) - tensor1.copy_(tensor2) - tensor2.copy_(tmp) - - def switch_main_parameter_weights(self, saving_ema_model: bool = False): - self.join() - self.in_saving_ema_model_context = saving_ema_model - for param, ema_param in zip(self.all_parameters(), self.ema_params): - self.swap_tensors(param.data, ema_param) - - @contextlib.contextmanager - def swap_ema_weights(self, enabled: bool = True): - r""" - A context manager to in-place swap regular parameters with EMA - parameters. - It swaps back to the original regular parameters on context manager - exit. - - Args: - enabled (bool): whether the swap should be performed - """ - - if enabled: - self.switch_main_parameter_weights() - try: - yield - finally: - if enabled: - self.switch_main_parameter_weights() - - def __getattr__(self, name): - return getattr(self.optimizer, name) - - def join(self): - if self.stream is not None: - self.stream.synchronize() - - if self.thread is not None: - self.thread.join() - - def state_dict(self): - self.join() - - if self.save_original_optimizer_state: - return self.optimizer.state_dict() - - # if we are in the context of saving an EMA model, the EMA weights are in the modules' actual weights - ema_params = self.ema_params if not self.in_saving_ema_model_context else list(self.all_parameters()) - state_dict = { - 'opt': self.optimizer.state_dict(), - 'ema': ema_params, - 'current_step': self.current_step, - 'decay': self.decay, - 'every_n_steps': self.every_n_steps, - } - return state_dict - - def load_state_dict(self, state_dict): - self.join() - - self.optimizer.load_state_dict(state_dict['opt']) - self.ema_params = tuple(param.to(self.device) for param in copy.deepcopy(state_dict['ema'])) - self.current_step = state_dict['current_step'] - self.decay = state_dict['decay'] - self.every_n_steps = state_dict['every_n_steps'] - self.rebuild_ema_params = False - - def add_param_group(self, param_group): - self.optimizer.add_param_group(param_group) - self.rebuild_ema_params = True diff --git a/nemo/collections/common/callbacks/ipl_epoch_stopper.py b/nemo/collections/common/callbacks/ipl_epoch_stopper.py deleted file mode 100644 index 63d5831f292fd70be7ab0f32b0891663bd3726d1..0000000000000000000000000000000000000000 --- a/nemo/collections/common/callbacks/ipl_epoch_stopper.py +++ /dev/null @@ -1,55 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from lightning.pytorch import Trainer -from lightning.pytorch.callbacks import Callback -from lightning.pytorch.core import LightningModule - - -class IPLEpochStopper(Callback): - """ - Callback to gracefully terminate training at the *end* of an epoch, - typically used in Iterative Pseudo-Labeling (IPL) pipelines. - - IPL is a semi-supervised learning approach where models are trained - iteratively, alternating between generating pseudo-labels and fine-tuning - on them. For more details, see our paper: - "TopIPL: Unified Semi-Supervised Pipeline for Automatic Speech Recognition" - https://arxiv.org/abs/2506.07659 - - This callback is used to signal the Trainer to stop training after a given number - of epochs, allowing pseudo-label generation and model reinitialization to occur. - - Args: - enable_stop (bool): If True, the trainer will be requested to stop during - `on_train_epoch_end`. If False, the callback is inert. - stop_every_n_epochs (int): Number of epochs to run before each stop. If set to 1, - training will stop after every epoch. - """ - - def __init__(self, enable_stop: bool = False, stop_every_n_epochs: int = 1) -> None: - super().__init__() - self.enable_stop = bool(enable_stop) - self.stop_every_n_epochs = stop_every_n_epochs - - def on_train_epoch_end(self, trainer: Trainer, pl_module: LightningModule) -> None: - """ - Sets `should_stop` stop flag to terminate the training. - """ - super().__init__() - - if self.stop_every_n_epochs != 0: - self.stop_every_n_epochs -= 1 - if self.stop_every_n_epochs == 0: - trainer.should_stop = True diff --git a/nemo/collections/common/data/Makefile b/nemo/collections/common/data/Makefile deleted file mode 100644 index 2e05c5b49fb9a43557ac557344b6e60badf95d36..0000000000000000000000000000000000000000 --- a/nemo/collections/common/data/Makefile +++ /dev/null @@ -1,23 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -CXXFLAGS += -O3 -Wall -shared -std=c++11 -fPIC -fdiagnostics-color -CPPFLAGS += $(shell python3 -m pybind11 --includes) -LIBNAME = helpers -LIBEXT = $(shell python3-config --extension-suffix) - -default: $(LIBNAME)$(LIBEXT) - -%$(LIBEXT): %.cpp - $(CXX) $(CXXFLAGS) $(CPPFLAGS) $< -o $@ diff --git a/nemo/collections/common/data/__init__.py b/nemo/collections/common/data/__init__.py deleted file mode 100644 index 7a103094f3cc29190c8a0c35e6786646d97c4551..0000000000000000000000000000000000000000 --- a/nemo/collections/common/data/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from nemo.collections.common.data.dataset import CodeSwitchedDataset, ConcatDataset, ConcatMapDataset -from nemo.collections.common.data.prompt_fn import apply_prompt_format_fn, get_prompt_format_fn diff --git a/nemo/collections/common/data/blendable_dataset.py b/nemo/collections/common/data/blendable_dataset.py deleted file mode 100644 index ad634a4f96b37e79e0b1cc90d3166263aff9cc81..0000000000000000000000000000000000000000 --- a/nemo/collections/common/data/blendable_dataset.py +++ /dev/null @@ -1,222 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Blendable dataset.""" - -import os -import subprocess -import time - -import numpy as np -import torch - -from nemo.utils import logging -from nemo.utils.app_state import AppState - - -class BlendableDataset(torch.utils.data.Dataset): - """ """ - - def __init__(self, datasets, weights, size): - self.datasets = datasets - num_datasets = len(datasets) - assert num_datasets == len(weights) - - self.size = size - - # Normalize weights. - weights = np.array(weights, dtype=np.float64) - sum_weights = np.sum(weights) - assert sum_weights > 0.0 - weights /= sum_weights - - # Build indecies. - start_time = time.time() - assert num_datasets < 255 - self.dataset_index = np.zeros(self.size, dtype=np.uint8) - self.dataset_sample_index = np.zeros(self.size, dtype=np.int64) - - app_state = AppState() - - # Determine if we are in a distributed environment - is_dist = torch.distributed.is_available() and torch.distributed.is_initialized() - - try: - # Defensive check for local_rank in AppState - local_rank = getattr(app_state, 'local_rank', 0) if is_dist else 0 - - if local_rank == 0: - compile_helper() - - if is_dist: - torch.distributed.barrier() - - # pylint: disable=import-outside-toplevel - from nemo.collections.common.data import helpers - except ImportError as exc: - raise ImportError( - 'Could not compile megatron dataset C++ helper functions and therefore ' - 'cannot import helpers python file.' - ) from exc - - # Only the main process (rank 0) should handle logging/progress within helpers - is_main_process = (torch.distributed.get_rank() == 0) if is_dist else True - - helpers.build_blending_indices( - self.dataset_index, - self.dataset_sample_index, - weights, - num_datasets, - self.size, - is_main_process, - ) - logging.info(f'> elapsed time for building blendable dataset indices: {time.time() - start_time:.2f} (sec)') - - def __len__(self): - return self.size - - def __getitem__(self, idx): - dataset_idx = self.dataset_index[idx] - sample_idx = self.dataset_sample_index[idx] - dataset_size = len(self.datasets[dataset_idx]) - # Ensure the sample index doesn't exceed the dataset size - if sample_idx >= dataset_size: - logging.warning(f"Index {sample_idx} out of bounds for dataset {dataset_idx}. Reusing existing examples.") - sample_idx = sample_idx % dataset_size - logging.warning(f"Reusing index {sample_idx} for dataset {dataset_idx}.") - - return self.datasets[dataset_idx][sample_idx] - - def create_data_mmap(self): - """ """ - for dataset in self.datasets: - dataset.create_data_mmap() - - -class MemoryEfficientBlendableDataset(torch.utils.data.Dataset): - """ - A BlendableDataset implementation that uses less memory than the original implementation. - Indices are computed algorithmically instead of storing them in memory. - - To test call: MemoryEfficientBlendableDataset.test_index_blending() - """ - - def __init__(self, datasets, weights, size, weight_bins=100): - self.datasets = datasets - num_datasets = len(datasets) - assert num_datasets == len(weights) - - weight_bins = min(weight_bins, size) - - self.size = size - self.weight_bins = weight_bins - - # Normalize weights. - weights = np.array(weights, dtype=np.float64) - assert (weights > 0.0).all() - sum_weights = np.sum(weights) - assert sum_weights > 0.0 - self.weights = weights / sum_weights - - # create ds index based on weights - ds_index = [] - ds_bias = [] - for i, w in enumerate(self.weights): - n = int(w * weight_bins) - ds_index.extend([i] * n) - ds_bias.extend(range(n)) - # make sure arrays have length of weight_bins - n = weight_bins - len(ds_index) - ds_index.extend([i] * n) - ds_bias.extend(range(ds_bias[-1], ds_bias[-1] + n)) - - self.ds_index = np.array(ds_index, dtype=np.uint32) - self.ds_index_size = np.array([(self.ds_index == i).sum() for i in range(num_datasets)], dtype=np.uint32) - assert (self.ds_index_size > 0).all(), ( - "Some datasets have no samples in the blendable dataset, " - "increase weight_bins or the offending weight. " - f"ds_index_size = {self.ds_index_size}" - ) - self.ds_bias = np.array(ds_bias, dtype=np.uint32) - - self.ds_size = np.array([len(ds) for ds in datasets], dtype=np.uint32) - - def get_ds_sample_idx(self, idx): - """Returns ds index and sample index (within the ds) for the given index in the blendable dataset.""" - - bin = idx % self.weight_bins - ds_idx = self.ds_index[bin] - sample_idx = (self.ds_bias[bin] + (idx // self.weight_bins) * self.ds_index_size[ds_idx]) % self.ds_size[ - ds_idx - ] - - return ds_idx, sample_idx - - def __len__(self): - return self.size - - def __getitem__(self, idx): - ds_idx, sample_idx = self.get_ds_sample_idx(idx) - - return self.datasets[ds_idx][sample_idx] - - @classmethod - def test_index_blending(cls): - """Visualize indices of blended dataset""" - - import matplotlib.pyplot as plt - - plt.ion() - - class DS(torch.utils.data.Dataset): - """ """ - - def __init__(self, size, data): - self.size = size - self.data = data - - def __len__(self): - return self.size - - def __getitem__(self, idx): - return self.data[idx] - - for weight_bins in [10, 100]: - blend_ds = MemoryEfficientBlendableDataset( - [DS(10, "a"), DS(10, "b"), DS(10, "c")], [0.5, 0.3, 0.2], 50, weight_bins=weight_bins - ) - - ds_sample_idx_list = [blend_ds.get_ds_sample_idx(i) for i in range(50)] - ds_list = list(zip(*ds_sample_idx_list))[0] - sample_list = list(zip(*ds_sample_idx_list))[1] - - plt.figure() - plt.plot(ds_list, label="ds idx") - plt.plot(sample_list, label="sample") - plt.legend() - plt.grid() - plt.title(f"weight_bins={weight_bins}") - - -def compile_helper(): - """Compile helper function ar runtime. Make sure this - is invoked on a single process.""" - - path = os.path.abspath(os.path.dirname(__file__)) - ret = subprocess.run(['make', '-C', path]) - if ret.returncode != 0: - logging.error("Making C++ dataset helpers module failed, exiting.") - import sys - - sys.exit(1) diff --git a/nemo/collections/common/data/data_samplers.py b/nemo/collections/common/data/data_samplers.py deleted file mode 100644 index 99b612fdff451b6078c80d269e8ccc840d1b3589..0000000000000000000000000000000000000000 --- a/nemo/collections/common/data/data_samplers.py +++ /dev/null @@ -1,478 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Dataloaders.""" - -import abc -import warnings -from itertools import chain -from typing import Optional, Tuple - -import torch - -from nemo.utils import logging -from nemo.utils.decorators import experimental - -__all__ = [ - "MegatronPretrainingBatchSampler", - "MegatronPretrainingRandomBatchSampler", -] - - -class BaseMegatronSampler: - """ """ - - def __init__( - self, - total_samples: int, - consumed_samples: int, - micro_batch_size: int, - data_parallel_rank: int, - data_parallel_size: int, - drop_last: bool = True, - global_batch_size: Optional[int] = None, - rampup_batch_size: Optional[list] = None, - pad_samples_to_global_batch_size: Optional[bool] = False, - ) -> None: - # Sanity checks. - if total_samples <= 0: - raise RuntimeError("no sample to consume: {}".format(total_samples)) - if micro_batch_size <= 0: - raise RuntimeError(f"micro_batch_size size must be greater than 0, but {micro_batch_size}") - if data_parallel_size <= 0: - raise RuntimeError(f"data parallel size must be greater than 0, but {data_parallel_size}") - if data_parallel_rank >= data_parallel_size: - raise RuntimeError( - "data_parallel_rank should be smaller than data size, but {} >= {}".format( - data_parallel_rank, data_parallel_size - ) - ) - if global_batch_size is not None and rampup_batch_size is None: - if global_batch_size % (micro_batch_size * data_parallel_size) != 0: - raise RuntimeError( - f"`global_batch_size` ({global_batch_size}) is not divisible by " - f"`micro_batch_size ({micro_batch_size}) x data_parallel_size " - f"({data_parallel_size})`" - ) - if pad_samples_to_global_batch_size and global_batch_size is None: - raise RuntimeError( - "`pad_samples_to_global_batch_size` can be `True` only when " - "`global_batch_size` is set to an integer value" - ) - - # Keep a copy of input params for later use. - self.total_samples = total_samples - self.consumed_samples = consumed_samples - self.micro_batch_size = micro_batch_size - self.data_parallel_rank = data_parallel_rank - self.data_parallel_size = data_parallel_size - self.micro_batch_times_data_parallel_size = self.micro_batch_size * data_parallel_size - self.drop_last = drop_last - self.global_batch_size = global_batch_size - self.pad_samples_to_global_batch_size = pad_samples_to_global_batch_size - - logging.info( - f'Instantiating MegatronPretrainingSampler with total_samples: {total_samples} ' - f'and consumed_samples: {consumed_samples}' - ) - - def __len__(self): - num_available_samples: int = self.total_samples - self.consumed_samples - if self.global_batch_size is not None: - if self.drop_last: - num_global_batches = num_available_samples // self.global_batch_size - else: - num_global_batches = (num_available_samples + self.global_batch_size - 1) // self.global_batch_size - # return len of dataloader in terms of micro batches to avoid discrepancy between len of dataloader and - # num of batches fetched (as training step fetches in terms of micro batches) - return num_global_batches * (self.global_batch_size // self.micro_batch_times_data_parallel_size) - else: - return (num_available_samples - 1) // self.micro_batch_times_data_parallel_size + 1 - - @abc.abstractmethod - def __iter__(self): ... - - -class MegatronPretrainingSampler(BaseMegatronSampler): - """ """ - - def get_start_end_idx(self): - """ """ - start_idx = self.data_parallel_rank * self.micro_batch_size - end_idx = start_idx + self.micro_batch_size - return start_idx, end_idx - - def _get_padding_indices(self, pad_samples_num): - """ """ - return range(-1, -pad_samples_num - 1, -1) - - def __iter__(self): - batch = [] - # Last batch will be dropped if drop_last is not set False - indices = range(self.consumed_samples, self.total_samples) - if (not self.drop_last) and self.pad_samples_to_global_batch_size: - pad_samples_num = -len(indices) % self.global_batch_size - pad_indices = self._get_padding_indices(pad_samples_num) - indices = chain(indices, pad_indices) - - for idx in indices: - batch.append(idx) - if len(batch) == self.micro_batch_times_data_parallel_size: - start_idx, end_idx = self.get_start_end_idx() - yield batch[start_idx:end_idx] - batch = [] - - # Check the last partial batch and see drop_last is set - if len(batch) > 0 and not self.drop_last: - assert ( - not self.pad_samples_to_global_batch_size - ), 'with pad_samples_to_global_batch_size all batches should be complete' - start_idx, end_idx = self.get_start_end_idx() - yield batch[start_idx:end_idx] - - -class MegatronCorePretrainingSampler(MegatronPretrainingSampler): - """ """ - - def _get_padding_indices(self, pad_samples_num): - """ """ - return [None] * pad_samples_num - - -class MegatronPretrainingRandomSampler(BaseMegatronSampler): - """ """ - - def __init__( - self, - total_samples: int, - consumed_samples: int, - micro_batch_size: int, - data_parallel_rank: int, - data_parallel_size: int, - drop_last: bool = True, - global_batch_size: Optional[int] = None, - pad_samples_to_global_batch_size: Optional[bool] = False, - seed: int = 0, - ) -> None: - super().__init__( - total_samples=total_samples, - consumed_samples=consumed_samples, - micro_batch_size=micro_batch_size, - data_parallel_rank=data_parallel_rank, - data_parallel_size=data_parallel_size, - drop_last=drop_last, - global_batch_size=global_batch_size, - pad_samples_to_global_batch_size=pad_samples_to_global_batch_size, - ) - assert ( - not pad_samples_to_global_batch_size - ), "`MegatronPretrainingRandomSampler` does not support sample padding" - if (not drop_last) and self.micro_batch_times_data_parallel_size > 1: - raise RuntimeError( - "`MegatronPretrainingRandomSampler` does not support drop_last=False when \ - micro_batch_size * data_parallel_size > 1. Please reduce your MBS and data parallelism to 1 \ - if you want to use drop_last=False, or switch to drop_last=True to avoid this error" - ) - self.last_batch_size = self.total_samples % self.micro_batch_times_data_parallel_size - self.seed = seed - - def __len__(self): - active_total_samples = self.total_samples - (self.last_batch_size if self.drop_last else 0) - num_available_samples = active_total_samples - self.consumed_samples % active_total_samples - if self.global_batch_size is not None: - if self.drop_last: - num_global_batches = num_available_samples // self.global_batch_size - else: - num_global_batches = (num_available_samples + self.global_batch_size - 1) // self.global_batch_size - # return len of dataloader in terms of micro batches to avoid discrepancy between len of dataloader and - # num of batches fetched (as training step fetches in terms of micro batches) - return num_global_batches * (self.global_batch_size // self.micro_batch_times_data_parallel_size) - else: - if self.drop_last: - return num_available_samples // self.micro_batch_times_data_parallel_size - else: - return (num_available_samples - 1) // self.micro_batch_times_data_parallel_size - - def __iter__(self): - active_total_samples = self.total_samples - self.last_batch_size - self.epoch = self.consumed_samples // active_total_samples - current_epoch_samples = self.consumed_samples % active_total_samples - assert current_epoch_samples % self.micro_batch_times_data_parallel_size == 0 - - # data sharding and random sampling - bucket_size = (self.total_samples // self.micro_batch_times_data_parallel_size) * self.micro_batch_size - bucket_offset = current_epoch_samples // self.data_parallel_size - start_idx = self.data_parallel_rank * bucket_size - - g = torch.Generator() - g.manual_seed(self.seed + self.epoch) - random_idx = torch.randperm(bucket_size, generator=g).tolist() - idx_range = [start_idx + x for x in random_idx[bucket_offset:]] - - batch = [] - # Last batch if not complete will be dropped. - for idx in idx_range: - batch.append(idx) - if len(batch) == self.micro_batch_size: - self.consumed_samples += self.micro_batch_times_data_parallel_size - yield batch - batch = [] - - # Check the last partial batch and see drop_last is set - if len(batch) > 0 and not self.drop_last: - yield batch - - -class BaseMegatronBatchSampler: - """Megatron style BatchSampler. - - Let mbs, gbs, tp, pp, and dp stand for "micro batch size", "global batch size", - "tensor model parallel world size", "pipeline model parallel world size", and - "data parallel world size", the number of micro batches (hereafter, nmb) is defined as - :math:`nmb = gbs \\div (mbs \\times dp)`. - - See `apex/transformer/microbatches.py#L91-L98 `_ - for the initial settings of the number of micro batches and - `apex/transformer/microbatches.py#L160-L177 _`. - for warming up of global batch size. - - e.g.) `(mbs, gbs, tp, pp, dp) = (1, 16, 1, 1, 2)`, then the number of micro batches is - :math:`gbs \\div (mbs \\times dp) = 16 \\div (1 \\times 2) = 8`. - In this case, an instance of Megatron Batch Sampler on each data parallel rank is expected - returns :math:`nmb \\times mbs = 8` indices. - """ - - _global_batch_size: int - _num_micro_batches: int - _global_batch_size_on_this_data_parallel_rank: int - - def __init__( - self, - total_samples: int, - consumed_samples: int, - micro_batch_size: int, - global_batch_size: int, - data_parallel_rank: int, - data_parallel_size: int, - drop_last: bool, - pad_samples_to_global_batch_size=False, - ) -> None: - """Constructor of Megatron-LM style Batch Sampler. - - Args: - total_samples: The size of dataset. - consumed_samples: The number of samples that have been used. - micro_batch_size: The size of each micro batch. - global_batch_size: The size of global batch. - data_parallel_rank: The value you can obtain via - `parallel_state.get_data_parallel_rank()` of megatron.core. - data_parallel_size: The value you can obtain via - `parallel_state.get_data_parallel_world_size()` of megatron.core. - """ - # Sanity checks. - if total_samples <= 0: - raise RuntimeError("no sample to consume: {}".format(total_samples)) - if micro_batch_size <= 0: - raise RuntimeError(f"micro_batch_size size must be greater than 0, but {micro_batch_size}") - if data_parallel_size <= 0: - raise RuntimeError(f"data parallel size must be greater than 0, but {data_parallel_size}") - if data_parallel_rank >= data_parallel_size: - raise RuntimeError( - "data_parallel_rank should be smaller than data size, but {} >= {}".format( - data_parallel_rank, data_parallel_size - ) - ) - # Keep a copy of input params for later use. - self.total_samples: int = total_samples - self.consumed_samples: int = consumed_samples - self.micro_batch_size: int = micro_batch_size - self.data_parallel_rank: int = data_parallel_rank - self.data_parallel_size: int = data_parallel_size - self.drop_last: bool = drop_last - self.pad_samples_to_global_batch_size = pad_samples_to_global_batch_size - self.micro_batch_times_data_parallel_size = self.micro_batch_size * self.data_parallel_size - - self.update_global_batch_size(global_batch_size) - - def update_global_batch_size(self, new_global_batch_size: int) -> None: - """Update the global batch size.""" - self._global_batch_size = new_global_batch_size - if self._global_batch_size % self.micro_batch_times_data_parallel_size != 0: - raise RuntimeError( - f"`global_batch_size` ({self._global_batch_size}) is not divisible by " - f"`micro_batch_size ({self.micro_batch_size}) x data_parallel_size " - f"({self.data_parallel_size})`" - ) - self._num_micro_batches = self._global_batch_size // self.micro_batch_times_data_parallel_size - self._global_batch_size_on_this_data_parallel_rank = self._num_micro_batches * self.micro_batch_size - - @property - def global_batch_size(self) -> int: - """ """ - return self._global_batch_size - - @global_batch_size.setter - def global_batch_size(self, new_global_batch_size: int) -> None: - """ """ - warnings.warn("`self.update_global_batch_size(new_global_batch_size)` is recommended.") - self.update_global_batch_size(new_global_batch_size=new_global_batch_size) - - def __len__(self) -> int: - """Length of Batch Sampler. - - ..note:: - When `rampup_batch_size` is enabled, the return value can be not exactly precise. - - """ - num_available_samples: int = self.total_samples - self.consumed_samples % self.total_samples - if self.drop_last: - return num_available_samples // self.global_batch_size - else: - return (num_available_samples + self.global_batch_size - 1) // self.global_batch_size - - @abc.abstractmethod - def __iter__(self): ... - - -class MegatronPretrainingBatchSampler(BaseMegatronBatchSampler): - """ """ - - def get_start_end_idx(self) -> Tuple[int, int]: - """ """ - start_idx = self.data_parallel_rank * self._global_batch_size_on_this_data_parallel_rank - end_idx = start_idx + self._global_batch_size_on_this_data_parallel_rank - return start_idx, end_idx - - def __iter__(self): - batch = [] - # Last batch will be dropped if drop_last is not set False - for idx in range(self.consumed_samples % self.total_samples, self.total_samples): - batch.append(idx) - if len(batch) == self._global_batch_size: - # start_idx, end_idx = self.get_start_end_idx() - indices = [ - batch[i] - for i in range( - self.data_parallel_rank, - self._global_batch_size, - self.data_parallel_size, - ) - ] - assert len(indices) == self._global_batch_size_on_this_data_parallel_rank - yield indices - # yield batch[start_idx:end_idx] - batch = [] - - # Check the last partial batch and see drop_last is set - if len(batch) > 0 and not self.drop_last: - # start_idx, end_idx = self.get_start_end_idx() - indices = [batch[i] for i in range(self.data_parallel_rank, len(batch), self.data_parallel_size)] - if self.pad_samples_to_global_batch_size: - num_pad = self._global_batch_size // self.data_parallel_size - len(indices) - indices = indices + [-1] * num_pad - yield indices - - -@experimental -class MegatronPretrainingRandomBatchSampler(BaseMegatronBatchSampler): - """ """ - - # NOTE (mkozuki): [[Argument of `dataset` and `data_sharding`]] - # From the commit below, it seems like `dataset` argument and `data_sharding` argument - # are necessary for ViT training. However, to keep this simple, - # I omit those two arguments. - # commit: https://github.com/NVIDIA/Megatron-LM/commit/7a77abd9b6267dc0020a60b424b4748fc22790bb - # - # NOTE (degert): I have re-written this class somewhat to give the length correctly when consumed_samples - # are larger than total_samples, which happens with epochs > 1 training when using this Sampler - # I have also added an explicit seed which allows us to remove Dataset-side shuffling in Nemo-Aligner - # - # This class does not currently work with pad_samples_to_global_batch_size=True - def __init__( - self, - total_samples: int, - consumed_samples: int, - micro_batch_size: int, - global_batch_size: int, - data_parallel_rank: int, - data_parallel_size: int, - drop_last: bool, - pad_samples_to_global_batch_size: bool = False, - seed: int = 0, - ) -> None: - super().__init__( - total_samples=total_samples, - consumed_samples=consumed_samples, - micro_batch_size=micro_batch_size, - data_parallel_rank=data_parallel_rank, - data_parallel_size=data_parallel_size, - drop_last=drop_last, - global_batch_size=global_batch_size, - pad_samples_to_global_batch_size=pad_samples_to_global_batch_size, - ) - assert ( - not pad_samples_to_global_batch_size - ), "`MegatronPretrainingRandomBatchSampler` does not support sample padding" - if (not drop_last) and self.micro_batch_times_data_parallel_size > 1: - raise RuntimeError( - "`MegatronPretrainingRandomBatchSampler` does not support drop_last=False \ - when micro_batch_size * data_parallel_size > 1. Please reduce your MBS and data parallelism to 1 \ - if you want to use drop_last=False, or switch to drop_last=True to avoid this error" - ) - self.last_batch_size = self.total_samples % self._global_batch_size - self.seed = seed - - def __len__(self) -> int: - """Length of Random Batch Sampler. - - ..note:: - When `rampup_batch_size` is enabled, the return value can be not exactly precise. - - """ - active_total_samples = self.total_samples - (self.last_batch_size if self.drop_last else 0) - num_available_samples = active_total_samples - self.consumed_samples % active_total_samples - if self.drop_last: - return num_available_samples // self.global_batch_size - else: - return (num_available_samples + self.global_batch_size - 1) // self.global_batch_size - - def __iter__(self): - active_total_samples = self.total_samples - self.last_batch_size - self.epoch = self.consumed_samples // active_total_samples - current_epoch_samples = self.consumed_samples % active_total_samples - assert current_epoch_samples % self.micro_batch_times_data_parallel_size == 0 - - # data sharding and random sampling - bucket_size = (self.total_samples // self.micro_batch_times_data_parallel_size) * self.micro_batch_size - bucket_offset = current_epoch_samples // self.data_parallel_size - start_idx = self.data_parallel_rank * bucket_size - - g = torch.Generator() - g.manual_seed(self.seed + self.epoch) - random_idx = torch.randperm(bucket_size, generator=g).tolist() - idx_range = [start_idx + x for x in random_idx[bucket_offset:]] - - batch = [] - # Last batch if not complete will be dropped. - for idx in idx_range: - batch.append(idx) - if len(batch) == self._global_batch_size_on_this_data_parallel_rank: - self.consumed_samples += self._global_batch_size - yield batch - batch = [] - # Check the last partial batch and see drop_last is set - if len(batch) > 0 and not self.drop_last: - yield batch diff --git a/nemo/collections/common/data/dataset.py b/nemo/collections/common/data/dataset.py deleted file mode 100644 index 71220dd9d5f2102da5e3cc00ce94c346e46e5eab..0000000000000000000000000000000000000000 --- a/nemo/collections/common/data/dataset.py +++ /dev/null @@ -1,664 +0,0 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import io -import logging -from typing import Any, List, Optional, Tuple, Union - -import numpy as np -import torch -import torch.utils.data as pt_data -from torch.utils.data import Dataset, IterableDataset - -__all__ = ['ConcatDataset', 'ConcatMapDataset', 'CodeSwitchedDataset'] - - -class ConcatDataset(IterableDataset): - """ - A dataset that accepts as argument multiple datasets and then samples from them based on the specified - sampling technique. - - Args: - datasets (list): A list of datasets to sample from. - shuffle (bool): Whether to shuffle individual datasets. Only works with non-iterable datasets. - Defaults to True. - sampling_technique (str): Sampling technique to choose which dataset to draw a sample from. - Defaults to 'temperature'. Currently supports 'temperature', 'random' and 'round-robin'. - sampling_temperature (int): Temperature value for sampling. Only used when sampling_technique = 'temperature'. - Defaults to 5. - sampling_scale: Gives you the ability to upsample / downsample the dataset. Defaults to 1. - sampling_probabilities (list): Probability values for sampling. Only used when sampling_technique = 'random'. - seed: Optional value to seed the numpy RNG. - global_rank (int): Worker rank, used for partitioning map style datasets. Defaults to 0. - world_size (int): Total number of processes, used for partitioning map style datasets. Defaults to 1. - """ - - def __init__( - self, - datasets: List[Any], - shuffle: bool = True, - sampling_technique: str = 'temperature', - sampling_temperature: int = 5, - sampling_scale: int = 1, - sampling_probabilities: List[float] = None, - seed: Optional[int] = None, - global_rank: int = 0, - world_size: int = 1, - ): - super().__init__() - - supported_sampling_techniques = ['temperature', 'random', 'round-robin'] - self.datasets = datasets - self.iterables = [None] * len(datasets) - self.shuffle = shuffle - self.global_rank = global_rank - self.world_size = world_size - self.sampling_kwargs = {} - self.sampling_scale = sampling_scale - - if sampling_technique == 'temperature': - self.index_generator = ConcatDataset.temperature_generator - self.sampling_kwargs['temperature'] = sampling_temperature - self.sampling_kwargs['seed'] = seed - elif sampling_technique == 'random': - self.index_generator = ConcatDataset.random_generator - self.sampling_kwargs['p'] = ( - sampling_probabilities if sampling_probabilities else [1 / len(datasets)] * len(datasets) - ) - self.sampling_kwargs['seed'] = seed - elif sampling_technique == 'round-robin': - self.index_generator = ConcatDataset.round_robin_generator - else: - raise ValueError(f"Currently we only support sampling techniques in {supported_sampling_techniques}.") - self.length = 0 - - if isinstance(datasets[0], IterableDataset): - self.kind = 'iterable' - else: - self.kind = 'map' - - for idx, dataset in enumerate(datasets): - isiterable = isinstance(dataset, IterableDataset) - if (isiterable and not self.kind == 'iterable') or (not isiterable and self.kind == 'iterable'): - raise ValueError("All datasets in ConcatDataset must be of the same kind (Iterable or Map).") - - if self.kind == 'map': - self.length += len(dataset) // world_size - else: - self.length += len(dataset) - - if self.sampling_scale != 1: - self.length = int(self.length * self.sampling_scale) - logging.info(f'applying {sampling_scale} sampling scale, concat ds len: {self.length}') - - def get_iterable(self, dataset): - if isinstance(dataset, IterableDataset): - return dataset.__iter__() - else: - indices = np.arange(len(dataset)) - if self.shuffle: - np.random.shuffle(indices) - return iter(indices) - - def __iter__(self): - worker_info = pt_data.get_worker_info() - if worker_info is None: - max_elements = self.length - wid = 0 - wnum = 1 - else: - wid = worker_info.id - wnum = worker_info.num_workers - max_elements = len(range(wid, self.length, wnum)) - - if self.kind == 'map': - for idx in range(len(self.datasets)): - start_idx = (len(self.datasets[idx]) // self.world_size) * self.global_rank - end_idx = start_idx + (len(self.datasets[idx]) // self.world_size) - if self.global_rank == self.world_size - 1: - end_idx = len(self.datasets[idx]) - indices = range(start_idx + wid, end_idx, wnum) - self.datasets[idx] = pt_data.Subset(self.datasets[idx], indices) - - for idx, dataset in enumerate(self.datasets): - iterable = self.get_iterable(dataset) - self.iterables[idx] = iterable - - n = 0 - ind_gen = self.index_generator(self.datasets, **self.sampling_kwargs) - while n < max_elements: - n += 1 - try: - ind = next(ind_gen) - except StopIteration: - return - try: - val = next(self.iterables[ind]) - if self.kind == 'map': - val = self.datasets[ind][val] - yield val - except StopIteration: - self.iterables[ind] = self.get_iterable(self.datasets[ind]) - n -= 1 - - def __len__(self): - return self.length - - @staticmethod - def temperature_generator(datasets, **kwargs): - temp = kwargs.get('temperature') - if not temp: - raise ValueError("Temperature generator expects a 'temperature' keyword argument.") - - seed = kwargs.get('seed', None) - np_rng = np.random.RandomState(seed) - lengths = [] - num = len(datasets) - for dataset in datasets: - lengths.append(len(dataset)) - - p = np.array(lengths) / np.sum(lengths) - p = np.power(p, 1 / temp) - p = p / np.sum(p) - - while True: - ind = np_rng.choice(np.arange(num), p=p) - yield ind - - @staticmethod - def round_robin_generator(datasets, **kwargs): - num = len(datasets) - while True: - for i in range(num): - yield i - - @staticmethod - def random_generator(datasets, **kwargs): - p = kwargs.get('p') - if not p: - raise ValueError("Random generator expects a 'p' keyowrd argument for sampling probabilities.") - - seed = kwargs.get('seed', None) - np_rng = np.random.RandomState(seed) - num = len(datasets) - if len(p) != num: - raise ValueError("Length of probabilities list must be equal to the number of datasets.") - - while True: - ind = np_rng.choice(np.arange(num), p=p) - yield ind - - -class ConcatMapDataset(Dataset): - """ - A dataset that accepts as argument multiple datasets and then samples from them based on the specified - sampling technique. - - Args: - datasets (list): A list of datasets to sample from. - sampling_technique (str): Sampling technique to choose which dataset to draw a sample from. - Defaults to 'temperature'. Currently supports 'temperature', 'random' and 'round-robin'. - sampling_temperature (int): Temperature value for sampling. Only used when sampling_technique = 'temperature'. - Defaults to 5. - sampling_probabilities (list): Probability values for sampling. Only used when sampling_technique = 'random'. - seed: Optional value to seed the numpy RNG. - """ - - def __init__( - self, - datasets: List[Any], - sampling_technique: str = 'temperature', - sampling_temperature: int = 5, - sampling_probabilities: Optional[List[float]] = None, - seed: Optional[int] = None, - ): - super().__init__() - self.datasets = datasets - self.lengths = [len(x) for x in self.datasets] - self.sampling_technique = sampling_technique - self.sampling_temperature = sampling_temperature - self.sampling_probabilities = sampling_probabilities - self.np_rng = np.random.RandomState(seed) - - # Build a list of size `len(self)`. Each tuple contains (dataset_id, dataset_index) - self.indices: List[Tuple[int, int]] = [] - # Current position as we consume indices from each data set - dataset_positions = [0] * len(self.datasets) - # Random permutation of each dataset. Will be regenerated when exhausted. - shuffled_indices = [self.np_rng.permutation(len(x)) for x in self.datasets] - # Build the list of randomly-chosen datasets spanning the entire length, adhering to sampling technique - if self.sampling_technique == "round-robin": - # To exhaust longest dataset, need to draw `num_datasets * max_dataset_len` samples - total_length = max(self.lengths) * len(self.lengths) - # For round robin, iterate through each dataset - dataset_ids = np.arange(total_length) % len(self.datasets) - for dataset_id in dataset_ids: - position = dataset_positions[dataset_id] - index = shuffled_indices[dataset_id][position] - self.indices.append((dataset_id, index)) - dataset_positions[dataset_id] += 1 - if dataset_positions[dataset_id] == len(shuffled_indices[dataset_id]): - dataset_positions[dataset_id] = 0 - shuffled_indices[dataset_id] = self.np_rng.permutation(len(self.datasets[dataset_id])) - else: - # Resolve probabilities of drawing from each data set - if self.sampling_technique == "random": - if sampling_probabilities is None or len(sampling_probabilities) != len(self.datasets): - raise ValueError( - f"Need {len(self.datasets)} probabilities; got " - f"{len(sampling_probabilities) if sampling_probabilities is not None else 'None'}" - ) - p = np.array(self.sampling_probabilities) - elif self.sampling_technique == "temperature": - p = np.array([len(x) for x in self.datasets]) - p = np.power(p, 1 / self.sampling_temperature) - else: - raise ValueError(f"Couldn't interpret sampling technique: {sampling_technique}") - # Normalize probabilities - p = p / np.sum(p) - # Will randomly choose from datasets - choices = np.arange(len(self.datasets)) - # Keep going until largest dataset is exhausted. - exhausted_datasets = set() - while len(exhausted_datasets) < len(self.datasets): - # Randomly choose a dataset for each position in accordance with p - dataset_id = self.np_rng.choice(a=choices, p=p) - dataset = self.datasets[dataset_id] - # Pick next index from dataset - position = dataset_positions[dataset_id] - index = shuffled_indices[dataset_id][position] - self.indices.append((dataset_id, index)) - # Maybe reset this dataset's permutation - dataset_positions[dataset_id] += 1 - if dataset_positions[dataset_id] >= len(dataset): - shuffled_indices[dataset_id] = self.np_rng.permutation(len(dataset)) - dataset_positions[dataset_id] = 0 - exhausted_datasets.add(dataset_id) - - def __len__(self): - return len(self.indices) - - def __getitem__(self, idx): - dataset_id, dataset_index = self.indices[idx] - return self.datasets[dataset_id][dataset_index] - - -class CodeSwitchedDataset(IterableDataset): - """ - A dataset that accepts as argument multiple sub-datasets (usually from different languages, but that's not required) and then - samples from them in order to create synthetic code-switched samples of up to N different sub-datasets - - Args: - datasets (list): A list of datasets - lang_probs (list): A list of probabilities (which must sum to 1) corresponding to the sampling probability for each dataset - shuffle (bool): Whether to shuffle individual datasets. Only works with non-iterable datasets. - Defaults to True. - min_duration (int): the minimum duration (secs) of each synthetic code-switched sample. Will draw randomly until this is hit. - Defaults to 4 - max_duration (int): the maximum duration (secs) of each synthetic code-switched sample. - Defaults to 20 - min_monolingual (float): this percentage of the dataset will be original monolingual samples - Defaults to 0.3 - means 30% - db_norm (float): will normalise the composite CS sample to this DB level - Defaults to -25.0 - pause_start (int): inserts silence equal to this value (msecs) at the start of each CS sample - Defaults to 0 - pause_join (int): inserts silence equal to this value (msecs) between all language changes in the CS sample - Defaults to 0 - pause_end (int): terminates all CS samples with silence equal to this value (msecs) - Defaults to 0 - sampling_scales (list or float): gives you the ability to upsample/downsample each individual dataset - seed: Optional value to seed the numpy RNG. - global_rank (int): Worker rank, used for partitioning map style datasets. Defaults to 0. - world_size (int): Total number of processes, used for partitioning map style datasets. Defaults to 1. - pure_random (bool): If true, then always draw random sample from lang_probs. If false, you only draw from those datasets - which you haven't sampled from yet for the composite sample - force_monochannel (bool): If true, then all output audio will be mono-channel - infinity_mode (bool): If true, then the dataset iterable will generate an infinite amount of samples - sample_rate (int): the sample rate of all audio being sent to this Dataset - augmentor (AudioAugmentor): The any perturbations you wish to have applied on the CS samples - """ - - def __init__( - self, - datasets: List[Any], - lang_probs: Optional[List[float]] = None, - shuffle: bool = True, - min_duration: int = 4, - max_duration: int = 20, - min_monolingual: float = 0.3, - db_norm: float = -25.0, - pause_start: int = 0, - pause_join: int = 0, - pause_end: int = 0, - sampling_scales: Optional[Union[float, List[float]]] = None, - seed: Optional[int] = None, - global_rank: int = 0, - world_size: int = 1, - pure_random: bool = False, - force_monochannel: bool = True, - infinity_mode: bool = False, - sample_rate: int = 16000, - augmentor: Optional['AudioAugmentor'] = None, - ): - super().__init__() - - if len(datasets) == 0: - raise ValueError("CodeSwitchedDataset must receive a non-zero length datasets dict object") - - self.datasets = datasets - self.langs = list(range(len(datasets))) - self.langs_set = set(self.langs) - self.lang_iterables = {k: None for k in self.langs} - self.lang_kind = {k: None for k in self.langs} - self.shuffle = shuffle - self.min_duration = min_duration - self.max_duration = max_duration - self.min_monolingual = min_monolingual - self.db_norm = db_norm - self.pause_start = pause_start - self.pause_join = pause_join - self.pause_end = pause_end - self.pure_random = pure_random - self.force_monochannel = force_monochannel - self.infinity_mode = infinity_mode - self.global_rank = global_rank - self.world_size = world_size - self.augmentor = augmentor - self.sample_rate = sample_rate - self.length = 0 - if lang_probs is None: - self.prob_dict = {l: 1.0 / len(self.langs) for l in self.langs} - else: - assert len(self.langs) == len( - lang_probs - ), "Size mismatch between languages and respective probs in CodeSwitchedDataset" - self.prob_dict = {l: lang_probs[l] for l in self.langs} - self.lang_probs = np.array(list(self.prob_dict.values())) - if sampling_scales is not None and not isinstance(sampling_scales, list): - self.sampling_scales = {k: sampling_scales for k in self.langs} - elif ( - sampling_scales is not None - and isinstance(sampling_scales, list) - and len(sampling_scales) == len(self.langs) - ): - self.sampling_scales = {k: v for k, v in zip(self.langs, sampling_scales)} - else: - self.sampling_scales = {k: 1 for k in self.langs} - - for lang, dataset in enumerate(self.datasets): - isiterable = isinstance(dataset, IterableDataset) - - if isiterable: - self.lang_kind[lang] = 'iterable' - self.length += int(len(dataset) * self.sampling_scales[lang]) - else: - self.lang_kind[lang] = 'map' - self.length += int((len(dataset) // world_size) * self.sampling_scales[lang]) - - if seed is not None: - np.random.seed(seed) - - # set this to ensure compatibility with models searching for the collate_fn - # since this class stores datasets as a dict, not list - # self.collate_fn = self.datasets[self.langs[0]].collate_fn - if hasattr(self.datasets[self.langs[0]], 'collate_fn'): - self.collate_fn = self.datasets[self.langs[0]].collate_fn - elif ( - hasattr(self.datasets[self.langs[0]], 'datasets') - and isinstance(self.datasets[self.langs[0]].datasets, list) - and len(self.datasets[self.langs[0]].datasets) > 0 - and hasattr(self.datasets[self.langs[0]].datasets[0], 'collate_fn') - ): - # support datasets that are lists of entries - self.collate_fn = self.datasets[self.langs[0]].datasets[0].collate_fn - elif ( - hasattr(self.datasets[self.langs[0]], 'datasets') - and isinstance(self.datasets[self.langs[0]].datasets, list) - and len(self.datasets[self.langs[0]].datasets) > 0 - and hasattr(self.datasets[self.langs[0]].datasets[0], 'datasets') - and isinstance(self.datasets[self.langs[0]].datasets[0].datasets, list) - and len(self.datasets[self.langs[0]].datasets[0].datasets) > 0 - and hasattr(self.datasets[self.langs[0]].datasets[0].datasets[0], 'collate_fn') - ): - # support datasets that are lists of lists - self.collate_fn = self.datasets[self.langs[0]].datasets[0].datasets[0].collate_fn - else: - raise RuntimeError("CodeSwitchedDataset could not locate a valid dataset collate_fn to bind to") - - # this method returns an iterator object for a given language ID - # it correctly handles whether the underlying dataset is IterableDataset or mappable - def get_iterable_by_lang(self, lang): - dataset = self.datasets[lang] - - if isinstance(dataset, IterableDataset): - return dataset.__iter__() - else: - indices = np.arange(len(dataset)) - if self.shuffle: - np.random.shuffle(indices) - return iter(indices) - - # this method is the main function which builds and returns a composite, synthetic code-switched - # utterance on the fly. It automatically works with all of the class-based variables stored to create - # the synthetic utterance - def build_single_CS_sample(self): - # get_sample_from_language returns a LongTensor for the transcripts so we create a LongTensor to hold - # all returned transcripts - comp_text = torch.LongTensor([]) - created_sample_duration_sec = 0 - created_sample_langs = [] - created_sample_audios = [] - - # if min_monolingual fires, it means we will just return a single, original monolingual utterance - # from one of our languages based on that language's probability - pure_mono = np.random.rand() <= self.min_monolingual - - # we continue to add to the composite utterance until we hit the min_duration - while created_sample_duration_sec < self.min_duration: - # we sample from only those languages which haven't already been sampled for this particular - # synthetic utterance, unless pure_random=True, in which case, you just sample with replacement - # every time - if (self.pure_random and not pure_mono) or ( - len(set(created_sample_langs)) == 0 or len(set(created_sample_langs)) == len(self.langs) - ): - lang_id = np.random.choice(self.langs, p=self.lang_probs) - # elif pure_mono: - # use this approach if you want synthetic utterances which are all monolingual - # lang_id = created_sample_langs[0] - else: - # this code is for when we need to sample from only those languages which haven't been sampled - # yet for this utterance - p = np.array(list(map(self.prob_dict.get, list(self.langs_set - set(created_sample_langs))))) - p = p / p.sum() - lang_id = np.random.choice(list(self.langs_set - set(created_sample_langs)), p=p) - - audio, audio_len, labels, labels_len, *_ = self.get_sample_from_language(lang_id) - - # in case you get an audio which is all silence we keep sampling - if audio.count_nonzero().item() == 0: - continue - - sample_duration = len(audio) / self.sample_rate - if (created_sample_duration_sec + sample_duration) > self.max_duration: - continue - - if comp_text.device != labels.device: - comp_text = comp_text.to(labels.device) - - if audio.ndim > 1 and self.force_monochannel: - audio = audio.mean(dim=-1) - - created_sample_duration_sec += sample_duration - created_sample_langs.append(lang_id) - # need to use numpy instead of torch here because we need numpy's trim_zeros function - created_sample_audios.append(audio.cpu().numpy()) - comp_text = torch.cat([comp_text, labels], dim=0) - - # we want a real, non-synth pure_mono sample so we break soon as we have one - if pure_mono: - break - - # check that all samples have the same number of channels - sample_channels = list(set([s.ndim for s in created_sample_audios])) - if len(sample_channels) > 1: - raise RuntimeError( - "Mixture of audios with different number of channels in CodeSwitchedDataset. All sources must be same number of channels." - ) - - multichannel = sample_channels[0] > 1 - - # we start with pause_start amount of silence (zero array) which needs the correct shape for multi/mono channel - if multichannel: - comp_audio = np.zeros( - shape=(int(self.pause_start * self.sample_rate / 1000.0), created_sample_audios[0].shape[-1]), - dtype=created_sample_audios[0].dtype, - ) - else: - comp_audio = np.zeros( - shape=(int(self.pause_start * self.sample_rate / 1000.0),), dtype=created_sample_audios[0].dtype - ) - - # iterate over all mono-lingual samples to build the final composite - for idx, wav in enumerate(created_sample_audios): - if not multichannel: - # this function only works if mono-channel - wav = np.trim_zeros(wav) - - # normalise to provided DB level - wav_norm = wav * (10.0 ** (self.db_norm / 20.0) / np.maximum(0.01, (wav**2).mean(axis=0) ** 0.5)) - - # this part appends the normed waveform to the existing waveform, and inserts pause_join amount of silence - # if necessary, otherwise just a straight append - if idx < len(created_sample_audios) - 1: - if multichannel: - wav_norm = np.append( - wav_norm, - np.zeros( - shape=( - int(self.pause_join * self.sample_rate / 1000.0), - created_sample_audios[0].shape[-1], - ), - dtype=comp_audio.dtype, - ), - axis=0, - ) - else: - wav_norm = np.append( - wav_norm, - np.zeros(shape=(int(self.pause_join * self.sample_rate / 1000.0),), dtype=comp_audio.dtype), - axis=0, - ) - - # this is the penultimate composite wavform, just need to add pause_end silence - comp_audio = np.append(comp_audio, wav_norm, axis=0) - - # here we add the pause_end amount of silence, in correct channel shape - if multichannel: - comp_audio = np.append( - comp_audio, - np.zeros( - shape=(int(self.pause_end * self.sample_rate / 1000.0), created_sample_audios[0].shape[-1]), - dtype=comp_audio.dtype, - ), - axis=0, - ) - else: - comp_audio = np.append( - comp_audio, - np.zeros(shape=(int(self.pause_end * self.sample_rate / 1000.0),), dtype=comp_audio.dtype), - axis=0, - ) - - # we only want augmentation to happen on the final, synthetic utterance, and not on any of the individual - # languages, which is why we set augmentor=None when building the individual language datasets in audio_to_text_dataset.get_code_switched_dataset - # here we now apply augmentation to the final, synthetic utterance only - # all of this logic here happens in-memory, nothing is written to disk - if self.augmentor is not None: - # import here to avoid circular import error - # import here because otherwise CI test-nlp-imports fails since soundfile is only in requirements_asr and not in requirements_common - import soundfile as sf - - from nemo.collections.asr.parts.preprocessing import AudioSegment - - mb = io.BytesIO() - sf.write(mb, comp_audio, self.sample_rate, format='WAV') - mb.seek(0) - comp_audio_as = AudioSegment.from_file(mb, target_sr=self.sample_rate) - self.augmentor.perturb(comp_audio_as) - comp_audio = comp_audio_as.samples - - return ( - torch.tensor(comp_audio, dtype=audio.dtype, device=audio.device), - torch.tensor(len(comp_audio), device=audio_len.device).long(), - comp_text, - torch.tensor(len(comp_text), device=labels_len.device).long(), - ) - - # this is a helper method which prepares all of the iterator objects for all languages - # based on whether that language's underlying dataset is a map or an IterableDataset - def prep_underlying_datasets(self): - worker_info = pt_data.get_worker_info() - if worker_info is None: - max_elements = self.length - wid = 0 - wnum = 1 - else: - wid = worker_info.id - wnum = worker_info.num_workers - max_elements = len(range(wid, self.length, wnum)) - - for lang in self.langs: - if self.lang_kind[lang] == 'map': - start_idx = (len(self.datasets[lang]) // self.world_size) * self.global_rank - end_idx = start_idx + (len(self.datasets[lang]) // self.world_size) - if self.global_rank == self.world_size - 1: - end_idx = len(self.datasets[lang]) - indices = range(start_idx + wid, end_idx, wnum) - self.datasets[lang] = pt_data.Subset(self.datasets[lang], indices) - - self.lang_iterables[lang] = self.get_iterable_by_lang(lang) - - return max_elements - - # returns a sample (audio and transcript) from any underlying language stored by the class on instantiation - # the sample returned is a tensor for the audio and a tensor of ints for the transcript - # this method automatically handles StopIteration errors for the underyling language and rebuilds - # the iterator if necessary - def get_sample_from_language(self, lang): - while True: - try: - val = next(self.lang_iterables[lang]) - if self.lang_kind[lang] == 'map': - val = self.datasets[lang][val] - return val - except StopIteration: - self.lang_iterables[lang] = self.get_iterable_by_lang(lang) - - def __iter__(self): - # we create primed iterators for all languages and return the grand total of samples for each - # underlying language as a sum - max_elements = self.prep_underlying_datasets() - - if self.infinity_mode: - while True: - yield self.build_single_CS_sample() - else: - n = 0 - while n < max_elements: - yield self.build_single_CS_sample() - n += 1 - - def __len__(self): - return self.length diff --git a/nemo/collections/common/data/fallback.py b/nemo/collections/common/data/fallback.py deleted file mode 100644 index 6a0aa9f2921fc760d1460ec562acbda93f9856c9..0000000000000000000000000000000000000000 --- a/nemo/collections/common/data/fallback.py +++ /dev/null @@ -1,51 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import torch - -from nemo.utils import logging - - -class FallbackDataset(torch.utils.data.Dataset): - """ - FallbackDataset is a wrapper on an existing map-style ``torch.utils.data.Dataset``. - It's used to return the previous item (or batch, depending on Dataset) whenever - the underlying ``Dataset`` returns ``None``. - This is useful when ``Dataset`` returns a full batch (as e.g. Lhotse datasets typically do), - and wasn't able to read any of the items in that batch. - - Example:: - - >>> dataset = AudioToTextLhotseDataset(...) - ... dataset = FallbackDataset(dataset) - """ - - def __init__(self, dataset): - self.dataset = dataset - self._fallback = None - - def __getitem__(self, item): - ans = self.dataset[item] - if ans is None: - if self._fallback is None: - logging.warning( - f"FallbackDataset received None from {self.dataset} on the first call to __getitem__, " - f"and must return None instead of an actual batch." - f"This indicates an issue with data reading." - ) - ans = self._fallback - self._fallback = ans - return ans - - def __len__(self): - return len(self.dataset) diff --git a/nemo/collections/common/data/helpers.cpp b/nemo/collections/common/data/helpers.cpp deleted file mode 100644 index 1777e951a2e135432868077821ad43166400321f..0000000000000000000000000000000000000000 --- a/nemo/collections/common/data/helpers.cpp +++ /dev/null @@ -1,728 +0,0 @@ -/* -Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. - -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -/* Helper methods for fast index mapping builds */ - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace py = pybind11; -using namespace std; - -const int32_t LONG_SENTENCE_LEN = 512; - - -void build_blending_indices(py::array_t& dataset_index, - py::array_t& dataset_sample_index, - const py::array_t& weights, - const int32_t num_datasets, - const int64_t size, const bool verbose) { - /* Given multiple datasets and a weighting array, build samples - such that it follows those weights.*/ - - if (verbose) { - std::cout << "> building indices for blendable datasets ..." << std::endl; - } - - // Get the pointer access without the checks. - auto dataset_index_ptr = dataset_index.mutable_unchecked<1>(); - auto dataset_sample_index_ptr = dataset_sample_index.mutable_unchecked<1>(); - auto weights_ptr = weights.unchecked<1>(); - - // Initialize buffer for number of samples used for each dataset. - int64_t current_samples[num_datasets]; - for(int64_t i = 0; i < num_datasets; ++i) { - current_samples[i] = 0; - } - - // For each sample: - for(int64_t sample_idx = 0; sample_idx < size; ++sample_idx) { - - // Determine where the max error in sampling is happening. - auto sample_idx_double = std::max(static_cast(sample_idx), 1.0); - int64_t max_error_index = 0; - double max_error = weights_ptr[0] * sample_idx_double - - static_cast(current_samples[0]); - for (int64_t dataset_idx = 1; dataset_idx < num_datasets; ++dataset_idx) { - double error = weights_ptr[dataset_idx] * sample_idx_double - - static_cast(current_samples[dataset_idx]); - if (error > max_error) { - max_error = error; - max_error_index = dataset_idx; - } - } - - // Populate the indices. - dataset_index_ptr[sample_idx] = static_cast(max_error_index); - dataset_sample_index_ptr[sample_idx] = current_samples[max_error_index]; - - // Update the total samples. - current_samples[max_error_index] += 1; - - } - - // print info - if (verbose) { - std::cout << " > sample ratios:" << std::endl; - for (int64_t dataset_idx = 0; dataset_idx < num_datasets; ++dataset_idx) { - auto ratio = static_cast(current_samples[dataset_idx]) / - static_cast(size); - std::cout << " dataset " << dataset_idx << ", input: " << - weights_ptr[dataset_idx] << ", achieved: " << ratio << std::endl; - } - } - -} - - -py::array build_sample_idx(const py::array_t& sizes_, - const py::array_t& doc_idx_, - const int32_t seq_length, - const int32_t num_epochs, - const int64_t tokens_per_epoch, - const bool drop_last = true, - const int add_extra_token = 1) { - /* Sample index (sample_idx) is used for gpt2 like dataset for which - the documents are flattened and the samples are built based on this - 1-D flatten array. It is a 2D array with sizes [number-of-samples + 1, 2] - where [..., 0] contains the index into `doc_idx` and [..., 1] is the - starting offset in that document.*/ - - // Consistency checks. - assert(seq_length > 1); - assert(num_epochs > 0); - assert(tokens_per_epoch > 1); - - // Remove bound checks. - auto sizes = sizes_.unchecked<1>(); - auto doc_idx = doc_idx_.unchecked<1>(); - - // Mapping and it's length (1D). - int64_t num_samples = 0; - if (drop_last == false) { - num_samples = ceil(float(num_epochs * tokens_per_epoch - add_extra_token) / seq_length); - } else { - num_samples = (num_epochs * tokens_per_epoch - add_extra_token) / seq_length; - } - int32_t* sample_idx = new int32_t[2*(num_samples+1)]; - - cout << " using:" << endl << std::flush; - cout << " number of documents: " << - doc_idx_.shape(0) / num_epochs << endl << std::flush; - cout << " number of epochs: " << num_epochs << - endl << std::flush; - cout << " sequence length: " << seq_length << - endl << std::flush; - cout << " total number of samples: " << num_samples << - endl << std::flush; - - // Index into sample_idx. - int64_t sample_index = 0; - // Index into doc_idx. - int64_t doc_idx_index = 0; - // Begining offset for each document. - int32_t doc_offset = 0; - // Start with first document and no offset. - sample_idx[2 * sample_index] = doc_idx_index; - sample_idx[2 * sample_index + 1] = doc_offset; - ++sample_index; - - while (sample_index <= num_samples) { - // Start with a fresh sequence. - int32_t remaining_seq_length = seq_length + add_extra_token; - while (remaining_seq_length != 0) { - // Get the document length. - auto doc_id = doc_idx[doc_idx_index]; - auto doc_length = sizes[doc_id] - doc_offset; - // And add it to the current sequence. - remaining_seq_length -= doc_length; - // If we have more than a full sequence, adjust offset and set - // remaining length to zero so we return from the while loop. - // Note that -1 here is for the same reason we have -1 in - // `_num_epochs` calculations. - if (remaining_seq_length <= 0) { - doc_offset += (remaining_seq_length + doc_length - add_extra_token); - remaining_seq_length = 0; - } else { - // Otherwise, start from the begining of the next document. - if (doc_idx_index == (doc_idx_.shape(0) - 1)) { - assert(sample_index == num_samples); - doc_offset = sizes[doc_idx[doc_idx_index]] - add_extra_token; - break; - } - ++doc_idx_index; - doc_offset = 0; - } - } - // Record the sequence. - sample_idx[2 * sample_index] = doc_idx_index; - sample_idx[2 * sample_index + 1] = doc_offset; - ++sample_index; - } - - // Method to deallocate memory. - py::capsule free_when_done(sample_idx, [](void *mem_) { - int32_t *mem = reinterpret_cast(mem_); - delete[] mem; - }); - - // Return the numpy array. - const auto byte_size = sizeof(int32_t); - return py::array(std::vector{num_samples+1, 2}, // shape - {2*byte_size, byte_size}, // C-style contiguous strides - sample_idx, // the data pointer - free_when_done); // numpy array references - -} - - -inline int32_t get_target_sample_len(const int32_t short_seq_ratio, - const int32_t max_length, - std::mt19937& rand32_gen) { - /* Training sample length. */ - if (short_seq_ratio == 0) { - return max_length; - } - const auto random_number = rand32_gen(); - if ((random_number % short_seq_ratio) == 0) { - return 2 + random_number % (max_length - 1); - } - return max_length; -} - - -template -py::array build_mapping_impl(const py::array_t& docs_, - const py::array_t& sizes_, - const int32_t num_epochs, - const uint64_t max_num_samples, - const int32_t max_seq_length, - const double short_seq_prob, - const int32_t seed, - const bool verbose, - const int32_t min_num_sent) { - /* Build a mapping of (start-index, end-index, sequence-length) where - start and end index are the indices of the sentences in the sample - and sequence-length is the target sequence length. - */ - - // Consistency checks. - assert(num_epochs > 0); - assert(max_seq_length > 1); - assert(short_seq_prob >= 0.0); - assert(short_seq_prob <= 1.0); - assert(seed > 0); - - // Remove bound checks. - auto docs = docs_.unchecked<1>(); - auto sizes = sizes_.unchecked<1>(); - - // For efficiency, convert probability to ratio. Note: rand() generates int. - int32_t short_seq_ratio = 0; - if (short_seq_prob > 0) { - short_seq_ratio = static_cast(round(1.0 / short_seq_prob)); - } - - if (verbose) { - const auto sent_start_index = docs[0]; - const auto sent_end_index = docs[docs_.shape(0) - 1]; - const auto num_sentences = sent_end_index - sent_start_index; - cout << " using:" << endl << std::flush; - cout << " number of documents: " << docs_.shape(0) - 1 << - endl << std::flush; - cout << " sentences range: [" << sent_start_index << - ", " << sent_end_index << ")" << endl << std::flush; - cout << " total number of sentences: " << num_sentences << - endl << std::flush; - cout << " number of epochs: " << num_epochs << - endl << std::flush; - cout << " maximum number of samples: " << max_num_samples << - endl << std::flush; - cout << " maximum sequence length: " << max_seq_length << - endl << std::flush; - cout << " short sequence probability: " << short_seq_prob << - endl << std::flush; - cout << " short sequence ration (1/prob): " << short_seq_ratio << - endl << std::flush; - cout << " seed: " << seed << endl << - std::flush; - } - - // Mapping and it's length (1D). - int64_t num_samples = -1; - DocIdx* maps = NULL; - - // Perform two iterations, in the first iteration get the size - // and allocate memory and in the second iteration populate the map. - bool second = false; - for (int32_t iteration=0; iteration<2; ++iteration) { - - // Set the seed so both iterations produce the same results. - std::mt19937 rand32_gen(seed); - - // Set the flag on second iteration. - second = (iteration == 1); - - // Counters: - uint64_t empty_docs = 0; - uint64_t one_sent_docs = 0; - uint64_t long_sent_docs = 0; - - // Current map index. - uint64_t map_index = 0; - - // For each epoch: - for (int32_t epoch=0; epoch= max_num_samples) { - if (verbose && (!second)) { - cout << " reached " << max_num_samples << " samples after " - << epoch << " epochs ..." << endl << std::flush; - } - break; - } - // For each document: - for (int32_t doc=0; doc<(docs.shape(0) - 1); ++doc) { - - // Document sentences are in [sent_index_first, sent_index_last) - const auto sent_index_first = docs[doc]; - const auto sent_index_last = docs[doc + 1]; - - // At the begining of the document previous index is the - // start index. - auto prev_start_index = sent_index_first; - - // Remaining documents. - auto num_remain_sent = sent_index_last - sent_index_first; - - // Some bookkeeping - if ((epoch == 0) && (!second)) { - if (num_remain_sent == 0) { - ++empty_docs; - } - if (num_remain_sent == 1) { - ++one_sent_docs; - } - } - - // Detect documents with long sentences. - bool contains_long_sentence = false; - if (num_remain_sent > 1) { - for (auto sent_index=sent_index_first; - sent_index < sent_index_last; ++sent_index) { - if (sizes[sent_index] > LONG_SENTENCE_LEN){ - if ((epoch == 0) && (!second)) { - ++long_sent_docs; - } - contains_long_sentence = true; - break; - } - } - } - - // If we have more than two sentences. - if ((num_remain_sent >= min_num_sent) && (!contains_long_sentence)) { - - // Set values. - auto seq_len = int32_t{0}; - auto num_sent = int32_t{0}; - auto target_seq_len = get_target_sample_len(short_seq_ratio, - max_seq_length, - rand32_gen); - - // Loop through sentences. - for (auto sent_index=sent_index_first; - sent_index < sent_index_last; ++sent_index) { - - // Add the size and number of sentences. - seq_len += sizes[sent_index]; - ++num_sent; - --num_remain_sent; - - // If we have reached the target length. - // and if not only one sentence is left in the document. - // and if we have at least two sentneces. - // and if we have reached end of the document. - if (((seq_len >= target_seq_len) && - (num_remain_sent > 1) && - (num_sent >= min_num_sent) ) || (num_remain_sent == 0)) { - - // Check for overflow. - if ((3 * map_index + 2) > - std::numeric_limits::max()) { - cout << "number of samples exceeded maximum " - << "allowed by type int64: " - << std::numeric_limits::max() - << endl; - throw std::overflow_error("Number of samples"); - } - - // Populate the map. - if (second) { - const auto map_index_0 = 3 * map_index; - maps[map_index_0] = static_cast(prev_start_index); - maps[map_index_0 + 1] = static_cast(sent_index + 1); - maps[map_index_0 + 2] = static_cast(target_seq_len); - } - - // Update indices / counters. - ++map_index; - prev_start_index = sent_index + 1; - target_seq_len = get_target_sample_len(short_seq_ratio, - max_seq_length, - rand32_gen); - seq_len = 0; - num_sent = 0; - } - - } // for (auto sent_index=sent_index_first; ... - } // if (num_remain_sent > 1) { - } // for (int doc=0; doc < num_docs; ++doc) { - } // for (int epoch=0; epoch < num_epochs; ++epoch) { - - if (!second) { - if (verbose) { - cout << " number of empty documents: " << empty_docs << - endl << std::flush; - cout << " number of documents with one sentence: " << - one_sent_docs << endl << std::flush; - cout << " number of documents with long sentences: " << - long_sent_docs << endl << std::flush; - cout << " will create mapping for " << map_index << - " samples" << endl << std::flush; - } - assert(maps == NULL); - assert(num_samples < 0); - maps = new DocIdx[3*map_index]; - num_samples = static_cast(map_index); - } - - } // for (int iteration=0; iteration < 2; ++iteration) { - - // Shuffle. - // We need a 64 bit random number generator as we might have more - // than 2 billion samples. - std::mt19937_64 rand64_gen(seed + 1); - for (auto i=(num_samples - 1); i > 0; --i) { - const auto j = static_cast(rand64_gen() % (i + 1)); - const auto i0 = 3 * i; - const auto j0 = 3 * j; - // Swap values. - swap(maps[i0], maps[j0]); - swap(maps[i0 + 1], maps[j0 + 1]); - swap(maps[i0 + 2], maps[j0 + 2]); - } - - // Method to deallocate memory. - py::capsule free_when_done(maps, [](void *mem_) { - DocIdx *mem = reinterpret_cast(mem_); - delete[] mem; - }); - - // Return the numpy array. - const auto byte_size = sizeof(DocIdx); - return py::array(std::vector{num_samples, 3}, // shape - {3*byte_size, byte_size}, // C-style contiguous strides - maps, // the data pointer - free_when_done); // numpy array references - -} - - -py::array build_mapping(const py::array_t& docs_, - const py::array_t& sizes_, - const int num_epochs, - const uint64_t max_num_samples, - const int max_seq_length, - const double short_seq_prob, - const int seed, - const bool verbose, - const int32_t min_num_sent) { - - if (sizes_.size() > std::numeric_limits::max()) { - if (verbose) { - cout << " using uint64 for data mapping..." << endl << std::flush; - } - return build_mapping_impl(docs_, sizes_, num_epochs, - max_num_samples, max_seq_length, - short_seq_prob, seed, verbose, - min_num_sent); - } else { - if (verbose) { - cout << " using uint32 for data mapping..." << endl << std::flush; - } - return build_mapping_impl(docs_, sizes_, num_epochs, - max_num_samples, max_seq_length, - short_seq_prob, seed, verbose, - min_num_sent); - } -} - -template -py::array build_blocks_mapping_impl(const py::array_t& docs_, - const py::array_t& sizes_, - const py::array_t& titles_sizes_, - const int32_t num_epochs, - const uint64_t max_num_samples, - const int32_t max_seq_length, - const int32_t seed, - const bool verbose, - const bool use_one_sent_blocks) { - /* Build a mapping of (start-index, end-index, sequence-length) where - start and end index are the indices of the sentences in the sample - and sequence-length is the target sequence length. - */ - - // Consistency checks. - assert(num_epochs > 0); - assert(max_seq_length > 1); - assert(seed > 0); - - // Remove bound checks. - auto docs = docs_.unchecked<1>(); - auto sizes = sizes_.unchecked<1>(); - auto titles_sizes = titles_sizes_.unchecked<1>(); - - if (verbose) { - const auto sent_start_index = docs[0]; - const auto sent_end_index = docs[docs_.shape(0) - 1]; - const auto num_sentences = sent_end_index - sent_start_index; - cout << " using:" << endl << std::flush; - cout << " number of documents: " << docs_.shape(0) - 1 << - endl << std::flush; - cout << " sentences range: [" << sent_start_index << - ", " << sent_end_index << ")" << endl << std::flush; - cout << " total number of sentences: " << num_sentences << - endl << std::flush; - cout << " number of epochs: " << num_epochs << - endl << std::flush; - cout << " maximum number of samples: " << max_num_samples << - endl << std::flush; - cout << " maximum sequence length: " << max_seq_length << - endl << std::flush; - cout << " seed: " << seed << endl << - std::flush; - } - - // Mapping and its length (1D). - int64_t num_samples = -1; - DocIdx* maps = NULL; - - // Acceptable number of sentences per block. - int min_num_sent = 2; - if (use_one_sent_blocks) { - min_num_sent = 1; - } - - // Perform two iterations, in the first iteration get the size - // and allocate memory and in the second iteration populate the map. - bool second = false; - for (int32_t iteration=0; iteration<2; ++iteration) { - - // Set the flag on second iteration. - second = (iteration == 1); - - // Current map index. - uint64_t map_index = 0; - - uint64_t empty_docs = 0; - uint64_t one_sent_docs = 0; - uint64_t long_sent_docs = 0; - // For each epoch: - for (int32_t epoch=0; epoch= max_num_samples) { - if (verbose && (!second)) { - cout << " reached " << max_num_samples << " samples after " - << epoch << " epochs ..." << endl << std::flush; - } - break; - } - // For each document: - for (int32_t doc=0; doc<(docs.shape(0) - 1); ++doc) { - - // Document sentences are in [sent_index_first, sent_index_last) - const auto sent_index_first = docs[doc]; - const auto sent_index_last = docs[doc + 1]; - const auto target_seq_len = max_seq_length - titles_sizes[doc]; - - // At the begining of the document previous index is the - // start index. - auto prev_start_index = sent_index_first; - - // Remaining documents. - auto num_remain_sent = sent_index_last - sent_index_first; - - // Some bookkeeping - if ((epoch == 0) && (!second)) { - if (num_remain_sent == 0) { - ++empty_docs; - } - if (num_remain_sent == 1) { - ++one_sent_docs; - } - } - // Detect documents with long sentences. - bool contains_long_sentence = false; - if (num_remain_sent >= min_num_sent) { - for (auto sent_index=sent_index_first; - sent_index < sent_index_last; ++sent_index) { - if (sizes[sent_index] > LONG_SENTENCE_LEN){ - if ((epoch == 0) && (!second)) { - ++long_sent_docs; - } - contains_long_sentence = true; - break; - } - } - } - // If we have enough sentences and no long sentences. - if ((num_remain_sent >= min_num_sent) && (!contains_long_sentence)) { - - // Set values. - auto seq_len = int32_t{0}; - auto num_sent = int32_t{0}; - - // Loop through sentences. - for (auto sent_index=sent_index_first; - sent_index < sent_index_last; ++sent_index) { - - // Add the size and number of sentences. - seq_len += sizes[sent_index]; - ++num_sent; - --num_remain_sent; - - // If we have reached the target length. - // and there are an acceptable number of sentences left - // and if we have at least the minimum number of sentences. - // or if we have reached end of the document. - if (((seq_len >= target_seq_len) && - (num_remain_sent >= min_num_sent) && - (num_sent >= min_num_sent) ) || (num_remain_sent == 0)) { - - // Populate the map. - if (second) { - const auto map_index_0 = 4 * map_index; - // Each sample has 4 items: the starting sentence index, ending sentence index, - // the index of the document from which the block comes (used for fetching titles) - // and the unique id of the block (used for creating block indexes) - - maps[map_index_0] = static_cast(prev_start_index); - maps[map_index_0 + 1] = static_cast(sent_index + 1); - maps[map_index_0 + 2] = static_cast(doc); - maps[map_index_0 + 3] = static_cast(block_id); - } - - // Update indices / counters. - ++map_index; - ++block_id; - prev_start_index = sent_index + 1; - seq_len = 0; - num_sent = 0; - } - } // for (auto sent_index=sent_index_first; ... - } // if (num_remain_sent > 1) { - } // for (int doc=0; doc < num_docs; ++doc) { - } // for (int epoch=0; epoch < num_epochs; ++epoch) { - - if (!second) { - if (verbose) { - cout << " number of empty documents: " << empty_docs << - endl << std::flush; - cout << " number of documents with one sentence: " << - one_sent_docs << endl << std::flush; - cout << " number of documents with long sentences: " << - long_sent_docs << endl << std::flush; - cout << " will create mapping for " << map_index << - " samples" << endl << std::flush; - } - assert(maps == NULL); - assert(num_samples < 0); - maps = new DocIdx[4*map_index]; - num_samples = static_cast(map_index); - } - - } // for (int iteration=0; iteration < 2; ++iteration) { - - // Shuffle. - // We need a 64 bit random number generator as we might have more - // than 2 billion samples. - std::mt19937_64 rand64_gen(seed + 1); - for (auto i=(num_samples - 1); i > 0; --i) { - const auto j = static_cast(rand64_gen() % (i + 1)); - const auto i0 = 4 * i; - const auto j0 = 4 * j; - // Swap values. - swap(maps[i0], maps[j0]); - swap(maps[i0 + 1], maps[j0 + 1]); - swap(maps[i0 + 2], maps[j0 + 2]); - swap(maps[i0 + 3], maps[j0 + 3]); - } - - // Method to deallocate memory. - py::capsule free_when_done(maps, [](void *mem_) { - DocIdx *mem = reinterpret_cast(mem_); - delete[] mem; - }); - - // Return the numpy array. - const auto byte_size = sizeof(DocIdx); - return py::array(std::vector{num_samples, 4}, // shape - {4*byte_size, byte_size}, // C-style contiguous strides - maps, // the data pointer - free_when_done); // numpy array references - -} - -py::array build_blocks_mapping(const py::array_t& docs_, - const py::array_t& sizes_, - const py::array_t& titles_sizes_, - const int num_epochs, - const uint64_t max_num_samples, - const int max_seq_length, - const int seed, - const bool verbose, - const bool use_one_sent_blocks) { - - if (sizes_.size() > std::numeric_limits::max()) { - if (verbose) { - cout << " using uint64 for data mapping..." << endl << std::flush; - } - return build_blocks_mapping_impl(docs_, sizes_, titles_sizes_, - num_epochs, max_num_samples, max_seq_length, seed, verbose, use_one_sent_blocks); - } else { - if (verbose) { - cout << " using uint32 for data mapping..." << endl << std::flush; - } - return build_blocks_mapping_impl(docs_, sizes_, titles_sizes_, - num_epochs, max_num_samples, max_seq_length, seed, verbose, use_one_sent_blocks); - } -} - -PYBIND11_MODULE(helpers, m) { - m.def("build_mapping", &build_mapping); - m.def("build_blocks_mapping", &build_blocks_mapping); - m.def("build_sample_idx", &build_sample_idx); - m.def("build_blending_indices", &build_blending_indices); -} diff --git a/nemo/collections/common/data/lhotse/__init__.py b/nemo/collections/common/data/lhotse/__init__.py deleted file mode 100644 index 64465e88e398946b716508886993ff0e13ebb1d2..0000000000000000000000000000000000000000 --- a/nemo/collections/common/data/lhotse/__init__.py +++ /dev/null @@ -1,31 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import inspect - -from lhotse.dataset.sampling.base import Sampler - -from nemo.collections.common.data.lhotse.cutset import read_cutset_from_config -from nemo.collections.common.data.lhotse.dataloader import ( - LhotseDataLoadingConfig, - get_lhotse_dataloader_from_config, - get_lhotse_sampler_from_config, -) -from nemo.collections.common.data.lhotse.nemo_adapters import LazyNeMoIterator, LazyNeMoTarredIterator -from nemo.collections.common.data.lhotse.text_adapters import ( - NeMoMultimodalConversation, - NeMoSFTExample, - SourceTargetTextExample, - TextExample, -) diff --git a/nemo/collections/common/data/lhotse/cutset.py b/nemo/collections/common/data/lhotse/cutset.py deleted file mode 100644 index d4e7ec482921d37e7965e3a870741c78cb3bca5f..0000000000000000000000000000000000000000 --- a/nemo/collections/common/data/lhotse/cutset.py +++ /dev/null @@ -1,1636 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""Lhotse CutSet utilities and Parquet manifest support for NeMo.""" - -import io -import logging -import random -import re -import warnings -from functools import partial -from itertools import repeat -from pathlib import Path -from typing import KeysView, List, Mapping, Sequence, Tuple, Union - -import numpy as np -import omegaconf -import soundfile as sf -from lhotse import CutSet, Features, MonoCut, Recording, SupervisionSegment -from lhotse.array import Array, TemporalArray -from lhotse.cut import Cut, MixedCut, PaddingCut -from lhotse.lazy import LazyIteratorChain -from lhotse.serialization import load_yaml -from lhotse.utils import fastcopy -from omegaconf import DictConfig, ListConfig, OmegaConf - -from nemo.collections.common.data.lhotse.nemo_adapters import ( - LazyNeMoIterator, - LazyNeMoTarredIterator, - LazyParquetIterator, - expand_sharded_filepaths, -) -from nemo.collections.common.data.lhotse.text_adapters import ( - AudioTurn, - LhotseTextAdapter, - LhotseTextJsonlAdapter, - LhotseTextPairAdapter, - NeMoMultimodalConversation, - NeMoMultimodalConversationJsonlAdapter, - NeMoMultimodalConversationShareGPTJsonlAdapter, - NeMoMultimodalConversationShareGPTWebdatasetAdapter, - NeMoSFTJsonlAdapter, - TextTurn, -) -from nemo.collections.common.parts.preprocessing.manifest import get_full_path - - -def temperature_reweighting(weights: List[Union[float, int]], temperature: float = 1.0) -> List[float]: - """ - Apply temperature scaling to dataset weights and normalize. - - Formula: normalized_weight_i = (w_i ^ temperature) / sum(w_j ^ temperature) - - Args: - weights: List of dataset weights (can be hours, sample counts, or probabilities). - Values can be any positive float/int, not limited to [0, 1]. - temperature: Scaling factor. - - 1.0: preserves original weight ratios - - 0.0: equalizes all weights (w^0 = 1) - - <1.0: oversamples smaller datasets - - >1.0: amplifies weight differences - - Returns: - Normalized weights that sum to 1.0 - - Example: - >>> temperature_reweighting([197, 2159], temperature=1.0) # hours - [0.0836, 0.9164] # preserves ratio - >>> temperature_reweighting([197, 2159], temperature=0.0) # equalize - [0.5, 0.5] - """ - if len(weights) == 0: - return [] - weights = np.asarray(weights) - if np.any(weights <= 0): - raise ValueError(f"All weights must be positive (> 0), got: {weights.tolist()}") - weights = weights**temperature - return (weights / weights.sum()).tolist() - - -def validate_and_standardize_reweight_temperature(config: Union[DictConfig, dict], propagate_attrs: dict) -> None: - """ - Validate and standardize reweight_temperature in propagate_attrs. - - Accepted formats: - - Scalar (int/float): broadcast to all nesting levels (warning logged). - - List: length must exactly match the input_cfg nesting depth. - - Raises: - ValueError: If list length does not match the nesting depth. - """ - if propagate_attrs["reweight_temperature"] is None: - return - - expected_length = count_input_cfg_levels(config) - reweight_temp = propagate_attrs["reweight_temperature"] - - if isinstance(reweight_temp, (int, float)): - propagate_attrs["reweight_temperature"] = [float(reweight_temp)] * expected_length - logging.warning( - f"reweight_temperature is a scalar ({reweight_temp}), broadcasting to all {expected_length} levels. " - f"Expanded to: {propagate_attrs['reweight_temperature']}" - ) - else: - reweight_temp = list(reweight_temp) - if len(reweight_temp) != expected_length: - raise ValueError( - f"reweight_temperature list length ({len(reweight_temp)}) does not match " - f"the input_cfg nesting depth ({expected_length}). " - f"Provide exactly {expected_length} values (one per nesting level), " - f"or use a scalar to apply the same temperature to all levels." - ) - propagate_attrs["reweight_temperature"] = reweight_temp - - -def read_cutset_from_config(config: Union[DictConfig, dict]) -> Tuple[CutSet, bool]: - """ - Reads NeMo configuration and creates a CutSet either from Lhotse or NeMo manifests. - - Returns a tuple of ``CutSet`` and a boolean indicating whether the data is tarred (True) or not (False). - """ - # First, check if the dataset is specified in the new configuration format and use it if possible. - if not isinstance(config, DictConfig): - config = DictConfig(config) - - if config.get("input_cfg") is not None: - cuts, is_tarred = read_dataset_config(config) - else: - # Now, we'll figure out if we should read Lhotse manifest or NeMo manifest. - use_nemo_manifest = all(config.get(opt) is None for opt in ("cuts_path", "shar_path")) - if use_nemo_manifest: - if config.get("manifest_filepath") is None: - raise IncompleteConfigError("You must specify either: manifest_filepath, cuts_path, or shar_path") - cuts, is_tarred = read_nemo_manifest(config) - else: - cuts, is_tarred = read_lhotse_manifest(config) - - return cuts, is_tarred - - -class IncompleteConfigError(RuntimeError): - """Placeholder for an error raised.""" - - pass - - -KNOWN_DATA_CONFIG_TYPES = {} - - -def get_known_config_data_types() -> KeysView[str]: - """ - Return the names of all registered data type parsers. - - Example: - - >>> get_known_config_data_types() - ["nemo", "nemo_tarred", "lhotse", ...] - """ - return KNOWN_DATA_CONFIG_TYPES.keys() - - -def get_parser_fn(data_type_name: str): - """ - Return the parsing function for a given data type name. - Parsing function reads a dataloading config and returns a tuple - of lhotse ``CutSet`` and boolean indicating whether we should use - iterable dataset (True) or map dataset (False) mechanism ("is tarred"). - """ - return KNOWN_DATA_CONFIG_TYPES[data_type_name] - - -def data_type_parser(name: Union[str, list[str]]): - """ - Decorator used to register data type parser functions. - Parsing function reads a dataloading config and returns a tuple - of lhotse ``CutSet`` and boolean indicating whether we should use - iterable dataset (True) or map dataset (False) mechanism ("is tarred"). - - Example: - - >>> @data_type_parser("my_new_format") - ... def my_new_format(config): - ... return CutSet(read_my_format(**config)), True - ... - ... fn = get_parser_fn("my_new_format") - ... cuts, is_tarred = fn({"my_arg_0": ..., "my_arg_1": ..., ...}) - """ - - def _decorator(fn): - global KNOWN_DATA_CONFIG_TYPES - if isinstance(name, str): - KNOWN_DATA_CONFIG_TYPES[name] = fn - else: - for n in name: - KNOWN_DATA_CONFIG_TYPES[n] = fn - return fn - - return _decorator - - -def read_dataset_config(config) -> tuple[CutSet, bool]: - """ - Input configuration format examples. - Example 1. Combine two datasets with equal weights and attach custom metadata in ``tags`` to each cut:: - input_cfg: - - type: nemo_tarred - manifest_filepath: /path/to/manifest__OP_0..512_CL_.json - tarred_audio_filepath: /path/to/tarred_audio/audio__OP_0..512_CL_.tar - weight: 0.5 - tags: - lang: en - some_metadata: some_value - - type: nemo_tarred - manifest_filepath: /path/to/manifest__OP_0..512_CL_.json - tarred_audio_filepath: /path/to/tarred_audio/audio__OP_0..512_CL_.tar - weight: 0.5 - tags: - lang: pl - some_metadata: some_value - Example 2. Combine multiple (4) datasets, with 2 corresponding to different tasks (ASR, AST). - There are two levels of weights: per task (outer) and per dataset (inner). - The final weight is the product of outer and inner weight:: - input_cfg: - - type: group - weight: 0.7 - tags: - task: asr - input_cfg: - - type: nemo_tarred - manifest_filepath: /path/to/asr1/manifest__OP_0..512_CL_.json - tarred_audio_filepath: /path/to/tarred_audio/asr1/audio__OP_0..512_CL_.tar - weight: 0.6 - tags: - lang: en - some_metadata: some_value - - type: nemo_tarred - manifest_filepath: /path/to/asr2/manifest__OP_0..512_CL_.json - tarred_audio_filepath: /path/to/asr2/tarred_audio/audio__OP_0..512_CL_.tar - weight: 0.4 - tags: - lang: pl - some_metadata: some_value - - type: group - weight: 0.3 - tags: - task: ast - input_cfg: - - type: nemo_tarred - manifest_filepath: /path/to/ast1/manifest__OP_0..512_CL_.json - tarred_audio_filepath: /path/to/ast1/tarred_audio/audio__OP_0..512_CL_.tar - weight: 0.2 - tags: - src_lang: en - tgt_lang: pl - - type: nemo_tarred - manifest_filepath: /path/to/ast2/manifest__OP_0..512_CL_.json - tarred_audio_filepath: /path/to/ast2/tarred_audio/audio__OP_0..512_CL_.tar - weight: 0.8 - tags: - src_lang: pl - tgt_lang: en - """ - propagate_attrs = { - "shuffle": config.get("shuffle", False), - "shard_seed": config.get("shard_seed", "trng"), - "text_field": config.get("text_field", "text"), - "lang_field": config.get("lang_field", "lang"), - "metadata_only": config.get("metadata_only", False), - "force_finite": config.get("force_finite", False), - "max_open_streams": config.get("max_open_streams", None), - "audio_locator_tag": config.get("audio_locator_tag", None), - "token_equivalent_duration": config.get("token_equivalent_duration", None), - "skip_missing_manifest_entries": config.get("skip_missing_manifest_entries", False), - "force_map_dataset": config.get("force_map_dataset", False), - "force_iterable_dataset": config.get("force_iterable_dataset", False), - "slice_length": config.get("slice_length", None), - # Temperature for re-weighting datasets. 1 is a neutral value. Lower temperature over-samples smaller datasets, and vice versa. - "reweight_temperature": config.get("reweight_temperature", None), - } - - validate_and_standardize_reweight_temperature(config, propagate_attrs) - - cuts, is_tarred = parse_and_combine_datasets(config.input_cfg, propagate_attrs=propagate_attrs) - return cuts, is_tarred - - -def parse_group(grp_cfg: DictConfig, propagate_attrs: dict) -> [CutSet, bool]: - """Parse a group configuration, potentially combining multiple datasets.""" - assert grp_cfg.type in get_known_config_data_types(), f"Unknown item type in dataset config list: {grp_cfg.type=}" - - # Note: Text data types will return is_tarred=True. - # We choose to treat text as-if it was tarred, which tends to be more - # efficient as it moves the text file iteration into dataloading subprocess. - if grp_cfg.type != "group": - parser_fn = get_parser_fn(grp_cfg.type) - cuts, is_tarred = parser_fn(grp_cfg) - else: - cuts, is_tarred = parse_and_combine_datasets( - grp_cfg.input_cfg, - propagate_attrs=propagate_attrs, - ) - # Attach extra tags to every utterance dynamically, if provided. - if (extra_tags := grp_cfg.get("tags")) is not None: - cuts = cuts.map(partial(attach_tags, tags=extra_tags), apply_fn=None) - return cuts, is_tarred - - -@data_type_parser("txt") -def read_txt_paths(config: DictConfig) -> tuple[CutSet, bool]: - """ - Read paths to text files and create a CutSet. - """ - cuts = CutSet( - LhotseTextAdapter( - paths=config.paths, - language=config.language, - shuffle_shards=config.shuffle, - shard_seed=config.shard_seed, - ) - ) - if not config.get("force_finite", False): - cuts = cuts.repeat(preserve_id=True) - return cuts, True - - -@data_type_parser("txt_jsonl") -def read_txt_jsonl_paths(config: DictConfig) -> tuple[CutSet, bool]: - """Read paths to text files in JSONL format and create a CutSet. - - This parser reads JSONL files where each line contains a JSON object with text fields. - The text_field parameter specifies which field in the JSON object contains the text to be used. - """ - cuts = CutSet( - LhotseTextJsonlAdapter( - paths=config.paths, - language=config.language, - text_field=config.text_field, - shuffle_shards=config.shuffle, - shard_seed=config.shard_seed, - ) - ) - if not config.get("force_finite", False): - cuts = cuts.repeat(preserve_id=True) - return cuts, True - - -@data_type_parser("txt_pair") -def read_txt_pair_paths(config: DictConfig) -> tuple[CutSet, bool]: - """Read paths to source and target text files and create a CutSet.""" - cuts = CutSet( - LhotseTextPairAdapter( - source_paths=config.source_paths, - target_paths=config.target_paths, - source_language=config.get("source_language"), - target_language=config.get("target_language"), - questions_path=config.get("questions_path"), - questions_language=config.get("questions_language"), - shuffle_shards=config.shuffle, - shard_seed=config.shard_seed, - ) - ) - if not config.get("force_finite", False): - cuts = cuts.repeat(preserve_id=True) - return cuts, True - - -@data_type_parser("nemo_sft_jsonl") -def read_nemo_sft_jsonl(config: DictConfig) -> tuple[CutSet, bool]: - """Read paths to Nemo SFT JSONL files and create a CutSet.""" - cuts = CutSet( - NeMoSFTJsonlAdapter( - paths=config.paths, - language=config.get("language"), - shuffle_shards=config.shuffle, - shard_seed=config.shard_seed, - ) - ) - if not config.get("force_finite", False): - cuts = cuts.repeat(preserve_id=True) - return cuts, True - - -@data_type_parser("multimodal_conversation") -def read_multimodal_conversation_jsonl(config: DictConfig) -> tuple[CutSet, bool]: - """Read paths to multimodal conversation JSONL files and create a CutSet.""" - cuts = CutSet( - NeMoMultimodalConversationJsonlAdapter( - manifest_filepath=config.manifest_filepath, - tarred_audio_filepaths=config.get("tarred_audio_filepaths"), - audio_locator_tag=config.audio_locator_tag, - token_equivalent_duration=config.get("token_equivalent_duration"), - shuffle_shards=config.shuffle, - shard_seed=config.shard_seed, - system_prompt=config.get("tags", {}).get("system_prompt"), - context=config.get("tags", {}).get("context"), - slice_length=config.get("slice_length"), - ) - ) - if not config.get("force_finite", False): - cuts = cuts.repeat() - return cuts, True - - -@data_type_parser(["share_gpt"]) -def read_share_gpt_as_conversation(config) -> tuple[CutSet, bool]: - """Read paths to ShareGPT JSONL files and create a CutSet of NeMoMultimodalConversation.""" - cuts = CutSet( - NeMoMultimodalConversationShareGPTJsonlAdapter( - manifest_filepath=config.manifest_filepath, - tarred_audio_filepaths=config.get("tarred_audio_filepaths"), - audio_locator_tag=config.audio_locator_tag, - audio_placeholders=config.audio_placeholders, - audio_root=config.get("audio_root"), - token_equivalent_duration=config.get("token_equivalent_duration"), - shuffle_shards=config.shuffle, - shard_seed=config.shard_seed, - slice_length=config.get("slice_length"), - ) - ) - if not config.get("force_finite", False): - cuts = cuts.repeat(preserve_id=True) - return cuts, True - - -@data_type_parser(["share_gpt_webdataset"]) -def read_share_gpt_webdataset_as_conversation(config) -> tuple[CutSet, bool]: - """Read ShareGPT conversations from WebDataset tar archives.""" - cuts = CutSet( - NeMoMultimodalConversationShareGPTWebdatasetAdapter( - data_dir=config.data_dir, - audio_locator_tag=config.audio_locator_tag, - audio_placeholders=config.get("audio_placeholders"), - token_equivalent_duration=config.get("token_equivalent_duration"), - shuffle_shards=config.shuffle, - shard_seed=config.shard_seed, - ) - ) - # When force_finite is False (default), repeat the dataset infinitely so that - # the dataloader never runs out of data; the trainer controls epoch boundaries. - if not config.get("force_finite", False): - cuts = cuts.repeat(preserve_id=True) - return cuts, True - - -def _resolve_shar_inputs(path: Union[str, Path], only_metadata: bool) -> dict: - if only_metadata: - return dict(fields={"cuts": sorted(Path(path).glob("cuts.*"))}) - else: - return dict(in_dir=path) - - -def attach_tags(cut, tags: dict): - """Attach extra tags to a cut dynamically.""" - for key, val in tags.items(): - setattr(cut, key, val) - return cut - - -def count_input_cfg_levels(config: Union[DictConfig, dict]) -> int: - """ - Compute the maximum nesting depth of 'input_cfg' keys in the configuration. - - Each 'input_cfg' represents one level of nesting that consumes one temperature - value from reweight_temperature. Since sibling groups at the same level share - the same temperature (due to propagate_attrs.copy()), we count max depth, - not total occurrences. - - Args: - config: Configuration dictionary that may contain nested 'input_cfg' keys. - - Returns: - Maximum nesting depth of 'input_cfg' keys. - - Example: - >>> config = { - ... "input_cfg": [ - ... {"type": "group", "input_cfg": [{"type": "nemo"}]}, - ... {"type": "group", "input_cfg": [{"type": "nemo"}]}, - ... ] - ... } - >>> count_input_cfg_levels(config) - 2 - """ - - def _max_depth(obj) -> int: - if isinstance(obj, (dict, DictConfig)): - depths = [] - for key, val in obj.items(): - if key == "input_cfg": - # Found input_cfg: this level counts as 1 + max depth of children - depths.append(1 + _max_depth(val)) - else: - depths.append(_max_depth(val)) - return max(depths, default=0) - elif isinstance(obj, (list, ListConfig)): - # For lists, find the max depth across all items (siblings) - return max((_max_depth(item) for item in obj), default=0) - return 0 - - return _max_depth(config) - - -@data_type_parser("group") -def parse_and_combine_datasets( - config_list: Union[list[DictConfig], ListConfig, str, Path], propagate_attrs: dict -) -> tuple[CutSet, bool]: - """Parse a list of dataset configurations, potentially combining multiple datasets.""" - cuts = [] - weights = [] - tarred_status = [] - - # Extract the temperature for re-weighting datasets. - if not propagate_attrs["reweight_temperature"]: - temperature = 1.0 - next_temperatures = None - else: - temperature, *next_temperatures = propagate_attrs["reweight_temperature"] - propagate_attrs["reweight_temperature"] = next_temperatures - - if isinstance(config_list, (str, Path)): - # Resolve local filepath /path/to/input_cfg.yaml or - # remote url s3://bucket/path/to/input_cfg.yaml into config contents if needed. - config_list = OmegaConf.create(load_yaml(config_list)) - assert len(config_list) > 0, "Empty group in dataset config list." - - for item in config_list: - # Check if we have any attributes that are propagated downwards to each item in the group. - # If a key already exists in the item, it takes precedence (we will not overwrite); - # otherwise we will assign it. - # We also update propagate_atts for the next sub-groups based on what's present in this group - next_propagate_attrs = propagate_attrs.copy() - for k, v in propagate_attrs.items(): - if k not in item: - item[k] = v - else: - next_propagate_attrs[k] = item[k] - - # Load the item (which may also be another group) as a CutSet. - item_cuts, item_is_tarred = parse_group(item, next_propagate_attrs) - cuts.append(item_cuts) - tarred_status.append(item_is_tarred) - if (w := item.get("weight")) is not None: - weights.append(w) - - all_same_tarred_status = all(t == tarred_status[0] for t in tarred_status) - if not all_same_tarred_status: - if propagate_attrs["force_map_dataset"] or propagate_attrs["force_iterable_dataset"]: - logging.warning( - f"Not all datasets in the group have the same tarred status, using provided force_map_dataset " - f"({propagate_attrs['force_map_dataset']}) and force_iterable_dataset " - f"({propagate_attrs['force_iterable_dataset']}) to determine the final tarred status." - ) - else: - raise ValueError( - "Mixing tarred and non-tarred datasets is not supported when neither force_map_dataset " - "nor force_iterable_dataset is True." - ) - - assert len(weights) == 0 or len(cuts) == len( - weights - ), "Missing dataset weight. When weighting datasets, every dataset must have a specified weight." - - if len(cuts) > 1: - if not weights: - reweights = None - else: - reweights = temperature_reweighting(weights, temperature=temperature) - - cuts = mux( - *cuts, - weights=reweights, - max_open_streams=propagate_attrs["max_open_streams"], - seed=propagate_attrs["shard_seed"], - force_finite=propagate_attrs["force_finite"] or propagate_attrs["metadata_only"], - ) - else: - (cuts,) = cuts - return cuts, tarred_status[0] - - -@data_type_parser(["lhotse", "lhotse_shar"]) -def read_lhotse_manifest(config) -> tuple[CutSet, bool]: - """Read paths to Lhotse manifest files and create a CutSet.""" - is_tarred = config.get("shar_path") is not None - if is_tarred: - # Lhotse Shar is the equivalent of NeMo's native "tarred" dataset. - # The combination of shuffle_shards, and repeat causes this to - # be an infinite manifest that is internally reshuffled on each epoch. - # The parameter ``config.shard_seed`` is used to determine shard shuffling order. Options: - # - "trng" means we'll defer setting the seed until the iteration - # is triggered, and we'll use system TRNG to get a completely random seed for each worker. - # This results in every dataloading worker using full data but in a completely different order. - # - "randomized" means we'll defer setting the seed until the iteration - # is triggered, and we'll use config.seed to get a pseudo-random seed for each worker. - # This results in every dataloading worker using full data but in a completely different order. - # Unlike "trng", this is deterministic, and if you resume training, you should change the seed - # to observe different data examples than in the previous run. - # - integer means we'll set a specific seed in every worker, and data would be duplicated across them. - # This is mostly useful for unit testing or debugging. - shard_seed = config.get("shard_seed", "trng") - metadata_only = config.get("metadata_only", False) - force_finite = config.get("force_finite", False) - if config.get("cuts_path") is not None: - warnings.warn("Note: lhotse.cuts_path will be ignored because lhotse.shar_path was provided.") - if isinstance(config.shar_path, (str, Path)): - cuts = CutSet.from_shar( - **_resolve_shar_inputs(config.shar_path, metadata_only), - shuffle_shards=True, - seed=shard_seed, - slice_length=config.get("slice_length", None), - ) - if not metadata_only and not force_finite: - cuts = cuts.repeat(preserve_id=True) - elif isinstance(config.shar_path, Sequence): - # Multiple datasets in Lhotse Shar format: we will dynamically multiplex them - # with probability approximately proportional to their size - cutsets = [] - weights = [] - for item in config.shar_path: - if isinstance(item, (str, Path)): - path = item - cs = CutSet.from_shar( - **_resolve_shar_inputs(path, metadata_only), - shuffle_shards=True, - seed=shard_seed, - slice_length=config.get("slice_length", None), - ) - weight = len(cs) - else: - assert isinstance(item, Sequence) and len(item) == 2 and isinstance(item[1], (int, float)), ( - "Supported inputs types for config.shar_path are: " - "str | list[str] | list[tuple[str, number]] " - "where str is a path and number is a mixing weight (it may exceed 1.0). " - f"We got: '{item}'" - ) - path, weight = item - cs = CutSet.from_shar( - **_resolve_shar_inputs(path, metadata_only), - shuffle_shards=True, - seed=shard_seed, - slice_length=config.get("slice_length", None), - ) - cutsets.append(cs) - weights.append(weight) - - cuts = mux( - *cutsets, - weights=weights, - max_open_streams=config.get("max_open_streams", None), - seed=shard_seed, - force_finite=force_finite, - ) - elif isinstance(config.shar_path, Mapping): - fields = {k: expand_sharded_filepaths(v) for k, v in config.shar_path.items()} - assert "cuts" in config.shar_path.keys(), ( - f"Invalid value for key 'shar_path': a dict was provided, but didn't specify key 'cuts' pointing " - f"to the manifests. We got the following: {config.shar_path=}" - ) - if metadata_only: - fields = {"cuts": fields["cuts"]} - cuts = CutSet.from_shar( - fields=fields, - shuffle_shards=True, - seed=shard_seed, - slice_length=config.get("slice_length", None), - ) - if not metadata_only and not force_finite: - cuts = cuts.repeat(preserve_id=True) - else: - raise RuntimeError( - f"Unexpected value for key 'shar_path'. We support string, list of strings, " - f"list of tuples[string,float], and dict[string,list[string]], " - f"but got: {type(config.shar_path)=} {config.shar_path=}" - ) - else: - # Regular Lhotse manifest points to individual audio files (like native NeMo manifest). - path = config.cuts_path - cuts = CutSet.from_file(path).map(partial(resolve_relative_paths, manifest_path=path)) - return cuts, is_tarred - - -@data_type_parser(["parquet"]) -def read_parquet_manifest(config: DictConfig) -> tuple[CutSet, bool]: - """ - Read paths to Parquet files and create a CutSet. - - Config options: - - manifest_filepath: path to .parquet file (or list of paths) - - audio_field: column name for audio (default: "audio") - - text_field: column name for text (default: "text") - - duration_field: column name for duration (default: "duration") - - lang_field: column name for language (default: "lang") - - sampling_rate: default sampling rate if not present (default: 16000) - - shuffle: whether to shuffle shards (default: False) - - shard_seed: seed for shuffling (default: "trng") - """ - # 1. Get the path(s) - paths = config.manifest_filepath - if isinstance(paths, str): - paths = [paths] - - # 2. Extract config options with defaults - audio_field = config.get("audio_field", "audio") - text_field = config.get("text_field", "text") - duration_field = config.get("duration_field", "duration") - lang_field = config.get("lang_field", "lang") - sampling_rate = config.get("sampling_rate", 16000) - - # Extract shuffling options (CRITICAL for distributed training) - shuffle_shards = config.get("shuffle", False) - shard_seed = config.get("shard_seed", "trng") - - # 3. Create Iterators for each file - iterators = [] - for path in paths: - logging.info(f"Initializing Lhotse Parquet Iterator: '{path}'") - adapter = LazyParquetIterator( - path=path, - audio_field=audio_field, - text_field=text_field, - duration_field=duration_field, - lang_field=lang_field, - sampling_rate=sampling_rate, - ) - iterators.append(adapter) - - # 4. Chain them together using Lhotse's lazy chaining - if len(iterators) == 1: - source = iterators[0] - else: - # This handles shuffling the order of .parquet files for multi-GPU training - # as requested by pzelasko - source = LazyIteratorChain(*iterators, shuffle_iters=shuffle_shards, seed=shard_seed) - - # 5. Create the final CutSet - cuts = CutSet(source) - - # 6. Handle infinite looping if requested - if not config.get("force_finite", False): - cuts = cuts.repeat(preserve_id=True) - - # Return cuts + is_tarred=True (since it's a stream, we treat it like tarred) - return cuts, True - - -def cut_to_conversation( - cut: Cut, audio_locator_tag: str, token_equivalent_duration: float -) -> NeMoMultimodalConversation: - """ - Converts a lhotse Cut into a two-turn NeMoMultimodalConversation, where the user turn contains cut's audio, - and assistant turn contains text response from ``cut.supervisions[0].text``. - - If ``cut`` has a custom field ``context``, it's pre-pended as an extra user text turn before the user's audio turn. - """ - if isinstance(cut, NeMoMultimodalConversation): - return cut - turns = [ - AudioTurn(cut=cut, role="user", audio_locator_tag=audio_locator_tag, text=cut.supervisions[0].text), - TextTurn(value=cut.supervisions[0].text, role="assistant"), - ] - if hasattr(cut, "context"): - turns = [TextTurn(value=cut.context, role="user")] + turns - if hasattr(cut, "system_prompt"): - turns = [TextTurn(value=cut.system_prompt, role="system")] + turns - return NeMoMultimodalConversation( - id=cut.id, - turns=turns, - token_equivalent_duration=token_equivalent_duration, - custom=cut.custom, - ) - - -@data_type_parser(["s2s_duplex_overlap_as_s2s_duplex"]) -def read_s2s_duplex_overlap_as_s2s_duplex(config) -> Tuple[CutSet, bool]: - """ - Convert a CutSet with overlapping agent/user segments into a standard S2S duplex format. - - Use Case: - This parser is designed for conversational data where agent and user speech can overlap - in time (e.g., natural turn-taking with interruptions or backchanneling). The input - format stores agent and user segments separately as `agent_segments` and `user_segments` - attributes on each cut. This function converts them into a unified timeline of sequential - SupervisionSegments, which is the standard format expected by DuplexS2S models. - - Expected Input Data Format: - Each cut should have: - - cut.agent_segments: List[Dict] with keys: - - "start" (float): Start time in seconds - - "end" (float): End time in seconds - - "text" (str): Agent's transcription - - cut.user_segments: List[Dict] with keys: - - "start" (float): Start time in seconds - - "end" (float): End time in seconds - - "text" (str): User's transcription - - Example: - Input cut with overlapping segments: - cut.agent_segments = [ - {"start": 0.5, "end": 2.0, "text": "Hello, how can I help?"}, - {"start": 3.0, "end": 4.5, "text": "Sure, I can do that."} - ] - cut.user_segments = [ - {"start": 1.8, "end": 3.2, "text": "I need assistance"}, - {"start": 4.0, "end": 5.5, "text": "Thank you"} - ] - - Output cut.supervisions (sorted by start time): - [ - SupervisionSegment(start=0.5, duration=1.5, text="Hello, how can I help?", speaker="agent"), - SupervisionSegment(start=1.8, duration=1.4, text="I need assistance", speaker="user"), - SupervisionSegment(start=3.0, duration=1.5, text="Sure, I can do that.", speaker="agent"), - SupervisionSegment(start=4.0, duration=1.5, "Thank you", speaker="user") - ] - - Args: - config: Dictionary containing parser options: - - move_agent_text_back_by (float): Time offset to shift agent text back (default: 0). - Useful for aligning agent text with earlier audio timing. - - filter_samples_starting_with_agent (bool): Whether to remove samples starting with agent (default: False). - When True, only keeps samples where the first speaker is a user. - - agent_roles (List[str]): Roles considered as agent (default: ["agent", "Assistant", "assistant"]). - - Returns: - Tuple[CutSet, bool]: Converted cuts with unified supervisions, and a flag indicating if the data was tarred. - """ - move_agent_text_back_by = config.get("move_agent_text_back_by", 0) - filter_samples_starting_with_agent = config.get("filter_samples_starting_with_agent", False) - agent_roles = config.get("agent_roles", ["agent", "Assistant", "assistant"]) - - cuts, is_tarred = read_cutset_from_config(config) - - def filter_cuts_starting_with_agent_fn(cuts: CutSet, agent_roles: Tuple[str, ...]) -> CutSet: - """Remove cuts where the first supervision belongs to an agent role.""" - - def _filter_fn(cut: Cut) -> bool: - if not cut.supervisions: - return False - cut.supervisions = sorted(cut.supervisions, key=lambda s: s.start) - return cut.supervisions[0].speaker not in agent_roles - - return cuts.filter(_filter_fn) - - def convert_overlap_cut_fn(cut: Cut) -> Cut: - """Convert agent/user overlapping segments into sequential SupervisionSegments.""" - agent_segments = [ - SupervisionSegment( - id=cut.id, - recording_id=cut.id, - start=seg["start"] - move_agent_text_back_by, - duration=seg["end"] - seg["start"] + move_agent_text_back_by, - text=seg["text"], - speaker="agent", - ) - for seg in cut.agent_segments - ] - - user_segments = [ - SupervisionSegment( - id=cut.id, - recording_id=cut.id, - start=seg["start"], - duration=seg["end"] - seg["start"], - text=seg["text"], - speaker="user", - ) - for seg in cut.user_segments - ] - - cut.supervisions = sorted(agent_segments + user_segments, key=lambda s: s.start) - cut.task = "s2s_duplex_overlap_as_s2s_duplex" - return cut - - cuts = cuts.map(convert_overlap_cut_fn) - if filter_samples_starting_with_agent: - cuts = filter_cuts_starting_with_agent_fn(cuts, tuple(agent_roles)) - - return cuts, is_tarred - - -@data_type_parser(["lhotse_magpietts_data_as_continuation"]) -def read_lhotse_magpietts_data_as_s2s_duplex(config) -> Tuple[CutSet, bool]: - """ - Convert MagpieTTS dataset cuts into the Duplex S2S format, with optional - `context_audio` that can be used as a speaker reference. - - Args: - config: Dictionary containing parser options: - - add_extra_end_silence (bool): Whether to add extra silence at the end. - - extra_end_silence_range (List[float]): Range of extra silence duration. - - max_cer (float): Maximum allowed character error rate. - - min_context_speaker_similarity (float): Minimum similarity score. - - target_speaker (str, optional): Target speaker filter. - - sample_rate (int): Audio sample rate for resampling. - - Returns: - Tuple[CutSet, bool]: Converted cuts and a flag indicating if data was tarred. - """ - cuts, is_tarred = read_cutset_from_config(config) - - add_extra_end_sil = config.get("add_extra_end_silence", False) - extra_end_silence_range = config.get("extra_end_silence_range", [0.5, 6.0]) - sample_rate = config.get("sample_rate", 22050) - - max_cer = config.get("max_cer", 0.03) - min_context_speaker_similarity = config.get("min_context_speaker_similarity", 0.6) - target_speaker = config.get("target_speaker", None) - keep_flag = "pass" - - def create_recording_from_array(samples: np.ndarray, sampling_rate: int, recording_id: str) -> Recording: - """Convert a numpy array into a Lhotse Recording object.""" - with io.BytesIO() as buffer: - sf.write(buffer, samples.T, samplerate=sampling_rate, format='WAV') - buffer.seek(0) - return Recording.from_bytes(buffer.read(), recording_id=recording_id) - - def convert_cut_fn(cut: Cut) -> Cut: - """Convert a single cut into the continuation format.""" - orig_agent_sup = fastcopy(cut.supervisions[0]) - target_audio_orig_dur = cut.target_audio.duration - - # Resample audios - cut.target_audio = cut.target_audio.resample(sample_rate) - cut.context_audio = cut.context_audio.resample(sample_rate) - total_duration = cut.target_audio.duration - - # Prepare MonoCuts - cut_target = MonoCut( - id=f"{cut.id}_target", - start=0.0, - duration=total_duration, - channel=0, - recording=cut.target_audio, - supervisions=[], - ) - - zero_audio = np.zeros((1, int(total_duration * sample_rate)), dtype=np.float32) - source_recording = create_recording_from_array(zero_audio, sample_rate, recording_id=f"{cut.id}_source") - - cut_source = MonoCut( - id=f"{cut.id}_source", - start=0.0, - duration=total_duration, - channel=0, - recording=source_recording, - supervisions=[], - ) - - # Save to memory - cut_source = cut_source.move_to_memory(audio_format='wav') - cut_target = cut_target.move_to_memory(audio_format='wav') - - # Create user and agent supervisions - user_sup = fastcopy(orig_agent_sup, start=0.0, duration=0.08, speaker="user", text="dummy text") - agent_sup = fastcopy(orig_agent_sup, start=0.0, duration=target_audio_orig_dur - 0.08, speaker="agent") - - # Optionally add extra silence - if add_extra_end_sil: - sil_duration = random.uniform(*extra_end_silence_range) - cut_target = cut_target.pad(duration=total_duration + sil_duration, direction="right") - cut_source = cut_source.pad(duration=total_duration + sil_duration, direction="right") - cut_source = cut_source.to_mono().move_to_memory(audio_format='wav') - cut_target = cut_target.to_mono().move_to_memory(audio_format='wav') - agent_sup.duration += sil_duration + 1.0 - user_sup.duration += sil_duration - - # Assemble final cut - cut_source.supervisions = [user_sup, agent_sup] - cut_source.target_audio = cut_target.recording - cut_source.duration = cut_target.duration - cut_source.context_audio = cut.context_audio - cut_source.task = "lhotse_magpietts_data_as_continuation" - - return cut_source - - # Filters - def filter_cer_fn(cut: Cut) -> bool: - return ( - len(cut.supervisions) == 0 - or not cut.supervisions[0].has_custom("cer") - or cut.supervisions[0].cer <= max_cer - ) - - def filter_val_flag_fn(cut: Cut) -> bool: - return not cut.has_custom("validation_status") or cut.validation_status == keep_flag - - def filter_secs_fn(cut: Cut) -> bool: - return ( - len(cut.supervisions) == 0 - or not cut.supervisions[0].has_custom("context_speaker_similarity") - or cut.supervisions[0].context_speaker_similarity >= min_context_speaker_similarity - ) - - def filter_target_speaker_fn(cut: Cut) -> bool: - return len(cut.supervisions) == 0 or target_speaker is None or target_speaker in cut.supervisions[0].speaker - - # Apply filters - cuts = ( - cuts.filter(filter_cer_fn).filter(filter_val_flag_fn).filter(filter_secs_fn).filter(filter_target_speaker_fn) - ) - - # Convert cuts - cuts = cuts.map(convert_cut_fn) - - return cuts, is_tarred - - -@data_type_parser(["lhotse_as_conversation"]) -def read_lhotse_as_conversation(config) -> tuple[CutSet, bool]: - """ - Conversion parser for regular ASR data. - Intended for converting ASR data in NeMo or Lhotse manifests from Lhotse Cut into NeMoMultimodalConversation. - The examples for multimodal LLM are constructed to present an optional "context" field and the acoustic representation as input, - and predict "text". - - Example of original data JSON in NeMo manifest format:: - - { - "audio_filepath": "/path/to/audio.wav", - "duration": 3.48, - "text": "Of exclusive national competence, let me assure you". - "lang": "en", - "context": "Transcribe the following:", - } - - Same example in Lhotse manifest format:: - - { - "id": "some-id-0", - "recording": { - "id": "some-id-0", - "sources": [ - "type": "path", - "source": "/path/to/audio.wav", - "channel_ids": [0], - ], - "sampling_rate": 16000, - "duration": 3.48, - "num_samples": 55680, - }, - "supervisions": [ - "id": "some-id-0", - "start": 0.0, - "duration": 3.48, - "channel": 0, - "text": "Of exclusive national competence, let me assure you". - "language": "en", - ], - "start": 0.0, - "duration": 3.48, - "channel": 0, - "custom": { - "context": "Transcribe the following:", - } - } - """ - cuts, is_tarred = read_cutset_from_config(config) - # Attach extra tags to every utterance dynamically, if provided. - # We need to attach them before cuts are converted to conversations. - if (extra_tags := config.get("tags")) is not None: - cuts = cuts.map(partial(attach_tags, tags=extra_tags), apply_fn=None) - cuts = cuts.map( - partial( - cut_to_conversation, - audio_locator_tag=config.audio_locator_tag, - token_equivalent_duration=config.token_equivalent_duration, - ) - ) - return cuts, is_tarred - - -def sqa_cut_to_conversation( - cut: Cut, audio_locator_tag: str, token_equivalent_duration: float -) -> NeMoMultimodalConversation: - """ - Converts a lhotse Cut representing a SQA example into a NeMoMultimodalConversation. - - The ``cut`` is expected to have ``question`` and ``answer`` fields. - """ - if isinstance(cut, NeMoMultimodalConversation): - return cut - turns = [ - TextTurn(value=cut.question, role="user"), - AudioTurn(cut=cut, role="user", audio_locator_tag=audio_locator_tag, text=getattr(cut, "text", "")), - TextTurn(value=cut.answer, role="assistant"), - ] - if hasattr(cut, "context"): - turns = [TextTurn(value=cut.context, role="user")] + turns - if hasattr(cut, "system_prompt"): - turns = [TextTurn(value=cut.system_prompt, role="system")] + turns - return NeMoMultimodalConversation( - id=cut.id, - turns=turns, - token_equivalent_duration=token_equivalent_duration, - custom=cut.custom, - ) - - -@data_type_parser(["sqa_as_conversation"]) -def read_sqa_as_conversation(config) -> tuple[CutSet, bool]: - """ - Conversion parser for old spoken-question-answering data saved in NeMo format. - Intended for converting SQA data in NeMo or Lhotse manifests from Lhotse Cut into NeMoMultimodalConversation. - The examples for multimodal LLM are constructed to present "question" + acoustic representation as input, - and predict "answer". - - Example of original data JSON in NeMo manifest format:: - - { - "audio_filepath": "/path/to/audio.wav", - "duration": 3.48, - "text": "Of exclusive national competence, let me assure you". - "lang": "en", - "question": "What is the nature of the competence described in the context?", - "answer": "The context mentions \"exclusive national competence\", indicating that the competence in question is solely within the authority of a nation.", - } - - Same example in Lhotse manifest format:: - - { - "id": "some-id-0", - "recording": { - "id": "some-id-0", - "sources": [ - "type": "path", - "source": "/path/to/audio.wav", - "channel_ids": [0], - ], - "sampling_rate": 16000, - "duration": 3.48, - "num_samples": 55680, - }, - "supervisions": [ - "id": "some-id-0", - "start": 0.0, - "duration": 3.48, - "channel": 0, - "text": "Of exclusive national competence, let me assure you". - "language": "en", - ], - "start": 0.0, - "duration": 3.48, - "channel": 0, - "custom": { - "question": "What is the nature of the competence described in the context?", - "answer": "The context mentions \"exclusive national competence\", indicating that the competence in question is solely within the authority of a nation.", - } - } - """ - cuts, is_tarred = read_cutset_from_config(config) - # Attach extra tags to every utterance dynamically, if provided. - # We need to attach them before cuts are converted to conversations. - if (extra_tags := config.get("tags")) is not None: - cuts = cuts.map(partial(attach_tags, tags=extra_tags), apply_fn=None) - cuts = cuts.map( - partial( - sqa_cut_to_conversation, - audio_locator_tag=config.audio_locator_tag, - token_equivalent_duration=config.token_equivalent_duration, - ) - ) - return cuts, is_tarred - - -def _strip_timestamps( - text: str, _TIMESTAMP_PATTERN=re.compile(r"<\|\d+\|>"), _SPACE_PATTERN=re.compile(r"\s+") -) -> str: - """ - Strips timestamp tokens from text, e.g. turns: - '<|0|> Hey <|3|> <|3|> how <|5|> <|7|> are <|8|> <|8|> <|10|> you? <|12|>' - into: - 'Hey how are you?' - """ - # Regexp pattern args are cached compiled patterns (micro-optimization). - text = _TIMESTAMP_PATTERN.sub("", text) # strip timestamp tokens if present - return _SPACE_PATTERN.sub(" ", text).strip() # strip multi-whitespaces - - -class FailedConversion: - pass - - -def s2s_cut_to_conversation( - cut: Cut, - audio_locator_tag: str, - token_equivalent_duration: float, - input_roles: Sequence[str] = ("user", "User"), - output_roles: Sequence[str] = ("assistant", "Assistant", "agent", "Agent"), - strip_timestamp_tokens: bool = True, -) -> NeMoMultimodalConversation: - """ - Converts a lhotse Cut representing multi-turn speech-to-speech conversation (with multiple supervision segments) - into a multi-turn NeMoMultimodalConversation, where the user has AudioTurns and assistant responds in TextTurns. - - Args: - cut: lhotse Cut to convert. - audio_locator_tag: special token indicating audio will be inserted in this location in the token sequence. - token_equivalent_duration: how much speech duration is counted as one token. - input_roles: when supervision.speaker is set to one of these values, we consider it user's turn. - output_roles: when supervision.speaker is set to one of these values, we consider it assistant's turn. - strip_timestamp_tokens: strips tokens like <|0|>, <|1|>, etc indicating timestamps from the text. - """ - turn_cuts = cut.trim_to_supervisions(keep_overlapping=False) - turns = [] - idx = 0 - for per_turn_cut in turn_cuts: - assert ( - len(per_turn_cut.supervisions) >= 1 - ), f"Expected at least one supervision per turn, got none in cut {cut.id}" - # If len(per_turn_cut.supervisions) > 1, only the first turn is considered for cut creation. - # We assume that len(per_turn_cut.supervisions) >= 1 happens because one of the turns - # is completely contained within another turn. - turn_speaker = per_turn_cut.supervisions[0].speaker - turn_text = per_turn_cut.supervisions[0].text - if strip_timestamp_tokens: - turn_text = _strip_timestamps(turn_text) - if len(per_turn_cut.supervisions) > 1: - assert per_turn_cut.supervisions[1].text == turn_cuts[idx - 1].supervisions[0].text - if turn_speaker in input_roles: - turns.append(AudioTurn(cut=per_turn_cut, role="user", audio_locator_tag=audio_locator_tag, text=turn_text)) - elif turn_speaker in output_roles: - turns.append(TextTurn(value=turn_text, role="assistant")) - else: - logging.warning(f"Speaker '{turn_speaker}' not found in user or agent roles for cut {cut.id}") - return FailedConversion() - idx += 1 - if hasattr(cut, "context"): - turns = [TextTurn(value=cut.context, role="user")] + turns - if hasattr(cut, "system_prompt"): - turns = [TextTurn(value=cut.system_prompt, role="system")] + turns - return NeMoMultimodalConversation( - id=cut.id, - turns=turns, - token_equivalent_duration=token_equivalent_duration, - custom=cut.custom, - ) - - -@data_type_parser(["s2s_as_conversation"]) -def read_s2s_as_conversation(config) -> tuple[CutSet, bool]: - cuts, is_tarred = read_cutset_from_config(config) - # Attach extra tags to every utterance dynamically, if provided. - # We need to attach them before cuts are converted to conversations. - if (extra_tags := config.get("tags")) is not None: - cuts = cuts.map(partial(attach_tags, tags=extra_tags), apply_fn=None) - cuts = cuts.map( - partial( - s2s_cut_to_conversation, - audio_locator_tag=config.audio_locator_tag, - token_equivalent_duration=config.token_equivalent_duration, - input_roles=config.get("input_roles", ["user", "User"]), - output_roles=config.get("output_roles", ["assistant", "Assistant", "agent", "Agent"]), - strip_timestamp_tokens=config.get("strip_timestamp_tokens", True), - ) - ).filter(lambda ex: not isinstance(ex, FailedConversion)) - return cuts, is_tarred - - -def create_recording_from_array(samples: np.ndarray, sampling_rate: int, recording_id: str) -> Recording: - with io.BytesIO() as buffer: - sf.write(buffer, samples.T, samplerate=sampling_rate, format='WAV') - buffer.seek(0) - return Recording.from_bytes(buffer.read(), recording_id=recording_id) - - -def resolve_relative_paths(cut: Cut, manifest_path: str) -> Cut: - """Resolve relative paths in a Cut object to their full paths.""" - if isinstance(cut, PaddingCut): - return cut - - if isinstance(cut, MixedCut): - for track in cut.tracks: - track.cut = resolve_relative_paths(track.cut, manifest_path) - return cut - - def resolve_recording(value): - for audio_source in value.sources: - if audio_source.type == "file": - audio_source.source = get_full_path(audio_source.source, manifest_file=manifest_path) - - def resolve_array(value): - if isinstance(value, TemporalArray): - value.array = resolve_array(value.array) - else: - if value.storage_type in ("numpy_files", "lilcom_files"): - abspath = Path( - get_full_path(str(Path(value.storage_path) / value.storage_key), manifest_file=manifest_path) - ) - value.storage_path = str(abspath.parent) - value.storage_key = str(abspath.name) - elif value.storage_type in ( - "kaldiio", - "chunked_lilcom_hdf5", - "lilcom_chunky", - "lilcom_hdf5", - "numpy_hdf5", - ): - value.storage_path = get_full_path(value.storage_path, manifest_file=manifest_path) - # ignore others i.e. url, in-memory data, etc. - - if cut.has_recording: - resolve_recording(cut.recording) - if cut.has_features: - resolve_array(cut.features) - if cut.custom is not None: - for key, value in cut.custom.items(): - if isinstance(value, Recording): - resolve_recording(value) - elif isinstance(value, (Array, TemporalArray, Features)): - resolve_array(value) - - return cut - - -@data_type_parser(["nemo", "nemo_tarred"]) -def read_nemo_manifest(config) -> tuple[CutSet, bool]: - """Read NeMo manifest and return a Lhotse CutSet.""" - common_kwargs = {} - for key in ("text_field", "lang_field", "shuffle", "shard_seed", "extra_fields"): - if key in config: - if key == "shuffle": - common_kwargs["shuffle_shards"] = config[key] - else: - common_kwargs[key] = config[key] - # The option below is to allow a special case of NeMo manifest iteration as Lhotse CutSet - # without performing any I/O. NeMo manifests typically don't have sampling_rate information required by Lhotse, - # so lhotse has to look up the headers of audio files to fill it on-the-fly. - # (this only has an impact on non-tarred data; tarred data is read into memory anyway). - # This is useful for utility scripts that iterate metadata and estimate optimal batching settings - # and other data statistics. - metadata_only = config.get("metadata_only", False) - force_finite = config.get("force_finite", False) - notar_kwargs = {"metadata_only": metadata_only} - is_tarred = config.get("tarred_audio_filepaths") is not None - if isinstance(config.manifest_filepath, (str, Path)): - if is_tarred and not metadata_only: - cuts = CutSet( - LazyNeMoTarredIterator( - config.manifest_filepath, - tar_paths=config.tarred_audio_filepaths, - skip_missing_manifest_entries=config.get("skip_missing_manifest_entries", False), - slice_length=config.get("slice_length", None), - **common_kwargs, - ) - ) - if not force_finite: - cuts = cuts.repeat(preserve_id=True) - else: - cuts = CutSet(LazyNeMoIterator(config.manifest_filepath, **notar_kwargs, **common_kwargs)) - else: - # Format option 1: - # Assume it's [[path1], [path2], ...] (same for tarred_audio_filepaths). - # This is the format for multiple NeMo buckets. - # Note: we set "weights" here to be proportional to the number of utterances in each data source. - # this ensures that we distribute the data from each source uniformly throughout each epoch. - # Setting equal weights would exhaust the shorter data sources closer the towards the beginning - # of an epoch (or over-sample it in the case of infinite CutSet iteration with .repeat()). - # Format option 2: - # Assume it's [[path1, weight1], [path2, weight2], ...] (while tarred_audio_filepaths remain unchanged). - # Note: this option allows to manually set the weights for multiple datasets. - # Format option 3: - # i.e., NeMo concatenated dataset - # Assume it's [path1, path2, ...] (while tarred_audio_filepaths in the same format). - cutsets = [] - weights = [] - tar_paths = config.tarred_audio_filepaths if is_tarred else repeat((None,)) - # Create a stream for each dataset. - for manifest_info, tar_path in zip(config.manifest_filepath, tar_paths): - if is_tarred and isinstance(tar_path, (list, tuple, ListConfig)): - # if it's in option 1 or 2 - (tar_path,) = tar_path - manifest_path = manifest_info[0] - else: - # if it's in option 3 - manifest_path = manifest_info - # First, convert manifest_path[+tar_path] to an iterator. - if is_tarred and not metadata_only: - nemo_iter = LazyNeMoTarredIterator( - manifest_path=manifest_path, - tar_paths=tar_path, - skip_missing_manifest_entries=config.get("skip_missing_manifest_entries", False), - slice_length=config.get("slice_length", None), - **common_kwargs, - ) - else: - nemo_iter = LazyNeMoIterator(manifest_path, **notar_kwargs, **common_kwargs) - # Then, determine the weight or use one provided - if isinstance(manifest_info, str) or len(manifest_info) == 1: - weight = len(nemo_iter) - else: - assert ( - isinstance(manifest_info, Sequence) - and len(manifest_info) == 2 - and isinstance(manifest_info[1], (int, float)) - ), ( - "Supported inputs types for config.manifest_filepath are: " - "str | list[list[str]] | list[tuple[str, number]] " - "where str is a path and number is a mixing weight (it may exceed 1.0). " - f"We got: '{manifest_info}'" - ) - weight = manifest_info[1] - # [optional] When we have a limit on the number of open streams, - # split the manifest to individual shards if applicable. - # This helps the multiplexing achieve closer data distribution - # to the one desired in spite of the limit. - if config.get("max_open_streams") is not None: - for subiter in nemo_iter.to_shards(): - cutsets.append(CutSet(subiter)) - weights.append(weight) - else: - cutsets.append(CutSet(nemo_iter)) - weights.append(weight) - cuts = mux( - *cutsets, - weights=weights, - max_open_streams=config.get("max_open_streams"), - seed=config.get("shard_seed", "trng"), - force_finite=force_finite or metadata_only, - ) - return cuts, is_tarred - - -@data_type_parser("multi_speaker_simulator") -def read_multi_speaker_simulator(config: DictConfig) -> tuple[CutSet, bool]: - # Import here to avoid circular dependency - from nemo.collections.asr.parts.utils.asr_multispeaker_utils import MultiSpeakerMixtureGenerator - - multi_speaker_cuts = CutSet( - MultiSpeakerMixtureGenerator( - manifest_filepath=config.manifest_filepath, - simulator_type=config.simulator_type, - sample_rate=config.get("sample_rate", 16000), - min_delay=config.get("min_delay", 0.5), - min_duration=config.get("min_duration", 0.1), - max_duration=config.get("max_duration", 60), - num_speakers=config.get("num_speakers", 2), - global_rank=config.get("global_rank", 0), - world_size=config.get("world_size", 1), - ) - ) - is_tarred = config.get("is_tarred", False) - return multi_speaker_cuts, is_tarred - - -def mux( - *cutsets: CutSet, - weights: list[Union[int, float]], - max_open_streams: Union[int, None] = None, - seed: Union[str, int] = "trng", - force_finite: bool = False, -) -> CutSet: - """ - Helper function to call the right multiplexing method flavour in lhotse. - The result is always an infinitely iterable ``CutSet``, but depending on whether ``max_open_streams`` is set, - it will select a more appropriate multiplexing strategy. - """ - if max_open_streams is not None: - assert not force_finite, "max_open_streams and metadata_only/force_finite options are not compatible" - cuts = CutSet.infinite_mux(*cutsets, weights=weights, seed=seed, max_open_streams=max_open_streams) - else: - if not force_finite: - cutsets = [cs.repeat(preserve_id=True) for cs in cutsets] - if len(cutsets) == 1: - # CutSet.mux must take more than one CutSet. - cuts = cutsets[0] - else: - cuts = CutSet.mux(*cutsets, weights=weights, seed=seed) - return cuts - - -def guess_parse_cutset(inp: Union[str, dict, omegaconf.DictConfig]) -> CutSet: - """ - Utility function that supports opening a CutSet from: - * a string path to YAML input spec (see :func:`read_dataset_config` for details) - * a string path to Lhotse non-tarred JSONL manifest - * a string path to NeMo non-tarred JSON manifest - * a dictionary specifying inputs with keys available in - :class:`nemo.collections.common.data.lhotse.dataloader.LhotseDataLoadingConfig` - - It's intended to be used in a generic context where we are not sure which way the user will specify the inputs. - """ - from nemo.collections.common.data.lhotse.dataloader import make_structured_with_schema_warnings - - if isinstance(inp, (dict, omegaconf.DictConfig)): - try: - config = make_structured_with_schema_warnings(OmegaConf.from_dotlist([f"{k}={v}" for k, v in inp.items()])) - cuts, _ = read_cutset_from_config(config) - return cuts - except Exception as e: - raise RuntimeError( - f"Couldn't open CutSet based on dict input {inp} (is it compatible with LhotseDataLoadingConfig?)" - ) from e - elif isinstance(inp, str): - if inp.endswith(".yaml"): - # Path to YAML file with the input configuration - config = make_structured_with_schema_warnings(OmegaConf.from_dotlist([f"input_cfg={inp}"])) - elif inp.endswith(".jsonl") or inp.endswith(".jsonl.gz"): - # Path to a Lhotse non-tarred manifest - config = make_structured_with_schema_warnings(OmegaConf.from_dotlist([f"cuts_path={inp}"])) - else: - # Assume anything else is a NeMo non-tarred manifest - config = make_structured_with_schema_warnings(OmegaConf.from_dotlist([f"manifest_filepath={inp}"])) - cuts, _ = read_cutset_from_config(config) - return cuts - else: - raise RuntimeError(f'Unsupported input type: {type(inp)} (expected a dict or a string)') - - -def _convert_tarred_to_duplex(cut, agent_silence_duration): - """Helper function to convert single supervision to duplex format. - - This is a module-level function (not nested) so it can be pickled for multiprocessing. - """ - if len(cut.supervisions) != 1: - # Skip cuts that don't have exactly one supervision - return cut - - original_sup = cut.supervisions[0] - orig_user_duration = cut.duration - - # Note here we use the last part of the audio as agent silence, which may cut user text, but this avoid using synthetic silence - # TODO(kevinhu): Evaluate how this impacts user EOU - - # Append agent_silence_duration of silence to the original recording - if agent_silence_duration > 0: - sr = cut.recording.sampling_rate - user_sil_samples = int(agent_silence_duration * sr) - silence_audio = np.zeros((1, user_sil_samples), dtype=np.float32) - # Concatenate silence to the end of the original audio - orig_audio = cut.recording.load_audio() - if orig_audio.ndim == 1: - orig_audio = orig_audio[None, :] - new_audio = np.concatenate([orig_audio, silence_audio], axis=1) - # Create a new Recording with the extended audio - new_recording = create_recording_from_array(new_audio, sr, cut.recording.id) - cut.recording = new_recording - cut.duration = new_audio.shape[1] / sr - - # Create user supervision (original speech) - user_dur = orig_user_duration - user_sup = SupervisionSegment( - id=f"{cut.id}_user", - recording_id=cut.recording_id, - start=0.0, - duration=user_dur, - text=original_sup.text, - language=original_sup.language, - speaker="user", - ) - - # Create agent supervision (silence with configurable duration) - agent_start = orig_user_duration + agent_silence_duration if agent_silence_duration < 0 else orig_user_duration - agent_dur = abs(agent_silence_duration) - agent_sup = SupervisionSegment( - id=f"{cut.id}_agent", - recording_id=cut.recording_id, - start=agent_start, - duration=agent_dur, - text="", # Empty text for silence - language=original_sup.language, - speaker="agent", - ) - - # Create target_audio with all zeros (silence) - sr = cut.recording.sampling_rate - num_samples = int(cut.duration * sr) - silence_audio = np.zeros((1, num_samples), dtype=np.float32) - - # Create a Recording from the silence audio - silence_recording = create_recording_from_array(silence_audio, sr, f"{cut.id}_target") - - # Replace the single supervision with user and agent supervisions - cut.supervisions = [user_sup, agent_sup] - cut.task = "asr" - - # Add target_audio to cut.custom - if cut.custom is None: - cut.custom = {} - cut.custom["target_audio"] = silence_recording - - return cut - - -@data_type_parser(["nemo_tarred_to_duplex"]) -def read_nemo_tarred_to_duplex(config) -> tuple[CutSet, bool]: - """Convert single-supervision NeMo tarred data to duplex format with user speech and agent silence. - - This parser wraps ``nemo_tarred`` and converts each single-supervision cut - into a two-supervision (user + agent) duplex cut. The user supervision - keeps the original audio and text, while the agent supervision is silence - with empty text. A silent ``target_audio`` recording (all zeros, same - length as the source) is attached via ``cut.custom["target_audio"]``. - - Input config YAML example (used inside an ``input_cfg`` list):: - - - manifest_filepath: /path/to/manifest__OP_0..63_CL_.json - tarred_audio_filepaths: /path/to/audio__OP_0..63_CL_.tar - type: nemo_tarred_to_duplex - agent_silence_duration: 2.0 # optional, default -0.08 - weight: 1.0 - - Each line in the NeMo manifest JSON is the standard NeMo format:: - - {"audio_filepath": "relative/path.wav", "text": "transcript", "duration": 4.5} - - ``agent_silence_duration`` controls how much silence is used for the agent - turn. A positive value appends that many seconds of silence after the - user audio. A negative value (the default, ``-0.08``) re-uses the last - ``abs(value)`` seconds of the user audio as the agent region instead of - appending new silence. - """ - - # by default, use the last part of user audio as agent silence duration - agent_silence_duration = config.get("agent_silence_duration", -0.08) - - # Reuse the existing nemo_tarred parser by creating a config with type: nemo_tarred - nemo_config = DictConfig(config) - nemo_config.type = "nemo_tarred" - - # Load the cuts using the original parser - cuts, is_tarred = read_nemo_manifest(nemo_config) - - # Apply the conversion using functools.partial to make it picklable - convert_fn = partial(_convert_tarred_to_duplex, agent_silence_duration=agent_silence_duration) - cuts = cuts.map(convert_fn) - - return cuts, is_tarred diff --git a/nemo/collections/common/data/lhotse/dataloader.py b/nemo/collections/common/data/lhotse/dataloader.py deleted file mode 100644 index f7838aa35d625a977b8632deb4e2658180cc1daa..0000000000000000000000000000000000000000 --- a/nemo/collections/common/data/lhotse/dataloader.py +++ /dev/null @@ -1,1046 +0,0 @@ -# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import os -import random -import warnings -from copy import deepcopy -from dataclasses import dataclass -from functools import partial -from typing import Any, List, Optional, Sequence, Tuple, Union - -import lhotse -import numpy as np -import torch -from lhotse import CutSet, RecordingSet -from lhotse.cut import Cut -from lhotse.dataset import ( - ClippingTransform, - Compress, - CutConcatenate, - DynamicBucketingSampler, - DynamicCutSampler, - IterableDatasetWrapper, - LowpassUsingResampling, - ReverbWithImpulseResponse, - RoundRobinSampler, - ZipSampler, - make_worker_init_fn, -) -from lhotse.dataset.dataloading import resolve_seed -from lhotse.dataset.sampling.base import CutSampler, SamplingConstraint, TimeConstraint -from lhotse.lazy import LazyFlattener -from lhotse.utils import fastcopy, fix_random_seed -from omegaconf import DictConfig, OmegaConf - -from nemo.collections.common.data.lhotse.cutset import ( - IncompleteConfigError, - guess_parse_cutset, - read_cutset_from_config, -) -from nemo.collections.common.data.lhotse.sampling import ( - BucketingFilter, - CERFilter, - ContextSpeakerSimilarityFilter, - DurationFilter, - FixedBucketBatchSizeConstraint2D, - MultimodalFixedBucketBatchSizeConstraint2D, - MultimodalSamplingConstraint, - TokenCountFilter, - TokenPerSecondFilter, - TokenPerTokenFilter, - ValidationStatusFilter, -) -from nemo.collections.common.data.prompt_fn import apply_prompt_format_fn -from nemo.collections.common.prompts import PromptFormatter -from nemo.collections.common.tokenizers.aggregate_tokenizer import TokenizerWrapper -from nemo.utils import logging - - -@dataclass -class LhotseDataLoadingConfig: - """ - Structured config used for OmegaConf schema validation. - It's also a single source of truth for reading default option values. - The options not supported anymore but present, e.g., in old configs, - will be emitted in a DeprecationWarning and ignored. - """ - - # 1. Data inputs. - # a. "Classic" NeMo input path fields. - input_cfg: Any = None # TODO(pzelasko): typing - manifest_filepath: Any = None # str | list[list[str | float]] | None = None - tarred_audio_filepaths: Any = None # str | list[list[str]] | None = None - # b. Lhotse CutSet manifest / Lhotse Shar tar dir paths. - cuts_path: str | None = None - shar_path: Any = None # str | list[str | tuple[str, float | int]] | None = None - # Enable this to support dataloading from JSON manifests that reference subsets of audio tar files. - skip_missing_manifest_entries: bool = False - tarred_random_access: bool = False # deprecated, replaced by: skip_missing_manifest_entries - # 2. Batch size. - # a. Existing NeMo options. - batch_size: int | None = None - # b. Lhotse dynamic batch sizes. - batch_duration: float | None = None - quadratic_duration: float | None = None - # c. Lhotse bucketing. - use_bucketing: bool = False - bucket_batch_size: list[int] | None = None - num_buckets: int = 30 - num_cuts_for_bins_estimate: int = 10000 - bucket_duration_bins: Any = None # list[float] | list[list[float]] | None = None - bucket_buffer_size: int = 10000 - concurrent_bucketing: bool = True # fetches data in a background thread - bucketing_2d_strict_mode: bool = True # reduces padding by discarding significant outliers - # d. Other Lhotse sampling options. - shuffle_buffer_size: int | None = 10000 - drop_last: bool = False - shard_seed: int | str = "trng" - max_open_streams: int | None = None - cuda_expandable_segments: bool = True - # Temperature for re-weighting datasets. 1 is a neutral value. Lower temperature over-samples smaller datasets, and vice versa. - # Can be a scalar (broadcast to all levels) or a list whose length must exactly match the input_cfg nesting depth. - # A list length mismatch raises ValueError. - reweight_temperature: Any = None # float | int | list[float] | None = None - # e. Multi-config related options. - # Setting multi_config=True will scan the config for keys with DictConfig values, - # create a separate sampler for each, and fuse the samplers according to sampler_fusion. - multi_config: bool = False - sampler_fusion: str = "round_robin" # round_robin | randomized_round_robin | zip - sampler_weights: dict[str, float] | None = None # only applicable to randomized_round_robin - - # 2.1 Multimodal sampling override options - pretokenize: bool = True # should we apply tokenizer before data sampling - prompt_format: str | None = None # when provided, we'll apply the prompt in addition to the tokenizer - use_multimodal_sampling: bool = False - audio_locator_tag: str | None = None # global audio placeholder token, propagates to datasets in input_cfg - token_equivalent_duration: float | None = None - batch_tokens: int | None = None - quadratic_factor: float | None = None - # Text pretraining data is usually very long, so we split it into smaller chunks. - # When provided, the text tokens will be cut into windows of this size. - cut_text_into_windows_tokens: int | None = None - - # 2.2 Filters on sequence lengths. - # * Speech input - min_duration: float | None = -1 - max_duration: float | None = float("inf") - min_tps: int = -1 # allowed tokens per second (audio-only) - max_tps: Any = float("inf") # float | list[float] - # * Text input - min_tokens: int | None = None - max_tokens: int | None = None - # When true, combine context+answer lengths into a total length; otherwise report context length. - # For 2D bucketing it's always false, as we report a tuple of (context_len, answer_len). - measure_total_length: bool = True - min_tpt: int = -1 # allowed tokens per token (text-only) - max_tpt: Any = float("inf") # float | list[float] - - # 2.3 Filters on CER and/or cosine speaker similarity of the context audio serving for TTS use cases. - max_cer: float | None = float("inf") - min_context_speaker_similarity: float | None = -1 - - # 2.4 Filters on validation status. If the validation status is not "pass", the cut will be filtered out. - keep: str = "pass" - - # 3. Supported existing NeMo options. - shuffle: bool = False - sample_rate: int = 16000 - seed: int | str = 0 - num_workers: int = 0 - pin_memory: bool = False - channel_selector: int | str | None = None - - # 4. Optional Lhotse data augmentation. - # a. On-the-fly noise/audio mixing. - noise_path: Any | None = ( - None # str | dict where dict can have any of keys: - # manifest_filepath, tarred_audio_filepaths, cuts_path, shar_path - ) - noise_snr: tuple[float, float] = (10.0, 20.0) - noise_mix_prob: float = 0.5 - # b. On-the-fly 3-way speed perturbation. - perturb_speed: bool = False - # c. Cut concatenation (glue together multiple utterances into a single one) - concatenate_samples: bool = False - concatenate_gap_seconds: float = 0.1 - concatenate_duration_factor: float = 1.0 - concatenate_merge_supervisions: bool = True - db_norm: Optional[float] = -25.0 # from CodeSwitchingDataset - # d. On-the-fly cut truncation or window slicing - # I) truncate: select one chunk of a fixed duration for each cut - truncate_duration: Optional[float] = None # set this to enable - truncate_offset_type: str = "random" # "random" | "start" (fixed) | "end" (fixed, counted back) - # II) cut_into_windows: convert each cut to smaller cut using a sliding window - # (define hop for overlapping windows) - cut_into_windows_duration: Optional[float] = None # set this to enable - cut_into_windows_hop: Optional[float] = None - # III) common options - keep_excessive_supervisions: bool = ( - True # when a cut is truncated in the middle of a supervision, should we keep them. - ) - # e. RIR augmentation (synthetic RIR if rir_path is None) - # at the moment supports only Lhotse recording manifests: - # e.g. https://github.com/lhotse-speech/lhotse/blob/master/lhotse/recipes/rir_noise.py - rir_enabled: bool = False - rir_path: str | None = None # str, must point to a lhotse RecordingSet manifest - rir_prob: float = 0.5 - # f. Padding to a minimum duration. Examples shorter than this will be padded, others are unaffected. - pad_min_duration: Optional[float] = None - pad_direction: str = "right" # "right" | "left" | "both" | "random" - # g. Bandwidth limitation via back-and-forth resampling - lowpass_enabled: bool = False - lowpass_frequencies_interval: Tuple[float, float] = (3500.0, 8000.0) - lowpass_prob: float = 0.5 - # h. Lossy compression augmentation (opus, mp3, vorbis, gsm) - # implemented via soundfile, so compression level is specified via number in [0.0, 1.0] - # 0.0 denotes the highest bitrate and denotes the lowest bitrate for a given codec - # overall, parameters mirror lhotse interface - compression_enabled: bool = False - compression_prob: float = 0.5 - compression_level_interval: Tuple[float, float] = (0.8, 0.99) - compression_codecs: Tuple[str] = ("opus",) - compression_codec_weights: Optional[List[float]] = None - compression_enable_for_custom_fields: bool = False - # i. Clipping/saturation augmentation - clipping_enabled: bool = False - clipping_gain_db: Tuple[float, float] = (0.0, 24.0) - clipping_normalize: bool = True - clipping_oversampling: Optional[int] = 2 - clipping_prob_hard: float = 0.5 - clipping_prob: float = 0.5 - - # 5. Other Lhotse options. - text_field: str = "text" # key to read the transcript from - lang_field: str = "lang" # key to read the language tag from - # Enables iteration of NeMo non-tarred manifests that don't have a "sampling_rate" key without performing any I/O. - # Note that this will not allow actual dataloading; it's only for manifest iteration as Lhotse objects. - metadata_only: bool = False - # Forces the resulting CutSet to be finite, so that the iteration will end after a full single epoch. - # Do not turn this on unless you're sure that you know what you're doing. - # In most cases (such as regular multi-GPU training) it will result in a deadlock due to - # a different number of steps on different DDP ranks. - force_finite: bool = False - # The following two options may be used to override auto-detection of appropriate PyTorch dataset flavor - # for your data types. PyTorch DataLoader uses two objects to yield data: dataset and sampler. - # *Map-dataset flavor.* There is one sampler per GPU that lives in the training loop process; - # it selects the examples to be prepared by map-dataset class. - # Each batch selection determined by the sampler is then passed by the dataloader - # to one of its worker processes to be processed by the dataset class. - # *Iterable-dataset flavor.* Each dataloading worker has its own sampler replica instead; - # the sampler must have the logic for either data deduplication or unique order shuffling to avoid - # duplicated data across workers and GPUs. Lhotse relies on unique order shuffling. - # The default settings are: - # * use iterable dataset for tarred audio data. - # * use iterable dataset for any text data. - # * use map dataset for non-tarred audio data (we might change this in the future) - force_map_dataset: bool = False - force_iterable_dataset: bool = False - # Force the dataloader to slice each data source. - # This may improve sampling randomness for large-scale runs with many dataset sources and large shards - # at the cost of some IO redundancy. - # The slicing is achieved with a randomly-selected offset K used to skip the first K examples, - # and reading them consecutively for ``slice_length`` iterations. - # The first K examples will actually be read and then discarded, incurring the IO cost, due to - # our support of object stores and gzipped files that generally don't have indexes of byte offsets per line. - slice_length: Optional[int] = None - - -def determine_use_iterable_dataset(use_iterable_dataset: bool, config: DictConfig) -> bool: - """Determine whether to use iterable dataset for a given configuration.""" - assert not ( - config.force_map_dataset and config.force_iterable_dataset - ), "Conflicting options: force_map_dataset=True and force_iterable_dataset=True" - use_iterable_dataset = (use_iterable_dataset or config.force_iterable_dataset) and not config.force_map_dataset - return use_iterable_dataset - - -def get_lhotse_dataloader_from_config( - config: Union[dict, DictConfig], - global_rank: int, - world_size: int, - dataset: torch.utils.data.Dataset, - tokenizer=None, -) -> torch.utils.data.DataLoader: - """ - Set up a Lhotse training dataloader. - - Expects a typical NeMo dataset configuration format, with additional fields: "use_lhotse=True". - Some fields in the original NeMo configuration may be ignored. - - The ``dataset`` parameter should be an instance of a Lhotse-compatible PyTorch Dataset class. - It only needs to define the following method ``__getitem__(self, cuts: CutSet) -> Dict[str, torch.Tensor]``. - This dataset is not expected to hold a reference to any actual data; it may be interpreted as a function - mapping a Lhotse CutSet into a mini-batch of tensors. - - For an example, see: :class:`nemo.collections.asr.data.audio_to_text_lhotse.LhotseSpeechToTextBpeDataset`, - which is constructed from just a tokenizer and essentially loads and collates audio and tokenizes the transcript. - - The ``tokenizer`` is used both for audio and text datasets for on-the-fly tokenization. - This allows us to stratify the bucketing by the count of input/output tokens (depending on modality). - If "prompt_format" is additionally provided in the config, we will also apply a prompt formatter. - Note that ``tokenizer`` can be any tokenizer type (e.g. both SentencePiece and Aggregate tokenizers work). - """ - if not isinstance(config, DictConfig): - config = OmegaConf.create(config) - - # Providing default value because we haven't filled the config defaults yet. - maybe_set_cuda_expandable_segments(enabled=config.get("cuda_expandable_segments", True)) - - if config.get("multi_config", False): - return get_lhotse_dataloader_from_multi_config( - top_level_config=config, - global_rank=global_rank, - world_size=world_size, - dataset=dataset, - tokenizer=tokenizer, - ) - else: - return get_lhotse_dataloader_from_single_config( - config=config, global_rank=global_rank, world_size=world_size, dataset=dataset, tokenizer=tokenizer - ) - - -def get_lhotse_dataloader_from_single_config( - config: DictConfig, - global_rank: int, - world_size: int, - dataset: torch.utils.data.Dataset, - tokenizer=None, -) -> torch.utils.data.DataLoader: - """ - Set up a Lhotse training dataloader. - - Expects a typical NeMo dataset configuration format, with additional fields: "use_lhotse=True". - Some fields in the original NeMo configuration may be ignored. - - The ``dataset`` parameter should be an instance of a Lhotse-compatible PyTorch Dataset class. - It only needs to define the following method ``__getitem__(self, cuts: CutSet) -> Dict[str, torch.Tensor]``. - This dataset is not expected to hold a reference to any actual data; it may be interpreted as a function - mapping a Lhotse CutSet into a mini-batch of tensors. - - For an example, see: :class:`nemo.collections.asr.data.audio_to_text_lhotse.LhotseSpeechToTextBpeDataset`, - which is constructed from just a tokenizer and essentially loads and collates audio and tokenizes the transcript. - - The ``tokenizer`` is used when text-only datasets are included in dataloading. - In these cases we will tokenize ``TextExample``s before sampling mini-batches so that - we can account for their number of tokens. - Note: this behaviour might eventually be extended to audio datasets too. - - Note that ``tokenizer`` can be any tokenizer type (e.g. both SentencePiece and Aggregate tokenizers work). - """ - logging.info("We will be using a Lhotse DataLoader.") - config = make_structured_with_schema_warnings(config) - - # First, resolve the random seed in case a string value was provided. - config.seed = resolve_seed(config.seed) - fix_random_seed(config.seed) - - sampler, use_iterable_dataset = get_lhotse_sampler_from_config( - config=config, global_rank=global_rank, world_size=world_size, tokenizer=tokenizer - ) - - # 4. Creating dataloader. - if use_iterable_dataset: - # Wrapper here is necessary when using NeMo tarred data or Lhotse Shar data, - # because then I/O happens upon sampler iteration. Normally, the sampler resides - # in the training loop process, but when we use iterable dataset, we can move it to - # the dataloading worker process. - # We use lhotse's own worker_init_fn which leverages information such as rank, world_size, - # worker_id, etc. to set a different random seed for each (node, worker) combination. - # This together with infinite datasets removes the need to split data across nodes/workers. - dloader_kwargs = dict( - dataset=IterableDatasetWrapper(dataset=dataset, sampler=sampler), - worker_init_fn=make_worker_init_fn(rank=global_rank, world_size=world_size, seed=config.seed), - persistent_workers=config.num_workers > 0, # helps Lhotse Shar maintain shuffling state - ) - else: - # For non-tarred data, the sampler resides in the training loop process and - # reads only light-weight JSON objects; it samples mini-batches and passes - # the meta-data to Dataset, which performs the actual I/O inside its __getitem__ method. - dloader_kwargs = dict(dataset=dataset, sampler=sampler) - dloader = torch.utils.data.DataLoader( - **dloader_kwargs, - batch_size=None, - num_workers=config.num_workers, - pin_memory=config.pin_memory, - ) - - return dloader - - -def get_lhotse_dataloader_from_multi_config( - top_level_config: DictConfig, - global_rank: int, - world_size: int, - dataset: torch.utils.data.Dataset, - tokenizer=None, -) -> torch.utils.data.DataLoader: - """ - Set up a Lhotse training dataloder. - - It works similarly to :func:`get_lhotse_dataloader_from_config`, except that - you can provide multiple configs to set up different sampling, batching, and - augmentation settings for every dataset and decide how to merge them. - - The expected format is that the ``configs`` is a dict of group name -> actual config. - - The first config is treated as a "main" config that determines the RNG, CUDA allocator, - and sampler fusion settings. - """ - - def gather_shared_opts(): - """ - In multi-config setting, the top-level config defines several attributes that overwrite - the ones present in sub-configs. - """ - assert all(k in top_level_config for k in ["seed", "shard_seed", "shuffle"]), ( - "In a multi-config setting (multi_config=True), the top-level namespace (typically train_ds)" - "must define at least 'seed', 'shard_seed', and 'shuffle' keys that will be " - "shared by all sub-configs." - ) - overwriting_opts = [ - "seed", - "shard_seed", - "num_workers", - "pin_memory", - "shuffle", - "sampler_fusion", - "sampler_weights", - "multi_config", - "metadata_only", - "force_finite", - ] - defaults = OmegaConf.structured(LhotseDataLoadingConfig) - top_level_config["seed"] = resolve_seed(top_level_config["seed"]) - return OmegaConf.create({k: top_level_config.get(k, defaults[k]) for k in overwriting_opts}) - - shared_opts = gather_shared_opts() - fix_random_seed(shared_opts.seed) - - configs = { - name: c - for name, c in top_level_config.items() - if isinstance(c, DictConfig) and name not in ("sampler_weights",) # exclude dict opts - } - - source_samplers, source_use_iterable_dataset = {}, [] - for name, config in configs.items(): - try: - expanded_config = make_structured_with_schema_warnings(config) - for k, v in shared_opts.items(): - expanded_config[k] = v - s, t = get_lhotse_sampler_from_config( - config=expanded_config, global_rank=global_rank, world_size=world_size, tokenizer=tokenizer - ) - except IncompleteConfigError as e: - raise IncompleteConfigError( - "Cannot create a sampler for one of the sub-configs in a multi_config setup." - f"The problematic config is under key={name} and has the following contents: {config}" - ) from e - source_samplers[name] = s - source_use_iterable_dataset.append(t) - - assert all(st == source_use_iterable_dataset[0] for st in source_use_iterable_dataset[1:]), ( - "When using multiple input_cfg sources ensure they are all tarred or non-tarred (can't mix). " - "You can provide force_iterable_dataset=True to each namespace to fix." - ) - use_iterable_dataset = all(source_use_iterable_dataset) - if shared_opts.sampler_fusion == "zip": - sampler = ZipSampler(*source_samplers.values()) - elif shared_opts.sampler_fusion == "round_robin": - sampler = RoundRobinSampler(*source_samplers.values()) - elif shared_opts.sampler_fusion == "randomized_round_robin": - _samplers, _weights = [], [] - for key in source_samplers.keys(): - _samplers.append(source_samplers[key]) - if shared_opts.sampler_weights is not None: - _weights.append(shared_opts.sampler_weights[key]) - sampler = RoundRobinSampler( - *_samplers, - randomize=_weights if len(_weights) > 0 else True, - seed=shared_opts.seed, - ) - else: - raise RuntimeError(f"Unsupported sampler fusion strategy: {shared_opts.sampler_fusion}") - - # 4. Creating dataloader. - if use_iterable_dataset: - # Wrapper here is necessary when using NeMo tarred data or Lhotse Shar data, - # because then I/O happens upon sampler iteration. Normally, the sampler resides - # in the training loop process, but when we use iterable dataset, we can move it to - # the dataloading worker process. - # We use lhotse's own worker_init_fn which leverages information such as rank, world_size, - # worker_id, etc. to set a different random seed for each (node, worker) combination. - # This together with infinite datasets removes the need to split data across nodes/workers. - dloader_kwargs = dict( - dataset=IterableDatasetWrapper(dataset=dataset, sampler=sampler), - worker_init_fn=make_worker_init_fn(rank=global_rank, world_size=world_size, seed=shared_opts.seed), - persistent_workers=shared_opts.num_workers > 0, # helps Lhotse Shar maintain shuffling state - ) - else: - # For non-tarred data, the sampler resides in the training loop process and - # reads only light-weight JSON objects; it samples mini-batches and passes - # the meta-data to Dataset, which performs the actual I/O inside its __getitem__ method. - dloader_kwargs = dict(dataset=dataset, sampler=sampler) - dloader = torch.utils.data.DataLoader( - **dloader_kwargs, - batch_size=None, - num_workers=shared_opts.num_workers, - pin_memory=shared_opts.pin_memory, - ) - - return dloader - - -def get_lhotse_sampler_from_config(config, global_rank, world_size, tokenizer=None) -> tuple[CutSampler, bool]: - """Create a CutSampler from a dataloader config.""" - # 1. Load a manifest as a Lhotse CutSet. - cuts, use_iterable_dataset = read_cutset_from_config(config) - use_iterable_dataset = determine_use_iterable_dataset(use_iterable_dataset, config) - - _auto_detect_bucketing_and_validate_batch_size(config) - - # Apply channel selector - if config.channel_selector is not None: - logging.info('Using channel selector %s.', config.channel_selector) - cuts = cuts.map(partial(_select_channel, channel_selector=config.channel_selector)) - - # Resample as a safeguard; it's a no-op when SR is already OK - cuts = cuts.map(partial(resample, sampling_rate=config.sample_rate), apply_fn=None) - - # Expands cuts if multiple translations are provided. - cuts = CutSet(LazyFlattener(cuts.map(_flatten_alt_text, apply_fn=None))) - - if config.use_multimodal_sampling: - assert tokenizer is not None, ( - "You must pass a tokenizer to `get_lhotse_dataloader_from_config` in order to" - "read text-only datasets (enabled via use_multimodal_dataloading)" - ) - - if tokenizer is not None and config.pretokenize: - if not use_iterable_dataset: - logging.warning( - "You are using a non-tarred dataset and requested tokenization during data sampling " - "(pretokenize=True). This will cause the tokenization to happen in the main (GPU) process," - "possibly impacting the training speed if your tokenizer is very large." - "If the impact is noticable, set pretokenize=False in dataloader config." - "(note: that will disable token-per-second filtering and 2D bucketing features)" - ) - - if config.use_multimodal_sampling and config.cut_text_into_windows_tokens is not None: - cuts = CutSet( - LazyFlattener( - cuts.map( - partial( - _cut_text_into_windows, - num_tokens=config.cut_text_into_windows_tokens, - tokenizer=tokenizer, - ), - apply_fn=None, - ) - ) - ) - - if config.prompt_format is not None: - cuts = cuts.map( - partial(tokenize_with_prompt, tokenizer=tokenizer, prompt_format=config.prompt_format), apply_fn=None - ) - else: - if not isinstance(tokenizer, TokenizerWrapper): - tokenizer = TokenizerWrapper(tokenizer) - cuts = cuts.map(partial(tokenize, tokenizer=tokenizer), apply_fn=None) - - # 2. Optional augmentations. - # 2.a. Noise mixing. - if config.noise_path is not None: - noise = guess_parse_cutset(config.noise_path) - # make sure the noise is resampled to the same sample rate as the audio cuts - noise = noise.resample(config.sample_rate) - cuts = cuts.mix( - cuts=noise, - snr=tuple(config.noise_snr), - mix_prob=config.noise_mix_prob, - seed=config.shard_seed, - random_mix_offset=True, - ) - - # 2.b. On-the-fly speed perturbation. - # mux here ensures it's uniformly distributed throughout sampling, - # and applying it here (before sampler/dataset) ensures optimal - # bucket allocation. - if config.perturb_speed: - cuts = CutSet.mux( - cuts, - cuts.perturb_speed(0.9), - cuts.perturb_speed(1.1), - ) - - # 2.d: truncation/slicing - if config.truncate_duration is not None: - cuts = cuts.truncate( - max_duration=config.truncate_duration, - offset_type=config.truncate_offset_type, - keep_excessive_supervisions=config.keep_excessive_supervisions, - ) - if config.cut_into_windows_duration is not None: - cuts = cuts.cut_into_windows( - duration=config.cut_into_windows_duration, - hop=config.cut_into_windows_hop, - keep_excessive_supervisions=config.keep_excessive_supervisions, - ) - - if config.pad_min_duration is not None: - cuts = cuts.pad(duration=config.pad_min_duration, direction=config.pad_direction, preserve_id=True) - - # Duration filtering, same as native NeMo dataloaders. - # We can filter after the augmentations because they are applied only when calling load_audio(). - cuts = cuts.filter(DurationFilter(config.min_duration, config.max_duration)) - cuts = cuts.filter( - TokenCountFilter(config.min_tokens, config.max_tokens, measure_total_length=config.measure_total_length) - ) - - # validation status filtering - cuts = cuts.filter(ValidationStatusFilter(config.keep)) - # CER filtering, same as native NeMo dataloaders. - cuts = cuts.filter(CERFilter(config.max_cer)) - # Context speaker similarity filtering, same as native NeMo dataloaders. - cuts = cuts.filter(ContextSpeakerSimilarityFilter(config.min_context_speaker_similarity)) - - if tokenizer is not None and config.pretokenize: - cuts = cuts.filter(TokenPerSecondFilter(config.min_tps, config.max_tps)) - cuts = cuts.filter(TokenPerTokenFilter(config.min_tpt, config.max_tpt)) - - # Select the strategy customizing Lhotse sampler behaviour. - # Provides support for dynamic batch sizes, multimodal dataloading, 2D bucketing, etc. - bucket_duration_bins = determine_bucket_duration_bins(config) - cuts, constraint = determine_sampling_constraint(cuts, bucket_duration_bins, config) - - # 3. The sampler. - if config.use_bucketing: - # Bucketing. Some differences from NeMo's native bucketing: - # - we can tweak the number of buckets and bucket duration bins using the configuration - # - batch size is dynamic and configurable via a single param: max_duration (config: batch_duration) - # - quadratic_duration introduces a penalty to balance batch sizes for quadratic time complexity models - logging.info( - f"Creating a Lhotse DynamicBucketingSampler " - f"(max_batch_duration={config.batch_duration} max_batch_size={config.batch_size})" - ) - # Determine the bucket duration bins - sampler = DynamicBucketingSampler( - cuts, - constraint=constraint, - shuffle=config.shuffle, - drop_last=config.drop_last, - shuffle_buffer_size=config.shuffle_buffer_size, - seed=config.shard_seed, - num_buckets=config.num_buckets, - duration_bins=determine_bucket_duration_bins(config), - num_cuts_for_bins_estimate=config.num_cuts_for_bins_estimate, - buffer_size=config.bucket_buffer_size, - concurrent=config.concurrent_bucketing, - rank=0 if use_iterable_dataset else global_rank, - world_size=1 if use_iterable_dataset else world_size, - ) - else: - # Non-bucketing sampler, similar to original NeMo dataloading without bucketing, - # but we also use batch_duration instead of batch_size here. - # Recommended for dev/test. - logging.info( - f"Creating a Lhotse DynamicCutSampler (bucketing is disabled, " - f"(max_batch_duration={config.batch_duration} max_batch_size={config.batch_size})" - ) - sampler = DynamicCutSampler( - cuts, - constraint=constraint, - shuffle=config.shuffle, - drop_last=config.drop_last, - shuffle_buffer_size=config.shuffle_buffer_size, - seed=config.shard_seed, - rank=0 if use_iterable_dataset else global_rank, - world_size=1 if use_iterable_dataset else world_size, - ) - - if config.concatenate_samples: - # Cut concatenation will produce longer samples out of shorter samples - # by gluing them together from the shortest to longest not to exceed a duration - # of longest_cut * duration_factor (greedy knapsack algorithm for minimizing padding). - # Useful e.g. for simulated code-switching in multilingual setups. - # We follow concatenation by ``merge_supervisions`` which creates a single supervision - # object with texts joined by a whitespace so that "regular" dataset classes don't - # have to add a special support for multi-supervision cuts. - sampler = sampler.map( - CutConcatenate( - gap=config.concatenate_gap_seconds, - duration_factor=config.concatenate_duration_factor, - ) - ) - if config.db_norm is not None: - sampler = sampler.map(partial(_normalize_loudness, db_norm=config.db_norm)) - if config.concatenate_merge_supervisions: - sampler = sampler.map(_merge_supervisions) - - if config.lowpass_enabled: - if lhotse.get_current_resampling_backend() != "libsox": - logging.warning( - "Lowpass augmentation works best with libsox backend. Consider setting resamping backend in Lhotse to libsox." - ) - sampler = sampler.map( - LowpassUsingResampling( - frequencies_interval=OmegaConf.to_container(config.lowpass_frequencies_interval), - p=config.lowpass_prob, - seed=config.shard_seed, - ) - ) - - if config.clipping_enabled: - sampler = sampler.map( - ClippingTransform( - gain_db=OmegaConf.to_container(config.clipping_gain_db), - normalize=config.clipping_normalize, - p=config.clipping_prob, - p_hard=config.clipping_prob_hard, - oversampling=config.clipping_oversampling, - seed=config.shard_seed, - ) - ) - - if config.rir_enabled: - sampler = sampler.map( - ReverbWithImpulseResponse( - rir_recordings=RecordingSet.from_file(config.rir_path) if config.rir_path is not None else None, - p=config.rir_prob, - randgen=random.Random(config.seed), - ) - ) - - if config.compression_enabled: - sampler = sampler.map( - Compress( - codecs=OmegaConf.to_container(config.compression_codecs), - p=config.compression_prob, - compression_level=OmegaConf.to_container(config.compression_level_interval), - codec_weights=( - OmegaConf.to_container(config.compression_codec_weights) - if config.compression_codec_weights - else config.compression_codec_weights - ), - compress_custom_fields=config.compression_enable_for_custom_fields, - seed=config.shard_seed, - ) - ) - - return sampler, use_iterable_dataset - - -def determine_sampling_constraint(cuts: CutSet, bucket_duration_bins, config) -> tuple[CutSet, SamplingConstraint]: - """ - Select an appropriate sampling strategy (constraint) for Lhotse samplers based on the configuration. - Sampling constraint affects the batch size (static/dynamic) and bucketing behaviour (1D/2D). - It is the appropriate customization point to introduce support of other modalities, - as it defines a method for example sequence length measurement (audio duration, text tokens, etc.). - - Some constraints apply extra filter on ``cuts`` which is why we accept and return the ``CutSet``. - - Lhotse's default is :class:`TimeConstraint` for regular audio data, other available options are - multimodal constraints (joint text + audio) and their 2D bucketing extensions. - """ - if config.use_multimodal_sampling: - if config.bucket_batch_size is not None: - assert ( - bucket_duration_bins is not None - ), "Cannot use bucket_batch_size option if bucket_duration_bins are not provided." - constraint = MultimodalFixedBucketBatchSizeConstraint2D( - max_seq_len_buckets=bucket_duration_bins, - batch_sizes=config.bucket_batch_size, - token_equivalent_duration=config.token_equivalent_duration, - strict_2d=config.bucketing_2d_strict_mode, - max_ratio=config.max_tpt if isinstance(config.max_tpt, Sequence) else None, - measure_total_length=config.measure_total_length, - ) - cuts = cuts.filter(BucketingFilter(constraint)) - else: - constraint = MultimodalSamplingConstraint( - token_equivalent_duration=config.token_equivalent_duration, - batch_size=config.batch_size, - batch_tokens=config.batch_tokens, - quadratic_factor=config.quadratic_factor, - measure_total_length=config.measure_total_length, - ) - else: - if config.bucket_batch_size is not None: - assert ( - bucket_duration_bins is not None - ), "Cannot use bucket_batch_size option if bucket_duration_bins are not provided." - constraint = FixedBucketBatchSizeConstraint2D( - max_seq_len_buckets=bucket_duration_bins, - batch_sizes=config.bucket_batch_size, - strict_2d=config.bucketing_2d_strict_mode, - max_ratio=config.max_tps if isinstance(config.max_tps, Sequence) else None, - ) - cuts = cuts.filter(BucketingFilter(constraint)) - else: - constraint = TimeConstraint( - max_cuts=config.batch_size, - max_duration=config.batch_duration, - quadratic_duration=config.quadratic_duration, - ) - return cuts, constraint - - -def _auto_detect_bucketing_and_validate_batch_size(config) -> None: - """ - Auto-enable ``use_bucketing`` when bucketing params are set, and validate - that at least one valid batch size combination is configured. - """ - # Auto-detect use_bucketing when bucketing params are set. - if not config.use_bucketing: - if config.bucket_batch_size is not None: - logging.info("Auto-enabling use_bucketing=True because bucket_batch_size is set.") - config.use_bucketing = True - elif config.bucket_duration_bins is not None: - logging.info("Auto-enabling use_bucketing=True because bucket_duration_bins is set.") - config.use_bucketing = True - - # Validate that at least one valid batch size combination is configured. - has_batch_size = config.batch_size is not None - has_batch_duration = not config.use_multimodal_sampling and config.batch_duration is not None - has_bucket_config = config.bucket_duration_bins is not None and config.bucket_batch_size is not None - has_batch_tokens = config.use_multimodal_sampling and config.batch_tokens is not None - if not (has_batch_size or has_batch_duration or has_bucket_config or has_batch_tokens): - raise ValueError( - "Batch size is not configured. Please set one of the following:\n" - " 1. batch_size\n" - " 2. batch_duration (when use_multimodal_sampling=False)\n" - " 3. bucket_duration_bins and bucket_batch_size (enables bucketing)\n" - " 4. batch_tokens (when use_multimodal_sampling=True)" - ) - - -def determine_bucket_duration_bins(config): - """ - Returns appropriate bucket bins based on configuration. - If user provided them explicitly, we just pass them along; - otherwise, we try to create provisional bins when min/max duration is available. - We might return None if it's impossible to determine the bins without computing data statistics, - in which case it will be automatically done at the start of training (but may take a few minutes). - """ - if config.bucket_duration_bins is not None: - # Bucket duration bins are provided: just use them. - ans = OmegaConf.to_container(config.bucket_duration_bins) - if isinstance(ans[0], Sequence): - # 2D bucketing. Ensure we're using tuples for correct behaviour of '<' operator - # between the bucket bin tuples and the output of measure_length. - ans = [tuple(item) for item in ans] - return ans - # Bucket duration bins are not set. - if config.use_multimodal_sampling: - # For multimodal sampling it's currently impossible to define a linspace over durations - # because the buckets are counted in the number of tokens. - # The bins will be auto-estimated by lhotse at the cost of a slight lag in the training start. - return None - elif config.max_duration is not None and config.max_duration < float("inf"): - # If max duration is provided, we can use that to compute uniformly distant bucket bins. - # This is not optimal but should be close enough for users who didn't want to estimate these up-front. - begin = config.min_duration if config.min_duration is not None and config.min_duration > 0 else 0.0 - end = config.max_duration - return np.linspace(begin, end, config.num_buckets + 1)[1:-1].tolist() - else: - # If we don't know max_duration, we can't guess a reasonable estimate of the upper bound of - # durations. - # The bins will be auto-estimated by lhotse at the cost of a slight lag in the training start. - return None - - -def make_structured_with_schema_warnings(config: Union[DictConfig, dict]) -> DictConfig: - """ - Checks the schema and fills missing default option values. - Warns the user if any of the fields are not supported by the current schema - but does not raise exceptions. - """ - default = OmegaConf.structured(LhotseDataLoadingConfig) - if not isinstance(config, DictConfig): - config = DictConfig(config) - - # Remove unsupported keys and warn about them. - supported_keys = set(OmegaConf.to_container(default).keys()) - received_keys = set(OmegaConf.to_container(config).keys()) - unsupported_keys = received_keys - supported_keys - unsupported_keys.discard("use_lhotse") - if unsupported_keys: - logging.warning( - f"The following configuration keys are ignored by Lhotse dataloader: {','.join(unsupported_keys)}", - ) - config = OmegaConf.masked_copy(config, list(supported_keys)) - - config = OmegaConf.merge(default, config) - - if config.get("tarred_random_access", False): - logging.warning( - "Option 'tarred_random_access' is deprecated and replaced with 'skip_missing_manifest_entries'.", - ) - config.skip_missing_manifest_entries = True - if config.skip_missing_manifest_entries: - logging.warning( - "Note: skip_missing_manifest_entries is set to True. " - "If any of your manifests and tar files are mismatched, the entire " - "tar file will be skipped without warning. It's your responsibility " - "to ensure data integrity with this setting." - ) - - return config - - -def tokenize(example, tokenizer): - """Return the text in the example according to the provided tokenizer.""" - if isinstance(example, Cut): - for s in example.supervisions: - if s.text is not None: - s.tokens = np.asarray(tokenizer(s.text, s.language)) - elif hasattr(example, "tokenize") and callable(example.tokenize): - example = example.tokenize(tokenizer) - else: - raise RuntimeError(f"Unsupported type of example: {type(example)}") - return example - - -def tokenize_with_prompt(example, tokenizer, prompt_format: str | PromptFormatter): - """Tokenize the example with the provided tokenizer and prompt format.""" - if isinstance(prompt_format, str): - prompt_format = PromptFormatter.resolve(prompt_format)(tokenizer) - encoded = apply_prompt_format_fn(example, prompt_format) - for key, value in encoded.items(): - setattr(example, key, value) - return example - - -# The helper callables below exist to avoid passing lambdas into lhotse CutSet map/filter methods. -# Lambdas are not serializable across processes by pickle. -# Note: lhotse offers LHOTSE_DILL_ENABLED=1 and ``lhotse.lazy.set_dill_enabled(True)`` -# to support pickling lambdas if its ever truly necessary. - - -def _normalize_loudness(cuts: CutSet, db_norm: float) -> CutSet: - return cuts.normalize_loudness(target=db_norm, mix_first=False) - - -def _merge_supervisions(cuts: CutSet) -> CutSet: - return cuts.merge_supervisions() - - -def _flatten_alt_text(cut) -> list: - ans = [cut] - if not isinstance(cut, Cut) or cut.custom is None or cut.custom.get("alt_text") is None: - return ans - cut = cut.move_to_memory(audio_format="wav") # performs I/O once and holds audio in memory from now on - # Popping to ease eyesight on debug. - paired_text = cut.custom.pop("alt_text") - for data in paired_text.values(): - # Copy to avoid lazy dataloading issues - data = data.copy() - text_instance = cut.map_supervisions(lambda s: fastcopy(s, text=data["text"], language=data["lang"])) - text_instance.custom = {"text": data.pop("text"), "lang": data.pop("lang"), **data} - ans.append(text_instance) - return ans - - -def maybe_set_cuda_expandable_segments(enabled: bool): - """ - Configures PyTorch memory allocator to expand existing allocated segments - instead of re-allocating them when tensor shape grows. - This can help speed up the training when sequence length and/or batch size change often, - and makes GPU more robust towards OOM. - - See here for more details: - pytorch.org/docs/stable/notes/cuda.html#optimizing-memory-usage-with-pytorch-cuda-alloc-conf - """ - if enabled and torch.cuda.is_available(): - if ( - (value := os.environ.get("PYTORCH_CUDA_ALLOC_CONF")) is not None - and len(value) > 0 - and "expandable_segments:True" not in value - ): - warnings.warn( - "You have set PYTORCH_CUDA_ALLOC_CONF without expandable_segments:True option. " - "We're setting that option anyway. To disable it, set cuda_expandable_segments=False " - "in NeMo dataloader configuration." - ) - - try: - torch.cuda.memory._set_allocator_settings("expandable_segments:True") - except RuntimeError: - logging.info( - "Failed to set expandable_segments:True for PyTorch CUDA allocator. " - "You may get training speed improvements if you enable this " - ) - - -def resample(example, sampling_rate): - from nemo.collections.common.data.lhotse.text_adapters import NeMoMultimodalConversation - - if isinstance(example, Cut): - return example.resample(sampling_rate) - elif isinstance(example, NeMoMultimodalConversation): - for turn in example.turns: - if hasattr(turn, "cut"): - turn.cut = turn.cut.resample(sampling_rate) - return example - else: - return example - - -def _select_channel(cut, channel_selector: int | str) -> list: - if isinstance(channel_selector, int): - channel_idx = channel_selector - elif isinstance(channel_selector, str): - if channel_selector in cut.custom: - channel_idx = cut.custom[channel_selector] - else: - raise ValueError(f"Channel selector {channel_selector} not found in cut.custom") - - if channel_idx >= cut.num_channels: - raise ValueError( - f"Channel index {channel_idx} is larger than the actual number of channels {cut.num_channels}" - ) - - if cut.num_channels == 1: - # one channel available and channel_idx==0 - return cut - else: - # with_channels only defined on MultiCut - return cut.with_channels(channel_idx) - - -def _cut_text_into_windows(cut, num_tokens: int, tokenizer) -> list: - """Split cut.text into chunks of num_tokens, creating new cuts with copied attributes from the original cut. - - This only applies to pretraining data without chat template. - - Args: - cut: TextExample, the cut object containing text to split - num_tokens: The number of tokens per chunk - tokenizer: The tokenizer to use to convert tokens to text - - Returns: - list: A list of new cut objects, each containing a chunk of tokens - """ - tokens = tokenizer.text_to_ids(cut.text) - ans = [] - for i in range(0, len(tokens), num_tokens): - new_cut = type(cut)( - text=tokenizer.ids_to_text(tokens[i : i + num_tokens]), - language=cut.language, - custom=deepcopy(cut.custom), - ) - ans.append(new_cut) - return ans diff --git a/nemo/collections/common/data/lhotse/indexed_adapters.py b/nemo/collections/common/data/lhotse/indexed_adapters.py deleted file mode 100644 index 831edf0b1f542cd9d9c8a8c7f9dddcf3b12ca931..0000000000000000000000000000000000000000 --- a/nemo/collections/common/data/lhotse/indexed_adapters.py +++ /dev/null @@ -1,319 +0,0 @@ -# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import json -import os -import random -import struct -import tarfile -from pathlib import Path -from typing import NamedTuple - -import numpy as np - -# Knuth's multiplicative hash constant (golden-ratio derived, 32-bit). -_KNUTH_HASH = 2654435761 - - -class LazyShuffledRange: - """ - Generates a permutation of ``range(n)`` lazily using a Feistel cipher, - without materializing the full index list. Each element is computed on - the fly in O(1) time and the object itself uses O(1) memory regardless - of ``n``. - - The technique is known as *cycle-walking* format-preserving encryption: - a Feistel network is a bijection on ``[0, 2^k)``, and repeatedly applying - it until the output falls within ``[0, n)`` restricts it to a bijection - on the desired domain. - - Args: - n: Size of the range to permute. - rng: A ``random.Random`` instance used to derive round keys. - num_rounds: Number of Feistel rounds (more rounds = better uniformity, - 6 is a good default for typical dataset sizes). - """ - - def __init__(self, n: int, rng: random.Random, num_rounds: int = 6): - self.n = n - if n <= 1: - return - bits = (n - 1).bit_length() - if bits < 2: - bits = 2 - if bits % 2: - bits += 1 - self._half = bits // 2 - self._mask = (1 << self._half) - 1 - self._num_rounds = num_rounds - self._keys = [rng.getrandbits(64) for _ in range(num_rounds)] - - def _permute_one(self, x: int) -> int: - left = (x >> self._half) & self._mask - right = x & self._mask - for key in self._keys: - left, right = right, left ^ (((right * _KNUTH_HASH) ^ key) >> 32 & self._mask) - return (left << self._half) | right - - def __len__(self) -> int: - return self.n - - def __iter__(self): - n = self.n - if n <= 0: - return - if n == 1: - yield 0 - return - for i in range(n): - x = i - while True: - x = self._permute_one(x) - if x < n: - yield x - break - - -def _load_index(data_path: str, idx_path: str | None = None): - """ - Load a memmap'd offset index for *data_path*. - - Returns ``(offsets, num_samples)`` where ``offsets`` always has - ``num_samples + 1`` entries — the last one being the data file size - (appended if absent in the on-disk index). - - Validates that all sample offsets fall within the data file. - """ - if idx_path is None: - idx_path = data_path + '.idx' - offsets = np.memmap(idx_path, dtype=np.dtype(' 0: - max_offset = int(offsets[:num_samples].max()) - if max_offset >= data_size: - raise ValueError( - f"Index for {data_path} contains offset {max_offset} " - f"beyond file size {data_size}. " - f"The .idx file may have been created by an incompatible tool " - f"or for a different file." - ) - return offsets, num_samples - - -def _resolve_idx(idx: int, length: int) -> int: - if idx < 0: - idx += length - if idx < 0 or idx >= length: - raise IndexError("Index out of bounds") - return idx - - -class IndexedJSONLReader: - def __init__(self, jsonl_path: Path | str, idx_path: Path | str | None = None): - self.data_path = str(jsonl_path) - self.offsets, self._len = _load_index(self.data_path, str(idx_path) if idx_path else None) - - def __len__(self): - return self._len - - def __getitem__(self, idx): - idx = _resolve_idx(idx, self._len) - start = int(self.offsets[idx]) - end = int(self.offsets[idx + 1]) - with open(self.data_path, 'rb') as f: - f.seek(start) - data = f.read(end - start) - return json.loads(data.decode('utf-8')) - - -class TarSample(NamedTuple): - """A single sample extracted from a WebDataset tar archive.""" - - json_data: dict - audio_bytes: bytes - audio_name: str - - -def _split_json_audio_pair(name_a, bytes_a, name_b, bytes_b) -> TarSample: - """Classify two tar members into a ``TarSample`` regardless of order.""" - if name_a.endswith('.json'): - return TarSample(json.loads(bytes_a), bytes_b, name_b) - if name_b.endswith('.json'): - return TarSample(json.loads(bytes_b), bytes_a, name_a) - raise ValueError(f"Expected one .json member in tar sample pair, got: {name_a}, {name_b}") - - -class IndexedTarSampleReader: - """ - Random access to WebDataset tar samples (``N.json`` + ``N.