Skip to content
ImagineWorld

Appendix E: Batching and throughput-oriented execution

node_idnode-book_build-a-reasoning-model_appendix-e-batching-and-throughput-oriented-execution
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_titleAppendix E: Batching and throughput-oriented execution
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Appendix E: Batching and throughput-oriented execution

Section titled “Appendix E: Batching and throughput-oriented execution”

appendix E Batching and throughput-oriented execution

In the code implemented through the book’s chapters, we usually processed one prompt or example at a time. This kept the code compact and easier to understand, and it also helped keep the resource requirements more manageable. The code in this book is already expensive to run, so adding batching support everywhere would often increase complexity without providing much real benefit, depending on your available hardware.

That being said, if you have access to relatively modern GPUs with enough memory, batched execution, illustrated in figure E.1, can be very useful. For example, if we want to evaluate many problems, sample several responses per prompt, or train on multiple examples at once, batching can help increase throughput and reduce the overall time required.

This appendix explains the broad idea behind batching and shows how you can use the batched implementations in the supplementary materials across various chapters.

When we talk about computational performance, it helps to separate the following overall goals:

  • Latency: how quickly we get the answer for one prompt
  • Throughput: how many prompts we can process in a fixed amount of time

Single-example generation is often best used for understanding the conceptual implementation of a concept, minimizing latency, and debugging. Batching can be seen

Single-example generation — one prompt is processed at a time

graph LR
    P1["1 - Solve 2x + 3 = 11"] --> L1["LLM"] --> O1["x = 4"]
    P2["2 - Compute 7^2 − 5^2"] --> L2["LLM"] --> O2["24"]
    P3["3 - Simplify 12/3 + 4"] --> L3["LLM"] --> O3["8."]

Batched generation — multiple prompts are processed simultaneously

graph LR
    B["Solve 2x + 3 = 11<br/>Compute 7^2 − 5^2<br/>Simplify 12/3 + 4"] --> L["LLM"]
    L --> O["x = 4<br/>24<br/>8."]

[!visual-conversion] Figure E.1 — An overview of single-example versus batched generation (printed p. 366, scan page-378.png). In batched generation, several prompts are packed into one batch, processed in parallel, and then decoded together to improve throughput. Print annotations: “In the regular, sequential model, one prompt is processed at a time” and “In the batched mode, multiple prompts are processed simultaneously.”

as an extension of single-example generation that primarily targets throughput. For example, if we want to evaluate hundreds of problems on MATH-500, generate several self-consistency samples, or train on a larger distillation dataset, batching can reduce total runtime substantially on suitable hardware.

But batching is not automatically faster on every device. Small models on CPUs or less optimized GPUs may benefit only a little, or not at all, because they introduce additional code complexity, including padding and other overheads, that can offset the gains from batching parallelism.

Batching is best understood as a throughput optimization, not as a universal speedup.

The main technical obstacle in batching is that prompts usually have different lengths. One math problem may tokenize to 40 tokens while another may tokenize to 120 tokens, but PyTorch tensors still have to be rectangular. So if we want to run several prompts together, we need a way to pad shorter rows and keep track of which positions are real tokens and which are just padding tokens.

Padding tokens are placeholder tokens that are added to a prompt to make it a certain length. For example, to extend a three-token prompt “3 + 3” to a five-token prompt, we may add two additional padding tokens to the right or the left: “<pad>``<pad> 3 + 3”. (In practice, it doesn’t matter which token we use as a padding token; it’s common to use an end-of-sequence token like <eos> or <|endoftext|>.)

Conceptually, padding and keeping track of padded positions make batched generation more complicated than single-prompt generation. In the book, we used the Qwen- 3Model class from reasoning_from_scratch.qwen3, which is the plain single-example implementation explained in appendix C.

For batched generation, the book’s supplementary materials therefore include a separate Qwen3Model class in reasoning_from_scratch.qwen3_batched. It can be used as a drop-in replacement, and it adds the bookkeeping needed for padding-aware execution in batching.

Let’s look at a single-sequence example that looks very similar to the code we used earlier in book. In the following listing, we apply it to two very small prompts, but we still run them one after the other.

Listing E.1 Single-example generation

