PyTorch for inference
PyTorch is the ground most language models stand on. Know tensors (shape, dtype, device), load a model in BF16 on the GPU, turn off gradients with inference_mode, generate text, and time GPU work correctly: the GPU runs in the background, so synchronize before you stop the clock, and warm up first.
Author: bezzad
Contents
The problem: “my benchmark says 0.3 ms per token”
A teammate tries our 8B shop model in a Python script and reports: “One token takes 0.3 ms. We can do 3,000 tokens per second for one user!” The serving engine later shows about 40 tokens per second for one user.
The model did not change. The measurement was wrong. Production engines like vLLM, SGLang or TensorRT-LLM hide most of PyTorch, but when you read model code, debug a wrong answer or measure a change, you work with PyTorch directly. This lesson covers the parts an inference engineer uses every week.
Tensors: shape, dtype, device
A tensor is an array of numbers, like a NumPy array, with three facts you must always know:
import torch
x = torch.randn(4, 6, 4096) # random numbers
print(x.shape) # torch.Size([4, 6, 4096])
print(x.dtype) # torch.float32
print(x.device) # cpu
x = x.to("cuda", dtype=torch.bfloat16)
print(x.dtype, x.device) # torch.bfloat16 cuda:0
- Shape. In a language model, the common shape is [batch, tokens, hidden].
- dtype. The number format:
float32,bfloat16,float16,int8… It decides memory: 4 × 6 × 4,096 numbers × 2 bytes in BF16 is about 197 KB. - device.
cpuorcuda. Both sides of an operation must be on the same device, or PyTorch raises an error.
Matrix multiply is @, just like NumPy: (4, 6, 4096) @ (4096, 14336) gives (4, 6, 14336).
Loading a model
The Hugging Face transformers library is the usual way to load open-weight models:
from transformers import AutoModelForCausalLM, AutoTokenizer
name = "our-org/shop-assistant-8b" # example name
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(
name,
dtype=torch.bfloat16, # older versions: torch_dtype=
device_map="cuda",
)
model.eval()
- Pick the dtype on purpose. Without it, weights may load in FP32: 32 GB instead of 16 GB.
device_map="cuda"puts the weights on the GPU.model.eval()switches off training-only behavior like dropout.
Check the memory after loading:
print(torch.cuda.memory_allocated() / 1e9, "GB") # about 16 for BF16
Turn off gradients
By default, PyTorch remembers what it did so it can compute gradients for training. Inference does not need that.
with torch.inference_mode():
out = model(**inputs)
torch.inference_mode()turns off gradient tracking. Less memory, a bit faster.torch.no_grad()is the older, similar option.inference_modeis stricter and usually a bit faster.- Forgetting both is a common reason for out-of-memory errors in test scripts.
Generating text
messages = [{"role": "user", "content": "Where is my order 1042?"}]
inputs = tok.apply_chat_template(
messages, add_generation_prompt=True,
return_tensors="pt", return_dict=True,
).to("cuda")
with torch.inference_mode():
ids = model.generate(**inputs, max_new_tokens=100, do_sample=False)
new_tokens = ids[0, inputs["input_ids"].shape[1]:]
print(tok.decode(new_tokens, skip_special_tokens=True))
- Use the chat template. Chat models expect special tokens around each message. Plain text gives worse answers.
- Always set
max_new_tokens. Without a limit, a bad prompt can run for a long time. do_sample=Falseis greedy decoding: good for tests, because the answer is more repeatable.generateis a loop of forward passes, with a KV cache inside. It is fine for tests, but it does not do continuous batching; that is what serving engines add.
Timing GPU work correctly
GPU work is asynchronous: Python queues kernels and returns at once. So this is wrong:
start = time.perf_counter()
out = model(**inputs) # only queued!
print(time.perf_counter() - start) # far too small
The right way:
def timed(fn, warmup=3, runs=10):
for _ in range(warmup): # first runs are slow
fn()
torch.cuda.synchronize()
start = time.perf_counter()
for _ in range(runs):
fn()
torch.cuda.synchronize() # wait for the GPU
return (time.perf_counter() - start) / runs
- Synchronize before you stop the clock.
torch.cuda.synchronize()waits until all queued GPU work is done. - Warm up first. The first runs pay one-time costs: loading kernels, allocating memory, compiling.
- Measure what users feel. Time to first token and time per token are different numbers; one forward pass is neither.
- Use realistic inputs. A 10-token prompt hides the cost of a 3,000-token prompt.
Back to our teammate: 0.3 ms was the time to queue the work, not to do it.
Common mistakes
| Mistake | Result | Right way |
|---|---|---|
| No dtype when loading | Model in FP32, twice the memory, slower. | dtype=torch.bfloat16 (or the model card’s format). |
Forgetting inference_mode |
Out-of-memory in long tests. | Wrap inference in torch.inference_mode(). |
| Timing without synchronize | Numbers 10 to 100 times too good. | torch.cuda.synchronize() before reading the clock. |
| No warm-up | The first slow run spoils the average. | A few warm-up runs, then measure. |
| Plain text instead of the chat template | Worse or strange answers. | tok.apply_chat_template(...). |
Summary in six lines
- Always know a tensor’s shape, dtype and device.
- In a language model, the usual shape is [batch, tokens, hidden].
- Load weights in BF16 on the GPU, then call
model.eval(). - Run inference inside
torch.inference_mode(). - Use the chat template and always set
max_new_tokens. - GPU work is asynchronous: warm up, synchronize, then read the clock.