This document is relevant for: Inf2, Trn1, Trn2, Trn3
How to identify and reduce host-to-device transfer overhead#
A host-to-device (H2D) transfer copies a tensor from host memory to the device’s HBM over PCIe. PyTorch issues one every time a CPU tensor is moved to the Neuron device: x.to(device), torch.tensor(data, device=device), or an operation that mixes a CPU tensor with a device tensor. The device cannot start an execution until the tensors it reads have arrived, so a copy on the critical path shows up as time when the device is idle.
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 allocating buffers on the device once and updating them in place. For copies in the other direction, see the D2H guide. For data movement inside a device execution, see the DMA guide.
When to suspect host-to-device transfers#
Look for this bottleneck when:
An iteration takes much longer than the device execution inside it. The device profile of one execution looks fine, but the end-to-end step time does not add up.
The main thread spends its time in
aten::to,aten::_to_copy, oraten::copy_rather than in the compiled region.The loop builds inputs on the host every iteration: tokenizer output, masks, position ids, or a cache that is kept as a CPU tensor and copied over before each call.
A tensor that the loop reads and writes is grown with
torch.cator rebuilt on the host each iteration, so the copy gets bigger every step.Inputs come from a data loader or NumPy and are moved with
.to(device)inside the training or inference step instead of ahead of it.
The cost is proportional to bytes copied per iteration. On the trn2.3xlarge used below, a 117 MB copy takes about 7.5 ms (15.6 GB/s); every megabyte copied on the critical path costs about 65 µs of idle device time. For an execution of a few milliseconds, a copy of tens of megabytes per iteration is the bottleneck.
What a copy looks like in the system profile#
One x.to(device) produces events on three rows of the System Trace Viewer:
The main thread runs
aten::to→aten::_to_copy; the Neuron backend recordsneuron::copy::cpu_to_neuronon a framework thread. The copy from a regular (pageable) CPU tensor is synchronous:aten::_to_copydoes not return until the data is on the device.The Neuron Runtime row (
neuron_rt/.../NC0) shows the runtime call that registers the copy,nrta_tensor_write.The
host_to_device_transfersrow shows the data movement itself asio_xu_complete: the DMA from host memory into HBM, with its size, direction and achieved bandwidth in Event Details.
The transfer bandwidth row (NC:0/host_to_device/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_write that requested it, and the Dependency Chain Viewer lists that event as its upstream; clicking the nrta_tensor_write in turn lists the neuron::copy::cpu_to_neuron 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 workload 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):
prefill(doc) # the loop under test; each chunk is inside record_function(f"chunk {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 D2H 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 andhost_to_device_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.
aten::to/aten::_to_copyblocks that line up withio_xu_completeblocks onhost_to_device_transfersmean the host is copying inputs to the device. If the copies take most of the gap, this guide applies.Measure one copy. Hover over an
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_writeon theneuron_rtrow that requested the copy; the Dependency Chain Viewer lists it, and clicking it there leads on to theneuron::copy::cpu_to_neuronop. Theaten::toon the main thread is the block directly above the copy in time.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::cpu_to_neuroninprof.key_averages(). A copy of the same size on every iteration, or one that grows each iteration, is the pattern to remove.
Example: prefill a long document with a KV cache#
Qwen3-0.6B on a trn2.3xlarge reads a 2048-token document in 128-token chunks. Each chunk attends to the keys and values (KV cache) of all earlier chunks, so the cache grows by 128 slots per chunk. step() runs one chunk; it is compiled once and takes the cache as a fixed-size input of 2048 slots:
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()
L, T = 2048, 128 # cache slots (document length), tokens per chunk
cfg = model.config
SHAPE = (cfg.num_hidden_layers, 1, cfg.num_key_value_heads, L, cfg.head_dim) # [28, 1, 8, 2048, 128]
@torch.compile(backend="neuron", fullgraph=True)
def step(chunk, pos, bias, k, v):
... # one chunk through the model; returns next-token ids and this chunk's keys and values
Profile 1: Baseline#
prefill() keeps the cache on the host and grows it with torch.cat. Every chunk, it pads the cache to 2048 slots and copies all of it to the device:
def prefill(doc):
ids = torch.tensor([doc], device=device)
bias = torch.full((1, 1, 1, 1, L), float("-inf"), dtype=torch.bfloat16, device=device)
pos = torch.arange(T, device=device).view(1, T)
k = torch.zeros(*SHAPE[:3], 0, SHAPE[4], dtype=torch.bfloat16, device="cpu") # cache on the host, starts empty
v = torch.zeros_like(k)
preds = []
for n in range(0, L, T):
with record_function(f"chunk {n // T}"): # labels the chunk in the profile
pad = torch.zeros(*SHAPE[:3], L - n, SHAPE[4], dtype=torch.bfloat16, device="cpu")
next_ids, new_k, new_v = step(ids[:, n:n + T].clone(), pos, bias,
torch.cat([k, pad], dim=3).to(device), # whole cache copied, every chunk
torch.cat([v, pad], dim=3).to(device))
k = torch.cat([k, new_k.cpu()], dim=3) # new host tensor, one chunk bigger
v = torch.cat([v, new_v.cpu()], dim=3)
bias[..., n:n + T] = 0
pos += T
preds.append(next_ids)
return torch.cat(preds, dim=1)[0].tolist()
2048 tokens: 1,264 ms (79 ms per chunk).
What the profile shows#
The whole recorded step (ProfilerStep#2, 1,222 ms) in the System Trace Viewer, with three rows pinned to the top: neuron_hw/.../NC0:4, neuron_hw/.../NC0:5 and host_to_device_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: sixteen pinknc_exec_runningblocks, one per chunk, 8.8 ms each. Together they are 141 ms of the 1,222 ms step. The device is computing 11% of the time.Pinned row
host_to_device_transfers: two purpleio_xu_completeblocks before every execution, 32 in all. Each is a copy from host memory into HBM.Main thread
framework/TID:13: the sixteen colored bars labeledchunk 0…chunk 15are therecord_function(f"chunk {n // T}")labels from the code; each is about 77 ms wide. The rows of short blocks under each bar are theaten::ops that chunk ran on the host.
How we identified the bottleneck#
Where is the device idle? In the image above, each 77 ms
chunk Nbar contains one 8.8 msnc_exec_runningblock. For the other 68 ms of every chunk the twoneuron_hwrows are empty: the device is waiting for the host.What fills the gap? Zoom to one chunk (
chunk 8, a 78 ms window). The main thread row now shows each op as its own block; the tooltip in the image is the hover over the firstio_xu_completeon the pinned transfer row:
Left to right on the main thread row, under the
chunk 8bar:Block
Duration
What it is
aten::zeros(withaten::zero_,aten::fill_stacked under it)4.7 ms
pad: the zero padding to 2048 slots, built on the hostaten::cat11.0 ms
torch.cat([k, pad]): the padded key cache, built on the hostaten::to(aten::_to_copyunder it)8.9 ms
.to(device)of the keys. The firstio_xu_completeon the pinned transfer row sits directly under this block.aten::cat9.6 ms
the padded value cache
aten::to(aten::_to_copy)8.8 ms
.to(device)of the values: the secondio_xu_completeTorchDynamo Cache Lookup,Torch-Compiled Region(the small blocks)2.2 ms
the
step()call. Thenc_exec_runningblock on the pinnedneuron_hwrows starts here, only after both copies have landed.aten::to(aten::_to_copy)10.4 ms
new_k.cpu(): waits for the execution to finish, then copies the new keys backaten::cat,aten::to,aten::cat5.0, 0.6, 5.2 ms
appending the new keys and values to the host cache
The two
.to(device)blocks and the twotorch.catblocks that feed them take 38 ms of the 77 ms chunk; the execution cannot start until they are done.How big is each copy? Click the first
io_xu_completeblock and open the Event Details tab in the bottom panel:
sizeis 117,440,512 bytes: the whole padded key cache, 28 layers × 8 heads × 2048 slots × 128 × 2 bytes.duration_nsis 7.67 ms andbandwidth_bytes_per_sec15.3 GB/s. Clicking the event also draws an arrow to thenrta_tensor_writeon theneuron_rtrow, the runtime call that requested the copy; the Dependency Chain Viewer tab lists it as the upstream event, and clicking it there lists theneuron::copy::cpu_to_neuronop on the backend thread, which is what theaten::toon the main thread is waiting for. The secondio_xu_completeis the value cache, same size: each chunk moves 235 MB to the device before it can run.How often? In the Search widget, searching field
nameforio_xu_completelists every transfer in the profile with itssizeandtransfer_direction: 32 of 117 MB in the step, two per chunk, each about 7.5 ms. The copies alone account for 240 ms of the step; thetorch.catcalls that build the padded tensors on the host account for another 460 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* 1.223s 1
aten::to 460.319ms 82
aten::_to_copy 459.757ms 82
aten::cat 458.445ms 67
neuron::copy::cpu_to_neuron 276.864ms 98
chunk 6 82.723ms 1
chunk 7 82.641ms 1
aten::to and aten::cat each take 37% of the step; neuron::copy::cpu_to_neuron is the backend side of the 98 host-to-device copies (32 large, the rest small tensors and scalars).
Profile 2: Allocate the cache on the device once#
Allocate the full-size cache on the device before the loop, and write each chunk’s keys and values into it:
def prefill(doc):
ids = torch.tensor([doc], device=device)
bias = torch.full((1, 1, 1, 1, L), float("-inf"), dtype=torch.bfloat16, device=device)
pos = torch.arange(T, device=device).view(1, T)
k = torch.zeros(SHAPE, dtype=torch.bfloat16, device=device) # changed: full size, on the device, once
v = torch.zeros_like(k)
preds = []
for n in range(0, L, T):
with record_function(f"chunk {n // T}"):
next_ids, new_k, new_v = step(ids[:, n:n + T].clone(), pos, bias, k, v) # changed: no copy
k[:, :, :, n:n + T] = new_k # changed: written in place, on the device
v[:, :, :, n:n + T] = new_v
bias[..., n:n + T] = 0
pos += T
preds.append(next_ids)
return torch.cat(preds, dim=1)[0].tolist()
2048 tokens: 168 ms (10.5 ms per chunk), 7.5x faster.
Why this works#
Three things change, and the profile shows each of them:
No host-to-device copy of the cache.
step()readskandvwhere they already are. Thehost_to_device_transfersrow shows only the small transfers ofidsand scalars; the 117 MBio_xu_completeblocks are gone, and with them the 7.5 ms per copy during which the device had nothing to run.No host-side concatenation. The slice write
k[:, :, :, n:n + T] = new_kis a 7 MB copy between two device buffers, done by the device, instead of a 117 MB concatenation done by the CPU. The main thread spends 1.3 ms per chunk instead of 77 ms.The loop no longer waits for the device.
new_k.cpu()forced the host to wait for each execution before it could build the next input. Without it, the main thread queues all 16 chunks in 23 ms and then waits once, in the final.tolist(), while the device works through the queue. The device, not the host, now sets the pace.
The whole recorded step (169 ms), same pinned rows. The sixteen chunk N labels are compressed into the first 23 ms of the main thread; the sixteen nc_exec_running blocks follow each other with 1.5 ms gaps:
What improved#
Profile 1: cache on the host |
Profile 2: cache on the device |
Change |
|
|---|---|---|---|
Copied to the device per chunk |
235 MB (keys and values, all layers) |
none |
|
Time for 2048 tokens (host-timed, median of 3) |
1,264 ms |
168 ms |
7.5x |
Per chunk |
79 ms |
10.5 ms |
|
Device execution per chunk ( |
8.8 ms |
8.8 ms |
same |
Device busy during the step |
11% |
83% |
|
Main thread per chunk ( |
77 ms |
1.3 ms |
Both versions produce the same predictions. The execution itself did not change; what changed is that the device now runs 83% of the time instead of 11%. The step time is now 16 executions of 8.8 ms plus 1.5 ms between them. The same fix applies to any buffer a loop reads and writes (caches, masks, position ids): allocate it on the device at its final size and update it in place there.
Do this with an agent#
The idle time in Profile 1 is what the Neuron Agentic Development Profile Analysis skill’s gap analysis reports (see Getting Started to install the skills). The skill is written for captures of a vLLM Neuron server and has no host-to-device check of its own, but the attribution is a query on the SystemProfileEvents table, which every system profile has, and the agent can run it:
Skill |
What it does |
|---|---|
|
Analyzes a capture starting from the system trace (deep dive). Its session analysis measures the gaps between executions; the query below then attributes a gap to the host-to-device copies that fill it, by the size and count of the runtime’s tensor-write events. 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 host-to-device copies are the cause. For the longest ProfilerStep, report
the device busy share, then list the nrta_tensor_write and io_xu_complete events grouped
by size, with count, average and total duration, and which main-thread aten op under
each "chunk N" label issues them.
After the fix:
Do the same for ./profiles/fixed and compare the two profiles: device busy share, bytes
copied to the device per chunk, and the duration of the "chunk 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 lists the copies. (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: 16 executions, 8.8 ms each, busy_pct 11.5
-- Profile 2: 16 executions, 8.8 ms each, busy_pct 82.9
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_write', '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: io_xu_complete, 117440512 B, 32 events, 7.46 ms each, 238.6 ms in total
-- nrta_tensor_write, 117440512 B, 32 events, 0.99 ms each, 31.7 ms in total
-- Profile 2: no 117440512 B events; one 16384 B copy of ids before the loop and a 2 B scalar per chunk remain
Common issues#
host_to_device_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_writeon theneuron_rtrow anddmem_buf_copyinon the transfer row, instead ofnrta_tensor_writeandio_xu_complete. A profile can show both paths; the large copies this guide is about use the asynchronous one. The analysis is the same.