This document is relevant for: Inf2, Trn1, Trn2, Trn3
How to identify and reduce inefficient DMA transfers#
Direct memory access (DMA) is how data moves between a NeuronCore’s memories without passing through a compute engine: from HBM into the on-chip SBUF before a tile is computed on, and back to HBM afterwards. Each NeuronCore has 16 DMA engines. A DMA transfer is one request to move a block of data, such as a nisa.dma_copy in a NKI kernel or a load the compiler inserts; the hardware splits it into packets, one per engine per group of SBUF partitions, and the engines execute the packets in parallel.
A transfer has a fixed cost that does not depend on its size: its descriptors have to be generated (by the compute engine that issues it, in the kernel below), the engines synchronize on semaphores, and each packet pays a setup latency before its bytes move. When a kernel moves its data in many small transfers, that fixed cost is paid many times over, the DMA engines spend most of their time between packets, and the compute engines wait for data. This is a DMA bottleneck: the kernel is limited by how fast transfers can be issued, not by how fast HBM can deliver bytes.
This guide shows how to recognize that pattern in a Neuron Explorer device profile, how to measure it, and how to fix it by moving more data per transfer. For copies between the host and the device, see the H2D and D2H guides; those use the system profile. This guide uses the device profile.
When to suspect DMA transfers#
Look for this bottleneck when:
The Summary Viewer shows no compute engine close to 100% active and DMA active time well below 100% as well. Something is waiting, and the DMA rows are the first place to look.
The DMA rows of the Device Timeline show many short packets with gaps between them, instead of long runs of back-to-back packets.
A
DMA_DIRECT2Dinstruction’ssrc_elem_size, the bytes each partition moves, is below 2 KiB. The NKI DMA bandwidth guide recommends at least 2 KiB of contiguous data per partition per transfer, and 4 KiB to saturate the DMA engines; for bf16 that is a free dimension of at least 1,024 elements. The packet size in the DMA rows is a different number: each partition’s data is copied as its own piece (one descriptor), and the pieces that go to one DMA engine are grouped into a single packet, so a transfer of 256 bytes per partition still shows 2 KiB packets. Checksrc_elem_size, not the packet size.The kernel’s tiles span fewer than 128 partitions. Each DMA engine serves eight partitions, so a transfer over 32 partitions uses four of the sixteen engines.
The kernel loads one small tile at a time inside a loop: a
[128, 128]tile of bf16 is 256 bytes per partition, an eighth of the minimum.Memory bandwidth utilization (MBU) is low for a kernel that is mostly data movement, such as an elementwise or reduction kernel that should run at HBM speed.
The Device Timeline also flags regions dominated by very small hardware-generated (DGE) transfers with an amber Small DMA transfers band; see Small DMA transfers warning. The transfers in this guide are issued by the kernel’s own instructions, so they do not trigger the band, and you find them with the steps below.
What a transfer looks like in the device profile#
One nisa.dma_copy of a [128, F] tile produces events on three kinds of rows of the Device Timeline:
On the row of the engine that issues it (here
GpSimd), oneDMA_DIRECT2Dinstruction: the trigger that generates the transfer’s descriptors. Its duration is the issue cost, about 0.7 µs whatever the size of the transfer. Event Details shows the bytes it moves (hbm_read_bytesorhbm_write_bytes), its duration, and inoperandsthe queue it was issued on and the bytes per partition.On the sixteen
DMA-E64…DMA-E79rows, the packets: each engine moves the bytes of eight partitions, so a transfer with 256 bytes per partition becomes sixteen 2 KiB packets, one per engine, and a transfer with 4 KiB per partition becomes 128 packets of 4 KiB. A hover shows the packet’s size, duration, throughput, the kernel argument it belongs to (input0,output0) and its queue; the queue name (qGpSimdDynamic-Q0-E64) names the issuing engine, the queue and the DMA engine. Each engine ends its part of a transfer with a 4-byte packet: the semaphore update that signals completion.On the
DMA ThroughputandCumulative DMA Throughputrows, bytes moved over time, which you can compare with the 368 GB/s that one Trn2 NeuronCore’s sixteen engines can sustain.
This is what a software DGE (descriptor generation engine) transfer looks like: a compute engine, here GpSimd, runs the DMA_DIRECT2D instruction that generates the descriptors, the queue is named q<Engine>Dynamic, and the Summary counts the packets as software_dynamic. It is the path nisa.dma_copy takes in this guide’s kernel, and the issue cost above is its cost. Transfers can take two other paths, with their own costs: hardware DGE, where the descriptors are generated by hardware for a transfer issued from the Sync (SP), Scalar (ACT) or Vector (DVE) engine (hardware_dynamic packets), and static DMA, where the compiler generates the descriptors at compile time and they are loaded with the NEFF (static packets). The queue name and the packet type tell you which path a transfer took. The per-partition size guidance in this guide applies to all three.
The Summary tab aggregates the same events: DMA active time, packet counts by type (static, software_dynamic, hardware_dynamic), transfer count and average transfer size, HBM bytes read and written, and mbu_estimated_percent, the achieved HBM bandwidth as a fraction of the hardware peak.
Capture a device profile#
Capture a device profile of the compiled kernel (NEFF) with neuron-explorer capture. Set NKI_DEBUG_INFO=True before the kernel is compiled so the NEFF carries the NKI source locations and the NKI regions used below, and TORCH_NEURONX_NEFF_CACHE_DIR so the NEFF is saved where you can find it. Run the kernel once, then capture. --num-exec=3 --profile-nth-exec=2 runs the kernel three times and profiles the second run, so first-run setup is not in the profile; --enable-dge-notifs records the per-transfer metadata (transfer count and size, the kernel argument each packet belongs to) that the Summary tab needs:
export NKI_DEBUG_INFO=True # NKI source locations and nl.profiler_region_open() regions in the profile
export TORCH_NEURONX_NEFF_CACHE_DIR=./neff_cache
python3 my_kernel.py # runs the kernel once and writes the NEFF
neuron-explorer capture -n ./neff_cache/<path>/file.neff -s ./profiles/baseline/profile.ntff \
--profile-nth-exec=2 --num-exec=3 --enable-dge-notifs
The capture writes profile_exec_2.ntff next to the NEFF. DGE notifications add a little DMA traffic of their own (the baseline below runs 7% longer with them than without), so compare profiles captured with the same flags.
Open the profile in Neuron Explorer#
Serve one profile with one command:
neuron-explorer view -n ./profiles/baseline/kernel.neff -s ./profiles/baseline/profile_exec_2.ntff
To compare the baseline with the fixed kernel in the same session (the Profile Comparison view needs both profiles on one server), start a server once and upload each profile into it. Pass the kernel source so the Source Code Viewer can show it:
neuron-explorer view --data-path ~/.local/share/neuron-explorer &
neuron-explorer upload --endpoint http://localhost:3002 --profile-directory ./profiles/baseline --name baseline \
--source-code ./my_kernel.py --wait
Open the profile. The Analysis tab shows the Device Timeline; the Summary tab the aggregated metrics. The rows of the Device Timeline:
Row |
What it shows |
|---|---|
|
One row per compute engine, one event per instruction. |
|
One row per DMA engine, one event per packet. Hover for size, duration, throughput, variable and queue. |
|
Packets of the host-device copies (the kernel’s inputs and outputs). |
|
Bytes moved over time by the sixteen engines, instantaneous and cumulative. |
|
The same for host-device traffic. |
|
SBUF bytes in use over time. |
|
Semaphore updates, the synchronization between engines and DMA queues. |
Find the bottleneck, step by step#
Start on the Summary tab. Read Total Runtime, the active time of each compute engine, DMA active time and
mbu_estimated_percent. If no compute engine is close to 100% and DMA active time is not either, the kernel is waiting. Low MBU on a kernel that is mostly data movement says the waiting is on the DMA side.Look at the DMA rows in the Device Timeline. Hover a row name and click the pin icon to keep
GpSimd,Vector,DMA Throughputand a couple ofDMA-E*rows at the top. Zoom to a few microseconds. Short packets with gaps between them mean the engines wait between transfers. The size in the hover tooltip is the packet, the pieces of the eight partitions this engine serves grouped together; for the bytes per partition, readsrc_elem_sizeon theDMA_DIRECT2Dthat issued it (next step). Click a packet for its full Event Details.Find who issues the transfers. Click a
DMA_DIRECT2Dinstruction on the engine row. Event Details gives the bytes it moves (hbm_read_bytesorhbm_write_bytes) and its duration, and the engine row’s active time tells you how much of the execution is spent issuing transfers rather than computing.Count transfers against bytes. On the Summary tab or in the Overall Summary widget, compare
Dma Transfer Countwith the HBM bytes read and written. If the same bytes take far more transfers than the tile shapes need, the transfers are too small. For the bytes per partition that the 2 KiB and 4 KiB thresholds refer to, readsrc_elem_sizeon aDMA_DIRECT2D.Compare before and after. When you have a fixed kernel, select both profiles in the Profile Manager and choose Actions → Compare profiles. The comparison view stacks the two Device Timelines and lists every summary metric side by side with the difference.
Example: scale and bias on a [1024, 2048] matrix#
A NKI kernel on a trn2.3xlarge computes y = x * scale + bias on three [1024, 2048] bf16 tensors. Each tile is loaded from HBM into SBUF with nisa.dma_copy, computed on the Vector engine, and stored back. The three phases are marked as NKI regions with nl.profiler_region_open / nl.profiler_region_close, so Neuron Explorer can list them in the Region Highlighter:
import torch
import nki
import nki.language as nl
import nki.isa as nisa
M, N, P = 1024, 2048, 128 # rows, columns, partitions per tile
device = torch.device("neuron")
x, scale, bias = (torch.randn(M, N, dtype=torch.bfloat16, device=device) for _ in range(3))
y = nki.jit(scale_bias)(x, scale, bias)
Profile 1: Baseline#
scale_bias tiles the matrix into [128, 128] tiles:
TILE_F = 128
def scale_bias(x, scale, bias):
out = nl.ndarray((M, N), dtype=x.dtype, buffer=nl.shared_hbm)
for i in nl.static_range(M // P): # 8 row groups
for j in nl.affine_range(N // TILE_F): # 16 column tiles per row group
rows, cols = nl.ds(i * P, P), nl.ds(j * TILE_F, TILE_F)
t = nl.ndarray((P, TILE_F), dtype=x.dtype, buffer=nl.sbuf)
s = nl.ndarray((P, TILE_F), dtype=x.dtype, buffer=nl.sbuf)
b = nl.ndarray((P, TILE_F), dtype=x.dtype, buffer=nl.sbuf)
nl.profiler_region_open("load") # NKI region, shown in the Region Highlighter
nisa.dma_copy(dst=t, src=x[rows, cols]) # 128 x 2 B = 256 B per partition
nisa.dma_copy(dst=s, src=scale[rows, cols])
nisa.dma_copy(dst=b, src=bias[rows, cols])
nl.profiler_region_close()
nl.profiler_region_open("compute")
tmp = nl.ndarray((P, TILE_F), dtype=x.dtype, buffer=nl.sbuf)
nisa.tensor_tensor(dst=tmp, data1=t, data2=s, op=nl.multiply)
res = nl.ndarray((P, TILE_F), dtype=x.dtype, buffer=nl.sbuf)
nisa.tensor_tensor(dst=res, data1=tmp, data2=b, op=nl.add)
nl.profiler_region_close()
nl.profiler_region_open("store")
nisa.dma_copy(dst=out[rows, cols], src=res)
nl.profiler_region_close()
return out
One execution: 394.1 µs.
What the profile shows#
The whole execution, with GpSimd, Vector, DMA Throughput and two DMA engine rows pinned to the top. The GpSimd row is a nearly solid band of DMA_DIRECT2D instructions from start to end; the Vector row is mostly empty; the DMA rows are dense but made of short packets:
How we identified the bottleneck#
Summary tab. Total runtime 394.1 µs. DMA active 48% of the execution, Vector engine active 15%, GpSimd engine active 90%.
mbu_estimated_percent5.9%: the kernel reads 12.6 MB and writes 4.2 MB, and moves them at 43 GB/s where HBM could deliver more than ten times that. Nothing is close to saturated except the GpSimd engine, which does no arithmetic in this kernel.DMA rows. Zoomed to 12 µs, each DMA engine row shows a repeating pattern of a 2 KiB packet followed by a 4-byte packet and a gap. Hovering a data packet gives
transfer_bytes2,048, a duration of about 100 ns, variableinput0and queueqGpSimdDynamic-Q0-E64: one[128, 128]tile is 256 bytes per partition, so each of the sixteen engines moves eight partitions’ worth, 2 KiB, per transfer, and the engines are busy for 17% of the time on average:
Engine rows. Click a
DMA_DIRECT2Don theGpSimdrow and open the Event Details tab in the bottom panel:
hbm_read_bytesandsbuf_write_bytesare 32,768: one[128, 128]tile. Theoperandsrow says the same thing in the hardware’s terms:src_elem_size=256bytes for each of 128 partitions, issued on theqGpSimdDynamicqueue.duration_nsis 752 ns. There are 512 of these instructions, 0.7 µs each, issued one every 0.68 µs: that alone is 350 µs of the 394 µs execution. The kernel is bound by issuing transfers. The 256TENSOR_TENSORinstructions on the Vector engine take 58 µs in total and spend the rest of the time waiting for their tiles.Counts. The Summary tab reports 512 DMA transfers (
hbm_read_bytes32 KiB each in Event Details) and 16,384software_dynamicpackets (8,192 data packets of 2 KiB and their 8,192 completion writes) for 16 MB of data. Moving the same bytes in[128, 2048]tiles would take 32 transfers.
The Region Highlighter widget (Add Widget → Region Highlighter) lists the kernel’s NKI regions load, compute and store, each with a filter for the loop iteration, so the three phases can be selected and compared in the Summary Viewer. See NKI Regions.
Profile 2: Move more data per transfer#
Load each 128-row group across the full row width, so each transfer moves 4 KiB per partition:
TILE_F = 2048 # changed: full row width
def scale_bias(x, scale, bias):
out = nl.ndarray((M, N), dtype=x.dtype, buffer=nl.shared_hbm)
for i in nl.static_range(M // P): # 8 row groups, one tile each
rows = nl.ds(i * P, P) # changed: no column loop
t = nl.ndarray((P, TILE_F), dtype=x.dtype, buffer=nl.sbuf)
s = nl.ndarray((P, TILE_F), dtype=x.dtype, buffer=nl.sbuf)
b = nl.ndarray((P, TILE_F), dtype=x.dtype, buffer=nl.sbuf)
nl.profiler_region_open("load")
nisa.dma_copy(dst=t, src=x[rows, 0:N]) # changed: 2048 x 2 B = 4 KiB per partition
nisa.dma_copy(dst=s, src=scale[rows, 0:N])
nisa.dma_copy(dst=b, src=bias[rows, 0:N])
nl.profiler_region_close()
nl.profiler_region_open("compute")
tmp = nl.ndarray((P, TILE_F), dtype=x.dtype, buffer=nl.sbuf)
nisa.tensor_tensor(dst=tmp, data1=t, data2=s, op=nl.multiply)
res = nl.ndarray((P, TILE_F), dtype=x.dtype, buffer=nl.sbuf)
nisa.tensor_tensor(dst=res, data1=tmp, data2=b, op=nl.add)
nl.profiler_region_close()
nl.profiler_region_open("store")
nisa.dma_copy(dst=out[rows, 0:N], src=res)
nl.profiler_region_close()
return out
One execution: 60.2 µs, 6.5x faster.
Why this works#
The kernel moves exactly the same bytes (12.6 MB read, 4.2 MB written) and does the same arithmetic. What changes is how the bytes are packaged:
16 times fewer transfers. 32
DMA_DIRECT2Dinstructions instead of 512. The issue cost per transfer is about the same (0.7 µs), so the GpSimd engine spends 25 µs issuing instead of 353 µs, and is active for 41% of a much shorter execution.Packets twice as large and no gaps. Each transfer is 512 KiB and becomes 128 packets of 4 KiB, 159 ns each; the sixteen engines are busy 75% of the time instead of 17%, and the 4,608 packets (4,096 data, 512 completion writes) replace 16,384.
The kernel is now bound by data movement, which is the right bound for it.
y = x * scale + biasreads three values and writes one for two floating-point operations; it should run at memory speed. DMA active time is 81%, the kernel moves 16.8 MB in 60.2 µs (280 GB/s, 76% of the 368 GB/s one core’s DMA engines can sustain on Trn2), and the Vector engine’s 36% active time overlaps with the transfers instead of waiting for them.
A hover on a packet of the fixed kernel shows transfer_bytes 4,096, and the rows around it show packets back to back:
Compare the two profiles#
Select both profiles in the Profile Manager and choose Actions → Compare profiles. The comparison view stacks the two Device Timelines, each at its own time scale: the baseline is 394 µs of dense small packets, the fixed kernel 60 µs of back-to-back 4 KiB packets:
The Overall Summary Comparison widget below the timelines lists every summary metric for both profiles with the difference. The rows that matter here:
What improved#
Profile 1: |
Profile 2: |
Change |
|
|---|---|---|---|
Bytes per partition per transfer |
256 B |
4 KiB |
16x |
DMA transfers ( |
512 × 32 KiB |
32 × 512 KiB |
|
DMA packets |
16,384 (2 KiB data packets) |
4,608 (4 KiB data packets) |
|
Execution time |
394.1 µs |
60.2 µs |
6.5x |
DMA active |
48% |
81% |
|
DMA engines busy (average of the 16) |
17% |
75% |
|
GpSimd engine active (issuing transfers) |
90% |
41% |
|
Vector engine active (compute) |
15% |
36% |
|
Memory bandwidth utilization (MBU) |
5.9% |
39% |
|
HBM bytes read / written |
12.6 MB / 4.2 MB |
12.6 MB / 4.2 MB |
same |
Both versions produce the same result. The execution is 6.5x shorter because the fixed cost of issuing a transfer is paid 32 times instead of 512, and because 4 KiB packets keep the DMA engines streaming. MBU went from 5.9% to 39% of the HBM peak; MFU and HFU are 0 for both profiles because the kernel has no Tensor Engine work, so for a kernel like this one the utilization metrics to watch are DMA active time, MBU and the compute engine’s active time. The same check applies to any kernel. The 2 KiB and 4 KiB thresholds are per partition, so read src_elem_size in the DMA_DIRECT2D operands (256 B in Profile 1, 4,096 B in Profile 2), not the whole-transfer size (32 KiB in Profile 1), which looks large enough even when each partition moves only 256 B. Then make the free dimension of each DMA tile as large as SBUF allows.
Use all of the partitions as well. Each DMA engine serves eight partitions, so a transfer spreads over the sixteen engines only when it spans all 128 partitions; fewer partitions means fewer engines and less bandwidth. With software DGE, the partition count should also be a multiple of 16 on older microcode, or the transfer may run on a single engine. In short: all 128 partitions, with at least 2 to 4 KiB each.
Do this with an agent#
The capture and the analysis above map onto two Neuron Agentic Development skills (see Getting Started), both driven by the neuron-nki-agent:
Skill |
What it does |
|---|---|
|
Runs the kernel, finds its NEFF, captures it with |
|
Serves the profile and queries its Parquet tables (SQL through |
A prompt for Profile 1:
Profile the kernel in ./my_kernel.py on NeuronCore 0 with DGE notifications enabled,
then tell me which engine is the bottleneck, how much DMA time is lost to small
transfers (packet size and bytes per transfer), and whether the GpSimd engine spends
its time issuing DMA_DIRECT2D instructions rather than computing.
After the fix:
Profile the fixed kernel the same way and show the two profiles side by side: total
time, DMA active time, DMA transfer count, bytes per partition, packet size, MBU, and the
GpSimd and Vector engine active time.
Two of the queries behind the numbers in this guide, on the Summary and DmaPacket tables. The *_percent fields are fractions of 1. (If you send them to the databaseExplorerQuery endpoint the skill uses, put each statement on one line.)
SELECT total_time, dma_active_time_percent, dma_transfer_count,
mbu_estimated_percent,
gpsimd_engine_active_time_percent, vector_engine_active_time_percent
FROM Summary;
-- Profile 1: 394 us, DMA active 0.48, 512 transfers,
-- MBU 0.059, GpSimd 0.90, Vector 0.15
-- Profile 2: 60 us, DMA active 0.81, 32 transfers,
-- MBU 0.39, GpSimd 0.41, Vector 0.36
SELECT transfer_bytes, COUNT(*) AS n, ROUND(AVG(duration_ns)) AS avg_ns
FROM DmaPacket WHERE transfer_bytes > 4
GROUP BY 1 ORDER BY n DESC LIMIT 3;
-- Profile 1: 8192 packets of 2048 B, 123 ns each
-- Profile 2: 4096 packets of 4096 B, 170 ns each
The investigation’s last step attributes the inefficient transfers to NKI source lines through the Instruction table’s nki_source_location and bir_debug_info_source_location columns. In the profiles captured for this guide those columns are empty for the kernel’s instructions, even when the kernel is compiled with the full set of debug variables from Profile a NKI kernel, so the agent reports the transfer sizes and counts but not the nisa.dma_copy line that issued them; read that from the kernel source as in the example above.
Common issues#
- No NEFF to capture
Set
TORCH_NEURONX_NEFF_CACHE_DIRbefore running the kernel, then look for the newest.nefffile under that directory.- The profile includes first-run setup
Capture with
--num-exec=3 --profile-nth-exec=2.Missing additional dynamic DMA metadatawarning on the Summary tab, emptyDma Transfer CountThe profile was captured without
--enable-dge-notifs. Capture again with the flag.- No NKI regions or source lines in the profile
The NEFF was compiled without
NKI_DEBUG_INFO=True, or a cached NEFF from an earlier compilation was reused. Set the variable, clear the NEFF cache, and compile again.- Larger tiles do not fit in SBUF
Keep the free dimension large and reduce the number of tiles that are live at the same time instead.