• Docs >
  • Online ASR with Emformer RNN-T
Shortcuts

Online ASR with Emformer RNN-T

Author: Jeff Hwang, Moto Hira

This tutorial shows how to use Emformer RNN-T and streaming API to perform online speech recognition.

Note

This tutorial requires Streaming API, FFmpeg libraries (>=4.1, <5), and SentencePiece.

The Streaming API is available in nightly builds. Please refer to https://pytorch.org/get-started/locally/ for instructions.

There are multiple ways to install FFmpeg libraries. If you are using Anaconda Python distribution, conda install 'ffmpeg<5' will install the required FFmpeg libraries.

You can install SentencePiece by running pip install sentencepiece.

1. Overview

Performing online speech recognition is composed of the following steps

  1. Build the inference pipeline Emformer RNN-T is composed of three components: feature extractor, decoder and token processor.

  2. Format the waveform into chunks of expected sizes.

  3. Pass data through the pipeline.

2. Preparation

import IPython
import torch
import torchaudio

try:
    from torchaudio.io import StreamReader
except ModuleNotFoundError:
    try:
        import google.colab

        print(
            """
            To enable running this notebook in Google Colab, install nightly
            torch and torchaudio builds and the requisite third party libraries by
            adding the following code block to the top of the notebook before running it:

            !pip3 uninstall -y torch torchvision torchaudio
            !pip3 install --pre torch torchaudio --extra-index-url https://download.pytorch.org/whl/nightly/cpu
            !pip3 install sentencepiece
            !add-apt-repository -y ppa:savoury1/ffmpeg4
            !apt-get -qq install -y ffmpeg
            """
        )
    except ModuleNotFoundError:
        pass
    raise

print(torch.__version__)
print(torchaudio.__version__)

Out:

1.12.0
0.12.0

3. Construct the pipeline

Pre-trained model weights and related pipeline components are bundled as torchaudio.pipelines.RNNTBundle().

We use torchaudio.pipelines.EMFORMER_RNNT_BASE_LIBRISPEECH(), which is a Emformer RNN-T model trained on LibriSpeech dataset.

bundle = torchaudio.pipelines.EMFORMER_RNNT_BASE_LIBRISPEECH

feature_extractor = bundle.get_streaming_feature_extractor()
decoder = bundle.get_decoder()
token_processor = bundle.get_token_processor()

Out:

  0%|          | 0.00/3.81k [00:00<?, ?B/s]
100%|##########| 3.81k/3.81k [00:00<00:00, 2.40MB/s]

  0%|          | 0.00/293M [00:00<?, ?B/s]
  2%|1         | 5.32M/293M [00:00<00:05, 55.8MB/s]
  4%|3         | 10.6M/293M [00:00<00:05, 53.5MB/s]
  6%|6         | 18.0M/293M [00:00<00:04, 64.1MB/s]
  9%|9         | 26.7M/293M [00:00<00:03, 74.7MB/s]
 12%|#2        | 35.7M/293M [00:00<00:03, 81.7MB/s]
 15%|#5        | 44.7M/293M [00:00<00:03, 85.6MB/s]
 18%|#8        | 53.5M/293M [00:00<00:02, 87.9MB/s]
 21%|##1       | 62.0M/293M [00:00<00:02, 88.3MB/s]
 24%|##4       | 70.4M/293M [00:00<00:02, 84.9MB/s]
 27%|##6       | 79.0M/293M [00:01<00:02, 86.3MB/s]
 30%|##9       | 87.6M/293M [00:01<00:02, 87.6MB/s]
 33%|###2      | 96.6M/293M [00:01<00:02, 89.5MB/s]
 36%|###5      | 105M/293M [00:01<00:02, 78.9MB/s]
 39%|###8      | 113M/293M [00:01<00:02, 80.7MB/s]
 41%|####1     | 121M/293M [00:01<00:02, 81.0MB/s]
 44%|####4     | 130M/293M [00:01<00:02, 84.1MB/s]
 47%|####7     | 139M/293M [00:01<00:01, 84.8MB/s]
 50%|#####     | 147M/293M [00:01<00:01, 83.0MB/s]
 53%|#####3    | 155M/293M [00:01<00:01, 85.1MB/s]
 56%|#####5    | 164M/293M [00:02<00:01, 86.8MB/s]
 59%|#####9    | 173M/293M [00:02<00:01, 88.6MB/s]
 62%|######1   | 181M/293M [00:02<00:01, 88.4MB/s]
 65%|######4   | 190M/293M [00:02<00:01, 88.0MB/s]
 68%|######7   | 198M/293M [00:02<00:01, 85.7MB/s]
 71%|#######   | 207M/293M [00:02<00:01, 87.6MB/s]
 74%|#######3  | 215M/293M [00:02<00:00, 86.4MB/s]
 76%|#######6  | 224M/293M [00:02<00:00, 86.2MB/s]
 79%|#######9  | 232M/293M [00:02<00:00, 87.7MB/s]
 82%|########2 | 241M/293M [00:03<00:00, 83.2MB/s]
 85%|########4 | 249M/293M [00:03<00:00, 83.6MB/s]
 88%|########7 | 257M/293M [00:03<00:00, 82.5MB/s]
 91%|######### | 265M/293M [00:03<00:00, 84.3MB/s]
 93%|#########3| 274M/293M [00:03<00:00, 85.3MB/s]
 96%|#########6| 282M/293M [00:03<00:00, 84.5MB/s]
 99%|#########9| 291M/293M [00:03<00:00, 86.4MB/s]
