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, or aten::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.cat or 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:

  1. The main thread runs aten::to → aten::_to_copy; the Neuron backend records neuron::copy::cpu_to_neuron on a framework thread. The copy from a regular (pageable) CPU tensor is synchronous: aten::_to_copy does not return until the data is on the device.

  2. The Neuron Runtime row (neuron_rt/.../NC0) shows the runtime call that registers the copy, nrta_tensor_write.

  3. The host_to_device_transfers row shows the data movement itself as io_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

framework/TID:0

The profiler session: PyTorch Profiler and __neuron_profiler__ spans.

framework/TID:<main thread>

Your Python code: ProfilerStep#N, the record_function labels, aten:: ops, TorchDynamo Cache Lookup, Torch-Compiled Region.

other framework/TID:* rows

Backend threads: neuron::copy::cpu_to_neuron and neuron::copy::neuron_to_cpu (copies), model_default (a compiled graph being executed), RuntimeWorker::sleep (the runtime worker waiting).

framework/Stream:*

The same backend work grouped by device stream.

neuron_rt/worker:0/NC0

Neuron Runtime calls for NeuronCore 0: nrta_tensor_write (copy request), nrta_execute_schedule and nrt_model_submit (launch), kbl_exec_wait (host waiting for the execution).

neuron_hw/worker:0/NC0:4, NC0:5

nc_exec_running: a NEFF executing on the two physical cores of logical NeuronCore 0. Click one to open its device profile.

worker:0/host_to_device_transfers

The transfer events track: one io_xu_complete per H2D copy, with size, direction and bandwidth.

worker:0/device_to_host_transfers

The same for D2H copies.

NC:0/host_to_device/transfer_bandwidth, device_to_host/transfer_bandwidth

The transfer bandwidth tracks: PCIe bandwidth used by each direction over time.

Find the bottleneck, step by step#

  1. 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_hw rows and host_to_device_transfers; pinned rows stay at the top while you scroll through the framework threads.

  2. Find the idle time. Zoom to two or three iterations (the record_function labels on the main thread mark them). Compare the width of each label with the nc_exec_running block inside it. The difference is time the device is not computing.

  3. See what fills it. Read the main thread between two executions. aten::to / aten::_to_copy blocks that line up with io_xu_complete blocks on host_to_device_transfers mean the host is copying inputs to the device. If the copies take most of the gap, this guide applies.

  4. Measure one copy. Hover over an io_xu_complete block to read its duration; click it and open Event Details for size, transfer_direction and bandwidth_bytes_per_sec. The click also draws an arrow to the nrta_tensor_write on the neuron_rt row that requested the copy; the Dependency Chain Viewer lists it, and clicking it there leads on to the neuron::copy::cpu_to_neuron op. The aten::to on the main thread is the block directly above the copy in time.

  5. Count the copies. In the Search widget, set the field to name, enter io_xu_complete and choose Submit. Every transfer in the profile is listed with its size and transfer_direction, and Focus jumps the timeline to it. Or read the # of Calls column of neuron::copy::cpu_to_neuron in prof.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):

Neuron Explorer system timeline of the whole Profile 1 step, 1,222 ms, with the NC0:4, NC0:5 and host_to_device_transfers rows pinned at the top: sixteen short pink nc_exec_running blocks with long gaps between them, two purple io_xu_complete blocks before each one, and on the main thread sixteen colored chunk N bars with rows of aten ops under them

Reading the rows from the top:

  • Pinned rows neuron_hw/.../NC0:4 and NC0:5: sixteen pink nc_exec_running blocks, 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 purple io_xu_complete blocks before every execution, 32 in all. Each is a copy from host memory into HBM.

  • Main thread framework/TID:13: the sixteen colored bars labeled chunk 0 … chunk 15 are the record_function(f"chunk {n // T}") labels from the code; each is about 77 ms wide. The rows of short blocks under each bar are the aten:: ops that chunk ran on the host.

