1. Home
  2. Explore
  3. Computer Science
  4. Transformers and Large Language Models

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Transformers and Large Language Models

Foundations of Transformers and Large Language Models

From task-specific NLP models to large language models

In the 2010s, natural language processing (NLP) commonly used a different model for each task. A sentiment classifier might label a review as positive, negative, or neutral; a translation model would translate text; and a named-entity recognizer would identify names, locations, and similar entities. These systems were generally not one model that could perform many different tasks.

A major shift began with the transformer, introduced in 2017. Its central mechanism, attention, made it possible to build models that could scale effectively: increasing training data, computation, or model size could produce substantial performance gains. By training and scaling transformer-based models, researchers developed large language models (LLMs) that can generate fluent text and code.

The public release of ChatGPT in 2022 was a further turning point in how people used these models: conversational interaction with an LLM became familiar to a broad audience. More recently, LLMs have been incorporated into coding agents and other systems that can take actions toward a goal. Understanding this development requires examining the models’ representations of text, their architectures, and how they generate sequences.


Tokenization: converting text into model inputs

Tokens and vocabularies

Models operate on numerical representations, not directly on words or sentences. Tokenization divides text into discrete units called tokens. A token may correspond to a word, part of a word, a character, or another unit defined by the tokenizer.

For example, a tokenizer might divide “a cute teddy bear is reading” into six tokens:

  • “a”

  • “cute”

  • “teddy”

  • “bear”

  • “is”

  • “reading”

The allowed tokens are collected in a vocabulary. Each token is later mapped to a numerical representation, typically a vector. The tokenizer determines how many tokens are used to represent an input; this number is its sequence length. Different tokenizers can produce different sequence lengths for the same text.

The vocabulary size and sequence length are related. A vocabulary with many common words or word fragments may represent typical text in fewer tokens. A tokenizer with a small vocabulary may need to split the same text into more pieces.

Word-level tokenization

A simple approach treats each word, separated by spaces, as one token.

  • Advantages: It is easy to understand and preserves whole-word units.

  • Disadvantages: A vocabulary must include many forms of words, such as plurals and inflections. This can make it large.

  • A word not seen during training may be out of vocabulary (OOV), meaning the tokenizer has no dedicated token for it.

  • Related forms, such as “bear” and “bears,” are separate tokens. Their representations are not automatically guaranteed to be similar.

Word-level tokenization is therefore simple but can have difficulty handling unfamiliar words and related word forms.

Character-level tokenization

Character-level tokenization represents text as individual characters.

  • Advantages: The vocabulary can be small, and almost any word can be represented using a known character set. Character sequences can also handle many misspellings or unfamiliar word forms without requiring a dedicated token for each complete word.

  • Disadvantages: Sequences become much longer. Longer sequences require more computation, and the representation of an individual character carries less direct semantic information than a representation of a word or word part.

Because sequence length affects computational cost, a tiny character vocabulary does not necessarily make processing more efficient.

Subword tokenization

Subword tokenization divides text into units between the size of a character and a whole word. Frequent word parts can be represented by their own tokens, while less common words can be split into smaller pieces.

For instance, “reading” might be divided into “read” and “ing.” Related words can then share a component: “bear” and “bears,” for example, can share the token “bear.”

Subword tokenization combines useful properties of word- and character-level approaches:

  • It can represent uncommon words by combining familiar pieces.

  • Related word forms can share tokens.

  • Frequent sequences can be kept as larger units, limiting sequence length compared with character-level tokenization.

Its vocabulary is learned from data, so the training corpus matters. A tokenizer trained mostly on one domain or language may split text from another domain or language inefficiently.

Byte Pair Encoding

A widely used subword approach is Byte Pair Encoding (BPE). At a high level, BPE builds a vocabulary through repeated merging:

  1. Begin with an initial set of units, often characters or bytes.

  2. Find adjacent pairs that occur frequently in the training data.

  3. Add a token corresponding to a frequent pair and merge those units in relevant text.

  4. Repeat until the desired vocabulary size is reached.

Frequent sequences are increasingly represented as single tokens, while rarer sequences remain decomposed into smaller pieces. The result is generally shorter than a character sequence while still being able to represent words not present as whole-word vocabulary entries.

For multilingual applications, the tokenizer’s training data should represent the languages of interest. A shared vocabulary may capture useful patterns across languages, but it also allocates vocabulary entries among them. Depending on the language and data, this can increase the number of tokens needed to encode some text.

Special tokens

