AI Logic

Architectures

Speech-Transformer

Updated:

Architecture of Speech-Transformer. The left side shows the overall flow (the encoder goes speech features → two 3×3, stride-2 convolutions → 2D-Attention × M (optional) → linear layer → positional encoding → encoder blocks × Ne; the decoder goes previous outputs → output embedding and positional encoding → decoder blocks × Nd that attend to the encoder output → linear layer and softmax → next character). The right side shows the inside of 2D-Attention (three convolutions produce Q, K, and V; attention is computed along time and along frequency; the 2c channels are concatenated and a convolution combines them into n channels)

Background and overview

Speech-Transformer is an encoder–decoder model that adapts the machine translation Transformer to speech recognition, producing a character sequence from speech using attention alone, without recurrence (RNNs). It was proposed in 2018 by Dong et al. at the Institute of Automation, Chinese Academy of Sciences.

Earlier encoder–decoder models for speech recognition (such as Listen, Attend and Spell) were built with recurrent networks like the LSTM. Recurrent networks compute one time step after another, which makes training hard to parallelize and slow. Speech-Transformer tackled this problem in two ways.

  • Removing recurrence: both the encoder and decoder are built only from self-attention and feed-forward layers. The relationship between any positions in the sequence can be computed at once, making training easier to parallelize.
  • Adapting to speech input: speech features (spectrograms) are like 2D images of time and frequency. The model first subsamples time and frequency with convolutions to shorten the sequence, and further proposes 2D-Attention, which applies attention along both the time and frequency axes.

According to the paper's abstract, it achieved a word error rate of 10.9% on WSJ (Wall Street Journal), a dataset of read English speech, with training taking only 1.2 days on a single GPU. The paper states that this is significantly faster than published results of recurrent encoder–decoder models. It is one of the early examples of using the Transformer as an encoder–decoder for speech recognition.

Architecture

Speech-Transformer consists of an encoder and a decoder. In the figure at the top of the article, the left side shows the overall flow and the right side shows the inside of 2D-Attention.

The encoder processes the input in the following order.

  1. Input: filterbank features (2D: time × frequency).
  2. Two convolutional layers: two convolutions of size 3×3 with stride 2 subsample both time and frequency. This part replaces the "word embedding" of the machine translation Transformer and shortens the sequence to lighten the attention computation.
  3. MM 2D-Attention modules (optional): stacked modules that capture relationships along time and frequency.
  4. Linear layer: flattens the convolution output and projects it to the model dimension.
  5. Add positional encoding: attention has no notion of order, so positional encoding adds the position of each time step.
  6. NeN_e encoder blocks: each consists of two parts, multi-head self-attention and a feed-forward network, each wrapped with a residual connection and layer normalization.

The decoder is almost the same as in the machine translation Transformer.

  1. Input: the sequence of characters produced so far, shifted one position to the right.
  2. Output embedding and positional encoding: characters are turned into learned vectors and positions are added.
  3. NdN_d decoder blocks: each consists of three parts: masked self-attention that hides future characters, attention over the encoder output, and a feed-forward network.
  4. Linear layer and softmax: output the probability of the next character.
PartMachine translation TransformerSpeech-Transformer
Encoder inputWord embeddingsSpeech features subsampled by two convolutional layers
Extra encoder componentsNone2D-Attention (optional)
Encoder and decoder blocksSelf-attention + feed-forward (the decoder also attends to the encoder)Same
Decoder outputWords (subwords)Characters

At inference, characters are emitted one at a time while expanding output candidates with beam search.

Speech features taken every 10 ms form a sequence much longer than the number of words in the same sentence. Since the cost of self-attention grows with the square of the sequence length, shrinking time to one quarter with the initial convolutions matters a great deal for keeping computation and memory in check.

2D-Attention: looking at both time and frequency

2D-Attention is a module that treats speech features as a 3D "channel × time × frequency" tensor, applies attention along the time axis and the frequency axis separately, and combines the two results. Ordinary self-attention only looks at relationships between time steps, but in speech, relationships between frequencies (between components at one pitch and another) also carry useful cues.

