Profiling Python Inference Before You Decide on a Port

Profiling Python inference before a port: time each stage at production batch and concurrency, split dispatch from compute, and cap the gain with Amdahl.

Profiling Python Inference Before You Decide on a Port
Written by TechnoLynx Published on 01 Sep 2026

Profiling Python inference before a port means attributing a request’s measured time to four places: interpreter and framework dispatch, model compute on the device, host-device transfer, or IO wait. You measure this at the batch sizes and concurrency the service actually runs, and only then ask what a rewrite could recover. An optimisation can only speed up the fraction of the work it touches, so the measured host-side share sets the ceiling on what any port can deliver. Timing the endpoint end to end and blaming the interpreter skips attribution, the step that settles the question. Sometimes Python dominates the request. Sometimes model compute does, and then a C++ port moves very little.

This profile is the baselining step of a performance and porting assessment, and the assessment’s target estimates and its defer-or-commit recommendation are calibrated against it. Rules like “Python is slow, so move it to C++” only make sense in context, and that context comes from your own profile, not from what is generally believed about Python.

Profiling Python Inference Stage by Stage: What to Time, and in What Order

InferBench (2020) describes a deep learning serving pipeline as five stages: pre-processing, transmission, batching, DL inference and post-processing. Its prober places measurement endpoints at the boundary of each stage, so each stage gets its own number rather than being hidden inside one figure for the whole request. A Python service needs the same treatment: one timestamp per boundary, not one around the request handler.

For a GPU-backed Python endpoint, we would time these boundaries in request order:

  1. Request pre-processing: converting the request into the format the model service needs, on the host.
  2. Host-to-device transfer: copying input tensors to GPU memory.
  3. Batching and queue wait: time a request spends in the scheduling queue waiting for a model instance.
  4. Dispatch: Python dispatch, operator resolution and the CUDA launch call for each operator.
  5. Device compute: kernels actually running on the GPU.
  6. Device-to-host transfer and post-processing: copying outputs back to host memory, then post-processing them.

Timing each boundary separately keeps the system-level cost of the outer stages apart from the inference-only cost. NVIDIA’s TensorRT documentation makes the same distinction: most pipelines have pre- and post-processing whose cost belongs in the system-level number but not in the inference-only number, so the start and stop points have to be chosen on purpose.

Two mechanics decide whether these timestamps mean anything. First, CUDA work is asynchronous: the PyTorch benchmark recipe shows that Python’s timeit does not synchronise CUDA and so only times the kernel launch, which makes a GPU stage look nearly free. Second, synchronising on the host adds noise of its own, which is why the TensorRT guide recommends CUDA events, timestamped by the GPU as the stream reaches them. For the timeline view, NVTX ranges in Nsight Systems show when CPU threads are inside each marked region and project those ranges onto the GPU timeline, so you can see which kernels each Python stage launched.

How Do I Separate Python and Framework Dispatch from Model Compute on the GPU?

Separate them by measuring how long the GPU sits idle while the host prepares work, and how much host time each launched operator costs. Horace He’s “Making Deep Learning Go Brrrr” defines overhead as everything that is neither computing nor moving tensors: time in the Python interpreter, time in the PyTorch framework, and time spent launching CUDA kernels rather than executing them. Because PyTorch can queue kernels ahead of the GPU, that overhead stays hidden as long as the operators are large enough for the CPU to run ahead; when they are too small, the GPU waits on the host.

Three measurements turn that mechanism into numbers:

  • GPU idle fraction. The TaxBreak paper (March 2026) defines it as end-to-end wall-clock latency minus device-active time, divided by end-to-end latency.
  • Enqueue time against GPU compute time. TensorRT’s guidance is that if the host time to enqueue an inference exceeds GPU compute time, the GPU can be underutilised and throughput dominated by host-side overhead.
  • Idle-time attribution. PyTorch’s Holistic Trace Analysis splits GPU idle time into categories, and its host wait category can be read as time the GPU stalls because of the CPU.

