My account

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.

Not reviewedWritten with AI helpReading time: 12 minShop assistant examplePyTorchHugging Face

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
batch = 4 requeststokens = 6hidden = 4,096 numbersone tokenshape [4, 6, 4096]
Most tensors in a language model have the shape [batch, tokens, hidden]: here 4 requests, 6 tokens each, 4,096 numbers per token.
  1. Shape. In a language model, the common shape is [batch, tokens, hidden].
  2. dtype. The number format: float32, bfloat16, float16, int8… It decides memory: 4 × 6 × 4,096 numbers × 2 bytes in BF16 is about 197 KB.
  3. device. cpu or cuda. 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()
  1. Pick the dtype on purpose. Without it, weights may load in FP32: 32 GB instead of 16 GB.
  2. device_map="cuda" puts the weights on the GPU.
  3. 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)
  1. torch.inference_mode() turns off gradient tracking. Less memory, a bit faster.
  2. torch.no_grad() is the older, similar option. inference_mode is stricter and usually a bit faster.
  3. 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))
  1. Use the chat template. Chat models expect special tokens around each message. Plain text gives worse answers.
  2. Always set max_new_tokens. Without a limit, a bad prompt can run for a long time.
  3. do_sample=False is greedy decoding: good for tests, because the answer is more repeatable.
  4. generate is 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

CPU (Python)GPUqueuekernel 1kernel 2kernel 3kernel 4clock stops: wrongclock stops after synchronize: righttime
The CPU only queues work for the GPU and moves on. Without synchronize, the clock stops while the GPU is still working. With synchronize, the clock waits for the GPU to finish.

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
  1. Synchronize before you stop the clock. torch.cuda.synchronize() waits until all queued GPU work is done.
  2. Warm up first. The first runs pay one-time costs: loading kernels, allocating memory, compiling.
  3. Measure what users feel. Time to first token and time per token are different numbers; one forward pass is neither.
  4. 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

  1. Always know a tensor’s shape, dtype and device.
  2. In a language model, the usual shape is [batch, tokens, hidden].
  3. Load weights in BF16 on the GPU, then call model.eval().
  4. Run inference inside torch.inference_mode().
  5. Use the chat template and always set max_new_tokens.
  6. GPU work is asynchronous: warm up, synchronize, then read the clock.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.