diff --git a/nemo/README.md b/nemo/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d5cc00e74caef440c2ea28d4b56f268255973fe3 --- /dev/null +++ b/nemo/README.md @@ -0,0 +1,26 @@ +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/collections/diffusion/models/__init__.py b/nemo/agents/__init__.py similarity index 89% rename from nemo/collections/diffusion/models/__init__.py rename to nemo/agents/__init__.py index d9155f923f186a086a69de138e984e2fab2817ec..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c 100644 --- a/nemo/collections/diffusion/models/__init__.py +++ b/nemo/agents/__init__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. diff --git a/nemo/collections/diffusion/__init__.py b/nemo/agents/voice_agent/__init__.py similarity index 89% rename from nemo/collections/diffusion/__init__.py rename to nemo/agents/voice_agent/__init__.py index d9155f923f186a086a69de138e984e2fab2817ec..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c 100644 --- a/nemo/collections/diffusion/__init__.py +++ b/nemo/agents/voice_agent/__init__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. diff --git a/nemo/export/__init__.py b/nemo/agents/voice_agent/pipecat/__init__.py similarity index 73% rename from nemo/export/__init__.py rename to nemo/agents/voice_agent/pipecat/__init__.py index 100d2dcca63bded43b404264d3b5bb237826f643..55fb128340afb58c4785a2c5cc7477a1d6867a33 100644 --- a/nemo/export/__init__.py +++ b/nemo/agents/voice_agent/pipecat/__init__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -12,9 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. - -use_tensorrt = True try: - from nemo.export.tensorrt_lazy_compiler import trt_compile -except Exception as e: - use_tensorrt = False + import pipecat +except ImportError: + raise ImportError("pipecat is not installed. Please install it with `pip install pipecat-ai`.") diff --git a/nemo/collections/diffusion/data/__init__.py b/nemo/agents/voice_agent/pipecat/frames/__init__.py similarity index 89% rename from nemo/collections/diffusion/data/__init__.py rename to nemo/agents/voice_agent/pipecat/frames/__init__.py index d9155f923f186a086a69de138e984e2fab2817ec..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c 100644 --- a/nemo/collections/diffusion/data/__init__.py +++ b/nemo/agents/voice_agent/pipecat/frames/__init__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. diff --git a/nemo/collections/nlp/data/entity_linking/__init__.py b/nemo/agents/voice_agent/pipecat/frames/frames.py similarity index 68% rename from nemo/collections/nlp/data/entity_linking/__init__.py rename to nemo/agents/voice_agent/pipecat/frames/frames.py index 659718d71b82c71853c2f515bbcf5eb7bf09230a..df5f1c2c6fef3bede47251b2f0403fe3d124a192 100644 --- a/nemo/collections/nlp/data/entity_linking/__init__.py +++ b/nemo/agents/voice_agent/pipecat/frames/frames.py @@ -1,4 +1,4 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -12,4 +12,15 @@ # See the License for the specific language governing permissions and # limitations under the License. -from nemo.collections.nlp.data.entity_linking.entity_linking_dataset import EntityLinkingDataset + +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/collections/diffusion/encoders/__init__.py b/nemo/agents/voice_agent/pipecat/processors/__init__.py similarity index 89% rename from nemo/collections/diffusion/encoders/__init__.py rename to nemo/agents/voice_agent/pipecat/processors/__init__.py index d9155f923f186a086a69de138e984e2fab2817ec..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c 100644 --- a/nemo/collections/diffusion/encoders/__init__.py +++ b/nemo/agents/voice_agent/pipecat/processors/__init__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. diff --git a/nemo/agents/voice_agent/pipecat/processors/frameworks/__init__.py b/nemo/agents/voice_agent/pipecat/processors/frameworks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c --- /dev/null +++ b/nemo/agents/voice_agent/pipecat/processors/frameworks/__init__.py @@ -0,0 +1,13 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..03106a41f2a873fd382799784f776d1df3b33493 --- /dev/null +++ b/nemo/agents/voice_agent/pipecat/processors/frameworks/rtvi.py @@ -0,0 +1,72 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c --- /dev/null +++ b/nemo/agents/voice_agent/pipecat/services/__init__.py @@ -0,0 +1,13 @@ +# 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/multimodal/speech_llm/__init__.py b/nemo/agents/voice_agent/pipecat/services/nemo/__init__.py similarity index 67% rename from nemo/collections/multimodal/speech_llm/__init__.py rename to nemo/agents/voice_agent/pipecat/services/nemo/__init__.py index f0c19a3eebb92005ad3adbbeba26ed040f546025..1b96c38c91ce888fa1c761fb3b6bf1190ac497f0 100644 --- a/nemo/collections/multimodal/speech_llm/__init__.py +++ b/nemo/agents/voice_agent/pipecat/services/nemo/__init__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -12,4 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. -from nemo.collections.multimodal.speech_llm import models, modules +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 new file mode 100644 index 0000000000000000000000000000000000000000..14d196d4c6dd8a4444df3b8462969068bb0b69de --- /dev/null +++ b/nemo/agents/voice_agent/pipecat/services/nemo/audio_logger.py @@ -0,0 +1,844 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..0cc856b59c36c033a0d6dd94d75aafb21d0c3531 --- /dev/null +++ b/nemo/agents/voice_agent/pipecat/services/nemo/diar.py @@ -0,0 +1,360 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..2e635a5078cae224c2f07558664447fe8beb0d6b --- /dev/null +++ b/nemo/agents/voice_agent/pipecat/services/nemo/llm.py @@ -0,0 +1,760 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..aeb6674216762857712d9641e268fd6e471ea38a --- /dev/null +++ b/nemo/agents/voice_agent/pipecat/services/nemo/streaming_asr.py @@ -0,0 +1,319 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..21bda1174c01308e6b71335c0837891de181fa19 --- /dev/null +++ b/nemo/agents/voice_agent/pipecat/services/nemo/streaming_diar.py @@ -0,0 +1,212 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..bb048f50805e4b32a7590144c95baff68404a04c --- /dev/null +++ b/nemo/agents/voice_agent/pipecat/services/nemo/stt.py @@ -0,0 +1,316 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..f226d6da0f406df8018c29f15fae18681a20af73 --- /dev/null +++ b/nemo/agents/voice_agent/pipecat/services/nemo/tts.py @@ -0,0 +1,892 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..0c593e359e8c410e1a154224ade3ec561ba8fc82 --- /dev/null +++ b/nemo/agents/voice_agent/pipecat/services/nemo/turn_taking.py @@ -0,0 +1,441 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..421bf9823b5a2c6a1caac704b57b195074befc48 --- /dev/null +++ b/nemo/agents/voice_agent/pipecat/services/nemo/utils.py @@ -0,0 +1,197 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c --- /dev/null +++ b/nemo/agents/voice_agent/pipecat/transports/__init__.py @@ -0,0 +1,13 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..79a477ad34169de78fc7da62312f6dfebaeda006 --- /dev/null +++ b/nemo/agents/voice_agent/pipecat/transports/base_input.py @@ -0,0 +1,58 @@ +# 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/collections/nlp/data/language_modeling/megatron/length_distribution_type.py b/nemo/agents/voice_agent/pipecat/transports/base_transport.py similarity index 70% rename from nemo/collections/nlp/data/language_modeling/megatron/length_distribution_type.py rename to nemo/agents/voice_agent/pipecat/transports/base_transport.py index 8570d3d5e55f8e8c71133c27046363efda395c8a..eb57024611b6bac3b1656e493ab58bad53ef4f05 100644 --- a/nemo/collections/nlp/data/language_modeling/megatron/length_distribution_type.py +++ b/nemo/agents/voice_agent/pipecat/transports/base_transport.py @@ -1,4 +1,4 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -12,10 +12,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -import enum +from pipecat.transports.base_transport import TransportParams as _TransportParams -class LengthDistribution(enum.Enum): - uniform = 1 - geometric = 2 - truncated_normal = 3 + +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 new file mode 100644 index 0000000000000000000000000000000000000000..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c --- /dev/null +++ b/nemo/agents/voice_agent/pipecat/transports/network/__init__.py @@ -0,0 +1,13 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..800d9ddb860e40b1c85e19fed32a5fddb9317dad --- /dev/null +++ b/nemo/agents/voice_agent/pipecat/transports/network/websocket_server.py @@ -0,0 +1,304 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c --- /dev/null +++ b/nemo/agents/voice_agent/pipecat/utils/__init__.py @@ -0,0 +1,13 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c --- /dev/null +++ b/nemo/agents/voice_agent/pipecat/utils/text/__init__.py @@ -0,0 +1,13 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..9767ac937d32a926e422b47e851b47b412cfdb19 --- /dev/null +++ b/nemo/agents/voice_agent/pipecat/utils/text/simple_text_aggregator.py @@ -0,0 +1,238 @@ +# 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/collections/vlm/clip/data/__init__.py b/nemo/agents/voice_agent/utils/__init__.py similarity index 83% rename from nemo/collections/vlm/clip/data/__init__.py rename to nemo/agents/voice_agent/utils/__init__.py index 58185aad1fb6ed1c5590a1e82d674e4499bea1f9..928a5f56cce66a05563e4a8c5fab0d0a704e1d98 100644 --- a/nemo/collections/vlm/clip/data/__init__.py +++ b/nemo/agents/voice_agent/utils/__init__.py @@ -11,6 +11,5 @@ # WITHOUT 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.vlm.clip.data.mock import MockDataModule as ClipMockDataModule -__all__ = ['ClipMockDataModule'] +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 new file mode 100644 index 0000000000000000000000000000000000000000..15e8a09bb2429ae5cd11b4f18bd2134eac5ca60e --- /dev/null +++ b/nemo/agents/voice_agent/utils/config_manager.py @@ -0,0 +1,312 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c --- /dev/null +++ b/nemo/agents/voice_agent/utils/tool_calling/__init__.py @@ -0,0 +1,13 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..6e35af85273c48cda5c83b59f7b24ceb17db8f13 --- /dev/null +++ b/nemo/agents/voice_agent/utils/tool_calling/basic_tools.py @@ -0,0 +1,72 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..1024c6dad681d52c8dd9a7c710ae3983646362a1 --- /dev/null +++ b/nemo/agents/voice_agent/utils/tool_calling/mixins.py @@ -0,0 +1,104 @@ +# 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/asr/README.md b/nemo/collections/asr/README.md new file mode 100644 index 0000000000000000000000000000000000000000..27f9472f1ac8963f51c05b9679b2737b3b7daa07 --- /dev/null +++ b/nemo/collections/asr/README.md @@ -0,0 +1,37 @@ +# 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/data/audio_to_diar_label.py b/nemo/collections/asr/data/audio_to_diar_label.py index 817938b758ae22109a6730fbf525b69e2d31158d..72781b4a10bf9fc90fd6a3312a03b1027640b849 100644 --- a/nemo/collections/asr/data/audio_to_diar_label.py +++ b/nemo/collections/asr/data/audio_to_diar_label.py @@ -13,140 +13,18 @@ # limitations under the License. import os -from collections import OrderedDict -from statistics import mode from typing import Dict, List, Optional, Tuple import numpy as np import torch -from nemo.collections.asr.parts.utils.offline_clustering import get_argmin_mat -from nemo.collections.asr.parts.utils.speaker_utils import convert_rttm_line, get_subsegments, prepare_split_data -from nemo.collections.common.parts.preprocessing.collections import ( - DiarizationSpeechLabel, - EndtoEndDiarizationSpeechLabel, -) +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, EncodedRepresentation, LengthsType, NeuralType, ProbsType +from nemo.core.neural_types import AudioSignal, LengthsType, NeuralType, ProbsType from nemo.utils import logging -def get_scale_mapping_list(uniq_timestamps): - """ - Call get_argmin_mat function to find the index of the non-base-scale segment that is closest to the - given base-scale segment. For each scale and each segment, a base-scale segment is assigned. - - Args: - uniq_timestamps: (dict) - The dictionary containing embeddings, timestamps and multiscale weights. - If uniq_timestamps contains only one scale, single scale diarization is performed. - - Returns: - scale_mapping_argmat (torch.tensor): - - The element at the m-th row and the n-th column of the scale mapping matrix indicates the (m+1)-th scale - segment index which has the closest center distance with (n+1)-th segment in the base scale. - - - Example: - `scale_mapping_argmat[2][101] = 85` - - In the above example, the code snippet means that 86-th segment in the 3rd scale (python index is 2) is - mapped to the 102-th segment in the base scale. Thus, the longer segments bound to have more repeating - numbers since multiple base scale segments (since the base scale has the shortest length) fall into the - range of the longer segments. At the same time, each row contains N numbers of indices where N is number - of segments in the base-scale (i.e., the finest scale). - """ - timestamps_in_scales = [] - for key, val in uniq_timestamps['scale_dict'].items(): - timestamps_in_scales.append(torch.tensor(val['time_stamps'])) - session_scale_mapping_list = get_argmin_mat(timestamps_in_scales) - scale_mapping_argmat = [[] for _ in range(len(uniq_timestamps['scale_dict'].keys()))] - for scale_idx in range(len(session_scale_mapping_list)): - scale_mapping_argmat[scale_idx] = session_scale_mapping_list[scale_idx] - scale_mapping_argmat = torch.stack(scale_mapping_argmat) - return scale_mapping_argmat - - -def extract_seg_info_from_rttm(rttm_lines, mapping_dict=None, target_spks=None): - """ - Get RTTM lines containing speaker labels, start time and end time. target_spks contains two targeted - speaker indices for creating groundtruth label files. Only speakers in target_spks variable will be - included in the output lists. - - Args: - uniq_id (str): - Unique file ID that refers to an input audio file and corresponding RTTM (Annotation) file. - rttm_lines (list): - List containing RTTM lines in str format. - mapping_dict (dict): - Mapping between the estimated speakers and the speakers in the ground-truth annotation. - `mapping_dict` variable is only provided when the inference mode is running in sequence-eval mode. - Sequence eval mode uses the mapping between the estimated speakers and the speakers - in ground-truth annotation. - Returns: - rttm_tup (tuple): - Tuple containing lists of start time, end time and speaker labels. - - """ - stt_list, end_list, speaker_list, pairwise_infer_spks = [], [], [], [] - if target_spks: - inv_map = {v: k for k, v in mapping_dict.items()} - for spk_idx in target_spks: - spk_str = f'speaker_{spk_idx}' - if spk_str in inv_map: - pairwise_infer_spks.append(inv_map[spk_str]) - for rttm_line in rttm_lines: - start, end, speaker = convert_rttm_line(rttm_line) - if target_spks is None or speaker in pairwise_infer_spks: - end_list.append(end) - stt_list.append(start) - speaker_list.append(speaker) - rttm_tup = (stt_list, end_list, speaker_list) - return rttm_tup - - -def assign_frame_level_spk_vector(rttm_timestamps, round_digits, frame_per_sec, target_spks, min_spks=2): - """ - 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 - `fr_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. - frame_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: - fr_level_target (torch.tensor): - Tensor containing label for each feature level frame. - """ - stt_list, end_list, speaker_list = rttm_timestamps - if len(speaker_list) == 0: - return None - else: - sorted_speakers = sorted(list(set(speaker_list))) - total_fr_len = int(max(end_list) * (10**round_digits)) - spk_num = max(len(sorted_speakers), min_spks) - speaker_mapping_dict = {rttm_key: x_int for x_int, rttm_key in enumerate(sorted_speakers)} - fr_level_target = torch.zeros(total_fr_len, spk_num) - - # If RTTM is not provided, then there is no speaker mapping dict in target_spks. - # Thus, return a zero-filled tensor as a placeholder. - for count, (stt, end, spk_rttm_key) in enumerate(zip(stt_list, end_list, speaker_list)): - stt, end = round(stt, round_digits), round(end, round_digits) - spk = speaker_mapping_dict[spk_rttm_key] - stt_fr, end_fr = int(round(stt, 2) * frame_per_sec), int(round(end, round_digits) * frame_per_sec) - fr_level_target[stt_fr:end_fr, spk] = 1 - return fr_level_target - - def get_subsegments_to_timestamps( subsegments: List[Tuple[float, float]], feat_per_sec: int = 100, max_end_ts: float = None, decimals=2 ): @@ -281,736 +159,6 @@ def get_frame_targets_from_rttm( return feat_level_target -class _AudioMSDDTrainDataset(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. - multiscale_args_dict (dict): - Dictionary containing the parameters for multiscale segmentation and clustering. - emb_dir (str): - Path to a temporary folder where segmentation information for embedding extraction is saved. - soft_label_thres (float): - Threshold that determines the label of each segment based on RTTM file information. - featurizer: - Featurizer instance for generating features from the raw waveform. - window_stride (float): - Window stride for acoustic feature. This value is used for calculating the numbers of feature-level frames. - emb_batch_size (int): - Number of embedding vectors that are trained with attached computational graphs. - pairwise_infer (bool): - This variable should be True if dataloader is created for an inference task. - random_flip (bool): - If True, the two labels and input signals are randomly flipped per every epoch while training. - """ - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - """Returns definitions of module output ports.""" - output_types = { - "features": NeuralType(('B', 'T'), AudioSignal()), - "feature_length": NeuralType(('B'), LengthsType()), - "ms_seg_timestamps": NeuralType(('B', 'C', 'T', 'D'), LengthsType()), - "ms_seg_counts": NeuralType(('B', 'C'), LengthsType()), - "clus_label_index": NeuralType(('B', 'T'), LengthsType()), - "scale_mapping": NeuralType(('B', 'C', 'T'), LengthsType()), - "targets": NeuralType(('B', 'T', 'C'), ProbsType()), - } - - return output_types - - def __init__( - self, - *, - manifest_filepath: str, - multiscale_args_dict: str, - emb_dir: str, - soft_label_thres: float, - featurizer, - window_stride, - emb_batch_size, - pairwise_infer: bool, - random_flip: bool = True, - global_rank: int = 0, - ): - super().__init__() - self.collection = DiarizationSpeechLabel( - manifests_files=manifest_filepath.split(','), - emb_dict=None, - clus_label_dict=None, - pairwise_infer=pairwise_infer, - ) - self.featurizer = featurizer - self.multiscale_args_dict = multiscale_args_dict - self.emb_dir = emb_dir - self.round_digits = 2 - self.decim = 10**self.round_digits - self.soft_label_thres = soft_label_thres - self.pairwise_infer = pairwise_infer - self.max_spks = 2 - self.frame_per_sec = int(1 / window_stride) - self.emb_batch_size = emb_batch_size - self.random_flip = random_flip - self.global_rank = global_rank - self.manifest_filepath = manifest_filepath - self.multiscale_timestamp_dict = prepare_split_data( - self.manifest_filepath, - self.emb_dir, - self.multiscale_args_dict, - self.global_rank, - ) - - def __len__(self): - return len(self.collection) - - def assign_labels_to_longer_segs(self, uniq_id, base_scale_clus_label): - """ - Assign the generated speaker labels from the base scale (the finest scale) to the longer scales. - This process is needed to get the cluster labels for each scale. The cluster labels are needed to - calculate the cluster-average speaker embedding for each scale. - - Args: - uniq_id (str): - Unique sample ID for training. - base_scale_clus_label (torch.tensor): - Tensor variable containing the speaker labels for the base-scale segments. - - Returns: - per_scale_clus_label (torch.tensor): - Tensor variable containing the speaker labels for each segment in each scale. - Note that the total length of the speaker label sequence differs over scale since - each scale has a different number of segments for the same session. - - scale_mapping (torch.tensor): - Matrix containing the segment indices of each scale. scale_mapping is necessary for reshaping the - multiscale embeddings to form an input matrix for the MSDD model. - """ - per_scale_clus_label = [] - self.scale_n = len(self.multiscale_timestamp_dict[uniq_id]['scale_dict']) - uniq_scale_mapping = get_scale_mapping_list(self.multiscale_timestamp_dict[uniq_id]) - for scale_index in range(self.scale_n): - new_clus_label = [] - scale_seq_len = len(self.multiscale_timestamp_dict[uniq_id]["scale_dict"][scale_index]["time_stamps"]) - for seg_idx in range(scale_seq_len): - if seg_idx in uniq_scale_mapping[scale_index]: - seg_clus_label = mode(base_scale_clus_label[uniq_scale_mapping[scale_index] == seg_idx]) - else: - seg_clus_label = 0 if len(new_clus_label) == 0 else new_clus_label[-1] - new_clus_label.append(seg_clus_label) - per_scale_clus_label.extend(new_clus_label) - per_scale_clus_label = torch.tensor(per_scale_clus_label) - return per_scale_clus_label, uniq_scale_mapping - - def get_diar_target_labels(self, uniq_id, sample, fr_level_target): - """ - Convert frame-level diarization target variable into segment-level target variable. - Since the granularity is reduced from frame level (10ms) to segment level (100ms~500ms), - we need a threshold value, `soft_label_thres`, which determines the label of each segment - based on the overlap between a segment range (start and end time) and the frame-level target variable. - - Args: - uniq_id (str): - Unique file ID that refers to an input audio file and corresponding RTTM (Annotation) file. - sample: - `DiarizationSpeechLabel` instance containing sample information such as - audio filepath and RTTM filepath. - fr_level_target (torch.tensor): - Tensor containing label for each feature-level frame. - - Returns: - seg_target (torch.tensor): - Tensor containing binary speaker labels for base-scale segments. - base_clus_label (torch.tensor): - Representative speaker label for each segment. This variable only has one speaker label - for each base-scale segment. - -1 means that there is no corresponding speaker in the target_spks tuple. - """ - seg_target_list, base_clus_label = [], [] - self.scale_n = len(self.multiscale_timestamp_dict[uniq_id]['scale_dict']) - subseg_time_stamp_list = self.multiscale_timestamp_dict[uniq_id]["scale_dict"][self.scale_n - 1]["time_stamps"] - for seg_stt, seg_end in subseg_time_stamp_list: - seg_stt_fr, seg_end_fr = int(seg_stt * self.frame_per_sec), int(seg_end * self.frame_per_sec) - soft_label_vec_sess = torch.sum(fr_level_target[seg_stt_fr:seg_end_fr, :], axis=0) / ( - seg_end_fr - seg_stt_fr - ) - label_int_sess = torch.argmax(soft_label_vec_sess) - soft_label_vec = soft_label_vec_sess.unsqueeze(0)[:, sample.target_spks].squeeze() - if label_int_sess in sample.target_spks and torch.sum(soft_label_vec_sess) > 0: - label_int = sample.target_spks.index(label_int_sess) - else: - label_int = -1 - label_vec = (soft_label_vec > self.soft_label_thres).float() - seg_target_list.append(label_vec.detach()) - base_clus_label.append(label_int) - seg_target = torch.stack(seg_target_list) - base_clus_label = torch.tensor(base_clus_label) - return seg_target, base_clus_label - - def parse_rttm_for_ms_targets(self, sample): - """ - 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.]] - - Args: - sample: - `DiarizationSpeechLabel` instance containing sample information such as - audio filepath and RTTM filepath. - target_spks (tuple): - Speaker indices that are generated from combinations. If there are only one or two speakers, - only a single target_spks tuple is generated. - - Returns: - clus_label_index (torch.tensor): - Groundtruth clustering label (cluster index for each segment) from RTTM files for training purpose. - seg_target (torch.tensor): - Tensor variable containing hard-labels of speaker activity in each base-scale segment. - scale_mapping (torch.tensor): - Matrix containing the segment indices of each scale. scale_mapping is necessary for reshaping the - multiscale embeddings to form an input matrix for the MSDD model. - - """ - with open(sample.rttm_file, 'r') as file: - rttm_lines = file.readlines() - uniq_id = self.get_uniq_id_with_range(sample) - rttm_timestamps = extract_seg_info_from_rttm(rttm_lines) - fr_level_target = assign_frame_level_spk_vector( - rttm_timestamps, self.round_digits, self.frame_per_sec, target_spks=sample.target_spks - ) - seg_target, base_clus_label = self.get_diar_target_labels(uniq_id, sample, fr_level_target) - clus_label_index, scale_mapping = self.assign_labels_to_longer_segs(uniq_id, base_clus_label) - return clus_label_index, seg_target, scale_mapping - - 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: - `DiarizationSpeechLabel` 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 get_ms_seg_timestamps(self, sample): - """ - Get start and end time of each diarization frame. - - Args: - sample: - `DiarizationSpeechLabel` instance from preprocessing.collections - Returns: - ms_seg_timestamps (torch.tensor): - Tensor containing timestamps for each frame. - ms_seg_counts (torch.tensor): - Number of segments for each scale. This information is used for reshaping embedding batch - during forward propagation. - """ - uniq_id = self.get_uniq_id_with_range(sample) - ms_seg_timestamps_list = [] - max_seq_len = len(self.multiscale_timestamp_dict[uniq_id]["scale_dict"][self.scale_n - 1]["time_stamps"]) - ms_seg_counts = [0 for _ in range(self.scale_n)] - for scale_idx in range(self.scale_n): - scale_ts_list = [] - for k, (seg_stt, seg_end) in enumerate( - self.multiscale_timestamp_dict[uniq_id]["scale_dict"][scale_idx]["time_stamps"] - ): - stt, end = ( - int((seg_stt - sample.offset) * self.frame_per_sec), - int((seg_end - sample.offset) * self.frame_per_sec), - ) - scale_ts_list.append(torch.tensor([stt, end]).detach()) - ms_seg_counts[scale_idx] = len( - self.multiscale_timestamp_dict[uniq_id]["scale_dict"][scale_idx]["time_stamps"] - ) - scale_ts = torch.stack(scale_ts_list) - scale_ts_padded = torch.cat([scale_ts, torch.zeros(max_seq_len - len(scale_ts_list), 2)], dim=0) - ms_seg_timestamps_list.append(scale_ts_padded.detach()) - ms_seg_timestamps = torch.stack(ms_seg_timestamps_list) - ms_seg_counts = torch.tensor(ms_seg_counts) - return ms_seg_timestamps, ms_seg_counts - - def __getitem__(self, index): - sample = self.collection[index] - if sample.offset is None: - sample.offset = 0 - clus_label_index, targets, scale_mapping = self.parse_rttm_for_ms_targets(sample) - features = self.featurizer.process(sample.audio_file, offset=sample.offset, duration=sample.duration) - feature_length = torch.tensor(features.shape[0]).long() - ms_seg_timestamps, ms_seg_counts = self.get_ms_seg_timestamps(sample) - if self.random_flip: - torch.manual_seed(index) - flip = torch.cat([torch.randperm(self.max_spks), torch.tensor(-1).unsqueeze(0)]) - clus_label_index, targets = flip[clus_label_index], targets[:, flip[: self.max_spks]] - return features, feature_length, ms_seg_timestamps, ms_seg_counts, clus_label_index, scale_mapping, targets - - -class _AudioMSDDInferDataset(Dataset): - """ - Dataset class that loads a json file containing paths to audio files, - RTTM files and number of speakers. This Dataset class is built for diarization inference and - evaluation. Speaker embedding sequences, segment timestamps, cluster-average speaker embeddings - are loaded from memory and fed into the dataloader. - - 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. - emb_dict (dict): - Dictionary containing cluster-average embeddings and speaker mapping information. - emb_seq (dict): - Dictionary containing multiscale speaker embedding sequence, - scale mapping and corresponding segment timestamps. - clus_label_dict (dict): - Subsegment-level (from base-scale) speaker labels from clustering results. - soft_label_thres (float): - A threshold that determines the label of each segment based on RTTM file information. - featurizer: - Featurizer instance for generating features from raw waveform. - seq_eval_mode (bool): - If True, F1 score will be calculated for each speaker pair during inference mode. - window_stride (float): - Window stride for acoustic feature. This value is used for calculating the numbers of feature-level frames. - use_single_scale_clus (bool): - Use only one scale for clustering instead of using multiple scales of embeddings for clustering. - pairwise_infer (bool): - This variable should be True if dataloader is created for an inference task. - """ - - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - """Returns definitions of module output ports.""" - output_types = OrderedDict( - { - "ms_emb_seq": NeuralType(('B', 'T', 'C', 'D'), SpectrogramType()), - "length": NeuralType(tuple('B'), LengthsType()), - "ms_avg_embs": NeuralType(('B', 'C', 'D', 'C'), EncodedRepresentation()), - "targets": NeuralType(('B', 'T', 'C'), ProbsType()), - } - ) - return output_types - - def __init__( - self, - *, - manifest_filepath: str, - emb_dict: Dict, - emb_seq: Dict, - clus_label_dict: Dict, - soft_label_thres: float, - seq_eval_mode: bool, - window_stride: float, - use_single_scale_clus: bool, - pairwise_infer: bool, - ): - super().__init__() - self.collection = DiarizationSpeechLabel( - manifests_files=manifest_filepath.split(','), - emb_dict=emb_dict, - clus_label_dict=clus_label_dict, - seq_eval_mode=seq_eval_mode, - pairwise_infer=pairwise_infer, - ) - self.emb_dict = emb_dict - self.emb_seq = emb_seq - self.clus_label_dict = clus_label_dict - self.round_digits = 2 - self.decim = 10**self.round_digits - self.frame_per_sec = int(1 / window_stride) - self.soft_label_thres = soft_label_thres - self.pairwise_infer = pairwise_infer - self.max_spks = 2 - self.use_single_scale_clus = use_single_scale_clus - self.seq_eval_mode = seq_eval_mode - - def __len__(self): - return len(self.collection) - - def parse_rttm_multiscale(self, sample): - """ - Generate target tensor variable by extracting groundtruth diarization labels from an RTTM file. - This function is only used when ``self.seq_eval_mode=True`` and RTTM files are provided. This function converts - (start, end, speaker_id) format into base-scale (the finest scale) segment level diarization label in a matrix - form to create target matrix. - - Args: - sample: - DiarizationSpeechLabel instance containing sample information such as audio filepath and RTTM filepath. - target_spks (tuple): - Two Indices of targeted speakers for evaluation. - Example of target_spks: (2, 3) - Returns: - seg_target (torch.tensor): - Tensor variable containing hard-labels of speaker activity in each base-scale segment. - """ - if sample.rttm_file is None: - raise ValueError(f"RTTM file is not provided for this sample {sample}") - rttm_lines = open(sample.rttm_file).readlines() - uniq_id = os.path.splitext(os.path.basename(sample.rttm_file))[0] - mapping_dict = self.emb_dict[max(self.emb_dict.keys())][uniq_id]['mapping'] - rttm_timestamps = extract_seg_info_from_rttm(rttm_lines, mapping_dict, sample.target_spks) - fr_level_target = assign_frame_level_spk_vector( - rttm_timestamps, self.round_digits, self.frame_per_sec, sample.target_spks - ) - seg_target = self.get_diar_target_labels_from_fr_target(uniq_id, fr_level_target) - return seg_target - - def get_diar_target_labels_from_fr_target(self, uniq_id: str, fr_level_target: torch.Tensor) -> torch.Tensor: - """ - Generate base-scale level binary diarization label from frame-level target matrix. For the given frame-level - speaker target matrix fr_level_target, we count the number of frames that belong to each speaker and calculate - ratios for each speaker into the `soft_label_vec` variable. Finally, `soft_label_vec` variable is compared - with `soft_label_thres` to determine whether a label vector should contain 0 or 1 for each speaker bin. - Note that seg_target variable has dimension of (number of base-scale segments x 2) dimension. - - Example of seg_target: - [[0., 1.], [0., 1.], [1., 1.], [1., 0.], [1., 0.], ..., [0., 1.]] - - Args: - uniq_id (str): - Unique file ID that refers to an input audio file and corresponding RTTM (Annotation) file. - fr_level_target (torch.tensor): - frame-level binary speaker annotation (1: exist 0: non-exist) generated from RTTM file. - - Returns: - seg_target (torch.tensor): - Tensor variable containing binary hard-labels of speaker activity in each base-scale segment. - - """ - if fr_level_target is None: - return None - else: - seg_target_list = [] - for seg_stt, seg_end, label_int in self.clus_label_dict[uniq_id]: - seg_stt_fr, seg_end_fr = int(seg_stt * self.frame_per_sec), int(seg_end * self.frame_per_sec) - soft_label_vec = torch.sum(fr_level_target[seg_stt_fr:seg_end_fr, :], axis=0) / ( - seg_end_fr - seg_stt_fr - ) - label_vec = (soft_label_vec > self.soft_label_thres).int() - seg_target_list.append(label_vec) - seg_target = torch.stack(seg_target_list) - return seg_target - - def __getitem__(self, index): - sample = self.collection[index] - if sample.offset is None: - sample.offset = 0 - - uniq_id = os.path.splitext(os.path.basename(sample.audio_file))[0] - scale_n = len(self.emb_dict.keys()) - _avg_embs = torch.stack([self.emb_dict[scale_index][uniq_id]['avg_embs'] for scale_index in range(scale_n)]) - - if self.pairwise_infer: - avg_embs = _avg_embs[:, :, self.collection[index].target_spks] - else: - avg_embs = _avg_embs - - if avg_embs.shape[2] > self.max_spks: - raise ValueError( - f" avg_embs.shape[2] {avg_embs.shape[2]} should be less than or equal to " - f"self.max_num_speakers {self.max_spks}" - ) - - feats = [] - for scale_index in range(scale_n): - repeat_mat = self.emb_seq["session_scale_mapping"][uniq_id][scale_index] - feats.append(self.emb_seq[scale_index][uniq_id][repeat_mat, :]) - feats_out = torch.stack(feats).permute(1, 0, 2) - feats_len = feats_out.shape[0] - - if self.seq_eval_mode: - targets = self.parse_rttm_multiscale(sample) - else: - targets = torch.zeros(feats_len, 2).float() - - return feats_out, feats_len, targets, avg_embs - - -def _msdd_train_collate_fn(self, batch): - """ - Collate batch of variables that are needed for raw waveform to diarization label training. - The following variables are included in training/validation batch: - - Args: - batch (tuple): - Batch tuple containing the variables for the diarization training. - Returns: - features (torch.tensor): - Raw waveform samples (time series) loaded from the audio_filepath in the input manifest file. - feature lengths (time series sample length): - A list of lengths of the raw waveform samples. - ms_seg_timestamps (torch.tensor): - Matrix containing the start time and end time (timestamps) for each segment and each scale. - ms_seg_timestamps is needed for extracting acoustic features from raw waveforms. - ms_seg_counts (torch.tensor): - Matrix containing The number of segments for each scale. ms_seg_counts is necessary for reshaping - the input matrix for the MSDD model. - clus_label_index (torch.tensor): - Groundtruth Clustering label (cluster index for each segment) from RTTM files for training purpose. - clus_label_index is necessary for calculating cluster-average embedding. - scale_mapping (torch.tensor): - Matrix containing the segment indices of each scale. scale_mapping is necessary for reshaping the - multiscale embeddings to form an input matrix for the MSDD model. - targets (torch.tensor): - Groundtruth Speaker label for the given input embedding sequence. - """ - packed_batch = list(zip(*batch)) - features, feature_length, ms_seg_timestamps, ms_seg_counts, clus_label_index, scale_mapping, targets = packed_batch - features_list, feature_length_list = [], [] - ms_seg_timestamps_list, ms_seg_counts_list, scale_clus_label_list, scale_mapping_list, targets_list = ( - [], - [], - [], - [], - [], - ) - - max_raw_feat_len = max([x.shape[0] for x in features]) - max_target_len = max([x.shape[0] for x in targets]) - max_total_seg_len = max([x.shape[0] for x in clus_label_index]) - - for feat, feat_len, ms_seg_ts, ms_seg_ct, scale_clus, scl_map, tgt in batch: - seq_len = tgt.shape[0] - pad_feat = (0, max_raw_feat_len - feat_len) - pad_tgt = (0, 0, 0, max_target_len - seq_len) - pad_sm = (0, max_target_len - seq_len) - pad_ts = (0, 0, 0, max_target_len - seq_len) - pad_sc = (0, max_total_seg_len - scale_clus.shape[0]) - padded_feat = torch.nn.functional.pad(feat, pad_feat) - padded_tgt = torch.nn.functional.pad(tgt, pad_tgt) - padded_sm = torch.nn.functional.pad(scl_map, pad_sm) - padded_ms_seg_ts = torch.nn.functional.pad(ms_seg_ts, pad_ts) - padded_scale_clus = torch.nn.functional.pad(scale_clus, pad_sc) - - features_list.append(padded_feat) - feature_length_list.append(feat_len.clone().detach()) - ms_seg_timestamps_list.append(padded_ms_seg_ts) - ms_seg_counts_list.append(ms_seg_ct.clone().detach()) - scale_clus_label_list.append(padded_scale_clus) - scale_mapping_list.append(padded_sm) - targets_list.append(padded_tgt) - - features = torch.stack(features_list) - feature_length = torch.stack(feature_length_list) - ms_seg_timestamps = torch.stack(ms_seg_timestamps_list) - clus_label_index = torch.stack(scale_clus_label_list) - ms_seg_counts = torch.stack(ms_seg_counts_list) - scale_mapping = torch.stack(scale_mapping_list) - targets = torch.stack(targets_list) - return features, feature_length, ms_seg_timestamps, ms_seg_counts, clus_label_index, scale_mapping, targets - - -def _msdd_infer_collate_fn(self, batch): - """ - Collate batch of feats (speaker embeddings), feature lengths, target label sequences - and cluster-average embeddings. - - Args: - batch (tuple): - Batch tuple containing feats, feats_len, targets and ms_avg_embs. - Returns: - feats (torch.tensor): - Collated speaker embedding with unified length. - feats_len (torch.tensor): - The actual length of each embedding sequence without zero padding. - targets (torch.tensor): - Groundtruth Speaker label for the given input embedding sequence. - ms_avg_embs (torch.tensor): - Cluster-average speaker embedding vectors. - """ - - packed_batch = list(zip(*batch)) - feats, feats_len, targets, ms_avg_embs = packed_batch - feats_list, flen_list, targets_list, ms_avg_embs_list = [], [], [], [] - max_audio_len = max(feats_len) - max_target_len = max([x.shape[0] for x in targets]) - - for feature, feat_len, target, ivector in batch: - flen_list.append(feat_len) - ms_avg_embs_list.append(ivector) - if feat_len < max_audio_len: - pad_a = (0, 0, 0, 0, 0, max_audio_len - feat_len) - pad_t = (0, 0, 0, max_target_len - target.shape[0]) - padded_feature = torch.nn.functional.pad(feature, pad_a) - padded_target = torch.nn.functional.pad(target, pad_t) - feats_list.append(padded_feature) - targets_list.append(padded_target) - else: - targets_list.append(target.clone().detach()) - feats_list.append(feature.clone().detach()) - - feats = torch.stack(feats_list) - feats_len = torch.tensor(flen_list) - targets = torch.stack(targets_list) - ms_avg_embs = torch.stack(ms_avg_embs_list) - return feats, feats_len, targets, ms_avg_embs - - -class AudioToSpeechMSDDTrainDataset(_AudioMSDDTrainDataset): - """ - 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. - multiscale_args_dict (dict): - Dictionary containing the parameters for multiscale segmentation and clustering. - emb_dir (str): - Path to a temporary folder where segmentation information for embedding extraction is saved. - soft_label_thres (float): - A threshold that determines the label of each segment based on RTTM file information. - featurizer: - Featurizer instance for generating features from the raw waveform. - window_stride (float): - Window stride for acoustic feature. This value is used for calculating the numbers of feature-level frames. - emb_batch_size (int): - Number of embedding vectors that are trained with attached computational graphs. - pairwise_infer (bool): - This variable should be True if dataloader is created for an inference task. - """ - - def __init__( - self, - *, - manifest_filepath: str, - multiscale_args_dict: Dict, - emb_dir: str, - soft_label_thres: float, - featurizer, - window_stride, - emb_batch_size, - pairwise_infer: bool, - global_rank: int, - ): - super().__init__( - manifest_filepath=manifest_filepath, - multiscale_args_dict=multiscale_args_dict, - emb_dir=emb_dir, - soft_label_thres=soft_label_thres, - featurizer=featurizer, - window_stride=window_stride, - emb_batch_size=emb_batch_size, - pairwise_infer=pairwise_infer, - global_rank=global_rank, - ) - - def msdd_train_collate_fn(self, batch): - """Collate batch of audio features, feature lengths, target label sequences for training.""" - return _msdd_train_collate_fn(self, batch) - - -class AudioToSpeechMSDDInferDataset(_AudioMSDDInferDataset): - """ - Dataset class that loads a json file containing paths to audio files, - rttm files and number of speakers. The created labels are used for diarization inference. - - 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. - emb_dict (dict): - Dictionary containing cluster-average embeddings and speaker mapping information. - emb_seq (dict): - Dictionary containing multiscale speaker embedding sequence, scale mapping - and corresponding segment timestamps. - clus_label_dict (dict): - Subsegment-level (from base-scale) speaker labels from clustering results. - soft_label_thres (float): - Threshold that determines speaker labels of segments depending on the overlap - with groundtruth speaker timestamps. - featurizer: - Featurizer instance for generating features from raw waveform. - use_single_scale_clus (bool): - Use only one scale for clustering instead of using multiple scales of embeddings for clustering. - seq_eval_mode (bool): - If True, F1 score will be calculated for each speaker pair during inference mode. - window_stride (float): - Window stride for acoustic feature. This value is used for calculating the numbers of - feature-level frames. - pairwise_infer (bool): - If True, this Dataset class operates in inference mode. In inference mode, a set of speakers - in the input audio is split into multiple pairs of speakers and speaker tuples - (e.g. 3 speakers: [(0,1), (1,2), (0,2)]) and then fed into the MSDD to merge the individual results. - """ - - def __init__( - self, - *, - manifest_filepath: str, - emb_dict: Dict, - emb_seq: Dict, - clus_label_dict: Dict, - soft_label_thres: float, - use_single_scale_clus: bool, - seq_eval_mode: bool, - window_stride: float, - pairwise_infer: bool, - ): - super().__init__( - manifest_filepath=manifest_filepath, - emb_dict=emb_dict, - emb_seq=emb_seq, - clus_label_dict=clus_label_dict, - soft_label_thres=soft_label_thres, - use_single_scale_clus=use_single_scale_clus, - window_stride=window_stride, - seq_eval_mode=seq_eval_mode, - pairwise_infer=pairwise_infer, - ) - - def msdd_infer_collate_fn(self, batch): - """Collate batch of audio features, feature lengths, target label sequences for inference.""" - return _msdd_infer_collate_fn(self, batch) - - class _AudioToSpeechE2ESpkDiarDataset(Dataset): """ Dataset class that loads a json file containing paths to audio files, @@ -1058,6 +206,7 @@ class _AudioToSpeechE2ESpkDiarDataset(Dataset): session_len_sec: float, num_spks: int, featurizer, + fb_featurizer, window_stride: float, min_subsegment_duration: float = 0.03, global_rank: int = 0, @@ -1073,6 +222,13 @@ class _AudioToSpeechE2ESpkDiarDataset(Dataset): 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) @@ -1086,10 +242,30 @@ class _AudioToSpeechE2ESpkDiarDataset(Dataset): 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 @@ -1098,7 +274,7 @@ class _AudioToSpeechE2ESpkDiarDataset(Dataset): Args: sample: - `DiarizationSpeechLabel` instance from collections. + `EndtoEndDiarizationSpeechLabel` instance from collections. Returns: uniq_id (str): @@ -1188,7 +364,7 @@ class _AudioToSpeechE2ESpkDiarDataset(Dataset): Args: sample: - `DiarizationSpeechLabel` instance from preprocessing.collections + `EndtoEndDiarizationSpeechLabel` instance from preprocessing.collections Returns: segment_timestamps (torch.tensor): Tensor containing Multiscale segment timestamps. @@ -1238,10 +414,15 @@ class _AudioToSpeechE2ESpkDiarDataset(Dataset): ) 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 @@ -1357,6 +538,7 @@ class AudioToSpeechE2ESpkDiarDataset(_AudioToSpeechE2ESpkDiarDataset): session_len_sec: float, num_spks: int, featurizer, + fb_featurizer, window_stride, global_rank: int, soft_targets: bool, @@ -1368,6 +550,7 @@ class AudioToSpeechE2ESpkDiarDataset(_AudioToSpeechE2ESpkDiarDataset): 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, diff --git a/nemo/collections/asr/data/audio_to_diar_label_lhotse.py b/nemo/collections/asr/data/audio_to_diar_label_lhotse.py index 6b9a687013a2326ab91da72f0c6d6b24bed983d9..e35780ec23eae5bbe42f3aece33ecac1115e70aa 100644 --- a/nemo/collections/asr/data/audio_to_diar_label_lhotse.py +++ b/nemo/collections/asr/data/audio_to_diar_label_lhotse.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -23,6 +23,7 @@ from nemo.collections.asr.parts.utils.asr_multispeaker_utils import ( speaker_to_target, ) from nemo.core.neural_types import AudioSignal, LabelsType, LengthsType, NeuralType +from nemo.utils import logging class LhotseAudioToSpeechE2ESpkDiarDataset(torch.utils.data.Dataset): @@ -55,22 +56,53 @@ class LhotseAudioToSpeechE2ESpkDiarDataset(torch.utils.data.Dataset): 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)) - self.spk_tar_all_zero = self.cfg.get('spk_tar_all_zero', False) def __getitem__(self, cuts) -> Tuple[torch.Tensor, ...]: - audio, audio_lens, cuts = self.load_audio(cuts) + # 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=cut, + 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, - spk_tar_all_zero=self.spk_tar_all_zero, 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) - targets = collate_matrices(speaker_activities).to(audio.dtype) + + 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( diff --git a/nemo/collections/asr/data/audio_to_eou_label_lhotse.py b/nemo/collections/asr/data/audio_to_eou_label_lhotse.py new file mode 100644 index 0000000000000000000000000000000000000000..725ccd994f04da2ac8a169d902ea7a85e8c2e630 --- /dev/null +++ b/nemo/collections/asr/data/audio_to_eou_label_lhotse.py @@ -0,0 +1,524 @@ +# 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 index 8dd65e3fa17a710042ce2af4742f2275cb738cf7..c7402e3085b3442b51dc416d1e7feca3b76c53b8 100644 --- a/nemo/collections/asr/data/audio_to_label.py +++ b/nemo/collections/asr/data/audio_to_label.py @@ -16,7 +16,6 @@ import os from typing import Dict, List, Optional, Union import torch -import webdataset as wds from nemo.collections.asr.data.audio_to_text import cache_datastore_manifests, expand_sharded_filepaths from nemo.collections.asr.parts.preprocessing.features import WaveformFeaturizer @@ -25,6 +24,7 @@ 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) @@ -587,6 +587,7 @@ class _TarredAudioLabelDataset(IterableDataset): world_size=world_size, global_rank=global_rank, ) + # Put together WebDataset self._dataset = wds.DataPipeline( wds.SimpleShardList(urls=audio_tar_filepaths), @@ -1193,6 +1194,7 @@ class TarredAudioToMultiLabelDataset(IterableDataset): world_size=world_size, global_rank=global_rank, ) + # Put together WebDataset self._dataset = wds.DataPipeline( wds.SimpleShardList(urls=audio_tar_filepaths), diff --git a/nemo/collections/asr/data/audio_to_text.py b/nemo/collections/asr/data/audio_to_text.py index 224ae4143bd2f826781e7c710c0640340899ddf9..4fb18dedbd92f63fbfa57d9c84be1a9c6c661b65 100644 --- a/nemo/collections/asr/data/audio_to_text.py +++ b/nemo/collections/asr/data/audio_to_text.py @@ -22,7 +22,6 @@ from typing import Callable, Dict, Iterable, List, Optional, Tuple, Union import braceexpand import numpy as np import torch -import webdataset as wds from torch.utils.data import ChainDataset from tqdm import tqdm @@ -34,14 +33,8 @@ 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.data_utils import ( - DataStoreObject, - datastore_object_get, - datastore_path_to_webdataset_url, - is_datastore_cache_shared, - is_datastore_path, - is_tarred_path, -) +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 @@ -209,12 +202,6 @@ def expand_sharded_filepaths(sharded_filepaths, shard_strategy: str, world_size: # Brace expand, set escape=False for Windows compatibility sharded_filepaths = list(braceexpand.braceexpand(sharded_filepaths, escape=False)) - # Expand store paths into WebDataset URLs - sharded_filepaths = [ - datastore_path_to_webdataset_url(p) if is_datastore_path(p) and is_tarred_path(p) else p - for p in sharded_filepaths - ] - # Check for distributed and partition shards accordingly if world_size > 1: if shard_strategy == 'scatter': @@ -949,9 +936,7 @@ class _TarredAudioToTextDataset(IterableDataset): self.current_bytes, self.current_fn = next(self.iterator) self.offset_id = 0 else: - import os - file_id, _ = os.path.splitext(os.path.basename(self.current_fn)) - offset_list = self.collection.mapping[file_id] + 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 diff --git a/nemo/collections/asr/data/audio_to_text_dali.py b/nemo/collections/asr/data/audio_to_text_dali.py index 77bd71129cc2b31debbb4400acecab99b50aa264..e7fba35ce27cef21f663c24d135d86f9deb57376 100644 --- a/nemo/collections/asr/data/audio_to_text_dali.py +++ b/nemo/collections/asr/data/audio_to_text_dali.py @@ -300,9 +300,7 @@ class _AudioTextDALIDataset(Iterator): f"'clamp'." ) - self.log_zero_guard_value = ( - params['log_zero_guard_value'] if 'log_zero_guard_value' in params else 2 ** -24 - ) + 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 @@ -346,8 +344,12 @@ class _AudioTextDALIDataset(Iterator): 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_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, @@ -374,7 +376,10 @@ class _AudioTextDALIDataset(Iterator): pad_last_batch=True, ) audio, _ = dali.fn.decoders.audio( - tar_file, dtype=dali.types.FLOAT, downmix=True, sample_rate=float(self.sample_rate), + 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) @@ -446,7 +451,7 @@ class _AudioTextDALIDataset(Iterator): ) # Normalization - spec = dali.fn.normalize(spec, axes=self.normalization_axes, epsilon=1e-5 ** 2, ddof=1) + 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,)) diff --git a/nemo/collections/asr/data/audio_to_text_dataset.py b/nemo/collections/asr/data/audio_to_text_dataset.py index 3e1301dd4d538222d2f66f694307817b010770ea..afb7a86a5f0e81ca7684f04571a16efc89163d04 100644 --- a/nemo/collections/asr/data/audio_to_text_dataset.py +++ b/nemo/collections/asr/data/audio_to_text_dataset.py @@ -18,7 +18,9 @@ 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 @@ -29,8 +31,9 @@ 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 process_augmentations +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 @@ -94,7 +97,7 @@ def get_concat_char_dataset( An instance of ConcatDataset containing one or more instances of AudioToCharDataset. """ if 'labels' not in config: - logging.warning(f"dataset does not have explicitly defined labels") + logging.warning("dataset does not have explicitly defined labels") manifest_filepaths = config['manifest_filepath'] datasets = [] @@ -138,7 +141,7 @@ def get_char_dataset(config: dict, augmentor: Optional['AudioAugmentor'] = None) An instance of AudioToCharDataset. """ if 'labels' not in config: - logging.warning(f"dataset does not have explicitly defined labels") + logging.warning("dataset does not have explicitly defined labels") dataset = audio_to_text.AudioToCharDataset( manifest_filepath=config['manifest_filepath'], @@ -332,7 +335,7 @@ def get_tarred_dataset( 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") + raise ValueError("bucket weights must be positive integers") if len(manifest_filepaths) != len(tarred_audio_filepaths): raise ValueError( @@ -340,10 +343,10 @@ def get_tarred_dataset( ) if 'labels' not in config: - logging.warning(f"dataset does not have explicitly defined labels") + logging.warning("dataset does not have explicitly defined labels") if 'max_utts' in config: - raise ValueError('"max_utts" parameter is not supported for tarred datasets') + 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) @@ -861,7 +864,7 @@ class ASRPredictionWriter(BasePredictionWriter): ): import lhotse - for sample_id, transcribed_text in prediction: + for sample_id, hypotheses in prediction: item = {} if isinstance(sample_id, lhotse.cut.Cut): sample = sample_id @@ -876,18 +879,29 @@ class ASRPredictionWriter(BasePredictionWriter): item["text"] = sample.supervisions[0].text or '' if hasattr(sample, 'shard_id'): item["shard_id"] = sample.shard_id - item["pred_text"] = transcribed_text - self.outf.write(json.dumps(item) + "\n") - self.samples_num += 1 + 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"] = transcribed_text - self.outf.write(json.dumps(item) + "\n") - self.samples_num += 1 + 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): diff --git a/nemo/collections/asr/data/audio_to_text_lhotse.py b/nemo/collections/asr/data/audio_to_text_lhotse.py index 0cec70174bc8a96f57010ad8e8c2a80d9b2891a1..46c301be082254a6fc087b84261a45efbaae1b23 100644 --- a/nemo/collections/asr/data/audio_to_text_lhotse.py +++ b/nemo/collections/asr/data/audio_to_text_lhotse.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -12,6 +12,7 @@ # 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 @@ -31,6 +32,11 @@ class LhotseSpeechToTextBpeDataset(torch.utils.data.Dataset): 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 @@ -46,7 +52,22 @@ class LhotseSpeechToTextBpeDataset(torch.utils.data.Dataset): def __init__(self, tokenizer: TokenizerSpec, return_cuts: bool = False): super().__init__() self.tokenizer = TokenizerWrapper(tokenizer) - self.load_audio = AudioSamples(fault_tolerant=True) + 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, ...]: diff --git a/nemo/collections/asr/data/audio_to_text_lhotse_prompt.py b/nemo/collections/asr/data/audio_to_text_lhotse_prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..181825b34372d5c3016a8f43d78d2baa401ada38 --- /dev/null +++ b/nemo/collections/asr/data/audio_to_text_lhotse_prompt.py @@ -0,0 +1,177 @@ +# 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 index 1bb1410555d664ae7a407967c92ab0405be6d241..a3510a78836a47f137a2c70e0de9875feef3b590 100644 --- a/nemo/collections/asr/data/audio_to_text_lhotse_prompted.py +++ b/nemo/collections/asr/data/audio_to_text_lhotse_prompted.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -11,8 +11,9 @@ # WITHOUT 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 Callable, Optional, Union +from typing import Optional, Union import torch.utils.data from lhotse import CutSet @@ -21,7 +22,7 @@ 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 CanaryPromptFormatter, PromptFormatter +from nemo.collections.common.prompts import PromptFormatter from nemo.collections.common.tokenizers import TokenizerSpec @@ -61,23 +62,68 @@ class PromptedAudioToTextLhotseDataset(torch.utils.data.Dataset): 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.load_audio = AudioSamples(fault_tolerant=True) + 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) - # Fast-path: the tokenization and prompt formatting was already done before sampling. + # 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: @@ -110,6 +156,93 @@ class PromptedAudioToTextLhotseDataset(torch.utils.data.Dataset): 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 diff --git a/nemo/collections/asr/data/audio_to_text_lhotse_speaker.py b/nemo/collections/asr/data/audio_to_text_lhotse_speaker.py new file mode 100644 index 0000000000000000000000000000000000000000..65cb68a3175118394de4c6a6ba761f9f38ecd91e --- /dev/null +++ b/nemo/collections/asr/data/audio_to_text_lhotse_speaker.py @@ -0,0 +1,97 @@ +# 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 index 369a95d9ee9a9ffddf0c50c93d7c298edbdd5bd6..2138a8d2eedae263d1d3cb4a9f2a8a973acf3ec1 100644 --- a/nemo/collections/asr/data/data_simulation.py +++ b/nemo/collections/asr/data/data_simulation.py @@ -67,122 +67,86 @@ class MultiSpeakerSimulator(object): Multispeaker Audio Session Simulator - Simulates multispeaker audio sessions using single-speaker audio files and corresponding word alignments. - Change Log: - v1.0: Dec 2022 - - First working verison, supports multispeaker simulation with overlaps, silence and RIR - v1.0.1: Feb 2023 - - Multi-GPU support for speed up - - Faster random sampling routine - - Fixed sentence duration bug - - Silence and overlap length sampling algorithms are updated to guarantee `mean_silence` approximation - v1.0.2: March 2023 - - Added support for segment-level gain perturbation and session-level white-noise perturbation - - Modified speaker sampling mechanism to include as many speakers as possible in each data-generation run - - Added chunking mechanism to avoid freezing in multiprocessing processes - - v1.1.0 March 2023 - - Faster audio-file loading with maximum audio duration parameter - - Re-organized MultiSpeakerSimulator class and moved util functions to util files. - v1.1.1 March 2023 - - Changed `silence_mean` to use exactly the same sampling equation as `overlap_mean`. - - Args: cfg: OmegaConf configuration loaded from yaml file. - 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). Short sessions - (e.g. ~240 seconds) tend to fall short of the expected overlap-ratio and silence-ratio. - - session_params: - max_audio_read_sec (int): The maximum audio length in second when loading an audio file. - The bigger the number, the slower the reading speed. Should be greater than 2.5 second. - sentence_length_params (list): k,p values for a negative_binomial distribution which is sampled to get the - sentence length (in number of words) - dominance_var (float): Variance in speaker dominance (where each speaker's dominance is sampled from a normal - distribution centered on 1/`num_speakers`, and then the dominance values are together - normalized to 1) - min_dominance (float): Minimum percentage of speaking time per speaker (note that this can cause the dominance of - the other speakers to be slightly reduced) - turn_prob (float): Probability of switching speakers after each utterance - - 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 - start_window (bool): Whether to window the start of sentences to smooth the audio signal (and remove silence at - the start of the clip) - window_type (str): Type of windowing used when segmenting utterances ("hamming", "hann", "cosine") - window_size (float): Length of window at the start or the end of segmented utterance (seconds) - start_buffer (float): Buffer of silence before the start of the sentence (to avoid cutting off speech or starting - abruptly) - 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) - release_buffer (float): Buffer before window at end of sentence (to avoid cutting off speech or ending abruptly) - normalize (bool): Normalize speaker volumes - normalization_type (str): Normalizing speakers ("equal" - same volume per speaker, "var" - variable volume per - speaker) - normalization_var (str): Variance in speaker volume (sample from standard deviation centered at 1) - min_volume (float): Minimum speaker volume (only used when variable normalization is used) - max_volume (float): Maximum speaker volume (only used when variable normalization is used) - end_buffer (float): Buffer at the end of the session to leave blank - - 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 - - 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), set `snr_min` and `snr_max` values to enable random SNR - snr_min (int): Min random SNR for background noise (using average speaker power), set `null` to use fixed SNR - snr_max (int): Max random SNR for background noise (using average speaker power), set `null` to use fixed SNR - - segment_augmentor: - add_seg_aug (bool): Set True to enable augmentation on each speech segment (Default: False) - segmentor: - gain: - prob (float): Probability range (uniform distribution) gain augmentation for individual segment - min_gain_dbfs (float): minimum gain in terms of dB - max_gain_dbfs (float): maximum gain in terms of dB - - session_augmentor: - add_sess_aug: (bool) set True to enable audio augmentation on the whole session (Default: False) - segmentor: - white_noise: + 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 terms of dB - max_level (float): maximum gain in terms of dB - - speaker_enforcement: - enforce_num_speakers (bool): Enforce that all requested speakers are present in the output wav file - enforce_time (list): Percentage of the way through the audio session that enforcement mode is triggered (sampled - between time 1 and 2) - - segment_manifest: (parameters for regenerating the segment 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 decimals for segment manifest file + 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): @@ -629,7 +593,7 @@ class MultiSpeakerSimulator(object): if num_missing != 0: warnings.warn( f"{self._params.data_simulator.session_config.num_speakers - num_missing}" - f"speakers were included in the clip instead of the requested amount of " + "speakers were included in the clip instead of the requested amount of " f"{self._params.data_simulator.session_config.num_speakers}" ) @@ -1117,7 +1081,7 @@ class MultiSpeakerSimulator(object): ) self.annotator.annote_lists['json'].append(new_json_entry) - new_ctm_entries = self.annotator.create_new_ctm_entry( + new_ctm_entries, _ = self.annotator.create_new_ctm_entry( words=self._words, alignments=self._alignments, session_name=filename, @@ -1148,7 +1112,7 @@ class MultiSpeakerSimulator(object): 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( + bg, snr, _ = get_background_noise( len_array=len(array), power_array=avg_power_array, noise_samples=self._noise_samples, @@ -1190,7 +1154,7 @@ class MultiSpeakerSimulator(object): Args: random_seed (int): random seed for reproducibility """ - logging.info(f"Generating Diarization Sessions") + logging.info("Generating Diarization Sessions") if random_seed is None: random_seed = self._params.data_simulator.random_seed np.random.seed(random_seed) @@ -1286,29 +1250,25 @@ class RIRMultiSpeakerSimulator(MultiSpeakerSimulator): Args: cfg: OmegaConf configuration loaded from yaml file. - Parameters (in addition to the base MultiSpeakerSimulator parameters): - 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 (1d array for specific, 2d array for random range to be - sampled from) - pos_src (list): Positions of the speakers in the simulated room environment (2d array for specific, 3d array - for random ranges to be sampled from) - noise_src_pos (list): Position in room for the ambient background noise source - mic_config: - num_channels (int): Number of output audio channels - pos_rcv (list): Microphone positions in the simulated room environment (1d/2d array for specific, 2d/3d array - for range assuming num_channels is 1/2+) - orV_rcv (list or null): Microphone orientations (needed for non-omnidirectional microphones) - mic_pattern (str): Microphone type ("omni" - omnidirectional) - currently only omnidirectional microphones are - supported for pyroomacoustics - absorbtion_params: (Note that only `T60` is used for pyroomacoustics simulations) - abs_weights (list): Absorption coefficient ratios for each surface - T60 (float): Room reverberation time (`T60` is the time it takes for the RIR to decay by 60DB) - att_diff (float): Starting attenuation (if this is different than att_max, the diffuse reverberation model is - used by gpuRIR) - att_max (float): End attenuation when using the diffuse reverberation model (gpuRIR) + 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): @@ -1466,6 +1426,8 @@ class RIRMultiSpeakerSimulator(MultiSpeakerSimulator): 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, @@ -1509,6 +1471,8 @@ class RIRMultiSpeakerSimulator(MultiSpeakerSimulator): 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)) @@ -1643,8 +1607,12 @@ class RIRMultiSpeakerSimulator(MultiSpeakerSimulator): ) self.annotator.annote_lists['json'].append(new_json_entry) - new_ctm_entries = self.annotator.create_new_ctm_entry( - filename, speaker_ids[speaker_turn], start / self._params.data_simulator.sr + 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) @@ -1659,23 +1627,21 @@ class RIRMultiSpeakerSimulator(MultiSpeakerSimulator): 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: - 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 + 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] - bg, snr = self._get_background(length, avg_power_array) 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] diff --git a/nemo/collections/asr/data/ssl_dataset.py b/nemo/collections/asr/data/ssl_dataset.py index f09056ece84c65c83d571ebc3a1673c9daa2ee7a..2fc644f197035d7adee4252218e71762548317b5 100644 --- a/nemo/collections/asr/data/ssl_dataset.py +++ b/nemo/collections/asr/data/ssl_dataset.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -103,12 +103,8 @@ def _audio_noise_collate_fn(batch: List[AudioNoiseItem], batch_augmentor: Any = noises = [x.noise for x in batch] noise_lengths = [x.noise_len for x in batch] - noisy_audios = [x.noisy_audio for x in batch] - noisy_audio_lengths = [x.noisy_audio_len for x in batch] - audio_signal_list = [] noise_signal_list = [] - noisy_audio_signal_list = [] for i, audio in enumerate(audios): audio_len = audio.size(0) if audio_len < max_audio_len: @@ -123,31 +119,23 @@ def _audio_noise_collate_fn(batch: List[AudioNoiseItem], batch_augmentor: Any = noise = torch.nn.functional.pad(noise, pad) noise_signal_list.append(noise[:max_audio_len]) - noisy_audio = noisy_audios[i] - noisy_audio_len = noisy_audio.size(0) - if noisy_audio_len < max_audio_len: - pad = (0, max_audio_len - noisy_audio_len) - noisy_audio = torch.nn.functional.pad(noisy_audio, pad) - noisy_audio_signal_list.append(noisy_audio[: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() - noisy_audio_signal = torch.stack(noisy_audio_signal_list).float() - noisy_audio_lengths = torch.stack(noisy_audio_lengths).long() output = AudioNoiseBatch( audio=audio_signal, audio_len=audio_lengths, noise=noise_signal, noise_len=noise_lengths, - noisy_audio=noisy_audio_signal, - noisy_audio_len=noisy_audio_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 @@ -344,8 +332,6 @@ class AudioNoiseDataset(audio_to_text.AudioToCharDataset): audio_len=audio_len, noise=noise, noise_len=noise_len, - noisy_audio=audio + noise, - noisy_audio_len=audio_len, ) return item @@ -421,8 +407,6 @@ class TarredAudioNoiseDataset(audio_to_text.TarredAudioToCharDataset): audio_len=audio_len, noise=noise, noise_len=noise_len, - noisy_audio=audio + noise, - noisy_audio_len=audio_len, ) return item @@ -460,21 +444,29 @@ class LhotseAudioNoiseDataset(torch.utils.data.Dataset): def __getitem__(self, cuts): audios, audio_lens, cuts = self.load_audio(cuts) - sampled_noises = [sample_noise(self.noise_data, cut.sampling_rate, cut.num_samples) for cut in cuts] - - items = [ - AudioNoiseItem( - sample_id=str(cuts[i].id), - audio=audios[i], - audio_len=audio_lens[i], - noise=sampled_noises[i][0], - noise_len=sampled_noises[i][1], - noisy_audio=audios[i] + sampled_noises[i][0], - noisy_audio_len=audio_lens[i], - ) - for i in range(len(cuts)) - ] - return _audio_noise_collate_fn(items, self.batch_augmentor) + 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( diff --git a/nemo/collections/asr/data/text_to_text.py b/nemo/collections/asr/data/text_to_text.py index 88b417ea21bc5e1a0ead0dc186d1ab60cc6ddb22..28f5c5f445b588965b63a3c6e3facee3b2c81374 100644 --- a/nemo/collections/asr/data/text_to_text.py +++ b/nemo/collections/asr/data/text_to_text.py @@ -335,7 +335,9 @@ class TextToTextDatasetBase: tts_tokenizer_global = copy.deepcopy(tokenizer) with concurrent.futures.ProcessPoolExecutor( - initializer=_init_tts_tokenize_process, initargs=(tts_parser,), max_workers=tokenizer_workers, + 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( @@ -373,7 +375,7 @@ class TextToTextDatasetBase: class TextToTextDataset(TextToTextDatasetBase, Dataset): - """Text-to-Text Map-style Dataset for hybrid ASR-TTS models""" + """Text-to-Text Map-style Dataset.""" def __init__( self, @@ -418,8 +420,8 @@ class TextToTextDataset(TextToTextDatasetBase, Dataset): class TextToTextIterableDataset(TextToTextDatasetBase, IterableDataset): """ - Text-to-Text Iterable Dataset for hybrid ASR-TTS models - Only part necessary for current process should be loaded and stored + Text-to-Text Iterable Dataset. + Only part necessary for current process should be loaded and stored. """ def __init__( diff --git a/nemo/collections/asr/inference/__init__.py b/nemo/collections/asr/inference/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c --- /dev/null +++ b/nemo/collections/asr/inference/__init__.py @@ -0,0 +1,13 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c --- /dev/null +++ b/nemo/collections/asr/inference/factory/__init__.py @@ -0,0 +1,13 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..cae8b8a4ded42555bdda87568489d55ccd5300af --- /dev/null +++ b/nemo/collections/asr/inference/factory/base_builder.py @@ -0,0 +1,172 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..17815e578cb4e4706ab6b862443e887833e1fc7f --- /dev/null +++ b/nemo/collections/asr/inference/factory/buffered_pipeline_builder.py @@ -0,0 +1,147 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..d8c31e1d4548c19a2350d46b3e489e656a03aabb --- /dev/null +++ b/nemo/collections/asr/inference/factory/cache_aware_pipeline_builder.py @@ -0,0 +1,120 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..54a58ad3332c408c861dee64cadba8f15bf4e32d --- /dev/null +++ b/nemo/collections/asr/inference/factory/pipeline_builder.py @@ -0,0 +1,74 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c --- /dev/null +++ b/nemo/collections/asr/inference/itn/__init__.py @@ -0,0 +1,13 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..99f52dd55882d5793d1c6772fa7ec8cebc65e4e4 --- /dev/null +++ b/nemo/collections/asr/inference/itn/batch_inverse_normalizer.py @@ -0,0 +1,185 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..38546d7caa89ebf0ee2c57b7a3fb4ed3f762ac0a --- /dev/null +++ b/nemo/collections/asr/inference/itn/inverse_normalizer.py @@ -0,0 +1,355 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c --- /dev/null +++ b/nemo/collections/asr/inference/model_wrappers/__init__.py @@ -0,0 +1,13 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..6be50dee5596b8818b92f9475f66433cf0467830 --- /dev/null +++ b/nemo/collections/asr/inference/model_wrappers/asr_inference_wrapper.py @@ -0,0 +1,285 @@ +# 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)}") from 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 new file mode 100644 index 0000000000000000000000000000000000000000..e05c0d029e0b6e4cca9a15e5efbde69f008c670d --- /dev/null +++ b/nemo/collections/asr/inference/model_wrappers/cache_aware_asr_inference_wrapper.py @@ -0,0 +1,136 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..d644e2eda14cc13af66a8fef007bcae165251e18 --- /dev/null +++ b/nemo/collections/asr/inference/model_wrappers/cache_aware_ctc_inference_wrapper.py @@ -0,0 +1,203 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..3aedcab10abc84c96411ed6c7e14ce098b1501a9 --- /dev/null +++ b/nemo/collections/asr/inference/model_wrappers/cache_aware_rnnt_inference_wrapper.py @@ -0,0 +1,195 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..64304f6611bead0ed8f6bc8422a69467f546b69f --- /dev/null +++ b/nemo/collections/asr/inference/model_wrappers/ctc_inference_wrapper.py @@ -0,0 +1,109 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..a554b960f0714c03c947abf2d02264cc7682fac2 --- /dev/null +++ b/nemo/collections/asr/inference/model_wrappers/rnnt_inference_wrapper.py @@ -0,0 +1,147 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..3355899c4b98702d27f2fcb71b044fc7fd346dec --- /dev/null +++ b/nemo/collections/asr/inference/model_wrappers/salm_asr_inference_wrapper.py @@ -0,0 +1,166 @@ +# 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)}") from 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 new file mode 100644 index 0000000000000000000000000000000000000000..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c --- /dev/null +++ b/nemo/collections/asr/inference/nmt/__init__.py @@ -0,0 +1,13 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..34c50b17eef930bc0a5c9dc47d4ae75dc5cda4d8 --- /dev/null +++ b/nemo/collections/asr/inference/nmt/llm_translator.py @@ -0,0 +1,296 @@ +# 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)}") from 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 new file mode 100644 index 0000000000000000000000000000000000000000..c2f62a5ebae861a88298303a8c4266610e0f1c73 --- /dev/null +++ b/nemo/collections/asr/inference/nmt/prompts.py @@ -0,0 +1,96 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c --- /dev/null +++ b/nemo/collections/asr/inference/pipelines/__init__.py @@ -0,0 +1,13 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..07669989d307ef0b90819a1837aae0799afde066 --- /dev/null +++ b/nemo/collections/asr/inference/pipelines/base_pipeline.py @@ -0,0 +1,642 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..ba10c2fbfd2e85e367f280eca2c146603ae28ef7 --- /dev/null +++ b/nemo/collections/asr/inference/pipelines/buffered_ctc_pipeline.py @@ -0,0 +1,447 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..e7a390e458dab1dc0399cc122188ecc78d033b79 --- /dev/null +++ b/nemo/collections/asr/inference/pipelines/buffered_rnnt_pipeline.py @@ -0,0 +1,813 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..b81c6cca8ebb43401531ca838a1faefd61d23903 --- /dev/null +++ b/nemo/collections/asr/inference/pipelines/buffered_salm_pipeline.py @@ -0,0 +1,249 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..91c86072d62f1a70c98f66681bdf46bee74cacd9 --- /dev/null +++ b/nemo/collections/asr/inference/pipelines/cache_aware_ctc_pipeline.py @@ -0,0 +1,432 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..2b4de83dac1ca345719fada152a225d9116dedb6 --- /dev/null +++ b/nemo/collections/asr/inference/pipelines/cache_aware_rnnt_pipeline.py @@ -0,0 +1,494 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..a66f879f21fcb4189d73845d2bde142f16f4be22 --- /dev/null +++ b/nemo/collections/asr/inference/pipelines/pipeline_interface.py @@ -0,0 +1,79 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c --- /dev/null +++ b/nemo/collections/asr/inference/streaming/__init__.py @@ -0,0 +1,13 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c --- /dev/null +++ b/nemo/collections/asr/inference/streaming/buffering/__init__.py @@ -0,0 +1,13 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..c1bc862f3652b06caa22baf6541e870f54f6e309 --- /dev/null +++ b/nemo/collections/asr/inference/streaming/buffering/audio_bufferer.py @@ -0,0 +1,131 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..f4a8c273a100daa1f163bde5abe7f74849f8e998 --- /dev/null +++ b/nemo/collections/asr/inference/streaming/buffering/cache_feature_bufferer.py @@ -0,0 +1,227 @@ +# 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: + if slot_id not in self.slotidx2streamidx: + continue + 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: list[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 new file mode 100644 index 0000000000000000000000000000000000000000..c1372bab61b0e83da6cad9caa0b8ea5c9899078f --- /dev/null +++ b/nemo/collections/asr/inference/streaming/buffering/feature_bufferer.py @@ -0,0 +1,160 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..19f6e1b88b15fd6db7f05103ec09be500dc22b86 --- /dev/null +++ b/nemo/collections/asr/inference/streaming/buffering/incremental_audio_bufferer.py @@ -0,0 +1,173 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c --- /dev/null +++ b/nemo/collections/asr/inference/streaming/decoders/__init__.py @@ -0,0 +1,13 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c --- /dev/null +++ b/nemo/collections/asr/inference/streaming/decoders/greedy/__init__.py @@ -0,0 +1,13 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..cc7001da95782868d87a026b42f95693aeca1c49 --- /dev/null +++ b/nemo/collections/asr/inference/streaming/decoders/greedy/greedy_ctc_decoder.py @@ -0,0 +1,199 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..9412330eb7a891a1a6a29040290ee7ff43abf7b1 --- /dev/null +++ b/nemo/collections/asr/inference/streaming/decoders/greedy/greedy_decoder.py @@ -0,0 +1,102 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..223462409a18bac6c6c4cc71a163446538b5327c --- /dev/null +++ b/nemo/collections/asr/inference/streaming/decoders/greedy/greedy_rnnt_decoder.py @@ -0,0 +1,235 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c --- /dev/null +++ b/nemo/collections/asr/inference/streaming/endpointing/__init__.py @@ -0,0 +1,13 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c --- /dev/null +++ b/nemo/collections/asr/inference/streaming/endpointing/greedy/__init__.py @@ -0,0 +1,13 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..446c513ed49f6e50851cda372c9037b00418d7ad --- /dev/null +++ b/nemo/collections/asr/inference/streaming/endpointing/greedy/greedy_ctc_endpointing.py @@ -0,0 +1,85 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..85a34427f7689d97a4d79f9c760441ab6df0db5b --- /dev/null +++ b/nemo/collections/asr/inference/streaming/endpointing/greedy/greedy_endpointing.py @@ -0,0 +1,312 @@ +# 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 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: + + # 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 new file mode 100644 index 0000000000000000000000000000000000000000..71598fdc3809e0ca0522b6ad9430c453109c61c5 --- /dev/null +++ b/nemo/collections/asr/inference/streaming/endpointing/greedy/greedy_rnnt_endpointing.py @@ -0,0 +1,63 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c --- /dev/null +++ b/nemo/collections/asr/inference/streaming/framing/__init__.py @@ -0,0 +1,13 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..f942d6d57712993693df87567cf93dd5f3d8ef3e --- /dev/null +++ b/nemo/collections/asr/inference/streaming/framing/mono_stream.py @@ -0,0 +1,114 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..b46e0821072891a68ffdb38b38f948af4d614b78 --- /dev/null +++ b/nemo/collections/asr/inference/streaming/framing/multi_stream.py @@ -0,0 +1,403 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..5706bcc31232e754eb4109c08a609a6c23b85dc4 --- /dev/null +++ b/nemo/collections/asr/inference/streaming/framing/request.py @@ -0,0 +1,107 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..ee12141dc6109b67a4b50730dd0b00fc183814af --- /dev/null +++ b/nemo/collections/asr/inference/streaming/framing/request_options.py @@ -0,0 +1,138 @@ +# 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 = None + enable_pnc: bool | None = None + stop_history_eou: int | None = None + asr_output_granularity: ASROutputGranularity | str | None = None + language_code: str | None = None + enable_nmt: bool | None = None + source_language: str | None = None + target_language: str | None = 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 new file mode 100644 index 0000000000000000000000000000000000000000..ecf2731d3f5b405213d65fed288aedd77421d6d9 --- /dev/null +++ b/nemo/collections/asr/inference/streaming/framing/stream.py @@ -0,0 +1,40 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c --- /dev/null +++ b/nemo/collections/asr/inference/streaming/state/__init__.py @@ -0,0 +1,13 @@ +# 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/multimodal/modules/imagen/encoder/__init__.py b/nemo/collections/asr/inference/streaming/state/cache_aware_ctc_state.py similarity index 64% rename from nemo/collections/multimodal/modules/imagen/encoder/__init__.py rename to nemo/collections/asr/inference/streaming/state/cache_aware_ctc_state.py index aee951313044f92f394e1a9301d5a71b8d9c8b1b..5b0beda8b2cb399ac1a5ce9eeabbab8fc3cd7941 100644 --- a/nemo/collections/multimodal/modules/imagen/encoder/__init__.py +++ b/nemo/collections/asr/inference/streaming/state/cache_aware_ctc_state.py @@ -1,4 +1,4 @@ -# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -12,13 +12,13 @@ # See the License for the specific language governing permissions and # limitations under the License. -from nemo.package_info import __version__ -# Set collection version equal to NeMo version. -__version = __version__ +from nemo.collections.asr.inference.streaming.state.cache_aware_state import CacheAwareStreamingState -# Authorship. -__author__ = "NVIDIA Corporation" -# Set collection name. -__description__ = "Speech Computer Vision collection" +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 new file mode 100644 index 0000000000000000000000000000000000000000..c9374c37ba264b400d12c5eb71c4d2cca099b13c --- /dev/null +++ b/nemo/collections/asr/inference/streaming/state/cache_aware_rnnt_state.py @@ -0,0 +1,66 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..db733fed41f8b4ba72223a7d40d414251df60032 --- /dev/null +++ b/nemo/collections/asr/inference/streaming/state/cache_aware_state.py @@ -0,0 +1,106 @@ +# 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) + if shift == 0: + return + if shift >= len(self.label_buffer): + self.label_buffer[:] = labels[-len(self.label_buffer) :] + return + 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/multimodal/modules/nerf/guidance/txt2img_guidance_base.py b/nemo/collections/asr/inference/streaming/state/ctc_state.py similarity index 68% rename from nemo/collections/multimodal/modules/nerf/guidance/txt2img_guidance_base.py rename to nemo/collections/asr/inference/streaming/state/ctc_state.py index db82584ba78e3e2d8b1ed46d5e7541b4e8c646e2..0ad5f21901d8ca0dbcfdf5dc9779e33b2b858613 100644 --- a/nemo/collections/multimodal/modules/nerf/guidance/txt2img_guidance_base.py +++ b/nemo/collections/asr/inference/streaming/state/ctc_state.py @@ -1,4 +1,4 @@ -# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -11,9 +11,13 @@ # WITHOUT 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.nn as nn +from nemo.collections.asr.inference.streaming.state.state import StreamingState -class Txt2ImgGuidanceBase(nn.Module): - def __init__(self): - super().__init__() + +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 new file mode 100644 index 0000000000000000000000000000000000000000..b2eade1badc54d3fe45dc8fd53eee4258e35d4a8 --- /dev/null +++ b/nemo/collections/asr/inference/streaming/state/rnnt_state.py @@ -0,0 +1,42 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..20025fa1e0567503bcc9e7e2bab7d88568dc2fc4 --- /dev/null +++ b/nemo/collections/asr/inference/streaming/state/salm_state.py @@ -0,0 +1,23 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..2e311a2900ee68efb85e3ebafd2f322f99ef30e6 --- /dev/null +++ b/nemo/collections/asr/inference/streaming/state/state.py @@ -0,0 +1,385 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c --- /dev/null +++ b/nemo/collections/asr/inference/streaming/text/__init__.py @@ -0,0 +1,13 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..13f7c259ce1bc20896a52300c543b71988964ce7 --- /dev/null +++ b/nemo/collections/asr/inference/streaming/text/text_processing.py @@ -0,0 +1,414 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c --- /dev/null +++ b/nemo/collections/asr/inference/utils/__init__.py @@ -0,0 +1,13 @@ +# 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/multimodal/modules/nerf/utils/activation.py b/nemo/collections/asr/inference/utils/audio_io.py similarity index 51% rename from nemo/collections/multimodal/modules/nerf/utils/activation.py rename to nemo/collections/asr/inference/utils/audio_io.py index 1b79676d57c6d15aab815a3dbdd402c973fb4398..17fc9d1a9a3f1b64d2a83ca7ca070f4eebe84090 100644 --- a/nemo/collections/multimodal/modules/nerf/utils/activation.py +++ b/nemo/collections/asr/inference/utils/audio_io.py @@ -1,4 +1,4 @@ -# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -11,23 +11,19 @@ # WITHOUT 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.cuda.amp import custom_bwd, custom_fwd - -class _trunc_exp(Function): - @staticmethod - @custom_fwd(cast_inputs=torch.float) - def forward(ctx, x): - ctx.save_for_backward(x) - return torch.exp(x) - - @staticmethod - @custom_bwd - def backward(ctx, g): - x = ctx.saved_tensors[0] - return g * torch.exp(x.clamp(max=15)) +import librosa +import torch -trunc_exp = _trunc_exp.apply +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 new file mode 100644 index 0000000000000000000000000000000000000000..18148801c64e4a31755d7f59bc8f2e6a679e9739 --- /dev/null +++ b/nemo/collections/asr/inference/utils/bpe_decoder.py @@ -0,0 +1,269 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..e4e2fea982a51fc5a3a03faa8a38350bdca475be --- /dev/null +++ b/nemo/collections/asr/inference/utils/config_io.py @@ -0,0 +1,40 @@ +# 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/vlm/clip/model/__init__.py b/nemo/collections/asr/inference/utils/constants.py similarity index 56% rename from nemo/collections/vlm/clip/model/__init__.py rename to nemo/collections/asr/inference/utils/constants.py index 0d1e28b6bc3568ff8ad29ace45dd8260099c9e36..c67488a96f76f44db082161f76f6a799cfd200d5 100644 --- a/nemo/collections/vlm/clip/model/__init__.py +++ b/nemo/collections/asr/inference/utils/constants.py @@ -12,21 +12,22 @@ # See the License for the specific language governing permissions and # limitations under the License. -from nemo.collections.vlm.clip.model.base import CLIPConfig, CLIPModel, CLIPTextModelConfig, CLIPViTConfig -from nemo.collections.vlm.clip.model.clip import ( - CLIPConfigB32, - CLIPConfigL14, - CLIPTextModelL_14_224_Config, - CLIPViTL_14_224_Config, -) +# Precision related constants +BIG_EPSILON = 1e-5 +SMALL_EPSILON = 1e-10 +ROUND_PRECISION = 9 -__all__ = [ - "CLIPViTConfig", - "CLIPTextModelConfig", - "CLIPConfig", - "CLIPViTL_14_224_Config", - "CLIPTextModelL_14_224_Config", - "CLIPConfigL14", - "CLIPConfigB32", - "CLIPModel", -] +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..012fa2477623dbe996c24994e55e15e6649b9527 --- /dev/null +++ b/nemo/collections/asr/inference/utils/context_manager.py @@ -0,0 +1,197 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..1861ed6869551a0a638ba56d10f2dbeb6b7ea55a --- /dev/null +++ b/nemo/collections/asr/inference/utils/device_utils.py @@ -0,0 +1,69 @@ +# 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_str = compute_dtype + compute_dtype = COMPUTE_DTYPE_MAP.get(compute_dtype_str, None) + if compute_dtype is None: + raise ValueError( + f"Invalid compute dtype: {compute_dtype_str}. 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 new file mode 100644 index 0000000000000000000000000000000000000000..c72a6230164c197dcf2ee76596220cbbbf7b3114 --- /dev/null +++ b/nemo/collections/asr/inference/utils/endpointing_utils.py @@ -0,0 +1,44 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..87c1092dc9ac040afe90607a078ee4b14636b634 --- /dev/null +++ b/nemo/collections/asr/inference/utils/enums.py @@ -0,0 +1,84 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..1316e099b77197bbd7cdd19f11987779ea998470 --- /dev/null +++ b/nemo/collections/asr/inference/utils/itn_utils.py @@ -0,0 +1,88 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..5f5a0e733b2df56622d3c853507bb98712f2d8a5 --- /dev/null +++ b/nemo/collections/asr/inference/utils/lcs_merge.py @@ -0,0 +1,113 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..2aca89d1e7a2e0e16afbe896926b55d239b9bb6f --- /dev/null +++ b/nemo/collections/asr/inference/utils/manifest_io.py @@ -0,0 +1,197 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..db94d854d9e6d8d7667deba7063f7b192f44b917 --- /dev/null +++ b/nemo/collections/asr/inference/utils/pipeline_eval.py @@ -0,0 +1,126 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..dcdcaf2f7ab674e49a5e703e68df56a3715d9926 --- /dev/null +++ b/nemo/collections/asr/inference/utils/pipeline_utils.py @@ -0,0 +1,312 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..ef6663bbdaa579b7c660454dedb0f815741f7efb --- /dev/null +++ b/nemo/collections/asr/inference/utils/progressbar.py @@ -0,0 +1,100 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..cabec9a9a54dd629d4ab4e03e2dd13d7d7fd7afd --- /dev/null +++ b/nemo/collections/asr/inference/utils/state_management_utils.py @@ -0,0 +1,193 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..77bc1c50e5e802b0730c615f82c53c17d95f0cd2 --- /dev/null +++ b/nemo/collections/asr/inference/utils/text_segment.py @@ -0,0 +1,319 @@ +# 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 index f88bd49d1f7b38cc1465d291529b5d4869d1c855..d833ce5cd4848130b48e5329c5713e1bad15a887 100644 --- a/nemo/collections/asr/losses/__init__.py +++ b/nemo/collections/asr/losses/__init__.py @@ -15,7 +15,6 @@ 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.lattice_losses import LatticeLoss 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 diff --git a/nemo/collections/asr/losses/bce_loss.py b/nemo/collections/asr/losses/bce_loss.py index 36a7a0166f2669cc632c1163d34645d683feebe3..61a7b3b2946bc02979e40d473298395a1912b8d6 100644 --- a/nemo/collections/asr/losses/bce_loss.py +++ b/nemo/collections/asr/losses/bce_loss.py @@ -77,7 +77,7 @@ class BCELoss(Loss, Typing): self.eps = 1e-6 @typecheck() - def forward(self, probs, labels, target_lens): + def forward(self, probs, labels, target_lens, enable_autocast=False): """ Calculate binary cross entropy loss based on probs, labels and target_lens variables. @@ -123,13 +123,14 @@ class BCELoss(Loss, Typing): binary_weight = torch.ones_like(labels).detach().clone() norm_weight = torch.ones_like(labels).detach().clone() - 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: + 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/lattice_losses.py b/nemo/collections/asr/losses/lattice_losses.py deleted file mode 100644 index 7dae44bfd1d18a0946a34efa25077ad9bacad947..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/losses/lattice_losses.py +++ /dev/null @@ -1,184 +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 typing import Optional - -import torch -from omegaconf import DictConfig - -from nemo.core.classes import Loss, typecheck -from nemo.core.neural_types import LabelsType, LengthsType, LogprobsType, LossType, NeuralType - - -class LatticeLoss(Loss): - """Family of loss functions based on various lattice scores. - - Note: - Requires k2 v1.14 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: # Model config - ... - graph_module_cfg: # Config for graph modules, e.g. LatticeLoss - criterion_type: "map" - loss_type: "mmi" - split_batch_size: 0 - backend_cfg: - topo_type: "default" # other options: "compact", "shared_blank", "minimal" - topo_with_self_loops: true - token_lm: # must be provided for criterion_type: "map" - - Args: - num_classes: Number of target classes for the decoder network to predict. - (Excluding the blank token). - - reduction: Type of reduction to perform on loss. Possible values are `mean_batch`, `mean`, `sum`, or None. - None will return a torch vector comprising the individual loss values of the batch. - - backend: Which backend to use for loss calculation. Currently only `k2` is supported. - - criterion_type: Type of criterion to use. Choices: `ml` and `map`, - with `ml` standing for Maximum Likelihood and `map` for Maximum A Posteriori Probability. - - loss_type: Type of the loss function to use. Choices: `ctc` and `rnnt` for `ml`, and `mmi` for `map`. - - split_batch_size: Local batch size. Used for memory consumption reduction at the cost of speed performance. - Effective if complies 0 < split_batch_size < batch_size. - - graph_module_cfg: Optional Dict of (str, value) pairs that are passed to the backend loss function. - """ - - @property - def input_types(self): - """Input types definitions for LatticeLoss. - """ - return { - "log_probs": NeuralType(("B", "T", "D") if self._3d_input else ("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 LatticeLoss. - loss: - NeuralType(None) - """ - return {"loss": NeuralType(elements_type=LossType())} - - def __init__( - self, - num_classes: int, - reduction: str = "mean_batch", - backend: str = "k2", - criterion_type: str = "ml", - loss_type: str = "ctc", - split_batch_size: int = 0, - graph_module_cfg: Optional[DictConfig] = None, - ): - super().__init__() - self._blank = num_classes - self.split_batch_size = split_batch_size - inner_reduction = None - if reduction == "mean_batch": - inner_reduction = "none" - self._apply_batch_mean = True - elif reduction in ["sum", "mean", "none"]: - inner_reduction = reduction - self._apply_batch_mean = False - - # we assume that self._blank + 1 == num_classes - if backend == "k2": - if criterion_type == "ml": - if loss_type == "ctc": - from nemo.collections.asr.parts.k2.ml_loss import CtcLoss as K2Loss - elif loss_type == "rnnt": - from nemo.collections.asr.parts.k2.ml_loss import RnntLoss as K2Loss - else: - raise ValueError(f"Unsupported `loss_type`: {loss_type}.") - elif criterion_type == "map": - if loss_type == "ctc": - from nemo.collections.asr.parts.k2.map_loss import CtcMmiLoss as K2Loss - else: - raise ValueError(f"Unsupported `loss_type`: {loss_type}.") - else: - raise ValueError(f"Unsupported `criterion_type`: {criterion_type}.") - - self._loss = K2Loss( - num_classes=self._blank + 1, blank=self._blank, reduction=inner_reduction, cfg=graph_module_cfg, - ) - elif backend == "gtn": - raise NotImplementedError(f"Backend {backend} is not supported.") - else: - raise ValueError(f"Invalid value of `backend`: {backend}.") - - self.criterion_type = criterion_type - self.loss_type = loss_type - self._3d_input = self.loss_type != "rnnt" - - if self.split_batch_size > 0: - # don't need to guard grad_utils - from nemo.collections.asr.parts.k2.grad_utils import PartialGrad - - self._partial_loss = PartialGrad(self._loss) - - def update_graph(self, graph): - """Updates graph of the backend loss function. - """ - if self.criterion_type != "ml": - self._loss.update_graph(graph) - - @typecheck() - def forward(self, log_probs, targets, input_lengths, target_lengths): - # override forward implementation - # custom logic, if necessary - - assert not (torch.isnan(log_probs).any() or torch.isinf(log_probs).any()) - - log_probs = log_probs.float() - input_lengths = input_lengths.long() - target_lengths = target_lengths.long() - targets = targets.long() - batch_size = log_probs.shape[0] - if self.split_batch_size > 0 and self.split_batch_size <= batch_size: - loss_list = [] - for batch_idx in range(0, batch_size, self.split_batch_size): - begin = batch_idx - end = min(begin + self.split_batch_size, batch_size) - input_lengths_part = input_lengths[begin:end] - log_probs_part = log_probs[begin:end, : input_lengths_part.max()] - target_lengths_part = target_lengths[begin:end] - targets_part = targets[begin:end, : target_lengths_part.max()] - loss_part, _ = ( - self._partial_loss(log_probs_part, targets_part, input_lengths_part, target_lengths_part) - if log_probs_part.requires_grad - else self._loss(log_probs_part, targets_part, input_lengths_part, target_lengths_part) - ) - del log_probs_part, targets_part, input_lengths_part, target_lengths_part - loss_list.append(loss_part) - loss = torch.cat(loss_list, 0) - else: - loss, _ = self._loss( - log_probs=log_probs, targets=targets, input_lengths=input_lengths, target_lengths=target_lengths, - ) - if self._apply_batch_mean: - # torch.mean gives nan if loss is empty - loss = torch.mean(loss) if loss.nelement() > 0 else torch.sum(loss) - return loss diff --git a/nemo/collections/asr/losses/rnnt.py b/nemo/collections/asr/losses/rnnt.py index 894be6319c99f82bd564fa765a50dde312eb3a19..7c99eb3d86f2566d4f1fe536bcd998ce7215a9e9 100644 --- a/nemo/collections/asr/losses/rnnt.py +++ b/nemo/collections/asr/losses/rnnt.py @@ -333,8 +333,7 @@ def resolve_rnnt_loss(loss_name: str, blank_idx: int, loss_kwargs: dict = None) class RNNTLoss(Loss): @property def input_types(self): - """Input types definitions for CTCLoss. - """ + """Input types definitions for RNNTLoss.""" return { "log_probs": NeuralType(('B', 'T', 'T', 'D'), LogprobsType()), "targets": NeuralType(('B', 'T'), LabelsType()), @@ -344,7 +343,7 @@ class RNNTLoss(Loss): @property def output_types(self): - """Output types definitions for CTCLoss. + """Output types definitions for RNNTLoss. loss: NeuralType(None) """ @@ -395,7 +394,7 @@ class RNNTLoss(Loss): 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 + 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 @@ -463,9 +462,7 @@ class RNNTLoss(Loss): 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 diff --git a/nemo/collections/asr/losses/ssl_losses/mlm.py b/nemo/collections/asr/losses/ssl_losses/mlm.py index 424374869c3db5bac12e7ea9eef929e4823e60cd..4ed6f580bbb28df80511f998f4943d7fe13047fa 100644 --- a/nemo/collections/asr/losses/ssl_losses/mlm.py +++ b/nemo/collections/asr/losses/ssl_losses/mlm.py @@ -65,11 +65,14 @@ class MLMLoss(Loss): if masks is None: masks = spec_masks - # B,D,T -> B,T,D - masks = masks.transpose(1, 2) + 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 + 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])) diff --git a/nemo/collections/asr/metrics/__init__.py b/nemo/collections/asr/metrics/__init__.py index 843d58ccf38f2cdc368bf42258682e77d612db5c..d116dbae5977d469d1883dc943bac772fdca0f43 100644 --- a/nemo/collections/asr/metrics/__init__.py +++ b/nemo/collections/asr/metrics/__init__.py @@ -13,4 +13,11 @@ # 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 index f422f36655616a6dc17a608cf1730ebaf6225b00..c99664160eafe68a981dd29bd625e6e8899f9265 100644 --- a/nemo/collections/asr/metrics/bleu.py +++ b/nemo/collections/asr/metrics/bleu.py @@ -12,10 +12,12 @@ # See the License for the specific language governing permissions and # limitations under the License. -from typing import Literal, Optional, Sequence, Union +from typing import Literal, Optional, Sequence, TypeAlias, Union import torch -from torchmetrics.functional.text.bleu import _bleu_score_compute +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 @@ -25,13 +27,29 @@ from nemo.utils import logging __all__ = ['BLEU'] +# Keyword to avoid mispelling issues. +BLEU_TOKENIZER = "bleu_tokenizer" -def move_dimension_to_the_front(tensor, dim_index): + +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 :])) -# TODO: Add documentation class BLEU(SacreBLEUScore): """ This metric computes numerator, denominator, hypotheses lengths, and target lengths for Overall Bilingual Evaluation Understudy (BLEU) @@ -51,79 +69,69 @@ class BLEU(SacreBLEUScore): def on_validation_epoch_end(self): ... - bleu_num = torch.stack([x['val_wer_num'] for x in self.val_outputs]).sum() - bleu_denom = torch.stack([x['val_wer_denom'] for x in self.val_outputs]).sum() - bleu_num = torch.stack([x[f"val_bleu_num"] for x in outputs]).sum(dim=0) - bleu_denom = torch.stack([x[f"val_bleu_denom"] for x in outputs]).sum(dim=0) - + 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: An instance of CTCDecoding, RNNTDecoding, or MultiTaskDecoding. - tokenize: Desired tokenizer for BLEU evaluation. (Depending on language, this will drastically affect BLEU score.) - n_gram: Maximum number of n_grams to compute BLEU values over. Max: 4. - lowercase: Whether to lowercase all inputs. - weights: List of float values to weight each n_gram score. - 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. + 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: - 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. + 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], - tokenize: Literal["none", "13a", "zh", "intl", "char"] = "13a", + bleu_tokenizer: SacreBLEUToken = "13a", n_gram: int = 4, lowercase: bool = False, weights: Optional[Sequence[float]] = None, smooth: bool = False, - log_prediction=True, + 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=tokenize, + 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, ) - self.decoding = decoding - self.decode = None - if isinstance(self.decoding, AbstractRNNTDecoding): - self.decode = lambda predictions, predictions_lengths, predictions_mask, input_ids, targets: 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, targets: 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, targets: 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"WER metric does not support decoding of type {type(self.decoding)}") - - self.tokenize = tokenize - self.log_prediction = log_prediction - self.batch_dim_index = batch_dim_index def update( self, @@ -133,6 +141,8 @@ class BLEU(SacreBLEUScore): 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. @@ -147,32 +157,54 @@ class BLEU(SacreBLEUScore): ``[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. """ - references = [] + 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(): - tgt_lenths_cpu_tensor = targets_lengths.long().cpu() - targets_cpu_tensor = targets.long().cpu() - # check batch_dim_index is first dim + # 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_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_tokens_to_str(target) - references.append(reference) - hypotheses = self.decode(predictions, predictions_lengths, predictions_mask, input_ids, targets) - - if self.log_prediction: - logging.info("\n") - logging.info(f"reference:{references[0]}") - logging.info(f"predicted:{hypotheses[0]}") - - super().update( - [h.text for h in hypotheses], [references] - ) # Note: [references] since BLEU allows multiple references. - - def compute(self, return_all_metrics=True, prefix="", suffix=""): + 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. @@ -180,23 +212,21 @@ class BLEU(SacreBLEUScore): 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. - suffix: str to append to metric value keys. Returns: - Dict: key-value pairs of BLEU metrics and values. Keys are prepended and appended with prefix - and suffix flags, respectively. + 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{suffix}": bleu, - f"{prefix}bleu_pred_len{suffix}": self.preds_len.detach().float(), - f"{prefix}bleu_target_len{suffix}": self.target_len.detach().float(), - f"{prefix}bleu_num{suffix}": self.numerator.detach().float(), - f"{prefix}bleu_denom{suffix}": self.denominator.detach().float(), + 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{suffix}": bleu, + f"{prefix}bleu": bleu, } # Adding wrapper to avoid imports and extra variables over the namespace @@ -210,3 +240,39 @@ class BLEU(SacreBLEUScore): 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 index c8dec24eaaca0849bba003b57c4aa81892b9995b..86342a8b6f8104868682f0633a79d7a17ee4a643 100644 --- a/nemo/collections/asr/metrics/der.py +++ b/nemo/collections/asr/metrics/der.py @@ -12,17 +12,15 @@ # 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 editdistance import numpy as np -import torch +import pandas as pd 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 scipy.optimize import linear_sum_assignment as scipy_linear_sum_assignment from nemo.utils import logging @@ -119,7 +117,7 @@ def uem_timeline_from_file(uem_file, uniq_name=''): UNIQ_SPEAKER_ID CHANNEL START_TIME END_TIME """ timeline = Timeline(uri=uniq_name) - with open(uem_file, 'r') as f: + with open(uem_file, 'r', encoding='utf-8') as f: lines = f.readlines() for line in lines: line = line.strip() @@ -205,6 +203,10 @@ def score_labels( 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" @@ -271,19 +273,19 @@ def evaluate_der(audio_rttm_map_dict, all_reference, all_hypothesis, diar_eval_m 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. + Calculate cpWER with brute-force permutation search. Matches MeetEval's cpWER algorithm: + each (ref_speaker, hyp_speaker) pair is scored independently via edit distance, then + cpWER = sum(errors) / sum(ref_word_counts). Args: spk_hypothesis (list): - List containing the hypothesis transcript for each speaker. A list containing the sequence - of words is assigned for each speaker. + List containing the hypothesis transcript 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. + List containing the reference transcript for each speaker. Example: >>> spk_reference = ["hi how are you well that's nice", "i'm good yeah how is your sister"] @@ -296,83 +298,59 @@ def calculate_session_cpWER_bruteforce(spk_hypothesis: List[str], spk_reference: 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]: + num_hyp = len(spk_hypothesis) + num_ref = len(spk_reference) + num_speakers_padded = max(num_hyp, num_ref) + + ref_word_lists = [ + spk_reference[ref_idx].split() if ref_idx < num_ref else [] for ref_idx in range(num_speakers_padded) + ] + hyp_word_lists = [ + spk_hypothesis[hyp_idx].split() if hyp_idx < num_hyp else [] for hyp_idx in range(num_speakers_padded) + ] + + best_total_errors = float('inf') + best_hyp_trans = "" + total_ref_length = sum(len(word_list) for word_list in ref_word_lists) + + for perm in permutations(range(num_speakers_padded)): + total_errors = 0 + hyp_texts = [] + for ref_idx, hyp_idx in enumerate(perm): + total_errors += editdistance.eval(ref_word_lists[ref_idx], hyp_word_lists[hyp_idx]) + hyp_texts.append(spk_hypothesis[hyp_idx] if hyp_idx < num_hyp else "") + if total_errors < best_total_errors: + best_total_errors = total_errors + best_hyp_trans = " ".join(hyp_texts) + + cpWER = best_total_errors / total_ref_length if total_ref_length > 0 else float('inf') + ref_trans = " ".join(spk_reference) + return cpWER, best_hyp_trans, ref_trans + + +def calculate_session_cpWER(spk_hypothesis: List[str], spk_reference: List[str]) -> 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) + Calculate a session-level concatenated minimum-permutation word error rate (cpWER) value, + matching MeetEval's cpWER algorithm (https://github.com/fgnt/meeteval). + + Algorithm (identical to MeetEval): + 1. Build a square cost matrix of size max(num_hyp, num_ref) using raw edit distance + counts between every (ref_speaker, hyp_speaker) pair. Missing speakers are padded + with empty word lists. + 2. Use the Hungarian algorithm (scipy.optimize.linear_sum_assignment) to find the + speaker assignment that minimizes total edit distance. + 3. Compute per-pair edit distance independently for the optimal assignment. + 4. cpWER = sum(errors_per_pair) / sum(ref_word_counts_per_pair). Args: spk_hypothesis (list): - List containing the hypothesis transcript for each speaker. A list containing the sequence - of words is assigned for each speaker. + List containing the hypothesis transcript 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. + List containing the reference transcript for each speaker. Example: >>> spk_reference = ["hi how are you well that's nice", "i'm good yeah how is your sister"] @@ -385,37 +363,40 @@ def calculate_session_cpWER( 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 = len(spk_hypothesis) + num_ref = len(spk_reference) - num_hyp_spks, num_ref_spks = len(spk_hypothesis), len(spk_reference) + if num_hyp == 0 and num_ref == 0: + return 0.0, "", "" - 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]) + num_speakers_padded = max(num_hyp, num_ref) + + ref_word_lists = [ + spk_reference[ref_idx].split() if ref_idx < num_ref else [] for ref_idx in range(num_speakers_padded) + ] + hyp_word_lists = [ + spk_hypothesis[hyp_idx].split() if hyp_idx < num_hyp else [] for hyp_idx in range(num_speakers_padded) + ] + + cost_matrix = np.zeros((num_speakers_padded, num_speakers_padded), dtype=np.float64) + for ref_idx in range(num_speakers_padded): + for hyp_idx in range(num_speakers_padded): + cost_matrix[ref_idx, hyp_idx] = editdistance.eval(ref_word_lists[ref_idx], hyp_word_lists[hyp_idx]) + + row_ind, col_ind = scipy_linear_sum_assignment(cost_matrix) + + total_errors = 0 + total_ref_length = 0 + hyp_texts = [] + for ref_idx, hyp_idx in zip(row_ind, col_ind): + total_errors += int(cost_matrix[ref_idx, hyp_idx]) + total_ref_length += len(ref_word_lists[ref_idx]) + hyp_texts.append(spk_hypothesis[hyp_idx] if hyp_idx < num_hyp else "") + + cpWER = total_errors / total_ref_length if total_ref_length > 0 else float('inf') + + min_perm_hyp_trans = " ".join(hyp_texts) + ref_trans = " ".join(spk_reference) return cpWER, min_perm_hyp_trans, ref_trans diff --git a/nemo/collections/asr/metrics/multi_binary_acc.py b/nemo/collections/asr/metrics/multi_binary_acc.py index 7b2b9148a74e56b939af0efdbd83b99ed213e1d1..f134bdbd89a1647e26f2e3b939fa521930b69bbc 100644 --- a/nemo/collections/asr/metrics/multi_binary_acc.py +++ b/nemo/collections/asr/metrics/multi_binary_acc.py @@ -81,8 +81,9 @@ class MultiBinaryAccuracy(Metric): 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 + 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. @@ -93,31 +94,30 @@ class MultiBinaryAccuracy(Metric): signal_lengths (torch.Tensor): Length of each sequence in the batch input. cumulative (bool): Whether to accumulate the values over time. """ - with torch.no_grad(): - 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)) + 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): """ @@ -133,6 +133,6 @@ class MultiBinaryAccuracy(Metric): f1_score = (2 * precision * recall / (precision + recall + self.eps)).detach().clone() if torch.isnan(f1_score): - logging.warn("self.f1_score contains NaN value. Returning -1 instead of NaN value.") + 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 new file mode 100644 index 0000000000000000000000000000000000000000..1c10e26de90d21434a4937481b1194e29617e7de --- /dev/null +++ b/nemo/collections/asr/metrics/multitask.py @@ -0,0 +1,423 @@ +# 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 index 312e43983ca575031e57cf4f62ca808db8118b3f..0011de8adc698ad7c41b75ad16daef23dd56546e 100644 --- a/nemo/collections/asr/metrics/wer.py +++ b/nemo/collections/asr/metrics/wer.py @@ -12,6 +12,7 @@ # 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 @@ -238,6 +239,7 @@ class WER(Metric): 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 @@ -255,6 +257,8 @@ class WER(Metric): 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) @@ -263,30 +267,33 @@ class WER(Metric): 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, targets: self.decoding.rnnt_decoder_predictions_tensor( - encoder_output=predictions, encoded_lengths=predictions_lengths + 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, targets: self.decoding.ctc_decoder_predictions_tensor( + 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, targets: self.decoding.decode_predictions_tensor( + 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, + 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, @@ -296,6 +303,7 @@ class WER(Metric): 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. @@ -311,6 +319,7 @@ class WER(Metric): words = 0 scores = 0 references = [] + with torch.no_grad(): tgt_lenths_cpu_tensor = targets_lengths.long().cpu() targets_cpu_tensor = targets.long().cpu() @@ -321,14 +330,18 @@ class WER(Metric): 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_tokens_to_str(target) + reference = self.decoding.decode_ids_to_str(target) references.append(reference) - hypotheses = self.decode(predictions, predictions_lengths, predictions_mask, input_ids, targets) + hypotheses = ( + self.decode(predictions, predictions_lengths, predictions_mask, input_ids) + if predictions.numel() > 0 + else [] + ) - if self.log_prediction: + if hypotheses and self.log_prediction: logging.info("\n") - logging.info(f"reference:{references[0]}") - logging.info(f"predicted:{hypotheses[0].text}") + 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): @@ -345,8 +358,22 @@ class WER(Metric): 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 index 34dead15b33d5828d2fa3d14a264e5d29fb2b88a..cc9b3a74e1ea504719aea6224465b58fc0e3d439 100644 --- a/nemo/collections/asr/models/__init__.py +++ b/nemo/collections/asr/models/__init__.py @@ -12,33 +12,52 @@ # See the License for the specific language governing permissions and # limitations under the License. -from nemo.collections.asr.models.aed_multitask_models import EncDecMultiTaskModel -from nemo.collections.asr.models.asr_model import ASRModel -from nemo.collections.asr.models.classification_models import ( +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 -from nemo.collections.asr.models.ctc_bpe_models import EncDecCTCModelBPE -from nemo.collections.asr.models.ctc_models import EncDecCTCModel -from nemo.collections.asr.models.hybrid_rnnt_ctc_bpe_models import EncDecHybridRNNTCTCBPEModel -from nemo.collections.asr.models.hybrid_rnnt_ctc_models import EncDecHybridRNNTCTCModel -from nemo.collections.asr.models.k2_sequence_models import ( - EncDecK2RnntSeqModel, - EncDecK2RnntSeqModelBPE, - EncDecK2SeqModel, - EncDecK2SeqModelBPE, +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.label_models import EncDecSpeakerLabelModel -from nemo.collections.asr.models.msdd_models import EncDecDiarLabelModel, NeuralDiarizer -from nemo.collections.asr.models.rnnt_bpe_models import EncDecRNNTBPEModel -from nemo.collections.asr.models.rnnt_models import EncDecRNNTModel -from nemo.collections.asr.models.slu_models import SLUIntentSlotBPEModel -from nemo.collections.asr.models.sortformer_diar_models import SortformerEncLabelModel -from nemo.collections.asr.models.ssl_models import ( +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 +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 index 18570e3063171360fc67a9603f0bc92aad9375a0..b5101db1380b27a6e082c2805d5056eb2b0c677c 100644 --- a/nemo/collections/asr/models/aed_multitask_models.py +++ b/nemo/collections/asr/models/aed_multitask_models.py @@ -29,7 +29,7 @@ from nemo.collections.asr.data.audio_to_text_lhotse_prompted import ( PromptedAudioToTextLhotseDataset, PromptedAudioToTextMiniBatch, ) -from nemo.collections.asr.metrics import BLEU, WER +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 ( @@ -40,7 +40,12 @@ from nemo.collections.asr.parts.mixins.transcription import ( 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 @@ -48,6 +53,7 @@ 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, @@ -59,6 +65,7 @@ from nemo.core.neural_types import ( SpectrogramType, ) from nemo.utils import logging, model_utils +from nemo.utils.app_state import AppState __all__ = ['EncDecMultiTaskModel'] @@ -104,6 +111,10 @@ class MultiTaskTranscriptionInternalConfig(InternalTranscribeConfig): 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 @@ -113,6 +124,7 @@ class MultiTaskTranscriptionConfig(TranscribeConfig): _internal: Optional[MultiTaskTranscriptionInternalConfig] = field( default_factory=lambda: MultiTaskTranscriptionInternalConfig() ) + enable_chunking: bool = True def __post_init__(self): self.prompt = parse_multitask_prompt(self.prompt) @@ -125,7 +137,7 @@ class EncDecMultiTaskModel(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRModu # 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) + cfg = model_utils.maybe_update_config_version(cfg, make_copy=False) _config_check(cfg) self.prompt_format = cfg.prompt_format @@ -221,16 +233,33 @@ class EncDecMultiTaskModel(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRModu self.val_loss = GlobalAverageLossMetric(dist_sync_on_step=False, take_avg_loss=True) - # TODO: PytorchMetrics lets you join two metrics together to save compute. - # But need to make wer and bleu have same outputs first - self.wer = WER(self.decoding, log_prediction=self.cfg.get("log_prediction")) - self.bleu = BLEU( - self.decoding, tokenize=self.cfg.get('bleu_tokenizer', "13a"), log_prediction=False - ) # Wer is handling logging + # 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. @@ -256,6 +285,9 @@ class EncDecMultiTaskModel(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRModu 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 @@ -381,6 +413,9 @@ class EncDecMultiTaskModel(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRModu 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 @@ -443,6 +478,9 @@ class EncDecMultiTaskModel(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRModu 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 @@ -466,8 +504,9 @@ class EncDecMultiTaskModel(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRModu ) -> 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 + 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. \ @@ -477,29 +516,44 @@ class EncDecMultiTaskModel(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRModu 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. + 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(). + 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 + 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={: , ...} + **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 + A list of transcriptions (or raw log probabilities if logprobs is True) in the same order as paths2audio_files """ - if timestamps: - raise NotImplementedError("Computing timestamps are not supported for this model yet.") + 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( @@ -510,6 +564,7 @@ class EncDecMultiTaskModel(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRModu augmentor=augmentor, verbose=verbose, prompt=prompt, + timestamps=timestamps, ) else: if not isinstance(override_config, MultiTaskTranscriptionConfig): @@ -518,16 +573,63 @@ class EncDecMultiTaskModel(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRModu 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") - return super().transcribe(audio=audio, override_config=trcfg) + 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]): - assert config.get("use_lhotse", False), ( - "Multi-task model only supports dataloading with Lhotse. " - "Please set config.{train,validation,test}_ds.use_lhotse=True" - ) + + 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, @@ -535,6 +637,7 @@ class EncDecMultiTaskModel(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRModu dataset=PromptedAudioToTextLhotseDataset( tokenizer=self.tokenizer, prompt=self.prompt, + enable_chunking=enable_chunking, # <-- enables chunking ), tokenizer=self.tokenizer, ) @@ -646,7 +749,10 @@ class EncDecMultiTaskModel(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRModu of shape (B, D, T). processed_signal_length: Vector of length B, that contains the individual lengths of the processed audio sequences. - # TODO: Add support for `transcript` and `transcript_length` in the docstring + 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 - @@ -690,7 +796,6 @@ class EncDecMultiTaskModel(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRModu # PTL-specific methods def training_step(self, batch: PromptedAudioToTextMiniBatch, batch_nb): - if batch is None: return torch.tensor([0.0]) @@ -717,19 +822,37 @@ class EncDecMultiTaskModel(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRModu loss_mask = lens_to_mask(input_ids_lens, maxlen) & ~lens_to_mask(batch.prompt_lens - 1, maxlen) else: loss_mask = None - audio_loss = self.loss(log_probs=transf_log_probs, labels=labels, output_mask=loss_mask) - - tensorboard_logs = { - 'train_loss': audio_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, - } + 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 {} + ) - return {'loss': audio_loss, 'log': tensorboard_logs} + 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() @@ -752,35 +875,20 @@ class EncDecMultiTaskModel(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRModu 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) - output_dict = {f'{eval_mode}_loss': transf_loss} - self.wer.update( + metric_dict = self.metric.eval( + batch=batch, predictions=enc_states, predictions_lengths=encoded_len, - targets=batch.transcript, - targets_lengths=batch.transcript_lens, predictions_mask=enc_mask, - input_ids=batch.prompt, + prefix=eval_mode, + return_all_metrics=True, # Need all metrics for computation at end of cycle. ) - wer, wer_num, wer_denom = self.wer.compute() - output_dict.update({"val_wer": wer, "val_wer_num": wer_num, "val_wer_denom": wer_denom}) - self.wer.reset() - - self.bleu.update( - predictions=enc_states, - predictions_lengths=encoded_len, - targets=batch.transcript, - targets_lengths=batch.transcript_lens, - predictions_mask=enc_mask, - input_ids=batch.prompt, - ) - bleu_metrics = self.bleu.compute(prefix=f"{eval_mode}_") - output_dict.update(bleu_metrics) - self.bleu.reset() - - return output_dict + 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") @@ -792,10 +900,10 @@ class EncDecMultiTaskModel(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRModu 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.val_dataloaders) == list and len(self.trainer.val_dataloaders) > 1: - self.validation_step_outputs[dataloader_idx].append(metrics) + if type(self.trainer.test_dataloaders) == list and len(self.trainer.test_dataloaders) > 1: + self.test_step_outputs[dataloader_idx].append(metrics) else: - self.validation_step_outputs.append(metrics) + self.test_step_outputs.append(metrics) return metrics def test_dataloader(self): @@ -826,6 +934,9 @@ class EncDecMultiTaskModel(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRModu 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]: @@ -842,10 +953,12 @@ class EncDecMultiTaskModel(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRModu 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) - return super()._transcribe_input_manifest_processing(audio_files, temp_dir, 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 @@ -925,12 +1038,15 @@ class EncDecMultiTaskModel(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRModu 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()`. @@ -940,39 +1056,89 @@ class EncDecMultiTaskModel(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRModu 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, encoded_len - + 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 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. + 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'] @@ -981,15 +1147,16 @@ class EncDecMultiTaskModel(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRModu # 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': min(batch_size, os.cpu_count() - 1), + 'num_workers': config.get('num_workers', min(batch_size, os.cpu_count() - 1)), 'pin_memory': True, - 'use_lhotse': True, + 'use_lhotse': config.get('use_lhotse', True), 'use_bucketing': False, 'drop_last': False, 'text_field': config.get('text_field', 'answer'), @@ -997,6 +1164,7 @@ class EncDecMultiTaskModel(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRModu '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)) @@ -1028,6 +1196,7 @@ class EncDecMultiTaskModel(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRModu # 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 @@ -1042,11 +1211,44 @@ class EncDecMultiTaskModel(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRModu 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 {} - for k, dv in (("source_lang", "en"), ("target_lang", "en"), ("taskname", "asr"), ("pnc", "yes")): + + # 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 @@ -1060,7 +1262,12 @@ class EncDecMultiTaskModel(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRModu return MultiTaskTranscriptionConfig() def predict_step( - self, batch: PromptedAudioToTextMiniBatch, batch_idx=0, dataloader_idx=0, has_processed_signal=False + self, + batch: PromptedAudioToTextMiniBatch, + batch_idx=0, + dataloader_idx=0, + has_processed_signal=False, + timestamps=False, ): if has_processed_signal: processed_signal = batch.audio @@ -1080,16 +1287,22 @@ class EncDecMultiTaskModel(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRModu processed_signal_length=processed_signal_length, ) - text = self.decoding.decode_predictions_tensor( + 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, text)) + return list(zip(batch.cuts, hypotheses)) else: - return text + return hypotheses @property def adapter_module_names(self) -> List[str]: @@ -1124,6 +1337,56 @@ class EncDecMultiTaskModel(ASRModel, ExportableEncDecModel, ASRBPEMixin, ASRModu ], } + 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: @@ -1155,21 +1418,21 @@ def parse_multitask_prompt(prompt: dict | None) -> list[dict]: # ], # ) if 'turns' in prompt: - assert ( + 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"]) - ), ( - 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=})" - ) + ): + 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") - assert not values_are_dicts, ( - f"We don't support dict values for prompt keys other than 'slots'. " f"We received {prompt=}" - ) + 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. @@ -1181,10 +1444,11 @@ def parse_multitask_prompt(prompt: dict | None) -> list[dict]: # slots=dict(source_lang='en', target_lang='de', task='asr', pnc=True, context='translate this text'), # ) if "role" in prompt and "slots" in prompt: - assert isinstance(prompt["slots"], dict), ( - f"When providing a single-turn prompt through 'role', 'slots' must also be provided " - f"(we received {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. diff --git a/nemo/collections/asr/models/asr_eou_models.py b/nemo/collections/asr/models/asr_eou_models.py new file mode 100644 index 0000000000000000000000000000000000000000..4cb0b8f6076cdad52e8db1195e7316d5cf77c1d6 --- /dev/null +++ b/nemo/collections/asr/models/asr_eou_models.py @@ -0,0 +1,967 @@ +# 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 index ca0634dfaa69893835ddb24dc9b9979b23670a15..3412595b53dee616b1c2883211b32e12c795d56c 100644 --- a/nemo/collections/asr/models/asr_model.py +++ b/nemo/collections/asr/models/asr_model.py @@ -30,7 +30,7 @@ from nemo.utils.cast_utils import cast_all __all__ = ['ASRModel'] -class ASRModel(ModelPT, ABC): +class ASRModel(ModelPT, WithOptionalCudaGraphs, ABC): def multi_validation_epoch_end(self, outputs, dataloader_idx: int = 0): val_loss = {} tensorboard_logs = {} @@ -49,10 +49,10 @@ class ASRModel(ModelPT, ABC): tensorboard_logs.update(val_wer) if "val_bleu_num" in outputs[0]: - bleu_pred_len = torch.stack([x[f"val_bleu_pred_len"] for x in outputs]).sum() - bleu_target_len = torch.stack([x[f"val_bleu_target_len"] for x in outputs]).sum() - bleu_num = torch.stack([x[f"val_bleu_num"] for x in outputs]).sum(dim=0) - bleu_denom = torch.stack([x[f"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() + 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) @@ -77,11 +77,11 @@ class ASRModel(ModelPT, ABC): tensorboard_logs.update(val_wer) if "test_bleu_num" in outputs[0]: - bleu_pred_len = torch.stack([x[f"test_bleu_pred_len"] for x in outputs]).sum() - bleu_target_len = torch.stack([x[f"test_bleu_target_len"] for x in outputs]).sum() - bleu_num = torch.stack([x[f"test_bleu_num"] for x in outputs]).sum() - bleu_denom = torch.stack([x[f"test_bleu_denom"] for x in outputs]).sum() - val_bleu = {"test_bleu": self.wer._compute_bleu(bleu_pred_len, bleu_target_len, bleu_num, bleu_denom)} + 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) @@ -170,29 +170,58 @@ class ASRModel(ModelPT, ABC): torch.distributed.all_reduce(valid_gradients, op=torch.distributed.ReduceOp.MIN) if valid_gradients < 1: - logging.warning(f'detected inf or nan values in gradients! Setting gradients to zero.') + 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 """ - WithOptionalCudaGraphs.disable_cuda_graphs_recursive(self, attribute_path="decoding.decoding") + 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 """ - WithOptionalCudaGraphs.enable_cuda_graphs_recursive(self, attribute_path="decoding.decoding") + 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. """ - WithOptionalCudaGraphs.enable_cuda_graphs_recursive(self, attribute_path="decoding.decoding") + self.maybe_enable_cuda_graphs(force_reinit=True) def on_validation_epoch_end(self) -> Optional[dict[str, dict[str, torch.Tensor]]]: """ @@ -200,24 +229,26 @@ class ASRModel(ModelPT, ABC): training will continue after validation EncDecRNNTModel.decoding.decoding is the inference class with CUDA graphs. """ - WithOptionalCudaGraphs.disable_cuda_graphs_recursive(self, attribute_path="decoding.decoding") + 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. """ - WithOptionalCudaGraphs.enable_cuda_graphs_recursive(self, attribute_path="decoding.decoding") + 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 """ - WithOptionalCudaGraphs.enable_cuda_graphs_recursive(self, attribute_path="decoding.decoding") + self.maybe_enable_cuda_graphs(force_reinit=True) @property def oomptimizer_schema(self) -> dict: diff --git a/nemo/collections/asr/models/classification_models.py b/nemo/collections/asr/models/classification_models.py index f84ece6d24ce878b1572bd5a69e2177f8d095bf6..f15665fa20cb08c9406fba7346039a2cb1a3116c 100644 --- a/nemo/collections/asr/models/classification_models.py +++ b/nemo/collections/asr/models/classification_models.py @@ -29,6 +29,7 @@ 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 @@ -39,7 +40,7 @@ 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 -from nemo.utils.decorators import deprecated + __all__ = ['EncDecClassificationModel', 'EncDecRegressionModel'] @@ -484,31 +485,226 @@ class _EncDecBaseModel(ASRModel, ExportableEncDecModel, TranscriptionMixin): return ClassificationInferConfig() -@deprecated(explanation='EncDecClassificationModel will be merged with EncDecSpeakerLabelModel class.') -class EncDecClassificationModel(_EncDecBaseModel): - """Encoder decoder Classification models.""" +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 - if cfg.get("is_regression_task", False): - raise ValueError(f"EndDecClassificationModel requires the flag is_regression_task to be set as false") + 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. - super().__init__(cfg=cfg, trainer=trainer) + If new_labels == self.decoder.vocabulary then nothing will be changed. - def _setup_preprocessor(self): - return EncDecClassificationModel.from_config_dict(self._cfg.preprocessor) + Args: - def _setup_encoder(self): - return EncDecClassificationModel.from_config_dict(self._cfg.encoder) + new_labels: list with new labels. Must contain at least 2 elements. Typically, \ + this is set of labels for the dataset. - def _setup_decoder(self): - return EncDecClassificationModel.from_config_dict(self._cfg.decoder) + Returns: None - def _setup_loss(self): - return CrossEntropyLoss() + """ + if new_labels is not None and not isinstance(new_labels, ListConfig): + new_labels = ListConfig(new_labels) - def _setup_metrics(self): - self._accuracy = TopKClassificationAccuracy(dist_sync_on_step=True) + 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]]: @@ -584,178 +780,125 @@ class EncDecClassificationModel(_EncDecBaseModel): results.append(model) return results - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - return {"outputs": NeuralType(('B', 'D'), LogitsType())} - - # PTL-specific methods - def training_step(self, batch, batch_nb): - audio_signal, audio_signal_len, labels, labels_len = batch - logits = self.forward(input_signal=audio_signal, input_signal_length=audio_signal_len) - loss_value = self.loss(logits=logits, labels=labels) - - self.log('train_loss', loss_value) - self.log('learning_rate', self._optimizer.param_groups[0]['lr']) - self.log('global_step', self.trainer.global_step) - - self._accuracy(logits=logits, labels=labels) - topk_scores = self._accuracy.compute() - self._accuracy.reset() - - for top_k, score in zip(self._accuracy.top_k, topk_scores): - self.log('training_batch_accuracy_top_{}'.format(top_k), score) - - return { - 'loss': loss_value, - } + def _setup_transcribe_dataloader(self, config: Dict) -> 'torch.utils.data.DataLoader': + """ + Setup function for a temporary data loader which wraps the provided audio file. - def validation_step(self, batch, batch_idx, dataloader_idx=0): - audio_signal, audio_signal_len, labels, labels_len = batch - logits = self.forward(input_signal=audio_signal, input_signal_length=audio_signal_len) - loss_value = self.loss(logits=logits, labels=labels) - acc = self._accuracy(logits=logits, labels=labels) - correct_counts, total_counts = self._accuracy.correct_counts_k, self._accuracy.total_counts_k - loss = { - 'val_loss': loss_value, - 'val_correct_counts': correct_counts, - 'val_total_counts': total_counts, - 'val_acc': acc, - } - if type(self.trainer.val_dataloaders) == list and len(self.trainer.val_dataloaders) > 1: - self.validation_step_outputs[dataloader_idx].append(loss) - else: - self.validation_step_outputs.append(loss) - return loss + Args: + config: A python dictionary which contains the following keys: - def test_step(self, batch, batch_idx, dataloader_idx=0): - audio_signal, audio_signal_len, labels, labels_len = batch - logits = self.forward(input_signal=audio_signal, input_signal_length=audio_signal_len) - loss_value = self.loss(logits=logits, labels=labels) - acc = self._accuracy(logits=logits, labels=labels) - correct_counts, total_counts = self._accuracy.correct_counts_k, self._accuracy.total_counts_k - loss = { - 'test_loss': loss_value, - 'test_correct_counts': correct_counts, - 'test_total_counts': total_counts, - 'test_acc': acc, + 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, } - if type(self.trainer.test_dataloaders) == list and len(self.trainer.test_dataloaders) > 1: - self.test_step_outputs[dataloader_idx].append(loss) - else: - self.test_step_outputs.append(loss) - return loss - - def multi_validation_epoch_end(self, outputs, dataloader_idx: int = 0): - val_loss_mean = torch.stack([x['val_loss'] for x in outputs]).mean() - correct_counts = torch.stack([x['val_correct_counts'] for x in outputs]).sum(axis=0) - total_counts = torch.stack([x['val_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._accuracy.reset() - - tensorboard_log = {'val_loss': val_loss_mean} - for top_k, score in zip(self._accuracy.top_k, topk_scores): - tensorboard_log['val_epoch_top@{}'.format(top_k)] = score - - return {'log': tensorboard_log} - - def multi_test_epoch_end(self, outputs, dataloader_idx: int = 0): - test_loss_mean = torch.stack([x['test_loss'] for x in outputs]).mean() - correct_counts = torch.stack([x['test_correct_counts'].unsqueeze(0) for x in outputs]).sum(axis=0) - total_counts = torch.stack([x['test_total_counts'].unsqueeze(0) 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._accuracy.reset() - - tensorboard_log = {'test_loss': test_loss_mean} - for top_k, score in zip(self._accuracy.top_k, topk_scores): - tensorboard_log['test_epoch_top@{}'.format(top_k)] = score - - return {'log': tensorboard_log} - - @typecheck() - def forward( - self, input_signal=None, input_signal_length=None, processed_signal=None, processed_signal_length=None - ): - logits = super().forward( - input_signal=input_signal, - input_signal_length=input_signal_length, - processed_signal=processed_signal, - processed_signal_length=processed_signal_length, - ) - return logits + temporary_datalayer = self._setup_dataloader_from_config(config=DictConfig(dl_config)) + return temporary_datalayer - def change_labels(self, new_labels: List[str]): + @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: """ - 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. + 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. - new_labels: list with new labels. Must contain at least 2 elements. Typically, \ - this is set of labels for the dataset. - - Returns: None + Returns: + A list of transcriptions (or raw log probabilities if logprobs is True) in the same order as paths2audio_files """ - if new_labels is not None and not isinstance(new_labels, ListConfig): - new_labels = ListConfig(new_labels) + if logprobs is None: + logprobs = self.is_regression_task - if self._cfg.labels == new_labels: - logging.warning( - f"Old labels ({self._cfg.labels}) and new labels ({new_labels}) match. Not changing anything" - ) + 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 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}') + 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 - # Update config - self._cfg.labels = new_labels + return super().transcribe(audio=audio, override_config=trcfg) - 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) + """ Transcription related methods """ - OmegaConf.set_struct(self._cfg.decoder, False) - self._cfg.decoder = new_decoder_config - OmegaConf.set_struct(self._cfg.decoder, True) + 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') - if 'train_ds' in self._cfg and self._cfg.train_ds is not None: - self._cfg.train_ds.labels = new_labels + config = {'paths2audio_files': audio_files, 'batch_size': trcfg.batch_size, 'temp_dir': temp_dir} + return config - if 'validation_ds' in self._cfg and self._cfg.validation_ds is not None: - self._cfg.validation_ds.labels = new_labels + 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 - if 'test_ds' in self._cfg and self._cfg.test_ds is not None: - self._cfg.test_ds.labels = new_labels + def _transcribe_output_processing( + self, outputs, trcfg: ClassificationInferConfig + ) -> Union[List[str], List[torch.Tensor]]: + logits = outputs.pop('logits') + labels = [] - logging.info(f"Changed decoder output to {self.decoder.num_classes} 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) - def _update_decoder_config(self, labels, cfg): - """ - Update the number of classes in the decoder based on labels provided. + # convenience: if only one top_k, pop out the nested list + if len(top_ks) == 1: + labels_k = labels_k[0] - Args: - labels: The current labels of the model - cfg: The config of the decoder which will be updated. - """ - OmegaConf.set_struct(cfg, False) + labels += labels_k + # reset top k to orignal value + self._accuracy.top_k = top_ks - if 'params' in cfg: - cfg.params.num_classes = len(labels) - else: - cfg.num_classes = len(labels) + return labels - OmegaConf.set_struct(cfg, True) + def forward(self, input_signal, input_signal_length): + logits, _ = super().forward(input_signal, input_signal_length) + return logits class EncDecRegressionModel(_EncDecBaseModel): @@ -777,7 +920,7 @@ class EncDecRegressionModel(_EncDecBaseModel): def __init__(self, cfg: DictConfig, trainer: Trainer = None): if not cfg.get('is_regression_task', False): - raise ValueError(f"EndDecRegressionModel requires the flag is_regression_task to be set as true") + raise ValueError("EndDecRegressionModel requires the flag is_regression_task to be set as true") super().__init__(cfg=cfg, trainer=trainer) def _setup_preprocessor(self): @@ -901,19 +1044,27 @@ class EncDecRegressionModel(_EncDecBaseModel): OmegaConf.set_struct(cfg, True) -class EncDecFrameClassificationModel(EncDecClassificationModel): - @property - def output_types(self) -> Optional[Dict[str, NeuralType]]: - return {"outputs": NeuralType(('B', 'T', 'C'), LogitsType())} +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 = [] @@ -925,6 +1076,32 @@ class EncDecFrameClassificationModel(EncDecClassificationModel): 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") @@ -1086,7 +1263,7 @@ class EncDecFrameClassificationModel(EncDecClassificationModel): self._macro_accuracy.update(preds=metric_logits, target=metric_labels) stats = self._macro_accuracy._final_state() - return { + output = { f'{tag}_loss': loss_value, f'{tag}_correct_counts': correct_counts, f'{tag}_total_counts': total_counts, @@ -1094,6 +1271,18 @@ class EncDecFrameClassificationModel(EncDecClassificationModel): 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) diff --git a/nemo/collections/asr/models/clustering_diarizer.py b/nemo/collections/asr/models/clustering_diarizer.py index 1f03cec59af7f50b59bf99d9e6af04497597f62d..59f043f745554d757861221d71f70352af051ef1 100644 --- a/nemo/collections/asr/models/clustering_diarizer.py +++ b/nemo/collections/asr/models/clustering_diarizer.py @@ -16,7 +16,6 @@ import json import os import pickle as pkl import shutil -import tarfile import tempfile from copy import deepcopy from typing import Any, List, Optional, Union @@ -47,6 +46,7 @@ from nemo.collections.asr.parts.utils.vad_utils import ( 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'] @@ -378,7 +378,7 @@ class ClusteringDiarizer(torch.nn.Module, Model, DiarizationMixin): prefix = get_uniqname_from_filepath(manifest_file) name = os.path.join(embedding_dir, prefix) - self._embeddings_file = name + f'_embeddings.pkl' + self._embeddings_file = name + '_embeddings.pkl' pkl.dump(self.embeddings, open(self._embeddings_file, 'wb')) logging.info("Saved embedding files to {}".format(embedding_dir)) @@ -460,11 +460,6 @@ class ClusteringDiarizer(torch.nn.Module, Model, DiarizationMixin): verbose=self.verbose, ) - @staticmethod - def __make_nemo_file_from_folder(filename, source_dir): - with tarfile.open(filename, "w:gz") as tar: - tar.add(source_dir, arcname="./") - @rank_zero_only def save_to(self, save_path: str): """ @@ -490,16 +485,7 @@ class ClusteringDiarizer(torch.nn.Module, Model, DiarizationMixin): vad_model = os.path.join(tmpdir, _VAD_MODEL) self._vad_model.save_to(vad_model) self._speaker_model.save_to(spkr_model) - self.__make_nemo_file_from_folder(filename=save_path, source_dir=tmpdir) - - @staticmethod - def __unpack_nemo_file(path2file: str, out_folder: str) -> str: - if not os.path.exists(path2file): - raise FileNotFoundError(f"{path2file} does not exist") - tar = tarfile.open(path2file, "r:gz") - tar.extractall(path=out_folder) - tar.close() - return out_folder + SaveRestoreConnector._make_nemo_file_from_folder(filename=save_path, source_dir=tmpdir) @classmethod def restore_from( @@ -507,7 +493,6 @@ class ClusteringDiarizer(torch.nn.Module, Model, DiarizationMixin): restore_path: str, override_config_path: Optional[str] = None, map_location: Optional[torch.device] = None, - strict: bool = False, ): # Get path where the command is executed - the artifacts will be "retrieved" there # (original .nemo behavior) @@ -515,7 +500,7 @@ class ClusteringDiarizer(torch.nn.Module, Model, DiarizationMixin): with tempfile.TemporaryDirectory() as tmpdir: try: - cls.__unpack_nemo_file(path2file=restore_path, out_folder=tmpdir) + 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) diff --git a/nemo/collections/asr/models/confidence_ensemble.py b/nemo/collections/asr/models/confidence_ensemble.py index 932d221be0f82d59a81539eec2d7b7c9b54bfe17..7f0b262ae420432a0f0b29b07ccd8e8ad844d87b 100644 --- a/nemo/collections/asr/models/confidence_ensemble.py +++ b/nemo/collections/asr/models/confidence_ensemble.py @@ -12,18 +12,21 @@ # 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 -from typing import Dict, List, Optional, Union -import joblib -import numpy as np +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 lightning.pytorch import Trainer -from omegaconf import DictConfig, open_dict +from sklearn.linear_model import LogisticRegression +from sklearn.pipeline import Pipeline +from sklearn.preprocessing import StandardScaler -from nemo.collections.asr.models.asr_model import ASRModel -from nemo.collections.asr.models.hybrid_rnnt_ctc_models import EncDecHybridRNNTCTCModel -from nemo.collections.asr.parts.preprocessing.segment import ChannelSelectorType from nemo.collections.asr.parts.utils.asr_confidence_utils import ( ConfidenceConfig, ConfidenceMethodConfig, @@ -31,9 +34,6 @@ from nemo.collections.asr.parts.utils.asr_confidence_utils import ( get_confidence_measure_bank, ) from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis -from nemo.core.classes import ModelPT -from nemo.utils import model_utils -from nemo.utils.decorators import deprecated # frozen is required to allow hashing of this class and use it @@ -152,183 +152,82 @@ def compute_confidence(hypothesis: Hypothesis, confidence_cfg: ConfidenceConfig) return conf_value -@deprecated(version='v2.1.0') -class ConfidenceEnsembleModel(ModelPT): - """Implementation of the confidence ensemble model. +def safe_joblib_load(file_path: str) -> Pipeline: + """ + Safely load a joblib file containing a scikit-learn pipeline. - See https://arxiv.org/abs/2306.15824 for details. + Args: + file_path: Path to the joblib file - .. note:: - Currently this class only support `transcribe` method as it requires - full-utterance confidence scores to operate. - """ + Returns: + Pipeline: A scikit-learn pipeline object - def __init__( - self, - cfg: DictConfig, - trainer: 'Trainer' = None, - ): - super().__init__(cfg=cfg, trainer=trainer) - - # either we load all models from ``load_models`` cfg parameter - # or all of them are specified in the config as modelX alongside the num_models key - # - # ideally, we'd like to directly store all models in a list, but that - # is not currently supported by the submodule logic - # so to access all the models, we do something like - # - # for model_idx in range(self.num_models): - # model = getattr(self, f"model{model_idx}") - - if 'num_models' in self.cfg: - self.num_models = self.cfg.num_models - for idx in range(self.num_models): - cfg_field = f"model{idx}" - model_cfg = self.cfg[cfg_field] - model_class = model_utils.import_class_by_path(model_cfg['target']) - self.register_nemo_submodule( - name=cfg_field, - config_field=cfg_field, - model=model_class(model_cfg, trainer=trainer), - ) - else: - self.num_models = len(cfg.load_models) - with open_dict(self.cfg): - self.cfg.num_models = self.num_models - for idx, model in enumerate(cfg.load_models): - cfg_field = f"model{idx}" - if model.endswith(".nemo"): - self.register_nemo_submodule( - name=cfg_field, - config_field=cfg_field, - model=ASRModel.restore_from(model, trainer=trainer, map_location="cpu"), - ) - else: - self.register_nemo_submodule( - cfg_field, - config_field=cfg_field, - model=ASRModel.from_pretrained(model, map_location="cpu"), - ) - - # registering model selection block - this is expected to be a joblib-saved - # pretrained sklearn pipeline containing standardization + logistic regression - # trained to predict "most-confident" model index from the confidence scores of all models - model_selection_block_path = self.register_artifact("model_selection_block", cfg.model_selection_block) - self.model_selection_block = joblib.load(model_selection_block_path) - self.confidence_cfg = ConfidenceConfig(**self.cfg.confidence) - - # making sure each model has correct temperature setting in the decoder strategy - for model_idx in range(self.num_models): - model = getattr(self, f"model{model_idx}") - # for now we assume users are direclty responsible for matching - # decoder type when building ensemble with inference type - # TODO: add automatic checks for errors - if isinstance(model, EncDecHybridRNNTCTCModel): - self.update_decoding_parameters(model.cfg.decoding) - model.change_decoding_strategy(model.cfg.decoding, decoder_type="rnnt") - self.update_decoding_parameters(model.cfg.aux_ctc.decoding) - model.change_decoding_strategy(model.cfg.aux_ctc.decoding, decoder_type="ctc") - else: - self.update_decoding_parameters(model.cfg.decoding) - model.change_decoding_strategy(model.cfg.decoding) - - def update_decoding_parameters(self, decoding_cfg: DictConfig): - """Updating temperature/preserve_alignment parameters of the config.""" - with open_dict(decoding_cfg): - decoding_cfg.temperature = self.cfg.temperature - decoding_cfg.preserve_alignments = True - - def setup_training_data(self, train_data_config: Union[DictConfig, Dict]): - """Pass-through to the ensemble models. - - Note that training is not actually supported for this class! - """ - for model_idx in range(self.num_models): - getattr(self, f"model{model_idx}").setup_training_data(train_data_config) - - def setup_validation_data(self, val_data_config: Union[DictConfig, Dict]): - """Pass-through to the ensemble models.""" - for model_idx in range(self.num_models): - getattr(self, f"model{model_idx}").setup_validation_data(val_data_config) - - def change_attention_model( - self, self_attention_model: str = None, att_context_size: List[int] = None, update_config: bool = True - ): - """Pass-through to the ensemble models.""" - for model_idx in range(self.num_models): - getattr(self, f"model{model_idx}").change_attention_model( - self_attention_model, att_context_size, update_config - ) - - def change_decoding_strategy(self, decoding_cfg: Optional[DictConfig] = None, decoder_type: str = None): - """Pass-through to the ensemble models. - - The only change here is that we always require expected temperature - to be set as well as ``decoding_cfg.preserve_alignments = True`` - """ - self.update_decoding_parameters(decoding_cfg) - for model_idx in range(self.num_models): - model = getattr(self, f"model{model_idx}") - if isinstance(model, EncDecHybridRNNTCTCModel): - model.change_decoding_strategy(decoding_cfg, decoder_type=decoder_type) - else: - model.change_decoding_strategy(decoding_cfg) - - @torch.no_grad() - def transcribe( - self, - paths2audio_files: List[str], - batch_size: int = 4, - return_hypotheses: bool = False, - num_workers: int = 0, - channel_selector: Optional[ChannelSelectorType] = None, - augmentor: DictConfig = None, - verbose: bool = True, - **kwargs, # any other model specific parameters are passed directly - ) -> List[str]: - """Confidence-ensemble transcribe method. - - Consists of the following steps: - - 1. Run all models (TODO: in parallel) - 2. Compute confidence for each model - 3. Use logistic regression to pick the "most confident" model - 4. Return the output of that model - """ - confidences = [] - all_transcriptions = [] - # always requiring to return hypothesis - # TODO: make sure to return text only if was False originally - return_hypotheses = True - for model_idx in range(self.num_models): - model = getattr(self, f"model{model_idx}") - transcriptions = model.transcribe( - paths2audio_files=paths2audio_files, - batch_size=batch_size, - return_hypotheses=return_hypotheses, - num_workers=num_workers, - channel_selector=channel_selector, - augmentor=augmentor, - verbose=verbose, - **kwargs, - ) - if isinstance(transcriptions, tuple): # transducers return a tuple - transcriptions = transcriptions[0] - - model_confidences = [] - for transcription in transcriptions: - model_confidences.append(compute_confidence(transcription, self.confidence_cfg)) - confidences.append(model_confidences) - all_transcriptions.append(transcriptions) - - # transposing with zip(*list) - features = np.array(list(zip(*confidences))) - model_indices = self.model_selection_block.predict(features) - final_transcriptions = [] - for transcrption_idx in range(len(all_transcriptions[0])): - final_transcriptions.append(all_transcriptions[model_indices[transcrption_idx]][transcrption_idx]) - - return final_transcriptions - - def list_available_models(self): - return [] + 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 index b25f1119adcffddd2def23f32d0cbaf9e5046a49..8a18906a7ec30a17a51bdc936c832fd55cb25fab 100644 --- a/nemo/collections/asr/models/configs/__init__.py +++ b/nemo/collections/asr/models/configs/__init__.py @@ -12,35 +12,29 @@ # See the License for the specific language governing permissions and # limitations under the License. -from nemo.collections.asr.models.configs.asr_models_config import ( +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 ( +from nemo.collections.asr.models.configs.classification_models_config import ( # noqa: F401 EncDecClassificationConfig, EncDecClassificationDatasetConfig, EncDecClassificationModelConfig, ) -from nemo.collections.asr.models.configs.diarizer_config import NeuralDiarizerInferenceConfig -from nemo.collections.asr.models.configs.matchboxnet_config import ( +from nemo.collections.asr.models.configs.matchboxnet_config import ( # noqa: F401 EncDecClassificationModelConfigBuilder, MatchboxNetModelConfig, MatchboxNetVADModelConfig, ) -from nemo.collections.asr.models.configs.quartznet_config import ( - EncDecCTCModelConfigBuilder, - JasperModelConfig, - QuartzNetModelConfig, -) -from nemo.collections.asr.modules.audio_preprocessing import ( +from nemo.collections.asr.modules.audio_preprocessing import ( # noqa: F401 AudioToMelSpectrogramPreprocessorConfig, AudioToMFCCPreprocessorConfig, CropOrPadSpectrogramAugmentationConfig, SpectrogramAugmentationConfig, ) -from nemo.collections.asr.modules.conv_asr import ( +from nemo.collections.asr.modules.conv_asr import ( # noqa: F401 ConvASRDecoderClassificationConfig, ConvASRDecoderConfig, ConvASREncoderConfig, diff --git a/nemo/collections/asr/models/configs/aligner_config.py b/nemo/collections/asr/models/configs/aligner_config.py deleted file mode 100644 index cf2cdd176719d3eb1b28c0f9104bd6959d3cd30a..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/configs/aligner_config.py +++ /dev/null @@ -1,44 +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 nemo.collections.asr.parts.k2.classes import GraphModuleConfig - - -@dataclass -class AlignerCTCConfig: - prob_suppress_index: int = -1 - prob_suppress_value: float = 1.0 - - -@dataclass -class AlignerRNNTConfig: - predictor_window_size: int = 0 - predictor_step_size: int = 1 - - -@dataclass -class AlignerWrapperModelConfig: - alignment_type: str = "forced" - word_output: bool = True - cpu_decoding: bool = False - decode_batch_size: int = 0 - ctc_cfg: AlignerCTCConfig = field(default_factory=lambda: AlignerCTCConfig()) - rnnt_cfg: AlignerRNNTConfig = field(default_factory=lambda: AlignerRNNTConfig()) - - -@dataclass -class K2AlignerWrapperModelConfig(AlignerWrapperModelConfig): - decoder_module_cfg: GraphModuleConfig = field(default_factory=lambda: GraphModuleConfig()) diff --git a/nemo/collections/asr/models/configs/diarizer_config.py b/nemo/collections/asr/models/configs/diarizer_config.py index 0745a6f2a4511d5545c1d23a421b05139f5743f8..63f220b5f494efef0d3081021c8408f8faee3b07 100644 --- a/nemo/collections/asr/models/configs/diarizer_config.py +++ b/nemo/collections/asr/models/configs/diarizer_config.py @@ -93,8 +93,8 @@ class VADParams(DiarizerComponentConfig): 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 small non_speech deletion - min_duration_off: float = 0.2 # Threshold for short speech segment deletion + 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 @@ -113,7 +113,7 @@ class SpeakerEmbeddingsParams(DiarizerComponentConfig): 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. True if clustering result is used for other models, such as MSDD. + # save speaker embeddings in pickle format. save_embeddings: bool = True @@ -145,30 +145,6 @@ class ClusteringConfig(DiarizerComponentConfig): parameters: ClusteringParams = field(default_factory=lambda: ClusteringParams()) -@dataclass -class MSDDParams(DiarizerComponentConfig): - # If True, use speaker embedding model in checkpoint, else provided speaker embedding model in config will be used. - use_speaker_model_from_ckpt: bool = True - # Batch size for MSDD inference. - infer_batch_size: int = 25 - # Sigmoid threshold for generating binarized speaker labels. The smaller the more generous on detecting overlaps. - sigmoid_threshold: Tuple[float] = (0.7,) - # If True, use oracle number of speaker and evaluate F1 score for the given speaker sequences. Default is False. - seq_eval_mode: bool = False - # If True, break the input audio clip to short sequences and calculate cluster average embeddings for inference. - split_infer: bool = True - # The length of split short sequence when split_infer is True. - diar_window_length: int = 50 - # If the estimated number of speakers are larger than this number, overlap speech is not estimated. - overlap_infer_spk_limit: int = 5 - - -@dataclass -class MSDDConfig(DiarizerComponentConfig): - model_path: Optional[str] = "diar_msdd_telephonic" - parameters: MSDDParams = field(default_factory=lambda: MSDDParams()) - - @dataclass class DiarizerConfig(DiarizerComponentConfig): manifest_filepath: Optional[str] = None @@ -179,26 +155,4 @@ class DiarizerConfig(DiarizerComponentConfig): vad: VADConfig = field(default_factory=lambda: VADConfig()) speaker_embeddings: SpeakerEmbeddingsConfig = field(default_factory=lambda: SpeakerEmbeddingsConfig()) clustering: ClusteringConfig = field(default_factory=lambda: ClusteringConfig()) - msdd_model: MSDDConfig = field(default_factory=lambda: MSDDConfig()) asr: ASRDiarizerConfig = field(default_factory=lambda: ASRDiarizerConfig()) - - -@dataclass -class NeuralDiarizerInferenceConfig(DiarizerComponentConfig): - diarizer: DiarizerConfig = field(default_factory=lambda: DiarizerConfig()) - device: str = "cpu" - verbose: bool = False - batch_size: int = 64 - num_workers: int = 1 - sample_rate: int = 16000 - name: str = "" - - @classmethod - def init_config(cls, diar_model_path: str, vad_model_path: str, map_location: str, verbose: bool): - return NeuralDiarizerInferenceConfig( - DiarizerConfig( - vad=VADConfig(model_path=vad_model_path), msdd_model=MSDDConfig(model_path=diar_model_path), - ), - device=map_location, - verbose=verbose, - ) diff --git a/nemo/collections/asr/models/configs/k2_sequence_models_config.py b/nemo/collections/asr/models/configs/k2_sequence_models_config.py deleted file mode 100644 index 53ed3e1377fe9e27253f1d07cc9d8a0686102cf7..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/configs/k2_sequence_models_config.py +++ /dev/null @@ -1,39 +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 nemo.collections.asr.models.configs.asr_models_config import EncDecCTCConfig -from nemo.collections.asr.parts.k2.classes import GraphModuleConfig as BackendConfig -from nemo.core.config.modelPT import NemoConfig - - -@dataclass -class GraphModuleConfig: - criterion_type: str = "ml" - loss_type: str = "ctc" - split_batch_size: int = 0 - dec_type: str = "topo" - transcribe_training: bool = True - backend_cfg: BackendConfig = field(default_factory=lambda: BackendConfig()) - - -@dataclass -class EncDecK2SeqConfig(EncDecCTCConfig): - graph_module_cfg: GraphModuleConfig = field(default_factory=lambda: GraphModuleConfig()) - - -@dataclass -class EncDecK2SeqModelConfig(NemoConfig): - model: EncDecK2SeqConfig = field(default_factory=lambda: EncDecK2SeqConfig()) diff --git a/nemo/collections/asr/models/configs/quartznet_config.py b/nemo/collections/asr/models/configs/quartznet_config.py deleted file mode 100644 index 93412b0053bf17296615f3d4f738c29f9f689d2b..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/configs/quartznet_config.py +++ /dev/null @@ -1,316 +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 asr_models_config as ctc_cfg -from nemo.collections.asr.modules.audio_preprocessing import ( - AudioToMelSpectrogramPreprocessorConfig, - SpectrogramAugmentationConfig, -) -from nemo.collections.asr.modules.conv_asr import ConvASRDecoderConfig, ConvASREncoderConfig, JasperEncoderConfig -from nemo.core.config import modelPT as model_cfg - - -# fmt: off -def qn_15x5(): - config = [ - JasperEncoderConfig(filters=256, repeat=1, kernel=[33], stride=[2], 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=256, repeat=5, kernel=[33], 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=256, repeat=5, kernel=[33], 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=256, repeat=5, kernel=[33], 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=256, repeat=5, kernel=[39], 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=256, repeat=5, kernel=[39], 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=256, repeat=5, kernel=[39], 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=512, repeat=5, kernel=[51], 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=512, repeat=5, kernel=[51], 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=512, repeat=5, kernel=[51], 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=512, repeat=5, kernel=[63], 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=512, repeat=5, kernel=[63], 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=512, repeat=5, kernel=[63], 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=512, repeat=5, kernel=[75], 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=512, repeat=5, kernel=[75], 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=512, repeat=5, kernel=[75], 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=512, repeat=1, kernel=[87], 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=1024, 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 jasper_10x5_dr(): - config = [ - JasperEncoderConfig(filters=256, repeat=1, kernel=[11], stride=[2], dilation=[1], dropout=0.2, - 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), - JasperEncoderConfig(filters=256, repeat=5, kernel=[11], stride=[1], dilation=[1], dropout=0.2, - residual=True, groups=1, separable=False, heads=-1, residual_mode='add', - residual_dense=True, se=False, se_reduction_ratio=8, se_context_size=-1, - se_interpolation_mode='nearest', kernel_size_factor=1.0, stride_last=False), - JasperEncoderConfig(filters=256, repeat=5, kernel=[11], stride=[1], dilation=[1], dropout=0.2, - residual=True, groups=1, separable=False, heads=-1, residual_mode='add', - residual_dense=True, se=False, se_reduction_ratio=8, se_context_size=-1, - se_interpolation_mode='nearest', kernel_size_factor=1.0, stride_last=False), - JasperEncoderConfig(filters=384, repeat=5, kernel=[13], stride=[1], dilation=[1], dropout=0.2, - residual=True, groups=1, separable=False, heads=-1, residual_mode='add', - residual_dense=True, se=False, se_reduction_ratio=8, se_context_size=-1, - se_interpolation_mode='nearest', kernel_size_factor=1.0, stride_last=False), - JasperEncoderConfig(filters=384, repeat=5, kernel=[13], stride=[1], dilation=[1], dropout=0.2, - residual=True, groups=1, separable=False, heads=-1, residual_mode='add', - residual_dense=True, se=False, se_reduction_ratio=8, se_context_size=-1, - se_interpolation_mode='nearest', kernel_size_factor=1.0, stride_last=False), - JasperEncoderConfig(filters=512, repeat=5, kernel=[17], stride=[1], dilation=[1], dropout=0.2, - residual=True, groups=1, separable=False, heads=-1, residual_mode='add', - residual_dense=True, se=False, se_reduction_ratio=8, se_context_size=-1, - se_interpolation_mode='nearest', kernel_size_factor=1.0, stride_last=False), - JasperEncoderConfig(filters=512, repeat=5, kernel=[17], stride=[1], dilation=[1], dropout=0.2, - residual=True, groups=1, separable=False, heads=-1, residual_mode='add', - residual_dense=True, se=False, se_reduction_ratio=8, se_context_size=-1, - se_interpolation_mode='nearest', kernel_size_factor=1.0, stride_last=False), - JasperEncoderConfig(filters=640, repeat=5, kernel=[21], stride=[1], dilation=[1], dropout=0.3, - residual=True, groups=1, separable=False, heads=-1, residual_mode='add', - residual_dense=True, se=False, se_reduction_ratio=8, se_context_size=-1, - se_interpolation_mode='nearest', kernel_size_factor=1.0, stride_last=False), - JasperEncoderConfig(filters=640, repeat=5, kernel=[21], stride=[1], dilation=[1], dropout=0.3, - residual=True, groups=1, separable=False, heads=-1, residual_mode='add', - residual_dense=True, se=False, se_reduction_ratio=8, se_context_size=-1, - se_interpolation_mode='nearest', kernel_size_factor=1.0, stride_last=False), - JasperEncoderConfig(filters=768, repeat=5, kernel=[25], stride=[1], dilation=[1], dropout=0.3, - residual=True, groups=1, separable=False, heads=-1, residual_mode='add', - residual_dense=True, se=False, se_reduction_ratio=8, se_context_size=-1, - se_interpolation_mode='nearest', kernel_size_factor=1.0, stride_last=False), - JasperEncoderConfig(filters=768, repeat=5, kernel=[25], stride=[1], dilation=[1], dropout=0.3, - residual=True, groups=1, separable=False, heads=-1, residual_mode='add', - residual_dense=True, se=False, se_reduction_ratio=8, se_context_size=-1, - se_interpolation_mode='nearest', kernel_size_factor=1.0, stride_last=False), - JasperEncoderConfig(filters=896, repeat=1, kernel=[29], stride=[1], dilation=[2], dropout=0.4, - 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), - JasperEncoderConfig(filters=1024, repeat=1, kernel=[1], stride=[1], dilation=[1], dropout=0.4, - 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 JasperModelConfig(ctc_cfg.EncDecCTCConfig): - # 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: ctc_cfg.ASRDatasetConfig = field( - default_factory=lambda: ctc_cfg.ASRDatasetConfig(manifest_filepath=None, shuffle=True, trim_silence=True) - ) - validation_ds: ctc_cfg.ASRDatasetConfig = field( - default_factory=lambda: ctc_cfg.ASRDatasetConfig(manifest_filepath=None, shuffle=False) - ) - test_ds: ctc_cfg.ASRDatasetConfig = field( - default_factory=lambda: ctc_cfg.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 general 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(activation="relu")) - decoder: ConvASRDecoderConfig = field(default_factory=lambda: ConvASRDecoderConfig()) - - -@dataclass -class QuartzNetModelConfig(JasperModelConfig): - separable: bool = True - - -class EncDecCTCModelConfigBuilder(model_cfg.ModelConfigBuilder): - VALID_CONFIGS = ['quartznet_15x5', 'quartznet_15x5_zh', 'jasper_10x5dr'] - - def __init__(self, name: str = 'quartznet_15x5', encoder_cfg_func: Optional[Callable[[], List[Any]]] = None): - if name not in EncDecCTCModelConfigBuilder.VALID_CONFIGS: - raise ValueError("`name` must be one of : \n" f"{EncDecCTCModelConfigBuilder.VALID_CONFIGS}") - - self.name = name - - if 'quartznet_15x5' in name: - if encoder_cfg_func is None: - encoder_cfg_func = qn_15x5 - - model_cfg = QuartzNetModelConfig( - repeat=5, - separable=True, - spec_augment=SpectrogramAugmentationConfig(rect_masks=5, rect_freq=50, rect_time=120), - encoder=ConvASREncoderConfig(jasper=encoder_cfg_func(), activation="relu"), - decoder=ConvASRDecoderConfig(), - ) - - elif 'jasper_10x5' in name: - if encoder_cfg_func is None: - encoder_cfg_func = jasper_10x5_dr - - model_cfg = JasperModelConfig( - repeat=5, - separable=False, - spec_augment=SpectrogramAugmentationConfig(rect_masks=5, rect_freq=50, rect_time=120), - encoder=ConvASREncoderConfig(jasper=encoder_cfg_func(), activation="relu"), - decoder=ConvASRDecoderConfig(), - ) - - else: - raise ValueError(f"Invalid config name submitted to {self.__class__.__name__}") - - super(EncDecCTCModelConfigBuilder, self).__init__(model_cfg) - self.model_cfg: ctc_cfg.EncDecCTCConfig = model_cfg # enable type hinting - - if 'zh' in name: - self.set_dataset_normalize(normalize=False) - - 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_dataset_normalize(self, normalize: bool): - self.model_cfg.train_ds.normalize = normalize - self.model_cfg.validation_ds.normalize = normalize - self.model_cfg.test_ds.normalize = normalize - - # 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[ctc_cfg.ASRDatasetConfig] = None): - # super().set_train_ds(cfg) - # - # def set_validation_ds(self, cfg: Optional[ctc_cfg.ASRDatasetConfig] = None): - # super().set_validation_ds(cfg) - # - # def set_test_ds(self, cfg: Optional[ctc_cfg.ASRDatasetConfig] = 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 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) -> ctc_cfg.EncDecCTCConfig: - return super().build() diff --git a/nemo/collections/asr/models/ctc_bpe_models.py b/nemo/collections/asr/models/ctc_bpe_models.py index 874cde628c354deddadd568ad2ff556d88f78df5..abd6cba0fb20c2b3b61aa34156d71267b0bb5f3a 100644 --- a/nemo/collections/asr/models/ctc_bpe_models.py +++ b/nemo/collections/asr/models/ctc_bpe_models.py @@ -42,7 +42,7 @@ class EncDecCTCModelBPE(EncDecCTCModel, ASRBPEMixin): 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) + 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 !") @@ -190,6 +190,7 @@ class EncDecCTCModelBPE(EncDecCTCModel, ASRBPEMixin): 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, @@ -250,7 +251,7 @@ class EncDecCTCModelBPE(EncDecCTCModel, ASRBPEMixin): ) if new_tokenizer_type.lower() not in ('bpe', 'wpe'): - raise ValueError(f'New tokenizer type must be either `bpe` or `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}) @@ -473,48 +474,6 @@ class EncDecCTCModelBPE(EncDecCTCModel, ASRBPEMixin): ) results.append(model) - model = PretrainedModelInfo( - pretrained_model_name="stt_en_squeezeformer_ctc_xsmall_ls", - description="For details about this model, please visit https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/stt_en_squeezeformer_ctc_xsmall_ls", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_squeezeformer_ctc_xsmall_ls/versions/1.13.0/files/stt_en_squeezeformer_ctc_xsmall_ls.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_squeezeformer_ctc_small_ls", - description="For details about this model, please visit https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/stt_en_squeezeformer_ctc_small_ls", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_squeezeformer_ctc_small_ls/versions/1.13.0/files/stt_en_squeezeformer_ctc_small_ls.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_squeezeformer_ctc_small_medium_ls", - description="For details about this model, please visit https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/stt_en_squeezeformer_ctc_small_medium_ls", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_squeezeformer_ctc_small_medium_ls/versions/1.13.0/files/stt_en_squeezeformer_ctc_small_medium_ls.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_squeezeformer_ctc_medium_ls", - description="For details about this model, please visit https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/stt_en_squeezeformer_ctc_medium_ls", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_squeezeformer_ctc_medium_ls/versions/1.13.0/files/stt_en_squeezeformer_ctc_medium_ls.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_squeezeformer_ctc_medium_large_ls", - description="For details about this model, please visit https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/stt_en_squeezeformer_ctc_medium_large_ls", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_squeezeformer_ctc_medium_large_ls/versions/1.13.0/files/stt_en_squeezeformer_ctc_medium_large_ls.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_squeezeformer_ctc_large_ls", - description="For details about this model, please visit https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/stt_en_squeezeformer_ctc_large_ls", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_squeezeformer_ctc_large_ls/versions/1.13.0/files/stt_en_squeezeformer_ctc_large_ls.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", diff --git a/nemo/collections/asr/models/ctc_models.py b/nemo/collections/asr/models/ctc_models.py index f65a28e855604a1784c3c9fc3a5420498785d6f7..00477092dff3fcaea89d1e61e254115ffef76af2 100644 --- a/nemo/collections/asr/models/ctc_models.py +++ b/nemo/collections/asr/models/ctc_models.py @@ -35,7 +35,7 @@ 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.transcribe_utils import process_timestamp_outputs +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 @@ -171,7 +171,6 @@ class EncDecCTCModel(ASRModel, ExportableEncDecModel, ASRModuleMixin, InterCTCMi return_hypotheses = True with open_dict(self.cfg.decoding): self.cfg.decoding.compute_timestamps = True - self.cfg.decoding.preserve_alignments = 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): @@ -798,24 +797,6 @@ class EncDecCTCModel(ASRModel, ExportableEncDecModel, ASRModuleMixin, InterCTCMi """ results = [] - model = PretrainedModelInfo( - pretrained_model_name="QuartzNet15x5Base-En", - description="QuartzNet15x5 model trained on six datasets: LibriSpeech, Mozilla Common Voice \ - (validated clips from en_1488h_2019-12-10), WSJ, Fisher, Switchboard, and NSC Singapore English. \ - It was trained with Apex/Amp optimization level O1 for 600 epochs. The model achieves a WER of \ - 3.79% on LibriSpeech dev-clean, and a WER of 10.05% on dev-other. Please visit \ - https://ngc.nvidia.com/catalog/models/nvidia:nemospeechmodels for further details.", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemospeechmodels/versions/1.0.0a5/files/QuartzNet15x5Base-En.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_quartznet15x5", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_quartznet15x5", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_quartznet15x5/versions/1.0.0rc1/files/stt_en_quartznet15x5.nemo", - ) - results.append(model) - 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", @@ -823,77 +804,6 @@ class EncDecCTCModel(ASRModel, ExportableEncDecModel, ASRModuleMixin, InterCTCMi ) results.append(model) - model = PretrainedModelInfo( - pretrained_model_name="stt_ca_quartznet15x5", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_ca_quartznet15x5", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_ca_quartznet15x5/versions/1.0.0rc1/files/stt_ca_quartznet15x5.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_it_quartznet15x5", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_it_quartznet15x5", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_it_quartznet15x5/versions/1.0.0rc1/files/stt_it_quartznet15x5.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_fr_quartznet15x5", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_fr_quartznet15x5", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_fr_quartznet15x5/versions/1.0.0rc1/files/stt_fr_quartznet15x5.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_es_quartznet15x5", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_es_quartznet15x5", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_es_quartznet15x5/versions/1.0.0rc1/files/stt_es_quartznet15x5.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_de_quartznet15x5", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_de_quartznet15x5", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_de_quartznet15x5/versions/1.0.0rc1/files/stt_de_quartznet15x5.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_pl_quartznet15x5", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_pl_quartznet15x5", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_pl_quartznet15x5/versions/1.0.0rc1/files/stt_pl_quartznet15x5.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_ru_quartznet15x5", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_ru_quartznet15x5", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_ru_quartznet15x5/versions/1.0.0rc1/files/stt_ru_quartznet15x5.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_zh_citrinet_512", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_zh_citrinet_512", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_zh_citrinet_512/versions/1.0.0rc1/files/stt_zh_citrinet_512.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_zh_citrinet_1024_gamma_0_25", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_zh_citrinet_1024_gamma_0_25", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_zh_citrinet_1024_gamma_0_25/versions/1.0.0/files/stt_zh_citrinet_1024_gamma_0_25.nemo", - ) - - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_zh_citrinet_1024_gamma_0_25", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_zh_citrinet_1024_gamma_0_25", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_zh_citrinet_1024_gamma_0_25/versions/1.0.0/files/stt_zh_citrinet_1024_gamma_0_25.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", diff --git a/nemo/collections/asr/models/hybrid_asr_tts_models.py b/nemo/collections/asr/models/hybrid_asr_tts_models.py deleted file mode 100644 index 89a7e1289675804208a8462dfb0889185ca8da5f..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/hybrid_asr_tts_models.py +++ /dev/null @@ -1,604 +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. - -import copy -import itertools -from dataclasses import dataclass -from pathlib import Path -from typing import Any, Dict, List, Optional, Tuple, Union, cast - -import torch -from lightning.pytorch import Trainer -from omegaconf import MISSING, DictConfig, OmegaConf, open_dict -from torch.nn.utils.rnn import pad_sequence - -from nemo.collections.asr.data.audio_to_text_dali import DALIOutputs -from nemo.collections.asr.data.audio_to_text_dataset import get_audio_to_text_bpe_dataset_from_config -from nemo.collections.asr.data.text_to_text import ( - TextOrAudioToTextBatch, - TextToTextBatch, - TextToTextDataset, - TextToTextIterableDataset, -) -from nemo.collections.asr.models.asr_model import ASRModel -from nemo.collections.asr.models.ctc_bpe_models import EncDecCTCModelBPE -from nemo.collections.asr.models.hybrid_rnnt_ctc_bpe_models import EncDecHybridRNNTCTCBPEModel -from nemo.collections.asr.models.rnnt_bpe_models import EncDecRNNTBPEModel -from nemo.collections.asr.modules.conformer_encoder import ConformerEncoder -from nemo.collections.asr.parts.preprocessing.features import clean_spectrogram_batch, normalize_batch -from nemo.collections.asr.parts.submodules.batchnorm import replace_bn_with_fused_bn_all -from nemo.collections.common.data import ConcatDataset, ConcatMapDataset -from nemo.collections.tts.models import FastPitchModel, SpectrogramEnhancerModel -from nemo.core.classes import Dataset, typecheck -from nemo.core.classes.common import PretrainedModelInfo -from nemo.utils import logging -from nemo.utils.enum import PrettyStrEnum -from nemo.utils.exceptions import NeMoBaseException - - -def _fuse_bn_in_conformer(asr_model: ASRModel): - """ - Replace BatchNorm with Fused BatchNorm in Conformer and fixes model config inplace - Expected `encoder` model to exist and be of type ConformerEncoder - """ - logging.info("Replacing BatchNorm with Fused BatchNorm") - if not hasattr(asr_model, "encoder"): - raise NotImplementedError("No encoder found in ASR Model, replacement not supported") - if not isinstance(asr_model.encoder, ConformerEncoder): - raise NotImplementedError(f"Unsupported encoder type: {type(asr_model.encoder)}") - replace_bn_with_fused_bn_all(asr_model.encoder) - if "conv_norm_type" not in asr_model.cfg.encoder: - # old CTC models from NGC don't have such param - logging.warning("conv_norm_type not in encoder config, adding parameter") - with open_dict(asr_model.cfg): - asr_model.cfg.encoder.conv_norm_type = "fused_batch_norm" - else: - asr_model.cfg.encoder.conv_norm_type = "fused_batch_norm" - - -@dataclass -class TextDataConfig: - """ - Text dataset subconfig for text-only dataset - """ - - manifest_filepath: Any = MISSING # actual Union[str, List[str]], but this type is not supported by OmegaConf - speakers_filepath: Any = MISSING - min_words: int = 1 - max_words: int = 45 # 45 - recommended value, ~16.7 sec for LibriSpeech - tokenizer_workers: int = 1 - asr_tts_sampling_technique: Optional[str] = None - asr_tts_sampling_temperature: Optional[int] = None - asr_tts_sampling_probabilities: Optional[List[float]] = None - - -class ASRWithTTSModel(ASRModel): - """ - Hybrid ASR-TTS model: a transparent wrapper for ASR model - with frozen text-to-spectrogram pretrained model, which allows to use text-only data for training/finetuning - Text-only data can be mixed with audio-text pairs - """ - - asr_model: Union[EncDecRNNTBPEModel, EncDecCTCModelBPE, EncDecHybridRNNTCTCBPEModel] - tts_model: FastPitchModel - enhancer_model: Optional[SpectrogramEnhancerModel] - - class ASRModelTypes(PrettyStrEnum): - """ - Supported ASR types, needed for training from scratch - """ - - RNNT_BPE = "rnnt_bpe" - CTC_BPE = "ctc_bpe" - HYBRID_RNNT_CTC_BPE = "hybrid_rnnt_ctc_bpe" - - @classmethod - def from_asr_model(cls, model: Any): - if isinstance(model, EncDecRNNTBPEModel): - return cls.RNNT_BPE - if isinstance(model, EncDecCTCModelBPE): - return cls.CTC_BPE - if isinstance(model, EncDecHybridRNNTCTCBPEModel): - return cls.HYBRID_RNNT_CTC_BPE - raise ValueError(f"Unsupported model type: {type(model)}") - - def get_asr_cls(self): - if self == self.RNNT_BPE: - return EncDecRNNTBPEModel - if self == self.CTC_BPE: - return EncDecCTCModelBPE - if self == self.HYBRID_RNNT_CTC_BPE: - return EncDecHybridRNNTCTCBPEModel - raise NotImplementedError(f"Not implemented for value {self.value}") - - @classmethod - def list_available_models(cls) -> List[PretrainedModelInfo]: - return [] - - @classmethod - def _check_config(cls, cfg: DictConfig): - """ - Check that all required fields are present in config - Structured configs are not compatible with model serialization, so we check fields manually - """ - expected_fields = [ - # asr - "asr_model", - "asr_model_path", - "asr_model_fuse_bn", - "asr_model_type", - # tts - "tts_model", - "tts_model_path", - # enhancer - "enhancer_model_path", - "enhancer_model", - ] - for field in expected_fields: - if field not in cfg: - raise NeMoBaseException(f"Field {field} is required in config (possibly should be None/null)") - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - self._full_init_guard = False - - self._check_config(cfg) # check all required keys are in config - - # setup datasets and optimizer after model is fully initialized - # since it's done automatically, remove options from config - cfg = copy.deepcopy(cfg) # copy to avoid modifying original config - with open_dict(cfg): - train_ds_cfg = cfg.pop("train_ds", None) - validation_ds_cfg = cfg.pop("validation_ds", None) - test_ds_cfg = cfg.pop("test_ds", None) - optim_cfg = cfg.pop("optim", None) - - super().__init__(cfg, trainer=trainer) - - # tts model - if cfg.tts_model is not None: - self.register_nemo_submodule("tts_model", config_field="tts_model", model=FastPitchModel(cfg.tts_model)) - else: - if cfg.tts_model_path is None: - raise NeMoBaseException("Either tts_model or tts_model_path should be provided") - self.register_nemo_submodule( - "tts_model", - config_field="tts_model", - model=FastPitchModel.restore_from(f"{cfg.tts_model_path}", map_location=torch.device("cpu")), - ) - self.tts_model.freeze() # tts model should be always frozen - - if cfg.asr_model is not None: - self.asr_model_type = self.ASRModelTypes(cfg.asr_model_type) # convert to enum - self.register_nemo_submodule( - "asr_model", config_field="asr_model", model=self.asr_model_type.get_asr_cls()(cfg.asr_model) - ) - else: - if cfg.asr_model_path is None: - raise NeMoBaseException("Either asr_model or asr_model_path should be provided") - self.register_nemo_submodule( - "asr_model", - config_field="asr_model", - model=ASRModel.restore_from(f"{cfg.asr_model_path}", map_location=torch.device("cpu")), - ) - self.asr_model_type = self.ASRModelTypes.from_asr_model(self.asr_model) - self.cfg.asr_model_type = f"{self.asr_model_type}" # save to config - - # replace BatchNorm with FusedBatchNorm - if cfg.asr_model_fuse_bn: - _fuse_bn_in_conformer(self.asr_model) - self.cfg.asr_model_fuse_bn = False # no need to fuse anymore - - if cfg.enhancer_model is not None: - self.register_nemo_submodule( - "enhancer_model", config_field="enhancer_model", model=SpectrogramEnhancerModel(cfg.enhancer_model) - ) - elif cfg.enhancer_model_path is not None: - self.register_nemo_submodule( - "enhancer_model", - config_field="enhancer_model", - model=SpectrogramEnhancerModel.restore_from(cfg.enhancer_model_path, map_location=torch.device("cpu")), - ) - else: - self.enhancer_model = None - - self._full_init_guard = True - - # initialize optimizer and datasets, asr/tts models are initialized here - if optim_cfg: - with open_dict(self.cfg): - self.cfg.optim = optim_cfg - self.setup_optimization(optim_config=optim_cfg) - if train_ds_cfg: - with open_dict(self.cfg): - self.cfg.train_ds = train_ds_cfg - self.setup_training_data(train_data_config=train_ds_cfg) - if validation_ds_cfg: - with open_dict(self.cfg): - self.cfg.validation_ds = validation_ds_cfg - self.setup_multiple_validation_data(val_data_config=validation_ds_cfg) - if test_ds_cfg: - with open_dict(self.cfg): - self.cfg.test_ds = test_ds_cfg - self.setup_test_data(test_data_config=test_ds_cfg) - - @classmethod - def from_asr_config( - cls, - asr_cfg: DictConfig, - asr_model_type: Union[str, ASRModelTypes], - tts_model_path: Union[str, Path], - enhancer_model_path: Optional[Union[str, Path]] = None, - trainer: Trainer = None, - ): - """ - Method to construct model from ASR config for training from scratch - """ - model_type = cls.ASRModelTypes(asr_model_type) - cfg = DictConfig( - dict( - asr_model_path=None, - asr_model=None, - asr_model_type=f"{model_type}", - asr_model_fuse_bn=False, # for training from scratch always should be False - tts_model_path=f"{tts_model_path}", - tts_model=None, - enhancer_model_path=f"{enhancer_model_path}" if enhancer_model_path is not None else None, - enhancer_model=None, - train_ds=None, - validation_ds=None, - test_ds=None, - optim=None, - ) - ) - - asr_cfg = copy.deepcopy(asr_cfg) # copy not to affect original config - with open_dict(asr_cfg): - for subconfig_path in ["train_ds", "validation_ds", "test_ds", "optim"]: - if subconfig_path in asr_cfg: - cfg[subconfig_path] = asr_cfg.pop(subconfig_path) - cfg.asr_model = asr_cfg - return cls(cfg=cfg, trainer=trainer) - - @classmethod - def from_pretrained_models( - cls, - asr_model_path: Union[str, Path], - tts_model_path: Union[str, Path], - enhancer_model_path: Optional[Union[str, Path]] = None, - asr_model_fuse_bn: bool = False, - cfg: Optional[DictConfig] = None, - trainer: Optional[Trainer] = None, - ): - """ - Load model from pretrained ASR and TTS models - Args: - asr_model_path: path to .nemo ASR model checkpoint - tts_model_path: path to .nemo TTS model checkpoint - enhancer_model_path: path to .nemo enhancer model checkpoint - asr_model_fuse_bn: automatically fuse batchnorm layers in ASR model - cfg: optional config for hybrid model - trainer: Pytorch-Lightning trainer - - Returns: - ASRWithTTSModel instance - """ - if cfg is None: - cfg = DictConfig( - dict( - asr_model_path=f"{asr_model_path}", - asr_model=None, - tts_model_path=f"{tts_model_path}", - tts_model=None, - enhancer_model_path=f"{enhancer_model_path}" if enhancer_model_path is not None else None, - enhancer_model=None, - asr_model_type=None, - asr_model_fuse_bn=asr_model_fuse_bn, - train_ds=None, - validation_ds=None, - test_ds=None, - optim=None, - ) - ) - else: - cfg = copy.deepcopy(cfg) # copy to avoid modifying original config - cfg.tts_model_path = f"{tts_model_path}" - cfg.asr_model_path = f"{asr_model_path}" - cfg.enhancer_model_path = f"{enhancer_model_path}" if enhancer_model_path is not None else None - return ASRWithTTSModel(cfg, trainer=trainer) - - def __setattr__(self, name, value): - # pytorch-lightning magic, allows to call *_step on asr_model - if name == "_current_fx_name" and self._full_init_guard: - self.asr_model._current_fx_name = value # need to make logging inside asr_model work - return super().__setattr__(name, value) - - def setup_optimization( - self, - optim_config: Optional[Union[DictConfig, Dict]] = None, - optim_kwargs: Optional[Dict[str, Any]] = None, - ): - """ - Setup optimizer and scheduler. Ensure tts model is frozen. - Add optimizer and scheduler to asr model, to allow `train_step` on ASR model - """ - self.tts_model.freeze() - optimizer, scheduler = super().setup_optimization(optim_config=optim_config, optim_kwargs=optim_kwargs) - # set ASR model optimizer/scheduler to allow training_step on asr_model - self.asr_model._optimizer = optimizer - self.asr_model._scheduler = scheduler - return optimizer, scheduler - - def setup_validation_data(self, val_data_config: Union[DictConfig, Dict]): - """Setup validation data for ASR model""" - return self.asr_model.setup_validation_data(val_data_config) - - def multi_validation_epoch_end(self, outputs, dataloader_idx: int = 0): - """Validation epoch end hook for ASR model""" - return self.asr_model.multi_validation_epoch_end(outputs=outputs, dataloader_idx=dataloader_idx) - - def multi_test_epoch_end(self, outputs, dataloader_idx: int = 0): - """Test epoch end hook for ASR model""" - return self.asr_model.multi_test_epoch_end(outputs=outputs, dataloader_idx=dataloader_idx) - - def transcribe(self, audio: List[str], batch_size: int = 4, verbose: bool = True) -> List[str]: - """Transcribe audio data using ASR model""" - return self.asr_model.transcribe(audio=audio, batch_size=batch_size, verbose=verbose) - - def setup_multiple_validation_data(self, val_data_config: Union[DictConfig, Dict]): - """Setup multiple validation data for ASR model""" - self.asr_model.setup_multiple_validation_data(val_data_config) - - def setup_test_data(self, test_data_config: Union[DictConfig, Dict]): - """Setup test data for ASR model""" - self.asr_model.setup_test_data(test_data_config) - - def setup_multiple_test_data(self, test_data_config: Union[DictConfig, Dict]): - """Setup multiple test data for ASR Model""" - return self.asr_model.setup_multiple_test_data(test_data_config) - - def save_asr_model_to(self, save_path: str): - """Save ASR model separately""" - return self.asr_model.save_to(save_path=save_path) - - def validation_step(self, batch, batch_idx, dataloader_idx=0): - """Validation step, forward to ASR model""" - loss = self.asr_model.validation_step(batch=batch, batch_idx=batch_idx, dataloader_idx=dataloader_idx) - if type(self.trainer.val_dataloaders) == list and len(self.trainer.val_dataloaders) > 1: - self.validation_step_outputs[dataloader_idx].append(loss) - else: - self.validation_step_outputs.append(loss) - return loss - - def on_validation_epoch_end(self) -> Optional[Dict[str, Dict[str, torch.Tensor]]]: - """Validation epoch end hook, forward to ASR model""" - return self.asr_model.on_validation_epoch_end() - - def on_test_epoch_end(self) -> Optional[Dict[str, Dict[str, torch.Tensor]]]: - """Test epoch end hook, forward to ASR model""" - return self.asr_model.on_test_epoch_end() - - def val_dataloader(self): - """Get valudation dataloader from ASR model""" - return self.asr_model.val_dataloader() - - def unfreeze(self) -> None: - """Unfreeze the ASR model, keep TTS model frozen.""" - super().unfreeze() - self.tts_model.freeze() # tts model should be always frozen - - def on_fit_start(self): - """Call asr_model on_fit_start hook, ensure TTS model is frozen""" - self.asr_model.on_fit_start() - self.tts_model.freeze() - - def train(self, mode: bool = True): - """Train mode, ensure TTS model is frozen""" - super().train(mode) - self.tts_model.eval() - return self - - def _get_tts_spectrogram( - self, tts_texts: torch.Tensor, speakers: torch.Tensor - ) -> Tuple[torch.Tensor, torch.Tensor]: - """Get TTS spectrogram from text and speaker ids""" - with torch.no_grad(): - spectrogram, spectrogram_len, *_ = self.tts_model(text=tts_texts, durs=None, pitch=None, speaker=speakers) - if self.enhancer_model is not None: - # apply enhancer - with typecheck.disable_checks(): - # spectrogram_len are of TokenDurationType, enhancer requires LengthsType - # TODO: fix FastPitch model to return LengthsType - spectrogram = self.enhancer_model.forward(input_spectrograms=spectrogram, lengths=spectrogram_len) - spectrogram, *_ = normalize_batch(spectrogram, spectrogram_len, self.asr_model.cfg.preprocessor.normalize) - return spectrogram, spectrogram_len - - def _get_batch_spect(self, batch: Union[TextToTextBatch, TextOrAudioToTextBatch, tuple]): - """Get batch with spectrograms from text-only, audio-text or mixed batch data""" - if isinstance(batch, TextToTextBatch): - spectrogram, spectrogram_len = self._get_tts_spectrogram(batch.tts_texts, batch.speakers) - transcript = batch.transcripts - transcript_len = batch.transcript_lengths - elif isinstance(batch, TextOrAudioToTextBatch): - tts_spectrogram, tts_spectrogram_len = self._get_tts_spectrogram(batch.tts_texts, batch.speakers) - asr_spectrogram, asr_spectrogram_len = self.asr_model.preprocessor( - input_signal=batch.audio_signals, - length=batch.audio_signal_lengths, - ) - - spectrogram = pad_sequence( - [ - x.squeeze(0) - for x in itertools.chain( - torch.tensor_split(tts_spectrogram.transpose(1, 2), tts_spectrogram.size(0)), - torch.tensor_split(asr_spectrogram.transpose(1, 2), asr_spectrogram.size(0)), - ) - ], - batch_first=True, - padding_value=0.0, - ).transpose(1, 2) - spectrogram_len = torch.cat([tts_spectrogram_len, asr_spectrogram_len], dim=0) - - transcript = batch.transcripts - transcript_len = batch.transcript_lengths - else: - audio_signal, audio_signal_len, transcript, transcript_len, *_ = batch # audio batch: 4 or 5 elements - spectrogram, spectrogram_len = self.asr_model.preprocessor( - input_signal=audio_signal, length=audio_signal_len - ) - spectrogram = clean_spectrogram_batch(spectrogram, spectrogram_len) - return spectrogram.detach(), spectrogram_len.detach(), transcript, transcript_len - - def setup_training_data(self, train_data_config: Optional[Union[DictConfig, Dict]]): - """ - Setup training data from config: text-only, audio-text or mixed data. - """ - if train_data_config is None: - logging.warning("No training data") - return - - self._update_dataset_config(dataset_name='train', config=train_data_config) - asr_dataset = get_audio_to_text_bpe_dataset_from_config( - train_data_config, - local_rank=self.local_rank, - global_rank=self.global_rank, - world_size=self.world_size, - tokenizer=self.asr_model.tokenizer, - preprocessor_cfg=self.asr_model.cfg.get("preprocessor", None), - ) - - dataset_iterable = True - if asr_dataset is not None and isinstance(asr_dataset, Dataset): - # asr_dataset is map-style, for mixing datasets use map-style text-to-text dataset - dataset_iterable = False - if train_data_config.get("text_data") is not None: - tts_dataset = self._setup_text_dataset_from_config(train_data_config, iterable=dataset_iterable) - else: - tts_dataset = None - - if tts_dataset and asr_dataset: - text_data_config: TextDataConfig = cast( - TextDataConfig, OmegaConf.merge(OmegaConf.structured(TextDataConfig), train_data_config.text_data) - ) - concat_kwargs = dict() - if text_data_config.asr_tts_sampling_technique is not None: - concat_kwargs["sampling_technique"] = text_data_config.asr_tts_sampling_technique - if text_data_config.asr_tts_sampling_temperature is not None: - concat_kwargs["sampling_temperature"] = text_data_config.asr_tts_sampling_temperature - if text_data_config.asr_tts_sampling_probabilities: - concat_kwargs["sampling_probabilities"] = text_data_config.asr_tts_sampling_probabilities - - if dataset_iterable: - dataset = ConcatDataset(datasets=[asr_dataset, tts_dataset], **concat_kwargs) - else: - dataset = ConcatMapDataset(datasets=[asr_dataset, tts_dataset], **concat_kwargs) - else: - dataset = tts_dataset or asr_dataset - - if dataset is None: - return - - if tts_dataset: - collate_fn = tts_dataset.collate_fn - else: - if hasattr(asr_dataset, 'collate_fn'): - collate_fn = asr_dataset.collate_fn - elif hasattr(asr_dataset.datasets[0], 'collate_fn'): - # support datasets that are lists of entries - collate_fn = asr_dataset.datasets[0].collate_fn - else: - # support datasets that are lists of lists - collate_fn = asr_dataset.datasets[0].datasets[0].collate_fn - - shuffle = train_data_config.get("shuffle", True) and not dataset_iterable - self._train_dl = torch.utils.data.DataLoader( - dataset=dataset, - batch_size=train_data_config['batch_size'], - collate_fn=collate_fn, - drop_last=train_data_config.get('drop_last', False), - shuffle=shuffle, - num_workers=train_data_config.get('num_workers', 0), - pin_memory=train_data_config.get('pin_memory', False), - ) - - def _setup_text_dataset_from_config( - self, train_data_config: DictConfig, iterable=True - ) -> Union[TextToTextDataset, TextToTextIterableDataset]: - """ - Construct text-to-text (text-only) dataset from config. - - Args: - train_data_config: config - iterable: construct iterable-style datasset if True, otherwise map-style - - Returns: - text-to-text dataset of TextToTextDataset or TextToTextIterableDataset type - """ - text_data_config: TextDataConfig = cast( - TextDataConfig, OmegaConf.merge(OmegaConf.structured(TextDataConfig), train_data_config.text_data) - ) - if iterable: - textonly_ds = TextToTextIterableDataset( - manifest_filepath=text_data_config.manifest_filepath, - speakers_filepath=text_data_config.speakers_filepath, - asr_tokenizer=self.asr_model.tokenizer, - asr_use_start_end_token=train_data_config.get("use_start_end_token", False), - tts_parser=self.tts_model.parser, - tts_text_pad_id=self.tts_model.vocab.pad, - tts_text_normalizer=self.tts_model.normalizer, - tts_text_normalizer_call_kwargs=self.tts_model.text_normalizer_call_kwargs, - min_words=text_data_config.min_words, - max_words=text_data_config.max_words, - tokenizer_workers=text_data_config.tokenizer_workers, - num_parts=self.world_size, - current_part_index=self.global_rank, - ) - else: - textonly_ds = TextToTextDataset( - manifest_filepath=text_data_config.manifest_filepath, - speakers_filepath=text_data_config.speakers_filepath, - asr_tokenizer=self.asr_model.tokenizer, - asr_use_start_end_token=train_data_config.get("use_start_end_token", False), - tts_parser=self.tts_model.parser, - tts_text_pad_id=self.tts_model.vocab.pad, - tts_text_normalizer=self.tts_model.normalizer, - tts_text_normalizer_call_kwargs=self.tts_model.text_normalizer_call_kwargs, - min_words=text_data_config.min_words, - max_words=text_data_config.max_words, - tokenizer_workers=text_data_config.tokenizer_workers, - ) - return textonly_ds - - def training_step(self, batch: Union[TextOrAudioToTextBatch, TextToTextBatch, DALIOutputs, tuple], batch_nb: int): - """ - Training step for ASR-TTS model. - - construct spectrogram for the batch (from text - using TTS model, from audio - using ASR preprocessor) - - call training_step on ASR model - """ - assert not self.tts_model.training - if isinstance(batch, DALIOutputs): - return self.asr_model.training_step(batch=batch, batch_nb=batch_nb) - with torch.no_grad(): - spectrogram, spectrogram_len, transcript, transcript_len = self._get_batch_spect(batch) - # TODO: maybe support precomputed without DALIOutputs - return self.asr_model.training_step( - batch=DALIOutputs( - dict( - processed_signal=spectrogram, - processed_signal_len=spectrogram_len, - transcript=transcript, - transcript_len=transcript_len, - ) - ), - batch_nb=batch_nb, - ) diff --git a/nemo/collections/asr/models/hybrid_rnnt_ctc_bpe_models.py b/nemo/collections/asr/models/hybrid_rnnt_ctc_bpe_models.py index cd04a5ad2462caae901919739ca1c0124e9134d2..0b41587971019c8b161598b6cea61c99fd0a6294 100644 --- a/nemo/collections/asr/models/hybrid_rnnt_ctc_bpe_models.py +++ b/nemo/collections/asr/models/hybrid_rnnt_ctc_bpe_models.py @@ -43,7 +43,7 @@ class EncDecHybridRNNTCTCBPEModel(EncDecHybridRNNTCTCModel, ASRBPEMixin): 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) + cfg = model_utils.maybe_update_config_version(cfg, make_copy=False) # Tokenizer is necessary for this model if 'tokenizer' not in cfg: @@ -233,6 +233,7 @@ class EncDecHybridRNNTCTCBPEModel(EncDecHybridRNNTCTCModel, ASRBPEMixin): 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, @@ -292,7 +293,7 @@ class EncDecHybridRNNTCTCBPEModel(EncDecHybridRNNTCTCModel, ASRBPEMixin): ) if new_tokenizer_type.lower() not in ('bpe', 'wpe'): - raise ValueError(f'New tokenizer type must be either `bpe` or `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}) 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 new file mode 100644 index 0000000000000000000000000000000000000000..992de84fc7a8e75f9c4076c4b1b5a3e8a85aee6b --- /dev/null +++ b/nemo/collections/asr/models/hybrid_rnnt_ctc_bpe_models_prompt.py @@ -0,0 +1,1012 @@ +# 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 index 9b6ef43565598910c0a9aef3f8fcaf29ebf53f56..5b0d1a98743a81d9d1e5c2e4f23f27810dc834e7 100644 --- a/nemo/collections/asr/models/hybrid_rnnt_ctc_models.py +++ b/nemo/collections/asr/models/hybrid_rnnt_ctc_models.py @@ -23,18 +23,18 @@ 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, InterCTCMixin, TranscribeConfig +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.transcribe_utils import process_timestamp_outputs +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): +class EncDecHybridRNNTCTCModel(EncDecRNNTModel, ASRBPEMixin, InterCTCMixin, ASRTranscriptionMixin): """Base class for hybrid RNNT/CTC models.""" def __init__(self, cfg: DictConfig, trainer: Trainer = None): @@ -102,7 +102,7 @@ class EncDecHybridRNNTCTCModel(EncDecRNNTModel, ASRBPEMixin, InterCTCMixin): channel_selector: Optional[ChannelSelectorType] = None, augmentor: DictConfig = None, verbose: bool = True, - timestamps: bool = False, + timestamps: bool = None, override_config: Optional[TranscribeConfig] = None, ) -> TranscriptionReturnType: """ @@ -141,23 +141,29 @@ class EncDecHybridRNNTCTCModel(EncDecRNNTModel, ASRBPEMixin, InterCTCMixin): 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 - with open_dict(decoding_cfg): - decoding_cfg.compute_timestamps = True - decoding_cfg.preserve_alignments = True - self.change_decoding_strategy(decoding_cfg, decoder_type=self.cur_decoder, verbose=False) + 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: - with open_dict(decoding_cfg): - decoding_cfg.compute_timestamps = False - decoding_cfg.preserve_alignments = False + 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 super().transcribe( + return ASRTranscriptionMixin.transcribe( + self, audio=audio, batch_size=batch_size, return_hypotheses=return_hypotheses, @@ -490,7 +496,6 @@ class EncDecHybridRNNTCTCModel(EncDecRNNTModel, ASRBPEMixin, InterCTCMixin): return {'loss': loss_value} def predict_step(self, batch, batch_idx, dataloader_idx=0): - # TODO: add support for CTC decoding signal, signal_len, transcript, transcript_len, sample_id = batch # forward() only performs encoder forward @@ -500,12 +505,21 @@ class EncDecHybridRNNTCTCModel(EncDecRNNTModel, ASRBPEMixin, InterCTCMixin): 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 - ) + 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_text)) + return list(zip(sample_id, best_hyp)) def validation_pass(self, batch, batch_idx, dataloader_idx): if self.is_interctc_enabled(): diff --git a/nemo/collections/asr/models/k2_aligner_model.py b/nemo/collections/asr/models/k2_aligner_model.py deleted file mode 100644 index 54d342df40e42146f1b4b05e494cc1681e9366eb..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/k2_aligner_model.py +++ /dev/null @@ -1,616 +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, Tuple, Union - -import numpy as np -import torch -from omegaconf import DictConfig, OmegaConf, open_dict -from tqdm.auto import tqdm - -from nemo.collections.asr.data.audio_to_ctm_dataset import FrameCtmUnit -from nemo.collections.asr.data.audio_to_text_dali import DALIOutputs -from nemo.collections.asr.models.asr_model import ASRModel -from nemo.utils import logging - - -class AlignerWrapperModel(ASRModel): - """ASR model wrapper to perform alignment building. - Functionality is limited to the components needed to build an alignment.""" - - def __init__(self, model: ASRModel, cfg: DictConfig): - model_cfg = model.cfg - for ds in ("train_ds", "validation_ds", "test_ds"): - if ds in model_cfg: - model_cfg[ds] = None - super().__init__(cfg=model_cfg, trainer=model.trainer) - self._model = model - self.alignment_type = cfg.get("alignment_type", "forced") - self.word_output = cfg.get("word_output", True) - self.cpu_decoding = cfg.get("cpu_decoding", False) - self.decode_batch_size = cfg.get("decode_batch_size", 0) - - # list possible alignment types here for future work - if self.alignment_type == "forced": - pass - elif self.alignment_type == "argmax": - pass - elif self.alignment_type == "loose": - raise NotImplementedError(f"alignment_type=`{self.alignment_type}` is not supported at the moment.") - elif self.alignment_type == "rnnt_decoding_aux": - raise NotImplementedError(f"alignment_type=`{self.alignment_type}` is not supported at the moment.") - else: - raise RuntimeError(f"Unsupported alignment type: {self.alignment_type}") - - self._init_model_specific(cfg) - - def _init_ctc_alignment_specific(self, cfg: DictConfig): - """Part of __init__ intended to initialize attributes specific to the alignment type for CTC models. - - This method is not supposed to be called outside of __init__. - """ - # do nothing for regular CTC with `argmax` alignment type - if self.alignment_type == "argmax" and not hasattr(self._model, "use_graph_lm"): - return - - from nemo.collections.asr.modules.graph_decoder import ViterbiDecoderWithGraph - - if self.alignment_type == "forced": - if hasattr(self._model, "use_graph_lm"): - if self._model.use_graph_lm: - self.graph_decoder = self._model.transcribe_decoder - self._model.use_graph_lm = False - else: - self.graph_decoder = ViterbiDecoderWithGraph( - num_classes=self.blank_id, backend="k2", dec_type="topo", return_type="1best" - ) - # override split_batch_size - self.graph_decoder.split_batch_size = self.decode_batch_size - else: - self.graph_decoder = ViterbiDecoderWithGraph( - num_classes=self.blank_id, split_batch_size=self.decode_batch_size, - ) - # override decoder args if a config is provided - decoder_module_cfg = cfg.get("decoder_module_cfg", None) - if decoder_module_cfg is not None: - self.graph_decoder._decoder.intersect_pruned = decoder_module_cfg.get("intersect_pruned") - self.graph_decoder._decoder.intersect_conf = decoder_module_cfg.get("intersect_conf") - return - - if self.alignment_type == "argmax": - # we use transcribe_decoder to get topology-independent output - if not self._model.use_graph_lm: - self._model.transcribe_decoder = ViterbiDecoderWithGraph( - num_classes=self.blank_id, backend="k2", dec_type="topo", return_type="1best" - ) - # override decoder args - self._model.transcribe_decoder.return_ilabels = False - self._model.transcribe_decoder.output_aligned = True - self._model.transcribe_decoder.split_batch_size = self.decode_batch_size - self._model.use_graph_lm = False - return - - def _init_rnnt_alignment_specific(self, cfg: DictConfig): - """Part of __init__ intended to initialize attributes specific to the alignment type for RNNT models. - - This method is not supposed to be called outside of __init__. - """ - if self.alignment_type == "argmax": - return - - from nemo.collections.asr.modules.graph_decoder import ViterbiDecoderWithGraph - - if self.alignment_type == "forced": - self.predictor_window_size = cfg.rnnt_cfg.get("predictor_window_size", 0) - self.predictor_step_size = cfg.rnnt_cfg.get("predictor_step_size", 0) - - from nemo.collections.asr.parts.k2.utils import apply_rnnt_prune_ranges, get_uniform_rnnt_prune_ranges - - self.prepare_pruned_outputs = lambda encoder_outputs, encoded_len, decoder_outputs, transcript_len: apply_rnnt_prune_ranges( - encoder_outputs, - decoder_outputs, - get_uniform_rnnt_prune_ranges( - encoded_len, - transcript_len, - self.predictor_window_size + 1, - self.predictor_step_size, - encoder_outputs.size(1), - ).to(device=encoder_outputs.device), - ) - - from nemo.collections.asr.parts.k2.classes import GraphModuleConfig - - self.graph_decoder = ViterbiDecoderWithGraph( - num_classes=self.blank_id, - backend="k2", - dec_type="topo_rnnt_ali", - split_batch_size=self.decode_batch_size, - graph_module_cfg=OmegaConf.structured( - GraphModuleConfig( - topo_type="minimal", - predictor_window_size=self.predictor_window_size, - predictor_step_size=self.predictor_step_size, - ) - ), - ) - # override decoder args if a config is provided - decoder_module_cfg = cfg.get("decoder_module_cfg", None) - if decoder_module_cfg is not None: - self.graph_decoder._decoder.intersect_pruned = decoder_module_cfg.get("intersect_pruned") - self.graph_decoder._decoder.intersect_conf = decoder_module_cfg.get("intersect_conf") - return - - def _init_model_specific(self, cfg: DictConfig): - """Part of __init__ intended to initialize attributes specific to the model type. - - This method is not supposed to be called outside of __init__. - """ - from nemo.collections.asr.models.ctc_models import EncDecCTCModel - - if isinstance(self._model, EncDecCTCModel): - self.model_type = "ctc" - self.blank_id = self._model.decoder.num_classes_with_blank - 1 - self._predict_impl = self._predict_impl_ctc - - prob_suppress_index = cfg.ctc_cfg.get("prob_suppress_index", -1) - prob_suppress_value = cfg.ctc_cfg.get("prob_suppress_value", 1.0) - if prob_suppress_value > 1 or prob_suppress_value <= 0: - raise ValueError(f"Suppression value has to be in (0,1]: {prob_suppress_value}") - if prob_suppress_index < -(self.blank_id + 1) or prob_suppress_index > self.blank_id: - raise ValueError( - f"Suppression index for the provided model has to be in [{-self.blank_id+1},{self.blank_id}]: {prob_suppress_index}" - ) - self.prob_suppress_index = ( - self._model.decoder.num_classes_with_blank + prob_suppress_index - if prob_suppress_index < 0 - else prob_suppress_index - ) - self.prob_suppress_value = prob_suppress_value - - self._init_ctc_alignment_specific(cfg) - return - - from nemo.collections.asr.models.rnnt_models import EncDecRNNTModel - - if isinstance(self._model, EncDecRNNTModel): - self.model_type = "rnnt" - self.blank_id = self._model.joint.num_classes_with_blank - 1 - self.log_softmax = None if self._model.joint.log_softmax is None else not self._model.joint.log_softmax - self._predict_impl = self._predict_impl_rnnt - - decoding_config = copy.deepcopy(self._model.cfg.decoding) - decoding_config.strategy = "greedy_batch" - with open_dict(decoding_config): - decoding_config.preserve_alignments = True - decoding_config.fused_batch_size = -1 - self._model.change_decoding_strategy(decoding_config) - self._init_rnnt_alignment_specific(cfg) - return - - raise RuntimeError(f"Unsupported model type: {type(self._model)}") - - def _rnnt_joint_pruned( - self, - encoder_outputs: torch.Tensor, - encoded_len: torch.Tensor, - decoder_outputs: torch.Tensor, - transcript_len: torch.Tensor, - ) -> torch.Tensor: - """A variant of the RNNT Joiner tensor calculation with pruned Encoder and Predictor sum. - Only the uniform pruning is supported at the moment. - """ - encoder_outputs = self._model.joint.enc(encoder_outputs.transpose(1, 2)) # (B, T, H) - decoder_outputs = self._model.joint.pred(decoder_outputs.transpose(1, 2)) # (B, U, H) - - encoder_outputs_pruned, decoder_outputs_pruned = self.prepare_pruned_outputs( - encoder_outputs, encoded_len, decoder_outputs, transcript_len - ) - res = self._model.joint.joint_net(encoder_outputs_pruned + decoder_outputs_pruned) - # copied from model.joint.joint(...) - if self._model.joint.log_softmax is None: - if not res.is_cuda: - res = res.log_softmax(dim=-1) - else: - if self._model.joint.log_softmax: - res = res.log_softmax(dim=-1) - return res - - def _apply_prob_suppress(self, log_probs: torch.Tensor) -> torch.Tensor: - """Multiplies probability of an element with index self.prob_suppress_index by self.prob_suppress_value times - with stochasticity preservation of the log_probs tensor. - - Often used to suppress probability of the output of a CTC model. - - Example: - For - - log_probs = torch.log(torch.tensor([0.015, 0.085, 0.9])) - - self.prob_suppress_index = -1 - - self.prob_suppress_value = 0.5 - the result of _apply_prob_suppress(log_probs) is - - torch.log(torch.tensor([0.0825, 0.4675, 0.45])) - """ - exp_probs = (log_probs).exp() - x = exp_probs[:, :, self.prob_suppress_index] - # we cannot do y=1-x because exp_probs can be not stochastic due to numerical limitations - y = torch.cat( - [exp_probs[:, :, : self.prob_suppress_index], exp_probs[:, :, self.prob_suppress_index + 1 :]], 2 - ).sum(-1) - b1 = torch.full((exp_probs.shape[0], exp_probs.shape[1], 1), self.prob_suppress_value, device=log_probs.device) - b2 = ((1 - self.prob_suppress_value * x) / y).unsqueeze(2).repeat(1, 1, exp_probs.shape[-1] - 1) - return ( - exp_probs * torch.cat([b2[:, :, : self.prob_suppress_index], b1, b2[:, :, self.prob_suppress_index :]], 2) - ).log() - - def _prepare_ctc_argmax_predictions( - self, log_probs: torch.Tensor, encoded_len: torch.Tensor - ) -> Tuple[List[torch.Tensor], List[torch.Tensor]]: - """Obtains argmax predictions with corresponding probabilities. - Replaces consecutive repeated indices in the argmax predictions with the index. - """ - if hasattr(self._model, "transcribe_decoder"): - predictions, _, probs = self.transcribe_decoder.forward(log_probs=log_probs, log_probs_length=encoded_len) - else: - greedy_predictions = log_probs.argmax(dim=-1, keepdim=False) - probs_tensor, _ = log_probs.exp().max(dim=-1, keepdim=False) - predictions, probs = [], [] - for i in range(log_probs.shape[0]): - utt_len = encoded_len[i] - probs.append(probs_tensor[i, :utt_len]) - pred_candidate = greedy_predictions[i, :utt_len].cpu() - # replace consecutive tokens with - previous = self.blank_id - for j in range(utt_len): - p = pred_candidate[j] - if p == previous and previous != self.blank_id: - pred_candidate[j] = self.blank_id - previous = p - predictions.append(pred_candidate.to(device=greedy_predictions.device)) - return predictions, probs - - def _predict_impl_rnnt_argmax( - self, - encoded: torch.Tensor, - encoded_len: torch.Tensor, - transcript: torch.Tensor, - transcript_len: torch.Tensor, - sample_id: torch.Tensor, - ) -> List[Tuple[int, 'FrameCtmUnit']]: - """Builds time alignment of an encoded sequence. - This method assumes that the RNNT model is used and the alignment type is `argmax`. - - It produces a list of sample ids and fours: (label, start_frame, length, probability), called FrameCtmUnit. - """ - hypotheses = self._model.decoding.rnnt_decoder_predictions_tensor( - encoded, encoded_len, return_hypotheses=True - )[0] - results = [] - for s_id, hypothesis in zip(sample_id, hypotheses): - pred_ids = hypothesis.y_sequence.tolist() - tokens = self._model.decoding.decode_ids_to_tokens(pred_ids) - token_begin = hypothesis.timestep - token_len = [j - i for i, j in zip(token_begin, token_begin[1:] + [len(hypothesis.alignments)])] - # we have no token probabilities for the argmax rnnt setup - token_prob = [1.0] * len(tokens) - if self.word_output: - words = [w for w in self._model.decoding.decode_tokens_to_str(pred_ids).split(" ") if w != ""] - words, word_begin, word_len, word_prob = ( - self._process_tokens_to_words(tokens, token_begin, token_len, token_prob, words) - if hasattr(self._model, "tokenizer") - else self._process_char_with_space_to_words(tokens, token_begin, token_len, token_prob, words) - ) - results.append( - (s_id, [FrameCtmUnit(t, b, l, p) for t, b, l, p in zip(words, word_begin, word_len, word_prob)]) - ) - else: - results.append( - ( - s_id, - [FrameCtmUnit(t, b, l, p) for t, b, l, p in zip(tokens, token_begin, token_len, token_prob)], - ) - ) - return results - - def _process_tokens_to_words( - self, - tokens: List[str], - token_begin: List[int], - token_len: List[int], - token_prob: List[float], - words: List[str], - ) -> Tuple[List[str], List[int], List[int], List[float]]: - """Transforms alignment information from token level to word level. - - Used when self._model.tokenizer is present. - """ - # suppose that there are no whitespaces - assert len(self._model.tokenizer.text_to_tokens(words[0])) == len( - self._model.tokenizer.text_to_tokens(words[0] + " ") - ) - word_begin, word_len, word_prob = [], [], [] - token_len_nonzero = [(t_l if t_l > 0 else 1) for t_l in token_len] - i = 0 - for word in words: - loc_tokens = self._model.tokenizer.text_to_tokens(word) - step = len(loc_tokens) - # we assume that an empty word consists of only one token - # drop current token - if step == 0: - token_begin[i + 1] = token_begin[i] - token_len[i + 1] += token_len[i] - token_len_nonzero[i + 1] += token_len_nonzero[i] - del tokens[i], token_begin[i], token_len[i], token_len_nonzero[i], token_prob[i] - continue - # fix tokenization - if step == 2 and loc_tokens[-1] == "??": - step -= 1 - j = i + step - word_begin.append(token_begin[i]) - word_len.append(sum(token_len[i:j])) - denominator = sum(token_len_nonzero[i:j]) - word_prob.append(sum(token_prob[k] * token_len_nonzero[k] for k in range(i, j)) / denominator) - i = j - return words, word_begin, word_len, word_prob - - def _process_char_with_space_to_words( - self, - tokens: List[str], - token_begin: List[int], - token_len: List[int], - token_prob: List[float], - words: List[str], - ) -> Tuple[List[str], List[int], List[int], List[float]]: - """Transforms alignment information from character level to word level. - This method includes separator (typically the space) information in the results. - - Used with character-based models (no self._model.tokenizer). - """ - # suppose that there are no whitespaces anywhere except between words - space_idx = (np.array(tokens) == " ").nonzero()[0].tolist() - assert len(words) == len(space_idx) + 1 - token_len_nonzero = [(t_l if t_l > 0 else 1) for t_l in token_len] - if len(space_idx) == 0: - word_begin = [token_begin[0]] - word_len = [sum(token_len)] - denominator = sum(token_len_nonzero) - word_prob = [sum(t_p * t_l for t_p, t_l in zip(token_prob, token_len_nonzero)) / denominator] - else: - space_word = "[SEP]" - word_begin = [token_begin[0]] - word_len = [sum(token_len[: space_idx[0]])] - denominator = sum(token_len_nonzero[: space_idx[0]]) - word_prob = [sum(token_prob[k] * token_len_nonzero[k] for k in range(space_idx[0])) / denominator] - words_with_space = [words[0]] - for word, i, j in zip(words[1:], space_idx, space_idx[1:] + [len(tokens)]): - # append space - word_begin.append(token_begin[i]) - word_len.append(token_len[i]) - word_prob.append(token_prob[i]) - words_with_space.append(space_word) - # append next word - word_begin.append(token_begin[i + 1]) - word_len.append(sum(token_len[i + 1 : j])) - denominator = sum(token_len_nonzero[i + 1 : j]) - word_prob.append(sum(token_prob[k] * token_len_nonzero[k] for k in range(i + 1, j)) / denominator) - words_with_space.append(word) - words = words_with_space - return words, word_begin, word_len, word_prob - - def _results_to_ctmUnits( - self, s_id: int, pred: torch.Tensor, prob: torch.Tensor - ) -> Tuple[int, List['FrameCtmUnit']]: - """Transforms predictions with probabilities to a list of FrameCtmUnit objects, - containing frame-level alignment information (label, start, duration, probability), for a given sample id. - - Alignment information can be either token-based (char, wordpiece, ...) or word-based. - """ - if len(pred) == 0: - return (s_id, []) - - non_blank_idx = (pred != self.blank_id).nonzero(as_tuple=True)[0].cpu() - pred_ids = pred[non_blank_idx].tolist() - prob_list = prob.tolist() - if self.model_type == "rnnt": - wer_module = self._model.decoding - # for rnnt forced alignment we always have num_blanks == num_frames, - # thus len(pred) == num_frames + num_non_blanks - token_begin = non_blank_idx - torch.arange(len(non_blank_idx)) - token_end = torch.cat((token_begin[1:], torch.tensor([len(pred) - len(non_blank_idx)]))) - else: - wer_module = self._model._wer - token_begin = non_blank_idx - token_end = torch.cat((token_begin[1:], torch.tensor([len(pred)]))) - tokens = wer_module.decode_ids_to_tokens(pred_ids) - token_len = (token_end - token_begin).tolist() - token_begin = token_begin.tolist() - token_prob = [ - sum(prob_list[i:j]) / (j - i) - for i, j in zip(non_blank_idx.tolist(), non_blank_idx[1:].tolist() + [len(pred)]) - ] - if self.word_output: - words = wer_module.decode_tokens_to_str(pred_ids).split(" ") - words, word_begin, word_len, word_prob = ( - self._process_tokens_to_words(tokens, token_begin, token_len, token_prob, words) - if hasattr(self._model, "tokenizer") - else self._process_char_with_space_to_words(tokens, token_begin, token_len, token_prob, words) - ) - return s_id, [FrameCtmUnit(t, b, l, p) for t, b, l, p in zip(words, word_begin, word_len, word_prob)] - return s_id, [FrameCtmUnit(t, b, l, p) for t, b, l, p in zip(tokens, token_begin, token_len, token_prob)] - - def _predict_impl_ctc( - self, - encoded: torch.Tensor, - encoded_len: torch.Tensor, - transcript: torch.Tensor, - transcript_len: torch.Tensor, - sample_id: torch.Tensor, - ) -> List[Tuple[int, 'FrameCtmUnit']]: - """Builds time alignment of an encoded sequence. - This method assumes that the CTC model is used. - - It produces a list of sample ids and fours: (label, start_frame, length, probability), called FrameCtmUnit. - """ - log_probs = encoded - - if self.prob_suppress_value != 1.0: - log_probs = self._apply_prob_suppress(log_probs) - - if self.alignment_type == "argmax": - predictions, probs = self._prepare_ctc_argmax_predictions(log_probs, encoded_len) - elif self.alignment_type == "forced": - if self.cpu_decoding: - log_probs, encoded_len, transcript, transcript_len = ( - log_probs.cpu(), - encoded_len.cpu(), - transcript.cpu(), - transcript_len.cpu(), - ) - predictions, probs = self.graph_decoder.align(log_probs, encoded_len, transcript, transcript_len) - else: - raise NotImplementedError() - - return [ - self._results_to_ctmUnits(s_id, pred, prob) - for s_id, pred, prob in zip(sample_id.tolist(), predictions, probs) - ] - - def _predict_impl_rnnt( - self, - encoded: torch.Tensor, - encoded_len: torch.Tensor, - transcript: torch.Tensor, - transcript_len: torch.Tensor, - sample_id: torch.Tensor, - ) -> List[Tuple[int, 'FrameCtmUnit']]: - """Builds time alignment of an encoded sequence. - This method assumes that the RNNT model is used. - - It produces a list of sample ids and fours: (label, start_frame, length, probability), called FrameCtmUnit. - """ - if self.alignment_type == "argmax": - return self._predict_impl_rnnt_argmax(encoded, encoded_len, transcript, transcript_len, sample_id) - elif self.alignment_type == "forced": - decoded = self._model.decoder(targets=transcript, target_length=transcript_len)[0] - log_probs = ( - self._rnnt_joint_pruned(encoded, encoded_len, decoded, transcript_len) - if self.predictor_window_size > 0 and self.predictor_window_size < transcript_len.max() - else self._model.joint(encoder_outputs=encoded, decoder_outputs=decoded) - ) - apply_log_softmax = True if self.log_softmax is None and encoded.is_cuda else self.log_softmax - if apply_log_softmax: - log_probs = log_probs.log_softmax(dim=-1) - if self.cpu_decoding: - log_probs, encoded_len, transcript, transcript_len = ( - log_probs.cpu(), - encoded_len.cpu(), - transcript.cpu(), - transcript_len.cpu(), - ) - predictions, probs = self.graph_decoder.align(log_probs, encoded_len, transcript, transcript_len) - return [ - self._results_to_ctmUnits(s_id, pred, prob) - for s_id, pred, prob in zip(sample_id.tolist(), predictions, probs) - ] - else: - raise NotImplementedError() - - @torch.no_grad() - def predict_step(self, batch, batch_idx, dataloader_idx=0) -> List[Tuple[int, 'FrameCtmUnit']]: - signal, signal_len, transcript, transcript_len, sample_id = batch - - if isinstance(batch, DALIOutputs) and batch.has_processed_signal: - encoded, encoded_len = self._model.forward(processed_signal=signal, processed_signal_length=signal_len)[:2] - else: - encoded, encoded_len = self._model.forward(input_signal=signal, input_signal_length=signal_len)[:2] - - return self._predict_impl(encoded, encoded_len, transcript, transcript_len, sample_id) - - @torch.no_grad() - def transcribe( - self, manifest: List[str], batch_size: int = 4, num_workers: int = None, verbose: bool = True, - ) -> List['FrameCtmUnit']: - """ - Does alignment. Use this method for debugging and prototyping. - - Args: - - manifest: path to dataset JSON manifest file (in NeMo format). \ - Recommended length per audio 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. - num_workers: (int) number of workers for DataLoader - verbose: (bool) whether to display tqdm progress bar - - Returns: - A list of four: (label, start_frame, length, probability), called FrameCtmUnit, \ - in the same order as in the manifest. - """ - hypotheses = [] - # Model's mode and device - mode = self._model.training - device = next(self._model.parameters()).device - dither_value = self._model.preprocessor.featurizer.dither - pad_to_value = self._model.preprocessor.featurizer.pad_to - - if num_workers is None: - num_workers = min(batch_size, os.cpu_count() - 1) - - try: - self._model.preprocessor.featurizer.dither = 0.0 - self._model.preprocessor.featurizer.pad_to = 0 - - # Switch model to evaluation mode - self._model.eval() - # Freeze the encoder and decoder modules - self._model.encoder.freeze() - self._model.decoder.freeze() - if hasattr(self._model, "joint"): - self._model.joint.freeze() - logging_level = logging.get_verbosity() - logging.set_verbosity(logging.WARNING) - - config = { - 'manifest_filepath': manifest, - 'batch_size': batch_size, - 'num_workers': num_workers, - } - temporary_datalayer = self._model._setup_transcribe_dataloader(config) - for test_batch in tqdm(temporary_datalayer, desc="Aligning", disable=not verbose): - test_batch[0] = test_batch[0].to(device) - test_batch[1] = test_batch[1].to(device) - hypotheses += [unit for i, unit in self.predict_step(test_batch, 0)] - del test_batch - finally: - # set mode back to its original value - self._model.train(mode=mode) - self._model.preprocessor.featurizer.dither = dither_value - self._model.preprocessor.featurizer.pad_to = pad_to_value - - logging.set_verbosity(logging_level) - if mode is True: - self._model.encoder.unfreeze() - self._model.decoder.unfreeze() - if hasattr(self._model, "joint"): - self._model.joint.unfreeze() - return hypotheses - - def setup_training_data(self, train_data_config: Optional[Union[DictConfig, Dict]]): - raise RuntimeError("This module cannot be used in training.") - - def setup_validation_data(self, val_data_config: Optional[Union[DictConfig, Dict]]): - raise RuntimeError("This module cannot be used in validation.") - - def setup_test_data(self, val_data_config: Optional[Union[DictConfig, Dict]]): - raise RuntimeError("This module cannot be used in testing.") diff --git a/nemo/collections/asr/models/k2_sequence_models.py b/nemo/collections/asr/models/k2_sequence_models.py deleted file mode 100644 index b60d08afe6356fef9e53c3861d2239600430ad2d..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/k2_sequence_models.py +++ /dev/null @@ -1,306 +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 - -from lightning.pytorch import Trainer -from omegaconf import DictConfig - -from nemo.collections.asr.models.ctc_bpe_models import EncDecCTCModelBPE -from nemo.collections.asr.models.ctc_models import EncDecCTCModel -from nemo.collections.asr.models.rnnt_bpe_models import EncDecRNNTBPEModel -from nemo.collections.asr.models.rnnt_models import EncDecRNNTModel -from nemo.collections.asr.parts.k2.classes import ASRK2Mixin -from nemo.core.classes.common import PretrainedModelInfo, typecheck -from nemo.utils import logging - - -class EncDecK2SeqModel(EncDecCTCModel, ASRK2Mixin): - """Encoder decoder models with various lattice losses.""" - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - loss_type = cfg.graph_module_cfg.get("loss_type", "ctc") - if loss_type != "ctc" and loss_type != "mmi": - raise ValueError(f"Class {self.__class__.__name__} does not support `loss_type`={loss_type}") - super().__init__(cfg=cfg, trainer=trainer) - self._init_k2() - - @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. - """ - pass - - def change_vocabulary(self, new_vocabulary: List[str]): - """ - 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 - - """ - super().change_vocabulary(new_vocabulary) - - if self.use_graph_lm: - self.token_lm = None - logging.warning( - f"""With .change_vocabulary() call for a model with criterion_type=`{self.loss.criterion_type}`, - a new token_lm has to be set manually: call .update_k2_modules(new_cfg) - or update .graph_module_cfg.backend_cfg.token_lm before calling this method.""" - ) - - self.update_k2_modules(self.graph_module_cfg) - - @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) - """ - log_probs, encoded_len, greedy_predictions = super().forward( - input_signal=input_signal, - input_signal_length=input_signal_length, - processed_signal=processed_signal, - processed_signal_length=processed_signal_length, - ) - return self._forward_k2_post_processing( - log_probs=log_probs, encoded_length=encoded_len, greedy_predictions=greedy_predictions - ) - - -class EncDecK2SeqModelBPE(EncDecCTCModelBPE, ASRK2Mixin): - """Encoder decoder models with Byte Pair Encoding and various lattice losses.""" - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - loss_type = cfg.graph_module_cfg.get("loss_type", "ctc") - if loss_type != "ctc" and loss_type != "mmi": - raise ValueError(f"Class {self.__class__.__name__} does not support `loss_type`={loss_type}") - super().__init__(cfg=cfg, trainer=trainer) - self._init_k2() - - @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. - """ - pass - - def change_vocabulary(self, new_tokenizer_dir: str, new_tokenizer_type: str): - """ - 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: Path to the new tokenizer directory. - new_tokenizer_type: Either `bpe` or `wpe`. `bpe` is used for SentencePiece tokenizers, - whereas `wpe` is used for `BertTokenizer`. - - Returns: None - - """ - super().change_vocabulary(new_tokenizer_dir, new_tokenizer_type) - - if self.use_graph_lm: - self.token_lm = None - logging.warning( - f"""With .change_vocabulary() call for a model with criterion_type=`{self.loss.criterion_type}`, - a new token_lm has to be set manually: call .update_k2_modules(new_cfg) - or update .graph_module_cfg.backend_cfg.token_lm before calling this method.""" - ) - - self.update_k2_modules(self.graph_module_cfg) - - @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) - """ - log_probs, encoded_len, greedy_predictions = super().forward( - input_signal=input_signal, - input_signal_length=input_signal_length, - processed_signal=processed_signal, - processed_signal_length=processed_signal_length, - ) - return self._forward_k2_post_processing( - log_probs=log_probs, encoded_length=encoded_len, greedy_predictions=greedy_predictions - ) - - -class EncDecK2RnntSeqModel(EncDecRNNTModel, ASRK2Mixin): - """Encoder decoder models with various lattice losses.""" - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - loss_type = cfg.graph_module_cfg.get("loss_type", "rnnt") - criterion_type = cfg.graph_module_cfg.get("criterion_type", "ml") - if loss_type != "rnnt" or criterion_type != "ml": - raise ValueError( - f"""Class {self.__class__.__name__} does not support - `criterion_type`={criterion_type} with `loss_type`={loss_type}""" - ) - super().__init__(cfg=cfg, trainer=trainer) - self._init_k2() - - @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. - """ - pass - - def change_vocabulary(self, new_vocabulary: List[str]): - """ - 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 - - """ - super().change_vocabulary(new_vocabulary) - - if self.use_graph_lm: - self.token_lm = None - logging.warning( - f"""With .change_vocabulary() call for a model with criterion_type=`{self.loss.criterion_type}`, - a new token_lm has to be set manually: call .update_k2_modules(new_cfg) - or update .graph_module_cfg.backend_cfg.token_lm before calling this method.""" - ) - - self.update_k2_modules(self.graph_module_cfg) - - -class EncDecK2RnntSeqModelBPE(EncDecRNNTBPEModel, ASRK2Mixin): - """Encoder decoder models with Byte Pair Encoding and various lattice losses.""" - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - loss_type = cfg.graph_module_cfg.get("loss_type", "rnnt") - criterion_type = cfg.graph_module_cfg.get("criterion_type", "ml") - if loss_type != "rnnt" or criterion_type != "ml": - raise ValueError( - f"""Class {self.__class__.__name__} does not support - `criterion_type`={criterion_type} with `loss_type`={loss_type}""" - ) - super().__init__(cfg=cfg, trainer=trainer) - self._init_k2() - - @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. - """ - pass - - def change_vocabulary(self, new_tokenizer_dir: str, new_tokenizer_type: str): - """ - 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: Path to the new tokenizer directory. - new_tokenizer_type: Either `bpe` or `wpe`. `bpe` is used for SentencePiece tokenizers, - whereas `wpe` is used for `BertTokenizer`. - - Returns: None - - """ - super().change_vocabulary(new_tokenizer_dir, new_tokenizer_type) - - if self.use_graph_lm: - self.token_lm = None - logging.warning( - f"""With .change_vocabulary() call for a model with criterion_type=`{self.loss.criterion_type}`, - a new token_lm has to be set manually: call .update_k2_modules(new_cfg) - or update .graph_module_cfg.backend_cfg.token_lm before calling this method.""" - ) - - self.update_k2_modules(self.graph_module_cfg) diff --git a/nemo/collections/asr/models/label_models.py b/nemo/collections/asr/models/label_models.py index 37391879547bca42ea90ada5a16967948c08574b..9300f7cfc897e946072508fbd05ec21c395633d6 100644 --- a/nemo/collections/asr/models/label_models.py +++ b/nemo/collections/asr/models/label_models.py @@ -47,7 +47,7 @@ from nemo.collections.asr.parts.preprocessing.perturb import process_augmentatio 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, typecheck +from nemo.core.classes.common import PretrainedModelInfo from nemo.core.neural_types import * from nemo.utils import logging @@ -172,6 +172,7 @@ class EncDecSpeakerLabelModel(ModelPT, ExportableEncDecModel, VerificationMixin) 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) @@ -356,8 +357,8 @@ class EncDecSpeakerLabelModel(ModelPT, ExportableEncDecModel, VerificationMixin) def forward_for_export(self, audio_signal, length): encoded, length = self.encoder(audio_signal=audio_signal, length=length) - logits, embs = self.decoder(encoder_output=encoded, length=length) - return logits, embs + 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( @@ -394,7 +395,11 @@ class EncDecSpeakerLabelModel(ModelPT, ExportableEncDecModel, VerificationMixin) loss = torch.nn.functional.mse_loss(cosine_sim, loss_labels) else: audio_signal, audio_signal_len, labels, _ = batch - logits, _ = self.forward(input_signal=audio_signal, input_signal_length=audio_signal_len) + 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) @@ -414,7 +419,11 @@ class EncDecSpeakerLabelModel(ModelPT, ExportableEncDecModel, VerificationMixin) return self.pair_evaluation_step(batch, batch_idx, dataloader_idx, tag) audio_signal, audio_signal_len, labels, _ = batch - logits, _ = self.forward(input_signal=audio_signal, input_signal_length=audio_signal_len) + 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) @@ -455,8 +464,8 @@ class EncDecSpeakerLabelModel(ModelPT, ExportableEncDecModel, VerificationMixin) 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._macro_accuracy.update(preds=logits, target=labels) - stats = self._macro_accuracy._final_state() + self._pair_macro_accuracy.update(preds=logits, target=labels) + stats = self._pair_macro_accuracy._final_state() output = { f'{tag}_loss': loss_value, @@ -500,14 +509,14 @@ class EncDecSpeakerLabelModel(ModelPT, ExportableEncDecModel, VerificationMixin) 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._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._macro_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): diff --git a/nemo/collections/asr/models/msdd_models.py b/nemo/collections/asr/models/msdd_models.py deleted file mode 100644 index 5e90f7d62d78690b01b1607a19df67e36ffb101a..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/msdd_models.py +++ /dev/null @@ -1,1592 +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 json -import os -import pickle as pkl -import tempfile -from collections import OrderedDict -from pathlib import Path -from statistics import mode -from typing import Any, Dict, List, Optional, Tuple, Union - -import numpy as np -import torch -from hydra.utils import instantiate -from lightning.pytorch import LightningModule, Trainer -from lightning.pytorch.utilities import rank_zero_only -from omegaconf import DictConfig, open_dict -from pyannote.core import Annotation -from pyannote.metrics.diarization import DiarizationErrorRate -from tqdm import tqdm - -from nemo.collections.asr.data.audio_to_diar_label import AudioToSpeechMSDDInferDataset, AudioToSpeechMSDDTrainDataset -from nemo.collections.asr.metrics.der import score_labels -from nemo.collections.asr.metrics.multi_binary_acc import MultiBinaryAccuracy -from nemo.collections.asr.models import ClusteringDiarizer -from nemo.collections.asr.models.asr_model import ExportableEncDecModel -from nemo.collections.asr.models.clustering_diarizer import ( - _MODEL_CONFIG_YAML, - _SPEAKER_MODEL, - _VAD_MODEL, - get_available_model_names, -) -from nemo.collections.asr.models.configs.diarizer_config import NeuralDiarizerInferenceConfig -from nemo.collections.asr.models.label_models import EncDecSpeakerLabelModel -from nemo.collections.asr.parts.preprocessing.features import WaveformFeaturizer -from nemo.collections.asr.parts.utils.speaker_utils import ( - audio_rttm_map, - get_embs_and_timestamps, - get_id_tup_dict, - get_scale_mapping_argmat, - get_uniq_id_list_from_manifest, - labels_to_pyannote_object, - make_rttm_with_overlap, - parse_scale_configs, - rttm_to_labels, -) -from nemo.core.classes import ModelPT -from nemo.core.classes.common import PretrainedModelInfo, typecheck -from nemo.core.neural_types import AudioSignal, LengthsType, NeuralType -from nemo.core.neural_types.elements import ProbsType -from nemo.utils import logging - -try: - from torch.cuda.amp import autocast -except ImportError: - from contextlib import contextmanager - - @contextmanager - def autocast(enabled=None): - """auto-casting context manager""" - yield - - -__all__ = ['EncDecDiarLabelModel', 'ClusterEmbedding', 'NeuralDiarizer'] - - -class EncDecDiarLabelModel(ModelPT, ExportableEncDecModel): - """ - Encoder decoder class for multiscale diarization decoder (MSDD). Model class creates training, - validation methods for setting up data performing model forward pass. - - This model class expects config dict for: - * preprocessor - * msdd_model - * speaker_model - """ - - @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_msdd_telephonic", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/" - "diar_msdd_telephonic/versions/1.0.1/files/diar_msdd_telephonic.nemo", - description="For details about this model, please visit " - "https://ngc.nvidia.com/catalog/models/nvidia:nemo:diar_msdd_telephonic", - ) - result.append(model) - return result - - def __init__(self, cfg: DictConfig, trainer: Trainer = None): - """ - Initialize an MSDD model and the specified speaker embedding model. In this init function, - training and validation datasets are prepared. - """ - self._trainer = trainer if trainer else None - self.cfg_msdd_model = cfg - - if self._trainer: - self._init_segmentation_info() - self.world_size = trainer.num_nodes * trainer.num_devices - self.emb_batch_size = self.cfg_msdd_model.emb_batch_size - self.pairwise_infer = False - else: - self.world_size = 1 - self.pairwise_infer = True - super().__init__(cfg=self.cfg_msdd_model, trainer=trainer) - - window_length_in_sec = self.cfg_msdd_model.diarizer.speaker_embeddings.parameters.window_length_in_sec - if isinstance(window_length_in_sec, int) or len(window_length_in_sec) <= 1: - raise ValueError("window_length_in_sec should be a list containing multiple segment (window) lengths") - else: - self.cfg_msdd_model.scale_n = len(window_length_in_sec) - self.cfg_msdd_model.msdd_module.scale_n = self.cfg_msdd_model.scale_n - self.scale_n = self.cfg_msdd_model.scale_n - - self.preprocessor = EncDecSpeakerLabelModel.from_config_dict(self.cfg_msdd_model.preprocessor) - self.frame_per_sec = int(1 / self.preprocessor._cfg.window_stride) - self.msdd = EncDecDiarLabelModel.from_config_dict(self.cfg_msdd_model.msdd_module) - - if trainer is not None: - self._init_speaker_model() - self.add_speaker_model_config(cfg) - else: - self.msdd._speaker_model = EncDecSpeakerLabelModel.from_config_dict(cfg.speaker_model_cfg) - - # Call `self.save_hyperparameters` in modelPT.py again since cfg should contain speaker model's config. - self.save_hyperparameters("cfg") - - self.loss = instantiate(self.cfg_msdd_model.loss) - self._accuracy_test = MultiBinaryAccuracy() - self._accuracy_train = MultiBinaryAccuracy() - self._accuracy_valid = MultiBinaryAccuracy() - - def add_speaker_model_config(self, cfg): - """ - Add config dictionary of the speaker model to the model's config dictionary. This is required to - save and load speaker model with MSDD model. - - Args: - cfg (DictConfig): DictConfig type variable that conatains hyperparameters of MSDD model. - """ - with open_dict(cfg): - cfg_cp = copy.copy(self.msdd._speaker_model.cfg) - cfg.speaker_model_cfg = cfg_cp - del cfg.speaker_model_cfg.train_ds - del cfg.speaker_model_cfg.validation_ds - - def _init_segmentation_info(self): - """Initialize segmentation settings: window, shift and multiscale weights.""" - self._diarizer_params = self.cfg_msdd_model.diarizer - 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 _init_speaker_model(self): - """ - Initialize speaker embedding model with model name or path passed through config. Note that - speaker embedding model is loaded to `self.msdd` to enable multi-gpu and multi-node training. - In addition, speaker embedding model is also saved with msdd model when `.ckpt` files are saved. - """ - model_path = self.cfg_msdd_model.diarizer.speaker_embeddings.model_path - self._diarizer_params = self.cfg_msdd_model.diarizer - - if not torch.cuda.is_available(): - rank_id = torch.device('cpu') - elif self._trainer: - rank_id = torch.device(self._trainer.global_rank) - else: - rank_id = None - - if model_path is not None and model_path.endswith('.nemo'): - self.msdd._speaker_model = EncDecSpeakerLabelModel.restore_from(model_path, map_location=rank_id) - 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=rank_id) - 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 = "titanet_large" - logging.info("Loading pretrained {} model from NGC".format(model_path)) - self.msdd._speaker_model = EncDecSpeakerLabelModel.from_pretrained( - model_name=model_path, map_location=rank_id - ) - self._speaker_params = self.cfg_msdd_model.diarizer.speaker_embeddings.parameters - - def __setup_dataloader_from_config(self, config): - featurizer = WaveformFeaturizer( - sample_rate=config['sample_rate'], int_values=config.get('int_values', False), augmentor=None - ) - - 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 = AudioToSpeechMSDDTrainDataset( - manifest_filepath=config.manifest_filepath, - emb_dir=config.emb_dir, - multiscale_args_dict=self.multiscale_args_dict, - soft_label_thres=config.soft_label_thres, - featurizer=featurizer, - window_stride=self.cfg_msdd_model.preprocessor.window_stride, - emb_batch_size=config.emb_batch_size, - pairwise_infer=False, - global_rank=self._trainer.global_rank, - ) - - self.data_collection = dataset.collection - collate_ds = dataset - collate_fn = collate_ds.msdd_train_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=False, - num_workers=config.get('num_workers', 0), - pin_memory=config.get('pin_memory', False), - ) - - def __setup_dataloader_from_config_infer( - self, config: DictConfig, emb_dict: dict, emb_seq: dict, clus_label_dict: dict, pairwise_infer=False - ): - shuffle = config.get('shuffle', 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 - - dataset = AudioToSpeechMSDDInferDataset( - manifest_filepath=config['manifest_filepath'], - emb_dict=emb_dict, - clus_label_dict=clus_label_dict, - emb_seq=emb_seq, - soft_label_thres=config.soft_label_thres, - seq_eval_mode=config.seq_eval_mode, - window_stride=self._cfg.preprocessor.window_stride, - use_single_scale_clus=False, - pairwise_infer=pairwise_infer, - ) - self.data_collection = dataset.collection - collate_ds = dataset - collate_fn = collate_ds.msdd_infer_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_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]]): - if self.pairwise_infer: - self._test_dl = self.__setup_dataloader_from_config_infer( - config=test_data_config, - emb_dict=self.emb_sess_test_dict, - emb_seq=self.emb_seq_test, - clus_label_dict=self.clus_test_label_dict, - pairwise_infer=self.pairwise_infer, - ) - - def setup_multiple_test_data(self, test_data_config): - """ - MSDD does not use multiple_test_data template. This function is a placeholder for preventing error. - """ - return 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 { - "features": NeuralType(('B', 'T'), audio_eltype), - "feature_length": NeuralType(('B',), LengthsType()), - "ms_seg_timestamps": NeuralType(('B', 'C', 'T', 'D'), LengthsType()), - "ms_seg_counts": NeuralType(('B', 'C'), LengthsType()), - "clus_label_index": NeuralType(('B', 'T'), LengthsType()), - "scale_mapping": NeuralType(('B', 'C', 'T'), LengthsType()), - "targets": NeuralType(('B', 'T', 'C'), ProbsType()), - } - - @property - def output_types(self) -> Dict[str, NeuralType]: - return OrderedDict( - { - "probs": NeuralType(('B', 'T', 'C'), ProbsType()), - "scale_weights": NeuralType(('B', 'T', 'C', 'D'), ProbsType()), - } - ) - - def get_ms_emb_seq( - self, embs: torch.Tensor, scale_mapping: torch.Tensor, ms_seg_counts: torch.Tensor - ) -> torch.Tensor: - """ - Reshape the given tensor and organize the embedding sequence based on the original sequence counts. - Repeat the embeddings according to the scale_mapping information so that the final embedding sequence has - the identical length for all scales. - - Args: - embs (Tensor): - Merged embeddings without zero-padding in the batch. See `ms_seg_counts` for details. - Shape: (Total number of segments in the batch, emb_dim) - scale_mapping (Tensor): - The element at the m-th row and the n-th column of the scale mapping matrix indicates - the (m+1)-th scale segment index which has the closest center distance with (n+1)-th segment - in the base scale. - - Example: - scale_mapping_argmat[2][101] = 85 - In the above example, it means that 86-th segment in the 3rd scale (python index is 2) - is mapped with 102-th segment in the base scale. Thus, the longer segments bound to have more - repeating numbers since multiple base scale segments (since the base scale has the shortest length) - fall into the range of the longer segments. At the same time, each row contains N numbers of - indices where N is number of segments in the base-scale (i.e., the finest scale). - Shape: (batch_size, scale_n, self.diar_window_length) - ms_seg_counts (Tensor): - Cumulative sum of the number of segments in each scale. This information is needed to reconstruct - the multi-scale input matrix during forward propagating. - - Example: `batch_size=3, scale_n=6, emb_dim=192` - ms_seg_counts = - [[8, 9, 12, 16, 25, 51], - [11, 13, 14, 17, 25, 51], - [ 9, 9, 11, 16, 23, 50]] - - In this function, `ms_seg_counts` is used to get the actual length of each embedding sequence without - zero-padding. - - Returns: - ms_emb_seq (Tensor): - Multi-scale embedding sequence that is mapped, matched and repeated. The longer scales are - less repeated, while shorter scales are more frequently repeated following the scale mapping tensor. - """ - scale_n, batch_size = scale_mapping[0].shape[0], scale_mapping.shape[0] - split_emb_tup = torch.split(embs, ms_seg_counts.view(-1).tolist(), dim=0) - batch_emb_list = [split_emb_tup[i : i + scale_n] for i in range(0, len(split_emb_tup), scale_n)] - ms_emb_seq_list = [] - for batch_idx in range(batch_size): - feats_list = [] - for scale_index in range(scale_n): - repeat_mat = scale_mapping[batch_idx][scale_index] - feats_list.append(batch_emb_list[batch_idx][scale_index][repeat_mat, :]) - repp = torch.stack(feats_list).permute(1, 0, 2) - ms_emb_seq_list.append(repp) - ms_emb_seq = torch.stack(ms_emb_seq_list) - return ms_emb_seq - - @torch.no_grad() - def get_cluster_avg_embs_model( - self, embs: torch.Tensor, clus_label_index: torch.Tensor, ms_seg_counts: torch.Tensor, scale_mapping - ) -> torch.Tensor: - """ - Calculate the cluster-average speaker embedding based on the ground-truth speaker labels - (i.e., cluster labels). - - Args: - embs (Tensor): - Merged embeddings without zero-padding in the batch. See `ms_seg_counts` for details. - Shape: (Total number of segments in the batch, emb_dim) - clus_label_index (Tensor): - Merged ground-truth cluster labels from all scales with zero-padding. Each scale's - index can be retrieved by using segment index in `ms_seg_counts`. - Shape: (batch_size, maximum total segment count among the samples in the batch) - ms_seg_counts (Tensor): - Cumulative sum of the number of segments in each scale. This information is needed - to reconstruct multi-scale input tensors during forward propagating. - - Example: `batch_size=3, scale_n=6, emb_dim=192` - .. code:: python - - ms_seg_counts = - [ - [ 8, 9, 12, 16, 25, 51], - [11, 13, 14, 17, 25, 51], - [ 9, 9, 11, 16, 23, 50] - ] - - Counts of merged segments: (121, 131, 118) - embs has shape of (370, 192) - clus_label_index has shape of (3, 131) - - Shape: (batch_size, scale_n) - - Returns: - ms_avg_embs (Tensor): - Multi-scale cluster-average speaker embedding vectors. These embedding vectors are used - as reference for each speaker to predict the speaker label for the given multi-scale - embedding sequences. - Shape: (batch_size, scale_n, emb_dim, self.num_spks_per_model) - """ - scale_n, batch_size = scale_mapping[0].shape[0], scale_mapping.shape[0] - split_emb_tup = torch.split(embs, ms_seg_counts.view(-1).tolist(), dim=0) - batch_emb_list = [split_emb_tup[i : i + scale_n] for i in range(0, len(split_emb_tup), scale_n)] - ms_avg_embs_list = [] - for batch_idx in range(batch_size): - oracle_clus_idx = clus_label_index[batch_idx] - max_seq_len = sum(ms_seg_counts[batch_idx]) - clus_label_index_batch = torch.split(oracle_clus_idx[:max_seq_len], ms_seg_counts[batch_idx].tolist()) - session_avg_emb_set_list = [] - for scale_index in range(scale_n): - spk_set_list = [] - for idx in range(self.cfg_msdd_model.max_num_of_spks): - _where = (clus_label_index_batch[scale_index] == idx).clone().detach() - if not torch.any(_where): - avg_emb = torch.zeros(self.msdd._speaker_model._cfg.decoder.emb_sizes).to(embs.device) - else: - avg_emb = torch.mean(batch_emb_list[batch_idx][scale_index][_where], dim=0) - spk_set_list.append(avg_emb) - session_avg_emb_set_list.append(torch.stack(spk_set_list)) - session_avg_emb_set = torch.stack(session_avg_emb_set_list) - ms_avg_embs_list.append(session_avg_emb_set) - - ms_avg_embs = torch.stack(ms_avg_embs_list).permute(0, 1, 3, 2) - ms_avg_embs = ms_avg_embs.float().detach().to(embs.device) - assert ( - not ms_avg_embs.requires_grad - ), "ms_avg_embs.requires_grad = True. ms_avg_embs should be detached from the torch graph." - return ms_avg_embs - - @torch.no_grad() - def get_ms_mel_feat( - self, - processed_signal: torch.Tensor, - processed_signal_len: torch.Tensor, - ms_seg_timestamps: torch.Tensor, - ms_seg_counts: torch.Tensor, - ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: - """ - Load acoustic feature from audio segments for each scale and save it into a torch.tensor matrix. - In addition, create variables containing the information of the multiscale subsegmentation information. - - Note: `self.emb_batch_size` determines the number of embedding tensors attached to the computational graph. - If `self.emb_batch_size` is greater than 0, speaker embedding models are simultaneosly trained. Due to the - constrant of GPU memory size, only a subset of embedding tensors can be attached to the computational graph. - By default, the graph-attached embeddings are selected randomly by `torch.randperm`. Default value of - `self.emb_batch_size` is 0. - - Args: - processed_signal (Tensor): - Zero-padded Feature input. - Shape: (batch_size, feat_dim, the longest feature sequence length) - processed_signal_len (Tensor): - The actual legnth of feature input without zero-padding. - Shape: (batch_size,) - ms_seg_timestamps (Tensor): - Timestamps of the base-scale segments. - Shape: (batch_size, scale_n, number of base-scale segments, self.num_spks_per_model) - ms_seg_counts (Tensor): - Cumulative sum of the number of segments in each scale. This information is needed to reconstruct - the multi-scale input matrix during forward propagating. - Shape: (batch_size, scale_n) - - Returns: - ms_mel_feat (Tensor): - Feature input stream split into the same length. - Shape: (total number of segments, feat_dim, self.frame_per_sec * the-longest-scale-length) - ms_mel_feat_len (Tensor): - The actual length of feature without zero-padding. - Shape: (total number of segments,) - seq_len (Tensor): - The length of the input embedding sequences. - Shape: (total number of segments,) - detach_ids (tuple): - Tuple containing both detached embeding indices and attached embedding indices - """ - device = processed_signal.device - _emb_batch_size = min(self.emb_batch_size, ms_seg_counts.sum().item()) - feat_dim = self.preprocessor._cfg.features - max_sample_count = int(self.multiscale_args_dict["scale_dict"][0][0] * self.frame_per_sec) - ms_mel_feat_len_list, sequence_lengths_list, ms_mel_feat_list = [], [], [] - total_seg_count = torch.sum(ms_seg_counts) - - batch_size = processed_signal.shape[0] - for batch_idx in range(batch_size): - for scale_idx in range(self.scale_n): - scale_seg_num = ms_seg_counts[batch_idx][scale_idx] - for k, (stt, end) in enumerate(ms_seg_timestamps[batch_idx][scale_idx][:scale_seg_num]): - stt, end = int(stt.detach().item()), int(end.detach().item()) - end = min(end, stt + max_sample_count) - _features = torch.zeros(feat_dim, max_sample_count).to(torch.float32).to(device) - _features[:, : (end - stt)] = processed_signal[batch_idx][:, stt:end] - ms_mel_feat_list.append(_features) - ms_mel_feat_len_list.append(end - stt) - sequence_lengths_list.append(ms_seg_counts[batch_idx][-1]) - ms_mel_feat = torch.stack(ms_mel_feat_list).to(device) - ms_mel_feat_len = torch.tensor(ms_mel_feat_len_list).to(device) - seq_len = torch.tensor(sequence_lengths_list).to(device) - - if _emb_batch_size == 0: - attached, _emb_batch_size = torch.tensor([]), 0 - detached = torch.arange(total_seg_count) - else: - torch.manual_seed(self._trainer.current_epoch) - attached = torch.randperm(total_seg_count)[:_emb_batch_size] - detached = torch.randperm(total_seg_count)[_emb_batch_size:] - detach_ids = (attached, detached) - return ms_mel_feat, ms_mel_feat_len, seq_len, detach_ids - - def forward_infer(self, input_signal, input_signal_length, emb_vectors, targets): - """ - Wrapper function for inference case. This `forward_infer` is only used during inference, where `forward` - is used for training and validation. - """ - preds, scale_weights = self.msdd( - ms_emb_seq=input_signal, length=input_signal_length, ms_avg_embs=emb_vectors, targets=targets - ) - return preds, scale_weights - - @typecheck() - def forward( - self, features, feature_length, ms_seg_timestamps, ms_seg_counts, clus_label_index, scale_mapping, targets - ): - """Function to compute forward pass for training/validation.""" - processed_signal, processed_signal_len = self.msdd._speaker_model.preprocessor( - input_signal=features, length=feature_length - ) - audio_signal, audio_signal_len, sequence_lengths, detach_ids = self.get_ms_mel_feat( - processed_signal, processed_signal_len, ms_seg_timestamps, ms_seg_counts - ) - - # For detached embeddings - with torch.no_grad(): - self.msdd._speaker_model.eval() - logits, embs_d = self.msdd._speaker_model.forward_for_export( - audio_signal=audio_signal[detach_ids[1]], length=audio_signal_len[detach_ids[1]] - ) - embs = torch.zeros(audio_signal.shape[0], embs_d.shape[1]).to(embs_d.device) - embs[detach_ids[1], :] = embs_d.detach() - - # For attached embeddings - self.msdd._speaker_model.train() - if len(detach_ids[0]) > 1: - logits, embs_a = self.msdd._speaker_model.forward_for_export( - audio_signal=audio_signal[detach_ids[0]], length=audio_signal_len[detach_ids[0]] - ) - embs[detach_ids[0], :] = embs_a - - ms_emb_seq = self.get_ms_emb_seq(embs, scale_mapping, ms_seg_counts) - ms_avg_embs = self.get_cluster_avg_embs_model(embs, clus_label_index, ms_seg_counts, scale_mapping) - preds, scale_weights = self.msdd( - ms_emb_seq=ms_emb_seq, length=sequence_lengths, ms_avg_embs=ms_avg_embs, targets=targets - ) - return preds, scale_weights - - def training_step(self, batch: list, batch_idx: int): - """Function to compute training step.""" - features, feature_length, ms_seg_timestamps, ms_seg_counts, clus_label_index, scale_mapping, targets = batch - sequence_lengths = torch.tensor([x[-1] for x in ms_seg_counts.detach()]) - preds, _ = self.forward( - features=features, - feature_length=feature_length, - ms_seg_timestamps=ms_seg_timestamps, - ms_seg_counts=ms_seg_counts, - clus_label_index=clus_label_index, - scale_mapping=scale_mapping, - targets=targets, - ) - # loss = self.loss(probs=preds, labels=targets, signal_lengths=sequence_lengths) - loss = self.loss(probs=preds, labels=targets, target_lens=sequence_lengths) - self._accuracy_train(preds, targets, sequence_lengths) - torch.cuda.empty_cache() - f1_acc, _, _ = self._accuracy_train.compute() - self.log('loss', loss, sync_dist=True) - self.log('learning_rate', self._optimizer.param_groups[0]['lr'], sync_dist=True) - self.log('train_f1_acc', f1_acc, sync_dist=True) - self._accuracy_train.reset() - return {'loss': loss} - - def validation_step(self, batch: list, batch_idx: int, dataloader_idx: int = 0): - """Function to compute validation step.""" - features, feature_length, ms_seg_timestamps, ms_seg_counts, clus_label_index, scale_mapping, targets = batch - sequence_lengths = torch.tensor([x[-1] for x in ms_seg_counts]) - preds, _ = self.forward( - features=features, - feature_length=feature_length, - ms_seg_timestamps=ms_seg_timestamps, - ms_seg_counts=ms_seg_counts, - clus_label_index=clus_label_index, - scale_mapping=scale_mapping, - targets=targets, - ) - # loss = self.loss(probs=preds, labels=targets, signal_lengths=sequence_lengths) - loss = self.loss(probs=preds, labels=targets, target_lens=sequence_lengths) - self._accuracy_valid(preds, targets, sequence_lengths) - f1_acc, _, _ = self._accuracy_valid.compute() - self.log('val_loss', loss, sync_dist=True) - self.log('val_f1_acc', f1_acc, sync_dist=True) - return { - 'val_loss': loss, - 'val_f1_acc': f1_acc, - } - - def multi_validation_epoch_end(self, outputs: list, dataloader_idx: int = 0): - val_loss_mean = torch.stack([x['val_loss'] for x in outputs]).mean() - f1_acc, _, _ = self._accuracy_valid.compute() - self._accuracy_valid.reset() - - self.log('val_loss', val_loss_mean, sync_dist=True) - self.log('val_f1_acc', f1_acc, sync_dist=True) - return { - 'val_loss': val_loss_mean, - 'val_f1_acc': f1_acc, - } - - def multi_test_epoch_end(self, outputs: List[Dict[str, torch.Tensor]], dataloader_idx: int = 0): - test_loss_mean = torch.stack([x['test_loss'] for x in outputs]).mean() - f1_acc, _, _ = self._accuracy_test.compute() - self._accuracy_test.reset() - self.log('test_f1_acc', f1_acc, sync_dist=True) - return { - 'test_loss': test_loss_mean, - 'test_f1_acc': f1_acc, - } - - def compute_accuracies(self): - """ - Calculate F1 score and accuracy of the predicted sigmoid values. - - Returns: - f1_score (float): F1 score of the estimated diarized speaker label sequences. - simple_acc (float): Accuracy of predicted speaker labels: - (total # of correct labels)/(total # of sigmoid values) - """ - f1_score, _, _ = self._accuracy_test.compute() - num_correct = torch.sum(self._accuracy_test.true.bool()) - total_count = torch.prod(torch.tensor(self._accuracy_test.targets.shape)) - simple_acc = num_correct / total_count - return f1_score, simple_acc - - -class ClusterEmbedding(torch.nn.Module): - """ - This class is built for calculating cluster-average embeddings, segmentation and load/save of - the estimated cluster labels. - - The methods in this class is used for the inference of MSDD models. - - Args: - cfg_diar_infer (DictConfig): - Config dictionary from diarization inference YAML file - cfg_msdd_model (DictConfig): - Config dictionary from MSDD model checkpoint file - - Class Variables: - self.cfg_diar_infer (DictConfig): - Config dictionary from diarization inference YAML file - cfg_msdd_model (DictConfig): - Config dictionary from MSDD model checkpoint file - self._speaker_model (class `EncDecSpeakerLabelModel`): - This is a placeholder for class instance of `EncDecSpeakerLabelModel` - self.scale_window_length_list (list): - List containing the window lengths (i.e., scale length) of each scale. - self.scale_n (int): - Number of scales for multi-scale clustering diarizer - self.base_scale_index (int): - The index of the base-scale which is the shortest scale among the given multiple scales - """ - - def __init__( - self, cfg_diar_infer: DictConfig, cfg_msdd_model: DictConfig, speaker_model: Optional[EncDecSpeakerLabelModel] - ): - super().__init__() - self.cfg_diar_infer = cfg_diar_infer - self._cfg_msdd = cfg_msdd_model - self._speaker_model = speaker_model - self.scale_window_length_list = list( - self.cfg_diar_infer.diarizer.speaker_embeddings.parameters.window_length_in_sec - ) - self.scale_n = len(self.scale_window_length_list) - self.base_scale_index = len(self.scale_window_length_list) - 1 - self.clus_diar_model = ClusteringDiarizer(cfg=self.cfg_diar_infer, speaker_model=self._speaker_model) - - def prepare_cluster_embs_infer(self): - """ - Launch clustering diarizer to prepare embedding vectors and clustering results. - """ - self.max_num_speakers = self.cfg_diar_infer.diarizer.clustering.parameters.max_num_speakers - self.emb_sess_test_dict, self.emb_seq_test, self.clus_test_label_dict, _ = self.run_clustering_diarizer( - self._cfg_msdd.test_ds.manifest_filepath, self._cfg_msdd.test_ds.emb_dir - ) - - def assign_labels_to_longer_segs(self, base_clus_label_dict: Dict, session_scale_mapping_dict: Dict): - """ - In multi-scale speaker diarization system, clustering result is solely based on the base-scale - (the shortest scale). To calculate cluster-average speaker embeddings for each scale that are longer - than the base-scale, this function assigns clustering results for the base-scale to the longer scales - by measuring the distance between subsegment timestamps in the base-scale and non-base-scales. - - Args: - base_clus_label_dict (dict): - Dictionary containing clustering results for base-scale segments. Indexed by `uniq_id` string. - session_scale_mapping_dict (dict): - Dictionary containing multiscale mapping information for each session. Indexed by `uniq_id` string. - - Returns: - all_scale_clus_label_dict (dict): - Dictionary containing clustering labels of all scales. Indexed by scale_index in integer format. - - """ - all_scale_clus_label_dict = {scale_index: {} for scale_index in range(self.scale_n)} - for uniq_id, uniq_scale_mapping_dict in session_scale_mapping_dict.items(): - base_scale_clus_label = np.array([x[-1] for x in base_clus_label_dict[uniq_id]]) - all_scale_clus_label_dict[self.base_scale_index][uniq_id] = base_scale_clus_label - for scale_index in range(self.scale_n - 1): - new_clus_label = [] - assert ( - uniq_scale_mapping_dict[scale_index].shape[0] == base_scale_clus_label.shape[0] - ), "The number of base scale labels does not match the segment numbers in uniq_scale_mapping_dict" - max_index = max(uniq_scale_mapping_dict[scale_index]) - for seg_idx in range(max_index + 1): - if seg_idx in uniq_scale_mapping_dict[scale_index]: - seg_clus_label = mode(base_scale_clus_label[uniq_scale_mapping_dict[scale_index] == seg_idx]) - else: - seg_clus_label = 0 if len(new_clus_label) == 0 else new_clus_label[-1] - new_clus_label.append(seg_clus_label) - all_scale_clus_label_dict[scale_index][uniq_id] = new_clus_label - return all_scale_clus_label_dict - - def get_base_clus_label_dict(self, clus_labels: List[str], emb_scale_seq_dict: Dict[int, dict]): - """ - Retrieve base scale clustering labels from `emb_scale_seq_dict`. - - Args: - clus_labels (list): - List containing cluster results generated by clustering diarizer. - emb_scale_seq_dict (dict): - Dictionary containing multiscale embedding input sequences. - Returns: - base_clus_label_dict (dict): - Dictionary containing start and end of base scale segments and its cluster label. - Indexed by `uniq_id`. - emb_dim (int): - Embedding dimension in integer. - """ - base_clus_label_dict = {key: [] for key in emb_scale_seq_dict[self.base_scale_index].keys()} - for line in clus_labels: - uniq_id = line.split()[0] - label = int(line.split()[-1].split('_')[-1]) - stt, end = [round(float(x), 2) for x in line.split()[1:3]] - base_clus_label_dict[uniq_id].append([stt, end, label]) - emb_dim = emb_scale_seq_dict[0][uniq_id][0].shape[0] - return base_clus_label_dict, emb_dim - - def get_cluster_avg_embs( - self, emb_scale_seq_dict: Dict, clus_labels: List, speaker_mapping_dict: Dict, session_scale_mapping_dict: Dict - ): - """ - MSDD requires cluster-average speaker embedding vectors for each scale. This function calculates - an average embedding vector for each cluster (speaker) and each scale. - - Args: - emb_scale_seq_dict (dict): - Dictionary containing embedding sequence for each scale. Keys are scale index in integer. - clus_labels (list): - Clustering results from clustering diarizer including all the sessions provided - in input manifest files. - speaker_mapping_dict (dict): - Speaker mapping dictionary in case RTTM files are provided. This is mapping between - integer based speaker index and speaker ID tokens in RTTM files. - Example: - {'en_0638': {'speaker_0': 'en_0638_A', 'speaker_1': 'en_0638_B'}, - 'en_4065': {'speaker_0': 'en_4065_B', 'speaker_1': 'en_4065_A'}, ...,} - session_scale_mapping_dict (dict): - Dictionary containing multiscale mapping information for each session. Indexed by `uniq_id` string. - - Returns: - emb_sess_avg_dict (dict): - Dictionary containing speaker mapping information and cluster-average speaker embedding vector. - Each session-level dictionary is indexed by scale index in integer. - output_clus_label_dict (dict): - Subegmentation timestamps in float type and Clustering result in integer type. - Indexed by `uniq_id` keys. - """ - self.scale_n = len(emb_scale_seq_dict.keys()) - emb_sess_avg_dict = { - scale_index: {key: [] for key in emb_scale_seq_dict[self.scale_n - 1].keys()} - for scale_index in emb_scale_seq_dict.keys() - } - output_clus_label_dict, emb_dim = self.get_base_clus_label_dict(clus_labels, emb_scale_seq_dict) - all_scale_clus_label_dict = self.assign_labels_to_longer_segs( - output_clus_label_dict, session_scale_mapping_dict - ) - for scale_index in emb_scale_seq_dict.keys(): - for uniq_id, _emb_tensor in emb_scale_seq_dict[scale_index].items(): - if type(_emb_tensor) == list: - emb_tensor = torch.tensor(np.array(_emb_tensor)) - else: - emb_tensor = _emb_tensor - clus_label_list = all_scale_clus_label_dict[scale_index][uniq_id] - spk_set = set(clus_label_list) - - # Create a label array which identifies clustering result for each segment. - label_array = torch.Tensor(clus_label_list) - avg_embs = torch.zeros(emb_dim, self.max_num_speakers) - for spk_idx in spk_set: - selected_embs = emb_tensor[label_array == spk_idx] - avg_embs[:, spk_idx] = torch.mean(selected_embs, dim=0) - - if speaker_mapping_dict is not None: - inv_map = {clus_key: rttm_key for rttm_key, clus_key in speaker_mapping_dict[uniq_id].items()} - else: - inv_map = None - - emb_sess_avg_dict[scale_index][uniq_id] = {'mapping': inv_map, 'avg_embs': avg_embs} - return emb_sess_avg_dict, output_clus_label_dict - - def run_clustering_diarizer(self, manifest_filepath: str, emb_dir: str): - """ - If no pre-existing data is provided, run clustering diarizer from scratch. This will create - scale-wise speaker embedding sequence, cluster-average embeddings, scale mapping and base scale - clustering labels. Note that speaker embedding `state_dict` is loaded from the `state_dict` - in the provided MSDD checkpoint. - - Args: - manifest_filepath (str): - Input manifest file for creating audio-to-RTTM mapping. - emb_dir (str): - Output directory where embedding files and timestamp files are saved. - - Returns: - emb_sess_avg_dict (dict): - Dictionary containing cluster-average embeddings for each session. - emb_scale_seq_dict (dict): - Dictionary containing embedding tensors which are indexed by scale numbers. - base_clus_label_dict (dict): - Dictionary containing clustering results. Clustering results are cluster labels - for the base scale segments. - """ - self.cfg_diar_infer.diarizer.manifest_filepath = manifest_filepath - self.cfg_diar_infer.diarizer.out_dir = emb_dir - - # Run ClusteringDiarizer which includes system VAD or oracle VAD. - self._out_dir = self.clus_diar_model._diarizer_params.out_dir - self.out_rttm_dir = os.path.join(self._out_dir, 'pred_rttms') - os.makedirs(self.out_rttm_dir, exist_ok=True) - - self.clus_diar_model._cluster_params = self.cfg_diar_infer.diarizer.clustering.parameters - self.clus_diar_model.multiscale_args_dict["multiscale_weights"] = ( - self.cfg_diar_infer.diarizer.speaker_embeddings.parameters.multiscale_weights - ) - self.clus_diar_model._diarizer_params.speaker_embeddings.parameters = ( - self.cfg_diar_infer.diarizer.speaker_embeddings.parameters - ) - cluster_params = self.clus_diar_model._cluster_params - cluster_params = dict(cluster_params) if isinstance(cluster_params, DictConfig) else cluster_params.dict() - clustering_params_str = json.dumps(cluster_params, indent=4) - - logging.info(f"Multiscale Weights: {self.clus_diar_model.multiscale_args_dict['multiscale_weights']}") - logging.info(f"Clustering Parameters: {clustering_params_str}") - scores = self.clus_diar_model.diarize(batch_size=self.cfg_diar_infer.batch_size) - - # If RTTM (ground-truth diarization annotation) files do not exist, scores is None. - if scores is not None: - metric, speaker_mapping_dict, _ = scores - else: - metric, speaker_mapping_dict = None, None - - # Get the mapping between segments in different scales. - self._embs_and_timestamps = get_embs_and_timestamps( - self.clus_diar_model.multiscale_embeddings_and_timestamps, self.clus_diar_model.multiscale_args_dict - ) - session_scale_mapping_dict = self.get_scale_map(self._embs_and_timestamps) - emb_scale_seq_dict = self.load_emb_scale_seq_dict(emb_dir) - clus_labels = self.load_clustering_labels(emb_dir) - emb_sess_avg_dict, base_clus_label_dict = self.get_cluster_avg_embs( - emb_scale_seq_dict, clus_labels, speaker_mapping_dict, session_scale_mapping_dict - ) - emb_scale_seq_dict['session_scale_mapping'] = session_scale_mapping_dict - return emb_sess_avg_dict, emb_scale_seq_dict, base_clus_label_dict, metric - - def get_scale_map(self, embs_and_timestamps): - """ - Save multiscale mapping data into dictionary format. - - Args: - embs_and_timestamps (dict): - Dictionary containing embedding tensors and timestamp tensors. Indexed by `uniq_id` string. - Returns: - session_scale_mapping_dict (dict): - Dictionary containing multiscale mapping information for each session. Indexed by `uniq_id` string. - """ - session_scale_mapping_dict = {} - for uniq_id, uniq_embs_and_timestamps in embs_and_timestamps.items(): - scale_mapping_dict = get_scale_mapping_argmat(uniq_embs_and_timestamps) - session_scale_mapping_dict[uniq_id] = scale_mapping_dict - return session_scale_mapping_dict - - def check_clustering_labels(self, out_dir): - """ - Check whether the laoded clustering label file is including clustering results for all sessions. - This function is used for inference mode of MSDD. - - Args: - out_dir (str): - Path to the directory where clustering result files are saved. - Returns: - file_exists (bool): - Boolean that indicates whether clustering result file exists. - clus_label_path (str): - Path to the clustering label output file. - """ - clus_label_path = os.path.join( - out_dir, 'speaker_outputs', f'subsegments_scale{self.base_scale_index}_cluster.label' - ) - file_exists = os.path.exists(clus_label_path) - if not file_exists: - logging.info(f"Clustering label file {clus_label_path} does not exist.") - return file_exists, clus_label_path - - def load_clustering_labels(self, out_dir): - """ - Load clustering labels generated by clustering diarizer. This function is used for inference mode of MSDD. - - Args: - out_dir (str): - Path to the directory where clustering result files are saved. - Returns: - emb_scale_seq_dict (dict): - List containing clustering results in string format. - """ - file_exists, clus_label_path = self.check_clustering_labels(out_dir) - logging.info(f"Loading cluster label file from {clus_label_path}") - with open(clus_label_path) as f: - clus_labels = f.readlines() - return clus_labels - - def load_emb_scale_seq_dict(self, out_dir): - """ - Load saved embeddings generated by clustering diarizer. This function is used for inference mode of MSDD. - - Args: - out_dir (str): - Path to the directory where embedding pickle files are saved. - Returns: - emb_scale_seq_dict (dict): - Dictionary containing embedding tensors which are indexed by scale numbers. - """ - window_len_list = list(self.cfg_diar_infer.diarizer.speaker_embeddings.parameters.window_length_in_sec) - emb_scale_seq_dict = {scale_index: None for scale_index in range(len(window_len_list))} - for scale_index in range(len(window_len_list)): - pickle_path = os.path.join( - out_dir, 'speaker_outputs', 'embeddings', f'subsegments_scale{scale_index}_embeddings.pkl' - ) - logging.info(f"Loading embedding pickle file of scale:{scale_index} at {pickle_path}") - with open(pickle_path, "rb") as input_file: - emb_dict = pkl.load(input_file) - for key, val in emb_dict.items(): - emb_dict[key] = val - emb_scale_seq_dict[scale_index] = emb_dict - return emb_scale_seq_dict - - -class NeuralDiarizer(LightningModule): - """ - Class for inference based on multiscale diarization decoder (MSDD). MSDD requires initializing - clustering results from clustering diarizer. Overlap-aware diarizer requires separate RTTM - generation and evaluation modules to check the effect of overlap detection in speaker diarization. - """ - - def __init__(self, cfg: Union[DictConfig, NeuralDiarizerInferenceConfig]): - super().__init__() - self._cfg = cfg - - # Parameter settings for MSDD model - self.use_speaker_model_from_ckpt = cfg.diarizer.msdd_model.parameters.get('use_speaker_model_from_ckpt', True) - self.use_clus_as_main = cfg.diarizer.msdd_model.parameters.get('use_clus_as_main', False) - self.max_overlap_spks = cfg.diarizer.msdd_model.parameters.get('max_overlap_spks', 2) - self.num_spks_per_model = cfg.diarizer.msdd_model.parameters.get('num_spks_per_model', 2) - self.use_adaptive_thres = cfg.diarizer.msdd_model.parameters.get('use_adaptive_thres', True) - self.max_pred_length = cfg.diarizer.msdd_model.parameters.get('max_pred_length', 0) - self.diar_eval_settings = cfg.diarizer.msdd_model.parameters.get( - 'diar_eval_settings', [(0.25, True), (0.25, False), (0.0, False)] - ) - - self._init_msdd_model(cfg) - self.diar_window_length = cfg.diarizer.msdd_model.parameters.diar_window_length - self.msdd_model.cfg = self.transfer_diar_params_to_model_params(self.msdd_model, cfg) - - # Initialize clustering and embedding preparation instance (as a diarization encoder). - self.clustering_embedding = ClusterEmbedding( - cfg_diar_infer=cfg, cfg_msdd_model=self.msdd_model.cfg, speaker_model=self._speaker_model - ) - - # Parameters for creating diarization results from MSDD outputs. - self.clustering_max_spks = self.msdd_model._cfg.max_num_of_spks - self.overlap_infer_spk_limit = cfg.diarizer.msdd_model.parameters.get( - 'overlap_infer_spk_limit', self.clustering_max_spks - ) - - def transfer_diar_params_to_model_params(self, msdd_model, cfg): - """ - Transfer the parameters that are needed for MSDD inference from the diarization inference config files - to MSDD model config `msdd_model.cfg`. - """ - msdd_model.cfg.diarizer.out_dir = cfg.diarizer.out_dir - msdd_model.cfg.test_ds.manifest_filepath = cfg.diarizer.manifest_filepath - msdd_model.cfg.test_ds.emb_dir = cfg.diarizer.out_dir - msdd_model.cfg.test_ds.batch_size = cfg.diarizer.msdd_model.parameters.infer_batch_size - msdd_model.cfg.test_ds.seq_eval_mode = cfg.diarizer.msdd_model.parameters.seq_eval_mode - msdd_model._cfg.max_num_of_spks = cfg.diarizer.clustering.parameters.max_num_speakers - return msdd_model.cfg - - @rank_zero_only - def save_to(self, save_path: str): - """ - Saves model instances (weights and configuration) into EFF archive. - 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 - """ - self.clus_diar = self.clustering_embedding.clus_diar_model - _NEURAL_DIAR_MODEL = "msdd_model.nemo" - - with tempfile.TemporaryDirectory() as tmpdir: - config_yaml = os.path.join(tmpdir, _MODEL_CONFIG_YAML) - spkr_model = os.path.join(tmpdir, _SPEAKER_MODEL) - neural_diar_model = os.path.join(tmpdir, _NEURAL_DIAR_MODEL) - - self.clus_diar.to_config_file(path2yaml_file=config_yaml) - if self.clus_diar.has_vad_model: - vad_model = os.path.join(tmpdir, _VAD_MODEL) - self.clus_diar._vad_model.save_to(vad_model) - self.clus_diar._speaker_model.save_to(spkr_model) - self.msdd_model.save_to(neural_diar_model) - self.clus_diar.__make_nemo_file_from_folder(filename=save_path, source_dir=tmpdir) - - def extract_standalone_speaker_model(self, prefix: str = 'msdd._speaker_model.') -> EncDecSpeakerLabelModel: - """ - MSDD model file contains speaker embedding model and MSDD model. This function extracts standalone - speaker model and save it to `self.spk_emb_state_dict` to be loaded separately for clustering diarizer. - - Args: - ext (str): - File-name extension of the provided model path. - Returns: - standalone_model_path (str): - Path to the extracted standalone model without speaker embedding extractor model. - """ - model_state_dict = self.msdd_model.state_dict() - spk_emb_module_names = [] - for name in model_state_dict.keys(): - if prefix in name: - spk_emb_module_names.append(name) - - spk_emb_state_dict = {} - for name in spk_emb_module_names: - org_name = name.replace(prefix, '') - spk_emb_state_dict[org_name] = model_state_dict[name] - - _speaker_model = EncDecSpeakerLabelModel.from_config_dict(self.msdd_model.cfg.speaker_model_cfg) - _speaker_model.load_state_dict(spk_emb_state_dict) - return _speaker_model - - def _init_msdd_model(self, cfg: Union[DictConfig, NeuralDiarizerInferenceConfig]): - """ - Initialized MSDD model with the provided config. Load either from `.nemo` file or `.ckpt` checkpoint files. - """ - model_path = cfg.diarizer.msdd_model.model_path - if model_path.endswith('.nemo'): - logging.info(f"Using local nemo file from {model_path}") - self.msdd_model = EncDecDiarLabelModel.restore_from(restore_path=model_path, map_location=cfg.device) - elif model_path.endswith('.ckpt'): - logging.info(f"Using local checkpoint from {model_path}") - self.msdd_model = EncDecDiarLabelModel.load_from_checkpoint( - checkpoint_path=model_path, map_location=cfg.device - ) - else: - if model_path not in get_available_model_names(EncDecDiarLabelModel): - logging.warning(f"requested {model_path} model name not available in pretrained models, instead") - logging.info("Loading pretrained {} model from NGC".format(model_path)) - self.msdd_model = EncDecDiarLabelModel.from_pretrained(model_name=model_path, map_location=cfg.device) - # Load speaker embedding model state_dict which is loaded from the MSDD checkpoint. - if self.use_speaker_model_from_ckpt: - self._speaker_model = self.extract_standalone_speaker_model() - else: - self._speaker_model = None - - def get_pred_mat(self, data_list: List[Union[Tuple[int], List[torch.Tensor]]]) -> torch.Tensor: - """ - This module puts together the pairwise, two-speaker, predicted results to form a finalized matrix - that has dimension of `(total_len, n_est_spks)`. The pairwise results are evenutally averaged. - For example, in 4 speaker case (speaker 1, 2, 3, 4), the sum of the pairwise results - (1, 2), (1, 3), (1, 4) are then divided by 3 to take average of the sigmoid values. - - Args: - data_list (list): - List containing data points from `test_data_collection` variable. `data_list` - has sublists `data` as follows: - data[0]: `target_spks` tuple - Examples: (0, 1, 2) - data[1]: Tensor containing estimaged sigmoid values. - [[0.0264, 0.9995], - [0.0112, 1.0000], - ..., - [1.0000, 0.0512]] - - Returns: - sum_pred (Tensor): - Tensor containing the averaged sigmoid values for each speaker. - """ - all_tups = tuple() - for data in data_list: - all_tups += data[0] - n_est_spks = len(set(all_tups)) - digit_map = dict(zip(sorted(set(all_tups)), range(n_est_spks))) - total_len = max([sess[1].shape[1] for sess in data_list]) - sum_pred = torch.zeros(total_len, n_est_spks) - for _dim_tup, pred_mat in data_list: - dim_tup = [digit_map[x] for x in _dim_tup] - if len(pred_mat.shape) == 3: - pred_mat = pred_mat.squeeze(0) - if n_est_spks <= self.num_spks_per_model: - sum_pred = pred_mat - else: - _end = pred_mat.shape[0] - sum_pred[:_end, dim_tup] += pred_mat.cpu().float() - sum_pred = sum_pred / (n_est_spks - 1) - return sum_pred - - def get_integrated_preds_list( - self, uniq_id_list: List[str], test_data_collection: List[Any], preds_list: List[torch.Tensor] - ) -> List[torch.Tensor]: - """ - Merge multiple sequence inference outputs into a session level result. - - Args: - uniq_id_list (list): - List containing `uniq_id` values. - test_data_collection (collections.DiarizationLabelEntity): - Class instance that is containing session information such as targeted speaker indices, - audio filepaths and RTTM filepaths. - preds_list (list): - List containing tensors filled with sigmoid values. - - Returns: - output_list (list): - List containing session-level estimated prediction matrix. - """ - session_dict = get_id_tup_dict(uniq_id_list, test_data_collection, preds_list) - output_dict = {uniq_id: [] for uniq_id in uniq_id_list} - for uniq_id, data_list in session_dict.items(): - sum_pred = self.get_pred_mat(data_list) - output_dict[uniq_id] = sum_pred.unsqueeze(0) - output_list = [output_dict[uniq_id] for uniq_id in uniq_id_list] - return output_list - - def get_emb_clus_infer(self, cluster_embeddings): - """Assign dictionaries containing the clustering results from the class instance `cluster_embeddings`.""" - self.msdd_model.emb_sess_test_dict = cluster_embeddings.emb_sess_test_dict - self.msdd_model.clus_test_label_dict = cluster_embeddings.clus_test_label_dict - self.msdd_model.emb_seq_test = cluster_embeddings.emb_seq_test - - @torch.no_grad() - def diarize(self) -> Optional[List[Optional[List[Tuple[DiarizationErrorRate, Dict]]]]]: - """ - Launch diarization pipeline which starts from VAD (or a oracle VAD stamp generation), - initialization clustering and multiscale diarization decoder (MSDD). Note that the result of MSDD - can include multiple speakers at the same time. Therefore, RTTM output of MSDD needs to be based on - `make_rttm_with_overlap()` function that can generate overlapping timestamps. - `self.run_overlap_aware_eval()` function performs DER evaluation. - """ - self.clustering_embedding.prepare_cluster_embs_infer() - self.msdd_model.pairwise_infer = True - self.get_emb_clus_infer(self.clustering_embedding) - preds_list, targets_list, signal_lengths_list = self.run_pairwise_diarization() - thresholds = list(self._cfg.diarizer.msdd_model.parameters.sigmoid_threshold) - return [self.run_overlap_aware_eval(preds_list, threshold) for threshold in thresholds] - - def get_range_average( - self, signals: torch.Tensor, emb_vectors: torch.Tensor, diar_window_index: int, test_data_collection: List[Any] - ) -> Tuple[torch.Tensor, torch.Tensor, int]: - """ - This function is only used when `split_infer=True`. This module calculates cluster-average embeddings - for the given short range. The range length is set by `self.diar_window_length`, and each cluster-average - is only calculated for the specified range. Note that if the specified range does not contain some speakers - (e.g. the range contains speaker 1, 3) compared to the global speaker sets (e.g. speaker 1, 2, 3, 4) then - the missing speakers (e.g. speakers 2, 4) are assigned with zero-filled cluster-average speaker embedding. - - Args: - signals (Tensor): - Zero-padded Input multi-scale embedding sequences. - Shape: (length, scale_n, emb_vectors, emb_dim) - emb_vectors (Tensor): - Cluster-average multi-scale embedding vectors. - Shape: (length, scale_n, emb_vectors, emb_dim) - diar_window_index (int): - Index of split diarization wondows. - test_data_collection (collections.DiarizationLabelEntity) - Class instance that is containing session information such as targeted speaker indices, - audio filepath and RTTM filepath. - - Returns: - return emb_vectors_split (Tensor): - Cluster-average speaker embedding vectors for each scale. - emb_seq (Tensor): - Zero-padded multi-scale embedding sequences. - seq_len (int): - Length of the sequence determined by `self.diar_window_length` variable. - """ - emb_vectors_split = torch.zeros_like(emb_vectors) - uniq_id = os.path.splitext(os.path.basename(test_data_collection.audio_file))[0] - clus_label_tensor = torch.tensor([x[-1] for x in self.msdd_model.clus_test_label_dict[uniq_id]]) - for spk_idx in range(len(test_data_collection.target_spks)): - stt, end = ( - diar_window_index * self.diar_window_length, - min((diar_window_index + 1) * self.diar_window_length, clus_label_tensor.shape[0]), - ) - seq_len = end - stt - if stt < clus_label_tensor.shape[0]: - target_clus_label_tensor = clus_label_tensor[stt:end] - emb_seq, seg_length = ( - signals[stt:end, :, :], - min( - self.diar_window_length, - clus_label_tensor.shape[0] - diar_window_index * self.diar_window_length, - ), - ) - target_clus_label_bool = target_clus_label_tensor == test_data_collection.target_spks[spk_idx] - - # There are cases where there is no corresponding speaker in split range, - # so any(target_clus_label_bool) could be False. - if any(target_clus_label_bool): - emb_vectors_split[:, :, spk_idx] = torch.mean(emb_seq[target_clus_label_bool], dim=0) - - # In case when the loop reaches the end of the sequence - if seq_len < self.diar_window_length: - emb_seq = torch.cat( - [ - emb_seq, - torch.zeros(self.diar_window_length - seq_len, emb_seq.shape[1], emb_seq.shape[2]).to( - signals.device - ), - ], - dim=0, - ) - else: - emb_seq = torch.zeros(self.diar_window_length, emb_vectors.shape[0], emb_vectors.shape[1]).to( - signals.device - ) - seq_len = 0 - return emb_vectors_split, emb_seq, seq_len - - def get_range_clus_avg_emb( - self, test_batch: List[torch.Tensor], _test_data_collection: List[Any], device: torch.device('cpu') - ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: - """ - This function is only used when `get_range_average` function is called. This module calculates - cluster-average embeddings for the given short range. The range length is set by `self.diar_window_length`, - and each cluster-average is only calculated for the specified range. - - Args: - test_batch: (list) - List containing embedding sequences, length of embedding sequences, ground truth labels - (if exists) and initializing embedding vectors. - test_data_collection: (list) - List containing test-set dataloader contents. test_data_collection includes wav file path, - RTTM file path, clustered speaker indices. - - Returns: - sess_emb_vectors (Tensor): - Tensor of cluster-average speaker embedding vectors. - Shape: (batch_size, scale_n, emb_dim, 2*num_of_spks) - sess_emb_seq (Tensor): - Tensor of input multi-scale embedding sequences. - Shape: (batch_size, length, scale_n, emb_dim) - sess_sig_lengths (Tensor): - Tensor of the actucal sequence length without zero-padding. - Shape: (batch_size) - """ - _signals, signal_lengths, _targets, _emb_vectors = test_batch - sess_emb_vectors, sess_emb_seq, sess_sig_lengths = [], [], [] - split_count = torch.ceil(torch.tensor(_signals.shape[1] / self.diar_window_length)).int() - self.max_pred_length = max(self.max_pred_length, self.diar_window_length * split_count) - for k in range(_signals.shape[0]): - signals, emb_vectors, test_data_collection = _signals[k], _emb_vectors[k], _test_data_collection[k] - for diar_window_index in range(split_count): - emb_vectors_split, emb_seq, seq_len = self.get_range_average( - signals, emb_vectors, diar_window_index, test_data_collection - ) - sess_emb_vectors.append(emb_vectors_split) - sess_emb_seq.append(emb_seq) - sess_sig_lengths.append(seq_len) - sess_emb_vectors = torch.stack(sess_emb_vectors).to(device) - sess_emb_seq = torch.stack(sess_emb_seq).to(device) - sess_sig_lengths = torch.tensor(sess_sig_lengths).to(device) - return sess_emb_vectors, sess_emb_seq, sess_sig_lengths - - def diar_infer( - self, test_batch: List[torch.Tensor], test_data_collection: List[Any] - ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: - """ - Launch forward_infer() function by feeding the session-wise embedding sequences to get pairwise - speaker prediction values. If split_infer is True, the input audio clips are broken into short - sequences then cluster average embeddings are calculated for inference. Split-infer might result in - an improved results if calculating clustering average on the shorter tim-espan can help speaker assignment. - - Args: - test_batch: (list) - List containing embedding sequences, length of embedding sequences, ground truth labels (if exists) - and initializing embedding vectors. - test_data_collection: (list) - List containing test-set dataloader contents. test_data_collection includes wav file path, - RTTM file path, clustered speaker indices. - - Returns: - preds (Tensor): - Tensor containing predicted values which are generated from MSDD model. - targets (Tensor): - Tensor containing binary ground-truth values. - signal_lengths (Tensor): - The actual Session length (number of steps = number of base-scale segments) without zero padding. - """ - signals, signal_lengths, _targets, emb_vectors = test_batch - if self._cfg.diarizer.msdd_model.parameters.split_infer: - split_count = torch.ceil(torch.tensor(signals.shape[1] / self.diar_window_length)).int() - sess_emb_vectors, sess_emb_seq, sess_sig_lengths = self.get_range_clus_avg_emb( - test_batch, test_data_collection, device=self.msdd_model.device - ) - with autocast(): - _preds, scale_weights = self.msdd_model.forward_infer( - input_signal=sess_emb_seq, - input_signal_length=sess_sig_lengths, - emb_vectors=sess_emb_vectors, - targets=None, - ) - _preds = _preds.reshape(len(signal_lengths), split_count * self.diar_window_length, -1) - _preds = _preds[:, : signals.shape[1], :] - else: - with autocast(): - _preds, scale_weights = self.msdd_model.forward_infer( - input_signal=signals, input_signal_length=signal_lengths, emb_vectors=emb_vectors, targets=None - ) - self.max_pred_length = max(_preds.shape[1], self.max_pred_length) - preds = torch.zeros(_preds.shape[0], self.max_pred_length, _preds.shape[2]) - targets = torch.zeros(_preds.shape[0], self.max_pred_length, _preds.shape[2]) - preds[:, : _preds.shape[1], :] = _preds - return preds, targets, signal_lengths - - @torch.no_grad() - def run_pairwise_diarization(self) -> Tuple[List[torch.Tensor], List[torch.Tensor], List[torch.Tensor]]: - """ - Setup the parameters needed for batch inference and run batch inference. Note that each sample is - pairwise speaker input. The pairwise inference results are reconstructed to make session-wise - prediction results. - - Returns: - integrated_preds_list: (list) - List containing the session-wise speaker predictions in torch.tensor format. - targets_list: (list) - List containing the ground-truth labels in matrix format filled with 0 or 1. - signal_lengths_list: (list) - List containing the actual length of each sequence in session. - """ - self.out_rttm_dir = self.clustering_embedding.out_rttm_dir - self.msdd_model.setup_test_data(self.msdd_model.cfg.test_ds) - self.msdd_model.eval() - cumul_sample_count = [0] - preds_list, targets_list, signal_lengths_list = [], [], [] - uniq_id_list = get_uniq_id_list_from_manifest(self.msdd_model.cfg.test_ds.manifest_filepath) - test_data_collection = [d for d in self.msdd_model.data_collection] - for sidx, test_batch in enumerate(tqdm(self.msdd_model.test_dataloader())): - signals, signal_lengths, _targets, emb_vectors = test_batch - cumul_sample_count.append(cumul_sample_count[-1] + signal_lengths.shape[0]) - preds, targets, signal_lengths = self.diar_infer( - test_batch, test_data_collection[cumul_sample_count[-2] : cumul_sample_count[-1]] - ) - if self._cfg.diarizer.msdd_model.parameters.seq_eval_mode: - self.msdd_model._accuracy_test(preds, targets, signal_lengths) - - preds_list.extend(list(torch.split(preds, 1))) - targets_list.extend(list(torch.split(targets, 1))) - signal_lengths_list.extend(list(torch.split(signal_lengths, 1))) - - if self._cfg.diarizer.msdd_model.parameters.seq_eval_mode: - f1_score, simple_acc = self.msdd_model.compute_accuracies() - logging.info(f"Test Inference F1 score. {f1_score:.4f}, simple Acc. {simple_acc:.4f}") - integrated_preds_list = self.get_integrated_preds_list(uniq_id_list, test_data_collection, preds_list) - return integrated_preds_list, targets_list, signal_lengths_list - - def run_overlap_aware_eval( - self, preds_list: List[torch.Tensor], threshold: float - ) -> List[Optional[Tuple[DiarizationErrorRate, Dict]]]: - """ - Based on the predicted sigmoid values, render RTTM files then evaluate the overlap-aware diarization results. - - Args: - preds_list: (list) - List containing predicted pairwise speaker labels. - threshold: (float) - A floating-point threshold value that determines overlapped speech detection. - - If threshold is 1.0, no overlap speech is detected and only detect major speaker. - - If threshold is 0.0, all speakers are considered active at any time step. - """ - logging.info( - f" [Threshold: {threshold:.4f}] [use_clus_as_main={self.use_clus_as_main}] " - f"[diar_window={self.diar_window_length}]" - ) - outputs = [] - manifest_filepath = self.msdd_model.cfg.test_ds.manifest_filepath - rttm_map = audio_rttm_map(manifest_filepath) - for k, (collar, ignore_overlap) in enumerate(self.diar_eval_settings): - all_reference, all_hypothesis = make_rttm_with_overlap( - manifest_filepath, - self.msdd_model.clus_test_label_dict, - preds_list, - threshold=threshold, - infer_overlap=True, - use_clus_as_main=self.use_clus_as_main, - overlap_infer_spk_limit=self.overlap_infer_spk_limit, - use_adaptive_thres=self.use_adaptive_thres, - max_overlap_spks=self.max_overlap_spks, - out_rttm_dir=self.out_rttm_dir, - ) - output = score_labels( - rttm_map, - all_reference, - all_hypothesis, - collar=collar, - ignore_overlap=ignore_overlap, - verbose=self._cfg.verbose, - ) - outputs.append(output) - logging.info(f" \n") - return outputs - - @classmethod - def from_pretrained( - cls, - model_name: str, - vad_model_name: str = 'vad_multilingual_marblenet', - map_location: Optional[str] = None, - verbose: bool = False, - ): - """ - Instantiate a `NeuralDiarizer` to run Speaker Diarization. - - Args: - model_name (str): Path/Name of the neural diarization model to load. - vad_model_name (str): Path/Name of the voice activity detection (VAD) model to load. - map_location (str): Optional str to map the instantiated model to a device (cpu, cuda). - By default, (None), it will select a GPU if available, falling back to CPU otherwise. - verbose (bool): Enable verbose logging when loading models/running diarization. - Returns: - `NeuralDiarizer` - """ - logging.setLevel(logging.INFO if verbose else logging.WARNING) - cfg = NeuralDiarizerInferenceConfig.init_config( - diar_model_path=model_name, - vad_model_path=vad_model_name, - map_location=map_location, - verbose=verbose, - ) - return cls(cfg) - - def __call__( - self, - audio_filepath: str, - batch_size: int = 64, - num_workers: int = 1, - max_speakers: Optional[int] = None, - num_speakers: Optional[int] = None, - out_dir: Optional[str] = None, - verbose: bool = False, - ) -> Union[Annotation, List[Annotation]]: - """ - Run the `NeuralDiarizer` inference pipeline. - - Args: - audio_filepath (str, list): Audio path to run speaker diarization on. - max_speakers (int): If known, the max number of speakers in the file(s). - num_speakers (int): If known, the exact number of speakers in the file(s). - batch_size (int): Batch size when running inference. - num_workers (int): Number of workers to use in data-loading. - out_dir (str): Path to store intermediate files during inference (default temp directory). - Returns: - `pyannote.Annotation` for each audio path, containing speaker labels and segment timestamps. - """ - if out_dir: - os.makedirs(out_dir, exist_ok=True) - with tempfile.TemporaryDirectory(dir=out_dir) as tmpdir: - manifest_path = os.path.join(tmpdir, 'manifest.json') - meta = [ - { - 'audio_filepath': audio_filepath, - 'offset': 0, - 'duration': None, - 'label': 'infer', - 'text': '-', - 'num_speakers': num_speakers, - 'rttm_filepath': None, - 'uem_filepath': None, - } - ] - - with open(manifest_path, 'w') as f: - f.write('\n'.join(json.dumps(x) for x in meta)) - - self._initialize_configs( - manifest_path=manifest_path, - max_speakers=max_speakers, - num_speakers=num_speakers, - tmpdir=tmpdir, - batch_size=batch_size, - num_workers=num_workers, - verbose=verbose, - ) - - self.msdd_model.cfg.test_ds.manifest_filepath = manifest_path - self.diarize() - - pred_labels_clus = rttm_to_labels(f'{tmpdir}/pred_rttms/{Path(audio_filepath).stem}.rttm') - return labels_to_pyannote_object(pred_labels_clus) - - def _initialize_configs( - self, - manifest_path: str, - max_speakers: Optional[int], - num_speakers: Optional[int], - tmpdir: tempfile.TemporaryDirectory, - batch_size: int, - num_workers: int, - verbose: bool, - ) -> None: - self._cfg.batch_size = batch_size - self._cfg.num_workers = num_workers - self._cfg.diarizer.manifest_filepath = manifest_path - self._cfg.diarizer.out_dir = tmpdir - self._cfg.verbose = verbose - self._cfg.diarizer.clustering.parameters.oracle_num_speakers = num_speakers is not None - if max_speakers: - self._cfg.diarizer.clustering.parameters.max_num_speakers = max_speakers - self.transfer_diar_params_to_model_params(self.msdd_model, self._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. - """ - return EncDecDiarLabelModel.list_available_models() diff --git a/nemo/collections/asr/models/multitalker_asr_models.py b/nemo/collections/asr/models/multitalker_asr_models.py new file mode 100644 index 0000000000000000000000000000000000000000..66261fa2c561cdad64f4af3acf3bd53a681bb167 --- /dev/null +++ b/nemo/collections/asr/models/multitalker_asr_models.py @@ -0,0 +1,142 @@ +# 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/rnnt_bpe_models.py b/nemo/collections/asr/models/rnnt_bpe_models.py index cd8667f2f0fedb673a4eb8d4bd1569c9852e6942..779f03e3719de5c84b41c73a92beb217ab92bb6d 100644 --- a/nemo/collections/asr/models/rnnt_bpe_models.py +++ b/nemo/collections/asr/models/rnnt_bpe_models.py @@ -48,48 +48,6 @@ class EncDecRNNTBPEModel(EncDecRNNTModel, ASRBPEMixin): """ results = [] - model = PretrainedModelInfo( - pretrained_model_name="stt_en_contextnet_256", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_contextnet_256", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_contextnet_256/versions/1.6.0/files/stt_en_contextnet_256.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_contextnet_512", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_contextnet_512", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_contextnet_512/versions/1.6.0/files/stt_en_contextnet_512.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_contextnet_1024", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_contextnet_1024", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_contextnet_1024/versions/1.9.0/files/stt_en_contextnet_1024.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_contextnet_256_mls", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_contextnet_256_mls", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_contextnet_256_mls/versions/1.0.0/files/stt_en_contextnet_256_mls.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_contextnet_512_mls", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_contextnet_512_mls", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_contextnet_512_mls/versions/1.0.0/files/stt_en_contextnet_512_mls.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_en_contextnet_1024_mls", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_en_contextnet_1024_mls", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_en_contextnet_1024_mls/versions/1.0.0/files/stt_en_contextnet_1024_mls.nemo", - ) - results.append(model) - 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", @@ -132,27 +90,6 @@ class EncDecRNNTBPEModel(EncDecRNNTModel, ASRBPEMixin): ) results.append(model) - model = PretrainedModelInfo( - pretrained_model_name="stt_de_contextnet_1024", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_de_contextnet_1024", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_de_contextnet_1024/versions/1.4.0/files/stt_de_contextnet_1024.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_fr_contextnet_1024", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_fr_contextnet_1024", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_fr_contextnet_1024/versions/1.5/files/stt_fr_contextnet_1024.nemo", - ) - results.append(model) - - model = PretrainedModelInfo( - pretrained_model_name="stt_es_contextnet_1024", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_es_contextnet_1024", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_es_contextnet_1024/versions/1.8.0/files/stt_es_contextnet_1024.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", @@ -181,13 +118,6 @@ class EncDecRNNTBPEModel(EncDecRNNTModel, ASRBPEMixin): ) results.append(model) - model = PretrainedModelInfo( - pretrained_model_name="stt_enes_contextnet_large", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:stt_enes_contextnet_large", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/stt_enes_contextnet_large/versions/1.0.0/files/stt_enes_contextnet_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", @@ -380,7 +310,7 @@ class EncDecRNNTBPEModel(EncDecRNNTModel, ASRBPEMixin): ) if new_tokenizer_type.lower() not in ('bpe', 'wpe'): - raise ValueError(f'New tokenizer type must be either `bpe` or `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}) @@ -599,6 +529,7 @@ class EncDecRNNTBPEModel(EncDecRNNTModel, ASRBPEMixin): 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, diff --git a/nemo/collections/asr/models/rnnt_models.py b/nemo/collections/asr/models/rnnt_models.py index b26337b26cba6899ede64b407ea7edf88dd83273..ef116cf2d6b5408fb92bd36faf3f80f2b953010f 100644 --- a/nemo/collections/asr/models/rnnt_models.py +++ b/nemo/collections/asr/models/rnnt_models.py @@ -41,7 +41,7 @@ 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.transcribe_utils import process_timestamp_outputs +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 @@ -241,6 +241,7 @@ class EncDecRNNTModel(ASRModel, ASRModuleMixin, ExportableEncDecModel, ASRTransc 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, @@ -255,11 +256,13 @@ class EncDecRNNTModel(ASRModel, ASRModuleMixin, ExportableEncDecModel, ASRTransc 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 + 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 @@ -268,13 +271,13 @@ class EncDecRNNTModel(ASRModel, ASRModuleMixin, ExportableEncDecModel, ASRTransc 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. + 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. + 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. @@ -285,27 +288,35 @@ class EncDecRNNTModel(ASRModel, ASRModuleMixin, ExportableEncDecModel, ASRTransc * 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 - with open_dict(self.cfg.decoding): - self.cfg.decoding.compute_timestamps = True - self.cfg.decoding.preserve_alignments = True - self.change_decoding_strategy(self.cfg.decoding, verbose=False) + 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 - with open_dict(self.cfg.decoding): - self.cfg.decoding.compute_timestamps = False - self.cfg.decoding.preserve_alignments = 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, @@ -320,10 +331,10 @@ class EncDecRNNTModel(ASRModel, ASRModuleMixin, ExportableEncDecModel, ASRTransc 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, + 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: @@ -815,7 +826,7 @@ class EncDecRNNTModel(ASRModel, ASRModuleMixin, ExportableEncDecModel, ASRTransc del signal best_hyp_text = self.decoding.rnnt_decoder_predictions_tensor( - encoder_output=encoded, encoded_lengths=encoded_len, return_hypotheses=False + encoder_output=encoded, encoded_lengths=encoded_len, return_hypotheses=True ) if isinstance(sample_id, torch.Tensor): @@ -998,6 +1009,45 @@ class EncDecRNNTModel(ASRModel, ASRModuleMixin, ExportableEncDecModel, ASRTransc 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: diff --git a/nemo/collections/asr/models/slu_models.py b/nemo/collections/asr/models/slu_models.py deleted file mode 100644 index c599b7f4272a7870e0cc73080bcea0ea24ad47f9..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/models/slu_models.py +++ /dev/null @@ -1,630 +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 os -from math import ceil -from typing import Any, Dict, List, Optional, Union - -import torch -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_dali import DALIOutputs -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 ( - ASRBPEMixin, - ASRModuleMixin, - ASRTranscriptionMixin, - TranscribeConfig, - TranscriptionReturnType, -) -from nemo.collections.asr.parts.preprocessing.perturb import process_augmentations -from nemo.collections.asr.parts.submodules.ctc_decoding import CTCBPEDecoding, CTCBPEDecodingConfig -from nemo.collections.asr.parts.utils.slu_utils import SequenceGenerator, SequenceGeneratorConfig, get_seq_mask -from nemo.collections.common.losses import SmoothedNLLLoss -from nemo.core.classes.common import PretrainedModelInfo, typecheck -from nemo.core.neural_types import AudioSignal, LabelsType, LengthsType, LogprobsType, NeuralType, SpectrogramType -from nemo.utils import logging, model_utils - -__all__ = ["SLUIntentSlotBPEModel"] - - -class SLUIntentSlotBPEModel(ASRModel, ExportableEncDecModel, ASRModuleMixin, ASRBPEMixin, ASRTranscriptionMixin): - """Model for end-to-end speech intent classification and slot filling, which is formulated as a speech-to-sequence task""" - - 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) - - 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) - - self.preprocessor = self.from_config_dict(self.cfg.preprocessor) - self.encoder = self.from_config_dict(self.cfg.encoder) - self.decoder = self.from_config_dict(self.cfg.decoder) - - if hasattr(self._cfg, 'spec_augment') and self._cfg.spec_augment is not None: - self.spec_augmentation = self.from_config_dict(self._cfg.spec_augment) - else: - self.spec_augmentation = None - - # Setup optional Optimization flags - self.setup_optimization_flags() - - # Adapter modules setup (from ASRAdapterModelMixin) - self.setup_adapters() - - self.vocabulary = self.tokenizer.tokenizer.get_vocab() - vocab_size = len(self.vocabulary) - - # Create embedding layer - self.cfg.embedding["vocab_size"] = vocab_size - self.embedding = self.from_config_dict(self.cfg.embedding) - - # Create token classifier - self.cfg.classifier["num_classes"] = vocab_size - self.classifier = self.from_config_dict(self.cfg.classifier) - - self.loss = SmoothedNLLLoss(label_smoothing=self.cfg.loss.label_smoothing) - - self.sequence_generator = SequenceGenerator( - cfg=self.cfg.sequence_generator, - embedding=self.embedding, - decoder=self.decoder, - log_softmax=self.classifier, - tokenizer=self.tokenizer, - ) - - # 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), - fold_consecutive=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), - "target_semantics": NeuralType(('B', 'T'), input_signal_eltype, optional=True), - "target_semantics_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 { - "log_probs": NeuralType(('B', 'T', 'D'), LogprobsType(), optional=True), - "lengths": NeuralType(tuple('B'), LengthsType(), optional=True), - "greedy_predictions": NeuralType(('B', 'T'), LabelsType(), optional=True), - } - - def set_decoding_strategy(self, cfg: SequenceGeneratorConfig): - cfg.max_sequence_length = self.sequence_generator.generator.max_seq_length - self.sequence_generator = SequenceGenerator(cfg, self.embedding, self.decoder, self.classifier, self.tokenizer) - - @typecheck() - def forward( - self, - input_signal=None, - input_signal_length=None, - target_semantics=None, - target_semantics_length=None, - processed_signal=None, - processed_signal_length=None, - ): - """ - Forward pass of the model. - - Params: - 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. - - target_semantics: Tensor that represents a batch of semantic tokens, of shape [B, L]. - - target_semantics_length: Vector of length B, that contains the individual lengths of the semantic 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 output sequence after decoder, of shape [B]. - 3) The token predictions of the model of shape [B, T]. - """ - 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) - encoded = encoded.transpose(1, 2) # BxDxT -> BxTxD - encoded_mask = get_seq_mask(encoded, encoded_len) - - if target_semantics is None: # in inference-only mode - predictions = self.sequence_generator(encoded, encoded_mask) - return None, None, predictions - - bos_semantics_tokens = target_semantics[:, :-1] - bos_semantics = self.embedding(bos_semantics_tokens) - bos_semantics_mask = get_seq_mask(bos_semantics, target_semantics_length - 1) - - decoded = self.decoder( - encoder_states=encoded, - encoder_mask=encoded_mask, - decoder_states=bos_semantics, - decoder_mask=bos_semantics_mask, - ) - log_probs = self.classifier(decoded) - - predictions = log_probs.argmax(dim=-1, keepdim=False) - - pred_len = self.sequence_generator.get_seq_length(predictions) - return log_probs, pred_len, predictions - - # PTL-specific methods - def training_step(self, batch, batch_nb): - if len(batch) == 4: - signal, signal_len, semantics, semantics_len = batch - else: - signal, signal_len, semantics, semantics_len, sample_id = batch - - log_probs, pred_len, predictions = self.forward( - input_signal=signal, - input_signal_length=signal_len, - target_semantics=semantics, - target_semantics_length=semantics_len, - ) - - eos_semantics = semantics[:, 1:] - eos_semantics_len = semantics_len - 1 # subtract 1 for eos tokens - - loss_value = self.loss(log_probs=log_probs, labels=eos_semantics, lengths=eos_semantics_len) - - tensorboard_logs = {'train_loss': loss_value.item()} - if len(self._optimizer.param_groups) == 1: - tensorboard_logs['learning_rate'] = self._optimizer.param_groups[0]['lr'] - else: - for i, group in enumerate(self._optimizer.param_groups): - tensorboard_logs[f'learning_rate_g{i}'] = group['lr'] - - 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 - - if (batch_nb + 1) % log_every_n_steps == 0: - self.wer.update( - predictions=predictions, - targets=eos_semantics, - predictions_lengths=pred_len, - targets_lengths=eos_semantics_len, - ) - wer, _, _ = self.wer.compute() - self.wer.reset() - tensorboard_logs.update({'training_batch_wer': wer}) - - return {'loss': loss_value, 'log': tensorboard_logs} - - def predict( - self, input_signal, input_signal_length, processed_signal=None, processed_signal_length=None, dataloader_idx=0 - ) -> List[str]: - 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) - encoded = encoded.transpose(1, 2) # BxDxT -> BxTxD - encoded_mask = get_seq_mask(encoded, encoded_len) - - pred_tokens = self.sequence_generator(encoded, encoded_mask) - predictions = self.sequence_generator.decode_semantics_from_tokens(pred_tokens) - return predictions - - def validation_pass(self, batch, batch_idx, dataloader_idx=0): - if len(batch) == 4: - signal, signal_len, semantics, semantics_len = batch - else: - signal, signal_len, semantics, semantics_len, sample_id = batch - - if isinstance(batch, DALIOutputs) and batch.has_processed_signal: - log_probs, pred_len, predictions = self.forward( - processed_signal=signal, - processed_signal_length=signal_len, - target_semantics=semantics, - target_semantics_length=semantics_len, - ) - else: - log_probs, pred_len, predictions = self.forward( - input_signal=signal, - input_signal_length=signal_len, - target_semantics=semantics, - target_semantics_length=semantics_len, - ) - - eos_semantics = semantics[:, 1:] - eos_semantics_len = semantics_len - 1 # subtract 1 for bos&eos tokens - - loss_value = self.loss(log_probs=log_probs, labels=eos_semantics, lengths=eos_semantics_len) - - self.wer.update( - predictions=predictions, - targets=eos_semantics, - predictions_lengths=pred_len, - targets_lengths=eos_semantics_len, - ) - wer, wer_num, wer_denom = self.wer.compute() - self.wer.reset() - - return { - 'val_loss': loss_value, - 'val_wer_num': wer_num, - 'val_wer_denom': wer_denom, - 'val_wer': wer, - } - - 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 test_dataloader(self): - if self._test_dl is None: - # None dataloader no longer supported in PTL2.0 - self._test_dl = [] - - return self._test_dl - - def _setup_dataloader_from_config(self, config: Optional[Dict]): - if 'augmentor' in config: - augmentor = process_augmentations(config['augmentor']) - else: - augmentor = None - - 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_bpe_dataset( - config=config, - tokenizer=self.tokenizer, - 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, - tokenizer=self.tokenizer, - 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_bpe_dataset( - config=config, tokenizer=self.tokenizer, 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) - - 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) - - 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, - 'batch_size': batch_size, - 'shuffle': False, - 'num_workers': config.get('num_workers', min(batch_size, os.cpu_count() - 1)), - 'pin_memory': True, - 'use_start_end_token': self.cfg.validation_ds.get('use_start_end_token', 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, - return_hypotheses: bool = False, - num_workers: int = 0, - verbose: bool = True, - ) -> TranscriptionReturnType: - """ - Uses greedy decoding to transcribe audio files into SLU semantics. - 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 - 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, - verbose=verbose, - ) - - """ Transcription related methods """ - - def _transcribe_forward(self, batch: Any, trcfg: TranscribeConfig): - predictions = self.predict(input_signal=batch[0], input_signal_length=batch[1]) - output = {'predictions': predictions} - return output - - def _transcribe_output_processing(self, outputs, trcfg: TranscribeConfig) -> List[str]: - hypotheses = outputs.pop('predictions') - return hypotheses - - @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="slu_conformer_transformer_large_slurp", - description="For details about this model, please visit https://ngc.nvidia.com/catalog/models/nvidia:nemo:slu_conformer_transformer_large_slurp", - location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/slu_conformer_transformer_large_slurp/versions/1.13.0/files/slu_conformer_transformer_large_slurp.nemo", - ) - results.append(model) - - @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 index bf773f1e00062dd54223e5cccadff78b4676b0c0..0f9d2c0a32f6f5d86fdfef6a083be488385b8bbc 100644 --- a/nemo/collections/asr/models/sortformer_diar_models.py +++ b/nemo/collections/asr/models/sortformer_diar_models.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -12,7 +12,9 @@ # 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 @@ -20,6 +22,7 @@ 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 @@ -31,7 +34,7 @@ from nemo.collections.asr.data.audio_to_diar_label_lhotse import LhotseAudioToSp 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 WaveformFeaturizer +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 @@ -61,12 +64,35 @@ class SortformerEncLabelModel(ModelPT, ExportableEncDecModel, SpkDiarizationMixi @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. + 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): @@ -108,15 +134,38 @@ class SortformerEncLabelModel(ModelPT, ExportableEncDecModel, SpkDiarizationMixi self.sortformer_modules.encoder_proj = None self._init_loss_weights() - self.eps = 1e-3 + 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) @@ -158,6 +207,17 @@ class SortformerEncLabelModel(ModelPT, ExportableEncDecModel, SpkDiarizationMixi 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}") @@ -176,6 +236,7 @@ class SortformerEncLabelModel(ModelPT, ExportableEncDecModel, SpkDiarizationMixi 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, @@ -235,22 +296,28 @@ class SortformerEncLabelModel(ModelPT, ExportableEncDecModel, SpkDiarizationMixi } ) - def frontend_encoder(self, processed_signal, processed_signal_length): + 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 + 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 + 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) + 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) @@ -261,14 +328,14 @@ class SortformerEncLabelModel(ModelPT, ExportableEncDecModel, SpkDiarizationMixi The main forward pass for diarization for offline diarization inference. Args: - emb_seq (torch.Tensor): tensor containing FastConformer encoder states (embedding vectors). - Dimension: (batch_size, diar_frame_count, emb_dim) - emb_seq_length (torch.Tensor): tensor containing lengths of FastConformer encoder states. - Dimension: (batch_size,) + 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. - Dimension: (batch_size, diar_frame_count, num_speakers) + 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) @@ -317,7 +384,6 @@ class SortformerEncLabelModel(ModelPT, ExportableEncDecModel, SpkDiarizationMixi 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 @@ -379,10 +445,58 @@ class SortformerEncLabelModel(ModelPT, ExportableEncDecModel, SpkDiarizationMixi '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. @@ -399,18 +513,28 @@ class SortformerEncLabelModel(ModelPT, ExportableEncDecModel, SpkDiarizationMixi Shape: (batch_size,) Returns: - tuple: A tuple containing: - - 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,) + 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) - audio_signal = (1 / (audio_signal.max() + self.eps)) * audio_signal - processed_signal, processed_signal_length = self.preprocessor( - input_signal=audio_signal, length=audio_signal_length - ) - if not self.training: + 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 @@ -423,21 +547,21 @@ class SortformerEncLabelModel(ModelPT, ExportableEncDecModel, SpkDiarizationMixi Forward pass for training and inference. Args: - audio_signal (torch.Tensor): tensor containing audio waveform - Dimension: (batch_size, num_samples) - audio_signal_length (torch.Tensor): tensor containing lengths of audio waveforms - Dimension: (batch_size,) + 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 - Dimension: (batch_size, diar_frame_count, num_speakers) + 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._cfg.get("streaming_mode", False): - raise NotImplementedError("Streaming mode is not implemented yet.") + 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 @@ -445,6 +569,272 @@ class SortformerEncLabelModel(ModelPT, ExportableEncDecModel, SpkDiarizationMixi 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. @@ -464,6 +854,14 @@ class SortformerEncLabelModel(ModelPT, ExportableEncDecModel, SpkDiarizationMixi 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) @@ -529,6 +927,14 @@ class SortformerEncLabelModel(ModelPT, ExportableEncDecModel, SpkDiarizationMixi 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) @@ -589,6 +995,29 @@ class SortformerEncLabelModel(ModelPT, ExportableEncDecModel, SpkDiarizationMixi 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}") @@ -630,6 +1059,14 @@ class SortformerEncLabelModel(ModelPT, ExportableEncDecModel, SpkDiarizationMixi 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) @@ -697,6 +1134,7 @@ class SortformerEncLabelModel(ModelPT, ExportableEncDecModel, SpkDiarizationMixi 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, @@ -718,13 +1156,14 @@ class SortformerEncLabelModel(ModelPT, ExportableEncDecModel, SpkDiarizationMixi 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. + 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, diff --git a/nemo/collections/asr/models/ssl_models.py b/nemo/collections/asr/models/ssl_models.py index d02be3f9fa4e94b40c17dfded4a0b3689ad629f4..6e149c3c17b82d19ed781864262b805c0e99e0ae 100644 --- a/nemo/collections/asr/models/ssl_models.py +++ b/nemo/collections/asr/models/ssl_models.py @@ -633,6 +633,7 @@ class EncDecMaskedTokenPredModel(SpeechEncDecSelfSupervisedModel): 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 @@ -653,6 +654,20 @@ class EncDecMaskedTokenPredModel(SpeechEncDecSelfSupervisedModel): 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'): @@ -664,8 +679,6 @@ class EncDecMaskedTokenPredModel(SpeechEncDecSelfSupervisedModel): "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), "apply_mask": NeuralType(optional=True), } @@ -729,8 +742,8 @@ class EncDecMaskedTokenPredModel(SpeechEncDecSelfSupervisedModel): return log_probs, encoded_len, masks, tokens - def training_step(self, batch, batch_idx): - input_signal, input_signal_length, _, _ = batch + 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 @@ -750,8 +763,8 @@ class EncDecMaskedTokenPredModel(SpeechEncDecSelfSupervisedModel): return {'loss': loss_value, 'log': tensorboard_logs} - def inference_pass(self, batch, batch_idx, dataloader_idx=0, mode='val', apply_mask=False): - input_signal, input_signal_length, _, _ = batch + 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 @@ -765,7 +778,7 @@ class EncDecMaskedTokenPredModel(SpeechEncDecSelfSupervisedModel): return {f'{mode}_loss': loss_value} - def validation_step(self, batch, batch_idx, dataloader_idx=0): + 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) @@ -773,7 +786,7 @@ class EncDecMaskedTokenPredModel(SpeechEncDecSelfSupervisedModel): self.validation_step_outputs.append(metrics) return metrics - def test_step(self, batch, batch_idx, dataloader_idx=0): + 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) @@ -815,6 +828,24 @@ class EncDecDenoiseMaskedTokenPredModel(EncDecMaskedTokenPredModel): 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) diff --git a/nemo/collections/asr/modules/__init__.py b/nemo/collections/asr/modules/__init__.py index 14abdd0d2776e2a692cdb8eb97c928582464b3d5..7259d077809eb2fb4841cbae5c732080e5a102fb 100644 --- a/nemo/collections/asr/modules/__init__.py +++ b/nemo/collections/asr/modules/__init__.py @@ -12,16 +12,20 @@ # See the License for the specific language governing permissions and # limitations under the License. -from nemo.collections.asr.modules.audio_preprocessing import ( +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 -from nemo.collections.asr.modules.conformer_encoder import ConformerEncoder, ConformerEncoderAdapter -from nemo.collections.asr.modules.conv_asr import ( +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, @@ -31,24 +35,52 @@ from nemo.collections.asr.modules.conv_asr import ( ParallelConvASREncoder, SpeakerDecoder, ) -from nemo.collections.asr.modules.graph_decoder import ViterbiDecoderWithGraph -from nemo.collections.asr.modules.hybrid_autoregressive_transducer import HATJoint -from nemo.collections.asr.modules.lstm_decoder import LSTMDecoder -from nemo.collections.asr.modules.msdd_diarizer import MSDD_module -from nemo.collections.asr.modules.rnn_encoder import RNNEncoder -from nemo.collections.asr.modules.rnnt import ( +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.squeezeformer_encoder import SqueezeformerEncoder, SqueezeformerEncoderAdapter from nemo.collections.asr.modules.ssl_modules import ( - ConformerMultiLayerFeatureExtractor, 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 index f567e3f5c8ffad5396b2d03842c7f339c888a46f..a621c8db83c7634fbd83e078ac62f05b10010959 100644 --- a/nemo/collections/asr/modules/audio_preprocessing.py +++ b/nemo/collections/asr/modules/audio_preprocessing.py @@ -19,11 +19,10 @@ from dataclasses import dataclass from typing import Any, Optional import torch -from packaging import version -from nemo.collections.asr.parts.numba.spec_augment import SpecAugmentNumba, spec_augment_launch_heuristics -from nemo.collections.asr.parts.preprocessing.features import FilterbankFeatures, FilterbankFeaturesTA +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, @@ -33,21 +32,11 @@ from nemo.core.neural_types import ( NeuralType, SpectrogramType, ) -from nemo.core.utils import numba_utils -from nemo.core.utils.numba_utils import __NUMBA_MINIMUM_VERSION__ +from nemo.core.utils.optional_libs import NUMBA_CUDA_AVAILABLE from nemo.utils import logging, logging_mode -try: - import torchaudio - import torchaudio.functional - import torchaudio.transforms - - TORCHAUDIO_VERSION = version.parse(torchaudio.__version__) - TORCHAUDIO_VERSION_MIN = version.parse('0.5') - - HAVE_TORCHAUDIO = True -except ModuleNotFoundError: - HAVE_TORCHAUDIO = False +if NUMBA_CUDA_AVAILABLE: + from nemo.collections.asr.parts.numba.spec_augment import SpecAugmentNumba, spec_augment_launch_heuristics __all__ = [ 'AudioToMelSpectrogramPreprocessor', @@ -171,7 +160,6 @@ class AudioToMelSpectrogramPreprocessor(AudioPreprocessor, Exportable): Defaults to 0.0 nb_max_freq (int) : Frequency above which all frequencies will be masked for narrowband augmentation. Defaults to 4000 - use_torchaudio: Whether to use the `torchaudio` implementation. mel_norm: Normalization used for mel filterbank weights. Defaults to 'slaney' (area normalization) stft_exact_pad: Deprecated argument, kept for compatibility with older checkpoints. @@ -237,13 +225,11 @@ class AudioToMelSpectrogramPreprocessor(AudioPreprocessor, Exportable): rng=None, nb_augmentation_prob=0.0, nb_max_freq=4000, - use_torchaudio: bool = False, 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 ): - super().__init__(n_window_size, n_window_stride) - 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.") @@ -255,13 +241,10 @@ class AudioToMelSpectrogramPreprocessor(AudioPreprocessor, Exportable): 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 - if not use_torchaudio: - featurizer_class = FilterbankFeatures - else: - featurizer_class = FilterbankFeaturesTA - self.featurizer = featurizer_class( + self.featurizer = FilterbankFeatures( sample_rate=self._sample_rate, n_window_size=n_window_size, n_window_stride=n_window_stride, @@ -290,11 +273,11 @@ class AudioToMelSpectrogramPreprocessor(AudioPreprocessor, Exportable): ) def input_example(self, max_batch: int = 8, max_dim: int = 32000, min_length: int = 200): - batch_size = torch.randint(low=1, high=max_batch, size=[1]).item() - max_length = torch.randint(low=min_length, high=max_dim, size=[1]).item() - signals = torch.rand(size=[batch_size, max_length]) * 2 - 1 - lengths = torch.randint(low=min_length, high=max_dim, size=[batch_size]) - lengths[0] = max_length + 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): @@ -307,7 +290,6 @@ class AudioToMelSpectrogramPreprocessor(AudioPreprocessor, Exportable): class AudioToMFCCPreprocessor(AudioPreprocessor): """Preprocessor that converts wavs to MFCCs. - Uses torchaudio.transforms.MFCC. Args: sample_rate: The sample rate of the audio. @@ -383,14 +365,6 @@ class AudioToMFCCPreprocessor(AudioPreprocessor): log=True, ): self._sample_rate = sample_rate - if not HAVE_TORCHAUDIO: - logging.error('Could not import torchaudio. Some features might not work.') - - raise ModuleNotFoundError( - "torchaudio is not installed but is necessary for " - "AudioToMFCCPreprocessor. We recommend you try " - "building it from source for the PyTorch version you have." - ) 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: @@ -426,7 +400,7 @@ class AudioToMFCCPreprocessor(AudioPreprocessor): mel_kwargs['window_fn'] = window_fn # Use torchaudio's implementation of MFCCs as featurizer - self.featurizer = torchaudio.transforms.MFCC( + self.featurizer = MFCC( sample_rate=self._sample_rate, n_mfcc=n_mfcc, dct_type=dct_type, @@ -528,7 +502,7 @@ class SpectrogramAugmentation(NeuralModule): 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_utils.numba_cuda_is_supported(__NUMBA_MINIMUM_VERSION__): + 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, @@ -747,8 +721,8 @@ class AudioToMelSpectrogramPreprocessorConfig: rng: Optional[str] = None nb_augmentation_prob: float = 0.0 nb_max_freq: int = 4000 - use_torchaudio: bool = False 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. diff --git a/nemo/collections/asr/modules/conformer_encoder.py b/nemo/collections/asr/modules/conformer_encoder.py index e6b415eab5ae90d740c09dc3c9671d65601fe69e..e56f5772306268926dd52de7725bf6470411a89e 100644 --- a/nemo/collections/asr/modules/conformer_encoder.py +++ b/nemo/collections/asr/modules/conformer_encoder.py @@ -20,8 +20,8 @@ from typing import List, Optional, Set, Tuple import torch import torch.distributed -import torch.nn as nn 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 @@ -46,10 +46,17 @@ 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, ChannelType, LengthsType, NeuralType, SpectrogramType +from nemo.core.neural_types import ( + AcousticEncodedRepresentation, + BoolType, + ChannelType, + LengthsType, + NeuralType, + SpectrogramType, +) from nemo.utils import logging -__all__ = ['ConformerEncoder'] +__all__ = ['ConformerEncoder', 'ConformerMultiLayerFeatureExtractor'] class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): @@ -65,7 +72,8 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): 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'] + 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. @@ -81,15 +89,13 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): Defaults to 1. ff_expansion_factor (int): the expansion factor in feed forward layers Defaults to 4. - self_attention_model (str): type of the attention layer and positional encoding + 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 @@ -98,14 +104,20 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): 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. + 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'. + att_chunk_context_size (List[List[int]]): specifies the context sizes for unified (offline/streaming) ASR training. + It defines the range of Left, Middle, and Right context sizes for the attention mechanism. + At each streaming step, the context size is sampled from the range of Left, Middle, and Right context sizes. + Example: att_chunk_context_size=[[70],[1,2,7,13],[0,1,3,7,13]] -> sampling -> [70, 2, 3] -> attention mask generation + att_context_style (str): 'regular', 'chunked_limited', or 'chunked_limited_with_rc'. Defaults to 'regular' - xscaling (bool): enables scaling the inputs to the multi-headed attention layers by sqrt(d_model) + 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. @@ -113,12 +125,19 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): 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]. + 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. + conv_context_style (str): 'regular' or 'dcc' + DCC - Dynamic Chunked Convolution that is used for unified ASR training. + Defaults to 'regular'. + 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. @@ -149,13 +168,19 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): 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 + 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): @@ -210,6 +235,7 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): "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), } ) @@ -223,6 +249,7 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): "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), } ) @@ -285,6 +312,7 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): n_heads=4, att_context_size=None, att_context_probs=None, + att_chunk_context_size=None, att_context_style='regular', xscaling=True, untie_biases=True, @@ -292,6 +320,7 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): conv_kernel_size=31, conv_norm_type='batch_norm', conv_context_size=None, + conv_context_style='regular', use_bias=True, dropout=0.1, dropout_pre_encoder=0.1, @@ -326,6 +355,22 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): self.use_pytorch_sdpa_backends = use_pytorch_sdpa_backends self.sync_max_audio_length = sync_max_audio_length + assert conv_context_style in ["regular", "dcc"], f"Invalid conv_context_style: {conv_context_style}!" + self.conv_context_style = conv_context_style + self.conv_kernel_size = conv_kernel_size + + # Setting up the att_chunk_context_size + if att_chunk_context_size is not None: + assert ( + att_context_style == "chunked_limited_with_rc" + ), "att_chunk_context_size is only supported for chunked_limited_with_rc attention style!" + assert ( + len(att_chunk_context_size) == 3 + ), "att_chunk_context_size must have 3 elements: [left_context, chunk_size, right_context]" + self.att_chunk_context_size = att_chunk_context_size + else: + self.att_chunk_context_size = None + # Setting up the att_context_size ( self.att_context_size_all, @@ -472,6 +517,9 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): 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) @@ -498,6 +546,13 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): ) 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 @@ -517,20 +572,67 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): @typecheck() def forward( - self, audio_signal, length, cache_last_channel=None, cache_last_time=None, cache_last_channel_len=None + self, + audio_signal, + length, + cache_last_channel=None, + cache_last_time=None, + cache_last_channel_len=None, + bypass_pre_encode=False, ): - self.update_max_seq_length(seq_length=audio_signal.size(2), device=audio_signal.device) + """ + 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 + 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 @@ -543,20 +645,21 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): else: cur_att_context_size = self.att_context_size - audio_signal = torch.transpose(audio_signal, 1, 2) + 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 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!") + 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: @@ -638,7 +741,6 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): 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: @@ -677,6 +779,13 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): 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) @@ -693,6 +802,9 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): """ 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 @@ -728,6 +840,33 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): torch.le(diff_chunks, left_chunks_num), torch.ge(diff_chunks, 0) ) att_mask = torch.logical_and(att_mask, chunked_limited_mask.unsqueeze(0)) + elif self.att_context_style == "chunked_limited_with_rc" and sum(att_context_size) != -3: + assert ( + len(att_context_size) == 3 + ), "att_context_size must have 3 elements: [left_context, chunk_size, right_context]" + + left_context_frames = att_context_size[0] + chunk_size_frames = att_context_size[1] + right_context_frames = att_context_size[2] + assert chunk_size_frames >= 1, "chunk_size_frames must be greater than 0!" + # Calculate chunk index for each frame (which processing group it belongs to) + frame_idx = torch.arange(0, max_audio_length, dtype=torch.int, device=att_mask.device) + chunk_idx = torch.div(frame_idx, chunk_size_frames, rounding_mode="trunc") + + window_start = chunk_idx * chunk_size_frames - left_context_frames + window_start = torch.maximum(window_start, torch.zeros_like(window_start)) + window_end = chunk_idx * chunk_size_frames + chunk_size_frames - 1 + right_context_frames + + window_end = torch.minimum(window_end, torch.full_like(window_end, max_audio_length - 1)) + # Create the mask: frame i can see frame j if window_start[i] <= j <= window_end[i] + j_indices = frame_idx.unsqueeze(0) # [1, T] + window_start_expanded = window_start.unsqueeze(1) # [T, 1] + window_end_expanded = window_end.unsqueeze(1) # [T, 1] + + chunked_limited_mask = torch.logical_and( + j_indices >= window_start_expanded, j_indices <= window_end_expanded + ) + att_mask = torch.logical_and(att_mask, chunked_limited_mask.unsqueeze(0)) else: att_mask = None @@ -756,6 +895,12 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): 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 @@ -782,6 +927,9 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): else: att_context_size_all = [[-1, -1]] + if att_context_style == "chunked_limited_with_rc": + att_context_size_all = [[-1, -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.") @@ -798,7 +946,7 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): conv_context_size = list(conv_context_size) if not isinstance(conv_context_size, list) and not isinstance(conv_context_size, str): raise ValueError( - f"Invalid conv_context_size! It should be the string 'causal' or a list of two integers." + "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] @@ -810,9 +958,16 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): 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 look-aheads: {self.att_context_size_all}" + 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 @@ -828,15 +983,17 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): max_context: int = 10000, ): """ - This function sets the needed values and parameters to perform streaming. The configuration would be stored in self.streaming_cfg. + 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) + 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() @@ -852,6 +1009,9 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): elif self.att_context_style == "chunked_limited": lookahead_steps = att_context_size[1] streaming_cfg.cache_drop_size = 0 + elif self.att_context_style == "chunked_limited_with_rc": + lookahead_steps = att_context_size[2] * self.n_layers + self.conv_context_size[1] * self.n_layers + 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 @@ -863,8 +1023,14 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): 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: - raise ValueError("left_chunks can not be None when chunk_size is set.") - streaming_cfg.last_channel_cache_size = left_chunks * chunk_size + 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() @@ -1036,7 +1202,7 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): self.att_context_size = att_context_size self.set_max_audio_length(self.pos_emb_max_len) - for name, m in self.named_modules(): + for _, m in self.named_modules(): if type(m) == ConformerLayer: if self_attention_model == 'rel_pos': new_attn = RelPositionMultiHeadAttention( @@ -1108,6 +1274,7 @@ class ConformerEncoder(NeuralModule, StreamingEncoder, Exportable, AccessMixin): 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): @@ -1156,23 +1323,41 @@ 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. + 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: List[int], - aggregator: NeuralModule = None, + 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.layer_idx_list = [int(l) for l in layer_idx_list] - for x in self.layer_idx_list: - if x < 0 or x >= len(encoder.layers): - raise ValueError(f"layer index {x} out of range [0, {len(encoder.layers)})") + 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, @@ -1185,6 +1370,13 @@ class ConformerMultiLayerFeatureExtractor(NeuralModule, Exportable, AccessMixin) 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)) @@ -1197,7 +1389,7 @@ class ConformerMultiLayerFeatureExtractor(NeuralModule, Exportable, AccessMixin) cache_last_channel_len=cache_last_channel_len, ) - ### chunk of code adapted from ConformerEncoder.forward_internal() + # 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: @@ -1213,7 +1405,8 @@ class ConformerMultiLayerFeatureExtractor(NeuralModule, Exportable, AccessMixin) 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." + 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") @@ -1222,29 +1415,31 @@ class ConformerMultiLayerFeatureExtractor(NeuralModule, Exportable, AccessMixin) self.encoder.reset_registry() self.set_access_enabled(access_enabled=old_access_flag, guid=getattr(self, "model_guid", None)) - ### end of adapted chunk + # End of the adapted chunk if self.aggregator is not None: - return self.aggregator(encoded_list, encoded_len_list) # Tensor[B,D*L,T], Tensor[B] + 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 -""" +# 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 + """ + 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 diff --git a/nemo/collections/asr/modules/conv_asr.py b/nemo/collections/asr/modules/conv_asr.py index e48d76a9b7a357466ed240adbf5c17b785443abe..b5fdac06b07d3af099958511e59d89c4d339902e 100644 --- a/nemo/collections/asr/modules/conv_asr.py +++ b/nemo/collections/asr/modules/conv_asr.py @@ -242,7 +242,7 @@ class ConvASREncoder(NeuralModule, Exportable, AccessMixin): class ParallelConvASREncoder(NeuralModule, Exportable): """ - Convolutional encoder for ASR models with parallel blocks. CarneliNet can be implemented with this class. + Convolutional encoder for ASR models with parallel blocks. """ def _prepare_for_export(self): @@ -421,13 +421,11 @@ class ConvASRDecoder(NeuralModule, Exportable, adapter_mixins.AdapterModuleMixin 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): + 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( - f"Neither of the vocabulary and num_classes are set! At least one of them need to be set." - ) + 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) @@ -442,7 +440,7 @@ class ConvASRDecoder(NeuralModule, Exportable, adapter_mixins.AdapterModuleMixin self.__vocabulary = vocabulary self._feat_in = feat_in # Add 1 for blank char - self._num_classes = num_classes + 1 + 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) @@ -880,11 +878,11 @@ class SpeakerDecoder(NeuralModule, Exportable): @typecheck() def forward(self, encoder_output, length=None): pool = self._pooling(encoder_output, length) - embs = [] for layer in self.emb_layers: - pool, emb = layer(pool), layer[: self.emb_id](pool) - embs.append(emb) + last_pool = pool + pool = layer(pool) + emb = layer[: self.emb_id](last_pool) pool = pool.squeeze(-1) if self.angular: @@ -894,7 +892,7 @@ class SpeakerDecoder(NeuralModule, Exportable): out = self.final(pool) - return out, embs[-1].squeeze(-1) + return out, emb.squeeze(-1) class ConvASREncoderAdapter(ConvASREncoder, adapter_mixins.AdapterModuleMixin): diff --git a/nemo/collections/asr/modules/graph_decoder.py b/nemo/collections/asr/modules/graph_decoder.py deleted file mode 100644 index d66dbd734a69b8a1668e55d3ebf842c144e0a7d7..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/graph_decoder.py +++ /dev/null @@ -1,214 +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 - -import torch -from omegaconf import DictConfig - -from nemo.core.classes import NeuralModule -from nemo.core.neural_types import LengthsType, LogprobsType, NeuralType, PredictionsType - - -class ViterbiDecoderWithGraph(NeuralModule): - """Viterbi Decoder with WFSA (Weighted Finite State Automaton) graphs. - - Note: - Requires k2 v1.14 or later to be installed to use this module. - - Decoder can be set up via the config, and optionally be passed keyword arguments as follows. - - Examples: - .. code-block:: yaml - - model: # Model config - ... - graph_module_cfg: # Config for graph modules, e.g. ViterbiDecoderWithGraph - split_batch_size: 0 - backend_cfg: - topo_type: "default" # other options: "compact", "shared_blank", "minimal" - topo_with_self_loops: true - token_lm: # must be provided for criterion_type: "map" - - Args: - num_classes: Number of target classes for the decoder network to predict. - (Excluding the blank token). - - backend: Which backend to use for decoding. Currently only `k2` is supported. - - dec_type: Type of decoding graph to use. Choices: `topo` and `token_lm`, - with `topo` standing for the loss topology graph only - and `token_lm` for the topology composed with a token_lm graph. - - return_type: Type of output. Choices: `1best` and `lattice`. - `1best` is represented as a list of 1D tensors. - `lattice` can be of type corresponding to the backend (e.g. k2.Fsa). - - return_ilabels: For return_type=`1best`. - Whether to return input labels of a lattice (otherwise output labels). - - output_aligned: For return_type=`1best`. - Whether the tensors length will correspond to log_probs_length - and the labels will be aligned to the frames of emission - (otherwise there will be only the necessary labels). - - split_batch_size: Local batch size. Used for memory consumption reduction at the cost of speed performance. - Effective if complies 0 < split_batch_size < batch_size. - - graph_module_cfg: Optional Dict of (str, value) pairs that are passed to the backend graph decoder. - """ - - @property - def input_types(self): - """Returns definitions of module input ports. - """ - return { - "log_probs": NeuralType(("B", "T", "D") if self._3d_input else ("B", "T", "T", "D"), LogprobsType()), - "input_lengths": NeuralType(tuple("B"), LengthsType()), - } - - @property - def output_types(self): - """Returns definitions of module output ports. - """ - return {"predictions": NeuralType(("B", "T"), PredictionsType())} - - def __init__( - self, - num_classes, - backend: str = "k2", - dec_type: str = "topo", - return_type: str = "1best", - return_ilabels: bool = True, - output_aligned: bool = True, - split_batch_size: int = 0, - graph_module_cfg: Optional[DictConfig] = None, - ): - self._blank = num_classes - self.return_ilabels = return_ilabels - self.output_aligned = output_aligned - self.split_batch_size = split_batch_size - self.dec_type = dec_type - - if return_type == "1best": - self.return_lattices = False - elif return_type == "lattice": - self.return_lattices = True - elif return_type == "nbest": - raise NotImplementedError(f"return_type {return_type} is not supported at the moment") - else: - raise ValueError(f"Unsupported return_type: {return_type}") - - # we assume that self._blank + 1 == num_classes - if backend == "k2": - if self.dec_type == "topo": - from nemo.collections.asr.parts.k2.graph_decoders import CtcDecoder as Decoder - elif self.dec_type == "topo_rnnt_ali": - from nemo.collections.asr.parts.k2.graph_decoders import RnntAligner as Decoder - elif self.dec_type == "token_lm": - from nemo.collections.asr.parts.k2.graph_decoders import TokenLMDecoder as Decoder - elif self.dec_type == "loose_ali": - raise NotImplementedError() - elif self.dec_type == "tlg": - raise NotImplementedError(f"dec_type {self.dec_type} is not supported at the moment") - else: - raise ValueError(f"Unsupported dec_type: {self.dec_type}") - - self._decoder = Decoder(num_classes=self._blank + 1, blank=self._blank, cfg=graph_module_cfg) - elif backend == "gtn": - raise NotImplementedError("gtn-backed decoding is not implemented") - - self._3d_input = self.dec_type != "topo_rnnt" - super().__init__() - - def update_graph(self, graph): - """Updates graph of the backend graph decoder. - """ - self._decoder.update_graph(graph) - - def _forward_impl(self, log_probs, log_probs_length, targets=None, target_length=None): - if targets is None and target_length is not None or targets is not None and target_length is None: - raise RuntimeError( - f"Both targets and target_length have to be None or not None: {targets}, {target_length}" - ) - # do not use self.return_lattices for now - if targets is None: - align = False - decode_func = lambda a, b: self._decoder.decode( - a, b, return_lattices=False, return_ilabels=self.return_ilabels, output_aligned=self.output_aligned - ) - else: - align = True - decode_func = lambda a, b, c, d: self._decoder.align( - a, b, c, d, return_lattices=False, return_ilabels=False, output_aligned=True - ) - batch_size = log_probs.shape[0] - if self.split_batch_size > 0 and self.split_batch_size <= batch_size: - predictions = [] - probs = [] - for batch_idx in range(0, batch_size, self.split_batch_size): - begin = batch_idx - end = min(begin + self.split_batch_size, batch_size) - log_probs_length_part = log_probs_length[begin:end] - log_probs_part = log_probs[begin:end, : log_probs_length_part.max()] - if align: - target_length_part = target_length[begin:end] - targets_part = targets[begin:end, : target_length_part.max()] - predictions_part, probs_part = decode_func( - log_probs_part, log_probs_length_part, targets_part, target_length_part - ) - del targets_part, target_length_part - else: - predictions_part, probs_part = decode_func(log_probs_part, log_probs_length_part) - del log_probs_part, log_probs_length_part - predictions += predictions_part - probs += probs_part - else: - predictions, probs = ( - decode_func(log_probs, log_probs_length, targets, target_length) - if align - else decode_func(log_probs, log_probs_length) - ) - assert len(predictions) == len(probs) - return predictions, probs - - @torch.no_grad() - def forward(self, log_probs, log_probs_length): - if self.dec_type == "looseali": - raise RuntimeError(f"Decoder with dec_type=`{self.dec_type}` is not intended for regular decoding.") - predictions, probs = self._forward_impl(log_probs, log_probs_length) - lengths = torch.tensor([len(pred) for pred in predictions], device=predictions[0].device) - predictions_tensor = torch.full((len(predictions), lengths.max()), self._blank).to( - device=predictions[0].device - ) - probs_tensor = torch.full((len(probs), lengths.max()), 1.0).to(device=predictions[0].device) - for i, (pred, prob) in enumerate(zip(predictions, probs)): - predictions_tensor[i, : lengths[i]] = pred - probs_tensor[i, : lengths[i]] = prob - return predictions_tensor, lengths, probs_tensor - - @torch.no_grad() - def align(self, log_probs, log_probs_length, targets, target_length): - len_enough = (log_probs_length >= target_length) & (target_length > 0) - if torch.all(len_enough) or self.dec_type == "looseali": - results = self._forward_impl(log_probs, log_probs_length, targets, target_length) - else: - results = self._forward_impl( - log_probs[len_enough], log_probs_length[len_enough], targets[len_enough], target_length[len_enough] - ) - for i, computed in enumerate(len_enough): - if not computed: - results[0].insert(i, torch.empty(0, dtype=torch.int32)) - results[1].insert(i, torch.empty(0, dtype=torch.float)) - return results diff --git a/nemo/collections/asr/modules/lstm_decoder.py b/nemo/collections/asr/modules/lstm_decoder.py index 9bb60e2fabca99fdb0ec8c1b21e73e10e02f1623..03f6cf6aa87579335595f1b1a9376ad89bd7957f 100644 --- a/nemo/collections/asr/modules/lstm_decoder.py +++ b/nemo/collections/asr/modules/lstm_decoder.py @@ -35,6 +35,7 @@ class LSTMDecoder(NeuralModule, Exportable): 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 @@ -45,7 +46,16 @@ class LSTMDecoder(NeuralModule, Exportable): 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): + 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: @@ -57,7 +67,7 @@ class LSTMDecoder(NeuralModule, Exportable): self.__vocabulary = vocabulary self._feat_in = feat_in # Add 1 for blank char - self._num_classes = num_classes + 1 + self._num_classes = num_classes + 1 if add_blank else num_classes self.lstm_layer = nn.LSTM( input_size=feat_in, diff --git a/nemo/collections/asr/modules/msdd_diarizer.py b/nemo/collections/asr/modules/msdd_diarizer.py deleted file mode 100644 index 949960ed33ee7a523ea647f55c3f37e95cf92454..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/msdd_diarizer.py +++ /dev/null @@ -1,442 +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.nn as nn -import torch.nn.functional as F - -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 EncodedRepresentation, LengthsType, NeuralType, SpectrogramType -from nemo.core.neural_types.elements import ProbsType - -__all__ = ['MSDD_module'] - - -class ConvLayer(nn.Module): - def __init__(self, in_channels=1, out_channels=1, kernel_size=(3, 1), stride=(1, 1)): - super(ConvLayer, self).__init__() - self.cnn = nn.Sequential( - nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride), - nn.ReLU(), - nn.BatchNorm2d(out_channels, eps=0.001, momentum=0.99), - ) - - def forward(self, feature): - feature = self.cnn(feature) - return feature - - -class MSDD_module(NeuralModule, Exportable): - """ - Multi-scale Diarization Decoder (MSDD) for overlap-aware diarization and improved diarization accuracy from clustering diarizer. - Based on the paper: Taejin Park et. al, "Multi-scale Speaker Diarization with Dynamic Scale Weighting", Interspeech 2022. - Arxiv version: https://arxiv.org/pdf/2203.15974.pdf - - Args: - num_spks (int): - Max number of speakers that are processed by the model. In `MSDD_module`, `num_spks=2` for pairwise inference. - hidden_size (int): - Number of hidden units in sequence models and intermediate layers. - num_lstm_layers (int): - Number of the stacked LSTM layers. - dropout_rate (float): - Dropout rate for linear layers, CNN and LSTM. - cnn_output_ch (int): - Number of channels per each CNN layer. - emb_dim (int): - Dimension of the embedding vectors. - scale_n (int): - Number of scales in multi-scale system. - clamp_max (float): - Maximum value for limiting the scale weight values. - conv_repeat (int): - Number of CNN layers after the first CNN layer. - weighting_scheme (str): - Name of the methods for estimating the scale weights. - context_vector_type (str): - If 'cos_sim', cosine similarity values are used for the input of the sequence models. - If 'elem_prod', element-wise product values are used for the input of the sequence models. - """ - - @property - def output_types(self): - """ - Return definitions of module output ports. - """ - return OrderedDict( - { - "probs": NeuralType(('B', 'T', 'C'), ProbsType()), - "scale_weights": NeuralType(('B', 'T', 'C', 'D'), ProbsType()), - } - ) - - @property - def input_types(self): - """ - Return definitions of module input ports. - """ - return OrderedDict( - { - "ms_emb_seq": NeuralType(('B', 'T', 'C', 'D'), SpectrogramType()), - "length": NeuralType(tuple('B'), LengthsType()), - "ms_avg_embs": NeuralType(('B', 'C', 'D', 'C'), EncodedRepresentation()), - "targets": NeuralType(('B', 'T', 'C'), ProbsType()), - } - ) - - def init_weights(self, m): - if type(m) == nn.Linear: - torch.nn.init.xavier_uniform_(m.weight) - m.bias.data.fill_(0.01) - elif type(m) in [nn.GRU, nn.LSTM, nn.RNN]: - for name, param in m.named_parameters(): - if 'weight_ih' in name: - torch.nn.init.xavier_uniform_(param.data) - elif 'weight_hh' in name: - torch.nn.init.orthogonal_(param.data) - elif 'bias' in name: - param.data.fill_(0.01) - - def __init__( - self, - num_spks: int = 2, - hidden_size: int = 256, - num_lstm_layers: int = 2, - dropout_rate: float = 0.5, - cnn_output_ch: int = 16, - emb_dim: int = 192, - scale_n: int = 5, - clamp_max: float = 1.0, - conv_repeat: int = 1, - weighting_scheme: str = 'conv_scale_weight', - context_vector_type: str = 'cos_sim', - ): - super().__init__() - self._speaker_model = None - self.batch_size: int = 1 - self.length: int = 50 - self.emb_dim: int = emb_dim - self.num_spks: int = num_spks - self.scale_n: int = scale_n - self.cnn_output_ch: int = cnn_output_ch - self.conv_repeat: int = conv_repeat - self.chan: int = 2 - self.eps: float = 1e-6 - self.num_lstm_layers: int = num_lstm_layers - self.weighting_scheme: str = weighting_scheme - self.context_vector_type: bool = context_vector_type - - self.softmax = torch.nn.Softmax(dim=2) - self.cos_dist = torch.nn.CosineSimilarity(dim=3, eps=self.eps) - self.lstm = nn.LSTM( - hidden_size, - hidden_size, - num_layers=self.num_lstm_layers, - batch_first=True, - bidirectional=True, - dropout=dropout_rate, - ) - - if self.weighting_scheme == 'conv_scale_weight': - self.conv = nn.ModuleList( - [ - ConvLayer( - in_channels=1, - out_channels=cnn_output_ch, - kernel_size=(self.scale_n + self.scale_n * num_spks, 1), - stride=(1, 1), - ) - ] - ) - for conv_idx in range(1, conv_repeat + 1): - self.conv.append( - ConvLayer( - in_channels=1, out_channels=cnn_output_ch, kernel_size=(self.cnn_output_ch, 1), stride=(1, 1) - ) - ) - self.conv_bn = nn.ModuleList() - for conv_idx in range(self.conv_repeat + 1): - self.conv_bn.append(nn.BatchNorm2d(self.emb_dim, affine=False)) - self.conv_to_linear = nn.Linear(emb_dim * cnn_output_ch, hidden_size) - self.linear_to_weights = nn.Linear(hidden_size, self.scale_n) - - elif self.weighting_scheme == 'attn_scale_weight': - self.W_a = nn.Linear(emb_dim, emb_dim, bias=False) - nn.init.eye_(self.W_a.weight) - else: - raise ValueError(f"No such weighting scheme as {self.weighting_scheme}") - - self.hidden_to_spks = nn.Linear(2 * hidden_size, self.num_spks) - if self.context_vector_type == "cos_sim": - self.dist_to_emb = nn.Linear(self.scale_n * self.num_spks, hidden_size) - self.dist_to_emb.apply(self.init_weights) - elif self.context_vector_type == "elem_prod": - self.product_to_emb = nn.Linear(self.emb_dim * self.num_spks, hidden_size) - else: - raise ValueError(f"No such context vector type as {self.context_vector_type}") - - self.dropout = nn.Dropout(dropout_rate) - self.hidden_to_spks.apply(self.init_weights) - self.lstm.apply(self.init_weights) - self.clamp_max = clamp_max - - def core_model(self, ms_emb_seq, length, ms_avg_embs, targets): - """ - Core model that accepts multi-scale cosine similarity values and estimates per-speaker binary label. - - Args: - ms_emb_seq (Tensor): - Multiscale input embedding sequence - Shape: (batch_size, length, scale_n, emb_dim) - length (Tensor): - The actual length of embedding sequences without zero padding - Shape: (batch_size,) - ms_avg_embs (Tensor): - Cluster-average speaker embedding vectors. - Shape: (batch_size, scale_n, self.emb_dim, max_spks) - targets (Tensor): - Ground-truth labels for the finest segment. - Shape: (batch_size, feats_len, max_spks) - - Returns: - preds (Tensor): - Predicted binary speaker label for each speaker. - Shape: (batch_size, feats_len, max_spks) - scale_weights (Tensor): - Multiscale weights per each base-scale segment. - Shape: (batch_size, length, scale_n, max_spks) - - """ - self.batch_size = ms_emb_seq.shape[0] - self.length = ms_emb_seq.shape[1] - self.emb_dim = ms_emb_seq.shape[-1] - - _ms_emb_seq = ms_emb_seq.unsqueeze(4).expand(-1, -1, -1, -1, self.num_spks) - ms_emb_seq_single = ms_emb_seq - ms_avg_embs = ms_avg_embs.unsqueeze(1).expand(-1, self.length, -1, -1, -1) - - ms_avg_embs_perm = ms_avg_embs.permute(0, 1, 2, 4, 3).reshape(self.batch_size, self.length, -1, self.emb_dim) - - if self.weighting_scheme == "conv_scale_weight": - scale_weights = self.conv_scale_weights(ms_avg_embs_perm, ms_emb_seq_single) - elif self.weighting_scheme == "attn_scale_weight": - scale_weights = self.attention_scale_weights(ms_avg_embs_perm, ms_emb_seq_single) - else: - raise ValueError(f"No such weighting scheme as {self.weighting_scheme}") - scale_weights = scale_weights.to(ms_emb_seq.device) - - if self.context_vector_type == "cos_sim": - context_emb = self.cosine_similarity(scale_weights, ms_avg_embs, _ms_emb_seq) - elif self.context_vector_type == "elem_prod": - context_emb = self.element_wise_product(scale_weights, ms_avg_embs, _ms_emb_seq) - else: - raise ValueError(f"No such context vector type as {self.context_vector_type}") - - context_emb = self.dropout(F.relu(context_emb)) - lstm_output = self.lstm(context_emb) - lstm_hidden_out = self.dropout(F.relu(lstm_output[0])) - spk_preds = self.hidden_to_spks(lstm_hidden_out) - preds = nn.Sigmoid()(spk_preds) - return preds, scale_weights - - def element_wise_product(self, scale_weights, ms_avg_embs, ms_emb_seq): - """ - Calculate element wise product values among cluster-average embedding vectors and input embedding vector sequences. - This function is selected by assigning `self.context_vector_type = "elem_prod"`. `elem_prod` method usually takes more - time to converge compared to `cos_sim` method. - - Args: - scale_weights (Tensor): - Multiscale weight vector. - Shape: (batch_size, feats_len, scale_n, max_spks) - ms_avg_embs_perm (Tensor): - Tensor containing cluster-average speaker embeddings for each scale. - Shape: (batch_size, length, scale_n, emb_dim) - ms_emb_seq (Tensor): - Tensor containing multi-scale speaker embedding sequences. `ms_emb_seq` is a single channel input from the - given audio stream input. - Shape: (batch_size, length, num_spks, emb_dim) - - Returns: - context_emb (Tensor): - Output of `dist_to_emb` linear layer containing context for speaker label estimation. - """ - scale_weight_flatten = scale_weights.reshape(self.batch_size * self.length, self.num_spks, self.scale_n) - ms_avg_embs_flatten = ms_avg_embs.reshape( - self.batch_size * self.length, self.scale_n, self.emb_dim, self.num_spks - ) - ms_emb_seq_flatten = ms_emb_seq.reshape(-1, self.scale_n, self.emb_dim) - ms_emb_seq_flatten_rep = ms_emb_seq_flatten.unsqueeze(3).reshape(-1, self.scale_n, self.emb_dim, self.num_spks) - elemwise_product = ms_avg_embs_flatten * ms_emb_seq_flatten_rep - context_vectors = torch.bmm( - scale_weight_flatten.reshape(self.batch_size * self.num_spks * self.length, 1, self.scale_n), - elemwise_product.reshape(self.batch_size * self.num_spks * self.length, self.scale_n, self.emb_dim), - ) - context_vectors = context_vectors.reshape(self.batch_size, self.length, self.emb_dim * self.num_spks) - context_emb = self.product_to_emb(context_vectors) - return context_emb - - def cosine_similarity(self, scale_weights, ms_avg_embs, _ms_emb_seq): - """ - Calculate cosine similarity values among cluster-average embedding vectors and input embedding vector sequences. - This function is selected by assigning self.context_vector_type = "cos_sim". - - Args: - scale_weights (Tensor): - Multiscale weight vector. - Shape: (batch_size, feats_len, scale_n, max_spks) - ms_avg_embs_perm (Tensor): - Tensor containing cluster-average speaker embeddings for each scale. - Shape: (batch_size, length, scale_n, emb_dim) - _ms_emb_seq (Tensor): - Tensor containing multi-scale speaker embedding sequences. `ms_emb_seq` is a single channel input from the - given audio stream input. - Shape: (batch_size, length, num_spks, emb_dim) - - Returns: - context_emb (Tensor): - Output of `dist_to_emb` linear layer containing context for speaker label estimation. - """ - cos_dist_seq = self.cos_dist(_ms_emb_seq, ms_avg_embs) - context_vectors = torch.mul(scale_weights, cos_dist_seq) - context_vectors = context_vectors.view(self.batch_size, self.length, -1) - context_emb = self.dist_to_emb(context_vectors) - return context_emb - - def attention_scale_weights(self, ms_avg_embs_perm, ms_emb_seq): - """ - Use weighted inner product for calculating each scale weight. W_a matrix has (emb_dim * emb_dim) learnable parameters - and W_a matrix is initialized with an identity matrix. Compared to "conv_scale_weight" method, this method shows more evenly - distributed scale weights. - - Args: - ms_avg_embs_perm (Tensor): - Tensor containing cluster-average speaker embeddings for each scale. - Shape: (batch_size, length, scale_n, emb_dim) - ms_emb_seq (Tensor): - Tensor containing multi-scale speaker embedding sequences. `ms_emb_seq` is input from the - given audio stream input. - Shape: (batch_size, length, num_spks, emb_dim) - - Returns: - scale_weights (Tensor): - Weight vectors that determine the weight of each scale. - Shape: (batch_size, length, num_spks, emb_dim) - """ - self.W_a(ms_emb_seq.flatten(0, 1)) - mat_a = self.W_a(ms_emb_seq.flatten(0, 1)) - mat_b = ms_avg_embs_perm.flatten(0, 1).permute(0, 2, 1) - - weighted_corr = torch.matmul(mat_a, mat_b).reshape(-1, self.scale_n, self.scale_n, self.num_spks) - scale_weights = torch.sigmoid(torch.diagonal(weighted_corr, dim1=1, dim2=2)) - scale_weights = scale_weights.reshape(self.batch_size, self.length, self.scale_n, self.num_spks) - scale_weights = self.softmax(scale_weights) - return scale_weights - - def conv_scale_weights(self, ms_avg_embs_perm, ms_emb_seq_single): - """ - Use multiple Convnet layers to estimate the scale weights based on the cluster-average embedding and - input embedding sequence. - - Args: - ms_avg_embs_perm (Tensor): - Tensor containing cluster-average speaker embeddings for each scale. - Shape: (batch_size, length, scale_n, emb_dim) - ms_emb_seq_single (Tensor): - Tensor containing multi-scale speaker embedding sequences. ms_emb_seq_single is input from the - given audio stream input. - Shape: (batch_size, length, num_spks, emb_dim) - - Returns: - scale_weights (Tensor): - Weight vectors that determine the weight of each scale. - Shape: (batch_size, length, num_spks, emb_dim) - """ - ms_cnn_input_seq = torch.cat([ms_avg_embs_perm, ms_emb_seq_single], dim=2) - ms_cnn_input_seq = ms_cnn_input_seq.unsqueeze(2).flatten(0, 1) - - conv_out = self.conv_forward( - ms_cnn_input_seq, conv_module=self.conv[0], bn_module=self.conv_bn[0], first_layer=True - ) - for conv_idx in range(1, self.conv_repeat + 1): - conv_out = self.conv_forward( - conv_input=conv_out, - conv_module=self.conv[conv_idx], - bn_module=self.conv_bn[conv_idx], - first_layer=False, - ) - - lin_input_seq = conv_out.view(self.batch_size, self.length, self.cnn_output_ch * self.emb_dim) - hidden_seq = self.conv_to_linear(lin_input_seq) - hidden_seq = self.dropout(F.leaky_relu(hidden_seq)) - scale_weights = self.softmax(self.linear_to_weights(hidden_seq)) - scale_weights = scale_weights.unsqueeze(3).expand(-1, -1, -1, self.num_spks) - return scale_weights - - def conv_forward(self, conv_input, conv_module, bn_module, first_layer=False): - """ - A module for convolutional neural networks with 1-D filters. As a unit layer batch normalization, non-linear layer and dropout - modules are included. - - Note: - If `first_layer=True`, the input shape is set for processing embedding input. - If `first_layer=False`, then the input shape is set for processing the output from another `conv_forward` module. - - Args: - conv_input (Tensor): - Reshaped tensor containing cluster-average embeddings and multi-scale embedding sequences. - Shape: (batch_size*length, 1, scale_n*(num_spks+1), emb_dim) - conv_module (ConvLayer): - ConvLayer instance containing torch.nn.modules.conv modules. - bn_module (torch.nn.modules.batchnorm.BatchNorm2d): - Predefined Batchnorm module. - first_layer (bool): - Boolean for switching between the first layer and the others. - Default: `False` - - Returns: - conv_out (Tensor): - Convnet output that can be fed to another ConvLayer module or linear layer. - Shape: (batch_size*length, 1, cnn_output_ch, emb_dim) - """ - conv_out = conv_module(conv_input) - conv_out = conv_out.permute(0, 2, 1, 3) if not first_layer else conv_out - conv_out = conv_out.reshape(self.batch_size, self.length, self.cnn_output_ch, self.emb_dim) - conv_out = conv_out.unsqueeze(2).flatten(0, 1) - conv_out = bn_module(conv_out.permute(0, 3, 2, 1)).permute(0, 3, 2, 1) - conv_out = self.dropout(F.leaky_relu(conv_out)) - return conv_out - - @typecheck() - def forward(self, ms_emb_seq, length, ms_avg_embs, targets): - preds, scale_weights = self.core_model(ms_emb_seq, length, ms_avg_embs, targets) - return preds, scale_weights - - def input_example(self): - """ - Generate input examples for tracing etc. - - Returns (tuple): - A tuple of input examples. - """ - device = next(self.parameters()).device - lens = torch.full(size=(input_example.shape[0],), fill_value=123, device=device) - input_example = torch.randn(1, lens, self.scale_n, self.emb_dim, device=device) - avg_embs = torch.randn(1, self.scale_n, self.emb_dim, self.num_spks, device=device) - targets = torch.randn(1, lens, self.num_spks).round().float() - return tuple([input_example, lens, avg_embs, targets]) diff --git a/nemo/collections/asr/modules/rnnt.py b/nemo/collections/asr/modules/rnnt.py index ac130ab2c2c3e8390a49341fccf88d6b65e2fadd..feaf0edfca927085b85c103d042605697f9bbf30 100644 --- a/nemo/collections/asr/modules/rnnt.py +++ b/nemo/collections/asr/modules/rnnt.py @@ -29,7 +29,7 @@ from typing import Any, Dict, List, Optional, Tuple, Union import torch -from omegaconf import DictConfig, OmegaConf +from omegaconf import DictConfig from nemo.collections.asr.modules import rnnt_abstract from nemo.collections.asr.parts.submodules import stateless_net @@ -321,12 +321,10 @@ class StatelessTransducerDecoder(rnnt_abstract.AbstractRNNTDecoder, Exportable): Args: decoder_states (list of list of torch.Tensor): list of decoder states - [B, 1, C] - - B: Batch size. - - C: Dimensionality of the hidden state. + 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]] + batch_states (list of torch.Tensor): batch of decoder states ``[[B x C]]``. """ new_state = torch.stack([s[0] for s in decoder_states]) @@ -379,30 +377,64 @@ class StatelessTransducerDecoder(rnnt_abstract.AbstractRNNTDecoder, Exportable): @classmethod def batch_replace_states_mask( cls, - src_states: list[torch.Tensor], - dst_states: list[torch.Tensor], + 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, ): - """Replace states in dst_states with states from src_states using the mask""" + """ + 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], dst_states[0], out=dst_states[0]) + 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""" - dst_states[0].copy_(src_states[0]) + if batch_size is None: + dst_states[0].copy_(src_states[0]) + else: + dst_states[0][:batch_size].copy_(src_states[0][:batch_size]) - def batch_split_states(self, batch_states: list[torch.Tensor]) -> list[list[torch.Tensor]]: + @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], @@ -982,19 +1014,17 @@ class RNNTDecoder(rnnt_abstract.AbstractRNNTDecoder, Exportable, AdapterModuleMi 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 + 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. + 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] + ``[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] @@ -1021,6 +1051,60 @@ class RNNTDecoder(rnnt_abstract.AbstractRNNTDecoder, Exportable, AdapterModuleMi 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. @@ -1057,32 +1141,80 @@ class RNNTDecoder(rnnt_abstract.AbstractRNNTDecoder, Exportable, AdapterModuleMi 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, ): - """Replace states in dst_states with states from src_states using the mask""" + """ + 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), dst_states[0], out=dst_states[0]) - torch.where(mask.unsqueeze(0).unsqueeze(-1), src_states[1].to(dtype), dst_states[1], out=dst_states[1]) + 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""" - dst_states[0].copy_(src_states[0]) - dst_states[1].copy_(src_states[1]) + 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( - self, batch_states: Tuple[torch.Tensor, torch.Tensor] - ) -> list[Tuple[torch.Tensor, torch.Tensor]]: + 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 list(zip(batch_states[0].split(1, dim=1), batch_states[1].split(1, dim=1))) + 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, @@ -1200,6 +1332,8 @@ class RNNTJoint(rnnt_abstract.AbstractRNNTJoint, Exportable, AdapterModuleMixin) - 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. @@ -1225,6 +1359,7 @@ class RNNTJoint(rnnt_abstract.AbstractRNNTJoint, Exportable, AdapterModuleMixin) "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 @@ -1337,6 +1472,8 @@ class RNNTJoint(rnnt_abstract.AbstractRNNTJoint, Exportable, AdapterModuleMixin) # to change, requires running ``model.temperature = T`` explicitly self.temperature = 1.0 + self.hypotheses = None + @typecheck() def forward( self, @@ -1346,6 +1483,7 @@ class RNNTJoint(rnnt_abstract.AbstractRNNTJoint, Exportable, AdapterModuleMixin) 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 @@ -1383,6 +1521,7 @@ class RNNTJoint(rnnt_abstract.AbstractRNNTJoint, Exportable, AdapterModuleMixin) 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): @@ -1467,6 +1606,9 @@ class RNNTJoint(rnnt_abstract.AbstractRNNTJoint, Exportable, AdapterModuleMixin) 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() @@ -1477,6 +1619,7 @@ class RNNTJoint(rnnt_abstract.AbstractRNNTJoint, Exportable, AdapterModuleMixin) 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 @@ -1494,8 +1637,19 @@ class RNNTJoint(rnnt_abstract.AbstractRNNTJoint, Exportable, AdapterModuleMixin) 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. diff --git a/nemo/collections/asr/modules/rnnt_abstract.py b/nemo/collections/asr/modules/rnnt_abstract.py index c895fc6deaf158337c5c1ff3d5432b8ccfa1b0ab..e83ccc76501e0a29969095fd60b3f43f5e0e4282 100644 --- a/nemo/collections/asr/modules/rnnt_abstract.py +++ b/nemo/collections/asr/modules/rnnt_abstract.py @@ -275,14 +275,52 @@ class AbstractRNNTDecoder(NeuralModule, ABC): """ 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: list[torch.Tensor], - dst_states: list[torch.Tensor], + 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, ): - """Replace states in dst_states with states from src_states using the mask, in a way that does not synchronize with the CPU""" + """ + 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 @@ -290,17 +328,35 @@ class AbstractRNNTDecoder(NeuralModule, ABC): 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() - def batch_split_states(self, batch_states: list[torch.Tensor]) -> list[list[torch.Tensor]]: + @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. diff --git a/nemo/collections/asr/modules/sortformer_modules.py b/nemo/collections/asr/modules/sortformer_modules.py index c158b22fe47361038704e738b9c6fa65a5161656..4b06c0e2978d28d3003fc75e74708754ab207644 100644 --- a/nemo/collections/asr/modules/sortformer_modules.py +++ b/nemo/collections/asr/modules/sortformer_modules.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -12,91 +12,885 @@ # 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). + 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 type(m) == nn.Linear: + 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, - hidden_size: int = 192, 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, ): - """ - Args: - num_spks (int): - Max number of speakers that are processed by the model. - hidden_size (int): - Number of hidden units in sequence models and intermediate layers. - dropout_rate (float): - Dropout rate for linear layers, CNN and LSTM. - fc_d_model (int): - Dimension of the embedding vectors. - tf_d_model (int): - Dimension of the embedding vectors. - """ 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.unit_n_spks: int = num_spks - self.hidden_to_spks = nn.Linear(2 * self.hidden_size, self.unit_n_spks) + 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.unit_n_spks) + 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 - def length_to_mask(self, lengths, max_length): + # 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 (frame counts) of sequences - max_length (int): maximum length (frame count) of the sequences in the batch + 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 + 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): """ - A set of layers for predicting speaker probabilities with a sigmoid activation function. + The final layer that outputs speaker probabilities using the Sigmoid activation function. Args: - hidden_out (torch.Tensor): tensor of shape (batch_size, seq_len, hidden_size) + hidden_out (torch.Tensor): Tensor containing hidden states from the encoder + Shape: (batch_size, n_frames, hidden_dim) Returns: - preds (torch.Tensor): tensor of shape (batch_size, seq_len, num_spks) containing speaker probabilities + 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 = nn.Sigmoid()(spk_preds) + 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/squeezeformer_encoder.py b/nemo/collections/asr/modules/squeezeformer_encoder.py deleted file mode 100644 index ae779380edf657f37780387409a1f28fabccc56a..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/modules/squeezeformer_encoder.py +++ /dev/null @@ -1,461 +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 collections import OrderedDict -from typing import List, Optional, Set - -import torch -import torch.distributed -import torch.nn as nn -from omegaconf import DictConfig - -from nemo.collections.asr.parts.submodules.multi_head_attention import PositionalEncoding, RelPositionalEncoding -from nemo.collections.asr.parts.submodules.squeezeformer_modules import SqueezeformerLayer -from nemo.collections.asr.parts.submodules.subsampling import ConvSubsampling, StackingSubsampling, TimeReductionModule -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, NeuralType, SpectrogramType - -__all__ = ['SqueezeformerEncoder'] - - -class SqueezeformerEncoder(NeuralModule, Exportable, AccessMixin): - """ - The encoder for ASR model of Squeezeformer. - Based on this paper: - 'Squeezeformer: An Efficient Transformer for Automatic Speech Recognition' by Sehoon Kim et al. - https://arxiv.org/abs/2206.00888 - - 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'] - Defaults to dw_striding. - subsampling_factor (int): the subsampling factor which should be power of 2 - Defaults to 4. - subsampling_conv_channels (int): the size of the convolutions in the subsampling module - Defaults to -1 which would set it to d_model. - ff_expansion_factor (int): the expansion factor in feed forward layers - Defaults to 4. - self_attention_model (str): type of the attention layer and positional encoding - 'rel_pos': relative positional embedding and Transformer-XL - 'abs_pos': absolute positional embedding and Transformer - default is rel_pos. - pos_emb_max_len (int): the maximum length of positional embeddings - Defaulst to 5000 - n_heads (int): number of heads in multi-headed attention layers - Defaults to 4. - 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'. - dropout (float): the dropout rate used in all layers except the attention layers - 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. - adaptive_scale (bool): Whether to scale the inputs to each component by affine `scale` and `bias` layer. - Or use a fixed scale=1 and bias=0. - time_reduce_idx (int): Optional integer index of a layer where a time reduction operation will occur. - All operations beyond this point will only occur at the reduced resolution. - time_recovery_idx (int): Optional integer index of a layer where the time recovery operation will occur. - All operations beyond this point will occur at the original resolution (resolution after - primary downsampling). If no value is provided, assumed to be the last layer. - """ - - 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 - input_example = torch.randn(max_batch, self._feat_in, max_dim).to(dev) - input_example_length = torch.randint(1, max_dim, (max_batch,)).to(dev) - 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, - feat_out: int = -1, - subsampling: str = 'dw_striding', - subsampling_factor: int = 4, - subsampling_conv_channels: int = -1, - ff_expansion_factor: int = 4, - self_attention_model: str = 'rel_pos', - n_heads: int = 4, - att_context_size: Optional[List[int]] = None, - xscaling: bool = True, - untie_biases: bool = True, - pos_emb_max_len: int = 5000, - conv_kernel_size: int = 31, - conv_norm_type: str = 'batch_norm', - dropout: float = 0.1, - dropout_emb: float = 0.1, - dropout_att: float = 0.0, - adaptive_scale: bool = True, - time_reduce_idx: Optional[int] = None, - time_recovery_idx: Optional[int] = None, - ): - super().__init__() - - d_ff = d_model * ff_expansion_factor - self.d_model = d_model - self._feat_in = feat_in - if att_context_size: - self.att_context_size = att_context_size - else: - self.att_context_size = [-1, -1] - - if xscaling: - self.xscale = math.sqrt(d_model) - else: - self.xscale = None - self.adaptive_scale = adaptive_scale - - self.time_reduce_idx = time_reduce_idx - if time_reduce_idx is not None: - if time_recovery_idx is None: - self.time_recovery_idx = n_layers - 1 # recover at last layer - else: - self.time_recovery_idx = time_recovery_idx # recover at given layer - - if self.time_reduce_idx is not None: - if self.time_reduce_idx < 0 or self.time_recovery_idx >= n_layers: - raise ValueError(f"Time reduce index must lie between [0, {n_layers})") - if self.time_recovery_idx < 0 or self.time_recovery_idx >= n_layers: - raise ValueError(f"Time recovery index must lie between [0, {n_layers})") - - if subsampling_conv_channels == -1: - subsampling_conv_channels = d_model - if subsampling and subsampling_factor > 1: - if subsampling == 'stacking': - self.pre_encode = StackingSubsampling( - subsampling_factor=subsampling_factor, feat_in=feat_in, feat_out=d_model - ) - else: - self.pre_encode = ConvSubsampling( - subsampling=subsampling, - subsampling_factor=subsampling_factor, - feat_in=feat_in, - feat_out=d_model, - conv_channels=subsampling_conv_channels, - activation=nn.ReLU(), - ) - # For Squeezeformer, initialize the parameters as required. - self.pre_encode.reset_parameters() - else: - self.pre_encode = nn.Linear(feat_in, d_model) - - self._feat_out = d_model - - 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 - - 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, - 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, 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 = SqueezeformerLayer( - d_model=d_model, - d_ff=d_ff, - self_attention_model=self_attention_model, - n_heads=n_heads, - conv_kernel_size=conv_kernel_size, - conv_norm_type=conv_norm_type, - dropout=dropout, - dropout_att=dropout_att, - pos_bias_u=pos_bias_u, - pos_bias_v=pos_bias_v, - adaptive_scale=adaptive_scale, - ) - self.layers.append(layer) - - # Time Reduction and Recovery layer setup - self.time_reduce_layer = None - self.time_recovery_layer = None - self.time_reduce_pos_enc = None - # Add time reduction layer - if self.time_reduce_idx is not None: - self.time_reduce_layer = TimeReductionModule(d_model, d_model, kernel_size=5, stride=2) - self.time_recovery_layer = nn.Linear(d_model, d_model) - - # Chose same type of positional encoding as the originally determined above - if self_attention_model == "rel_pos": - self.time_reduce_pos_enc = RelPositionalEncoding( - d_model=d_model, - dropout_rate=0.0, - max_len=pos_emb_max_len, - xscale=None, - dropout_rate_emb=0.0, - ) - else: - self.time_reduce_pos_enc = PositionalEncoding( - d_model=d_model, dropout_rate=0.0, max_len=pos_emb_max_len, xscale=None, dropout_rate_emb=0.0 - ) - - self.pre_ln = nn.LayerNorm(d_model) - - 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 - - # will be set in self.forward() if defined in AccessMixin config - self.interctc_capture_at_layers = None - - def set_max_audio_length(self, max_audio_length): - """Sets maximum input length. - Pre-calculates internal seq_range mask. - """ - self.max_audio_length = max_audio_length - device = next(self.parameters()).device - dtype = next(self.parameters()).dtype - 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) - self.pos_enc.extend_pe(max_audio_length, device, dtype) - - if self.time_reduce_pos_enc is not None: - self.time_reduce_pos_enc.extend_pe(max_audio_length, device, dtype) - - @typecheck() - def forward(self, audio_signal, length=None): - self.update_max_seq_length(seq_length=audio_signal.size(2), device=audio_signal.device) - return self.forward_for_export(audio_signal=audio_signal, length=length) - - @typecheck() - def forward_for_export(self, audio_signal, length): - max_audio_length: int = audio_signal.size(-1) - - if max_audio_length > self.max_audio_length: - self.set_max_audio_length(max_audio_length) - - 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) - - audio_signal, pos_emb = self.pos_enc(audio_signal) - # adjust size - max_audio_length = audio_signal.size(1) - # Create the self-attention and padding masks - - pad_mask = self.make_pad_mask(max_audio_length, length) - att_mask = pad_mask.unsqueeze(1).repeat([1, max_audio_length, 1]) - att_mask = torch.logical_and(att_mask, att_mask.transpose(1, 2)) - if self.att_context_size[0] >= 0: - att_mask = att_mask.triu(diagonal=-self.att_context_size[0]) - if self.att_context_size[1] >= 0: - att_mask = att_mask.tril(diagonal=self.att_context_size[1]) - att_mask = ~att_mask - - if self.use_pad_mask: - pad_mask = ~pad_mask - else: - pad_mask = None - - # Create cache of activations for the time reduction step - # Note: NeMo codebase allows only a single time reduction step to occur - recovery_activation_cache = [] - - audio_signal = self.pre_ln(audio_signal) - for lth, layer in enumerate(self.layers): - # Perform time reduction - if self.time_reduce_layer is not None and lth == self.time_reduce_idx: - # Perform time reduction - recovery_activation_cache.append((audio_signal, att_mask, pad_mask, pos_emb)) - audio_signal, att_mask, pad_mask = self.time_reduce_layer( - x=audio_signal, att_mask=att_mask, pad_mask=pad_mask - ) - # Only update PE, not the original audio_signal - _, pos_emb = self.time_reduce_pos_enc(audio_signal) - - # Perform time recovery - if self.time_recovery_layer is not None and lth == self.time_recovery_idx: - recovery_audio_signal, att_mask, pad_mask, pos_emb = recovery_activation_cache.pop(0) - # repeat interleaved values for 2x seq length - audio_signal = torch.repeat_interleave(audio_signal, repeats=2, dim=1) - - B, T, D = recovery_audio_signal.size() - audio_signal = audio_signal[:, :T, :] # Slice off the exact T timesteps as original cache value - audio_signal = self.time_recovery_layer(audio_signal) # learn non linear mapping - audio_signal = recovery_audio_signal + audio_signal # learn just the residual - - audio_signal = layer(x=audio_signal, att_mask=att_mask, pos_emb=pos_emb, pad_mask=pad_mask) - - # 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) - - audio_signal = torch.transpose(audio_signal, 1, 2) - return audio_signal, length - - def update_max_seq_length(self, seq_length: int, device): - # Find global max audio length across all nodes - 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: - self.set_max_audio_length(seq_length) - - def make_pad_mask(self, max_audio_length, seq_lens): - """Make masking for padding.""" - mask = self.seq_range[:max_audio_length].expand(seq_lens.size(0), -1) < seq_lens.unsqueeze(-1) - return mask - - def enable_pad_mask(self, on=True): - # On inference, user may chose to disable pad mask - mask = self.use_pad_mask - self.use_pad_mask = on - return mask - - -class SqueezeformerEncoderAdapter(SqueezeformerEncoder, adapter_mixins.AdapterModuleMixin): - - # 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 - - -""" -Register any additional information -""" -if adapter_mixins.get_registered_adapter(SqueezeformerEncoder) is None: - adapter_mixins.register_adapter(base_class=SqueezeformerEncoder, adapter_class=SqueezeformerEncoderAdapter) diff --git a/nemo/collections/asr/modules/ssl_modules/__init__.py b/nemo/collections/asr/modules/ssl_modules/__init__.py index c9b7e970fe2ccce1ab12c4b1eacb21a371f2c6ca..f33127bd7d853b3ddec9d52df4a1db1d476f5285 100644 --- a/nemo/collections/asr/modules/ssl_modules/__init__.py +++ b/nemo/collections/asr/modules/ssl_modules/__init__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -17,9 +17,16 @@ from nemo.collections.asr.modules.ssl_modules.augmentation import ( SpeakerNoiseAugmentation, ) from nemo.collections.asr.modules.ssl_modules.masking import ConvFeatureMaksingWrapper, RandomBlockMasking -from nemo.collections.asr.modules.ssl_modules.multi_layer_feat import ( - ConformerMultiLayerFeatureExtractor, - ConformerMultiLayerFeaturePreprocessor, -) +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 index bb63b7f38b9ace798e999949e077a502139db8e7..cd665634f841352b67b3cf9e9a9dc7c57b36ba8a 100644 --- a/nemo/collections/asr/modules/ssl_modules/augmentation.py +++ b/nemo/collections/asr/modules/ssl_modules/augmentation.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -13,8 +13,9 @@ # limitations under the License. import math +import random +from collections import Counter -import numpy as np import torch from nemo.collections.asr.data.ssl_dataset import AudioNoiseBatch @@ -83,29 +84,27 @@ class SpeakerNoiseAugmentation(object): noise = batch.noise noise_len = batch.noise_len - noisy_audio = batch.noisy_audio - noisy_audio_len = batch.noisy_audio_len for i in range(batch_size): - if np.random.rand() > self.prob: + 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 = np.random.randint( - int(audio_lengths[i] * self.min_mix_rate), int(audio_lengths[i] * self.max_mix_rate) + 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 = np.random.randint(audio_lengths[i] - mix_len) + mix_start_idx = random.randint(0, audio_lengths[i] - mix_len - 1) # randomly select the energy ratio between speech and noise - if np.random.rand() < self.noise_ratio or batch_size == 1: - energy_ratio = np.random.uniform(self.min_r_noise, self.max_r_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 = np.random.uniform(self.min_r_speech, self.max_r_speech) - j = np.random.choice([x for x in range(batch_size) if x != i]) + 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] @@ -117,7 +116,7 @@ class SpeakerNoiseAugmentation(object): noise_len[i] = mix_len else: # randomly select a segment of noise - noise_start_idx = np.random.randint(noise_len[i] - mix_len) + 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] @@ -129,9 +128,6 @@ class SpeakerNoiseAugmentation(object): noise_signal = torch.zeros_like(audio_signal[i]) noise_signal[mix_start_idx : mix_start_idx + mix_len] = mix_scale * noise_clip - # add noise to audio - noisy_audio[i] = audio_signal[i] + noise_signal - noisy_audio_len[i] = audio_lengths[i] noise[i] = noise_signal noise_len[i] = audio_lengths[i] @@ -141,8 +137,8 @@ class SpeakerNoiseAugmentation(object): audio_len=batch.audio_len, noise=noise, noise_len=noise_len, - noisy_audio=noisy_audio, - noisy_audio_len=noisy_audio_len, + noisy_audio=batch.audio + noise, + noisy_audio_len=noise_len, ) @@ -184,34 +180,32 @@ class MultiSpeakerNoiseAugmentation(SpeakerNoiseAugmentation): noise = batch.noise noise_len = batch.noise_len - noisy_audio = batch.noisy_audio - noisy_audio_len = batch.noisy_audio_len for i in range(batch_size): - if np.random.rand() > self.prob: + 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 = np.random.uniform(self.min_mix_rate, self.max_mix_rate) + 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 = np.random.randint(self.min_num_segments, self.max_num_segments + 1) - num_speakers = np.random.randint(self.min_num_speakers, self.max_num_speakers + 1) + 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 = np.random.multinomial(mix_len, [1 / num_segments] * 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 np.random.rand() < self.noise_ratio or batch_size == 1: + if random.random() < self.noise_ratio or batch_size == 1: mode = "noise" - energy_ratio = np.random.uniform(self.min_r_noise, self.max_r_noise) + energy_ratio = random.uniform(self.min_r_noise, self.max_r_noise) else: mode = "speech" - energy_ratio = np.random.uniform(self.min_r_speech, self.max_r_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]) @@ -220,7 +214,7 @@ class MultiSpeakerNoiseAugmentation(SpeakerNoiseAugmentation): for j in range(num_segments): start_idx = min_start_idx if min_start_idx < max_start_idx: - start_idx = np.random.randint(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] @@ -232,10 +226,6 @@ class MultiSpeakerNoiseAugmentation(SpeakerNoiseAugmentation): # get the residual signal to be added to original audio noise_signal = mix_scale * noise_signal - - # add noise to audio - noisy_audio[i] = audio_signal[i] + noise_signal - noisy_audio_len[i] = audio_lengths[i] noise[i] = noise_signal noise_len[i] = audio_lengths[i] @@ -245,8 +235,8 @@ class MultiSpeakerNoiseAugmentation(SpeakerNoiseAugmentation): audio_len=batch.audio_len, noise=noise, noise_len=noise_len, - noisy_audio=noisy_audio, - noisy_audio_len=noisy_audio_len, + noisy_audio=batch.audio + noise, + noisy_audio_len=noise_len, ) def get_noise_segments(self, batch_idx, batch, segment_lens, num_speakers, mode): @@ -271,7 +261,7 @@ class MultiSpeakerNoiseAugmentation(SpeakerNoiseAugmentation): 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 = np.random.choice(speaker_candidates, min(num_speakers, batch_size - 1), replace=False) + 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] @@ -280,11 +270,11 @@ class MultiSpeakerNoiseAugmentation(SpeakerNoiseAugmentation): self.repeat_noise(audio_signal[bid], audio_lengths[bid], seg_len), seg_len ) else: - start_idx = np.random.randint(audio_lengths[bid] - seg_len) if audio_lengths[bid] > seg_len else 0 + 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 = np.random.randint(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 index 3c3550dddd4ca4e1882a6ff161fcf6c337011d3f..c491c56fa82922dd26fe0210c18e3524bcf30159 100644 --- a/nemo/collections/asr/modules/ssl_modules/masking.py +++ b/nemo/collections/asr/modules/ssl_modules/masking.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -15,7 +15,6 @@ from typing import Optional, Union -import numpy as np import torch import torch.nn as nn @@ -99,29 +98,42 @@ class RandomBlockMasking(NeuralModule): masks (Tensor): the generated masks, shape=(batch, features, time) """ batch_size = input_feats.size(0) - mask_value = self.mask_embedding.unsqueeze(-1) masks = torch.zeros_like(input_feats) - maksed_feats = input_feats.clone() + 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_idx = [0] + 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,), device=input_feats.device)[0] + 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_idx = torch.randperm(max_num_patches - 1, device=input_feats.device)[:num_patches] - for j in range(num_patches): - start = patch_idx[j] * block_size + offset - end = start + block_size - masks[i, :, start:end] = 1.0 - maksed_feats[i, :, start:end] = mask_value - return maksed_feats, masks + 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): """ @@ -133,27 +145,39 @@ class RandomBlockMasking(NeuralModule): masks (Tensor): the generated masks, shape=(batch, features, time) """ batch_size = input_feats.size(0) - mask_value = self.mask_embedding.unsqueeze(-1) masks = torch.zeros_like(input_feats) - maksed_feats = input_feats.clone() + masked_feats = input_feats + mask_prob = torch.tensor(self.mask_prob) + indices = [] for i in range(batch_size): - if self.block_size >= input_lengths[i] * self.max_mask_ratio: + input_length = input_lengths[i].item() + if self.block_size >= input_length * self.max_mask_ratio: # handle case where audio is too short - curr_block_size = 8 + block_size = 8 num_patches = 1 - patch_idices = [0] + patch_indices = torch.tensor([0]) else: - curr_block_size = self.block_size - curr_len = input_lengths[i].detach().cpu().numpy() - num_patches = np.random.binomial(max(0, curr_len - self.block_size), self.mask_prob) - patch_idices = torch.randperm(max(0, curr_len - self.block_size), device=input_feats.device) - patch_idices = patch_idices[:num_patches] - for j in range(num_patches): - start = patch_idices[j] - end = min(start + curr_block_size, input_lengths[i]) - masks[i, :, start:end] = 1.0 - maksed_feats[i, :, start:end] = mask_value - return maksed_feats, masks + 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): diff --git a/nemo/collections/asr/modules/ssl_modules/multi_layer_feat.py b/nemo/collections/asr/modules/ssl_modules/multi_layer_feat.py index b1ff1c1cc74b53b5e0f385f673077e6073dcb86a..73ca41438437dcff3b92ea63429a9ab59c475ff4 100644 --- a/nemo/collections/asr/modules/ssl_modules/multi_layer_feat.py +++ b/nemo/collections/asr/modules/ssl_modules/multi_layer_feat.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -12,16 +12,19 @@ # See the License for the specific language governing permissions and # limitations under the License. -from typing import Callable, List, Optional, Tuple +from typing import List, Optional, Tuple import torch import torch.distributed import torch.nn as nn -from nemo.collections.asr.modules import AudioToMelSpectrogramPreprocessor, ConformerEncoder +from nemo.collections.asr.modules import ( + AudioToMelSpectrogramPreprocessor, + ConformerEncoder, + ConformerMultiLayerFeatureExtractor, +) from nemo.core.classes import Exportable, NeuralModule from nemo.core.classes.mixins import AccessMixin -from nemo.utils import logging class Aggregator(nn.Module): @@ -81,85 +84,12 @@ class Aggregator(nn.Module): raise ValueError(f"Unknown mode {self.mode}") -class ConformerMultiLayerFeatureExtractor(NeuralModule, Exportable): - def __init__(self, encoder, aggregator: Optional[Callable] = None, layer_idx_list: Optional[List[int]] = None): - """ - Args: - encoder: ConformerEncoder instance. - aggregator: Aggregator instance. - layer_idx_list: List of layer indices to extract features from. - """ - super().__init__() - self.encoder = encoder - self.aggregator = aggregator - self.layer_idx_list = ( - [int(l) for l in layer_idx_list] - if layer_idx_list is not None - else [i for i in range(len(self.encoder.layers))] - ) - for x in self.layer_idx_list: - if x < 0 or x >= len(self.encoder.layers): - raise ValueError(f"layer index {x} out of range [0, {len(self.encoder.layers)})") - logging.info(f"Extracting features from layers {self.layer_idx_list}") - self.access_cfg = { - "interctc": { - "capture_layers": self.layer_idx_list, - }, - "detach": False, - "convert_to_cpu": False, - } - self._is_access_enabled = False - - 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 of aggregated features of shape [B, D, T] and lengths of shape [B] - """ - self.encoder.update_access_cfg(self.access_cfg, guid=getattr(self, "model_guid", None)) - self.encoder.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, - ) - - total_registry = {} - for module_registry in self.encoder.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() - if self.aggregator is None: - return encoded_list, encoded_len_list - return self.aggregator(encoded_list, encoded_len_list) - - 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, diff --git a/nemo/collections/asr/modules/ssl_modules/multi_softmax_decoder.py b/nemo/collections/asr/modules/ssl_modules/multi_softmax_decoder.py index d9311cd1ac216468a8744572b6048aa913b65a6d..67c76e342c38fd0b321f9a394059bd167850d09d 100644 --- a/nemo/collections/asr/modules/ssl_modules/multi_softmax_decoder.py +++ b/nemo/collections/asr/modules/ssl_modules/multi_softmax_decoder.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. diff --git a/nemo/collections/asr/modules/ssl_modules/quantizers.py b/nemo/collections/asr/modules/ssl_modules/quantizers.py index ebc9c65e2e7c4ff6276a9be99399a014e2753509..8a53a7c000987e8fe81735137a9c3aca429d89a1 100644 --- a/nemo/collections/asr/modules/ssl_modules/quantizers.py +++ b/nemo/collections/asr/modules/ssl_modules/quantizers.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. diff --git a/nemo/collections/asr/modules/transformer/__init__.py b/nemo/collections/asr/modules/transformer/__init__.py index dc392de020b00cd8ec1a6ec506def4eb86071af4..f3cea616f00ffe5a34559a331a1ab6061f6e0bef 100644 --- a/nemo/collections/asr/modules/transformer/__init__.py +++ b/nemo/collections/asr/modules/transformer/__init__.py @@ -24,6 +24,7 @@ from nemo.collections.asr.modules.transformer.transformer_decoders import Transf from nemo.collections.asr.modules.transformer.transformer_encoders import TransformerEncoder from nemo.collections.asr.modules.transformer.transformer_generators import ( BeamSearchSequenceGenerator, + BeamSearchSequenceGeneratorWithFusionModels, BeamSearchSequenceGeneratorWithLanguageModel, EnsembleBeamSearchSequenceGenerator, GreedySequenceGenerator, @@ -31,3 +32,23 @@ from nemo.collections.asr.modules.transformer.transformer_generators import ( ) 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/transformer.py b/nemo/collections/asr/modules/transformer/transformer.py index 0ea376340d186d4765893564f2b048d4904d640f..b96c481f837fc52d29b570fa783b8f4786a8c323 100644 --- a/nemo/collections/asr/modules/transformer/transformer.py +++ b/nemo/collections/asr/modules/transformer/transformer.py @@ -23,7 +23,6 @@ from nemo.collections.asr.modules.transformer.encoder_module import EncoderModul 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.submodules.adapters.attention_adapter_mixin import AttentionAdapterModuleMixin from nemo.collections.asr.parts.utils import adapter_utils from nemo.core.classes.common import typecheck from nemo.core.classes.exportable import Exportable @@ -226,7 +225,7 @@ class TransformerDecoderNM(DecoderModule, Exportable): 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 = self._decoder( + decoder_hidden_states, xatt_scores_list = self._decoder( decoder_states=decoder_embeddings, decoder_mask=decoder_mask, encoder_states=encoder_embeddings, diff --git a/nemo/collections/asr/modules/transformer/transformer_decoders.py b/nemo/collections/asr/modules/transformer/transformer_decoders.py index 30c6179b85a6a6e3c7f5222e46de5b3cf1f92a01..b8b7e820b1b6a5334b592c4612ad3ce082b9c932 100644 --- a/nemo/collections/asr/modules/transformer/transformer_decoders.py +++ b/nemo/collections/asr/modules/transformer/transformer_decoders.py @@ -63,7 +63,11 @@ class TransformerDecoderBlock(nn.Module, AttentionAdapterModuleMixin): ) 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 + 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) @@ -79,7 +83,7 @@ class TransformerDecoderBlock(nn.Module, AttentionAdapterModuleMixin): 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, _ = self.first_sub_layer(decoder_query, decoder_keys, decoder_keys, decoder_mask) self_attn_output += residual if self.is_adapter_available(): @@ -95,7 +99,9 @@ class TransformerDecoderBlock(nn.Module, AttentionAdapterModuleMixin): residual = self_attn_output self_attn_output = self.layer_norm_2(self_attn_output) - enc_dec_attn_output = self.second_sub_layer(self_attn_output, encoder_states, encoder_states, encoder_mask) + 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 @@ -112,14 +118,14 @@ class TransformerDecoderBlock(nn.Module, AttentionAdapterModuleMixin): pack_input = self.forward_enabled_adapters(pack_input) output_states = pack_input['x'] - return output_states + 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, _ = self.first_sub_layer(decoder_query, decoder_keys, decoder_keys, decoder_mask) self_attn_output += decoder_query if self.is_adapter_available(): @@ -135,7 +141,9 @@ class TransformerDecoderBlock(nn.Module, AttentionAdapterModuleMixin): self_attn_output = self.layer_norm_1(self_attn_output) - enc_dec_attn_output = self.second_sub_layer(self_attn_output, encoder_states, encoder_states, encoder_mask) + 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) @@ -151,7 +159,7 @@ class TransformerDecoderBlock(nn.Module, AttentionAdapterModuleMixin): pack_ip = self.forward_enabled_adapters(pack_ip) output_states = pack_ip['x'] - return self.layer_norm_3(output_states) + 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: @@ -251,9 +259,14 @@ class TransformerDecoder(nn.Module): else: cached_mems_list = memory_states.unsqueeze(0) + xatt_scores_list = [] + for i, layer in enumerate(self.layers): - decoder_states = layer(decoder_states, decoder_attn_mask, memory_states, encoder_states, encoder_attn_mask) + 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) @@ -270,9 +283,9 @@ class TransformerDecoder(nn.Module): cached_mems_list = torch.cat((cached_mems_list, memory_states.unsqueeze(0)), dim=0) if return_mems: - return cached_mems_list + return cached_mems_list, xatt_scores_list else: - return memory_states + return memory_states, xatt_scores_list def input_example(self, max_batch=1, max_dim=256): """ diff --git a/nemo/collections/asr/modules/transformer/transformer_encoders.py b/nemo/collections/asr/modules/transformer/transformer_encoders.py index d3116db82482ec310243dd88ca0776aadbdbc166..3f3236b3a794f46ba6514593cf118e84be7b78e1 100644 --- a/nemo/collections/asr/modules/transformer/transformer_encoders.py +++ b/nemo/collections/asr/modules/transformer/transformer_encoders.py @@ -75,7 +75,7 @@ class TransformerEncoderBlock(nn.Module, AttentionAdapterModuleMixin): 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, _ = self.first_sub_layer(encoder_query, encoder_keys, encoder_keys, encoder_mask) self_attn_output += residual if self.is_adapter_available(): @@ -110,7 +110,7 @@ class TransformerEncoderBlock(nn.Module, AttentionAdapterModuleMixin): 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, _ = self.first_sub_layer(encoder_query, encoder_keys, encoder_keys, encoder_mask) self_attn_output += encoder_query if self.is_adapter_available(): diff --git a/nemo/collections/nlp/modules/common/transformer/transformer_encoders.py b/nemo/collections/asr/modules/transformer/transformer_encoders_nlp.py similarity index 99% rename from nemo/collections/nlp/modules/common/transformer/transformer_encoders.py rename to nemo/collections/asr/modules/transformer/transformer_encoders_nlp.py index 6755a86ba40f35b36ef922fb74ff6891d5f86c3b..ea6de7cb1848d7a9a8c56466ba5cc1060be09176 100644 --- a/nemo/collections/nlp/modules/common/transformer/transformer_encoders.py +++ b/nemo/collections/asr/modules/transformer/transformer_encoders_nlp.py @@ -1,4 +1,4 @@ -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# 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. diff --git a/nemo/collections/asr/modules/transformer/transformer_generators.py b/nemo/collections/asr/modules/transformer/transformer_generators.py index 16d8011ad0f3bda46d0207b85917b472976d5fea..d78518a1fcd1b8d7d7cc83c3cd9e116034e67ef9 100644 --- a/nemo/collections/asr/modules/transformer/transformer_generators.py +++ b/nemo/collections/asr/modules/transformer/transformer_generators.py @@ -28,6 +28,7 @@ __all__ = [ "TopKSequenceGenerator", "BeamSearchSequenceGenerator", "BeamSearchSequenceGeneratorWithLanguageModel", + "BeamSearchSequenceGeneratorWithNGramLM", "EnsembleBeamSearchSequenceGenerator", ] @@ -57,6 +58,8 @@ class GreedySequenceGenerator(ConfidenceMethodMixin): 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). @@ -101,6 +104,7 @@ class GreedySequenceGenerator(ConfidenceMethodMixin): n_samples=1, temperature=None, preserve_step_confidence=False, + return_xattn_scores=False, confidence_method_cfg: Optional[DictConfig] = None, ): super().__init__() @@ -114,6 +118,7 @@ class GreedySequenceGenerator(ConfidenceMethodMixin): 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 @@ -140,14 +145,14 @@ class GreedySequenceGenerator(ConfidenceMethodMixin): 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 + 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 = self.decoder.forward( + decoder_mems_list, xatt_scores_list = self.decoder.forward( decoder_hidden_states, decoder_input_mask, encoder_hidden_states, @@ -156,12 +161,14 @@ class GreedySequenceGenerator(ConfidenceMethodMixin): return_mems=True, ) else: - decoder_mems_list = self.decoder.forward( + 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 + + return logits, decoder_mems_list, xatt_scores_list def _prepare_for_search(self, decoder_input_ids=None, encoder_hidden_states=None): """ @@ -201,6 +208,7 @@ class GreedySequenceGenerator(ConfidenceMethodMixin): 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) @@ -222,14 +230,16 @@ class GreedySequenceGenerator(ConfidenceMethodMixin): 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 = self._one_step_forward( + logits, decoder_mems_list, new_xatt_scores_list = self._one_step_forward( input_ids, encoder_hidden_states, encoder_input_mask, @@ -237,6 +247,14 @@ class GreedySequenceGenerator(ConfidenceMethodMixin): 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) @@ -267,7 +285,7 @@ class GreedySequenceGenerator(ConfidenceMethodMixin): samples = list(tgt.view(orig_batch_size, self.n_samples, -1)) tgt = tgt[:: self.n_samples] - return tgt, samples, step_confidence_tensor + 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 @@ -279,12 +297,12 @@ class GreedySequenceGenerator(ConfidenceMethodMixin): if not return_beam_scores: return results else: - prefixes, scores, tgt = results + 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 + return prefixes, scores, tgt, xatt_scores_list def freeze(self) -> None: """Freeze weights of embedding, decoder, and classification layers to prevent memory leak.""" @@ -353,7 +371,7 @@ class TopKSequenceGenerator(GreedySequenceGenerator): pos=0, return_scores: bool = True, ): - log_probs, decoder_mems_list = super()._one_step_forward( + log_probs, decoder_mems_list, _ = super()._one_step_forward( decoder_input_ids, encoder_hidden_states, encoder_input_mask, @@ -408,7 +426,11 @@ class BeamSearchSequenceGenerator(GreedySequenceGenerator): 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 = self._one_step_forward(tgt, encoder_hidden_states, encoder_input_mask, None, 0) + 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) @@ -427,6 +449,10 @@ class BeamSearchSequenceGenerator(GreedySequenceGenerator): 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() @@ -442,7 +468,7 @@ class BeamSearchSequenceGenerator(GreedySequenceGenerator): pad_mask = pad_profile.repeat(1, self.beam_size) # generate and score candidates for prefixes continuation - log_probs, decoder_mems_list = self._one_step_forward( + 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) @@ -471,6 +497,21 @@ class BeamSearchSequenceGenerator(GreedySequenceGenerator): 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 @@ -494,13 +535,229 @@ class BeamSearchSequenceGenerator(GreedySequenceGenerator): # 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) + 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 ) - tgt = prefixes.view(batch_size, self.beam_size, -1).gather(1, best_guesses).squeeze(1) + 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 + return prefixes, scores * len_penalties, tgt, xatt_scores_list else: return tgt @@ -884,7 +1141,7 @@ class BeamSearchSequenceGeneratorWithLanguageModel(GreedySequenceGenerator): pos=0, ): - nmt_log_probs, decoder_mems_list = super()._one_step_forward( + nmt_log_probs, decoder_mems_list, _ = super()._one_step_forward( decoder_input_ids, encoder_hidden_states, encoder_input_mask, diff --git a/nemo/collections/asr/modules/transformer/transformer_modules.py b/nemo/collections/asr/modules/transformer/transformer_modules.py index 58981b317c365a2bc1ee215f8c8cebe7a05b14c7..5c45aca92237d87c701648747722cffdb4bd7a70 100644 --- a/nemo/collections/asr/modules/transformer/transformer_modules.py +++ b/nemo/collections/asr/modules/transformer/transformer_modules.py @@ -22,7 +22,6 @@ from torch import nn from torch.nn.functional import gelu from nemo.collections.common.parts import form_attention_mask -from nemo.utils import logging __all__ = ["TransformerEmbedding", "AttentionBridge"] @@ -109,10 +108,23 @@ class TransformerEmbedding(nn.Module): 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) @@ -140,7 +152,14 @@ class MultiHeadAttention(nn.Module): whole layer, but before layer normalization """ - def __init__(self, hidden_size, num_attention_heads, attn_score_dropout=0.0, attn_layer_dropout=0.0): + 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( @@ -159,6 +178,7 @@ class MultiHeadAttention(nn.Module): 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) @@ -193,7 +213,12 @@ class MultiHeadAttention(nn.Module): # output projection output_states = self.out_projection(context) output_states = self.layer_dropout(output_states) - return output_states + + extra_output = {} + if self.return_xatt_scores: + extra_output['xatt_scores'] = attention_probs + + return output_states, extra_output class PositionWiseFF(nn.Module): diff --git a/nemo/collections/asr/modules/wav2vec_modules.py b/nemo/collections/asr/modules/wav2vec_modules.py index d1f5b090d4e1ac4341695846631e59c8f5a66212..e823943de4e2650ea5e283b234fcb526c6d34b44 100644 --- a/nemo/collections/asr/modules/wav2vec_modules.py +++ b/nemo/collections/asr/modules/wav2vec_modules.py @@ -19,7 +19,7 @@ import math import random -from typing import Dict, List, Tuple +from typing import Dict, List import torch from omegaconf import DictConfig @@ -27,8 +27,8 @@ 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.collections.nlp.modules.common.transformer import TransformerEncoder from nemo.core.classes.module import NeuralModule from nemo.core.neural_types import AcousticEncodedRepresentation, AudioSignal, LengthsType, NeuralType, SpectrogramType @@ -55,10 +55,10 @@ class SamePad(torch.nn.Module): 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.) + 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 @@ -78,7 +78,7 @@ class ConvFeatureEncoder(NeuralModule): @property def output_types(self): - """Returns definitions of module output ports. + """Returns definitions of module output ports. For compatibility, processed features are treated as Spectrogram types processed_signal: 0: AxisType(BatchTag) @@ -107,7 +107,13 @@ class ConvFeatureEncoder(NeuralModule): self.normalize_input = normalize_audio def block( - n_in, n_out, k, stride, is_layer_norm=False, is_group_norm=False, conv_bias=False, + 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) @@ -123,7 +129,11 @@ class ConvFeatureEncoder(NeuralModule): nn.GELU(), ) elif is_group_norm: - return nn.Sequential(make_conv(), nn.GroupNorm(dim, dim, affine=True), nn.GELU(),) + return nn.Sequential( + make_conv(), + nn.GroupNorm(dim, dim, affine=True), + nn.GELU(), + ) else: return nn.Sequential(make_conv(), nn.GELU()) @@ -213,34 +223,34 @@ class ConvFeatureEncoder(NeuralModule): 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 + 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): @@ -271,7 +281,7 @@ class Wav2VecTransformerEncoder(TransformerEncoder): @property def input_types(self): - """Returns definitions of module output ports. + """Returns definitions of module output ports. We treat features as SpectrogramType for Nemo compatibility audio_signal: 0: AxisType(BatchTag) @@ -287,7 +297,7 @@ class Wav2VecTransformerEncoder(TransformerEncoder): @property def output_types(self): - """Returns definitions of module output ports. + """Returns definitions of module output ports. We're using SpectrogramType for now to keep things Nemo safe processed_signal: 0: AxisType(BatchTag) diff --git a/nemo/collections/asr/parts/context_biasing/__init__.py b/nemo/collections/asr/parts/context_biasing/__init__.py index 506dc70c5dea8d6cc97ddb475977b55cc711afc8..93bd6116a8742b0248f9bd9e247e5a6aface355d 100644 --- a/nemo/collections/asr/parts/context_biasing/__init__.py +++ b/nemo/collections/asr/parts/context_biasing/__init__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -12,9 +12,22 @@ # 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 new file mode 100644 index 0000000000000000000000000000000000000000..c4032035f9927478ca5c1f0cec8c2aef6726dd17 --- /dev/null +++ b/nemo/collections/asr/parts/context_biasing/biasing_multi_model.py @@ -0,0 +1,719 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..a7cd54714bd0ca49ae79e0a18b9615882fefaea7 --- /dev/null +++ b/nemo/collections/asr/parts/context_biasing/boosting_graph_batched.py @@ -0,0 +1,615 @@ +# 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 index f168d92bdbc716e3cab8b853e0efd6b83b0b6755..141ac0cdd4c39d9a64b0544ae7a39caf00134af6 100644 --- a/nemo/collections/asr/parts/context_biasing/context_biasing_utils.py +++ b/nemo/collections/asr/parts/context_biasing/context_biasing_utils.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -11,13 +11,12 @@ # WITHOUT 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 -import texterrors +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 @@ -150,7 +149,10 @@ def merge_alignment_with_ws_hyps( def compute_fscore( - recognition_results_manifest: str, key_words_list: List, eps: str = "" + 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. @@ -161,7 +163,7 @@ def compute_fscore( 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 ('' in case of texterrors aligner). + eps: epsilon symbol for alignment. Returns: Returns tuple of precision, recall and fscore. """ @@ -185,10 +187,7 @@ def compute_fscore( # get alignment by texterrors ref = item['text'].split() hyp = item['pred_text'].split() - texterrors_ali = texterrors.align_texts(ref, hyp, False) - ali = [] - for i in range(len(texterrors_ali[0])): - ali.append((texterrors_ali[0][i], texterrors_ali[1][i])) + ali = align(ref, hyp, eps) # 1-grams for idx in range(len(ali)): @@ -252,22 +251,25 @@ def compute_fscore( recall = tp / (gt + 1e-8) fscore = 2 * (precision * recall) / (precision + recall + 1e-8) - logging.info("=" * 60) - logging.info("Per words statistic (word: correct/totall | false positive):\n") + 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] - logging.info( - f"{word:>{max_len}}: {key_words_stat[word][0]:3}/{key_words_stat[word][1]:<3} |{false_positive:>3}" - ) - 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) + 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 index bcfcdf2435f13b85f049feb9e2bc905032bb07d9..b0282efa4d4eea20c8bb99ccecdb5cc04e53b89c 100644 --- a/nemo/collections/asr/parts/context_biasing/context_graph_ctc.py +++ b/nemo/collections/asr/parts/context_biasing/context_graph_ctc.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -47,7 +47,10 @@ class ContextState: """The state in ContextGraph""" def __init__( - self, index: int, is_end: bool = False, word: Optional[str] = None, + self, + index: int, + is_end: bool = False, + word: Optional[str] = None, ): """Create a ContextState. Args: @@ -86,14 +89,14 @@ class ContextGraphCTC: 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[tuple[str, int]]]]]): + 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 BPE word tokenizations + tokenizations: a list of possible BPE word tokenizations (each word can have several tokenizations to improve the recognition accuracy) """ @@ -154,7 +157,11 @@ class ContextGraphCTC: 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": + 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 diff --git a/nemo/collections/asr/parts/context_biasing/context_graph_universal.py b/nemo/collections/asr/parts/context_biasing/context_graph_universal.py new file mode 100644 index 0000000000000000000000000000000000000000..5671f5bdd90afe31957b77428d6f60cdc431dd19 --- /dev/null +++ b/nemo/collections/asr/parts/context_biasing/context_graph_universal.py @@ -0,0 +1,389 @@ +# 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 index ac6e19bd19d177f3144458031261ec56a40e18c6..d9240eec8d8dc9b15603ead550cc43a2d8e08f8f 100644 --- a/nemo/collections/asr/parts/context_biasing/ctc_based_word_spotter.py +++ b/nemo/collections/asr/parts/context_biasing/ctc_based_word_spotter.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -57,9 +57,9 @@ class WSHyp: 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 @@ -77,10 +77,10 @@ def beam_pruning(next_tokens: List[Token], beam_threshold: float) -> List[Token] 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 """ @@ -149,7 +149,7 @@ def find_best_hyps(spotted_words: List[WSHyp], intersection_threshold: int = 10) 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. @@ -224,9 +224,9 @@ def filter_wb_hyps(best_hyp_list: List[WSHyp], word_alignment: List[tuple]) -> L Args: best_hyp_list: list of spotted hypotheses WSHyp word_alignment: world level ctc alignment with word scores - + Returns: - filtered best_hyp_list + filtered best_hyp_list """ if not word_alignment: @@ -279,8 +279,8 @@ def run_word_spotter( 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. - + The algorithm is implemented in log semiring. + Args: logprobs: CTC logprobs for one file [Time, Vocab+blank] context_graph: Context-Biasing graph diff --git a/nemo/collections/asr/parts/k2/classes.py b/nemo/collections/asr/parts/k2/classes.py deleted file mode 100644 index d4c498f32a2dd88888636574b37982b372d55180..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/k2/classes.py +++ /dev/null @@ -1,170 +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 -from dataclasses import dataclass, field -from typing import Any, Optional, Tuple - -import torch -from omegaconf import DictConfig - -from nemo.utils import logging - - -@dataclass -class GraphIntersectDenseConfig: - """Graph dense intersection config. - """ - - search_beam: float = 20.0 - output_beam: float = 10.0 - min_active_states: int = 30 - max_active_states: int = 10000 - - -@dataclass -class GraphModuleConfig: - """Config for graph modules. - Typically used with graph losses and decoders. - """ - - topo_type: str = "default" - topo_with_self_loops: bool = True - token_lm: Optional[Any] = None - intersect_pruned: bool = False - intersect_conf: GraphIntersectDenseConfig = field(default_factory=lambda: GraphIntersectDenseConfig()) - boost_coeff: float = 0.0 - predictor_window_size: int = 0 - predictor_step_size: int = 1 - - -class ASRK2Mixin(ABC): - """k2 Mixin class that simplifies the construction of various models with k2-based losses. - - It does the following: - - Sets up the graph loss and decoder (methods _init_k2 and update_k2_modules). - - Registers external graphs, if needed. - - Augments forward(...) with optional graph decoding to get accurate predictions. - """ - - def _init_k2(self): - """ - k2-related initialization implementation. - - This method is expected to run after the __init__ which sets self._cfg - self._cfg is expected to have the attribute graph_module_cfg - """ - if not hasattr(self, "_cfg"): - raise ValueError("self._cfg must be set before calling _init_k2().") - if not hasattr(self._cfg, "graph_module_cfg") or self._cfg.graph_module_cfg is None: - raise ValueError("self._cfg.graph_module_cfg must be set and cannot be None.") - self.graph_module_cfg = self._cfg.graph_module_cfg - - # register token_lm for MAPLoss - criterion_type = self.graph_module_cfg.get("criterion_type", "ml") - self.use_graph_lm = criterion_type == "map" - if self.use_graph_lm: - token_lm_path = self.graph_module_cfg.backend_cfg.get("token_lm", None) - if token_lm_path is None: - raise ValueError( - f"graph_module_cfg.backend_cfg.token_lm is empty. It must be set for criterion_type == `{criterion_type}`" - ) - token_lm_path = self.register_artifact('graph_module_cfg.backend_cfg.token_lm', token_lm_path) - self.graph_module_cfg.backend_cfg["token_lm"] = token_lm_path - - self.update_k2_modules(self.graph_module_cfg) - - def update_k2_modules(self, input_cfg: DictConfig): - """ - Helper function to initialize or update k2 loss and transcribe_decoder. - - Args: - input_cfg: DictConfig to take new parameters from. Schema is expected as in - nemo.collections.asr.models.configs.k2_sequence_models_config.GraphModuleConfig - """ - del self.loss - if hasattr(self, "transcribe_decoder"): - del self.transcribe_decoder - - if hasattr(self, "joint"): - # RNNT - num_classes = self.joint.num_classes_with_blank - 1 - else: - # CTC, MMI, ... - num_classes = self.decoder.num_classes_with_blank - 1 - remove_consecutive = input_cfg.backend_cfg.get("topo_with_self_loops", True) and input_cfg.backend_cfg.get( - "topo_type", "default" - ) not in ["forced_blank", "identity",] - self._wer.remove_consecutive = remove_consecutive - - from nemo.collections.asr.losses.lattice_losses import LatticeLoss - - self.loss = LatticeLoss( - num_classes=num_classes, - reduction=self._cfg.get("ctc_reduction", "mean_batch"), - backend="k2", - criterion_type=input_cfg.get("criterion_type", "ml"), - loss_type=input_cfg.get("loss_type", "ctc"), - split_batch_size=input_cfg.get("split_batch_size", 0), - graph_module_cfg=input_cfg.backend_cfg, - ) - - criterion_type = self.loss.criterion_type - self.use_graph_lm = criterion_type == "map" - transcribe_training = input_cfg.get("transcribe_training", False) - if transcribe_training and criterion_type == "ml": - logging.warning( - f"""You do not need to use transcribe_training=`{transcribe_training}` - with criterion_type=`{criterion_type}`. transcribe_training will be set to False.""" - ) - transcribe_training = False - self.transcribe_training = transcribe_training - if self.use_graph_lm: - from nemo.collections.asr.modules.graph_decoder import ViterbiDecoderWithGraph - - self.transcribe_decoder = ViterbiDecoderWithGraph( - num_classes=num_classes, - backend="k2", - dec_type="token_lm", - return_type="1best", - return_ilabels=True, - output_aligned=True, - split_batch_size=input_cfg.get("split_batch_size", 0), - graph_module_cfg=input_cfg.backend_cfg, - ) - - def _forward_k2_post_processing( - self, log_probs: torch.Tensor, encoded_length: torch.Tensor, greedy_predictions: torch.Tensor - ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: - """ - k2-related post-processing parf of .forward() - - Args: - log_probs: The log probabilities tensor of shape [B, T, D]. - encoded_length: The lengths of the acoustic sequence after propagation through the encoder, of shape [B]. - greedy_predictions: The greedy token predictions of the model of shape [B, T] - - 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) - """ - # greedy_predictions from .forward() are incorrect for criterion_type=`map` - # getting correct greedy_predictions, if needed - if self.use_graph_lm and (not self.training or self.transcribe_training): - greedy_predictions, encoded_length, _ = self.transcribe_decoder.forward( - log_probs=log_probs, log_probs_length=encoded_length - ) - return log_probs, encoded_length, greedy_predictions diff --git a/nemo/collections/asr/parts/k2/grad_utils.py b/nemo/collections/asr/parts/k2/grad_utils.py deleted file mode 100644 index 6278fb9c86caf28f7ae26e82250d632935eef0dd..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/k2/grad_utils.py +++ /dev/null @@ -1,93 +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 - -from nemo.collections.asr.parts.k2.utils import make_non_pad_mask - - -class GradExpNormalize(torch.autograd.Function): - """Function for fast gradient normalization. - Typical use case is normalization for mle loss. - """ - - @staticmethod - def forward( - ctx, log_probs: torch.Tensor, input_lengths: torch.Tensor, reduction: str = "mean", - ): - mask = make_non_pad_mask(input_lengths, log_probs.shape[1]) - probs = log_probs.exp() - norm_probs = torch.zeros_like(log_probs) - norm_probs[mask] += probs[mask] - if reduction == "mean": - norm_probs /= norm_probs.shape[0] - ctx.save_for_backward(norm_probs) - return log_probs - - @staticmethod - def backward(ctx, grad_output: torch.Tensor): - return grad_output - grad_output.sum(-1).unsqueeze(-1) * ctx.saved_tensors[0], None, None - - -class GradInsert(torch.autograd.Function): - """Function to attach a pre-computed gradient to a tensor. - Typical use case is gradient computation before calling loss.backward(). - """ - - @staticmethod - def forward( - ctx, input_tensor: torch.Tensor, output_tensor: torch.Tensor, grad: torch.Tensor, mask: torch.Tensor, - ): - assert input_tensor.requires_grad - assert not output_tensor.requires_grad and not grad.requires_grad - - ctx.save_for_backward(grad, mask) - return output_tensor - - @staticmethod - def backward(ctx, grad_output: torch.Tensor): - saved_grad, mask = ctx.saved_tensors - # TODO (alaptev): make it work for grad_output with arbitrary shape - padded_grad_output = torch.zeros(saved_grad.shape[0], dtype=grad_output.dtype, device=grad_output.device) - padded_grad_output[mask] = grad_output - return (padded_grad_output * saved_grad.T).T, None, None, None - - -class PartialGrad(torch.nn.Module): - """Module for partial gradient computation. - Useful when computing loss on batch splits to save memory. - """ - - def __init__(self, func: torch.nn.Module): - super().__init__() - self.func = func - - def forward( - self, - input_tensor: torch.Tensor, - targets: torch.Tensor, - input_lengths: torch.Tensor, - target_lengths: torch.Tensor, - ): - # break the gradient chain - loc_tensor = input_tensor.detach() - loc_tensor.requires_grad_(True) - - new_tensor, mask = self.func(loc_tensor, targets, input_lengths, target_lengths) - loc_new_tensor = new_tensor.detach() - - new_tensor.sum().backward() - grad = loc_tensor.grad - - return GradInsert.apply(input_tensor, loc_new_tensor, grad, mask), mask diff --git a/nemo/collections/asr/parts/k2/graph_compilers.py b/nemo/collections/asr/parts/k2/graph_compilers.py deleted file mode 100644 index 8b82dcf5cc0f46d17d2c21c7591b4b4f75aed019..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/k2/graph_compilers.py +++ /dev/null @@ -1,191 +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) 2020, Xiaomi CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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, Tuple - -import torch - -from nemo.collections.asr.parts.k2.utils import add_self_loops, compose_with_self_loops, intersect_with_self_loops - -from nemo.core.utils.k2_guard import k2 # import k2 from guard module - - -class CtcTopologyCompiler(object): - """Default graph compiler. - It applies its topology to the input token sequence to compile the supervision graph. - - Based on https://github.com/k2-fsa/snowfall/blob/master/snowfall/training/ctc_graph.py - """ - - def __init__( - self, - num_classes: int, - blank: int, - topo_type: str = "default", - topo_with_self_loops: bool = True, - device: torch.device = torch.device("cpu"), - ): - self.topo_type = topo_type - self.device = device - from nemo.collections.asr.parts.k2.topologies import build_topo - - self.base_graph = k2.arc_sort(build_topo(topo_type, list(range(num_classes)), blank, topo_with_self_loops)).to( - self.device - ) - self.ctc_topo_inv = k2.arc_sort(self.base_graph.invert()) - - def to(self, device: torch.device): - self.ctc_topo_inv = self.ctc_topo_inv.to(device) - if self.base_graph is not None: - self.base_graph = self.base_graph.to(device) - self.device = device - - def compile(self, targets: torch.Tensor, target_lengths: torch.Tensor) -> 'k2.Fsa': - token_ids_list = [t[:l].tolist() for t, l in zip(targets, target_lengths)] - label_graph = k2.linear_fsa(token_ids_list).to(self.device) - label_graph.aux_labels = label_graph.labels.clone() - supervision_graphs = compose_with_self_loops(self.base_graph, label_graph) - supervision_graphs = k2.arc_sort(supervision_graphs).to(self.device) - - # make sure the gradient is not accumulated - supervision_graphs.requires_grad_(False) - return supervision_graphs - - -class CtcNumGraphCompiler(CtcTopologyCompiler): - """Graph compiler with auxiliary graph to compose with the topology. - The supervision graph contains the auxiliary graph information. - """ - - def __init__( - self, - num_classes: int, - blank: int, - topo_type: str = "default", - topo_with_self_loops: bool = True, - device: torch.device = torch.device("cpu"), - aux_graph: Optional['k2.Fsa'] = None, - ): - super().__init__(num_classes, blank, topo_type, topo_with_self_loops, device) - if aux_graph is None: - self.decoding_graph = k2.create_fsa_vec([self.ctc_topo_inv.invert()]).to(self.device) - else: - self.base_graph = intersect_with_self_loops(self.ctc_topo_inv, aux_graph).invert_() - self.base_graph = k2.arc_sort(self.base_graph).to(self.device) - - def compile( - self, targets: torch.Tensor, target_lengths: torch.Tensor, aux_graph: Optional['k2.Fsa'] = None, - ) -> 'k2.Fsa': - if aux_graph is None and self.base_graph is None: - raise ValueError( - f"At least one of aux_graph and self.base_graph must be set: {aux_graph}, {self.base_graph}" - ) - elif aux_graph is not None: - self.base_graph = intersect_with_self_loops(self.ctc_topo_inv, aux_graph).invert() - self.base_graph = k2.arc_sort(self.base_graph).to(self.device) - return super().compile(targets, target_lengths) - - -class MmiGraphCompiler(CtcNumGraphCompiler): - """Graph compiler for MMI loss. - The decoding graph is a composition of the auxiliary graph and the topology. - It is returned along with the supervision graph on every compile() call. - """ - - def __init__( - self, - num_classes: int, - blank: int, - topo_type: str = "default", - topo_with_self_loops: bool = True, - device: torch.device = torch.device("cpu"), - aux_graph: Optional['k2.Fsa'] = None, - ): - super().__init__(num_classes, blank, topo_type, topo_with_self_loops, device, aux_graph) - if aux_graph is None: - self.decoding_graph = k2.create_fsa_vec([self.ctc_topo_inv.invert()]).to(self.device) - else: - self.decoding_graph = k2.create_fsa_vec([self.base_graph.detach()]).to(self.device) - - def to(self, device: torch.device): - if self.decoding_graph is not None: - self.decoding_graph = self.decoding_graph.to(device) - super().to(device) - - def compile( - self, targets: torch.Tensor, target_lengths: torch.Tensor, aux_graph: Optional['k2.Fsa'] = None, - ) -> Tuple['k2.Fsa', 'k2.Fsa']: - supervision_graphs = super().compile(targets, target_lengths, aux_graph) - if aux_graph is None and self.decoding_graph is None: - raise ValueError( - f"At least one of aux_graph and self.decoding_graph must be set: {aux_graph}, {self.decoding_graph}" - ) - elif aux_graph is not None: - self.decoding_graph = k2.create_fsa_vec([self.base_graph.detach()]).to(self.device) - return supervision_graphs, self.decoding_graph - - -class RnntTopologyCompiler(CtcTopologyCompiler): - """Default graph compiler for RNNT loss. - Each supervision graph is composed with the corresponding RNNT emission adapter. - - If max_adapter_length is provided, the maximum adapter length is limited. - - Note: - The actual number of classes is `num_classes` + 1 with as the class 0. - - Warning: - It is currently not recommended to use topologies other than "minimal". - """ - - def __init__( - self, - num_classes: int, - blank: int, - topo_type: str = "minimal", - topo_with_self_loops: bool = True, - device: torch.device = torch.device("cpu"), - max_adapter_length: int = 0, - ): - if topo_type == "compact": - raise NotImplementedError(f"This compiler does not support topo_type==`compact`.") - super().__init__(num_classes, blank, topo_type, topo_with_self_loops, device) - from nemo.collections.asr.parts.k2.topologies import RnntEmissionAdapterBuilder - - self.max_adapter_length = max_adapter_length - self._builder = RnntEmissionAdapterBuilder(list(range(num_classes)), blank, num_classes) - - def compile(self, targets: torch.Tensor, target_lengths: torch.Tensor) -> 'k2.Fsa': - supervision_graphs = add_self_loops(super().compile(targets, target_lengths), self._builder.eps_num, "input") - - adapters = self._builder( - torch.where(target_lengths > self.max_adapter_length, self.max_adapter_length, target_lengths) - if self.max_adapter_length > 0 and self.max_adapter_length < target_lengths.max() - else target_lengths - ).to(device=self.device) - return k2.intersect(adapters, supervision_graphs, treat_epsilons_specially=False) diff --git a/nemo/collections/asr/parts/k2/graph_decoders.py b/nemo/collections/asr/parts/k2/graph_decoders.py deleted file mode 100644 index 981025e7c418be621847411cabca8c12ae6b18b8..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/k2/graph_decoders.py +++ /dev/null @@ -1,686 +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 abstractmethod -from collections import defaultdict -from pathlib import Path -from typing import List, Optional, Tuple, Union - -import torch -from jiwer import wer as word_error_rate -from omegaconf import DictConfig - -from nemo.collections.asr.parts.k2.classes import GraphIntersectDenseConfig -from nemo.collections.asr.parts.k2.loss_mixins import CtcK2Mixin, RnntK2Mixin -from nemo.collections.asr.parts.k2.utils import ( - create_supervision, - invert_permutation, - levenshtein_graph_k2, - load_graph, -) -from nemo.collections.asr.parts.submodules.wfst_decoder import ( - AbstractWFSTDecoder, - WfstNbestHypothesis, - collapse_tokenword_hypotheses, -) -from nemo.core.utils.k2_guard import k2 -from nemo.utils import logging - - -class BaseDecoder(object): - """Base graph decoder with topology for decoding graph. - Typically uses the same parameters as for the corresponding loss function. - - Can do decoding and forced alignment. - - cfg takes precedence over all optional parameters - We keep explicit parameter setting to be able to create an instance without the need of a config. - """ - - @abstractmethod - def __init__( - self, - num_classes: int, - blank: int, - cfg: Optional[DictConfig] = None, - intersect_pruned: bool = False, - intersect_conf: GraphIntersectDenseConfig = GraphIntersectDenseConfig(), - topo_type: str = "default", - topo_with_self_loops: bool = True, - device: torch.device = torch.device("cpu"), - ): - - if cfg is not None: - intersect_pruned = cfg.get("intersect_pruned", intersect_pruned) - intersect_conf = cfg.get("intersect_conf", intersect_conf) - topo_type = cfg.get("topo_type", topo_type) - topo_with_self_loops = cfg.get("topo_with_self_loops", topo_with_self_loops) - - self.num_classes = num_classes - self.blank = blank - self.intersect_pruned = intersect_pruned - self.device = device - self.topo_type = topo_type - self.topo_with_self_loops = topo_with_self_loops - self.pad_fsavec = self.topo_type == "ctc_compact" - self.intersect_conf = intersect_conf - self.graph_compiler = None # expected to be initialized in child classes - self.base_graph = None # expected to be initialized in child classes - self.decoding_graph = None - - def to(self, device: torch.device): - if self.graph_compiler.device != device: - self.graph_compiler.to(device) - if self.base_graph.device != device: - self.base_graph = self.base_graph.to(device) - if self.decoding_graph is not None and self.decoding_graph.device != device: - self.decoding_graph = self.decoding_graph.to(device) - self.device = device - - def update_graph(self, graph: 'k2.Fsa'): - raise NotImplementedError - - def _decode_impl( - self, - log_probs: torch.Tensor, - supervisions: torch.Tensor, - return_lattices: bool = False, - return_ilabels: bool = False, - output_aligned: bool = True, - ) -> Union['k2.Fsa', Tuple[List[torch.Tensor], List[torch.Tensor]]]: - if self.decoding_graph is None: - self.decoding_graph = self.base_graph - - if log_probs.device != self.device: - self.to(log_probs.device) - emissions_graphs = self._prepare_emissions_graphs(log_probs, supervisions) - - if self.intersect_pruned: - lats = k2.intersect_dense_pruned( - a_fsas=self.decoding_graph, - b_fsas=emissions_graphs, - search_beam=self.intersect_conf.search_beam, - output_beam=self.intersect_conf.output_beam, - min_active_states=self.intersect_conf.min_active_states, - max_active_states=self.intersect_conf.max_active_states, - ) - else: - indices = torch.zeros(emissions_graphs.dim0(), dtype=torch.int32, device=self.device) - dec_graphs = ( - k2.index_fsa(self.decoding_graph, indices) - if self.decoding_graph.shape[0] == 1 - else self.decoding_graph - ) - lats = k2.intersect_dense(dec_graphs, emissions_graphs, self.intersect_conf.output_beam) - self.decoding_graph = None - - order = supervisions[:, 0] - if return_lattices: - lats = k2.index_fsa(lats, invert_permutation(order).to(device=log_probs.device)) - if self.blank != 0: - # change only ilabels - # suppose self.blank == self.num_classes - 1 - lats.labels = torch.where(lats.labels == 0, self.blank, lats.labels - 1) - return lats - else: - shortest_path_fsas = k2.index_fsa( - k2.shortest_path(lats, True), - invert_permutation(order).to(device=log_probs.device), - ) - return self._extract_labels_and_probabilities(shortest_path_fsas, return_ilabels, output_aligned) - - def decode( - self, - log_probs: torch.Tensor, - log_probs_length: torch.Tensor, - return_lattices: bool = False, - return_ilabels: bool = False, - output_aligned: bool = True, - ) -> Union['k2.Fsa', Tuple[List[torch.Tensor], List[torch.Tensor]]]: - log_probs, supervisions, _, _ = self._prepare_log_probs_and_targets(log_probs, log_probs_length, None, None) - return self._decode_impl( - log_probs, - supervisions, - return_lattices=return_lattices, - return_ilabels=return_ilabels, - output_aligned=output_aligned, - ) - - def align( - self, - log_probs: torch.Tensor, - log_probs_length: torch.Tensor, - targets: torch.Tensor, - target_lengths: torch.Tensor, - return_lattices: bool = False, - return_ilabels: bool = False, - output_aligned: bool = True, - ) -> Tuple[List[torch.Tensor], List[torch.Tensor]]: - log_probs, supervisions, targets, target_lengths = self._prepare_log_probs_and_targets( - log_probs, log_probs_length, targets, target_lengths - ) - order = supervisions[:, 0].to(dtype=torch.long) - self.decoding_graph = self.graph_compiler.compile(targets[order], target_lengths[order]) - return self._decode_impl( - log_probs, - supervisions, - return_lattices=return_lattices, - return_ilabels=return_ilabels, - output_aligned=output_aligned, - ) - - -class CtcDecoder(BaseDecoder, CtcK2Mixin): - """Regular CTC graph decoder with custom topologies. - Available topologies: - - `default`, with or without self-loops - - `compact`, with or without self-loops - - `shared_blank`, with or without self-loops - - `minimal`, without self-loops - - Can do decoding and forced alignment. - """ - - def __init__( - self, - num_classes: int, - blank: int, - cfg: Optional[DictConfig] = None, - intersect_pruned: bool = False, - intersect_conf: GraphIntersectDenseConfig = GraphIntersectDenseConfig(), - topo_type: str = "default", - topo_with_self_loops: bool = True, - device: torch.device = torch.device("cpu"), - ): - super().__init__( - num_classes, blank, cfg, intersect_pruned, intersect_conf, topo_type, topo_with_self_loops, device - ) - from nemo.collections.asr.parts.k2.graph_compilers import CtcTopologyCompiler - - self.graph_compiler = CtcTopologyCompiler( - self.num_classes, self.blank, self.topo_type, self.topo_with_self_loops, self.device - ) - self.base_graph = k2.create_fsa_vec([self.graph_compiler.ctc_topo_inv.invert()]).to(self.device) - - -class RnntAligner(BaseDecoder, RnntK2Mixin): - """RNNT graph decoder with the `minimal` topology. - If predictor_window_size is not provided, this decoder works as a Viterbi over regular RNNT lattice. - With predictor_window_size provided, it applies uniform pruning when compiling Emission FSAs - to reduce memory and compute consumption. - - Can only do forced alignment. - """ - - def __init__( - self, - num_classes: int, - blank: int, - cfg: Optional[DictConfig] = None, - intersect_pruned: bool = False, - intersect_conf: GraphIntersectDenseConfig = GraphIntersectDenseConfig(), - topo_type: str = "default", - topo_with_self_loops: bool = True, - predictor_window_size: int = 0, - predictor_step_size: int = 1, - device: torch.device = torch.device("cpu"), - ): - if cfg is not None: - topo_type = cfg.get("topo_type", topo_type) - predictor_window_size = cfg.get("predictor_window_size", predictor_window_size) - predictor_step_size = cfg.get("predictor_step_size", predictor_step_size) - if topo_type != "minimal": - raise NotImplementedError(f"Only topo_type=`minimal` is supported at the moment.") - super().__init__( - num_classes, blank, cfg, intersect_pruned, intersect_conf, topo_type, topo_with_self_loops, device - ) - self.predictor_window_size = predictor_window_size - self.predictor_step_size = predictor_step_size - from nemo.collections.asr.parts.k2.graph_compilers import RnntTopologyCompiler - - self.graph_compiler = RnntTopologyCompiler( - self.num_classes, - self.blank, - self.topo_type, - self.topo_with_self_loops, - self.device, - max_adapter_length=self.predictor_window_size, - ) - self.base_graph = self.graph_compiler.base_graph - - def decode( - self, - log_probs: torch.Tensor, - log_probs_length: torch.Tensor, - return_lattices: bool = False, - return_ilabels: bool = False, - output_aligned: bool = True, - ) -> Union['k2.Fsa', Tuple[List[torch.Tensor], List[torch.Tensor]]]: - raise NotImplementedError("RNNT decoding is not implemented. Only .align(...) method is supported.") - - def align( - self, - log_probs: torch.Tensor, - log_probs_length: torch.Tensor, - targets: torch.Tensor, - target_lengths: torch.Tensor, - return_lattices: bool = False, - return_ilabels: bool = False, - output_aligned: bool = True, - ) -> Tuple[List[torch.Tensor], List[torch.Tensor]]: - assert self.predictor_window_size == 0 or log_probs.size(2) <= self.predictor_window_size + 1 - - return super().align( - log_probs, - log_probs_length, - targets, - target_lengths, - return_lattices=return_lattices, - return_ilabels=return_ilabels, - output_aligned=output_aligned, - ) - - -class TokenLMDecoder(BaseDecoder): - """Graph decoder with token_lm-based decoding graph. - Available topologies: - - `default`, with or without self-loops - - `compact`, with or without self-loops - - `shared_blank`, with or without self-loops - - `minimal`, without self-loops - - Can do decoding and forced alignment. - - cfg takes precedence over all optional parameters - We keep explicit parameter setting to be able to create an instance without the need of a config. - """ - - def __init__( - self, - num_classes: int, - blank: int, - cfg: Optional[DictConfig] = None, - token_lm: Optional[Union['k2.Fsa', str]] = None, - intersect_pruned: bool = False, - intersect_conf: GraphIntersectDenseConfig = GraphIntersectDenseConfig(), - topo_type: str = "default", - topo_with_self_loops: bool = True, - device: torch.device = torch.device("cpu"), - ): - super().__init__( - num_classes, blank, cfg, intersect_pruned, intersect_conf, topo_type, topo_with_self_loops, device - ) - if cfg is not None: - token_lm = cfg.get("token_lm", token_lm) - if token_lm is not None: - self.token_lm = load_graph(token_lm) if isinstance(token_lm, str) else token_lm - if self.token_lm is not None: - self.update_graph(self.token_lm) - else: - logging.warning( - f"""token_lm was set to None. Use this for debug - purposes only or call .update_graph(token_lm) before using.""" - ) - else: - logging.warning( - f"""token_lm was set to None. Use this for debug - purposes only or call .update_graph(token_lm) before using.""" - ) - self.token_lm = None - - def update_graph(self, graph: 'k2.Fsa'): - self.token_lm = graph - token_lm = self.token_lm.clone() - if hasattr(token_lm, "aux_labels"): - delattr(token_lm, "aux_labels") - labels = token_lm.labels - if labels.max() != self.num_classes - 1: - raise ValueError(f"token_lm is not compatible with the num_classes: {labels.unique()}, {self.num_classes}") - self.graph_compiler = CtcNumGraphCompiler( - self.num_classes, self.blank, self.topo_type, self.topo_with_self_loops, self.device, token_lm - ) - self.base_graph = k2.create_fsa_vec([self.graph_compiler.base_graph]).to(self.device) - - -class K2WfstDecoder(AbstractWFSTDecoder): - """ - Used for performing WFST decoding of the logprobs with the k2 WFST decoder. - - Args: - lm_fst: - Kaldi-type language model WFST or its path. - - decoding_mode: - Decoding mode. Choices: `nbest`, `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` - - device: - Device for running decoding. Choices: `cuda`, `cpu`. - """ - - def __init__( - self, - lm_fst: Union['k2.Fsa', Path, str], - decoding_mode: str = 'nbest', - beam_size: float = 10.0, - config: Optional[GraphIntersectDenseConfig] = None, - tokenword_disambig_id: int = -1, - lm_weight: float = 1.0, - nbest_size: int = 1, - device: str = "cuda", - ): - self._nbest_size = nbest_size - self._device = device - super().__init__(lm_fst, decoding_mode, beam_size, config, tokenword_disambig_id, lm_weight) - - def _set_decoder_config(self, config: Optional[GraphIntersectDenseConfig] = None): - if config is None: - config = GraphIntersectDenseConfig() - config.search_beam = 20.0 - config.output_beam = self._beam_size - config.max_active_states = 10000 - self._config = config - - def _set_decoding_mode(self, decoding_mode: str): - if decoding_mode not in ('nbest', 'lattice'): - raise ValueError(f"Unsupported mode: {decoding_mode}") - self._decoding_mode = decoding_mode - - @torch.inference_mode(False) - def _init_decoder(self): - lm_fst = load_graph(self._lm_fst) if isinstance(self._lm_fst, (Path, str)) else self._lm_fst.clone() - lm_fst.lm_scores = lm_fst.scores.clone() - self._lm_fst = lm_fst.to(device=self._device) - - if self._id2word is None: - self._id2word = { - int(line.split()[1]): line.split()[0] - for line in self._lm_fst.aux_labels_sym.to_str().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()[1]): line.split()[0] for line in self._lm_fst.labels_sym.to_str().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 - - def _beam_size_setter(self, value: float): - if self._beam_size != value: - self._config.output_beam = value - self._beam_size = value - - def _lm_weight_setter(self, value: float): - if self._lm_weight != value: - self._lm_weight = 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._nbest_size = value - - def _decoding_mode_setter(self, value: str): - if self._decoding_mode != value: - self._set_decoding_mode(value) - - @torch.inference_mode(False) - def _decode_lattice(self, emissions_fsas: 'k2.DenseFsaVec', order: torch.Tensor) -> 'k2.Fsa': - """ - Decodes logprobs into k2-type lattices. - - Args: - emissions_fsas: - A k2.DenseFsaVec of the predicted log-probabilities. - order: - A torch.Tensor that stores the order of the emissions_fsas elements. - - Returns: - k2-type FsaVec. - """ - lats = k2.intersect_dense_pruned( - a_fsas=self._lm_fst, - b_fsas=emissions_fsas, - search_beam=self._config.search_beam, - output_beam=self._config.output_beam, - min_active_states=self._config.min_active_states, - max_active_states=self._config.max_active_states, - frame_idx_name="frame_idx", - allow_partial=True, - ) - lats = k2.connect(k2.expand_ragged_attributes(lats)) - lats.am_scores = lats.scores - lats.lm_scores - if self._lm_weight != 1.0: - lats.scores = lats.am_scores + self._lm_weight * lats.lm_scores - # just in case - lats.__dict__["_properties"] = None - return k2.index_fsa(lats, invert_permutation(order).to(device=self._device)) - - @torch.inference_mode(False) - def decode( - self, log_probs: torch.Tensor, log_probs_length: torch.Tensor - ) -> Union[List[WfstNbestHypothesis], List['k2.Fsa']]: - """ - 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. - """ - supervisions = create_supervision(log_probs_length) - order = supervisions[:, 0] - emissions_fsas = k2.DenseFsaVec(log_probs.to(device=self._device), supervisions) - lats = self._decode_lattice(emissions_fsas, order) - hypotheses = self._post_decode(lats) - return hypotheses - - @torch.inference_mode(False) - def _post_decode(self, hypotheses: 'k2.Fsa') -> Union[List[WfstNbestHypothesis], List['k2.Fsa']]: - """ - Does various post-processing of the recognition hypotheses. - - Args: - hypotheses: - FsaVec of k2-type lattices. - - Returns: - List of processed recognition hypotheses. - """ - if self._decoding_mode == 'nbest': - hypotheses_fsa = hypotheses - hypotheses = [] - if self._nbest_size == 1: - shortest_path_fsas = k2.shortest_path(hypotheses_fsa, True) - scores = shortest_path_fsas.get_tot_scores(True, False).tolist() - # direct iterating does not work as expected - for i in range(shortest_path_fsas.shape[0]): - fsa = shortest_path_fsas[i] - non_eps_mask = fsa.aux_labels > 0 - words = [self._id2word[l] for l in fsa.aux_labels[non_eps_mask].tolist()] - alignment = fsa.labels[fsa.labels > 0].tolist() - # some timesteps may be 0 if self.open_vocabulary_decoding - timesteps = fsa.frame_idx[non_eps_mask] - timesteps_left = timesteps[:-1] - timesteps_right = timesteps[1:] - timesteps_right_zero_mask = timesteps_right == 0 - timesteps_right[timesteps_right_zero_mask] = timesteps_left[timesteps_right_zero_mask] - timesteps[1:] = timesteps_right - timesteps = timesteps.tolist() - hypotheses.append( - WfstNbestHypothesis( - tuple( - [ - tuple([tuple(words), tuple(timesteps), tuple(alignment), -scores[i]]), - ] - ) - ) - ) - else: - nbest_fsas = k2.Nbest.from_lattice(hypotheses_fsa, self._nbest_size) - nbest_fsas.fsa.frame_idx = k2.index_select(hypotheses_fsa.frame_idx, nbest_fsas.kept_path.values) - scores = nbest_fsas.fsa.get_tot_scores(True, False).tolist() - nbest_hypothesis_list = [[] for _ in range(nbest_fsas.shape.dim0)] - for i, j in enumerate(nbest_fsas.shape.row_ids(1)): - fsa = nbest_fsas.fsa[i] - non_eps_mask = fsa.aux_labels > 0 - words = [self._id2word[l] for l in fsa.aux_labels[non_eps_mask].tolist()] - alignment = fsa.labels[fsa.labels > 0].tolist() - # some timesteps may be 0 if self.open_vocabulary_decoding - timesteps = fsa.frame_idx[non_eps_mask] - timesteps_left = timesteps[:-1] - timesteps_right = timesteps[1:] - timesteps_right_zero_mask = timesteps_right == 0 - timesteps_right[timesteps_right_zero_mask] = timesteps_left[timesteps_right_zero_mask] - timesteps[1:] = timesteps_right - timesteps = timesteps.tolist() - nbest_hypothesis_list[j].append( - tuple([tuple(words), tuple(timesteps), tuple(alignment), -scores[i]]) - ) - for nbest_hypothesis in nbest_hypothesis_list: - hypotheses.append(WfstNbestHypothesis(tuple(nbest_hypothesis))) - return ( - collapse_tokenword_hypotheses(hypotheses, self._id2word[self._tokenword_disambig_id]) - if self._open_vocabulary_decoding - else hypotheses - ) - else: - return [hypotheses[i].to(device="cpu") for i in range(len(hypotheses))] - - @torch.inference_mode(False) - 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 - nbest_size_backup = self.nbest_size - self.decoding_mode = "lattice" - lattices = self.decode(log_probs, log_probs_length) - best_lm_weight, best_wer = -1.0, float('inf') - self.decoding_mode = "nbest" - self.nbest_size = 1 - for lm_weight in range(1, 21): # enough for most cases - lm_weight_act = lm_weight / 10 - for lat in lattices: - lat.scores = lat.am_scores + lm_weight_act * lat.lm_scores - hypotheses = self._post_decode(lattices) - wer = word_error_rate([" ".join(h[0].words) for h in hypotheses], reference_texts) - if wer < best_wer: - best_lm_weight, best_wer = lm_weight_act, wer - self.nbest_size = nbest_size_backup - self.decoding_mode = decoding_mode_backup - self.lm_weight = lm_weight_backup - return best_lm_weight, best_wer - - @torch.inference_mode(False) - 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) - word_ids = [[self._word2id[w] for w in text.split()] for text in reference_texts] - counts = torch.tensor([len(wid) for wid in word_ids]) - decoding_mode_backup = self.decoding_mode - self.decoding_mode = "lattice" - lattices = self.decode(log_probs, log_probs_length) - oracle_disambig = max(self._id2word.keys()) + 1 - lattices.aux_labels[lattices.aux_labels == 0] = oracle_disambig - lattices = lattices.invert() - delattr(lattices, 'aux_labels') - hyps = levenshtein_graph_k2(lattices).invert() - refs = levenshtein_graph_k2(k2.linear_fsa(word_ids)) - refs, arc_map = k2.add_epsilon_self_loops(refs, ret_arc_map=True) - labels = refs.labels.clone() - labels[arc_map == -1] = oracle_disambig - refs.labels = labels - refs.__dict__["_properties"] = None - refs = k2.arc_sort(refs) - ali_lats = k2.compose(hyps, refs, treat_epsilons_specially=False) - ali_lats = k2.remove_epsilon_self_loops(ali_lats) - # TODO: find out why it fails for some utterances - try: - alignment = k2.shortest_path(ali_lats, use_double_scores=True) - except RuntimeError as e: - logging.warning("calculate_oracle_wer failed") - return -1.0, [] - scores = -alignment.get_tot_scores(True, True).to(dtype=torch.int64) - wer_per_utt = scores / counts - self.decoding_mode = decoding_mode_backup - return (scores.sum() / counts.sum()).item(), wer_per_utt.tolist() diff --git a/nemo/collections/asr/parts/k2/loss_mixins.py b/nemo/collections/asr/parts/k2/loss_mixins.py deleted file mode 100644 index ad8286e43e236c7bee8caa8e4d7a4a287d1e4d90..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/k2/loss_mixins.py +++ /dev/null @@ -1,233 +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 -from typing import List, Optional, Tuple - -import torch - -from nemo.collections.asr.parts.k2.grad_utils import GradExpNormalize -from nemo.collections.asr.parts.k2.utils import ( - create_supervision, - get_arc_weights, - get_uniform_rnnt_prune_ranges, - make_non_pad_mask, - make_non_pad_mask_3d, - prep_padded_densefsavec, -) -from nemo.core.utils.k2_guard import k2 # import k2 from guard module - - -class CtcK2Mixin(ABC): - """k2 Mixin class that simplifies the construction of various k2-based CTC-like losses. - - It does the following: - - Prepares and adapts the input tensors (method _prepare_log_probs_and_targets). - - Creates Emissions graphs (method _prepare_emissions_graphs). - - Extracts the labels and probabilities of the best lattice path (method _extract_labels_and_probabilities). - """ - - def _prepare_log_probs_and_targets( - self, - log_probs: torch.Tensor, - input_lengths: torch.Tensor, - targets: Optional[torch.Tensor] = None, - target_lengths: Optional[torch.Tensor] = None, - ) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor], Optional[torch.Tensor]]: - """Creates k2-style supervisions and shifts targets by one if the number is not zero. - """ - assert log_probs.size(-1) == self.num_classes - supervisions = create_supervision(input_lengths) - # shift targets to make output epsilon ID zero - return ( - log_probs, - supervisions, - torch.where(targets < self.blank, targets + 1, targets) if targets is not None else None, - target_lengths, - ) - - def _prepare_emissions_graphs(self, log_probs: torch.Tensor, supervisions: torch.Tensor) -> 'k2.DenseFsaVec': - """Creates DenseFsaVec, padding it with frames if the topology is `compact`. - In particular, every second frame of the DenseFsaVec is the frame. - - frame is a frame with log-probability zero and every other log-probability is -inf. - """ - return ( - prep_padded_densefsavec(log_probs, supervisions) - if self.pad_fsavec - else k2.DenseFsaVec(log_probs, supervisions) - ) - - def _maybe_normalize_gradients(self, log_probs: torch.Tensor, input_lengths: torch.Tensor) -> torch.Tensor: - """PyTorch is doing the log-softmax normalization as part of the CTC computation. - More: https://github.com/k2-fsa/k2/issues/575 - """ - return GradExpNormalize.apply(log_probs, input_lengths, "mean" if self.reduction != "sum" else "none") - - def _extract_labels_and_probabilities( - self, shortest_path_fsas: 'k2.Fsa', return_ilabels: bool = False, output_aligned: bool = True - ) -> Tuple[List[torch.Tensor], List[torch.Tensor]]: - """Extracts the labels and probabilities of the best lattice path, - dropping arcs and restoring the targets shift, if needed. - """ - shortest_paths = [] - probs = [] - # direct iterating does not work as expected - for i in range(shortest_path_fsas.shape[0]): - shortest_path_fsa = shortest_path_fsas[i] - # suppose that artificial input epsilon numbers >= self.num_classes - non_eps_mask = (shortest_path_fsa.labels != -1) & (shortest_path_fsa.labels < self.num_classes) - if return_ilabels: - labels = shortest_path_fsa.labels[non_eps_mask] - else: - labels = shortest_path_fsa.aux_labels[non_eps_mask] - if self.blank != 0: - # suppose output epsilon number == 0 - # since the input epsilons were removed, we treat all remaining epsilons as blanks - labels[labels == 0] = self.blank - labels[(labels > 0) & (labels < self.blank)] -= 1 - labels = labels.to(dtype=torch.long) - if not return_ilabels and not output_aligned: - labels = labels[labels != self.blank] - shortest_paths.append(labels) - probs.append(get_arc_weights(shortest_path_fsa)[non_eps_mask].exp().to(device=shortest_path_fsas.device)) - return shortest_paths, probs - - -class RnntK2Mixin(CtcK2Mixin): - """k2 Mixin class that simplifies the construction of various k2-based RNNT-like losses. Inherits CtcK2Mixin. - - It does the following: - - Prepares and adapts the input tensors. - - Creates Emissions graphs. - - Extracts the labels and probabilities of the best lattice path (method _extract_labels_and_probabilities). - """ - - def _prepare_log_probs_and_targets( - self, - log_probs: torch.Tensor, - input_lengths: torch.Tensor, - targets: torch.Tensor, - target_lengths: torch.Tensor, - ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: - """Before calling super()._prepare_log_probs_and_targets, this method reshapes the log_probs tensor - from (B, T, U+1, D) to (B, T', D) where T' = T*(U+1), shifts paddings along T and U towards the end of T', - and recomputes input_lengths. - - It also calculates indices on which steps should be applied to the log_probs tensor to emulate - arcs shift of the Emissions graph for the pruned RNNT variant. - """ - assert len(log_probs.size()) == 4 # B T U D - B, T, U, D = log_probs.size() - TU = T * U - - # save step indices if, as we assume, decoder output pruning has been applied - if self.predictor_window_size > 0 and self.predictor_window_size < target_lengths.max(): - window_size_with_blank = self.predictor_window_size + 1 - ranges_begin = get_uniform_rnnt_prune_ranges( - input_lengths, target_lengths, window_size_with_blank, self.predictor_step_size, T, True - ) - step_sizes = ranges_begin[:, 1:] - ranges_begin[:, :-1] - raw_step_indices = torch.where(step_sizes > 0) - if self.predictor_step_size > 1: - raw_step_indices = torch.repeat_interleave( - torch.stack(raw_step_indices).T, step_sizes[raw_step_indices], dim=0 - ).T - raw_step_indices = (raw_step_indices[0], raw_step_indices[1]) - unique, count = torch.unique(raw_step_indices[0], return_counts=True) - shift_mask = raw_step_indices[0].unsqueeze(0).repeat(len(unique), 1) == unique.unsqueeze(-1) - step_indices = ( - raw_step_indices[0], - ( - torch.arange(ranges_begin.size(1)).unsqueeze(0).repeat(ranges_begin.size(0), 1) - * window_size_with_blank - )[(raw_step_indices[0], raw_step_indices[1] + 1)] - + torch.cumsum(shift_mask, 1)[shift_mask] - - 1, - ) - max_count = count.max() - max_count_vec = torch.full((B,), max_count) - max_count_vec[unique] -= count - pad_indices_row = torch.repeat_interleave(torch.arange(B), max_count_vec) - pad_unique = torch.unique(pad_indices_row) - pad_shift_mask = pad_indices_row.unsqueeze(0).repeat(len(pad_unique), 1) == pad_unique.unsqueeze(-1) - pad_indices = ( - pad_indices_row, - T * window_size_with_blank + max_count - torch.cumsum(pad_shift_mask, 1)[pad_shift_mask], - ) - self.__step_indices = ( - torch.cat((step_indices[0], pad_indices[0])), - torch.cat((step_indices[1], pad_indices[1])), - ) - self.__supervisions_add = max_count - max_count_vec - else: - self.__step_indices = None - self.__supervisions_add = None - - # reshape 4D log_probs to 3D with respect to target_lengths - non_pad_mask_true = make_non_pad_mask_3d(input_lengths, target_lengths + 1, T, U).flatten(1) - input_lengths = non_pad_mask_true.sum(1) - non_pad_mask_fake = make_non_pad_mask(input_lengths, TU).flatten() - non_pad_mask_true = non_pad_mask_true.flatten() - rearranged_indices = torch.arange(TU * B, device=log_probs.device) - rearranged_indices_buffer = rearranged_indices.clone() - rearranged_indices[non_pad_mask_fake] = rearranged_indices_buffer[non_pad_mask_true] - rearranged_indices[~non_pad_mask_fake] = rearranged_indices_buffer[~non_pad_mask_true] - log_probs = log_probs.reshape(-1, D)[rearranged_indices].view(B, -1, D) - - return super()._prepare_log_probs_and_targets(log_probs, input_lengths, targets, target_lengths) - - def _prepare_emissions_graphs(self, log_probs: torch.Tensor, supervisions: torch.Tensor) -> 'k2.DenseFsaVec': - """Overrides super()._prepare_emissions_graphs. - Creates DenseFsaVec, adding outputs to the end of the D dimension. - - If pruning is used, this method also pads the DenseFsaVec with frames - according to the steps, calculated before. - - frame is a frame with log-probability zero and every other log-probability is -inf. - """ - if self.__step_indices is None or self.__supervisions_add is None: - log_probs_eps = torch.cat( - (log_probs, torch.zeros((log_probs.size(0), log_probs.size(1), 1), device=log_probs.device)), dim=2 - ) - else: - mask = torch.zeros( - (log_probs.size(0), log_probs.size(1) + int(len(self.__step_indices[0]) / log_probs.size(0))), - dtype=torch.bool, - ) - mask[self.__step_indices] = True - log_probs_eps = torch.zeros((mask.size(0), mask.size(1), log_probs.size(2) + 1), device=log_probs.device) - log_probs_eps[mask] = torch.tensor( - [torch.finfo(torch.float32).min] * log_probs.size(2) + [0], device=log_probs.device - ) - log_probs_eps[~mask] = torch.cat( - (log_probs, torch.zeros((log_probs.size(0), log_probs.size(1), 1), device=log_probs.device)), dim=2 - ).view(-1, log_probs.size(-1) + 1) - input_lengths = supervisions[:, -1] + self.__supervisions_add[supervisions[:, 0].to(dtype=torch.long)] - if not torch.all(input_lengths[:-1] - input_lengths[1:] >= 0): - # have to reorder supervisions inplace - order = torch.argsort(input_lengths, descending=True) - # the second column is assumed to be zero - supervisions[:, 0] = supervisions[order, 0] - supervisions[:, -1] = input_lengths[order] - else: - supervisions[:, -1] = input_lengths - self.__step_indices = None - self.__supervisions_add = None - return k2.DenseFsaVec(log_probs_eps, supervisions) - - def _maybe_normalize_gradients(self, log_probs: torch.Tensor, input_lengths: torch.Tensor) -> torch.Tensor: - """Not required for RNNT. - """ - return log_probs diff --git a/nemo/collections/asr/parts/k2/map_loss.py b/nemo/collections/asr/parts/k2/map_loss.py deleted file mode 100644 index c261a4f2ef6b12af8802a0db6fc08591b1c2450e..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/k2/map_loss.py +++ /dev/null @@ -1,320 +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) 2020, Xiaomi CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 typing import Any, Optional, Tuple, Union - -import torch -from omegaconf import DictConfig - -from nemo.collections.asr.parts.k2.classes import GraphIntersectDenseConfig -from nemo.collections.asr.parts.k2.loss_mixins import CtcK2Mixin -from nemo.collections.asr.parts.k2.ml_loss import MLLoss -from nemo.collections.asr.parts.k2.utils import ( - create_sparse_wrapped, - get_tot_objf_and_finite_mask, - invert_permutation, - load_graph, -) -from nemo.core.utils.k2_guard import k2 # import k2 from guard module -from nemo.utils import logging - - -class MAPLoss(MLLoss): - """ - Maximum a Posteriori Probability criterion. - It implements Lattice-Free Maximum Mutual Information (LF-MMI) and LF-boosted-MMI (LF-bMMI) losses. - - Based on https://github.com/k2-fsa/snowfall/blob/master/snowfall/objectives/mmi.py - - cfg takes precedence over all optional parameters - We keep explicit parameter setting to be able to create an instance without the need of a config. - """ - - @abstractmethod - def __init__( - self, - num_classes: int, - blank: int, - reduction: str, - cfg: Optional[DictConfig] = None, - topo_type: str = "default", - topo_with_self_loops: bool = True, - token_lm: Optional[Union['k2.Fsa', str]] = None, - intersect_pruned: bool = False, - intersect_conf: GraphIntersectDenseConfig = GraphIntersectDenseConfig(), - boost_coeff: float = 0.0, - ): - super().__init__( - num_classes=num_classes, - blank=blank, - reduction=reduction, - cfg=cfg, - topo_type=topo_type, - topo_with_self_loops=topo_with_self_loops, - ) - if cfg is not None: - token_lm = cfg.get("token_lm", token_lm) - intersect_pruned = cfg.get("intersect_pruned", intersect_pruned) - intersect_conf = cfg.get("intersect_conf", intersect_conf) - boost_coeff = cfg.get("boost_coeff", boost_coeff) - self.boost_coeff = boost_coeff - self._intersect_calc_scores_impl = ( - self._intersect_calc_scores_impl_pruned if intersect_pruned else self._intersect_calc_scores_impl_exact_opt - ) - self.intersect_conf = intersect_conf - self.graph_compiler = None # expected to be initialized in .update_graph(...) - if token_lm is None: - logging.warning( - f"""token_lm is empty. - Trainable token_lm is not supported yet. - Please call .update_graph(token_lm) before using.""" - ) - else: - self.lm_graph = load_graph(token_lm) if isinstance(token_lm, str) else token_lm - if self.lm_graph is None: - raise ValueError(f"""lm_graph is empty.""") - else: - self.update_graph(self.lm_graph) - - @abstractmethod - def update_graph(self, graph: 'k2.Fsa'): - # expected to be set in child classes - raise NotImplementedError - - def _intersect_calc_scores_impl_exact_opt( - self, dense_fsa_vec: 'k2.DenseFsaVec', num_graphs: 'k2.Fsa', den_graph: 'k2.Fsa', return_lats: bool = True, - ) -> Tuple[torch.Tensor, torch.Tensor, Optional['k2.Fsa'], Optional['k2.Fsa']]: - """Inner intersection method. - Does joint (simultaneous) exact intersection of dense_fsa_vec against num_graphs and den_graph. - - Optiolally returns the numerator and the denominator lattices. - """ - device = dense_fsa_vec.device - assert device == num_graphs.device and device == den_graph.device - - num_fsas = num_graphs.shape[0] - assert dense_fsa_vec.dim0() == num_fsas - - den_graph = den_graph.clone() - num_graphs = num_graphs.clone() - - num_den_graphs = k2.cat([num_graphs, den_graph]) - - # NOTE: The a_to_b_map in k2.intersect_dense must be sorted - # so the following reorders num_den_graphs. - - # [0, 1, 2, ... ] - num_graphs_indexes = torch.arange(num_fsas, dtype=torch.int32) - - # [num_fsas, num_fsas, num_fsas, ... ] - den_graph_indexes = torch.tensor([num_fsas] * num_fsas, dtype=torch.int32) - - # [0, num_fsas, 1, num_fsas, 2, num_fsas, ... ] - num_den_graphs_indexes = torch.stack([num_graphs_indexes, den_graph_indexes]).t().reshape(-1).to(device) - - num_den_reordered_graphs = k2.index_fsa(num_den_graphs, num_den_graphs_indexes) - - # [[0, 1, 2, ...]] - a_to_b_map = torch.arange(num_fsas, dtype=torch.int32).reshape(1, -1) - - # [[0, 1, 2, ...]] -> [0, 0, 1, 1, 2, 2, ... ] - a_to_b_map = a_to_b_map.repeat(2, 1).t().reshape(-1).to(device) - - num_den_lats = k2.intersect_dense( - a_fsas=num_den_reordered_graphs, - b_fsas=dense_fsa_vec, - output_beam=self.intersect_conf.output_beam, - a_to_b_map=a_to_b_map, - seqframe_idx_name="seqframe_idx" if return_lats else None, - ) - - num_den_tot_scores = num_den_lats.get_tot_scores(log_semiring=True, use_double_scores=False) - num_tot_scores = num_den_tot_scores[::2] - den_tot_scores = num_den_tot_scores[1::2] - - if return_lats: - lat_slice = torch.arange(num_fsas, dtype=torch.int32).to(device) * 2 - return ( - num_tot_scores, - den_tot_scores, - k2.index_fsa(num_den_lats, lat_slice), - k2.index_fsa(num_den_lats, lat_slice + 1), - ) - else: - return num_tot_scores, den_tot_scores, None, None - - def _intersect_calc_scores_impl_pruned( - self, dense_fsa_vec: 'k2.DenseFsaVec', num_graphs: 'k2.Fsa', den_graph: 'k2.Fsa', return_lats: bool = True, - ) -> Tuple[torch.Tensor, torch.Tensor, Optional['k2.Fsa'], Optional['k2.Fsa']]: - """Inner intersection method. - Does exact intersection of dense_fsa_vec against num_graphs and pruned intersection against den_graph. - - Optiolally returns the numerator and the denominator lattices. - """ - device = dense_fsa_vec.device - assert device == num_graphs.device and device == den_graph.device - - num_fsas = num_graphs.shape[0] - assert dense_fsa_vec.dim0() == num_fsas - - num_lats = k2.intersect_dense( - a_fsas=num_graphs, - b_fsas=dense_fsa_vec, - output_beam=self.intersect_conf.output_beam, - seqframe_idx_name="seqframe_idx" if return_lats else None, - ) - den_lats = k2.intersect_dense_pruned( - a_fsas=den_graph, - b_fsas=dense_fsa_vec, - search_beam=self.intersect_conf.search_beam, - output_beam=self.intersect_conf.output_beam, - min_active_states=self.intersect_conf.min_active_states, - max_active_states=self.intersect_conf.max_active_states, - seqframe_idx_name="seqframe_idx" if return_lats else None, - ) - - num_tot_scores = num_lats.get_tot_scores(log_semiring=True, use_double_scores=False) - den_tot_scores = den_lats.get_tot_scores(log_semiring=True, use_double_scores=False) - - if return_lats: - return num_tot_scores, den_tot_scores, num_lats, den_lats - else: - return num_tot_scores, den_tot_scores, None, None - - def _intersect_calc_scores( - self, emissions_graphs: 'k2.DenseFsaVec', supervision_graphs: Any, supervisions: torch.Tensor, - ) -> Tuple[torch.Tensor, torch.Tensor]: - """Intersects emissions_graphs with supervision_graphs and calculates lattice scores. - This version implicitly assumes supervision_graphs to be a pair of the numerator and the denominator FSAs. - - It can also calculate accuracy between the numerator and the denominator lattices to use it as additional loss. - - Can be overridden. - """ - boosted = self.boost_coeff != 0.0 - num_tot_scores, den_tot_scores, num_lats, den_lats = self._intersect_calc_scores_impl( - emissions_graphs, supervision_graphs[0], supervision_graphs[1], boosted - ) - - inverted_batch_order = invert_permutation(supervisions[:, 0].to(dtype=torch.long)) - self.__batch_order = None - tot_scores = (num_tot_scores - den_tot_scores)[inverted_batch_order] - mmi_tot_scores, mmi_valid_mask = get_tot_objf_and_finite_mask(tot_scores, self.reduction) - - if boosted: - assert num_lats is not None and den_lats is not None - - size = ( - emissions_graphs.dim0(), - emissions_graphs.scores.shape[0], - emissions_graphs.scores.shape[1] - 1, - ) - row_ids = emissions_graphs.emissions_graphs.shape().row_ids(1) - num_sparse = create_sparse_wrapped( - indices=[k2.index_select(row_ids, num_lats.seqframe_idx), num_lats.seqframe_idx, num_lats.phones,], - values=num_lats.get_arc_post(False, True).exp(), - size=size, - min_col_index=0, - ) - del num_lats - den_sparse = create_sparse_wrapped( - indices=[k2.index_select(row_ids, den_lats.seqframe_idx), den_lats.seqframe_idx, den_lats.phones,], - values=den_lats.get_arc_post(False, True).exp(), - size=size, - min_col_index=0, - ) - del den_lats - - acc_loss = torch.sparse.sum((num_sparse - den_sparse).coalesce().abs(), (1, 2)).to_dense() - del num_sparse, den_sparse - - acc_tot_scores, acc_valid_mask = get_tot_objf_and_finite_mask(acc_loss, self.reduction) - valid_mask = mmi_valid_mask & acc_valid_mask - total_loss = ( - (self.boost_coeff * acc_tot_scores[inverted_batch_order][valid_mask] - mmi_tot_scores[valid_mask]) - if self.reduction == "none" - else self.boost_coeff * acc_tot_scores - mmi_tot_scores - ) - else: - valid_mask = mmi_valid_mask - total_loss = -mmi_tot_scores[valid_mask] if self.reduction == "none" else -mmi_tot_scores - return total_loss, valid_mask - - -class CtcMmiLoss(MAPLoss, CtcK2Mixin): - """MMI loss with custom CTC topologies. - Available topologies: - - `default`, with or without self-loops - - `compact`, with or without self-loops - - `shared_blank`, with or without self-loops - - `minimal`, without self-loops - - cfg takes precedence over all optional parameters - We keep explicit parameter setting to be able to create an instance without the need of a config. - """ - - def __init__( - self, - num_classes: int, - blank: int, - reduction: str, - cfg: Optional[DictConfig] = None, - topo_type: str = "default", - topo_with_self_loops: bool = True, - token_lm: Optional[Union['k2.Fsa', str]] = None, - intersect_pruned: bool = False, - intersect_conf: GraphIntersectDenseConfig = GraphIntersectDenseConfig(), - boost_coeff: float = 0.0, - ): - super().__init__( - num_classes=num_classes, - blank=blank, - reduction=reduction, - cfg=cfg, - topo_type=topo_type, - topo_with_self_loops=topo_with_self_loops, - token_lm=token_lm, - intersect_pruned=intersect_pruned, - intersect_conf=intersect_conf, - boost_coeff=boost_coeff, - ) - - def update_graph(self, graph: 'k2.Fsa'): - self.lm_graph = graph - lm_graph = self.lm_graph.clone() - if hasattr(lm_graph, "aux_labels"): - delattr(lm_graph, "aux_labels") - labels = lm_graph.labels - if labels.max() != self.num_classes - 1: - raise ValueError(f"lm_graph is not compatible with the num_classes: {labels.unique()}, {self.num_classes}") - from nemo.collections.asr.parts.k2.graph_compilers import MmiGraphCompiler as compiler - - self.graph_compiler = compiler( - self.num_classes, self.blank, self.topo_type, self.topo_with_self_loops, aux_graph=lm_graph - ) diff --git a/nemo/collections/asr/parts/k2/ml_loss.py b/nemo/collections/asr/parts/k2/ml_loss.py deleted file mode 100644 index ef916ee2f69d9c5d33906a915764a96b48a70ee1..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/k2/ml_loss.py +++ /dev/null @@ -1,220 +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) 2020, Xiaomi CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 typing import Any, Optional, Tuple - -import torch -from omegaconf import DictConfig - -from nemo.collections.asr.parts.k2.graph_compilers import CtcTopologyCompiler, RnntTopologyCompiler -from nemo.collections.asr.parts.k2.loss_mixins import CtcK2Mixin, RnntK2Mixin -from nemo.collections.asr.parts.k2.utils import get_tot_objf_and_finite_mask, invert_permutation -from nemo.core.utils.k2_guard import k2 # import k2 from guard module - - -class MLLoss(torch.nn.Module): - """ - Maximum Likelihood criterion. - It implements Connectionist Temporal Classification (CTC) loss, - but can be extended to support other loss functions (ASG, HMM, RNNT, ...). - - Based on https://github.com/k2-fsa/snowfall/blob/master/snowfall/objectives/ctc.py - - cfg takes precedence over all optional parameters - We keep explicit parameter setting to be able to create an instance without the need of a config. - """ - - @abstractmethod - def __init__( - self, - num_classes: int, - blank: int, - reduction: str, - cfg: Optional[DictConfig] = None, - topo_type: str = "default", - topo_with_self_loops: bool = True, - ): - super().__init__() - if cfg is not None: - topo_type = cfg.get("topo_type", topo_type) - topo_with_self_loops = cfg.get("topo_with_self_loops", topo_with_self_loops) - self.blank = blank - self.num_classes = num_classes - self.reduction = reduction - self.topo_type = topo_type - self.topo_with_self_loops = topo_with_self_loops - self.pad_fsavec = topo_type == "compact" - self.graph_compiler = None # expected to be initialized in child classes - - def _prepare_graphs_for_intersection( - self, - log_probs: torch.Tensor, - targets: torch.Tensor, - input_lengths: torch.Tensor, - target_lengths: torch.Tensor, - ) -> Tuple['k2.DenseFsaVec', Any, torch.Tensor]: - """Converts input tensors to FST graphs: - log_probs to supervision_graphs (DenseFsaVec) - targets to supervision_graphs - Can be overridden. - """ - log_probs, supervisions, targets, target_lengths = self._prepare_log_probs_and_targets( - log_probs, input_lengths, targets, target_lengths - ) - log_probs = self._maybe_normalize_gradients(log_probs, supervisions[:, -1].to(dtype=torch.long)) - emissions_graphs = self._prepare_emissions_graphs(log_probs, supervisions) - del log_probs - - if emissions_graphs.device != self.graph_compiler.device: - self.graph_compiler.to(emissions_graphs.device) - order = supervisions[:, 0].to(dtype=torch.long) - supervision_graphs = self.graph_compiler.compile(targets[order], target_lengths[order]) - - return emissions_graphs, supervision_graphs, supervisions - - def _intersect_calc_scores( - self, emissions_graphs: 'k2.DenseFsaVec', supervision_graphs: Any, supervisions: torch.Tensor - ) -> Tuple[torch.Tensor, torch.Tensor]: - """Intersects emissions_graphs with supervision_graphs and calculates lattice scores. - Can be overridden. - """ - lats = k2.intersect_dense(supervision_graphs, emissions_graphs, torch.finfo(torch.float32).max / 10) - del emissions_graphs - - num_tot_scores = lats.get_tot_scores(log_semiring=True, use_double_scores=False) - del lats - tot_scores = num_tot_scores[invert_permutation(supervisions[:, 0].to(dtype=torch.long))] - tot_scores, valid_mask = get_tot_objf_and_finite_mask(tot_scores, self.reduction) - return -tot_scores[valid_mask] if self.reduction == "none" else -tot_scores, valid_mask - - def forward( - self, - log_probs: torch.Tensor, - targets: torch.Tensor, - input_lengths: torch.Tensor, - target_lengths: torch.Tensor, - ) -> Tuple[torch.Tensor, torch.Tensor]: - assert self.graph_compiler is not None - - emissions_graphs, supervision_graphs, supervisions = self._prepare_graphs_for_intersection( - log_probs, targets, input_lengths, target_lengths - ) - scores, mask = self._intersect_calc_scores(emissions_graphs, supervision_graphs, supervisions) - return scores, mask - - -class CtcLoss(MLLoss, CtcK2Mixin): - """Regular CTC loss with custom topologies. - Available topologies: - - `default`, with or without self-loops - - `compact`, with or without self-loops - - `shared_blank`, with or without self-loops - - `minimal`, without self-loops - cfg takes precedence over all optional parameters - We keep explicit parameter setting to be able to create an instance without the need of a config. - """ - - def __init__( - self, - num_classes: int, - blank: int, - reduction: str, - cfg: Optional[DictConfig] = None, - topo_type: str = "default", - topo_with_self_loops: bool = True, - ): - super().__init__( - num_classes=num_classes, - blank=blank, - reduction=reduction, - cfg=cfg, - topo_type=topo_type, - topo_with_self_loops=topo_with_self_loops, - ) - self.graph_compiler = CtcTopologyCompiler( - self.num_classes, self.blank, self.topo_type, self.topo_with_self_loops - ) - - -class RnntLoss(MLLoss, RnntK2Mixin): - """RNNT loss with the `minimal` topology. - If predictor_window_size is not provided, this loss works as regular RNNT. - With predictor_window_size provided, it applies uniform pruning when compiling Emission FSAs - to reduce memory and compute consumption. - cfg takes precedence over all optional parameters - We keep explicit parameter setting to be able to create an instance without the need of a config. - """ - - def __init__( - self, - num_classes: int, - blank: int, - reduction: str, - cfg: Optional[DictConfig] = None, - topo_type: str = "minimal", - topo_with_self_loops: bool = True, - predictor_window_size: int = 0, - predictor_step_size: int = 1, - ): - super().__init__( - num_classes=num_classes, - blank=blank, - reduction=reduction, - cfg=cfg, - topo_type=topo_type, - topo_with_self_loops=topo_with_self_loops, - ) - if cfg is not None: - topo_type = cfg.get("topo_type", topo_type) - predictor_window_size = cfg.get("predictor_window_size", predictor_window_size) - predictor_step_size = cfg.get("predictor_step_size", predictor_step_size) - if topo_type != "minimal": - raise NotImplementedError(f"Only topo_type=`minimal` is supported at the moment.") - self.predictor_window_size = predictor_window_size - self.predictor_step_size = predictor_step_size - self.graph_compiler = RnntTopologyCompiler( - self.num_classes, - self.blank, - self.topo_type, - self.topo_with_self_loops, - max_adapter_length=self.predictor_window_size, - ) - - def forward( - self, - log_probs: torch.Tensor, - targets: torch.Tensor, - input_lengths: torch.Tensor, - target_lengths: torch.Tensor, - ) -> Tuple[torch.Tensor, torch.Tensor]: - assert self.predictor_window_size == 0 or log_probs.size(2) <= self.predictor_window_size + 1 - - return super().forward( - log_probs=log_probs, targets=targets, input_lengths=input_lengths, target_lengths=target_lengths - ) diff --git a/nemo/collections/asr/parts/k2/rnnt_logprobs.py b/nemo/collections/asr/parts/k2/rnnt_logprobs.py index c41615f83bf93df13be81882ca7e601124a07406..599bd3555c61000c6fc7d10ef52a3e74f20f072a 100644 --- a/nemo/collections/asr/parts/k2/rnnt_logprobs.py +++ b/nemo/collections/asr/parts/k2/rnnt_logprobs.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. diff --git a/nemo/collections/asr/parts/k2/rnnt_logprobs_triton.py b/nemo/collections/asr/parts/k2/rnnt_logprobs_triton.py index 64bc8abbdbebb8937e1bd2bdf8448b0457063103..a52bea49509351111b75668bdcb29470bb9e7b02 100644 --- a/nemo/collections/asr/parts/k2/rnnt_logprobs_triton.py +++ b/nemo/collections/asr/parts/k2/rnnt_logprobs_triton.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. diff --git a/nemo/collections/asr/parts/k2/topologies.py b/nemo/collections/asr/parts/k2/topologies.py deleted file mode 100644 index a3b6fcf0fef71279cf8f41bd8369446215e2bbc2..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/k2/topologies.py +++ /dev/null @@ -1,211 +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 functools import lru_cache -from typing import List, Optional, Union - -import torch - -from nemo.core.utils.k2_guard import k2 # import k2 from guard module - - -def build_topo(name: str, tokens: List[int], blank_num: int, with_self_loops: bool = True) -> 'k2.Fsa': - """Helper function to build a topology. - It allows to build topologies with a non-zero blank ID. - Args: - name: - The topology name. Choices: default, compact, shared_blank, minimal - tokens: - A list of tokens, e.g., phones, characters, etc. - blank_num: - Blank number. Must be in tokens - with_self_loops: - Whether to add token-to-epsilon self-loops to a topology - Returns: - Returns a topology FST. - """ - if name == "default": - ans = build_default_topo(tokens, with_self_loops) - elif name == "compact": - ans = build_compact_topo(tokens, with_self_loops) - elif name == "shared_blank": - ans = build_shared_blank_topo(tokens, with_self_loops) - elif name == "minimal": - ans = build_minimal_topo(tokens) - else: - raise ValueError(f"Unknown topo name: {name}") - if blank_num != 0: - labels = ans.labels - blank_mask = labels == 0 - labels[(labels != -1) & (labels <= blank_num)] -= 1 - labels[blank_mask] = blank_num - ans.labels = labels # force update ans.labels property to notify FSA about modifications, required by k2 - ans = k2.arc_sort(ans) - return ans - - -def build_default_topo(tokens: List[int], with_self_loops: bool = True) -> 'k2.Fsa': - """Build the default CTC topology. - Zero is assumed to be the ID of the blank symbol. - """ - assert -1 not in tokens, "We assume -1 is ID of the final transition" - assert 0 in tokens, "We assume 0 is the ID of the blank symbol" - - num_states = len(tokens) - final_state = num_states - arcs = "" if with_self_loops else f"0 0 0 0 0.0\n" - for i in range(num_states): - for j in range(num_states): - if i == j: - if with_self_loops: - arcs += f"{i} {i} {tokens[i]} 0 0.0\n" - else: - arcs += f"{i} {j} {tokens[j]} {tokens[j]} 0.0\n" - arcs += f"{i} {final_state} -1 -1 0.0\n" - arcs += f"{final_state}" - ans = k2.Fsa.from_str(arcs, num_aux_labels=1) - ans = k2.arc_sort(ans) - return ans - - -def build_compact_topo(tokens: List[int], with_self_loops: bool = True) -> 'k2.Fsa': - """Build the compact CTC topology. - Zero is assumed to be the ID of the blank symbol. - See https://arxiv.org/abs/2110.03098 - """ - assert -1 not in tokens, "We assume -1 is ID of the final transition" - assert 0 in tokens, "We assume 0 is the ID of the blank symbol" - - eps_num = tokens[-1] + 1 - selfloops_shift = int(with_self_loops) - num_states = len(tokens) + selfloops_shift - final_state = num_states - arcs = "" - for i in range(selfloops_shift, num_states): - arcs += f"0 {i} {tokens[i - selfloops_shift]} {tokens[i - selfloops_shift]} 0.0\n" - arcs += f"0 {final_state} -1 -1 0.0\n" - for i in range(1, num_states): - arcs += f"{i} 0 {eps_num} 0 0.0\n" - if with_self_loops: - arcs += f"{i} {i} {tokens[i - selfloops_shift]} 0 0.0\n" - arcs += f"{final_state}" - ans = k2.Fsa.from_str(arcs, num_aux_labels=1) - ans = k2.arc_sort(ans) - return ans - - -def build_shared_blank_topo(tokens: List[int], with_self_loops: bool = True) -> 'k2.Fsa': - """Build the shared blank CTC topology. - Zero is assumed to be the ID of the blank symbol. - See https://github.com/k2-fsa/k2/issues/746#issuecomment-856421616 - """ - assert -1 not in tokens, "We assume -1 is ID of the final transition" - assert 0 in tokens, "We assume 0 is the ID of the blank symbol" - - tokens = tokens.copy() - tokens.remove(0) - num_tokens = len(tokens) - start = 0 - final = num_tokens + 1 - arcs = [] - arcs.append([start, start, 0, 0, 0]) - arcs.append([start, final, -1, -1, 0]) - arcs.append([final]) - for i, p in enumerate(tokens): - i += 1 - arcs.append([start, start, p, p, 0]) - arcs.append([start, i, p, p, 0]) - arcs.append([i, start, p, 0, 0]) - if with_self_loops: - arcs.append([i, i, p, 0, 0]) - arcs = sorted(arcs, key=lambda arc: arc[0]) - arcs = [[str(i) for i in arc] for arc in arcs] - arcs = [" ".join(arc) for arc in arcs] - arcs = "\n".join(arcs) - ans = k2.Fsa.from_str(arcs, num_aux_labels=1) - ans = k2.arc_sort(ans) - return ans - - -def build_minimal_topo(tokens: List[int]) -> 'k2.Fsa': - """Build the minimal topology. - Zero is assumed to be the ID of the blank symbol. - See https://arxiv.org/abs/2110.03098 - """ - assert -1 not in tokens, "We assume -1 is ID of the final transition" - assert 0 in tokens, "We assume 0 is the ID of the blank symbol" - - num_tokens = len(tokens) - final_state = 1 - arcs = "" - for i in range(num_tokens): - arcs += f"0 0 {tokens[i]} {tokens[i]} 0.0\n" - arcs += f"0 {final_state} -1 -1 0.0\n" - arcs += f"{final_state}" - ans = k2.Fsa.from_str(arcs, num_aux_labels=1) - ans = k2.arc_sort(ans) - return ans - - -class RnntEmissionAdapterBuilder(object): - """Builder class for RNNT Emission Adapters. - - An Emission Adapter is an FSA used to emulate desired temporal Emissions FSA properties of a trivial Emissions FSA. - Temporal properties are emulated by -arcs with zero log-weight. - These additional arcs do not contribute to the lattice scores and can be easily removed from the best path. - - k2 does not have Emissions FSAs. Instead, it has DenseFsaVec, which is not a real FSA. - Thus, Emission Adapters should be composed with Supervision FSAs. - IMPOTRANT: -outputs are expected to be present in the DenseFsaVec. - - These RNNT adapters do only the re-routing (emulate hopping over U dimension). - Redundant non- are not removed by these adapters. - - At initialization, the builder expects a list of tokens, number and number. - When called, the builder returns adapters according to the provided text lengths. - """ - - def __init__(self, tokens: List[int], blank_num: int, eps_num: Optional[int] = None): - assert -1 not in tokens, "We assume -1 is ID of the final transition" - assert blank_num in tokens, "The blank ID must be in tokens" - assert eps_num is None or eps_num not in tokens, "The epsion ID must not be in tokens" - - self.tokens = tokens - self.blank_num = blank_num - self.eps_num = self.tokens[-1] + 1 if eps_num is None else eps_num - - def __call__(self, adapter_lengths: Union[torch.Tensor, List[int]]) -> 'k2.Fsa': - # if you don't make adapter_lengths a list beforehand, - # "i" will be implicitly converted to int, and this will always be considered a cache miss - return k2.create_fsa_vec([self._build_single_adapter(i) for i in adapter_lengths.tolist()]) - - @lru_cache(maxsize=1024) - def _build_single_adapter(self, adapter_length: int) -> 'k2.Fsa': - assert adapter_length >= 1, "`adapter_length` cannot be less than one" - - first_eps_state = adapter_length + 1 - final_state = adapter_length * 2 + 1 - arcs = "" - for i in range(adapter_length): - for j in range(len(self.tokens)): - if j != self.blank_num: - arcs += f"{i} {i + 1} {self.tokens[j]} 0.0\n" - arcs += f"{i} {first_eps_state} {self.blank_num} 0.0\n" - arcs += f"{adapter_length} {first_eps_state} {self.blank_num} 0.0\n" - for i in range(first_eps_state, final_state): - arcs += f"{i} {i + 1 if i < final_state - 1 else 0} {self.eps_num} 0.0\n" - arcs += f"{i} {final_state} -1 0.0\n" - arcs += f"{final_state}" - - return k2.arc_sort(k2.Fsa.from_str(arcs, acceptor=True)) diff --git a/nemo/collections/asr/parts/k2/utils.py b/nemo/collections/asr/parts/k2/utils.py deleted file mode 100644 index eca2b2379b43a72cded39a47af2ec88e85f17ceb..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/k2/utils.py +++ /dev/null @@ -1,392 +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) 2020, Xiaomi CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 struct -from pickle import UnpicklingError -from typing import List, Optional, Tuple, Union - -import torch - -from nemo.core.utils.k2_guard import k2 # import k2 from guard module -from nemo.utils import logging - - -def create_supervision(input_lengths: torch.Tensor) -> torch.Tensor: - """Creates a special supervisions tensor from input lengths. - These supervisions are required for some k2 methods. - """ - supervisions = torch.stack( - ( - torch.tensor(range(input_lengths.shape[0])), - torch.zeros(input_lengths.shape[0]), - input_lengths.cpu(), - ), - 1, - ).to(dtype=torch.int32) - # the duration column has to be sorted in decreasing order - return supervisions[torch.argsort(supervisions[:, -1], descending=True)] - - -def invert_permutation(indices: torch.Tensor) -> torch.Tensor: - """Produces a tensor of reverse permutation for a given indices. - - Based on https://github.com/k2-fsa/snowfall/blob/master/snowfall/common.py - """ - ans = torch.zeros(indices.shape, device=indices.device, dtype=indices.dtype) - ans[indices.to(dtype=torch.long)] = torch.arange(0, indices.shape[0], device=indices.device, dtype=indices.dtype) - return ans - - -def make_non_pad_mask(input_lengths: torch.Tensor, seq_len: int): - """Converts input_lengths to a non-padding mask. The mask is 2D.""" - batch_size = input_lengths.shape[0] - seq_range = torch.arange(0, seq_len, device=input_lengths.device) - seq_range_expand = seq_range.unsqueeze(0).expand(batch_size, seq_len) - seq_length_expand = input_lengths.clone().detach().to(seq_range_expand.device).unsqueeze(-1) - mask = seq_range_expand < seq_length_expand - return mask - - -def make_non_pad_mask_3d( - lengths_x: torch.Tensor, lengths_y: torch.Tensor, max_length_x: int, max_length_y: int -) -> torch.Tensor: - """Converts two orthogonal input_lengths to a non-padding mask. The mask is 3D.""" - assert lengths_x.size() == lengths_y.size() - return make_non_pad_mask(lengths_x, max_length_x).unsqueeze(2) & make_non_pad_mask( - lengths_y, max_length_y - ).unsqueeze(1) - - -def ragged_to_tensor_2axes_simple(rt: k2.RaggedTensor) -> Optional[torch.Tensor]: - """Converts k2.RaggedTensor to torch.Tensor if the RaggedTensor is shallow (has two axes).""" - rt_list = rt.tolist() - result_list = [] - for e in rt_list: - if len(e) == 0: - result_list.append(0) - elif len(e) == 1: - result_list.append(e[0]) - else: - return None - return torch.tensor(result_list, dtype=torch.int32) - - -def load_graph(graph_path: str) -> 'k2.Fsa': - """Fsa graph loading helper function. Loads graphs stored in different formats.""" - if os.path.exists(graph_path): - errors = [] - try: - graph_dict = torch.load(graph_path, map_location="cpu") - graph = k2.Fsa.from_dict(graph_dict) - return graph - except UnpicklingError as e: - errors.append(e) - with open(graph_path, "rt", encoding="utf-8") as f: - graph_txt = f.read() - # order from the most frequent case to the least - for func, acceptor in [(k2.Fsa.from_openfst, False), (k2.Fsa.from_str, True), (k2.Fsa.from_str, False)]: - try: - graph = func(graph_txt, acceptor=acceptor) - return graph - except (TypeError, ValueError, RuntimeError) as e: - errors.append(e) - raise Exception(errors) - else: - logging.warning(f"""No such file: '{graph_path}'""") - return None - - -def intersect_with_self_loops(base_graph: 'k2.Fsa', aux_graph: 'k2.Fsa') -> 'k2.Fsa': - """Intersection helper function.""" - assert hasattr(base_graph, "aux_labels") - assert not hasattr(aux_graph, "aux_labels") - aux_graph_with_self_loops = k2.arc_sort(k2.add_epsilon_self_loops(aux_graph)).to(base_graph.device) - result = k2.intersect(k2.arc_sort(base_graph), aux_graph_with_self_loops, treat_epsilons_specially=False) - setattr(result, "phones", result.labels) - return result - - -def compose_with_self_loops(base_graph: 'k2.Fsa', aux_graph: 'k2.Fsa') -> 'k2.Fsa': - """Composition helper function.""" - aux_graph_with_self_loops = k2.arc_sort(k2.add_epsilon_self_loops(aux_graph)).to(base_graph.device) - return k2.compose(base_graph, aux_graph_with_self_loops, treat_epsilons_specially=False, inner_labels="phones") - - -def create_sparse_wrapped( - indices: List[torch.Tensor], - values: torch.Tensor, - size: Optional[Union[Tuple[int, int], Tuple[int, int, int]]] = None, - min_col_index: Optional[int] = None, -) -> torch.Tensor: - """Wraps up k2.create_sparse to create 2- or 3-dimensional sparse tensors.""" - assert size is None or len(indices) == len(size) - - if len(indices) == 2: - return k2.create_sparse( - rows=indices[0], - cols=indices[1], - values=values, - size=size, - min_col_index=min_col_index, - ) - elif len(indices) == 3: - assert indices[0].ndim == indices[1].ndim == indices[2].ndim == 1 - assert indices[0].numel() == indices[1].numel() == indices[2].numel() == values.numel() - - if min_col_index is not None: - assert isinstance(min_col_index, int) - kept_indices = indices[-1] >= min_col_index - indices = [i[kept_indices] for i in indices] - values = values[kept_indices] - if size is not None: - return torch.sparse_coo_tensor( - torch.stack(indices), - values, - size=size, - device=values.device, - requires_grad=values.requires_grad, - ) - else: - return torch.sparse_coo_tensor( - torch.stack(indices), - values, - device=values.device, - requires_grad=values.requires_grad, - ) - else: - raise ValueError(f"len(indices) = {len(indices)}") - - -def prep_padded_densefsavec(log_softmax: torch.Tensor, supervisions: torch.Tensor) -> 'k2.DenseFsaVec': - """Performs special epsilon-padding required for composition with some of the topologies.""" - log_softmax_eps = torch.cat( - [ - log_softmax, - torch.full( - (log_softmax.shape[0], log_softmax.shape[1], 1), - -float("inf"), - device=log_softmax.device, - ), - ], - axis=-1, - ) - log_softmax_padded = torch.zeros( - ( - log_softmax_eps.shape[0], - log_softmax_eps.shape[1] * 2, - log_softmax_eps.shape[2], - ), - device=log_softmax.device, - ) - log_softmax_padded[:, ::2] = log_softmax_eps - supervisions_padded = supervisions.clone() - supervisions_padded[:, 2] *= 2 - dense_log_softmax_padded = k2.DenseFsaVec(log_softmax_padded, supervisions_padded) - return dense_log_softmax_padded - - -def shift_labels_inpl(lattices: List['k2.Fsa'], shift: int): - """Shifts lattice labels and aux_labels by a given number. - This is an in-place operation, if the lattice is on GPU. - """ - for lattice in lattices: - mask = lattice.labels > 0 - lattice.labels[mask] += shift - if hasattr(lattice, "aux_labels"): - mask = lattice.aux_labels > 0 - lattice.aux_labels[mask] += shift - return reset_properties_fsa(lattices) - - -def reset_properties_fsa(graph: 'k2.Fsa'): - """Resets properties of a graph. - In-place (does not create a new graph) if the graph is on GPU. - Use this every time you alter a graph in-place. - See https://github.com/k2-fsa/k2/issues/978 for more information.""" - graph.__dict__["_properties"] = None - # CPU graphs need to be sorted e.g. for intersection - if graph.device == torch.device("cpu"): - graph = k2.arc_sort(graph) - return graph - - -def add_self_loops(graph: 'k2.Fsa', label: int = 0, mode: str = "auto"): - """Adds self-loops with given label to a graph. - Supported modes are ``input``, ``output``, and ``auto``, - Where ``input`` leaves aux_labels zeroes, if present, ``output`` leaves labels zeroes""" - assert mode in ("input", "output", "auto"), "Supported modes are ``input``, ``output``, and ``auto``: {mode}" - assert mode != "output" or hasattr(graph, "aux_labels"), "Graph must have aux_labels for mode ``output``" - new_graph, arc_map = k2.add_epsilon_self_loops(graph, ret_arc_map=True) - - if mode != "output": - new_graph.labels[arc_map == -1] = label - if mode != "input" and hasattr(graph, "aux_labels"): - new_graph.aux_labels[arc_map == -1] = label - return reset_properties_fsa(new_graph) - - -def get_arc_weights(graph: 'k2.Fsa') -> torch.Tensor: - """Returns 1d torch.Tensor with arc weights of a given graph.""" - if len(graph.shape) > 2: - raise NotImplementedError("FsaVec is not supported at the moment.") - weights_int = graph.arcs.values()[:, -1].tolist() - weights_float = struct.unpack('%sf' % len(weights_int), struct.pack('%si' % len(weights_int), *weights_int)) - return torch.Tensor(weights_float) - - -def get_tot_objf_and_finite_mask(tot_scores: torch.Tensor, reduction: str) -> Tuple[torch.Tensor, torch.Tensor]: - """Figures out the total score(log-prob) over all successful supervision segments - (i.e. those for which the total score wasn't -infinity). - Args: - tot_scores: a Torch tensor of shape (num_segments,) containing total scores - from forward-backward - reduction: a reduction type ('mean', 'sum' or 'none') - Returns: - Returns a tuple of 2 scalar tensors: (tot_score, finite_mask) - where finite_mask is a tensor containing successful segment mask. - - Based on get_tot_objf_and_num_frames - from https://github.com/k2-fsa/snowfall/blob/master/snowfall/objectives/common.py - """ - finite_mask = ~torch.isnan(tot_scores) & torch.ne(tot_scores, -float("inf")) - if reduction == "mean": - tot_scores = tot_scores[finite_mask].mean() - elif reduction == "sum": - tot_scores = tot_scores[finite_mask].sum() - return tot_scores, finite_mask - - -def get_uniform_rnnt_prune_ranges( - encoded_lengths: torch.Tensor, - target_lengths: torch.Tensor, - window_size_with_blank: int, - step: int = 1, - max_seq_len: Optional[int] = None, - begin_only: bool = False, -) -> torch.Tensor: - """Creates the pruning ranges for the Encoder and Predictor of RNNT. - The ranges are similar to https://k2-fsa.github.io/k2/python_api/api.html#k2.get_rnnt_prune_ranges - but they are constructed under the assumption of the uniform distribution token activations across time frames - and without any posterior knowledge. - """ - assert window_size_with_blank > 1 - assert step >= 1 - assert window_size_with_blank > step - assert len(encoded_lengths) == len(target_lengths) - ranges_begin = torch.zeros( - ( - len(encoded_lengths), - encoded_lengths.max() if max_seq_len is None else max(max_seq_len, encoded_lengths.max()), - ), - dtype=torch.long, - ) - for i in (target_lengths >= window_size_with_blank).nonzero(as_tuple=True)[0]: - encoded_len = encoded_lengths[i] - ranges_begin_raw = torch.arange(int((target_lengths[i] - window_size_with_blank) / step + 2)) * step - ranges_begin_raw[-1] = target_lengths[i] - window_size_with_blank + 1 - ranges_begin[i, :encoded_len] = torch.nn.functional.interpolate( - ranges_begin_raw.reshape(1, 1, -1).to(dtype=torch.float), encoded_len, mode="nearest-exact" - ).to(dtype=torch.long) - ranges_begin[i, encoded_len:] = ranges_begin[i, encoded_len - 1] - return ( - ranges_begin - if begin_only - else ranges_begin.unsqueeze(-1).repeat(1, 1, window_size_with_blank) + torch.arange(window_size_with_blank) - ) - - -def apply_rnnt_prune_ranges( - encoder_outputs: torch.Tensor, decoder_outputs: torch.Tensor, ranges: torch.Tensor -) -> Tuple[torch.Tensor, torch.Tensor]: - """Prepares pruned encoder and decoder outputs according to the prune ranges. - Based on k2.do_rnnt_pruning(...) - """ - B, T, window_size_with_blank = ranges.size() - D1 = encoder_outputs.size(-1) - _, U, D2 = decoder_outputs.size() - assert B == encoder_outputs.size(0) - assert T == encoder_outputs.size(1) - assert B == decoder_outputs.size(0) - encoder_outputs_pruned = encoder_outputs.unsqueeze(2).expand((B, T, window_size_with_blank, D1)) - decoder_outputs_pruned = torch.gather( - decoder_outputs.unsqueeze(1).expand((B, T, U, D2)), - dim=2, - index=ranges.reshape((B, T, window_size_with_blank, 1)).expand((B, T, window_size_with_blank, D2)), - ) - return encoder_outputs_pruned, decoder_outputs_pruned - - -def levenshtein_graph_k2(fsa: 'k2.Fsa', ins_del_score: float = -0.501) -> 'k2.Fsa': - """Construct the levenshtein graph from a k2-type WFST or a lattice. - - See also levenshtein_graph from k2. - - Args: - fst: - K2-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: - K2-type levenshtein WFST. - """ - sub_score = -0.5 - sub_score_int = struct.unpack('@i', struct.pack('@f', sub_score))[0] - arcs = fsa.arcs.values() - final_indices = (fsa.labels == -1).nonzero() - template_mask = ~torch.zeros(len(arcs) * 2, dtype=bool) - no_duplicate_final_mask = template_mask.clone() - no_duplicate_final_mask[final_indices * 2 + 1] = False - new_mask = ~template_mask - new_mask[1::2] = True - new_mask = new_mask[no_duplicate_final_mask] - duplicate_indices = torch.arange(len(arcs)).repeat_interleave(2)[no_duplicate_final_mask] - new_arcs = arcs[duplicate_indices] - new_arcs[:, -1] = torch.where(new_mask, sub_score_int, 0) - if len(fsa.shape) == 3: - new_shape, _ = fsa.arcs.shape().index(2, duplicate_indices.to(dtype=torch.int32)) - # apparently k2 does not support indexing RaggedArc with RaggedShape - new_splits = new_shape.row_splits(2)[new_shape.row_splits(1)] - levenshtein_fsa = k2.create_fsa_vec([k2.Fsa(new_arcs[i:j]) for i, j in zip(new_splits[:-1], new_splits[1:])]) - else: - levenshtein_fsa = k2.Fsa(new_arcs) - levenshtein_fsa.aux_labels = levenshtein_fsa.labels.clone() - labels = levenshtein_fsa.labels.clone() - labels[new_mask] = 0 - levenshtein_fsa.labels = labels - levenshtein_fsa.__dict__["_properties"] = None - levenshtein_fsa, arc_map = k2.add_epsilon_self_loops(levenshtein_fsa, ret_arc_map=True) - scores = levenshtein_fsa.scores.clone() - scores[arc_map == -1] = ins_del_score - levenshtein_fsa.scores = scores - levenshtein_fsa.__dict__["_properties"] = None - levenshtein_fsa = k2.arc_sort(levenshtein_fsa) - return levenshtein_fsa diff --git a/nemo/collections/asr/parts/mixins/__init__.py b/nemo/collections/asr/parts/mixins/__init__.py index 02378bd9d282f13828abc64c7541aad53d595913..c8bfd1503454ad82c98048ca53cec0503a811bef 100644 --- a/nemo/collections/asr/parts/mixins/__init__.py +++ b/nemo/collections/asr/parts/mixins/__init__.py @@ -20,9 +20,23 @@ from nemo.collections.asr.parts.mixins.mixins import ( 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/diarization.py b/nemo/collections/asr/parts/mixins/diarization.py index fe8f6bbecb211a1278ed309ec8ae593b4a4dc346..f59b5a3475f82838972a26a7e30d134e770c59ac 100644 --- a/nemo/collections/asr/parts/mixins/diarization.py +++ b/nemo/collections/asr/parts/mixins/diarization.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -16,11 +16,13 @@ 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 +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 @@ -31,6 +33,38 @@ 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.""" @@ -40,6 +74,7 @@ class InternalDiarizeConfig: 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 @@ -48,6 +83,7 @@ class InternalDiarizeConfig: # Scratch space temp_dir: Optional[str] = None manifest_filepath: Optional[str] = None + max_num_of_spks: Optional[int] = 4 @dataclass @@ -57,10 +93,12 @@ class DiarizeConfig: 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 @@ -93,33 +131,62 @@ class SpkDiarizationMixin(ABC): """ An abstract class for diarize-able models. - Creates a template function `diarize()` that provides an interface to perform transcription of audio tensors or + Creates a template function `diarize()` that provides an interface to perform diarization of audio tensors or filepaths. + """ - The following abstract classes must be implemented by the subclass: - - - `_setup_diarize_dataloader()`: - Setup the dataloader for diarization. Receives the output from - `_diarize_input_manifest_processing()`. + def __init__(self): + self._diarize_audio_rttm_map = {} - - `_diarize_forward()`: - Implements the model's custom forward pass to return outputs that are processed by - `_diarize_output_processing()`. + 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.") - - `_diarize_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. + 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 __init__(self): - self._diarize_audio_rttm_map = {} + 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, DataLoader], + 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, @@ -141,6 +208,7 @@ class SpkDiarizationMixin(ABC): include_tensor_outputs=include_tensor_outputs, postprocessing_yaml=postprocessing_yaml, postprocessing_params=postprocessing_params, + sample_rate=sample_rate, **config_kwargs, ) else: @@ -155,6 +223,16 @@ class SpkDiarizationMixin(ABC): 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() @@ -187,8 +265,8 @@ class SpkDiarizationMixin(ABC): # If nested list structure if isinstance(processed_outputs[0], list): - for i, processed_output in enumerate(processed_outputs): - results[i].extend(processed_output) + 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): @@ -197,15 +275,19 @@ class SpkDiarizationMixin(ABC): f"match the results of the current batch ({len(processed_outputs)})." ) - for i, processed_output in enumerate(processed_outputs): - results[i].append(processed_output) + 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, override_config: Optional[DiarizeConfig]): + 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. """ @@ -326,7 +408,7 @@ class SpkDiarizationMixin(ABC): # Model's mode and device diarcfg._internal.training_mode = self.training - # Switch model to evaluation mode + # 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 @@ -343,6 +425,10 @@ class SpkDiarizationMixin(ABC): 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 @@ -364,37 +450,108 @@ class SpkDiarizationMixin(ABC): # 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'): + if len(audio) == 1 and (audio[0].endswith('.json') or audio[0].endswith('.jsonl')): # Assume it is a path to a manifest file - diarcfg._internal.manifest_filepath = audio[0] self._diarize_audio_rttm_map = audio_rttm_map(audio[0]) - audio_files = [] - for uniq_id, meta_dict in self._diarize_audio_rttm_map.items(): - audio_files.append(meta_dict['audio_filepath']) + # 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, tmp_dir, diarcfg) + 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) is supported as input." + 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[str], temp_dir: str, diarcfg: DiarizeConfig + 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 string filepaths for audio files. + 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. @@ -420,6 +577,7 @@ class SpkDiarizationMixin(ABC): '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 @@ -474,7 +632,7 @@ class SpkDiarizationMixin(ABC): def _diarize_on_end(self, diarcfg: DiarizeConfig): """ - Internal function to teardown the model after transcription. Perform all teardown and post-checks here. + 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. diff --git a/nemo/collections/asr/parts/mixins/mixins.py b/nemo/collections/asr/parts/mixins/mixins.py index 577b6393248cbe8039817020eb176e964db05970..af973be3cc4c569c37e13ef86ca6d218134433f5 100644 --- a/nemo/collections/asr/parts/mixins/mixins.py +++ b/nemo/collections/asr/parts/mixins/mixins.py @@ -14,9 +14,7 @@ import json import os -import shutil import tarfile -import unicodedata from abc import ABC, abstractmethod from typing import List @@ -29,8 +27,13 @@ from nemo.collections.asr.parts.mixins.asr_adapter_mixins import ASRAdapterModel 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): @@ -429,7 +432,7 @@ class ASRBPEMixin(ABC): # 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 = shutil.copy2(v, dir) + loc = robust_copy(v, dir) logging.info(f"Saved {k} at {loc}") if isinstance(v, str) and v.startswith('nemo:'): @@ -482,11 +485,8 @@ class ASRBPEMixin(ABC): def _derive_tokenizer_properties(self): vocab = self.tokenizer.tokenizer.get_vocab() - capitalized_tokens = {token.strip() for token in vocab if any(char.isupper() for char in token)} - self.tokenizer.supports_capitalization = bool(capitalized_tokens) - - punctuation = {char for token in vocab for char in token if unicodedata.category(char).startswith('P')} - self.tokenizer.supported_punctuation = punctuation + self.tokenizer.supports_capitalization = bool(extract_capitalized_tokens_from_vocab(vocab)) + self.tokenizer.supported_punctuation = extract_punctuation_from_vocab(vocab) class ASRModuleMixin(ASRAdapterModelMixin): @@ -602,6 +602,7 @@ class ASRModuleMixin(ASRAdapterModelMixin): 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. @@ -610,7 +611,7 @@ class ASRModuleMixin(ASRAdapterModelMixin): 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: engths for cache_last_channel + 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 @@ -657,6 +658,7 @@ class ASRModuleMixin(ASRAdapterModelMixin): 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 ( diff --git a/nemo/collections/asr/parts/mixins/multitalker_asr_mixins.py b/nemo/collections/asr/parts/mixins/multitalker_asr_mixins.py new file mode 100644 index 0000000000000000000000000000000000000000..d9629e4ab8981db8086f85ec506310814d31602c --- /dev/null +++ b/nemo/collections/asr/parts/mixins/multitalker_asr_mixins.py @@ -0,0 +1,279 @@ +# 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 index d6fd0b9b354ba3a551c4061cdbf3946d167e0ff8..2db68da5a3d2a0060a73ae320a2b5cdce74005ba 100644 --- a/nemo/collections/asr/parts/mixins/streaming.py +++ b/nemo/collections/asr/parts/mixins/streaming.py @@ -14,13 +14,12 @@ from abc import ABC, abstractmethod -import torch - class StreamingEncoder(ABC): @abstractmethod def setup_streaming_params( - self, max_look_ahead: int = 10000, + 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. @@ -47,6 +46,7 @@ class StreamingEncoder(ABC): 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() @@ -65,6 +65,7 @@ class StreamingEncoder(ABC): 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) diff --git a/nemo/collections/asr/parts/mixins/transcription.py b/nemo/collections/asr/parts/mixins/transcription.py index ac928fe9927203cc19d0ed01b3d0530ccfe3f7c1..7a48b99049b3b82eeff5c0433afffabe74db8f80 100644 --- a/nemo/collections/asr/parts/mixins/transcription.py +++ b/nemo/collections/asr/parts/mixins/transcription.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -29,10 +29,11 @@ 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']]] +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]]] @@ -55,6 +56,7 @@ class InternalTranscribeConfig: @dataclass class TranscribeConfig: + use_lhotse: bool = True batch_size: int = 4 return_hypotheses: bool = False num_workers: Optional[int] = None @@ -100,6 +102,10 @@ class TranscriptionTensorDataset(Dataset): 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: @@ -116,6 +122,25 @@ class TranscriptionTensorDataset(Dataset): 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] @@ -134,7 +159,7 @@ class TranscriptionTensorDataset(Dataset): samples = self.augmentor.perturb(segment) samples = torch.tensor(samples.samples, dtype=original_dtype) - # Calculate seq length + 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). @@ -174,6 +199,7 @@ class TranscriptionMixin(ABC): 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, @@ -192,6 +218,8 @@ class TranscriptionMixin(ABC): 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 @@ -228,6 +256,7 @@ class TranscriptionMixin(ABC): if override_config is None: transcribe_cfg = TranscribeConfig( + use_lhotse=use_lhotse, batch_size=batch_size, return_hypotheses=return_hypotheses, num_workers=num_workers, @@ -273,18 +302,7 @@ class TranscriptionMixin(ABC): if results is None: results = [] - # if list of inner list of results, copy structure - if isinstance(processed_outputs[0], list): - for _ in processed_outputs: - results.append([]) - - # 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 - results.extend(processed_outputs) + results.extend(processed_outputs) elif isinstance(processed_outputs, dict): # Create a results of the same type as each element in processed_outputs @@ -536,12 +554,15 @@ class TranscriptionMixin(ABC): ) 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) @@ -724,6 +745,7 @@ class ASRTranscriptionMixin(TranscriptionMixin): ) 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, 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 index 3e7fe2cb782823987a6e3de0f74ef919fc2d4026..c72026ae2fee853c72459b639ad08eeabc991dc6 100644 --- 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 @@ -284,12 +284,12 @@ def ReduceHelper( stream: CUDA Stream. """ if minus: - grid_size = num_cols + 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 = num_cols + 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) diff --git a/nemo/collections/asr/parts/preprocessing/feature_loader.py b/nemo/collections/asr/parts/preprocessing/feature_loader.py index 8c629cf4cfd408f6497055961f5128d7d4470640..e715d2dafb95396597e89d4f1a1eb1cc1dce417b 100644 --- a/nemo/collections/asr/parts/preprocessing/feature_loader.py +++ b/nemo/collections/asr/parts/preprocessing/feature_loader.py @@ -18,12 +18,13 @@ import torch class ExternalFeatureLoader(object): - """Feature loader that load external features store in certain format. + """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, + self, + augmentor: Optional["nemo.collections.asr.parts.perturb.FeatureAugmentor"] = None, ): """ Feature loader @@ -50,23 +51,27 @@ class ExternalFeatureLoader(object): Integers will be scaled to [-1, 1] in float32. """ float32_samples = samples.astype('float32') - if samples.dtype in np.sctypes['int']: + 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.sctypes['float']: + 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 + # 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) diff --git a/nemo/collections/asr/parts/preprocessing/features.py b/nemo/collections/asr/parts/preprocessing/features.py index 5138a3148e913798a2577443297a20d0cab463f3..ec0fa8f6f74d35a577f7db556f111437361e091d 100644 --- a/nemo/collections/asr/parts/preprocessing/features.py +++ b/nemo/collections/asr/parts/preprocessing/features.py @@ -34,7 +34,6 @@ # This file contains code artifacts adapted from https://github.com/ryanleary/patter import math import random -from typing import Optional, Tuple, Union import librosa import numpy as np @@ -45,14 +44,6 @@ from nemo.collections.asr.parts.preprocessing.perturb import AudioAugmentor from nemo.collections.asr.parts.preprocessing.segment import AudioSegment from nemo.utils import logging -try: - import torchaudio - - HAVE_TORCHAUDIO = True -except ModuleNotFoundError: - HAVE_TORCHAUDIO = False - - CONSTANT = 1e-5 @@ -87,6 +78,7 @@ def normalize_batch(x, seq_len, normalize_type): 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 @@ -302,13 +294,14 @@ class FilterbankFeatures(nn.Module): f"{self} got an invalid value for either n_window_size or " f"n_window_stride. Both must be positive ints." ) - logging.info(f"PADDING: {pad_to}") + 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") @@ -387,8 +380,9 @@ class FilterbankFeatures(nn.Module): 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), + window=self.window.to(dtype=torch.float, device=x.device), return_complex=True, + pad_mode="constant", ) def log_zero_guard_value_fn(self, x): @@ -409,7 +403,7 @@ class FilterbankFeatures(nn.Module): 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) + 1 + seq_len = torch.floor_divide((seq_len + pad_amount - self.n_fft), self.hop_length) return seq_len.to(dtype=torch.long) @property @@ -417,11 +411,14 @@ class FilterbankFeatures(nn.Module): return self.fb def forward(self, x, seq_len, linear_spec=False): - seq_len = self.get_seq_len(seq_len) + 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), "reflect" + x.unsqueeze(1), (self.stft_pad_amount, self.stft_pad_amount), "constant" ).squeeze(1) # dither (only in training mode for eval determinism) @@ -430,7 +427,9 @@ class FilterbankFeatures(nn.Module): # 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): @@ -455,8 +454,11 @@ class FilterbankFeatures(nn.Module): if linear_spec: return x, seq_len - # dot with filterbank energies - x = torch.matmul(self.fb.to(x.dtype), x) + # 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": @@ -488,187 +490,3 @@ class FilterbankFeatures(nn.Module): if pad_amt != 0: x = nn.functional.pad(x, (0, pad_to - pad_amt), value=self.pad_value) return x, seq_len - - -class FilterbankFeaturesTA(nn.Module): - """ - Exportable, `torchaudio`-based implementation of Mel Spectrogram extraction. - - See `AudioToMelSpectrogramPreprocessor` for args. - - """ - - def __init__( - self, - sample_rate: int = 16000, - n_window_size: int = 320, - n_window_stride: int = 160, - normalize: Optional[str] = "per_feature", - nfilt: int = 64, - n_fft: Optional[int] = None, - preemph: float = 0.97, - lowfreq: float = 0, - highfreq: Optional[float] = None, - log: bool = True, - log_zero_guard_type: str = "add", - log_zero_guard_value: Union[float, str] = 2**-24, - dither: float = 1e-5, - window: str = "hann", - pad_to: int = 0, - pad_value: float = 0.0, - mel_norm="slaney", - # Seems like no one uses these options anymore. Don't convolute the code by supporting thm. - use_grads: bool = False, # Deprecated arguments; kept for config compatibility - max_duration: float = 16.7, # Deprecated arguments; kept for config compatibility - frame_splicing: int = 1, # Deprecated arguments; kept for config compatibility - exact_pad: bool = False, # Deprecated arguments; kept for config compatibility - nb_augmentation_prob: float = 0.0, # Deprecated arguments; kept for config compatibility - nb_max_freq: int = 4000, # Deprecated arguments; kept for config compatibility - mag_power: float = 2.0, # Deprecated arguments; kept for config compatibility - rng: Optional[random.Random] = None, # Deprecated arguments; kept for config compatibility - stft_exact_pad: bool = False, # Deprecated arguments; kept for config compatibility - stft_conv: bool = False, # Deprecated arguments; kept for config compatibility - ): - super().__init__() - if not HAVE_TORCHAUDIO: - raise ValueError(f"Need to install torchaudio to instantiate a {self.__class__.__name__}") - - # Make sure log zero guard is supported, if given as a string - supported_log_zero_guard_strings = {"eps", "tiny"} - if isinstance(log_zero_guard_value, str) and log_zero_guard_value not in supported_log_zero_guard_strings: - raise ValueError( - f"Log zero guard value must either be a float or a member of {supported_log_zero_guard_strings}" - ) - - # Copied from `AudioPreprocessor` due to the ad-hoc structuring of the Mel Spec extractor class - 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, - } - - # Ensure we can look up the window function - if window not in self.torch_windows: - raise ValueError(f"Got window value '{window}' but expected a member of {self.torch_windows.keys()}") - - self.win_length = n_window_size - self.hop_length = n_window_stride - self._sample_rate = sample_rate - self._normalize_strategy = normalize - self._use_log = log - self._preemphasis_value = preemph - self.log_zero_guard_type = log_zero_guard_type - self.log_zero_guard_value: Union[str, float] = log_zero_guard_value - self.dither = dither - self.pad_to = pad_to - self.pad_value = pad_value - self.n_fft = n_fft - self._mel_spec_extractor: torchaudio.transforms.MelSpectrogram = torchaudio.transforms.MelSpectrogram( - sample_rate=self._sample_rate, - win_length=self.win_length, - hop_length=self.hop_length, - n_mels=nfilt, - window_fn=self.torch_windows[window], - mel_scale="slaney", - norm=mel_norm, - n_fft=n_fft, - f_max=highfreq, - f_min=lowfreq, - wkwargs={"periodic": False}, - ) - - @property - def filter_banks(self): - """Matches the analogous class""" - return self._mel_spec_extractor.mel_scale.fb - - def _resolve_log_zero_guard_value(self, dtype: torch.dtype) -> float: - if isinstance(self.log_zero_guard_value, float): - return self.log_zero_guard_value - return getattr(torch.finfo(dtype), self.log_zero_guard_value) - - def _apply_dithering(self, signals: torch.Tensor) -> torch.Tensor: - if self.training and self.dither > 0.0: - noise = torch.randn_like(signals) * self.dither - signals = signals + noise - return signals - - def _apply_preemphasis(self, signals: torch.Tensor) -> torch.Tensor: - if self._preemphasis_value is not None: - padded = torch.nn.functional.pad(signals, (1, 0)) - signals = signals - self._preemphasis_value * padded[:, :-1] - return signals - - def _compute_output_lengths(self, input_lengths: torch.Tensor) -> torch.Tensor: - out_lengths = input_lengths.div(self.hop_length, rounding_mode="floor").add(1).long() - return out_lengths - - def _apply_pad_to(self, features: torch.Tensor) -> torch.Tensor: - # Only apply during training; else need to capture dynamic shape for exported models - if not self.training or self.pad_to == 0 or features.shape[-1] % self.pad_to == 0: - return features - pad_length = self.pad_to - (features.shape[-1] % self.pad_to) - return torch.nn.functional.pad(features, pad=(0, pad_length), value=self.pad_value) - - def _apply_log(self, features: torch.Tensor) -> torch.Tensor: - if self._use_log: - zero_guard = self._resolve_log_zero_guard_value(features.dtype) - if self.log_zero_guard_type == "add": - features = features + zero_guard - elif self.log_zero_guard_type == "clamp": - features = features.clamp(min=zero_guard) - else: - raise ValueError(f"Unsupported log zero guard type: '{self.log_zero_guard_type}'") - features = features.log() - return features - - def _extract_spectrograms(self, signals: torch.Tensor) -> torch.Tensor: - # Complex FFT needs to be done in single precision - with torch.amp.autocast('cuda', enabled=False): - features = self._mel_spec_extractor(waveform=signals) - return features - - def _apply_normalization(self, features: torch.Tensor, lengths: torch.Tensor, eps: float = 1e-5) -> torch.Tensor: - # For consistency, this function always does a masked fill even if not normalizing. - mask: torch.Tensor = make_seq_mask_like(lengths=lengths, like=features, time_dim=-1, valid_ones=False) - features = features.masked_fill(mask, 0.0) - # Maybe don't normalize - if self._normalize_strategy is None: - return features - # Use the log zero guard for the sqrt zero guard - guard_value = self._resolve_log_zero_guard_value(features.dtype) - if self._normalize_strategy == "per_feature" or self._normalize_strategy == "all_features": - # 'all_features' reduces over each sample; 'per_feature' reduces over each channel - reduce_dim = 2 - if self._normalize_strategy == "all_features": - reduce_dim = [1, 2] - # [B, D, T] -> [B, D, 1] or [B, 1, 1] - means = features.sum(dim=reduce_dim, keepdim=True).div(lengths.view(-1, 1, 1)) - stds = ( - features.sub(means) - .masked_fill(mask, 0.0) - .pow(2.0) - .sum(dim=reduce_dim, keepdim=True) # [B, D, T] -> [B, D, 1] or [B, 1, 1] - .div(lengths.view(-1, 1, 1) - 1) # assume biased estimator - .clamp(min=guard_value) # avoid sqrt(0) - .sqrt() - ) - features = (features - means) / (stds + eps) - else: - # Deprecating constant std/mean - raise ValueError(f"Unsupported norm type: '{self._normalize_strategy}") - features = features.masked_fill(mask, 0.0) - return features - - def forward(self, input_signal: torch.Tensor, length: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: - feature_lengths = self._compute_output_lengths(input_lengths=length) - signals = self._apply_dithering(signals=input_signal) - signals = self._apply_preemphasis(signals=signals) - features = self._extract_spectrograms(signals=signals) - features = self._apply_log(features=features) - features = self._apply_normalization(features=features, lengths=feature_lengths) - features = self._apply_pad_to(features=features) - return features, feature_lengths diff --git a/nemo/collections/asr/parts/preprocessing/perturb.py b/nemo/collections/asr/parts/preprocessing/perturb.py index a63a051d3e0b76ccd8433de1a8208d58aef8c88e..6f1704d07f02dfeed923ae139fd67dec540acd2c 100644 --- a/nemo/collections/asr/parts/preprocessing/perturb.py +++ b/nemo/collections/asr/parts/preprocessing/perturb.py @@ -54,8 +54,10 @@ from nemo.utils import logging # TODO @blisc: Perhaps refactor instead of import guarding HAVE_OMEGACONG_WEBDATASET = True try: - import webdataset as wds from omegaconf import DictConfig, OmegaConf + + from nemo.utils import webdataset as wds + except ModuleNotFoundError: from nemo.utils.exceptions import LightningNotInstalledException @@ -171,17 +173,18 @@ class SpeedPerturbation(Perturbation): class TimeStretchPerturbation(Perturbation): """ - Time-stretch an audio series by a fixed rate while preserving pitch, based on [1, 2]. + 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. - Reference - [1] [Ellis, D. P. W. “A phase vocoder in Matlab.” Columbia University, 2002.] - (http://www.ee.columbia.edu/~dpwe/resources/matlab/pvoc/) - [2] [librosa.effects.time_stretch] - (https://librosa.github.io/librosa/generated/librosa.effects.time_stretch.html) + 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. diff --git a/nemo/collections/asr/parts/preprocessing/segment.py b/nemo/collections/asr/parts/preprocessing/segment.py index aceab6637006d9c73a5a3ae75bef75023dc101c8..00558769b0204eea08e0fde3027edfec5d096042 100644 --- a/nemo/collections/asr/parts/preprocessing/segment.py +++ b/nemo/collections/asr/parts/preprocessing/segment.py @@ -67,14 +67,15 @@ 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`. + 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. + 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 @@ -92,7 +93,8 @@ def select_channels(signal: npt.NDArray, channel_selector: Optional[ChannelSelec if num_channels >= num_samples: logging.warning( - 'Number of channels (%d) is greater or equal than number of samples (%d). Check for possible transposition.', + 'Number of channels (%d) is greater or equal than number of samples (%d). ' + 'Check for possible transposition.', num_channels, num_samples, ) @@ -199,7 +201,8 @@ class AudioSegment(object): 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 + # 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 @@ -260,10 +263,10 @@ class AudioSegment(object): Integers will be scaled to [-1, 1] in float32. """ float32_samples = samples.astype('float32') - if samples.dtype in np.sctypes['int']: + 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.sctypes['float']: + elif samples.dtype in (np.float16, np.float32, np.float64): pass else: raise TypeError("Unsupported sample type: %s." % samples.dtype) @@ -303,11 +306,12 @@ class AudioSegment(object): :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 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 + :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 @@ -415,7 +419,8 @@ class AudioSegment(object): # Shortcut when selecting a single channel if channel_selector >= len(audio_file_list): raise RuntimeError( - f'Channel cannot be selected: channel_selector={channel_selector}, num_audio_files={len(audio_file_list)}' + 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]] @@ -441,7 +446,8 @@ class AudioSegment(object): # 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} channels from file {a_file}' + f'Expecting a single-channel audio signal, but loaded {a_segment.num_channels} ' + f'channels from file {a_file}' ) if target_sr is None: @@ -523,14 +529,16 @@ class AudioSegment(object): 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 maximum possible ({max_audio_start})' + 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)}) of the audio file {audio_file}. This may lead to shape mismatch errors." + 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: @@ -550,14 +558,17 @@ class AudioSegment(object): @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: @@ -565,10 +576,12 @@ class AudioSegment(object): @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 @@ -579,21 +592,26 @@ class AudioSegment(object): @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): @@ -622,7 +640,8 @@ class AudioSegment(object): 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. Current samples dimension: {samples_ndim}." + f"Padding not implemented for signals with more that 2 dimensions. " + f"Current samples dimension: {samples_ndim}." ) # apply padding self._samples = np.pad( diff --git a/nemo/collections/asr/parts/submodules/adapters/attention_adapter_mixin.py b/nemo/collections/asr/parts/submodules/adapters/attention_adapter_mixin.py index 9fee3cea24360ec37dafbb4ef927ad1e26e47223..9efbcee76f0f8064db2f7d2c1a970dde53b08b91 100644 --- a/nemo/collections/asr/parts/submodules/adapters/attention_adapter_mixin.py +++ b/nemo/collections/asr/parts/submodules/adapters/attention_adapter_mixin.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. 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 index 4319a6962f4fc74041fab16bc4f720a27de30b72..b0cf8cbc0035097d5f5f85de6422c9bc095a3f67 100644 --- 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 @@ -25,7 +25,6 @@ from nemo.collections.asr.parts.submodules.adapters.multi_head_attention_adapter MHAResidualAddAdapterStrategyConfig, ) from nemo.collections.common.parts import adapter_modules -from nemo.core.classes.mixins import adapter_mixin_strategies, adapter_mixins class TransformerMultiHeadAttentionAdapter(transformer_modules.MultiHeadAttention, adapter_modules.AdapterModuleUtil): @@ -104,7 +103,9 @@ class TransformerMultiHeadAttentionAdapter(transformer_modules.MultiHeadAttentio key = self.pre_norm(keys) value = self.pre_norm(values) - return super().forward(query, key, value, attention_mask) + output, extra_output = super().forward(query, key, value, attention_mask) + + return output def reset_parameters(self): with torch.no_grad(): diff --git a/nemo/collections/vlm/recipes/__init__.py b/nemo/collections/asr/parts/submodules/aed_decoding/__init__.py similarity index 65% rename from nemo/collections/vlm/recipes/__init__.py rename to nemo/collections/asr/parts/submodules/aed_decoding/__init__.py index fc1642224f5903ebd55ca3a5604486ece93dbdbe..30c675039aa064098090957750c2e08f446ad8f1 100644 --- a/nemo/collections/vlm/recipes/__init__.py +++ b/nemo/collections/asr/parts/submodules/aed_decoding/__init__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -12,14 +12,12 @@ # See the License for the specific language governing permissions and # limitations under the License. - -from nemo.collections.vlm.recipes import clip_b32, llava15_7b, llava15_13b, llava_next_7b, mllama_11b, mllama_90b +from nemo.collections.asr.parts.submodules.aed_decoding.aed_batched_streaming import ( + GreedyBatchedStreamingAEDComputer, + return_decoder_input_ids, +) __all__ = [ - "llava15_7b", - "llava15_13b", - "mllama_11b", - "mllama_90b", - "llava_next_7b", - "clip_b32", + "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 new file mode 100644 index 0000000000000000000000000000000000000000..da15ea110da8df0b609d99ce4f6eea6061186dbe --- /dev/null +++ b/nemo/collections/asr/parts/submodules/aed_decoding/aed_batched_streaming.py @@ -0,0 +1,546 @@ +# 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/ctc_batched_beam_decoding.py b/nemo/collections/asr/parts/submodules/ctc_batched_beam_decoding.py new file mode 100644 index 0000000000000000000000000000000000000000..66165100f3ad8c10c87ad9359b46e3d3f66ad2fb --- /dev/null +++ b/nemo/collections/asr/parts/submodules/ctc_batched_beam_decoding.py @@ -0,0 +1,751 @@ +# 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 index 5328af1b778522848914288e9625b77d7820ccb7..362c784deaf505700add07fff78d347f66136235 100644 --- a/nemo/collections/asr/parts/submodules/ctc_beam_decoding.py +++ b/nemo/collections/asr/parts/submodules/ctc_beam_decoding.py @@ -21,16 +21,17 @@ from typing import List, Optional, Tuple, Union import torch -from nemo.collections.asr.parts.k2.classes import GraphIntersectDenseConfig +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 -DEFAULT_TOKEN_OFFSET = 100 - def pack_hypotheses( hypotheses: List[rnnt_utils.NBestHypotheses], @@ -205,7 +206,7 @@ class AbstractBeamCTCInfer(Typing): class BeamCTCInfer(AbstractBeamCTCInfer): - """A greedy CTC decoder. + """A beam CTC decoder. Provides a common abstraction for sample level and batch level greedy decoding. @@ -228,9 +229,9 @@ class BeamCTCInfer(AbstractBeamCTCInfer): return_best_hypothesis: bool = True, preserve_alignments: bool = False, compute_timestamps: bool = False, - beam_alpha: float = 1.0, + ngram_lm_alpha: float = 0.3, beam_beta: float = 0.0, - kenlm_path: str = None, + ngram_lm_model: str = None, flashlight_cfg: Optional['FlashlightConfig'] = None, pyctcdecode_cfg: Optional['PyCTCDecodeConfig'] = None, ): @@ -261,11 +262,11 @@ class BeamCTCInfer(AbstractBeamCTCInfer): # Log the beam search algorithm logging.info(f"Beam search algorithm: {search_type}") - self.beam_alpha = beam_alpha + self.ngram_lm_alpha = ngram_lm_alpha self.beam_beta = beam_beta # Default beam search args - self.kenlm_path = kenlm_path + self.ngram_lm_model = ngram_lm_model # PyCTCDecode params if pyctcdecode_cfg is None: @@ -350,9 +351,9 @@ class BeamCTCInfer(AbstractBeamCTCInfer): if self.default_beam_scorer is None: # Check for filepath - if self.kenlm_path is None or not os.path.exists(self.kenlm_path): + 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.kenlm_path}. " + f"KenLM binary file not found at : {self.ngram_lm_model}. " f"Please set a valid path in the decoding config." ) @@ -368,9 +369,9 @@ class BeamCTCInfer(AbstractBeamCTCInfer): self.default_beam_scorer = BeamSearchDecoderWithLM( vocab=vocab, - lm_path=self.kenlm_path, + lm_path=self.ngram_lm_model, beam_width=self.beam_size, - alpha=self.beam_alpha, + alpha=self.ngram_lm_alpha, beta=self.beam_beta, num_cpus=max(1, os.cpu_count()), input_tensor=False, @@ -452,7 +453,7 @@ class BeamCTCInfer(AbstractBeamCTCInfer): if self.pyctcdecode_beam_scorer is None: self.pyctcdecode_beam_scorer = pyctcdecode.build_ctcdecoder( - labels=self.vocab, kenlm_model_path=self.kenlm_path, alpha=self.beam_alpha, beta=self.beam_beta + 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() @@ -534,9 +535,9 @@ class BeamCTCInfer(AbstractBeamCTCInfer): if self.flashlight_beam_scorer is None: # Check for filepath - if self.kenlm_path is None or not os.path.exists(self.kenlm_path): + 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.kenlm_path}. " + f"KenLM binary file not found at : {self.ngram_lm_model}. " "Please set a valid path in the decoding config." ) @@ -551,7 +552,7 @@ class BeamCTCInfer(AbstractBeamCTCInfer): from nemo.collections.asr.modules.flashlight_decoder import FlashLightKenLMBeamSearchDecoder self.flashlight_beam_scorer = FlashLightKenLMBeamSearchDecoder( - lm_path=self.kenlm_path, + lm_path=self.ngram_lm_model, vocabulary=self.vocab, tokenizer=self.tokenizer, lexicon_path=self.flashlight_cfg.lexicon_path, @@ -559,7 +560,7 @@ class BeamCTCInfer(AbstractBeamCTCInfer): beam_size=self.beam_size, beam_size_token=self.flashlight_cfg.beam_size_token, beam_threshold=self.flashlight_cfg.beam_threshold, - lm_weight=self.beam_alpha, + 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, @@ -622,7 +623,7 @@ class WfstCTCInfer(AbstractBeamCTCInfer): self, blank_id: int, beam_size: int, - search_type: str = "riva", # 'riva', 'k2' + search_type: str = "riva", return_best_hypothesis: bool = True, preserve_alignments: bool = False, compute_timestamps: bool = False, @@ -634,7 +635,6 @@ class WfstCTCInfer(AbstractBeamCTCInfer): arpa_lm_path: str = None, wfst_lm_path: str = None, riva_decoding_cfg: Optional['RivaDecoderConfig'] = None, - k2_decoding_cfg: Optional['GraphIntersectDenseConfig'] = None, ): super().__init__(blank_id=blank_id, beam_size=beam_size) @@ -646,8 +646,6 @@ class WfstCTCInfer(AbstractBeamCTCInfer): self.decoding_algorithm = None if search_type in ("default", "riva"): self.decoding_algorithm = self._riva_decoding - elif search_type == "k2": - self.decoding_algorithm = self._k2_decoding # Log the WFST search_type logging.info(f"WFST beam search search_type: {search_type}") @@ -673,11 +671,9 @@ class WfstCTCInfer(AbstractBeamCTCInfer): self.wfst_lm_path = wfst_lm_path self.riva_decoding_cfg = riva_decoding_cfg - self.k2_decoding_cfg = k2_decoding_cfg # Default beam search scorer functions self.riva_decoder = None - self.k2_decoder = None @typecheck() def forward( @@ -708,7 +704,7 @@ class WfstCTCInfer(AbstractBeamCTCInfer): 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, k2)" + f"Please use one of : (default, riva)" ) with torch.no_grad(), torch.inference_mode(): @@ -732,7 +728,7 @@ class WfstCTCInfer(AbstractBeamCTCInfer): return (packed_result,) - def _prepare_decoding_lm_wfst(self) -> Union[str, 'kaldifst.StdFst', 'k2.Fsa']: # noqa: F821 + 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) @@ -742,10 +738,6 @@ class WfstCTCInfer(AbstractBeamCTCInfer): raise ValueError( f"Search type `riva` expects WFSTs in the `.fst` format. Provided: `{self.wfst_lm_path}`" ) - if self.search_type == "k2" and not self.wfst_lm_path.endswith(".pt"): - raise ValueError( - f"Search type `k2` expects WFSTs in the `.pt` 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." @@ -769,7 +761,7 @@ class WfstCTCInfer(AbstractBeamCTCInfer): 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" if self.search_type == "riva" else "k2" + target = "kaldi" from nemo.collections.asr.parts.utils.wfst_utils import mkgraph_ctc_ov @@ -832,50 +824,136 @@ class WfstCTCInfer(AbstractBeamCTCInfer): return self.riva_decoder.decode(x.to(device=self.device), out_len.to(device=self.device)) - @torch.no_grad() - def _k2_decoding(self, x: torch.Tensor, out_len: torch.Tensor) -> List['WfstNbestHypothesis']: - """ - K2 WFST decoder Algorithm. + +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: - 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. + decoder_output: A tensor of size (batch, timesteps, features). + decoder_lengths: list of int representing the length of each sequence + output sequence. Returns: - A list of WfstNbestHypothesis objects, one for each sequence in the batch. + packed list containing batch number of sentences (Hypotheses). """ - if self.k2_decoder is None: - lm_fst = self._prepare_decoding_lm_wfst() - if self.open_vocabulary_decoding and self._tokenword_disambig_id == -1: - if isinstance(lm_fst, str): - from nemo.collections.asr.parts.k2.utils import load_graph - - with torch.inference_mode(False): - lm_fst = load_graph(lm_fst) - try: - tokenword_disambig_id = lm_fst.aux_labels_sym.get("#1") - self._tokenword_disambig_id = tokenword_disambig_id - except KeyError: - raise ValueError( - "Cannot determine `tokenword_disambig_id` " - "which is required if `open_vocabulary_decoding` == True" - ) + 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}" + ) - from nemo.collections.asr.parts.k2.graph_decoders import K2WfstDecoder + batched_beam_hyps = self.search_algorithm(decoder_output, decoder_lengths) - self.k2_decoder = K2WfstDecoder( - lm_fst=lm_fst, - decoding_mode=self.decoding_mode, - beam_size=self.beam_width, - config=self.k2_decoding_cfg, - tokenword_disambig_id=self._tokenword_disambig_id, - lm_weight=self.lm_weight, - nbest_size=self.beam_size, - device=self.device, - ) + 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 self.k2_decoder.decode(x.to(device=self.device), out_len.to(device=self.device)) + return (hyps,) @dataclass @@ -907,10 +985,16 @@ class BeamCTCInferConfig: preserve_alignments: bool = False compute_timestamps: bool = False return_best_hypothesis: bool = True + allow_cuda_graphs: bool = True - beam_alpha: float = 1.0 - beam_beta: float = 0.0 - kenlm_path: Optional[str] = None + 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()) @@ -919,7 +1003,7 @@ class BeamCTCInferConfig: @dataclass class WfstCTCInferConfig: beam_size: int - search_type: str = "riva" # 'riva', 'k2' + search_type: str = "riva" return_best_hypothesis: bool = True preserve_alignments: bool = False compute_timestamps: bool = False @@ -931,4 +1015,3 @@ class WfstCTCInferConfig: arpa_lm_path: Optional[str] = None wfst_lm_path: Optional[str] = None riva_decoding_cfg: Optional['RivaDecoderConfig'] = field(default_factory=lambda: RivaDecoderConfig()) - k2_decoding_cfg: Optional['GraphIntersectDenseConfig'] = field(default_factory=lambda: GraphIntersectDenseConfig()) diff --git a/nemo/collections/asr/parts/submodules/ctc_decoding.py b/nemo/collections/asr/parts/submodules/ctc_decoding.py index 13591a8b113fe906c9c86db8746552440defdac7..9d8fcbc49f4cdbf1fa26aad607565b7ceb67f574 100644 --- a/nemo/collections/asr/parts/submodules/ctc_decoding.py +++ b/nemo/collections/asr/parts/submodules/ctc_decoding.py @@ -12,11 +12,11 @@ # See the License for the specific language governing permissions and # limitations under the License. +import copy import re -import unicodedata -from abc import abstractmethod +from abc import abstractmethod, abstractproperty from dataclasses import dataclass, field, is_dataclass -from typing import Callable, Dict, List, Optional, Set, Union +from typing import Dict, List, Optional, Set, Union import numpy as np import torch @@ -25,6 +25,8 @@ 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 @@ -177,20 +179,27 @@ class AbstractCTCDecoding(ConfidenceMixin): 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. - beam_alpha: + ngram_lm_alpha: float, the strength of the Language model on the final score of a token. - final_score = acoustic_score + beam_alpha * lm_score + beam_beta * seq_length. + 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 + beam_alpha * lm_score + beam_beta * seq_length. + final_score = acoustic_score + ngram_lm_alpha * lm_score + beam_beta * seq_length. - kenlm_path: + 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: @@ -225,7 +234,7 @@ class AbstractCTCDecoding(ConfidenceMixin): 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'] + 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}") @@ -243,6 +252,14 @@ class AbstractCTCDecoding(ConfidenceMixin): 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)) @@ -258,6 +275,20 @@ class AbstractCTCDecoding(ConfidenceMixin): 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, @@ -274,6 +305,12 @@ class AbstractCTCDecoding(ConfidenceMixin): 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': @@ -285,9 +322,9 @@ class AbstractCTCDecoding(ConfidenceMixin): return_best_hypothesis=self.cfg.beam.get('return_best_hypothesis', True), preserve_alignments=self.preserve_alignments, compute_timestamps=self.compute_timestamps, - beam_alpha=self.cfg.beam.get('beam_alpha', 1.0), + ngram_lm_alpha=self.cfg.beam.get('ngram_lm_alpha', 1.0), beam_beta=self.cfg.beam.get('beam_beta', 0.0), - kenlm_path=self.cfg.beam.get('kenlm_path', None), + ngram_lm_model=self.cfg.beam.get('ngram_lm_model', None), ) self.decoding.override_fold_consecutive_value = False @@ -301,9 +338,9 @@ class AbstractCTCDecoding(ConfidenceMixin): return_best_hypothesis=self.cfg.beam.get('return_best_hypothesis', True), preserve_alignments=self.preserve_alignments, compute_timestamps=self.compute_timestamps, - beam_alpha=self.cfg.beam.get('beam_alpha', 1.0), + ngram_lm_alpha=self.cfg.beam.get('ngram_lm_alpha', 1.0), beam_beta=self.cfg.beam.get('beam_beta', 0.0), - kenlm_path=self.cfg.beam.get('kenlm_path', None), + ngram_lm_model=self.cfg.beam.get('ngram_lm_model', None), pyctcdecode_cfg=self.cfg.beam.get('pyctcdecode_cfg', None), ) @@ -318,9 +355,9 @@ class AbstractCTCDecoding(ConfidenceMixin): return_best_hypothesis=self.cfg.beam.get('return_best_hypothesis', True), preserve_alignments=self.preserve_alignments, compute_timestamps=self.compute_timestamps, - beam_alpha=self.cfg.beam.get('beam_alpha', 1.0), + ngram_lm_alpha=self.cfg.beam.get('ngram_lm_alpha', 1.0), beam_beta=self.cfg.beam.get('beam_beta', 0.0), - kenlm_path=self.cfg.beam.get('kenlm_path', None), + ngram_lm_model=self.cfg.beam.get('ngram_lm_model', None), flashlight_cfg=self.cfg.beam.get('flashlight_cfg', None), ) @@ -343,7 +380,26 @@ class AbstractCTCDecoding(ConfidenceMixin): 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), - k2_decoding_cfg=self.cfg.wfst.get('k2_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 @@ -354,6 +410,13 @@ class AbstractCTCDecoding(ConfidenceMixin): 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, @@ -427,7 +490,7 @@ class AbstractCTCDecoding(ConfidenceMixin): all_hypotheses.append(decoded_hyps) if return_hypotheses: - return all_hypotheses # type: list[list[Hypothesis]] + 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] @@ -525,11 +588,7 @@ class AbstractCTCDecoding(ConfidenceMixin): # in order to compute exact time stamps. hypothesis = (decoded_prediction, token_lengths, token_repetitions) else: - hypothesis = self.decode_tokens_to_str(decoded_prediction) - - # TODO: remove - # collapse leading spaces before . , ? for PC models - hypothesis = re.sub(r'(\s+)([\.\,\?])', r'\2', hypothesis) + hypothesis = self.decode_tokens_to_str_with_strip_punctuation(decoded_prediction) # Preserve this wrapped hypothesis or decoded text tokens. hypotheses_list[ind].text = hypothesis @@ -607,6 +666,23 @@ class AbstractCTCDecoding(ConfidenceMixin): """ 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. @@ -644,35 +720,37 @@ class AbstractCTCDecoding(ConfidenceMixin): 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): - char_offsets[i]["char"] = self.decode_tokens_to_str([char]) + 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"]]) - char_offsets = self._refine_timestamps(char_offsets, self.supported_punctuation) - - # detect char vs subword models - lens = [len(list(v["char"])) > 1 for v in char_offsets] - if any(lens): - text_type = 'subword' - else: - text_type = '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']: - if text_type == 'char': - word_offsets = self._get_word_offsets_chars(char_offsets, word_delimiter_char=self.word_seperator) - else: - word_offsets = self._get_word_offsets_subwords_sentencepiece( - char_offsets, - hypothesis, - decode_ids_to_tokens=self.decode_ids_to_tokens, - decode_tokens_to_str=self.decode_tokens_to_str, - ) + 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 = segment_offsets = self._get_segment_offsets( + segment_offsets = get_segment_offsets( word_offsets, segment_delimiter_tokens=self.segment_seperators, supported_punctuation=self.supported_punctuation, @@ -701,7 +779,7 @@ class AbstractCTCDecoding(ConfidenceMixin): hypothesis.timestamp['segment'] = segment_offsets # Convert the token indices to text - hypothesis.text = self.decode_tokens_to_str(hypothesis.text) + hypothesis.text = self.decode_tokens_to_str_with_strip_punctuation(hypothesis.text) return hypothesis @@ -744,244 +822,23 @@ class AbstractCTCDecoding(ConfidenceMixin): @staticmethod def _refine_timestamps( - char_offsets: List[Dict[str, Union[str, int]]], supported_punctuation: Optional[Set] = None + 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 char_offsets + 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 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: - offset['end_offset'] = offset['start_offset'] - - return char_offsets - - @staticmethod - def _get_word_offsets_chars( - offsets: Dict[str, Union[str, float]], word_delimiter_char: str = " " - ) -> Dict[str, Union[str, float]]: - """ - Utility method which constructs word time stamps out of character time stamps. + encoded_char_offsets[i]['end_offset'] = offset['end_offset'] = offset['start_offset'] - References: - This code is a port of the Hugging Face code for word time stamp construction. - - Args: - offsets: A list of dictionaries, each containing "char", "start_offset" and "end_offset". - word_delimiter_char: Character token that represents the word delimiter. By default, " ". - - Returns: - A list of dictionaries containing the word offsets. Each item contains "word", "start_offset" and - "end_offset". - """ - word_offsets = [] - - last_state = "SPACE" - word = "" - start_offset = 0 - end_offset = 0 - for i, offset in enumerate(offsets): - char = offset["char"] - state = "SPACE" if char == word_delimiter_char else "WORD" - - if state == last_state: - # If we are in the same state as before, we simply repeat what we've done before - end_offset = offset["end_offset"] - word += char - else: - # Switching state - if state == "SPACE": - # Finishing a word - word_offsets.append({"word": word, "start_offset": start_offset, "end_offset": end_offset}) - else: - # Starting a new word - start_offset = offset["start_offset"] - end_offset = offset["end_offset"] - word = char - - last_state = state - if last_state == "WORD": - word_offsets.append({"word": word, "start_offset": start_offset, "end_offset": end_offset}) - - return word_offsets - - @staticmethod - def _get_word_offsets_subwords_sentencepiece( - offsets: Dict[str, Union[str, float]], - hypothesis: Hypothesis, - decode_ids_to_tokens: Callable[[List[int]], str], - decode_tokens_to_str: Callable[[List[int]], str], - ) -> Dict[str, Union[str, float]]: - """ - Utility method which constructs word time stamps out of sub-word time stamps. - - **Note**: Only supports Sentencepiece based tokenizers ! - - Args: - offsets: A list of dictionaries, each containing "char", "start_offset" and "end_offset". - hypothesis: Hypothesis object that contains `text` field, where each token is a sub-word id - after ctc collapse. - decode_ids_to_tokens: A Callable function that accepts a list of integers and maps it to a sub-word. - decode_tokens_to_str: A Callable function that accepts a list of integers and maps it to text / str. - - Returns: - A list of dictionaries containing the word offsets. Each item contains "word", "start_offset" and - "end_offset". - """ - word_offsets = [] - built_token = [] - previous_token_index = 0 - # For every collapsed sub-word token - for i, char in enumerate(hypothesis.text): - # Compute the sub-word text representation, and the decoded text (stripped of sub-word markers). - token = decode_ids_to_tokens([char])[0] - token_text = decode_tokens_to_str([char]) - - # 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. - if token != token_text: - # 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 len(built_token) > 0: - word_offsets.append( - { - "word": decode_tokens_to_str(built_token), - "start_offset": offsets[previous_token_index]["start_offset"], - "end_offset": offsets[i - 1]["end_offset"], - } - ) - - # Prepare list of new sub-word ids - built_token.clear() - built_token.append(char) - previous_token_index = i - else: - # If the token does not contain any sub-word start mark, then the sub-word has not completed yet - # Append to current sub-word list. - built_token.append(char) - - # 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 len(built_token) > 0: - word_offsets.append( - { - "word": decode_tokens_to_str(built_token), - "start_offset": offsets[0]["start_offset"], - "end_offset": offsets[-1]["end_offset"], - } - ) - built_token.clear() - else: - word_offsets[0]["start_offset"] = offsets[0]["start_offset"] - - # 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 len(built_token) > 0: - word_offsets.append( - { - "word": decode_tokens_to_str(built_token), - "start_offset": offsets[-(len(built_token))]["start_offset"], - "end_offset": offsets[-1]["end_offset"], - } - ) - built_token.clear() - - return word_offsets - - @staticmethod - def _get_segment_offsets( - offsets: Dict[str, Union[str, float]], - segment_delimiter_tokens: List[str], - supported_punctuation: Optional[Set] = None, - segment_gap_threshold: Optional[int] = None, - ) -> 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(offsets): - - word = offset['word'] - # check if thr word ends with any delimeter token or the word itself is a delimeter - if segment_gap_threshold and segment_words: - gap_between_words = offset['start_offset'] - offsets[i - 1]['end_offset'] - - if gap_between_words >= segment_gap_threshold: - segment_offsets.append( - { - "segment": ' '.join(segment_words), - "start_offset": offsets[previous_word_index]["start_offset"], - "end_offset": offsets[i - 1]["end_offset"], - } - ) - - segment_words = [word] - previous_word_index = i - continue - - 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": offsets[previous_word_index]["start_offset"], - "end_offset": offset["end_offset"], - } - ) - - segment_words = [] - previous_word_index = i + 1 - continue - - segment_words.append(word) - - if segment_words: - start_offset = offsets[previous_word_index]["start_offset"] - segment_offsets.append( - { - "segment": ' '.join(segment_words), - "start_offset": start_offset, - "end_offset": offsets[-1]["end_offset"], - } - ) - segment_words.clear() - - return segment_offsets + return encoded_char_offsets, char_offsets @property def preserve_alignments(self): @@ -1161,15 +1018,15 @@ class CTCDecoding(AbstractCTCDecoding): 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. - beam_alpha: + ngram_lm_alpha: float, the strength of the Language model on the final score of a token. - final_score = acoustic_score + beam_alpha * lm_score + beam_beta * seq_length. + 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 + beam_alpha * lm_score + beam_beta * seq_length. + final_score = acoustic_score + ngram_lm_alpha * lm_score + beam_beta * seq_length. - kenlm_path: + 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 @@ -1187,9 +1044,7 @@ class CTCDecoding(AbstractCTCDecoding): self.vocabulary = vocabulary self.labels_map = dict([(i, vocabulary[i]) for i in range(len(vocabulary))]) - supported_punctuation = { - char for token in vocabulary for char in token if unicodedata.category(char).startswith('P') - } + supported_punctuation = extract_punctuation_from_vocab(vocabulary) super().__init__(decoding_cfg=decoding_cfg, blank_id=blank_id, supported_punctuation=supported_punctuation) @@ -1198,6 +1053,10 @@ class CTCDecoding(AbstractCTCDecoding): 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. @@ -1212,17 +1071,17 @@ class CTCDecoding(AbstractCTCDecoding): self.decode_tokens_to_str(hypothesis.text[0]).split(), hypothesis.token_confidence ) - def decode_tokens_to_str(self, tokens: List[int]) -> str: + 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. + tokens: List of str representing the token str. Returns: A decoded string. """ - hypothesis = ''.join(self.decode_ids_to_tokens(tokens)) + hypothesis = ''.join(tokens) return hypothesis def decode_ids_to_tokens(self, tokens: List[int]) -> List[str]: @@ -1378,31 +1237,38 @@ class CTCBPEDecoding(AbstractCTCDecoding): 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. - beam_alpha: + ngram_lm_alpha: float, the strength of the Language model on the final score of a token. - final_score = acoustic_score + beam_alpha * lm_score + beam_beta * seq_length. + 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 + beam_alpha * lm_score + beam_beta * seq_length. + final_score = acoustic_score + ngram_lm_alpha * lm_score + beam_beta * seq_length. - kenlm_path: + 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 - vocabulary = self.tokenizer.vocab - supported_punctuation = { - char for token in vocabulary for char in token if unicodedata.category(char).startswith('P') - } + 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) @@ -1421,6 +1287,10 @@ class CTCBPEDecoding(AbstractCTCDecoding): 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. @@ -1437,17 +1307,17 @@ class CTCBPEDecoding(AbstractCTCDecoding): self.decode_tokens_to_str(hypothesis.text[0]).split(), hypothesis.token_confidence, hypothesis.text[0] ) - def decode_tokens_to_str(self, tokens: List[int]) -> str: + 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. + tokens: List of str representing the tokens. Returns: A decoded string. """ - hypothesis = self.tokenizer.ids_to_text(tokens) + hypothesis = self.tokenizer.tokens_to_text(tokens) return hypothesis def decode_ids_to_tokens(self, tokens: List[int]) -> List[str]: diff --git a/nemo/collections/asr/parts/submodules/ctc_greedy_decoding.py b/nemo/collections/asr/parts/submodules/ctc_greedy_decoding.py index bdcb71e9d7213beca02633eca894f64f3b8f2c7b..7e587fd75c441c14a7666454c549f8eeb2316259 100644 --- a/nemo/collections/asr/parts/submodules/ctc_greedy_decoding.py +++ b/nemo/collections/asr/parts/submodules/ctc_greedy_decoding.py @@ -13,16 +13,125 @@ # limitations under the License. from dataclasses import dataclass, field -from typing import List, Optional +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( @@ -281,7 +390,7 @@ class GreedyCTCInfer(Typing, ConfidenceMethodMixin): return self.forward(*args, **kwargs) -class GreedyBatchedCTCInfer(Typing, ConfidenceMethodMixin): +class GreedyBatchedCTCInfer(Typing, ConfidenceMethodMixin, WithOptionalCudaGraphs): """A vectorized greedy CTC decoder. This is basically always faster than GreedyCTCInfer, and supports @@ -337,6 +446,14 @@ class GreedyBatchedCTCInfer(Typing, ConfidenceMethodMixin): """ + 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.""" @@ -360,6 +477,12 @@ class GreedyBatchedCTCInfer(Typing, ConfidenceMethodMixin): 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__() @@ -372,6 +495,29 @@ class GreedyBatchedCTCInfer(Typing, ConfidenceMethodMixin): # 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, @@ -407,6 +553,8 @@ class GreedyBatchedCTCInfer(Typing, ConfidenceMethodMixin): 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) @@ -422,9 +570,24 @@ class GreedyBatchedCTCInfer(Typing, ConfidenceMethodMixin): max_time = x.shape[1] predictions = x - # In CTC greedy decoding, each output maximum likelihood token - # is calculated independent of the other tokens. - predictions_logprobs, predictions_labels = predictions.max(dim=-1) + + 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". @@ -515,6 +678,334 @@ class GreedyBatchedCTCInfer(Typing, ConfidenceMethodMixin): 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) @@ -526,6 +1017,12 @@ class GreedyCTCInferConfig: 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( 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 index a0be0e1f4a04aa69534e54b1d2c3f1724f3c3712..5e4e179266a75eb14b6bcaad13ade764364482cb 100644 --- a/nemo/collections/asr/parts/submodules/cuda_graph_rnnt_greedy_decoding.py +++ b/nemo/collections/asr/parts/submodules/cuda_graph_rnnt_greedy_decoding.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -13,17 +13,11 @@ # limitations under the License. +from typing import List, Optional + import numpy as np import torch -try: - from cuda import cudart - - HAVE_CUDA_PYTHON = True -except ImportError: - HAVE_CUDA_PYTHON = False -from typing import List, Optional - 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, @@ -31,6 +25,10 @@ from nemo.core.utils.cuda_python_utils import ( 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" @@ -77,7 +75,7 @@ def create_inner_while_loop_kernel(): class RNNTGreedyDecodeCudaGraph: def __init__(self, max_symbols: int, caller): - if HAVE_CUDA_PYTHON: + if CUDA_PYTHON_AVAILABLE: check_cuda_python_cuda_graphs_conditional_nodes_supported() else: raise ValueError("Cannot instantiate RNNTGreedyDecodeCudaGraph without `pip install cuda-python`") @@ -114,6 +112,7 @@ class RNNTGreedyDecodeCudaGraph: 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 @@ -205,7 +204,8 @@ class RNNTGreedyDecodeCudaGraph: # Get max sequence length self.max_out_len_t = self.encoder_output_length.max() - capture_status, _, graph, _, _ = cu_call( + # 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 diff --git a/nemo/collections/asr/parts/submodules/jasper.py b/nemo/collections/asr/parts/submodules/jasper.py index ec0def1b3ebbfd88efbdd8e409daa783ab95b139..f29332ea522b83e30cc29dc32e770cba67b1c1bd 100644 --- a/nemo/collections/asr/parts/submodules/jasper.py +++ b/nemo/collections/asr/parts/submodules/jasper.py @@ -477,7 +477,13 @@ class SqueezeExcite(nn.Module): # 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 - x = x.float() # For stable AMP, SE must be computed at fp32. + + # 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] @@ -490,6 +496,8 @@ class SqueezeExcite(nn.Module): 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): diff --git a/nemo/collections/asr/parts/submodules/multitask_beam_decoding.py b/nemo/collections/asr/parts/submodules/multitask_beam_decoding.py index d49c6e69215f82592da39c2a5b8c6f042f04b905..3c2a424dcd09974aa193e73967c658c75c55b754 100644 --- a/nemo/collections/asr/parts/submodules/multitask_beam_decoding.py +++ b/nemo/collections/asr/parts/submodules/multitask_beam_decoding.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -13,12 +13,18 @@ # limitations under the License. from abc import ABC, abstractmethod -from dataclasses import dataclass +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 +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 @@ -27,7 +33,10 @@ from nemo.utils import logging def pack_hypotheses( - hypotheses: List[Hypothesis], beam_hypotheses: torch.Tensor, scores: List[Optional[float]] + 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 @@ -43,6 +52,9 @@ def pack_hypotheses( 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 @@ -129,6 +141,11 @@ class TransformerAEDBeamInfer(AEDBeamInfer, Typing): 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, @@ -142,18 +159,53 @@ class TransformerAEDBeamInfer(AEDBeamInfer, Typing): self.bos = tokenizer.bos self.pad = tokenizer.pad self.eos = tokenizer.eos - 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, - ) + + # 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: @@ -183,7 +235,10 @@ class TransformerAEDBeamInfer(AEDBeamInfer, Typing): packed list containing batch number of sentences (Hypotheses). """ with torch.inference_mode(): - topk_hypotheses, beam_scores, best_hypo = self.beam_search( + 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, @@ -198,21 +253,28 @@ class TransformerAEDBeamInfer(AEDBeamInfer, Typing): 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]) - self.format_hypotheses(hypotheses, decoder_input_ids) 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) + 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], decoder_input_ids: Union[torch.Tensor, None]) -> None: + 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 @@ -224,21 +286,28 @@ class TransformerAEDBeamInfer(AEDBeamInfer, Typing): 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] :] - 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] + + 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 @@ -249,3 +318,8 @@ class AEDBeamInferConfig: 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 index 99010bdc14b8f96474012fb313c9dead1562b1a0..1d49a8bbda8ffa53dadd5166a1774d68f3ca43ce 100644 --- a/nemo/collections/asr/parts/submodules/multitask_decoding.py +++ b/nemo/collections/asr/parts/submodules/multitask_decoding.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -174,7 +174,10 @@ class AbstractMultiTaskDecoding(ConfidenceMixin): 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, @@ -185,6 +188,7 @@ class AbstractMultiTaskDecoding(ConfidenceMixin): 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': @@ -199,6 +203,11 @@ class AbstractMultiTaskDecoding(ConfidenceMixin): 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: @@ -295,7 +304,7 @@ class AbstractMultiTaskDecoding(ConfidenceMixin): if type(prediction) != list: prediction = prediction.tolist() - hypothesis = self.decode_tokens_to_str(prediction) + hypothesis = self.decode_ids_to_str(prediction) if self.compute_hypothesis_token_set: hypotheses_list[ind].tokens = self.decode_ids_to_tokens(prediction) @@ -511,7 +520,23 @@ class MultiTaskDecoding(AbstractMultiTaskDecoding): if isinstance(self.decoding, AEDBeamInfer): self.decoding.set_decoding_type('subword') - def decode_tokens_to_str(self, tokens: List[int]) -> str: + 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. @@ -595,6 +620,23 @@ class MultiTaskDecoding(AbstractMultiTaskDecoding): 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" @@ -618,3 +660,6 @@ class MultiTaskDecodingConfig: # 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 index eeae38ecef301e165fcb085bb3e68360c576cc9d..71dd97265ce7b751067e45263f7d794451e82289 100644 --- a/nemo/collections/asr/parts/submodules/multitask_greedy_decoding.py +++ b/nemo/collections/asr/parts/submodules/multitask_greedy_decoding.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -33,6 +33,7 @@ def pack_hypotheses( 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 @@ -52,6 +53,9 @@ def pack_hypotheses( 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 @@ -134,6 +138,7 @@ class TransformerAEDGreedyInfer(AEDGreedyInfer, Typing): 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, @@ -159,6 +164,7 @@ class TransformerAEDGreedyInfer(AEDGreedyInfer, Typing): 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 @@ -189,7 +195,10 @@ class TransformerAEDGreedyInfer(AEDGreedyInfer, Typing): packed list containing batch number of sentences (Hypotheses). """ with torch.inference_mode(): - best_hypo, topk_hypotheses, step_confidence = self.greedy_search( + 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, @@ -199,25 +208,39 @@ class TransformerAEDGreedyInfer(AEDGreedyInfer, Typing): 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 + 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) + 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: @@ -251,6 +274,8 @@ class TransformerAEDGreedyInfer(AEDGreedyInfer, Typing): 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 diff --git a/nemo/collections/nlp/data/spellchecking_asr_customization/__init__.py b/nemo/collections/asr/parts/submodules/ngram_lm/__init__.py similarity index 61% rename from nemo/collections/nlp/data/spellchecking_asr_customization/__init__.py rename to nemo/collections/asr/parts/submodules/ngram_lm/__init__.py index 4e786276108c13c8c7fb986ebf3caadcef73db2c..f0657d8aadaa0dc540cc5d15c0119c54439a29fa 100644 --- a/nemo/collections/nlp/data/spellchecking_asr_customization/__init__.py +++ b/nemo/collections/asr/parts/submodules/ngram_lm/__init__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# 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. @@ -13,8 +13,7 @@ # limitations under the License. -from nemo.collections.nlp.data.spellchecking_asr_customization.dataset import ( - SpellcheckingAsrCustomizationDataset, - SpellcheckingAsrCustomizationTestDataset, - TarredSpellcheckingAsrCustomizationDataset, -) +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/tts/models/speechllm/__init__.py b/nemo/collections/asr/parts/submodules/ngram_lm/constants.py similarity index 80% rename from nemo/collections/tts/models/speechllm/__init__.py rename to nemo/collections/asr/parts/submodules/ngram_lm/constants.py index 9df65818d226976845f5e1570ec263a48d304ba7..1b7c5d86efdb1e2848ecc869f2e45cdd45390b4e 100644 --- a/nemo/collections/tts/models/speechllm/__init__.py +++ b/nemo/collections/asr/parts/submodules/ngram_lm/constants.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# 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. @@ -11,3 +11,5 @@ # WITHOUT 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 new file mode 100644 index 0000000000000000000000000000000000000000..a38a6ab8d5069c58e4b94af75b316a7332de8ce5 --- /dev/null +++ b/nemo/collections/asr/parts/submodules/ngram_lm/kenlm_utils.py @@ -0,0 +1,245 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..b5335d2ed3a47791cedcb300687f20554804ce0c --- /dev/null +++ b/nemo/collections/asr/parts/submodules/ngram_lm/ngram_lm_batched.py @@ -0,0 +1,1129 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..0eb957e6b1a5982dc786e6934f317b2f02a80d31 --- /dev/null +++ b/nemo/collections/asr/parts/submodules/ngram_lm/ngram_lm_triton.py @@ -0,0 +1,177 @@ +# 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 index b34a962d280d703ebc067b2b1e4fdd0677e556e8..d0b02a73daaf7804fe7c53815723ba349ee571a0 100644 --- a/nemo/collections/asr/parts/submodules/rnnt_beam_decoding.py +++ b/nemo/collections/asr/parts/submodules/rnnt_beam_decoding.py @@ -27,7 +27,7 @@ # limitations under the License. import copy -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np @@ -35,6 +35,12 @@ 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, @@ -42,6 +48,7 @@ from nemo.collections.asr.parts.utils.rnnt_utils import ( 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 @@ -75,9 +82,10 @@ def pack_hypotheses(hypotheses: List[Hypothesis]) -> List[Hypothesis]: if hyp.dec_state is not None: hyp.dec_state = _states_to_device(hyp.dec_state) - # Remove -1 from timestep 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 @@ -265,6 +273,10 @@ class BeamRNNTInfer(Typing): 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 @@ -301,6 +313,27 @@ class BeamRNNTInfer(Typing): 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 @@ -351,13 +384,8 @@ class BeamRNNTInfer(Typing): self.token_offset = 0 if ngram_lm_model: - if KENLM_AVAILABLE: - self.ngram_lm = kenlm.Model(ngram_lm_model) - self.ngram_lm_alpha = ngram_lm_alpha - else: - raise ImportError( - "KenLM package (https://github.com/kpu/kenlm) is not installed. " "Use ngram_lm_model=None." - ) + self.ngram_lm = ngram_lm_model + self.ngram_lm_alpha = ngram_lm_alpha else: self.ngram_lm = None @@ -1492,11 +1520,190 @@ class BeamRNNTInfer(Typing): """ # 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 +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: """ @@ -1520,5 +1727,11 @@ class BeamRNNTInferConfig: 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 index 1a50f10d3ed43ca59e73d854c3391c5f2928e138..c9a0989d102237b71c0da8166d6e545ec04bf721 100644 --- a/nemo/collections/asr/parts/submodules/rnnt_decoding.py +++ b/nemo/collections/asr/parts/submodules/rnnt_decoding.py @@ -14,21 +14,74 @@ import copy import re -import unicodedata -from abc import abstractmethod +from abc import abstractmethod, abstractproperty from dataclasses import dataclass, field, is_dataclass -from typing import Callable, Dict, List, Optional, Set, Union +from typing import Dict, List, Optional, Set, Union -import numpy as np 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, logging_mode +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): @@ -229,29 +282,28 @@ class AbstractRNNTDecoding(ConfidenceMixin): 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.big_blank_durations is not None and self.big_blank_durations != []: + if self._with_multiple_blanks: raise ValueError("duration and big_blank_durations can't both be not None") - if self.cfg.strategy not in ['greedy', 'greedy_batch', 'beam', 'maes']: - raise ValueError( - "currently only greedy, greedy_batch, beam and maes inference is supported for TDT models" - ) - if ( - self.big_blank_durations is not None and self.big_blank_durations != [] - ): # this means it's a multi-blank model. - if blank_id == 0: - raise ValueError("blank_id must equal len(vocabs) for multi-blank RNN-T models") - if self.cfg.strategy not in ['greedy', 'greedy_batch']: - raise ValueError( - "currently only greedy and greedy_batch inference is supported for multi-blank models" - ) + if self._with_multiple_blanks and blank_id == 0: + raise ValueError("blank_id must equal len(vocabs) for multi-blank RNN-T models") - possible_strategies = ['greedy', 'greedy_batch', 'beam', 'tsd', 'alsd', 'maes'] - if self.cfg.strategy not in possible_strategies: - raise ValueError(f"Decoding strategy must be one of {possible_strategies}") + 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: @@ -269,18 +321,18 @@ class AbstractRNNTDecoding(ConfidenceMixin): elif self.cfg.strategy in ['beam', 'tsd', 'alsd', 'maes']: self.compute_timestamps = self.cfg.beam.get('compute_timestamps', False) - # Test if alignments are being preserved for RNNT - if not self._is_tdt and self.compute_timestamps is True and self.preserve_alignments is False: - raise ValueError("If `compute_timesteps` flag is set, then `preserve_alignments` flag must also be set.") + # 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 self._is_tdt: - if self.preserve_frame_confidence is True and self.preserve_alignments is False: - raise ValueError( - "If `preserve_frame_confidence` flag is set, then `preserve_alignments` flag must also be set." - ) + 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 @@ -293,38 +345,84 @@ class AbstractRNNTDecoding(ConfidenceMixin): ): raise NotImplementedError(f"Confidence calculation is not supported for strategy `{self.cfg.strategy}`") - if self.cfg.strategy == 'greedy': - if self.big_blank_durations is None or self.big_blank_durations == []: - if not self._is_tdt: - 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, + 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`." ) - else: - 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, + 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." ) - else: self.decoding = rnnt_greedy_decoding.GreedyMultiblankRNNTInfer( decoder_model=decoder, joint_model=joint, @@ -337,43 +435,48 @@ class AbstractRNNTDecoding(ConfidenceMixin): preserve_frame_confidence=self.preserve_frame_confidence, confidence_method_cfg=self.confidence_method_cfg, ) - - elif self.cfg.strategy == 'greedy_batch': - if self.big_blank_durations is None or self.big_blank_durations == []: - if not self._is_tdt: - 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), - ) - else: - 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), + # 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." ) - - else: self.decoding = rnnt_greedy_decoding.GreedyBatchedMultiblankRNNTInfer( decoder_model=decoder, joint_model=joint, @@ -386,108 +489,206 @@ class AbstractRNNTDecoding(ConfidenceMixin): preserve_frame_confidence=self.preserve_frame_confidence, confidence_method_cfg=self.confidence_method_cfg, ) - - elif self.cfg.strategy == 'beam': - if self.big_blank_durations is None or self.big_blank_durations == []: - if not self._is_tdt: - 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, + # 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`." ) - else: - 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, + 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`." ) - - elif self.cfg.strategy == 'tsd': - 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, - ) - - elif self.cfg.strategy == 'alsd': - 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, - ) - - elif self.cfg.strategy == 'maes': - if self.big_blank_durations is None or self.big_blank_durations == []: - if not self._is_tdt: - 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=self.cfg.beam.get('ngram_lm_model', None), - ngram_lm_alpha=self.cfg.beam.get('ngram_lm_alpha', 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), + 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`." ) - else: - 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=self.cfg.beam.get('ngram_lm_model', None), - ngram_lm_alpha=self.cfg.beam.get('ngram_lm_alpha', 0.3), + 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`." ) - else: - - raise ValueError( - f"Incorrect decoding strategy supplied. Must be one of {possible_strategies}\n" - f"but was provided {self.cfg.strategy}" - ) + 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, @@ -576,9 +777,9 @@ class AbstractRNNTDecoding(ConfidenceMixin): Returns: A list of strings. """ - for ind in range(len(hypotheses_list)): + for hyp in hypotheses_list: # Extract the integer encoded hypothesis - prediction = hypotheses_list[ind].y_sequence + prediction = hyp.y_sequence if type(prediction) != list: prediction = prediction.tolist() @@ -593,28 +794,11 @@ class AbstractRNNTDecoding(ConfidenceMixin): else: # standard RNN-T prediction = [p for p in prediction if p != self.blank_id] - # De-tokenize the integer tokens; if not computing timestamps - if self.compute_timestamps is True and self._is_tdt: - hypothesis = (prediction, None, None) - elif self.compute_timestamps is True: - # keep the original predictions, wrap with the number of repetitions per token and alignments - # this is done so that `rnnt_decoder_predictions_tensor()` can process this hypothesis - # in order to compute exact time stamps. - alignments = copy.deepcopy(hypotheses_list[ind].alignments) - token_repetitions = [1] * len(alignments) # preserve number of repetitions per token - hypothesis = (prediction, alignments, token_repetitions) - else: - hypothesis = self.decode_tokens_to_str(prediction) - - # TODO: remove - # collapse leading spaces before . , ? for PC models - hypothesis = re.sub(r'(\s+)([\.\,\?])', r'\2', hypothesis) - - if self.compute_hypothesis_token_set: - hypotheses_list[ind].tokens = self.decode_ids_to_tokens(prediction) + # De-tokenize the integer tokens; + hyp.text = self.decode_tokens_to_str_with_strip_punctuation(prediction) - # De-tokenize the integer tokens - hypotheses_list[ind].text = hypothesis + if self.compute_hypothesis_token_set: + hyp.tokens = self.decode_ids_to_tokens(prediction) return hypotheses_list @@ -753,6 +937,24 @@ class AbstractRNNTDecoding(ConfidenceMixin): """ 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. @@ -806,38 +1008,33 @@ class AbstractRNNTDecoding(ConfidenceMixin): """ assert timestamp_type in ['char', 'word', 'segment', 'all'] - # Unpack the temporary storage - decoded_prediction, alignments, token_repetitions = hypothesis.text - # Retrieve offsets char_offsets = word_offsets = None - char_offsets = self._compute_offsets(hypothesis, token_repetitions, self.blank_id) - - # finally, set the flattened decoded predictions to text field for later text decoding - hypothesis.text = decoded_prediction + 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] - # Assert number of offsets and hypothesis tokens are 1:1 match. - num_flattened_tokens = 0 - for t in range(len(char_offsets)): - # Subtract one here for the extra RNNT BLANK token emitted to designate "End of timestep" - num_flattened_tokens += len(char_offsets[t]['char']) - 1 - - if num_flattened_tokens != len(hypothesis.text): + if len(char_offsets) != len(y_sequence_blank_removed): raise ValueError( - f"`char_offsets`: {char_offsets} and `processed_tokens`: {hypothesis.text}" + 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(hypothesis.text)}" + 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): - decoded_chars = [] - for char in offsets['char'][:-1]: # ignore the RNNT Blank token at end of every timestep with -1 subset - decoded_chars.append(self.decode_tokens_to_str([int(char)])) - char_offsets[i]["char"] = decoded_chars + 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 @@ -856,31 +1053,21 @@ class AbstractRNNTDecoding(ConfidenceMixin): max_len = max(len(c) for c in tokens) lens.append(max_len) - # array of one or more chars implies subword based model with multiple char emitted per TxU step (via subword) - if sum(lens) > len(lens): - text_type = 'subword' - else: - # full array of ones implies character based model with 1 char emitted per TxU step - text_type = 'char' - # retrieve word offsets from character offsets word_offsets = None if timestamp_type in ['word', 'segment', 'all']: - if text_type == 'char': - word_offsets = self._get_word_offsets_chars(char_offsets, word_delimiter_char=self.word_seperator) - else: - # utilize the copy of char offsets with the correct integer ids for tokens - # so as to avoid tokenize -> detokenize -> compare -> merge steps. - word_offsets = self._get_word_offsets_subwords_sentencepiece( - encoded_char_offsets, - hypothesis, - decode_ids_to_tokens=self.decode_ids_to_tokens, - decode_tokens_to_str=self.decode_tokens_to_str, - ) + 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 = self._get_segment_offsets( + segment_offsets = get_segment_offsets( word_offsets, segment_delimiter_tokens=self.segment_seperators, supported_punctuation=self.supported_punctuation, @@ -908,59 +1095,39 @@ class AbstractRNNTDecoding(ConfidenceMixin): if segment_offsets is not None and timestamp_type in ['segment', 'all']: hypothesis.timestamp['segment'] = segment_offsets - # Convert the flattened token indices to text - hypothesis.text = self.decode_tokens_to_str(hypothesis.text) - return hypothesis @staticmethod - def _compute_offsets( - hypothesis: Hypothesis, token_repetitions: List[int], rnnt_token: int - ) -> List[Dict[str, Union[str, int]]]: + 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. - token_repetitions: A list of ints representing the number of repetitions of each emitted token. - rnnt_token: The integer of the rnnt blank token used during 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. """ - start_index = 0 - - # If the exact timestep information is available, utilize the 1st non-rnnt blank token timestep - # as the start index. - if hypothesis.timestamp is not None and len(hypothesis.timestamp) > 0: - first_timestep = hypothesis.timestamp[0] - first_timestep = first_timestep if isinstance(first_timestep, int) else first_timestep.item() - start_index = max(0, first_timestep - 1) - - # Construct the start and end indices brackets - end_indices = np.asarray(token_repetitions).cumsum() - start_indices = np.concatenate(([start_index], end_indices[:-1])) - - # Process the TxU dangling alignment tensor, containing pairs of (logits, label) - alignment_labels = [al_logits_labels for al_logits_labels in hypothesis.text[1]] - for t in range(len(alignment_labels)): - for u in range(len(alignment_labels[t])): - alignment_labels[t][u] = alignment_labels[t][u][1] # pick label from (logit, label) tuple + if isinstance(hypothesis.timestamp, torch.Tensor): + hypothesis.timestamp = hypothesis.timestamp.cpu().tolist() # Merge the results per token into a list of dictionaries offsets = [ - {"char": a, "start_offset": s, "end_offset": e} - for a, s, e in zip(alignment_labels, start_indices, end_indices) + {"char": [t], "start_offset": s, "end_offset": s + 1} + for t, s in zip(hypothesis.y_sequence, hypothesis.timestamp) + if t != blank_id ] - # Filter out RNNT token (blank at [t][0] position). This is because blank can only occur at end of a - # time step for RNNT, so if 0th token is blank, then that timestep is skipped. - offsets = list(filter(lambda offsets: offsets["char"][0] != rnnt_token, offsets)) return offsets @staticmethod - def _compute_offsets_tdt(hypothesis: Hypothesis, *args) -> List[Dict[str, Union[str, int]]]: + 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. @@ -969,12 +1136,24 @@ class AbstractRNNTDecoding(ConfidenceMixin): 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, -1], "start_offset": int(s), "end_offset": int(s + d)} - for t, s, d in zip(hypothesis.text[0], hypothesis.timestamp, hypothesis.token_duration) + {"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 @@ -1012,230 +1191,16 @@ class AbstractRNNTDecoding(ConfidenceMixin): return encoded_char_offsets, char_offsets @staticmethod - def _get_word_offsets_chars( - offsets: Dict[str, Union[str, float]], word_delimiter_char: str = " " - ) -> Dict[str, Union[str, float]]: - """ - Utility method which constructs word time stamps out of character time stamps. - - References: - This code is a port of the Hugging Face code for word time stamp construction. - - Args: - offsets: A list of dictionaries, each containing "char", "start_offset" and "end_offset". - word_delimiter_char: Character token that represents the word delimiter. By default, " ". - - Returns: - A list of dictionaries containing the word offsets. Each item contains "word", "start_offset" and - "end_offset". - """ - word_offsets = [] - - last_state = "SPACE" - word = "" - start_offset = 0 - end_offset = 0 - for i, offset in enumerate(offsets): - chars = offset["char"] - for char in chars: - state = "SPACE" if char == word_delimiter_char else "WORD" - - if state == last_state: - # If we are in the same state as before, we simply repeat what we've done before - end_offset = offset["end_offset"] - word += char - else: - # Switching state - if state == "SPACE": - # Finishing a word - word_offsets.append({"word": word, "start_offset": start_offset, "end_offset": end_offset}) - else: - # Starting a new word - start_offset = offset["start_offset"] - end_offset = offset["end_offset"] - word = char - - last_state = state - - if last_state == "WORD": - word_offsets.append({"word": word, "start_offset": start_offset, "end_offset": end_offset}) - - return word_offsets - - @staticmethod - def _get_word_offsets_subwords_sentencepiece( - offsets: Dict[str, Union[str, float]], - hypothesis: Hypothesis, - decode_ids_to_tokens: Callable[[List[int]], str], - decode_tokens_to_str: Callable[[List[int]], str], - ) -> Dict[str, Union[str, float]]: - """ - Utility method which constructs word time stamps out of sub-word time stamps. - - **Note**: Only supports Sentencepiece based tokenizers ! - - Args: - offsets: A list of dictionaries, each containing "char", "start_offset" and "end_offset". - hypothesis: Hypothesis object that contains `text` field, where each token is a sub-word id - after rnnt collapse. - decode_ids_to_tokens: A Callable function that accepts a list of integers and maps it to a sub-word. - decode_tokens_to_str: A Callable function that accepts a list of integers and maps it to text / str. - - Returns: - A list of dictionaries containing the word offsets. Each item contains "word", "start_offset" and - "end_offset". - """ - word_offsets = [] - built_token = [] - previous_token_index = 0 - # For every offset token - for i, offset in enumerate(offsets): - # For every subword token in offset token list (ignoring the RNNT Blank token at the end) - for char in offset['char'][:-1]: - char = int(char) - - # Compute the sub-word text representation, and the decoded text (stripped of sub-word markers). - token = decode_ids_to_tokens([char])[0] - token_text = decode_tokens_to_str([char]) - - # 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. - if token != token_text: - # 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_token: - word_offsets.append( - { - "word": decode_tokens_to_str(built_token), - "start_offset": offsets[previous_token_index]["start_offset"], - "end_offset": offsets[i - 1]["end_offset"], - } - ) - - # Prepare list of new sub-word ids - built_token.clear() - built_token.append(char) - previous_token_index = i - else: - # If the token does not contain any sub-word start mark, then the sub-word has not completed yet - # Append to current sub-word list. - built_token.append(char) - - # 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. - # This should only be done when these arrays contain more than one element. - if offsets and word_offsets: - word_offsets[0]["start_offset"] = offsets[0]["start_offset"] - - # If there are any remaining tokens left, inject them all into the final word offset. - # The start offset of this token is the start time of the next token to process. - # The end offset of this token is the end time of the last token from offsets. - # Note that built_token is a flat list; but offsets contains a nested list which - # may have different dimensionality. - # As such, we can't rely on the length of the list of built_token to index offsets. - if built_token: - # start from the previous token index as this hasn't been committed to word_offsets yet - # if we still have content in built_token - start_offset = offsets[previous_token_index]["start_offset"] - word_offsets.append( - { - "word": decode_tokens_to_str(built_token), - "start_offset": start_offset, - "end_offset": offsets[-1]["end_offset"], - } - ) - built_token.clear() - - return word_offsets - - @staticmethod - def _get_segment_offsets( - offsets: Dict[str, Union[str, float]], - segment_delimiter_tokens: List[str], - supported_punctuation: Optional[Set] = None, - segment_gap_threshold: Optional[int] = None, - ) -> Dict[str, Union[str, float]]: + def _load_kenlm_model(ngram_lm_model: str): """ - 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". + Load a KenLM model from a file path. """ - 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(offsets): - - word = offset['word'] - # check if thr word ends with any delimeter token or the word itself is a delimeter - if segment_gap_threshold and segment_words: - gap_between_words = offset['start_offset'] - offsets[i - 1]['end_offset'] - - if gap_between_words >= segment_gap_threshold: - segment_offsets.append( - { - "segment": ' '.join(segment_words), - "start_offset": offsets[previous_word_index]["start_offset"], - "end_offset": offsets[i - 1]["end_offset"], - } - ) - - segment_words = [word] - previous_word_index = i - continue - - elif 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": offsets[previous_word_index]["start_offset"], - "end_offset": offset["end_offset"], - } - ) - - segment_words = [] - previous_word_index = i + 1 - continue - - segment_words.append(word) - - if segment_words: - start_offset = offsets[previous_word_index]["start_offset"] - segment_offsets.append( - { - "segment": ' '.join(segment_words), - "start_offset": start_offset, - "end_offset": offsets[-1]["end_offset"], - } + 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." ) - segment_words.clear() - - return segment_offsets class RNNTDecoding(AbstractRNNTDecoding): @@ -1416,9 +1381,7 @@ class RNNTDecoding(AbstractRNNTDecoding): ): # 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 = { - char for token in vocabulary for char in token if unicodedata.category(char).startswith('P') - } + supported_punctuation = extract_punctuation_from_vocab(vocabulary) if hasattr(decoding_cfg, 'model_type') and decoding_cfg.model_type == 'tdt': blank_id = len(vocabulary) @@ -1438,6 +1401,10 @@ class RNNTDecoding(AbstractRNNTDecoding): ): 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. @@ -1450,7 +1417,7 @@ class RNNTDecoding(AbstractRNNTDecoding): """ return self._aggregate_token_confidence_chars(hypothesis.words, hypothesis.token_confidence) - def decode_tokens_to_str(self, tokens: List[int]) -> str: + def decode_tokens_to_str(self, tokens: List[str]) -> str: """ Implemented by subclass in order to decoder a token list into a string. @@ -1460,7 +1427,7 @@ class RNNTDecoding(AbstractRNNTDecoding): Returns: A decoded string. """ - hypothesis = ''.join(self.decode_ids_to_tokens(tokens)) + hypothesis = ''.join(tokens) return hypothesis def decode_ids_to_tokens(self, tokens: List[int]) -> List[str]: @@ -1694,7 +1661,11 @@ class RNNTBPEDecoding(AbstractRNNTDecoding): def __init__(self, decoding_cfg, decoder, joint, tokenizer: TokenizerSpec): blank_id = tokenizer.tokenizer.vocab_size # RNNT or TDT models. - supported_punctuation = tokenizer.supported_punctuation + + 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': @@ -1715,6 +1686,10 @@ class RNNTBPEDecoding(AbstractRNNTDecoding): ): 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. @@ -1731,17 +1706,17 @@ class RNNTBPEDecoding(AbstractRNNTDecoding): hypothesis.words, hypothesis.token_confidence, hypothesis.y_sequence ) - def decode_tokens_to_str(self, tokens: List[int]) -> str: + 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. + tokens: List of str representing the tokens. Returns: A decoded string. """ - hypothesis = self.tokenizer.ids_to_text(tokens) + hypothesis = self.tokenizer.tokens_to_text(tokens) return hypothesis def decode_ids_to_tokens(self, tokens: List[int]) -> List[str]: diff --git a/nemo/collections/asr/parts/submodules/rnnt_greedy_decoding.py b/nemo/collections/asr/parts/submodules/rnnt_greedy_decoding.py index 9200e3b0c2da1f419094d65bee6b53841512a560..e6cfdcd45b4bcfefaa61c713bd59a8e90203068d 100644 --- a/nemo/collections/asr/parts/submodules/rnnt_greedy_decoding.py +++ b/nemo/collections/asr/parts/submodules/rnnt_greedy_decoding.py @@ -34,8 +34,12 @@ import torch from omegaconf import DictConfig, OmegaConf from nemo.collections.asr.modules import rnnt_abstract -from nemo.collections.asr.parts.submodules.rnnt_loop_labels_computer import GreedyBatchedRNNTLoopLabelsComputer -from nemo.collections.asr.parts.submodules.tdt_loop_labels_computer import GreedyBatchedTDTLoopLabelsComputer +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 @@ -593,6 +597,9 @@ class GreedyBatchedRNNTInfer(_GreedyRNNTInfer, WithOptionalCudaGraphs): 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__( @@ -606,6 +613,9 @@ class GreedyBatchedRNNTInfer(_GreedyRNNTInfer, WithOptionalCudaGraphs): 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, @@ -622,12 +632,12 @@ class GreedyBatchedRNNTInfer(_GreedyRNNTInfer, WithOptionalCudaGraphs): # Depending on availability of `blank_as_pad` support # switch between more efficient batch decoding technique - self._decoding_computer = None + 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 = GreedyBatchedRNNTLoopLabelsComputer( + self.decoding_computer = GreedyBatchedRNNTLabelLoopingComputer( decoder=self.decoder, joint=self.joint, blank_index=self._blank_index, @@ -636,9 +646,18 @@ class GreedyBatchedRNNTInfer(_GreedyRNNTInfer, WithOptionalCudaGraphs): 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: @@ -667,41 +686,51 @@ class GreedyBatchedRNNTInfer(_GreedyRNNTInfer, WithOptionalCudaGraphs): 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): + 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 + return False if not self.decoder.blank_as_pad: # blank as pad uses decoding without CUDA graphs - return + return False if self.loop_labels: # Label-Looping implementation - self._decoding_computer.disable_cuda_graphs() + 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): + 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 + return False if not self.decoder.blank_as_pad: # blank as pad uses decoding without CUDA graphs - return + return False if self.loop_labels: # Label-Looping implementation - self._decoding_computer.maybe_enable_cuda_graphs() + 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( @@ -753,20 +782,53 @@ class GreedyBatchedRNNTInfer(_GreedyRNNTInfer, WithOptionalCudaGraphs): x: torch.Tensor, out_len: torch.Tensor, device: torch.device, - partial_hypotheses: Optional[list[rnnt_utils.Hypothesis]] = None, + 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 """ - if partial_hypotheses is not None: - raise NotImplementedError("`partial_hypotheses` support is not implemented") - - batched_hyps, alignments, last_decoder_state = self._decoding_computer(x=x, out_len=out_len) + # 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 in zip(hyps, self.decoder.batch_split_states(last_decoder_state)): - hyp.dec_state = state + 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( @@ -2407,6 +2469,11 @@ class GreedyBatchedRNNTInferConfig: 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 @@ -2517,10 +2584,12 @@ class GreedyTDTInfer(_GreedyRNNTInfer): ): """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). """ @@ -2664,10 +2733,12 @@ class GreedyTDTInfer(_GreedyRNNTInfer): if self.preserve_alignments: # convert Ti-th logits into a torch array - hypothesis.alignments.append([]) # blank buffer for next timestep + for i in range(skip): + hypothesis.alignments.append([]) # blank buffer until next timestep if self.preserve_frame_confidence: - hypothesis.frame_confidence.append([]) # blank buffer for next timestep + for i in range(skip): + hypothesis.frame_confidence.append([]) # blank buffer for next timestep if symbols_added == self.max_symbols: time_idx += 1 @@ -2690,7 +2761,9 @@ class GreedyTDTInfer(_GreedyRNNTInfer): 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. @@ -2752,6 +2825,9 @@ class GreedyBatchedTDTInfer(_GreedyRNNTInfer, WithOptionalCudaGraphs): 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__( @@ -2767,6 +2843,9 @@ class GreedyBatchedTDTInfer(_GreedyRNNTInfer, WithOptionalCudaGraphs): 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, @@ -2783,10 +2862,11 @@ class GreedyBatchedTDTInfer(_GreedyRNNTInfer, WithOptionalCudaGraphs): # Depending on availability of `blank_as_pad` support # switch between more efficient batch decoding technique - self._decoding_computer = None + self.decoding_computer = None + if self.decoder.blank_as_pad: # batched "loop frames" is not implemented for TDT - self._decoding_computer = GreedyBatchedTDTLoopLabelsComputer( + self.decoding_computer = GreedyBatchedTDTLabelLoopingComputer( decoder=self.decoder, joint=self.joint, blank_index=self._blank_index, @@ -2798,9 +2878,16 @@ class GreedyBatchedTDTInfer(_GreedyRNNTInfer, WithOptionalCudaGraphs): 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() @@ -2812,10 +2899,12 @@ class GreedyBatchedTDTInfer(_GreedyRNNTInfer, WithOptionalCudaGraphs): ): """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). """ @@ -2859,28 +2948,63 @@ class GreedyBatchedTDTInfer(_GreedyRNNTInfer, WithOptionalCudaGraphs): x: torch.Tensor, out_len: torch.Tensor, device: torch.device, - partial_hypotheses: Optional[list[rnnt_utils.Hypothesis]] = None, + 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 """ - if partial_hypotheses is not None: - raise NotImplementedError("`partial_hypotheses` support is not implemented") - - batched_hyps, alignments, last_decoder_state = self._decoding_computer(x=x, out_len=out_len) + # 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 in zip(hyps, self.decoder.batch_split_states(last_decoder_state)): - hyp.dec_state = state + 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): + def disable_cuda_graphs(self) -> bool: """Disable CUDA graphs (e.g., for decoding in training)""" - if self._decoding_computer is not None: - self._decoding_computer.disable_cuda_graphs() + if self.decoding_computer is not None: + return self.decoding_computer.disable_cuda_graphs() + return False - def maybe_enable_cuda_graphs(self): + def maybe_enable_cuda_graphs(self) -> bool: """Enable CUDA graphs (if allowed)""" - if self._decoding_computer is not None: - self._decoding_computer.maybe_enable_cuda_graphs() + 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 new file mode 100644 index 0000000000000000000000000000000000000000..1af34f11ac8ec115f168826d9d81b14c95ece44c --- /dev/null +++ b/nemo/collections/asr/parts/submodules/rnnt_maes_batched_computer.py @@ -0,0 +1,442 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..f1ef93c64f5d0c9a78edd3ffa81a44d0a9023239 --- /dev/null +++ b/nemo/collections/asr/parts/submodules/rnnt_malsd_batched_computer.py @@ -0,0 +1,1184 @@ +# 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/squeezeformer_modules.py b/nemo/collections/asr/parts/submodules/squeezeformer_modules.py deleted file mode 100644 index 212320e1f76fce8212d59b1cd03d802c6918c3e5..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/squeezeformer_modules.py +++ /dev/null @@ -1,203 +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 -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.conformer_modules import ConformerConvolution, ConformerFeedForward -from nemo.collections.asr.parts.submodules.multi_head_attention import ( - MultiHeadAttention, - RelPositionMultiHeadAttention, -) -from nemo.core.classes.mixins import AccessMixin - -__all__ = ['SqueezeformerLayer', 'ConformerFeedForward', 'SqueezeformerLayer'] - - -class ScaleBiasLayer(torch.nn.Module): - """ - Computes an affine transformation y = x * scale + bias, either learned via adaptive weights, or fixed. - Efficient alternative to LayerNorm where we can avoid computing the mean and variance of the input, and - just rescale the output of the previous layer. - - Args: - d_model (int): input dimension of layer. - adaptive_scale (bool): whether to learn the affine transformation parameters or not. If set to False, - the scale is fixed to 1 and bias to 0, effectively performing a No-Op on the input. - This is done for export compatibility. - """ - - def __init__(self, d_model: int, adaptive_scale: bool): - super().__init__() - self.adaptive_scale = adaptive_scale - if adaptive_scale: - self.scale = nn.Parameter(torch.ones(d_model)) - self.bias = nn.Parameter(torch.zeros(d_model)) - else: - self.register_buffer('scale', torch.ones(d_model), persistent=True) - self.register_buffer('bias', torch.zeros(d_model), persistent=True) - - def forward(self, x): - scale = self.scale.view(1, 1, -1) - bias = self.bias.view(1, 1, -1) - return x * scale + bias - - -class SqueezeformerLayer(torch.nn.Module, AttentionAdapterModuleMixin, AccessMixin): - """A single block of the Squeezeformer encoder. - - Args: - d_model (int): input dimension of MultiheadAttentionMechanism and PositionwiseFeedForward - d_ff (int): hidden dimension of PositionwiseFeedForward - 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 - adaptive_scale (bool): Whether to scale the inputs to each component by affine `scale` and `bias` layer. - Or use a fixed scale=1 and bias=0. - """ - - def __init__( - self, - d_model, - d_ff, - self_attention_model='rel_pos', - n_heads=4, - conv_kernel_size=31, - conv_norm_type='batch_norm', - dropout=0.1, - dropout_att=0.1, - pos_bias_u=None, - pos_bias_v=None, - adaptive_scale: bool = True, - ): - super().__init__() - - self.self_attention_model = self_attention_model - self.n_heads = n_heads - self.fc_factor = 1.0 - self.adaptive_scale = adaptive_scale - - # 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) - self.feed_forward1_scale = ScaleBiasLayer(d_model=d_model, adaptive_scale=adaptive_scale) - - # 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, pointwise_activation='swish' - ) - self.conv_scale = ScaleBiasLayer(d_model=d_model, adaptive_scale=adaptive_scale) - - # multi-headed self-attention module - self.norm_self_att = LayerNorm(d_model) - 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 - ) - elif self_attention_model == 'abs_pos': - self.self_attn = MultiHeadAttention(n_head=n_heads, n_feat=d_model, dropout_rate=dropout_att) - 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', 'abs_pos']" - ) - self.self_attn_scale = ScaleBiasLayer(d_model=d_model, adaptive_scale=adaptive_scale) - - # 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) - self.feed_forward2_scale = ScaleBiasLayer(d_model=d_model, adaptive_scale=adaptive_scale) - - self.dropout = nn.Dropout(dropout) - # self.norm_out = LayerNorm(d_model) - - # initialize parameters properly - self.reset_parameters() - - def forward(self, x, att_mask=None, pos_emb=None, pad_mask=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 - Returns: - x (torch.Tensor): (B, T, d_model) - """ - residual = x - - x = self.self_attn_scale(x) - if self.self_attention_model == 'rel_pos': - x = self.self_attn(query=x, key=x, value=x, mask=att_mask, pos_emb=pos_emb) - elif self.self_attention_model == 'abs_pos': - x = self.self_attn(query=x, key=x, value=x, mask=att_mask) - else: - x = None - x = residual + self.dropout(x) - x = self.norm_self_att(x) - residual = x - - 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) - x = pack_ip['x'] - - x = self.feed_forward1_scale(x) - x = self.feed_forward1(x) - x = residual + self.dropout(x) * self.fc_factor - x = self.norm_feed_forward1(x) - residual = x - - x = self.conv_scale(x) - x = self.conv(x, pad_mask) - x = residual + self.dropout(x) - x = self.norm_conv(x) - residual = x - - x = self.feed_forward2_scale(x) - x = self.feed_forward2(x) - x = residual + self.dropout(x) * self.fc_factor - x = self.norm_feed_forward2(x) - - if self.is_adapter_available(): - # Call the adapters - pack_ip = { - 'x': x, - 'loc': 'post', - } - pack_ip = self.forward_enabled_adapters(pack_ip) - x = pack_ip['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) - - return x - - def reset_parameters(self): - # Used for Squeezeformer initialization only - self.feed_forward1.reset_parameters_ff() - self.feed_forward2.reset_parameters_ff() - self.conv.reset_parameters_conv() diff --git a/nemo/collections/asr/parts/submodules/subsampling.py b/nemo/collections/asr/parts/submodules/subsampling.py index 068cd36022b0fca73dbdbab2924682e447c3a005..7f9fc606991cb2a32411e38a6ec34f19007456d2 100644 --- a/nemo/collections/asr/parts/submodules/subsampling.py +++ b/nemo/collections/asr/parts/submodules/subsampling.py @@ -66,7 +66,7 @@ class ConvSubsampling(torch.nn.Module): 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) + 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 @@ -374,7 +374,7 @@ class ConvSubsampling(torch.nn.Module): else: raise ValueError(f"Not valid sub-sampling: {subsampling}!") - self.conv = torch.nn.Sequential(*layers) + self.conv = MaskedConvSequential(*layers) def get_sampling_frames(self): return [1, self.subsampling_factor] @@ -383,7 +383,7 @@ class ConvSubsampling(torch.nn.Module): return [0, self.subsampling_factor + 1] def forward(self, x, lengths): - lengths = calc_length( + out_lengths = calc_length( lengths, all_paddings=self._left_padding + self._right_padding, kernel_size=self._kernel_size, @@ -392,11 +392,8 @@ class ConvSubsampling(torch.nn.Module): repeat_num=self._sampling_num, ) - # Unsqueeze Channel Axis - if self.conv2d_subsampling: - x = x.unsqueeze(1) # Transpose to Channel First mode - else: + if not self.conv2d_subsampling: x = x.transpose(1, 2) # split inputs if chunking_factor is set @@ -405,7 +402,7 @@ class ConvSubsampling(torch.nn.Module): # 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 + x_ceil = 2**31 / self._conv_channels * self._stride * self._stride if torch.numel(x) > x_ceil: need_to_split = True else: @@ -415,16 +412,18 @@ class ConvSubsampling(torch.nn.Module): need_to_split = True if need_to_split: - x, success = self.conv_split_by_batch(x) + 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 = self.conv(x) # try anyway + x, lengths = self.conv(x, lengths) # try anyway else: - x = self.conv(x) + x, lengths = self.conv(x, lengths) else: - x = self.conv(x) + x, lengths = self.conv(x) # Flatten Channel and Frequency Axes if self.conv2d_subsampling: @@ -442,8 +441,8 @@ class ConvSubsampling(torch.nn.Module): 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 + 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) @@ -459,11 +458,11 @@ class ConvSubsampling(torch.nn.Module): 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): - """ Tries to split input by batch, run conv and concat results """ - b, _, _, _ = x.size() + 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, False + return x, lengths, False if self.subsampling_conv_chunking_factor > 1: cf = self.subsampling_conv_chunking_factor @@ -471,20 +470,31 @@ class ConvSubsampling(torch.nn.Module): 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 + 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 + 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, False + return x, lengths, False logging.debug(f'conv subsampling: using split batch size {new_batch_size}') - return torch.cat([self.conv(chunk) for chunk in torch.split(x, new_batch_size, 0)]), True + + 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 """ + """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 @@ -497,8 +507,8 @@ class ConvSubsampling(torch.nn.Module): 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 + 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) @@ -520,7 +530,7 @@ class ConvSubsampling(torch.nn.Module): return x def channel_chunked_conv(self, conv, chunk_size, x): - """ Performs channel chunked convolution""" + """Performs channel chunked convolution""" ind = 0 out_chunks = [] @@ -564,7 +574,7 @@ class ConvSubsampling(torch.nn.Module): 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""" + """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): @@ -576,71 +586,6 @@ def calc_length(lengths, all_paddings, kernel_size, stride, ceil_mode, repeat_nu return lengths.to(dtype=torch.int) -class TimeReductionModule(nn.Module): - """ - Squeezeformer Time Reduction procedure. Downsamples the audio by `stride` in the time dimension. - - Args: - d_model (int): input dimension of MultiheadAttentionMechanism and PositionwiseFeedForward - out_dim (int): Output dimension of the module. - kernel_size (int): Conv kernel size for depthwise convolution in convolution module - stride (int): Downsampling factor in time dimension. - """ - - def __init__(self, d_model: int, out_dim: int, kernel_size: int = 5, stride: int = 2): - super().__init__() - - self.d_model = d_model - self.out_dim = out_dim - self.kernel_size = kernel_size - self.stride = stride - self.padding = max(0, self.kernel_size - self.stride) - - self.dw_conv = nn.Conv1d( - in_channels=d_model, - out_channels=d_model, - kernel_size=kernel_size, - stride=stride, - padding=self.padding, - groups=d_model, - ) - - self.pw_conv = nn.Conv1d( - in_channels=d_model, out_channels=out_dim, kernel_size=1, stride=1, padding=0, groups=1, - ) - - self.reset_parameters() - - def forward(self, x, att_mask=None, pad_mask=None): - x = x.transpose(1, 2) # [B, C, T] - if pad_mask is not None: - x = x.float().masked_fill(pad_mask.unsqueeze(1), 0.0) - - x = self.dw_conv(x) - x = self.pw_conv(x) - - x = x.transpose(1, 2) # [B, T, C] - - B, T, D = x.size() - if att_mask is not None and pad_mask is not None: - att_mask = att_mask[:, :: self.stride, :: self.stride] - pad_mask = pad_mask[:, :: self.stride] - L = pad_mask.size(-1) - x = torch.nn.functional.pad(x, (0, 0, 0, L - T)) - - return x, att_mask, pad_mask - - def reset_parameters(self): - dw_max = self.kernel_size ** -0.5 - pw_max = self.d_model ** -0.5 - - with torch.no_grad(): - torch.nn.init.uniform_(self.dw_conv.weight, -dw_max, dw_max) - torch.nn.init.uniform_(self.dw_conv.bias, -dw_max, dw_max) - torch.nn.init.uniform_(self.pw_conv.weight, -pw_max, pw_max) - torch.nn.init.uniform_(self.pw_conv.bias, -pw_max, pw_max) - - class SubsamplingReductionModule(nn.Module): """Downsamples the audio signal in time dimension.""" @@ -671,8 +616,8 @@ class SubsamplingReductionModule(nn.Module): def forward(self, x, lengths): """Shapes: - - x: [B, T, C] - - lengths: [B] + - x: [B, T, C] + - lengths: [B] """ if self.reduction == 'striding': @@ -691,3 +636,54 @@ class SubsamplingReductionModule(nn.Module): 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/tdt_beam_decoding.py b/nemo/collections/asr/parts/submodules/tdt_beam_decoding.py index 7aeb3417b8b290d10b02caeaa0f18c21e00601fd..65255b85849df97ef4097d32f823674827f2050d 100644 --- a/nemo/collections/asr/parts/submodules/tdt_beam_decoding.py +++ b/nemo/collections/asr/parts/submodules/tdt_beam_decoding.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -33,8 +33,13 @@ 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 @@ -161,6 +166,10 @@ class BeamTDTInfer(Typing): 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 @@ -206,6 +215,27 @@ class BeamTDTInfer(Typing): 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) @@ -237,14 +267,8 @@ class BeamTDTInfer(Typing): if ngram_lm_model: if search_type != "maes": raise ValueError("For decoding with language model `maes` decoding strategy must be chosen.") - - if KENLM_AVAILABLE: - self.ngram_lm = kenlm.Model(ngram_lm_model) - self.ngram_lm_alpha = ngram_lm_alpha - else: - raise ImportError( - "KenLM package (https://github.com/kpu/kenlm) is not installed. " "Use ngram_lm_model=None." - ) + self.ngram_lm = ngram_lm_model + self.ngram_lm_alpha = ngram_lm_alpha else: self.ngram_lm = None @@ -798,3 +822,155 @@ class BeamTDTInfer(Typing): 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_loop_labels_computer.py b/nemo/collections/asr/parts/submodules/tdt_loop_labels_computer.py deleted file mode 100644 index a830bc3046918cf34a530b2486be4013c7bf7913..0000000000000000000000000000000000000000 --- a/nemo/collections/asr/parts/submodules/tdt_loop_labels_computer.py +++ /dev/null @@ -1,1019 +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. - - -from dataclasses import dataclass, field -from typing import Any, Optional, Tuple, Union - -import numpy as np -import torch -import torch.nn.functional as F -from omegaconf import DictConfig, ListConfig - -from nemo.collections.asr.parts.utils import rnnt_utils -from nemo.collections.asr.parts.utils.asr_confidence_utils import ConfidenceMethodMixin -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, - cu_call, - run_nvrtc, - with_conditional_node, -) -from nemo.utils import logging -from nemo.utils.enum import PrettyStrEnum - -try: - from cuda import cudart - - HAVE_CUDA_PYTHON = True -except ImportError: - HAVE_CUDA_PYTHON = False - - -class LoopLabelsState: - """ - 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 - - all_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 - - 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 - # if the element was active on the previous step: to identify the end of decoding and store final hidden state - active_mask_prev: torch.Tensor - became_inactive_mask: torch.Tensor # mask for elements that became inactive (end of decoding) - - 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') - - 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) - - batched_hyps: rnnt_utils.BatchedHyps # batched hypotheses - decoding result - alignments: Optional[rnnt_utils.BatchedAlignments] = None # batched alignments - - 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, - ): - """ - - 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 - """ - 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_prev = torch.zeros_like(self.active_mask) - self.became_inactive_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.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, - 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 - ) - - -@dataclass -class SeparateGraphsLoopLabels: - """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) - - -class GreedyBatchedTDTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMethodMixin): - """ - Label Looping algorithm implementation: optimized batched greedy decoding. Callable. - 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_loop_labels_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[SeparateGraphsLoopLabels] - full_graph: Optional[torch.cuda.CUDAGraph] - cuda_graphs_mode: Optional[CudaGraphsMode] - state: Optional[LoopLabelsState] - - def __init__( - self, - decoder, - joint, - blank_index: int, - durations: Union[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, - ): - """ - 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 - """ - 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.allow_cuda_graphs = allow_cuda_graphs - 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.state = None - self.full_graph = None - self.separate_graphs = None - - self.cuda_graphs_mode = None - self.maybe_enable_cuda_graphs() - - def maybe_enable_cuda_graphs(self): - """Enable CUDA graphs if conditions met""" - if self.cuda_graphs_mode is not None: - # CUDA graphs are enabled - return - - if not self.allow_cuda_graphs: - self.cuda_graphs_mode = None - elif self.include_duration: - logging.warning("`include_duration` is not implemented for 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() - - def disable_cuda_graphs(self): - """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 - self.cuda_graphs_mode = None - self.reset_cuda_graphs_state() - - 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 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.state = None - - def loop_labels_torch( - self, - encoder_output: torch.Tensor, - encoder_output_length: torch.Tensor, - ) -> Tuple[rnnt_utils.BatchedHyps, Optional[rnnt_utils.BatchedAlignments], Any]: - """ - 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 - - # 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, - ) - # sample state, will be replaced further when the decoding for hypothesis is done - last_decoder_state = self.decoder.initialize_state(encoder_output_projected) - # 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 - all_durations = self.durations.to(device, non_blocking=True) - num_durations = all_durations.shape[0] - - # initial state, needed for torch.jit to compile (cannot handle None) - state = self.decoder.initialize_state(encoder_output_projected) - # indices of elements in batch (constant) - batch_indices = torch.arange(batch_size, dtype=torch.long, device=device) - # last found labels - initially () symbol - labels = torch.full_like(batch_indices, fill_value=self._SOS) - - # time indices - time_indices = torch.zeros_like(batch_indices) - safe_time_indices = torch.zeros_like(time_indices) # time indices, guaranteed to be < out_len - time_indices_current_labels = torch.zeros_like(time_indices) - last_timesteps = encoder_output_length - 1 - - # masks for utterances in batch - active_mask: torch.Tensor = encoder_output_length > 0 - advance_mask = torch.empty_like(active_mask) - - # for storing the last state we need to know what elements became "inactive" on this step - active_mask_prev = torch.empty_like(active_mask) - became_inactive_mask = torch.empty_like(active_mask) - - # loop while there are active utterances - while active_mask.any(): - active_mask_prev.copy_(active_mask, non_blocking=True) - # stage 1: get decoder (prediction network) 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 - - # stage 2: 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( - encoder_output_projected[batch_indices, safe_time_indices].unsqueeze(1), - decoder_output, - ) - .squeeze(1) - .squeeze(1) - ) - scores, labels = logits[:, :-num_durations].max(dim=-1) - jump_durations_indices = logits[:, -num_durations:].argmax(dim=-1) - durations = all_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, non_blocking=True) - 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=( - 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 - ) - ), - ) - - # 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 - 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) - - # 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) - # 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 = all_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=( - 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 - ) - ), - ) - - 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) - - # stage 3: filter labels and state, store hypotheses - # select states for hyps that became inactive (is it necessary?) - # this seems to be redundant, but used in the `loop_frames` output - torch.ne(active_mask, active_mask_prev, out=became_inactive_mask) - self.decoder.batch_replace_states_mask( - src_states=state, - dst_states=last_decoder_state, - mask=became_inactive_mask, - ) - - # 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, - labels, - time_indices_current_labels, - scores, - durations if self.include_duration else None, - ) - else: - # auto-adjusted storage - batched_hyps.add_results_masked_( - active_mask, - labels, - time_indices_current_labels, - scores, - durations if self.include_duration else None, - ) - - # stage 4: to avoid looping, go to 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) - if use_alignments: - return batched_hyps, alignments, last_decoder_state - return batched_hyps, None, last_decoder_state - - def loop_labels_cuda_graphs( - self, - encoder_output: torch.Tensor, - encoder_output_length: torch.Tensor, - ) -> Tuple[rnnt_utils.BatchedHyps, Optional[rnnt_utils.BatchedAlignments], Any]: - """ - Implementation with CUDA graphs. - - Args: - encoder_output: output from the encoder - encoder_output_length: lengths of the utterances in `encoder_output` - """ - 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) - - # 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[: 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.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_decoder_output() - self._before_inner_loop_get_joint_output() - while self.state.advance_mask_any.item(): - self._inner_loop_code() - self._after_inner_loop() - else: - raise NotImplementedError(f"Unknown graph mode: {self.cuda_graphs_mode}") - - return ( - self.state.batched_hyps, - self.state.alignments, - self.state.last_decoder_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_loop_labels_conditional(cudaGraphConditionalHandle handle, const bool *active_mask_any) - { - cudaGraphSetConditional(handle, *active_mask_any); - } - """ - return run_nvrtc(kernel_string, b"outer_loop_labels_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, - encoder_output_length: torch.Tensor, - ): - batch_size, max_time, encoder_dim = encoder_output_projected.shape - - self.state = LoopLabelsState( - 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, - ) - self.state.all_durations = self.durations.to(self.state.device) - - self.state.last_decoder_state = self.decoder.initialize_state(encoder_output_projected) - self.state.decoder_state = self.decoder.initialize_state(encoder_output_projected) - decoder_output, *_ = self.decoder.predict( - self.state.labels.unsqueeze(1), self.state.decoder_state, add_sos=False, batch_size=self.state.batch_size - ) - # to avoid recalculation of joint projection, store decoder output in state - self.state.decoder_output = self.joint.project_prednet(decoder_output) - if self.cuda_graphs_mode is self.CudaGraphsMode.FULL_GRAPH: - self._full_graph_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 = SeparateGraphsLoopLabels() - 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_decoder_output() - 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_code() - - 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() - - 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() - - capture_status, _, graph, _, _ = cu_call( - cudart.cudaStreamGetCaptureInfo(torch.cuda.current_stream(device=self.state.device).cuda_stream) - ) - assert capture_status == cudart.cudaStreamCaptureStatus.cudaStreamCaptureStatusActive - - (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_decoder_output() - self._before_inner_loop_get_joint_output() - 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_code() - self._after_inner_loop() - - 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_() - - # initial state - self.decoder.batch_replace_states_all( - src_states=self.decoder.initialize_state(self.state.encoder_output_projected), - dst_states=self.state.decoder_state, - ) - # last found labels - initially () symbol - self.state.labels.fill_(self._SOS) - 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) - - # 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) - - def _before_inner_loop_get_decoder_output(self): - """Get decoder output""" - # stage 1: get decoder (prediction network) output - 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_all(src_states=new_state, dst_states=self.state.decoder_state) - decoder_output_projected = self.joint.project_prednet(decoder_output) # do not recalculate joint projection - self.state.decoder_output.copy_(decoder_output_projected) - - 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 2: 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, non_blocking=True) - 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.all_durations.shape[0]].max(-1) - torch.max(logits[:, : -self.state.all_durations.shape[0]], dim=-1, out=(self.state.scores, self.state.labels)) - jump_durations_indices = logits[:, -self.state.all_durations.shape[0] :].argmax(dim=-1) - durations = self.state.all_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, non_blocking=True) - # for blank labels force duration >= 1 - durations.masked_fill_(torch.logical_and(durations == 0, self.state.blank_mask), 1) - - if self.state.alignments is not None: - float_dtype = self.state.float_dtype - 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=( - torch.stack( - ( - self._get_confidence_tensor( - F.log_softmax(logits[:, : -self.state.all_durations.shape[0]], dim=-1) - ).to(dtype=float_dtype), - self._get_confidence_tensor( - F.log_softmax(logits[:, -self.state.all_durations.shape[0] :], dim=-1) - ).to(dtype=float_dtype), - ), - dim=-1, - ) - if self.include_duration_confidence - else ( - self._get_confidence_tensor( - F.log_softmax(logits[:, : -self.state.all_durations.shape[0]], dim=-1) - ).to(dtype=float_dtype) - if self.preserve_frame_confidence - else None - ) - ), - ) - - # 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_(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) - - # 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_code(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.all_durations.shape[0]].max(-1) - jump_durations_indices = logits[:, -self.state.all_durations.shape[0] :].argmax(dim=-1) - durations = self.state.all_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: - float_dtype = self.state.float_dtype - 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=( - torch.stack( - ( - self._get_confidence_tensor( - F.log_softmax(logits[:, : -self.state.all_durations.shape[0]], dim=-1) - ).to(dtype=float_dtype), - self._get_confidence_tensor( - F.log_softmax(logits[:, -self.state.all_durations.shape[0] :], dim=-1) - ).to(dtype=float_dtype), - ), - dim=-1, - ) - if self.include_duration_confidence - else ( - self._get_confidence_tensor( - F.log_softmax(logits[:, : -self.state.all_durations.shape[0]], dim=-1) - ).to(dtype=float_dtype) - if self.preserve_frame_confidence - else None - ) - ), - ) - - # 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 - durations.masked_fill_(torch.logical_and(durations == 0, self.state.blank_mask), 1) - # self.time_indices += self.blank_mask - torch.where( - self.state.advance_mask, - self.state.time_indices + durations, - self.state.time_indices, - out=self.state.time_indices, - ) - - 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(self): - """Store hypotheses, state for finished hypotheses, avoid looping""" - # stage 3: filter labels and state, store hypotheses - # select states for hyps that became inactive (is it necessary?) - # this seems to be redundant, but used in the `loop_frames` output - torch.ne(self.state.active_mask, self.state.active_mask_prev, out=self.state.became_inactive_mask) - self.decoder.batch_replace_states_mask( - src_states=self.state.decoder_state, - dst_states=self.state.last_decoder_state, - mask=self.state.became_inactive_mask, - ) - - self.state.batched_hyps.add_results_masked_no_checks_( - self.state.active_mask, - self.state.labels, - self.state.time_indices_current_labels, - self.state.scores, - ) - - # 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 __call__( - self, - x: torch.Tensor, - out_len: torch.Tensor, - ) -> Tuple[rnnt_utils.BatchedHyps, Optional[rnnt_utils.BatchedAlignments], Any]: - if self.cuda_graphs_mode is not None and x.device.type == "cuda": - return self.loop_labels_cuda_graphs(encoder_output=x, encoder_output_length=out_len) - - return self.loop_labels_torch(encoder_output=x, encoder_output_length=out_len) diff --git a/nemo/collections/asr/parts/submodules/tdt_malsd_batched_computer.py b/nemo/collections/asr/parts/submodules/tdt_malsd_batched_computer.py new file mode 100644 index 0000000000000000000000000000000000000000..45ecfed299a5a08c3b95e93966b8bfb7794cc40b --- /dev/null +++ b/nemo/collections/asr/parts/submodules/tdt_malsd_batched_computer.py @@ -0,0 +1,1307 @@ +# 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/transducer_decoding/__init__.py b/nemo/collections/asr/parts/submodules/transducer_decoding/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..07ba03407b36410f48f14f1a4c821cde89d6249e --- /dev/null +++ b/nemo/collections/asr/parts/submodules/transducer_decoding/__init__.py @@ -0,0 +1,31 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..30a4b97366cdea07747c3116d163176e0c257f66 --- /dev/null +++ b/nemo/collections/asr/parts/submodules/transducer_decoding/label_looping_base.py @@ -0,0 +1,309 @@ +# 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/rnnt_loop_labels_computer.py b/nemo/collections/asr/parts/submodules/transducer_decoding/rnnt_label_looping.py similarity index 52% rename from nemo/collections/asr/parts/submodules/rnnt_loop_labels_computer.py rename to nemo/collections/asr/parts/submodules/transducer_decoding/rnnt_label_looping.py index a3b7ac9d3c343cc127a754e4a6a9162892cb2c2b..a732f45e2721283a429a1bfc68535cedf8b86d33 100644 --- a/nemo/collections/asr/parts/submodules/rnnt_loop_labels_computer.py +++ b/nemo/collections/asr/parts/submodules/transducer_decoding/rnnt_label_looping.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -12,35 +12,33 @@ # See the License for the specific language governing permissions and # limitations under the License. -from dataclasses import dataclass, field -from typing import Any, Optional, Tuple, Union + +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.collections.common.parts.optional_cuda_graphs import WithOptionalCudaGraphs -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.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 -from nemo.utils.enum import PrettyStrEnum -try: - from cuda import cudart +if CUDA_PYTHON_AVAILABLE: + from cuda.bindings import runtime as cudart - HAVE_CUDA_PYTHON = True -except ImportError: - HAVE_CUDA_PYTHON = False - -class LoopLabelsState: +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. @@ -67,20 +65,27 @@ class LoopLabelsState: 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 - # if the element was active on the previous step: to identify the end of decoding and store final hidden state - active_mask_prev: torch.Tensor - became_inactive_mask: torch.Tensor # mask for elements that became inactive (end of decoding) 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') - 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) + 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, @@ -132,12 +137,14 @@ class LoopLabelsState: 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.became_inactive_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, @@ -166,19 +173,9 @@ class LoopLabelsState: ) -@dataclass -class SeparateGraphsLoopLabels: - """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) - - -class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMethodMixin): +class GreedyBatchedRNNTLabelLoopingComputer(GreedyBatchedLabelLoopingComputerBase, ConfidenceMethodMixin): """ - Label Looping algorithm implementation: optimized batched greedy decoding. Callable. + 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), @@ -187,17 +184,12 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth """ INITIAL_MAX_TIME = 375 # initial max time, used to init state for Cuda graphs - CUDA_PROGRAM_NAME = b"while_loop_labels_conditional_rnnt.cu" + CUDA_PROGRAM_NAME = b"while_label_looping_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[SeparateGraphsLoopLabels] + separate_graphs: Optional[SeparateGraphsLabelLooping] full_graph: Optional[torch.cuda.CUDAGraph] - cuda_graphs_mode: Optional[CudaGraphsMode] - state: Optional[LoopLabelsState] + state: Optional[LabelLoopingState] + fusion_models: Optional[List[NGramGPULanguageModel]] def __init__( self, @@ -209,6 +201,9 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth 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. @@ -220,6 +215,9 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth 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 @@ -228,81 +226,73 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth self.max_symbols = max_symbols_per_step self.preserve_alignments = preserve_alignments self.preserve_frame_confidence = preserve_frame_confidence - self.allow_cuda_graphs = allow_cuda_graphs 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 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.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 - - 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() - - def disable_cuda_graphs(self): - """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 - self.cuda_graphs_mode = None - self.reset_cuda_graphs_state() - 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 loop_labels_torch( + 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, - ) -> Tuple[rnnt_utils.BatchedHyps, Optional[rnnt_utils.BatchedAlignments], Any]: + 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) @@ -316,8 +306,6 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth device=device, float_dtype=float_dtype, ) - # sample state, will be replaced further when the decoding for hypothesis is done - last_decoder_state = self.decoder.initialize_state(encoder_output_projected) # 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 @@ -331,38 +319,46 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth store_frame_confidence=self.preserve_frame_confidence, ) - # initial state, needed for torch.jit to compile (cannot handle None) - state = self.decoder.initialize_state(encoder_output_projected) # indices of elements in batch (constant) batch_indices = torch.arange(batch_size, dtype=torch.long, device=device) - # last found labels - initially () symbol - labels = torch.full_like(batch_indices, fill_value=self._SOS) # 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.zeros_like(time_indices) # time indices, guaranteed to be < out_len + 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) - last_timesteps = encoder_output_length - 1 # masks for utterances in batch - active_mask: torch.Tensor = encoder_output_length > 0 + active_mask: torch.Tensor = time_indices < encoder_output_length advance_mask = torch.empty_like(active_mask) - # for storing the last state we need to know what elements became "inactive" on this step - active_mask_prev = torch.empty_like(active_mask) - became_inactive_mask = torch.empty_like(active_mask) - - # loop while there are active utterances - while active_mask.any(): - active_mask_prev.copy_(active_mask, non_blocking=True) - # stage 1: get decoder (prediction network) output + 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 - # stage 2: get joint output, iteratively seeking for non-blank labels + # 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), @@ -373,21 +369,33 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth ) 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, non_blocking=True) + 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_confidence_tensor(F.log_softmax(logits, dim=-1)).to(dtype=float_dtype) - if self.preserve_frame_confidence - else None - ), + confidence=self._get_frame_confidence(logits=logits), ) # advance_mask is a mask for current batch for searching non-blank labels; @@ -397,7 +405,7 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth torch.less(time_indices, encoder_output_length, out=active_mask) torch.logical_and(active_mask, blank_mask, out=advance_mask) - # inner loop: find next non-blank labels (if exist) + # 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 @@ -412,7 +420,17 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth ) # 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) + 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 @@ -424,11 +442,7 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth 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_confidence_tensor(F.log_softmax(logits, dim=-1)).to(dtype=float_dtype) - if self.preserve_frame_confidence - else None - ), + confidence=self._get_frame_confidence(logits=logits), ) blank_mask = labels == self._blank_index @@ -437,35 +451,54 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth torch.less(time_indices, encoder_output_length, out=active_mask) torch.logical_and(active_mask, blank_mask, out=advance_mask) - # stage 3: filter labels and state, store hypotheses - # select states for hyps that became inactive (is it necessary?) - # this seems to be redundant, but used in the `loop_frames` output - torch.ne(active_mask, active_mask_prev, out=became_inactive_mask) - self.decoder.batch_replace_states_mask( - src_states=state, - dst_states=last_decoder_state, - mask=became_inactive_mask, - ) - - # store hypotheses + # 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, - labels, - time_indices_current_labels, - scores, + 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, - labels, - time_indices_current_labels, - scores, + fusion_states_candidates[batch_indices, labels * active_mask], + fusion_states, + out=fusion_states, ) - # stage 4: to avoid looping, go to next frame after max_symbols emission + # 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 @@ -484,23 +517,167 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth 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, last_decoder_state - return batched_hyps, None, last_decoder_state + 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 loop_labels_cuda_graphs( + 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, - ) -> Tuple[rnnt_utils.BatchedHyps, Optional[rnnt_utils.BatchedAlignments], Any]: + 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) @@ -509,16 +686,31 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth 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, encoder_output_length) + self._graph_reinitialize(encoder_output) - # copy (projected) encoder output and lenghts + # 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: @@ -533,18 +725,52 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth # manual loop instead of using graphs self._before_outer_loop() while self.state.active_mask_any.item(): - self._before_inner_loop_get_decoder_output() self._before_inner_loop_get_joint_output() while self.state.advance_mask_any.item(): - self._inner_loop_code() - self._after_inner_loop() + 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, - self.state.alignments, - self.state.last_decoder_state, + self.state.batched_hyps.clone(), + self.state.alignments.clone() if self.preserve_alignments else None, + decoding_state, ) @classmethod @@ -555,16 +781,16 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth """ 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_loop_labels_conditional(cudaGraphConditionalHandle handle, const bool *active_mask_any) + void outer_label_looping_conditional(cudaGraphConditionalHandle handle, const bool *active_mask_any) { cudaGraphSetConditional(handle, *active_mask_any); } """ - return run_nvrtc(kernel_string, b"outer_loop_labels_conditional", cls.CUDA_PROGRAM_NAME) + return run_nvrtc(kernel_string, b"outer_label_looping_conditional", cls.CUDA_PROGRAM_NAME) @classmethod def _create_inner_while_loop_kernel(cls): @@ -574,9 +800,9 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth """ 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) { @@ -588,11 +814,10 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth def _graph_reinitialize( self, encoder_output_projected: torch.Tensor, - encoder_output_length: torch.Tensor, ): batch_size, max_time, encoder_dim = encoder_output_projected.shape - self.state = LoopLabelsState( + self.state = LabelLoopingState( batch_size=batch_size, max_time=max(max_time, self.INITIAL_MAX_TIME), encoder_dim=encoder_dim, @@ -604,15 +829,60 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth preserve_frame_confidence=self.preserve_frame_confidence, ) - self.state.last_decoder_state = self.decoder.initialize_state(encoder_output_projected) + # 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) - decoder_output, *_ = 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_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 = self.joint.project_prednet(decoder_output) + 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: - self._full_graph_compile() + 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: @@ -621,12 +891,31 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth 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 = SeparateGraphsLoopLabels() + self.separate_graphs = SeparateGraphsLabelLooping() with ( torch.cuda.stream(stream_for_graph), torch.inference_mode(), @@ -643,7 +932,6 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth self.separate_graphs.before_inner_loop, stream=stream_for_graph, capture_error_mode="thread_local" ), ): - self._before_inner_loop_get_decoder_output() self._before_inner_loop_get_joint_output() with ( @@ -653,7 +941,7 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth self.separate_graphs.inner_loop_code, stream=stream_for_graph, capture_error_mode="thread_local" ), ): - self._inner_loop_code() + self._inner_loop_step_find_next_non_blank() with ( torch.cuda.stream(stream_for_graph), @@ -662,12 +950,14 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth self.separate_graphs.after_inner_loop, stream=stream_for_graph, capture_error_mode="thread_local" ), ): - self._after_inner_loop() + 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), @@ -676,7 +966,8 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth ): self._before_outer_loop() - capture_status, _, graph, _, _ = cu_call( + # 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 @@ -689,11 +980,12 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth [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_decoder_output() self._before_inner_loop_get_joint_output() # capture: while self.advance_mask_any.item(): inner_while_loop_kernel = self._create_inner_while_loop_kernel() @@ -706,11 +998,48 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth ], 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_code() - self._after_inner_loop() + 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""" @@ -718,13 +1047,6 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth if self.state.alignments is not None: self.state.alignments.clear_() - # initial state - self.decoder.batch_replace_states_all( - src_states=self.decoder.initialize_state(self.state.encoder_output_projected), - dst_states=self.state.decoder_state, - ) - # last found labels - initially () symbol - self.state.labels.fill_(self._SOS) self.state.scores.fill_(0.0) # time indices @@ -737,25 +1059,13 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth # 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) - def _before_inner_loop_get_decoder_output(self): - """Get decoder output""" - # stage 1: get decoder (prediction network) output - 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_all(src_states=new_state, dst_states=self.state.decoder_state) - decoder_output_projected = self.joint.project_prednet(decoder_output) # do not recalculate joint projection - self.state.decoder_output.copy_(decoder_output_projected) - 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 2: get joint output, iteratively seeking for 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, non_blocking=True) logits = ( self.joint.joint_after_projection( self.state.encoder_output_projected[self.state.batch_indices, self.state.safe_time_indices].unsqueeze( @@ -769,23 +1079,42 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth # 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, non_blocking=True) + self.state.time_indices_current_labels.copy_(self.state.time_indices) if self.state.alignments is not None: - float_dtype = self.state.float_dtype 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_confidence_tensor(F.log_softmax(logits, dim=-1)).to(dtype=float_dtype) - if self.preserve_frame_confidence - else None - ), + confidence=self._get_frame_confidence(logits=logits), ) # advance_mask is a mask for current batch for searching non-blank labels; @@ -799,7 +1128,7 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth # same as: self.advance_mask_any = advance_mask.any() torch.any(self.state.advance_mask, out=self.state.advance_mask_any) - def _inner_loop_code(self): + 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 @@ -822,23 +1151,29 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth # 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: - float_dtype = self.state.float_dtype 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_confidence_tensor(F.log_softmax(logits, dim=-1)).to(dtype=float_dtype) - if self.preserve_frame_confidence - else None - ), + confidence=self._get_frame_confidence(logits=logits), ) # blank_mask = self.labels == self._blank_index @@ -851,26 +1186,51 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth 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(self): - """Store hypotheses, state for finished hypotheses, avoid looping""" - # stage 3: filter labels and state, store hypotheses - # select states for hyps that became inactive (is it necessary?) - # this seems to be redundant, but used in the `loop_frames` output - torch.ne(self.state.active_mask, self.state.active_mask_prev, out=self.state.became_inactive_mask) - self.decoder.batch_replace_states_mask( - src_states=self.state.decoder_state, - dst_states=self.state.last_decoder_state, - mask=self.state.became_inactive_mask, - ) + 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_( - self.state.active_mask, - self.state.labels, - self.state.time_indices_current_labels, - self.state.scores, + active_mask=self.state.active_mask, + labels=self.state.labels, + time_indices=self.state.time_indices_current_labels, + scores=self.state.scores, ) - # stage 4: to avoid looping, go to next frame after max_symbols emission + 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( @@ -890,12 +1250,17 @@ class GreedyBatchedRNNTLoopLabelsComputer(WithOptionalCudaGraphs, ConfidenceMeth 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 __call__( - self, - x: torch.Tensor, - out_len: torch.Tensor, - ) -> Tuple[rnnt_utils.BatchedHyps, Optional[rnnt_utils.BatchedAlignments], Any]: - if self.cuda_graphs_mode is not None and x.device.type == "cuda": - return self.loop_labels_cuda_graphs(encoder_output=x, encoder_output_length=out_len) - - return self.loop_labels_torch(encoder_output=x, encoder_output_length=out_len) + 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 new file mode 100644 index 0000000000000000000000000000000000000000..52aa71e98f3ef03fc68f8264573d8289bd3689ca --- /dev/null +++ b/nemo/collections/asr/parts/submodules/transducer_decoding/tdt_label_looping.py @@ -0,0 +1,1373 @@ +# 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 index 373e041da1bec167bb0f21413efce0a5d63ca5b1..a6155ace4fc82c9f2b6fe8e9aed92b12cfa7afae 100644 --- a/nemo/collections/asr/parts/submodules/wfst_decoder.py +++ b/nemo/collections/asr/parts/submodules/wfst_decoder.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. diff --git a/nemo/collections/asr/parts/utils/aligner_utils.py b/nemo/collections/asr/parts/utils/aligner_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9b18e934783bb3c3c285172a7e824b17990f0d8f --- /dev/null +++ b/nemo/collections/asr/parts/utils/aligner_utils.py @@ -0,0 +1,1060 @@ +# 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 index 87480da5a9ea29e575eb5ac49fae4701669118a7..c9bdab94f1f452cf0d095ac41b0f4275e9d55e53 100644 --- a/nemo/collections/asr/parts/utils/asr_batching.py +++ b/nemo/collections/asr/parts/utils/asr_batching.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. diff --git a/nemo/collections/asr/parts/utils/asr_confidence_benchmarking_utils.py b/nemo/collections/asr/parts/utils/asr_confidence_benchmarking_utils.py index 262c98401f95a4afbd940c6bc2dc68f917ddbd9e..f91d205f0760baed4e3eca51ca3008b2b4a5bdaf 100644 --- a/nemo/collections/asr/parts/utils/asr_confidence_benchmarking_utils.py +++ b/nemo/collections/asr/parts/utils/asr_confidence_benchmarking_utils.py @@ -18,8 +18,8 @@ from pathlib import Path from typing import List, Optional, Tuple, Union import numpy as np -import texterrors import torch +from kaldialign import align from omegaconf import open_dict from nemo.collections.asr.models import ASRModel, EncDecRNNTModel @@ -44,11 +44,12 @@ def get_correct_marks(r: Union[List[int], List[str]], h: Union[List[int], List[s This method considers only insertions and substitutions as incorrect marks. """ - return [ - a == b - for a, b in zip(*(texterrors.align_texts([str(rr) for rr in r], [str(hh) for hh in h], False)[:-1])) - if b != "" - ] + 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]]: @@ -78,7 +79,6 @@ def run_confidence_benchmark( draw_plot = plot_dir is not None if isinstance(plot_dir, str): plot_dir = Path(plot_dir) - is_rnnt = isinstance(model, EncDecRNNTModel) # transcribe audio with torch.amp.autocast(model.device.type, enabled=use_amp): @@ -86,8 +86,6 @@ def run_confidence_benchmark( transcriptions = model.transcribe( audio=filepaths, batch_size=batch_size, return_hypotheses=True, num_workers=num_workers ) - if is_rnnt: - transcriptions = transcriptions[0] levels = [] if target_level != "word": diff --git a/nemo/collections/asr/parts/utils/asr_confidence_utils.py b/nemo/collections/asr/parts/utils/asr_confidence_utils.py index cecc3c497429de6a439ddc1cbc611f8a193a4a82..35a9ae30937ff58177aa5186f2f386664edcd9e9 100644 --- a/nemo/collections/asr/parts/utils/asr_confidence_utils.py +++ b/nemo/collections/asr/parts/utils/asr_confidence_utils.py @@ -22,7 +22,6 @@ import torch from omegaconf import DictConfig, OmegaConf from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis -from nemo.utils import logging class ConfidenceMethodConstants: @@ -447,7 +446,7 @@ class ConfidenceMixin(ABC): 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_tokens_to_str([int(token_id)]) + 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: diff --git a/nemo/collections/asr/parts/utils/asr_multispeaker_utils.py b/nemo/collections/asr/parts/utils/asr_multispeaker_utils.py index 66cfcc75f49f472394757e9b785c82ca9402dd41..d0bb3aa82226462b8211ab5d2e1bf91cae0a49b9 100644 --- a/nemo/collections/asr/parts/utils/asr_multispeaker_utils.py +++ b/nemo/collections/asr/parts/utils/asr_multispeaker_utils.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -11,13 +11,20 @@ # WITHOUT 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 -from lhotse import SupervisionSet -from lhotse.cut import MixedCut, MonoCut +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: @@ -195,7 +202,6 @@ def find_segments_from_rttm( 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. """ @@ -220,7 +226,6 @@ def get_mask_from_segments( speaker_to_idx_map: torch.Tensor, num_speakers: int = 4, feat_per_sec: int = 100, - ignore_num_spk_mismatch: bool = False, ): """ Generate mask matrix from segments list. @@ -232,8 +237,6 @@ def get_mask_from_segments( 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 - ignore_num_spk_mismatch (bool): This is a temporary solution to handle speaker mismatch. - Will be removed in the future. Returns: mask (Tensor): A numpy array of shape (num_speakers, encoder_hidden_len). @@ -244,11 +247,7 @@ def get_mask_from_segments( mask = torch.zeros((num_samples, num_speakers)) for rttm_sup in segments: speaker_idx = speaker_to_idx_map[rttm_sup.speaker] - if speaker_idx >= num_speakers: - if ignore_num_spk_mismatch: - continue - else: - raise ValueError(f"Speaker Index {speaker_idx} exceeds the max index: {num_speakers-1}") + stt = max(rttm_sup.start, 0) ent = min(rttm_sup.end, a_cut.duration) stf = int(stt * feat_per_sec) @@ -299,6 +298,9 @@ def get_hidden_length_from_sample_length( 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. @@ -307,49 +309,38 @@ def get_hidden_length_from_sample_length( Returns: hidden_length (int): The calculated hidden length in terms of the number of frames. """ - mel_frame_count = math.ceil((num_samples + 1) / num_sample_per_mel_frame) + 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: int = 4, + num_speakers: Optional[int] = None, num_sample_per_mel_frame: int = 160, num_mel_frame_per_asr_frame: int = 8, - spk_tar_all_zero: bool = False, boundary_segments: bool = False, soft_label: bool = False, - ignore_num_spk_mismatch: bool = True, 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. + ''' + 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 - spk_tar_all_zero (Tensor): - Set to True gives all zero "mask" - 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. - ignore_num_spk_mismatch (bool): - This is a temporary solution to handle speaker mismatch. Will be removed in the future. + 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) - """ + 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)] @@ -361,16 +352,27 @@ def speaker_to_target( raise ValueError(f"Unsupported cut type type{a_cut}: only MixedCut and MonoCut are supported") segments_total = [] + for i, cut in enumerate(cut_list): - rttms = SupervisionSet.from_rttm(cut.rttm_filepath) + 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=cut.recording_id, rttms=rttms, start_after=cut.start, end_before=cut.end, tolerance=0.0 + 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=cut.recording_id, start_after=cut.start, end_before=cut.end, adjust_offset=True - ) + 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: @@ -380,7 +382,6 @@ def speaker_to_target( 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) @@ -389,23 +390,25 @@ def speaker_to_target( 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 len(speaker_to_idx_map) > num_speakers and not ignore_num_spk_mismatch: # raise error if number of speakers - raise ValueError( - f"Number of speakers {len(speaker_to_idx_map)} is larger than " - f"the maximum number of speakers {num_speakers}" - ) + 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 ) - if spk_tar_all_zero: - frame_mask = torch.zeros((num_samples, num_speakers)) - else: - frame_mask = get_mask_from_segments( - segments_total, a_cut, speaker_to_idx_map, num_speakers, feat_per_sec, ignore_num_spk_mismatch - ) + 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: @@ -413,4 +416,281 @@ def speaker_to_target( else: mask = (soft_mask > soft_thres).float() - return mask + 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 new file mode 100644 index 0000000000000000000000000000000000000000..e0af3b7623d7b8b3d25b86adc9505a327d1e1f1a --- /dev/null +++ b/nemo/collections/asr/parts/utils/batched_beam_decoding_utils.py @@ -0,0 +1,623 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..83be3a3be3f70317850fefabee54fceab4c4df5b --- /dev/null +++ b/nemo/collections/asr/parts/utils/chunking_utils.py @@ -0,0 +1,451 @@ +# 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/data_simulation_utils.py b/nemo/collections/asr/parts/utils/data_simulation_utils.py index 66b21c2478a0baa9b77dce821b05b09806ca9ff7..14a853bcb6a387a2bc345e347d91741423d67905 100644 --- a/nemo/collections/asr/parts/utils/data_simulation_utils.py +++ b/nemo/collections/asr/parts/utils/data_simulation_utils.py @@ -16,7 +16,7 @@ import copy import os import shutil from collections import defaultdict -from typing import IO, Dict, List, Optional, Tuple +from typing import Dict, List, Optional, Tuple import numpy as np import torch @@ -67,10 +67,13 @@ def get_cleaned_base_path(output_dir: str, overwrite_output: bool = True) -> str def binary_search_alignments( - inds: List[int], max_audio_read_sec: float, min_alignment_count: int, alignments: List[float], + 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, + 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. @@ -103,7 +106,10 @@ def binary_search_alignments( def get_subset_of_audio_manifest( - audio_manifest: dict, offset_index: int, max_audio_read_sec: float, min_alignment_count: int, + 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. @@ -202,7 +208,6 @@ def read_audio_from_buffer( 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. @@ -285,7 +290,10 @@ def get_scaled_audio_signal( def get_desired_avg_power_noise( - power_array: float, snr_min: float, snr_max: float, background_noise_snr: float, + power_array: float, + snr_min: float, + snr_max: float, + background_noise_snr: float, ): """ Calculate the desired average power of the noise. @@ -318,6 +326,7 @@ def get_background_noise( 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). @@ -332,7 +341,7 @@ def get_background_noise( 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. @@ -343,9 +352,11 @@ def get_background_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) - file_id = np.random.randint(len(noise_samples)) audio_file, sr, audio_manifest = read_audio_from_buffer( audio_manifest=noise_samples[file_id], buffer_dict=audio_read_buffer_dict, @@ -353,6 +364,16 @@ def get_background_noise( 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: @@ -368,7 +389,7 @@ def get_background_noise( bg_array[running_len_samples:end_audio_file] = scaled_audio_file running_len_samples = end_audio_file - return bg_array, desired_snr + return bg_array, desired_snr, noise_segment_list def get_random_offset_index( @@ -379,7 +400,7 @@ def get_random_offset_index( min_alignment_count: int = 2, ) -> int: """ - Get an index for randomly accessing the silence in alignment timestamps. + Get an index for randomly accessing the silence in alignment timestamps. Args: audio_manifest (dict): Audio manifest dictionary. @@ -389,7 +410,7 @@ def get_random_offset_index( 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: + Returns: (int): Random offset index smaller than `offset_count`. """ if len(audio_manifest['alignments']) <= min_alignment_count: @@ -442,12 +463,15 @@ def get_speaker_ids(sess_idx: int, speaker_samples: dict, permutated_speaker_ind speaker_ids (list): List of speaker IDs """ all_speaker_ids = list(speaker_samples.keys()) - idx_list = permutated_speaker_inds[sess_idx, :] + # 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) -> dict: +def build_speaker_samples_map(manifest: dict, tqdm_bar: bool = False) -> dict: """ Build a dictionary for mapping speaker ID to their list of samples @@ -456,8 +480,9 @@ def build_speaker_samples_map(manifest: dict) -> dict: 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)): + # 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 @@ -492,6 +517,20 @@ def read_noise_manifest(add_bg: bool, background_manifest: str): 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. @@ -499,7 +538,7 @@ def get_speaker_samples(speaker_ids: List[str], speaker_samples: dict) -> Dict[s 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. """ @@ -527,7 +566,10 @@ def add_silence_to_alignments(audio_manifest: dict): def load_speaker_sample( - speaker_wav_align_map: List[dict], speaker_ids: List[str], speaker_turn: int, min_alignment_count: int, + 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. @@ -539,7 +581,7 @@ def load_speaker_sample( 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. """ @@ -587,11 +629,15 @@ def get_split_points_in_alignments( 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),] + [ + int(new_start * sr), + int(new_end * sr), + ] ) new_start = alignments[i] - split_buffer # The last split point should be added @@ -630,12 +676,12 @@ 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 + 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 @@ -659,7 +705,7 @@ class DataAnnotator(object): Initialize file writing arguments """ self._file_base_str = "synthetic" - self._file_types = ["wav", "rttm", "json", "ctm", "txt", "meta"] + self._file_types = ["wav", "rttm", "json", "noise", "ctm", "txt", "meta"] self._annotation_types = ["rttm", "json", "ctm"] def _init_filelist_lists(self): @@ -678,9 +724,14 @@ class DataAnnotator(object): self.annote_lists[file_type] = [] def create_new_rttm_entry( - self, words: List[str], alignments: List[float], start: int, end: int, speaker_id: int + 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) @@ -690,7 +741,7 @@ class DataAnnotator(object): 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 """ @@ -703,11 +754,18 @@ class DataAnnotator(object): if ( silence_length > 2 * self._params.data_simulator.session_params.split_buffer ): # split utterance on silence - new_end = start + alignments[i - 1] + self._params.data_simulator.session_params.split_buffer + 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] - self._params.data_simulator.session_params.split_buffer + 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) @@ -754,8 +812,8 @@ class DataAnnotator(object): } return meta - def create_new_ctm_entry( - self, words: List[str], alignments: List[float], session_name: str, speaker_id: int, start: int + 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) @@ -766,12 +824,70 @@ class DataAnnotator(object): 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 ( @@ -780,6 +896,7 @@ class DataAnnotator(object): 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, @@ -789,9 +906,11 @@ class DataAnnotator(object): 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 + return arr, word_and_ts_list def add_to_filename_lists(self, basepath: str, filename: str): """ @@ -835,10 +954,27 @@ class DataAnnotator(object): 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 + Class for sampling speech samples for Multispeaker Audio Session Simulator Args: cfg: OmegaConf configuration loaded from yaml file. @@ -856,23 +992,23 @@ class SpeechSampler(object): 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: + 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. + 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 + + 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. + 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 + 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 + per_overlap_max (float): Maximum per overlap duration in seconds, set -1 for no maximum """ def __init__(self, cfg): @@ -916,7 +1052,7 @@ class SpeechSampler(object): Returns: Tuple[float, float]: a and b parameters for beta distribution. """ - a = mean ** 2 * (1 - mean) / var - mean + a = mean**2 * (1 - mean) / var - mean b = mean * (1 - mean) ** 2 / var - (1 - mean) return a, b @@ -959,7 +1095,7 @@ class SpeechSampler(object): 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 + 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: @@ -993,7 +1129,7 @@ class SpeechSampler(object): 0 < mean_silence_var < mean_silence * (1 - mean_silence) Args: - silence_mean (float): + silence_mean (float): Target mean silence for the current session """ self._init_silence_params() @@ -1045,16 +1181,16 @@ class SpeechSampler(object): 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 + 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`. + 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_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). @@ -1069,11 +1205,7 @@ class SpeechSampler(object): 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() - ) + 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) ) @@ -1092,15 +1224,15 @@ class SpeechSampler(object): 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`. + 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): + non_silence_len_samples (int): The total amount of non-silence (speech) region regardless of overlap status Returns: - desired_overlap_amount (int): + 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) / ( @@ -1110,7 +1242,7 @@ class SpeechSampler(object): 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()) + 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) ) @@ -1126,7 +1258,7 @@ class SpeechSampler(object): Sample noise manifest to a specified count `num_noise_files` for the current simulated audio session. Args: - noise_manifest (list): + noise_manifest (list): List of noise source samples to be sampled from. Returns: diff --git a/nemo/collections/asr/parts/utils/diarization_utils.py b/nemo/collections/asr/parts/utils/diarization_utils.py index f0b951eb89d33c90ada57e7c2097e1eea3c84901..a99f86d6a634709d45a05ea6a828412e4ec852bb 100644 --- a/nemo/collections/asr/parts/utils/diarization_utils.py +++ b/nemo/collections/asr/parts/utils/diarization_utils.py @@ -16,13 +16,16 @@ 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, Tuple +from typing import Dict, List, Optional, Tuple import numpy as np +from pyannote.metrics.diarization import DiarizationErrorRate -from nemo.collections.asr.metrics.der import concat_perm_word_error_rate +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 ( @@ -44,6 +47,23 @@ except ImportError: __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. @@ -72,6 +92,36 @@ def write_txt(w_path: str, val: str): 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. @@ -188,7 +238,9 @@ def convert_word_dict_seq_to_ctm( def get_total_result_dict( - der_results: Dict[str, Dict[str, float]], wer_results: Dict[str, Dict[str, float]], csv_columns: List[str], + 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. @@ -259,6 +311,408 @@ def get_num_of_spk_from_labels(labels: List[str]) -> int: 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. @@ -320,25 +774,9 @@ class OfflineDiarWithASR: self.make_file_lists() - self.color_palette = self.get_color_palette() + self.color_palette = get_color_palette() self.csv_columns = self.get_csv_columns() - @staticmethod - def get_color_palette() -> Dict[str, str]: - return { - 'speaker_0': '\033[1;32m', - 'speaker_1': '\033[1;34m', - 'speaker_2': '\033[1;30m', - 'speaker_3': '\033[1;31m', - 'speaker_4': '\033[1;35m', - 'speaker_5': '\033[1;36m', - 'speaker_6': '\033[1;37m', - 'speaker_7': '\033[1;30m', - 'speaker_8': '\033[1;33m', - 'speaker_9': '\033[0;34m', - 'white': '\033[0;37m', - } - @staticmethod def get_csv_columns() -> List[str]: return [ @@ -387,34 +825,6 @@ class OfflineDiarWithASR: 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 _init_session_trans_dict(self, 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(self): - """ - Initialize a dictionary format for Gecko style json. - - Returns: - (dict): - Gecko style json dictionary. - """ - return od({'schemaVersion': 2.0, 'monologues': []}) - 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 @@ -438,7 +848,8 @@ class OfflineDiarWithASR: @staticmethod def get_speech_labels_from_decoded_prediction( - input_word_ts: List[float], nonspeech_threshold: float, + input_word_ts: List[float], + nonspeech_threshold: float, ) -> List[float]: """ Extract speech labels from the ASR output (decoded predictions) @@ -640,7 +1051,9 @@ class OfflineDiarWithASR: return cursor def _compensate_word_ts_list( - self, audio_file_list: List[str], word_ts_dict: Dict[str, List[float]], + 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. @@ -717,7 +1130,7 @@ class OfflineDiarWithASR: if self.fix_word_ts_with_VAD: if self.frame_VAD == {}: logging.warning( - f"VAD timestamps are not provided. Fixing word timestamps without VAD. Please check the hydra configurations." + "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: @@ -782,7 +1195,7 @@ class OfflineDiarWithASR: 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. @@ -795,9 +1208,9 @@ class OfflineDiarWithASR: 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'}, + >>> [{'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: @@ -817,7 +1230,10 @@ class OfflineDiarWithASR: 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]], + 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. @@ -865,61 +1281,10 @@ class OfflineDiarWithASR: ] } """ - 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': ''} - - n_spk = get_num_of_spk_from_labels(diar_labels) - logging.info(f"Creating results for Session: {uniq_id} n_spk: {n_spk} ") - session_trans_dict = self._init_session_trans_dict(uniq_id=uniq_id, n_spk=n_spk) - gecko_dict = self._init_session_gecko_dict() - - 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) - gecko_dict['monologues'].append({'speaker': {'name': None, 'id': speaker}, 'terms': terms_list}) - - # Speaker independent transcription - session_trans_dict['transcription'] = ' '.join(word_seq_list) - # add sentences to transcription information dict - session_trans_dict['sentences'] = sentences + 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 @@ -1108,7 +1473,7 @@ class OfflineDiarWithASR: 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): + 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 @@ -1162,38 +1527,6 @@ class OfflineDiarWithASR: except IOError: logging.info("I/O error has occurred while writing a csv file.") - def _break_lines(self, string_out: str, max_chars_in_line: int = 90) -> str: - """ - Break the lines in the transcript. - - Args: - string_out (str): - Input transcript with speaker labels - 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 - def _write_and_log( self, uniq_id: str, @@ -1218,9 +1551,9 @@ class OfflineDiarWithASR: List containing sentence dictionary """ # print the sentences in the .txt output - string_out = self.print_sentences(sentences) + string_out = print_sentences(sentences, color_palette=self.color_palette, params=self.params) if self.params['break_lines']: - string_out = self._break_lines(string_out) + 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']) @@ -1231,6 +1564,40 @@ class OfflineDiarWithASR: 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]]): """ @@ -1257,50 +1624,3 @@ class OfflineDiarWithASR: ) else: logging.info(DER_info) - - def print_sentences(self, sentences: List[Dict[str, float]]): - """ - 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 = '' - - for sentence in sentences: - # extract info - speaker = sentence['speaker'] - start_point = sentence['start_time'] - end_point = sentence['end_time'] - text = sentence['text'] - - if self.params['colored_text']: - color = self.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 self.params['print_time']: - time_str = f'[{start_point_str} - {end_point_str}] ' - else: - time_str = '' - - # string out concatenation - string_out += f'{color}{time_str}{speaker}: {text}\n' - - return string_out diff --git a/nemo/collections/asr/parts/utils/eou_utils.py b/nemo/collections/asr/parts/utils/eou_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..478fc44df3a93648a1a4cb8b4a2d2e0181212a7f --- /dev/null +++ b/nemo/collections/asr/parts/utils/eou_utils.py @@ -0,0 +1,289 @@ +# 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 index 5584a50471785243f043fb4e46c009fb3db359f4..c7d23a214bbca3bd2ef51e311927bee63d7dd91d 100644 --- a/nemo/collections/asr/parts/utils/eval_utils.py +++ b/nemo/collections/asr/parts/utils/eval_utils.py @@ -167,8 +167,8 @@ def cal_write_wer( 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) + """ + 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 = [] @@ -177,7 +177,10 @@ def cal_write_wer( eval_metric = "cer" if use_cer else "wer" with open(pred_manifest, 'r') as fp: - for line in 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: @@ -266,7 +269,10 @@ def cal_write_text_metric( 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: + for line in fp.readlines(): + line = line.strip() + if not line: + continue sample = json.loads(line) if gt_text_attr_name not in sample: @@ -322,3 +328,18 @@ def cal_write_text_metric( 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/manifest_utils.py b/nemo/collections/asr/parts/utils/manifest_utils.py index 418f95832f486203c54d23018d209406c044b407..6cd53136046e8fdead63dee696a42be567e2846d 100644 --- a/nemo/collections/asr/parts/utils/manifest_utils.py +++ b/nemo/collections/asr/parts/utils/manifest_utils.py @@ -183,7 +183,7 @@ def get_subsegment_dict(subsegments_manifest_file: str, window: float, shift: fl for segment in segments: segment = segment.strip() dic = json.loads(segment) - audio, offset, duration, label = dic['audio_filepath'], dic['offset'], dic['duration'], dic['label'] + 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'] @@ -432,7 +432,7 @@ def create_manifest( if rttm is not None: rttm = rttm.strip() labels = rttm_to_labels(rttm) - num_speakers = Counter([l.split()[-1] for l in labels]).keys().__len__() + num_speakers = Counter([label.split()[-1] for label in labels]).keys().__len__() else: num_speakers = None @@ -554,3 +554,21 @@ def write_text(output_path: str, target_ctm: Dict[str, dict]): 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 new file mode 100644 index 0000000000000000000000000000000000000000..291705a54f1e84de2f3990064876ab51d4159fc6 --- /dev/null +++ b/nemo/collections/asr/parts/utils/multispk_transcribe_utils.py @@ -0,0 +1,1921 @@ +# 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/rnnt_utils.py b/nemo/collections/asr/parts/utils/rnnt_utils.py index 3e3146ad39019ee12905be062013c34f477568ed..1765a493ced9cfa60567170e390fd9c2480520ab 100644 --- a/nemo/collections/asr/parts/utils/rnnt_utils.py +++ b/nemo/collections/asr/parts/utils/rnnt_utils.py @@ -31,6 +31,8 @@ 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: @@ -87,6 +89,9 @@ class Hypothesis: 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 @@ -106,8 +111,10 @@ class Hypothesis: 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[List[int]] = 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]: @@ -143,6 +150,50 @@ class Hypothesis: """ 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: @@ -242,6 +293,7 @@ class BatchedHyps: init_length: int, device: Optional[torch.device] = None, float_dtype: Optional[torch.dtype] = None, + is_with_durations: bool = False, ): """ @@ -257,6 +309,10 @@ class BatchedHyps: 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) @@ -265,7 +321,8 @@ class BatchedHyps: # 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 - self.token_durations = torch.zeros((batch_size, self._max_length), device=device, dtype=torch.long) + 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) @@ -284,11 +341,13 @@ class BatchedHyps: self.current_lengths.fill_(0) self.transcript.fill_(0) self.timestamps.fill_(0) - self.token_durations.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 @@ -296,7 +355,8 @@ class BatchedHyps: """ 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) - self.token_durations = torch.cat((self.token_durations, torch.zeros_like(self.token_durations)), 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_( @@ -327,7 +387,7 @@ class BatchedHyps: labels=labels, time_indices=time_indices, scores=scores, - token_durations=token_durations, + token_durations=token_durations if self.is_with_durations else None, ) def add_results_no_checks_( @@ -383,6 +443,7 @@ class BatchedHyps: 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() @@ -391,7 +452,7 @@ class BatchedHyps: labels=labels, time_indices=time_indices, scores=scores, - token_durations=token_durations, + token_durations=token_durations if self.is_with_durations else None, ) def add_results_masked_no_checks_( @@ -412,6 +473,7 @@ class BatchedHyps: 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 @@ -420,7 +482,7 @@ class BatchedHyps: # store transcript and timestamps self.transcript[self._batch_indices, self.current_lengths] = labels self.timestamps[self._batch_indices, self.current_lengths] = time_indices - if token_durations is not None: + 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 @@ -441,6 +503,71 @@ class BatchedHyps: # 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: """ @@ -474,6 +601,10 @@ class BatchedAlignments: 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 @@ -622,6 +753,25 @@ class BatchedAlignments: # 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 @@ -641,17 +791,20 @@ def batched_hyps_to_hypotheses( """ 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=batched_hyps.scores[i].item(), - y_sequence=batched_hyps.transcript[i, : batched_hyps.current_lengths[i]], - timestamp=batched_hyps.timestamps[i, : batched_hyps.current_lengths[i]], + score=scores[i].item(), + y_sequence=transcript[i, : current_lengths[i]], + timestamp=timestamps[i, : batched_hyps.current_lengths[i]], token_duration=( - durations - if not torch.all( - (durations := batched_hyps.token_durations[i, : batched_hyps.current_lengths[i]]) == 0 - ) - else [] + 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, diff --git a/nemo/collections/asr/parts/utils/speaker_utils.py b/nemo/collections/asr/parts/utils/speaker_utils.py index 223916e60a76183cda8fbbd97038315d8f0c0fbc..99bd29760ffc0a39d9caf1232f5afc648068d6ef 100644 --- a/nemo/collections/asr/parts/utils/speaker_utils.py +++ b/nemo/collections/asr/parts/utils/speaker_utils.py @@ -16,9 +16,8 @@ import gc import json import math import os -import shutil from copy import deepcopy -from typing import Dict, List, Tuple, Union +from typing import Dict, List, Tuple import numpy as np import soundfile as sf @@ -29,7 +28,6 @@ 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.collections.asr.parts.utils.offline_clustering import get_argmin_mat, split_input_data from nemo.utils import logging @@ -1363,351 +1361,6 @@ def get_online_subsegments_from_buffer( return sigs_list, sig_rangel_list, sig_indexes -def get_scale_mapping_argmat(uniq_embs_and_timestamps: Dict[str, dict]) -> Dict[int, torch.Tensor]: - """ - Calculate cosine similarity values among speaker embeddings for each scale then - apply multiscale weights to calculate the fused similarity matrix. - - Args: - uniq_embs_and_timestamps: (dict) - The dictionary containing embeddings, timestamps and multiscale weights. - If uniq_embs_and_timestamps contains only one scale, single scale diarization - is performed. - - Returns: - scale_mapping_argmat (dict) - Dictionary containing scale mapping information matrix for each scale. - """ - scale_mapping_argmat = {} - 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'], - ) - session_scale_mapping_list = get_argmin_mat(timestamps_in_scales) - for scale_idx in range(len(session_scale_mapping_list)): - mapping_argmat = session_scale_mapping_list[scale_idx] - scale_mapping_argmat[scale_idx] = mapping_argmat - return scale_mapping_argmat - - -def get_overlap_stamps(cont_stamps: List[str], ovl_spk_idx: List[str]): - """ - Generate timestamps that include overlap speech. Overlap-including timestamps are created based on - the segments that are created for clustering diarizer. Overlap speech is assigned to the existing - speech segments in `cont_stamps`. - - Args: - cont_stamps (list): - Non-overlapping (single speaker per segment) diarization output in string format. Each line - contains the start and end time of segments and corresponding speaker labels. - ovl_spk_idx (list): - List containing segment index of the estimated overlapped speech. The start and end of - segments are based on the single-speaker (i.e., non-overlap-aware) RTTM generation. - - Returns: - total_ovl_cont_list (list): - Rendered diarization output in string format. Each line contains the start and end time of - segments and corresponding speaker labels. This format is identical to `cont_stamps`. - """ - ovl_spk_cont_list = [[] for _ in range(len(ovl_spk_idx))] - for spk_idx in range(len(ovl_spk_idx)): - for idx, cont_a_line in enumerate(cont_stamps): - start, end, speaker = cont_a_line.split() - if idx in ovl_spk_idx[spk_idx]: - ovl_spk_cont_list[spk_idx].append(f"{start} {end} speaker_{spk_idx}") - total_ovl_cont_list = [] - for ovl_cont_list in ovl_spk_cont_list: - if len(ovl_cont_list) > 0: - total_ovl_cont_list.extend(merge_stamps(ovl_cont_list)) - return total_ovl_cont_list - - -def get_adaptive_threshold(estimated_num_of_spks: int, min_threshold: float, overlap_infer_spk_limit: int): - """ - This function controls the magnitude of the sigmoid threshold based on the estimated number of - speakers. As the number of speakers becomes larger, diarization error rate is very sensitive - to overlap speech detection. This function linearly increases the threshold in proportion to - the estimated number of speakers so more confident overlap speech results are reflected when - the number of estimated speakers is relatively high. - - Args: - estimated_num_of_spks (int): - Estimated number of speakers from the clustering result. - min_threshold (float): - Sigmoid threshold value from the config file. This threshold value is the minimum - threshold when `estimated_num_of_spks=2`. - overlap_infer_spk_limit (int): - If the `estimated_num_of_spks` is less than `overlap_infer_spk_limit`, overlap speech - estimation is skipped. - - Returns: - adaptive_threshold (float): - Threshold value that is scaled based on the `estimated_num_of_spks`. - """ - adaptive_threshold = min_threshold - (estimated_num_of_spks - 2) * (min_threshold - 1) / ( - overlap_infer_spk_limit - 2 - ) - return adaptive_threshold - - -def generate_speaker_timestamps( - clus_labels: List[Union[float, int]], msdd_preds: List[torch.Tensor], **params -) -> Tuple[List[str], List[str]]: - """ - Generate speaker timestamps from the segmentation information. If `use_clus_as_main=True`, use - clustering result for main speaker labels and use timestamps from the predicted sigmoid values. - In this function, the main speaker labels in `maj_labels` exist for every subsegment step, while - overlap speaker labels in `ovl_labels` only exist for segments where overlap speech occurs. - - Args: - clus_labels (list): - List containing integer-valued speaker clustering results. - msdd_preds (list): - List containing tensors of the predicted sigmoid values. Each tensor has shape of: - (Session length, estimated number of speakers). - params: - Parameters for generating RTTM output and evaluation. Parameters include: - infer_overlap (bool): If False, overlap speech will not be detected. - use_clus_as_main (bool): Add overlap-speech detection from MSDD to clustering results. - If False, only MSDD output is used for constructing output - RTTM files. - overlap_infer_spk_limit (int): Above this limit, overlap-speech detection is bypassed. - use_adaptive_thres (bool): Boolean that determines whether to use adaptive thresholds - depending on the estimated number of speakers. - max_overlap_spks (int): Maximum number of overlap speakers detected. Default is 2. - threshold (float): Sigmoid threshold for MSDD output. - - Returns: - maj_labels (list): - List containing string-formatted single-speaker speech segment timestamps and corresponding - speaker labels. - Example: [..., '551.685 552.77 speaker_1', '552.99 554.43 speaker_0', '554.97 558.19 speaker_0', ...] - ovl_labels (list): - List containing string-formatted additional overlapping speech segment timestamps and - corresponding speaker labels. Note that `ovl_labels` includes only overlapping speech that - is not included in `maj_labels`. - Example: [..., '152.495 152.745 speaker_1', '372.71 373.085 speaker_0', '554.97 555.885 speaker_1', ...] - """ - msdd_preds.squeeze(0) - estimated_num_of_spks = msdd_preds.shape[-1] - overlap_speaker_list = [[] for _ in range(estimated_num_of_spks)] - infer_overlap = estimated_num_of_spks < int(params['overlap_infer_spk_limit']) - main_speaker_lines = [] - if params['use_adaptive_thres']: - threshold = get_adaptive_threshold( - estimated_num_of_spks, params['threshold'], params['overlap_infer_spk_limit'] - ) - else: - threshold = params['threshold'] - for seg_idx, cluster_label in enumerate(clus_labels): - msdd_preds.squeeze(0) - spk_for_seg = (msdd_preds[0, seg_idx] > threshold).int().cpu().numpy().tolist() - sm_for_seg = msdd_preds[0, seg_idx].cpu().numpy() - - if params['use_clus_as_main']: - main_spk_idx = int(cluster_label[2]) - else: - main_spk_idx = np.argsort(msdd_preds[0, seg_idx].cpu().numpy())[::-1][0] - - if sum(spk_for_seg) > 1 and infer_overlap: - idx_arr = np.argsort(sm_for_seg)[::-1] - for ovl_spk_idx in idx_arr[: params['max_overlap_spks']].tolist(): - if ovl_spk_idx != int(main_spk_idx): - overlap_speaker_list[ovl_spk_idx].append(seg_idx) - main_speaker_lines.append(f"{cluster_label[0]} {cluster_label[1]} speaker_{main_spk_idx}") - cont_stamps = get_contiguous_stamps(main_speaker_lines) - maj_labels = merge_stamps(cont_stamps) - ovl_labels = get_overlap_stamps(cont_stamps, overlap_speaker_list) - return maj_labels, ovl_labels - - -def get_uniq_id_list_from_manifest(manifest_file: str): - """Retrieve `uniq_id` values from the given manifest_file and save the IDs to a list.""" - uniq_id_list = [] - 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_id = get_uniqname_from_filepath(dic['audio_filepath']) - uniq_id_list.append(uniq_id) - return uniq_id_list - - -def get_id_tup_dict(uniq_id_list: List[str], test_data_collection, preds_list: List[torch.Tensor]): - """ - Create session-level dictionary containing data needed to construct RTTM diarization output. - - Args: - uniq_id_list (list): - List containing the `uniq_id` values. - test_data_collection (collections.DiarizationLabelEntity): - Class instance that is containing session information such as targeted speaker indices, - audio filepath and RTTM filepath. - preds_list (list): - List containing tensors of predicted sigmoid values. - - Returns: - session_dict (dict): - Dictionary containing session-level target speakers data and predicted simoid values in tensor format. - """ - session_dict = {x: [] for x in uniq_id_list} - for idx, line in enumerate(test_data_collection): - uniq_id = get_uniqname_from_filepath(line.audio_file) - session_dict[uniq_id].append([line.target_spks, preds_list[idx]]) - return session_dict - - -def prepare_split_data(manifest_filepath, _out_dir, multiscale_args_dict, global_rank): - """ - This function is needed for preparing diarization training data for multiscale diarization decoder (MSDD). - Prepare multiscale timestamp data for training. Oracle VAD timestamps from RTTM files are used as VAD timestamps. - In this function, timestamps for embedding extraction are extracted without extracting the embedding vectors. - - Args: - manifest_filepath (str): - Input manifest file for creating audio-to-RTTM mapping. - _out_dir (str): - Output directory where timestamp json files are saved. - - Returns: - multiscale_args_dict (dict): - - Dictionary containing two types of arguments: multi-scale weights and subsegment timestamps - for each data sample. - - Each data sample has two keys: `multiscale_weights` and `scale_dict`. - - `multiscale_weights` key contains a list containing multiscale weights. - - `scale_dict` is indexed by integer keys which are scale index. - - Each data sample is indexed by using the following naming convention: - `__` - - Example: `fe_03_00106_mixed_626310_642300` - """ - speaker_dir = os.path.join(_out_dir, 'speaker_outputs') - - # Only if this is for the first run of modelPT instance, remove temp folders. - if global_rank == 0: - if os.path.exists(speaker_dir): - shutil.rmtree(speaker_dir) - os.makedirs(speaker_dir) - split_audio_rttm_map = audio_rttm_map(manifest_filepath, attach_dur=True) - - # Speech Activity Detection part - _speaker_manifest_path = os.path.join(speaker_dir, f'oracle_vad_manifest.json') - logging.info(f"Extracting oracle VAD timestamps and saving at {speaker_dir}") - if not os.path.exists(_speaker_manifest_path): - write_rttm2manifest(split_audio_rttm_map, _speaker_manifest_path, include_uniq_id=True) - - multiscale_timestamps_by_scale = {} - - # Segmentation - for scale_idx, (window, shift) in multiscale_args_dict['scale_dict'].items(): - subsegments_manifest_path = os.path.join(speaker_dir, f'subsegments_scale{scale_idx}.json') - if not os.path.exists(subsegments_manifest_path): - # Sub-segmentation for the current scale (scale_idx) - segments_manifest_to_subsegments_manifest( - segments_manifest_file=_speaker_manifest_path, - subsegments_manifest_file=subsegments_manifest_path, - window=window, - shift=shift, - include_uniq_id=True, - ) - logging.info( - f"Subsegmentation for timestamp extracted for: scale-{scale_idx} at {subsegments_manifest_path}" - ) - multiscale_timestamps = extract_timestamps(subsegments_manifest_path) - multiscale_timestamps_by_scale[scale_idx] = multiscale_timestamps - - multiscale_timestamps_dict = get_timestamps(multiscale_timestamps_by_scale, multiscale_args_dict) - return multiscale_timestamps_dict - - -def extract_timestamps(manifest_file: str): - """ - This method extracts timestamps from segments passed through manifest_file. - - Args: - manifest_file (str): - Manifest file containing segmentation information. - Returns: - time_stamps (dict): - Dictionary containing lists of timestamps. - """ - logging.info(f"Extracting timestamps from {manifest_file} for multiscale subsegmentation.") - time_stamps = {} - 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 = dic['uniq_id'] - if uniq_name not in time_stamps: - time_stamps[uniq_name] = [] - start = dic['offset'] - end = start + dic['duration'] - time_stamps[uniq_name].append([start, end]) - return time_stamps - - -def make_rttm_with_overlap( - manifest_file_path: str, - clus_label_dict: Dict[str, List[Union[float, int]]], - msdd_preds: List[torch.Tensor], - **params, -): - """ - Create RTTM files that include detected overlap speech. Note that the effect of overlap detection is only - notable when RTTM files are evaluated with `ignore_overlap=False` option. - - Args: - manifest_file_path (str): - Path to the input manifest file. - clus_label_dict (dict): - Dictionary containing subsegment timestamps in float type and cluster labels in integer type. - Indexed by `uniq_id` string. - msdd_preds (list): - List containing tensors of the predicted sigmoid values. - Each tensor has shape of: (Session length, estimated number of speakers). - params: - Parameters for generating RTTM output and evaluation. Parameters include: - infer_overlap (bool): If False, overlap-speech will not be detected. - See docstrings of `generate_speaker_timestamps` function for other variables in `params`. - - Returns: - all_hypothesis (list): - List containing Pyannote's `Annotation` objects that are created from hypothesis RTTM outputs. - all_reference - List containing Pyannote's `Annotation` objects that are created from ground-truth RTTM outputs - """ - AUDIO_RTTM_MAP = audio_rttm_map(manifest_file_path) - manifest_file_lengths_list = [] - all_hypothesis, all_reference = [], [] - no_references = False - with open(manifest_file_path, 'r', encoding='utf-8') as manifest: - for i, line in enumerate(manifest.readlines()): - uniq_id = get_uniq_id_from_manifest_line(line) - manifest_dic = AUDIO_RTTM_MAP[uniq_id] - clus_labels = clus_label_dict[uniq_id] - manifest_file_lengths_list.append(len(clus_labels)) - maj_labels, ovl_labels = generate_speaker_timestamps(clus_labels, msdd_preds[i], **params) - if params['infer_overlap']: - hyp_labels = maj_labels + ovl_labels - else: - hyp_labels = maj_labels - hypothesis = labels_to_pyannote_object(hyp_labels, uniq_name=uniq_id) - if params['out_rttm_dir']: - hyp_labels = sorted(hyp_labels, key=lambda x: float(x.split()[0])) - labels_to_rttmfile(hyp_labels, uniq_id, params['out_rttm_dir']) - all_hypothesis.append([uniq_id, hypothesis]) - rttm_file = manifest_dic.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 = [] - return all_reference, all_hypothesis - - def timestamps_to_pyannote_object( speaker_timestamps: List[Tuple[float, float]], uniq_id: str, diff --git a/nemo/collections/asr/parts/utils/streaming_utils.py b/nemo/collections/asr/parts/utils/streaming_utils.py index d7b97292b3c603b63a2cebc7f968e6a354b42d0e..d657c56a67b6da3150357bfb59d973d449f16173 100644 --- a/nemo/collections/asr/parts/utils/streaming_utils.py +++ b/nemo/collections/asr/parts/utils/streaming_utils.py @@ -13,19 +13,29 @@ # limitations under the License. import copy +import logging +import math import os -from typing import Optional +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.utils.data import DataLoader +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 @@ -287,39 +297,62 @@ def longest_common_subsequence_merge(X, Y, filepath=None): return result_idx, LCSuff -def lcs_alignment_merge_buffer(buffer, data, delay, model, max_steps_per_timestep: int = 5, filepath: str = None): +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 assumptio is violated, the results of the + 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 delay timesteps is 0, that means no future context was used. Simply concatenate the buffer with new data. - if delay < 1: - buffer += data - return buffer - # If buffer is empty, simply concatenate the buffer and data. - if len(buffer) == 0: + 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 - # Prepare a subset of the buffer that will be LCS Merged with new data search_size = int(delay * max_steps_per_timestep) buffer_slice = buffer[-search_size:] - # Perform LCS Merge lcs_idx, lcs_alignment = longest_common_subsequence_merge(buffer_slice, data, filepath=filepath) + i_rel, j_rel, length = lcs_idx - # Slice off new data - # i, j, slice_len = lcs_idx - slice_idx = lcs_idx[1] + lcs_idx[-1] # slice = j + slice_len - data = data[slice_idx:] + if length < min_lcs_length: + return buffer + data - # Concat data to buffer - buffer += data - return buffer + 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): @@ -738,7 +771,10 @@ class FrameBatchASR: self.unmerged = [] if self.decoder is None: - self.blank_id = len(asr_model.tokenizer.vocabulary) + 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: @@ -998,6 +1034,7 @@ class BatchedFrameASRRNNT(FrameBatchASR): batch_size=32, max_steps_per_timestep: int = 5, stateful_decoding: bool = False, + target_lang_id=None, ): ''' Args: @@ -1007,12 +1044,14 @@ class BatchedFrameASRRNNT(FrameBatchASR): 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)] @@ -1029,6 +1068,8 @@ class BatchedFrameASRRNNT(FrameBatchASR): 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 @@ -1036,6 +1077,10 @@ class BatchedFrameASRRNNT(FrameBatchASR): 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 @@ -1124,7 +1169,7 @@ class BatchedFrameASRRNNT(FrameBatchASR): feat_signals.append(feat_signal) feat_signal_lens.append(feat_signal_len) - # preserve batch indeices + # preserve batch indices new_batch_keys.append(idx) if len(feat_signals) == 0: @@ -1135,7 +1180,51 @@ class BatchedFrameASRRNNT(FrameBatchASR): del feat_signals, feat_signal_lens - encoded, encoded_len = self.asr_model(processed_signal=feat_signal, processed_signal_length=feat_signal_len) + # 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: @@ -1263,6 +1352,108 @@ class BatchedFrameASRRNNT(FrameBatchASR): 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. @@ -1607,45 +1798,119 @@ class CacheAwareStreamingAudioBuffer: 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": - missing_keys = [k for k in ("source_lang", "target_lang", "taskname", "pnc") 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}" - ) - tokens = self.asr_model.prompt.encode_dialog( - turns=[ - { - "role": "user", - "slots": { - **sample, - self.asr_model.prompt.PROMPT_LANGUAGE_SLOT: "spl_tokens", - }, - } - ] - )["context_ids"] + 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) - samples = np.pad(samples, (0, int(delay * model_stride_in_secs * self.asr_model._cfg.sample_rate))) + padded_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 + 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): + 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() @@ -1660,25 +1925,138 @@ class FrameBatchMultiTaskAED(FrameBatchASR): prompted_transcript=None, prompted_transcript_lens=None, ) - predictions = self.asr_model.predict_step(batch_input, has_processed_signal=True) + 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 + 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) + 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) - hypothesis = " ".join([h.text for h in self.all_preds]) 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): @@ -1783,3 +2161,234 @@ class FrameBatchChunkedCTC(FrameBatchASR): 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 new file mode 100644 index 0000000000000000000000000000000000000000..e4ce4eef8baaae6432dc330a8cd5193ead47b880 --- /dev/null +++ b/nemo/collections/asr/parts/utils/timestamp_utils.py @@ -0,0 +1,670 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..d4f15f5123de57e760bb84b5e6dd3bf3b11cb3c1 --- /dev/null +++ b/nemo/collections/asr/parts/utils/tokenizer_utils.py @@ -0,0 +1,71 @@ +# 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 index 1589a813387bbe845dcbe8be7e392af6028d2d2a..9c576ce3c09349c7129e16939806d82433efd877 100644 --- a/nemo/collections/asr/parts/utils/transcribe_utils.py +++ b/nemo/collections/asr/parts/utils/transcribe_utils.py @@ -24,7 +24,6 @@ import torch from omegaconf import DictConfig from tqdm.auto import tqdm -import nemo.collections.asr as nemo_asr 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 @@ -33,6 +32,73 @@ from nemo.collections.common.metrics.punct_er import OccurancePunctuationErrorRa 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, @@ -42,6 +108,7 @@ def get_buffered_pred_feat_rnnt( batch_size: int, manifest: str = None, filepaths: List[list] = None, + target_lang_id: str = None, accelerator: Optional[str] = 'cpu', ) -> List[rnnt_utils.Hypothesis]: """ @@ -50,6 +117,7 @@ def get_buffered_pred_feat_rnnt( """ hyps = [] refs = [] + lang_ids = [] if filepaths and manifest: raise ValueError("Please select either filepaths or manifest") @@ -70,22 +138,46 @@ def get_buffered_pred_feat_rnnt( 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.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: @@ -93,12 +185,19 @@ def get_buffered_pred_feat_rnnt( 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'): @@ -115,71 +214,6 @@ def get_buffered_pred_feat_rnnt( return wrapped_hyps -def get_buffered_pred_feat( - asr: FrameBatchASR, - frame_len: float, - tokens_per_chunk: int, - delay: int, - preprocessor_cfg: DictConfig, - model_stride_in_secs: int, - device: Union[List[int], int], - manifest: str = None, - filepaths: List[list] = None, -) -> List[rnnt_utils.Hypothesis]: - """ - Moved from examples/asr/asr_chunked_inference/ctc/speech_to_text_buffered_infer_ctc.py - Write all information presented in input manifest to output manifest and removed WER calculation. - """ - # 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 = nemo_asr.models.EncDecCTCModelBPE.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: - for L in tqdm(filepaths, desc="Sample:"): - asr.reset() - asr.read_audio_file(L, delay, model_stride_in_secs) - hyp = asr.transcribe(tokens_per_chunk, delay) - hyps.append(hyp) - else: - with open(manifest, "r", encoding='utf_8') as mfst_f: - for L in tqdm(mfst_f, desc="Sample:"): - asr.reset() - L = L.strip() - if not L: - continue - row = json.loads(L) - if 'text' in row: - refs.append(row['text']) - audio_file = get_full_path(audio_file=row['audio_filepath'], manifest_file=manifest) - # do not support partial audio - asr.read_audio_file(audio_file, delay, model_stride_in_secs) - hyp = asr.transcribe(tokens_per_chunk, delay) - hyps.append(hyp) - - 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, @@ -188,6 +222,7 @@ def get_buffered_pred_feat_multitaskAED( 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 @@ -217,10 +252,11 @@ def get_buffered_pred_feat_multitaskAED( '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() + hyp = asr.transcribe(timestamps=timestamps) hyps.append(hyp) else: with open(manifest, "r", encoding='utf_8') as fin: @@ -231,12 +267,15 @@ def get_buffered_pred_feat_multitaskAED( 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() + hyp = asr.transcribe(timestamps=timestamps) hyps.append(hyp) wrapped_hyps = wrap_transcription(hyps) @@ -245,6 +284,9 @@ def get_buffered_pred_feat_multitaskAED( 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) @@ -349,7 +391,7 @@ def read_and_maybe_sort_manifest(path: str, try_sort: bool = False) -> List[dict def restore_transcription_order(manifest_path: str, transcriptions: list) -> list: - with open(manifest_path) as f: + 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 @@ -361,6 +403,7 @@ def restore_transcription_order(manifest_path: str, transcriptions: list) -> lis 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 @@ -593,61 +636,6 @@ def compute_metrics_per_sample( return samples_with_metrics -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, rnnt_utils.Hypothesis): - outputs = [outputs] - - if not isinstance(outputs[0], rnnt_utils.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 - - class PunctuationCapitalization: def __init__(self, punctuation_marks: str): """ diff --git a/nemo/collections/asr/parts/utils/vad_utils.py b/nemo/collections/asr/parts/utils/vad_utils.py index 593ccab0af8d2815e87ac30644d790bc473659a7..0848a4f9c3f1a991aa309a11ac653034c22d0ad9 100644 --- a/nemo/collections/asr/parts/utils/vad_utils.py +++ b/nemo/collections/asr/parts/utils/vad_utils.py @@ -59,8 +59,8 @@ class PostProcessingParams: 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 small non-speech deletion - min_duration_off: float = 0.0 # Threshold for short speech segment deletion + 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: @@ -625,9 +625,9 @@ def filtering(speech_segments: torch.Tensor, per_args: Dict[str, float]) -> torc torch.Tensor([[start1, end1], [start2, end2]]). per_args: min_duration_on (float): - Threshold for small non-speech deletion. - min_duration_off (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. diff --git a/nemo/collections/asr/parts/utils/wfst_utils.py b/nemo/collections/asr/parts/utils/wfst_utils.py index 867b44fd6053c5ccec2c0f86c279f05265ed4204..d06493783ccca47cab357ab428f78513acfa761d 100644 --- a/nemo/collections/asr/parts/utils/wfst_utils.py +++ b/nemo/collections/asr/parts/utils/wfst_utils.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -881,8 +881,8 @@ def mkgraph_ctc_ov( 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", # "kaldi", "k2" -) -> Tuple[Union['kaldifst.StdVectorFst', 'k2.Fsa'], int]: + target: str = "kaldi", +) -> Tuple['kaldifst.StdVectorFst', int]: """ Builds a decoding WFST (TLG.fst or TLG.pt). @@ -908,10 +908,10 @@ def mkgraph_ctc_ov( Pair of weights (oov_word_weight, token_unigram_weight). target: - What type to build the WFST for. Choices: kaldi, k2. + What type to build the WFST for. Choices: kaldi. Returns: - A pair of kaldi- or k2-type decoding WFST and its id of the tokenword disambiguation token. + A pair of kaldi-type decoding WFST and its id of the tokenword disambiguation token. """ _kaldifst_maybe_raise() @@ -953,37 +953,6 @@ def mkgraph_ctc_ov( if write_tlg_path: logging.info(f"Buffering TLG.fst into {write_tlg_path} ...") TLG.write(write_tlg_path) - elif target == "k2": - logging.info("Converting TLG.fst to k2 ...") - import torch - - from nemo.core.utils.k2_guard import k2 - - blank_id = [i for i, t in lexicon_disambig.id2token.items() if t.mark == "blank"][0] - first_token_disambig_id = [i for i, t in lexicon_disambig.id2token.items() if t.mark == "disambig_backoff"][0] - word_disambig_id = lexicon_disambig.word2id[lexicon_disambig.id2token[first_token_disambig_id].name] - assert lexicon_disambig.id2word[word_disambig_id].mark == "disambig_backoff" - input_symbols = "\n".join( - [f"{k} {v - 1}" for k, v in lexicon_disambig.token2id.items() if 0 < v < first_token_disambig_id] - ) - output_symbols = str(TLG.output_symbols) - TLG.input_symbols = None - TLG.output_symbols = None - # k2 does not support torch.inference_mode enabled - with torch.inference_mode(False): - TLG = k2.Fsa.from_openfst(TLG.to_str(show_weight_one=True), acceptor=False) - TLG.labels[TLG.labels >= first_token_disambig_id] = blank_id - TLG.aux_labels[TLG.aux_labels.values == word_disambig_id] = 0 - TLG.__dict__["_properties"] = None - TLG = k2.arc_sort(k2.connect(k2.remove_epsilon(TLG))) - TLG.labels[TLG.labels > 0] = TLG.labels[TLG.labels > 0] - 1 - TLG.__dict__["_properties"] = None - TLG.labels_sym = k2.SymbolTable.from_str(input_symbols) - TLG.aux_labels_sym = k2.SymbolTable.from_str(output_symbols) - TLG = k2.arc_sort(TLG) - if write_tlg_path: - logging.info(f"Buffering TLG.pt into {write_tlg_path} ...") - torch.save(TLG.as_dict(), write_tlg_path) else: raise ValueError(f"Unsupported target: `{target}`") diff --git a/nemo/collections/audio/README.md b/nemo/collections/audio/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9dd6215c554c255f5f2651a190775a4e1c9f0909 --- /dev/null +++ b/nemo/collections/audio/README.md @@ -0,0 +1,12 @@ +# 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 index f3d156609487108b3da0b8444676167417b2d25b..b53a75b366428110a9e1fb523007a92b519e7625 100644 --- a/nemo/collections/audio/__init__.py +++ b/nemo/collections/audio/__init__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. diff --git a/nemo/collections/audio/data/__init__.py b/nemo/collections/audio/data/__init__.py index d9155f923f186a086a69de138e984e2fab2817ec..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c 100644 --- a/nemo/collections/audio/data/__init__.py +++ b/nemo/collections/audio/data/__init__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. diff --git a/nemo/collections/audio/data/audio_to_audio.py b/nemo/collections/audio/data/audio_to_audio.py index 78d863e312d1742ef626df57ff4d667309f9ad3b..bb56b89d64c3c6d97ee0514d7af87f559fb3ca9e 100644 --- a/nemo/collections/audio/data/audio_to_audio.py +++ b/nemo/collections/audio/data/audio_to_audio.py @@ -794,23 +794,17 @@ 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 - ``` - { - 'input_key': 'path/to/input.wav', - 'target_key': 'path/to/path_to_target.wav', - 'duration': duration_of_input, - } - ``` + 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, - ``` - { - 'input_key': 'path/to/input.wav', - 'target_key': ['path/to/path_to_target_ch0.wav', 'path/to/path_to_target_ch1.wav'], - 'duration': duration_of_input, - } - ``` + + .. 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`). @@ -883,15 +877,15 @@ class AudioToTargetDataset(BaseAudioDataset): """Returns definitions of module output ports. Returns: - Ordered dictionary in the following form: - ``` - { - 'input_signal': batched single- or multi-channel format, - 'input_length': batched original length of each input signal - 'target_signal': batched single- or multi-channel format, - 'target_length': batched original length of each target signal - } - ``` + 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()) @@ -922,14 +916,10 @@ class AudioToTargetWithReferenceDataset(BaseAudioDataset): - reference from another sensor that correlates with the target signal Each line of the manifest file is expected to have the following format - ``` - { - 'input_key': 'path/to/input.wav', - 'target_key': 'path/to/path_to_target.wav', - 'reference_key': 'path/to/path_to_reference.wav', - 'duration': duration_of_input, - } - ``` + + .. 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. @@ -1031,17 +1021,19 @@ class AudioToTargetWithReferenceDataset(BaseAudioDataset): """Returns definitions of module output ports. Returns: - Ordered dictionary in the following form: - ``` - { - 'input_signal': batched single- or multi-channel format, - 'input_length': batched original length of each input signal - 'target_signal': batched single- or multi-channel format, - 'target_length': batched original length of each target signal - 'reference_signal': single- or multi-channel format, - 'reference_length': original length of each reference signal - } - ``` + 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()) @@ -1069,14 +1061,10 @@ class AudioToTargetWithEmbeddingDataset(BaseAudioDataset): is in a form of a vector. Each line of the manifest file is expected to have the following format - ``` - { - input_key: 'path/to/input.wav', - target_key: 'path/to/path_to_target.wav', - embedding_key: 'path/to/path_to_reference.npy', - 'duration': duration_of_input, - } - ``` + + .. 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. @@ -1155,17 +1143,19 @@ class AudioToTargetWithEmbeddingDataset(BaseAudioDataset): """Returns definitions of module output ports. Returns: - Ordered dictionary in the following form: - ``` - { - 'input_signal': batched single- or multi-channel format, - 'input_length': batched original length of each input signal - 'target_signal': batched single- or multi-channel format, - 'target_length': batched original length of each target signal - 'embedding_vector': batched embedded vector format, - 'embedding_length': batched original length of each embedding vector - } - ``` + 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()) diff --git a/nemo/collections/audio/data/audio_to_audio_lhotse.py b/nemo/collections/audio/data/audio_to_audio_lhotse.py index 4cf243b68ed306938eea5690d21707c45f938a49..aca86787b44eff2b2479bc47189248f9a9fc23ae 100644 --- a/nemo/collections/audio/data/audio_to_audio_lhotse.py +++ b/nemo/collections/audio/data/audio_to_audio_lhotse.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. diff --git a/nemo/collections/audio/data/data_simulation.py b/nemo/collections/audio/data/data_simulation.py index d03c5c64d307d1770f72a8609de027710b745cee..f70b34fe83ed02faa9a172e16280a2b6cf62d63a 100644 --- a/nemo/collections/audio/data/data_simulation.py +++ b/nemo/collections/audio/data/data_simulation.py @@ -18,7 +18,6 @@ import os import random from typing import Dict, Iterable, List, Optional, Tuple, Union -import h5py import librosa import matplotlib.pyplot as plt import numpy as np @@ -41,6 +40,13 @@ try: 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 @@ -878,6 +884,8 @@ def save_rir_simulation(filepath: str, rir_dataset: Dict[str, List[np.array]], m 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}') @@ -914,6 +922,8 @@ def load_rir_simulation(filepath: str, source: int = 0, rir_key: str = 'rir') -> 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}'][:] diff --git a/nemo/collections/audio/losses/__init__.py b/nemo/collections/audio/losses/__init__.py index f4a1a42ff20bdce36974ca0753e6ddb3c93d9201..154f14f0228d3f3b63c58aa748af912fe6e65e2c 100644 --- a/nemo/collections/audio/losses/__init__.py +++ b/nemo/collections/audio/losses/__init__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -13,3 +13,5 @@ # 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 index ce6b82875e6b83321c55d0bd4a7c8fe55e574c2a..04f55ea463e3377ee203e8f47e6c2980b8852b46 100644 --- a/nemo/collections/audio/losses/audio.py +++ b/nemo/collections/audio/losses/audio.py @@ -367,10 +367,7 @@ class SDRLoss(Loss, Typing): @property def output_types(self): - """Output types definitions for SDRLoss. - loss: - NeuralType(None) - """ + """Output types definitions for SDRLoss.""" return {"loss": NeuralType(elements_type=LossType())} @typecheck() @@ -539,10 +536,7 @@ class MSELoss(Loss, Typing): @property def output_types(self): - """Output types definitions for SDRLoss. - loss: - NeuralType(None) - """ + """Output types definitions for MSELoss.""" return {"loss": NeuralType(elements_type=LossType())} @typecheck() @@ -663,9 +657,9 @@ class MAELoss(Loss, Typing): 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(f'Channel weight set to %s', weight) + logging.info('Channel weight set to %s', weight) self.register_buffer('weight', weight) - self.weight: Optional[Tensor] + self.weight: Optional[torch.Tensor] # Batch reduction self.reduction = reduction @@ -704,10 +698,7 @@ class MAELoss(Loss, Typing): @property def output_types(self): - """Output types definitions for MAELoss. - loss: - NeuralType(None) - """ + """Output types definitions for MAELoss.""" return {"loss": NeuralType(elements_type=LossType())} @typecheck() diff --git a/nemo/collections/llm/distillation/__init__.py b/nemo/collections/audio/losses/maxine/__init__.py similarity index 83% rename from nemo/collections/llm/distillation/__init__.py rename to nemo/collections/audio/losses/maxine/__init__.py index 78eddd3b5ad7e883d360c27e002f0c6ca4fdfc87..6fcdfe815c0dde793570a1722625382e53a8c56c 100644 --- a/nemo/collections/llm/distillation/__init__.py +++ b/nemo/collections/audio/losses/maxine/__init__.py @@ -12,7 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. -from .loss import LogitsKLLoss -from .model import DistillationGPTModel +from nemo.collections.audio.losses.maxine.losses_combined import CombinedLoss -__all__ = ["LogitsKLLoss", "DistillationGPTModel"] +__all__ = [ + 'CombinedLoss', +] diff --git a/nemo/collections/audio/losses/maxine/losses_combined.py b/nemo/collections/audio/losses/maxine/losses_combined.py new file mode 100644 index 0000000000000000000000000000000000000000..95d95fe64ae82f615bd8866031db8e9f04b97b18 --- /dev/null +++ b/nemo/collections/audio/losses/maxine/losses_combined.py @@ -0,0 +1,205 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..89c20e5cd0a3130515f7e42d47ff2de8e8f5f0ed --- /dev/null +++ b/nemo/collections/audio/losses/maxine/sisnr_loss.py @@ -0,0 +1,149 @@ +# 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 index 20c8fd2fa4e28a2c6a4224c4170ef9129e6d3793..7a3c234cedf824860d49bc126ceaf51b7ee76f16 100644 --- a/nemo/collections/audio/metrics/__init__.py +++ b/nemo/collections/audio/metrics/__init__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. diff --git a/nemo/collections/audio/metrics/squim.py b/nemo/collections/audio/metrics/squim.py index c20be43f79f8e863f04835d1ed28c73a50501ad7..58f42f86d03709f92d2d6a4b8569848a84dcd77a 100644 --- a/nemo/collections/audio/metrics/squim.py +++ b/nemo/collections/audio/metrics/squim.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. diff --git a/nemo/collections/audio/models/__init__.py b/nemo/collections/audio/models/__init__.py index ac5316695a9e034a379e5ca6984215b3636f4ff2..28845859872c5c81fc48461b3c96d4734a7b7c5d 100644 --- a/nemo/collections/audio/models/__init__.py +++ b/nemo/collections/audio/models/__init__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -20,3 +20,12 @@ from nemo.collections.audio.models.enhancement import ( SchroedingerBridgeAudioToAudioModel, ScoreBasedGenerativeAudioToAudioModel, ) + +__all__ = [ + "AudioToAudioModel", + "EncMaskDecAudioToAudioModel", + "FlowMatchingAudioToAudioModel", + "PredictiveAudioToAudioModel", + "SchroedingerBridgeAudioToAudioModel", + "ScoreBasedGenerativeAudioToAudioModel", +] diff --git a/nemo/collections/audio/models/enhancement.py b/nemo/collections/audio/models/enhancement.py index 8e2206afcef1c804f657b831e1451eea2b12fde9..02c449a5b2b824ec57ae5662e5f8b0c999255a5e 100644 --- a/nemo/collections/audio/models/enhancement.py +++ b/nemo/collections/audio/models/enhancement.py @@ -643,11 +643,13 @@ class FlowMatchingAudioToAudioModel(AudioToAudioModel): # 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) + 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 @@ -703,6 +705,7 @@ class FlowMatchingAudioToAudioModel(AudioToAudioModel): @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, @@ -711,6 +714,51 @@ class FlowMatchingAudioToAudioModel(AudioToAudioModel): 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`. """ @@ -725,11 +773,15 @@ class FlowMatchingAudioToAudioModel(AudioToAudioModel): # 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 self.ssl_pretrain_masking is not None: + 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 @@ -796,9 +848,14 @@ class FlowMatchingAudioToAudioModel(AudioToAudioModel): # Estimate the vector using the neural estimator estimate, estimate_len = self.estimator(input=estimator_input, input_length=input_enc_len, condition=time) - conditional_vector_field = self.flow.vector_field(time=time, x_start=x_start, x_end=target_enc, point=sample) + 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=conditional_vector_field, input_length=input_enc_len) + return self.loss(estimate=estimate, target=loss_target, input_length=input_enc_len) # PTL-specific methods def training_step(self, batch, batch_idx): @@ -867,7 +924,7 @@ class FlowMatchingAudioToAudioModel(AudioToAudioModel): if update_metrics: # Generate output signal - output_signal, _ = self.forward( + output_signal, _ = self.forward_eval( input_signal=input_signal[:num_examples, ...], input_length=input_length[:num_examples] ) diff --git a/nemo/collections/vlm/peft/__init__.py b/nemo/collections/audio/models/maxine/__init__.py similarity index 78% rename from nemo/collections/vlm/peft/__init__.py rename to nemo/collections/audio/models/maxine/__init__.py index ab0c451a7d9d30ca3086c6e416dc321824ff23fe..125cc06253f029c98214fbe0dd6ed5ae73e62149 100644 --- a/nemo/collections/vlm/peft/__init__.py +++ b/nemo/collections/audio/models/maxine/__init__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -12,6 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. -from nemo.collections.vlm.peft.lora import LoRA +from nemo.collections.audio.models.maxine.bnr import BNR2 -__all__ = ["LoRA"] +__all__ = [ + 'BNR2', +] diff --git a/nemo/collections/audio/models/maxine/bnr.py b/nemo/collections/audio/models/maxine/bnr.py new file mode 100644 index 0000000000000000000000000000000000000000..6cff8ead9c87d0189b290eec19b1778f98beafba --- /dev/null +++ b/nemo/collections/audio/models/maxine/bnr.py @@ -0,0 +1,294 @@ +# 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 index d9155f923f186a086a69de138e984e2fab2817ec..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c 100644 --- a/nemo/collections/audio/modules/__init__.py +++ b/nemo/collections/audio/modules/__init__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. diff --git a/nemo/collections/audio/modules/features.py b/nemo/collections/audio/modules/features.py index ce6cedf0c533a91cc325cd2ea4e77fcf60356535..b20670850de5edca9c5a72434c337a01c7c9bcb2 100644 --- a/nemo/collections/audio/modules/features.py +++ b/nemo/collections/audio/modules/features.py @@ -231,6 +231,8 @@ class SpectrogramToMultichannelFeatures(NeuralModule): 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) @@ -250,23 +252,28 @@ class SpectrogramToMultichannelFeatures(NeuralModule): # 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: - # 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) + 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) diff --git a/nemo/collections/audio/modules/projections.py b/nemo/collections/audio/modules/projections.py index 9012432287dbd3577523f7f2d6984c49f18a9dd5..8dcc8a69d26a8c8d65329c0608029b6d8aec804d 100644 --- a/nemo/collections/audio/modules/projections.py +++ b/nemo/collections/audio/modules/projections.py @@ -67,6 +67,9 @@ class MixtureConsistencyProjection(NeuralModule): 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 diff --git a/nemo/collections/audio/modules/ssl_pretrain_masking.py b/nemo/collections/audio/modules/ssl_pretrain_masking.py index ba0722f180d84a7cd2b24afe91980acc74702f3d..66883b60df31c1650155010d63dbc67de24c1bc6 100644 --- a/nemo/collections/audio/modules/ssl_pretrain_masking.py +++ b/nemo/collections/audio/modules/ssl_pretrain_masking.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# 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. @@ -59,11 +59,14 @@ class SSLPretrainWithMaskedPatch(NeuralModule): mask_fraction: float = 0.7, ): super().__init__() - self.patch_size = patch_size + 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('mask_patches cannot be negative') - else: - self.mask_fraction = mask_fraction + 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): @@ -83,17 +86,20 @@ class SSLPretrainWithMaskedPatch(NeuralModule): """ augmented_spec = input_spec - min_len = torch.min(length) if self.training: - len_fraction = int(min_len * self.mask_fraction) - mask_patches = len_fraction // self.patch_size + int(len_fraction % self.patch_size != 0) - - if min_len < self.patch_size * mask_patches: - mask_patches = min_len // self.patch_size - 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: diff --git a/nemo/collections/audio/modules/transforms.py b/nemo/collections/audio/modules/transforms.py index cfa0c2c8ebb7416de6988f0032306eda0940ad1d..2970601f24e297cc82a4844063a2519db2fc23fc 100644 --- a/nemo/collections/audio/modules/transforms.py +++ b/nemo/collections/audio/modules/transforms.py @@ -21,15 +21,6 @@ from nemo.core.classes import NeuralModule, typecheck from nemo.core.neural_types import AudioSignal, LengthsType, NeuralType, SpectrogramType from nemo.utils import logging -try: - import torchaudio - import torchaudio.functional - import torchaudio.transforms - - HAVE_TORCHAUDIO = True -except ModuleNotFoundError: - HAVE_TORCHAUDIO = False - class AudioToSpectrogram(NeuralModule): """Transform a batch of input multi-channel signals into a batch of @@ -44,7 +35,9 @@ class AudioToSpectrogram(NeuralModule): scale: Positive scaling of the spectrogram. """ - def __init__(self, fft_length: int, hop_length: int, magnitude_power: float = 1.0, scale: float = 1.0): + 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 @@ -66,7 +59,7 @@ class AudioToSpectrogram(NeuralModule): 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) @@ -96,7 +89,7 @@ class AudioToSpectrogram(NeuralModule): hop_length=self.hop_length, win_length=self.win_length, window=self.window, - center=True, + center=self.center, pad_mode=self.pad_mode, normalized=False, onesided=True, @@ -182,127 +175,6 @@ class AudioToSpectrogram(NeuralModule): return output_length -class AudioToSpectrogramTA(NeuralModule): - """Transform a batch of input multi-channel signals into a batch of - STFT-based spectrograms. Using torchaudio. - - 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): - if not HAVE_TORCHAUDIO: - logging.error('Could not import torchaudio. Some features might not work.') - - raise ModuleNotFoundError( - f"torchaudio is not installed but is necessary to instantiate a {self.__class__.__name__}" - ) - - 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.stft = torchaudio.transforms.Spectrogram( - n_fft=fft_length, hop_length=hop_length, power=None, pad_mode='constant' - ) - - # number of subbands - 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 - - 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 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,) - """ - output_length = input_length.div(self.stft.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. @@ -312,9 +184,35 @@ class SpectrogramToAudio(NeuralModule): 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): + 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 @@ -331,7 +229,7 @@ class SpectrogramToAudio(NeuralModule): 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 @@ -342,6 +240,13 @@ class SpectrogramToAudio(NeuralModule): 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 @@ -355,9 +260,6 @@ class SpectrogramToAudio(NeuralModule): Returns: Time-domain signal ``x = iSTFT(x_spec)``, shape (..., T). """ - if not x_spec.is_complex(): - raise ValueError("Expected `x_spec` to be complex dtype.") - # pack batch B, C, F, N = x_spec.size() x_spec = rearrange(x_spec, 'B C F N -> (B C) F N') @@ -368,7 +270,7 @@ class SpectrogramToAudio(NeuralModule): hop_length=self.hop_length, win_length=self.win_length, window=self.window, - center=True, + center=self.center, normalized=False, onesided=True, length=None, @@ -401,18 +303,24 @@ class SpectrogramToAudio(NeuralModule): """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: - Time-domain signal with T time-domain samples and C channels, (B, C, T) - and output length with shape (B,). + - 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() @@ -424,6 +332,14 @@ class SpectrogramToAudio(NeuralModule): 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: @@ -453,120 +369,119 @@ class SpectrogramToAudio(NeuralModule): 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) -class SpectrogramToAudioTA(NeuralModule): - """Transform a batch of input multi-channel spectrograms into a batch of - time-domain multi-channel signals. Using torchaudio. + @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.") - 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. - """ + if self.center: + raise ValueError("Streaming iSTFT requires center=False.") - def __init__(self, fft_length: int, hop_length: int, magnitude_power: float = 1.0, scale: float = 1.0): - if not HAVE_TORCHAUDIO: - logging.error('Could not import torchaudio. Some features might not work.') + # Lazily initialize buffers + self._init_stream_buffers(input) - raise ModuleNotFoundError( - f"torchaudio is not installed but is necessary to instantiate a {self.__class__.__name__}" - ) + 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}" - super().__init__() + # 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) - # 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') + # 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) - self.istft = torchaudio.transforms.InverseSpectrogram( - n_fft=fft_length, hop_length=hop_length, pad_mode='constant' - ) + # 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) - self.num_subbands = fft_length // 2 + 1 + # Iterate over frames for OLA + for t in range(num_frames): + frame_t = frames_time_windowed[..., t] # (B, C, T) - if magnitude_power <= 0: - raise ValueError(f'Magnitude power needs to be positive: current value {magnitude_power}') - self.magnitude_power = magnitude_power + # Overlap-add accumulation and window-sum-square weights + self._ola_accum.add_(frame_t) + self._ola_weight.add_(win_sq) - if scale <= 0: - raise ValueError(f'Scale needs to be positive: current value {scale}') - self.scale = scale + # 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) - 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) + # Shift buffers left by hop_length + self._shift_left_inplace(self._ola_accum) + self._shift_left_inplace(self._ola_weight) - @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), - } + return torch.cat(emitted_parts, dim=-1) - @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. + @torch.no_grad() + def stream_finalize(self) -> torch.Tensor: + """Flush the remaining buffered samples (final tail for center=False). - 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: - Time-domain signal with T time-domain samples and C channels, (B, C, T) - and output length with shape (B,). + 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. """ - 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 self._stream_initialized: + return torch.tensor((), device=self.window.device) - # iSTFT output (B, C, T) - with torch.amp.autocast(input.device.type, enabled=False): - output = input.cfloat() + tail_len = self.win_length - self.hop_length + if tail_len <= 0: + return torch.tensor((), device=self.window.device) - 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()) - 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,) - """ - output_length = input_length.sub(1).mul(self.istft.hop_length).long() - return output_length + 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 index d9155f923f186a086a69de138e984e2fab2817ec..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c 100644 --- a/nemo/collections/audio/parts/__init__.py +++ b/nemo/collections/audio/parts/__init__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. diff --git a/nemo/collections/audio/parts/submodules/__init__.py b/nemo/collections/audio/parts/submodules/__init__.py index d9155f923f186a086a69de138e984e2fab2817ec..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c 100644 --- a/nemo/collections/audio/parts/submodules/__init__.py +++ b/nemo/collections/audio/parts/submodules/__init__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. diff --git a/nemo/collections/audio/parts/submodules/conformer.py b/nemo/collections/audio/parts/submodules/conformer.py index 07385aa4a76d219c87ab7b87db2139e48514e288..6f9ccae5daa03ca356479789b5f0e6f0147ee4eb 100644 --- a/nemo/collections/audio/parts/submodules/conformer.py +++ b/nemo/collections/audio/parts/submodules/conformer.py @@ -63,7 +63,7 @@ class SpectrogramConformer(NeuralModule): 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) + logging.debug('Conformer params: %s', conformer_params) self.conformer = ConformerEncoder(**conformer_params) # Output projection to generate real and imaginary components of the output channels diff --git a/nemo/collections/audio/parts/submodules/conformer_unet.py b/nemo/collections/audio/parts/submodules/conformer_unet.py new file mode 100644 index 0000000000000000000000000000000000000000..75573b2783930b176fe315a4caead78374abb332 --- /dev/null +++ b/nemo/collections/audio/parts/submodules/conformer_unet.py @@ -0,0 +1,418 @@ +# 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 index 2c9e08fc30fd1a347b11d366b0c69405176c477d..7a75943de686828b3df83abba442875c70a20982 100644 --- a/nemo/collections/audio/parts/submodules/diffusion.py +++ b/nemo/collections/audio/parts/submodules/diffusion.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# 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. diff --git a/nemo/collections/audio/parts/submodules/flow.py b/nemo/collections/audio/parts/submodules/flow.py index 56e77389b2e019bbac19f7c59376b47458b9a7ed..924bfd06667f815071a9ad26fa7c18eb3d270b99 100644 --- a/nemo/collections/audio/parts/submodules/flow.py +++ b/nemo/collections/audio/parts/submodules/flow.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# 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. @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. from abc import ABC, abstractmethod -from typing import Tuple +from typing import Literal, Tuple import einops import torch @@ -20,6 +20,8 @@ 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): """ @@ -71,11 +73,12 @@ class ConditionalFlow(ABC): return time - def generate_time(self, batch_size: int) -> torch.Tensor: + def generate_time(self, batch_size: int, rng: torch.random.Generator = None) -> torch.Tensor: """ - Randomly sample a batchsize of time_steps from U[0~1] + 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.clamp(torch.rand((batch_size,)), self.time_min, self.time_max) + 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: """ @@ -210,6 +213,8 @@ class ConditionalFlowMatchingEulerSampler(ConditionalFlowMatchingSampler): 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, @@ -217,10 +222,17 @@ class ConditionalFlowMatchingEulerSampler(ConditionalFlowMatchingSampler): 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) @@ -234,6 +246,7 @@ class ConditionalFlowMatchingEulerSampler(ConditionalFlowMatchingSampler): 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) @@ -242,9 +255,13 @@ class ConditionalFlowMatchingEulerSampler(ConditionalFlowMatchingSampler): else: estimator_input = torch.cat([state, estimator_condition], dim=1) - vector_field, _ = self.estimator(input=estimator_input, input_length=state_length, condition=time) - - state = state + vector_field * self.time_step + 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) diff --git a/nemo/collections/audio/parts/submodules/multichannel.py b/nemo/collections/audio/parts/submodules/multichannel.py index 9492c05b6aedab9bedc8e9ca49269defbd3e6137..407e9a3fe03db6ebc3ccaf525280cbdc761e0350 100644 --- a/nemo/collections/audio/parts/submodules/multichannel.py +++ b/nemo/collections/audio/parts/submodules/multichannel.py @@ -20,17 +20,11 @@ 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 -try: - import torchaudio - - HAVE_TORCHAUDIO = True -except ModuleNotFoundError: - HAVE_TORCHAUDIO = False - class ChannelAugment(NeuralModule): """Randomly permute and selects a subset of channels. @@ -414,13 +408,6 @@ class ParametricMultichannelWienerFilter(NeuralModule): diag_reg: Optional[float] = 1e-6, eps: float = 1e-8, ): - if not HAVE_TORCHAUDIO: - logging.error('Could not import torchaudio. Some features might not work.') - - raise ModuleNotFoundError( - f"torchaudio is not installed but is necessary to instantiate a {self.__class__.__name__}" - ) - super().__init__() # Parametric filter @@ -448,9 +435,6 @@ class ParametricMultichannelWienerFilter(NeuralModule): raise ValueError(f'Epsilon {eps} must be positive.') self.eps = eps - # PSD estimator - self.psd = torchaudio.transforms.PSD() - # Reference channel self.ref_channel = ref_channel if self.ref_channel == 'max_snr': @@ -597,15 +581,15 @@ class ParametricMultichannelWienerFilter(NeuralModule): """ iodtype = input.dtype - with torch.amp.autocast(self.device.type, enabled=False): + 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 = self.psd(input, mask_s) - psd_n = self.psd(input, mask_n) + 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] @@ -955,16 +939,12 @@ class WPEFilter(NeuralModule): `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} (1) - for each (b, f). - The matrix calculated in (1) has shape (C * filter_length, C * filter_length) + 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 (2) - for each (b, f). - The matrix calculated in (2) has shape (C * filter_length, C) + 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. """ @@ -986,8 +966,7 @@ class WPEFilter(NeuralModule): 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) + 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: diff --git a/nemo/collections/audio/parts/submodules/ncsnpp.py b/nemo/collections/audio/parts/submodules/ncsnpp.py index 543e29fc7847e0afddb6953b8b78bf11d96e80ff..01f36537af95610e1d4755411a4376fd44636364 100644 --- a/nemo/collections/audio/parts/submodules/ncsnpp.py +++ b/nemo/collections/audio/parts/submodules/ncsnpp.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# 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. diff --git a/nemo/collections/audio/parts/submodules/schroedinger_bridge.py b/nemo/collections/audio/parts/submodules/schroedinger_bridge.py index 07bfc2f880118a17ab4ed17681758e6a90adb3a0..77a971ed89231f22957108eec9d5b7aacafeb1f4 100644 --- a/nemo/collections/audio/parts/submodules/schroedinger_bridge.py +++ b/nemo/collections/audio/parts/submodules/schroedinger_bridge.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# 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. diff --git a/nemo/collections/audio/parts/submodules/transformerunet.py b/nemo/collections/audio/parts/submodules/transformerunet.py index b7c14d513bab09499e94b7e9f5f225deeaac88e9..89d8bcc275df0812e42eef4c5b0d6bb1b0d445f0 100644 --- a/nemo/collections/audio/parts/submodules/transformerunet.py +++ b/nemo/collections/audio/parts/submodules/transformerunet.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION & AFFILIATES. +# 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. @@ -224,7 +224,12 @@ class TransformerUNet(NeuralModule): self.layers = nn.ModuleList([]) self.init_alibi(max_positions=max_positions, heads=heads) - if adaptive_rmsnorm: + 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 @@ -399,6 +404,7 @@ class SpectrogramTransformerUNet(NeuralModule): 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 @@ -409,8 +415,8 @@ class SpectrogramTransformerUNet(NeuralModule): time_hidden_dim = dim * 4 self.proj_in = nn.Linear(dim_in, dim) - - self.sinu_pos_emb = nn.Sequential(LearnedSinusoidalPosEmb(dim), nn.Linear(dim, time_hidden_dim), nn.SiLU()) + 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 @@ -424,7 +430,7 @@ class SpectrogramTransformerUNet(NeuralModule): ff_dropout=ff_dropout, attn_dropout=attn_dropout, max_positions=max_positions, - adaptive_rmsnorm=True, + adaptive_rmsnorm=adaptive_rmsnorm, adaptive_rmsnorm_cond_dim_in=time_hidden_dim, use_unet_skip_connection=True, ) @@ -494,9 +500,9 @@ class SpectrogramTransformerUNet(NeuralModule): x = self.conv_embed(x, mask=key_padding_mask) + x if condition is None: - raise NotImplementedError - - time_emb = self.sinu_pos_emb(condition) + 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) diff --git a/nemo/collections/audio/parts/utils/__init__.py b/nemo/collections/audio/parts/utils/__init__.py index d9155f923f186a086a69de138e984e2fab2817ec..341a77c5bc66dee5d2ba0edf888f91e5bf225e3c 100644 --- a/nemo/collections/audio/parts/utils/__init__.py +++ b/nemo/collections/audio/parts/utils/__init__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. diff --git a/nemo/collections/audio/parts/utils/audio.py b/nemo/collections/audio/parts/utils/audio.py index 25ab66468c825019be1ab4693cedbd82f1530677..9019f3ee2945de38110ef09b1257b1d48ecb57cd 100644 --- a/nemo/collections/audio/parts/utils/audio.py +++ b/nemo/collections/audio/parts/utils/audio.py @@ -19,11 +19,10 @@ import librosa import numpy as np import numpy.typing as npt import scipy -import soundfile as sf import torch +from einops import rearrange, reduce from scipy.spatial.distance import pdist, squareform - SOUND_VELOCITY = 343.0 # m/s @@ -517,3 +516,60 @@ def toeplitz(x: torch.Tensor) -> torch.Tensor: 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 index ff975c93ecc73e3f7c6a062834c32f9b03f007df..b78cc30445787bd2d833cee73b203ceb42b6a1dc 100644 --- a/nemo/collections/audio/parts/utils/callbacks.py +++ b/nemo/collections/audio/parts/utils/callbacks.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# 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. diff --git a/nemo/collections/audio/parts/utils/maxine.py b/nemo/collections/audio/parts/utils/maxine.py new file mode 100644 index 0000000000000000000000000000000000000000..01f0daa5cb5bb8d13e22750ac02809cadb5e11fa --- /dev/null +++ b/nemo/collections/audio/parts/utils/maxine.py @@ -0,0 +1,35 @@ +# 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 new file mode 100644 index 0000000000000000000000000000000000000000..6f7f914799044d031781c4b9e50cb45a8cc731ad --- /dev/null +++ b/nemo/collections/audio/parts/utils/transforms.py @@ -0,0 +1,1105 @@ +# 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/callbacks/ema.py b/nemo/collections/common/callbacks/ema.py index 39afe7bf2445ff1be9c0f9f74be2fa835f8e0cce..dee125be54ef16f8588ba0e4c17b4e2258d6e64f 100644 --- a/nemo/collections/common/callbacks/ema.py +++ b/nemo/collections/common/callbacks/ema.py @@ -135,7 +135,7 @@ class EMA(Callback): 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'), weights_only=False) + ema_state_dict = torch.load(ema_path, map_location=torch.device('cpu')) checkpoint['optimizer_states'] = ema_state_dict['optimizer_states'] del ema_state_dict diff --git a/nemo/collections/common/callbacks/ipl_epoch_stopper.py b/nemo/collections/common/callbacks/ipl_epoch_stopper.py new file mode 100644 index 0000000000000000000000000000000000000000..63d5831f292fd70be7ab0f32b0891663bd3726d1 --- /dev/null +++ b/nemo/collections/common/callbacks/ipl_epoch_stopper.py @@ -0,0 +1,55 @@ +# 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/nlp/data/language_modeling/megatron/Makefile b/nemo/collections/common/data/Makefile similarity index 92% rename from nemo/collections/nlp/data/language_modeling/megatron/Makefile rename to nemo/collections/common/data/Makefile index 150939026443cbb832123fefd44a2e16b44042e4..2e05c5b49fb9a43557ac557344b6e60badf95d36 100644 --- a/nemo/collections/nlp/data/language_modeling/megatron/Makefile +++ b/nemo/collections/common/data/Makefile @@ -1,4 +1,4 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# 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. diff --git a/nemo/collections/nlp/data/language_modeling/megatron/blendable_dataset.py b/nemo/collections/common/data/blendable_dataset.py similarity index 76% rename from nemo/collections/nlp/data/language_modeling/megatron/blendable_dataset.py rename to nemo/collections/common/data/blendable_dataset.py index 39b64ae8986574ef9980879a818e0db0778cf817..ad634a4f96b37e79e0b1cc90d3166263aff9cc81 100644 --- a/nemo/collections/nlp/data/language_modeling/megatron/blendable_dataset.py +++ b/nemo/collections/common/data/blendable_dataset.py @@ -1,4 +1,4 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -14,6 +14,8 @@ """Blendable dataset.""" +import os +import subprocess import time import numpy as np @@ -24,6 +26,8 @@ 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) @@ -44,17 +48,30 @@ class BlendableDataset(torch.utils.data.Dataset): 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: - if app_state.local_rank == 0: - from nemo.collections.nlp.data.language_modeling.megatron.dataset_utils import compile_helper + # 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() - torch.distributed.barrier() - from nemo.collections.nlp.data.language_modeling.megatron import helpers - except ImportError: + + if is_dist: + torch.distributed.barrier() + + # pylint: disable=import-outside-toplevel + from nemo.collections.common.data import helpers + except ImportError as exc: raise ImportError( - f'Could not compile megatron dataset C++ helper functions and therefore cannot import helpers python file.' - ) + '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, @@ -62,11 +79,9 @@ class BlendableDataset(torch.utils.data.Dataset): weights, num_datasets, self.size, - torch.distributed.get_rank() == 0, - ) - logging.info( - '> elapsed time for building blendable dataset indices: ' '{:.2f} (sec)'.format(time.time() - start_time) + 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 @@ -84,6 +99,7 @@ class BlendableDataset(torch.utils.data.Dataset): return self.datasets[dataset_idx][sample_idx] def create_data_mmap(self): + """ """ for dataset in self.datasets: dataset.create_data_mmap() @@ -127,9 +143,11 @@ class MemoryEfficientBlendableDataset(torch.utils.data.Dataset): 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(), f"Some datasets have no samples in the blendable dataset, increase weight_bins or the offending weight. ds_index_size = {self.ds_index_size}" + 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) @@ -162,6 +180,8 @@ class MemoryEfficientBlendableDataset(torch.utils.data.Dataset): plt.ion() class DS(torch.utils.data.Dataset): + """ """ + def __init__(self, size, data): self.size = size self.data = data @@ -187,3 +207,16 @@ class MemoryEfficientBlendableDataset(torch.utils.data.Dataset): 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/nlp/data/language_modeling/megatron/megatron_batch_samplers.py b/nemo/collections/common/data/data_samplers.py similarity index 54% rename from nemo/collections/nlp/data/language_modeling/megatron/megatron_batch_samplers.py rename to nemo/collections/common/data/data_samplers.py index 31d8eb1afd0c8e3fde41f9073b774a811f019f1c..99b612fdff451b6078c80d269e8ccc840d1b3589 100644 --- a/nemo/collections/nlp/data/language_modeling/megatron/megatron_batch_samplers.py +++ b/nemo/collections/common/data/data_samplers.py @@ -1,4 +1,4 @@ -# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -11,12 +11,17 @@ # WITHOUT 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 typing import Tuple +from itertools import chain +from typing import Optional, Tuple import torch +from nemo.utils import logging from nemo.utils.decorators import experimental __all__ = [ @@ -25,6 +30,210 @@ __all__ = [ ] +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. @@ -112,10 +321,12 @@ class BaseMegatronBatchSampler: @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) @@ -137,7 +348,10 @@ class BaseMegatronBatchSampler: 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 @@ -145,7 +359,7 @@ class MegatronPretrainingBatchSampler(BaseMegatronBatchSampler): 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): + 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() @@ -174,6 +388,7 @@ class MegatronPretrainingBatchSampler(BaseMegatronBatchSampler): @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 @@ -213,8 +428,9 @@ class MegatronPretrainingRandomBatchSampler(BaseMegatronBatchSampler): ), "`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" + "`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 diff --git a/nemo/collections/common/data/fallback.py b/nemo/collections/common/data/fallback.py new file mode 100644 index 0000000000000000000000000000000000000000..6a0aa9f2921fc760d1460ec562acbda93f9856c9 --- /dev/null +++ b/nemo/collections/common/data/fallback.py @@ -0,0 +1,51 @@ +# 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/nlp/data/language_modeling/megatron/helpers.cpp b/nemo/collections/common/data/helpers.cpp similarity index 99% rename from nemo/collections/nlp/data/language_modeling/megatron/helpers.cpp rename to nemo/collections/common/data/helpers.cpp index 4a65b313c816f53787a713da0762d44119e31937..1777e951a2e135432868077821ad43166400321f 100644 --- a/nemo/collections/nlp/data/language_modeling/megatron/helpers.cpp +++ b/nemo/collections/common/data/helpers.cpp @@ -1,5 +1,5 @@ /* -Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +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. diff --git a/nemo/collections/common/data/lhotse/__init__.py b/nemo/collections/common/data/lhotse/__init__.py index 95f0d01db297a252163418c1b1c038bc13b32e98..64465e88e398946b716508886993ff0e13ebb1d2 100644 --- a/nemo/collections/common/data/lhotse/__init__.py +++ b/nemo/collections/common/data/lhotse/__init__.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -12,6 +12,10 @@ # 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, diff --git a/nemo/collections/common/data/lhotse/cutset.py b/nemo/collections/common/data/lhotse/cutset.py index d33adb37a28769ea324b0b67db26e657f1f8ad5c..d4e7ec482921d37e7965e3a870741c78cb3bca5f 100644 --- a/nemo/collections/common/data/lhotse/cutset.py +++ b/nemo/collections/common/data/lhotse/cutset.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -11,34 +11,118 @@ # WITHOUT 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, Mapping, Sequence, Tuple, Union +from typing import KeysView, List, Mapping, Sequence, Tuple, Union +import numpy as np import omegaconf -from lhotse import CutSet, Features, Recording +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. @@ -48,16 +132,19 @@ def read_cutset_from_config(config: Union[DictConfig, dict]) -> Tuple[CutSet, bo # 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: - return read_dataset_config(config) - # 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) + cuts, is_tarred = read_dataset_config(config) else: - cuts, is_tarred = read_lhotse_manifest(config) + # 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 @@ -191,14 +278,19 @@ def read_dataset_config(config) -> tuple[CutSet, bool]: "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), } - input_cfg = config.input_cfg - if isinstance(input_cfg, (str, Path)): - # Resolve /path/to/input_cfg.yaml into config contents if needed. - input_cfg = OmegaConf.load(input_cfg) - cuts, is_tarred = parse_and_combine_datasets(input_cfg, propagate_attrs=propagate_attrs) + + 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 @@ -225,7 +317,9 @@ def parse_group(grp_cfg: DictConfig, propagate_attrs: dict) -> [CutSet, bool]: @data_type_parser("txt") def read_txt_paths(config: DictConfig) -> tuple[CutSet, bool]: - """Read paths to text files and create a CutSet.""" + """ + Read paths to text files and create a CutSet. + """ cuts = CutSet( LhotseTextAdapter( paths=config.paths, @@ -235,7 +329,28 @@ def read_txt_paths(config: DictConfig) -> tuple[CutSet, bool]: ) ) if not config.get("force_finite", False): - cuts = cuts.repeat() + 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 @@ -255,7 +370,7 @@ def read_txt_pair_paths(config: DictConfig) -> tuple[CutSet, bool]: ) ) if not config.get("force_finite", False): - cuts = cuts.repeat() + cuts = cuts.repeat(preserve_id=True) return cuts, True @@ -271,7 +386,7 @@ def read_nemo_sft_jsonl(config: DictConfig) -> tuple[CutSet, bool]: ) ) if not config.get("force_finite", False): - cuts = cuts.repeat() + cuts = cuts.repeat(preserve_id=True) return cuts, True @@ -286,6 +401,9 @@ def read_multimodal_conversation_jsonl(config: DictConfig) -> tuple[CutSet, bool 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): @@ -293,6 +411,54 @@ def read_multimodal_conversation_jsonl(config: DictConfig) -> tuple[CutSet, bool 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(): @@ -300,18 +466,74 @@ def attach_tags(cut, tags: dict): 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], propagate_attrs: dict + 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. @@ -330,14 +552,33 @@ def parse_and_combine_datasets( if (w := item.get("weight")) is not None: weights.append(w) - assert all(t == tarred_status[0] for t in tarred_status), "Mixing tarred and non-tarred datasets is not supported." + 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=weights if weights else None, + 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"], @@ -366,32 +607,33 @@ def read_lhotse_manifest(config) -> tuple[CutSet, bool]: # 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.shard_seed - metadata_only = config.metadata_only - force_finite = config.force_finite + 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)): - logging.info(f"Initializing Lhotse Shar CutSet (tarred) from a single data source: '{config.shar_path}'") cuts = CutSet.from_shar( - **_resolve_shar_inputs(config.shar_path, metadata_only), shuffle_shards=True, seed=shard_seed + **_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() + 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 - logging.info( - "Initializing Lhotse Shar CutSet (tarred) from multiple data sources with a weighted multiplexer. " - "We found the following sources and weights: " - ) 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 + **_resolve_shar_inputs(path, metadata_only), + shuffle_shards=True, + seed=shard_seed, + slice_length=config.get("slice_length", None), ) weight = len(cs) else: @@ -403,16 +645,19 @@ def read_lhotse_manifest(config) -> tuple[CutSet, bool]: ) path, weight = item cs = CutSet.from_shar( - **_resolve_shar_inputs(path, metadata_only), shuffle_shards=True, seed=shard_seed + **_resolve_shar_inputs(path, metadata_only), + shuffle_shards=True, + seed=shard_seed, + slice_length=config.get("slice_length", None), ) - logging.info(f"- {path=} {weight=}") cutsets.append(cs) weights.append(weight) + cuts = mux( *cutsets, weights=weights, - max_open_streams=config.max_open_streams, - seed=config.shard_seed, + max_open_streams=config.get("max_open_streams", None), + seed=shard_seed, force_finite=force_finite, ) elif isinstance(config.shar_path, Mapping): @@ -423,9 +668,14 @@ def read_lhotse_manifest(config) -> tuple[CutSet, bool]: ) if metadata_only: fields = {"cuts": fields["cuts"]} - cuts = CutSet.from_shar(fields=fields, shuffle_shards=True, seed=shard_seed) + 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() + cuts = cuts.repeat(preserve_id=True) else: raise RuntimeError( f"Unexpected value for key 'shar_path'. We support string, list of strings, " @@ -439,11 +689,587 @@ def read_lhotse_manifest(config) -> tuple[CutSet, bool]: return cuts, is_tarred -def _resolve_shar_inputs(path: Union[str, Path], only_metadata: bool) -> dict: - if only_metadata: - return dict(fields={"cuts": sorted(Path(path).glob("cuts.*"))}) +@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: - return dict(in_dir=path) + # 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: @@ -498,36 +1324,36 @@ def resolve_relative_paths(cut: Cut, manifest_path: str) -> 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 = { - "text_field": config.text_field, - "lang_field": config.lang_field, - "shuffle_shards": config.shuffle, - "shard_seed": config.shard_seed, - "extra_fields": config.get("extra_fields", None), - } + 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. - notar_kwargs = {"metadata_only": config.metadata_only} - metadata_only = config.metadata_only - force_finite = config.force_finite + 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)): - logging.info(f"Initializing Lhotse CutSet from a single NeMo manifest (tarred): '{config.manifest_filepath}'") if is_tarred and not metadata_only: cuts = CutSet( LazyNeMoTarredIterator( config.manifest_filepath, tar_paths=config.tarred_audio_filepaths, - skip_missing_manifest_entries=config.skip_missing_manifest_entries, + 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() + cuts = cuts.repeat(preserve_id=True) else: cuts = CutSet(LazyNeMoIterator(config.manifest_filepath, **notar_kwargs, **common_kwargs)) else: @@ -544,27 +1370,25 @@ def read_nemo_manifest(config) -> tuple[CutSet, bool]: # Format option 3: # i.e., NeMo concatenated dataset # Assume it's [path1, path2, ...] (while tarred_audio_filepaths in the same format). - logging.info( - "Initializing Lhotse CutSet from multiple tarred NeMo manifest sources with a weighted multiplexer. " - "We found the following sources and weights: " - ) 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 isinstance(tar_path, (list, tuple, ListConfig)): + 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.skip_missing_manifest_entries, + skip_missing_manifest_entries=config.get("skip_missing_manifest_entries", False), + slice_length=config.get("slice_length", None), **common_kwargs, ) else: @@ -584,29 +1408,49 @@ def read_nemo_manifest(config) -> tuple[CutSet, bool]: f"We got: '{manifest_info}'" ) weight = manifest_info[1] - logging.info(f"- {manifest_path=} {weight=}") # [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.max_open_streams is not None: + 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) - # Finally, we multiplex the dataset streams to mix the data. cuts = mux( *cutsets, weights=weights, - max_open_streams=config.max_open_streams, - seed=config.shard_seed, + 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]], @@ -624,8 +1468,12 @@ def mux( cuts = CutSet.infinite_mux(*cutsets, weights=weights, seed=seed, max_open_streams=max_open_streams) else: if not force_finite: - cutsets = [cs.repeat() for cs in cutsets] - cuts = CutSet.mux(*cutsets, weights=weights, seed=seed) + 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 @@ -665,3 +1513,124 @@ def guess_parse_cutset(inp: Union[str, dict, omegaconf.DictConfig]) -> CutSet: 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 index bbe6e0d9dd35dcb3eea74a5f648bed221a654039..f7838aa35d625a977b8632deb4e2658180cc1daa 100644 --- a/nemo/collections/common/data/lhotse/dataloader.py +++ b/nemo/collections/common/data/lhotse/dataloader.py @@ -1,4 +1,4 @@ -# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# 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. @@ -14,19 +14,24 @@ import os import random import warnings +from copy import deepcopy from dataclasses import dataclass from functools import partial -from typing import Any, Optional, Sequence, Union +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, @@ -45,6 +50,8 @@ from nemo.collections.common.data.lhotse.cutset import ( ) from nemo.collections.common.data.lhotse.sampling import ( BucketingFilter, + CERFilter, + ContextSpeakerSimilarityFilter, DurationFilter, FixedBucketBatchSizeConstraint2D, MultimodalFixedBucketBatchSizeConstraint2D, @@ -52,6 +59,7 @@ from nemo.collections.common.data.lhotse.sampling import ( TokenCountFilter, TokenPerSecondFilter, TokenPerTokenFilter, + ValidationStatusFilter, ) from nemo.collections.common.data.prompt_fn import apply_prompt_format_fn from nemo.collections.common.prompts import PromptFormatter @@ -100,6 +108,10 @@ class LhotseDataLoadingConfig: 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. @@ -111,9 +123,13 @@ class LhotseDataLoadingConfig: 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 @@ -130,6 +146,13 @@ class LhotseDataLoadingConfig: 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 @@ -175,6 +198,27 @@ class LhotseDataLoadingConfig: # 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 @@ -202,6 +246,14 @@ class LhotseDataLoadingConfig: # * 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: @@ -221,7 +273,7 @@ def get_lhotse_dataloader_from_config( tokenizer=None, ) -> torch.utils.data.DataLoader: """ - Set up a Lhotse training dataloder. + 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. @@ -267,7 +319,7 @@ def get_lhotse_dataloader_from_single_config( tokenizer=None, ) -> torch.utils.data.DataLoader: """ - Set up a Lhotse training dataloder. + 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. @@ -457,13 +509,15 @@ def get_lhotse_sampler_from_config(config, global_rank, world_size, tokenizer=No 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.resample(config.sample_rate) + 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))) @@ -484,6 +538,20 @@ def get_lhotse_sampler_from_config(config, global_rank, world_size, tokenizer=No "(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 @@ -492,13 +560,13 @@ def get_lhotse_sampler_from_config(config, global_rank, world_size, tokenizer=No if not isinstance(tokenizer, TokenizerWrapper): tokenizer = TokenizerWrapper(tokenizer) cuts = cuts.map(partial(tokenize, tokenizer=tokenizer), apply_fn=None) - cuts = cuts.filter(TokenPerSecondFilter(config.min_tps, config.max_tps)) - cuts = cuts.filter(TokenPerTokenFilter(config.min_tpt, config.max_tpt)) # 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), @@ -542,6 +610,17 @@ def get_lhotse_sampler_from_config(config, global_rank, world_size, tokenizer=No 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) @@ -611,6 +690,31 @@ def get_lhotse_sampler_from_config(config, global_rank, world_size, tokenizer=No 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( @@ -620,6 +724,22 @@ def get_lhotse_sampler_from_config(config, global_rank, world_size, tokenizer=No ) ) + 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 @@ -646,6 +766,7 @@ def determine_sampling_constraint(cuts: CutSet, bucket_duration_bins, config) -> 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: @@ -654,6 +775,7 @@ def determine_sampling_constraint(cuts: CutSet, bucket_duration_bins, config) -> 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: @@ -676,6 +798,35 @@ def determine_sampling_constraint(cuts: CutSet, bucket_duration_bins, config) -> 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. @@ -834,6 +985,20 @@ def maybe_set_cuda_expandable_segments(enabled: bool): ) +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 @@ -854,3 +1019,28 @@ def _select_channel(cut, channel_selector: int | str) -> list: 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 new file mode 100644 index 0000000000000000000000000000000000000000..831edf0b1f542cd9d9c8a8c7f9dddcf3b12ca931 --- /dev/null +++ b/nemo/collections/common/data/lhotse/indexed_adapters.py @@ -0,0 +1,319 @@ +# 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.