GNGiseldo Neo and Alana NeoBooks
Language Models with Python1 / 16

Introduction to LLMs

We will explore the architectural transition that made models such as GPT and BERT possible, followed by a guide to setting up a high-performance development environment with Python and PyTorch.

Learning objectives

By the end of this chapter, you should be able to explain what a language model computes, distinguish a parameter from a hyperparameter, compare n-grams, RNNs, and Transformers, and recognize the three most common families of Transformer architectures.

1.1 What Are LLMs?

In this book, we will take apart the inner workings of Large Language Models (LLMs), diving into the details of the Transformer architecture and opening the “black box” behind these technologies.

Large Language Models, known by the acronym LLM, are among the most impressive achievements of modern artificial intelligence. They are computational systems designed to understand, generate, and manipulate natural-language text in a way that resembles — and in many cases surpasses — the human ability to communicate in writing.

An LLM is, fundamentally, a sophisticated mathematical system that learns linguistic patterns from vast amounts of text. Unlike traditional computer programs, which follow explicit instructions written by programmers, an LLM “learns” language through massive exposure to text examples. This approach is commonly called machine learning, and more specifically deep learning, because it relies on neural networks with many layers.

The essence of a language model lies in its ability to predict what comes next in a sequence of text. When you type an incomplete sentence, the model can suggest words or constructions that complete the thought coherently. This probabilistic prediction ability is the foundation on which the whole architecture of LLMs was built.

This description can be made more precise. Given a context formed by the tokens x1,…,xtx_1,\ldots,x_t, the model produces a vector of logits, one value for each item in the vocabulary. The softmax function converts these values into a distribution P(xt+1∣x1:t)P(x_{t+1}\mid x_{1:t}). The system does not retrieve a ready-made sentence: it recomputes this distribution, chooses a token according to a decoding strategy, and repeats the process.

Conceptual view of an autoregressive LLM: the context is transformed by the model’s layers into a distribution over the next token.

Figure 1.1. Conceptual view of an autoregressive LLM: the context is transformed by the model’s layers into a distribution over the next token.

Note that a token is not necessarily a word. It can be a whole word, part of a word, punctuation, or a byte. This distinction will matter because the cost of attention, the size of the context, and the speed of generation are all measured in tokens, not words.

A probabilistic model is not a database

The parameters store distributed regularities learned during training. They are not a reliable table of facts, nor do they guarantee that the most likely continuation is true. Fluency and factual correctness are different properties.

1.2 What Are Neural Networks?

In recent decades, advanced artificial intelligence systems — such as machine translation models, image recognition, text generation, and LLMs themselves — have come to be dominated by a specific class of techniques known as deep learning. Although the term may suggest something overly complex or obscure, its conceptual basis is relatively straightforward: it is the systematic use of artificial neural networks to approximate complex functions from data. See the figure below:

In classical computer science, we are used to solving problems by spelling out rules and algorithms: we provide a well-defined function and expect it to produce the correct output for any valid input. However, many relevant real-world problems do not admit an exact algorithmic formulation. In these cases, what we have is not the function itself, but only examples of its behavior. Neural networks arise precisely as a mathematical mechanism to deal with this scenario.

Conceptual diagram

Figure 1.2. Conceptual diagram

Historically, the idea of neural networks goes back to 1943, with the seminal work of Warren McCulloch and Walter Pitts, who proposed a simplified mathematical model of biological neurons. Since then, the field has gone through cycles of enthusiasm and frustration. What explains its contemporary success is not a radical conceptual change, but the convergence of three factors: massive availability of data, advances in optimization methods, and a significant increase in computing power, especially through the use of GPUs.

<!– include the reference to Warren’s work –>

From a functional point of view, a neural network can be understood as a universal function approximator. Given a sufficiently large set of representative examples, the network is able to learn a function that maps inputs to outputs with controlled error. This is why it can, for example, estimate the probability that a tumor is malignant from clinical exams, even though no closed-form equation describing such a decision exists.

The internal structure of a neural network is organized into layers composed of units called artificial neurons. Each neuron performs an elementary mathematical operation: it receives a set of input values, multiplies each by an associated weight, sums these products, and adds a constant term called the bias. The result of this sum is then transformed by an activation function.