Tokenizers and language models also use special tokens to mark structural or control information. Their names and exact conventions can differ across systems.

  • An unknown token represents text that cannot be matched to the tokenizer’s ordinary vocabulary.

  • A beginning-of-sequence token marks the start of a sequence or signals that generation should begin.

  • An end-of-sequence token marks the end of a sequence or signals that generation should stop.

  • A padding token can bring shorter sequences up to a shared length, which can be useful when processing batches of inputs with tensor-based hardware.

  • Systems can also use special tokens to mark roles such as user and assistant.

These tokens carry information about the structure or intended use of the sequence; they are not simply ordinary words.


Token representations: from identifiers to embeddings

One-hot encodings

A token can be represented using a one-hot encoding: a vector with a 111 at the position assigned to that token and 000s elsewhere. If the vocabulary has size VVV, each one-hot vector has length VVV.

One-hot encodings distinguish tokens, but they do not express relationships among them. The dot product of two different one-hot vectors is zero, so the representation itself says that every distinct token is equally unrelated to every other token. It does not indicate that “bear” and “bears” are related, or that a teddy bear may be soft.

A useful representation should encode patterns that help a model perform its task, such as predicting the next token or assigning a class to a text.

Learned word embeddings and Word2Vec

Word embeddings represent tokens as dense vectors whose values are learned from data. A common early strategy, exemplified by Word2Vec, is to learn embeddings using a proxy task: a training objective that is not necessarily the final application but encourages the model to learn useful representations.

Two Word2Vec objectives are:

  • Continuous Bag of Words (CBOW): Predict a target word from surrounding context words.

  • Skip-gram: Predict surrounding words from a target word.

A simple neural-network version can be understood as follows:

  1. Represent an input token with a one-hot vector of vocabulary size VVV.

  2. Multiply it by a learned weight matrix to produce a hidden representation of dimension DDD.

  3. Project the hidden representation back to vocabulary-sized scores.

  4. Use a softmax to turn the scores into probabilities.

  5. Compare the predicted probabilities with the target token and update the weights to reduce the prediction error.

The hidden representation is the learned embedding. Training on many examples can make words used in similar contexts acquire similar vectors. The geometry of the vectors can therefore encode semantic or relational patterns.

Limits of static embeddings

A single embedding per word is static: the word receives the same vector in every sentence. This creates important limitations:

  • Polysemy: A word can have different meanings in different contexts. “Bank” in “river bank” and “bank account” has one spelling but different meanings.

  • Context-dependent meaning: A word such as “cute” can be literal or sarcastic; a fixed vector cannot directly reflect that difference.

  • Word order: A bag-of-words representation does not distinguish sentences that contain the same words in different orders, even when the sentences mean different things.

  • Unseen words: A word not represented during training may lack a learned representation, depending on how the tokenizer handles it.

These limitations motivated models that process sequences and produce representations informed by context.


Recurrent neural networks and sequential context

Recurrent neural networks

A recurrent neural network (RNN) processes a sequence one token at a time. At each step, it uses both the current token and a hidden state that summarizes the sequence seen so far. That state is updated as new tokens arrive.

This allows an RNN to use word order and context. For example, when processing a sentence, the representation at a later position can depend on the words that came before it. RNNs were used for tasks such as:

  • Text classification: Use the sequence representation to predict a label, such as sentiment.

  • Token classification: Use the contextual representation at each position to label a word, such as classifying it as a noun or verb.

  • Sequence generation: Predict the next token using the current input and the accumulated hidden state.

Long-range dependency and vanishing gradients

An RNN compresses prior sequence information into a hidden state that is repeatedly updated. This can make it difficult to preserve information over long distances. A word or fact from far back in the sequence may be needed to interpret a later token, but its influence may weaken as the sequence is processed.

This is related to the vanishing gradient problem during training. When gradients are propagated through many sequential steps, they can become very small, making it difficult for the model to learn dependencies over long distances. These issues can impair the model’s ability to connect a later reference, such as “it,” to something mentioned much earlier.

Long Short-Term Memory

Long Short-Term Memory (LSTM) networks are a variation of RNNs designed to help preserve information over longer intervals. In addition to a hidden state, an LSTM maintains a cell state intended to carry information across more steps. Although this improves the handling of longer-term information, it does not remove every limitation of recurrent processing.

RNNs also process tokens sequentially: later computations depend on the hidden state produced by earlier ones. This limits parallelism and can make training and inference slow for long sequences.


Attention: direct connections to relevant context

