This document is relevant for: Trn2, Trn3

Deep dive: NKI compile configuration#

A NKI kernel can ask NKI to allocate memory and schedule instructions itself, instead of leaving both to neuronx-cc. This topic explains how NKI allocation and NKI scheduling work, why DMA loads wait for compute, and what each optimization in nki.compiler.CompileConfig changes in the compiled kernel. For the option values and defaults, see NKI CompileConfig options reference.

What you should know before reading#

Before you start, you must be familiar with the following:

Overview#

Two decisions determine how a compiled kernel uses the hardware. The first decision is where each tensor goes in SBUF, PSUM and HBM. The second decision is the order in which the engines run the instructions. By default, neuronx-cc makes both decisions after NKI traces the kernel, and the kernel has few means to influence them, for example explicit addresses, engine= arguments and the scheduling APIs.

With allocation=Allocation.LINEAR, NKI allocates the kernel’s tensors before neuronx-cc runs. The lifetime of each tensor then follows from the kernel source, and the kernel can enable optimizations that act on that allocation. With scheduling=True in addition, NKI also orders the instructions, and the rest of compilation keeps that order. nki.compiler.CompileConfig selects these modes and the optimizations for each kernel.

When NKI allocation runs out of memory, the error names the largest live tensor and lists the changes that can make the kernel fit (see Out-of-memory errors).

Availability#

NKI allocation and NKI scheduling are experimental and opt-in. A kernel that sets no allocation uses neuronx-cc allocation and scheduling.

Warning

NKI scheduling (scheduling=True) is less mature than NKI allocation. It can slow down some kernels, fail to compile others, or produce incorrect results.

Use NKI allocation without scheduling=True first, for example allocation=Allocation.LINEAR with opt_level=OptLevel.O2. Treat scheduling=True as an additional experiment on top of NKI allocation. Validate the kernel’s results carefully, and do not use scheduling=True in production code.

The kernels most likely to benefit are kernels whose profile shows DMA loads that wait for compute, or copies that the kernel does not need. To find the options for a kernel, see How to tune a NKI kernel with CompileConfig.

Terminology#

Allocation

The assignment of an address in SBUF, PSUM or HBM to each tensor, and the release of that address when the kernel no longer uses the tensor.

Scheduling

The order in which the engines run the instructions of the kernel. A schedule must respect the dependencies between instructions.

neuronx-cc allocation and scheduling

The mode of a kernel that sets no allocation, or sets allocation=Allocation.COLORING. After NKI traces the kernel, neuronx-cc allocates the tensors with graph coloring and schedules the instructions. The API reference calls this mode the current flow.

NKI allocation

The mode of a kernel that sets allocation=Allocation.LINEAR. NKI allocates the tensors with linear scan before the rest of compilation. Compiler messages say “NKI allocates” for this mode. The API reference calls it the new flow.

NKI scheduling

The mode of a kernel that sets allocation=Allocation.LINEAR and scheduling=True. NKI also schedules the instructions before the rest of compilation. Compiler messages say “NKI schedules” for this mode.

Graph coloring allocation

An allocation that considers the live ranges of all tensors together. It assigns addresses so that tensors whose live ranges overlap do not share memory.

Linear scan allocation

An allocation that visits the instructions in program order. It assigns an address to a tensor at the tensor’s first write, and releases the address after the tensor’s last read.

Tensor

One nl.ndarray allocation. Allocation places tensors.

Tile

The block of data that one iteration of a kernel loads or computes, for example tile i of a tensor in HBM.

Live range

The interval from a write that defines the data of a tensor to the last read of that data. A tensor that the kernel overwrites with unrelated data has more than one live range (see How split_reused_buffers splits live ranges).

Data dependency

A read-after-write order between two instructions: the second instruction reads data that the first instruction writes.

Anti-dependency

A write-after-read order. An instruction must wait to overwrite memory until an earlier instruction has read that memory, although it needs no data from the earlier instruction (see Why loads wait for compute).

Output dependency

A write-after-write order between two instructions that write the same memory.

Allocation strategy

The policy that NKI allocation uses to select an address in free memory, an AllocationMode (see Allocation strategies).

Prefetch tensor

An SBUF tensor that a DMA fills before compute reads it. prefetch_auto places prefetch tensors apart from the other tensors (see How prefetch_auto places SBUF tensors).

Why loads wait for compute#

A kernel that streams data through SBUF loads tile i+1 while the engines compute on tile i. The load and the compute overlap only when the two tiles are at different SBUF addresses. When the load destination is at an address that compute still reads, the load must wait until the read is done. This wait is an anti-dependency: the load needs no data from the compute, only its memory.

When these waits are on the critical path, loading and computing run one after the other. The DMA queue is idle until compute is done, and then compute is idle until the load completes. The kernel then takes about the sum of DMA time and compute time, instead of the larger of the two. In the profile timeline, the DMA loads and the compute instructions alternate instead of overlapping.

The kernel source shows which option removes the wait:

  • If the load writes a different tensor than the tensor that compute reads, NKI allocation placed the two tensors at the same address. prefetch_auto keeps load destinations apart from compute tensors (see How prefetch_auto places SBUF tensors).

  • If the load writes the same tensor that compute reads, as in a loop that reloads one tensor in every iteration, split_reused_buffers gives each live range its own tensor (see How split_reused_buffers splits live ranges). With neuronx-cc allocation, non_ssa_legalization does the same.

OptLevel.O2 turns on prefetch_auto and split_reused_buffers. Where NKI allocation can place two tensors at one address also depends on the allocation strategy (see Allocation strategies).

How prefetch_auto places SBUF tensors#

With prefetch_auto, NKI allocation sorts the SBUF tensors into two groups and places each group in its own part of SBUF:

Prefetch tensors

Every destination of a DMA that loads from HBM, and every tensor allocated with nl.ndarray(..., prefetch=True).

Compute tensors

Every other SBUF tensor.

A load into a prefetch tensor then seldom takes the memory of a compute tensor, so the load waits for compute less often. The placement reduces these waits but does not remove them. A load still waits for the last read of the tensor whose memory it takes. That tensor can be an earlier prefetch tensor, when the prefetch tensors do not all fit in their part at different addresses. It can also be an earlier compute tensor, when the soft bounds in the following section let the load use memory that the compute tensor freed.

Default layout with soft bounds#

By default, NKI allocation sizes the two parts itself, and their bounds are soft. Prefetch tensors prefer the top half of SBUF. Compute tensors prefer the bottom quarter. Both groups can use the quarter between them. When its part is full, each group can use any memory that the other group does not use at that time. A prefetch tensor only has to stay above the live compute tensors, and a compute tensor only has to stay below the live prefetch tensors.

Effect on the SBUF allocation strategy#

In the default layout, NKI allocation places every SBUF tensor itself, and the SBUF allocation strategy does not apply. experimental_sbuf_allocation_mode does not change where SBUF tensors go, and the SBUF retries of sbuf_allocation_fallback place them the same way. Because OptLevel.O2 turns on prefetch_auto, this is the case at O2 by default. The HBM and PSUM strategies still apply. To use an SBUF strategy, set prefetch_auto=False, or set NKI_PREFETCH_RING_SIZE. With a fixed prefetch region, the SBUF strategy applies to the compute tensors below the region.

Fixed prefetch region with hard bounds#

The NKI_PREFETCH_RING_SIZE environment variable gives prefetch tensors a fixed region of that many bytes per partition at the top of SBUF. The bounds of this region are hard. Every prefetch tensor goes in the region, and every compute tensor goes below it. Compute tensors never use the region, even when it is empty. Prefetch tensors never leave it, even when the rest of SBUF is free. For how to set the variable and the error that a full region gives, see Sizing the prefetch region.

How split_reused_buffers splits live ranges#

A kernel often allocates one tensor and reuses it in every iteration of a loop, as in this part of the split_reused_buffers example:

tile = nl.ndarray((128, x.shape[1]), dtype=x.dtype, buffer=nl.sbuf)
res = nl.ndarray((128, x.shape[1]), dtype=x.dtype, buffer=nl.sbuf)
for i in range(x.shape[0] // 128):
    # Load block i of x into tile, overwriting block i - 1.
    nisa.dma_copy(dst=tile, src=x[i * 128 : (i + 1) * 128, :])
    # Read block i.
    nisa.reciprocal(dst=res, data=tile)
    nisa.dma_copy(dst=out[i * 128 : (i + 1) * 128, :], src=res)

Each iteration loads a new block of x into tile and reads it. Block i+1 does not depend on block i. The two blocks only share the tensor. The span from the load of a block to the last read of that block is one live range of tile, so this loop gives tile one live range per block.

NKI allocation places tile once, so every block goes to the same SBUF address. To keep the blocks from corrupting each other, the compiler must order the load of block i+1 after the accesses to block i:

Write after read

The load of block i+1 must wait until reciprocal has finished reading block i. Otherwise the load overwrites data that reciprocal still reads.

Write after write

The load of block i+1 must also complete after the load of block i, so that the memory holds the newer block.

These anti-dependencies and output dependencies come from the shared memory, not from data that the instructions need. They make loading and computing run one after the other (see Why loads wait for compute). A loop is the common source, but any two independent overwrites of one tensor have the same effect, for example two different weight tiles loaded into one tensor one after the other.

With split_reused_buffers, the compiler finds the live ranges of each reused SBUF tensor and replaces the tensor with one clone per live range. Every access in a live range then uses the clone of that live range. In the preceding loop, block i goes into its own clone of tile, as if the kernel had allocated a separate nl.ndarray in each iteration.

After the split, two blocks share no tensor, so the compiler records no write-after-read or write-after-write dependency between them. NKI allocation places the clones like separate nl.ndarray calls, and can place them at different addresses. The load of block i+1 can then run while reciprocal still reads block i. DMA and compute can overlap, and the loop time can approach the larger of DMA time and compute time.

Where a live range starts and ends#

A live range starts at a write that replaces every byte that the following reads use. The live range ends at the last read of those bytes. An in-place write or an accumulating write, such as nisa.tensor_tensor(dst=acc, data1=acc, ...), reads the current data. Such a write continues the live range instead of starting a new one. Live ranges whose accesses interleave in program order stay in one clone.

Which loops are split#

The split runs before NKI allocation. NKI unrolls a Python for loop when it traces the kernel, and unrolls nl.fori_loop(..., unroll=True) before the split, so each iteration of these loops can get its own clone. An nl.fori_loop that stays rolled (the default, or unroll=False) is still a loop when the split runs, so its iterations are not split.

Memory use#

The split does not increase the amount of SBUF that is live at any time. Live ranges that overlap stay in one clone, so no two clones of a tensor are live at the same time. The split changes only where the clones go, and that depends on the allocation strategy:

  • Under RING, the clones spread over more of SBUF. They can share an address again when RING wraps around.

  • Under FAST and MAX_REUSE, every clone can go at the address of the previous clone, and the split does not remove the waits.

  • With prefetch_auto and no NKI_PREFETCH_RING_SIZE, as at OptLevel.O2, the SBUF strategy does not apply (see Effect on the SBUF allocation strategy).

non_ssa_legalization does the same split for neuronx-cc allocation. With allocation=Allocation.LINEAR, NKI allocation has already placed every tensor when non_ssa_legalization runs. Every clone then keeps the address of the original tensor, so the live ranges still share memory.

How copy elimination works#

NKI allocation can remove two kinds of copy before or after it places the tensors: an nisa.tensor_copy that only moves a tile, and an nisa.dma_copy that loads data that SBUF already holds.

tensor_copy_elim#

A kernel often copies a tile only to move it to a place where an instruction can read it, for example a matmul result from PSUM to SBUF before an activation reads it. When the reading instruction can read the original tile, the copy uses engine time and a second tensor without a purpose. tensor_copy_elim removes such a copy before NKI allocation runs. The readers of the copy then read the copy’s source, the copy takes no engine time, and its destination takes no SBUF or PSUM.

The compiler removes a copy only when all of these conditions are true:

  • The copy moves the tile unchanged. Both sides have the same shape, data type and layout, the indices are constant, and the copy writes every element of the destination once. A copy that converts the data type, transposes, broadcasts, strides or uses a run-time index stays.

  • Every instruction that reads the copied data reads only inside the region that the copy wrote, and no instruction writes that region after the copy.

  • No instruction overwrites or frees the source between the copy and its last reader.

  • The copy does not carry an ordering edge such as depends_on.

  • The copy and its readers are not inside an nl.no_reorder block, and not inside a loop that the compiler keeps rolled.

Each reader must also be able to read the source where it is:

  • For a copy from PSUM to SBUF, every reader must be able to read PSUM. The copy stays when a reader needs SBUF, for example a matmul, a DMA or a gather.

  • An activation must read the copied value as its data input. When the activation reads it as another operand, such as its bias, the copy stays.

  • The copy stays when another PSUM tensor is first written between the copy and the last reader, because a longer-lived source competes with that tensor for PSUM.

  • A copy that a select instruction reads, such as nisa.range_select or nisa.select_reduce, stays.

  • A copy that a tensor-tensor instruction reads stays when, after the rewrite, both inputs of that instruction are in the same memory (both SBUF or both PSUM). For example, an SBUF-to-SBUF copy stays when the other input of the instruction is also in SBUF.

  • An integer tensor-tensor instruction can run on GpSimd, which cannot read PSUM, so a copy out of PSUM that it reads stays.

  • After the rewrite, each reader must still be legal on its engine. If one reader is not legal, the copy stays.

tensor_copy_elim runs before NKI allocation assigns any address, so the allocation strategy does not change which copies it removes.

Copy removal later in compilation#

Later in compilation, in every mode, the compiler also removes an nisa.tensor_copy whose readers can read its source, unless dead_code_elim=False. This later removal keeps a copy when an instruction writes the source between the copy and its last reader. Without NKI scheduling, this later removal removes many of the copies that tensor_copy_elim targets.

NKI scheduling moves copies away from their readers, so the later removal keeps more of them. tensor_copy_elim runs before NKI scheduling, while the instructions are still in the order of the kernel source. For this reason tensor_copy_elim matters most with NKI scheduling. dead_code_elim=False does not keep a copy that tensor_copy_elim removes.

dma_copy_elim#

A kernel often loads the same block of a tensor more than once, for example a weight tile that two stages of the kernel read:

a = nl.ndarray((128, 512), dtype=nl.bfloat16, buffer=nl.sbuf)
nisa.dma_copy(dst=a, src=w[0:128, :])
nisa.reciprocal(dst=inv, data=a)

b = nl.ndarray((128, 512), dtype=nl.bfloat16, buffer=nl.sbuf)
nisa.dma_copy(dst=b, src=w[0:128, :])   # the same bytes as a
nisa.tensor_tensor(dst=inv, data1=inv, data2=b, op=nl.add)

The second load moves the same bytes from HBM again. It uses DMA bandwidth, and the instructions that read b wait for it. In a DMA-bound kernel, each repeated load adds about the time of the load to the kernel’s runtime.

After NKI allocation has placed every tensor, the compiler looks for a dma_copy whose source matches an earlier dma_copy exactly: the same tensor, the same access pattern and the same element type. The compiler removes the later dma_copy, and points its readers at the earlier destination, only when all of these conditions are true:

  • No instruction writes the source or the earlier destination between the two dma_copy instructions. In the following code, a changes before the second load, so the second load stays:

    nisa.dma_copy(dst=a, src=w)
    nisa.tensor_tensor(dst=a, data1=a, data2=a, op=nl.add)
    nisa.dma_copy(dst=b, src=w)
    
  • No instruction overwrites the earlier destination while the later destination is in use. In the following code, a changes before tensor_tensor reads b, so the second load stays:

    nisa.dma_copy(dst=b, src=w)
    nisa.tensor_tensor(dst=a, data1=a, data2=a, op=nl.add)
    nisa.tensor_tensor(dst=inv, data1=inv, data2=b, op=nl.add)
    
  • No instruction overwrites part of the later destination while it is in use. In the following code, half of b changes before tensor_tensor reads all of b, so the second load stays:

    nisa.dma_copy(dst=b, src=w)
    nisa.tensor_tensor(dst=b[:, 0:256], data1=inv[:, 0:256],
                       data2=inv[:, 0:256], op=nl.add)
    nisa.tensor_tensor(dst=inv, data1=inv, data2=b, op=nl.add)
    

    An instruction that overwrites all of b does not keep the load, because the kernel no longer uses the loaded data after that instruction.

Because the removal runs after allocation, it does not change where tensors go or how much SBUF the kernel allocates. For the same reason, the load stays when NKI allocation has already given the memory of the earlier tensor to another tensor before the last read of the later tensor. On an LNC=2 kernel, the compiler removes a redundant dma_copy on each core independently.

How address rotation removes waits#

An allocator reuses memory. After the kernel no longer needs a tensor, a later tensor can go at an address that overlaps it. When the two tensors do not depend on each other, the write into the later tensor must still wait until every read of the earlier tensor at that address is done. This write-after-read wait comes only from where the tensors are. On the critical path, the wait stops instructions from overlapping, for example a load into the later tensor and the compute that reads the earlier tensor.

After allocation, the compiler looks for such waits. Where it finds memory that is free while the later tensor is live, it moves the later tensor to that memory, so the two instructions no longer use the same memory. Rotation uses no additional memory. address_rotation controls which tensors the compiler can move:

  • With neuronx-cc allocation, the default AUTO already lets the compiler move most tensors. Only tensors with an explicit address stay fixed.

  • With NKI allocation, AUTO keeps every tensor where NKI allocation put it. Only ENABLE lets the compiler remove the waits that NKI allocation created. OptLevel.O2 changes AUTO to ENABLE.

OptLevel.O2 also turns on prefetch_auto, which places DMA load destinations apart from compute tensors from the start. Fewer such waits are then left for rotation to remove.

Rotation moves one tensor away from another. It does not separate the live ranges of one tensor that the kernel reloads in every iteration. For that case, see How split_reused_buffers splits live ranges.

How element widening works#

The time that a tensor_copy or a memset takes increases with the number of elements it processes in each partition. A bfloat16 tensor has twice as many elements as a float32 tensor of the same size in bytes, and a float8 tensor has four times as many. Two kinds of instruction do not need to know the data type of their bytes:

  • A tensor_copy whose source and destination have the same data type copies the bytes unchanged:

    src = nl.ndarray((128, 512), dtype=nl.bfloat16, buffer=nl.sbuf)
    dst = nl.ndarray((128, 512), dtype=nl.bfloat16, buffer=nl.sbuf)
    nisa.tensor_copy(dst=dst, src=src)   # 512 elements per partition
    
  • A memset to zero writes bytes that are all zero, and zero has the same bit pattern at every element width:

    tile = nl.ndarray((128, 512), dtype=nl.bfloat16, buffer=nl.sbuf)
    nisa.memset(dst=tile, value=0.0)     # 512 elements per partition
    

After NKI allocation has placed every tensor, element_widening rewrites each of these instructions to treat its bytes as 2-byte or 4-byte integers:

  • For a same-type tensor_copy, the compiler rewrites the source and the destination. The preceding tensor_copy then moves 256 4-byte elements per partition instead of 512 bfloat16 elements.

  • For a zero memset, the compiler rewrites the destination, and the value becomes an integer zero of the new width. The preceding memset then writes 256 4-byte elements per partition instead of 512 bfloat16 elements.

The instruction moves the same bytes, so the result is bit-exact. The compiler uses the widest element, 2 or 4 bytes, that keeps every access whole:

  • The start address and the number of bytes accessed in each partition are a multiple of the new element size.

  • The innermost dimension of each access is contiguous, and every other dimension steps by whole new elements.

How engine balancing chooses engines#

Some instructions can run on more than one engine. Without engine=, such an instruction gets a fixed default engine, the same for every call. The default is Vector for nisa.tensor_scalar, nisa.tensor_tensor and nisa.memset. A kernel that issues many of these instructions puts them all in the Vector queue, while Scalar or GpSimd can be idle.

With engine_balancing, NKI scheduling estimates when each such instruction would finish on each engine that can run it. The estimate includes the work already waiting on that engine. NKI scheduling then puts the instruction on the engine where it finishes first. When the estimates are almost equal, the engine that has received less of this work so far gets the instruction. NKI scheduling already places nisa.tensor_copy this way, without the option.

The following instructions can move when they have no engine=:

  • nisa.tensor_scalar: Vector, GpSimd, and Scalar on trn2 and later.

  • nisa.tensor_tensor and nisa.memset: Vector or GpSimd.

An engine is a candidate only when it supports the operation and the data types of the instruction. An instruction that only one engine can run does not move. GpSimd is not a candidate when an operand is in PSUM, and integer arithmetic in nisa.tensor_tensor does not move. nisa.activation and nisa.activate2 always run on the engine that their engine= names, Scalar by default. DMAs, nisa.tensor_reduce, random-number instructions, collectives and single-engine instructions such as nisa.nc_matmul also keep their engine.

The choice comes from an estimate of NKI scheduling, not from a measurement. On an LNC=2 kernel, each core chooses its own engines. The exception is where the cores are not scheduled together, such as inside an nl.no_reorder block. There, both cores use the choice of the first core.

How register load reuse works#

A kernel that reads a tensor at a runtime position keeps the position in a (1, 1) SBUF tensor. The kernel passes that tensor as the scalar_offset of an access pattern, or as the index of NkiTensor.select(). An instruction that computes on an SBUF or PSUM tensor, such as nisa.activation or nisa.tensor_copy, reads that offset from a register. The compiler therefore loads the index into a register before each such instruction, and each load waits for the write of the index tensor. Each engine has its own register file, so the compiler puts a copy of the load on every engine.

A scalar that the kernel loads itself with nki.isa.scalar_load(), and that only DMAs started by one engine read, is loaded on that engine only. A DMA whose scalar_offset is an SBUF tensor reads the offset from the tensor itself, so it needs no register load.

With register_load_reuse, an instruction that takes the same element of the same tensor as an earlier instruction reads the register that the earlier load filled. This reuse requires that no instruction between the two can write the index tensor.

A reused register stays live from its load to the last instruction that reads it, on every engine that the load runs on. The compiler cannot spill registers to memory. To limit the number of live registers, the compiler keeps at most four loads available for reuse at a time. When it makes a new load while four loads are available, it drops the load that it made or reused least recently.

Allocation strategies#

The allocation strategy controls how NKI allocation selects an address in free memory. The kernel selects it with experimental_allocation_mode for all memories, or with experimental_sbuf_allocation_mode, experimental_hbm_allocation_mode and experimental_psum_allocation_mode for one memory (see Experimental options).

RING (default)

Gives each tensor a fresh address. RING reuses freed memory only after it reaches the end of the memory and wraps around. Until then, separate tensors, such as the clones that split_reused_buffers makes, stay at their own addresses, so loads can overlap with compute (see Why loads wait for compute). RING fragments memory the most.

FAST and MAX_REUSE

Reuse freed memory sooner, so the kernel fits in less SBUF or HBM. A tensor can then take the address of a tensor freed shortly before, and the waits of loads for compute return.

In PSUM, every strategy can place a tensor in any free banks, so the PSUM strategy matters only for a tensor that spans several banks when the free banks are not next to each other.

With prefetch_auto and no NKI_PREFETCH_RING_SIZE, as at OptLevel.O2, the SBUF strategy does not apply (see Effect on the SBUF allocation strategy). The HBM and PSUM strategies always apply.

When memory runs out, NKI allocation uses only the strategy that the kernel selects. It tries a more compact strategy only with sbuf_allocation_fallback=True (see sbuf_allocation_fallback).

HBM under RING#

In HBM, the end of the memory under RING is the end of the DRAM of one core. NKI allocation therefore reuses freed HBM only after the kernel has used all of that DRAM. Until then, the HBM that a kernel uses is about the sum of all the HBM tensors that it allocates, including tensors that are never live at the same time. This has the following effects:

  • After the kernel has used all of the DRAM, RING wraps around and reuses freed HBM. If no freed region is large enough for the next HBM tensor, the kernel fails to compile with an HBM out-of-memory error. With sbuf_allocation_fallback=True, NKI allocation then tries MAX_REUSE for HBM.

  • With lnc greater than 1, compilation also fails when the HBM of all the cores adds up to more than the DRAM of one core plus 10 percent. This check applies under every strategy, but RING makes the failure more likely.

  • A kernel that compiles can need more device memory than is available when the runtime loads it. sbuf_allocation_fallback does not help in this case, because compilation does not fail.

FAST and MAX_REUSE reuse the HBM of a tensor after its last use. A write into reused HBM waits for the reads of the tensor that used it before. For the fix of a device out-of-memory error, see Troubleshooting: NKI compile configuration.