Article

What is a Large Language Model (LLM)?

VishalPublished·21 min read

Introduction

This article aims to outline the technology and process behind modern language models like GPT, Gemini, and more. We will look at Tokenization and dive deep into Transformers as presented by Ashish Vaswani et al. in Attention Is All You Need (Google, 2017). I will refer to GPT-3 as presented in Language Models are Few-Shot Learners (OpenAI, 2020) to provide examples. Note that there is a lot more depth to the topic than presented in this article; however, I hope this serves as a solid introduction or revision!

I found the following resources very helpful in my learning and encourage you to refer to them if you'd like to dive deeper into transformers or technologies that it succeeds:

  • If you are a visual learner, refer to the awesome Neural Networks YouTube playlist by 3Blue1Brown that covers gradient descent, back propagation, neural networks, and transformers.
  • If you'd like to get hands on experience building small n-gram language models, neural networks, and transformer models, checkout the Google DeepMind: AI Research Foundations path on Google skills.

With that said, let's dive in!

A language model is a machine learning model that understands and generates language. We refer to language models that require large computational power and training datasets as Large Language Models (LLMs). LLMs like GPT-3 generate language by predicting the next word based on its understanding of the language, as learned through its training data and process. Such models are also called auto-regressive.

At a high level, developing a language model involves the following steps:

  1. Retrieve data that we want the model to learn
  2. Train the model
    • Set up the architecture of the model (Transformers!) and initialize the weights.
    • Run training iterations to find the optimal values of the weights.
  3. Fine-tune the model for specific tasks
    • Take a model that understands the language and update its weights further to improve on specific tasks like question answering (QA).
  4. Evaluate the model
    • Assess how the model performs.

This article will primarily focus on the Transformer architecture and training.

Pre-processing

Once we have identified the training datasets, we may want to process it before training to retrieve high quality data. This could involve removing duplicates and HTML tags and encoding symbols like emojis.

GPT-3 was trained on the Common Crawl dataset that consists of nearly a trillion words from raw webpage data, metadata extracts, and text extracts. To maintain high quality training data, researchers filtered Common Crawl data based on similarity to known high quality datasets, de-duped data, and added known high quality data to the training corpus.

To help walkthrough the following components in the article, assume our training data contains the following quote from Edsger Dijkstra

The question of whether machines can think is about as relevant as the question of whether submarines can swim.

Encoding

Once we have the processed data, we need to encode it into a machine translatable representation - numbers.

Here are the high-level steps:

  • Define tokens - symbols in the data.
  • Define the vocabulary (VV) - ordered set of all tokens.
  • Given V={t1="wo",t2="r",t3="d",… }V = \{t_1 = "wo", t_2 = "r", t_3 = "d", \dots\}, we can break down strings in the language like "wordword" into tokens "t1t2t3t_1t_2t_3". This process is called Tokenization.
  • Given a tokenized string "t1t2t3t_1t_2t_3", we can represent it as a list of numbers [1,2,3][1, 2, 3] corresponding to the indices of the tokens in the vocabulary. This process is called Encoding.

How do we define tokens and the vocabulary?

Here are two simple algorithms:

  • Character tokenization - every character is considered a token.
  • Word tokenization - every space separated substring (~word) is considered a token.

Character vs Word

Assume our training data includes all ASCII characters and majority of English words

CharacterWord
Vocabulary size96 ASCII characters. Lower computational complexity to compute meanings of tokens.Around a million English words. Higher computation complexity to compute meaning of each token.
Encoding meaningFewer tokens mean that each token needs to encode more meaning, making it more difficult to be precise. For example, 'a' needs to encode what it means to the words "apple", "astrophysics", etc.More tokens mean that a given token can encode its meaning precisely. For example, "apple" can encode its meaning distinct from "astrophysics". However, it is likely that some words occur infrequently resulting in not precise understanding.
New stringsWith characters as vocabulary, we can tokenize and understand something about a new string in the language. For example, if we wanted to encode a word not in our data, say "artificial", we could form some understanding by putting together the meaning of "a", "r", and so on.With words as vocabulary, we cannot tokenize a new word and thereby cannot understand it.
Sequence lengthLonger encoding sequences - our Dijkstra quote is 111 tokens long. Higher computational complexity to process more context.Shorter encoding sequences - our Dijkstra quote is 19 tokens long! Lower computation complexity to process more context.