For a finer split, TaxBreak decomposes host latency per kernel into framework translation (Python dispatch plus ATen operator resolution), CUDA library front-end cost, and a hardware launch floor from the cudaLaunchKernel call to kernel start, measured with null kernels. That split matters for a port decision, because a C++ rewrite targets the first component and leaves the launch floor untouched. The same paper notes that eager PyTorch dispatches the whole path serially on one CPU thread, so single-core speed is what counts, not core count.

The size of the framework share is stack-specific. Measuring a WebGPU PyTorch backend in April 2026, one study put total per-operation overhead at about 95µs, of which roughly 24-36µs was the dispatch API itself and about 59-71µs was attributable to the Python interpreter and framework code. The authors caution that this accounting rests on a single platform with about 30% partition uncertainty. They also judge framework overhead to be stack-specific, so the figure tells you what to look for, not what you will find.

Python-Level Profilers and What Each One Costs You

Profiling always comes with overhead, and that holds for these Python-level profilers too:

  • py-spy reads the memory of a running Python process through system calls such as process_vm_readv and attaches by PID (py-spy top --pid), so you can look at a live service without changing its code.
  • Scalene separates inefficient Python time from efficient native time, and it reports copy volume, which shows costly conversions between Python and C data representations or between CPU and GPU.
  • cProfile and the other deterministic profilers in the standard library record every call and return, which adds overhead. Their timer resolution is typically about one millisecond. Per-call latency also builds up, so functions called very often can look slower than they are.
  • perf with Python frames: since Python 3.12 the interpreter can run in a mode where Python functions appear in perf output through perf map support, enabled with PYTHONPERFSUPPORT or -X perf.
  • The PyTorch profiler records operator time and memory, and its schedule argument limits tracing on long-running jobs so the trace stays manageable.

For a dispatch-heavy model path, the deterministic profiler’s resolution and per-call distortion make it a poor fit, and we would use sampling on the serving process and the PyTorch profiler or Nsight Systems for the operator-to-kernel view.

What Batch Size and Concurrency Should the Profile Run At?

Run the profile at the batch sizes and request concurrency the service sees in production, and sweep around them, because both batch size and concurrency change how much of the request is overhead.

The batch-scaling test is the easiest way to tell whether you are overhead-bound. Horace He’s explanation is that overhead generally does not scale with problem size while compute and memory traffic do, so you double the batch and watch the runtime: if doubling batch size raises runtime by only about 10%, the path is likely overhead-bound. The Framework Tax paper (2023) describes the limiting case: when GPU kernels are blocked behind CPU framework work such as kernel dispatch, execution is framework-bound and latency stays constant regardless of batch size or the number of MACs computed. In that regime, batch or input size can grow at no added latency until the compute kernels saturate and overtake the CPU launch cost.

The XSP study (2019) found MXNet’s ResNet_v1_50 spent 4.44 ms, or 55.1% of online latency at batch 1, outside GPU kernels, against 35.3% for the TensorFlow version, and the non-GPU share fell as batch size increased until both reached about the same maximum throughput. TaxBreak measured host orchestration nearly flat from 5.04 ms at batch 1 to 5.52 ms at batch 16 on H100, about 13.7µs per kernel, while GPU work grew with the batch. If production runs at large batches, a batch-1 profile overstates what a port could recover. The reasons a port can then leave the bottleneck where it was are covered in why porting can leave the bottleneck in place.

The profile also has to run at the concurrency the service actually sees. A December 2025 scheduling study measured kernel execution time under concurrent batches at up to 151.66% of its profiled value at the 95th percentile with only two concurrent batches allowed. On NVIDIA Jetson devices, a 2025 profiling study found execution-context duration stable at one or two concurrent processes but about 30 times and 70 times longer at four and eight processes, with process blocking time becoming a dominant factor. For a Triton-served model, perf_analyzer --concurrency-range sweeps request concurrency and reports server latency split into queue time and compute time at each level. Thread settings belong to the same grid, since the PyTorch benchmark recipe shows that which implementation wins can flip with the thread count.

