NVIDIA-NeMo/Speech · #16656
Add planned long-form chunking to ASR transcription
docs/source/asr/inference.rst58 + / 1 −
@@ -201,17 +201,74 @@ For decoding customization (confidence, CUDA graphs, language models, word boost print(f"{start:0.2f} - {end:0.2f} : {word}") +.. _asr-long-audio-inference:+ Long Audio Inference -------------------- For audio longer than what fits in memory (especially with Conformer's quadratic attention): +**Planned chunking (recommended):**++.. code-block:: python++ from nemo.collections.asr.parts.mixins.transcription import ChunkingConfig++ outputs = model.transcribe(+ ["recording.wav"],+ batch_size=4,+ timestamps=True, # optional+ chunking=ChunkingConfig(chunk_size=30.0, context_size=2.0),+ )+ print(outputs[0].text)++From the command line:++.. code-block:: bash++ python examples/asr/transcribe_speech.py \+ pretrained_name=nvidia/parakeet-tdt-0.6b-v2 \+ audio_dir=/path/to/audio \+ '+chunking={chunk_size:30.0,context_size:2.0}'++Each recording is split into chunks of ``chunk_size`` seconds. Each chunk is transcribed with+``context_size`` seconds of extra audio on each side; the context improves recognition near+chunk edges, and its output is kept from one chunk only, so joins are not duplicated. Encoder+memory depends on the chunk duration plus context and on the batch size, not on the recording+length. CTC models keep each recording's owned output frames on the CPU until the recording is+complete: frame labels by default, and full log probabilities when hypotheses, alignments,+confidence or a fusion model are requested, so that storage grows with the recording length.+The defaults (30 s and 2 s) suit Parakeet and Canary models.++Planned chunking works with CTC, RNNT/TDT, hybrid and AED (Canary) models, and accepts files,+manifests and waveforms at the model's sample rate. It is off unless ``chunking`` is set. With+``override_config`` or ``transcribe_generator``, set ``config.chunking`` instead; as with the+other arguments, ``override_config`` takes precedence over ``chunking=``.++Limitations:++* CTC results keep the usual CTC hypothesis fields, including confidence and alignments.+ RNNT/TDT and AED results contain text and word/segment timestamps; token confidence,+ alignments and AED cross-attention scores are not returned.+* AED models transcribe only (no speech translation). Their timestamps require a CTC timestamp+ model, as in ``canary-1b-v2``.+* One best hypothesis per chunk. CTC supports ``greedy`` and ``greedy_batch`` without an n-gram LM.+* These raise an error: RNNT/TDT models with an aggregate tokenizer, or with a character+ vocabulary and TDT durations; ``decoding.restart_after_tokens``; augmentations; partial+ hypotheses; external DataLoaders.+* The encoder sees one chunk at a time, so results can differ from whole-recording inference.++**Which method to use:** planned chunking for every model type. Local attention (below) is an+alternative for Fast Conformer models; it keeps one encoder pass over the whole recording, so+memory still grows with its length. Buffered inference scripts (below) are a streaming-style+alternative.+ **Buffered / chunked inference:** Divide audio into overlapping chunks and merge outputs. Scripts are in `examples/asr/asr_chunked_inference <https://github.com/NVIDIA-NeMo/Speech/tree/main/examples/asr/asr_chunked_inference>`_. -**Local attention (recommended for Fast Conformer):**+**Local attention (alternative for Fast Conformer):** Switch to Longformer-style local+global attention for linear-cost inference on audio >1 hour: docs/source/asr/intro.rst1 + / 1 −
@@ -51,7 +51,7 @@ Key Features **Multitalker** — Streaming multi-speaker ASR with speaker kernel injection handles overlapping speech in real time. See `Multitalker Parakeet <https://huggingface.co/nvidia/multitalker-parakeet-streaming-0.6b-v1>`__. -**Long Audio** — Inference on audio over 1 hour via local attention or buffered chunked processing.+**Long Audio** — Inference on audio over 1 hour via planned chunking (recommended), local attention, or buffered chunked processing. **Decoder Types** — NeMo supports CTC, RNN-T, TDT, AED, and Hybrid decoders. For a comparison of decoder types, see :ref:`asr_language_modeling_and_customization`. docs/source/asr/results.rst7 + / 3 −
@@ -135,12 +135,16 @@ Inference on long audio In some cases the audio is too long for standard inference, especially if you're using a model such as Conformer, where the time and memory costs of the attention layers scale quadratically with the duration. -There are two main ways of performing inference on long audio files in NeMo:+The recommended way is planned chunking: pass ``chunking=ChunkingConfig(chunk_size=30.0, context_size=2.0)`` to+``transcribe()``. It works for CTC, RNNT/TDT, hybrid, and AED models and bounds encoder memory independent of the+recording length. See :ref:`asr-long-audio-inference`. -The first way is to use buffered inference, where the audio is divided into chunks to run on, and the output is merged afterwards.+There are two alternatives:++The first alternative is to use buffered inference, where the audio is divided into chunks to run on, and the output is merged afterwards. The relevant scripts for this are contained in `this folder <https://github.com/NVIDIA-NeMo/Speech/blob/stable/examples/asr/asr_chunked_inference>`_. -The second way, specifically for models with the Conformer/Fast Conformer encoder, is to use local attention, which changes the costs to be linear.+The second alternative, specifically for models with the Conformer/Fast Conformer encoder, is to use local attention, which changes the costs to be linear. You can train Fast Conformer models with Longformer-style (https://arxiv.org/abs/2004.05150) local+global attention using one of the following configs: CTC config at ``<NeMo_git_root>/examples/asr/conf/fastconformer/fast-conformer-long_ctc_bpe.yaml`` and transducer config at ``<NeMo_git_root>/examples/asr/conf/fastconformer/fast-conformer-long_transducer_bpe.yaml``. You can also convert any model trained with full context attention to local, though this may result in lower WER in some cases. You can switch to local attention when running theexamples/asr/transcribe_speech.py3 + / 0 −
@@ -142,6 +142,7 @@ class TranscriptionConfig: # Set to True to output greedy timestamp information (only supported models) and returns full alignment hypotheses timestamps: Optional[bool] = None+ chunking: dict[str, float] = field(default_factory=dict) # empty disables; owned duration/context in seconds # Set to True to return hypotheses instead of text from the transcribe function return_hypotheses: bool = False@@ -425,6 +426,8 @@ def main(cfg: TranscriptionConfig) -> Union[TranscriptionConfig, List[Hypothesis override_cfg.text_field = cfg.gt_text_attr_name override_cfg.lang_field = cfg.gt_lang_attr_name override_cfg.timestamps = cfg.timestamps+ if cfg.chunking:+ override_cfg.chunking = cfg.chunking if hasattr(override_cfg, "prompt"): override_cfg.prompt = parse_multitask_prompt(OmegaConf.to_container(cfg.prompt)) # Prompt-conditioned RNNT models: forward the language-ID prompt. None is forwarded too,nemo/collections/asr/models/aed_multitask_models.py124 + / 3 −
@@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import copy import os import warnings from collections.abc import Mapping, Sequence@@ -42,10 +43,18 @@ 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.longform_inference import (+ ChunkingConfig,+ select_chunk_words,+ stitch_chunk_words,+ transfer_word_times,+ words_to_hypothesis,+) 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,+ process_timestamp_outputs, ) from nemo.collections.common import tokenizers from nemo.collections.common.data.lhotse.dataloader import get_lhotse_dataloader_from_config@@ -501,6 +510,7 @@ def transcribe( verbose: bool = True, timestamps: Optional[bool] = None, override_config: Optional[MultiTaskTranscriptionConfig] = None,+ chunking: Optional[ChunkingConfig] = None, **prompt, ) -> Union[List[str], List[Hypothesis]]: """@@ -529,6 +539,7 @@ def transcribe( verbose: (bool) whether to display tqdm progress bar override_config: (Optional[MultiTaskTranscriptionConfig]) A config to override the default config.+ chunking: Optional offline chunk plan for ASR output. Timestamps require a CTC timestamp model. **prompt: Optional input to construct the prompts for the model. Accepted formats are: 1) legacy Canary-1B API source_lang=<lang>, target_lang=<lang>, etc. 2) explicit single-turn role=<role>, slots={<slot>: <value>, ...}@@ -566,6 +577,7 @@ def transcribe( verbose=verbose, prompt=prompt, timestamps=timestamps,+ chunking=chunking, ) else: if not isinstance(override_config, MultiTaskTranscriptionConfig):@@ -574,7 +586,16 @@ def transcribe( f"but got {type(override_config)}" ) trcfg = override_config- trcfg.timestamps = timestamps+ if trcfg.chunking is None:+ trcfg.timestamps = timestamps++ if trcfg.chunking is not None:+ # Keep the released Canary chunker separate from planned offline chunking.+ trcfg = copy.deepcopy(trcfg)+ trcfg.enable_chunking = False+ # The prompt carries the timestamp slot ('no' for text only); the output request is a boolean.+ trcfg.timestamps = _requests_timestamps(trcfg.timestamps)+ return super().transcribe(audio=audio, override_config=trcfg) if trcfg.enable_chunking: # Check if only one audio is provided with string@@ -913,6 +934,94 @@ def test_dataloader(self): """ Transcription methods """ + def _transcribe_chunk_validate(self, trcfg):+ if trcfg.timestamps and self.timestamps_asr_model is None:+ raise ValueError('Planned AED chunking returns timestamps only for models with a CTC timestamp model.')+ if self.decoding.cfg.get('return_xattn_scores', False):+ raise ValueError('Planned AED chunking does not return cross-attention scores.')+ cfg = self.decoding.cfg+ n_best = cfg.strategy == 'beam' and not cfg.beam.get('return_best_hypothesis', True)+ # Greedy decoding samples several outputs when a temperature is set and n_samples > 1.+ sampling = (+ cfg.strategy in ('greedy', 'greedy_batch') and (cfg.get('greedy') or {}).get('temperature') is not None+ )+ if n_best or (sampling and cfg.greedy.get('n_samples', 1) > 1):+ raise ValueError('Planned AED chunking requires one best hypothesis per chunk.')++ def _transcribe_chunk_batch(self, audio, lengths, cuts, trcfg):+ # A None prompt makes the forward pass build the prompt from trcfg, as for tensor input.+ prompts = None+ if all(cut is not None for cut in cuts):+ from lhotse.dataset.collation import collate_vectors++ from nemo.collections.common.data import apply_prompt_format_fn++ prompts = [apply_prompt_format_fn(cut, self.prompt)['context_ids'] for cut in cuts]+ prompts = collate_vectors([torch.as_tensor(p) for p in prompts], padding_value=self.tokenizer.pad_id)+ prompts = prompts.to(audio.device)+ return audio, lengths, None, None, prompts, cuts++ def _transcribe_chunk_outputs(self, outputs, chunks, frame_samples, trcfg):+ audio, lengths, _, _, _, cuts = outputs['batch']+ # The normal AED path owns prompt construction and decoding; its text needs no alignment.+ text_config = copy.deepcopy(trcfg)+ text_config.timestamps = False+ text_config.enable_chunking = False+ hypotheses = self._transcribe_output_processing(outputs, text_config)+ # Greedy CTC words time each read window. Unlike forced alignment, they exist for any speech rate.+ timed = None if self.timestamps_asr_model is None else self._transcribe_chunk_ctc_words(audio, lengths)+ sample_rate = int(self.cfg.sample_rate)+ parts = []++ def plain(slots): # Unset slots keep their defaults; '<|de|>' and 'de' name the same language.+ return {k: v.strip('<|>') if isinstance(v, str) else v for k, v in slots.items() if v is not None}++ default_slots = {}+ for turn in self.prompt.get_default_dialog_slots() + (trcfg.prompt or []):+ if turn['role'] == 'user':+ default_slots.update(plain(turn['slots']))+ for i, (hyp, chunk, cut) in enumerate(zip(hypotheses, chunks, cuts)):+ slots = dict(default_slots)+ if cut is not None:+ slots.update(plain(cut.custom or {}))+ source_lang = slots.get('source_lang')+ target_lang = slots.get('target_lang', source_lang)+ task = slots.get('task', slots.get('taskname', 'asr'))+ if source_lang != target_lang or task not in ('asr', 'transcribe'):+ raise ValueError('Time-selected AED chunks support transcription, not speech translation.')+ words = hyp.text.split()+ if timed is not None:+ duration = (chunk.read_end - chunk.read_start) / sample_rate+ words = select_chunk_words(transfer_word_times(words, timed[i], duration), chunk, sample_rate)+ parts.append((words, target_lang))+ return parts++ def _transcribe_chunk_ctc_words(self, audio, lengths):+ """Greedy words of the CTC timestamp model for each read window, in seconds from its start."""+ ctc = self.timestamps_asr_model+ log_probs, encoded_len = ctc.forward(input_signal=audio, input_signal_length=lengths)[:2]+ decoding = copy.copy(ctc.decoding)+ decoding.decoding = copy.copy(decoding.decoding)+ decoding.compute_timestamps = decoding.decoding.compute_timestamps = True+ hyps = decoding.ctc_decoder_predictions_tensor(log_probs, encoded_len, return_hypotheses=True)+ hyps = process_timestamp_outputs(hyps, ctc.encoder.subsampling_factor, ctc.cfg.preprocessor.window_stride)+ return [hyp.timestamp['word'] for hyp in hyps]++ def _transcribe_chunk_finalize(self, parts, chunks, frame_samples, trcfg):+ if self.timestamps_asr_model is None:+ stitched = stitch_chunk_words([selected for selected, _ in parts], chunks, int(self.cfg.sample_rate))+ words = [{'word': word} for word in stitched]+ else:+ words = [word for selected, _ in parts for word in selected]+ text_to_ids = self.tokenizer.text_to_ids+ if isinstance(self.tokenizer, tokenizers.AggregateTokenizer):+ language = parts[0][1]+ if language is None:+ raise ValueError('Set target_lang for planned chunking with an AggregateTokenizer.')+ text_to_ids = lambda text: self.tokenizer.text_to_ids(text, lang_id=language)+ frame_seconds = frame_samples / self.cfg.sample_rate+ return words_to_hypothesis(words, text_to_ids, frame_seconds, trcfg.timestamps, ['.', '!', '?'])+ def _transcribe_on_begin(self, audio, trcfg: MultiTaskTranscriptionConfig): """ Transcription setup method.@@ -935,7 +1044,7 @@ def _transcribe_on_begin(self, audio, trcfg: MultiTaskTranscriptionConfig): 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:+ if (trcfg.timestamps or trcfg.chunking is not None) and self.timestamps_asr_model is not None: self.timestamps_asr_model.to(trcfg._internal.device) def _transcribe_input_manifest_processing(@@ -954,7 +1063,12 @@ def _transcribe_input_manifest_processing( 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)+ if trcfg.chunking is not None:+ audio_files = (+ self._may_be_make_dict_and_fix_paths([entry], manifest_filepath, trcfg)[0] for entry in audio_files+ )+ else:+ audio_files = self._may_be_make_dict_and_fix_paths(audio_files, manifest_filepath, trcfg) ds_config = super()._transcribe_input_manifest_processing(audio_files, temp_dir, trcfg) if trcfg.enable_chunking and self.timestamps_asr_model is not None:@@ -1461,3 +1575,10 @@ def parse_multitask_prompt(prompt: dict | None) -> list[dict]: # ) role = prompt.pop("role", "user") return [dict(role=role, slots=prompt)]+++def _requests_timestamps(value) -> Optional[bool]:+ """Read a timestamp request given as a boolean or as a legacy Canary prompt value ('yes', 'no', ...)."""+ if value is None:+ return None+ return str(value).lower() in ('true', 'yes', 'timestamp', '1')nemo/collections/asr/models/ctc_models.py67 + / 1 −
@@ -35,6 +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.longform_inference import ChunkingConfig, resolve_chunking, select_chunk_frames from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis from nemo.collections.asr.parts.utils.timestamp_utils import process_timestamp_outputs from nemo.collections.common.data.lhotse import get_lhotse_dataloader_from_config@@ -147,6 +148,7 @@ def transcribe( verbose: bool = True, timestamps: Optional[bool] = None, override_config: Optional[TranscribeConfig] = None,+ chunking: Optional[ChunkingConfig] = None, ) -> TranscriptionReturnType: """ Uses greedy decoding to transcribe audio files. Use this method for debugging and prototyping.@@ -174,13 +176,15 @@ def transcribe( override_config: (Optional[TranscribeConfig]) override transcription config pre-defined by the user. **Note**: All other arguments in the function will be ignored if override_config is passed. You should call this argument as `model.transcribe(audio, override_config=TranscribeConfig(...))`.+ chunking: Optional offline chunk plan. Owned frames are assembled before CTC collapse. Returns: A list of transcriptions (or raw log probabilities if logprobs is True) in the same order as paths2audio_files """ timestamps = timestamps or (override_config.timestamps if override_config is not None else None)- if timestamps is not None:+ planned_chunking = resolve_chunking(chunking, override_config) is not None+ if timestamps is not None and not planned_chunking: # else retain the decoder state (users can set it using change_decoding_strategy) if timestamps or (override_config is not None and override_config.timestamps): logging.info(@@ -207,6 +211,7 @@ def transcribe( verbose=verbose, timestamps=timestamps, override_config=override_config,+ chunking=chunking, ) def change_vocabulary(self, new_vocabulary: List[str], decoding_cfg: Optional[DictConfig] = None):@@ -722,6 +727,67 @@ def test_dataloader(self): """ Transcription related methods """ + def _transcribe_chunk_validate(self, trcfg):+ decoding = self._transcribe_chunk_ctc_decoding()+ if decoding.cfg.strategy not in ('greedy', 'greedy_batch'):+ raise ValueError('Planned CTC chunking currently supports greedy and greedy_batch decoding.')+ if decoding.cfg.get('greedy', {}).get('ngram_lm_model'):+ raise ValueError('Planned CTC chunking currently requires decoding without an n-gram LM.')++ def _transcribe_chunk_ctc_decoding(self):+ return self.decoding++ def _transcribe_chunk_ctc_decoder(self):+ return self.decoder++ def _transcribe_chunk_outputs(self, outputs, chunks, frame_samples, trcfg):+ logits = outputs['logits']+ lengths = outputs.get('logits_len', outputs.get('encoded_len'))+ decoding = self._transcribe_chunk_ctc_decoding()+ # Fusion models (e.g. a boosting tree) score log probabilities, not argmax labels.+ retain_logits = (+ trcfg.return_hypotheses+ or decoding.preserve_alignments+ or decoding.preserve_frame_confidence+ or getattr(decoding.decoding, 'fusion_models', None) is not None+ )+ selected = []+ upsampling_factor = getattr(self._transcribe_chunk_ctc_decoder(), 'upsampling_factor', 1)+ for i, (length, chunk) in enumerate(zip(lengths, chunks)):+ frames = select_chunk_frames(logits[i, : int(length)], chunk, frame_samples, upsampling_factor)+ selected.append((frames if retain_logits else frames.argmax(-1)).detach().cpu().clone())+ return selected++ def _transcribe_chunk_finalize(self, parts, chunks, frame_samples, trcfg):+ # A single CTC collapse preserves repeated labels and blanks across chunk joins.+ frames = torch.cat(parts)+ decoding = copy.copy(self._transcribe_chunk_ctc_decoding())+ decoding.decoding = copy.copy(decoding.decoding)+ timestamps = trcfg.timestamps if trcfg.timestamps is not None else decoding.compute_timestamps+ decoding.compute_timestamps = bool(+ timestamps or decoding.preserve_token_confidence or decoding.preserve_word_confidence+ )+ decoding.decoding.compute_timestamps = decoding.compute_timestamps or decoding.preserve_frame_confidence+ hyp = decoding.ctc_decoder_predictions_tensor(+ frames.unsqueeze(0), torch.tensor([len(frames)]), return_hypotheses=True+ )[0]+ if trcfg.return_hypotheses:+ hyp.y_sequence = frames+ if hyp.alignments is None:+ hyp.alignments = frames+ if timestamps:+ hyp = process_timestamp_outputs(+ hyp,+ self.encoder.subsampling_factor,+ self.cfg.preprocessor.window_stride+ / getattr(self._transcribe_chunk_ctc_decoder(), 'upsampling_factor', 1),+ )[0]+ else:+ hyp.timestamp = []+ if not trcfg.return_hypotheses and not timestamps:+ hyp = Hypothesis(hyp.score, hyp.y_sequence, hyp.text)+ return hyp+ def _transcribe_forward(self, batch: Any, trcfg: TranscribeConfig): logits, logits_len, greedy_predictions = self.forward(input_signal=batch[0], input_signal_length=batch[1]) output = dict(logits=logits, logits_len=logits_len)nemo/collections/asr/models/hybrid_rnnt_ctc_bpe_models_prompt.py7 + / 1 −
@@ -34,6 +34,7 @@ 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.longform_inference import ChunkingConfig, resolve_chunking from nemo.collections.asr.parts.utils.prompt_language_utils import ( AUTO_PROMPT_LANGUAGE, resolve_deprecated_prompt_arguments,@@ -382,6 +383,7 @@ def transcribe( verbose: bool = True, timestamps: Optional[bool] = None, override_config: Optional[HybridRNNTCTCPromptTranscribeConfig] = None,+ chunking: Optional[ChunkingConfig] = None, **prompt, ) -> TranscriptionReturnType: """@@ -405,6 +407,7 @@ def transcribe( 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.+ chunking: Optional offline chunk plan. Retains each utterance's language prompt. **prompt: Optional input to construct the prompts for the model. ``target_lang`` (str) is the language of every utterance (e.g., "en-US", "de", or the language-agnostic "auto"); when omitted, each manifest entry's ``lang_field`` is used, or "auto"@@ -421,7 +424,9 @@ def transcribe( f"{self.cur_decoder} is not supported for cur_decoder. Supported values are ['ctc', 'rnnt']" ) - if timestamps is not None:+ # Planned chunking computes timestamps call-locally and leaves the model decoding unchanged.+ planned_chunking = resolve_chunking(chunking, override_config) is not None+ if timestamps is not None and not planned_chunking: 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']"@@ -456,6 +461,7 @@ def transcribe( timestamps=timestamps, target_lang=prompt.get('target_lang', defaults.target_lang), lang_field=prompt.get('lang_field', defaults.lang_field),+ chunking=chunking, ) else:nemo/collections/asr/models/hybrid_rnnt_ctc_models.py29 + / 1 −
@@ -23,11 +23,13 @@ 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.ctc_models import EncDecCTCModel from nemo.collections.asr.models.rnnt_models import EncDecRNNTModel from nemo.collections.asr.parts.mixins import ASRBPEMixin, ASRTranscriptionMixin, InterCTCMixin, TranscribeConfig from nemo.collections.asr.parts.mixins.transcription import TranscriptionReturnType from nemo.collections.asr.parts.preprocessing.segment import ChannelSelectorType from nemo.collections.asr.parts.submodules.ctc_decoding import CTCDecoding, CTCDecodingConfig+from nemo.collections.asr.parts.utils.longform_inference import ChunkingConfig, resolve_chunking from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis from nemo.collections.asr.parts.utils.timestamp_utils import process_timestamp_outputs from nemo.core.classes.common import PretrainedModelInfo@@ -106,6 +108,7 @@ def transcribe( verbose: bool = True, timestamps: bool = None, override_config: Optional[TranscribeConfig] = None,+ chunking: Optional[ChunkingConfig] = None, ) -> TranscriptionReturnType: """ Uses greedy decoding to transcribe audio files. Use this method for debugging and prototyping.@@ -130,14 +133,17 @@ def transcribe( Default is None and would retain the previous state set by using self.change_decoding_strategy(). verbose: (bool) whether to display tqdm progress bar logprobs: (bool) whether to return ctc logits insted of hypotheses+ chunking: Optional offline chunk plan, applied to the currently selected decoder head. Returns: Returns a tuple of 2 items - * A list of greedy transcript texts / Hypothesis * An optional list of beam search transcript texts / Hypothesis / NBestHypothesis. """ - if timestamps is not None:+ # Planned chunking computes timestamps call-locally and leaves the model decoding unchanged.+ planned_chunking = resolve_chunking(chunking, override_config) is not None+ if timestamps is not None and not planned_chunking: 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']"@@ -176,8 +182,30 @@ def transcribe( verbose=verbose, timestamps=timestamps, override_config=override_config,+ chunking=chunking, ) + def _transcribe_chunk_ctc_decoding(self):+ return self.ctc_decoding++ def _transcribe_chunk_ctc_decoder(self):+ return self.ctc_decoder++ def _transcribe_chunk_validate(self, trcfg):+ if self.cur_decoder == 'ctc':+ return EncDecCTCModel._transcribe_chunk_validate(self, trcfg)+ return super()._transcribe_chunk_validate(trcfg)++ def _transcribe_chunk_outputs(self, outputs, chunks, frame_samples, trcfg):+ if self.cur_decoder == 'ctc':+ return EncDecCTCModel._transcribe_chunk_outputs(self, outputs, chunks, frame_samples, trcfg)+ return super()._transcribe_chunk_outputs(outputs, chunks, frame_samples, trcfg)++ def _transcribe_chunk_finalize(self, parts, chunks, frame_samples, trcfg):+ if self.cur_decoder == 'ctc':+ return EncDecCTCModel._transcribe_chunk_finalize(self, parts, chunks, frame_samples, trcfg)+ return super()._transcribe_chunk_finalize(parts, chunks, frame_samples, trcfg)+ def _transcribe_on_begin(self, audio, trcfg: TranscribeConfig): super()._transcribe_on_begin(audio, trcfg) nemo/collections/asr/models/rnnt_bpe_models_prompt.py13 + / 1 −
@@ -32,6 +32,7 @@ from nemo.collections.asr.parts.mixins.transcription import TranscriptionReturnType from nemo.collections.asr.parts.preprocessing.segment import ChannelSelectorType from nemo.collections.asr.parts.submodules.rnnt_decoding import RNNTBPEDecoding+from nemo.collections.asr.parts.utils.longform_inference import ChunkingConfig, resolve_chunking from nemo.collections.asr.parts.utils.prompt_language_utils import ( AUTO_PROMPT_LANGUAGE, resolve_deprecated_prompt_arguments,@@ -647,9 +648,19 @@ def transcribe( verbose: bool = True, timestamps: Optional[bool] = None, override_config: Optional[RNNTPromptTranscribeConfig] = None,+ chunking: Optional[ChunkingConfig] = None, **prompt, ) -> TranscriptionReturnType:- if timestamps is not None:+ """Transcribe with per-utterance language conditioning.++ Arguments follow ``EncDecRNNTModel.transcribe``. ``chunking`` enables the+ shared offline chunk plan. ``target_lang`` in ``prompt`` overrides manifest+ languages. With ``override_config``, set its ``chunking`` and ``target_lang``+ fields instead. Returns one transcription hypothesis per input utterance.+ """+ # Planned chunking computes timestamps call-locally and leaves the model decoding unchanged.+ planned_chunking = resolve_chunking(chunking, override_config) is not None+ if timestamps is not None and not planned_chunking: decoding_cfg = self.cfg.decoding if timestamps or (override_config is not None and override_config.timestamps): return_hypotheses = True@@ -675,6 +686,7 @@ def transcribe( timestamps=timestamps, target_lang=prompt.get('target_lang', defaults.target_lang), lang_field=prompt.get('lang_field', defaults.lang_field),+ chunking=chunking, ) else: if not isinstance(override_config, RNNTPromptTranscribeConfig):nemo/collections/asr/models/rnnt_models.py66 + / 1 −
@@ -42,10 +42,17 @@ 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.longform_inference import (+ ChunkingConfig,+ resolve_chunking,+ select_chunk_words,+ words_to_hypothesis,+) from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis from nemo.collections.asr.parts.utils.timestamp_utils import process_timestamp_outputs from nemo.collections.common.data.lhotse import get_lhotse_dataloader_from_config from nemo.collections.common.parts.preprocessing.parsers import make_parser+from nemo.collections.common.tokenizers.aggregate_tokenizer import AggregateTokenizer from nemo.core.classes.common import PretrainedModelInfo, typecheck from nemo.core.classes.mixins import AccessMixin from nemo.core.neural_types import AcousticEncodedRepresentation, AudioSignal, LengthsType, NeuralType, SpectrogramType@@ -259,6 +266,7 @@ def transcribe( verbose: bool = True, timestamps: Optional[bool] = None, override_config: Optional[TranscribeConfig] = None,+ chunking: Optional[ChunkingConfig] = None, ) -> TranscriptionReturnType: """ Uses greedy decoding to transcribe audio files. Use this method for debugging and prototyping.@@ -290,6 +298,7 @@ def transcribe( override_config: (Optional[TranscribeConfig]) override transcription config pre-defined by the user. **Note**: All other arguments in the function will be ignored if override_config is passed. You should call this argument as `model.transcribe(audio, override_config=TranscribeConfig(...))`.+ chunking: Optional offline chunk plan. Each read window is decoded; words are selected by time. Returns: Returns a tuple of 2 items -@@ -298,7 +307,9 @@ def transcribe( """ timestamps = timestamps or (override_config.timestamps if override_config is not None else None)- if timestamps is not None:+ # Planned chunking computes word timestamps call-locally and leaves the model decoding unchanged.+ planned_chunking = resolve_chunking(chunking, override_config) is not None+ if timestamps is not None and not planned_chunking: need_change_decoding = False if timestamps or (override_config is not None and override_config.timestamps): logging.info(@@ -335,6 +346,7 @@ def transcribe( override_config=override_config, # Additional arguments partial_hypothesis=partial_hypothesis,+ chunking=chunking, ) def change_vocabulary(self, new_vocabulary: List[str], decoding_cfg: Optional[DictConfig] = None):@@ -952,6 +964,59 @@ def multi_test_epoch_end(self, outputs, dataloader_idx: int = 0): """ Transcription related methods """ + def _transcribe_chunk_validate(self, trcfg):+ if getattr(self.decoding, 'restart_token_ids', None):+ raise ValueError('Planned RNNT/TDT chunking does not support `restart_after_tokens`.')+ if isinstance(getattr(self.decoding, 'tokenizer', None), AggregateTokenizer):+ # Word timestamps and assembled token IDs would need a language for every word.+ raise ValueError('Planned RNNT/TDT chunking does not support an aggregate tokenizer.')+ beam = self.decoding.cfg.get('beam') or {}+ if self.decoding.cfg.strategy not in ('greedy', 'greedy_batch') and not beam.get(+ 'return_best_hypothesis', True+ ):+ raise ValueError('Planned RNNT/TDT chunking requires one best hypothesis per chunk.')++ def _transcribe_chunk_decoding(self, trcfg):+ """The model's decoding with word timestamps, which select words by time; the model is unchanged."""+ if trcfg._internal.chunk_decoding is None:+ decoding = self.decoding+ timestamp_type = decoding.cfg.get('rnnt_timestamp_type', 'all')+ if not decoding.compute_timestamps or timestamp_type not in ('all', 'word'):+ cfg = copy.deepcopy(decoding.cfg)+ with open_dict(cfg):+ cfg.compute_timestamps = True+ cfg.rnnt_timestamp_type = 'all'+ kwargs = (+ {'tokenizer': decoding.tokenizer}+ if hasattr(decoding, 'tokenizer')+ else {'vocabulary': list(decoding.labels_map.values())}+ )+ decoding = type(decoding)(cfg, self.decoder, self.joint, **kwargs)+ trcfg._internal.chunk_decoding = decoding+ return trcfg._internal.chunk_decoding++ def _transcribe_chunk_outputs(self, outputs, chunks, frame_samples, trcfg):+ # Decode each read window with a fresh decoder that warms up on its left context.+ # A decoder state carried across chunks can stay in blank through long stretches of speech.+ decoding = self._transcribe_chunk_decoding(trcfg)+ hyps = decoding.rnnt_decoder_predictions_tensor(+ outputs['encoded'], outputs['encoded_len'], return_hypotheses=True+ )+ hyps = process_timestamp_outputs(hyps, self.encoder.subsampling_factor, self.cfg.preprocessor.window_stride)+ sample_rate = int(self.cfg.sample_rate)+ return [select_chunk_words(hyp.timestamp['word'], chunk, sample_rate) for hyp, chunk in zip(hyps, chunks)]++ def _transcribe_chunk_finalize(self, parts, chunks, frame_samples, trcfg):+ decoding = self._transcribe_chunk_decoding(trcfg)+ if hasattr(decoding, 'tokenizer'):+ text_to_ids = decoding.tokenizer.text_to_ids+ else:+ label_ids = {label: i for i, label in decoding.labels_map.items()}+ text_to_ids = lambda text: [label_ids[c] for c in text if c in label_ids]+ words = [word for part in parts for word in part]+ frame_seconds = frame_samples / self.cfg.sample_rate+ return words_to_hypothesis(words, text_to_ids, frame_seconds, trcfg.timestamps, decoding.segment_seperators)+ def _transcribe_forward(self, batch: Any, trcfg: TranscribeConfig): return self._transcribe_encode(batch[0], batch[1], trcfg) nemo/collections/asr/parts/mixins/mixins.py15 + / 0 −
@@ -1068,3 +1068,18 @@ def _apply_prompt_to_encoded(self, encoded: Tensor) -> Tensor: out_dtype = encoded.dtype encoded = self.prompt_kernel(torch.cat([encoded, prompt], dim=-1)).to(out_dtype) return encoded.transpose(1, 2) # (B, T, D) -> (B, D, T)++ def _transcribe_chunk_batch(self, audio, lengths, cuts, trcfg):+ """Retain each utterance's language prompt when its chunks share an inference batch."""+ languages = [+ (+ trcfg.target_lang+ if trcfg.target_lang is not None+ else (cut.supervisions[0].language if cut is not None and cut.supervisions else None)+ )+ for cut in cuts+ ]+ indices = torch.tensor(+ [self.resolve_prompt_language(lang) for lang in languages], device=audio.device, dtype=torch.long+ )+ return audio, lengths, None, None, indicesnemo/collections/asr/parts/mixins/transcription.py134 + / 1 −
@@ -13,11 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. +import copy import json import os import tempfile from abc import ABC, abstractmethod-from dataclasses import dataclass+from dataclasses import dataclass, field from functools import partial from typing import Any, Dict, List, Optional, Tuple, Union @@ -31,6 +32,12 @@ 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.longform_inference import (+ ChunkBatches,+ ChunkedAudioDataset,+ ChunkingConfig,+ collate_audio_chunks,+) from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis from nemo.collections.common.data.utils import move_data_to_device from nemo.lightning.speech_throughput import register_throughput_policy@@ -55,6 +62,7 @@ class InternalTranscribeConfig: # Scratch space temp_dir: Optional[str] = None manifest_filepath: Optional[str] = None+ chunk_decoding: Optional[Any] = None @dataclass@@ -67,6 +75,8 @@ class TranscribeConfig: augmentor: Optional[DictConfig] = None timestamps: Optional[bool] = None # returns timestamps for each word and segments if model supports punctuations verbose: bool = True+ # Opt-in offline chunk planning and output selection. Keyword-only, so positional fields keep their order.+ chunking: Optional[ChunkingConfig] = field(default=None, kw_only=True) # Utility partial_hypothesis: Optional[List[Any]] = None@@ -211,6 +221,7 @@ def transcribe( verbose: bool = True, timestamps: Optional[bool] = None, override_config: Optional[TranscribeConfig] = None,+ chunking: Optional[ChunkingConfig] = None, **config_kwargs, ) -> GenericTranscriptionType: """@@ -239,6 +250,8 @@ def transcribe( override_config: (Optional[TranscribeConfig]) override transcription config pre-defined by the user. **Note**: All other arguments in the function will be ignored if override_config is passed. You should call this argument as `model.transcribe(audio, override_config=TranscribeConfig(...))`.+ chunking: Optional offline chunk plan. Supported models select output from disjoint time regions.+ With override_config, set override_config.chunking instead. **config_kwargs: (Optional[Dict]) additional arguments to override the default TranscribeConfig. Note: If override_config is passed, these arguments will be ignored. @@ -267,6 +280,7 @@ def transcribe( augmentor=augmentor, verbose=verbose, timestamps=timestamps,+ chunking=chunking, **config_kwargs, ) else:@@ -352,6 +366,10 @@ def transcribe_generator(self, audio, override_config: Optional[TranscribeConfig A generator version of `transcribe` function. """ + if override_config is not None and getattr(override_config, 'chunking', None) is not None:+ yield from self._transcribe_chunked_generator(audio, override_config)+ return+ if override_config is None: override_config = TranscribeConfig() @@ -412,6 +430,121 @@ def transcribe_generator(self, audio, override_config: Optional[TranscribeConfig # set mode back to its original value self._transcribe_on_end(transcribe_cfg) + def _transcribe_chunk_validate(self, trcfg):+ """Validate model support before loading audio or changing model state."""+ raise NotImplementedError(f'{type(self).__name__} does not support planned chunk transcription.')++ def _transcribe_chunk_batch(self, audio, lengths, cuts, trcfg):+ """Adapt waveform tensors and optional Lhotse cuts to the model input contract."""+ return audio, lengths, None, None++ def _transcribe_chunk_outputs(self, outputs, chunks, frame_samples, trcfg):+ """Select one owned output per chunk in the model's native representation."""+ raise NotImplementedError++ def _transcribe_chunk_finalize(self, parts, chunks, frame_samples, trcfg):+ """Assemble one source result and compute its final text and metadata."""+ raise NotImplementedError++ @torch.inference_mode()+ def _transcribe_chunked_generator(self, audio, config):+ """Batch independent read intervals and emit each complete utterance in input order."""+ if isinstance(audio, DataLoader):+ raise ValueError('Planned chunking requires files, a manifest, or waveforms, not an external DataLoader.')+ trcfg = copy.deepcopy(config)+ if isinstance(trcfg.chunking, (dict, DictConfig)):+ trcfg.chunking = ChunkingConfig(**trcfg.chunking)+ if not isinstance(trcfg.chunking, ChunkingConfig):+ raise ValueError('chunking must be a ChunkingConfig or a mapping with chunk_size and context_size.')+ self._transcribe_chunk_validate(trcfg)+ if trcfg.batch_size <= 0:+ raise ValueError('batch_size must be positive.')+ if trcfg.augmentor is not None or trcfg.partial_hypothesis:+ raise ValueError('Planned chunking does not accept augmentations or partial hypotheses.')+ # A model's legacy chunker must not run at the same time as the shared chunk plan.+ if hasattr(trcfg, 'enable_chunking'):+ trcfg.enable_chunking = False+ trcfg._internal = type(trcfg._internal)() if trcfg._internal is not None else InternalTranscribeConfig()+ sample_rate = int(self.cfg.sample_rate)+ frame_size = sample_rate * self.cfg.preprocessor.window_stride * self.encoder.subsampling_factor+ frame_samples = round(frame_size)+ if frame_samples <= 0 or abs(frame_size - frame_samples) > 1e-5:+ raise ValueError('Chunked transcription requires an integral encoder frame size in audio samples.')+ if isinstance(audio, (str, np.ndarray, torch.Tensor)):+ audio = [audio]+ else:+ audio = list(audio)+ if not audio:+ raise ValueError('Input audio is empty.')+ try:+ self._transcribe_on_begin(audio, trcfg)+ with tempfile.TemporaryDirectory() as tmpdir:+ trcfg._internal.temp_dir = tmpdir+ tensors = None+ if isinstance(audio[0], str):+ from lhotse.lazy import LazyJsonlIterator++ from nemo.collections.common.data.lhotse.nemo_adapters import LazyNeMoIterator+ from nemo.collections.common.parts.preprocessing.manifest import get_full_path++ if len(audio) == 1 and audio[0].endswith(('.json', '.jsonl')):+ trcfg._internal.manifest_filepath = audio[0]+ audio = LazyJsonlIterator(audio[0])+ audio = (+ dict(+ entry,+ audio_filepath=get_full_path(+ entry['audio_filepath'], manifest_file=trcfg._internal.manifest_filepath+ ),+ )+ for entry in audio+ )+ ds_config = self._transcribe_input_manifest_processing(audio, tmpdir, trcfg)+ sources = LazyNeMoIterator(+ os.path.join(tmpdir, 'manifest.json'),+ text_field=ds_config.get('text_field', 'text'),+ lang_field=ds_config.get('lang_field', 'lang'),+ )+ elif all(isinstance(a, (np.ndarray, torch.Tensor)) for a in audio):+ sources = tensors = audio+ else:+ raise ValueError('Provide a homogeneous list of file paths or mono waveforms.')+ # Plan in the main process; workers only load the audio of their batches.+ loader = DataLoader(+ ChunkedAudioDataset(tensors, sample_rate, trcfg.channel_selector),+ batch_sampler=ChunkBatches(sources, sample_rate, trcfg.chunking, frame_samples, trcfg.batch_size),+ num_workers=trcfg.num_workers or 0,+ collate_fn=collate_audio_chunks,+ )+ pending = {}+ saw_chunk = False+ for waveforms, lengths, indices, chunks, cuts in tqdm(+ loader, disable=not trcfg.verbose, desc='Transcribing chunks'+ ):+ saw_chunk = True+ # Right padding permits feature extraction on sub-second sources without+ # shifting their times. Semantic lengths still exclude padding.+ if waveforms.shape[1] < sample_rate:+ waveforms = torch.nn.functional.pad(waveforms, (0, sample_rate - waveforms.shape[1]))+ waveforms, lengths = move_data_to_device((waveforms, lengths), trcfg._internal.device)+ batch = self._transcribe_chunk_batch(waveforms, lengths, cuts, trcfg)+ outputs = self._transcribe_forward(batch, trcfg)+ selected = self._transcribe_chunk_outputs(outputs, chunks, frame_samples, trcfg)+ if len(selected) != len(chunks):+ raise RuntimeError('Chunk output selection must return one result per input chunk.')+ for source_idx, chunk, part in zip(indices, chunks, selected):+ parts, plan = pending.setdefault(source_idx, ([], []))+ parts.append(part)+ plan.append(chunk)+ if chunk.is_last:+ yield [self._transcribe_chunk_finalize(parts, plan, frame_samples, trcfg)]+ del pending[source_idx]+ del waveforms, lengths, batch, outputs, selected+ if not saw_chunk:+ raise ValueError('Input manifest contains no audio entries.')+ finally:+ self._transcribe_on_end(trcfg)+ """ Transcribe Execution Flow """nemo/collections/asr/parts/submodules/ctc_decoding.py1 + / 1 −
@@ -1070,7 +1070,7 @@ def _aggregate_token_confidence(self, hypothesis: Hypothesis) -> List[float]: A list of word-level confidence scores. """ return self._aggregate_token_confidence_chars(- self.decode_tokens_to_str(hypothesis.text[0]).split(), hypothesis.token_confidence+ self.decode_ids_to_str(hypothesis.text[0]).split(), hypothesis.token_confidence ) def decode_tokens_to_str(self, tokens: List[str]) -> str:nemo/collections/asr/parts/utils/longform_inference.pyadded312 + / 0 −
@@ -0,0 +1,312 @@+# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Chunk planning and output selection for offline long-form transcription.++The transcription mixin splits every input into disjoint owned intervals with read context,+loads and batches the read intervals, and assembles one result per input. Each model selects+output from a read interval in its native representation:++* CTC keeps the owned logit frames. One CTC collapse runs over the joined frames, so repeated+ labels and blanks stay correct across joins.+* RNNT/TDT decodes each read interval with a fresh decoder, which warms up on the left context,+ and keeps the words whose timestamp midpoints fall in the owned interval. A decoder state+ carried across chunks can keep a transducer in blank through long stretches of speech.+* AED times its decoded words by matching them to the greedy words of its CTC timestamp model,+ then keeps the words in the owned interval. Without a timestamp model, neighbouring windows+ are joined at the longest run of words they share in their overlap.+"""++import difflib+import math+import re+from dataclasses import dataclass++import numpy as np+import torch+from torch.utils.data import Dataset++from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis+++@dataclass(frozen=True)+class ChunkingConfig:+ """Offline chunk sizes in seconds.++ ``chunk_size`` is the duration owned by one chunk. ``context_size`` is extra audio+ read on each side. Sizes are rounded up to complete encoder frames. Context is+ discarded before CTC/RNNT decoding, or selected by word time for AED output.+ """++ chunk_size: float = 30.0+ context_size: float = 2.0+++@dataclass(frozen=True)+class AudioChunk:+ """Read and owned intervals in samples, relative to the source utterance."""++ read_start: int+ read_end: int+ keep_start: int+ keep_end: int+ is_last: bool+++def resolve_chunking(chunking: ChunkingConfig | None, override_config=None) -> ChunkingConfig | None:+ """The chunking ``transcribe()`` applies: ``override_config`` takes precedence over the argument,+ as it does for every other transcription option."""+ if override_config is not None:+ return getattr(override_config, 'chunking', None)+ return chunking+++def make_chunk_plan(+ num_samples: int, sample_rate: int, config: ChunkingConfig, frame_samples: int = 1+) -> list[AudioChunk]:+ """Partition an utterance into disjoint owned intervals with overlapping read context.++ Args:+ num_samples: Positive source length at the model sample rate.+ sample_rate: Model sample rate.+ config: Owned chunk and context durations.+ frame_samples: Samples per encoder frame; read starts align to this grid.++ Returns:+ Ordered chunks with half-open intervals. Every source sample has one owner. A remainder+ shorter than two frames joins the previous chunk.+ """+ if num_samples <= 0 or sample_rate <= 0 or frame_samples <= 0:+ raise ValueError('Audio length, sample rate, and frame size must be positive.')+ if not math.isfinite(config.chunk_size) or config.chunk_size <= 0:+ raise ValueError('chunk_size must be finite and greater than zero.')+ if not math.isfinite(config.context_size) or config.context_size < 0:+ raise ValueError('context_size must be finite and nonnegative.')+ size = max(1, math.ceil(config.chunk_size * sample_rate / frame_samples)) * frame_samples+ context = math.ceil(config.context_size * sample_rate / frame_samples) * frame_samples+ min_read = 2 * frame_samples+ chunks = []+ start = 0+ while start < num_samples:+ is_last = num_samples - (start + size) < min_read+ keep_end = num_samples if is_last else start + size+ chunks.append(+ AudioChunk(+ read_start=max(0, start - context),+ read_end=min(num_samples, keep_end + context),+ keep_start=start,+ keep_end=keep_end,+ is_last=is_last,+ )+ )+ start = keep_end+ return chunks+++def select_chunk_frames(+ frames: torch.Tensor, chunk: AudioChunk, frame_samples: int, upsampling_factor: int = 1+) -> torch.Tensor:+ """Select owned encoder frames along the first dimension, before decoding.++ The feature extractor drops a final partial hop. A source that ends off the frame grid+ can therefore yield one encoder frame fewer than its last owned interval spans. The+ last chunk keeps every frame that the encoder returned. Any other shortfall raises.+ """+ start = (chunk.keep_start - chunk.read_start) // frame_samples * upsampling_factor+ end = math.ceil((chunk.keep_end - chunk.read_start) / frame_samples) * upsampling_factor+ if chunk.is_last and end - upsampling_factor <= frames.shape[0] < end:+ end = frames.shape[0]+ if end > frames.shape[0]:+ raise RuntimeError(f'Encoder returned {frames.shape[0]} frames, but chunk ownership requires {end}.')+ return frames[start:end]+++def select_chunk_words(words: list[dict], chunk: AudioChunk, sample_rate: int) -> list[dict]:+ """Keep words whose midpoints belong to the chunk; shift times by its actual start.++ Repeated words remain separate entries. This does not compare word text, invent+ missing timestamps, or change valid word durations.+ """+ selected = []+ offset = chunk.read_start / sample_rate+ for word in words:+ start, end = word['start'], word['end']+ if not math.isfinite(start) or not math.isfinite(end) or start < 0 or end < start:+ raise ValueError('Aligned chunk words must have finite, nonnegative, ordered timestamps.')+ # Twice the midpoint, in whole samples. Frame-aligned word times land on half samples, so+ # rounding removes only float error and neighbouring windows agree at their shared boundary.+ midpoint2 = 2 * chunk.read_start + round((start + end) * sample_rate)+ # The last chunk also owns words whose timing runs past the source end.+ if 2 * chunk.keep_start <= midpoint2 and (chunk.is_last or midpoint2 < 2 * chunk.keep_end):+ entry = {k: v for k, v in word.items() if k not in ('start_offset', 'end_offset')}+ entry.update(start=offset + start, end=offset + end)+ selected.append(entry)+ return selected+++def words_to_hypothesis(words, text_to_ids, frame_seconds, timestamps, segment_separators) -> Hypothesis:+ """Build one source's result from its selected words, each a dict with ``word`` and times.++ Independently decoded windows define no joint score, so the score is zero, and no+ per-token decoder state, confidence, or alignment is exposed.+ """+ from nemo.collections.asr.parts.utils.timestamp_utils import get_segment_offsets++ text = ' '.join(word['word'] for word in words)+ hyp = Hypothesis(score=0.0, y_sequence=torch.tensor(text_to_ids(text), dtype=torch.long), text=text)+ if timestamps:+ for word in words:+ word.update(+ start_offset=round(word['start'] / frame_seconds), end_offset=round(word['end'] / frame_seconds)+ )+ hyp.timestamp = {'word': words, 'segment': get_segment_offsets(words, segment_separators)}+ return hyp+++def transfer_word_times(words: list[str], timed_words: list[dict], duration: float) -> list[dict]:+ """Time ``words`` by matching them to a timed transcript of the same audio.++ A matched word takes the times of its match. A run of unmatched words shares the span+ between its timed neighbours, or the audio edges, evenly. Matching ignores case and+ punctuation, so it cannot fail; times are in seconds from the audio start.+ """+ keys = [_word_key(w) for w in words], [_word_key(t['word']) for t in timed_words]+ times = [None] * len(words)+ for tag, i1, i2, j1, j2 in difflib.SequenceMatcher(None, *keys, autojunk=False).get_opcodes():+ if tag == 'equal' or (tag == 'replace' and i2 - i1 == j2 - j1):+ for i, j in zip(range(i1, i2), range(j1, j2)):+ times[i] = (timed_words[j]['start'], timed_words[j]['end'])+ elif tag == 'replace':+ _spread(times, i1, i2, timed_words[j1]['start'], timed_words[j2 - 1]['end'])+ i = 0+ while i < len(times):+ j = i+ while j < len(times) and times[j] is None:+ j += 1+ if j > i:+ start = times[i - 1][1] if i > 0 else 0.0+ _spread(times, i, j, start, max(start, times[j][0] if j < len(times) else duration))+ i = j + 1+ return [{'word': w, 'start': start, 'end': end} for w, (start, end) in zip(words, times)]+++def stitch_chunk_words(parts: list[list[str]], plan: list[AudioChunk], sample_rate: int) -> list[str]:+ """Join the words of overlapping read windows when no word times exist.++ The longest run of at least two words shared by both sides of an overlap is the join, and+ each side keeps half of it. Windows without such a run, or without overlap, are concatenated.+ """+ out = list(parts[0])+ for prev_words, words, prev, chunk in zip(parts, parts[1:], plan, plan[1:]):+ overlap = (prev.read_end - chunk.read_start) / sample_rate+ # Search only the words each side spoke in the overlap (with margin), so that a common+ # phrase outside the overlap cannot become the join.+ tail = out[-_words_in(overlap, prev_words, prev, sample_rate) :]+ head = words[: _words_in(overlap, words, chunk, sample_rate)]+ match = difflib.SequenceMatcher(+ None, [_word_key(w) for w in tail], [_word_key(w) for w in head], autojunk=False+ ).find_longest_match(0, len(tail), 0, len(head))+ if overlap > 0 and match.size >= 2:+ half = match.size // 2+ out = out[: len(out) - len(tail) + match.a + half] + list(words[match.b + half :])+ else:+ out += words+ return out+++class ChunkBatches:+ """Plan batches of chunk descriptors once, in source and chunk order, for a DataLoader.++ The DataLoader iterates this planner in the main process, so lazy sources are consumed+ once: each manifest entry is parsed, and its file header read, a single time for any+ number of workers. A descriptor is ``(source_index, source, chunk)``; tensor sources are+ referenced by index only. Workers load the audio of the batches they are given.+ """++ def __init__(self, sources, sample_rate, config, frame_samples, batch_size):+ self.sources = sources+ self.sample_rate = sample_rate+ self.config = config+ self.frame_samples = frame_samples+ self.batch_size = batch_size+ make_chunk_plan(1, sample_rate, config, frame_samples)++ def __iter__(self):+ batch = []+ for index, source in enumerate(self.sources):+ is_tensor = isinstance(source, (np.ndarray, torch.Tensor))+ if is_tensor and source.ndim != 1:+ raise ValueError('Chunked tensor input must contain one mono waveform per entry.')+ length = len(source) if is_tensor else round(source.duration * self.sample_rate)+ for chunk in make_chunk_plan(length, self.sample_rate, self.config, self.frame_samples):+ batch.append((index, None if is_tensor else source, chunk))+ if len(batch) == self.batch_size:+ yield batch+ batch = []+ if batch:+ yield batch+++class ChunkedAudioDataset(Dataset):+ """Load the audio of one planned chunk from a mono tensor or a Lhotse cut.++ Tensor sources stay with the dataset; file cuts arrive with their descriptor. Files are+ read through Lhotse at the model sample rate.+ """++ def __init__(self, tensors, sample_rate, channel_selector=None):+ self.tensors = tensors+ self.sample_rate = sample_rate+ self.channel_selector = channel_selector++ def __getitem__(self, descriptor):+ index, source, chunk = descriptor+ return self._load_chunk(self.tensors[index] if source is None else source, index, chunk)++ def _load_chunk(self, source, source_idx, chunk):+ cut = None+ if isinstance(source, (np.ndarray, torch.Tensor)):+ audio = torch.as_tensor(source[chunk.read_start : chunk.read_end])+ else:+ from lhotse.cut import MultiCut++ from nemo.collections.asr.parts.preprocessing.segment import AudioSegment++ cut = source.truncate(+ offset=chunk.read_start / self.sample_rate,+ duration=(chunk.read_end - chunk.read_start) / self.sample_rate,+ preserve_id=True,+ )+ samples = cut.resample(self.sample_rate).load_audio()+ samples = samples[0] if samples.shape[0] == 1 else samples.T+ samples = AudioSegment(samples, self.sample_rate, channel_selector=self.channel_selector).samples+ audio = torch.as_tensor(samples)+ if isinstance(cut, MultiCut):+ # The audio is now one channel; prompts and languages read single-channel cut metadata.+ cut = cut.to_mono(mono_downmix=True)+ if audio.ndim != 1:+ raise ValueError('Select one channel or average channels for chunked transcription.')+ return audio, source_idx, chunk, cut+++def collate_audio_chunks(items):+ """Right-pad waveform slices and keep source and interval metadata on the CPU."""+ audio, indices, chunks, cuts = zip(*items)+ lengths = torch.tensor([len(a) for a in audio], dtype=torch.long)+ batch = torch.nn.utils.rnn.pad_sequence(audio, batch_first=True)+ return batch, lengths, indices, chunks, cuts+++def _words_in(seconds: float, words: list[str], chunk: AudioChunk, sample_rate: int) -> int:+ rate = len(words) * sample_rate / max(1, chunk.read_end - chunk.read_start)+ return math.ceil(seconds * rate * 1.5) + 2+++def _word_key(word: str) -> str:+ return re.sub(r'\W', '', word.lower())+++def _spread(times: list, i1: int, i2: int, start: float, end: float) -> None:+ step = (end - start) / (i2 - i1)+ for k in range(i2 - i1):+ times[i1 + k] = (start + k * step, start + (k + 1) * step)tests/collections/asr/test_asr_hybrid_rnnt_ctc_model_bpe_prompt.py53 + / 0 −
@@ -637,3 +637,56 @@ def test_prompt_truncation(self, hybrid_asr_model_with_prompt): # Should not crash and should produce valid output assert encoded.shape[0] == 1 assert encoded_len.shape[0] == 1+++@pytest.mark.unit+@pytest.mark.parametrize('decoder_type', ['rnnt', 'ctc'])+@pytest.mark.parametrize('timestamps', [True, False])+def test_planned_chunking_skips_legacy_timestamp_setup(+ hybrid_asr_model_with_prompt, monkeypatch, decoder_type, timestamps+):+ from nemo.collections.asr.parts.mixins.transcription import ChunkingConfig, TranscriptionMixin++ model = hybrid_asr_model_with_prompt+ model.change_decoding_strategy(decoder_type=decoder_type, verbose=False)+ settings = copy.deepcopy(model.cfg)++ def change_decoding_strategy(*args, **kwargs):+ raise AssertionError('Planned chunking must not change the model decoding.')++ seen = []+ monkeypatch.setattr(model, 'change_decoding_strategy', change_decoding_strategy)+ monkeypatch.setattr(+ TranscriptionMixin,+ 'transcribe',+ lambda self, audio, override_config=None, **kwargs: seen.append(override_config),+ )+ chunking = ChunkingConfig(chunk_size=10.0, context_size=1.0)+ model.transcribe(['audio.wav'], chunking=chunking, timestamps=timestamps)+ assert len(seen) == 1 and seen[0].chunking == chunking and seen[0].timestamps is timestamps+ assert model.cfg == settings+++@pytest.mark.unit+@pytest.mark.parametrize('decoder_type', ['rnnt', 'ctc'])+def test_override_config_takes_precedence_over_the_chunking_argument(+ hybrid_asr_model_with_prompt, monkeypatch, decoder_type+):+ from nemo.collections.asr.models.hybrid_rnnt_ctc_bpe_models_prompt import HybridRNNTCTCPromptTranscribeConfig+ from nemo.collections.asr.parts.mixins.transcription import ChunkingConfig, TranscriptionMixin++ model = hybrid_asr_model_with_prompt+ model.change_decoding_strategy(decoder_type=decoder_type, verbose=False)+ changes, seen = [], []+ monkeypatch.setattr(model, 'change_decoding_strategy', lambda *args, **kwargs: changes.append(args))+ monkeypatch.setattr(+ TranscriptionMixin,+ 'transcribe',+ lambda self, audio, override_config=None, **kwargs: seen.append(override_config),+ )+ override = HybridRNNTCTCPromptTranscribeConfig(timestamps=True, return_hypotheses=True)+ model.transcribe(['audio.wav'], timestamps=True, override_config=override, chunking=ChunkingConfig(10.0, 1.0))+ # The override config has no chunking, so the plain path runs with the usual timestamp setup.+ decoding_cfg = model.cfg.aux_ctc.decoding if decoder_type == 'ctc' else model.cfg.decoding+ assert seen == [override] and override.chunking is None+ assert changes and decoding_cfg.compute_timestampstests/collections/asr/test_asr_longform_chunking_models.pyadded382 + / 0 −
@@ -0,0 +1,382 @@+# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Planned chunking through small saved and restored transducer, hybrid and AED checkpoints."""++import json+import os++import pytest+import soundfile as sf+import torch+from omegaconf import DictConfig, OmegaConf++from nemo.collections.asr.models import (+ EncDecCTCModelBPE,+ EncDecHybridRNNTCTCBPEModel,+ EncDecMultiTaskModel,+ EncDecRNNTBPEModel,+)+from nemo.collections.asr.parts.mixins.transcription import TranscribeConfig+from nemo.collections.asr.parts.submodules.ctc_decoding import CTCBPEDecodingConfig+from nemo.collections.asr.parts.utils.longform_inference import ChunkingConfig++CHUNKING = ChunkingConfig(chunk_size=0.8, context_size=0.16)+WORD = 'yes' # A whole-word token of the CI tokenizer; deterministic heads emit it.+++def _preprocessor():+ return {+ '_target_': 'nemo.collections.asr.modules.AudioToMelSpectrogramPreprocessor',+ 'sample_rate': 16000,+ 'window_stride': 0.01,+ 'features': 16,+ 'dither': 0.0,+ }+++def _conformer(d_model=16):+ return {+ '_target_': 'nemo.collections.asr.modules.ConformerEncoder',+ 'feat_in': 16,+ 'n_layers': 1,+ 'd_model': d_model,+ 'n_heads': 2,+ 'subsampling': 'striding',+ 'subsampling_factor': 4,+ 'subsampling_conv_channels': 8,+ 'ff_expansion_factor': 2,+ 'conv_kernel_size': 3,+ 'dropout': 0.0,+ 'dropout_pre_encoder': 0.0,+ 'dropout_att': 0.0,+ }+++def _transducer_config(test_data_dir, model_type, hybrid=False):+ durations = [0, 1, 2, 3, 4] if model_type == 'tdt' else []+ config = {+ 'sample_rate': 16000,+ 'preprocessor': _preprocessor(),+ 'model_defaults': {'enc_hidden': 16, 'pred_hidden': 16, 'tdt_durations': durations},+ 'encoder': _conformer(),+ 'decoder': {+ '_target_': 'nemo.collections.asr.modules.RNNTDecoder',+ 'prednet': {'pred_hidden': 16, 'pred_rnn_layers': 1},+ },+ 'joint': {+ '_target_': 'nemo.collections.asr.modules.RNNTJoint',+ 'num_extra_outputs': len(durations),+ 'jointnet': {'joint_hidden': 16, 'activation': 'relu'},+ },+ 'tokenizer': {'dir': os.path.join(test_data_dir, 'asr', 'tokenizers', 'an4_wpe_128'), 'type': 'wpe'},+ 'decoding': {+ 'strategy': 'greedy_batch',+ 'greedy': {'max_symbols': 1},+ 'model_type': model_type,+ 'durations': durations,+ },+ 'loss': (+ {'loss_name': 'tdt', 'tdt_kwargs': {'durations': durations, 'sigma': 0.02}}+ if model_type == 'tdt'+ else {'loss_name': 'default'}+ ),+ }+ if hybrid:+ config['aux_ctc'] = {+ 'ctc_loss_weight': 0.3,+ 'decoder': {+ '_target_': 'nemo.collections.asr.modules.ConvASRDecoder',+ 'feat_in': 16,+ 'num_classes': -2,+ 'vocabulary': None,+ },+ 'decoding': DictConfig(CTCBPEDecodingConfig),+ }+ return DictConfig(config)+++def _emit_one_word_per_frame(model):+ """Make the joint always emit WORD for one frame, so emissions are dense and deterministic."""+ word = model.tokenizer.text_to_ids(WORD)+ assert len(word) == 1+ vocab = model.tokenizer.vocab_size+ with torch.no_grad():+ layer = model.joint.joint_net[-1]+ layer.weight.zero_()+ layer.bias.zero_()+ layer.bias[word[0]] = 10.0+ if layer.bias.numel() > vocab + 1: # TDT durations follow the blank: choose duration 1.+ layer.bias[vocab + 2] = 10.0+ if hasattr(model, 'ctc_decoder'):+ conv = model.ctc_decoder.decoder_layers[0]+ conv.weight.zero_()+ conv.bias.zero_()+ conv.bias[word[0]] = 10.0+++def _restore(model, tmp_path):+ path = str(tmp_path / f'{type(model).__name__}.nemo')+ model.save_to(path)+ return type(model).restore_from(path, map_location='cpu').eval()+++def _sources(tmp_path):+ generator = torch.Generator().manual_seed(0)+ tensors = [torch.randn(n, generator=generator) * 0.1 for n in (32000, 52800)] # 2.0 s and 3.3 s+ files = []+ for i, tensor in enumerate(tensors):+ files.append(str(tmp_path / f'source{i}.wav'))+ sf.write(files[-1], tensor.numpy(), 16000, subtype='FLOAT')+ return tensors, files+++def _encoder_frames(model, source):+ with torch.inference_mode():+ return int(model.forward(input_signal=source[None], input_signal_length=torch.tensor([len(source)]))[1][0])+++@pytest.mark.unit+@pytest.mark.parametrize('model_type', ['rnnt', 'tdt'])+def test_restored_transducer_chunks_sources_in_order(test_data_dir, tmp_path, model_type):+ model = EncDecRNNTBPEModel(cfg=_transducer_config(test_data_dir, model_type)).eval()+ _emit_one_word_per_frame(model)+ model = _restore(model, tmp_path)+ tensors, files = _sources(tmp_path)++ results = model.transcribe(tensors, batch_size=4, chunking=CHUNKING, timestamps=True, verbose=False)+ assert len(results) == 2+ for source, hyp in zip(tensors, results):+ words = hyp.timestamp['word']+ # One word per encoder frame: every frame is owned by exactly one window.+ assert abs(len(words) - _encoder_frames(model, source)) <= 1+ assert hyp.text.split() == [WORD] * len(words)+ starts = [w['start'] for w in words]+ assert starts == sorted(starts) and 0 <= starts[0] and starts[-1] <= len(source) / 16000+ assert hyp.score == 0.0 and hyp.token_confidence is None and hyp.alignments is None+ assert [h.text for h in model.transcribe(tensors, batch_size=1, chunking=CHUNKING, verbose=False)] == [+ h.text for h in results+ ]+ assert [h.text for h in model.transcribe(files, batch_size=3, chunking=CHUNKING, verbose=False)] == [+ h.text for h in results+ ]+++@pytest.mark.unit+def test_restored_hybrid_chunks_with_both_heads(test_data_dir, tmp_path):+ model = EncDecHybridRNNTCTCBPEModel(cfg=_transducer_config(test_data_dir, 'rnnt', hybrid=True)).eval()+ _emit_one_word_per_frame(model)+ model = _restore(model, tmp_path)+ tensors, _ = _sources(tmp_path)++ model.change_decoding_strategy(decoder_type='rnnt', verbose=False)+ rnnt = model.transcribe(tensors, batch_size=4, chunking=CHUNKING, verbose=False)+ assert [len(h.text.split()) for h in rnnt] == pytest.approx([_encoder_frames(model, t) for t in tensors], abs=1)++ model.change_decoding_strategy(decoder_type='ctc', verbose=False)+ ctc = model.transcribe(tensors, batch_size=4, chunking=CHUNKING, verbose=False)+ plain = model.transcribe(tensors, batch_size=2, verbose=False)+ # Owned CTC frames are joined before one collapse, so chunking keeps the plain result here.+ assert [h.text for h in ctc] == [h.text for h in plain] == [WORD, WORD]+++@pytest.mark.unit+@pytest.mark.parametrize('head', ['rnnt', 'hybrid-rnnt', 'hybrid-ctc'])+@pytest.mark.parametrize('timestamps', [True, False])+def test_restored_transducer_chunking_leaves_model_decoding_unchanged(test_data_dir, tmp_path, head, timestamps):+ if head == 'rnnt':+ model = EncDecRNNTBPEModel(cfg=_transducer_config(test_data_dir, 'rnnt')).eval()+ else:+ model = EncDecHybridRNNTCTCBPEModel(cfg=_transducer_config(test_data_dir, 'rnnt', hybrid=True)).eval()+ model.change_decoding_strategy(decoder_type=head.split('-')[1], verbose=False)+ model = _restore(model, tmp_path)+ tensors, _ = _sources(tmp_path)+ decoding, ctc_decoding = model.decoding, getattr(model, 'ctc_decoding', None)+ settings = OmegaConf.to_container(model.cfg)+ results = model.transcribe(tensors, chunking=CHUNKING, timestamps=timestamps, verbose=False)+ assert len(results) == 2 and bool(results[0].timestamp) is timestamps+ assert model.decoding is decoding and getattr(model, 'ctc_decoding', None) is ctc_decoding+ assert OmegaConf.to_container(model.cfg) == settings+++@pytest.mark.unit+@pytest.mark.parametrize(+ 'head, timestamps',+ # The hybrid wrappers set up timestamps only when the argument is given.+ [('rnnt', None), ('rnnt', True), ('hybrid-rnnt', True), ('hybrid-ctc', True)],+)+def test_override_config_takes_precedence_over_the_chunking_argument(test_data_dir, tmp_path, head, timestamps):+ # The override config has no chunking, so the plain path runs and needs the usual timestamp setup.+ if head == 'rnnt':+ model = EncDecRNNTBPEModel(cfg=_transducer_config(test_data_dir, 'rnnt')).eval()+ else:+ model = EncDecHybridRNNTCTCBPEModel(cfg=_transducer_config(test_data_dir, 'rnnt', hybrid=True)).eval()+ model.change_decoding_strategy(decoder_type=head.split('-')[1], verbose=False)+ model = _restore(model, tmp_path)+ tensors, _ = _sources(tmp_path)++ def transcribe(**kwargs):+ override = TranscribeConfig(timestamps=True, return_hypotheses=True, verbose=False)+ return model.transcribe(tensors, timestamps=timestamps, override_config=override, **kwargs)++ results = transcribe(chunking=CHUNKING)+ plain = transcribe()+ assert [h.text for h in results] == [h.text for h in plain]+ assert [h.timestamp['word'] for h in results] == [h.timestamp['word'] for h in plain]+++@pytest.mark.unit+def test_transducer_with_aggregate_tokenizer_rejects_chunking(test_data_dir, tmp_path):+ config = _transducer_config(test_data_dir, 'rnnt')+ wpe = {'dir': config.tokenizer.dir, 'type': 'wpe'}+ config.tokenizer = {'dir': None, 'type': 'agg', 'langs': {'en': wpe, 'de': wpe}}+ model = EncDecRNNTBPEModel(cfg=config).eval()+ tensors, _ = _sources(tmp_path)+ assert len(model.transcribe(tensors, verbose=False)) == 2 # Plain transcription supports it.+ with pytest.raises(ValueError, match='aggregate tokenizer'):+ model.transcribe(tensors, chunking=CHUNKING, verbose=False)+++def _aed_model(test_data_dir):+ tokenizers = os.path.join(test_data_dir, 'asr', 'tokenizers')+ config = DictConfig(+ {+ 'prompt_format': 'canary',+ 'prompt_defaults': [+ {'role': 'user', 'slots': {'source_lang': 'en', 'target_lang': 'en', 'task': 'asr', 'pnc': 'yes'}}+ ],+ 'sample_rate': 16000,+ 'preprocessor': _preprocessor(),+ 'model_defaults': {'asr_enc_hidden': 16, 'lm_enc_hidden': 16, 'lm_dec_hidden': 16},+ 'encoder': _conformer(),+ 'transf_decoder': {+ '_target_': 'nemo.collections.asr.modules.transformer.get_nemo_transformer',+ 'model_name': None,+ 'pretrained': False,+ 'encoder': None,+ 'pre_ln_final_layer_norm': True,+ 'config_dict': {+ 'max_sequence_length': 64,+ 'num_token_types': 0,+ 'hidden_size': 16,+ 'inner_size': 32,+ 'num_layers': 1,+ 'num_attention_heads': 2,+ 'pre_ln': True,+ 'vocab_size': None,+ },+ },+ 'head': {+ '_target_': 'nemo.collections.asr.parts.submodules.token_classifier.TokenClassifier',+ 'num_layers': 1,+ 'activation': 'relu',+ 'log_softmax': True,+ 'hidden_size': 16,+ 'num_classes': None,+ },+ 'tokenizer': {+ 'dir': None,+ 'type': 'agg',+ 'langs': {+ 'spl_tokens': {'dir': os.path.join(tokenizers, 'canary'), 'type': 'bpe'},+ 'en': {'dir': os.path.join(tokenizers, 'an4_wpe_128'), 'type': 'wpe'},+ 'de': {'dir': os.path.join(tokenizers, 'an4_wpe_128'), 'type': 'wpe'},+ },+ 'custom_tokenizer': {+ '_target_': 'nemo.collections.common.tokenizers.canary_tokenizer.CanaryTokenizer',+ 'tokenizers': None,+ },+ },+ 'decoding': {'strategy': 'beam', 'beam': {'beam_size': 1}},+ 'loss': {+ '_target_': 'nemo.collections.common.losses.smoothed_cross_entropy.SmoothedCrossEntropyLoss',+ 'label_smoothing': 0.0,+ },+ }+ )+ torch.manual_seed(0)+ return EncDecMultiTaskModel(cfg=config).eval()+++def _ctc_timestamp_model(test_data_dir):+ config = DictConfig(+ {+ 'sample_rate': 16000,+ 'preprocessor': _preprocessor(),+ 'encoder': _conformer(),+ 'decoder': {+ '_target_': 'nemo.collections.asr.modules.ConvASRDecoder',+ 'feat_in': 16,+ 'num_classes': -1,+ 'vocabulary': None,+ },+ 'tokenizer': {'dir': os.path.join(test_data_dir, 'asr', 'tokenizers', 'an4_wpe_128'), 'type': 'wpe'},+ 'decoding': {'strategy': 'greedy_batch'},+ }+ )+ torch.manual_seed(1)+ return EncDecCTCModelBPE(cfg=config).eval()+++@pytest.mark.unit+def test_restored_aed_chunks_with_ctc_word_timing(test_data_dir, tmp_path):+ model = _restore(_aed_model(test_data_dir), tmp_path)+ object.__setattr__(model, 'timestamps_asr_model', _ctc_timestamp_model(test_data_dir))+ tensors, files = _sources(tmp_path)++ results = model.transcribe(tensors, batch_size=4, chunking=CHUNKING, timestamps=True, verbose=False)+ assert len(results) == 2 and all(h.text for h in results) # The checks below need real emissions.+ for source, hyp in zip(tensors, results):+ assert hyp.y_sequence.tolist() == model.tokenizer.text_to_ids(hyp.text, 'en')+ assert all(0 <= w['start'] <= w['end'] <= len(source) / 16000 + 0.2 for w in hyp.timestamp['word'])+ assert hyp.score == 0.0 and hyp.token_confidence is None++ # Bare and wrapped language names select the same German token IDs.+ for lang in ('de', '<|de|>'):+ german = model.transcribe(tensors, chunking=CHUNKING, source_lang=lang, target_lang=lang, verbose=False)+ assert all(h.text for h in german)+ assert [h.y_sequence.tolist() for h in german] == [model.tokenizer.text_to_ids(h.text, 'de') for h in german]+ with pytest.raises(ValueError, match='not speech translation'):+ model.transcribe(tensors, chunking=CHUNKING, source_lang='en', target_lang='de', verbose=False)++ # A manifest builds each file's prompt from its own entry; final IDs use that file's language.+ manifest = tmp_path / 'aed_manifest.json'+ entries = [+ {'audio_filepath': path, 'duration': len(source) / 16000, 'answer': '', 'task': 'asr', 'pnc': 'yes'}+ | {'source_lang': lang, 'target_lang': lang}+ for path, source, lang in zip(files, tensors, ('en', 'de'))+ ]+ manifest.write_text(''.join(json.dumps(entry) + '\n' for entry in entries))+ per_file = model.transcribe(str(manifest), batch_size=4, chunking=CHUNKING, verbose=False)+ assert len(per_file) == 2 and all(h.text for h in per_file)+ for hyp, lang in zip(per_file, ('en', 'de')):+ assert hyp.y_sequence.tolist() == model.tokenizer.text_to_ids(hyp.text, lang)+++@pytest.mark.unit+def test_restored_aed_without_timestamp_model_stitches_windows(test_data_dir, tmp_path):+ model = _restore(_aed_model(test_data_dir), tmp_path)+ object.__setattr__(model, 'timestamps_asr_model', None)+ tensors, _ = _sources(tmp_path)+ results = model.transcribe(tensors, batch_size=4, chunking=CHUNKING, verbose=False)+ assert len(results) == 2 and all(h.text for h in results)+ assert all(h.y_sequence.tolist() == model.tokenizer.text_to_ids(h.text, 'en') for h in results)+ # An explicit text-only request needs no timestamp model.+ text_only = model.transcribe(tensors, batch_size=4, chunking=CHUNKING, timestamps=False, verbose=False)+ assert len(text_only) == 2 and all(h.text for h in text_only)+ with pytest.raises(ValueError, match='CTC timestamp model'):+ model.transcribe(tensors, chunking=CHUNKING, timestamps=True, verbose=False)+++@pytest.mark.unit+def test_restored_aed_chunks_a_selected_channel_of_a_stereo_file(test_data_dir, tmp_path):+ model = _restore(_aed_model(test_data_dir), tmp_path)+ object.__setattr__(model, 'timestamps_asr_model', None)+ tensors, _ = _sources(tmp_path)+ other = torch.randn(len(tensors[1]), generator=torch.Generator().manual_seed(9)) * 0.1+ stereo, mono = str(tmp_path / 'stereo.wav'), str(tmp_path / 'mono.wav')+ sf.write(stereo, torch.stack([other, tensors[1]], dim=1).numpy(), 16000, subtype='FLOAT')+ sf.write(mono, tensors[1].numpy(), 16000, subtype='FLOAT')+ selected = model.transcribe(stereo, channel_selector=1, chunking=CHUNKING, verbose=False)+ reference = model.transcribe(mono, chunking=CHUNKING, verbose=False)+ assert selected[0].text and [h.text for h in selected] == [h.text for h in reference]tests/collections/asr/test_asr_rnnt_prompt_language.py83 + / 0 −
@@ -647,3 +647,86 @@ def test_plain_model_forward_signature_has_no_prompt(self): assert not {'language_prompt_features', 'language_prompt_indices', 'prompt', 'prompt_indices'} & set( parameters )+++@pytest.mark.unit+def test_chunked_transcription_keeps_each_manifest_language(prompt_model, tmp_path):+ import json++ import soundfile as sf+ from omegaconf import open_dict++ from nemo.collections.asr.parts.mixins.transcription import ChunkingConfig++ with open_dict(prompt_model.cfg):+ prompt_model.cfg.sample_rate = 16000+ prompt_model.cfg.preprocessor.window_stride = 0.01+ signal, _ = make_audio(batch_size=1, samples=20000)+ sf.write(tmp_path / 'audio.wav', signal[0].numpy(), 16000)+ manifest = tmp_path / 'manifest.json'+ entries = [+ {'audio_filepath': str(tmp_path / 'audio.wav'), 'duration': 1.25, 'text': '', 'lang': lang}+ for lang in ['de-DE', 'ja-JP']+ ]+ manifest.write_text(''.join(json.dumps(entry) + '\n' for entry in entries))+ # Run the language-conditioned path through a saved and restored checkpoint.+ checkpoint = tmp_path / 'prompted.nemo'+ prompt_model.save_to(str(checkpoint))+ prompt_model = type(prompt_model).restore_from(str(checkpoint), map_location='cpu').eval()+ assert isinstance(prompt_model, EncDecRNNTBPEModelWithPrompt) and prompt_model.concat+ seen = []+ forward = prompt_model.forward++ def record(*args, language_prompt_indices=None, **kwargs):+ seen.extend(language_prompt_indices.tolist())+ return forward(*args, language_prompt_indices=language_prompt_indices, **kwargs)++ prompt_model.forward = record+ # Three windows per 1.25 s source, batched across the two sources.+ chunking = ChunkingConfig(0.5, 0.1)+ results = prompt_model.transcribe(str(manifest), batch_size=2, verbose=False, chunking=chunking)+ assert len(results) == 2+ # Every window conditions the encoder on its own utterance's manifest language.+ assert seen == [PROMPT_DICTIONARY['de-DE']] * 3 + [PROMPT_DICTIONARY['ja-JP']] * 3+ seen.clear()+ prompt_model.transcribe(str(manifest), batch_size=2, verbose=False, chunking=chunking, target_lang='de-DE')+ assert seen == [PROMPT_DICTIONARY['de-DE']] * 6 # An explicit language applies to every utterance.+++@pytest.mark.unit+@pytest.mark.parametrize('timestamps', [True, False])+def test_chunked_transcription_leaves_model_decoding_unchanged(prompt_model, timestamps):+ from omegaconf import OmegaConf, open_dict++ from nemo.collections.asr.parts.mixins.transcription import ChunkingConfig++ with open_dict(prompt_model.cfg):+ prompt_model.cfg.sample_rate = 16000+ prompt_model.cfg.preprocessor.window_stride = 0.01+ signal, _ = make_audio(batch_size=1, samples=20000)+ decoding, settings = prompt_model.decoding, OmegaConf.to_container(prompt_model.cfg)+ results = prompt_model.transcribe(+ [signal[0]], chunking=ChunkingConfig(0.5, 0.1), timestamps=timestamps, target_lang='de-DE', verbose=False+ )+ assert len(results) == 1+ assert prompt_model.decoding is decoding and OmegaConf.to_container(prompt_model.cfg) == settings+++@pytest.mark.unit+def test_override_config_takes_precedence_over_the_chunking_argument(prompt_model, monkeypatch):+ from nemo.collections.asr.parts.mixins.transcription import ChunkingConfig, TranscriptionMixin++ changes, seen = [], []+ monkeypatch.setattr(prompt_model, 'change_decoding_strategy', lambda *args, **kwargs: changes.append(args))+ monkeypatch.setattr(+ TranscriptionMixin,+ 'transcribe',+ lambda self, audio, override_config=None, **kwargs: seen.append(override_config),+ )+ override = RNNTPromptTranscribeConfig(timestamps=True, return_hypotheses=True)+ prompt_model.transcribe(+ ['audio.wav'], timestamps=True, override_config=override, chunking=ChunkingConfig(10.0, 1.0)+ )+ # The override config has no chunking, so the plain path runs with the usual timestamp setup.+ assert seen == [override] and override.chunking is None+ assert changes and prompt_model.cfg.decoding.compute_timestampstests/collections/asr/utils/test_longform_inference.pyadded1075 + / 0 −
@@ -0,0 +1,1075 @@+# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++import inspect+from types import SimpleNamespace++import pytest+import torch+from omegaconf import OmegaConf, open_dict++from nemo.collections.asr.models.aed_multitask_models import EncDecMultiTaskModel, MultiTaskTranscriptionConfig+from nemo.collections.asr.models.ctc_models import EncDecCTCModel+from nemo.collections.asr.models.hybrid_rnnt_ctc_bpe_models_prompt import HybridRNNTCTCPromptTranscribeConfig+from nemo.collections.asr.models.hybrid_rnnt_ctc_models import EncDecHybridRNNTCTCModel+from nemo.collections.asr.models.rnnt_bpe_models_prompt import RNNTPromptTranscribeConfig+from nemo.collections.asr.models.rnnt_models import EncDecRNNTModel+from nemo.collections.asr.modules.rnnt import RNNTDecoder, RNNTJoint+from nemo.collections.asr.parts.mixins.mixins import PromptStreamingMixin+from nemo.collections.asr.parts.mixins.transcription import (+ ASRTranscriptionMixin,+ InternalTranscribeConfig,+ TranscribeConfig,+ TranscriptionMixin,+)+from nemo.collections.asr.parts.submodules.ctc_decoding import CTCDecoding+from nemo.collections.asr.parts.submodules.rnnt_decoding import RNNTBPEDecoding+from nemo.collections.asr.parts.utils.longform_inference import (+ ChunkBatches,+ ChunkedAudioDataset,+ ChunkingConfig,+ collate_audio_chunks,+ make_chunk_plan,+ select_chunk_frames,+ select_chunk_words,+ transfer_word_times,+)+from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis+++@pytest.mark.unit+@pytest.mark.parametrize('duration', [1, 15999, 16000, 480001, 16000 * 600])+def test_chunk_plan_owns_every_sample_once(duration):+ plan = make_chunk_plan(duration, 16000, ChunkingConfig(), frame_samples=1280)+ assert plan[0].keep_start == 0+ assert plan[-1].keep_end == duration+ assert all(a.keep_end == b.keep_start for a, b in zip(plan, plan[1:]))+ for chunk in plan:+ assert 0 <= chunk.read_start <= chunk.keep_start < chunk.keep_end <= chunk.read_end <= duration+ assert chunk.read_start % 1280 == 0+++@pytest.mark.unit+@pytest.mark.parametrize(+ 'kwargs',+ [+ {'chunk_size': 0},+ {'chunk_size': -1},+ {'context_size': -1},+ {'chunk_size': float('nan')},+ {'context_size': float('inf')},+ ],+)+def test_invalid_chunk_configuration(kwargs):+ with pytest.raises(ValueError):+ make_chunk_plan(100, 10, ChunkingConfig(**kwargs))+++@pytest.mark.unit+def test_chunk_frames_remove_context_before_ctc_collapse():+ plan = make_chunk_plan(8, 1, ChunkingConfig(chunk_size=4, context_size=1))+ # Global CTC path: a a blank b | b blank b blank. The b at the join must collapse once.+ path = torch.tensor([1, 1, 0, 2, 2, 0, 2, 0])+ selected = [select_chunk_frames(path[c.read_start : c.read_end], c, 1) for c in plan]+ result = torch.cat(selected)+ assert torch.equal(result, path)+ collapsed = [v for i, v in enumerate(result.tolist()) if v and (i == 0 or v != result[i - 1])]+ assert collapsed == [1, 2, 2]+++@pytest.mark.unit+def test_word_selection_keeps_real_repetitions_and_exact_start_times():+ plan = make_chunk_plan(600, 10, ChunkingConfig(chunk_size=30, context_size=2))+ first = [+ {'word': 'yes', 'start': 29.2, 'end': 29.4},+ {'word': 'yes', 'start': 29.5, 'end': 29.7},+ {'word': 'later', 'start': 30.2, 'end': 30.4},+ ]+ second = [{'word': 'yes', 'start': 1.5, 'end': 1.7}, {'word': 'later', 'start': 2.2, 'end': 2.4}]+ words = select_chunk_words(first, plan[0], 10) + select_chunk_words(second, plan[1], 10)+ assert [w['word'] for w in words] == ['yes', 'yes', 'later']+ assert words[1]['start'] == 29.5 and words[1]['end'] == 29.7+ assert words[2]['start'] == pytest.approx(30.2)+ assert first[1]['start'] == 29.5 # Inputs must not be changed.+++@pytest.mark.unit+def test_last_chunk_accepts_encoder_dropping_final_partial_hop():+ # 25 frames plus 1 sample: the feature extractor drops the final partial hop.+ last = make_chunk_plan(1280 * 25 + 1, 16000, ChunkingConfig(chunk_size=0.8, context_size=0.16), 1280)[-1]+ assert last.is_last and select_chunk_frames(torch.arange(7), last, 1280).tolist() == [2, 3, 4, 5, 6]+ with pytest.raises(RuntimeError, match='requires 8'):+ select_chunk_frames(torch.arange(6), last, 1280)+ inner = make_chunk_plan(1280 * 25, 16000, ChunkingConfig(chunk_size=0.8, context_size=0.16), 1280)[0]+ with pytest.raises(RuntimeError, match='requires 10'):+ select_chunk_frames(torch.arange(9), inner, 1280)+++@pytest.mark.unit+def test_chunk_plan_has_no_cumulative_timestamp_drift():+ plan = make_chunk_plan(16000 * 30000, 16000, ChunkingConfig(chunk_size=299, context_size=1), 1280)+ assert plan[100].keep_start == 100 * plan[0].keep_end+ assert plan[100].keep_start % 1280 == 0+ assert plan[100].read_start % 1280 == 0+++@pytest.mark.unit+def test_word_ownership_uses_half_open_intervals():+ plan = make_chunk_plan(60, 1, ChunkingConfig(chunk_size=30, context_size=2))+ assert select_chunk_words([{'word': 'boundary', 'start': 29, 'end': 31}], plan[0], 1) == []+ words = select_chunk_words([{'word': 'boundary', 'start': 1, 'end': 3}], plan[1], 1)+ assert len(words) == 1 and words[0]['start'] == 29+++@pytest.mark.unit+def test_last_chunk_keeps_words_timed_past_the_source_end():+ # A transducer can emit the last word on the padded final frame, with a duration past the end.+ plan = make_chunk_plan(45, 1, ChunkingConfig(chunk_size=30, context_size=2))+ words = select_chunk_words([{'word': 'last', 'start': 15, 'end': 21}], plan[1], 1)+ assert [(w['word'], w['start'], w['end']) for w in words] == [('last', 43, 49)]+++@pytest.mark.unit+@pytest.mark.parametrize('boundary_index', [1, 2])+@pytest.mark.parametrize('half_width', [0, 1, 2])+def test_frame_timed_word_on_a_chunk_boundary_has_one_owner(boundary_index, half_width):+ # 16 kHz, 80 ms frames, 0.8 s chunks and 0.16 s context: both neighbours read from nonzero offsets.+ frame = 1280+ plan = make_chunk_plan(16000 * 3, 16000, ChunkingConfig(chunk_size=0.8, context_size=0.16), frame)+ boundary = plan[boundary_index].keep_start // frame+ first, last = boundary - half_width, boundary + half_width # Midpoint exactly on the boundary.+ owners = 0+ for chunk in plan:+ read_first = chunk.read_start // frame+ if first < read_first or last > chunk.read_end // frame:+ continue+ # Transducer word times are frame offsets times the frame duration, relative to the read start.+ word = {'word': 'w', 'start': (first - read_first) * 0.01 * 8, 'end': (last - read_first) * 0.01 * 8}+ owners += len(select_chunk_words([word], chunk, 16000))+ assert owners == 1+++@pytest.mark.unit+def test_word_midpoints_on_half_samples_have_one_owner_whatever_the_read_offset():+ # One-sample words have midpoints on half samples; read starts alternate in parity here.+ plan = make_chunk_plan(40, 10, ChunkingConfig(chunk_size=0.3, context_size=0.1))+ assert {chunk.read_start % 2 for chunk in plan[1:]} == {0, 1}+ for sample in range(40):+ owners = 0+ for chunk in plan:+ if chunk.read_start <= sample < chunk.read_end:+ word = {'word': 'w', 'start': (sample - chunk.read_start) * 0.1}+ word['end'] = word['start'] + 0.1+ owners += len(select_chunk_words([word], chunk, 10))+ assert owners == 1+++@pytest.mark.unit+@pytest.mark.parametrize('num_samples', [12960, 12800 * 4 + 160])+def test_short_remainder_joins_the_previous_chunk(num_samples):+ # A 160-sample remainder is a single feature frame.+ plan = make_chunk_plan(num_samples, 16000, ChunkingConfig(chunk_size=0.8, context_size=0), frame_samples=640)+ last = plan[-1]+ assert len(plan) == num_samples // 12800+ assert (last.keep_start, last.keep_end) == (num_samples - 12800 - 160, num_samples)+ assert all(c.read_end - c.read_start >= 2 * 640 for c in plan)+ assert all(a.keep_end == b.keep_start for a, b in zip(plan, plan[1:]))+ assert all(a.read_end <= b.read_start for a, b in zip(plan, plan[1:]))+++@pytest.mark.unit+@pytest.mark.parametrize('tail_frames', [0.375, 1, 1.5, 2, 3, 4])+def test_no_final_read_reaches_into_the_previous_chunk_without_context(tail_frames):+ num_samples = 15360 + round(tail_frames * 1280)+ plan = make_chunk_plan(num_samples, 16000, ChunkingConfig(chunk_size=0.96, context_size=0), frame_samples=1280)+ assert len(plan) == (1 if tail_frames < 2 else 2)+ assert all(a.read_end <= b.read_start for a, b in zip(plan, plan[1:]))+ assert plan[-1].keep_end == num_samples+++@pytest.mark.unit+@pytest.mark.parametrize('context_size', [0, 0.16])+def test_final_window_with_two_encoder_frames_reads_only_its_context(context_size):+ # 0.9 s chunks of a 1.8 s source leave a 0.84 s final chunk; it needs no extra left context.+ config = ChunkingConfig(chunk_size=0.9, context_size=context_size)+ first, last = make_chunk_plan(28800, 16000, config, frame_samples=1280)+ assert (last.keep_start, last.keep_end) == (first.keep_end, 28800)+ assert last.read_start == last.keep_start - round(context_size * 16000)+++@pytest.mark.unit+@pytest.mark.parametrize(+ 'device',+ [+ 'cpu',+ pytest.param(+ 'cuda',+ marks=[pytest.mark.gpu, pytest.mark.skipif(not torch.cuda.is_available(), reason='CUDA is required.')],+ ),+ ],+)+def test_conformer_ctc_chunking_with_a_one_frame_final_window(device):+ model = _tiny_char_ctc_model().to(device)+ waveform = torch.randn(12960, generator=torch.Generator().manual_seed(5)) * 0.1+ result = model.transcribe(+ waveform,+ chunking=ChunkingConfig(chunk_size=0.8, context_size=0),+ return_hypotheses=True,+ batch_size=2,+ verbose=False,+ )[0]+ with torch.inference_mode():+ _, num_frames = model.forward(+ input_signal=waveform[None].to(device), input_signal_length=torch.tensor([12960], device=device)+ )[:2]+ # The final window owns its single encoder frame; owned frames tile the whole source.+ assert result.y_sequence.shape[0] == int(num_frames[0])+++@pytest.mark.unit+@pytest.mark.parametrize('timestamps', [None, True])+def test_ctc_override_config_takes_precedence_over_the_chunking_argument(timestamps):+ # The override config has no chunking, so the plain path runs and needs the usual timestamp setup.+ model = _tiny_char_ctc_model()+ waveform = torch.randn(32000, generator=torch.Generator().manual_seed(5)) * 0.1++ def transcribe(**kwargs):+ override = TranscribeConfig(timestamps=True, return_hypotheses=True, verbose=False)+ return model.transcribe(waveform, timestamps=timestamps, override_config=override, **kwargs)[0]++ result, plain = transcribe(chunking=ChunkingConfig(chunk_size=0.8, context_size=0.16)), transcribe()+ assert result.text == plain.text and result.timestamp['word'] == plain.timestamp['word']+++def _tiny_char_ctc_model():+ config = OmegaConf.create(+ {+ **_tiny_conformer_config(),+ 'decoder': {+ '_target_': 'nemo.collections.asr.modules.ConvASRDecoder',+ 'feat_in': 8,+ 'num_classes': 3,+ 'vocabulary': ['a', 'b', ' '],+ },+ 'decoding': {'strategy': 'greedy_batch'},+ }+ )+ return EncDecCTCModel(config).eval()+++@pytest.mark.unit+@pytest.mark.parametrize(+ 'config_class',+ [TranscribeConfig, MultiTaskTranscriptionConfig, RNNTPromptTranscribeConfig, HybridRNNTCTCPromptTranscribeConfig],+)+def test_chunking_does_not_shift_positional_transcribe_config_fields(config_class):+ parameters = inspect.signature(config_class).parameters+ assert parameters['chunking'].kind is inspect.Parameter.KEYWORD_ONLY+ positional = [name for name, p in parameters.items() if p.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD]+ # The field order released before planned chunking.+ released = [+ 'use_lhotse',+ 'batch_size',+ 'return_hypotheses',+ 'num_workers',+ 'channel_selector',+ 'augmentor',+ 'timestamps',+ 'verbose',+ 'partial_hypothesis',+ '_internal',+ ]+ assert positional[: len(released)] == released+ internal = InternalTranscribeConfig()+ config = config_class(True, 4, False, None, None, None, None, True, ['partial'], internal)+ assert config.partial_hypothesis == ['partial'] and config._internal is internal and config.chunking is None+++class _LabelCTCModel(TranscriptionMixin, torch.nn.Module):+ """Real mixin and CTC decoder; deterministic acoustic output needs no checkpoint."""++ _transcribe_chunk_validate = EncDecCTCModel._transcribe_chunk_validate+ _transcribe_chunk_ctc_decoding = EncDecCTCModel._transcribe_chunk_ctc_decoding+ _transcribe_chunk_ctc_decoder = EncDecCTCModel._transcribe_chunk_ctc_decoder+ _transcribe_chunk_outputs = EncDecCTCModel._transcribe_chunk_outputs+ _transcribe_chunk_finalize = EncDecCTCModel._transcribe_chunk_finalize+ _transcribe_input_manifest_processing = ASRTranscriptionMixin._transcribe_input_manifest_processing++ def __init__(self, confidence=False, strategy='greedy'):+ super().__init__()+ self.weight = torch.nn.Parameter(torch.zeros(1))+ self.cfg = OmegaConf.create({'sample_rate': 10, 'preprocessor': {'window_stride': 0.1}})+ self.encoder = torch.nn.Identity()+ self.encoder.subsampling_factor = 1+ self.decoder = SimpleNamespace(upsampling_factor=1)+ self.decoding = CTCDecoding(+ OmegaConf.create(+ {+ 'strategy': strategy,+ 'greedy': {'preserve_frame_confidence': confidence},+ 'confidence_cfg': {+ 'preserve_frame_confidence': confidence,+ 'preserve_token_confidence': confidence,+ 'preserve_word_confidence': confidence,+ },+ }+ ),+ vocabulary=['a', 'b', ' '],+ )++ def _transcribe_forward(self, batch, trcfg):+ labels = batch[0].long()+ logits = torch.nn.functional.one_hot(labels, num_classes=4).float() * 10+ factor = self.decoder.upsampling_factor+ return {'logits': logits.repeat_interleave(factor, dim=1).log_softmax(-1), 'logits_len': batch[1] * factor}++ def _setup_transcribe_dataloader(self, config):+ raise AssertionError('Planned chunking must use the common chunk dataset.')++ def _transcribe_output_processing(self, outputs, trcfg):+ raise AssertionError('Planned chunking must use the model output selection hook.')+++@pytest.mark.unit+@pytest.mark.parametrize('batch_size', [1, 2, 5])+@pytest.mark.parametrize('strategy', ['greedy', 'greedy_batch'])+def test_transcribe_chunked_ctc_across_batches(batch_size, strategy):+ model = _LabelCTCModel(strategy=strategy)+ # CTC blank is 3. A repeated b across the join collapses; b separated by blank survives.+ audio = torch.tensor([0.0, 0.0, 3.0, 1.0, 1.0, 3.0, 1.0, 3.0, 2.0, 0.0, 3.0])+ result = model.transcribe(+ [audio, audio], batch_size=batch_size, verbose=False, chunking=ChunkingConfig(chunk_size=0.4, context_size=0.1)+ )+ assert len(result) == 2+ assert [h.text for h in result] == ['abb a', 'abb a']+ assert model.training+++@pytest.mark.unit+def test_transcribe_ctc_confidence_matches_words_after_chunk_selection():+ model = _LabelCTCModel(confidence=True)+ audio = torch.tensor([0.0, 0.0, 3.0, 1.0, 1.0, 3.0, 1.0, 3.0, 2.0, 0.0, 3.0])+ result = model.transcribe(+ audio,+ return_hypotheses=True,+ timestamps=True,+ verbose=False,+ chunking=ChunkingConfig(chunk_size=0.4, context_size=0.1),+ )[0]+ assert result.text == 'abb a'+ assert len(result.word_confidence) == len(result.text.split())+ assert len(result.frame_confidence) == len(audio)+ assert result.y_sequence.shape == (len(audio), 4)+ from nemo.collections.asr.parts.utils.timestamp_utils import process_timestamp_outputs++ # Compare against the normal CTC frame timeline, including its word-boundary convention.+ outputs = model._transcribe_forward((audio.unsqueeze(0), torch.tensor([len(audio)])), None)+ baseline = model.decoding.ctc_decoder_predictions_tensor(+ outputs['logits'], outputs['logits_len'], return_hypotheses=True+ )[0]+ baseline = process_timestamp_outputs(baseline, 1, 0.1)[0]+ assert result.timestamp == baseline.timestamp+ assert result.token_confidence == baseline.token_confidence+ assert result.word_confidence == baseline.word_confidence+++@pytest.mark.unit+def test_ctc_fusion_model_keeps_log_probs():+ model = _LabelCTCModel(strategy='greedy_batch')+ model.decoding.decoding.fusion_models = [object()]+ chunk = make_chunk_plan(4, 10, ChunkingConfig(chunk_size=1.0, context_size=0.0))[0]+ outputs = {'logits': torch.zeros(1, 4, 4), 'logits_len': torch.tensor([4])}+ [part] = model._transcribe_chunk_outputs(outputs, [chunk], 1, ASRTranscriptionMixin.get_transcribe_config())+ assert part.shape == (4, 4)+++@pytest.mark.unit+def test_character_ctc_word_confidence_decodes_token_ids():+ model = _LabelCTCModel(confidence=True)+ labels = torch.tensor([[0, 3, 2, 1, 3]])+ logits = (torch.nn.functional.one_hot(labels, 4).float() * 10).log_softmax(-1)+ result = model.decoding.ctc_decoder_predictions_tensor(logits, torch.tensor([5]), return_hypotheses=True)[0]+ assert result.text == 'a b'+ assert len(result.word_confidence) == 2+++@pytest.mark.unit+def test_ctc_upsampling_keeps_frame_count_and_timestamp_rate():+ from nemo.collections.asr.parts.utils.timestamp_utils import process_timestamp_outputs++ model = _LabelCTCModel(confidence=True)+ model.decoder.upsampling_factor = 2+ audio = torch.tensor([0.0, 0.0, 3.0, 1.0, 1.0, 3.0, 1.0, 3.0, 2.0, 0.0, 3.0])+ result = model.transcribe(+ audio,+ return_hypotheses=True,+ timestamps=True,+ verbose=False,+ chunking=ChunkingConfig(chunk_size=0.4, context_size=0.1),+ )[0]+ outputs = model._transcribe_forward((audio.unsqueeze(0), torch.tensor([len(audio)])), None)+ baseline = model.decoding.ctc_decoder_predictions_tensor(+ outputs['logits'], outputs['logits_len'], return_hypotheses=True+ )[0]+ baseline = process_timestamp_outputs(baseline, 1, 0.05)[0]+ assert result.text == baseline.text+ assert result.y_sequence.shape == (len(audio) * 2, 4)+ assert result.timestamp == baseline.timestamp+++@pytest.mark.unit+def test_cli_chunking_mapping_accepts_hydra_override():+ from examples.asr.transcribe_speech import TranscriptionConfig++ config = OmegaConf.structured(TranscriptionConfig)+ assert not config.chunking+ OmegaConf.set_struct(config, True)+ OmegaConf.update(config, 'chunking', {'chunk_size': 30.0, 'context_size': 2.0}, merge=True, force_add=True)+ assert config.chunking.chunk_size == 30.0+ assert config.chunking.context_size == 2.0+++def _tiny_conformer_config(subsampling='striding', factor=4):+ return {+ 'sample_rate': 16000,+ 'preprocessor': {+ '_target_': 'nemo.collections.asr.modules.AudioToMelSpectrogramPreprocessor',+ 'sample_rate': 16000,+ 'features': 8,+ 'n_fft': 256,+ 'window_size': 0.016,+ 'window_stride': 0.01,+ 'dither': 0.0,+ 'pad_to': 0,+ },+ 'encoder': {+ '_target_': 'nemo.collections.asr.modules.ConformerEncoder',+ 'feat_in': 8,+ 'n_layers': 1,+ 'd_model': 8,+ 'n_heads': 2,+ 'subsampling': subsampling,+ 'subsampling_factor': factor,+ 'subsampling_conv_channels': 8,+ 'ff_expansion_factor': 2,+ 'conv_kernel_size': 3,+ 'dropout': 0.0,+ 'dropout_pre_encoder': 0.0,+ 'dropout_att': 0.0,+ },+ }+++@pytest.mark.unit+# 640 * 50 + r samples. A remainder below one 160-sample hop yields no final feature frame.+@pytest.mark.parametrize('num_samples', [32163, 32001, 32159])+def test_restored_conformer_checkpoint_chunking_with_files_and_tensors(tmp_path, num_samples):+ import soundfile as sf++ config = OmegaConf.create(+ {+ **_tiny_conformer_config(),+ 'decoder': {+ '_target_': 'nemo.collections.asr.modules.ConvASRDecoder',+ 'feat_in': 8,+ 'num_classes': 3,+ 'vocabulary': ['a', 'b', ' '],+ },+ 'decoding': {'strategy': 'greedy_batch'},+ }+ )+ model = EncDecCTCModel(config)+ checkpoint = tmp_path / 'tiny.nemo'+ model.save_to(str(checkpoint))+ restored = EncDecCTCModel.restore_from(str(checkpoint), map_location='cpu')+ waveform = torch.randn(num_samples, generator=torch.Generator().manual_seed(21)) * 0.1+ sf.write(tmp_path / 'audio.wav', waveform.numpy(), 16000, subtype='FLOAT')+ chunking = ChunkingConfig(chunk_size=0.64, context_size=0.16)+ tensor = restored.transcribe(+ waveform, chunking=chunking, return_hypotheses=True, timestamps=True, batch_size=1, verbose=False+ )[0]+ file = restored.transcribe(+ str(tmp_path / 'audio.wav'),+ chunking=chunking,+ return_hypotheses=True,+ timestamps=True,+ batch_size=2,+ verbose=False,+ )[0]+ with torch.inference_mode():+ _, num_frames = restored.forward(input_signal=waveform[None], input_signal_length=torch.tensor([num_samples]))[+ :2+ ]+ # Owned frames tile the encoder output of the whole source: none missing, none repeated.+ assert tensor.y_sequence.shape == file.y_sequence.shape == (int(num_frames[0]), 4)+ assert tensor.text == file.text+ assert torch.allclose(tensor.y_sequence, file.y_sequence, atol=1e-5)+ assert tensor.timestamp == file.timestamp+++@pytest.mark.unit+# 1280 * 25 + r samples. A remainder below one 160-sample hop yields no final feature frame.+@pytest.mark.parametrize('num_samples', [32001, 32159, 32160])+def test_transducer_chunking_accepts_source_end_off_the_frame_grid(num_samples):+ # Character vocabulary, so RNNT only: NeMo's character TDT decoding cannot build timestamps.+ model_type, vocabulary, durations = 'rnnt', ['a', 'b', ' '], []+ config = OmegaConf.create(+ {+ **_tiny_conformer_config('dw_striding', 8),+ 'labels': vocabulary,+ 'model_defaults': {'enc_hidden': 8, 'pred_hidden': 8, 'tdt_durations': durations},+ 'decoder': {+ '_target_': 'nemo.collections.asr.modules.RNNTDecoder',+ 'vocab_size': 3,+ 'prednet': {'pred_hidden': 8, 'pred_rnn_layers': 1},+ },+ 'joint': {+ '_target_': 'nemo.collections.asr.modules.RNNTJoint',+ 'num_classes': 3,+ 'num_extra_outputs': len(durations),+ 'vocabulary': vocabulary,+ 'jointnet': {'joint_hidden': 8, 'activation': 'relu', 'encoder_hidden': 8, 'pred_hidden': 8},+ },+ 'decoding': {+ 'strategy': 'greedy_batch',+ 'greedy': {'max_symbols': 10},+ 'model_type': model_type,+ 'durations': durations,+ },+ 'loss': (+ {'loss_name': 'tdt', 'tdt_kwargs': {'durations': durations, 'sigma': 0.02}}+ if model_type == 'tdt'+ else {'loss_name': 'default'}+ ),+ }+ )+ torch.manual_seed(0)+ model = EncDecRNNTModel(config).eval()+ waveform = torch.randn(num_samples, generator=torch.Generator().manual_seed(5)) * 0.1+ result = model.transcribe(+ waveform,+ chunking=ChunkingConfig(chunk_size=0.8, context_size=0.16),+ timestamps=True,+ batch_size=2,+ verbose=False,+ )[0]+ words = result.timestamp['word']+ assert result.text.split() == [w['word'] for w in words]+ assert all(0 <= w['start'] <= w['end'] <= num_samples / 16000 + 0.08 for w in words)+++@pytest.mark.unit+def test_chunked_file_tensor_and_offset_manifest_match(tmp_path):+ import json++ import soundfile as sf++ model = _LabelCTCModel()+ audio = torch.tensor([0.0, 0.0, 3.0, 1.0, 1.0, 3.0, 1.0, 3.0, 2.0, 0.0, 3.0])+ sf.write(tmp_path / 'audio.wav', audio.numpy(), 10, subtype='FLOAT')+ manifest = tmp_path / 'input.jsonl'+ manifest.write_text(json.dumps({'audio_filepath': 'audio.wav', 'offset': 0.3, 'duration': 0.8, 'text': ''}) + '\n')+ config = ChunkingConfig(chunk_size=0.4, context_size=0.1)+ file_result = model.transcribe([str(tmp_path / 'audio.wav')] * 2, chunking=config, verbose=False)+ tensor_result = model.transcribe([audio] * 2, chunking=config, verbose=False)+ assert [h.text for h in file_result] == [h.text for h in tensor_result]+ offset_result = model.transcribe(str(manifest), chunking=config, verbose=False)+ assert offset_result[0].text == model.transcribe(audio[3:], chunking=config, verbose=False)[0].text+++@pytest.mark.unit+@pytest.mark.parametrize('workers', [0, 2])+def test_lazy_chunk_dataset_preserves_order_with_workers(workers):+ sources = [torch.arange(14), torch.arange(7)]+ plan = ChunkBatches(sources, 1, ChunkingConfig(chunk_size=4, context_size=1), frame_samples=1, batch_size=2)+ loader = torch.utils.data.DataLoader(+ ChunkedAudioDataset(sources, 1), batch_sampler=plan, num_workers=workers, collate_fn=collate_audio_chunks+ )+ order = [(idx, chunk.keep_start) for _, _, ids, chunks, _ in loader for idx, chunk in zip(ids, chunks)]+ assert order == [(0, 0), (0, 4), (0, 8), (0, 12), (1, 0), (1, 4)]+++@pytest.mark.unit+@pytest.mark.parametrize('workers', [0, 2, 4])+def test_manifest_entries_are_parsed_once_whatever_the_worker_count(tmp_path, monkeypatch, workers):+ import json++ import soundfile as sf++ from nemo.collections.common.data.lhotse.nemo_adapters import LazyNeMoIterator++ audio = torch.tensor([0.0, 0.0, 3.0, 1.0, 1.0, 3.0, 1.0, 3.0, 2.0, 0.0, 3.0])+ sf.write(tmp_path / 'a.wav', audio.numpy(), 10, subtype='FLOAT')+ sf.write(tmp_path / 'b.wav', audio[:4].numpy(), 10, subtype='FLOAT')+ manifest = tmp_path / 'input.jsonl'+ # No sample-rate field, so every parse reads the file header; a.wav appears twice.+ entries = [('a.wav', 1.1), ('b.wav', 0.4), ('a.wav', 1.1)]+ manifest.write_text(+ ''.join(json.dumps({'audio_filepath': f, 'duration': d, 'text': ''}) + '\n' for f, d in entries)+ )+ parses = []+ create = LazyNeMoIterator._create_recording++ def counted(self, *args, **kwargs):+ assert torch.utils.data.get_worker_info() is None, 'workers must not parse the manifest'+ parses.append(1)+ return create(self, *args, **kwargs)++ monkeypatch.setattr(LazyNeMoIterator, '_create_recording', counted)+ model = _LabelCTCModel()+ # 3 + 1 + 3 chunks in batches of 2 leave a partial final batch.+ results = model.transcribe(+ str(manifest), chunking=ChunkingConfig(0.4, 0.1), batch_size=2, num_workers=workers, verbose=False+ )+ assert len(parses) == len(entries)+ expected = model.transcribe([audio, audio[:4], audio], chunking=ChunkingConfig(0.4, 0.1), verbose=False)+ assert [h.text for h in results] == [h.text for h in expected]+++@pytest.mark.unit+def test_chunking_failure_restores_model_and_caller_config():+ model = _LabelCTCModel()+ config = ASRTranscriptionMixin.get_transcribe_config()+ config.chunking = ChunkingConfig(chunk_size=-1)+ config.verbose = False+ with pytest.raises(ValueError, match='chunk_size'):+ model.transcribe(torch.ones(10), override_config=config)+ assert model.training+ assert config.chunking.chunk_size == -1+++@pytest.mark.unit+def test_chunking_rejects_external_loader_and_unsupported_decoder():+ model = _LabelCTCModel()+ loader = torch.utils.data.DataLoader([torch.ones(10)])+ with pytest.raises(ValueError, match='external DataLoader'):+ model.transcribe(loader, chunking=ChunkingConfig())+ model.decoding.cfg.strategy = 'beam'+ with pytest.raises(ValueError, match='greedy'):+ model.transcribe(torch.ones(10), chunking=ChunkingConfig())+++class _TinyBPETokenizer:+ vocab = ['▁a', 'b', ' ']+ tokenizer = SimpleNamespace(vocab_size=3)++ def ids_to_tokens(self, ids):+ return [self.vocab[int(i)] for i in ids]++ def tokens_to_text(self, tokens):+ return ''.join(tokens).replace('▁', ' ').strip()++ def ids_to_text(self, ids):+ return self.tokens_to_text(self.ids_to_tokens(ids))++ def text_to_ids(self, text):+ return [0 for _ in text.split()]+++class _ConstantRNNTModel(_LabelCTCModel):+ _transcribe_chunk_validate = EncDecRNNTModel._transcribe_chunk_validate+ _transcribe_chunk_decoding = EncDecRNNTModel._transcribe_chunk_decoding+ _transcribe_chunk_outputs = EncDecRNNTModel._transcribe_chunk_outputs+ _transcribe_chunk_finalize = EncDecRNNTModel._transcribe_chunk_finalize++ def __init__(self, model_type='rnnt', strategy='greedy', duration=1, timestamps=False):+ super().__init__()+ decoder = RNNTDecoder({'pred_hidden': 4, 'pred_rnn_layers': 1}, vocab_size=3)+ joint = RNNTJoint(+ {'encoder_hidden': 1, 'pred_hidden': 4, 'joint_hidden': 4, 'activation': 'relu'},+ num_classes=3,+ num_extra_outputs=3 if model_type == 'tdt' else 0,+ )+ with torch.no_grad():+ for parameter in joint.parameters():+ parameter.zero_()+ joint.joint_net[-1].bias[0] = 10+ if model_type == 'tdt':+ joint.joint_net[-1].bias[5 if duration == 1 else 6] = 10+ self.decoder, self.joint = decoder, joint+ self.decoding = RNNTBPEDecoding(+ OmegaConf.create(+ {+ 'strategy': strategy,+ 'model_type': model_type,+ 'durations': [0, 1, 3] if model_type == 'tdt' else [],+ # EncDecRNNTModel.transcribe() sets this when timestamps are requested.+ 'compute_timestamps': timestamps,+ # Non-batched TDT greedy confidence reads the alignments.+ 'preserve_alignments': model_type == 'tdt' and strategy == 'greedy',+ 'greedy': {'max_symbols_per_step': 1, 'preserve_frame_confidence': True},+ 'beam': {'beam_size': 2},+ 'confidence_cfg': {+ 'preserve_frame_confidence': True,+ 'preserve_token_confidence': True,+ 'preserve_word_confidence': True,+ },+ }+ ),+ decoder,+ joint,+ tokenizer=_TinyBPETokenizer(),+ )++ def _transcribe_forward(self, batch, trcfg):+ return {'encoded': batch[0].unsqueeze(1), 'encoded_len': batch[1]}+++@pytest.mark.unit+@pytest.mark.parametrize('model_type', ['rnnt', 'tdt'])+@pytest.mark.parametrize('timestamps', [False, True])+@pytest.mark.parametrize('strategy', ['greedy', 'greedy_batch'])+def test_rnnt_chunks_keep_each_word_once_at_its_time(model_type, timestamps, strategy):+ # One word per frame; every read window is decoded, and only owned words are kept.+ model = _ConstantRNNTModel(model_type=model_type, strategy=strategy)+ result = model.transcribe(+ torch.ones(11),+ return_hypotheses=True,+ timestamps=timestamps,+ verbose=False,+ chunking=ChunkingConfig(chunk_size=0.4, context_size=0.1),+ )[0]+ assert result.text.split() == ['a'] * 11+ assert len(result.y_sequence) == 11+ if timestamps:+ assert [w['start'] for w in result.timestamp['word']] == pytest.approx([k / 10 for k in range(11)])+ assert [w['start_offset'] for w in result.timestamp['word']] == list(range(11))+ assert not model.decoding.compute_timestamps # Word times come from a call-local decoding.+++@pytest.mark.unit+@pytest.mark.parametrize('compute_timestamps', [False, True])+@pytest.mark.parametrize('timestamp_type', ['char', 'segment'])+@pytest.mark.parametrize('timestamps', [None, True])+def test_rnnt_chunking_computes_word_times_for_any_timestamp_type(compute_timestamps, timestamp_type, timestamps):+ model = _ConstantRNNTModel(strategy='greedy_batch', timestamps=compute_timestamps)+ with open_dict(model.decoding.cfg):+ model.decoding.cfg.rnnt_timestamp_type = timestamp_type+ decoding = model.decoding+ result = model.transcribe(+ torch.ones(11),+ timestamps=timestamps,+ verbose=False,+ chunking=ChunkingConfig(chunk_size=0.4, context_size=0.1),+ )[0]+ assert result.text.split() == ['a'] * 11+ if timestamps:+ assert [w['start_offset'] for w in result.timestamp['word']] == list(range(11))+ # Selection uses call-local word times; the model's decoding is unchanged.+ assert model.decoding is decoding and decoding.cfg.rnnt_timestamp_type == timestamp_type+ assert decoding.compute_timestamps is compute_timestamps+++@pytest.mark.unit+def test_rnnt_chunking_rejects_n_best():+ model = _ConstantRNNTModel(strategy='greedy_batch')+ model.decoding.cfg = OmegaConf.create({'strategy': 'beam', 'beam': {'return_best_hypothesis': False}})+ with pytest.raises(ValueError, match='one best hypothesis'):+ model.transcribe(torch.ones(11), chunking=ChunkingConfig())+++@pytest.mark.unit+def test_rnnt_chunking_rejects_restart_after_tokens():+ model = _ConstantRNNTModel(strategy='greedy_batch')+ model.decoding.restart_token_ids = [0] # Restart decoding encodes inside output processing, not per chunk.+ with pytest.raises(ValueError, match='restart_after_tokens'):+ model.transcribe(torch.ones(11), chunking=ChunkingConfig())+++class _FramewiseRNNTModel(_ConstantRNNTModel):+ """Random prediction and joint networks over a context-free encoder."""++ def __init__(self, model_type, strategy):+ super().__init__(model_type=model_type, strategy=strategy)+ generator = torch.Generator().manual_seed(7)+ with torch.no_grad():+ for parameter in [*self.decoder.parameters(), *self.joint.parameters()]:+ parameter.copy_(torch.randn(parameter.shape, generator=generator))+++@pytest.mark.unit+@pytest.mark.parametrize('model_type', ['rnnt', 'tdt'])+@pytest.mark.parametrize('strategy', ['greedy_batch', 'malsd_batch'])+@pytest.mark.parametrize(+ 'device',+ [+ 'cpu',+ pytest.param(+ 'cuda',+ marks=[pytest.mark.gpu, pytest.mark.skipif(not torch.cuda.is_available(), reason='CUDA is required.')],+ ),+ ],+)+def test_rnnt_chunking_is_batch_invariant_and_one_window_matches_plain_decoding(model_type, strategy, device):+ model = _FramewiseRNNTModel(model_type, strategy).to(device)+ generator = torch.Generator().manual_seed(3)+ sources = [torch.randn(n, generator=generator) * 4 for n in (23, 9, 4, 17)]+ chunked = [+ [h.text for h in model.transcribe(sources, batch_size=b, verbose=False, chunking=ChunkingConfig(0.4, 0.2))]+ for b in (1, 3, 8)+ ]+ assert chunked[0] == chunked[1] == chunked[2]+ # A window that covers the whole source is one plain decode of that source.+ whole = model.transcribe(sources, batch_size=8, verbose=False, chunking=ChunkingConfig(10.0, 0.0))+ num_words = 0+ for source, hyp in zip(sources, whole):+ encoded = source.to(device)[None, None]+ reference = model.decoding.rnnt_decoder_predictions_tensor(+ encoded, torch.tensor([len(source)], device=device), return_hypotheses=True+ )[0]+ assert hyp.text.split() == reference.text.split()+ num_words += len(reference.text.split())+ assert num_words >= 3 # The comparison needs real emissions.+++class _AlignedAEDModel(_LabelCTCModel):+ _transcribe_chunk_validate = EncDecMultiTaskModel._transcribe_chunk_validate+ _transcribe_chunk_batch = EncDecMultiTaskModel._transcribe_chunk_batch+ _transcribe_chunk_outputs = EncDecMultiTaskModel._transcribe_chunk_outputs+ _transcribe_chunk_finalize = EncDecMultiTaskModel._transcribe_chunk_finalize++ def __init__(self):+ super().__init__()+ self.timestamps_asr_model = torch.nn.Identity()+ self.prompt = SimpleNamespace(+ get_default_dialog_slots=lambda: [{'role': 'user', 'slots': {'source_lang': 'de', 'target_lang': 'de'}}]+ )+ self.tokenizer = SimpleNamespace(text_to_ids=lambda text: [ord(c) for c in text])++ self.keep_ctc_words = lambda words: words++ @staticmethod+ def _words(audio, length):+ # One word per sample: 'ja' for 1, otherwise a word naming the sample value.+ return ['ja' if int(x) == 1 else f'w{int(x)}' for x in audio[: int(length)]]++ def _transcribe_forward(self, batch, trcfg):+ return {'batch': batch}++ def _transcribe_output_processing(self, outputs, trcfg):+ assert not trcfg.timestamps and not trcfg.enable_chunking+ audio, lengths = outputs['batch'][:2]+ return [+ Hypothesis(score=-1, y_sequence=None, text=' '.join(self._words(a, n))) for a, n in zip(audio, lengths)+ ]++ def _transcribe_chunk_ctc_words(self, audio, lengths):+ timed = [+ [{'word': w, 'start': k / 10, 'end': (k + 1) / 10} for k, w in enumerate(self._words(a, n))]+ for a, n in zip(audio, lengths)+ ]+ return [self.keep_ctc_words(words) for words in timed]+++@pytest.mark.unit+def test_aed_adapter_keeps_repeated_words_with_original_duration():+ from nemo.collections.asr.models.aed_multitask_models import MultiTaskTranscriptionConfig++ model = _AlignedAEDModel()+ config = MultiTaskTranscriptionConfig(+ chunking=ChunkingConfig(chunk_size=0.4, context_size=0.1),+ timestamps=True,+ verbose=False,+ batch_size=2,+ num_workers=0,+ )+ result = model.transcribe(torch.ones(11), override_config=config)[0]+ assert result.text.split() == ['ja'] * 11+ assert [w['start'] for w in result.timestamp['word']] == pytest.approx([i / 10 for i in range(11)])+ assert all(w['end'] - w['start'] == pytest.approx(0.1) for w in result.timestamp['word'])+ assert config.enable_chunking # The new path must not change the caller's legacy setting.+ assert model.training+++@pytest.mark.unit+def test_aed_adapter_keeps_words_the_ctc_model_misses():+ # Fast speech: the CTC model times only every third word; the AED words still all survive once.+ model = _AlignedAEDModel()+ model.keep_ctc_words = lambda words: words[::3]+ audio = torch.arange(2, 25).float()+ result = model.transcribe(audio, override_config=_aed_config())[0]+ assert result.text.split() == [f'w{i}' for i in range(2, 25)]+++@pytest.mark.unit+def test_aed_without_ctc_model_stitches_overlapping_windows():+ model = _AlignedAEDModel()+ model.timestamps_asr_model = None+ audio = torch.arange(2, 25).float()+ result = model.transcribe(audio, override_config=_aed_config())[0]+ assert result.text.split() == [f'w{i}' for i in range(2, 25)]+ with pytest.raises(ValueError, match='CTC timestamp model'):+ model.transcribe(audio, override_config=_aed_config(timestamps=True))+++@pytest.mark.unit+def test_aed_without_ctc_model_keeps_a_word_once_after_a_short_final_chunk():+ # 0.9 s chunks without context leave a 0.9 s final chunk. A read reaching into the previous+ # chunk repeats one word there, too short a shared run to stitch, so it appears twice.+ model = _AlignedAEDModel()+ model.timestamps_asr_model = None+ audio = torch.arange(2, 20).float()+ config = _aed_config()+ config.chunking = ChunkingConfig(chunk_size=0.9, context_size=0)+ result = model.transcribe(audio, override_config=config)[0]+ assert result.text.split() == [f'w{i}' for i in range(2, 20)]+++@pytest.mark.unit+def test_aed_without_ctc_model_keeps_a_word_once_after_a_remainder_under_two_frames():+ # A one-frame remainder used to re-read one word of the previous chunk, which was kept twice.+ model = _AlignedAEDModel()+ model.timestamps_asr_model = None+ audio = torch.arange(2, 12).float()+ config = _aed_config()+ config.chunking = ChunkingConfig(chunk_size=0.9, context_size=0)+ result = model.transcribe(audio, override_config=config)[0]+ assert result.text.split() == [f'w{i}' for i in range(2, 12)]+++def _aed_config(**kwargs):+ from nemo.collections.asr.models.aed_multitask_models import MultiTaskTranscriptionConfig++ return MultiTaskTranscriptionConfig(+ chunking=ChunkingConfig(chunk_size=0.4, context_size=0.1), verbose=False, batch_size=2, **kwargs+ )+++@pytest.mark.unit+def test_transfer_word_times_matches_and_fills_gaps():+ timed = [{'word': 'hello', 'start': 0.0, 'end': 1.0}, {'word': 'world', 'start': 2.0, 'end': 3.0}]+ words = transfer_word_times(['Hello,', 'big', 'world', 'again'], timed, duration=5.0)+ assert [(w['start'], w['end']) for w in words] == [(0.0, 1.0), (1.0, 2.0), (2.0, 3.0), (3.0, 5.0)]+ assert [(w['start'], w['end']) for w in transfer_word_times(['a', 'b'], [], duration=4.0)] == [(0, 2), (2, 4)]+++@pytest.mark.unit+@pytest.mark.parametrize(+ 'decoding, rejected',+ [+ ({'strategy': 'beam', 'beam': {'beam_size': 2, 'return_best_hypothesis': False}}, True),+ ({'strategy': 'greedy', 'greedy': {'temperature': 1.0, 'n_samples': 2}}, True),+ ({'strategy': 'greedy_batch', 'greedy': {'temperature': 1.0, 'n_samples': 2}}, True),+ ({'strategy': 'greedy', 'greedy': {'temperature': 1.0, 'n_samples': 1}}, False),+ ({'strategy': 'greedy_batch', 'greedy': {'temperature': None, 'n_samples': 2}}, False),+ ({'strategy': 'beam', 'beam': {'beam_size': 2, 'return_best_hypothesis': True}}, False),+ ],+)+def test_aed_adapter_rejects_multiple_outputs_per_chunk(decoding, rejected):+ model = _AlignedAEDModel()+ model.decoding.cfg = OmegaConf.create(decoding)+ forward = model._transcribe_forward+ calls = []+ model._transcribe_forward = lambda *args: calls.append(1) or forward(*args)+ if rejected:+ with pytest.raises(ValueError, match='one best hypothesis'):+ model.transcribe(torch.ones(11), override_config=_aed_config())+ assert not calls # Rejected before any forward pass.+ else:+ assert model.transcribe(torch.ones(11), override_config=_aed_config())[0].text.split() == ['ja'] * 11+++@pytest.mark.unit+def test_aed_adapter_accepts_wrapped_and_unset_prompt_languages():+ from nemo.collections.asr.models.aed_multitask_models import MultiTaskTranscriptionConfig++ config = MultiTaskTranscriptionConfig(+ chunking=ChunkingConfig(chunk_size=0.4, context_size=0.1),+ prompt={'source_lang': '<|de|>', 'target_lang': None},+ verbose=False,+ )+ result = _AlignedAEDModel().transcribe(torch.ones(11), override_config=config)[0]+ assert result.text.split() == ['ja'] * 11+++@pytest.mark.unit+def test_generator_close_restores_state_and_emits_complete_utterances():+ model = _LabelCTCModel()+ config = ASRTranscriptionMixin.get_transcribe_config()+ config.chunking = ChunkingConfig(chunk_size=0.4)+ config.verbose = False+ config.num_workers = 0+ generator = model.transcribe_generator([torch.zeros(11), torch.zeros(11)], override_config=config)+ assert next(generator)[0].text == 'a'+ assert not model.training+ generator.close()+ assert model.training+++@pytest.mark.unit+def test_empty_manifest_raises_and_restores_state(tmp_path):+ manifest = tmp_path / 'empty.jsonl'+ manifest.write_text('')+ model = _LabelCTCModel()+ with pytest.raises(ValueError, match='no audio entries'):+ model.transcribe(str(manifest), chunking=ChunkingConfig(), verbose=False)+ assert model.training+++class _HybridCTCModel(_LabelCTCModel):+ _transcribe_chunk_ctc_decoding = EncDecHybridRNNTCTCModel._transcribe_chunk_ctc_decoding+ _transcribe_chunk_ctc_decoder = EncDecHybridRNNTCTCModel._transcribe_chunk_ctc_decoder+ _transcribe_chunk_validate = EncDecHybridRNNTCTCModel._transcribe_chunk_validate+ _transcribe_chunk_outputs = EncDecHybridRNNTCTCModel._transcribe_chunk_outputs+ _transcribe_chunk_finalize = EncDecHybridRNNTCTCModel._transcribe_chunk_finalize++ def __init__(self):+ super().__init__()+ self.cur_decoder = 'ctc'+ self.ctc_decoder = self.decoder+ self.ctc_decoding = self.decoding+ self.decoding = SimpleNamespace(cfg=OmegaConf.create({'strategy': 'beam'}))+++@pytest.mark.unit+def test_hybrid_chunking_uses_selected_ctc_head():+ model = _HybridCTCModel()+ result = model.transcribe(+ torch.tensor([0.0, 1.0, 1.0, 1.0, 1.0, 3.0, 1.0]),+ verbose=False,+ chunking=ChunkingConfig(chunk_size=0.4, context_size=0.1),+ )+ assert result[0].text == 'abb'+++@pytest.mark.unit+def test_prompt_conditioned_chunk_batch_preserves_per_utterance_language():+ model = SimpleNamespace(resolve_prompt_language=lambda lang: {None: 0, 'de': 1, 'en': 2}[lang])+ cuts = [SimpleNamespace(supervisions=[SimpleNamespace(language=lang)]) for lang in ['de', 'en']]+ config = SimpleNamespace(target_lang=None)+ batch = PromptStreamingMixin._transcribe_chunk_batch(+ model, torch.zeros(2, 10), torch.tensor([10, 10]), cuts, config+ )+ assert batch[4].tolist() == [1, 2]+ config.target_lang = 'en'+ batch = PromptStreamingMixin._transcribe_chunk_batch(+ model, torch.zeros(2, 10), torch.tensor([10, 10]), cuts, config+ )+ assert batch[4].tolist() == [2, 2]+++@pytest.mark.unit+@pytest.mark.gpu+@pytest.mark.skipif(not torch.cuda.is_available(), reason='CUDA is required.')+@pytest.mark.parametrize('kind', ['ctc', 'rnnt', 'tdt'])+def test_chunk_selection_and_metadata_on_cuda(kind):+ if kind == 'ctc':+ model = _LabelCTCModel(confidence=True, strategy='greedy_batch')+ audio = torch.tensor([0.0, 0.0, 3.0, 1.0, 1.0, 3.0, 1.0, 3.0, 2.0, 0.0, 3.0])+ expected_words = ['abb', 'a']+ else:+ model = _ConstantRNNTModel(model_type=kind, strategy='greedy_batch')+ audio = torch.ones(11)+ expected_words = ['a'] * 11+ model = model.to('cuda')+ result = model.transcribe(+ audio,+ return_hypotheses=True,+ timestamps=True,+ verbose=False,+ chunking=ChunkingConfig(chunk_size=0.4, context_size=0.1),+ )[0]+ assert result.text.split() == expected_words+ if kind == 'ctc': # Transducer chunks are assembled from words, without token confidence.+ assert len(result.word_confidence) == len(expected_words)+ assert result.y_sequence.device.type == 'cpu'