Transformer as a Language Model

A GPT-style model is a decoder-only transformer arranged so each position predicts what comes next.

The Big Question

The previous chapter explained the transformer block: self-attention, positional information, feed-forward networks, residual connections, and layer normalization.

To build a GPT-style model, we use that architecture in a specific way.

How do we arrange a transformer so it can predict the next token?

The answer is a decoder-only transformer. It reads a prefix, blocks access to future tokens with a causal mask, and produces one contextual representation at every position.

Deep Learning TransformerGeneral architecture for contextual token representations
Decoder-Only TransformerTransformer restricted with causal masking
Language ModelDecoder-only transformer plus an output head that scores next tokens

Core Intuition

Imagine the model reading Jessie ordered a. The representation at the final position contains information from Jessie, ordered, and a. That final representation is the model's summary of the current context.

A language model adds one more piece: an output head that turns that representation into scores for possible next tokens. The detailed probability and loss story belongs to the Language Modelling lesson. This bridge lesson is about how the transformer is arranged so that prediction is possible.

Causal Context

During next-token prediction, a position may use only itself and earlier tokens. It must not peek at the answer. That is why decoder-only transformers use causal masking.

token at position t may attend only to positions t\text{token at position }t\text{ may attend only to positions }\le t

Interactive Demo

Transformer block explorer

One transformer block

Token representations

Jessie
position 1
ordered
position 2
a
position 3
burger
position 4
queryJessieorderedaburger
Jessie0.420.280.080.22
ordered0.350.080.060.51
a0.080.120.120.68
burger0.180.460.060.30
Selected component
Mix information across tokens

Self-attention lets each token retrieve relevant context from every other allowed token.

Attention versus transformer

Attention is the token-mixing operation. A transformer block wraps attention with positional information, feed-forward networks, residual paths, and normalization.

Causal masking

Decoder-only language models must not look at future tokens during training. Turn on the mask to block attention to positions on the right.

Order matters

Without positional information, self-attention knows which tokens are present but not where they appear. That is why position is added before attention.

Turn on causal masking. That masked attention pattern is the key architectural change that makes a transformer usable for next-token prediction.

Architecture

Input Shape

After text is converted into token IDs, each token is looked up in an embedding matrix. A sequence of nn tokens becomes:

XRn×dmodelX\in\mathbb{R}^{n\times d_{\text{model}}}

Positional information is added so the model can distinguish the same tokens in different orders.

Causal Self-Attention

The transformer still computes queries, keys, and values:

Q=XWQ,K=XWK,V=XWVQ=XW_Q,\qquad K=XW_K,\qquad V=XW_V

But the attention matrix is masked before softmax so future positions are invisible:

Attention(Q,K,V)=softmax(QKT+Mdk)V\text{Attention}(Q,K,V)=\text{softmax}\left(\frac{QK^T+M}{\sqrt{d_k}}\right)V

Here MM contains large negative values wherever a token would otherwise attend to the future.

Context Window

A decoder-only transformer can only attend to tokens inside its context window. If the context window is 4,000 tokens, then token 4,001 cannot directly see token 1 unless the system provides that information again.

This is why context windows matter so much in LLM applications: they define how much text the model can condition on at once.

Output Head

Each position leaves the transformer as a contextual vector hth_t. A language-model head maps that vector to one score per vocabulary token:

zt=Woutht+boutz_t=W_{\text{out}}h_t+b_{\text{out}}

These scores are logits. The next lessons explain how raw text becomes tokens and how logits become a trained language-modelling objective.

Implementation

This sketch shows the architecture only: token embeddings, positional embeddings, causal transformer block, and output head.

import torch
from torch import nn

class DecoderOnlyTransformer(nn.Module):
    def __init__(self, vocab_size, d_model, num_heads, max_len):
        super().__init__()
        self.token_embedding = nn.Embedding(vocab_size, d_model)
        self.position_embedding = nn.Embedding(max_len, d_model)
        self.block = nn.TransformerEncoderLayer(
            d_model=d_model,
            nhead=num_heads,
            dim_feedforward=4 * d_model,
            batch_first=True,
        )
        self.output_head = nn.Linear(d_model, vocab_size)

    def forward(self, token_ids):
        batch_size, seq_len = token_ids.shape
        positions = torch.arange(seq_len, device=token_ids.device)

        x = self.token_embedding(token_ids)
        x = x + self.position_embedding(positions)[None, :, :]

        causal_mask = torch.triu(
            torch.ones(seq_len, seq_len, device=token_ids.device),
            diagonal=1,
        ).bool()

        h = self.block(x, src_mask=causal_mask)
        logits = self.output_head(h)
        return logits

The result is not yet a trained language model. It is the architecture that the language-modelling objective will train.

Interview Discussion

What makes a transformer decoder-only?

It uses masked self-attention so each position can attend only to itself and earlier positions.

Why does next-token prediction require causal masking?

Without a causal mask, the model could look at the future token it is supposed to predict.

What is a context window?

It is the maximum number of tokens the model can condition on at once.

What does the output head do?

It maps each contextual transformer vector to logits over the vocabulary.

Active Recall

1. What changes when a transformer is used as a decoder-only language model?

2. Why is causal masking necessary?

3. What is the role of the context window?

4. What does the output head produce?

5. Why is this lesson only a bridge into tokenisation and language modelling?

Connection To Tokenisation

We now know how to arrange a transformer for next-token prediction. The next question is how raw text becomes the tokens that this architecture consumes.