import torch
from reasoning_from_scratch.ch02 import (
get_device,
generate_text_basic_stream_cache,
)
from reasoning_from_scratch.ch03 import (
load_model_and_tokenizer,
render_prompt,
)
device = get_device()
model, tokenizer = load_model_and_tokenizer(
which_model="base",
device=device,
use_compile=False,
)
for problem in ["2+2?", "3+3?"]: # The two prompts we sequentially process
prompt = render_prompt(problem)
input_ids = torch.tensor(
tokenizer.encode(prompt),
dtype=torch.long,
device=device,
).unsqueeze(0)
for token in generate_text_basic_stream_cache(
model=model,
<!-- page: 380 (printed 368) -->
token_ids=input_ids,
max_new_tokens=32,
eos_token_id=tokenizer.eos_token_id,
):
next_token_id = token.squeeze(0)
print(tokenizer.decode(next_token_id.tolist()), end="", flush=True)
print() # Force a new line after each answer.

This is the resulting output:

\boxed{4} \boxed{6}

The code in listing E.1 is still ordinary single-example generation. We render the prompt, tokenize it, add a batch dimension of size 1, and then stream the generated tokens as they arrive. This is conceptually simple, which is why we used this style in the book.

Listing E.2 shows the corresponding batched version. The overall workflow is similar, but now we switch to reasoning_from_scratch.qwen3_batched, tokenize both prompts up front, left-pad them to the same length, and generate them together.

Listing E.2 Batched generation

from reasoning_from_scratch.qwen3_batched import (
generate_text_basic_batched_cache,
load_model_and_tokenizer,
)
model, tokenizer = load_model_and_tokenizer(
which_model="base",
device=device,
use_compile=False,
)
problems = ["2+2?", "3+3=6"]
prompts = [render_prompt(problem) for problem in problems]
tokenized = [tokenizer.encode(p) for p in prompts]
pad_id = tokenizer.pad_token_id
max_len = max(len(t) for t in tokenized)
left_padded = [
[pad_id] * (max_len - len(t)) + t # Left-pad shorter sequences so all prompts in the batch have the same length.
for t in tokenized
]
input_ids = torch.tensor(left_padded, dtype=torch.long, device=device)
generated = generate_text_basic_batched_cache(
model=model,
token_ids=input_ids,
max_new_tokens=32,
<!-- page: 381 (printed 369) -->
eos_token_id=tokenizer.eos_token_id,
pad_id=pad_id, # Needed so generation can distinguish real tokens from padding.
)
for row in generated:
eos_pos = (row == tokenizer.eos_token_id).nonzero(as_tuple=True)[0]
if len(eos_pos) > 0:
row = row[:eos_pos[0]]
print(tokenizer.decode(row.tolist()))

The results are the same as before, but this time they are produced in parallel:

\boxed{4} \boxed{6}

In this example, we used the nonstreaming batched helper, so we need to wait until the whole batch is finished before decoding and printing the results. That keeps the example simple and makes it easier to see the role of the padding before we dig into the internal masking logic.

There is also a more optimized variant of the text generation function, generate_text_basic_batched_cache_stop, which removes finished rows from the active compute batch instead of carrying them along until the longest row finishes. In contrast, the generate_text_basic_batched_cache we used in listing E.2 keeps every row in the active batch for every decode step.

In generate_text_basic_batched_cache, once a row has emitted EOS, the implementation forces that row to keep producing EOS so that the batch shape stays aligned, even though the row is already finished from the perspective of the final decoded output. The difference between these two functions is illustrated in figure E.2. Note that Qwen3 uses <|endoftext|> as the EOS token for the base model, but figure E.2 labels it simply as <eos> for visual compactness.

The next section goes into a bit more detail about how the padding is handled internally.

In single-example mode, if we tokenize a short prompt such as “2+2?”, we can pass it to the model as a simple tensor of shape (1, 4):

input_ids = torch.tensor([[17, 10, 17, 30]])

Internally, the model builds a standard causal attention mask so that each position can attend only to itself and earlier tokens. If you are unfamiliar with causal attention masks and self-attention, my article titled “Understanding and Coding Self-Attention, Multi-Head Attention, Causal-Attention, and Cross-Attention in LLMs,” provides more background information: https://magazine.sebastianraschka.com/p/understanding-and-coding-self-attention.

In single-sequence generation via generate_text_basic_stream_cache, we keep on generating until we encounter an end-of-sequence token (<eos>).

Step 1 Step 2 Step 3 Step 4 ” Solve 2x + 3 = 11” → x = 4 <eos>