The key observation from the table is the inverse impact of vocabulary size and sequence length on computational complexity. Algorithms that help us balance the two by defining sub-word tokens are called sub-word algorithms. One such popular algorithm is Byte-Pair Encoding.

Byte-Pair Encoding (BPE)

The idea of BPE is to define tokens based on their frequency. Here is the pseudocode for the algorithm [5]:

// Initialize
EOW = special symbol that denotes end of word

tokenized_word_list = []
vocabulary = {EOW}

for word in dataset:
    add character tokenized word to tokenized_word_list
    // example: tokenized_word_list[i] = ["w", "o", "r", "d", EOW]

    add character to vocabulary set if not exist already

for i in NUM_ITERS:
    token1, token2 = most frequent consecutive pair of tokens
    // example: "r" and "d"

    add new token (token1 + token2) to vocabulary 
    // example: add "rd"

    replace occurrences of token1, token2 in tokenized_word_list
    // example: ["w", "o", "rd", EOW]


return vocabulary    

GPT-3 used a BPE vocabulary with 50,257 tokens.

The result of BPE can be categorized as follows:

  • Vocabulary size is moderate, balancing compute with encoding meaning. For example, frequent tokens like "the" can encode its meaning while it also contributes to the meaning of other words that do not have their own tokens like "theatre".
  • BPE enables us to understand something about new words more efficiently. For example, we can understand something about "theatre" from the token "the".
  • Sequence lengths are moderate. By merging together frequent tokens, BPE directly increases the likelihood that a string will include merged tokens which reduces the sequence length!

Overall, BPE and sub-word tokenizers enable us to encode precise meaning and understand new strings with manageable compute, giving us the best of two extremes.

In practice, the algorithm is run on bytes and not characters for efficiency.

Training

LLMs are trained using a machine learning method called self-supervised learning. The training goal is to predict the next token in a sequence; the input sequence and output token pairs are retrieved from the training data. For example, given our Dijkstra quote and a word tokenizer, one objective is to output "machines" for input "The question of whether".

For demonstration purposes, we will use a word tokenizer, context length (ctx) of 4, and our data will be "The question of whether machines". The process is the same if we use BPE and a context of a million tokens!

The first step is to obtain the input and output pairs. This can be represented as the following:

// Suppose the encoding of "The question of whether machines"
encoded_data = [10, 2, 33, 42, 56] 

inputs = encoded_data[:-1]             //  [10, 2, 33, 42]
outputs = encoded_data[1:]             //  [2, 33, 42, 56]

With the help of matrices, we can train with several input-output pairs at the same time. The above representation signifies that we want token 2 to follow 10, token 33 to follow 10, 2, and so on. We remove the last token in the input list since there is nothing that follows it and similarly the first token in the output since there is nothing that it could follow.

Below is the high-level architecture of the pipeline that the data flows through. We will cover the various steps in the following sections.

Embedding

While encoding represents data, embeddings represent meaning of data. They are dense vectors in a high dimensional space (12, 288 for GPT-3). The dimension of a model's embeddings is commonly represented with the hyperparameter dmodeld_{model}.

Every token will have a corresponding embedding that is learned through training. The values are initialized to small random numbers. That is, for each token in our input, we have an embedding vector tei⃗\vec{te_i} of size dmodeld_{model}.

But the meaning of text is not solely captured by tokens. "The question of" does not mean the same as "question of The". We need to encode where the tokens are to capture their meaning. This is done through positional embeddings.

Vaswani et al. used sinsin and cosinecosine functions in an alternating pattern as follows where pospos is position of the token and jj is the embedding dimension:

PE(pos,2j)=sin(pos/100002j/dmodel)PE(pos,2j+1)=cos(pos/100002j/dmodel) PE_{(pos, 2j)} = sin(pos/10000^{2j/d_{model}}) \\ PE_{(pos, 2j + 1)} = cos(pos/10000^{2j/d_{model}})

So PE(pos=1)PE(pos=1) gives the positional encoding for input 1 ("The"). The final embedding then for each token at position ii in our input is

ei⃗=tei⃗+PE(pos=i) \vec{e_i} = \vec{te_i} + PE(pos = i)

If you're curious, another popular solution is rotary positional embeddings.

Last note for embeddings: we want to learn the embedding vectors for each token in the vocabulary, so the number of embedding parameters/weights to learn are ∣V∣∗dmodel|V| * d_{model}. This is one way how the vocabulary size impacts compute!

Transformer

Transformer is the underlying architecture that drives LLMs. I will continue the running example and provide diagrams and math to help understanding. If you're overwhelmed by the expressions beyond this point, it's okay! You can always revisit them later. On the other hand, if you're interested in more details, optimizations, and nuances, check out the resources and papers I've linked.

Note that Transformers were presented with an encoder and a decoder component. However, LLMs like GPT-3 and Gemini are decoder-only which is what we will look at.

As we see in the high-level diagram, LLMs have NN transformer blocks/layers in sequence. The input and output for each block is a matrix of dimensions (ctx,dmodel)(ctx, d_{model}). Let's look at what's inside a block.

Attention

Attention is the key mechanism introduced by Vaswani et al. that drives LLMs. An attention function maps a query and a set of key-value pairs to a weighted sum of the values where the weights are assigned by a compatibility function of the query and corresponding key.

The goal of attention is to encode how the context of a token affects its meaning. For example, "bank" could refer to the financial institution or a riverside, depending on the words that it is surrounded by.

The idea is that every input has corresponding query (q⃗\vec{q}), key (k⃗\vec{k}), and value (v⃗\vec{v}) vectors. One example to think about is q2⃗\vec{q_2} encoding "What does your terrain look like?" and k1⃗\vec{k_1} encoding "geographical terrain" with v1⃗\vec{v_1} encoding "large water body". How much k1⃗\vec{k_1} matches q2⃗\vec{q_2} gives us how much v1⃗\vec{v_1} affects the meaning of input 2. In this example, they are highly compatible and the value of v1⃗\vec{v_1} could imply that the bank is a river bank.

In reality, the queries, keys, and values are more abstract and we do not know exactly what they encode. They are learned during training!

Formally, we compute this for all combinations of inputs using matrices as follows where qi⃗\vec{q_i} and ki⃗\vec{k_i} have dimension dhd_h, vi⃗\vec{v_i} has dimension dvd_v, Q=[q1⃗,q2⃗,…,qctx⃗]T,K=[k1⃗,k2⃗,…,kctx⃗]T,V=[v1⃗,v2⃗,…,vctx⃗]TQ = [\vec{q_1}, \vec{q_2}, \dots, \vec{q_{ctx}}]^T, K = [\vec{k_1}, \vec{k_2}, \dots, \vec{k_{ctx}}]^T, V = [\vec{v_1}, \vec{v_2}, \dots, \vec{v_{ctx}}]^T

Attention(Q,K,V)=softmax(QKTdh)Vsoftmax(x⃗)i=exi∑j=1nexjAttention(Q, K, V) = softmax(\frac{QK^T}{\sqrt{d_h}})V \\ softmax(\vec{x})_i = \frac{e^{x_i}}{\sum_{j=1}^n{e^{x_j}}}

The softmax function is commonly used in machine learning to convert a vector of numbers to a probability distribution where each resulting value is in between (0, 1), sum of all values is 1, and larger values have exponentially larger probabilities. Vaswani et al. scale QKTQK^T by a factor 1/dh1/\sqrt{d_h} to prevent values from getting large and into regions where the softmax function has small gradients.

In addition, we do not want later tokens to influence earlier tokens (for example, input 3 should not affect meaning of input 2 since that would bias our prediction!). This is achieved by "masking" later tokens by setting them to a big negative number before softmax, which in turn results in ~0 probability when softmax is applied.