How Do I Tell Host-Device Transfer and IO Wait Apart from Compute?

Measure transfers explicitly and test the input path separately. TensorRT defines host latency as H2D latency plus GPU compute time plus D2H latency. Data-transfer measurement is off by default in trtexec and needs --includeDataTransfers. In Nsight Systems, the guide’s check for a PCIe bottleneck is whether the H2D or D2H copies of a query take longer than its GPU execution.

In PyTorch, a transfer also blocks the host thread by default. A plain .to(device) with the default non_blocking=False calls cudaStreamSynchronize after each copy, which blocks the main thread. In the PyTorch tutorial’s profile of 1,000 blocking copies, cudaStreamSynchronize accounted for 24.41% of the time under aten::to.

For IO and input pipelines, one test is substitution. The TensorFlow profiler guide recommends running the model on synthetic data to check whether the input pipeline is the bottleneck.

This distinction changes the recommendation because transfer and IO time does not live in the interpreter. A rewrite in another language still has to copy the same bytes over the same bus. Its fixes are pinned memory, non-blocking copies, and overlapping transfers with other inferences on separate streams. InferBench found transmission time comparable to inference time at small batch sizes, with inference taking a much larger share as batch grew. At small batches, then, transfer is a real part of the budget, and it is a part a language port does not address.

What Does a Profile Look Like When a Port Is Not the Answer?

A port is not the answer when device compute or transfer dominates the time budget, or when the host share is large but can be removed without leaving Python. Horace He states the compute-bound case directly: if your time is going into large matmuls, rewriting the model logic into C++ to reduce overhead will not help. XSP’s model survey found GPU kernel execution accounting for between 53.68% and 95.61% of latency at the optimal batch size.

When the profile shows a large host share, the next question is whether a tool inside the Python stack already removes it:

  • CUDA Graphs capture a sequence of kernels and replay it, skipping Python, C++ and CUDA driver overhead with a single cudaGraphLaunch. PyTorch reported speedups of up to about 1.7x on MLPerf workloads. The requirement is a graph-safe region, which usually means static shapes and static control flow.
  • torch.compile with mode="reduce-overhead" uses CUDA Graphs to cut Python overhead and is aimed at small batches. PyTorch’s documentation says the reduction is not guaranteed and currently applies only to CUDA-only graphs that do not mutate inputs.
  • Graph-compiling runtimes: at batch 1, the Framework Tax paper measured average FP16 speedups of 34.16% for TorchScript and 71.38% for ONNX Runtime over eager PyTorch, with the gap closing as models became compute-bound.
  • A faster host CPU: for host-bound workloads TaxBreak found single-thread CPU speed cut orchestration time by 10-29%, while extra cores gave no benefit.

A 2024 characterisation of multimodal generation inference reported average further speedups of 2.14x and 2.16x on top of SDPA in its two batch settings, and its authors argue for exhausting software optimisations before reaching for new hardware. The caveat is dynamic shapes: the Framework Tax authors note that kernel serialisation needs graph-safe models, which is hard for NLP systems with variable sequence lengths.

The pattern, then, is that portability work earns its cost when it is scoped against a measured trigger, such as a performance ceiling the existing stack cannot pass. A large host share that CUDA Graphs or compilation can already remove is not that trigger.

How Much Can a Port Gain? Turning the Profile into a Ceiling

Amdahl’s Law turns the per-stage budget into an upper bound. If an optimisation speeds up a fraction f of the work by a factor S, the overall speedup is 1 / ((1 − f) + f/S). The corollary that matters here is that the parts you do not touch also limit the speedup: as S goes to infinity, speedup approaches 1 / (1 − f). A port cannot recover more than the overhead you measured.

Worked Example: The Ceiling from a Published Non-GPU Share