In batched generation via generate_text_basic_batched_cache, we keep on generating until all sequences omit an <eos> token. Then we remove all extra tokens generated in postprocessing.

Step 1 Step 2 Step 3 Step 4 “Solve 2x + 3 = 11” → x = 4 <eos> “Compute 7^2 - 5^2” → 24 <eos> <eos> <eos> “Simplify 12/3 + 4” → 8 . <eos> <eos>

In batched generation via generate_text_basic_batched_cache_stop, we remove sequences from further generation steps once they have generated an <eos> token.

Step 1 Step 2 Step 3 Step 4 “Solve 2x + 3 = 11” → x = 4 <eos> “Compute 7^2 - 5^2” → 24 <eos> <eos> “Simplify 12/3 + 4” → 8 <eos>

Figure E.2 Sequential generation (1) versus regular batched generation (2) and early-stop batched generation (3). The regular batched helper (2) keeps finished rows in the batch as placeholder EOS rows, whereas the _stop variant (3) removes finished rows from the active compute batch as soon as they emit EOS.

The causal attention mask for the “2+2?” prompt is illustrated in figure E.3. In the causal mask, the value 1 means “masked out” and 0 means “allowed.” In this figure, the first token cannot look ahead to later positions, the second token can look only at the first two positions, and so on. This is the standard autoregressive masking pattern.

Batching changes the situation because different prompts usually have different lengths. Suppose we process “2+2?” together with the slightly longer prompt, “3+3=6?”.

(1) Single-sequence generation via generate_text_basic_stream_cache — keep generating until an end-of-sequence token (<eos>) is encountered

PromptStep 1Step 2Step 3Step 4
“Solve 2x + 3 = 11”x=4<eos>

(2) Regular batched generation via generate_text_basic_batched_cache — keep generating until all sequences emit an <eos> token, then remove extra tokens in postprocessing

PromptStep 1Step 2Step 3Step 4
“Solve 2x + 3 = 11”x=4<eos>
“Compute 7^2 − 5^2”24<eos><eos><eos>
“Simplify 12/3 + 4”8.<eos><eos>

(3) Early-stop batched generation via generate_text_basic_batched_cache_stop — remove sequences from further generation steps once they have generated an <eos> token

PromptStep 1Step 2Step 3Step 4
“Solve 2x + 3 = 11”x=4<eos>
“Compute 7^2 − 5^2”24<eos>——
“Simplify 12/3 + 4”8.<eos>—

[!visual-conversion] Figure E.2 — Sequential generation (1) versus regular batched generation (2) and early-stop batched generation (3) (printed p. 370, scan page-382.png). The regular batched helper (2) keeps finished rows in the batch as placeholder EOS rows, whereas the _stop variant (3) removes finished rows from the active compute batch as soon as they emit EOS.

Token IDs corresponding to the input prompt, obtained via tokenizer.encode(prompt)

① prompt = “2+2?” ② tokenized = [17, 10, 17, 30] ③ input_ids = torch.tensor([[17, 10, 17, 30]])

The token “2” (token ID 17) can only attend itself, not future tokens in the sequence.

④ causal_mask = [ [0, 1, 1, 1], [0, 0, 1, 1], [0, 0, 0, 1], [0, 0, 0, 0], ]

Causal mask for a 4-token prompt

prompt = "2+2?" 1
tokenized = [17, 10, 17, 30] 2
input_ids = torch.tensor([[17, 10, 17, 30]]) 3
causal_mask = [ 4
[0, 1, 1, 1],
[0, 0, 1, 1],
[0, 0, 0, 1],
[0, 0, 0, 0],
]
"2" "+" "2" "?"
17 10 17 30
"2" 17 [ 0 1 1 1 ]
"+" 10 [ 0 0 1 1 ]
"2" 17 [ 0 0 0 1 ]
"?" 30 [ 0 0 0 0 ]
Positions with a "1" are masked, meaning they are hidden.

[!visual-conversion] Figure E.3 — The causal mask used in single-example generation (printed p. 371, scan page-383.png). Tokens can attend only to themselves and earlier positions, which is the standard autoregressive setup. Print annotations: “Token IDs corresponding to the input prompt, obtained via tokenizer.encode(prompt)”, “Tokenized prompt converted into an input tensor as LLM input”, “The token ‘2’ (token ID 17) can only attend to itself, not future tokens in the sequence”, “Causal mask for a 4-token prompt”, and “Positions with a ‘1’ are masked, meaning they are hidden.” In the print the upper triangle is shaded to show the masked-out region. All values are transcribed from the figure.