The computation proceeds as follows.

  1. Create Q, K, and V with convolutions: apply three parallel convolutions to the input II to create the query QQ, key KK, and value VV, each with cc channels. The ii-th channel's Qi,Ki,ViQ_i, K_i, V_i are time × frequency matrices. Each channel is used as one head of multi-head attention.
  2. Time-axis attention: in each channel, compute scaled dot-product attention with time steps as rows. This captures relationships between time steps.
  3. Frequency-axis attention: transpose the same Qi,Ki,ViQ_i, K_i, V_i, compute attention with frequencies as rows, and transpose back. This captures relationships between frequencies.
  4. Concatenate and combine: concatenate the results of both axes, 2c2c channels in total, and combine them into nn channels with a convolution WOW^O.
channelit=Attention(Qi,Ki,Vi),channelif=Attention(Qi⊤,Ki⊤,Vi⊤)⊤\mathrm{channel}^t_i = \mathrm{Attention}(Q_i, K_i, V_i), \qquad \mathrm{channel}^f_i = \mathrm{Attention}(Q_i^\top, K_i^\top, V_i^\top)^\top 2D-Attention(I)=WO∗concat[channel1t,…,channelct,channel1f,…,channelcf]\text{2D-Attention}(I) = W^O * \mathrm{concat}\left[\mathrm{channel}^t_1, \dots, \mathrm{channel}^t_c, \mathrm{channel}^f_1, \dots, \mathrm{channel}^f_c\right]

Here Attention(Q,K,V)=softmax(QK⊤/dk) V\mathrm{Attention}(Q, K, V) = \mathrm{softmax}(QK^\top / \sqrt{d_k})\,V, and ∗* denotes convolution.

The paper's abstract states that 2D-Attention can jointly attend to the time and frequency axes of the 2D speech input, yielding more expressive representations.

If a spectrogram is compared to a musical score, time-axis attention looks at "which bars relate to which bars", while frequency-axis attention looks at "which notes sounding at the same instant go together".

Why training is fast

Speech-Transformer trains quickly because it removes the recurrence that computes time steps in order, allowing the entire sequence to be computed at once.

  • Parallel along time: an LSTM needs the result at time t−1t-1 to compute time tt, so longer utterances mean longer waits. Self-attention computes the relationships between all pairs of time steps together through matrix multiplication, so it can be processed in parallel on a GPU.
  • Direct connections between distant time steps: in self-attention, information travels between any two time steps in a single computation. There is no need to pass information along dozens of steps in sequence, as in a recurrent network.
  • Shortening the sequence first: the initial convolutions subsample time, so the sequence handled by attention is shorter and the growth of computation is kept down.

Decoder training also feeds the correct character sequence shifted one position to the right and uses masked self-attention to "predict the next character looking only at previous ones", so all positions can be trained at once.

Experimental results

The results given in the paper's abstract are as follows.

ItemValue
DatasetWSJ (read English speech from the Wall Street Journal)
Word error rate (best model)10.9%
Training time1.2 days on a single GPU

The paper states that this error rate is competitive with published recurrent encoder–decoder models, while training is much faster.

Since then, Speech-Transformer has been used as a baseline model in speech recognition research. Examples of configurations in later work are as follows.

WorkPreprocessingEncoder / decoder blocksModel dimensionHeadsFeed-forward dimension
Bai et al. (2019, Mandarin speech recognition)Subsampling every 3 frames6 / 651282,048
Zhang et al. (2020, Mandarin–English code-switching speech recognition)Two 3×3, stride-2 convolutional layers12 / 651282,048

(Both are configurations from studies that used Speech-Transformer as a base model, not the settings of the original paper itself.)

Practical considerations

Keep the following points in mind when using Speech-Transformer.

  • Computation grows with the square of the number of time steps: even with convolutional shortening, longer utterances require more computation and memory.
  • Not suited to streaming recognition: the encoder applies self-attention over the whole utterance and the decoder also looks at the entire encoder output, so transcribing incrementally while someone is still speaking requires changes such as limiting the attention span.
  • Weak mechanism for attending to nearby time steps: self-attention has no built-in preference for nearby time steps. Di Gangi et al. (2019), who studied direct translation from speech into text in another language, reported that using Speech-Transformer as is could not beat LSTM models, and that a mechanism favoring nearby time steps (weakening attention with distance) improved results. The later Conformer addresses this by incorporating a convolution module.
  • The decoder emits one character at a time: training can be parallelized, but at inference the previous output is fed in to produce the next, so computation proceeds sequentially for the length of the output.

