NeMo ASR Configuration Files#
This section describes the NeMo configuration file setup that is specific to models in the ASR collection. For general information about how to set up and run experiments that is common to all NeMo models (e.g. Experiment Manager and PyTorch Lightning trainer parameters), see the NeMo Models section.
The model section of the NeMo ASR configuration files generally requires information about the dataset(s) being used, the preprocessor for audio files, parameters for any augmentation being performed, as well as the model architecture specification. The sections on this page cover each of these in more detail.
Example configuration files for all of the NeMo ASR scripts can be found in the config directory of the examples.
Dataset Configuration#
Training, validation, and test parameters are specified using the train_ds, validation_ds, and
test_ds sections in the configuration file, respectively. Depending on the task, there may be arguments specifying the sample rate
of the audio files, the vocabulary of the dataset (for character prediction), whether or not to shuffle the dataset, and so on. You may
also decide to leave fields such as the manifest_filepath blank, to be specified via the command-line at runtime.
Any initialization parameter that is accepted for the Dataset class used in the experiment can be set in the config file. Refer to the Datasets section of the API for a list of Datasets and their respective parameters.
An example ASR train and validation configuration should look similar to the following:
# Specified at the beginning of the config file
labels: &labels [" ", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "'"]
model:
train_ds:
manifest_filepath: ???
sample_rate: 16000
labels: *labels # Uses the labels above
batch_size: 32
trim_silence: True
max_duration: 16.7
shuffle: True
num_workers: 8
pin_memory: true
# tarred datasets
is_tarred: false # If set to true, uses the tarred version of the Dataset
tarred_audio_filepaths: null # Not used if is_tarred is false
shuffle_n: 2048 # Not used if is_tarred is false
# bucketing params
bucketing_strategy: "synced_randomized"
bucketing_batch_size: null
bucketing_weights: null
validation_ds:
manifest_filepath: ???
sample_rate: 16000
labels: *labels # Uses the labels above
batch_size: 32
shuffle: False # No need to shuffle the validation data
num_workers: 8
pin_memory: true
There are two ways to test/validate on more than one manifest:
Specify a list in the manifest_filepath field. Results will be reported for each, the first one being used for overall loss / WER (specify val_dl_idx if you wish to change that). In this case, all manifests will share configuration parameters.
Use the ds_item key and pass a list of config objects to it. This allows you to use differently configured datasets for validation, e.g.
model:
validation_ds:
ds_item:
- name: dataset1
manifest_filepath: ???
# Config parameters for dataset1
...
- name: dataset2
manifest_filepath: ???
# Config parameters for dataset2
...
By default, dataloaders are set up when the model is instantiated. However, dataloader setup can be deferred to
model’s setup() method by setting defer_setup in the configuration.
For example, training data setup can be deferred as follows:
model:
train_ds:
# Configure training data as usual
...
# Defer train dataloader setup from `__init__` to `setup`
defer_setup: true
Preprocessor Configuration#
If you are loading audio files for your experiment, you will likely want to use a preprocessor to convert from the
raw audio signal to features (e.g. mel-spectrogram or MFCC). The preprocessor section of the config specifies the audio
preprocessor to be used via the _target_ field, as well as any initialization parameters for that preprocessor.
An example of specifying a preprocessor is as follows:
model:
...
preprocessor:
# _target_ is the audio preprocessor module you want to use
_target_: nemo.collections.asr.modules.AudioToMelSpectrogramPreprocessor
normalize: "per_feature"
window_size: 0.02
...
# Other parameters for the preprocessor
Refer to the Audio Preprocessors API section for the preprocessor options, expected arguments, and defaults.
Augmentation Configurations#
There are a few on-the-fly spectrogram augmentation options for NeMo ASR, which can be specified by the
configuration file using a spec_augment section.
For example, there are options for Cutout and
SpecAugment available via the SpectrogramAugmentation module.
The following example sets up both Cutout (via the rect_* parameters) and SpecAugment (via the freq_*
and time_* parameters).
model:
...
spec_augment:
_target_: nemo.collections.asr.modules.SpectrogramAugmentation
# Cutout parameters
rect_masks: 5 # Number of rectangles to cut from any given spectrogram
rect_freq: 50 # Max cut of size 50 along the frequency dimension
rect_time: 120 # Max cut of size 120 along the time dimension
# SpecAugment parameters
freq_masks: 2 # Cut two frequency bands
freq_width: 15 # ... of width 15 at maximum
time_masks: 5 # Cut out 10 time bands
time_width: 25 # ... of width 25 at maximum
You can use any combination of Cutout, frequency/time SpecAugment, or neither of them.
You can also add audio augmentation pipelines via an augmentor section in train_ds.
Caution
The augmentor pipeline is not supported by the Lhotse dataloader, which provides its own set of augmentation options.
See Lhotse Dataloading for details.
Augmentors are applied on-the-fly to audio data in the data layer. The following example adds white noise (probability 0.5, level between -50 dB and -10 dB) and room impulse response augmentation (probability 0.3, from a manifest of impulse responses):
model:
...
train_ds:
...
augmentor:
white_noise:
prob: 0.5
min_level: -50
max_level: -10
impulse:
prob: 0.3
manifest_path: /path/to/impulse_manifest.json
Refer to the Audio Augmentors API section for more details.
Metric Configurations#
NeMo ASR models supports WER and BLEU metric logging during training and validation. All metrics are based on the TorchMetrics backend, allowing for distributed training without additional code.
Word Error Rate (WER)#
WER is the default metric for all ASR models and measures transcription accuracy at the word or character level.
model:
use_cer: false # Set to true for Character Error Rate instead (default: false)
log_prediction: true # Whether to log a sample prediction during training (default: true)
batch_dim_index: 0 # Index of batch dimension in prediction tensors output. Set to 1 for RNNT models.
wer_text_normalize: false # Normalize references and predictions before computing WER/CER (default: false)
Models trained with punctuation and capitalization produce WER that is dominated by casing and punctuation errors.
For CTC, RNN-T and hybrid RNN-T/CTC models (EncDecCTCModel, EncDecCTCModelBPE, EncDecRNNTModel,
EncDecRNNTBPEModel, EncDecRNNTBPEModelWithPrompt, EncDecHybridRNNTCTCModel,
EncDecHybridRNNTCTCBPEModel, EncDecHybridRNNTCTCBPEModelWithPrompt), set wer_text_normalize: true to
lowercase the text, remove punctuation and collapse whitespace in both references and predictions before scoring
(see nemo.collections.asr.parts.utils.eval_utils.clean_label). Typographic apostrophes inside words are treated
as ASCII apostrophes (It’s matches it's), while contractions stay distinct from other words (it's does not
match its). For hybrid models the flag also applies to the auxiliary CTC WER. Logged sample predictions and
returned hypotheses keep the original text.
BLEU Score#
BLEU score can be used for ASR models to evaluate translation quality. NeMo’s BLEU implementation is based on SacreBLEU for standardized, reproducible scoring:
model:
bleu_tokenizer: "13a" # SacreBLEU tokenizer type (see below). (default: "13a")
n_gram: 4 # Maximum n-gram order for BLEU calculation. (default: 4)
lowercase: false # Whether to lowercase before computing BLEU. (default: False)
weights: null # Optional custom weights for n-gram orders. (default: null)
smooth: false # Whether to apply smoothing to BLEU calculation. (default: False)
check_cuts_for_bleu_tokenizers: false # Enable per-sample tokenizer selection. (See below for more details.) (default: False)
log_prediction: true # Whether to log sample predictions. (default: True)
batch_dim_index: 0 # Index of batch dimension in prediction tensors output. Set to 1 for RNNT models. (default: 0)
BLEU score relies on TorchMetrics’ SacreBLEU implementation and supports all SacreBLEU tokenization options. Valid strings may be passed to bleu_tokenizer parameter to configure base tokenizer behavior during BLEU calculation. Available options are:
"13a"- Default WMT tokenizer (mteval-v13a script compatible)"none"- No tokenization applied"intl"- International tokenization (mteval-v14 script compatible)"char"- Character-level tokenization (language-agnostic)"zh"- Chinese tokenization (separates Chinese characters, uses 13a for non-Chinese)"ja-mecab"- Japanese tokenization using MeCab morphological analyzer"ko-mecab"- Korean tokenization using MeCab-ko morphological analyzer"flores101"/"flores200"- SentencePiece models from Flores datasets
Note Due to their unique orthographies, it is highly recommended to use zh, ja-mecab, or ko-mecab tokenizers for Chinese, Japanese, and Korean target evaluations, respectively. For more information on SacreBLEU tokenizers, please refer to the SacreBLEU documentation.
Dynamic Tokenizer Selection
In multilingual training scenarios, it is sometimes desirable to configure the BLEU tokenizer per sample to avoid sub-optimal parsing (e.g. tokenizing Chinese characters as English words). This can be toggled with check_cuts_for_bleu_tokenizers: true. When enabled with Lhotse dataloading, BLEU will check individual cuts in a batch’s Lhotse CutSet for the bleu_tokenizer attribute. If found, the tokenizer will be used for that sample. If not, the default bleu_tokenizer from config will be used.
MultiTask Metrics#
Multiple metrics can be configured simultaneously using a MultiTaskMetric config. This is done by specifying in the config each desired metric as a DictConfig entry with a custom key name and _target_ path, along with desired properties. All properties specified within a metric config will be passed only to the metric class. All properties specified at the top level of the config will be inherited by all submetrics.
model:
multitask_metrics_config:
log_prediction: true
metrics:
wer:
_target_: nemo.collections.asr.metrics.wer.WER
use_cer: true
constraint: ".task==transcribe" # Only apply WER to transcription samples
bleu:
_target_: nemo.collections.asr.metrics.bleu.BLEU
bleu_tokenizer: flores101
lowercase: true
check_cuts_for_bleu_tokenizers: true
constraint: ".task==translate" # Only apply BLEU to translation samples
Metric Constraints
Each metric within MultiTaskMetric can be configured with an optional boolean constraint pattern that filters batch samples before metric computation. This allows validation to be limited to only applicable samples in a batch (e.g. only apply WER to transcription samples, only apply BLEU to translation samples). Constraint patterns match against property keywords in the batch’s Lhotse CutSet.
model:
multitask_metrics_config:
metrics:
pnc_wer:
_target_: nemo.collections.asr.metrics.wer.WER
constraint: ".task==transcribe and .pnc==true"
multilingual_bleu:
_target_: nemo.collections.asr.metrics.bleu.BLEU
constraint: "(.source_lang!=.target_lang) or .task==translate"
Note: MultiTaskMetric is currently only supported for AED multitask models.
Tokenizer Configurations#
Some models utilize sub-word encoding via an external tokenizer instead of explicitly defining their vocabulary.
For such models, a tokenizer section is added to the model config. ASR models currently support two types of
custom tokenizers:
Google Sentencepiece tokenizers (tokenizer type of
bpein the config)HuggingFace WordPiece tokenizers (tokenizer type of
wpein the config)Aggregate tokenizers ((tokenizer type of
aggin the config), see below)
In order to build custom tokenizers, refer to the ASR_with_Subword_Tokenization notebook available in the
ASR tutorials directory.
The following example sets up a SentencePiece Tokenizer at a path specified by the user:
model:
...
tokenizer:
dir: "<path to the directory that contains the custom tokenizer files>"
type: "bpe" # can be "bpe" or "wpe"
The Aggregate (agg) tokenizer feature makes it possible to combine tokenizers in order to train multilingual
models. The config file would look like this:
model:
...
tokenizer:
type: "agg" # aggregate tokenizer
langs:
en:
dir: "<path to the directory that contains the tokenizer files>"
type: "bpe" # can be "bpe" or "wpe"
es:
dir: "<path to the directory that contains the tokenizer files>"
type: "bpe" # can be "bpe" or "wpe"
In the above config file, each language is associated with its own pre-trained tokenizer, which gets assigned
a token id range in the order the tokenizers are listed. To train a multilingual model, one needs to populate the
lang field in the manifest file, allowing the routing of each sample to the correct tokenizer. At inference time,
the routing is done based on the inferred token id range.
For models which utilize sub-word tokenization, we share the decoder module (ConvASRDecoder) with character tokenization models.
All parameters are shared, but for models which utilize sub-word encoding, there are minor differences when setting up the config. For
such models, the tokenizer is utilized to fill in the missing information when the model is constructed automatically.
For example, a decoder config corresponding to a sub-word tokenization model should look similar to the following:
model:
...
decoder:
_target_: nemo.collections.asr.modules.ConvASRDecoder
feat_in: *enc_final
num_classes: -1 # filled with vocabulary size from tokenizer at runtime
vocabulary: [] # filled with vocabulary from tokenizer at runtime
On-the-fly Code Switching#
Nemo supports creating code-switched synthetic utterances on-the-fly during training/validation/testing. This allows you to create ASR models which support intra-utterance code switching. If you have Nemo formatted audio data on disk (either JSON manifests or tarred audio data), you can easily mix as many of these audio sources together as desired by adding some extra parameters to your train_ds, validation_ds, and test_ds.
Please note that this allows you to mix any kind of audio sources together to create synthetic utterances which sample from all sources. The most common use case for this is blending different languages together to create a multilingual code-switched model, but you can also blend together different audio sources from the same languages (or language families), to create noise robust data, or mix fast and slow speech from the same language.
For multilingual code-switched models, we recommend using AggTokenizer for your Tokenizer if mixing different languages.
The following example shows how to mix 3 different languages: English (en), German (de), and Japanese (ja) added to the train_ds model block, however you can add similar logic to your validation_ds and test_ds blocks for on-the-fly code-switched validation and test data too. This example mixes together 3 languages, but you can use as many as you want. However, be advised that the more languages you add, the higher your min_duration and max_duration need to be set to ensure all languages are sampled into each synthetic utterance, and setting these hyperparameters higher will use more VRAM per mini-batch during training and evaluation.
model:
train_ds:
manifest_filepath: [/path/to/EN/tarred_manifest.json, /path/to/DE/tarred_manifest.json, /path/to/JA/tarred_manifest.json]
tarred_audio_filepaths: ['/path/to/EN/tars/audio__OP_0..511_CL_.tar', '/path/to/DE/tars/audio__OP_0..1023_CL_.tar', '/path/to/JA/tars/audio__OP_0..2047_CL_.tar']
is_code_switched: true
is_tarred: true
shuffle: true
code_switched: # add this block for code-switching
min_duration: 12 # the minimum number of seconds for each synthetic code-switched utterance
max_duration: 20 # the maximum number of seconds for each synthetic code-switched utterance
min_monolingual: 0.3 # the minimum percentage of utterances which will be pure monolingual (0.3 = 30%)
probs: [0.25, 0.5, 0.25] # the probability to sample each language (matches order of `language` above) if not provided, assumes uniform distribution
force_monochannel: true # if your source data is multi-channel, then setting this to True will force the synthetic utterances to be mono-channel
sampling_scales: 0.75 # allows you to down/up sample individual languages. Can set this as an array for individual languages, or a scalar for all languages
seed: 123 # add a seed for replicability in future runs (highly useful for `validation_ds` and `test_ds`)
Model Architecture Configurations#
Each configuration file should describe the model architecture being used for the experiment. Models in the NeMo ASR collection need
an encoder section and a decoder section, with the _target_ field specifying the module to use for each.
Here is the list of the parameters in the model section which are shared among most of the ASR models:
Parameter |
Datatype |
Description |
Supported Values |
|---|---|---|---|
|
bool |
Whether a random sample should be printed in the output at each step, along with its predicted transcript. |
|
|
string |
Specifies the reduction type of CTC loss. Defaults to |
|
For more information about the ASR models, refer to the Featured Models section.
Conformer-CTC#
The config files for Conformer-CTC model contain character-based encoding and sub-word encoding at
<NeMo_git_root>/examples/asr/conf/conformer/conformer_ctc_char.yaml and <NeMo_git_root>/examples/asr/conf/conformer/conformer_ctc_bpe.yaml
respectively. Some components of the configs of Conformer-CTC include the following datasets:
train_ds,validation_ds, andtest_dsoptimizer (
optim)augmentation (
spec_augment)decodertrainerexp_manager
There should be a tokenizer section where you can specify the tokenizer if you want to use sub-word encoding instead of character-based encoding.
The encoder section includes the details about the Conformer-CTC encoder architecture. You may find more information in the config files and also nemo.collections.asr.modules.ConformerEncoder.
Conformer-Transducer#
Please refer to the model page of Conformer-Transducer for more information on this model.
Streaming Transformer#
nemo.collections.asr.modules.StreamingTransformerEncoder
is a convolution-free Transformer encoder for streaming ASR. It extends
TransformerEncoder with local attention and a rolling KV cache,
and implements the same cache-aware streaming interface as ConformerEncoder, so it can be
driven by the shared streaming tooling unchanged.
Attention is bounded by att_context_size: [left, right], in encoder frames, under one of two
att_context_style values:
chunked_limited— frames are grouped into chunks ofright + 1, and a query attends to its whole chunk plus theleft // (right + 1)preceding chunks. The look-ahead does not compound across layers, so streaming stays exact at any depth. Use this for in-chunk look-ahead.sliding_window(default) — a query attends to[t - left, t + right]. Exact for streaming only whenright == 0, since a sliding right context compounds across layers.
The read-only cache_size property reports how many encoder frames the rolling KV cache retains.
For sliding_window it equals left. For chunked_limited it is rounded down to the visible
whole chunks when right is finite: (left // (right + 1)) * (right + 1). An unlimited right
context uses left directly. A negative cache size means unbounded left context;
setup_streaming_params maps it to max_context (10,000 frames by default) for the allocated
streaming cache. This is separate from pre_encode_cache_size, which retains input-feature frames
needed before subsampling.
Passing a list of pairs trains one model across several latencies; one entry is sampled per
training batch, and evaluation and streaming use the first entry (or whatever
set_default_att_context_size pins). Select the operating point at inference with
transcribe_speech.py att_context_size=[70,13].
model:
encoder:
_target_: nemo.collections.asr.modules.transformer_encoder.StreamingTransformerEncoder
d_model: 1024
n_heads: 8
n_layers: 48
subsampling: feature_stacking
subsampling_factor: 8
self_attention_model: rope # rel_pos | abs_pos | rope | no_pos
qk_norm: true
att_context_style: chunked_limited
att_context_size: [[70, 13], [70, 6], [70, 1], [70, 0]]
# Input-frame look-back prepended to each streaming chunk so the mel front-end's STFT
# window has its context. Must be a multiple of ``subsampling_factor``. ``FeatureStacking``
# is non-overlapping and needs none of this offline, but a streaming front-end that
# recomputes the spectrogram per chunk does.
pre_encode_cache_size: ${model.encoder.subsampling_factor}
A ready-to-train RNN-T recipe ships at
examples/asr/conf/transformer/transformer_stacking_rnnt_bpe_streaming.yaml.
Transducer Configurations#
All CTC-based ASR model configs can be modified to support Transducer loss training. Below, we discuss the modifications required in the config to enable Transducer training. All modifications are made to the model config.
Model Defaults#
It is a subsection to the model config representing the default values shared across the entire model represented as model.model_defaults.
There are three values that are primary components of a transducer model. They are :
enc_hidden: The hidden dimension of the final layer of the Encoder network.pred_hidden: The hidden dimension of the final layer of the Prediction network.joint_hidden: The hidden dimension of the intermediate layer of the Joint network.
One can access these values inside the config by using OmegaConf interpolation as follows :
model:
...
model_defaults:
enc_hidden: 256
pred_hidden: 256
joint_hidden: 256
...
decoder:
...
prednet:
pred_hidden: ${model.model_defaults.pred_hidden}
Acoustic Encoder Model#
The transducer model is comprised of three models combined. One of these models is the Acoustic (encoder) model. We should be able to drop in any CTC Acoustic model config into this section of the transducer config.
The only condition that needs to be met is that the final layer of the acoustic model must have the hidden dimension defined in ``model_defaults.enc_hidden``.
Decoder / Prediction Model#
The Prediction model is generally an autoregressive, causal model that consumes text tokens and returns embeddings that will be used by the Joint model. The base config for an LSTM based Prediction network can be found in the decoder section of Transducer architectures. For further information refer to the Intro to Transducers tutorial in the ASR tutorial section.
This config can be copy-pasted into any custom transducer model with no modification.
Let us discuss some of the important arguments:
blank_as_pad: In ordinary transducer models, the embedding matrix does not acknowledge theTransducer Blanktoken (similar to CTC Blank). However, this causes the autoregressive loop to be more complicated and less efficient. Instead, this flag which is set by default, will add theTransducer Blanktoken to the embedding matrix - and use it as a pad value (zeros tensor). This enables more efficient inference without harming training. For further information refer to theIntro to Transducerstutorial in the ASR tutorial section.prednet.pred_hidden: The hidden dimension of the LSTM and the output dimension of the Prediction network.
decoder:
_target_: nemo.collections.asr.modules.RNNTDecoder
normalization_mode: null
random_state_sampling: false
blank_as_pad: true
prednet:
pred_hidden: ${model.model_defaults.pred_hidden}
pred_rnn_layers: 1
t_max: null
dropout: 0.0
Joint Model#
The Joint model is a simple feed-forward Multi-Layer Perceptron network. This MLP accepts the output of the Acoustic and Prediction models and computes a joint probability distribution over the entire vocabulary space. The base config for the Joint network can be found in the joint section of Transducer architectures. For further information refer to the Intro to Transducers tutorial in the ASR tutorial section.
This config can be copy-pasted into any custom transducer model with no modification.
The Joint model config has several essential components which we discuss below :
log_softmax: Due to the cost of computing softmax on such large tensors, the Numba CUDA implementation of RNNT loss will implicitly compute the log softmax when called (so its inputs should be logits). The CPU version of the loss doesn’t face such memory issues so it requires log-probabilities instead. Since the behaviour is different for CPU-GPU, theNonevalue will automatically switch behaviour dependent on whether the input tensor is on a CPU or GPU device.preserve_memory: This flag will calltorch.cuda.empty_cache()at certain critical sections when computing the Joint tensor. While this operation might allow us to preserve some memory, the empty_cache() operation is tremendously slow and will slow down training by an order of magnitude or more. It is available to use but not recommended.fuse_loss_wer: This flag performs “batch splitting” and then “fused loss + metric” calculation. It will be discussed in detail in the next tutorial that will train a Transducer model.fused_batch_size: When the above flag is set to True, the model will have two distinct “batch sizes”. The batch size provided in the three data loader configs (model.*_ds.batch_size) will now be theAcoustic modelbatch size, whereas thefused_batch_sizewill be the batch size of thePrediction model, theJoint model, thetransducer lossmodule and thedecodingmodule.turbo_kernel: Optional memory-efficient Joint kernel used to compute the loss during training, see Joint Turbo Kernel. Disabled by default.jointnet.joint_hidden: The hidden intermediate dimension of the joint network.
joint:
_target_: nemo.collections.asr.modules.RNNTJoint
log_softmax: null # sets it according to cpu/gpu device
# fused mode
fuse_loss_wer: false
fused_batch_size: 16
jointnet:
joint_hidden: ${model.model_defaults.joint_hidden}
activation: "relu"
dropout: 0.0
Sampled Softmax Joint Model#
There are some situations where a large vocabulary with a Transducer model - such as for multilingual models with a large number of languages. In this setting, we need to consider the cost of memory of training Transducer networks which does not allow large vocabulary.
For such cases, one can instead utilize the SampledRNNTJoint module instead of the usual RNNTJoint module, in order
to compute the loss using a sampled subset of the vocabulary rather than the full vocabulary file.
It adds only one additional parameter :
n_samples: Specifies the minimum number of tokens to sample from the vocabulary space, excluding the RNNT blank token. If a given value is larger than the entire vocabulary size, then the full vocabulary will be used.
The only difference in config required is to replace nemo.collections.asr.modules.RNNTJoint with nemo.collections.asr.modules.SampledRNNTJoint
joint:
_target_: nemo.collections.asr.modules.SampledRNNTJoint
n_samples: 500
... # All other arguments from RNNTJoint can be used after this.
Effect of Batch Splitting / Fused Batch step#
The following information below explain why memory is an issue when training Transducer models and how NeMo tackles the issue with its Fused Batch step. The material can be read for a thorough understanding, otherwise, it can be skipped. You can also follow these steps in the “ASR_with_Transducers” tutorial.
Diving deeper into the memory costs of Transducer Joint
One of the significant limitations of Transducers is the exorbitant memory cost of computing the Joint module. The Joint module is comprised of two steps.
Projecting the Acoustic and Transcription feature dimensions to some standard hidden dimension (specified by model.model_defaults.joint_hidden)
Projecting this intermediate hidden dimension to the final vocabulary space to obtain the transcription.
Take the following example.
BS=32 ; T (after 2x stride) = 800, U (with character encoding) = 400-450 tokens, Vocabulary size V = 28 (26 alphabet chars, space and apostrophe). Let the hidden dimension of the Joint model be 640 (Most Google Transducer papers use hidden dimension of 640).
Memory (Hidden, gb) = 32 x 800 x 450 x 640 x 4 = 29.49 gigabytes (4 bytes per float).
Memory (Joint, gb) = 32 x 800 x 450 x 28 x 4 = 1.290 gigabytes (4 bytes per float)
NOTE: This is just for the forward pass! We need to double this memory to store gradients! This much memory is also just for the Joint model alone. Far more memory is required for the Prediction model as well as the large Acoustic model itself and its gradients!
Even with mixed precision, that’s ~30 GB of GPU RAM for just 1 part of the network + its gradients.
Effect of Fused Batch Step#
The fundamental problem is that the joint tensor grows in size when [T x U] grows in size. This growth in memory cost is due to many reasons - either by model construction (downsampling) or the choice of dataset preprocessing (character tokenization vs. sub-word tokenization).
Another dimension that NeMo can control is batch. Due to how we batch our samples, small and large samples all get clumped together into a single batch. So even though the individual samples are not all as long as the maximum length of T and U in that batch, when a batch of such samples is constructed, it will consume a significant amount of memory for the sake of compute efficiency.
So as is always the case - trade-off compute speed for memory savings.
The fused operation goes as follows :
Forward the entire acoustic model in a single pass. (Use global batch size here for acoustic model - found in
model.*_ds.batch_size)Split the Acoustic Model’s logits by
fused_batch_sizeand loop over these sub-batches.Construct a sub-batch of same
fused_batch_sizefor the Prediction model. Now the target sequence length is U_sub-batch < U.Feed this U_sub-batch into the Joint model, along with a sub-batch from the Acoustic model (with T_sub-batch < T). Remember, we only have to slice off a part of the acoustic model here since we have the full batch of samples (B, T, D) from the acoustic model.
Performing steps (3) and (4) yields T_sub-batch and U_sub-batch. Perform sub-batch joint step - costing an intermediate (B, T_sub-batch, U_sub-batch, V) in memory.
Compute loss on sub-batch and preserve in a list to be later concatenated.
Compute sub-batch metrics (such as Character / Word Error Rate) using the above Joint tensor and sub-batch of ground truth labels. Preserve the scores to be averaged across the entire batch later.
Delete the sub-batch joint matrix (B, T_sub-batch, U_sub-batch, V). Only gradients from .backward() are preserved now in the computation graph.
Repeat steps (3) - (8) until all sub-batches are consumed.
Cleanup step. Compute full batch WER and log. Concatenate loss list and pass to PTL to compute the equivalent of the original (full batch) Joint step. Delete ancillary objects necessary for sub-batching.
Joint Turbo Kernel#
The Joint output of size [B, T, U+1, V] is usually the largest tensor in Transducer training, and the same amount of memory
is required for its gradient. The RNN-T loss, however, needs only the log-probabilities of the target and blank labels,
two tensors of size [B, T, U+1]. The Joint turbo kernel (joint.turbo_kernel) computes these log-probabilities directly
from the Joint hidden representation [B, T, U+1, H]: the vocabulary projection and log-softmax are fused in a single GPU
kernel, and the logits are recomputed in the backward pass instead of being stored. The Joint output and its gradient
are never materialized, so the memory used by the Joint and the loss does not depend on the vocabulary size, and the batch
does not need to be split, in contrast to the fused batch step described above.
For example, for B=64, T=150, U=72, H=640 in bfloat16 precision, the Joint and the turbo_rnnt loss
(forward and backward) use about 3.1 GB of GPU memory with the turbo kernel for any vocabulary size, compared with 4.8 GB
for the standard Joint with the vocabulary of 1025 tokens, and 23.5 GB with the vocabulary of 8193 tokens. The speed is
similar to the standard Joint or better (measured on RTX A6000 with
tests/collections/asr/turbo_transducer/benchmark_rnnt_joint_multi.py).
The kernel is used only to compute the loss (in training and validation). Decoding, export and the model checkpoints are not affected: the parameters of the Joint are the same, so the kernel can be enabled or disabled for an existing model.
joint:
_target_: nemo.collections.asr.modules.RNNTJoint
log_softmax: null
fuse_loss_wer: false # incompatible with the turbo kernel
turbo_kernel:
type: fused_vocab # options: null (disabled), fused_vocab
backend: triton # the only implemented backend
use_high_precision_mm: false
mm_full_precision: false
input_grad_full_precision: false
weight_grad_full_precision: false
backward_mode: chunked # options: chunked, atomic (experimental)
pruning: # experimental
type: null # options: null (disabled), backward, two_pass
range_size: 16 # target positions per frame; use values 8 or 16
start_step: 5000
jointnet:
joint_hidden: ${model.model_defaults.joint_hidden}
activation: "relu"
dropout: 0.2
loss:
loss_name: "turbo_rnnt" # the loss must accept target and blank log-probabilities
The turbo_kernel section has the following parameters (unknown parameters are rejected):
type: The kernel type.null(or a missingturbo_kernelsection) disables the kernel, the other parameters are ignored.fused_vocabfuses the vocabulary projection with log-softmax; the Joint hidden representation is still materialized.backend:triton(default, requires Triton) is the only implemented backend;nullselects it automatically.cutileis reserved for the planned cuTile backend: requesting it raisesNotImplementedError.mm_full_precision: Withbfloat16activations (trainer.precision: bf16), the vocabulary projection is computed withbfloat16operands, while the parameters are stored infloat32. Set totrueto usefloat32operands: more accurate, but slower. Log-softmax is always computed infloat32.use_high_precision_mm: Usefloat32operands and IEEE precision for the matrix multiplication in Triton instead of the default (TF32). Impliesmm_full_precision. Mostly useful for testing and debugging.input_grad_full_precision,weight_grad_full_precision: Accumulate the gradient for the Joint hidden representation / the weight of the vocabulary projection infloat32instead of the dtype of the activations.backward_mode: The algorithm of the backward pass.chunked(default, also selected bynull) processes the lattice by chunks: a GPU kernel computes the gradient for the logits of a chunk into a buffer of a fixed size (128 MiB), and the gradients are computed from it by matrix multiplications.atomicrecomputes the logits and accumulates all gradients in a single GPU kernel with atomic operations, without the buffer.atomicis experimental: its behavior can change in future releases. It requires Triton 3.4 or higher forbfloat16gradients, and it was slower thanchunkedon the GPUs where both algorithms were compared (RTX A6000, GB300); nativebfloat16atomic operations are available only on the GPUs with compute capability 9.0 or higher (e.g., H100 or newer). Both algorithms compute the same gradients (input_grad_full_precisionandweight_grad_full_precisionaffect onlyatomic;chunkedrounds each gradient once).pruning: Optional section, a missing section ornulldisables pruning. Pruning is experimental: its behavior and parameters can change in future releases, and a warning is logged when it is enabled. With pruning, the Joint is evaluated only forrange_sizecontiguous target positions (a pruning range) for each frame, since the alignments with non-negligible probability pass only through a narrow band of the lattice. Pruning is applied only in training mode. The section has the following parameters:type:null(default) disables pruning, the other parameters are ignored.backwardcomputes the forward pass for the full lattice and selects the ranges with the largest gradient of the loss for the target and blank log-probabilities; only the backward pass of the Joint is pruned. The loss value is not changed, but its gradient is approximated. The backward pass is several times faster for large vocabularies.two_passfirst evaluates the Joint for the full lattice without gradient (and without dropout) and selects the ranges with the largest probability that an alignment passes through them. The ranges are adjusted to form a connected lattice (as in the pruned RNN-T loss of k2). Then the Joint is evaluated only for the ranges, with gradient. The loss is the loss of the pruned lattice: it is not less than the loss of the full lattice, and its gradient is exact. The activations required for the backward pass are stored only for the ranges, so the memory used by the Joint is several times lower, and the backward pass is faster than withbackwardpruning. The RNN-T loss of the full lattice computed by the first pass is logged astrain_loss_full_lattice. It is a baseline computed without dropout (and without masking of the prediction network output) and FastEmit scaling, whiletrain_loss(train_rnnt_lossfor Hybrid RNNT-CTC models) is computed for the pruned lattice with the training settings, andtrain_losscan include auxiliary losses. The difference between them is therefore only a rough indicator: it does not isolate the probability of the alignments removed by pruning, and it also changes with dropout and the configuration of the loss.train_loss_full_latticeis not logged for the batches without pruning (beforestart_step, or if the range covers all target positions). With the consistency loss, it is computed (and normalized) only for the positions inside the ranges. A frame can emit at mostrange_size - 1tokens inside its range: the loss is infinite for an utterance with more than(range_size - 1) * num_framestokens.range_size: The number of target positions per frame, required iftypeis set: at least 1 forbackwardand at least 2 fortwo_pass. If the range covers all target positions of a batch, the full lattice is used.start_step: The first optimizer step with pruning. Before this step the full lattice is used, since the alignments of a randomly initialized model are not reliable.null(or a non-positive value) enables pruning from the first step. Note that the memory required beforestart_stepis the memory of training without pruning.
Requirements and limitations:
A CUDA GPU and the
turbo_rnntloss (see Turbo-RNNT Loss) without gradient clamping (clamp): clamping is applied to the gradient for the Joint output, which is not materialized. An incompatible loss is rejected when the model is constructed.The loss does not depend on the temperature set by the decoding config (
decoding.temperature): the temperature is applied only in decoding. Note that the Joint output of the standard Joint withlog_softmax: trueis scaled by the temperature, so the loss computed from it differs if the temperature is not 1.The
tritonbackend supports Triton 3.3 and newer (the version installed with PyTorch 2.7). The kernels are autotuned: on the first training steps (separately for small and for full-size batches) Triton compiles several variants of each kernel and selects the fastest one for the GPU, which takes up to a minute for large vocabularies. The result is cached on disk (~/.triton/cache, or the directory set by theTRITON_CACHE_DIRenvironment variable) and reused by the next runs. Triton 3.3 does not cache the results: the kernels are autotuned in each run.Not compatible with
fuse_loss_wer,preserve_memoryand the Joint with extra outputs (e.g., TDT models).Supported by
RNNTJoint;HATJointandSampledRNNTJointdo not support the kernel.Supported by all ASR models with the RNN-T loss, including Hybrid RNNT-CTC models and the models with prompt conditioning.
A complete example config can be found at <NeMo_git_root>/examples/asr/conf/transformer/transformer_stacking_rnnt_bpe.yaml.
Transducer Decoding#
Models which have been trained with CTC can transcribe text simply by performing a regular argmax over the output of their decoder. For transducer-based models, the three networks must operate in a synchronized manner in order to transcribe the acoustic features. The base config for the Transducer decoding step can be found in the decoding section of Transducer architectures. For further information refer to the Intro to Transducers tutorial in the ASR tutorial section.
This config can be copy-pasted into any custom transducer model with no modification.
The most important component at the top level is the strategy. It can take one of many values:
greedy: This is sample-level greedy decoding. It is generally exceptionally slow as each sample in the batch will be decoded independently. For publications, this should be used alongside batch size of 1 for exact results.greedy_batch: This is the general default and should nearly match thegreedydecoding scores (if the acoustic features are not affected by feature mixing in batch mode). Even for small batch sizes, this strategy is significantly faster thangreedy.beam: Runs beam search with the implicit language model of the Prediction model. It will generally be quite slow, and might need some tuning of the beam size to get better transcriptions.tsd: Time synchronous decoding. Please refer to the paper: Alignment-Length Synchronous Decoding for RNN Transducer for details on the algorithm implemented. Time synchronous decoding (TSD) execution time grows by the factor T * max_symmetric_expansions. For longer sequences, T is greater and can therefore take a long time for beams to obtain good results. TSD also requires more memory to execute.alsd: Alignment-length synchronous decoding. Please refer to the paper: Alignment-Length Synchronous Decoding for RNN Transducer for details on the algorithm implemented. Alignment-length synchronous decoding (ALSD) execution time is faster than TSD, with a growth factor of T + U_max, where U_max is the maximum target length expected during execution. Generally, T + U_max < T * max_symmetric_expansions. However, ALSD beams are non-unique. Therefore it is required to use larger beam sizes to achieve the same (or close to the same) decoding accuracy as TSD. For a given decoding accuracy, it is possible to attain faster decoding via ALSD than TSD.maes: Modified Adaptive Expansion Search Decoding. Please refer to the paper Accelerating RNN Transducer Inference via Adaptive Expansion Search. Modified Adaptive Synchronous Decoding (mAES) execution time is adaptive w.r.t the number of expansions (for tokens) required per timestep. The number of expansions can usually be constrained to 1 or 2, and in most cases 2 is sufficient. This beam search technique can possibly obtain superior WER while sacrificing some evaluation time.
decoding:
strategy: "greedy_batch"
# preserve decoding alignments
preserve_alignments: false
# Overrides the fused batch size after training.
# Setting it to -1 will process whole batch at once when combined with `greedy_batch` decoding strategy
fused_batch_size: -1
# greedy strategy config
greedy:
max_symbols: 10
# beam strategy config
beam:
beam_size: 2
score_norm: true
softmax_temperature: 1.0 # scale the logits by some temperature prior to softmax
tsd_max_sym_exp: 10 # for Time Synchronous Decoding, int > 0
alsd_max_target_len: 5.0 # for Alignment-Length Synchronous Decoding, float > 1.0
maes_num_steps: 2 # for modified Adaptive Expansion Search, int > 0
maes_prefix_alpha: 1 # for modified Adaptive Expansion Search, int > 0
maes_expansion_beta: 2 # for modified Adaptive Expansion Search, int >= 0
maes_expansion_gamma: 2.3 # for modified Adaptive Expansion Search, float >= 0
Transducer Loss#
This section configures the type of Transducer loss itself, along with possible sub-sections. By default, an optimized implementation of Transducer loss will be used which depends on Numba for CUDA acceleration. The base config for the Transducer loss section can be found in the loss section of Transducer architectures. For further information refer to the Intro to Transducers tutorial in the ASR tutorial section.
This config can be copy-pasted into any custom transducer model with no modification.
The loss config is based on a resolver pattern and can be used as follows:
loss_name:defaultis generally a good option. Will select one of the available resolved losses and match the kwargs from a sub-configs passed via explicit{loss_name}_kwargssub-config.{loss_name}_kwargs: This sub-config is passed to the resolved loss above and can be used to configure the resolved loss.
loss:
loss_name: "default"
warprnnt_numba_kwargs:
fastemit_lambda: 0.0
Turbo-RNNT Loss#
turbo_rnnt is a memory-efficient RNN-T loss implemented in Triton (requires a CUDA GPU and Triton 3.3 or newer).
It first reduces the Joint output to the log-probabilities of the target and blank labels with a fused log-softmax kernel,
then computes the loss from these small tensors. Computations are performed in float32, but the gradient for the Joint output
is stored in the dtype of the Joint output, so bfloat16 training does not require upcasting the Joint output to float32.
This makes the loss significantly faster than warprnnt_numba and reduces memory usage for bfloat16 training.
loss:
loss_name: "turbo_rnnt"
turbo_rnnt_kwargs:
fastemit_lambda: 0.0
Since the loss does not materialize additional full-size tensors, fused Joint and loss computation (fuse_loss_wer) is not
required to limit the memory used by the loss itself. Fused computation can still reduce the memory used by the Joint output
and its gradient (they are computed in sub-batches with the padding trimmed), so disable it for faster training when
the full Joint output fits in memory. To avoid materializing the Joint output without splitting the batch, use
the Joint Turbo Kernel.
Gradient clamping is supported with the clamp argument (as for warprnnt_numba): when set to a positive value,
the gradient of each per-utterance loss for the Joint output is clamped to [-clamp, clamp] before the reduction of the loss
is applied, so the result does not depend on the batch size. Clamping is computed in the same kernel as the gradient
and does not affect the speed or memory usage of the loss.
loss:
loss_name: "turbo_rnnt"
turbo_rnnt_kwargs:
clamp: 1.0
The loss is infinite for an utterance without a valid alignment (e.g., -inf logits for a target label), and NaN for invalid
targets (labels outside the vocabulary). Set mask_non_finite: true in turbo_rnnt_kwargs to exclude such utterances
from the loss (zero loss and gradient), and warn_non_finite: true to log them.
Numba Transducer Warmup#
RNNT models automatically warm up Numba loss kernels on CUDA before training, including supported FP16 RNNT kernels and both FP32 branches for TDT models. This reduces memory retained during compilation without changing random states.
Custom training loops can call RNNTLoss.warmup(device) before allocating batch activations.
FastEmit Regularization#
FastEmit Regularization is supported for the default Numba based WarpRNNT loss and for the turbo_rnnt loss. Recently proposed regularization approach - FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization allows us near-direct control over the latency of transducer models.
Refer to the above paper for results and recommendations of fastemit_lambda.
For decoding customization (confidence scores, CUDA graphs, language models, word boosting), see ASR Language Modeling and Customization.
InterCTC Config#
All CTC-based models also support InterCTC loss. To use it, you need to specify 2 parameters as in example below
model:
# ...
interctc:
loss_weights: [0.3]
apply_at_layers: [8]
which can be used to reproduce the default setup from the paper (assuming the total number of layers is 18). You can also specify multiple CTC losses from different layers, e.g., to get 2 losses from layers 3 and 8 with weights 0.1 and 0.3, specify:
model:
# ...
interctc:
loss_weights: [0.1, 0.3]
apply_at_layers: [3, 8]
Note that the final-layer CTC loss weight is automatically computed to normalize all weight to 1 (0.6 in the example above).
Stochastic Depth Config#
Stochastic Depth is a useful technique for regularizing ASR model training. Currently it’s only supported for nemo.collections.asr.modules.ConformerEncoder. To use it, specify the following parameters in the encoder config file to reproduce the default setup from the paper:
model:
# ...
encoder:
# ...
stochastic_depth_drop_prob: 0.3
stochastic_depth_mode: linear # linear or uniform
stochastic_depth_start_layer: 1
See documentation of ConformerEncoder for more details. Note that stochastic depth is supported for both CTC and Transducer model variations (or any other kind of model/loss that’s using conformer as encoder).
Fused Subsampling Kernels Config#
With Triton installed, the dw_striding pre-encoder of
nemo.collections.asr.modules.ConformerEncoder runs as fused Triton kernels rather than
separate PyTorch convolutions. Weights and checkpoints are identical either way, so only speed and peak memory change.
The kernels need dw_striding, a subsampling_factor of 4 or more, a ReLU activation and CUDA inputs. Anything
else uses the PyTorch path, as do tracing and export. Use use_triton to control this:
model:
# ...
encoder:
# ...
use_triton: false # null, the default, uses the kernels when Triton is installed
Asking for use_triton: true on a configuration the kernels do not cover logs a warning and falls back to PyTorch.
Asking for it without Triton installed raises on the first forward pass that would have used the kernels.
Per-Stage Time Strides in Convolutional Subsampling#
ConvSubsampling with subsampling: striding halves time and frequency in every 3x3 stage,
so its subsampling_factor is a power of two.
conv_strides gives each stage its own time stride instead, with the product of the strides as the factor,
and the stages then keep the frequency axis;
freq_pools adds an optional max-pool over the frequency axis after each stage (1 for none).
conv_channels may name the channels per stage, and out_bias controls the bias of the output projection.
A factor of 6 reads:
from nemo.collections.asr.parts.submodules.subsampling import ConvSubsampling
subsampling = ConvSubsampling(
subsampling="striding",
subsampling_factor=6,
feat_in=80,
feat_out=512,
conv_channels=[32, 64, 64],
conv_strides=[1, 3, 2],
freq_pools=[2, 1, 1],
out_bias=False,
)
The output lengths follow the stages one by one,
batch chunking (subsampling_conv_chunking_factor) applies as for the stride-2 form,
and the module exports to ONNX.
Hybrid-Transducer-CTC with Prompt Conditioning Configuration#
The Hybrid-Transducer-CTC model with prompt conditioning
(EncDecHybridRNNTCTCBPEModelWithPrompt) extends the base hybrid model to support prompt-based multilingual ASR/AST.
Key Configuration Parameters:
The model introduces several prompt-specific configuration parameters in the model_defaults section:
model:
model_defaults:
# Prompt Feature Configuration
initialize_prompt_feature: true # Enable prompt conditioning
num_prompts: 128 # Number of supported prompt categories
prompt_dictionary: { # Mapping from identifiers to prompt indices
# Language prompts (0-99)
'en-US': 0,
'de-DE': 1,
'fr-FR': 2,
'es-ES': 3,
# Task/domain prompts (100-127)
'pnc': 100, # Punctuation mode
'no_pnc': 101, # No punctuation mode
}
Dataset Configuration:
The model requires training data with language annotations when using Lhotse datasets:
model:
train_ds:
use_lhotse: true
initialize_prompt_feature: true
lang_field: target_lang # Manifest key holding the utterance language
prompt_dictionary: ${model.model_defaults.prompt_dictionary}
num_prompts: ${model.model_defaults.num_prompts}
default_prompt_mode: unified # langID | auto | unified
unified_auto_ratio: 0.5 # Probability of the "auto" prompt in unified mode
validation_ds:
use_lhotse: true
initialize_prompt_feature: true
lang_field: target_lang
prompt_dictionary: ${model.model_defaults.prompt_dictionary}
num_prompts: ${model.model_defaults.num_prompts}
default_prompt_mode: langID
The prompt index for each utterance is chosen by its prompt mode:
langID: the utterance’s language.auto: the language-agnosticautoprompt.unified:autowith probabilityunified_auto_ratio, otherwise the utterance’s language. This is the default; it trains one model for both prompted and language-agnostic decoding.
A Lhotse input config can set the mode per dataset with tags: {prompt_mode: langID}; otherwise
default_prompt_mode applies. Transcription always uses langID.
Manifest Format:
The language is read from the manifest key named by lang_field (lang by default; the example
configs use target_lang). It must be a key of prompt_dictionary, or a bare code such as en
that matches exactly one locale key; unsupported languages raise an error.
{
"audio_filepath": "/path/to/audio.wav",
"text": "transcription text",
"duration": 10.5,
"target_lang": "en-US"
}
Example Configuration:
A complete example configuration can be found at:
<NeMo_git_root>/examples/asr/conf/fastconformer/hybrid_transducer_ctc/fastconformer_hybrid_transducer_ctc_bpe_prompt.yaml
Training Command:
python <NeMo_git_root>/examples/asr/asr_hybrid_transducer_ctc/speech_to_text_hybrid_rnnt_ctc_bpe_prompt.py \
--config-path=<NeMo_git_root>/examples/asr/conf/fastconformer/hybrid_transducer_ctc/ \
--config-name=fastconformer_hybrid_transducer_ctc_bpe_prompt.yaml \
model.train_ds.manifest_filepath=<path_to_train_manifest> \
model.validation_ds.manifest_filepath=<path_to_val_manifest> \
model.tokenizer.dir=<path_to_tokenizer> \
model.test_ds.manifest_filepath=<path_to_test_manifest>
RNN-T with Prompt Conditioning Configuration#
The RNN-T model with prompt conditioning
(EncDecRNNTBPEModelWithPrompt) is the RNN-T-only counterpart of the hybrid prompt model
(no auxiliary CTC head). It targets cache-aware streaming multilingual ASR using the same
one-hot language-ID prompt concatenation as the hybrid variant.
Key Configuration Parameters:
The prompt-specific parameters live in the model_defaults section, mirroring the hybrid
variant:
model:
model_defaults:
# Prompt Feature Configuration
initialize_prompt_feature: true # Enable prompt conditioning
num_prompts: 128 # Number of supported prompt categories
prompt_dictionary: { # Mapping from identifiers to prompt indices
'en-US': 0,
'de-DE': 1,
'fr-FR': 2,
'es-ES': 3,
# ... additional language codes ...
'auto': 127, # Language-agnostic prompt
}
Dataset Configuration:
The model uses the same index-based Lhotse dataset
(LhotseSpeechToTextBpeDatasetWithPromptIndex) as the hybrid model:
model:
train_ds:
use_lhotse: true
initialize_prompt_feature: true
lang_field: target_lang
prompt_dictionary: ${model.model_defaults.prompt_dictionary}
num_prompts: ${model.model_defaults.num_prompts}
default_prompt_mode: unified # langID | auto | unified
unified_auto_ratio: 0.5
validation_ds:
use_lhotse: true
initialize_prompt_feature: true
lang_field: target_lang
prompt_dictionary: ${model.model_defaults.prompt_dictionary}
num_prompts: ${model.model_defaults.num_prompts}
default_prompt_mode: langID
Prompt modes behave as described for the hybrid model.
Manifest Format:
Identical to the hybrid model — each entry needs a target_lang field:
{
"audio_filepath": "/path/to/audio.wav",
"text": "transcription text",
"duration": 10.5,
"target_lang": "en-US"
}
Example Configuration:
A cache-aware streaming RNN-T prompt config ships at:
<NeMo_git_root>/examples/asr/conf/fastconformer/cache_aware_streaming/fastconformer_transducer_bpe_streaming_prompt.yaml
Training Command:
python <NeMo_git_root>/examples/asr/asr_transducer/speech_to_text_rnnt_bpe_prompt.py \
--config-path=<NeMo_git_root>/examples/asr/conf/fastconformer/cache_aware_streaming/ \
--config-name=fastconformer_transducer_bpe_streaming_prompt.yaml \
model.train_ds.manifest_filepath=<path_to_train_manifest> \
model.validation_ds.manifest_filepath=<path_to_val_manifest> \
model.tokenizer.dir=<path_to_tokenizer> \
model.test_ds.manifest_filepath=<path_to_test_manifest>
Streaming Inference:
The standard cache-aware streaming inference script accepts target_lang (and the optional
strip_lang_tags / lang_tag_pattern flags) for prompt-conditioned models:
python <NeMo_git_root>/examples/asr/asr_cache_aware_streaming/speech_to_text_cache_aware_streaming_infer.py \
model_path=<path_to_nemo_checkpoint> \
dataset_manifest=<path_to_manifest> \
target_lang=<en-US|auto|...> \
strip_lang_tags=true