Since PyTorch tensors must be rectangular, the shorter row has to be padded to match the longer one, as illustrated in figure E.4 with left padding.

Figure E.4 shows that we keep an additional attn_mask internally. This mask is used to keep track of the padded positions, where True means padded and False means not padded. We use this additional attn_mask to identify the tokens in the causal mask that correspond to pad token IDs. Masking padded keys and zeroing padded queries are important steps to make batching behave similarly to the single-example execution.

In the remainder of this appendix, you will see how to use scripts from the book’s supplementary materials that implement the optional batched variants for different chapters.

E4 Chapter 3: Batched MATH-500 evaluation

The book’s supplementary materials include a script for the single-example evaluation method from chapter 3 that you can download and run directly using the download function we introduced in chapter 7.

prompts = ["2+2?", "3+3=6?"]

We now have two prompts being tokenized via tokenizer.encode(prompt).

tokenized = [
[17, 10, 17, 30],
[18, 10, 18, 28, 21, 30],
]

We add padding tokens to the first prompt so that all prompts have equal lengths.

padded = [
[151643, 151643, 17, 10, 17, 30],
[18, 10, 18, 28, 21, 30],
]

The attn_mask stores information about which prompt token IDs are padding tokens (0) and which are “real” token IDs (1).

attn_mask = torch.tensor([
[True, True, False, False, False, False],
[False, False, False, False, False, False],
])

Internally, the attn_mask is then used to identify which positions in the causal mask should be masked (because we want to ignore padding tokens in the computation).

mask_prompt_1 = [
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 1, 0, 1, 1, 1],
[1, 1, 0, 0, 1, 1],
[1, 1, 0, 0, 0, 1],
[1, 1, 0, 0, 0, 0],
]

The padding tokens are masked out via the 1’s; inside the larger causal mask, we have a causal mask that looks like the 4-token causal mask from before.

mask_prompt_2 = [
[0, 1, 1, 1, 1, 1],
[0, 0, 1, 1, 1, 1],
[0, 0, 0, 1, 1, 1],
[0, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0],
]

There are no padding tokens in the second prompt, so this looks like a regular causal mask.

Figure E.4 Left padding in batched generation. The shorter row is padded up to the maximum sequence length in the batch, and the padding-aware mask ensures that these padded positions do not affect attention.

Listing E.3 Downloading the single-example evaluation script

Section titled “Listing E.3 Downloading the single-example evaluation script”
from reasoning_from_scratch.ch07 import download_from_github
download_from_github(
"ch03/02_math500-verifier-scripts/evaluate_math500.py"
)
download_from_github(
"ch03/01_main-chapter-code/math500_test.json",
out="math500_test.json",
)

After downloading the script and dataset via listing E.3, we can run the single-example evaluation from the terminal as follows (if you are not using uv, simply replace uv run with python):

uv run evaluate_math500.py
—dataset_size 500
—which_model “reasoning”

The supplementary material also includes a batched version that applies the batching method we discussed previously. The download is almost identical, except that we replace evaluate_math500.py with evaluate_math500_batched.py.

Listing E.4 Downloading the evaluation script with batch support

download_from_github( "ch03/02_math500-verifier-scripts/evaluate_math500_batched.py" )

The use of the batched script is very similar to the nonbatched version, except that we now provide an additional —batch_size argument to specify how many prompts and answers the model should process in parallel:

uv run evaluate_math500_batched.py
—dataset_size 500
—which_model “reasoning”
—batch_size 64

The ideal batch size depends entirely on what your hardware can handle, so it’s best to start with a smaller value and scale upward until you hit the throughput and memory limit that makes sense for your setup.

We will return to a comparison of single-example and batched generation performance at the end of this appendix.

E5 Chapter 4: Batched self-consistency sampling

The optional self_consistency_math500_batched.py script for chapter 4 does not mix different prompts into one padded tensor. Instead, it repeats the same prompt num_samples times and samples several continuations in parallel for self-consistency voting, because parallelizing over the different numbers of samples for each prompt is a natural angle we can take advantage of.

Because every row starts from the same prompt length, this script can use the regular Qwen3Model from reasoning_from_scratch.qwen3 instead of reasoning_from_scratch.qwen3_batched. In other words, the batch dimension here is used for multiple sampled rollouts of the same prompt, not for padding together unrelated prompts of different lengths.

