Transformer (NLP)

Machine Learning
Introduced by
Vaswani, A. et al.
Year
2017
Type
Attention-based deep neural network

What does it do?

The Transformer is an attention-based deep neural network introduced by Vaswani and colleagues in 2017.

Its central operation, self-attention, lets each token in a sequence weigh its relationship to every other token, and the whole sequence is processed in parallel rather than word by word. It is used for text classification, named-entity recognition and language modelling.

The intuition behind the method

Older sequence models read text one word at a time, which makes it hard to connect words that are far apart. The Transformer lets every token look at all the other tokens at once and assign each one a weight that reflects how relevant it is to the token's meaning. Stacking these attention steps produces a context-dependent representation of each token, so the same word can be represented differently in different sentences.

History

Vaswani and colleagues introduced the Transformer in 2017 in the paper Attention Is All You Need, proposing an architecture built entirely on attention without recurrence. Attention-based models then quickly replaced recurrent neural networks across nearly all applications, including natural language processing, speech recognition and computer vision. Today's large-scale language models and foundation models are direct descendants of this shift.

When to use it

Consider a Transformer when your task is text classification, named-entity recognition or language modelling, and the correct output depends on context spread across a sentence or document. As a rough rule of thumb, around 500 labelled examples is a starting point rather than a threshold; the amount of data actually needed depends on the task, the number of labels and whether a pre-trained model is fine-tuned, so it should be judged by testing. With limited data, fine-tuning a pre-trained model on your data is usually more practical than training one from scratch. Avoid training a Transformer from scratch on a small or specialised text corpus. For small problems where a few interpretable features carry most of the information, classical methods such as Random Forest, XGBoost or logistic regression are often easier to justify.

Limitations and considerations

  • Self-attention compares every token with every other token, so its time and memory cost grows quadratically with sequence length. Long documents usually require truncation or efficient attention variants.
  • With few labelled examples, results can be less reliable and more sensitive to the particular training and test split, so they should be checked on held-out data.
  • Training from scratch is computationally expensive, which is why pre-trained models are normally used as the starting point.
  • The learned representations are spread across many weights and attention heads, so the reason for a particular prediction is hard to read off directly.

Source conditions do not replace independent scientific review or validation by an analysis engine.

Strengths

  • Self-attention links tokens at any distance in a single step, rather than passing information along a chain of intermediate word states as recurrent models do.
  • Because the sequence is not processed step by step, training can be parallelised across positions, which makes large text corpora practical to use.
  • Pre-trained language models can be fine-tuned on a target task, so a task with limited labelled data can reuse representations learned from large text corpora.
  • One architecture covers classification, named-entity recognition and language modelling, with the output layer changing between tasks.

Applications

  • Text classification, such as sentiment or topic labelling.
  • Named-entity recognition (NER) over documents.
  • Language modelling and next-token prediction.
  • Fine-tuning pre-trained language models for domain-specific text tasks.

How it works

How it works

1

The text is split into tokens, and each token is mapped to a learned numeric vector. Self-attention by itself does not encode word order, so position information is added to these vectors so that the model can tell where each token sits in the sequence.

2

Each token vector is projected into a query, a key and a value. Scaled dot-product attention compares each query with all keys, divides the scores by the square root of the key dimension d_k to keep them in a manageable range, applies a softmax to obtain weights, and uses those weights to average the value vectors. Several attention layers are stacked, so each token's final representation reflects the whole sequence.

Formula
\text{Attention}(Q,K,V) = \text{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_k}}\right)V
3

The contextual representations feed a task-specific output layer: a class label for text classification, a tag for each token in named-entity recognition, or a probability distribution over next tokens for language modelling. In practice, a model pre-trained on a large text corpus is commonly fine-tuned on the target task.

Common pitfalls

  • Training from scratch on a small dataset, where the attention layers have too little signal to learn stable patterns.
  • Fine-tuning a pre-trained model without checking whether its pre-training text matches your domain.
  • Reading attention weights as an explanation of the prediction; a token receiving high attention does not by itself show that it caused the output.
  • Using a Transformer on a problem with few examples per class and expecting it to outperform a simple baseline without testing that comparison.

Frequently asked questions

How much text data do I need?

Around 500 labelled examples is a rough starting point, not a threshold. The amount depends on the task, the number of labels and whether a pre-trained model is fine-tuned. With little data, fine-tuning a pre-trained model, or a classical method such as Random Forest or XGBoost, is usually the better choice, and results should be checked on held-out data.

Should I train a Transformer from scratch?

Usually no. A pre-trained language model fine-tuned on your task is normally the more practical starting point, because it reuses representations learned from large text corpora. Training from scratch is computationally expensive.

What tasks does it handle?

Text classification, named-entity recognition, and language modelling, all built on the same self-attention architecture.

Why is the attention mechanism important?

It lets every token in a sequence attend directly to every other token, capturing long-range context that earlier word-by-word recurrent models handled poorly.

Related methods

Sources

  1. Vaswani, A. et al. (2017). Attention Is All You Need. NeurIPS.

    Open publication reference
  2. BATDI-BASARAN-nitel-arastirmada-yapay-zeka-II, p. 161