How we identified the bottleneck#

  1. Where is the device idle? In the image above, each 77 ms chunk N bar contains one 8.8 ms nc_exec_running block. For the other 68 ms of every chunk the two neuron_hw rows are empty: the device is waiting for the host.

  2. 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 first io_xu_complete on the pinned transfer row:

    Neuron Explorer system timeline of one Profile 1 chunk, 78 ms, with the pinned rows at the top: two io_xu_complete blocks on host_to_device_transfers, the first with a hover tooltip reading Duration 7,671,363 ns, one nc_exec_running block that starts after the second copy, and on the main thread the chunk 8 bar with aten::zeros, aten::cat, aten::to, aten::cat, aten::to, the compiled call, aten::to and aten::cat under it

    Left to right on the main thread row, under the chunk 8 bar:

    Block

    Duration

    What it is

    aten::zeros (with aten::zero_, aten::fill_ stacked under it)

    4.7 ms

    pad: the zero padding to 2048 slots, built on the host

    aten::cat

    11.0 ms

    torch.cat([k, pad]): the padded key cache, built on the host

    aten::to (aten::_to_copy under it)

    8.9 ms

    .to(device) of the keys. The first io_xu_complete on the pinned transfer row sits directly under this block.

    aten::cat

    9.6 ms

    the padded value cache

    aten::to (aten::_to_copy)

    8.8 ms

    .to(device) of the values: the second io_xu_complete

    TorchDynamo Cache Lookup, Torch-Compiled Region (the small blocks)

    2.2 ms

    the step() call. The nc_exec_running block on the pinned neuron_hw rows 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 back

    aten::cat, aten::to, aten::cat

    5.0, 0.6, 5.2 ms

    appending the new keys and values to the host cache

    The two .to(device) blocks and the two torch.cat blocks that feed them take 38 ms of the 77 ms chunk; the execution cannot start until they are done.

  3. How big is each copy? Click the first io_xu_complete block and open the Event Details tab in the bottom panel:

    Neuron Explorer Event Details table for the clicked io_xu_complete event: bandwidth_bytes_per_sec 15308949921, direction h2d, duration_ns 7.6714 ms, name io_xu_complete, size 117440512, trace_event_source neuron_rt, transfer_direction host_to_device

    size is 117,440,512 bytes: the whole padded key cache, 28 layers × 8 heads × 2048 slots × 128 × 2 bytes. duration_ns is 7.67 ms and bandwidth_bytes_per_sec 15.3 GB/s. Clicking the event also draws an arrow to the nrta_tensor_write on the neuron_rt row, the runtime call that requested the copy; the Dependency Chain Viewer tab lists it as the upstream event, and clicking it there lists the neuron::copy::cpu_to_neuron op on the backend thread, which is what the aten::to on the main thread is waiting for. The second io_xu_complete is the value cache, same size: each chunk moves 235 MB to the device before it can run.

  4. How often? In the Search widget, searching field name for io_xu_complete lists every transfer in the profile with its size and transfer_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; the torch.cat calls 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() reads k and v where they already are. The host_to_device_transfers row shows only the small transfers of ids and scalars; the 117 MB io_xu_complete blocks 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_k is 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:

Neuron Explorer system timeline of the whole Profile 2 step over 171 ms: sixteen nc_exec_running blocks back to back on the pinned NC0:4 and NC0:5 rows, an almost empty host_to_device_transfers row, and sixteen short chunk labels packed into the first 23 ms of the main thread followed by one long aten::to

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 (nc_exec_running)

8.8 ms

8.8 ms

same

Device busy during the step

11%

83%

Main thread per chunk (chunk N label)

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

neuron-framework-profile-analysis-vllm-neuron

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, neuron-framework-profile-analysis-vllm-neuron-agent, also carries neuron-nki-profile-querying (serves a profile with neuron-explorer and runs SQL against it) and neuron-explorer-profile-schema (what each field means).

neuron-framework-profiling-vllm-neuron

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_transfers is empty

Make sure ProfileMode.RUNTIME is in NeuronConfig(modes=...) and ProfilerActivity.PrivateUse1 is in activities.

Different event names

A copy made through the runtime’s synchronous path appears as nrt_tensor_write on the neuron_rt row and dmem_buf_copyin on the transfer row, instead of nrta_tensor_write and io_xu_complete. A profile can show both paths; the large copies this guide is about use the asynchronous one. The analysis is the same.