Pidoku

CPU and Python Profiling

Module 22 Lesson 22.i 1h Difficulty 3/5

Prerequisites 3.k, 22.h


Before you start: words you need#

WordPlain meaning
Sampling profilerA tool that looks at what a program is doing many times a second and counts where it was. Low overhead; no code changes (3.k).
Instrumenting profilerA tool that records every function call (like cProfile). Exact counts, large slowdown.
Flame graphA picture of sampled stacks: width is time, height is call depth (3.k).
On-CPU / off-CPUTime a thread spends running on a core, versus time it spends blocked (waiting for the GPU, a lock, the network).
GILPython’s global interpreter lock: only one thread runs Python bytecode at a time (3.e).
Engine coreThe process that runs the scheduler and drives the GPU workers; in vLLM it is separate from the API server (16.d).
IPCInstructions per cycle: how much useful work a CPU core does each clock tick.

1. What is it?#

Finding where the CPU time goes in an inference server, and where its threads wait. A large share of inference performance problems are on the CPU:

CPU work in an inference server
  HTTP parsing, JSON decoding and encoding       (API server)
  chat templates, tokenizing, detokenizing       (API server)
  image and audio preprocessing                  (API server)
  scheduling and KV block bookkeeping, per step  (engine core)
  building input tensors, per step               (engine core / workers)
  structured-output grammar masks, per step      (engine core)
  kernel launches when graphs are not used       (workers)
  streaming each token to each client            (API server)

When this work is on the critical path, the GPU waits. Lesson 22.h’s “GPU busy below 70%” is the usual sign; this lesson finds the cause. Tool versions below: py-spy 0.4.3, Python 3.15.0. Facts checked on 13 November 2026.


2. Why does it matter?#

Because the GPU is only as fast as the CPU that feeds it. At large batch the per-step Python work grows with the number of requests: preparing inputs for 256 sequences can take milliseconds of a 10–15 ms step. At batch 1 on a small model, launch and scheduling overhead can be most of the step. And none of it shows up in a GPU profiler except as gaps.

Engines have moved much of this off the critical path (separate API and engine processes, asynchronous scheduling that plans step n+1 while step n runs (17.d), CUDA graphs), but custom code, new features and misconfiguration put it back.


3. Simple analogy#

A pit crew and a race car. The car (GPU) is fast, but it can only leave when the crew (CPU) has finished. Timing the car’s laps tells you nothing about a slow tyre change. You have to watch the crew: who is working (on-CPU), who is standing waiting for a tool someone else holds (off-CPU, lock contention), and which job takes longest (the widest bar in the flame graph).


4. Tiny example: one command on a live server#

Shell
py-spy top --pid $(pgrep -f "EngineCore" | head -1)
  %Own   %Total  OwnTime  TotalTime  Function (filename)
 31.0%   31.0%    9.30s     9.30s   _apply_grammar_mask (structured_output.py)
 12.0%   48.0%    3.60s    14.40s   schedule (scheduler.py)
  8.0%    8.0%    2.40s     2.40s   wait (threading.py)
  ...

(Illustrative output.) A third of the engine core’s CPU time goes to structured-output masks: this deployment’s JSON-mode traffic is CPU-bound in the engine core, whatever the GPU is doing. No restart and no code change were needed to see it.


5. Technical explanation#

The tools#

py-spy                 Sampling profiler for Python. Attaches to a running process by PID, no
                       restart, low overhead. Latest 0.4.3 (2 November 2026).
profiling.sampling     The standard-library sampling profiler ("Tachyon"), new in Python 3.15
                       (9 October 2026). Attaches by PID; the profiler and target must run the
                       same Python minor version.
perf                   Linux system-wide sampler. Sees C, C++, CUDA driver and kernel time.
                       Since Python 3.12 it can also show Python function names (below).
nsys --python-sampling Python stacks inside the GPU timeline (22.h), to tie a gap to a function.
torch.profiler         PyTorch operators with CPU and GPU time.
cProfile               Instrumenting; large slowdown. Development only.
bpftrace / eBPF        Custom low-overhead measurements in production (3.k).

