AI Logic

Glossary

Encoder

Updated:

Inputs and outputs of an encoder. Left: the flow in which the input becomes a latent representation through the encoder and connects to a decoder or a head depending on the task. Right: examples of an autoencoder, a Transformer encoder and the TTM backbone

What is an encoder?

An encoder is the part that converts input data into feature vectors (latent representations) that are easy to use in later processing. It replaces inputs of varying form and size, such as images, text, audio and time series, with sequences of numbers in which items with similar meanings take similar values.

This is similar to reading a long document and summarizing the key points in a memo. The memo (the latent representation) keeps only the information from the original document that later tasks need. That memo can then be used to rewrite the original document (reconstruction), translate it into another language (translation), or classify its content.

The latent representation output by an encoder is also called an embedding or features. The part that receives the latent representation and produces the output falls into two types depending on the task.

  • Decoder: Produces data of the same kind as the input (images, text, etc.) from the latent representation. Used for reconstruction, generation and translation.
  • Head: Produces answers such as classes or numbers from the latent representation. It is usually a few fully connected layers. Used for classification, regression and forecasting.

Combining with decoders and heads

Depending on how encoders, decoders and heads are combined, model architectures fall into three main types.

ConfigurationWhat it doesRepresentative models
Encoder + decoderCompresses the input into a latent representation and generates another sequence or data from itAutoencoder, VAE, Seq2Seq, the Transformer for translation, TTM
Encoder + headUnderstands the input and outputs an answer for classification or predictionBERT, ViT
Decoder onlyGenerates each next part in turn from the preceding partsLanguage models that generate text, such as GPT

For tasks that only require understanding the input (sentence classification, image classification, similar-sentence search, etc.), an encoder and a head are often sufficient, and no decoder is needed.

Representative encoders

The inside of an encoder differs from model to model. As long as its role is to convert the input into feature vectors, it is called an encoder regardless of what is inside.

  • Autoencoder encoder: Compresses the input into a latent vector smaller than the input. Because it is trained so that the decoder can reconstruct the input from it, the latent vector is packed with the important information of the input. In 2006, Hinton and Salakhutdinov showed that deep autoencoders can obtain better low-dimensional representations than principal component analysis. The inside uses an MLP or a convolutional network.
  • Transformer encoder: Stacks layers made of self-attention (multi-head attention) and a position-wise feed-forward layer, with 6 layers in the original paper. It keeps the number of input words unchanged and turns each word into a vector that reflects the context of the whole sentence. Unlike the decoder, it can attend to words both before and after.
  • TTM backbone: TTM is a time series forecasting model, and its paper calls the encoder the "backbone." It splits a time series into short segments (patches) and stacks TSMixer blocks made only of MLPs to turn them into per-patch embeddings. It is pre-trained on a large amount of time series data, and during fine-tuning its weights are frozen and only a small decoder and head are trained.

A VAE encoder outputs not the latent vector itself but the distribution of the latent vector (mean and variance). Sampling a value from it and passing it to the decoder makes it possible to generate new data.

Using pre-trained encoders

A major advantage of encoders is that pre-trained ones can be reused for other tasks. An encoder pre-trained on a large amount of data captures general features of the input, so it can be applied to a wide range of tasks just by swapping the head and training on a small amount of data. There are two main ways to use one.

  • Feature extraction: Freeze the encoder's weights and use its output as features. Since only the head is trained, computation is light, and once the features are computed, experiments with different heads can be repeated cheaply.
  • Fine-tuning: Retrain including the encoder's weights. Accuracy tends to improve, but computation increases. The BERT paper reports that fine-tuning the large model (BERT-LARGE) on small datasets was sometimes unstable.

The shape of an encoder's output differs between models. An autoencoder outputs one vector per input, while a Transformer encoder outputs one vector per word (token), that is, a matrix of "number of words × dimension." To turn a whole sentence into a single vector for a classification head, the vectors must be pooled, for example by averaging or by using the vector of a special token at the beginning.

Note that the "encoding" in "positional encoding" or "one-hot encoding" refers to replacing data with numbers by a fixed rule, which is different from the encoder in this article that extracts features through learning.