An encoder–decoder whose decoder freely attends to the entire input does not explicitly fix the alignment between input and output, so it may skip parts of an utterance or output the same part repeatedly. Countermeasures include splitting long audio into segments and combining the loss with a CTC loss to regularize the alignment.

Comparison with other models

Speech recognition encoder–decoders and related models compare as follows.

ModelEncoderHow output is producedEase of parallel trainingStreaming recognition
Listen, Attend and SpellPyramidal bidirectional LSTMLSTM decoder attends to the input and emits one character at a timeLow (computed in time order)Difficult
Speech-TransformerConvolutions + (2D-Attention) + TransformerTransformer decoder emits one character at a timeHighDifficult
RNN-TransducerBidirectional LSTM, etc.Chooses blank or a label at each time stepDepends on the encoderPossible with a unidirectional encoder
ConformerTransformer + convolution moduleTrained with RNN-Transducer in the paperHighRequires modifications
WhisperTwo convolutional layers + TransformerTransformer decoder (multilingual, multitask)HighDifficult (per 30-second segment)

As a rule of thumb:

  • To learn the basic form of a Transformer encoder–decoder or train from scratch on your own data: the Speech-Transformer configuration (subsample with convolutions → Transformer) is a starting point. Whisper also subsamples with convolutions before feeding a Transformer.
  • For higher accuracy: a Conformer encoder, which incorporates convolutions to capture nearby time steps, is a strong choice.
  • For streaming recognition: RNN-Transducer, which decides outputs in time order, is a good fit.

PyTorch example

Show code
python
import torch
import torch.nn as nn

"""
A small implementation of the Speech-Transformer layout (subsample with convolutions → linear layer → positional encoding → Transformer).
2D-Attention computes time-axis and frequency-axis attention per channel, concatenates them, and combines them with a convolution.
Note: detailed settings from the paper (dimensions, number of layers, etc.) are not reproduced here.
"""


class Conv2dSubsampling(nn.Module):
    """Two 3×3, stride-2 conv layers reduce time and frequency to about 1/4 each"""
    def __init__(self, channels=64):
        super().__init__()
        self.conv = nn.Sequential(
            nn.Conv2d(1, channels, 3, stride=2), nn.ReLU(),
            nn.Conv2d(channels, channels, 3, stride=2), nn.ReLU())

    def forward(self, x):                        # x: [B, T, F]
        return self.conv(x.unsqueeze(1))         # [B, C, T', F']


class TwoDAttention(nn.Module):
    """2D-Attention: build Q, K, V with convolutions and, treating each channel as one head, attend along both time and frequency"""
    def __init__(self, in_ch, c=64, out_ch=64):
        super().__init__()
        self.q = nn.Conv2d(in_ch, c, 3, padding=1)
        self.k = nn.Conv2d(in_ch, c, 3, padding=1)
        self.v = nn.Conv2d(in_ch, c, 3, padding=1)
        self.out = nn.Conv2d(2 * c, out_ch, 3, padding=1)     # W^O: 2c channels → n channels

    @staticmethod
    def attend(q, k, v):                                       # [B, c, L, D]: relations along L
        w = torch.softmax(q @ k.transpose(-1, -2) / q.size(-1) ** 0.5, dim=-1)
        return w @ v

    def forward(self, x):                                      # x: [B, C, T, F]
        q, k, v = self.q(x), self.k(x), self.v(x)              # each [B, c, T, F]
        t = self.attend(q, k, v)                               # Time axis (T × T weights)
        f = self.attend(q.transpose(-1, -2), k.transpose(-1, -2), v.transpose(-1, -2)).transpose(-1, -2)  # Frequency axis
        return self.out(torch.cat([t, f], dim=1))              # [B, n, T, F]


def sinusoidal(length, d):
    pos = torch.arange(length).unsqueeze(1)
    i = torch.arange(0, d, 2)
    pe = torch.zeros(length, d)
    pe[:, 0::2] = torch.sin(pos / 10000 ** (i / d))
    pe[:, 1::2] = torch.cos(pos / 10000 ** (i / d))
    return pe


