Skip to content

Transformer

I. Parallel processing and self-attention — overview of Transformer

    %%{init: { 'theme': 'base', 'themeVariables': { 'edgeLabelBackground': '#fff' }}}%%
flowchart LR
    A1["Limits of sequential computation"] -- "Parallel processing via Self-Attention" --> B1["Long-range dependencies and efficiency"]
    style A1 fill:#f9f9f9,stroke:#333,stroke-width:1px
    style B1 fill:#e1f5fe,stroke:#01579b,stroke-width:1px
  

Definition: an innovative neural network architecture that overcomes the limitations of RNNs, which require sequential computation, by processing the relationships between all words in a sentence in parallel through the Self-Attention mechanism

Characteristics: ( Parallel Computation ) takes the entire sequence as input at once, making it optimal for GPU acceleration and large-scale data training ( Long-term Dependency ) directly connects relationships between distant words without loss, via the attention mechanism ( Scalability ) performance continues to improve as model size (parameters) and data volume increase

II. Core components and mechanism of Transformer

A. The encoder-decoder structure and attention flow

    graph TD
    A2["Input Embedding"] --> B2["Multi-Head Attention"]
    B2 --> C2["Add & Norm"]
    C2 --> D2["Feed Forward"]
    D2 --> E2["Add & Norm"]
    E2 -- "Context" --> F2["Decoder Layer"]
  

B. Core technical elements

ComponentDetailed DescriptionKey Role
Self-AttentionQuantifies the relationship each word in a sentence has with every other wordCaptures contextual meaning
Multi-HeadRuns multiple attention operations in parallel to gather information from different perspectivesExtracts richer features
Positional EncodingNumerically injects positional information into the Transformer, which otherwise has no notion of orderPreserves sequence order
Residual ConnectionAdds the input to the output so that signals propagate well even as layers get deeperEnsures training stability

C. Inside one attention layer — Query, Key, Value

An attention layer takes a sequence of input vectors and returns a sequence of the same length, where every output vector has been rewritten in terms of the other tokens it depends on. The layer holds three learned projection matrices, and multiplying the input by each of them produces the three roles that drive the computation:

    graph LR
    H["H_in\n(token vectors)"] --> Q["Q = H·W_Q"]
    H --> K["K = H·W_K"]
    H --> V["V = H·W_V"]
    Q --> S["Scores = Q·Kᵀ"]
    K --> S
    S --> M["Scale by 1/√d_k\n+ causal mask"]
    M --> W["Softmax → attention weights"]
    W --> O["Output = weights · V"]
    V --> O
  
RoleProjectionIntuition
Query ( Q )H · W_QWhat the current token is looking for
Key ( K )H · W_KThe index each token advertises about itself
Value ( V )H · W_VThe content a token hands over once it is attended to

The layer computes Attention(Q, K, V) = softmax(Q·Kᵀ / √d_k) · V, which reads as four steps:

StepOperationWhy it is there
1. RelevanceInner product between the query at position t and every keyA large inner product means the two vectors point the same way, i.e. the tokens are related
2. ScalingDivide the scores by √d_kWithout it the scores grow with dimension and push softmax into a near-one-hot regime, killing the gradient
3. NormalizationSoftmax across the rowTurns raw scores into a probability vector — how much of its attention budget position t spends on each earlier position
4. AggregationMultiply the weights by VThe output is a linear combination of value vectors, so it carries context rather than just the token’s own identity

D. Causal masking — why a generative model cannot look ahead

A decoder-only model is trained to predict the next token, so at position t it must not see positions t+1 and beyond; otherwise it would read the answer off its own input and learn nothing useful. The whole sequence is still processed in parallel, so the constraint is enforced inside the score matrix rather than by feeding tokens one at a time:

StageWhat happens to the score matrix
Raw scoresA T × T matrix in which every position has a score against every other position, future included
MaskAdd -∞ to the strictly upper triangle (all future positions)
Softmaxexp(-∞) = 0, so future positions receive exactly zero weight
ResultPosition t aggregates only positions 1…t — the autoregressive property holds by construction

This is what makes training efficient: one forward pass over a sequence of length T yields T next-token predictions at once, each one honest about what it was allowed to see.

E. Multi-head attention — several views of the same sentence

A single attention head produces one weighting per position, which forces one set of projections to represent every kind of relationship at once. Instead, the layer runs h heads in parallel, each with its own W_Q, W_K, W_V on a lower-dimensional slice, then concatenates their outputs and passes them through a final output projection W_O.

PropertyDetailed description
SpecializationDifferent heads empirically latch onto different signals — syntactic dependencies, coreference, named entities, sentiment-bearing words
Cost neutralityEach head works in d_model / h dimensions, so h heads cost roughly what one full-width head would
RecombinationConcatenate the head outputs, then apply W_O so the layer can mix what the heads found instead of leaving them side by side

III. Impact and future direction of Transformer

ItemDetailed Content
Natural Language ProcessingThe standard architecture behind virtually every modern NLP model, including BERT (understanding) and GPT (generation)
Multimodal ExpansionExtended to every domain, including images ( ViT ), audio, and video
Limitations and ChallengesComputation grows quadratically with sequence length (recent research includes Linear Attention and similar approaches)

The O(T²) bottleneck and how it is worked around

Attention has to score every position against every other position, so a sequence of length T implies a T × T matrix — the cost is O(T²) in both compute and memory, and doubling the context quadruples it. Memory is usually the binding constraint first, because naïvely materializing that matrix in GPU high-bandwidth memory dominates the layer’s traffic.

ApproachHow it attacks the costTrade-off
Flash AttentionTiles the computation and keeps the score block in on-chip SRAM, so the full T × T matrix is never written outExact same result, far less memory traffic — now the default kernel
Sparse / Sliding-window AttentionEach token attends only to a local window or a fixed pattern of positionsCheaper, but distant dependencies must route through several layers
Linear AttentionReorders the products so cost grows linearly with TApproximates the softmax weighting; quality is workload-dependent
KV CacheAt decoding time, reuses keys and values already computed for earlier tokensRemoves recomputation, but cache size grows linearly with context

Technology trends: the Transformer has now become the basic backbone of foundation models ( Foundation Model ) that go far beyond simple language models, and the large language models ( LLM ) built on it are driving a new paradigm in artificial intelligence