NVIDIA-NeMo/Speech · #16632
fix(asr): keep decoding after <EOU> on multi-utterance audio
examples/asr/asr_eou/README.md14 + / 0 −
@@ -297,6 +297,20 @@ python speech_to_text_eou_eval.py \ The script will show the WER metrics along with EOU metrics like latency, early cutoff rate, miss detection rate, etc. +### 4.1 Inference on audio with multiple utterances++The model is trained on single-utterance samples, so by default it stops emitting tokens after the first `<EOU>`. To transcribe audio with multiple utterances, set `decoding.restart_after_tokens`; the encoder and decoder then restart from a fresh state after each of these tokens:+```python+from omegaconf import open_dict++decoding_cfg = model.cfg.decoding+with open_dict(decoding_cfg):+ decoding_cfg.restart_after_tokens = ["<EOU>", "<EOB>"]+model.change_decoding_strategy(decoding_cfg)+model.transcribe(["long_audio.wav"])+```+With this option, `transcribe()` runs batched cache-aware streaming over the audio, so its cost stays linear in the audio length. For streaming inference, use `rnnt_decoding.restart_after_tokens='["<EOU>","<EOB>"]'` with `speech_to_text_cache_aware_streaming_infer.py`. The option requires a cache-aware streaming model and `greedy_batch` decoding; other decoding strategies, buffered (no-cache) streaming, and `partial_hypothesis` are not supported. With this option, `Hypothesis.length` is the total number of encoder frames decoded for the audio (also in streaming).+ ## 5. Model deployment with voice agent nemo/collections/asr/models/asr_eou_models.py2 + / 6 −
@@ -423,9 +423,7 @@ def _transcribe_forward(self, batch: Any, trcfg: TranscribeConfig): else: signal = batch[0] signal_len = batch[1]- encoded, encoded_len = self.forward(input_signal=signal, input_signal_length=signal_len)- output = dict(encoded=encoded, encoded_len=encoded_len)- return output+ return self._transcribe_encode(signal, signal_len, trcfg) def training_step(self, batch: AudioToTextEOUBatch, batch_nb): # Reset access registry@@ -771,9 +769,7 @@ def _transcribe_forward(self, batch: Any, trcfg: TranscribeConfig): else: signal = batch[0] signal_len = batch[1]- encoded, encoded_len = self.forward(input_signal=signal, input_signal_length=signal_len)- output = dict(encoded=encoded, encoded_len=encoded_len)- return output+ return self._transcribe_encode(signal, signal_len, trcfg) def training_step(self, batch: AudioToTextEOUBatch, batch_nb): signal = batch.audio_signalnemo/collections/asr/models/rnnt_models.py30 + / 14 −
@@ -949,24 +949,40 @@ def multi_test_epoch_end(self, outputs, dataloader_idx: int = 0): """ Transcription related methods """ def _transcribe_forward(self, batch: Any, trcfg: TranscribeConfig):- encoded, encoded_len = self.forward(input_signal=batch[0], input_signal_length=batch[1])- output = dict(encoded=encoded, encoded_len=encoded_len)- return output+ return self._transcribe_encode(batch[0], batch[1], trcfg)++ def _transcribe_encode(self, signal: torch.Tensor, signal_len: torch.Tensor, trcfg: TranscribeConfig) -> dict:+ """Encode audio for ``transcribe()``; with ``decoding.restart_after_tokens``, only extract features."""+ if getattr(self, 'cur_decoder', 'rnnt') == 'rnnt' and getattr(self.decoding, 'restart_token_ids', None):+ if trcfg.partial_hypothesis is not None:+ raise NotImplementedError("`partial_hypothesis` is not supported with `restart_after_tokens`.")+ processed_signal, processed_signal_length = self.preprocessor(input_signal=signal, length=signal_len)+ return dict(processed_signal=processed_signal, processed_signal_length=processed_signal_length)+ encoded, encoded_len = self.forward(input_signal=signal, input_signal_length=signal_len)+ return dict(encoded=encoded, encoded_len=encoded_len) def _transcribe_output_processing( self, outputs, trcfg: TranscribeConfig ) -> Union[List['Hypothesis'], List[List['Hypothesis']]]:- encoded = outputs.pop('encoded')- encoded_len = outputs.pop('encoded_len')-- hyp = self.decoding.rnnt_decoder_predictions_tensor(- encoded,- encoded_len,- return_hypotheses=trcfg.return_hypotheses,- partial_hypotheses=trcfg.partial_hypothesis,- )- # cleanup memory- del encoded, encoded_len+ if 'processed_signal' in outputs:+ with torch.inference_mode():+ hyp = self.cache_aware_transcribe_with_restart(+ outputs.pop('processed_signal'),+ outputs.pop('processed_signal_length'),+ self.decoding.restart_token_ids,+ )+ hyp = self.decoding.postprocess_hypotheses(hyp, return_hypotheses=trcfg.return_hypotheses)+ else:+ encoded = outputs.pop('encoded')+ encoded_len = outputs.pop('encoded_len')+ hyp = self.decoding.rnnt_decoder_predictions_tensor(+ encoded,+ encoded_len,+ return_hypotheses=trcfg.return_hypotheses,+ partial_hypotheses=trcfg.partial_hypothesis,+ )+ # cleanup memory+ del encoded, encoded_len if trcfg.timestamps: hyp = process_timestamp_outputs(nemo/collections/asr/parts/mixins/mixins.py282 + / 7 −
@@ -18,7 +18,7 @@ import tarfile from abc import ABC, abstractmethod from pathlib import PurePosixPath-from typing import List, Optional+from typing import List, Optional, Sequence, Union import torch from omegaconf import DictConfig, OmegaConf, open_dict@@ -27,6 +27,7 @@ import nemo.collections.asr.models as asr_models from nemo.collections.asr.parts.mixins.asr_adapter_mixins import ASRAdapterModelMixin from nemo.collections.asr.parts.mixins.streaming import StreamingEncoder+from nemo.collections.asr.parts.submodules.transducer_decoding.label_looping_base import LabelLoopingStateItem from nemo.collections.asr.parts.utils import asr_module_utils from nemo.collections.asr.parts.utils.prompt_language_utils import resolve_prompt_index from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis@@ -754,12 +755,31 @@ def conformer_stream_step( all_hyp_or_transcribed_texts.append(decoded_out[0]) best_hyp = None else:- best_hyp = self.decoding.rnnt_decoder_predictions_tensor(- encoder_output=encoded,- encoded_lengths=encoded_len,- return_hypotheses=True,- partial_hypotheses=previous_hypotheses,- )+ restart_token_ids = getattr(self.decoding, 'restart_token_ids', None)+ if restart_token_ids:+ if bypass_pre_encode:+ raise NotImplementedError("`restart_after_tokens` is not supported with `bypass_pre_encode`.")+ hyps, (cache_last_channel_next, cache_last_time_next, cache_last_channel_next_len) = (+ self.decode_chunk_with_restart(+ encoded=encoded,+ encoded_len=encoded_len,+ processed_signal=processed_signal,+ processed_signal_length=processed_signal_length,+ hypotheses=previous_hypotheses,+ caches=(cache_last_channel_next, cache_last_time_next, cache_last_channel_next_len),+ restart_token_ids=restart_token_ids,+ keep_all_outputs=keep_all_outputs,+ drop_extra_pre_encoded=drop_extra_pre_encoded or 0,+ )+ )+ best_hyp = self.decoding.postprocess_hypotheses(hyps, return_hypotheses=True)+ else:+ best_hyp = self.decoding.rnnt_decoder_predictions_tensor(+ encoder_output=encoded,+ encoded_lengths=encoded_len,+ return_hypotheses=True,+ partial_hypotheses=previous_hypotheses,+ ) greedy_predictions = [hyp.y_sequence for hyp in best_hyp] all_hyp_or_transcribed_texts = best_hyp@@ -778,6 +798,200 @@ def conformer_stream_step( return tuple(result) + def decode_chunk_with_restart(+ self,+ encoded: Tensor,+ encoded_len: Tensor,+ processed_signal: Tensor,+ processed_signal_length: Tensor,+ hypotheses: Optional[List[Optional[Hypothesis]]],+ caches: tuple,+ restart_token_ids: List[int],+ keep_all_outputs: Union[bool, List[bool]] = True,+ drop_extra_pre_encoded: int = 0,+ ) -> tuple:+ """+ Greedy-decode one cache-aware streaming chunk, restarting from a fresh state after each token from+ ``decoding.restart_after_tokens`` (e.g. ``<EOU>``). End-of-utterance models are trained on single utterances+ and stop emitting tokens after ``<EOU>`` otherwise.++ For a stream that emits a restart token at chunk frame ``t``, the frames up to ``t`` are re-decoded from the+ previous decoder state, then the decoder state is reset and the rest of the chunk is re-encoded with a fresh+ encoder cache (repeated as needed). A restart token on the last frame resets the state for the next chunk.+ The ``length`` of the returned hypotheses is the total number of encoder frames decoded for the stream.++ Args:+ encoded: encoder output of the chunk [B, D, T].+ encoded_len: number of valid encoder frames per stream [B].+ processed_signal: chunk features [B, F, T_feat] (including the pre-encode cache).+ processed_signal_length: number of valid features per stream [B].+ hypotheses: raw hypotheses carried from the previous chunk (updated in place), or None.+ caches: (cache_last_channel, cache_last_time, cache_last_channel_len) after encoding the chunk.+ restart_token_ids: ids of the restart tokens.+ keep_all_outputs: ``keep_all_outputs`` of the encoder step, for the whole batch or per stream.+ drop_extra_pre_encoded: number of encoder frames dropped from the beginning of the chunk.++ Returns:+ Tuple of (raw hypotheses, updated caches).+ """+ decoding_computer = getattr(self.decoding.decoding, 'decoding_computer', None)+ if decoding_computer is None:+ raise NotImplementedError("`restart_after_tokens` requires `greedy_batch` decoding.")+ batch_size = encoded.shape[0]+ if isinstance(keep_all_outputs, bool):+ keep_all_outputs = [keep_all_outputs] * batch_size+ restart_token_ids = set(restart_token_ids)+ hypotheses = list(hypotheses) if hypotheses is not None else [None] * batch_size+ start_frames = _decoded_lengths(hypotheses)+ continuations = self._decode_continuation(encoded, encoded_len, hypotheses)+ num_frames_list, signal_len_list = encoded_len.tolist(), processed_signal_length.tolist()+ caches = list(caches)+ for b in range(batch_size):+ enc, num_frames, cont = encoded[b : b + 1], num_frames_list[b], continuations[b]+ signal, signal_len = processed_signal[b : b + 1], signal_len_list[b]+ start_frame, drop = start_frames[b], drop_extra_pre_encoded+ while True:+ prev = hypotheses[b]+ restart_frame = _find_restart_frame(cont, restart_token_ids, start_frame + num_frames)+ if restart_frame is not None: # re-decode only up to the restart frame+ restart_frame -= start_frame+ cont = self._decode_continuation(enc[:, :, : restart_frame + 1], [restart_frame + 1], [prev])[0]+ if prev is None:+ hypotheses[b] = cont+ else:+ _append_hypothesis_segment(prev, cont)+ if restart_frame is None:+ if any(int(token) in restart_token_ids for token in cont.y_sequence): # on the last frame+ _reset_hypothesis_decoder_state(hypotheses[b], decoding_computer)+ caches = _replace_cache_row(caches, b)+ break+ start_frame += restart_frame + 1+ _reset_hypothesis_decoder_state(hypotheses[b], decoding_computer)+ # causal subsampling: (pre-drop) output frame k ends at feature k * subsampling_factor+ tail_start = (restart_frame + 1 + drop) * self.encoder.subsampling_factor+ signal, signal_len = signal[:, :, tail_start:signal_len], signal_len - tail_start+ drop = 0 # the rest of the chunk is encoded as the beginning of a new stream+ enc, enc_len, new_cache = self._encode_fresh(+ signal, torch.tensor([signal_len], device=enc.device), keep_all_outputs[b]+ )+ caches = _replace_cache_row(caches, b, new_cache)+ if not keep_all_outputs[b]: # keep only the remaining frames of the chunk, as in the original stream+ enc_len = enc_len.clamp(max=num_frames - restart_frame - 1)+ num_frames = int(enc_len[0])+ cont = self._decode_continuation(enc, enc_len, [hypotheses[b]])[0]+ return hypotheses, tuple(caches)++ def _decode_continuation(+ self, encoded: Tensor, encoded_len, hypotheses: List[Optional[Hypothesis]]+ ) -> List[Hypothesis]:+ """Raw greedy decoding of new frames, continuing from the decoder states of ``hypotheses`` (not modified)."""+ encoded_len = torch.as_tensor(encoded_len, device=encoded.device)+ states = [+ (+ None+ if hyp is None+ else Hypothesis(+ score=0.0,+ y_sequence=torch.empty(0, dtype=torch.long),+ timestamp=torch.empty(0, dtype=torch.long),+ dec_state=hyp.dec_state,+ last_token=hyp.last_token,+ biasing_cfg=hyp.biasing_cfg,+ )+ )+ for hyp in hypotheses+ ]+ return self.decoding.decoding(encoder_output=encoded, encoded_lengths=encoded_len, partial_hypotheses=states)[+ 0+ ]++ def _encode_fresh(self, signal: Tensor, signal_length: Tensor, keep_all_outputs: bool):+ """Cache-aware encoding of one stream's features starting from the initial encoder cache."""+ cache = self.encoder.get_initial_cache_state(batch_size=1, dtype=signal.dtype, device=signal.device)+ encoded, encoded_len, *new_cache = self.encoder.cache_aware_stream_step(+ processed_signal=signal,+ processed_signal_length=signal_length,+ cache_last_channel=cache[0],+ cache_last_time=cache[1],+ cache_last_channel_len=cache[2],+ keep_all_outputs=keep_all_outputs,+ drop_extra_pre_encoded=0,+ )+ return self._apply_prompt_to_encoded(encoded), encoded_len, new_cache++ def cache_aware_transcribe_with_restart(+ self, processed_signal: Tensor, processed_signal_length: Tensor, restart_token_ids: List[int]+ ) -> List[Hypothesis]:+ """+ Offline decoding with restarts after ``decoding.restart_after_tokens``, run as batched cache-aware streaming+ over the features, so that the cost stays linear in the audio length. All utterances of the batch advance+ through each chunk together; an utterance leaves the batch after its last chunk.++ Returns:+ Raw (not post-processed) hypotheses.+ """+ if not isinstance(self.encoder, StreamingEncoder):+ raise NotImplementedError("`restart_after_tokens` requires a cache-aware streaming encoder.")+ if self.encoder.streaming_cfg is None:+ self.encoder.setup_streaming_params()+ cfg = self.encoder.streaming_cfg++ def size(value, step):+ return (value[0] if step == 0 else value[1]) if isinstance(value, list) else value++ lengths = processed_signal_length.tolist()+ if min(lengths) <= 0:+ raise ValueError("`restart_after_tokens` requires non-empty audio.")+ hypotheses = [None] * len(lengths)+ active = list(range(len(lengths))) # utterances that have not reached their last chunk yet+ caches = self.encoder.get_initial_cache_state(+ batch_size=len(active), dtype=processed_signal.dtype, device=processed_signal.device+ )+ position, step = 0, 0+ while active:+ chunk_start = position - size(cfg.pre_encode_cache_size, step)+ chunk_end = position + size(cfg.chunk_size, step)+ drop_extra_pre_encoded = 0 if step == 0 else cfg.drop_extra_pre_encoded+ chunk = processed_signal[active, :, max(0, chunk_start) : chunk_end]+ if chunk_start < 0: # zero pre-encode cache at the beginning, as in streaming+ chunk = torch.nn.functional.pad(chunk, (-chunk_start, 0))+ chunk_len = [min(chunk_end, lengths[b]) - chunk_start for b in active]+ is_last = [chunk_end >= lengths[b] for b in active]+ encoded, encoded_len, *caches = self.encoder.cache_aware_stream_step(+ processed_signal=chunk,+ processed_signal_length=torch.tensor(chunk_len, device=chunk.device),+ cache_last_channel=caches[0],+ cache_last_time=caches[1],+ cache_last_channel_len=caches[2],+ keep_all_outputs=any(is_last),+ drop_extra_pre_encoded=drop_extra_pre_encoded,+ )+ if any(is_last) and not all(is_last) and cfg.valid_out_len > 0:+ # keep_all_outputs=False for utterances that continue after this chunk+ continues = torch.tensor([not last for last in is_last], device=encoded_len.device)+ encoded_len = torch.where(continues, encoded_len.clamp(max=cfg.valid_out_len), encoded_len)+ hyps, caches = self.decode_chunk_with_restart(+ encoded=self._apply_prompt_to_encoded(encoded),+ encoded_len=encoded_len,+ processed_signal=chunk,+ processed_signal_length=torch.tensor(chunk_len, device=chunk.device),+ hypotheses=[hypotheses[b] for b in active],+ caches=caches,+ restart_token_ids=restart_token_ids,+ keep_all_outputs=is_last,+ drop_extra_pre_encoded=drop_extra_pre_encoded,+ )+ for b, hyp in zip(active, hyps):+ hypotheses[b] = hyp+ if any(is_last): # the remaining chunks of these utterances would only repeat decoded frames+ keep = [i for i, last in enumerate(is_last) if not last]+ active = [active[i] for i in keep]+ keep = torch.tensor(keep, dtype=torch.long, device=caches[0].device)+ caches = [caches[0][:, keep], caches[1][:, keep], caches[2][keep]]+ position += size(cfg.shift_size, step)+ step += 1+ return hypotheses+ @torch.no_grad() def transcribe_simulate_cache_aware_streaming( self,@@ -1047,3 +1261,64 @@ 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 _replace_cache_row(caches: list, idx: int, row: Optional[list] = None) -> list:+ """Replace the encoder cache of stream ``idx`` with ``row`` (1-stream caches), or with the initial (zero) cache."""+ if row is None:+ row = [torch.zeros_like(caches[0][:, :1]), torch.zeros_like(caches[1][:, :1]), torch.zeros_like(caches[2][:1])]+ return [+ torch.cat((caches[0][:, :idx], row[0].to(caches[0].dtype), caches[0][:, idx + 1 :]), dim=1),+ torch.cat((caches[1][:, :idx], row[1].to(caches[1].dtype), caches[1][:, idx + 1 :]), dim=1),+ torch.cat((caches[2][:idx], row[2].to(caches[2].dtype), caches[2][idx + 1 :]), dim=0),+ ]+++def _decoded_lengths(hypotheses: List[Optional[Hypothesis]]) -> List[int]:+ """Number of frames already decoded for each hypothesis (0 for a new stream), with a single device sync."""+ lengths = [+ hyp.dec_state.decoded_length if hyp is not None and hyp.dec_state is not None else None for hyp in hypotheses+ ]+ known = [length for length in lengths if length is not None]+ known = iter(torch.stack([torch.as_tensor(length) for length in known]).tolist() if known else [])+ return [0 if length is None else int(next(known)) for length in lengths]+++def _reset_hypothesis_decoder_state(hypothesis: Hypothesis, decoding_computer) -> None:+ """Reset the decoder state of a partial hypothesis to start-of-sequence, keeping its tokens and time offset."""+ state = hypothesis.dec_state+ if isinstance(state, LabelLoopingStateItem):+ batched_state = decoding_computer.merge_to_batched_state([state])+ decoded_lengths = batched_state.decoded_lengths.clone() # offsets the timestamps of the next step+ batched_state = decoding_computer.reset_state_by_mask(+ batched_state, torch.ones_like(decoded_lengths, dtype=torch.bool)+ )+ batched_state.decoded_lengths = decoded_lengths+ hypothesis.dec_state = decoding_computer.split_batched_state(batched_state)[0]+ hypothesis.dec_state.time_jump = state.time_jump+ else:+ hypothesis.dec_state = None+ hypothesis.last_token = None+++def _find_restart_frame(hypothesis: Hypothesis, token_ids: Sequence[int], num_frames: int) -> Optional[int]:+ """Frame of the first token from ``token_ids`` emitted before the last frame, or None."""+ for token, frame in zip(_to_list(hypothesis.y_sequence), _to_list(hypothesis.timestamp)):+ if token in token_ids and frame < num_frames - 1:+ return int(frame)+ return None+++def _append_hypothesis_segment(hypothesis: Hypothesis, segment: Hypothesis) -> None:+ """Append (in place) a raw hypothesis segment with absolute timestamps; ``length`` accumulates decoded frames."""+ token_duration = hypothesis.token_duration+ if isinstance(token_duration, torch.Tensor) and isinstance(segment.token_duration, torch.Tensor):+ token_duration = torch.cat((token_duration, segment.token_duration), dim=0)+ elif isinstance(token_duration, list) and isinstance(segment.token_duration, list):+ token_duration = token_duration + segment.token_duration+ hypothesis.merge_(segment) # merge_ does not handle token_duration+ hypothesis.token_duration = token_duration+++def _to_list(values) -> list:+ return values.tolist() if isinstance(values, torch.Tensor) else list(values)nemo/collections/asr/parts/submodules/rnnt_decoding.py39 + / 0 −
@@ -699,6 +699,9 @@ def __init__(self, decoding_cfg, decoder, joint, blank_id: int, supported_punctu # Update the joint fused batch size or disable it entirely if needed. self.update_joint_fused_batch_size() + # ids of `restart_after_tokens`, resolved once (empty when not configured)+ self.restart_token_ids = self._resolve_restart_token_ids()+ def set_strip_lang_tags(self, strip_lang_tags: bool, lang_tag_pattern: Optional[str] = None): """ Toggle language-tag stripping on decoded text.@@ -757,6 +760,12 @@ def rnnt_decoder_predictions_tensor( # extract the hypotheses hypotheses_list = hypotheses_list[0] # type: List[Hypothesis] + return self.postprocess_hypotheses(hypotheses_list, return_hypotheses=return_hypotheses)++ def postprocess_hypotheses(+ self, hypotheses_list: List[Union[Hypothesis, NBestHypotheses]], return_hypotheses: bool = False+ ) -> Union[List[Hypothesis], List[List[Hypothesis]]]:+ """Decode text and compute timestamps/confidence for raw hypotheses (see ``rnnt_decoder_predictions_tensor``).""" prediction_list = hypotheses_list if isinstance(prediction_list[0], NBestHypotheses):@@ -1254,6 +1263,32 @@ def _load_kenlm_model(ngram_lm_model: str): "KenLM package (https://github.com/kpu/kenlm) is not installed. " "Use ngram_lm_model=None." ) + def _resolve_restart_token_ids(self) -> List[int]:+ """Validate ``restart_after_tokens`` against the decoding setup and return the ids of these tokens."""+ tokens = self.cfg.get('restart_after_tokens', None)+ if not tokens:+ return []+ if getattr(self.decoding, 'decoding_computer', None) is None:+ raise NotImplementedError(+ "`restart_after_tokens` is only supported with `greedy_batch` decoding using label looping, "+ f"got strategy={self.cfg.strategy}"+ )+ tokenizer = getattr(self, 'tokenizer', None)+ if tokenizer is None: # character vocabulary+ vocabulary = {label: idx for idx, label in self.labels_map.items()}+ token_ids = []+ for token in tokens:+ if tokenizer is not None:+ token_id = tokenizer.token_to_id(token)+ is_token = tokenizer.ids_to_tokens([token_id]) == [token]+ else:+ token_id = vocabulary.get(token)+ is_token = token_id is not None+ if not is_token:+ raise ValueError(f"`restart_after_tokens`: {token} is not a single token in the model vocabulary.")+ token_ids.append(int(token_id))+ return token_ids+ class RNNTDecoding(AbstractRNNTDecoding): """@@ -1893,6 +1928,10 @@ class RNNTDecodingConfig: # type of timestamps to calculate rnnt_timestamp_type: str = "all" # can be char, word or all for both + # Tokens (e.g. ['<EOU>', '<EOB>'] for end-of-utterance models) after which `transcribe()` and cache-aware+ # streaming restart the encoder and decoder from a fresh state. Requires `greedy_batch` decoding (label looping).+ restart_after_tokens: Optional[List[str]] = None+ # greedy decoding config greedy: rnnt_greedy_decoding.GreedyBatchedRNNTInferConfig = field( default_factory=rnnt_greedy_decoding.GreedyBatchedRNNTInferConfigtests/collections/asr/test_asr_eou_multi_utterance.pyadded506 + / 0 −
@@ -0,0 +1,506 @@+# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""+Multi-utterance decoding with end-of-utterance models and ``decoding.restart_after_tokens``.++These models are trained on single-utterance samples and stop emitting tokens after the first ``<EOU>`` unless+decoding restarts after it. The tests use a tiny randomly-initialized model whose decoding algorithm is replaced+with a simulation of this behavior: it emits ``<word> <EOU>`` for the next utterance and nothing after that.+"""++import dataclasses++import pytest+import torch+from omegaconf import DictConfig, OmegaConf, open_dict++from nemo.collections.asr.models import EncDecRNNTBPEModel+from nemo.collections.asr.parts.mixins.mixins import _append_hypothesis_segment, _reset_hypothesis_decoder_state+from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis+from nemo.collections.common.tokenizers.sentencepiece_tokenizer import create_spt_model++WORD_ID = 5+SEED = 0+SUBSAMPLING_FACTOR = 4+++@pytest.fixture(scope="module")+def eou_tokenizer_dir(tmp_path_factory):+ tmp_path = tmp_path_factory.mktemp("eou_tokenizer")+ text_file = tmp_path / "text.txt"+ text_file.write_text("\n".join(["go no stop yes one two three four five six seven eight nine ten"] * 10))+ create_spt_model(+ str(text_file),+ vocab_size=40,+ sample_size=-1,+ do_lower_case=True,+ tokenizer_type="bpe",+ output_dir=str(tmp_path),+ user_defined_symbols=["<EOU>", "<EOB>"],+ )+ return str(tmp_path)+++def _make_model(tokenizer_dir: str) -> EncDecRNNTBPEModel:+ cfg = DictConfig(+ {+ 'sample_rate': 16000,+ 'model_defaults': {'enc_hidden': 16, 'pred_hidden': 16},+ 'preprocessor': {+ '_target_': 'nemo.collections.asr.modules.AudioToMelSpectrogramPreprocessor',+ 'sample_rate': 16000,+ 'features': 64,+ 'normalize': 'NA',+ 'dither': 0.0,+ 'pad_to': 0,+ },+ 'encoder': {+ '_target_': 'nemo.collections.asr.modules.ConformerEncoder',+ 'feat_in': 64,+ 'n_layers': 1,+ 'd_model': 16,+ 'subsampling': 'striding',+ 'subsampling_factor': SUBSAMPLING_FACTOR,+ 'subsampling_conv_channels': 8,+ 'causal_downsampling': True,+ 'ff_expansion_factor': 2,+ 'self_attention_model': 'rel_pos',+ 'n_heads': 2,+ 'att_context_size': [16, 1],+ 'att_context_style': 'chunked_limited',+ 'conv_kernel_size': 9,+ 'conv_context_size': 'causal',+ 'dropout': 0.0,+ 'dropout_pre_encoder': 0.0,+ 'dropout_emb': 0.0,+ 'dropout_att': 0.0,+ },+ 'decoder': {+ '_target_': 'nemo.collections.asr.modules.RNNTDecoder',+ 'prednet': {'pred_hidden': 16, 'pred_rnn_layers': 1},+ },+ 'joint': {+ '_target_': 'nemo.collections.asr.modules.RNNTJoint',+ 'jointnet': {'joint_hidden': 16, 'activation': 'relu', 'encoder_hidden': 16, 'pred_hidden': 16},+ },+ 'tokenizer': {'dir': tokenizer_dir, 'type': 'bpe'},+ 'decoding': {+ 'strategy': 'greedy_batch',+ 'greedy': {'max_symbols': 5},+ 'restart_after_tokens': ['<EOU>', '<EOB>'],+ },+ 'loss': {'loss_name': 'default'},+ }+ )+ model = EncDecRNNTBPEModel(cfg=cfg)+ model.eval()+ return model+++@pytest.fixture()+def eou_model(eou_tokenizer_dir):+ return _make_model(eou_tokenizer_dir)+++class _SingleUtteranceDecodingSim:+ """+ Simulates the greedy decoding of an end-of-utterance model trained on single-utterance samples.++ Decoder states are real label-looping state items: ``decoded_length`` gives the absolute frame offset, and the last+ label is ``<EOU>`` once the utterance has ended. A hypothesis that has not ended emits ``<word> <EOU>`` on the next+ utterance frame (absolute encoder frame); after ``<EOU>``, it emits nothing unless its decoder state is reset.+ Utterance frames are looked up by stream: a new stream is identified by its batch index (so all streams must start+ in the first call), stored in the unused ``time_jump`` field of the state, which persists across decoder resets.+ """++ def __init__(self, decoding_computer, utterance_frames: list[list[int]], eou_id: int):+ self.decoding_computer = decoding_computer+ self.utterance_frames = utterance_frames+ self.eou_id = eou_id+ self.calls = [] # (stream, start frame, encoder output) of each decoded segment++ def __call__(self, encoder_output, encoded_lengths, partial_hypotheses=None):+ hypotheses = []+ for b, num_frames in enumerate(encoded_lengths.tolist()):+ prev = partial_hypotheses[b] if partial_hypotheses is not None else None+ state = prev.dec_state if prev is not None and prev.dec_state is not None else None+ if state is None:+ state = self.decoding_computer._get_decoding_state_item_after_sos(device=encoder_output.device)+ state.time_jump = torch.tensor(b)+ start = int(state.decoded_length)+ self.calls.append((int(state.time_jump), start, encoder_output[b, :, :num_frames].clone()))+ tokens, timestamps, label = [], [], int(state.label)+ if label != self.eou_id:+ for u in self.utterance_frames[int(state.time_jump)]:+ if start <= u < start + num_frames:+ tokens, timestamps, label = [WORD_ID, self.eou_id], [u, u], self.eou_id+ break+ new_state = dataclasses.replace(+ state,+ label=torch.tensor(label),+ decoded_length=torch.tensor(start + num_frames),+ )+ hyp = Hypothesis(+ score=-float(len(tokens)),+ y_sequence=torch.tensor(tokens, dtype=torch.long),+ timestamp=torch.tensor(timestamps, dtype=torch.long),+ dec_state=new_state,+ length=num_frames,+ )+ if prev is not None:+ prev.merge_(hyp)+ hyp = prev+ hypotheses.append(hyp)+ return (hypotheses,)+++def _simulate(model, utterance_frames: list[list[int]]) -> int:+ eou_id = model.tokenizer.token_to_id("<EOU>")+ computer = model.decoding.decoding.decoding_computer+ model.decoding.decoding = _SingleUtteranceDecodingSim(computer, utterance_frames, eou_id=eou_id)+ return eou_id+++def _change_decoding(model, overrides: dict) -> None:+ cfg = model.cfg.decoding+ with open_dict(cfg):+ for key, value in overrides.items():+ OmegaConf.update(cfg, key, value)+ model.change_decoding_strategy(cfg, verbose=False)+++@pytest.mark.unit+def test_restart_token_ids(eou_model):+ """Restart token ids are resolved once, and unsupported setups are rejected when the decoding is configured."""+ assert eou_model.tokenizer.ids_to_tokens(eou_model.decoding.restart_token_ids) == ["<EOU>", "<EOB>"]+ with pytest.raises(ValueError):+ _change_decoding(eou_model, {"restart_after_tokens": ["<XYZ>"]})+ for strategy in ("greedy", "beam"):+ with pytest.raises(NotImplementedError, match="greedy_batch"):+ _change_decoding(eou_model, {"restart_after_tokens": ["<EOU>"], "strategy": strategy})+ with pytest.raises(NotImplementedError, match="greedy_batch"):+ _change_decoding(eou_model, {"strategy": "greedy_batch", "greedy.loop_labels": False})+ _change_decoding(eou_model, {"restart_after_tokens": None, "greedy.loop_labels": True})+ assert eou_model.decoding.restart_token_ids == []+++@pytest.mark.unit+def test_transcribe_continues_after_eou(eou_model):+ """transcribe() decodes every utterance of a multi-utterance audio, not only the first one."""+ utterance_frames = [3, 20, 21, 40, 60] # 20 and 21 fall into the same streaming chunk+ eou_id = _simulate(eou_model, [utterance_frames])+ audio = torch.randn(16000 * 3) * 0.1++ hyp = eou_model.transcribe([audio.numpy()], batch_size=1, return_hypotheses=True)[0]++ assert hyp.y_sequence.tolist() == [WORD_ID, eou_id] * len(utterance_frames)+ assert hyp.timestamp.tolist() == [t for u in utterance_frames for t in (u, u)]+ assert hyp.text.count("<EOU>") == len(utterance_frames)+ # segments are disjoint: decoded frames are counted once, and scores of re-decoded chunks are not duplicated+ assert hyp.score == -2.0 * len(utterance_frames)+ assert hyp.length == hyp.dec_state.decoded_length.item()+++@pytest.mark.unit+def test_transcribe_encodes_audio_once(eou_model):+ """Offline restarts stream over the features, so the encoded features grow linearly with the audio."""+ _simulate(eou_model, [list(range(2, 1000, 4))]) # an utterance in every other chunk+ encoded_features = []+ stream_step = eou_model.encoder.cache_aware_stream_step++ def counting_stream_step(**kwargs):+ encoded_features.append(int(kwargs['processed_signal_length'][0]))+ return stream_step(**kwargs)++ eou_model.encoder.cache_aware_stream_step = counting_stream_step+ for seconds in (2, 4):+ encoded_features.clear()+ eou_model.transcribe([(torch.randn(16000 * seconds) * 0.1).numpy()], batch_size=1)+ num_features = seconds * 100+ # chunk features + pre-encode cache per chunk, with at most one re-encoded chunk tail per restart+ assert sum(encoded_features) < 3 * num_features+++@pytest.mark.unit+def test_transcribe_without_restart_tokens_is_unchanged(eou_model):+ """Without ``restart_after_tokens``, the regular single-pass decoding is used."""+ _change_decoding(eou_model, {"restart_after_tokens": None})+ eou_id = _simulate(eou_model, [[3, 20]])+ hyp = eou_model.transcribe([(torch.randn(16000 * 3) * 0.1).numpy()], batch_size=1, return_hypotheses=True)[0]+ assert hyp.y_sequence.tolist() == [WORD_ID, eou_id]+++@pytest.mark.unit+def test_stream_step_restarts_within_chunk(eou_model):+ """Several utterances ending inside a single (final) chunk are all decoded, with absolute timestamps."""+ utterance_frames = [1, 3, 7]+ eou_id = _simulate(eou_model, [utterance_frames])+ eou_model.encoder.setup_streaming_params()+ features = torch.randn(1, 64, 10 * SUBSAMPLING_FACTOR)+ num_frames = 10 + 1 # causal subsampling: floor(num_features / subsampling_factor) + 1+ cache = eou_model.encoder.get_initial_cache_state(batch_size=1)+ with torch.inference_mode():+ *_, cache_len, hyps = eou_model.conformer_stream_step(+ processed_signal=features,+ processed_signal_length=torch.tensor([features.shape[-1]]),+ cache_last_channel=cache[0],+ cache_last_time=cache[1],+ cache_last_channel_len=cache[2],+ keep_all_outputs=True,+ drop_extra_pre_encoded=0,+ )+ assert hyps[0].y_sequence.tolist() == [WORD_ID, eou_id] * 3+ assert hyps[0].timestamp.tolist() == [t for u in utterance_frames for t in (u, u)]+ assert hyps[0].dec_state.decoded_length.item() == num_frames+ assert cache_len[0].item() == num_frames - (+ utterance_frames[-1] + 1+ ) # encoder context restarted after the last <EOU>+++@pytest.mark.unit+def test_cache_aware_streaming_continues_after_eou(eou_model):+ """conformer_stream_step restarts decoding and resets the encoder cache only for the streams that emit <EOU>."""+ utterance_frames = [[3, 20, 40], []] # the second stream never emits <EOU>+ eou_id = _simulate(eou_model, utterance_frames)+ eou_model.encoder.setup_streaming_params()+ cfg = eou_model.encoder.streaming_cfg++ num_feature_frames = 80 * SUBSAMPLING_FACTOR+ features = torch.randn(2, 64, num_feature_frames)+ cache_last_channel, cache_last_time, cache_last_channel_len = eou_model.encoder.get_initial_cache_state(+ batch_size=2+ )+ hyps = None+ start, step = 0, 0+ with torch.inference_mode():+ while start < num_feature_frames:+ first = step == 0+ size = cfg.chunk_size[0] if first else cfg.chunk_size[1]+ chunk = features[:, :, (start if first else max(0, start - cfg.pre_encode_cache_size[1])) : start + size]+ num_eou_before = [+ 0 if hyps is None else hyp.y_sequence.tolist().count(eou_id) for hyp in hyps or [None] * 2+ ]+ (_, _, cache_last_channel, cache_last_time, cache_last_channel_len, hyps) = (+ eou_model.conformer_stream_step(+ processed_signal=chunk,+ processed_signal_length=torch.tensor([chunk.shape[-1]] * 2),+ cache_last_channel=cache_last_channel,+ cache_last_time=cache_last_time,+ cache_last_channel_len=cache_last_channel_len,+ keep_all_outputs=start + size >= num_feature_frames,+ previous_hypotheses=hyps,+ drop_extra_pre_encoded=0 if first else cfg.drop_extra_pre_encoded,+ )+ )+ if hyps[0].y_sequence.tolist().count(eou_id) > num_eou_before[0]:+ # the encoder context of the first stream restarted within this chunk, the other stream is unaffected+ assert cache_last_channel_len[0].item() < cache_last_channel_len[1].item()+ start += size if first else cfg.shift_size[1]+ step += 1++ assert hyps[0].y_sequence.tolist() == [WORD_ID, eou_id] * 3+ assert hyps[0].timestamp.tolist() == [t for u in utterance_frames[0] for t in (u, u)]+ assert hyps[1].y_sequence.tolist() == []+ assert cache_last_channel_len[1].item() == cfg.last_channel_cache_size+ # `length` counts all encoder frames decoded for the stream, not only those of the last chunk+ for hyp in hyps:+ assert int(hyp.length) == hyp.dec_state.decoded_length.item()+ assert int(hyps[1].length) == sum(num_frames for _, num_frames in _decoded_segments(eou_model, 1))+++@pytest.mark.unit+def test_reset_hypothesis_decoder_state_keeps_time_offset(eou_model):+ """Resetting a label-looping decoder state restores the start-of-sequence state but keeps the frame offset."""+ computer = eou_model.decoding.decoding.decoding_computer+ with torch.inference_mode():+ encoded = torch.randn(1, 16, 10)+ hyp = eou_model.decoding.rnnt_decoder_predictions_tensor(+ encoded, torch.tensor([10]), return_hypotheses=True, partial_hypotheses=[None]+ )[0]+ start_item = computer.split_batched_state(computer._get_batched_decoding_state_after_sos("cpu", 1))[0]+ hyp.dec_state.label.fill_(WORD_ID)+ _reset_hypothesis_decoder_state(hyp, computer)++ assert hyp.dec_state.decoded_length.item() == 10+ assert hyp.dec_state.label.item() == start_item.label.item()+ torch.testing.assert_close(hyp.dec_state.predictor_output, start_item.predictor_output)+ for state, start_state in zip(hyp.dec_state.predictor_state, start_item.predictor_state):+ torch.testing.assert_close(state, start_state)+++@pytest.mark.unit+def test_append_hypothesis_segment():+ hyp = Hypothesis(score=-1.0, y_sequence=[5, 1], timestamp=[1, 2], token_duration=[0, 1], length=3)+ segment = Hypothesis(score=-2.0, y_sequence=[6], timestamp=[3], token_duration=[2], length=4)+ _append_hypothesis_segment(hyp, segment)+ assert hyp.y_sequence == [5, 1, 6]+ assert hyp.timestamp == [1, 2, 3]+ assert hyp.token_duration == [0, 1, 2]+ assert hyp.score == -3.0+ assert hyp.length == 7+++@pytest.mark.unit+def test_stream_step_without_restart_tokens_uses_regular_decoding(eou_model):+ """Without ``restart_after_tokens``, streaming keeps the regular batched decoding path."""+ _change_decoding(eou_model, {"restart_after_tokens": None})+ eou_model.decode_chunk_with_restart = None # must not be called+ eou_model.encoder.setup_streaming_params()+ features = torch.randn(1, 64, 10 * SUBSAMPLING_FACTOR)+ cache = eou_model.encoder.get_initial_cache_state(batch_size=1)+ with torch.inference_mode():+ *_, hyps = eou_model.conformer_stream_step(+ processed_signal=features,+ processed_signal_length=torch.tensor([features.shape[-1]]),+ cache_last_channel=cache[0],+ cache_last_time=cache[1],+ cache_last_channel_len=cache[2],+ keep_all_outputs=True,+ drop_extra_pre_encoded=0,+ )+ assert len(hyps) == 1+++@pytest.mark.unit+def test_offline_batch_matches_single_streams(eou_model):+ """Offline restarts advance the whole batch through each chunk, with the same results as one stream at a time."""+ utterance_frames = [[3, 20, 21, 40, 70], [5, 6, 30], [10, 23]] # 23 is on the last frame of the third stream+ lengths = [301, 180, 97]+ features = torch.randn(3, 64, max(lengths))+ for b, length in enumerate(lengths):+ features[b, :, length:] = 100.0 # padding must not leak into the shorter streams+ restart_token_ids = eou_model.decoding.restart_token_ids++ _simulate(eou_model, utterance_frames)+ with torch.inference_mode():+ batched = eou_model.cache_aware_transcribe_with_restart(features, torch.tensor(lengths), restart_token_ids)+ batched_calls = _segments_by_stream(eou_model.decoding.decoding.calls)++ for b, length in enumerate(lengths):+ _simulate(eou_model, [utterance_frames[b]])+ with torch.inference_mode():+ single = eou_model.cache_aware_transcribe_with_restart(+ features[b : b + 1, :, :length], torch.tensor([length]), restart_token_ids+ )[0]+ assert batched[b].y_sequence.tolist() == single.y_sequence.tolist()+ assert batched[b].timestamp.tolist() == [t for u in utterance_frames[b] for t in (u, u)]+ assert batched[b].timestamp.tolist() == single.timestamp.tolist()+ assert batched[b].score == single.score+ assert int(batched[b].length) == int(single.length) == batched[b].dec_state.decoded_length.item()+ single_calls = _segments_by_stream(eou_model.decoding.decoding.calls)[0]+ assert [start for start, _ in batched_calls[b]] == [start for start, _ in single_calls]+ for (_, batched_enc), (_, single_enc) in zip(batched_calls[b], single_calls):+ torch.testing.assert_close(batched_enc, single_enc, atol=1e-5, rtol=1e-5)+++@pytest.mark.unit+def test_transcribe_batch_matches_batch_size_one(eou_model):+ """transcribe() gives the same multi-utterance results with and without batching audio of different lengths."""+ utterance_frames = [[3, 20, 21, 40], [5, 30], [10]]+ audio = [(torch.randn(int(16000 * seconds)) * 0.1).numpy() for seconds in (2, 1.5, 0.5)]+ results = {}+ for batch_size in (1, 3):+ hyps = []+ for b in range(len(audio)) if batch_size == 1 else [None]:+ _simulate(eou_model, utterance_frames if b is None else [utterance_frames[b]])+ inputs = audio if b is None else [audio[b]]+ hyps += eou_model.transcribe(inputs, batch_size=batch_size, return_hypotheses=True)+ results[batch_size] = hyps+ for single, batched, frames in zip(results[1], results[3], utterance_frames):+ assert batched.y_sequence.tolist() == single.y_sequence.tolist()+ assert batched.timestamp.tolist() == single.timestamp.tolist() == [t for u in frames for t in (u, u)]+ assert batched.text == single.text+ assert int(batched.length) == int(single.length)+++@pytest.mark.unit+def test_offline_decodes_each_frame_once_with_overlapping_chunks(eou_model):+ """With a shift smaller than the chunk size, decoding stops at the last chunk instead of re-decoding its frames."""+ eou_model.encoder.setup_streaming_params(chunk_size=4, shift_size=2)+ assert eou_model.encoder.streaming_cfg.shift_size[1] < eou_model.encoder.streaming_cfg.chunk_size[1]+ eou_id = _simulate(eou_model, [[3, 20, 73]]) # an utterance ends near the end of the audio+ features = torch.randn(1, 64, 301)+ with torch.inference_mode():+ _, num_frames = eou_model.encoder(audio_signal=features, length=torch.tensor([301]))+ hyp = eou_model.cache_aware_transcribe_with_restart(+ features, torch.tensor([301]), eou_model.decoding.restart_token_ids+ )[0]+ assert hyp.y_sequence.tolist() == [WORD_ID, eou_id] * 3+ assert hyp.timestamp.tolist() == [3, 3, 20, 20, 73, 73]+ assert int(hyp.length) == hyp.dec_state.decoded_length.item() == num_frames.item()+ segments = _decoded_segments(eou_model, 0)+ for (start, num), (next_start, _) in zip(segments, segments[1:]):+ assert next_start >= start + num or next_start == start # contiguous; equal starts are re-decoded prefixes+++@pytest.mark.unit+def test_offline_restart_with_greedy_batch_decoder(eou_tokenizer_dir):+ """+ The real greedy_batch decoder continues after <EOU>, with the same results in a batch and one stream at a time.+ The joint ignores the prediction network and emits <EOU> instead of blank on ~20% of the frames.+ """+ torch.manual_seed(SEED)+ eou_model = _make_model(eou_tokenizer_dir)+ _change_decoding(eou_model, {"greedy.max_symbols": 1})+ eou_id, blank_id = eou_model.decoding.restart_token_ids[0], eou_model.decoding.blank_id+ lengths = [301, 180, 97]+ features = torch.randn(3, 64, max(lengths))+ joint, output_layer = eou_model.joint, eou_model.joint.joint_net[-1]+ with torch.no_grad():+ joint.pred.weight.zero_()+ joint.pred.bias.zero_()+ output_layer.bias.fill_(-1e4)+ output_layer.bias[blank_id] = 0.0+ # calibrate the <EOU> bias on the streaming encoder outputs (all blank)+ encoded = []+ eou_model._apply_prompt_to_encoded = lambda enc: encoded.append(enc.transpose(1, 2).flatten(0, 1)) or enc+ with torch.inference_mode():+ eou_model.cache_aware_transcribe_with_restart(+ features, torch.tensor(lengths), eou_model.decoding.restart_token_ids+ )+ del eou_model._apply_prompt_to_encoded+ logits = output_layer(joint.joint_net[:-1](joint.project_encoder(torch.cat(encoded))))+ with torch.no_grad():+ output_layer.bias[eou_id] = -(logits[:, eou_id] - logits[:, blank_id]).quantile(0.8)++ with torch.inference_mode():+ batched = eou_model.cache_aware_transcribe_with_restart(+ features, torch.tensor(lengths), eou_model.decoding.restart_token_ids+ )+ _, num_frames = eou_model.encoder(audio_signal=features, length=torch.tensor(lengths))+ for b, length in enumerate(lengths):+ single = eou_model.cache_aware_transcribe_with_restart(+ features[b : b + 1, :, :length], torch.tensor([length]), eou_model.decoding.restart_token_ids+ )[0]+ assert batched[b].y_sequence.tolist() == single.y_sequence.tolist()+ assert batched[b].timestamp.tolist() == single.timestamp.tolist()+ assert int(batched[b].length) == int(single.length) == num_frames[b].item()++ tokens, timestamps = batched[0].y_sequence.tolist(), batched[0].timestamp.tolist()+ assert set(tokens) == {eou_id} and len(tokens) > 2 # decoding continues after the first <EOU>+ assert timestamps == sorted(set(timestamps)) and timestamps[-1] > eou_model.encoder.streaming_cfg.chunk_size[1]+++def _segments_by_stream(calls) -> dict:+ segments = {}+ for stream, start, encoded in calls:+ segments.setdefault(stream, []).append((start, encoded))+ return segments+++def _decoded_segments(model, stream: int) -> list:+ """(start frame, number of frames) of the segments decoded for ``stream`` by the simulator."""+ return [(start, enc.shape[-1]) for s, start, enc in model.decoding.decoding.calls if s == stream]