class SpeechTransformer(nn.Module):
    def __init__(self, n_mels=80, n_chars=31, d_model=256, heads=4, n_enc=12, n_dec=6, n_2d=1, ch=64):
        super().__init__()
        self.sub = Conv2dSubsampling(ch)
        self.att2d = nn.ModuleList([TwoDAttention(ch, ch, ch) for _ in range(n_2d)])   # Optional (M modules)
        f = ((n_mels - 1) // 2 - 1) // 2                        # Number of frequency bins after subsampling
        self.proj = nn.Linear(ch * f, d_model)                  # Flatten and project to the model dimension
        self.embed = nn.Embedding(n_chars, d_model)
        self.transformer = nn.Transformer(
            d_model, heads, n_enc, n_dec, dim_feedforward=4 * d_model, dropout=0.1, batch_first=True)
        self.head = nn.Linear(d_model, n_chars)
        self.d_model = d_model

    def forward(self, feats, prev_chars):                      # feats: [B, T, n_mels], prev_chars: [B, U]
        h = self.sub(feats)
        for m in self.att2d:
            h = h + m(h)
        b, c, t, f = h.shape
        src = self.proj(h.permute(0, 2, 1, 3).reshape(b, t, c * f))
        src = src + sinusoidal(t, self.d_model)
        tgt = self.embed(prev_chars) * self.d_model ** 0.5 + sinusoidal(prev_chars.size(1), self.d_model)
        mask = self.transformer.generate_square_subsequent_mask(prev_chars.size(1))   # Mask future characters
        out = self.transformer(src, tgt, tgt_mask=mask)
        return self.head(out)                                   # [B, U, n_chars]


model = SpeechTransformer()
feats = torch.randn(2, 400, 80)                                 # 4 seconds (every 10 ms)
prev = torch.randint(0, 31, (2, 20))                            # Ground-truth characters shifted right by one
target = torch.randint(0, 31, (2, 20))

model.train()                                                   # Dropout is active
logits = model(feats, prev)
loss = nn.functional.cross_entropy(logits.reshape(-1, 31), target.reshape(-1))
loss.backward()

model.eval()                                                    # Disable dropout for inference

FAQ

Q. What is the difference between Speech-Transformer and the machine translation Transformer?
A.

The encoder input differs. The machine translation Transformer takes word embeddings, whereas Speech-Transformer applies two 3×3, stride-2 convolutional layers to speech features (spectrograms) to subsample time and frequency, projects them to the model dimension with a linear layer, and then feeds them in. In addition, 2D-Attention, which applies attention along both time and frequency, can optionally be added. The contents of the blocks and the decoder are almost the same.

Q. Is 2D-Attention required?
A.

No. 2D-Attention is an optional module stacked after the encoder's convolutions. In later work built on Speech-Transformer, configurations without 2D-Attention, which feed the convolutionally subsampled features directly into the Transformer encoder, are also used (e.g., Zhang et al. 2020).

Q. How do Speech-Transformer and Conformer differ?
A.

The Speech-Transformer encoder is a stack of ordinary Transformer blocks. Conformer is an encoder that inserts a convolution module into each block so that it also captures fine features of nearby time steps. Also, Speech-Transformer emits characters one at a time with a Transformer decoder, whereas the Conformer paper trains with RNN-Transducer.

References

  1. Dong, L., Xu, S., & Xu, B. (2018). Speech-Transformer: A No-Recurrence Sequence-to-Sequence Model for Speech Recognition. ICASSP 2018, pp. 5884–5888.
  2. Di Gangi, M. A., Negri, M., Cattoni, R., Dessì, R., & Turchi, M. (2019). Enhancing Transformer for End-to-end Speech-to-Text Translation. MT Summit XVII.
  3. Zhang, S., Yi, J., Tian, Z., Bai, Y., Tao, J., & Wen, Z. (2020). Decoupling Pronunciation and Language for End-to-end Code-switching Automatic Speech Recognition. arXiv:2010.14798.
  4. Bai, Y., Yi, J., Tao, J., Tian, Z., & Wen, Z. (2019). Learn Spelling from Teachers: Transferring Knowledge from Language Models to Sequence-to-Sequence Speech Recognition. arXiv:1907.06017.
  5. Latif, S., Zaidi, A., Cuayahuitl, H., Shamshad, F., Shoukat, M., Usama, M., & Qadir, J. (2023). Transformers in Speech Processing: A Survey. arXiv:2303.11607.
  6. Vaswani, A., et al. (2017). Attention Is All You Need. NeurIPS 2017. arXiv:1706.03762.