What we just saw is a single head of attention. Transformers run the attention computation in multiple heads in parallel. The idea being that each head can compute a different meaning - q2q_2 in head 1 could encode "What is your terrain?" while q2q_2 in head 2 could encode "What is your purpose?".

Consequently, each head has its only Q,K,VQ, K, V matrices. This is done by linearly projecting all the queries, keys, and values to appropriate dimensions for each head. The outputs are concatenated and projected again to get the final output.

Let the number of heads be hh, we can represent multi head attention as

MultiHead(Q,K,V)=concat(head1,…,headh)WOheadi=Attention(QWiQ,KWiK,VWiV)MultiHead(Q, K, V) = concat(head_1, \dots, head_h)W^O \\ head_i = Attention(QW_i^Q, KW_i^K, VW_i^V)

Where parameter matrices WiQ∈Rdmodel×dh,WiK∈Rdmodel×dh,WiV∈Rdmodel×dv,WO∈Rhdv×dmodelW_i^Q \in \mathbb{R}^{d_{model} \times d_h}, W_i^K \in \mathbb{R}^{d_{model} \times d_h}, W_i^V \in \mathbb{R}^{d_{model} \times d_v}, W^O \in \mathbb{R}^{hd_{v} \times d_{model}} are the projections. Note that typically dh=dmodel/hd_h = d_{model}/h. For example, GPT-3 used h=96h = 96 with dh=12,288/96=128d_h = 12, 288/96 = 128.

Now let's apply what we learned to our example:

Note that the diagram shows attention for one head of transformer block 1, which receives input E=[e1⃗,e2⃗,e3⃗,e4⃗]T,∣E∣=(ctx,dmodel)E = [\vec{e_1}, \vec{e_2}, \vec{e_3}, \vec{e_4}]^T, |E| = (ctx, d_{model}). For heads in consequent blocks, the input is the output of the previous block. The process remains the same with the input multiplied by the parameter matrices WiQ,WiK,WiVW_i^Q, W_i^K, W_i^V to retrieve Q,K,VQ, K, V for each of the hh heads.

So each head outputs a matrix of size (ctx,dv)(ctx, d_v). The outputs are concatenated, resulting in a matrix of size (ctx,hdvctx, hd_v). Multiplying by parameter output matrix WOW^O gives us the attention output matrix for the block, which has size (ctx,dmodel)(ctx, d_{model})!

Feedforward Neural Network

Transformers consist of a fully connected Feedforward Neural Network with 1 hidden layer. Neural networks precede attention and excel in learning non-linear relationships. While attention is designed for inputs to attend to each other, each input is passed through the neural network in parallel.

The abstract idea behind this step is that the various neurons of a layer can learn different aspects of language - one neuron could learn about blueness, another about size, and so on. I encourage you to refer to the linked resources and learn more about neural networks if this is new to you.

All connections in the network have associated weights that are learned. In practice, all the weights between inputs and hidden layer neurons are arranged in a dmodel×dffd_{model} \times d_{ff} matrix where dffd_{ff} is the number of neurons in the hidden layer. We will refer to this matrix as the Up matrix. Similarly, we have the dff×dmodeld_{ff} \times d_{model} Down matrix that is made of weights from the hidden layer to the output layer.

Two important considerations for neural networks are the number of neurons and the activation function. GPT-3 used dff=4∗dmodeld_{ff} = 4 * d_{model} and the Gaussian Error Linear Unit (GELU) activation function.

Residual Connection (Add)

As we increase the depth of neural networks, we observe a degradation problem - accuracy (validation error) saturates and then drastically degrades. Researchers have shown that the degradation is not a result of overfitting and that training error increases as layers are added [6].

To overcome this limitation, researchers introduced deep residual learning. Say the desired function to learn for a given layer is H(x)H(x). The idea is that the layer will learn the residual function F(x)=H(x)−xF(x) = H(x) - x instead of H(x)H(x). The final output then is H(x)=F(x)+xH(x) = F(x) + x which is implemented in neural networks with "shortcut connections" (inputs (x) bypass layers to be added to the output F(x)F(x)). Not only did residual learning show lower training error, but it also improved accuracy as layers were added!

Abstractively, residual learning can be thought of as learning the change in meaning to the input to get the desired output. We have residual connections following the attention and neural network components in transformers, which has enabled us to scale LLMs and improve learning.

Layer Normalization (Norm)

Transformers use layer normalization to stabilize and accelerate training by ensuring that for a given input vector, the mean of its values is 0 and the variance is 1. This prevents gradients (change in weights) from becoming too small (slowing down learning) or too big (making training unstable).

The high-level diagram shows layer norm components after the attention and MLP blocks. Remember the output of both of those blocks is a ctx×dmodelctx \times d_{model} matrix. For every row x⃗\vec{x} in those matrices, we have

LayerNorm(xi)=γixi−μ(x)var(x)+ϵ+βiLayerNorm(x_i) = \gamma_i \frac{x_i - \mu(x)}{\sqrt{var(x)}+\epsilon} + \beta_i

Where γi\gamma_i is the scaling vector, βi\beta_i is the shifting vector, and ϵ\epsilon is a small constant for stability.

Unembedding

Given the ctx×dmodelctx \times d_{model} output matrix of the final transformer block, where each row is an abstract meaning of the corresponding input token, we want to predict the next token for each input.

To do so, we perform yet another linear transformation using a dmodel×∣V∣d_{model} \times |V| parameter matrix, often called the unembedding/output matrix. The values in the resulting ctx×∣V∣ctx \times |V| matrix multiplication output are referred to as logits.

Logit at (x,y)(x, y) is a raw score for token yy in the vocabulary following input token xx. We use softmax on each row to convert the logits to a probability distribution for the next token. For example, applying softmax on row 1 will give us the probability of token 1 in the vocabulary following input 1, and so on.

Loss & Back-propagation

For each input token, we have computed the probabilities for next tokens. But remember, the output is based on the current values assigned to the model parameters. We need to assess how good the prediction is and update the values of the parameters accordingly. This is where the learning actually happens.

From our example, we know that input 1 (“The”) is followed by token 2 (“question”). If the model assigns a high probability p1,2p_{1,2} to token 2 following input 1, we want the loss to be small. If the probability is very low, the loss should be large. A common loss function that achieves this is cross-entropy loss (−log(p1,2))-log(p_{1,2})).

Training aims to minimize the loss. During back-propagation, gradients are first computed with respect to the output scores (logits), then propagated backward through the output layer, transformer blocks, and finally to the token embeddings, adjusting parameters to increase the probability of correct next tokens.

What we walked through is 1 input of context size 4. The loss of entire input is the avg negative log-likelihood over all the input tokens. In practice, inputs are further grouped together into batches for training.

Counting Parameters

Now that we have an understanding of the underlying architecture, let's look at what the 175B parameters in GPT-3 are.

ComponentGeneral FormulaGPT-3 value
Embedding|V| ∗  dmodel* \; d_{model}50,257∗12,288=617,558,01650, 257 * 12, 288 = 617,558,016
QueryN∗h∗dmodel∗dhN * h * d_{model} * d_h96∗96∗12,288∗128=14,495,514,62496 * 96 * 12, 288 * 128 = 14,495,514,624
KeyN∗h∗dmodel∗dhN * h * d_{model} * d_h96∗96∗12,288∗128=14,495,514,62496 * 96 * 12, 288 * 128 = 14,495,514,624
ValueN∗h∗dmodel∗dvN * h * d_{model} * d_v96∗96∗12,288∗128=14,495,514,62496 * 96 * 12, 288 * 128 = 14,495,514,624
OutputN∗hdv∗dmodelN * hd_v * d_{model}96∗(96∗128)∗12,288=14,495,514,62496 * (96 * 128) * 12, 288 = 14,495,514,624
UpN∗dmodel∗dffN * d_{model} * d_{ff}96∗12,288∗(4∗12,288)=57,982,058,49696 * 12, 288 * (4 * 12, 288) = 57,982,058,496
DownN∗dff∗dmodelN * d_{ff} * d_{model}96∗(4∗12,288)∗12,288=57,982,058,49696 * (4 * 12, 288) * 12, 288 = 57,982,058,496
Unembeddingdmodel  ∗d_{model} \; * |V|50,257∗12,288=617,558,01650, 257 * 12, 288 = 617,558,016

Symbol guide:

  • ∣V∣|V|: vocabulary size
  • dmodeld_{model}: dimension of embeddings
  • NN: number of transformer blocks/layers
  • hh: number of heads in an attention block
  • dhd_h: dimension of each Query, Key in an attention block
  • dvd_v: dimension of each Value in an attention block
  • dffd_{ff}: dimension of the hidden layer in the feedforward network

Fine-tuning

The process we saw so far has come to be a part of training modern LLMs and referred to as pre-training. The process of taking a pre-trained model that understands language and training it further to improve on specific tasks or domains is called fine-tuning.

For Gemini, this refinement includes two widely used techniques [7]:

  • Supervised Fine-tuning (SFT): The model is trained on high quality prompt-response pairs written or reviewed by humans.

  • Reinforcement Learning from Human Feedback (RLHF): The model is updated based on how its responses are scored by human evaluators on accuracy, relevancy, safety, etc.

Inference

During training, the model learned the values of the parameters that help it understand language. When a trained model is invoked with a given input prompt, it is processed through the pipeline with the learned values:

  • prompt is tokenized
  • embeddings for the corresponding tokens are retrieved
  • processed through the transformer blocks
  • logits are converted to probabilities

Generating the next token given the probabilities is called decoding. Here are some popular decoding algorithms:

Greedy decoding: Select the most probable token. While it may be more accurate, it is deterministic and does not allow the model to recover from a bad choice.

Random sampling: Choose (sample) the next token randomly based on the probabilities. This enables randomness at the cost of accuracy.

We want to have some randomness in generation, but also be relevant and factual. Here are two parametric algorithms that enable us to control creativity and factuality:

Top-k sampling: Select the top kk most probable tokens, re-normalize the probabilities among them, and sample a token.

Top-p sampling: Sort the tokens in order of decreasing probabilities, select the first xx tokens for which the cumulative probability is >p>p, re-normalize and sample. This is favoured over top-k because it directly depends on the probabilities instead of a static number of tokens. Depending on the probability distribution, top-k may exclude equally probable tokens or include very random ones.

Given a prompt, we generated the next token. The generated token is then included in the input to generate the following token, and so on! Models that generate one token at a time are called auto-regressive.

Conclusion

We uncovered the underlying technology and process behind LLMs. Specifically, we saw how we take data and train a model to understand language. In addition, we looked at decoding algorithms that generate the text we see during inference. If it still feels like magic, you're not alone! And if you're shocked by the amount of computation the model performs to write your email, maybe that is a good thing.

While large language models have demonstrated remarkable capabilities, they have limitations. They remain expensive to train and serve, opaque in their internal reasoning, sensitive to data quality, and prone to confidently generating incorrect or misleading outputs. As we push the limits of compute, there is increasing research into more efficient architectures. I look forward to what we uncover.

With that, I hope this helped you get started with understanding LLMs and modern AI. Happy learning!

References

  1. Vaswani, Ashish et al. Attention Is All You Need (Google, 2017)
  2. Brown, Tom B. et al. Language Models Are Few-Shot Learners (OpenAI, 2020)
  3. Radford, Alec et al. Language Models Are Unsupervised Multitask Learners (2019)
  4. Radford, Alec et al. Improving Language Understanding by Generative Pre-Training (2018)
  5. Sennrich, Rico et al. Neural Machine Translation of Rare Words with Subword Units (2015)
  6. He, Kaiming et al. Deep Residual Learning for Image Recognition (Microsoft, 2015)
  7. Gemini Team. Gemini: A Family of Highly Capable Multimodal Models (Google, 2023)
Comments (0)
No comments yet. Be the first to comment!