py-spy recipes#

Shell
# What is every thread doing right now? (a hang, a stall)
py-spy dump --pid <pid> --locals

# Live, top-like view
py-spy top --pid <pid>

# A 60-second flame graph, including time spent waiting
py-spy record -o engine.svg --pid <pid> --duration 60 --idle

# Include native frames (PyTorch C++, CUDA driver calls)
py-spy record -o engine.svg --pid <pid> --duration 60 --native

# Follow child processes (API server, engine core, workers)
py-spy record -o all.svg --pid <api_server_pid> --subprocesses --duration 30
  • --idle includes samples of threads that are not running. By default py-spy shows only on-CPU time. Much of a server’s wall time is waiting, and that is often where the answer is.
  • --native shows time inside C and C++ code. Without it, a long PyTorch call appears as one opaque Python line.
  • --gil shows only samples where the thread holds the GIL: what actually runs Python.
  • Attaching to another process needs permission: root, or CAP_SYS_PTRACE in a container.

The standard-library equivalent on Python 3.15:

Shell
python -m profiling.sampling attach <pid>                         # summary of a running process
python -m profiling.sampling attach --flamegraph -o engine.html <pid>
python -m profiling.sampling run --mode=gil script.py             # only samples holding the GIL

Reading a flame graph#

Width = time. Height = call depth. Look for WIDE plateaus, not tall towers.

     ┌───────────────────────────────────────────────────────┐
     │                    engine step                         │
     ├──────────────┬─────────────────┬──────────────────────┤
     │ schedule     │  prepare_inputs │   execute_model      │
     ├──────┬───────┼──────┬──────────┼──────────────────────┤
     │alloc │append │build │ torch.   │  cudaGraphLaunch     │
     │_slots│_slots │lists │ tensor() │                      │
     └──────┴───────┴──────┴──────────┴──────────────────────┘

Common wide plateaus in inference servers:

torch.tensor(python_list)        building tensors from Python lists each step.
                                 Preallocate (pinned) buffers and fill in place.
per-request Python loops         at batch 256 they add up. Use flat arrays (NumPy).
json.dumps / json.loads          use orjson or msgspec in hot paths.
tokenizer calls                  check the fast (Rust) tokenizer is in use.
logging with f-strings           f-strings are built even when the level filters the
                                 message out. Use lazy %-style formatting.
grammar masks                    structured output costs CPU per step per request.

Off-CPU time: what threads wait on#

cudaStreamSynchronize / cudaEventSynchronize   waiting for the GPU: normal if brief and once per step
epoll_wait                                      waiting for requests: normal
futex                                           waiting for a lock: investigate if large
read / write / sendmsg                          network or IPC
zmq / socket polling                            messages between API server and engine core

A large futex share means lock contention: several threads fighting over one data structure. py-spy dump during a slow moment shows which threads hold or wait for what.

The GIL#

✓ Rust tokenizers, CUDA calls and I/O release the GIL: threads help for them.
✗ Python bookkeeping (scheduling, request objects) does not run in parallel on threads.
✗ A CPU-heavy Python callback on the engine's thread blocks the engine.

→ separate processes for API and engine (vLLM does this), and more API server processes when
  tokenizing or preprocessing is the bottleneck (`--api-server-count`, 19.d)
→ keep the engine loop's Python work small

Python 3.14 made the free-threaded (no-GIL) build officially supported, but engines and their dependencies still mostly run on the standard build; check before assuming.

perf for the native side#

Shell
perf record -F 99 -g -p <pid> -- sleep 30
perf report --stdio --sort=dso,symbol | head -40

# With Python names in the stacks (Python 3.12+; start the process with it)
PYTHONPERFSUPPORT=1 python serve.py      # or: python -X perf serve.py
# Python 3.13+: -X perf_jit uses DWARF unwinding instead (needs perf 6.8 or later)

# Python 3.15 is built with frame pointers by default (PEP 831), so perf -g can walk
# through the interpreter's C frames without DWARF. Native extensions must keep frame
# pointers too, or the chain breaks at them.