PyTorch example

Show code
python
import torch
import torch.nn as nn

'''
Check how inputs turn into feature vectors with two kinds of encoders
'''

# 1. Autoencoder encoder (784-dim MNIST image -> 32-dim latent vector)
class Encoder(nn.Module):
  def __init__(self, in_dim=28 * 28, latent_dim=32):
    super().__init__()
    self.net = nn.Sequential(
      nn.Flatten(),                 # [B, 1, 28, 28] -> [B, 784]
      nn.Linear(in_dim, 256),
      nn.ReLU(),
      nn.Linear(256, latent_dim)    # Latent vector
    )

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


class Decoder(nn.Module):
  def __init__(self, latent_dim=32, out_dim=28 * 28):
    super().__init__()
    self.net = nn.Sequential(
      nn.Linear(latent_dim, 256),
      nn.ReLU(),
      nn.Linear(256, out_dim),
      nn.Sigmoid()                  # Map pixel values to 0-1
    )

  def forward(self, z):
    return self.net(z).view(-1, 1, 28, 28)


encoder, decoder = Encoder(), Decoder()
images = torch.rand(8, 1, 28, 28)            # Random images as an example (use MNIST etc. in practice)
z = encoder(images)
recon = decoder(z)
loss = nn.functional.mse_loss(recon, images)  # Train to reconstruct the input
print(z.shape, recon.shape)  # torch.Size([8, 32]) torch.Size([8, 1, 28, 28])

# 2. Transformer encoder (sequence of words -> context vector for each word)
vocab_size, d_model, seq_len = 1000, 128, 16
embed = nn.Embedding(vocab_size, d_model)
layer = nn.TransformerEncoderLayer(d_model=d_model, nhead=4, dim_feedforward=256, batch_first=True)
transformer_encoder = nn.TransformerEncoder(layer, num_layers=2)

tokens = torch.randint(0, vocab_size, (8, seq_len))  # [B, number of words]
h = transformer_encoder(embed(tokens))               # Positional encoding omitted
print(h.shape)  # torch.Size([8, 16, 128])  a 128-dim vector for each word

# For whole-sentence classification, average the word vectors and feed them to a head (fully connected layer)
head = nn.Linear(d_model, 2)
logits = head(h.mean(dim=1))
print(logits.shape)  # torch.Size([8, 2])

FAQ

Q. What does an encoder do?
A.

It converts input data into meaningful feature vectors, making them easier to use in downstream tasks.

Q. What is characteristic of the Transformer encoder?
A.

It uses self-attention to capture relationships between words in a sentence. This allows it to learn long-range dependencies effectively.

Q. Are models ever built from an encoder alone?
A.

Yes. For tasks where understanding the input is enough, such as sentence classification or feature extraction, an encoder on its own can achieve highly accurate results.

References

  1. Hinton, G. E., & Salakhutdinov, R. R. (2006). Reducing the dimensionality of data with neural networks. Science, 313(5786), 504–507.
  2. Vaswani, A., Shazeer, N., Parmar, N., et al. (2017). Attention Is All You Need. NeurIPS 2017.
  3. Ekambaram, V., Jati, A., Dayama, P., et al. (2024). Tiny Time Mixers (TTMs): Fast Pre-trained Models for Enhanced Zero/Few-Shot Forecasting of Multivariate Time Series. NeurIPS 2024.
  4. I. Goodfellow, Y. Bengio, and A. Courville, "Deep Learning," MIT Press, 2016, Chapter 14: Autoencoders.
  5. A. Zhang, Z. C. Lipton, M. Li, and A. J. Smola, "Dive into Deep Learning," Section 10.6 The Encoder–Decoder Architecture.
  6. Devlin, J., Chang, M.-W., Lee, K., & Toutanova, K. (2019). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. NAACL 2019.
  7. Dosovitskiy, A., et al. (2021). An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale. ICLR 2021.
  8. Radford, A., Narasimhan, K., Salimans, T., & Sutskever, I. (2018). Improving Language Understanding by Generative Pre-Training. OpenAI.