You can download the script as shown next.

Listing E.5 Downloading self-consistency sampling with batch support

download_from_github( "ch04/02_math500-inference-scaling-scripts/" "self_consistency_math500_batched.py" )

To download the nonbatched version instead, simply remove the “_batched” part from the filename in listing E.5.

We can run the batched script as follows, and the syntax for the nonbatched script is otherwise the same:

uv run self_consistency_math500_batched.py
—which_model base
—temperature 0.9
—top_p 0.9
—num_samples 3
—dataset_size 500
—prompt_suffix “\n\nExplain step by step.”

Self-refinement in chapter 5 is fundamentally sequential and therefore does not benefit much from simple batching. In principle, you could run self-refinement loops for multiple inputs in parallel, but that is nontrivial to implement and is therefore not part of the book’s supplementary material. Instead, the next batched example appears in the chapter 6 RLVR code.

In chapter 6, we again use the same prompt for multiple rollouts, so no padding is required. As in section E.5, the code can therefore stay with the regular Qwen3Model class from reasoning_from_scratch.qwen3. The relevant scripts can be fetched as follows.

Listing E.6 Downloading the RLVR script with batch support

download_from_github( "ch06/02_rlvr_grpo_scripts_intro/" "rlvr_grpo_original_no_kl_batched.py" )

As before, to download the single-generation script, simply drop “_batched” from the filename in listing E.6.

A typical batched run looks like this:

uv run rlvr_grpo_original_no_kl_batched.py
—num_rollouts 8
—batch_size 4
—max_new_tokens 512

Here, —batch_size controls how many rollouts are generated in parallel within one training step. This improves throughput, but it also increases memory pressure, so you may need to reduce —num_rollouts or —max_new_tokens.

Chapter 8 returns to the padding-aware style from chapter 3 because the distillation examples have different prompt and answer lengths. In other words, we are again batching unrelated examples of different lengths into a single rectangular tensor, which means that masking and padding matter again. You can download the batched training script and fetch a sample training dataset as follows.

Listing E.7 Downloading the distillation script with batch support

from reasoning_from_scratch.ch08 import load_distill_data
download_from_github( "ch08/04_train_with_distillation/distill_batched.py" ) _ = load_distill_data( partition="deepseek-r1-math-train", local_path="deepseek-r1-math-train.json", )

For the nonbatched version, remove the “_batched” part from the filename in listing E.7. A representative run of the batched version looks like this:

uv run distill_batched.py
—data_path deepseek-r1-math-train.json
—dataset_size 500
—validation_size 10
—epochs 2
—use_think_tokens
—batch_size 32

Here, —batch_size lets us process multiple distillation examples per optimization step. But because training also has to store activations, the resource demands can be much higher than in the chapter 3 evaluator, so chapter 8 introduces the training analogue of the padding-aware batching strategy discussed earlier in this appendix.

The supplementary scripts in chapters 3 and 8 batch together different-length examples, so they need padding-aware attention masks and more careful bookkeeping. Chapters 4 and 6 batch repeated copies of the same prompt or rollout setup, so they can stay with the regular model implementation and avoid the more complicated padding logic.

Either way, batched generation can result in higher throughput and shorter runtimes, at the cost of increased RAM use. Table 8.1 compares single to batched generation using the settings shown in the previous sections.

Table E.1 RAM use and runtime comparison

ScriptBatch sizeRAMH100 total timeDGX Spark total time
1evaluate_math500.py-1.8 GB90 min174 min
2evaluate_math500_batched.py6423.39 GB16 min108 min
3self_consistency_math500.py-1.79 GB252 min340 min
4self_consistency_math500_batched.py32.45 GB129 min243 min
5rlvr_grpo_original_no_kl.py-43.35 GB68 min63 min
6rlvr_grpo_original_no_kl_batched.py444.91 GB19 min23 min
7distill.py-8.29 GB10 min32 min
8distill_batched.py48.34 GB9 min28 min

As shown in table E.1, the batched variants are always faster than the single-sequence variants. In most cases, the difference is very noticeable. One exception is distillation (rows 7 and 8), where batching only yields a modest advantage. This could be because the GPU is already well utilized in single-batch mode, and the extra overhead of batched generation from the additional mask generation is not worth it, given the small size of the Qwen3 6-billion-parameter model.