Skip to content
ImagineWorld

Running inference

node_idnode-book_build-small-language-model_chapter-04-running-inference
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num4
chapter_titleRunning inference
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

This chapter covers

  • Generating different types of content
  • Calculating the cost of inference with a large model
  • Identifying areas for performance improvements and cost savings

Chapters 2 and 3 presented examples of data preparation and SLM tuning. Now I’ll introduce SLM inference and offer tips for estimating GPU costs and finding performance and cost improvements.

In this chapter, we’ll use a language model as a reference for content generation. We’ll cover the key factors that drive execution speed, accuracy, and compute cost—background that you’ll use when applying the diverse quantization methods I’ll explain in chapters 5, 6, and 9.

Our reference open source model is GPT-Neo large (2.7 billion trainable parameters, https://huggingface.co/EleutherAI/gpt-neo-2.7B) from the EleutherAI research group (https://www.eleuther.ai/). Although GPT-Neo is no longer actively developed and has been replaced by newer models, it remains a useful example for explaining the topics in this chapter because it is a Transformer model that replicates the GPT3 architecture. The topics in this chapter are not limited to GPT-Neo; they apply to any LLM available through the Hugging Face Transformers and Accelerate (https://github.com/huggingface/accelerate) libraries (both used in this example) and to domain-specific models trained on your own data. The code examples in this chapter are also provided in the two companion Colab notebooks.

You can load the GPT-Neo model and its tokenizer the usual way:

import torch
from transformers import GPTNeoForCausalLM, GPT2Tokenizer
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model_id = "EleutherAI/gpt-neo-2.7B"
tokenizer = GPT2Tokenizer.from_pretrained(model_id)
model = GPTNeoForCausalLM.from_pretrained(model_id, device_map="auto")
model.to(device)

The pretrained model (available on the Hugging Face Hub) is loaded onto a GPU to speed up inference. GPTNeoForCausalLM, a specialized PreTrainedModel class for GPT-Neo, is available in the Transformers library, and the tokenizer can be downloaded via the GPT2Tokenizer class. We set device_map to auto so the Accelerate library can run inference even when the model doesn’t fully fit on the GPU. Accelerate places as many layers as possible on the fastest devices (here, a single GPU) and offloads the rest to the CPU—or even disk if RAM is limited. This split is transparent to developers, so the inference code stays the same. In this example, the model is loaded in float32 type (the default) because the free-tier Colab GPU can fit it in that format. In other environments, you’ll likely need lower precision.

To estimate the memory needed to load a model, Accelerate also provides a command-line tool. For GPT-Neo 2.7B, it looks like this:

accelerate estimate-memory EleutherAI/gpt-neo-2.7B

Pass the model ID from the Hugging Face Hub to the command (that’s the only required argument). The command returns the download size for each available precision type:

Loading pretrained config for 'EleutherAI/gpt-neo-2.7B' from 'transformers'...

Memory usage for loading EleutherAI/gpt-neo-2.7B

dtypeLargest LayerTotal SizeTraining using Adam
float32490.79 MB9.89 GB39.57 GB
float16245.4 MB4.95 GB19.79 GB
int8122.7 MB2.47 GB9.89 GB
int461.35 MB1.24 GB4.95 GB

In the preceding output, the Total Size column is the one relevant for inference. In this example, using float32 gives a model size of 9.89 GB. You can also filter this command’s output to one or more supported precisions with the -dtypes option. Note that accelerate estimate-memory calculates only the memory required to load the model; it doesn’t include additional memory needed for inference, which we’ll discuss in the following sections.

When you load this model in a hardware-accelerated Colab VM, run the hf_device_map function:

model.hf_device_map

It will return the following output:

{”: 0}

This confirms that all model layers fit in the available T4 GPU memory. Otherwise, the command will show how the layers are split across GPU memory, RAM, and disk.

Let’s look at an example using this prompt:

prompt = "The story so far: in the beginning, the universe was created."
input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)

You can generate text (completions) with the generate function; then decode the output:

generated_ids = model.generate(input_ids,
do_sample=True,
temperature=0.9,
max_length=200,
pad_token_id=50256)
generated_text = tokenizer.decode(generated_ids[0])

The generated content will look something like this:

The story so far: in the beginning, the universe was created. The Big Bang.

But things didn’t just immediately go from nothing to everything in a few seconds. After the Universe had gotten started, it had to evolve. The laws of physics had to change.

