AI Logic

Architectures

Conformer

Updated:

Structure of Conformer. Left: the overall flow of the encoder (filterbank features → SpecAugment → convolutional subsampling → linear layer → dropout → Conformer block × N). Center: inside a Conformer block (a ½-scaled feed-forward, self-attention with relative positions, a convolution module, and another ½-scaled feed-forward, connected by residual connections and followed by layer normalization). Right: inside the convolution module (layer normalization, pointwise convolution, GLU, depthwise convolution, batch normalization, Swish, pointwise convolution, dropout)

Background and overview

Conformer (Convolution-augmented Transformer) is a speech recognition encoder that builds a convolution module into the Transformer block to capture both "relations to distant time steps" and "fine features of nearby time steps" in speech. It was proposed by Gulati et al. at Google in 2020.

Until then, speech recognition encoders followed two lines:

  • Transformer (self-attention): good at capturing content-dependent relations to distant time steps across the whole utterance, but weak at extracting fine local feature patterns.
  • CNN (convolution): captures local features efficiently, but needs many stacked layers and parameters to gather information from the whole utterance.

Conformer stacks blocks in which a convolution module is placed right after the self-attention module, and the two are sandwiched between half-weighted feed-forward modules. The combination is designed to exploit the strengths of both with few parameters.

The word error rates on LibriSpeech test-clean / test-other are:

  • 2.1 / 4.3% without a language model and 1.9 / 3.9% with an external language model (Conformer L, 118.8M parameters)
  • 2.7 / 6.3% without a language model even for a small 10.3M-parameter model (Conformer S)
  • Conformer M with 30.7M parameters outperforms the 139M-parameter Transformer Transducer

Architecture

The Conformer encoder processes its input in the following order. In the figure at the top of the article, the left shows the overall flow of the encoder, the center the inside of a Conformer block, and the right the inside of the convolution module.

  1. Input: 80-channel filterbank features computed with a 25 ms window shifted every 10 ms.
  2. SpecAugment: data augmentation that masks parts of the frequency and time axes, applied only during training.
  3. Convolutional subsampling: convolution reduces the time steps to one quarter, one every 40 ms.
  4. Linear layer and dropout: project to the encoder dimension.
  5. Stack NN Conformer blocks.

A single Conformer block computes the output yiy_i from the input xix_i as follows:

x~i=xi+12 FFN(xi)xi′=x~i+MHSA(x~i)xi′′=xi′+Conv(xi′)yi=LayerNorm(xi′′+12 FFN(xi′′))\begin{aligned} \tilde{x}_i &= x_i + \tfrac{1}{2}\,\mathrm{FFN}(x_i) \\ x'_i &= \tilde{x}_i + \mathrm{MHSA}(\tilde{x}_i) \\ x''_i &= x'_i + \mathrm{Conv}(x'_i) \\ y_i &= \mathrm{LayerNorm}\left(x''_i + \tfrac{1}{2}\,\mathrm{FFN}(x''_i)\right) \end{aligned}

The contents of the four modules are as follows. Every module has the "Pre-LN" form: layer normalization is applied to the input first, and the output is added to the input (Pre-LN vs. Post-LN).

ModuleContents
Feed-forward (FFN)Layer norm → linear (4× dimension) → Swish → dropout → linear (back to original dimension) → dropout
Multi-head self-attention (MHSA)Layer norm → multi-head attention with relative positions → dropout
Convolution module (Conv)Layer norm → pointwise convolution (2× channels) → GLU → 1D depthwise convolution → batch normalization → Swish → pointwise convolution → dropout
FinalLayer norm
  • Two feed-forward modules sandwiching the block: a form borrowed from Macaron-Net. The single feed-forward of an ordinary Transformer is split into two, before and after attention, and each output is scaled by 12\tfrac{1}{2} before being added (half-step residuals).
  • Attention with relative positions: uses the relative sinusoidal positional encoding of Transformer-XL. The paper says this makes performance more robust to varying utterance lengths.
  • Convolution module: gating with a pointwise convolution (kernel width 1) and a GLU (Gated Linear Unit: split the channels in half, pass one half through a sigmoid, and multiply it with the other), then a depthwise convolution that gathers nearby features channel by channel.

The paper's three sizes are as follows. All use a single-layer LSTM transducer decoder (RNN-Transducer).

ModelParametersBlocks NNEncoder dimHeadsConv kernel widthDecoder dim
Conformer S10.3M16144432320
Conformer M30.7M16256432640
Conformer L118.8M17512832640

Training

The training setup in the paper is as follows:

ItemValue
DataLibriSpeech (about 970 hours of transcribed speech)
Data augmentationSpecAugment (frequency mask parameter F=27F = 27, 10 time masks, each mask up to 5% of the utterance length)
Dropout0.1 on the output of each module (before adding to the input)
Other regularizationVariational noise; L2 regularization with weight 10−610^{-6} on all weights
OptimizationAdam (β1=0.9\beta_1 = 0.9, β2=0.98\beta_2 = 0.98, ϵ=10−9\epsilon = 10^{-9})
Learning rateTransformer learning rate schedule (10k warmup steps, peak 0.05/d0.05/\sqrt{d}, where dd is the encoder dimension)

When a language model is used, a 3-layer LSTM (width 4,096) trained on the LibriSpeech language model text is combined via shallow fusion (adding the language model score, weighted by λ\lambda, to the recognition score).

Why it works

The paper checks how much each Conformer component contributes with an ablation that removes components one at a time, moving the Conformer block toward a Transformer block (with the number of parameters kept the same) (Conformer L, no language model; word error rate in %).

Modeldev-cleandev-othertest-cleantest-other
Conformer1.94.42.14.3
Replace Swish with ReLU1.94.42.04.5
+ Remove the convolution module2.14.82.14.9
+ Merge the two feed-forwards into one2.15.12.15.0
+ Drop relative positions (plain Transformer)2.35.82.45.6

(Each row adds one more change to the changes of the row above.)

The paper concludes that the convolution module is the most important component, and that sandwiching with two feed-forwards is more effective than a single feed-forward with the same number of parameters. Swish was observed to speed up convergence rather than improve accuracy.

In speech, a single sound lasts only a short time, and its shape is determined by the sequence of a few nearby frames. On the other hand, deciding which word it is also requires clues from distant parts of the utterance. It helps to think of convolution as handling "patterns in nearby sequences" and self-attention as handling "relations to distant parts."

The paper also compares ways of combining convolution and attention (dev-clean / dev-other).

CombinationWord error rate (%)
Conformer (convolution after attention)1.9 / 4.4
Replace depthwise convolution with lightweight convolution2.0 / 4.8
Place convolution before attention1.9 / 4.5
Run attention and convolution in parallel and concatenate outputs2.0 / 4.9

Placing convolution in series after attention gave the best result.

For the kernel width of the depthwise convolution, widths of 3, 7, 17, 32, and 65 were compared: results improved with larger widths up to 17 and 32, and worsened at 65. Comparing to two decimal places, 32 gives the best result (dev-other 4.30%, test-other 4.29%).

Experimental results

Comparison on LibriSpeech (word error rate on test-clean / test-other, in %)

ModelParametersWithout LMWith LM
QuartzNet (CTC)19M3.9 / 11.32.7 / 7.3
LSTM (LAS)360M2.6 / 6.02.2 / 5.2
Transformer Transducer139M2.4 / 5.62.0 / 4.6
ContextNet (S)10.8M2.9 / 7.02.3 / 5.5
ContextNet (L)112.7M2.1 / 4.61.9 / 4.1
Conformer (S)10.3M2.7 / 6.32.1 / 5.0
Conformer (M)30.7M2.3 / 5.02.0 / 4.3
Conformer (L)118.8M2.1 / 4.31.9 / 3.9

(The QuartzNet values are the paper's 3.90 / 11.28 and 2.69 / 7.25 rounded to one decimal place.)

Compared at similar sizes, Conformer has fewer errors than the CNN-based ContextNet and the Transformer Transducer at every size, with the gap especially large on the noisier test-other. Conformer L with a language model reduces test-other errors by about 15% relative to the Transformer Transducer.

Number of heads (Conformer L, dev-other / test-other): 4.6 / 4.5% with 4, 4.4 / 4.3% with 8, 4.3 / 4.4% with 16, and 4.4 / 4.5% with 32. The paper notes that increasing to 16 helps, especially on dev-other.

Practical notes

When using Conformer, keep the following points in mind:

  • Conformer is an encoder: the paper uses it as a transducer combined with a single-layer LSTM decoder. It can also be combined with CTC Loss or an attention decoder, but performance in those settings must be verified separately from the paper's numbers.
  • Computation is quadratic in the number of time steps: because of self-attention, longer audio requires more computation and memory.
  • Streaming requires adaptation: in the paper's configuration, self-attention sees the whole utterance. Recognizing incrementally while someone is still speaking requires changes such as limiting the attention range.
  • It contains batch normalization: the convolution module has batch normalization, so behavior differs between training and inference. Use model.eval() at inference. Because statistics become unstable with small batches, some implementations replace it with group normalization or similar.
  • Use fairly strong regularization: the paper combines dropout, variational noise, L2 regularization, and SpecAugment.

The position of the convolution module and the 12\tfrac{1}{2}-scaled feed-forward residuals were the parts that mattered for performance in the paper's comparisons. When implementing it yourself, make sure that the convolution comes after attention and that the outputs of the two feed-forwards are scaled by 12\tfrac{1}{2} before being added.

Comparison with other models

Comparing representative speech recognition encoder designs from the same angles gives the following:

ModelBlock contentsRelations to distant time stepsFeatures of nearby time stepsTraining
Transformer (Transformer Transducer, etc.)Self-attention + feed-forwardDirectly via self-attentionWeak (compensated by position information and many layers)Supervised with transcriptions
ContextNetConvolution + Squeeze-and-ExcitationOnly an average over the whole sequenceStrong via convolutionSupervised with transcriptions
Conformer½ FFN + self-attention + convolution + ½ FFNDirectly via self-attentionStrong via convolutionSupervised with transcriptions
wav2vec 2.0, HuBERTCNN feature encoder + TransformerDirectly via self-attentionVia the initial CNNPre-training without transcriptions → fine-tuning
Whisper2 convolution layers + Transformer encoder and decoderDirectly via self-attentionVia the initial convolutionsSupervised on 680k hours of transcribed audio

Rough guidelines for choosing:

  • Transcribed data is available and the balance of accuracy and size matters for one language or domain: Conformer is a strong choice. Even at around 10M parameters, the paper reports 6.3% on test-other without a language model.
  • Few transcriptions are available: use a self-supervised pre-trained model such as wav2vec 2.0 or HuBERT. The HuBERT paper also compares against a Conformer XXL (about 1B parameters) pre-trained on 60k hours of Libri-light.
  • Multilingual recognition should work right away without additional training: a general-purpose model trained on large amounts of transcribed audio, such as Whisper, is a good fit.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torchaudio

"""
1. Use torchaudio's built-in Conformer encoder
   Note: torchaudio's implementation uses ordinary multi-head attention instead of the paper's attention with relative positions.
   Also, the depthwise convolution kernel width must be odd, so 31 is used instead of the paper's 32
2. A small implementation of the Conformer block exactly following Eq. (1) of the paper (relative positions omitted)
"""

# --- 1. torchaudio.models.Conformer ---
encoder = torchaudio.models.Conformer(
  input_dim=144,                  # encoder dimension (same as Conformer S)
  num_heads=4,
  ffn_dim=144 * 4,                # feed-forward hidden size (4x)
  num_layers=16,                  # number of blocks N
  depthwise_conv_kernel_size=31,  # must be odd
  dropout=0.1,
)
x = torch.randn(2, 250, 144)                 # [batch, time (after subsampling to 40 ms), dim]
lengths = torch.tensor([250, 180])           # true length of each utterance
encoder.eval()                               # disable dropout; batch norm uses learned statistics
with torch.no_grad():
  y, out_lengths = encoder(x, lengths)       # y: [2, 250, 144]


# --- 2. Conformer block following Eq. (1) ---
class FeedForward(nn.Module):
  def __init__(self, d, expansion=4, p=0.1):
    super().__init__()
    self.net = nn.Sequential(
      nn.LayerNorm(d), nn.Linear(d, d * expansion), nn.SiLU(),   # SiLU = Swish
      nn.Dropout(p), nn.Linear(d * expansion, d), nn.Dropout(p))

  def forward(self, x):
    return self.net(x)


class ConvModule(nn.Module):
  def __init__(self, d, kernel_size=31, p=0.1):
    super().__init__()
    self.norm = nn.LayerNorm(d)
    self.pw1 = nn.Conv1d(d, 2 * d, 1)                      # pointwise convolution (2x channels)
    self.glu = nn.GLU(dim=1)                               # use half as a gate and multiply -> d channels
    self.dw = nn.Conv1d(d, d, kernel_size, padding=kernel_size // 2, groups=d)  # depthwise convolution
    self.bn = nn.BatchNorm1d(d)
    self.act = nn.SiLU()
    self.pw2 = nn.Conv1d(d, d, 1)
    self.drop = nn.Dropout(p)

  def forward(self, x):                                    # x: [B, T, d]
    h = self.norm(x).transpose(1, 2)                       # to [B, d, T] for convolution
    h = self.glu(self.pw1(h))
    h = self.act(self.bn(self.dw(h)))
    h = self.drop(self.pw2(h))
    return h.transpose(1, 2)


class ConformerBlock(nn.Module):
  def __init__(self, d=144, heads=4, kernel_size=31, p=0.1):
    super().__init__()
    self.ff1 = FeedForward(d, p=p)
    self.attn_norm = nn.LayerNorm(d)
    self.attn = nn.MultiheadAttention(d, heads, dropout=p, batch_first=True)  # the paper uses relative positions
    self.attn_drop = nn.Dropout(p)
    self.conv = ConvModule(d, kernel_size, p)
    self.ff2 = FeedForward(d, p=p)
    self.final_norm = nn.LayerNorm(d)

  def forward(self, x, key_padding_mask=None):
    x = x + 0.5 * self.ff1(x)                              # x~ = x + 1/2 FFN(x)
    h = self.attn_norm(x)
    h, _ = self.attn(h, h, h, key_padding_mask=key_padding_mask, need_weights=False)
    x = x + self.attn_drop(h)                              # x' = x~ + MHSA(x~)
    x = x + self.conv(x)                                   # x'' = x' + Conv(x')
    return self.final_norm(x + 0.5 * self.ff2(x))          # y = LayerNorm(x'' + 1/2 FFN(x''))


block = ConformerBlock()
block.train()
out = block(torch.randn(2, 100, 144))
print(out.shape)                                           # torch.Size([2, 100, 144])

FAQ

Q. What is the difference between Conformer and Transformer?
A.

A Conformer block is a Transformer block with three changes: (1) a convolution module using depthwise convolution is added after self-attention, (2) the single feed-forward is replaced by two feed-forwards sandwiching the block (with outputs scaled by 12\tfrac{1}{2} before being added), and (3) attention with relative positions is used. In the paper's comparisons, the convolution module mattered most.

Q. Can Conformer alone perform speech recognition?
A.

Conformer is an encoder, so it needs an output mechanism to emit characters or word pieces. The paper trains it as a transducer combined with a single-layer LSTM decoder (RNN-Transducer). It can also be used by adding a CTC Loss output layer or by combining it with an attention decoder.

Q. Why is convolution placed after attention rather than before?
A.

Because placing it after performed better in the paper's comparison experiments. Placing convolution before attention worsened the dev-other word error rate from 4.4% to 4.5%, and running attention and convolution in parallel and concatenating worsened it to 4.9%.

References

  1. Gulati, A., Qin, J., Chiu, C.-C., Parmar, N., Zhang, Y., Yu, J., Han, W., Wang, S., Zhang, Z., Wu, Y., & Pang, R. (2020). Conformer: Convolution-augmented Transformer for Speech Recognition. Interspeech 2020. arXiv:2005.08100.
  2. Lu, Y., Li, Z., He, D., Sun, Z., Dong, B., Qin, T., Wang, L., & Liu, T.-Y. (2019). Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View(Macaron-Net). arXiv:1906.02762.
  3. PyTorch. torchaudio documentation: torchaudio.models.Conformer.