100%|##########| 293M/293M [00:03<00:00, 83.9MB/s]

  0%|          | 0.00/295k [00:00<?, ?B/s]
100%|##########| 295k/295k [00:00<00:00, 43.0MB/s]

Streaming inference works on input data with overlap. Emformer RNN-T model treats the newest portion of the input data as the “right context” — a preview of future context. In each inference call, the model expects the main segment to start from this right context from the previous inference call. The following figure illustrates this.

https://download.pytorch.org/torchaudio/tutorial-assets/emformer_rnnt_context.png

The size of main segment and right context, along with the expected sample rate can be retrieved from bundle.

sample_rate = bundle.sample_rate
segment_length = bundle.segment_length * bundle.hop_length
context_length = bundle.right_context_length * bundle.hop_length

print(f"Sample rate: {sample_rate}")
print(f"Main segment: {segment_length} frames ({segment_length / sample_rate} seconds)")
print(f"Right context: {context_length} frames ({context_length / sample_rate} seconds)")

Out:

Sample rate: 16000
Main segment: 2560 frames (0.16 seconds)
Right context: 640 frames (0.04 seconds)

4. Configure the audio stream

Next, we configure the input audio stream using StreamReader().

For the detail of this API, please refer to the Media Stream API tutorial.

The following audio file was originally published by LibriVox project, and it is in the public domain.

https://librivox.org/great-pirate-stories-by-joseph-lewis-french/

It was re-uploaded for the sake of the tutorial.

src = "https://download.pytorch.org/torchaudio/tutorial-assets/greatpiratestories_00_various.mp3"

streamer = StreamReader(src)
streamer.add_basic_audio_stream(frames_per_chunk=segment_length, sample_rate=bundle.sample_rate)

print(streamer.get_src_stream_info(0))
print(streamer.get_out_stream_info(0))

Out:

StreamReaderSourceAudioStream(media_type='audio', codec='mp3', codec_long_name='MP3 (MPEG audio layer 3)', format='fltp', bit_rate=128000, num_frames=0, bits_per_sample=0, sample_rate=44100.0, num_channels=2)
StreamReaderOutputStream(source_index=0, filter_description='aresample=16000,aformat=sample_fmts=fltp')

As previously explained, Emformer RNN-T model expects input data with overlaps; however, Streamer iterates the source media without overlap, so we make a helper structure that caches a part of input data from Streamer as right context and then appends it to the next input data from Streamer.

The following figure illustrates this.

