This document is relevant for: Trn2, Trn3

Reference: NKI CompileConfig options#

This topic provides reference for the per-kernel compile options of nki.compiler.CompileConfig in the AWS Neuron SDK. Use this page to look up the default of an option, the allocation and scheduling modes in which it acts, what it costs, and how to confirm that it took effect.

Overview#

Pass a nki.compiler.CompileConfig to nki.jit() to select the allocation and scheduling modes of a kernel and its optimizations. The following kernel uses NKI allocation and enables prefetch_auto:

import nki
import nki.isa as nisa
import nki.language as nl
from nki.compiler import Allocation, CompileConfig


@nki.jit(
    compile_config=CompileConfig(allocation=Allocation.LINEAR, prefetch_auto=True)
)
def add_one_kernel(x):
    """out = x + 1."""
    tile = nl.ndarray(x.shape, dtype=x.dtype, buffer=nl.sbuf)
    nisa.dma_copy(dst=tile, src=x)
    result = nl.ndarray(x.shape, dtype=x.dtype, buffer=nl.sbuf)
    nisa.tensor_scalar(dst=result, data=tile, op0=nl.add, operand0=1.0)
    out = nl.ndarray(x.shape, dtype=x.dtype, buffer=nl.shared_hbm)
    nisa.dma_copy(dst=out, src=result)
    return out


The API reference of CompileConfig lists every option. This page covers the options that need more than a few sentences. For how each optimization works, see Deep dive: NKI compile configuration. This page uses the terminology of that topic: NKI allocation is allocation=Allocation.LINEAR, NKI scheduling is scheduling=True with NKI allocation, and neuronx-cc allocation is the default or allocation=Allocation.COLORING.

Usage#

Use this reference to look up one option. Each option section starts with a field list:

Default

The value of the option when the kernel does not set it.

At OptLevel.O2

Whether opt_level=OptLevel.O2 turns the option on.

Acts with

The allocation and scheduling modes in which the option has an effect. See Options by mode for what happens in other modes.

To select options for a kernel, see How to tune a NKI kernel with CompileConfig.

Allocation and scheduling modes#

allocation and scheduling select which compiler allocates and schedules the kernel. opt_level selects how many optimizations NKI applies (see Optimization levels). The following kernel sets all three. It uses NKI allocation and NKI scheduling at OptLevel.O2. NKI scheduling is experimental (see Availability), so start without scheduling=True.

import nki
import nki.isa as nisa
import nki.language as nl
from nki.compiler import Allocation, CompileConfig, OptLevel


@nki.jit(
    compile_config=CompileConfig(
        allocation=Allocation.LINEAR,
        scheduling=True,
        opt_level=OptLevel.O2,
    )
)
def add_one_per_tile(in_tensor):
    """out = in + 1, one (128, 512) tile at a time."""
    out = nl.ndarray(in_tensor.shape, dtype=in_tensor.dtype, buffer=nl.shared_hbm)
    for i in range(in_tensor.shape[0]):
        tile = nl.ndarray((128, 512), dtype=in_tensor.dtype, buffer=nl.sbuf)
        nisa.dma_copy(dst=tile, src=in_tensor[i])
        result = nl.ndarray((128, 512), dtype=in_tensor.dtype, buffer=nl.sbuf)
        nisa.tensor_scalar(dst=result, data=tile, op0=nl.add, operand0=1.0)
        nisa.dma_copy(dst=out[i], src=result)
    return out


allocation

scheduling

Mode

None (default)

None or False

neuronx-cc allocation and scheduling.

Allocation.COLORING

None or False

neuronx-cc allocation and scheduling.

Allocation.LINEAR

None or False

NKI allocation, neuronx-cc scheduling.

Allocation.LINEAR

True

NKI allocation and NKI scheduling (experimental).

Any other combination raises ValueError when you create the CompileConfig, because scheduling=True needs Allocation.LINEAR.

None and Allocation.COLORING compile the kernel the same way in this release. Use None to follow the default, which can change in a future release. Use Allocation.COLORING to keep neuronx-cc allocation for the kernel when the default changes, or when a framework integration selects another mode for kernels that set no allocation.

Options by mode#

Most options change NKI allocation or NKI scheduling, so they act only in those modes. In the following table, “Error” means that CompileConfig raises ValueError when you set the option to a value other than its default. For register_load_reuse, that value is False.

Options

allocation not set

Allocation.COLORING

Allocation.LINEAR, scheduling not True

Allocation.LINEAR, scheduling=True

Allocation options: split_reused_buffers, tensor_copy_elim, remove_unused_instructions, remove_overwritten_writes, sbuf_allocation_fallback, experimental_allocation_mode and the experimental_*_allocation_mode options

No effect

Error

Act

Act

prefetch_auto, dma_copy_elim and element_widening

No effect

No effect, no error

Act

Act

Scheduling options: engine_balancing, register_load_reuse and experimental_scheduling_heuristic

No effect. Error with scheduling=False.

Error

Error

Act

A kernel that sets no allocation uses the default mode, which is neuronx-cc allocation, so these options have no effect. A framework integration can select NKI allocation for kernels that set no allocation. In that case, the allocation options act as with NKI allocation. The scheduling options act only when the framework also selects NKI scheduling. Otherwise, they have no effect, and no ValueError occurs.

The other options follow these rules:

Option

Acts with

barrier_check, dead_code_elim, address_rotation

Every mode.

non_ssa_legalization

neuronx-cc allocation only. With Allocation.LINEAR, no error and no benefit; use split_reused_buffers.

nki_alloc_fallback

NKI allocation only. With Allocation.COLORING, no error and no effect.

opt_level

NKI allocation only. With neuronx-cc allocation, no error and no effect.

With nki_alloc_fallback=True, a kernel that runs out of memory in NKI allocation compiles with neuronx-cc allocation, and the options that need NKI allocation have no effect for it (see nki_alloc_fallback).

The following rules apply to every option on this page:

  • An optimization can make one kernel faster and another kernel slower. Compare the runtime with and without the option, and check its effect in a profile.

  • The option is part of the compiled kernel. A kernel compiled with the option does not reuse a cached compilation without it.

Optimization levels#

opt_level

Effect

OptLevel.O0

A predictable baseline. Each instruction that has no engine= and that more than one engine can run, including nisa.tensor_copy, runs on its default engine. engine_balancing has no effect.

OptLevel.O1 (default)

The compiler chooses the engine of each nisa.tensor_copy that has no engine=. Other instructions that have no engine= run on their default engine, unless engine_balancing is on.

OptLevel.O2

O1, plus these options: prefetch_auto, split_reused_buffers, tensor_copy_elim, dma_copy_elim, element_widening, remove_unused_instructions and remove_overwritten_writes (see dead_code_elim, remove_unused_instructions and remove_overwritten_writes), and address_rotation=AddressRotation.ENABLE when address_rotation is AUTO. With scheduling=True, also engine_balancing.

An option that you set explicitly works as follows at every level:

  • prefetch_auto, split_reused_buffers, dma_copy_elim, element_widening, engine_balancing, tensor_copy_elim, remove_unused_instructions and remove_overwritten_writes default to None. None follows the level: off at O0 and O1, on at O2. True turns the option on at every level. The exception is engine_balancing: at O0, every instruction runs on its default engine. False keeps the option off, even at O2.

  • address_rotation defaults to AUTO, which O2 changes to ENABLE. An explicit ENABLE or DISABLE stays at every level.

O2 does not change the other options, such as register_load_reuse, non_ssa_legalization and dead_code_elim. opt_level acts only with NKI allocation. With neuronx-cc allocation, every level compiles the same kernel. An explicit engine= on an instruction applies at every level.

Nested kernels#

A nested @nki.jit kernel runs inline in the top-level kernel and uses the configuration of the top-level kernel. The call raises NkiValidationError when both of these conditions are true:

  • The nested kernel sets a CompileConfig option, or lnc, to a value other than its default.

  • That value is different from the value of the top-level kernel.

The error occurs even when both kernels would compile in the same mode. The compiler does not check an option that the nested kernel leaves at its default or sets to its default. For such an option, the value of the top-level kernel applies. To apply the configuration of the top-level kernel to the nested kernel with a warning instead of the error, set SpecializationConfig(allow_nested_config_override=True) on the top-level kernel.

prefetch_auto#

prefetch_auto places DMA prefetch tensors apart from compute tensors in SBUF, so that a DMA that loads the next tile does not wait for compute that still reads the current tile. It reduces the waits in Why loads wait for compute when the load and the compute use different tensors. For the placement rules, see How prefetch_auto places SBUF tensors.

Default:

None (off at O0 and O1)

At OptLevel.O2:

On

Acts with:

NKI allocation

When to use it#

Enable prefetch_auto when the profile shows loads that wait for compute, and the load writes a different tensor than the tensor that compute reads. If the waits are a small part of the kernel’s runtime, the option cannot help much.

Cost#

The split of SBUF into a prefetch part and a compute part constrains placement:

  • Compute tensors cannot reuse memory that a prefetch tensor holds. With NKI_PREFETCH_RING_SIZE, compute tensors cannot use the prefetch region at all. The peak SBUF use of the kernel can increase, and a kernel that fits in SBUF with mixed placement can stop fitting.

  • The stricter placement can add new waits, for example between compute tensors that now share a smaller part of SBUF.

  • With the default layout, the SBUF allocation strategy does not apply (see Effect on the SBUF allocation strategy).

When anti-dependencies were not the bottleneck, these costs can make the kernel slower.

Sizing the prefetch region#

Set the NKI_PREFETCH_RING_SIZE environment variable to a number of bytes per SBUF partition to give prefetch tensors a fixed region of that size at the top of SBUF. The variable is not a per-kernel option. It applies to every kernel that the process compiles. For example:

$ NKI_PREFETCH_RING_SIZE=65536 python my_script.py

The bounds of this region are hard (see How prefetch_auto places SBUF tensors). A prefetch tensor that does not fit makes NKI allocation fail with an error that names the prefetch region:

error: Out of DMA prefetch region in sbuf while allocating 16384 bytes for a
prefetch buffer (prefetch region 8192 bytes/partition, 0 bytes live)

To fit the tensor, increase NKI_PREFETCH_RING_SIZE. Use the variable when you know how much SBUF the prefetch tensors of the kernel need: reserve that amount and leave the rest to compute.

Marking tensors with prefetch=True#

NKI allocation recognizes only DMA loads from HBM as prefetch tensors on its own. Mark a tensor with prefetch=True when the kernel fills it ahead of the compute that reads it, but it is not the destination of a DMA load. For example, mark the destination of an SBUF-to-SBUF DMA, or a compute output that the kernel writes well before the compute that reads it. NKI allocation then places the marked tensor with the prefetch tensors.

prefetch=True changes only where a tensor goes. It does not give the tensor a second buffer. When a loop writes the same tensor in each iteration, the write for the next iteration waits until the current iteration has read the tensor, wherever the tensor is. To overlap the two, use a separate tensor for each iteration, or split_reused_buffers.

Where the marked tensor goes depends on prefetch_auto and NKI_PREFETCH_RING_SIZE:

Setting

NKI_PREFETCH_RING_SIZE not set

NKI_PREFETCH_RING_SIZE above 0

prefetch_auto enabled

With the prefetch tensors.

In the prefetch region, with the DMA load destinations.

prefetch_auto disabled

The mark is ignored.

In the prefetch region. DMA load destinations are not in the region.

With NKI_PREFETCH_RING_SIZE=0, there is no prefetch region. Prefetch tensors then go where compute tensors go, and the mark has no effect.

Limits#

  • prefetch=True is accepted only for SBUF tensors, and cannot be combined with an explicit address.

  • NKI allocation recognizes only DMA loads from HBM as prefetch tensors on its own.

  • The compiler does not move a tensor allocated with prefetch=True during address rotation, with any value of address_rotation.

How to check it#

In the instruction timeline of Neuron Explorer, find a DMA load into a tile and the compute instruction that reads the previous tile. Without the option, the load starts only after that compute instruction ends. With the option in effect, the load starts while that compute instruction still runs.

Example#

The following kernel loads x into SBUF, computes 1 / x into computed, and then adds one. loaded is a DMA load destination, so prefetch_auto treats it as a prefetch tensor on its own. computed is a compute output, and prefetch=True places it with the prefetch tensors as well. result stays a compute tensor, at the bottom of SBUF.

import nki
import nki.isa as nisa
import nki.language as nl
from nki.compiler import Allocation, CompileConfig


@nki.jit(
    compile_config=CompileConfig(allocation=Allocation.LINEAR, prefetch_auto=True)
)
def prefetch_hint_kernel(x):
    """out = 1 / x + 1."""
    loaded = nl.ndarray(x.shape, dtype=x.dtype, buffer=nl.sbuf)
    nisa.dma_copy(dst=loaded, src=x)
    computed = nl.ndarray(x.shape, dtype=x.dtype, buffer=nl.sbuf, prefetch=True)
    nisa.reciprocal(dst=computed, data=loaded)
    result = nl.ndarray(x.shape, dtype=x.dtype, buffer=nl.sbuf)
    nisa.tensor_scalar(dst=result, data=computed, op0=nl.add, operand0=1.0)
    out = nl.ndarray(x.shape, dtype=x.dtype, buffer=nl.shared_hbm)
    nisa.dma_copy(dst=out, src=result)
    return out


Example: the next load overlaps compute#

The following kernel doubles x one tile at a time, and keeps each tile in a separate tensor. It uses the FAST strategy, which reuses freed memory early (see Allocation strategies).

  • Without prefetch_auto, each tile takes the address that the previous tile freed. The load of tile i+1 then waits until the compute on tile i has read it, and the kernel loads, computes and stores one tile at a time.

  • With prefetch_auto, the tiles are prefetch tensors, at different addresses above the doubled tensors. NKI scheduling issues the load of tile i+1 before the compute on tile i, so the two can run at the same time.

Under RING, the default strategy, the tiles of this small kernel are at different addresses with or without the option. The option then does not change the order of loads and compute.

import nki
import nki.isa as nisa
import nki.language as nl
from nki.compiler import Allocation, AllocationMode, CompileConfig


@nki.jit(
    compile_config=CompileConfig(
        allocation=Allocation.LINEAR,
        scheduling=True,
        experimental_sbuf_allocation_mode=AllocationMode.FAST,
        prefetch_auto=True,
    )
)
def double_each_tile(x):
    """out[i] = 2 * x[i] for x of shape (n, 128, 512)."""
    out = nl.ndarray(x.shape, dtype=x.dtype, buffer=nl.shared_hbm)
    for i in range(x.shape[0]):
        # A separate tensor for each tile, so the load of tile i + 1 does not
        # have to overwrite tile i.
        tile = nl.ndarray((128, 512), dtype=x.dtype, buffer=nl.sbuf)
        nisa.dma_copy(dst=tile, src=x[i])
        doubled = nl.ndarray((128, 512), dtype=x.dtype, buffer=nl.sbuf)
        nisa.tensor_scalar(dst=doubled, data=tile, op0=nl.multiply, operand0=2.0)
        nisa.dma_copy(dst=out[i], src=doubled)
    return out


split_reused_buffers#

split_reused_buffers splits the live ranges of a reused SBUF tensor into separate tensors. Instructions that use different live ranges then no longer depend on each other through the memory that they share. You do not need to change the kernel. For how the split works, see How split_reused_buffers splits live ranges.

A reused tensor is one nl.ndarray that the kernel fills, reads, and then fills again with new data that does not depend on the old data. Each fill and the reads of that fill are one live range of the tensor.

Default:

None (off at O0 and O1)

At OptLevel.O2:

On

Acts with:

NKI allocation

When to use it#

Enable split_reused_buffers when the profile timeline shows loads into one tensor and the compute that reads it alternating: the load for the next iteration starts only after the compute on the previous iteration ends. The largest gains are in DMA-bound kernels that reload a weight or activation tile into the same tensor many times. Compute-bound kernels seldom get faster.

Cost#

The split does not increase the amount of SBUF that is live at any time. Under FAST and MAX_REUSE, the clones can share an address, and the option does not help (see How split_reused_buffers splits live ranges). With sbuf_allocation_fallback=True, NKI allocation can change to these strategies when SBUF runs short. When the waits on the reused tensor were not the bottleneck, the option does not help.

Limits#

The compiler does not split a tensor when any of the following conditions is true:

  • The tensor is not in SBUF, or it has only one live range.

  • The tensor has an explicit address.

  • The kernel uses the tensor inside a loop that stays rolled, such as an nl.fori_loop without unroll=True, and did not allocate the tensor in that loop.

  • A write to the tensor can leave some of the bytes that it addresses unchanged, such as a predicated copy, a stream shuffle, or a DMA with a dynamic or out-of-bounds-skipping access pattern. Such a write does not show which data the later reads see, so the split is not safe.

  • The reuse is not regular: the first write that recurs does not recur after a read of the tensor, as a write that loop iterations repeat would.

On an LNC=2 kernel, each core holds its own copy of the tensor, so a write on one core never ends a live range on the other core.

How to check it#

In the instruction timeline of Neuron Explorer, find the load for the next iteration. Without the option, it starts only after the compute of the current iteration ends. With the option in effect, it starts while that compute still runs.

Example#

The following kernel streams x through SBUF 128 rows at a time. The kernel allocates tile and res once and overwrites both in every iteration. With split_reused_buffers, each iteration gets its own clone of both, so the load for the next iteration can run while the current iteration computes.

import nki
import nki.isa as nisa
import nki.language as nl
from nki.compiler import Allocation, CompileConfig


@nki.jit(
    compile_config=CompileConfig(
        allocation=Allocation.LINEAR, split_reused_buffers=True
    )
)
def split_reused_kernel(x):
    """out = 1 / x, streamed through SBUF 128 rows at a time."""
    out = nl.ndarray(x.shape, dtype=x.dtype, buffer=nl.shared_hbm)
    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):
        nisa.dma_copy(dst=tile, src=x[i * 128 : (i + 1) * 128, :])
        nisa.reciprocal(dst=res, data=tile)
        nisa.dma_copy(dst=out[i * 128 : (i + 1) * 128, :], src=res)
    return out


non_ssa_legalization#

non_ssa_legalization lets the compiler split a reused tensor into one clone per live range with neuronx-cc allocation. It removes the same waits that split_reused_buffers removes with NKI allocation (see How split_reused_buffers splits live ranges).

Default:

False

At OptLevel.O2:

Not changed

Acts with:

neuronx-cc allocation (allocation=Allocation.COLORING, or no allocation)

With non_ssa_legalization=True, the compiler replaces each reused tensor with one clone per live range. neuronx-cc allocation then places each clone separately, so it can place the clones at different addresses. The load for the next use can then overlap with the compute that still reads the previous use.

When to use it#

Enable non_ssa_legalization with neuronx-cc allocation in the same conditions as split_reused_buffers with NKI allocation: the profile shows that the load into a reused tensor waits for the compute that reads the previous use, and these waits are on the critical path.

Cost#

Each clone has the full size of the original tensor. neuronx-cc allocation decides where the clones go and how much SBUF they take together. When the waits on the reused tensor were not the bottleneck, the option does not help.

Limits#

The compiler does not split a tensor when any of the following conditions is true:

  • The tensor is an input or output of the kernel, or the cores share it.

  • The tensor has only one live range, or its reuse is not regular: the same write does not recur after a read of the tensor, as a write that loop iterations repeat would.

  • A write to the tensor can leave some of the bytes that it addresses unchanged, such as a predicated copy or a DMA with a dynamic access pattern.

  • The tensor is a PSUM tensor that a matrix multiplication accumulates into.

  • The kernel accesses the tensor from more than one block of control flow, for example inside and outside a loop that stays rolled.

With allocation=Allocation.LINEAR, NKI allocation has already placed every tensor when the compiler splits them. Every clone keeps the address that NKI allocation selected for the original tensor, so the option does not help. The exception is when nki_alloc_fallback compiles the kernel again with neuronx-cc allocation. With NKI allocation, use split_reused_buffers instead.

How to check it#

Compare a profile with the option and a profile without it. With the option in effect, the load into the reused tensor for the next iteration starts while compute still reads the tensor of the current iteration.

tensor_copy_elim#

tensor_copy_elim removes an nisa.tensor_copy whose readers can read the source of the copy directly. The readers then read the source, and the compiler does not allocate the destination of the copy. For the conditions that a copy must meet, see tensor_copy_elim.

Default:

None (off at O0 and O1)

At OptLevel.O2:

On

Acts with:

NKI allocation

When to use it#

Enable tensor_copy_elim when a profile shows tensor_copy instructions that only move a tile that the next instruction could read in place, and the engines that run those copies (Vector, Scalar or GpSimd) are busy. The option matters most with NKI scheduling. Without NKI scheduling, a later removal in compilation removes many of these copies (see Copy removal later in compilation).

Cost#

  • The source tensor stays allocated until its last reader, instead of until the copy. For a PSUM source, this holds its PSUM bank longer, which can leave less room for other PSUM tensors.

  • A reader that read SBUF now reads PSUM, which can change how long the reader takes.

Limits#

  • The allocation strategy, such as experimental_sbuf_allocation_mode, does not change which copies the option removes, because the option runs before NKI allocation assigns any address.

  • A copy that does not meet every condition in tensor_copy_elim stays, and the kernel compiles as written.

How to check it#

Search the instruction timeline of Neuron Explorer for tensor_copy instructions in a profile with the option and in a profile without it. With the option in effect, the removed copies are not on the Vector, Scalar or GpSimd engine, and their readers start without waiting for them.

Example#

The following kernel multiplies two tiles into PSUM, copies the result to SBUF, and applies exp. The activation can read PSUM, so tensor_copy_elim removes the copy, and the activation reads product in PSUM directly. The compiler does not allocate product_sbuf.

import nki
import nki.isa as nisa
import nki.language as nl
from nki.compiler import Allocation, CompileConfig


@nki.jit(
    compile_config=CompileConfig(
        allocation=Allocation.LINEAR,
        scheduling=True,
        tensor_copy_elim=True,
    )
)
def exp_of_matmul(a, b):
    """out = exp(a.T @ b) for a of shape (128, 128) and b of shape (128, 512)."""
    a_tile = nl.ndarray(a.shape, dtype=a.dtype, buffer=nl.sbuf)
    b_tile = nl.ndarray(b.shape, dtype=b.dtype, buffer=nl.sbuf)
    nisa.dma_copy(dst=a_tile, src=a)
    nisa.dma_copy(dst=b_tile, src=b)

    product = nl.ndarray((128, 512), dtype=nl.float32, buffer=nl.psum)
    nisa.nc_matmul(dst=product, stationary=a_tile, moving=b_tile)

    # The copy only moves the matmul result out of PSUM. The activation can
    # read PSUM itself, so tensor_copy_elim removes the copy and the
    # activation reads `product` directly.
    product_sbuf = nl.ndarray((128, 512), dtype=nl.float32, buffer=nl.sbuf)
    nisa.tensor_copy(dst=product_sbuf, src=product)

    result = nl.ndarray((128, 512), dtype=nl.float32, buffer=nl.sbuf)
    nisa.activation(dst=result, op=nl.exp, data=product_sbuf)
    out = nl.ndarray((128, 512), dtype=nl.float32, buffer=nl.shared_hbm)
    nisa.dma_copy(dst=out, src=result)
    return out


address_rotation#

address_rotation lets the compiler move a tensor to a different SBUF address or PSUM bank after allocation, so that a write no longer waits for a read of a different tensor that shares its memory. It takes an nki.compiler.AddressRotation. For how rotation works, see How address rotation removes waits.

Default:

AddressRotation.AUTO

At OptLevel.O2:

AUTO becomes ENABLE with NKI allocation

Acts with:

Every mode

Value

Tensors that the compiler can move

AUTO (default)

Only the tensors that neuronx-cc allocation places. A tensor whose address is already fixed keeps it. Fixed tensors are tensors allocated with nl.ndarray(..., address=...) and, with allocation=Allocation.LINEAR, every tensor that NKI allocation places.

ENABLE

Every tensor, including tensors whose address is fixed.

DISABLE

None.

When to use it#

Keep AUTO unless a profile shows a reason to change it.

  • Set ENABLE when the kernel uses NKI allocation and the profile shows a write that waits for a read of a different tensor that shares its memory. OptLevel.O2 does this for you.

  • Set DISABLE to keep every tensor where the kernel or the compiler placed it, for example to compare a profile with a profile without rotation.

Cost#

Rotation uses no additional memory. When the waits that it removes are not on the critical path, a change of the value does not make the kernel faster.

Limits#

  • Rotation does not separate the live ranges of one tensor that the kernel reloads in every iteration. Use split_reused_buffers or non_ssa_legalization for that case.

  • With ENABLE, a tensor placed with nl.ndarray(..., address=...) might not be at that address in the compiled kernel.

  • The compiler does not move a tensor allocated with nl.ndarray(..., prefetch=True), with any value of address_rotation.

  • With allocation=Allocation.LINEAR at OptLevel.O2, AUTO and ENABLE compile the same kernel and share one cached compilation.

How to check it#

Compare a profile with each value. Find the write that waited and the read of the other tensor that it overlapped. Where rotation moved the tensor, the write starts before that read ends.

dma_copy_elim#

dma_copy_elim removes an nisa.dma_copy that loads data that an earlier nisa.dma_copy already loaded into SBUF. Instructions that read the destination of the removed dma_copy read the destination of the earlier dma_copy instead, so the data moves into SBUF only once. You do not need to change the kernel. For the conditions that a load must meet, see How copy elimination works.

Default:

None (off at O0 and O1)

At OptLevel.O2:

On

Acts with:

NKI allocation

When to use it#

Enable dma_copy_elim when the profile shows the same HBM data loaded into SBUF more than once while the first copy is still in SBUF. The largest gains are in DMA-bound kernels that reload a weight or activation tile for each use instead of keeping it.

Cost#

The earlier destination now stays in use until the last redirected read, so a later write to its address waits for that read. When the kernel reuses that address soon after, the removal of a load can add a wait elsewhere.

Limits#

The compiler keeps a dma_copy when any of the following conditions is true:

  • Its source has a dynamic access pattern, such as an index computed at run time.

  • Its destination is not in SBUF.

  • It fills only part of its destination, such as dst=b[:, 0:256].

  • It waits on another instruction or core, or another instruction waits on it, such as through depends_on.

  • It is inside a rolled loop, such as an nl.fori_loop without unroll=True.

  • A rolled loop or a runtime branch, such as nl.if_else, runs between it and the earlier dma_copy, or reads its destination.

NKI unrolls a Python for loop when it traces the kernel, so the compiler checks the iterations of such a loop like straight-line code.

How to check it#

Compare a profile with the option and a profile without it. With the option in effect, the DMA rows of the instruction timeline show fewer loads of the same HBM data.

Example#

The following kernel reads w in two stages, and each stage loads it into its own tensor. With dma_copy_elim, the compiler removes the second load, and the second stage reads the tensor of the first stage. The second stage writes its result into inv in place. If the second stage wrote a new result tensor instead, that tensor could take the memory that a frees after the first stage, and the second load would stay.

import nki
import nki.isa as nisa
import nki.language as nl
from nki.compiler import Allocation, CompileConfig


@nki.jit(
    compile_config=CompileConfig(allocation=Allocation.LINEAR, dma_copy_elim=True)
)
def dma_copy_elim_kernel(w):
    """out = 1 / w + w, in two stages that each load w."""
    out = nl.ndarray(w.shape, dtype=w.dtype, buffer=nl.shared_hbm)

    # Stage 1 loads w and computes 1 / w.
    a = nl.ndarray(w.shape, dtype=w.dtype, buffer=nl.sbuf)
    nisa.dma_copy(dst=a, src=w)
    inv = nl.ndarray(w.shape, dtype=w.dtype, buffer=nl.sbuf)
    nisa.reciprocal(dst=inv, data=a)

    # Stage 2 loads w again. dma_copy_elim removes this load and reads a.
    b = nl.ndarray(w.shape, dtype=w.dtype, buffer=nl.sbuf)
    nisa.dma_copy(dst=b, src=w)
    nisa.tensor_tensor(dst=inv, data1=inv, data2=b, op=nl.add)

    nisa.dma_copy(dst=out, src=inv)
    return out


element_widening#

element_widening runs an nisa.tensor_copy or a zero nisa.memset of 1-byte or 2-byte elements on fewer, wider elements. The instruction moves the same bytes, so the result is bit-exact, and it takes less time. You do not need to change the kernel. For how the rewrite works, see How element widening works.

Default:

None (off at O0 and O1)

At OptLevel.O2:

On

Acts with:

NKI allocation

Cost:

None known. The option does not change where tensors go, how much memory the kernel uses, or the results.

When to use it#

Enable element_widening when the profile shows tensor_copy or memset instructions on 1-byte or 2-byte data types, such as bfloat16, float16, float8 or int8, that take a noticeable part of engine time.

Limits#

The compiler does not rewrite an instruction when any of the following conditions is true:

  • For a tensor_copy: its source and destination data types are different, so it converts each element.

  • For a memset: its value is not zero. -0.0 is not zero for this purpose, because its sign bit is set.

  • Its elements are 4 bytes or wider, such as float32.

  • An access is not aligned to a wider element: its start or its size is not a multiple of twice the element size, such as dst=padded[:, 1:513] or dst=padded[:, 0:511].

  • An access is strided in its innermost dimension, such as src=tile[:, ::2].

  • An access is indirect or has an address known only at run time, such as an index computed at run time.

How to check it#

Compare a profile with the option and a profile without it. With the option in effect, the tensor_copy and memset instructions that the option rewrites take less time.

Example#

The following kernel pads a float16 tile with zero columns. With element_widening, the memset that zeroes padded runs on 512 4-byte elements per partition instead of 1024 2-byte elements. The tensor_copy into the left half of padded runs on 256 elements instead of 512.

import nki
import nki.isa as nisa
import nki.language as nl
from nki.compiler import Allocation, CompileConfig


@nki.jit(
    compile_config=CompileConfig(allocation=Allocation.LINEAR, element_widening=True)
)
def element_widening_kernel(x):
    """out = x with 512 zero columns appended, for a (128, 512) float16 x."""
    out = nl.ndarray((128, 1024), dtype=x.dtype, buffer=nl.shared_hbm)

    tile = nl.ndarray((128, 512), dtype=x.dtype, buffer=nl.sbuf)
    nisa.dma_copy(dst=tile, src=x)

    # Both instructions move 2-byte elements; element_widening runs each of
    # them on half as many 4-byte elements.
    padded = nl.ndarray((128, 1024), dtype=x.dtype, buffer=nl.sbuf)
    nisa.memset(dst=padded, value=0.0)
    nisa.tensor_copy(dst=padded[:, 0:512], src=tile)

    nisa.dma_copy(dst=out, src=padded)
    return out


engine_balancing#

engine_balancing lets NKI scheduling choose the engine of each instruction that has no engine= and that more than one engine can run. For the instructions that can move and how NKI scheduling chooses, see How engine balancing chooses engines.

Default:

None (off at O0 and O1)

At OptLevel.O2:

On, with scheduling=True

Acts with:

NKI scheduling (allocation=Allocation.LINEAR and scheduling=True)

When to use it#

Enable engine_balancing when the kernel uses NKI scheduling and a profile shows one engine, usually Vector, busy for most of the kernel. Another engine that can run the same instructions must be idle, and those instructions must have no engine=. The option cannot help when the busy engine runs instructions that cannot move, or when the kernel waits for DMAs. To move a few known instructions, set engine= on them instead, which gives a predictable result.

Cost#

  • Scheduling takes longer, more for kernels with many instructions that can move.

  • The choice comes from an estimate of NKI scheduling, not from a measurement.

  • Work moved to GpSimd can delay DMAs that use software DGE (nisa.dge_mode.swdge), because GpSimd generates their descriptors.

Limits#

  • OptLevel.O0 keeps every instruction on its default engine, even with engine_balancing=True.

  • On an LNC=2 kernel, inside an nl.no_reorder block, both cores use the engine choice of the first core.

How to check it#

Compare a profile with the option and a profile without it. With the option in effect, some instructions that ran on the busy engine run on another engine, at the same time as the instructions that remain.

Example#

The following kernel multiplies one tile by four constants with independent nisa.tensor_scalar instructions. Without engine_balancing, all four instructions run on Vector, one after the other. With engine_balancing, NKI scheduling moves some of them to another engine, such as Scalar, so they run at the same time.

import nki
import nki.isa as nisa
import nki.language as nl
from nki.compiler import Allocation, CompileConfig


@nki.jit(
    compile_config=CompileConfig(
        allocation=Allocation.LINEAR,
        scheduling=True,
        engine_balancing=True,
    )
)
def scale_four_ways(x):
    """out[k] = x * (k + 1) for k in 0..3, for x of shape (128, 512)."""
    x_tile = nl.ndarray(x.shape, dtype=x.dtype, buffer=nl.sbuf)
    nisa.dma_copy(dst=x_tile, src=x)

    out = nl.ndarray((4,) + x.shape, dtype=x.dtype, buffer=nl.shared_hbm)
    for k in range(4):
        # No engine=, so each multiply may run on Vector, Scalar or GpSimd.
        # Without engine_balancing all four run on Vector, one after another.
        scaled = nl.ndarray(x.shape, dtype=x.dtype, buffer=nl.sbuf)
        nisa.tensor_scalar(
            dst=scaled, data=x_tile, op0=nl.multiply, operand0=float(k + 1)
        )
        nisa.dma_copy(dst=out[k], src=scaled)
    return out


register_load_reuse#

register_load_reuse lets instructions that take the same runtime index from the same SBUF tensor share one register load of that index, instead of each instruction loading it again. For how the reuse works, see How register load reuse works.

Default:

True

At OptLevel.O2:

Not changed. The option is on at every level.

Acts with:

NKI scheduling (allocation=Allocation.LINEAR and scheduling=True)

When to use it#

Keep the default. Set register_load_reuse=False when the kernel fails to compile because too many registers are live at the same time, or to measure what the reuse saves. To control the register yourself, load the index once with nki.isa.scalar_load() and pass the scalar as the offset.

Cost#

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 keeps at most four loads available for reuse at a time. The option uses no SBUF or PSUM.

Limits#

An instruction loads the index into its own register, as without the option, when any of the following conditions is true:

  • No earlier load reads the same element of the same tensor, or the compiler dropped that load at the limit of four loads.

  • An instruction between the two can write or free the index tensor, or any other tensor that a load still available for reuse reads. A write to a kernel input or output, or to a tensor at an explicit address, also ends the reuse. Keep stores to the outputs after the instructions that share an index.

  • The two instructions are at different loop levels, or a rolled loop (such as nl.fori_loop without unroll=True) or an nl.if_else is between them. NKI unrolls a Python for loop when it traces the kernel, so its iterations are at one level.

How to check it#

Compare the register loads of the kernel in a profile with the default and a profile with register_load_reuse=False. With the reuse in effect, the instructions that share an index share one register load.

Example#

The following kernel applies exp to the table entry at a runtime index in four column blocks. The kernel stores the result only after the last activation, so the four activations share one register load of index. With register_load_reuse=False, the kernel loads index into a register four times, once for each activation.

import nki
import nki.isa as nisa
import nki.language as nl
from nki.compiler import Allocation, CompileConfig


@nki.jit(
    compile_config=CompileConfig(
        allocation=Allocation.LINEAR,
        scheduling=True,
        register_load_reuse=True,
    )
)
def exp_of_entry(table, entry):
    """out = exp(table[:, entry[0, 0], :]) for a table of shape (128, 4, 512)."""
    index = nl.ndarray((1, 1), dtype=nl.int32, buffer=nl.sbuf)
    nisa.dma_copy(dst=index, src=entry)
    table_sb = nl.ndarray(table.shape, dtype=table.dtype, buffer=nl.sbuf)
    nisa.dma_copy(dst=table_sb, src=table)

    # Each activation reads `table_sb` at the runtime index held in `index`, so
    # each needs the index in a register. With register_load_reuse, the four
    # activations share one register load.
    selected = table_sb.select(1, index)
    result = nl.ndarray((128, 512), dtype=table.dtype, buffer=nl.sbuf)
    for j in range(4):
        cols = slice(j * 128, (j + 1) * 128)
        nisa.activation(dst=result[:, cols], op=nl.exp, data=selected[:, cols])

    out = nl.ndarray((128, 512), dtype=table.dtype, buffer=nl.shared_hbm)
    nisa.dma_copy(dst=out, src=result)
    return out


dead_code_elim, remove_unused_instructions and remove_overwritten_writes#

Three options control the removal of instructions whose results the kernel does not use:

Option

Acts with

Effect

dead_code_elim

Every mode

True (the default) lets the compiler remove, later in compilation, an instruction whose output no instruction reads, and an nisa.tensor_copy whose readers can read the source directly. False keeps these instructions.

remove_unused_instructions

NKI allocation

Before NKI allocation, removes an instruction whose output no other instruction reads. The instruction then takes no engine time, and its tensor takes no memory.

remove_overwritten_writes

NKI allocation

Before NKI allocation, removes a write that a later write fully replaces before any instruction reads it, and a write that no instruction reads before the kernel ends.

dead_code_elim does not affect the two options that act before NKI allocation. remove_unused_instructions and remove_overwritten_writes default to None, which follows the level: off at OptLevel.O0 and OptLevel.O1, on at OptLevel.O2. True turns an option on, and False keeps it off, even at OptLevel.O2.

tensor_copy_elim is a different removal of copies (see Copy removal later in compilation). dead_code_elim=False does not keep a copy that tensor_copy_elim removes.

When to use it#

Keep an instruction whose result the kernel does not use, for example a copy that moves data out of PSUM early so that a PSUM bank becomes free sooner, or a section of the kernel that you time on its own:

  • With neuronx-cc allocation, set dead_code_elim=False.

  • With NKI allocation, also set remove_unused_instructions=False and remove_overwritten_writes=False. You need both, because remove_overwritten_writes also removes a write that no instruction reads.

Cost#

Every instruction that the compiler keeps takes engine time, and every tensor that it writes takes memory.

Limits#

  • The compiler always keeps writes to kernel outputs. With NKI allocation, it also keeps writes to kernel arguments and to nl.shared_hbm tensors, and collective operations.

  • remove_overwritten_writes has no effect on a kernel with nl.if_else, nl.while_loop, or an nl.fori_loop that is not fully unrolled.

  • An accumulating write, such as a matmul into PSUM that adds to the earlier value, is not an overwrite.

A removed instruction does not appear in the profile.

Example#

In the following kernel, no instruction reads unused. At OptLevel.O2, NKI allocation removes the reciprocal and the tensor, so the compiled kernel has only the two DMA copies. With remove_unused_instructions=False, remove_overwritten_writes=False and dead_code_elim=False added to the CompileConfig, the compiled kernel keeps the reciprocal.

import nki
import nki.isa as nisa
import nki.language as nl
from nki.compiler import Allocation, CompileConfig, OptLevel


@nki.jit(
    compile_config=CompileConfig(allocation=Allocation.LINEAR, opt_level=OptLevel.O2)
)
def unused_reciprocal_kernel(x):
    """out = x. The reciprocal is never read, so the compiler removes it."""
    tile = nl.ndarray(x.shape, dtype=x.dtype, buffer=nl.sbuf)
    nisa.dma_copy(dst=tile, src=x)
    unused = nl.ndarray(x.shape, dtype=x.dtype, buffer=nl.sbuf)
    nisa.reciprocal(dst=unused, data=tile)
    out = nl.ndarray(x.shape, dtype=x.dtype, buffer=nl.shared_hbm)
    nisa.dma_copy(dst=out, src=tile)
    return out


nki_alloc_fallback#

nki_alloc_fallback compiles a kernel with neuronx-cc allocation when NKI allocation runs out of memory.

Default:

False

At OptLevel.O2:

Not changed

Acts with:

NKI allocation

With nki_alloc_fallback=True, when NKI allocation runs out of SBUF, PSUM or HBM, the compiler compiles the kernel again with neuronx-cc allocation instead of raising the out-of-memory error, and a warning names the failure. The prefetch region error (see Sizing the prefetch region) also triggers the fallback. Allocation failures that are not a memory shortage always raise an error.

When to use it#

Turn on nki_alloc_fallback when a kernel must compile even if NKI allocation cannot place it, for example in a model that compiles many kernels. We recommend that you change the kernel to fit instead (see Out-of-memory errors), because the fallback gives up NKI allocation for that kernel.

Cost#

After the fallback, the kernel uses neuronx-cc allocation and scheduling, and the options that need NKI allocation have no effect for it (see Options by mode). Its performance can be different from its performance with NKI allocation.

How to check it#

The fallback emits a warning that starts with Kernel '<name>': NKI memory allocation ran out of memory. In this warning, “NKI allocation” is NKI allocation, “neuronx-cc allocation” is neuronx-cc allocation, and an “NKI-allocated build” is a compilation with NKI allocation.

sbuf_allocation_fallback#

sbuf_allocation_fallback lets NKI allocation try a more compact strategy when the requested strategy runs out of memory. Without the option, a kernel keeps the strategy that it requested, and the out-of-memory error names the strategies to try (see Out-of-memory errors).

Default:

False

At OptLevel.O2:

Not changed

Acts with:

NKI allocation

The SBUF strategy is experimental_sbuf_allocation_mode when it is set, and experimental_allocation_mode otherwise. The default is AllocationMode.RING. With sbuf_allocation_fallback=True, when the strategy runs out of SBUF, NKI allocation tries the next strategy and uses the first one that fits:

Requested strategy

Strategies tried, in order

RING

FAST, then MAX_REUSE

FAST

MAX_REUSE

MAX_REUSE

None

An HBM shortage causes one more attempt, under MAX_REUSE. NKI allocation does not retry a PSUM shortage. If every attempt fails, the out-of-memory error occurs as without the option. With prefetch_auto and no NKI_PREFETCH_RING_SIZE, as at OptLevel.O2, the SBUF retries place SBUF tensors the same way (see Effect on the SBUF allocation strategy).

When to use it#

Turn on sbuf_allocation_fallback when a kernel runs out of memory under its requested strategy, and you prefer a compiled kernel with less overlap of loads and compute to an error. To keep control of the strategy, set experimental_sbuf_allocation_mode yourself instead.

Cost#

A kernel that fits only after a retry can be slower than under RING (see Allocation strategies), and each retry adds compile time.

How to check it#

When you compile through nki.jit(), the compiler does not report a retry. Compile the kernel without the option. If compilation fails with an out-of-memory error, the kernel fits only with a more compact strategy.

Example#

In the following kernel, the kernel frees a before it allocates d and e, and b stays live until the end. RING places d after b instead of in the memory of a. No free part of SBUF is then large enough for e, although the three live tensors fit in SBUF together. FAST places d in the memory of a, and e fits. With its configuration, the kernel fails to compile with an SBUF out-of-memory error. With sbuf_allocation_fallback=True, NKI allocation tries FAST, and the kernel compiles. The widths are for trn2. On a target with more SBUF, scale them to its SBUF size.

import nki
import nki.isa as nisa
import nki.language as nl
from nki.compiler import Allocation, CompileConfig

# Widths in float32 columns. trn2 SBUF holds about 53,000 per partition.
A, B, D, E = 17408, 11776, 11776, 20480


@nki.jit(
    compile_config=CompileConfig(
        allocation=Allocation.LINEAR,
        sbuf_allocation_fallback=False,
        nki_alloc_fallback=False,
    )
)
def fragmenting_kernel(x):
    """out = x, for x of shape (128, E)."""
    out = nl.ndarray(x.shape, dtype=x.dtype, buffer=nl.shared_hbm)
    a = nl.ndarray((128, A), dtype=x.dtype, buffer=nl.sbuf)
    nisa.dma_copy(dst=a, src=x[:, :A])
    b = nl.ndarray((128, B), dtype=x.dtype, buffer=nl.sbuf)
    nisa.dma_copy(dst=b, src=x[:, :B])
    # The last read of a: its SBUF is free from here on.
    nisa.dma_copy(dst=out[:, :A], src=a)
    d = nl.ndarray((128, D), dtype=x.dtype, buffer=nl.sbuf)
    nisa.dma_copy(dst=d, src=x[:, :D])
    e = nl.ndarray((128, E), dtype=x.dtype, buffer=nl.sbuf)
    nisa.dma_copy(dst=e, src=x)
    nisa.dma_copy(dst=out[:, :B], src=b)
    nisa.dma_copy(dst=out[:, :D], src=d)
    nisa.dma_copy(dst=out, src=e)
    return out


Experimental options#

The options in this section are experimental. Their names, values, defaults and behavior can change in a future release. Use them to investigate a kernel, and do not depend on them in production code. They act only with NKI allocation (see Options by mode).

Allocation strategy options#

These options select the allocation strategy of NKI allocation, an AllocationMode. For what each strategy does, see Allocation strategies.

Option

Effect

experimental_allocation_mode

The strategy for SBUF, HBM and PSUM together. Default None, which is RING.

experimental_sbuf_allocation_mode

The strategy for SBUF. Overrides experimental_allocation_mode for SBUF.

experimental_hbm_allocation_mode

The strategy for HBM. Overrides experimental_allocation_mode for HBM.

experimental_psum_allocation_mode

The strategy for PSUM. Overrides experimental_allocation_mode for PSUM.

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).

experimental_scheduling_heuristic#

experimental_scheduling_heuristic selects how NKI scheduling chooses the next instruction from the instructions that are ready, a SchedulingHeuristic.

Default:

None (ASAP)

Acts with:

NKI scheduling (allocation=Allocation.LINEAR and scheduling=True)

Value

Next instruction

ASAP (default, None)

The instruction that can start first.

CRITICAL_PATH

The instruction on the longest path to the outputs of the kernel.

DMA_PREFETCH

A DMA before an instruction that is not a DMA.

TRIVIAL

The program order of the kernel.

ASAP suits most kernels. Another value can make a kernel slower, so compare the runtime with and without it.

Learn more#

This document is relevant for: Trn2, Trn3