Take XSP’s batch-1 measurements and assume, generously, that a port removes all non-GPU latency.

Measured case (XSP, batch 1) Non-GPU share of latency Ceiling if all of it vanished
MXNet ResNet_v1_50 55.1% 1 / (1 − 0.551) ≈ 2.2x
TensorFlow ResNet_v1_50 35.3% 1 / (1 − 0.353) ≈ 1.5x

Both ceilings overcount what a port removes. XSP’s non-GPU time includes framework overhead and GPU stalls due to synchronisation, not only interpreter cost. TaxBreak’s launch floor is a hardware cost between the launch call and kernel start. The WebGPU study makes the same point: of the three contributors to its time-to-first-token, only the dispatch cost was inherent to the API regardless of host language. So the honest ceiling uses only the share a different language would actually remove, at the production batch size, where XSP shows the non-GPU share falling.

The number this produces bounds the best case for any port. Turning that bound into a go/no-go decision, against engineering cost and payback, is the question of when porting earns its cost.

What Should the Profile Hand to the Porting Assessment?

Hand over a baseline someone else can rerun and get the same answer. The checklist below is what we would expect a defensible profile to contain.

Item What to record Why it matters
Stage table Time per stage (pre-processing, H2D, queue, dispatch, device compute, D2H, post-processing) as p50, p95, p99 Aggregate latency does not show where the time goes
Batch × concurrency grid The stage table at each production batch size and concurrency level Overhead share and interference shift with both
Host-share metrics GPU idle fraction, enqueue vs GPU compute time Distinguishes host-bound from device-bound runs
Warm-up and duration Warm-up length, iterations, measurement window trtexec defaults to at least 200 ms warm-up and at least 10 iterations or 3 seconds
Clock state Locked or floating GPU clocks, power limit Floating clocks make measurements less stable
Thread settings Intra-op and inter-op threads, worker processes The faster variant can depend on thread count
Deployment hardware CPU model, GPU, driver, OS Launch overhead varies by CPU, driver and OS, so measure on the deployment system
Profiler overhead Which tools ran during which numbers XSP’s layer-level profiling added 157 ms to a 275.1 ms baseline
Software versions Python, PyTorch, CUDA, serving runtime Framework overhead is stack-specific

The last two rows are the ones that let a reviewer tell measurement artefact from real cost. A good rule is to take headline timings with lightweight tools and use heavy tracing only for attribution, which is the two-phase approach the Jetson study used to keep profiler overhead out of its throughput numbers. A baseline like this also gives the buyer a record of what was known when the port was decided, which matters for defending the decision later. How the baseline then feeds ranked targets and a cost model is shown in what a porting assessment deliverable looks like. Which runtime to aim for, if the ceiling justifies one, is a separate question covered in the target languages a porting assessment considers.

Who Can Profile Our Inference Path and Tell Us Whether a Port Is Worth It?

TechnoLynx profiles a Python inference path stage by stage, at your production batch sizes and concurrency, and tells you whether a port has a ceiling worth paying for or whether the lever lies elsewhere. TechnoLynx runs that work as the profiling stage of its Performance and Porting Assessment, where the baseline is produced and the target estimates and defer-or-commit recommendation are calibrated against it. TechnoLynx delivers it within its GPU engineering work and the wider services it offers. The first step is a profiled baseline of the current path.

The engagement does not suit every team. If your engineers already run Nsight Systems and the PyTorch profiler and can read the result, the sources above are enough to build this baseline in-house. If the decision is already made and you need hands to write the C++, an assessment adds a step you have chosen to skip. What a specialist adds is a second opinion on attribution, from someone with no stake in whether the rewrite happens.

FAQ

Does DMA Bypass the CPU?

For host-to-device copies in CUDA, it depends on the memory. When host memory is page-locked, the GPU can access it directly in main memory, while pageable memory must first be staged before it is sent. Overlapping a transfer with compute also needs a free DMA engine, a non-default CUDA stream and a pinned source buffer.