This document is relevant for: Inf2, Trn1, Trn2, Trn3
How to identify and reduce device-to-host transfer overhead#
A device-to-host (D2H) transfer copies a tensor from the device’s HBM back to host memory over PCIe. PyTorch issues one whenever Python needs a device value: .cpu(), .item(), .tolist(), print(tensor), int(tensor), or a comparison used in an if. Each of these also synchronizes: the host thread waits for every execution the tensor depends on, then waits for the copy, and the device sits idle until the host has launched the next execution.
This guide shows how to recognize that pattern in a Neuron Explorer system profile, how to measure what each copy costs, and how to remove the copies by reducing results on the device and copying back only what the host needs. For copies in the other direction, see the H2D guide. For data movement inside a device execution, see the DMA guide.
When to suspect device-to-host transfers#
Look for this bottleneck when:
A loop runs a compiled graph and then makes a decision on the host every iteration: picking the next token, checking a stopping condition, computing a metric, or logging a loss.
The main thread spends most of an iteration in
aten::to/aten::_to_copyoraten::item/aten::_local_scalar_dense, while the compiled region itself is short.A large output (logits, hidden states, an attention map) is copied back when the host only needs a scalar or a slice of it.
Results are copied back inside the loop (
losses.append(loss.item())) when they could be collected on the device and copied once after it.
The cost has two parts. The copy itself is proportional to the bytes moved: on the trn2.3xlarge used below, 39 MB takes about 9.8 ms from request to completion. The synchronization is paid even for 8 bytes: the host cannot queue the next execution until the value has arrived, so the device idles for the copy plus the host’s turnaround (here about 2 ms per iteration).
What a copy looks like in the system profile#
One x.cpu() produces events on three rows of the System Trace Viewer:
The main thread runs
aten::to→aten::_to_copy(for.item():aten::item→aten::_local_scalar_dense→aten::to). The block starts when the copy is requested and ends when the data is on the host, so it also covers any execution the tensor was still waiting for. The Neuron backend recordsneuron::copy::neuron_to_cpuon a framework thread.The Neuron Runtime row (
neuron_rt/.../NC0) showskbl_exec_waitwhile the host waits for the execution to finish, thennrta_tensor_read, the runtime call that reads the tensor out of HBM.The
device_to_host_transfersrow shows the data movement itself asio_xu_complete: the DMA from HBM into host memory, with its size, direction and achieved bandwidth in Event Details.
The transfer bandwidth row (NC:0/device_to_host/transfer_bandwidth) plots the PCIe bandwidth these copies used over time. The events are linked: clicking an io_xu_complete draws an arrow to the nrta_tensor_read that requested it, and the Dependency Chain Viewer lists that event as its upstream; clicking the nrta_tensor_read in turn lists the neuron::copy::neuron_to_cpu framework op on the backend thread (see Linking Transfers to Framework Operations in the System Trace Viewer overview).
Capture a system profile#
Capture with torch.profiler.profile and a NeuronConfig in RUNTIME mode, as described in Capture PyTorch profiles. ProfileMode.RUNTIME records the Neuron Runtime events, including the transfer events, and ProfilerActivity.PrivateUse1 adds them to the trace next to the CPU ops. The schedule runs the loop three times and records only the third run, so compilation and first-time allocation are not in the profile. Wrap each iteration in torch.profiler.record_function so the profile has a labeled block per iteration:
import torch
from torch.profiler import ProfilerActivity, profile, record_function
from torch_neuronx.profiling import NeuronConfig, NeuronProfiler, ProfileMode
config = NeuronConfig(modes=[ProfileMode.RUNTIME], profile_output_dir="./profiles/baseline", capture_enabled_for_nc="0")
with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.PrivateUse1],
experimental_config=config, on_trace_ready=NeuronProfiler(config).export_trace,
schedule=torch.profiler.schedule(wait=1, warmup=1, active=1)) as prof:
for _ in range(3):
generate(prompt) # the loop under test; each token is inside record_function(f"token {i}")
torch.neuron.synchronize()
prof.step()
print(prof.key_averages().table(sort_by="cpu_time_total", row_limit=12))
The record_function labels appear on the main thread row in Neuron Explorer and as rows in prof.key_averages(), so the same profile can be read with PyTorch’s own tools. For the other modes and parameters, see Capture PyTorch profiles with Neuron Explorer.
Open the profile in Neuron Explorer#
The profile directory holds the PyTorch trace (trace.json) and the runtime trace (ntrace.pb). Serve it:
neuron-explorer view -d ./profiles/baseline
Open the profile and the System Timeline. The rows, grouped by instance and process:
Row |
What it shows |
|---|---|
|
The profiler session: |
|
Your Python code: |
other |
Backend threads: |
|
The same backend work grouped by device stream. |
|
Neuron Runtime calls for NeuronCore 0: |
|
|
|
The transfer events track: one |
|
The same for H2D copies. |
|
The transfer bandwidth tracks: PCIe bandwidth used by each direction over time. |
Find the bottleneck, step by step#
Pin the rows that matter. In the System Trace Viewer, hover over a row name and click the pin icon that appears next to it. Pin the two
neuron_hwrows,neuron_rt/.../NC0anddevice_to_host_transfers; pinned rows stay at the top while you scroll through the framework threads.Find the idle time. Zoom to two or three iterations (the
record_functionlabels on the main thread mark them). Compare the width of each label with thenc_exec_runningblock inside it. The difference is time the device is not computing.See what fills it. Read the main thread between two executions. An
aten::to/aten::_to_copy(oraten::item) block that starts before the execution ends and runs on past it, withnrta_tensor_readon the runtime row andio_xu_completeondevice_to_host_transfersin the same span, means the host is waiting for data from the device. If that wait takes most of the gap, this guide applies.Measure one copy. Hover over the
io_xu_completeblock to read its duration; click it and open Event Details forsize,transfer_directionandbandwidth_bytes_per_sec. The click also draws an arrow to thenrta_tensor_readon theneuron_rtrow that requested the copy; the Dependency Chain Viewer lists it, and clicking it there leads on to theneuron::copy::neuron_to_cpuop. Read the time from the start ofnrta_tensor_readto the end ofio_xu_completeas the cost of the copy.Count the copies. In the Search widget, set the field to
name, enterio_xu_completeand choose Submit. Every transfer in the profile is listed with itssizeandtransfer_direction, and Focus jumps the timeline to it. Or read the# of Callscolumn ofneuron::copy::neuron_to_cpuinprof.key_averages(). A large copy on every iteration of a loop is the pattern to remove.
Example: a generation loop#
A greedy generation loop on Qwen3-0.6B running on a trn2.3xlarge. The forward pass is compiled once and runs on a fixed-size buffer of 128 tokens:
import torch
from torch.profiler import record_function
from transformers import AutoModelForCausalLM, AutoTokenizer
device = torch.device("neuron")
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-0.6B", dtype=torch.bfloat16).to(device).eval()
prompt = tokenizer("Explain what a KV cache is in two sentences.").input_ids
L, NEW_TOKENS = 128, 32 # a fixed-size token buffer keeps one compiled graph
@torch.compile(backend="neuron", fullgraph=True)
def forward(buf):
return model(input_ids=buf, use_cache=False).logits # [1, 128, vocab]
Profile 1: Baseline#
generate() copies the logits to the host and picks the next token there:
def generate(prompt):
tokens = list(prompt)
for i in range(NEW_TOKENS):
with record_function(f"token {i}"): # labels the iteration in the profile
buf = torch.tensor([tokens + [0] * (L - len(tokens))]).to(device)
logits = forward(buf).cpu() # 39 MB of logits to the host, every token
tokens.append(int(logits[0, len(tokens) - 1].argmax())) # next token picked on the host
return tokenizer.decode(tokens[len(prompt):])
32 tokens: 710 ms (22.2 ms per token).
What the profile shows#
The whole recorded step (ProfilerStep#2, 736 ms) in the System Trace Viewer, with four rows pinned to the top: neuron_hw/.../NC0:4, neuron_hw/.../NC0:5, neuron_rt/.../NC0 and device_to_host_transfers. Below them are the first two framework rows, TID:0 (the profiler session) and TID:13 (the main thread):
Reading the rows from the top:
Pinned rows
neuron_hw/.../NC0:4andNC0:5: 32 pinknc_exec_runningblocks, one per token, 8.3 ms each, 23 ms apart. Together they are 266 ms of the 736 ms step: the device is computing 36% of the time.Pinned row
neuron_rt/.../NC0: after each execution, a bluekbl_exec_wait(the host waiting for the execution) followed by a greennrta_tensor_read(the runtime reading a tensor out of HBM).Pinned row
device_to_host_transfers: one purpleio_xu_completeper token, 32 in all, each at the end of anrta_tensor_read.Main thread
framework/TID:13: the 32 colored bars labeledtoken 0…token 31are therecord_function(f"token {i}")labels from the code, about 23 ms each. The longaten::tobar under each one isforward(buf).cpu().
How we identified the bottleneck#
Where is the device idle? In the image above, each 23 ms
token Nbar contains one 8.3 msnc_exec_runningblock. For the other 14 ms of every token the twoneuron_hwrows are empty, and the pinnedneuron_rtand transfer rows show what the device is waiting for: anrta_tensor_readand anio_xu_complete.What fills the gap? Zoom to one token (
token 16, a 25 ms window). The tooltip in the image is the hover over theio_xu_completeon the pinned transfer row:
Left to right on the main thread row, under the
token 16bar:Block
Duration
What it is
aten::to(aten::_to_copyunder it)18.7 ms
forward(buf).cpu(). It starts when the copy is requested, spans the 8.3 ms execution (the copy has to wait for the logits), then the 7.4 msnrta_tensor_readand the 2.6 msio_xu_completeon the pinned rows.aten::argmax0.6 ms
picking the next token on the host
TorchDynamo Cache Lookup,Torch-Compiled Region(start of the nexttokenbar)2.5 ms
the next
forwardcall; the nextnc_exec_runningblock starts hereOf the 23 ms token, 18.7 ms is the host waiting in
.cpu(): 8.3 ms for the execution it depends on and about 10 ms for the copy.How big is the copy? Click the
io_xu_completeblock and open the Event Details tab in the bottom panel:
sizeis 38,895,616 bytes: 128 positions × 151,936 vocabulary entries × 2 bytes, the whole logits tensor, of which the host reads one row.duration_ns(2.59 ms) andbandwidth_bytes_per_sec(15.0 GB/s) cover the completion event only; the copy as the host experiences it runs from the start ofnrta_tensor_readto the end ofio_xu_complete, 9.8 ms. Clicking the event also draws an arrow to thatnrta_tensor_readon theneuron_rtrow; the Dependency Chain Viewer tab lists it as the upstream event, and clicking it there lists theneuron::copy::neuron_to_cpuop on the backend thread, which is what theaten::toon the main thread is waiting for.How often? In the Search widget, searching field
nameforio_xu_completelists every transfer in the profile with itssizeandtransfer_direction: 32 of 38.9 MB in the step, one per token. The copies account for about 310 ms of the 736 ms step; the executions for 266 ms.
The same numbers from PyTorch’s own report, prof.key_averages().table(sort_by="cpu_time_total") (excerpt):
Name CPU total # of Calls
ProfilerStep* 735.622ms 1
aten::to 599.922ms 96
aten::_to_copy 599.611ms 64
neuron::copy::neuron_to_cpu 316.152ms 64
model_default 274.692ms 64
token 16 24.516ms 1
token 25 24.394ms 1
aten::to takes 81% of the step: 32 copies of the logits, each also waiting for its execution, plus the 32 small copies of buf to the device.
Profile 2: Keep the result on the device#
The loop only needs the token id. Compute it inside the compiled function and copy back only that:
@torch.compile(backend="neuron", fullgraph=True)
def forward(buf):
return model(input_ids=buf, use_cache=False).logits.argmax(dim=-1) # changed: token ids, on the device
def generate(prompt):
tokens = list(prompt)
for i in range(NEW_TOKENS):
with record_function(f"token {i}"):
buf = torch.tensor([tokens + [0] * (L - len(tokens))]).to(device)
next_ids = forward(buf) # changed: no .cpu() of the logits
tokens.append(int(next_ids[0, len(tokens) - 1])) # changed: 8 bytes back
return tokenizer.decode(tokens[len(prompt):])
32 tokens: 378 ms (11.8 ms per token), 1.9x faster.
Why this works#
The host still needs one value per token, so one synchronization per token stays. What changes is how much data that synchronization carries:
The copy shrinks from 39 MB to 8 bytes.
argmaxruns on the device, inside the compiled graph, and the only tensor the host reads is oneint64per position. On the pinned rows,nrta_tensor_readtakes 11 µs andio_xu_complete1 to 1.5 µs instead of 7.4 ms and 2.4 ms.The execution grows by 1.1 ms (8.3 → 9.4 ms): the
argmaxover 128 × 151,936 logits is now device work. That is the price for removing 9.8 ms of copy per token.The host’s share of each token drops to the dispatch.
aten::itemon the main thread now spans only the execution it waits for (10.2 ms) and the 8-byte read; the rest of thetokenlabel is 1.1 ms ofTorchDynamo Cache LookupandTorch-Compiled Region.
One token, same pinned rows, hovering the token-id copy on device_to_host_transfers: io_xu_complete, 969 ns. kbl_exec_wait on the runtime row still spans the execution, but the nrta_tensor_read that follows it has shrunk from 7.4 ms to 11 µs:
Three tokens of the recorded step, same pinned rows. The nc_exec_running blocks follow each other with 2 ms gaps, and the transfer row shows only the tiny token-id copies:
What improved#
Profile 1: Baseline |
Profile 2: result on the device |
Change |
|
|---|---|---|---|
Copied to the host per token |
39 MB of logits |
8 bytes (one token id) |
|
Time for 32 tokens (host-timed, median of 3) |
710 ms |
378 ms |
1.9x |
Per token |
22.2 ms |
11.8 ms |
|
Device execution per token ( |
8.3 ms |
9.4 ms |
+1.1 ms ( |
Device idle between executions |
14.4 ms |
2.1 ms |
|
Device busy during the step |
36% |
82% |
Both versions generate the same tokens. Reduce on the device first (argmax, top-k, sum, mean), and copy back only what the host needs. If the host needs results from every iteration, keep them on the device and copy them once after the loop.
Do this with an agent#
The readback in Profile 1 is one of the cases the Neuron Agentic Development Profile Analysis skill checks for (see Getting Started to install the skills). The skill is written for captures of a vLLM Neuron server, but this check is a query on the SystemProfileEvents table, which every system profile has:
Skill |
What it does |
|---|---|
|
Analyzes a capture starting from the system trace (deep dive). Its session analysis measures the gaps between executions, and its host-side readback check reads the size and count of the runtime’s tensor-read events to find a tensor that is copied back whole when the host only needs a reduction of it: the pattern in Profile 1. The agent, |
|
Captures the profile when the workload is a vLLM Neuron server (deep dive). For a workload like the one in this guide, capture as shown above and point the agent at the output directory. |
A prompt for Profile 1:
Analyze the system profile in ./profiles/baseline. The device is idle between executions;
check whether a device-to-host readback is the cause. For the longest ProfilerStep, report
the device busy share, then list the nrta_tensor_read and io_xu_complete events grouped
by size, with count, average and total duration, and which main-thread aten op under
each "token N" label waits for them.
After the fix:
Do the same for ./profiles/fixed and compare the two profiles: device busy share, bytes
copied back per token, and the duration of the "token N" labels.
The two queries behind those numbers, on SystemProfileEvents, both scoped to the recorded step through its ProfilerStep#2 event. The first counts the executions on one of the two neuron_hw rows (pcore_idx 4), skipping the sub-millisecond helper graphs; the second is the readback check. (If you send them to the databaseExplorerQuery endpoint the querying skill uses, put each statement on one line.)
SELECT COUNT(*) AS n_exec, ROUND(AVG(e.duration_ns) / 1e6, 1) AS avg_ms,
ROUND(100.0 * SUM(e.duration_ns) / MAX(step.duration_ns), 1) AS busy_pct
FROM SystemProfileEvents AS e,
(SELECT start_ts, end_ts, duration_ns FROM SystemProfileEvents
WHERE name LIKE 'ProfilerStep#2%') AS step
WHERE e.name = 'nc_exec_running' AND e.pcore_idx = 4 AND e.duration_ns > 1000000
AND e.start_ts >= step.start_ts AND e.end_ts <= step.end_ts;
-- Profile 1: 32 executions, 8.3 ms each, busy_pct 36.2
-- Profile 2: 32 executions, 9.4 ms each, busy_pct 81.6
SELECT e.name, json_extract(e.extra_attributes_json, '$.size') AS size_bytes,
COUNT(*) AS n, ROUND(AVG(e.duration_ns) / 1e6, 2) AS avg_ms,
ROUND(SUM(e.duration_ns) / 1e6, 1) AS total_ms
FROM SystemProfileEvents AS e,
(SELECT start_ts, end_ts FROM SystemProfileEvents
WHERE name LIKE 'ProfilerStep#2%') AS step
WHERE e.name IN ('nrta_tensor_read', 'io_xu_complete')
AND e.start_ts >= step.start_ts AND e.end_ts <= step.end_ts
GROUP BY 1, 2 ORDER BY total_ms DESC;
-- Profile 1: nrta_tensor_read, 38895616 B, 32 events, 7.52 ms each, 240.7 ms in total
-- io_xu_complete, 38895616 B, 32 events, 2.29 ms each, 73.2 ms in total
-- Profile 2: both events 8 B x 32, under 0.5 ms in total
One event name to watch: the skill’s reference query filters on nrt_tensor_read, the event of the runtime’s synchronous copy path. The copies in this guide go through the asynchronous path and appear as nrta_tensor_read, as in the query above, so a query on the synchronous name finds none of them (see “Different event names” under Common issues).
Common issues#
device_to_host_transfersis emptyMake sure
ProfileMode.RUNTIMEis inNeuronConfig(modes=...)andProfilerActivity.PrivateUse1is inactivities.- Different event names
A copy made through the runtime’s synchronous path appears as
nrt_tensor_readon theneuron_rtrow anddmem_buf_copyouton the transfer row, instead ofnrta_tensor_readandio_xu_complete. A profile can show both paths; the large copies this guide is about use the asynchronous one. The analysis is the same.