Attention offers a way to connect a token directly to other tokens in the sequence rather than relying only on a single evolving hidden state. A model can learn which earlier tokens are relevant when constructing a representation or making a prediction.

For example, in translation, a model predicting a target-language word may need to focus on the source-language word or phrase that corresponds to it. A direct connection to relevant source tokens can make this information easier to use than compressing the entire source sequence into one recurrent state.

Queries, keys, and values

Self-attention uses three learned representations for each token:

  • A query represents what a token is looking for in other tokens.

  • A key represents what a token offers as a potential match.

  • A value contains information that can contribute to the resulting representation.

For a given query, the model compares it with the keys of tokens in the sequence. These comparisons determine weights, and the weights are applied to the corresponding values. The resulting representation is therefore a weighted combination of information from the sequence.

Conceptually, if a token’s query matches another token’s key strongly, that token’s value receives greater weight. A teddy-bear token might assign a large weight to “cute” if that token is useful for representing the teddy bear in context.

Scaled dot-product attention

Let QQQ, KKK, and VVV denote the matrices of queries, keys, and values for a sequence. The standard scaled dot-product attention operation is:

Attention⁡(Q,K,V)=softmax⁡(QK⊤dk)V\operatorname{Attention}(Q,K,V) = \operatorname{softmax} \left( \frac{QK^\top}{\sqrt{d_k}} \right)VAttention(Q,K,V)=softmax(dk​​QK⊤​)V

Here:

  • QK⊤QK^\topQK⊤ contains query–key dot products.

  • dkd_kdk​ is the dimension of each key vector.

  • The factor dk\sqrt{d_k}dk​​ scales the dot products.

  • The softmax converts the scores for each query into weights that sum to one.

  • Multiplication by VVV forms a weighted combination of value vectors.

With a sequence of nnn tokens, the matrix QK⊤QK^\topQK⊤ has size n×nn \times nn×n. Each row corresponds to a query token, and each column corresponds to a key token. A cell records the score between one query and one key. The attention weights in a row indicate how much that query uses information from each token’s value.

The scaling factor helps control the magnitude of dot products as the key dimension changes, supporting stable softmax behavior.

Self-attention and word order

In self-attention, queries, keys, and values are all derived from the same sequence. Each token can use information from other tokens in that sequence to form a context-aware representation.

Self-attention by itself does not inherently indicate token order. If the same collection of tokens were presented in a different order, the mechanism would need additional positional information to distinguish the arrangements. Transformers therefore add position information to token representations.


The transformer architecture

The original transformer was designed for machine translation. It uses an encoder–decoder architecture:

  • The encoder processes the source sequence and produces contextual representations.

  • The decoder uses those representations, along with the tokens generated so far, to produce the target sequence.

This design replaces recurrent sequence processing with attention-based connections, allowing tokens to interact more directly and enabling more parallel computation during training.

Input embeddings and positional information

Each input token is first mapped to a learned token embedding. This embedding represents the token itself but, before contextual processing, does not encode its role in the sentence.

A position embedding provides information about where the token appears. In the original transformer, position information is added to the token embedding:

input representation=token embedding+position embedding\text{input representation} = \text{token embedding} + \text{position embedding}input representation=token embedding+position embedding

Position embeddings can be learned or constructed using predefined functions. The original transformer used sinusoidal functions with different frequencies, based on sine and cosine. Different frequencies provide distinguishable patterns across positions, and nearby positions have related patterns.

Learned position embeddings can work well within the positions seen during training, but they may be limited when an input exceeds the learned position range. Predefined positional functions offer an alternative that is not tied in the same way to a fixed set of learned positions.

Encoder blocks

An encoder processes the source sequence through repeated layers. Each encoder block contains two central components:

  1. Self-attention: Each token representation incorporates information from other tokens in the source sequence.

  2. Feed-forward neural network: A neural network processes each position’s representation, typically projecting it to a higher-dimensional intermediate space and applying a nonlinear activation.

The feed-forward network gives the model additional capacity to transform representations. Attention determines how information is gathered across tokens; the feed-forward component transforms the resulting features.

After several encoder blocks, each source token has a contextual representation that reflects the sequence around it.

Decoder blocks

The decoder generates the target sequence one token at a time. A decoder block in the original transformer uses:

  1. Masked self-attention: Each target position can attend to itself and earlier target positions, but not to future target positions.

  2. Cross-attention: Target-side queries attend to the encoder’s source-side representations. This allows generation to use information from the input sequence.

  3. Feed-forward neural network: This further transforms the representations.