The activation function plays a conceptually crucial role. Without it, the whole network would reduce to a single linear transformation, regardless of the number of layers. By introducing nonlinearity, functions such as ReLU, sigmoid, or tanh allow the network to represent highly complex relationships between variables. Intuitively, the activation function decides which signals should be propagated forward and which should be attenuated or discarded.

Most classical neural network architectures are feed-forward: information flows only from input to output, with no cycles. The data pass successively through the layers, being transformed step by step, until the last layer produces the model’s final output. This output can represent a class, a continuous value, or even a probability distribution, depending on the problem.

The learning process consists of iteratively adjusting the network’s weights and biases. Initially, these parameters are set to random values. The network then produces an output for each training example, which is compared with the expected correct output. The difference between these two quantities is measured by a loss function, which quantifies how far the model is from the desired behavior.

From this loss, optimization algorithms — such as gradient descent and its variants — adjust the network’s parameters so as to progressively reduce the error. Conceptually, training can be seen as a search in a very high-dimensional space for a parameter configuration that minimizes the average loss over the training data while retaining the ability to generalize.

This perspective helps demystify neural networks. They do not “think” or “understand” in the human sense, but implement an elegant mathematical mechanism for capturing statistical regularities in data. Their strength lies less in each individual neuron and more in the emergent collective behavior of thousands or millions of these units working together.

It is important to emphasize that this conceptual framework serves as the basis for more sophisticated architectures, such as convolutional networks, recurrent networks, and attention-based models. However, all these variations share the same fundamental principle described here: learning a complex function from examples through successive compositions of simple transformations.

1.3 The Scale of Modern LLMs

In large language models, the term “large” is not merely decorative. These models are so called because they were trained on massive amounts of textual data and have billions or even trillions of adjustable parameters. A parameter, in this context, is a numerical value that the model learns during training and that determines how it processes and transforms information.

To grasp the magnitude involved, consider that public models in the Llama family have been released at scales from billions to hundreds of billions of parameters. For proprietary models, the parameter count and organization are not always disclosed; for this reason, it is best to avoid estimates treated as facts. Each parameter is a small numerical variable, but behavior emerges from the interaction among all of them, the data, the training objective, and the alignment procedure.

A parameter is learned, like an element of a weight matrix. A hyperparameter is chosen by the designer, such as the learning rate, the number of layers, or the embedding dimension. Keeping the two concepts apart helps you read papers and model configurations without confusing what training discovers with what the engineer defines.

1.4 Why LLMs Matter

The relevance of large language models goes beyond mere technological fascination. They represent a change in how humans and machines interact. Before LLMs, communicating with computers required humans to learn programming languages or specific interfaces. With LLMs, natural language becomes the primary medium of communication, democratizing access to information and automation.

These models have applications spanning practically every sector of human activity. In medicine, they assist in diagnosis and scientific research. In education, they work as personalized tutors. In creative writing, they serve as collaborators and sources of inspiration. In customer service, they operate as assistants available twenty-four hours a day. The versatility of LLMs is a direct consequence of the generality of the problem they solve: understanding and generating language.

1.5 The Evolution of Natural Language Processing (NLP)

1.5.1 The Beginnings: Statistical Language Models

To understand the revolution represented by modern LLMs, it is instructive to step back in time and examine the approaches that preceded them. In the 1980s and 1990s, language models were predominantly statistical. Models such as n-grams dominated the field, in which the probability of a word appearing was computed from the previous n words.

These statistical models had severe limitations. The larger the value of n needed to capture relevant context, the more data was required to estimate all possible combinations. The curse of dimensionality made it impossible to capture long-range dependencies efficiently. Moreover, these models could not generalize to sequences never seen during training, since they were essentially probabilistic lookup tables.

1.5.2 The Era of Recurrent Neural Networks

The next leap came with the introduction of recurrent neural networks (RNNs), especially Long Short-Term Memory (LSTM) networks and Gated Recurrent Units (GRUs). These architectures overcame the limitations of n-grams by learning dense, continuous representations of words, known as embeddings, and by processing sequences step by step while maintaining an internal state that captured contextual information.

