Skip to content
ImagineWorld

Generating text with a pretrained LLM

node_idnode-book_build-a-reasoning-model_chapter-02-generating-text-with-a-pretrained-llm
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num2
chapter_titleGenerating text with a pretrained LLM
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 2 — Generating text with a pretrained LLM

Section titled “Chapter 2 — Generating text with a pretrained LLM”

This chapter covers

  • Setting up the code environment for working with LLMs
  • Using a tokenizer to prepare input text for an LLM
  • The step-by-step process of generating text with a pretrained LLM
  • Caching and compilation techniques for speeding up LLM text generation

In the previous chapter, we discussed the difference between conventional large language models (LLMs) and reasoning models. We also introduced several techniques that can improve the reasoning capabilities of LLMs. These techniques are usually applied on top of a conventional (base) LLM.

In this chapter, we’ll lay the groundwork for the upcoming chapters by loading a pretrained base model, as shown in figure 2.1. Previously, we discussed how reasoning methods are often added after the usual post-training stages. But starting from a base model makes it easier to see which capabilities come from the reasoning methods

Introducing LLMs for text generation themselves. The conventional LLM in this chapter is a nonreasoning LLM, and more specifically, a pretrained base model rather than an instruction- or preference-tuned assistant.

This chapter: LLM basics

Stage 1: We start with a pretrained LLM as a base model that we’ll turn into a reasoning model (chapter 2).

Stage 2: Model evaluation techniques are essential for comparing the response qualities of the various methods and LLMs we are developing (chapter 3).

Stage 3: After the LLM and evaluation basics, we’ll explore reasoning-enhancing techniques that do not require training the LLM (chapters 4 and 5).

Stage 4: We’ll cover two main categories of training techniques to improve the reasoning capabilities of LLMs (chapters 6 to 8).

graph LR
    subgraph G1 ["1 - Conventional LLM"]
        direction TB
        A1["Loading pretrained weights"]
        A2["Text generation"]
    end
    subgraph G2 ["2 - Evaluation"]
        direction TB
        B1["Benchmark-based evaluation"]
        B2["Judgment-based evaluation"]
    end
    subgraph G3 ["3 - Inference techniques"]
        direction TB
        C1["Advanced text generation and voting"]
        C2["Self-refinement"]
    end
    subgraph G4 ["4 - Training techniques"]
        direction TB
        D1["Reinforcement learning"]
        D2["Distillation"]
    end
    G1 --> G2 --> G3 --> G4

[!visual-conversion] Figure 2.1 — The four main stages of developing a reasoning model (printed p. 19, scan page-031.png). This chapter focuses on stage 1: loading a conventional LLM and implementing the text generation functionality. Stage 1 is boxed in the print and annotated “This chapter: LLM basics”. Print stage captions:

  • Stage 1: We start with a pretrained LLM as a base model that we’ll turn into a reasoning model (chapter 2).
  • Stage 2: Model evaluation techniques are essential for comparing the response qualities of the various methods and LLMs we are developing (chapter 3).
  • Stage 3: After the LLM and evaluation basics, we’ll explore reasoning-enhancing techniques that do not require training the LLM (chapters 4 and 5).
  • Stage 4: We’ll cover two main categories of training techniques to improve the reasoning capabilities of LLMs (chapters 6 to 8).

In addition to setting up the coding environment and loading a pretrained LLM, you will learn how to use a tokenizer to prepare text input for the model. As shown in figure 2.1, you will also implement a text generation function, enabling practical use of the LLM to generate text. This functionality will be used and improved on in later chapters.

2.1 Introducing LLMs for text generation

The LLM we’ll use in this chapter is a base model that has undergone only pretraining, but it will already be capable of generating coherent text and, in some cases, of following basic instructions. Figure 2.2 summarizes the components of an LLM text generation pipeline, and we’ll discuss and implement these steps in more detail later in this chapter.

NOTE By convention, diagrams involving neural networks such as LLMs are drawn and read vertically from bottom (inputs) to top (outputs). Arrows indicate the flow of information upward through the model.

graph BT
    I["User-provided input text:<br/>'Explain large language models.'"] --> P["Input preparation steps"]
    P --> L["LLM"]
    L --> O["Output processing steps"]
    O --> T["LLM-generated output text:<br/>'Large language models are advanced ...'"]

[!visual-conversion] Figure 2.2 — An overview of an LLM generating a response (output text) given a user query (input text) (printed p. 20, scan page-032.png). By convention, diagrams involving neural networks such as LLMs are drawn and read vertically from bottom (inputs) to top (outputs); arrows indicate the flow of information upward through the model. The print annotates the central box “A pretrained LLM that can follow basic instructions and generate text”.

Setting up the coding environment

pip install -r https://raw.githubusercontent.com/ rasbt/reasoning-from-scratch/refs/heads/main/requirements.txt

Python packages used in this chapter

If you prefer to install only the packages used in this chapter, you can start with the following command:

pip install torch>=2.10.0 tokenizers>=0.22.2 reasoning-from-scratch