# Hardware counters: what kind of CPU work is it?
perf stat -e cycles,instructions,cache-misses,branch-misses -p <pid> -- sleep 10
IPC below 1 with many cache misses    pointer chasing: Python objects, dictionaries
IPC below 1 with many branch misses   branchy code: interpreter loops, tokenizer
IPC above ~2.5                        tight numeric code

A Python-heavy engine process typically shows IPC around 1. Much lower suggests a pathologically cache-hostile hot path.


6. Under the hood: how a sampling profiler sees Python#

  • py-spy and Tachyon read the target’s memory from outside. They find the interpreter’s thread states and walk each thread’s Python frame list, many times a second. The target runs normally between samples, which is why overhead is low and no restart is needed. It is also why they need ptrace-level permission and must understand the exact Python version’s data layout.
  • perf samples the CPU’s instruction pointer. It sees C functions natively. Python functions are all the same interpreter loop to it, unless the interpreter inserts a small trampoline per Python function (-X perf) or emits DWARF unwind information (-X perf_jit), which is what the 3.12+ support does.
  • Off-CPU samples are thread states. --idle keeps samples of threads blocked in a system call. The blocking call’s name (futex, epoll_wait) tells you what they wait on.
  • Sampling estimates, it does not count. At 100 samples a second over 60 seconds you have 6,000 samples; a function at 1% is about 60 of them. Rare, short events need longer recordings or tracing.

7. Performance implications#

  • Engine-loop CPU cost grows with batch. Profile at the batch you run in production, not at batch 1.
  • CPU-bound engines show flat throughput as concurrency rises while GPU busy stays below 90%. More GPU will not help; less Python per step, a dedicated core, or more engine processes will.
  • CPU per GPU matters. Plan 8–16 cores per GPU for LLM serving (3.a), more for agents and heavy preprocessing; check the container is not CPU-throttled (3.j).
  • Profilers cost something. py-spy and Tachyon are usually a few per cent; cProfile can double run time and changes what you measure.

8. Production implications#

  • Ship py-spy in the production image (or use Python 3.15’s built-in profiler). Installing tools during an incident wastes the incident.
  • Allow attachment. Grant CAP_SYS_PTRACE to the debug container, or plan an ephemeral debug container that shares the process namespace.
  • Run continuous profiling (Grafana Pyroscope, Parca) so you have a profile from before the incident to compare with.
  • Profile the API server and the engine core separately. They have different bottlenecks.
  • Never leave cProfile enabled in production.

9. Common mistakes#

  1. Profiling without --idle and missing where the server actually waits.
  2. Using cProfile on a server. It changes what you are measuring.
  3. Assuming the GPU is the bottleneck. For small models and small batches it often is not.
  4. Profiling at batch 1 when production runs at batch 128.
  5. Profiling only the API process and missing the engine core, or the reverse.
  6. Ignoring lock contention.
  7. Optimising a wide plateau on a background thread that is not on the critical path.

10. Hands-on exercise#

  1. Learn py-spy. On a running vLLM server, run dump, top and record --idle --native on the API server and the engine core. Identify the engine loop thread and where its time goes.
  2. The CPU/GPU split. For decode at batch 1, 32 and 256, measure GPU busy % (22.h) and engine-core CPU time per step. At which batch does the CPU become significant?
  3. Structured output. Send 50% JSON-schema requests. How does the engine core’s flame graph change? Does throughput drop?
  4. GIL contention. Add a CPU-heavy Python callback to a decode loop. Measure the ITL impact; confirm with py-spy record --gil.
  5. Python names in perf. Start a script with -X perf and record it with perf record. Do Python function names appear in perf report?

11. Interview questions#

  1. Why does CPU profiling matter for a GPU workload?
  2. What does py-spy --idle show that the default does not, and why does it matter for servers?
  3. How do you tell whether an inference step is CPU-bound or GPU-bound?
  4. What is GIL contention and how would you detect it in a running server?
  5. Why does the engine loop’s CPU cost grow with batch size?
  6. How do you profile a production Python server without restarting it?
  7. How does perf show Python function names on Python 3.12 and later?

12. Further reading#

Checked on 13 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in