RNNs allowed, for the first time, language models to capture long-term dependencies in text. An RNN can, in theory, “remember” information seen hundreds of steps earlier in the sequence. In practice, however, RNNs suffered from vanishing gradients (gradients that shrink during training), which made it hard to learn very long dependencies.

  • Sequential processing: RNNs process words one at a time, in strict order (left to right). The hidden state at step tt depends on the current input and on the hidden state at step t−1t-1.
  • The bottleneck: Impossibility of parallelization: Because computing step tt requires the result of step t−1t-1, it is not possible to make massive use of the parallelism of modern GPUs. Long-term forgetting: Even with LSTMs, context fades in very long sequences. The model “forgets” the beginning of the sentence by the time it reaches the end.

1.5.3 The Transformer Revolution

In 2017, an academic paper titled “Attention Is All You Need”, written by researchers at Google and the University of Toronto, introduced an architecture that would irreversibly transform the field of natural language processing. The Transformer, as it was named, completely abandoned sequential processing in favor of a mechanism called self-attention.

<!– include reference to the Transformer paper –>

The paper showed that, using attention mechanisms exclusively, it was possible to achieve results superior to those of recurrence-based architectures, with the additional advantage of being highly parallelizable, allowing training on graphics hardware (GPUs) and tensor processors (TPUs) far more efficiently. Therefore, the modern history of NLP can be divided into two main eras: the pre-Transformer era (dominated by recurrent networks) and the post-Transformer era (dominated by attention mechanisms).

The Transformer architecture discarded recurrence in favor of the self-attention mechanism.

  • Full parallelization: The Transformer processes the entire input sequence simultaneously, not sequentially.
  • Attention mechanism: It lets the model “look” at all the other words in the sentence at once to understand the context of a specific word, regardless of the distance between them.
  • Positional encoding: Since there is no recurrence, word order is injected mathematically through position vectors.

After the seminal 2017 paper, a new class of models emerged: pre-trained generative models, known by the acronym GPT (Generative Pre-trained Transformer). The first GPT, presented by OpenAI in 2018, showed that it was possible to pre-train a language model on large volumes of unlabeled text and then refine it (fine-tune it) for specific tasks with relatively few examples.

This approach of pre-training followed by fine-tuning became the dominant paradigm and ushered in an era of unprecedented scalability. Each generation of models brought exponential increases in the number of parameters and the amount of training data, resulting in ever more impressive capabilities.

1.5.4 Evolution and Architecture Diagram

The diagram below illustrates the complete flow of an n-gram language model, from the training phase to the inference phase (prediction/text generation).

N-gram training phase

Figure 1.3. N-gram training phase

The diagram above has two phases.

Training phase:

  • It receives a volume of raw text (Corpus).
  • It splits the text into basic pieces (Tokens).
  • It groups these tokens to the desired size, for example, two at a time for a bigram model (N-gram Extraction).
  • It counts repetitions and generates statistical probabilities to learn “which word is most likely to appear after X” (Probability Calculation).

Inference / generation phase:

  • To generate text or autocomplete, the model takes the current sentence (Context).
  • It looks only at the preceding words, limited to the size of the n-gram (History Extraction).
  • It consults its “Magic Table” (Model Lookup).
  • It spits out the word that statistically makes the most sense next (Prediction).

The diagram below illustrates the linear processing of a Recurrent Neural Network (RNN).

Diagram

In the diagram above you can see the “bottleneck” of these networks.

  • The diagram flows from left to right, representing time passing as the model reads a sentence, word by word:

  • Inputs (Inputs 1, 2, and 3): They represent the tokens of your sequence being fed in one at a time. For example, in a sentence like “The cat slept”, Input 1 would be “The”, Input 2 would be “cat”, and so on.

  • Hidden states (Hidden 1, 2, and 3): This is the network’s short-term “memory”. It accumulates the knowledge of what has already been read.

  • When Input 1 enters, it generates state Hidden 1.

  • When Input 2 enters, notice that there are two arrows pointing to Hidden 2: one coming from Input 2 and another coming from Hidden 1. This means the model processes the current word combined with the “memory” of the previous one.

  • Hidden 3 does the same, depending on Input 3 and on all the memory accumulated earlier at the Hidden 2 step.

  • Output: At the end of the chain, the final hidden state (Hidden 3) holds (in theory) the encapsulated context of the entire sequence read, and is used to generate the final result, such as predicting the next word.

  • The diagram serves visually to demonstrate the processing bottleneck: the impossibility of parallelization.

  • Thanks to the arrows connecting the successive Hidden nodes, it is evident that you cannot mathematically compute block Hidden 3 without first finishing block Hidden 2, which needs block Hidden 1.

  • Modern computers and graphics cards (GPUs) are extremely fast and built to process thousands of things at the same time (“in parallel”). However, this technique breaks that power, because it forces the machine to patiently wait for the previous step to finish (single file).

Diagram

1.6 Types of Transformer-Based LLMs and Causal Language Modeling (CLM)

Modern LLMs generally use variations of the original Transformer architecture:

  1. Encoder-only (e.g., BERT): Specialists in “understanding” text. Great for classification, entity recognition, and sentiment analysis. The model sees bidirectional context (left and right).
  2. Decoder-only (e.g., GPT, LLaMA): Specialists in “generating” text. Trained to predict the next word (causal language modeling). The model sees only the left context.
  3. Encoder-decoder (e.g., T5, BART): Used for translation and summarization, where one sequence is transformed into another.

Causal Language Modeling (CLM) is the training objective in which the model learns to predict the next token in a sequence, using only the preceding tokens as context.

In simple terms, given a text such as:

I like to study

the model learns something like:

  • after I → predict like
  • after I like → predict to
  • after I like to → predict study

In other words, it always predicts from left to right.

The word causal here does not mean “cause” in the philosophical sense. It means the model respects a causal mask: when predicting the current token, it cannot look at the future. It sees only the preceding tokens.

Formally, for a sequence (x1,x2,...,xT)(x_1, x_2, ..., x_T), CLM maximizes the probability:

P(x1,x2,...,xT)=∏t=1TP(xt∣x<t)P(x_1, x_2, ..., x_T) = \prod_{t=1}^{T} P(x_t \mid x_{<t})

This means the probability of the entire sequence is decomposed as a chain of next-token predictions.

During training, teacher forcing is normally used: the correct sequence is given to the model, and it tries to predict each next token. The loss is usually the cross-entropy between the predicted distribution and the true next token.

Example with shifting:

  • Input: The cat sleeps
  • Target: cat sleeps <eos>

So the model receives the shifted sentence and learns to predict the next element at each position.

This objective is typical of autoregressive models such as GPT, LLaMA, Mistral, Gemma, and similar ones.

It differs from objectives such as Masked Language Modeling (MLM), used in BERT, where some tokens are masked and the model tries to recover them using context from both sides.

In practice, CLM is well suited to text generation, autocomplete, chatbots, generative summarization, autoregressive translation, code generation, and other NLP tasks.

The key intuition is: the model learns to continue plausible sequences.

Example in pseudo-format:

Sequence:  [I] [like] [Python]

Training steps:
input: [I]                 target: [like]
input: [I like]            target: [Python]

Summary

We saw that the sequential-processing limitation of RNNs led to the development of Transformers, which use attention mechanisms and parallel processing.

Check your understanding

If a model assigns probabilities 0.6, 0.3, and 0.1 to three possible next tokens, this does not mean it “knows” which one is correct. It only means that, conditioned on the context and the current parameters, the first token received the largest share of probability mass. Explain why a sampling strategy could still choose any of the three.

1.7 From Learning a Function to In-Context Learning

A traditional neural network learns a function during training and keeps its parameters fixed when it receives new examples. An LLM also works this way, but the context window adds an interesting possibility: examples provided in the prompt itself can temporarily change behavior without altering the weights. This phenomenon is called in-context learning.

Consider the task of classifying commands as read or write. We can provide two example pairs and then a new command:

"show the file" -> read
"save the report" -> write
"list the folder" -> ?

The model uses the examples as part of the sequence and tries to continue the pattern with read. With zero examples, the task is zero-shot; with one example, one-shot; with a few examples, few-shot. Nothing was permanently recorded: when another context starts, this adaptation disappears.

This distinction separates three moments. In pre-training, the parameters absorb regularities from large text collections. In fine-tuning, some or all of the parameters are modified for a specific purpose. In in-context learning, only the activations change while the model processes the prompt. Confusing these mechanisms leads to wrong expectations about memory and learning.

A demonstration is not a guarantee

An example in the prompt guides the continuation but does not create a formal rule. Changes in order, wording, or context can alter the result; for this reason, important tasks still require testing and validation.