It took 13.8 billion years, but slowly, the universe continued to evolve.

Now: according to the story so far, a few more than 4.5 billion years after the Big Bang, the universe was still expanding. Which meant that the laws of physics had not yet changed.

And it turned out that something in the universe was changing the laws of physics in just the right way.

This new way of doing things was called dark energy. And back in 2005, when he first put forward the idea of dark energy, the idea didn’t really catch on. It was slow to catch on until later in the 21st century that it became one of

You can also generate text for a batch of prompts:

prompts = ["Once there was a man ",
"The weather today will be ",
"A great soccer player must "]
tokenizer.padding_side = "left"
tokenizer.pad_token = tokenizer.eos_token
encoding = tokenizer(prompts, padding=True, return_tensors='pt').to(device)
with torch.no_grad():
generated_ids = model.generate(**encoding,
do_sample=True,
temperature=0.9,
max_length=50,
pad_token_id=50256)
generated_texts = tokenizer.batch_decode(
generated_ids, skip_special_tokens=True)

The output contains the generated text to complete each input sentence:

Once there was a man
Who lived on a hill,
The best man I ever saw,
He gave me a ride.
He made me forget
All I had left
The weather today will be
much warmer than yesterday,
and there'll be a lot more
sunshine. We'll have
some very hot weather
tonight. It should be a
A great soccer player must
Be at his best when playing
In a great place
With great friends
In a great city
With great players
And great fans

GPT-based models can do more than text completion. Another powerful capability is few-shot learning: given a few examples in a prompt, the model can generalize to new, unseen ones. For example, you can use it for few-shot text classification:

prompt = """
Sentence: This movie is very nice.
Sentiment: positive
#####
Sentence: I hated this movie, it sucks.
Sentiment: negative
#####
Sentence: This movie was actually pretty funny.
Sentiment: positive
#####
Sentence: This movie could have been better.
Sentiment: neutral
"""
input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)
generated_ids = model.generate(input_ids,
do_sample=True,
temperature=0.9,
max_length=200,
pad_token_id=50256)
generated_text = tokenizer.decode(generated_ids[0])

Given the initial samples in the prompt, the model starts generating others like them (and the output includes the input too):

Sentence: This movie is very nice.
Sentiment: positive
#####
Sentence: I hated this movie, it sucks.
Sentiment: negative
#####
Sentence: This movie was actually pretty funny.
Sentiment: positive
####
Sentence: This movie could have been better.
Sentiment: neutral
####
Sentence: This movie is actually really scary.
Sentiment: negative
####
Sentence: This movie was awesome.
Sentiment: positive
####
Sentence: This movie has a weird plot.
Sentiment: neutral
####
Sentence: This movie is awesome.
Sentiment: positive
####
Sentence: This movie is actually really good.
Sentiment: positive
####
Sentence: I really like this movie.
Sentiment: positive

The generated output isn’t limited to natural language. Trained on the Pile dataset, which includes many samples from GitHub repositories, the model can generate code too. The prompt must follow this format:

Instruction: Answer:

Let’s ask the model to write a function to reverse a list of integers (even though Python lists already support reversing):

prompt = """Instruction: Generate a Python function that lets you reverse a list of integers.
Answer: """
input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)

Code generation can be performed just like the other use cases:

generated_ids = model.generate(input_ids,
do_sample=True,
temperature=0.9,
max_length=200,
pad_token_id=50256
)
generated_text = tokenizer.decode(generated_ids[0])

The generated content will look like the following; it includes the input and is truncated to the first 200 tokens because the generation request sets max_length:

Instruction: Generate a Python function that lets you reverse a list of integers.
Answer:
def reverse(x):
return x[::-1]
A:
The way I would do it differently is to create a wrapper function that looks similar to this for one list of integers:
def reverse(aList):
new_alist = [int(i) for i in alist]
new_alist = new_alist[::-1]
return new_alist
And then iterate over the list to reverse it.
Def reverse_list(aList):
tmp = None
for x in aList:
if tmp is None:
tmp = x

Code generated by this model always needs developer review. You may need to lint or refine it, and other models are better at producing working code (as will be discussed in later chapters). This example simply illustrates the possibilities of using a single LLM.

Note that GPT-Neo and other open source pretrained models aren’t meant to be used as is; they typically require fine-tuning or techniques like LoRA or RAG. If you try to replicate this chapter’s examples without that, expect hallucinations or lower-quality results. For now, we’ll pretend we’re working with a model we’ve already customized. My goal here is to show you what happens behind the high-level Python inference API—these are details you’ll need to keep in mind when deciding on an optimization or quantization strategy.