PyTorch installation can be platform- and hardware-specific, especially if you want GPU acceleration. If the preceding command does not install the right build for your system, I recommend using the installation selector on the official PyTorch website (https://pytorch.org/get-started/locally/) and then installing the remaining packages separately:

  • torch refers to PyTorch, a widely used deep learning library that provides tools for building and training neural networks.
  • tokenizers is a library that provides efficient tokenization algorithms used to prepare input data for LLMs.
  • reasoning-from-scratch is a custom library that I developed for this book. It includes all the code examples used throughout the chapters, along with additional utility functions we will be using.

While pip is the canonical way to install Python packages, my preferred way to use Python is with the widely recommended uv Python package and project manager instead. Like many others, I now recommend uv because it is significantly faster and handles dependency resolution more reliably than pip. It also creates isolated environments automatically and comes with its own Python executable (but will use the system Python if a compatible version is already installed), so it’s a great option if you do not have Python installed on your system yet. Figure 2.3 outlines the four-step process, from installing uv to getting ready to execute the code in this chapter.

Figure 2.3 shows the installation and use of uv in a macOS terminal, but it’s also supported on Linux and Windows:

  1. To install uv, run the installer for your OS from the official website: https://docs.astral.sh/uv/getting-started/installation/.
  2. Next, clone the GitHub repo:

git clone —depth 1 https://github.com/rasbt/reasoning-from-scratch.git

Here, the —depth 1 option tells git to perform a shallow clone, which means it only downloads the latest version of the code without the full version history. This makes the download faster and uses less space.

$ curl -LsSf https://astral.sh/uv/install.sh | sh # 1. Install uv and
downloading uv 0.8.2 aarch64-apple-darwin # Python interpreter
no checksums to verify
installing to /Users/Author/.local/bin
uv
uvx
everything's installed!
$ git clone --depth 1 https://github.com/rasbt/reasoning-from-scratch.git
Cloning into 'reasoning-from-scratch'... # 2. Clone GitHub
remote: Enumerating objects: 100% (36/36), done. # repository
remote: Counting objects: 100% (36/36), done.
remote: Compressing objects: 100% (32/32), done.
remote: Total 36 (delta 6), reused 18 (delta 1), pack-reused 0 (from 0)
Receiving objects: 100% (36/36), 2.07 MiB | 4.35 MiB/s, done.
Resolving deltas: 100% (6/6), done.
$ cd reasoning-from-scratch # 3. Navigate into
$ uv run jupyter lab # cloned directory
Using CPython 3.13.5 interpreter at: /opt/homebrew/opt/[email protected]/bin/python3.13
Creating virtual environment at: .venv # 4. Starting a JupyterLab
Built reasoning-from-scratch @ file:///Users/Author/... # notebook environment will
Installed 116 packages in 447ms # install the necessary
[I 2025-07-23 19:01:30.714 ServerApp] jupyter_lab | extension was successfully linked.

[!visual-conversion] Figure 2.3 — Installing and using the uv Python package and project manager via the macOS terminal (printed p. 22, scan page-034.png). The print is a terminal screenshot; the session is transcribed above, with the four numbered callouts from the figure kept as trailing comments on the commands they point to.

If you don’t have git installed, you can manually download the source code repository from the publisher’s website or by opening this link in your browser: https:// github.com/rasbt/reasoning-from-scratch/archive/refs/heads/main.zip (unzip it after downloading).

3 In the terminal, navigate to the reasoning-from-scratch folder.

4 Inside the reasoning-from-scratch folder, execute

uv run jupyter lab

This command launches JupyterLab, where you can open a blank Jupyter notebook to type and run code, or you can open the chapter 2 notebook that contains all the code covered in this chapter. (You don’t need to create or activate a virtual environment first.)

Python script files can be executed via uv run script-name.py. This command also sets up a local virtual environment (usually inside an invisible .venv/ folder) and automatically installs all dependencies from the pyproject.toml file in the reasoning-from-scratch folder, so manually installing code dependencies via the requirements file is not needed. However, if you plan to install additional packages, you can use the following command:

uv add packagename

Understanding hardware needs and recommendations

The supplementary code repository contains additional installation instructions and details inside the ch02 subfolder if you need them.

2.3 Understanding hardware needs and recommendations

You may have heard that training LLMs is very expensive. For leading LLM companies, it is not uncommon to spend anywhere from $1–$10 million on the low end to more than $50 million on the high end in compute costs to train a new base-model LLM before adding any reasoning techniques.

For example, the DeepSeek V3 model, which serves as the base checkpoint for the DeepSeek R1 reasoning system, was trained on 2,048 NVIDIA H800 GPUs for about 11 weeks at an estimated cost of US$5.5 million. (DeepSeek V3 is one of the few recent models with a fully transparent compute disclosure.) According to the technical report, the final training run used 14.8 million GPU-hours of compute. The energy usage was roughly 620 MWh, about the amount of electricity an average American household uses in 55 years.

These resource requirements and the high price tag would make developing an LLM unfeasible for me and most readers. Instead, we will use a relatively small (but capable) pretrained LLM, on top of which we’ll implement reasoning techniques. This smaller LLM is a scaled-down version that otherwise follows the same architecture as contemporary state-of-the-art models. The reasoning methods that we’ll apply are the same as those used by larger LLMs. The difference is that the smaller LLM will let us explore these methods in a budget-friendly way.

As an analogy, imagine you are curious to learn how cars work. If you are new to cars, you probably wouldn’t start out building an expensive Ferrari right away. Instead, you would start with a more basic car, like a Volkswagen Beetle, which will still teach you a lot about how engines and transmissions work. In fact, I would even say that working on a simpler car would help you better understand how the engine and transmission work because it doesn’t have the complicated refinements of a more expensive car.

While we’ll use a relatively small model in this book, using, developing, and applying the reasoning techniques are still computationally intensive. The techniques in later chapters, such as chapters 5–8, will benefit from a GPU. You can check whether your computer has a PyTorch-supported GPU by running the following PyTorch code in Python:

import torch
print(f"PyTorch version {torch.__version__}")
if torch.cuda.is_available():
print(f"CUDA/ROCm GPU: {torch.cuda.get_device_name(0)}")
elif torch.xpu.is_available():
<!-- page: 036 (printed 24) -->
print(f"Intel GPU: {torch.xpu.get_device_name()}")
elif torch.backends.mps.is_available():
print("Apple Silicon GPU")
else:
print("Only CPU")

Depending on your machine, the code may return the following results:

PyTorch version 2.18.0 Only CPU

Don’t worry if your machine does not have a GPU to run the code. Chapters 2–5 can be run in a reasonable time on a CPU. For some chapters, the code will automatically use an NVIDIA GPU if one is available; otherwise, it will run on the CPU (or an Apple Silicon GPU if recommended for a particular section or chapter). I will provide more information in the relevant sections and chapters.

NOTE If you want GPU acceleration and are unsure which PyTorch build to install, use the official PyTorch install selector (https://pytorch.org/get-started) to choose the correct CPU, CUDA, or ROCm build for your system. For this book, any recent supported PyTorch CUDA build is fine.

Like many other AI researchers who work on and with LLMs daily, I don’t have a machine with the necessary GPU hardware to train LLMs at home, so I use cloud resources instead. If you are looking for cloud provider options, my personal preference is Lightning AI Studio (https://lightning.ai/) because of its ease of use and feature support, as shown in figure 2.4. Google Colab (https://colab.research.google.com/) is another good choice.

As of this writing, Lightning AI also offers users free compute credits after the sign-up and verification process, and these can be used for the different GPU choices shown in figure 2.4. (As I’ve mentioned, a GPU is not needed for this chapter, but if you want to use one, the L4 GPU is more than sufficient.)

NOTE For disclosure: I helped build and launch the Lightning AI platform in 2023, but I no longer have any financial interest in the company. I am not sponsored to recommend it, and I pay for it myself. I use it because I find it the most convenient option. It supports multiple types of GPUs, allows easy switching between them and back to CPU to save costs, and lets me pause or resume environments without redoing the setup.

The supplementary code repository contains additional GPU platform recommendations inside the ch02 subfolder.

+--------------------------------------------------------------------------+
| Lightning AI Studio [browser]|
+---------------+----------------------------------------------------------+
| file tree | editor / notebook pane | Choose GPU machine |
| | | ( ) CPU |
| [.py] [.ipynb] <- Supports both Python | (o) GPU <- Switches |
| | scripts and Jupyter | between CPU and GPU|
| | notebooks | |
| | | +--------------------+ |
| | | | T4 | 16 GB | |
| | | | L4 | 24 GB | |
| | | | A10G | 24 GB | |
| | | | A100 | 40 GB | |
| | | | H100 | 80 GB | |
| | | +--------------------+ |
| | | ^ Different GPU |
| | | choices |
+---------------+---------------------------------+-------------------------+
| Terminal access $ _ |
+--------------------------------------------------------------------------+

[!visual-conversion] Figure 2.4 — An overview of the Lightning AI GPU cloud platform in a web browser (printed p. 25, scan page-037.png). The interface supports Python scripts, Jupyter notebooks, and terminal access, and it lets users switch between CPU and various GPU types based on their compute needs. (Colors were inverted and the image was converted to grayscale for print reproduction.) Rendered here as a wireframe of the labelled regions rather than a raster crop; the four print callouts are retained inline. The individual GPU names and memory sizes in the selector are not legible at scan resolution — the rows above indicate the table’s position and shape, not verified values.

Using PyTorch

In this section, we imported and used the PyTorch library, which is currently the most widely used general-purpose library. We will use it throughout this book to run and train LLMs, including the reasoning methods we will develop. If you are new to PyTorch, I recommend reading my “PyTorch in One Hour: From Tensors to Training Neural Networks on Multiple GPUs” tutorial to get the most out of this book. It is freely available on my website at https://sebastianraschka.com/teaching/pytorch-1h.

Let’s now explore how we can use a tokenizer to process input and output text for an LLM. Tokenizers are essential because every prompt, reasoning trace, and generated answer ultimately has to be represented as token IDs before the model can process them. Figure 2.5 provides a more detailed view of the input and output preparation steps shown earlier in figure 2.2 .

graph BT
    I["User-provided input text:<br/>'Explain large language models.'"] --> T1["Tokenized text:<br/>Ex | plain | large | language | models | ..."]
    T1 --> ID1["Input token IDs:<br/>840 | 20772 | 3460 | 4128 | 4119 | 13"]
    ID1 --> L["LLM"]
    L --> ID2["Output token IDs:<br/>20286 | 4128 | 4119 | 525 | 10847 | ..."]
    ID2 --> T2["Tokenized text:<br/>Large | language | models | are | advanced | ..."]
    T2 --> O["LLM-generated text:<br/>'Large language models are advanced ...'"]

[!visual-conversion] Figure 2.5 — A simplified illustration of how an LLM receives input data and generates output (printed p. 26, scan page-038.png). The user-provided text is tokenized into token IDs using the tokenizer’s encode method, which are then processed by the LLM to generate output token IDs. These are decoded back into human-readable text using the tokenizer’s decode method. Print annotations: Input preparation — use the tokenizer’s encode method to convert text into token IDs; Output preparation — use the tokenizer’s decode method to convert token IDs into text; and, at the model, “Given a sequence of input token IDs, the LLM generates a response as a series of output token IDs.”

To see how this works in practice, we’ll begin by loading a tokenizer from this book’s reasoning-from-scratch Python package (installed in section 2.2). To download the tokenizer files (corresponding to the Qwen3 0.6B base LLM), run this command:

from reasoning_from_scratch.qwen3 import download_qwen3_small
download_qwen3_small(kind="base", tokenizer_only=True, out_dir="qwen3")

This will display a progress bar:

tokenizer-base.json: 100% (6 MiB / 6 MiB)

The command downloads the tokenizer-base.json file (approximately 6 MB in size) and saves it in a qwen3 subdirectory.

Now we can load the tokenizer settings from the tokenizer file into Qwen3Tokenizer:

from pathlib import Path
from reasoning_from_scratch.qwen3 import Qwen3Tokenizer
tokenizer_path = Path("qwen3") / "tokenizer-base.json"
tokenizer = Qwen3Tokenizer(tokenizer_file_path=tokenizer_path)

Since we have not loaded the LLM yet (the central component in figure 2.5), we will start with a simpler dry run using just the tokenizer. Specifically, we will do a tokenization round trip: encode a text into token IDs and then decode those IDs back to text, as illustrated in figure 2.6.

graph BT
    I["User-provided input text:<br/>'Explain large language models.'"] --> T1["Tokenized text:<br/>Ex | plain | large | language | models | ..."]
    T1 --> ID["Input token IDs:<br/>840 | 20772 | 3460 | 4128 | 4119 | 13"]
    ID --> T2["Tokenized text:<br/>Ex | plain | large | language | models | ..."]
    T2 --> O["User-provided input text:<br/>'Explain large language models.'"]

[!visual-conversion] Figure 2.6 — The round-trip tokenization process using a tokenizer (printed p. 27, scan page-039.png). The user-provided input text is first converted into token IDs using the encode method and then reconstructed into the original text using the decode method. Print annotations: the lower half is labelled “Use the tokenizer’s encode method to convert text into token IDs”, the upper half “Use the tokenizer’s decode method to convert token IDs into text”, and the topmost box “Regenerate the original input from token IDs”.

The following code snippet implements the encoding process shown at the bottom of figure 2.6:

prompt = "Explain large language models." input_token_ids_list = tokenizer.encode(prompt)

The following code implements the decoding process, converting the token IDs back into text, shown at the top of figure 2.6:

text = tokenizer.decode(input_token_ids_list) print(text)

Based on the following printed result, we can see that the tokenizer reconstructed the original input prompt from the token IDs:

‘Explain large language models.’

Before we move on to the LLM, let’s take a look at the token IDs generated by the encode method. The following code prints each token ID and its corresponding decoded string to illustrate how the tokenizer works:

for i in input_token_ids_list:
print(f"{i} --> {tokenizer.decode([i])}")

The output is as follows:

840 --> Ex
20772 --> plain
3460 --> large
4128 --> language
4119 --> models
13 --> .

As you can see in the output, the original text is split into six token IDs. Each token represents a word or subword, depending on how the tokenizer segments the input.

For example, “Explain” was split into two separate tokens, “Ex” and “plain.” This is because the tokenizer algorithm uses a subword-based method called byte pair encoding (BPE). BPE can represent both common and rare words using a mix of full words and subword units. Spaces are also often included in tokens (for example, “large”), which helps the LLM detect word boundaries.

The Qwen3Tokenizer has a vocabulary of about 151,000 tokens, which is relatively large as of this writing (for comparison, early GPT-2 has a vocabulary of approximately 50,000 tokens, and Llama 3 has a vocabulary of approximately 128,000 tokens).

A larger vocabulary in a language model increases the model’s size because the embedding and output layers must store more token representations. It can also increase the per-token compute cost of producing next-token probabilities. A larger vocabulary also allows more words to be represented as single tokens rather than being split into subword components, which can reduce sequence length. For example, splitting a word like “Explain” into “Ex” and “plain” results in more input tokens. More tokens lead to longer input sequences, which increases processing time and resource usage. The tradeoff is between a larger vocabulary with a somewhat higher per-token cost and a smaller vocabulary that often produces longer token sequences. For instance, doubling the number of tokens in a sequence can roughly double the computational cost of running the model, since the model has to process and generate more tokens overall.

Unfortunately, the details of tokenizers and their implementations are outside the scope of this book. If you’re interested, you can find additional resources, including my from-scratch implementation, in appendix A.

Exercise 2.1: Encoding unknown words Experiment with the tokenizer to see if and how it handles unknown words. To do this, get creative and make up words that don’t exist. Also, if you speak multiple languages, try to encode words in a language other than English.

In the previous section, we loaded and familiarized ourselves with the tokenizer, which prepares the input data for an LLM and converts LLM outputs back into human-readable text. In this section, we’ll load the LLM itself with its pretrained weights, as shown in figure 2.7. Once this base model is in place, the following chapters will build directly on it by evaluating it, prompting it in different ways, and eventually training it into a stronger reasoning model.

graph LR
    subgraph G1 ["1 - Conventional LLM"]
        direction TB
        A1["Loading pretrained weights"]
        A2["Text generation"]
    end
    subgraph G2 ["2 - Evaluation"]
        direction TB
        B1["Benchmark-based evaluation"]
        B2["Judgment-based evaluation"]
    end
    subgraph G3 ["3 - Inference techniques"]
        direction TB
        C1["Advanced text generation and voting"]
        C2["Self-refinement"]
    end
    subgraph G4 ["4 - Training techniques"]
        direction TB
        D1["Reinforcement learning"]
        D2["Distillation"]
    end
    G1 --> G2 --> G3 --> G4

[!visual-conversion] Figure 2.7 — An overview of the four key stages in developing a reasoning model in this book (printed p. 29, scan page-041.png). This section focuses on loading a pretrained LLM in stage 1; in the print, the “Loading pretrained weights” substep is highlighted and marked “This section”. Print stage headings: Stage 1: LLM basics (chapter 2) · Stage 2: Measuring performance (chapter 3) · Stage 3: Reasoning without training (chapters 4 and 5) · Stage 4: Reasoning with training (chapters 6 to 8).

This book uses Qwen3 0.6B as its pretrained base model. The “0.6B” in the name indicates that the model contains approximately 0.6 billion weight parameters.

Why use Qwen3? After carefully evaluating several open-weight base models, I chose Qwen3 0.6B for the following reasons:

  • For this book, we want a small yet capable open-weight model (open-weight models are models whose trained weights are publicly downloadable) that can run on consumer hardware.

  • Qwen3 offers both a base model (the focus of our reasoning model development) and an official reasoning variant that we can use as a reference for evaluation purposes.

NOTE The canonical spelling of “Qwen3” does not include whitespace, whereas, for example, “Llama 3” does.

In the spirit of building things “from scratch,” this book uses a custom reimplementation of Qwen3 that I wrote in pure PyTorch and that is entirely independent of external LLM libraries. The emphasis of this reimplementation is on code readability and tweakability in case you want to modify it later for your own experiments. Despite being built from scratch, this implementation remains fully compatible with the original pretrained Qwen3 model weights.

This book does not cover the Qwen3 code implementation in depth. That topic alone would fill a separate book, similar to my Build a Large Language Model (From Scratch) book. Instead, this book focuses on implementing reasoning methods on top of a base model, in this case, Qwen3. If you’re interested in more details about Qwen3 and the model code, see appendix C.

NOTE This reimplemented Qwen3 LLM runs entirely locally, just like any other neural network implemented in PyTorch. There are no server-side components or external API calls involved. All model usage happens on your own machine, and your data stays on your device. If you are concerned about privacy, the setup we are using ensures full control over both the LLM inputs and outputs.

Before we load the model, we can specify the device we are going to use, namely, a CPU or GPU. The code in the following listing automatically selects the best available device.

Listing 2.1 Get the device automatically

def get_device(enable_tensor_cores=True):
if torch.cuda.is_available():
device = torch.device("cuda")
print("Using NVIDIA CUDA GPU")
if enable_tensor_cores:
major, minor = map(int, torch.__version__.split(".")[:2])
if (major, minor) >= (2, 9):
torch.backends.cuda.matmul.fp32_precision = "tf32"
torch.backends.cudnn.conv.fp32_precision = "tf32"
else:
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
elif torch.backends.mps.is_available():
device = torch.device("mps")
print("Using Apple Silicon GPU (MPS)")
elif torch.xpu.is_available():
device = torch.device("xpu")
print("Using Intel GPU")
else:
<!-- page: 043 (printed 31) -->
device = torch.device("cpu")
print("Using CPU")
return device

Note that if you have a modern NVIDIA GPU (based on the Ampere architecture or newer), the get_device() function automatically enables Tensor Cores for faster matrix multiplications when enable_tensor_cores=True. This can slightly change floating-point rounding, but it does not noticeably affect results in this book, and the speed advantage on newer cards is worth it. On non-NVIDIA devices, these settings are ignored.

Using the code from listing 2.1, we can obtain the device as follows:

device = get_device()

While GPUs generally provide substantial speed and performance gains, it can be helpful to run the remaining code in this chapter on the CPU for compatibility and debugging. You can temporarily override the automatic selection by explicitly setting the device:

device = torch.device("cpu")

After you’ve finished the chapter and verified that the code works properly on the CPU, you can remove or comment out the manual override and rerun the code. If your system has a GPU, you should then see better performance.

NOTE The code in the remainder of this chapter was executed on a Mac Mini with an Apple M4 CPU. Performance comparisons with the Apple Silicon M4 GPU and the NVIDIA H100 GPU are included at the end of the chapter.

Before we load the model and put it onto the selected device, we first need to download the weights for Qwen3 0.6B. These files are required to initialize the pretrained model correctly. In the previous section, we called the download_qwen3_small() function with tokenizer_only=True to download only the tokenizer files. Here, we’ll use the same function but set tokenizer_only=False so that the model weights are downloaded as well:

download_qwen3_small(kind="base", tokenizer_only=False, out_dir="qwen3")

The output is as follows:

qwen3-0.6B-base.pth: 100% (1433 MiB / 1433 MiB)
✓ qwen3/tokenizer-base.json already up-to-date

(There is a checkmark next to the tokenizer because we already downloaded it in the previous section.)

Now that we’ve downloaded the model weights, we can instantiate a Qwen3Model class and load the pretrained weights via PyTorch’s load_state_dict method:

from reasoning_from_scratch.qwen3 import Qwen3Model, QWEN_CONFIG_06_B
model_path = Path("qwen3") / "qwen3-0.6B-base.pth"
model = Qwen3Model(QWEN_CONFIG_06_B)
model.load_state_dict(torch.load(model_path))
model.to(device)

Instantiate a Qwen3 model with random weights as placeholders. Load the pretrained weights into the model. Transfer the model to the designated device (e.g., “cuda”).

Note that if the device setting is “cpu”, the model.to(device) operation is skipped because the model already resides in CPU memory by default.

After executing the preceding code, you should see the following output. (If you are not running the code in an interactive environment like a Jupyter notebook, you will have to run print(model) to see the output.)

Qwen3Model( (tok_emb): Embedding(151936, 1024) (trf_blocks): ModuleList( (0-27): 28 x TransformerBlock( (att): GroupedQueryAttention( (W_query): Linear(in_features=1024, out_features=2048, bias=False) (W_key): Linear(in_features=1024, out_features=1024, bias=False) (W_value): Linear(in_features=1024, out_features=1024, bias=False) (out_proj): Linear(in_features=2048, out_features=1024, bias=False) (q_norm): RMSNorm() (k_norm): RMSNorm() ) (ff): FeedForward( (fc1): Linear(in_features=1024, out_features=3072, bias=False) (fc2): Linear(in_features=1024, out_features=3072, bias=False) (fc3): Linear(in_features=3072, out_features=1024, bias=False) ) (norm1): RMSNorm() (norm2): RMSNorm() ) (final_norm): RMSNorm() (out_head): Linear(in_features=1024, out_features=151936, bias=False) )

This output is a summary of the Qwen3 0.6B base model architecture, as printed by PyTorch. It highlights the model’s core components: an embedding layer, a stack of 28 transformer blocks, and a final linear projection head. Each transformer block includes a grouped-query attention mechanism and a multilayer feed-forward network, along with normalization layers throughout.

These components are also illustrated in figure 2.8 for readers familiar with LLM architectures, but a detailed understanding of this architecture is not required for this

"Large language models are advanced ..."
^
[ Output processing steps ]
^
[ Linear output layer ]
^
[ Final RMSNorm ]
^
.--------------------------- (+) <------------------.
| ^ |
| [ Feed forward ] | Feed forward is a mini
| ^ | neural network composed of
| [ RMSNorm 2 ] | linear layer and nonlinear
| ^ | activation functions.
'--------------------------- | ---------------------'
|
.--------------------------- (+) <------------------.
| ^ |
| Q/K RMSNorm --> [ Grouped-query attention ] | Additional normalization
| ^ |
| [ RMSNorm 1 ] | A type of data
'--------------------------- | ---------------------' normalization layer
| ( x 28 -- this block is
| repeated 28 times )
[ Token embedding layer ]
^
[ Tokenized text ]
^
"Explain large language models."

[!visual-conversion] Figure 2.8 — Overview of the Qwen3 0.6B model architecture, as instantiated earlier (printed p. 33, scan page-045.png). Input text is tokenized and passed through an embedding layer, followed by 28 repeated transformer blocks. Each block contains grouped-query attention, feed-forward layers, and RMS normalization. The model ends with a final normalization and linear output layer. Arrows show the data flow through the model; (+) marks the residual additions.

book. Since we are not modifying the base model itself, but rather building reasoning methods on top of it, you can safely treat the architecture as a black box for now. If you’re interested, you can find more information on these components, such as RMSNorm, in appendix C.

We have now loaded a pretrained model that should be capable of generating coherent text. In the next section, we’ll code a text generation function that feeds tokenized data into the model and returns the output in a human-readable format.

2.6 Understanding the sequential LLM text generation process

Section titled “2.6 Understanding the sequential LLM text generation process”

Now that we’ve loaded the pretrained LLM, our goal is to write a function that uses the LLM to generate text. This function will form the foundation for reasoning-improving methods that we’ll implement later in the book, as shown in figure 2.9.

graph LR
    subgraph G1 ["1 - Conventional LLM"]
        direction TB
        A1["Loading pretrained weights"]
        A2["Text generation"]
    end
    subgraph G2 ["2 - Evaluation"]
        direction TB
        B1["Benchmark-based evaluation"]
        B2["Judgment-based evaluation"]
    end
    subgraph G3 ["3 - Inference techniques"]
        direction TB
        C1["Advanced text generation and voting"]
        C2["Self-refinement"]
    end
    subgraph G4 ["4 - Training techniques"]
        direction TB
        D1["Reinforcement learning"]
        D2["Distillation"]
    end
    G1 --> G2 --> G3 --> G4

[!visual-conversion] Figure 2.9 — An overview of the four key stages in developing a reasoning model in this book (printed p. 34, scan page-046.png). This section explains the main concept behind text generation in LLMs, which will enable us to implement a text generation function that uses the pretrained LLM. In the print the “Text generation” substep is highlighted and annotated “In this section, we go over the main concepts behind how text generation works”. Print stage headings: Stage 1: LLM basics (chapter 2) · Stage 2: Measuring performance (chapter 3) · Stage 3: Reasoning without training (chapters 4 and 5) · Stage 4: Reasoning with training (chapters 6 to 8).

You may already know that text generation in LLMs is a sequential process in which LLMs generate one word (or token) at a time. This is often also called autoregressive text generation. Figure 2.10 presents a broad overview, with one generated output token (in the top row) shown at each step as it is fed an input prompt.

Chatbot interfaces

A chat interface simply wraps the underlying next-token prediction process (shown in figure 2.10) in a conversational loop. The chatbot model still predicts one token at a time, but the system feeds the entire dialogue history back into the model so that each new reply feels context aware and coherent from turn to turn. This book focuses on single-turn conversations, where the current answer is independent of previous answers. If you’re interested, you can find an implementation of a chat interface with answer history in appendix G.

IterationInput to the LLMNext output token
1“Explain large language models.”“Large”
2“Explain large language models. Large”“language”
3“Explain large language models. Large language”“models”
4“Explain large language models. Large language models”“are”
………

[!visual-conversion] Figure 2.10 — Sequential (autoregressive) text generation in LLMs (printed p. 35, scan page-047.png). At each iteration, the model generates the next token based on the input and previously generated tokens, which are cumulatively fed back into the model to produce coherent output. Drawn in print as four “LLM iteration N” boxes in a row, each with its input below and its newly generated token above; rendered here as a table because the figure is a step-by-step trace. Print annotations: (1) the user-provided text input, (2) the next output token generated by the model, (3) the output token is added to the input of the previous round.

If we zoom in on one of figure 2.10’s iterations, we can see that the LLM processes the full input sequence in one forward pass and produces one prediction for each input position. This means that if we have six input tokens, the model returns six corresponding predictions, as illustrated in figure 2.11. The figure makes the position-by-position structure easy to see, but model outputs are not, in general, just the input prompt shifted by one position. Rather, each position produces a distribution over possible next tokens. For text generation, we only use the prediction at the last position, because that’s the one that tells us which new token to append next.

Before we implement a text generation function that uses the concept shown in figure 2.11 in each iteration of the autoregressive text generation process, let’s look at a

graph BT
    P["User-provided prompt:<br/>'Explain large language models.'"] --> IN
    subgraph IN ["LLM inputs"]
        direction LR
        I1["Ex<br/>840"]
        I2["plain<br/>20772"]
        I3["large<br/>3460"]
        I4["language<br/>4128"]
        I5["models<br/>4119"]
        I6[".<br/>13"]
    end
    IN --> L["LLM iteration 1"]
    L --> OUT
    subgraph OUT ["LLM outputs - one prediction per input position"]
        direction LR
        O1["gram<br/>20772<br/>(discarded)"]
        O2["...<br/>(discarded)"]
        O3["...<br/>(discarded)"]
        O4["...<br/>(discarded)"]
        O5["...<br/>(discarded)"]
        O6["Large<br/>20286<br/>KEPT"]
    end

[!visual-conversion] Figure 2.11 — The LLM processes the full input sequence and produces one next-token prediction per input position (printed p. 36, scan page-048.png). These predictions are conceptually shifted one step ahead because each position predicts the following token. The illustration is position aligned for intuition, but the outputs are not literally the input prompt shifted by one position. During generation, we keep only the final prediction and use it to continue the input prompt one token at a time. Print annotations: “Intermediate values we discard” on the leading output positions and “New generated token” on the last.

code example that further illustrates figure 2.11. We’ll reuse the “Explain large language models.” prompt from section 2.4:

prompt = "Explain large language models."
input_token_ids_list = tokenizer.encode(prompt)
print(f"Number of input tokens: {len(input_token_ids_list)}")
input_tensor = torch.tensor(input_token_ids_list)
input_tensor_fmt = input_tensor.unsqueeze(0)
input_tensor_fmt = input_tensor_fmt.to(device)
with torch.inference_mode():
output_tensor = model(input_tensor_fmt)
output_tensor_fmt = output_tensor.squeeze(0)
print(f"Formatted Output tensor shape: {output_tensor_fmt.shape}")

The preceding code produces the following output:

Number of input tokens: 6 Formatted Output tensor shape: torch.Size([6, 151936])

As we can see, we feed six input tokens into the model, which returns a 6×151,936-dimensional matrix. The 6 in this matrix corresponds to the six input tokens. The second dimension, 151,936, corresponds to the vocabulary size that the model supports. For instance, each of the six tokens is represented by a vector with 151,936 values. We can think of the values in these vectors as scores for each possible word in the vocabulary, where the highest score corresponds to the most likely word or subword (in the 151,936-entry vocabulary) to be chosen as the generated token.

Squeezing and unsqueezing tensors

Tensors are generalized matrices of nn dimensions. Many PyTorch functions and model components expect tensors with specific dimensions, so being able to add or remove dimensions is important for making data compatible with these operations.

The .squeeze() and .unsqueeze() operations in PyTorch are used to change the shape of a tensor by removing or adding dimensions of size 1. This is often useful for reshaping a tensor to match what a model expects. For example, a model might expect input tensors with two dimensions (e.g., rows and columns) so it can process batches of inputs (see appendix E). But if the input is just a row vector, we can use .unsqueeze(0) to add an extra dimension and make it compatible:

example = torch.tensor([1, 2, 3])
print(example)
print(example.unsqueeze(0))

This returns the following:

tensor([1, 2, 3])
tensor([[1, 2, 3]])

Here, .unsqueeze(0) adds a new dimension at position 0, turning a 1D tensor into a 2D tensor with shape (1, 3). Conversely, .squeeze(0) removes a dimension of size 1 from position 0:

example = torch.tensor([[1, 2, 3]])
print(example)
print(example.squeeze(0))

This returns the following:

tensor([[1, 2, 3]])
tensor([1, 2, 3])

This is useful when you want to remove extra dimensions that are not needed.

To get the next generated word, we extract the last row of this 6×151,936-dimensional matrix, find the token ID corresponding to the largest score value in this row, and convert this token ID back into text via the tokenizer, as illustrated in figure 2.12.

Column index positions → [0] [1] [2] [20286] [151933] [151934] [151935]

tensor([[ 7.4062, 11.4375, 9.2500, ..., 8.5000, ..., 3.7188, 3.7188, 3.7188],
[ 9.5000, 10.6250, 7.3125, ..., 8.9375, ..., 3.2031, 3.2031, 3.2031],
[10.8750, 10.0625, 7.5000, ..., 7.7188, ..., 0.1299, 0.1299, 0.1299],
[ 7.1875, 9.2500, 6.2188, ..., 5.3125, ..., -2.0469, -2.0469, -2.0469],
[11.5625, 13.6250, 10.2500, ..., 1.0469, ..., 11.6875, 1.0469, 1.0469],
[ 7.3750, 2.0312, 8.0000, ..., 20.5000, ..., -2.5469, -2.5469, -2.5469]],

6×151,936-dimensional LLM output matrix

  1. Extract the last row (corresponds to the last token). → (output_tensor_fmt[-1])

The largest value in this row (vector)

  1. Find the index position of the largest value. → (torch.argmax())

  2. The index position coincides with the token ID, which we can convert back into text. → (tokenizer.decode()) → “Large”

Figure 2.12 A closer look at how the raw scores output by an LLM, in a single text generation iteration, are converted into a token ID and its corresponding text representation.

Let’s see how we can convert the LLM output matrix into the generated text token (shown in figure 2.12) in code.

Note that for text generation we run the model in inference mode rather than training mode, so PyTorch does not need to track gradients. As shown in figure 2.11, the earlier positions correspond to predictions for tokens that are already inside the prompt. Only the last position predicts the next unseen token that we want to append, which we can obtain via the [-1] index:

last_token = output_tensor_fmt[-1] print(last_token)

Using torch.inference_mode() in the previous step avoids storing gradient information that we do not need during generation. This reduces memory usage and usually improves speed.

This prints the 151,936 values corresponding to the last token:

tensor([ 7.3750, 2.0312, 8.0000, …, -2.5469, -2.5469, -2.5469], dtype=torch.bfloat16)

The dtype=torch.bfloat16 suffix indicates that these scores are stored in bfloat16, a reduced-precision format commonly used to lower memory usage and improve efficiency in LLM inference. Depending on your hardware and settings, you may instead see a different dtype.

Then, we can use the argmax function to obtain the position with the largest value score (value) in this tensor:

print(torch.argmax(last_token, dim=-1, keepdim=True))

The result is

tensor([20286])

This returned integer value is the position of the largest value in this vector, and it also corresponds to the token ID of the generated token (last_token), which we can translate back into text via the tokenizer:

print(tokenizer.decode([20286]))

This prints the generated token:

Large

max vs. argmax

It is helpful to briefly recall how max and argmax work and how they differ, since we will use torch.argmax() later when we select the next token when implementing the text generation function. In this chapter, using argmax corresponds to greedy decoding, where we always pick the single highest-scoring next token. We will discuss alternatives to this later in the book.

The torch.max() function returns the largest value in a tensor, whereas torch.argmax() returns the index of that value. For example:

example = torch.tensor([-2, 1, 3, 1])
print(torch.max(example))
print(torch.argmax(example))

This returns:

tensor(3) tensor(2)

The maximum value is 3, and it first appears at index 2.

We can also use keepdim=True with torch.argmax() to keep the output shape consistent by retaining the reduced dimension:

print(torch.argmax(example, keepdim=True))

(continued) This returns: tensor([2])

Here, keepdim=True keeps the result as a 1D tensor with the same number of dimensions as the input, which can be helpful for keeping the shape required by the tokenizer and for concatenation later on in our text generation function.

To recap, figure 2.10 illustrated the iterative (autoregressive) text generation process in an LLM. Then, figure 2.11 zooms in on one of the iterations in this process. Figure 2.12 then further zooms in on this one iteration and shows how the score matrix (output by an LLM), gets converted into a token ID (and its corresponding text representation).

While we have seen how to use the LLM to generate a single token, in the next section, we will put these concepts into action and implement a function that applies this concept sequentially to generate coherent output text.

2.7 Coding a minimal text generation function

Section titled “2.7 Coding a minimal text generation function”

The previous section explained a single iteration in the basic, sequential text generation process in LLMs. In this section, building on that concept, we will implement a text generation function that uses the pretrained LLM to generate coherent text following a user prompt, as illustrated in figure 2.13 in the chapter overview.

graph LR
    subgraph G1 ["1 - Conventional LLM"]
        direction TB
        A1["Loading pretrained weights"]
        A2["Text generation"]
    end
    subgraph G2 ["2 - Evaluation"]
        direction TB
        B1["Benchmark-based evaluation"]
        B2["Judgment-based evaluation"]
    end
    subgraph G3 ["3 - Inference techniques"]
        direction TB
        C1["Advanced text generation and voting"]
        C2["Self-refinement"]
    end
    subgraph G4 ["4 - Training techniques"]
        direction TB
        D1["Reinforcement learning"]
        D2["Distillation"]
    end
    G1 --> G2 --> G3 --> G4

[!visual-conversion] Figure 2.13 — An overview of the four key stages in developing a reasoning model in this book (printed p. 40, scan page-052.png). In this section, we implement a text generation function for the pretrained LLM. The print highlights the “Text generation” substep and carries two callouts: “We have discussed how text generation works; now, we’ll code a simple text generation function in this section” and “We’ll extend the capabilities of the simple text generation function later in chapter 4”. Print stage headings: Stage 1: LLM basics (chapter 2) · Stage 2: Measuring performance (chapter 3) · Stage 3: Reasoning without training (chapters 4 and 5) · Stage 4: Reasoning with training (chapters 6 to 8).

This text generation function, mentioned in figure 2.13, works by first converting the input prompt into token IDs that the model can process. The model then predicts the next most likely token, appends it to the sequence, and reprocesses the extended sequence to generate the next token. This iterative process continues until a stopping condition is met, and the generated token IDs are then decoded back into text.

Figure 2.14 shows this process step by step, with both the generated token IDs and their corresponding text at each stage. (This figure is similar to figure 2.10 shown at the beginning of the previous section, except figure 2.14 also shows the generated token IDs below their text representation.)

IterationInput token IDsInput textNext tokenToken ID
1[840, 20772, 3460, 4128, 4119, 13]“Explain large language models.”Large[20286]
2[840, 20772, 3460, 4128, 4119, 13, 20286]“Explain large language models. Large”language[4128]
3[840, 20772, 3460, 4128, 4119, 13, 20286, 4128]“Explain large language models. Large language”models[4119]
4[840, 20772, 3460, 4128, 4119, 13, 20286, 4128, 4119]“Explain large language models. Large language models”are[525]
……………

[!visual-conversion] Figure 2.14 — An illustration of sequential (autoregressive) text generation in large language models (LLMs), with token IDs shown explicitly (printed p. 41, scan page-053.png). At each iteration, the model generates the next token based on the original input and all previously generated tokens. The predicted token is added to the sequence in both its textual and token ID form. Similar to figure 2.10, except that this figure also shows the generated token IDs below their text representation. Print annotations: (1) the user-provided text input, (2) the next output token generated by the model, (3) the output token is added to the input of the previous round, plus “Text representation of the generated output token” and “Token ID of the generated output token”.

The generate_text_basic_stream function in listing 2.2 implements the sequential text generation process (figure 2.14) using the argmax function introduced in the previous section.

Listing 2.2 A basic text generation function

@torch.inference_mode() # Disable gradient tracking for speed and memory efficiency.
def generate_text_basic_stream(
<!-- page: 054 (printed 42) -->
model, token_ids, max_new_tokens, eos_token_id=None
):
model.eval() # Switch model to evaluation mode to enable deterministic behavior.
for _ in range(max_new_tokens):
out = model(token_ids)[:, -1]
next_token = torch.argmax(out, dim=-1, keepdim=True) # Get the scores of the last token.
if (eos_token_id is not None
and torch.all(next_token == eos_token_id)):
break # Stop if all sequences in the batch have generated EOS.
yield next_token # Yield each token as soon as it's generated.
token_ids = torch.cat([token_ids, next_token], dim=1) # Append the newly predicted token.

In essence, the generate_text_basic_stream function in listing 2.2 applies the argmax-based token ID extraction via a for loop for a user-specified number of iterations (max_new_tokens). It returns the generated token IDs, similar to what’s shown in Figure 2.14, which we can then convert back into text.

Let’s use the function to generate a 100-token response to a simple “Explain large language models in a single sentence.” prompt to make sure that the Qwen3Model and generate_text_basic_stream function work (we get to the reasoning task examples in later chapters).

Please note that the following code will be slow and can take 1–3 minutes to complete, depending on your computer (we will speed it up in later sections):

prompt = "Explain large language models in a single sentence."
input_token_ids_tensor = torch.tensor(
tokenizer.encode(prompt),
device=device
).unsqueeze(0) # Transfer the input token IDs onto the same device (CPU, GPU) where the model is located.
max_new_tokens = 100 # Let the model generate up to 100 new tokens.
for token in generate_text_basic_stream(
model=model,
token_ids=input_token_ids_tensor,
max_new_tokens=max_new_tokens,
):
token_id = token.squeeze(0).tolist() # Convert output token IDs from PyTorch tensor to Python list.
print(
tokenizer.decode(token_id),
end="",
flush=True, # Deactivates buffering so tokens are printed live
)

The generated output text is as follows:

Large language models are artificial intelligence systems that can understand, generate, and process human language, enabling them to perform a wide range of tasks, from answering questions to writing articles, and even creating creative content.<|endoftext|>Human language is a complex and dynamic system that has evolved over millions of years to enable effective communication and social interaction. It is composed of a vast array of symbols, including letters, numbers, and words, which are used to convey meaning and express thoughts and ideas. The evolution of language has

Note that the output was generated on a CPU. Depending on the device (e.g., CPU versus GPU), the exact wording may vary slightly due to differences in floating-point behavior on different hardware.

As we can see based on the output, the model follows the instruction quite well by producing a single, clear sentence in response to the prompt. It continues generating additional, off-topic text after the special token <|endoftext|>. This token is used during training to mark the end of a document and separate different samples.

TIP The leading whitespace in " Large" (the first output word) is expected because many tokenizers encode words with a preceding space when they follow earlier text. In listing 2.2, tokens are streamed one by one, following the input text, so this leading space appears naturally in the first emitted token. If we want a cleaner output, we can call .lstrip() on the first token or the final assembled string.

When using the model for inference (generating text after training), we typically want it to stop as soon as it produces the special token <|endoftext|>. This token is represented by the ID 151643, which we can confirm using

print(tokenizer.encode("<|endoftext|>"))
tokenizer.decode(token_id), end="", flush=True )

The output looks like this:

Large language models are artificial intelligence systems that can understand, generate, and process human language, enabling them to perform a wide range of tasks, from answering questions to writing articles, and even creating creative content.

If we compare this response to the previous response, we can see that the text generation stopped once the end-of-sequence token was encountered.

You may have noticed that generating the response is relatively slow and might take several seconds up to multiple minutes, depending on the hardware. Before we wrap up and learn how to speed up this function substantially, let’s implement a simple utility function in the next listing that measures the runtime of the text generation process.

Listing 2.3 Token generation speed and memory usage

import warnings
def generate_stats(output_token_ids, tokenizer, start_time, end_time):
total_time = end_time - start_time
print(f"\n\nTime: {total_time:.2f} sec")
print(f"{int(output_token_ids.numel()) / total_time} tokens/sec")
for name, backend in (("CUDA", getattr(torch, "cuda", None)),
("XPU", getattr(torch, "xpu", None))):
if backend is not None and backend.is_available():
device_type = output_token_ids.device.type
if device_type != name.lower():
warnings.warn(
f"{name} is available but tensors are on "
f"{device_type}. Memory stats may be 0."
)
backend.synchronize()
max_mem_bytes = backend.max_memory_allocated()
max_mem_gb = max_mem_bytes / (1024 ** 3)
print(f"Max {name} memory allocated: {max_mem_gb:.2f} GB")

The generate_stats function in listing 2.3 will calculate the total runtime, given a start and end timestamp, the generation speed in terms of tokens per second (tokens/sec), and the GPU memory used. Note that the GPU memory usage is currently only computed for CUDA-supported GPUs (and some newer Intel GPUs via XPU), as PyTorch lacks similar utility functions for CPUs and Apple Silicon GPUs.

To apply the generate_stats function, we obtain a start_time and end_time stamp immediately before and after running the generate_text_basic_stream function via Python’s time module:

import time
start_time = time.time()
generated_ids = []
for token in generate_text_basic_stream(
model=model,
token_ids=input_token_ids_tensor,
max_new_tokens=max_new_tokens,
eos_token_id=tokenizer.eos_token_id
):
token_id = token.squeeze(0).tolist()
print(
tokenizer.decode(token_id),
end="",
flush=True
)
next_token_id = token.squeeze(0)
generated_ids.append(next_token_id) # Collect generated tokens.
end_time = time.time()
output_token_ids_tensor = torch.cat(generated_ids, dim=0)
generate_stats(output_token_ids_tensor, tokenizer, start_time, end_time)

The output, on a Mac Mini M4 CPU, is as follows:

Time: 7.94 sec 5 tokens/sec Large language models are artificial intelligence systems that can understand, generate, and process human language, enabling them to perform a wide range of tasks, from answering questions to writing articles, and even creating creative content.

At five tokens per second, the generation speed is relatively slow. In the next section, we will implement a caching technique that speeds up the generation process 5–6 fold.

Text generation and inference terminology

When reading LLM literature or software documentation, you will often see the term inference used where you might expect text generation. In a neural network context, inference means something very specific, namely, taking a model whose parameters are already learned and fixed, running a forward pass, and producing a prediction (for example, generating the next token). Nothing is being estimated or learned during this stage. In the forward pass, we are simply applying a function.

(continued)

This is different from inference in statistics, where the goal is to learn unknown information from data. Statistical inference involves estimating parameters, quantifying uncertainty, or testing hypotheses about a population or data-generating process.

Note that, while in large language model contexts the model is computing the next-token distribution, and people sometimes say the model is “estimating” or “inferring” the next token, this is not estimation in the statistical sense. At this stage, the model is a fixed function and its parameters are already learned.

So when we call the generate_text_basic_stream function, we are not performing statistical inference. We are performing neural network inference, which is just the forward application of a trained model to produce the next-token distribution and select the next generated token from this distribution.

Now that we have a basic text generation function in place, we can turn our attention to what happens when we actually run it in practice. As you may have noticed, the text generation in the previous section can be a bit slow. That slowdown points us to a key concern: performance during inference.

When running inference with LLMs, which in this context means generating text from a prompt, runtime performance (efficiency) quickly becomes important, especially for long sequences. While the code in this book emphasizes clarity over speed, real-world systems often use engineering tricks to make inference more efficient.

This is useful for the later chapters as well, because evaluation and reasoning workflows often require generating many tokens or many candidate answers, so small speed-ups here compound quickly.

In the remaining two sections, we will cover two fundamental techniques, KV caching and model compilation, as shown in the overview in figure 2.15, to speed up the text generation.

As mentioned in figure 2.15, one engineering trick that increases the text generation speed is KV caching, where KV refers to the keys and values used in the model’s attention mechanism. If you are not familiar with these terms, that’s okay. The key idea is that we can cache certain intermediate values and reuse them at each step of text generation, as shown in figure 2.16, which helps speed up inference.

The key idea of KV caching, as shown in figure 2.16, is to store intermediate values computed in each iteration in a cache. Previously, each new token generated by the network was concatenated to the entire input sequence and fed back into the model repeatedly (indicated by crossed-out boxes in the diagram). This approach was inefficient because all tokens, except the newly generated one, remained identical in subsequent iterations. By using a KV cache, we avoid redundant computation and instead directly retrieve stored intermediate representations.

Stage 1: LLM basics (chapter 2)

① Conventional LLM

Loading pretrained weights

Text generation

★ KV caching Model compilation

Stage 2: Measuring performance (chapter 3)

② Evaluation

Benchmark-based evaluation

Judgment-based evaluation

Stage 3: Reasoning without training (chapters 4 and 5)

③ Inference techniques

Advanced text generation and voting

Self-refinement

Stage 4: Reasoning with training (chapters 6 to 8)

④ Training techniques

Reinforcement learning

Distillation

In the remainder of this chapter, we will use two techniques to increase the execution speed; this section focuses on KV caching.

SPEED UP EXECUTION

Figure 2.15 An overview of the four key stages in developing a reasoning model in this book. This section builds on pretrained LLM and the basic text generation function we coded earlier and applies KV caching to speed up execution.

An intermediate representation of “Explain large language models.” is stored in the KV cache.

The LLM stores a representation for the next token (here, “Large”) and retrieves a representation from previous steps.

KV cache

Large

language

models

are

LLM iteration 1

LLM iteration 2

LLM iteration 3

LLM iteration 4

…

Explain large language models.

Explain large language models. Large

Explain large language models. Large language

Explain large language models. Large language models

The concatenated inputs are not needed anymore.

Figure 2.16 Illustration of how a KV cache improves efficiency during autoregressive text generation. Instead of reprocessing the entire input sequence at each step, the KV cache stores intermediate representations so that the LLM can reuse them to generate the next token. This eliminates the need to concatenate the generated token with prior inputs in each subsequent iteration.

In rough terms, generating nn new tokens without KV caching requires repeatedly recomputing work over an increasingly long sequence, which adds up to about O(n2)O(n^2) total decoding work. Here, O(n2)O(n^2) means the total work grows roughly with the square of the output length. With KV caching, after the initial pass, each new step processes only the newly added token, reducing this to roughly O(n)O(n), which means the total work grows approximately in direct proportion to the number of generated tokens.

As mentioned earlier, the nonreasoning focused LLM details like KV caching, which we used to improve the token generation speed, are outside the scope of this book, and they are not required for the topics covered later in this book. However, interested readers can find more information on the mechanics of KV caching in my freely available article: Understanding and Coding the KV Cache in LLMs from Scratch (https://magazine.sebastianraschka.com/p/coding-the-kv-cache-in-llms).

Following is a modified version of the generate_text_basic_stream function that incorporates a KV cache, which is almost identical to the basic text generation function in listing 2.2, except for the KV cache-related change highlighted via the comments:

Listing 2.4 A basic text generation function with KV cache

from reasoning_from_scratch.qwen3 import KVCache
@torch.inference_mode()
def generate_text_basic_stream_cache(
model,
token_ids,
max_new_tokens,
eos_token_id=None
):
model.eval()
cache = KVCache(n_layers=model.cfg["n_layers"])
model.reset_kv_cache()
out = model(token_ids, cache=cache)[:,-1]
for _ in range(max_new_tokens):
next_token = torch.argmax(out, dim=-1, keepdim=True)
if (eos_token_id is not None
and torch.all(next_token == eos_token_id)):
break
yield next_token
out = model(next_token, cache=cache)[:,-1]

The generate_text_basic_stream_cache function in listing 2.4 differs only slightly from the generate_text_basic_stream function in listing 2.2. The main difference is the introduction of a KVCache object.

During the first iteration, the model is given the full input token sequence as before, using model(token_ids, cache=cache). Behind the scenes, the KV cache stores the attention keys and values computed for all these input tokens, so they do not need to be recomputed in later iterations.

In the following iterations, we no longer need to pass the entire sequence. Instead, we only provide the next_token to the model using model(next_token, cache=cache). The model then retrieves the necessary context from the previously stored KV cache.

Let’s time this function to see whether it provides any performance benefits:

start_time = time.time()
generated_ids = []
for token in generate_text_basic_stream_cache(
model=model,
token_ids=input_token_ids_tensor,
max_new_tokens=max_new_tokens,
eos_token_id=tokenizer.eos_token_id
):
token_id = token.squeeze(0).tolist()
print(
tokenizer.decode(token_id),
end="",
flush=True
)
next_token_id = token.squeeze(0)
generated_ids.append(next_token_id)
end_time = time.time()
output_token_ids_tensor = torch.cat(generated_ids, dim=0)
generate_stats(output_token_ids_tensor, tokenizer, start_time, end_time)

The output is

Time: 1.40 sec 29 tokens/sec

Large language models are artificial intelligence systems that can understand, generate, and process human language, enabling them to perform a wide range of tasks, from answering questions to writing articles, and even creating creative content.

As we can see, this approach is significantly faster, generating 29 tokens per second compared to just 5 tokens per second previously (measured on a Mac Mini M4 CPU). We also see that the generated text is the same as before, which is an important sanity check to ensure that the KV cache is implemented and used correctly.

In the next section, we will learn about another technique we can use to further improve the generation speed, which will come in handy when we evaluate the model in the upcoming chapters. Faster generation allows us to run more evaluations in less time and makes it easier to compare different models or settings efficiently.

2.9 Faster inference via PyTorch model compilation

Section titled “2.9 Faster inference via PyTorch model compilation”

In the previous section, we covered KV caching as a technique to improve runtime efficiency as shown in the overview in figure 2.17.

graph LR
    subgraph G1 ["1 - Conventional LLM"]
        direction TB
        A1["Loading pretrained weights"]
        A2["Text generation"]
    end
    subgraph G2 ["2 - Evaluation"]
        direction TB
        B1["Benchmark-based evaluation"]
        B2["Judgment-based evaluation"]
    end
    subgraph G3 ["3 - Inference techniques"]
        direction TB
        C1["Advanced text generation and voting"]
        C2["Self-refinement"]
    end
    subgraph G4 ["4 - Training techniques"]
        direction TB
        D1["Reinforcement learning"]
        D2["Distillation"]
    end
    G1 --> G2 --> G3 --> G4

[!visual-conversion] Figure 2.17 — An overview of the four key stages in developing a reasoning model in this book (printed p. 50, scan page-062.png). This section builds on the pretrained LLM and the basic text generation function we coded earlier, including KV caching, and adds model compilation to speed up the execution speed even further. In the print, the “Text generation” substep branches down into two speed-up steps under the heading SPEED UP EXECUTION:

graph LR
    T["Text generation"] --> K["KV caching"]
    T --> M["Model compilation"]

annotated “In this last section of the chapter, we will increase the execution speed even further by compiling the LLM.” Print stage headings: Stage 1: LLM basics (chapter 2) · Stage 2: Measuring performance (chapter 3) · Stage 3: Reasoning without training (chapters 4 and 5) · Stage 4: Reasoning with training (chapters 6 to 8).

As shown in figure 2.17, in this remaining section of this chapter, we will apply another technique that can substantially speed up model inference: model compilation using torch.compile. In simple terms, torch.compile analyzes the model’s internal computation graph and tries to turn groups of operations into more optimized kernels, which reduces Python overhead and other execution inefficiencies. This can improve runtime performance during text generation, especially when we call the same model code repeatedly in a loop.

That will matter later when we run larger evaluations and more elaborate reasoning workflows, where even modest per-step speedups can save substantial total runtime. We can compile the model as follows:

major, minor = map(int, torch.version.split(”.”)[:2])

if (major, minor) >= (2, 8):
# This avoids retriggering model recompilations
# in PyTorch 2.8 and newer
# if the model contains code like self.pos = self.pos + 1
torch._dynamo.config.allow_unspec_int_on_nn_module = True
model_compiled = torch.compile(model)

If you are using a Mac with Apple Silicon and encounter an InductorError, please make sure to use PyTorch 2.9 or newer.

It is worth noting that the first execution using the compiled model may be slower than usual due to the initial compilation and optimization steps. To better measure the performance improvement, we will repeat the text generation process multiple times.

To begin, we will test this using the noncached version of the generation function. The code in listing 2.5 is similar to what we used before except that we run it three times in a row. The code execution may take a few minutes to finish, depending on the system.

Listing 2.5 Generating text with the compiled model

for i in range(3):
start_time = time.time()
generated_ids = []
for token in generate_text_basic_stream(
model=model_compiled,
token_ids=input_token_ids_tensor,
max_new_tokens=max_new_tokens,
eos_token_id=tokenizer.eos_token_id
):
token_id = token.squeeze(0).tolist()
print(
tokenizer.decode(token_id),
end="",
flush=True
)
next_token_id = token.squeeze(0)
generated_ids.append(next_token_id)
end_time = time.time()
if i == 0:
print("\n\nWarm-up run")
else:
print(f"\n\nTimed run {i}:")
output_token_ids_tensor = torch.cat(generated_ids, dim=0)
generate_stats(output_token_ids_tensor, tokenizer, start_time, end_time)
print(f"\n{'-'*30}\n")

The output is as follows:

Large language models are artificial intelligence systems that can understand, generate, and process human language, enabling them to
<!-- page: 064 (printed 52) -->
perform a wide range of tasks, from answering questions to writing articles, and even creating creative content.
Warm-up run
Time: 11.68 sec
3 tokens/sec
------------------------------
Large language models are artificial intelligence systems that can understand, generate, and process human language, enabling them to perform a wide range of tasks, from answering questions to writing articles, and even creating creative content.
Timed run 1:
Time: 6.78 sec
6 tokens/sec
------------------------------
Large language models are artificial intelligence systems that can understand, generate, and process human language, enabling them to perform a wide range of tasks, from answering questions to writing articles, and even creating creative content.
Timed run 2:
Time: 6.80 sec
6 tokens/sec
------------------------------

As we can see from the results, the compiled model achieves a slight improvement in speed, with around 6 tokens per second compared to the previous 5 tokens per second.

Next, let’s see how the KV cache version performs in comparison, using the same code as before except for swapping generate_text_basic_stream with generate_text_basic_stream_cache.

Listing 2.6 Generating text with the compiled model using a KV cache

for i in range(3):
start_time = time.time()
generated_ids = []
for token in generate_text_basic_stream_cache(
model=model_compiled,
token_ids=input_token_ids_tensor,
max_new_tokens=max_new_tokens,
eos_token_id=tokenizer.eos_token_id
):
token_id = token.squeeze(0).tolist()
print(
tokenizer.decode(token_id),
end="",
flush=True
)
next_token_id = token.squeeze(0)
generated_ids.append(next_token_id)
end_time = time.time()
if i == 0:
print("\n\nWarm-up run")
else:
print(f"\n\nTimed run {i}:")
output_token_ids_tensor = torch.cat(generated_ids, dim=0)
generate_stats(
output_token_ids_tensor, tokenizer, start_time, end_time
)
print(f"\n{'-'*30}\n")

The output is as follows:

Large language models are artificial intelligence systems that can understand, generate, and process human language, enabling them to perform a wide range of tasks, from answering questions to writing articles, and even creating creative content.
Warm-up run
Time: 8.07 sec
5 tokens/sec
----------------------------
Large language models are artificial intelligence systems that can understand, generate, and process human language, enabling them to perform a wide range of tasks, from answering questions to writing articles, and even creating creative content.
Timed run 1:
Time: 0.60 sec
68 tokens/sec
----------------------------
Large language models are artificial intelligence systems that can understand, generate, and process human language, enabling them to perform a wide range of tasks, from answering questions to writing
articles, and even creating creative content.
Timed run 2:
Time: 6.60 sec
68 tokens/sec

As we can see based on the outputs, the model generation speed improved from 29 tokens per second for the uncompiled model with KV cache to 68 tokens per second when the same model is compiled (on a Mac Mini M4 CPU), which is more than a two-fold speed-up.

If you don’t see any improvement, try running torch.compile with the “max-autotune” mode instead of the default settings. For instance, replace

model = torch.compile(model)

with

model = torch.compile(model, mode="max-autotune")

Exercise 2.2: Rerunning code on non-CPU devices

If you have access to a GPU, rerun the code in this chapter on a GPU device and compare the runtimes to the CPU runtimes.

In case you are curious about how the different model configurations compare on an Apple Silicon GPU and a high-end NVIDIA GPU, see table 2.1.

Table 2.1 Token generation speeds and GPU memory usage for different model configurations on different hardware

ModeHardwareTokens/secGPU memory
RegularMac Mini M4 CPU5-
Regular compiledMac Mini M4 CPU6-
KV cacheMac Mini M4 CPU28-
KV cache compiledMac Mini M4 CPU68-
RegularMac Mini M4 GPU27-
Regular compiledMac Mini M4 GPU43-
KV cacheMac Mini M4 GPU41-

| KV cache compiled | Mac Mini M4 GPU | 71 | - | | Regular | NVIDIA H100 GPU | 51 | 1.55 GB | | Regular compiled | NVIDIA H100 GPU | 164 | 1.61 GB | | KV cache | NVIDIA H100 GPU | 48 | 1.52 GB | | KV cache compiled | NVIDIA H100 GPU | 146 | 1.61 GB |

As shown in table 2.1, the NVIDIA GPU delivers the best performance, which is expected. The CPU still performs surprisingly well once a KV cache and a compiled model are enabled. However, there are a few important details that explain why the GPU gains are not larger for this particular setup.

First, the model in this chapter is not optimized for GPUs. The implementation aims for a good balance between memory usage and compute speed because memory is the main bottleneck for most readers. A GPU-optimized variant would preallocate the full K and V tensors up to the maximum context length (in this case, 40 thousand tokens). This preallocation avoids repeated concatenation via torch.cat, but it also increases memory consumption.

With a large context size, preallocating, for example, 40 thousand entries for both K and V adds a noticeable footprint. Another approach would be to let users specify a fixed context size at construction time, but that introduces extra configuration overhead. The KV cache here grows on demand via torch.cat, which is simpler and more memory friendly, although concatenating non-preallocated tensors is a bit slower on GPUs.

I included a GPU-optimized version in the bonus materials, where the KV cache variant is slightly faster than the regular version, but it uses more memory (see https://github.com/rasbt/reasoning-from-scratch/tree/main/ch02/03_optimized-LLM).

Second, the model used for benchmarking is small. Larger models benefit much more from KV caching and from GPU-optimized memory layouts. The same holds for batched inference, where GPUs can better saturate their compute units. With a larger model or a GPU-focused implementation, the performance gap in favor of the NVIDIA GPU would be more pronounced.

All examples were run using a single prompt (i.e., a batch size of 1). For readers interested in how performance scales with multiple inputs, batched inference is discussed in appendix E.

Summary

  • Using LLMs to generate text involves multiple key steps:
    • Setting up the coding environment to run LLM code and install necessary dependencies - Loading a pretrained base LLM (such as Qwen3 0.6B), which will be extended with reasoning capabilities in later chapters - Initializing and using a tokenizer, which converts text input into token IDs and decodes output back to human-readable form
  • Text generation in LLMs follows a sequential (autoregressive) process, where the model generates one token at a time by predicting the next most likely token.
  • The speed and efficiency of text generation can be improved through
    • KV caching, which stores intermediate states to avoid recomputing previously encountered input tokens at each step - Model compilation using torch.compile, which optimizes runtime performance
  • This chapter lays the technical foundation for reasoning capabilities in upcoming chapters by implementing a functional, efficient text generation pipeline using a pretrained base LLM.