https://download.pytorch.org/torchaudio/tutorial-assets/emformer_rnnt_streamer_context.png
class ContextCacher:
    """Cache the end of input data and prepend the next input data with it.

    Args:
        segment_length (int): The size of main segment.
            If the incoming segment is shorter, then the segment is padded.
        context_length (int): The size of the context, cached and appended.
    """

    def __init__(self, segment_length: int, context_length: int):
        self.segment_length = segment_length
        self.context_length = context_length
        self.context = torch.zeros([context_length])

    def __call__(self, chunk: torch.Tensor):
        if chunk.size(0) < self.segment_length:
            chunk = torch.nn.functional.pad(chunk, (0, self.segment_length - chunk.size(0)))
        chunk_with_context = torch.cat((self.context, chunk))
        self.context = chunk[-self.context_length :]
        return chunk_with_context

5. Run stream inference

Finally, we run the recognition.

First, we initialize the stream iterator, context cacher, and state and hypothesis that are used by decoder to carry over the decoding state between inference calls.

cacher = ContextCacher(segment_length, context_length)

state, hypothesis = None, None

Next we, run the inference.

For the sake of better display, we create a helper function which processes the source stream up to the given times and call it repeatedly.

stream_iterator = streamer.stream()


@torch.inference_mode()
def run_inference(num_iter=200):
    global state, hypothesis
    chunks = []
    for i, (chunk,) in enumerate(stream_iterator, start=1):
        segment = cacher(chunk[:, 0])
        features, length = feature_extractor(segment)
        hypos, state = decoder.infer(features, length, 10, state=state, hypothesis=hypothesis)
        hypothesis = hypos[0]
        transcript = token_processor(hypothesis[0], lstrip=False)
        print(transcript, end="", flush=True)

        chunks.append(chunk)
        if i == num_iter:
            break

    return IPython.display.Audio(torch.cat(chunks).T.numpy(), rate=bundle.sample_rate)
run_inference()

Out:

forward great pirate's this is aver's recording all thects recordings are in the public dum for more information or please visit liberg recording by james christopher great pirite stories by various edited by josey embodies the romance of theed expression it is a sad but inevable comment on our civilization that so far as the sea is concerned


run_inference()

Out:

it is developed from its infancy down to a century or so ago under one phase or another of pircy if men were savages on land they were doubly so at sea and all the years oftime adventure years that added to theap world there was little left to discover could not wholly eradate theat germ it went out gradually with the settlement of the farmed colonies great britain foremost of sea powers must be credit both directly and indirely for theation of crime and disord on the high seas than any other


run_inference()

Out:

force but the conquest was not complete till the advent the sea rover into the farthest corners of his domini it is said that he survised even to day in certain spots in the chinese but he is certainly an innocuous rolle a pir of any sort would be as great a curiosity to day if he could be caught and exhibited as a fab's the fact remains and will always persist that in theore of the sea he is far away the most picturesque figure in the more genuine and gross his character the higher degree of interest as he inspire there


run_inference()

Out:

may be a certain perversity in this for the pirate was unquestionably a bad man at his best or worst consid his surrene's andtily the worst man that ever lived there is little to soften the dark yet glowing picture of his explox but again it must be remembered that not only does the note of distant subdu and even lend a certain enchantment to the scene but the effective contrast between our peaceful times andributes much to deepen our interest in him perhaps it is this latter added to that death waspen breast that


run_inference()

Out:

glows at the tale of adventure which makes them the kind of hero of romance that is today he is undeni redoubtable historical figure it is a curious fact that commerce was crad in the lapane the constant danger of the deeps in this form only made heartier marin of the merchras actually stimating and strenuing maritime enterprise bucco turned for piry thus became the high romance of the sea the great centuries ofton venture it went hand in hand with disco


run_inference()

Out:

very they were in fact almost insepar most of mighty mariners from the days of leafou through those of the redoubtable sir francis drakeke down to our owns answered to the roll it was a bold hearty world this avarice up to the advent our giant steam every foot of which was won by fierce conquest of one sort or another out of this pass the pir emerges are romantic even at times heroic figure this final niche despite his crimes cannot altogether be denied a heroi is and all remained


run_inference()

Out:

so long as tales of the are told so have him in these pages joseth lewich and of four recording by james christopher jist christ christopher yah come


Total running time of the script: ( 3 minutes 21.860 seconds)

Gallery generated by Sphinx-Gallery

Docs

Access comprehensive developer documentation for PyTorch

View Docs

Tutorials

Get in-depth tutorials for beginners and advanced developers

View Tutorials

Resources

Find development resources and get your questions answered

View Resources