Before deploying an LLM to production, it’s good practice to evaluate it to measure output quality and decide what to do next (mitigate or deploy). LLM evaluation is tedious and complex, with challenges that vary by model architecture and the task the model was trained for.

The Evaluation Harness library (https://github.com/EleutherAI/lm-evaluation-harness) from EleutherAI, also known as LM-Eval, offers a unified way to test LLMs across many evaluation tasks. It’s implemented in Python and is open source (MIT license). It includes more than 200 built-in tasks and lets you create custom tasks on third-party or private data. In addition to its task coverage, it supports several Transformer model sources: open source models from the Hugging Face Hub (via the Transformers library), commercial models via the OpenAI API (requires an OpenAI key) and other providers, models in Neural Magic’s SparseZoo repository (via the DeepSparse OSS library), and GPTQ, GGUF-, or GGML-quantized models (covered in chapters 6 and 9).

Depending on the task, different evaluation metrics are supported. Because the framework is open source and flexible, you can easily extend it and tailor existing tasks. Task versioning is another key feature, ensuring reproducibility even after tasks are updated.

LM-Eval isn’t currently available through a Python package installer, so you must install it from source. Clone the official GitHub repository, and install it with pip (Python 3.8+ required):

Terminal window
git clone https://github.com/EleutherAI/lm-evaluation-harness
cd lm-evaluation-harness
pip install -e .

You’re now ready to run evaluation tests. To evaluate a model hosted on the Hugging Face Hub for a given task, use the provided main.py script:

Terminal window
python main.py \
--model hf-causal \
--model_args pretrained=EleutherAI/gpt-neo-2.7B,dtype="float16" \
--tasks wikitext \
--device cuda:0

The following options can be set in the script:

  • model—The model type.
  • model_args—A list of arguments that specify which model to download from the Hub and evaluate. Only pretrained is required, and its value must match the exact Hugging Face Hub model ID. We’ll use GPT-Neo 2.7B throughout this chapter. You can also pass any other arguments supported by the Transformers PreTrainedModel class’s from_pretrained method.
  • tasks—A list of evaluation tasks to run.
  • device—The device or devices to use (GPU or CPU). Use hardware acceleration for evaluation tests.

In the preceding example, the evaluation task is wikitext, one of LM-Eval’s built-in tests. It uses 62 samples from a dataset of verified good and featured Wikipedia articles (https://huggingface.co/datasets/Salesforce/wikitext) to compute three metrics for the model under test: word_perplexity (predictive power), byte_perplexity (how well the model predicts the next byte given prior bytes), and bits_per_byte (average bits needed to predict the next symbol). LM-Eval can compute additional metrics depending on the task; see the official GitHub repository for the current list of tasks and metrics. For the GPT-Neo model on wikitext, the results are as follows:

hf-causal (pretrained=EleutherAI/gpt-neo-2.7B,dtype=float16), limit: None, provide_description: False, num_fewshot: 0, batch_size: None

TaskVersionMetricValueStderr
wikitext1word_perplexity13.9382
byte_perplexity1.6367
bits_per_byte0.7108

We’ll reference LM-Eval and other libraries when evaluating models.

Deploying an LLM to production to handle multiple inference requests costs money. In the previous section, you learned that larger models cost more because their weights require more GPU memory, and you often need extra headroom to maintain performance. You also saw a CLI tool in the Accelerate library that estimates the required memory. It’s worth understanding how it makes that calculation so you can estimate memory needs when serving LLMs outside the Transformers library and make other sizing decisions. Model documentation for available pretrained open source models usually lists the number of trainable parameters, but for deployment, you need the model’s in-memory size so you can decide which GPU (or combination of GPUs) you’ll need. The formula for estimating inference memory (in GB) is

memory=4×P32÷F×1.2\text{memory} = \frac{4 \times P}{32 \div F} \times 1.2

where

  • 4 is the number of bytes for each trainable parameter.
  • P is the model’s total number of trainable parameters (in billions).
  • F is the number of bits for the chosen precision (32 for FP32, 16 for FP16, 8 for INT8).
  • 1.2 is a factor that includes an average 20% overhead due to several factors (detailed later in this chapter).

Returning to our GPT-Neo example from section 4.1, the model has 2.7 billion parameters. We loaded it in FP32, so applying the preceding formula gives us 12.96 GB.

Loading the same model in FP16 reduces this to 5.4 GB. If we run the same calculation for a different model, such as Mistral 7B (https://huggingface.co/mistralai/Mistral-7B-v0.3), it requires about 33.6 GB of GPU memory in FP32, or about 16.2 GB in FP16. Most open source Transformers models are trained in mixed precision (FP16 + FP32 or BF16 + FP32), which reduces the memory needed for training and, as the formula shows, for inference too, without a major performance loss when casting an LLM from FP32 to FP16 (and to INT8, as you’ll see in subsequent chapters). So if you need to fit within your hardware constraints, it’s fine to load a pretrained model in FP16.

An LLM’s size is one factor to consider when deciding whether to deploy it to production, but it’s not the only one. There are several other important factors:

  • Full GPU power utilization—Even if GPUs are available in your environment (we’ll also cover CPU-only setups later), deploying a model and running inference doesn’t automatically use all GPU resources—or use them efficiently. Techniques can help you better use the available hardware acceleration.

  • Time to first token (TTFT)—How quickly does a user see the model’s first output token after entering a prompt?

  • Time per output token (TPOT)—How long does it take to generate an output token for each active user?

  • Latency—How long does it take to generate a complete response for a user? This depends on TTFT and TPOT.

  • Throughput—How many output tokens can the serving system generate per second for all users and requests?

Optimization and quantization techniques (the core topic of this book) can reduce the hardware requirements for LLM serving and help meet latency and throughput targets. But there are also other challenges, validations, and factors to consider before and after optimization and quantization. We’ll look at those next.

4.3 Areas for improvement (cost savings and performance)

Section titled “4.3 Areas for improvement (cost savings and performance)”

The metrics in the previous section give you a clear picture of how well your LLM’s inference serving performs, helping you spot areas for improvement that can reduce costs (use only the computational power you need, get the most from it, and keep users engaged). Next, we’ll look at what you can do up front to address common inference serving challenges. Although this section uses GPU-Neo as an example, the same considerations apply to other LLM architectures.

The companion code for this chapter is a Colab notebook that uses hardware acceleration (an NVIDIA Tesla T4 GPU, https://www.nvidia.com/en-us/data-center/tesla-t4, also available in Colab’s free tier).

When choosing a GPU, we focus on three characteristics: compute throughput, memory, and memory bandwidth. According to the T4’s datasheet, it provides 65 TFLOPS (tera floating-point operations per second) in full (FP32) or half precision (FP16), 16 GB of memory, and 300 GB/sec of memory bandwidth (that is, up to 300 GB of data can move from GPU memory to on-chip shared [SRAM] memory per second). For GPT-Neo, memory isn’t a concern: in half precision it requires 12.96 GB, leaving room for other inference-time operations.

Using the remaining specs, we can compute the device’s ops/byte ratio, which is the number of floating-point operations (FLOPS) per second per byte of memory accessed. We calculate it as follows:

OpsToByte=ComputeBandWidthMemoryBandWidth\text{OpsToByte} = \frac{\text{ComputeBandWidth}}{\text{MemoryBandWidth}}

For the T4 GPU, this value is 216.6 ops/byte. To fully use its computational power, we must perform 216.6 floating-point operations for every byte read from memory. At runtime, if we observe fewer than 216.6 operations per byte, our system is memory bound: performance is limited by the data-transfer rate. Conversely, if we need to perform more than 216.6 operations per byte but can’t, our system is compute bound: performance is limited by available compute units, not memory. Our goal is to determine which case applies on our hardware and optimize accordingly. To do that, we need to compute the model’s arithmetic intensity: the number of compute operations divided by the number of bytes accessed. This metric is hardware-agnostic. Next, we need to identify which model layers demand the most computational power. In Transformer architectures, the attention layers are prime candidates because weighting each next-token prediction based on the relevance of previous tokens is computationally intensive.

Generative Transformer inference sampling has two phases: prefill and autoregressive sampling. In the prefill phase, the model ingests the prompt tokens in parallel and populates the key-value (KV) cache. This cache stores the model’s state inside the attention operation. No token generation happens in this phase. In the autoregressive sampling phase, the model uses the state in the KV cache to sample and decode the next token. The cache costs storage (GPU VRAM, or CPU RAM when no GPU is available), but it avoids recomputing attention on all prior tokens at each step. Without the KV cache, each successive token would take longer to sample because all previously seen tokens would need to pass through the model again. The generate function in the Transformers library’s PreTrainedModel classes (encoder-decoder and decoder-only) exposes a use_cache parameter to enable KV caching; it defaults to True. Still, when you import third-party code, verify that KV caching is actually enabled—frameworks other than Transformers may not turn it on by default. Figure 4.1 summarizes how KV caching works.

Step 1
Queries Keys transpose Values Results
┌──────────┐ ┌───┐ ┌──────────┐ ┌──┐
│ │ 4 x │ 4 │ 64 x │ │ 64 │ │
│ │ │ │ │ │ │ │
└──────────┘ └───┘ └──────────┘ └──┘
64 4 64
│ Caching K │ Caching V
▼ ▼
┌───────────────────────────────────┐
│ Cache memory │
└───────────────────────────────────┘
│ Restoring K │ Restoring V
▼ ▼
Step N
Queries Keys transpose Values Results
┌──────────┐ ┌───┐ ┌──────────┐ ┌──┐
│ │ 1 x │ 5 │ 64 x │ │ 64 │ │ 1
└──────────┘ └───┘ └──────────┘ └──┘
64 5 64 64
Legend: ▒ values computed on this step ░ values taken from the cache

[!visual-conversion] Figure 4.1 — The (Q × Kᵀ) × V computation process with caching (p. 72)

Using the previous GPT-Neo example again, let’s see how inference speed change without a KV cache. We’ll run multiple text generations on a T4 GPU, first with the KV cache enabled and then disabled:

import time
import numpy as np
prompt = "The story so far: in the beginning, the universe was created."
input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)
for use_cache in (True, False):
times = []
for _ in range(20):
start = time.time()
generated_ids = model.generate(input_ids,
do_sample=True,
temperature=0.9,
max_length=200,
pad_token_id=50256,
use_cache=use_cache)
times.append(time.time() - start)
print(f'{"Using" if use_cache else 'No'} KV cache: {round(np.mean(times), 3)} +- {round(np.std(times), 3)} seconds")

These are the average execution times:

Using KV cache: 10.281 +- 0.327 seconds
No KV cache: 51.978 +- 0.208 seconds

As expected, using the cache reduces the matrix sizes, giving a considerable speedup. For a negligible increase in VRAM use (assuming you still have capacity), you get a big boost in generation speed. We prepared for this by adding an extra 20% GPU memory in the inference-memory formula. You should definitely use the KV cache.

Now let’s calculate the arithmetic intensity for our use case. The formula for multi-head attention is as follows:

Attention(Q,K,V)=softmax(QKTdk)V\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V

where

Q∈Rh×Sdkh and K,V∈Rh×L×dkhQ \in Rh \times Sd_k^h \text{ and } K, V \in Rh \times L \times d_k^h

In this equation, QQ, KK, and VV are matrices used to compute attention: QQ represents the query tokens, and KK and VV represent the keys and values (as discussed earlier in the context of the KV cache). We can express the preceding formula with the following pseudocode algorithm, which repeats the same basic steps—load values from memory, compute, and store the results back in memory:

Require: Matrices QQ, KK, V∈RN×dV \in RN \times d in memory. Step 1: Load QQ, KK from memory, then compute S=QKTS = QKT and write it to memory. Step 2: Read SS from memory, then compute P=softmax(S)P = \text{softmax}(S) and write it to memory. Step 3: Load PP and VV from memory, then compute O=P×VO = P \times V and write it to memory.

The sqrt(dk)sqrt(d_k) term in the previous equation can be ignored because it’s minor compared with the others. For completeness, NN is the model’s context window (2048 for GPT-Neo ), and dkd_k is the dimension of a single attention head (128 for GPT-Neo). The QQ, KK, and VV matrices are 2048×1282048 \times 128; SS and PP are 2048×20482048 \times 2048; and OO is 2048×1282048 \times 128. Arithmetic intensity depends on total memory movement and total computation. For the three operations in each step of the algorithm, the formulas to compute these values are as follows (the first is in bytes; the second is in FLOPS):

total_memory_movement
= (2 * 4 * (N * d)) + (4 * (N * N)) + (4 * ((N*N) + (N * d))) + (4 * (N * N)) + (4 * (N * N)) + (4 * (N * d))

and

total_compute
= ((2 * d) * (N * N)) + (3 * (N * N)) + ((2 * N) * (N * d))

The arithmetic intensity can then be calculated this way:

arithmetic_intensity
= total compute / total memory movement

For GPT-Neo, these metrics are

total_memory_movement = 71303168
total_compute = 2160066560
arithmetic_intensity = 30.29 ops/byte

Given the ops/byte ratio we calculated for this device (216.6 ops/byte on a T4 GPU), our system appears memory-bound: in the time it takes to move one byte from memory to compute, the GPU could have done many more calculations. In other words, we’re not fully using the available GPU compute. Can we fix this? The next section answers that question.

You can also pass an LLM a batch of prompts and generate responses for all of them at once. We can use static batching (multiple prompts from the same request), or, to reduce memory-boundedness, we can use dynamic batching: instead of starting generation immediately for each incoming request, queue requests, and run them together in a single pass. This reuses model state already loaded in GPU memory across the batch, increasing arithmetic intensity (more compute per memory access) and making the workload less memory-bound. The next question is how large the batch can be, which depends on available GPU memory. In our GPT-Neo example, FP32 precision requires 12.96 GB; on a T4 GPU with 16 GB of VRAM, that leaves 3.04 GB theoretically available. Let’s calculate how many sequences can fit in that spare memory. We also need to account for the KV cache. During the prefill phase, the cache is populated with the input sequence and stores the K and V matrices used in the attention computation. First, we need the KV-cache size for our case, which we can compute with the following formula:

kv_cache_size = (2 * num_bytes * n_layers * model_dim)

This is measured in bytes/token. In our example, we use 4 bytes (full precision), 24 attention layers, and a model dimension of 2,048. That gives a KV cache size of 393,216 bytes/token (about 0.00039 GB/token), which translates to the following:

kv_cache_tokens
= 3.04 GB / 0.00039 GB/token
= 7795 tokens

With GPT-Neo’s standard sequence length of 2,048 tokens, our example has enough capacity to handle a batch of three sequences at once. During inference, batching three requests to fill the KV cache will increase throughput.

Batching helps in some cases but hurts in others. It’s a good strategy when you’re using LLMs to process a large document queue asynchronously, because throughput is much higher than when processing items one by one. You can also schedule inference calls to fill batches quickly and keep added latency low. But for chatbot-style systems, where latency must be minimal, batching is usually a poor fit because queuing increases the response time users feel. In those cases, your main options are to use a GPU with more memory or better performance, or to use model quantization (covered starting in chapter 5).

Given an LLM and one or more GPUs, it can be useful to estimate up front how long content generation will take. To do this, we first need to estimate the time to generate a single token. We can approximate it by dividing the total number of bytes moved by the GPU’s memory bandwidth:

time/token = total number of bytes moved/GPU memory bandwidth

You can estimate the number of bytes moved by multiplying the model’s trainable parameters by the bytes per parameter (based on your chosen precision). For our GPT-Neo example, the model has 2.7 billion parameters, it’s loaded in full precision (4 bytes each), and the T4 GPU has 300 GB/s memory bandwidth, so generating a single token takes roughly 36 ms.

This isn’t exact: it assumes no on-chip communication during inference, perfect parallelism, and no overhead for a forward pass. A more accurate estimate would include the prefill phase. If we batch all prompt tokens into a single forward pass, a formula for that metric is shown here:

prefill time = number of tokens * (total number of bytes moved/ GPU compute bandwidth)

In our GPT-Neo example, assuming 300 tokens and a T4 compute bandwidth of 65 TFLOPS, the prefill time is about 50 ms. Taking this into account, the total generation time is

total generation time = prefill time + (number of tokens * time/token)

For our example (300 tokens), that’s 50 + (300 * 36) = 10.85 seconds. We can verify if this estimate is accurate or not:

import time
import numpy as np
prompt = "The story so far: in the beginning, the universe was created."
input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)
max_length = 300
times = []
inference_runs = 21
for _ in range(inference_runs):
start = time.time()
generated_ids = model.generate(input_ids,
do_sample=True,
temperature=0.9,
max_length=max_length,
pad_token_id=50256,
)
times.append(time.time() - start)
print(f"Average Total Generation time: {round(np.mean(times[1:]), 3)} +- {round(np.std(times[1:]), 3)} seconds")

On a T4 GPU, that gives a total generation time like this:

Average Total Generation time: 15.562 +- 2.465 seconds

These observed times also include overhead from other operations beyond the GPU computation.

LLM inference can benefit from techniques such as the following:

  • Operator fusion—This combines adjacent operators, often improving latency.
  • Quantization—This compresses an LLM’s weights or activations to use fewer bits.
  • Compression strategies, such as sparsity (making parts of a model inactive or zero-valued to reduce computation) or distillation (training a smaller model using a larger one as a “teacher,” to compress knowledge).
  • Parallelization—Use tensor parallelism across devices or pipeline parallelism for larger models.

The rest of the book covers multiple techniques related to quantization, but it also touches on the other areas listed here.

To reduce compute and memory use—and fit larger models on a single GPU or GPU cluster—you can use DeepSpeed (https://github.com/microsoft/DeepSpeed). DeepSpeed is an open source library from Microsoft (Apache 2.0 license) for deep learning optimization. It makes distributed training and inference easier and more efficient, it supports PyTorch, and it integrates with Hugging Face’s Transformers and Accelerate libraries. Key features include ZeRO (Zero Redundancy Optimizer, https://arxiv.org/abs/1910.02054), mixed-precision training, custom model parallelism, and optimizations for low-latency, high-throughput inference. Model parallelism doesn’t just help models fit in GPU memory; it can also reduce inference latency for smaller language models. DeepSpeed also provides inference-specific kernels to further reduce latency and cost. For compatible Transformer-based models trained with DeepSpeed, Hugging Face, or Megatron, DeepSpeed’s inference mode works without exporting the model or creating new checkpoints. It automatically partitions the model as needed, injects high-performance kernels, and manages inter-GPU communication in multi-GPU environments. This section focuses on inference with DeepSpeed.

Let’s see how DeepSpeed works. For our first example, we’ll again use the GPT-Neo model, running on a Colab VM with hardware acceleration (a T4 GPU). You can run Python scripts that use the DeepSpeed API via the deepspeed CLI or programmatically, which is what we’ll do in this section.

Note that to run inference in Colab or Jupyter notebooks, we’ll need some initialization code because, at the time of writing, no DeepSpeed launcher is available. We’ll mock DeepSpeed’s native launcher by setting a few environment variables, as follows:

import os
os.environ['MASTER_ADDR'] = 'localhost'
os.environ['MASTER_PORT'] = '9999'
os.environ['RANK'] = "0"
os.environ['LOCAL_RANK'] = "0"
os.environ['WORLD_SIZE'] = "1"

The master port can be any available port, and the world size is the number of GPUs. Rank and world size define the DeepSpeed state; here, we’ll set rank to 0 because we aren’t using a distributed PyTorch backend.

Now we’ll initialize the DeepSpeed engine and set the default device to CUDA, since we’ll run inference on an NVIDIA GPU:

import deepspeed
import torch
device = "cuda" if torch.cuda.is_available() else "cpu"
deepspeed.init_distributed()
ds_device = torch.device(device, int(os.getenv('LOCAL_RANK')))

If you’re not running in a notebook, you can skip the code so far. The rest doesn’t depend on the execution environment.

Now that the DeepSpeed engine is initialized, we can load the GPT-Neo model the usual way. For this example, we’ll use half precision to fit both the base model and the DeepSpeed-optimized version in GPU memory:

import torch
from transformers import GPTNeoForCausalLM, GPT2Tokenizer
model_id = "EleutherAI/gpt-neo-2.7B"
tokenizer = GPT2Tokenizer.from_pretrained(model_id)
model = GPTNeoForCausalLM.from_pretrained(model_id,
torch_dtype=torch.float16,
device_map="auto")

Next, we’ll set up the DeepSpeed inference engine for our pipeline:

ds_model = deepspeed.init_inference(
model=model,
mp_size=1,
dtype=torch.float16,
replace_method="auto",
replace_with_kernel_inject=True,
)

The model passed to DeepSpeed is the one we downloaded earlier. We use the only GPU available in our environment. We set replace_method to auto, letting DeepSpeed choose which layers to replace with more performant implementations (a good default when you’re unsure which policy fits a given model). We set replace_with_kernel_inject to True to enable inference-kernel injection for our GPT-Neo model. Kernel injection speeds up deep learning workloads by replacing selected operations (kernels) in the computation graph with DeepSpeed’s optimized versions.

After this step, you can see which layers of the original model DeepSpeed has replaced with higher-performance implementations:

InferenceEngine(
(module): GPTNeoForCausalLM(
(transformer): GPTNeoModel(
(wte): Embedding(50257, 2560)
(wpe): Embedding(2048, 2560)
(drop): Dropout(p=0.0, inplace=False)
(h): ModuleList(
(0-31): 32 x DeepSpeedGPTInference(
(attention): DeepSpeedSelfAttention(
(qkv_func): QKVGemOp()
(score_context_func): SoftmaxContextOp()
(linear_func): LinearOp()
(vector_matmul_func): VectorMatMulOp()
)
(mlp): DeepSpeedMLP(
(mlp_gemm_func): MLPGemOp()
(vector_matmul_func): VectorMatMulOp()
(fused_gemm_gelu): GELUGemmOp()
(residual_add_func): ResidualAddOp()
)
)
(ln_f): LayerNorm((2560,), eps=1e-05, elementwise_affine=True)
)
(lm_head): Linear(in_features=2560, out_features=50257, bias=False)
)
)
)

Finally, we can run inference with the DeepSpeed-modified model. The code is very similar to standard HF Transformers inference:

example = "The story so far: in the beginning, the universe was created."
input_ids = tokenizer(example, return_tensors="pt").input_ids.to(model.device)
logits = ds_model.generate(input_ids,
do_sample=True,
max_length=100,
pad_token_id=50256)
tokenizer.decode(logits[0].tolist())

This is the output:

The story so far: in the beginning, the universe was created. Chaos was at the centre. After some time, an intelligent and powerful being had fallen in love with a beautiful princess. They married and had a daughter. This daughter would grow up to be the one who would shatter the universe to bits and the princess would lose her life, but in that moment, both lived and both would make their daughter immortal. This was the first of many sacrifices to make in order to be together. Over

To see how DeepSpeed’s model parallelism and kernels affect inference performance, let’s run a small benchmark. Using the same prompt as the other examples in this chapter, with sampling enabled and a maximum length of 300 tokens, we’ll run 20 generation tasks with the vanilla GPT-Neo model and its DeepSpeed-optimized counterpart (a helper function for these benchmarks is provided in the accompanying Colab notebook). The following results compare both versions of the model:

Vanilla model: P95 latency (ms) - 10679.311647649865; Average latency (ms) - 10511.16 +/- 166.87;

DeepSpeed model: P95 latency (ms) - 8835.399639349884; Average latency (ms) - 8552.32 +/- 125.19;

Using DeepSpeed reduced the latency by about 18% on average. Still, it’s important to validate the output’s quality: DeepSpeed, like other optimization techniques, can affect model accuracy. The change may be small—it depends on your problem’s KPIs. You may need to trade off latency and accuracy.

DeepSpeed also provides MoQ, a strategy for quantizing models to shrink them and reduce production inference costs. We’ll cover MoQ later, after introducing LLM quantization.

  • The GPT-Neo 2.7B model, using the Transformers library, can complete text, learn from few-shot prompts, and generate code.
  • Memory requirements are calculated using this formula: memory (GB) = (4 × P) / (32 ÷ F) × 1.2, where P is the number of parameters (in billions) and F is the precision (in bits).
  • GPT-Neo 2.7B needs 12.96 GB (FP32) or 5.4 GB (FP16); Mistral 7B needs 33.6 GB (FP32) or 16.2 GB (FP16).
  • Key inference metrics are time to first token (TTFT), time per output token (TPOT), latency, and throughput.
  • The KV cache stores attention-layer states to avoid recalculating them for each token, yielding a 5× speedup in tests.
  • The operations/byte ratio determines whether a system is memory-bound or compute-bound; the T4 GPU’s ratio is 216.6 ops/byte.
  • Arithmetic intensity is operations per byte accessed; GPT-Neo’s 30.29 ops/byte suggests memory-bound performance.
  • Dynamic batching processes multiple requests at once, improving throughput by reusing model weights already in GPU memory.
  • Batch size is limited by available GPU memory after accounting for model weights and the KV cache.
  • Token generation time is estimated by dividing bytes moved by GPU memory bandwidth; on a T4 GPU, GPT-Neo generates about one token every 36 ms.
  • The LM-Eval framework standardizes evaluation with 200+ built-in tasks and metrics, such as word perplexity, byte perplexity, and bits per byte.
  • The DeepSpeed library optimizes inference through model parallelism, kernel injection, and the ZeRO optimizer.
  • DeepSpeed reduced GPT-Neo inference latency by 18% compared to a baseline implementation.
  • The Accelerate library includes the estimate-memory command for calculating memory requirements across precision levels.