The distinction between the two attention operations is important:

  • Self-attention connects tokens within the same sequence.

  • Cross-attention connects the target sequence to the encoder’s source sequence.

Masked attention and causal generation

During autoregressive generation, the model must not use future target tokens because those tokens have not been generated yet. Causal masking enforces this restriction by blocking attention from a position to later positions.

A causal mask is often implemented by assigning blocked attention scores a value equivalent to negative infinity before the softmax. Their resulting softmax weights are zero, so the model cannot use information from those future positions.

During training, masking also ensures that a token’s prediction is based only on information that would have been available at generation time.

Output probabilities and autoregressive decoding

At the end of a decoder block, a linear projection maps the representation to vocabulary-sized scores. A softmax converts these scores into a probability distribution over possible next tokens.

Generation proceeds autoregressively:

  1. The decoder receives a beginning-of-sequence token.

  2. It predicts a distribution over the next token.

  3. A token is selected from that distribution.

  4. The selected token is appended to the sequence and provided as input for the next step.

  5. The process repeats until the model produces an end-of-sequence token or another stopping condition is reached.

The method used to select a token from the probability distribution is a decoding choice. Selecting the highest-probability token is one possibility; other strategies can also be used.


Transformer dimensions and multi-head attention

Dimensions in attention

Suppose the input sequence has nnn tokens, and each token representation has dimension dmodeld_{\text{model}}dmodel​. The input can be arranged as a matrix of shape n×dmodeln \times d_{\text{model}}n×dmodel​.

Learned projection matrices transform this input into queries, keys, and values:

  • Queries have shape n×dqn \times d_qn×dq​.

  • Keys have shape n×dkn \times d_kn×dk​.

  • Values have shape n×dvn \times d_vn×dv​.

For the query–key matrix multiplication, dqd_qdq​ and dkd_kdk​ must match. The resulting attention-score matrix has shape n×nn \times nn×n. Applying those weights to the values produces an output with shape n×dvn \times d_vn×dv​.

Multi-head attention

Instead of computing attention once, multi-head attention computes several attention operations in parallel using different learned projections. Each head can learn a different way to relate tokens, such as focusing on different contextual or syntactic patterns.

The outputs of the heads are concatenated and then projected back into the model representation space. If there are hhh heads, each head produces its own representation, and a learned output projection combines them.

This resembles using multiple distinct filters in a convolutional neural network: each one can detect or model different patterns in the input.


Additional mechanisms used in transformers

Residual connections

A residual connection adds a layer’s input to its output. Rather than requiring a layer to replace the entire representation, the layer can learn a change to the input:

output=x+f(x)\text{output} = x + f(x)output=x+f(x)

Residual connections help information pass through deep networks and support effective gradient flow during training.

Layer normalization

Layer normalization normalizes activations within a representation. It can improve the stability of learning and help the model converge during training.

Dropout

Dropout is a regularization technique. During training, some units are randomly omitted with a specified probability. This discourages the model from relying too heavily on a small set of features and can improve generalization.

Label smoothing

With ordinary one-hot targets, a model is trained to assign all target probability to one token. Label smoothing softens this target distribution by assigning most, but not all, probability to the correct token and distributing a small amount among alternatives.

This reflects the fact that language may allow multiple plausible continuations. For example, several different words may form a reasonable completion of a phrase. Label smoothing can reduce overconfidence and was used in machine-translation systems.

Attention softmax versus output softmax

Transformers use softmax in different places, but these uses have different purposes:

  • In an attention layer, softmax converts query–key scores into weights over tokens. Those weights determine how values are combined.

  • At the output layer, softmax converts vocabulary scores into probabilities for the next token.

The operation is mathematically related in both places, but it acts on different scores and serves a different function.


Why the transformer was a turning point

Transformers retain direct connections among tokens through attention rather than relying only on a recurrent hidden state. This provides a way to represent relationships across a sequence and allows the model to consider distant tokens directly.

Two major sources of model capacity are:

  • Attention layers, which determine how information is combined across tokens.

  • Feed-forward layers, which perform learned transformations at each position and contain much of the model’s capacity.

Other mechanisms—such as positional information, residual connections, normalization, masking, and regularization—help the architecture represent sequence structure and train effectively.

The original transformer established an architecture that could be scaled to larger models and more training data. Modern LLMs build on transformer-based ideas, while later systems may use only selected components or introduce other generation approaches. Understanding the basic transformer therefore provides a foundation for studying both LLM training and applications such as conversational assistants and coding agents.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent