This document is relevant for: Trn2, Trn3

Kernel reference: FGCC allgather_matmul, allgather_swiglu and matmul_reduce_scatter#

This topic documents allgather_matmul, allgather_swiglu and matmul_reduce_scatter, three fine-grained collective compute (FGCC) kernels for sequence-parallel projections, and allgather_qkv_norm_rope, the Q/K/V gather with the attention’s QK norm and RoPE. They implement one idea: split the collective next to a projection into row chunks and issue them from inside the kernel, so each chunk moves while earlier rows are multiplied. Read it for the kernels’ design and interface, or as a pattern to adapt.

Applies to#

  • Component: projections next to a sequence-parallel (SP) collective in a transformer block, at batch 1: all-gather + matmul (for example Q/K/V), all-gather + SwiGLU gate/up (the FFN’s first half), and matmul + reduce-scatter (the attention out-projection and the FFN down projection)

  • Pattern: chunk the collective that sits next to a projection and run it from the kernel, so only the first chunk’s transfer is exposed, and start that chunk’s matmuls on the rank’s own rows while it is in flight

  • Platforms: Trainium2 and Trainium3, LNC2 only; the MXFP8 variants (*_mx) run on Trainium3

  • Current user: the MiniMax-H3 DiT, through the gates in minimax_h3_transformer.py

  • Source: fgcc.py

What you should know before reading#

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

  • The NKI programming model: @nki.jit kernels over SBUF and PSUM tiles. nc_matmul takes a stationary operand of up to 128 x 128 and a moving operand of up to 128 x 512; the moving operand may have several free dimensions, the stationary one only one. A PSUM bank holds 512 float32 columns per partition.

  • Sequence parallelism: between blocks, each of the R ranks of an SP group holds m of the sequence’s R * m rows. The rows are all-gathered before a projection that needs all of them, and a projection’s rank-partial output is reduce-scattered back to the rows’ owners.

  • NKI collectives: ncc.all_gather and ncc.reduce_scatter over a ReplicaGroup, issued from inside a kernel.

  • LNC2: one logical core is two physical cores, each running one program of the kernel. nisa.core_barrier orders a buffer that both programs write before either reads it.

  • Runtime addressing: .ap(..., scalar_offset=..., indirect_dim=0) offsets a DMA by a value known only at run time, either an NkiScalar (a register) or a 1x1 int32 SBUF tensor.

Overview#

 all-gather + matmul on one rank

 compiler: [ all-gather R * m rows             ][ matmul R * m rows                    ]
 FGCC:     [ AG c0 ][ AG c1  ][ AG c2 ]
           [ own ][ mm c0 remote ][ mm c1           ][ mm c2      ]

 matmul + reduce-scatter, the mirror image

 compiler: [ matmul R * m rows                      ][ reduce-scatter       ][ AdaLN    ]
 FGCC:     [ mm c0 ][ mm c1 ][ mm c2 ][ mm c3 ][ mm c4 ]
                   [ RS c0 ][ RS c1 ][ RS c2 ][ RS c3 ][ RS c4 ]
                                                       [ AdaLN c0..c3 ][ c4 ]

allgather_matmul and allgather_swiglu return the gathered rows’ product in rank order; matmul_reduce_scatter returns this rank’s rows of the group sum, optionally with the AdaLN that follows it fused in. A model calls them behind a gate that checks the shapes against the kernels’ limits and falls back to the compiler path when a shape does not fit (see Interface).

Design#

1) In-kernel all-gathers of row chunks#

A ring that passes row shards with collective_permute, multiplying one shard while the next arrives, cannot run over a replica group that spans chips with several cores each: the runtime rejects a flat ring over it (must_use_ring for the implicit permute, failed to build ring for explicit source-target pairs). A two-level ring (within each chip, then across) works, but was much slower than one in-kernel ncc.all_gather over the same group.

The kernel therefore gathers with ncc.all_gather, one row chunk at a time. Each LNC program splits its own rows into row chunks sized for the matmul (see 3)). _row_chunks — the same rule both kernels use — takes whole stationary tiles (128 rows) and the remainder last. Fewer, bigger chunks are what both want: a chunk’s gathered slices pack into the 128 partitions together (_tiles), and a tile costs the same matmuls however few rows it holds, so full chunks leave only the remainder’s tiles partly empty; on the reduce-scatter side every chunk replays this program’s whole weight share. For example, 295 rows per program become chunks of 128, 128 and 39 rows: 38 stationary tiles over 16 slices, where chunks of 41, 58, 81 and 115 rows would take 46.

Each chunk travels in its own all-gather, K-major, so every tile loads as one contiguous run per slice; in the example that is three gathers. The kernel issues every all-gather before the first matmul.

1b) Start on the rank’s own rows#

Nothing hides the first gather, so the kernel does not wait for it to start multiplying. The first gather’s tiles begin with this rank’s own slices (both programs’), which are in its send buffer before the gather leaves, and then its remote slices follow in ring order after this rank, so no slice is multiplied twice. Later gathers are hidden behind earlier matmuls and keep the static order.

The remote ranks are only known at run time: ncc.self_index_in_replica_group gives this rank’s index me, and ring step i reads rank (me + i) % R. Those ranks are stored once into 1x1 int32 SBUF tiles with nisa.scalar_store, and every runtime-addressed load and store reads its scalar_offset from one of them. Holding them in registers instead (NkiScalar values) keeps R registers per kernel live across the kernel and the graph’s other kernels; each engine sequencer has 64, and a graph of a few chained blocks then fails with NCC_IGCA094.

2) Each LNC core keeps its share of the weight columns resident#

The two programs split the weight’s columns, not the rows. Each program holds its share resident in SBUF and multiplies every gathered row by it in one pass, so the whole pass overlaps the gathers. The share loads in the order the matmuls read it — k-tile by k-tile across every weight and column group (_load_weights), as nkilib’s MLP projections load theirs — so the first tile starts while the rest streams in. Every statically addressed DMA in the kernels runs on the hardware DGE (dge_mode=hwdge); only the ring’s runtime-indexed loads and stores keep the default. Because a gathered buffer holds both programs’ rows, each program waits on a core_barrier before it first reads a gather.

The share also has to fit PSUM: each 512-column group of each weight accumulates in its own 2 KB bank, and trn2 has eight. _weight_fits checks both, and a weight that does not fit stops the compile: running it in column chunks would overlap only the first chunk’s pass with the gathers. Splitting the rows between the programs instead would give each program the whole weight, twice the SBUF.

3) The gathered rows are the stationary operand#

Each program transposes its rows once, on the PE, before the gather, so every gathered slice arrives K-major. A stationary tile packs n slices of up to 128 // n rows, and the resident weight streams through it as the moving operand, 512 columns per nc_matmul. The product leaves PSUM token-major, so each slice’s rows store as they are, with no transpose back; per k-tile one stationary load serves every 512-column group (and both SwiGLU weights). The stationary operand takes one free dimension, so a tile of several slices is first copied K-major on chip (k-tile k’s rows of every slice side by side); a single-slice tile is used as loaded.

Tiles load slice-major, so each slice’s K-major rows load as one contiguous run: a row-major layout splits the same load into short runs and many more DMA descriptors, which stalls the PE between tiles.

4) Prefetch across row-chunk boundaries#

_ROW_BUFFERS = 3 rotating SBUF tiles hold the gathered rows: one is multiplied while the next two load, and the loads run ahead across row-chunk and gather boundaries, so a new chunk does not start with an empty pipeline. The own-row transposes before the gathers work in two of the same tiles, which leaves room for a second weight (SwiGLU).

5) Reduce-scatter in destination-block chunks#

matmul_reduce_scatter mirrors the gather, in the same row chunks (_row_chunks): chunk c holds rows [c * 128, (c + 1) * 128) of every destination’s block, the remainder last, so the last chunk — the one no later matmul hides — is the shortest. The rows of a are the stationary operand, 128 at a time inside one destination’s block, and the weight streams in 512-column groups, so results land token-major in the chunk’s send buffer without a transpose. As in the gather, the k-tile loop is the outer one: per k-tile one stationary load serves _SCATTER_PASS_GROUPS = 3 groups, each in its own PSUM bank, so two passes in flight and the token-major a’s transposes fit the eight banks. The groups leave PSUM into one tile, so each destination block stores with one DMA of this program’s columns, as the gather stores its tiles. After a core_barrier (the send buffer holds both programs’ columns), the chunk’s ncc.reduce_scatter goes out while the next chunk is multiplied, into its own receive buffer. The copies from the receive buffers to the output are issued after every reduce-scatter, so none queues ahead of a later chunk’s stores. Rows of a from S to padded_rows are sent as zeros.

transpose_a selects the operand layout: a given K-major (for example an attention output that is already d-major) or token-major, which is transposed per destination block on the PE. _scatter_plan keeps a K-major a resident in SBUF when it fits beside the weight share and otherwise loads it per destination block. The weight share always stays resident: running it in column pieces would reload every piece for every row chunk, so a shape whose share does not fit fails the kernel’s assert.

5b) The AdaLN epilogue#

The scattered rows’ consumer in a DiT block is an AdaLN: Norm(residual + gate * scattered) * mul + add, every step of it per row. Left to the graph it is a second kernel, so it cannot start until the whole scattered result is in HBM — which also leaves the last chunk’s reduce-scatter, the one no matmul hides, exposed.

With adaln, matmul_reduce_scatter runs it where the receive-buffer copies would have been, through adaln_epilogue, which is adaln_quant_kernel’s own tile pipeline on HBM views — the same gated add, fp32 reduction and modulation as the standalone kernel. Each program runs it on its own columns of every row of the chunk, so it reads nothing the other program wrote and needs no barrier on the receive buffer. With RMSNorm the two programs add their per-row sums of squares through shared HBM and one core_barrier per chunk (_row_sum_sq, the row_sum hook between the statistic and the rsqrt), in program order, so both scale a row’s two halves by the same statistic; without a norm the epilogue is elementwise and needs nothing more. The epilogues of the earlier chunks then cover the last chunk’s collective, and the scattered result never makes the HBM round trip. Only RMSNorm’s statistic is exchanged, so LayerNorm is not supported here. The sum of squares adds in a different order than one whole-row reduction, so with RMSNorm the output can differ from the standalone kernel’s by a bf16 rounding.

The epilogue’s tiles (the scattered and residual rows, the per-row modulation inputs, the fp32 gated product and, when it normalizes, the fp32 reduction scratch) sit in SBUF beside the reduce-scatter’s operands, and _scatter_plan does not count them, so a much wider hidden size would fail the allocator rather than fall back.

6) The SwiGLU epilogue#

allgather_swiglu shares the gather path. For each 512-column group it accumulates the gate and the up products in two PSUM tiles from the same stationary rows, then applies silu(gate) * up on the token-major result, so the hidden stores with no transpose. _weight_fits counts both weights.

6b) The attention prologue in the Q/K/V gather#

allgather_qkv_norm_rope (and allgather_qkv_norm_rope_mx) is the Q/K/V gather with the attention’s per-head QK RMSNorm and partial rotate-half RoPE run on each result tile before it is stored, so the normed and roped Q and K leave the kernel instead of a second pass over them in the graph. The default split would give one program Q and half of K, and a per-head norm needs whole heads, so each program takes two column segments instead: program 0 Q and the first half of V, program 1 K and the second half. The output columns keep the [Q | K | V] order. The norm and RoPE stay in FP32 and round to BF16 once. RoPE’s cos/sin rows are those of each row’s position in the gathered sequence, which for a ring tile is known only at run time, so the tables are read with the same scalar_offset access pattern as the slices.

Best practices#

  • Let the runtime route a collective that spans chips. An in-kernel ncc.all_gather over the whole replica group beat every permute ring we built, and the in-kernel ncc.reduce_scatter beat the compiler’s.

  • Keep the first gather short, and start on the rank’s own rows. It is the only gather nothing can hide.

  • Keep the reduce-scatter’s last chunk the shortest. Only the earlier chunks’ epilogues run behind its collective.

  • Keep runtime addresses in SBUF, not registers. A scalar_offset read from a 1x1 int32 SBUF tile holds no register; ranks held as NkiScalar values add up across a graph’s kernels.

  • Count DMA descriptors, not bytes. The same tile can cost a few hundred descriptors in one layout and tens of thousands in another, and the difference shows up as PE idle time.

  • Prefetch across chunk boundaries. A pipeline that drains at each chunk boundary pays the load latency once per chunk.

  • Barrier only where a program or a collective reads what the other program wrote, once per buffer.

  • Decide on end-to-end numbers. An isolated benchmark omits the graph around the kernel, and a kernel that is faster alone can be slower end to end, or the other way round.

Implementation#

allgather_matmul, allgather_swiglu and allgather_qkv_norm_rope share _allgather_matmul, and matmul_reduce_scatter runs _matmul_reduce_scatter, as their MXFP8 variants (allgather_matmul_mx, allgather_swiglu_mx, allgather_qkv_norm_rope_mx, matmul_reduce_scatter_mx) do; everything else in the file is a private helper. _weight_fits and _scatter_plan are the shape checks the BF16 kernels assert on, which a model’s gate mirrors (see Interface).

Gather: issue every gather, then multiply#

for c, slice_rows in enumerate(sizes):
    _transpose_rows(x, srcs[0], program, program * rows + row_off, slice_rows, contraction, k_tiles, scratch)
    gathered.append((c, recvs, srcs, row_off, slice_rows))
    row_off += slice_rows
    for src, recv in zip(srcs, recvs):
        if programs > 1:
            nisa.core_barrier(src, tuple(range(programs)))
        ncc.all_gather(dsts=[recv], srcs=[src], replica_group=group, collective_dim=0)

_transpose_rows writes this program’s rows K-major into its 128 partitions of the gather’s send buffer, so the gathered buffer holds ranks x programs slices of the chunk, each already in the stationary operand’s layout.

Schedule: own rows, then the ring, then the rest#

me = ncc.self_index_in_replica_group(group)
ring = [nl.ndarray((1, 1), dtype=nl.int32, buffer=nl.sbuf) for _ in range(num_ranks)]
for i, tile in enumerate(ring):
    nisa.scalar_store(tile, (me + i) % num_ranks if i else me)
# gather 0: ("local", own slices from src), then ("ring", remote slices at ring[1:])
# later gathers: ("static", every slice in rank order)

A ring tile loads each member slice with its own DMA, by_rank.ap(..., scalar_offset=rank_tile, indirect_dim=0) on the gathered buffer viewed [R, programs * 128, cols], and stores each slice’s rows the same way into the output viewed [R, m, N].

Multiply: two tiles loading ahead#

for i in range(min(_ROW_BUFFERS - 1, len(schedule))):
    load(i)
for i, (kind, _, _, row_off, slice_rows, members) in enumerate(schedule):
    if i + _ROW_BUFFERS - 1 < len(schedule):
        load(i + _ROW_BUFFERS - 1)
    rows_sb = _k_major(tile[0], len(members), slice_rows, k_tiles)
    for s, (col, cols) in enumerate(segments):
        res = _matmul_tile(rows_sb, resident[s], tile_rows, contraction, k_tiles, cols, x.dtype)
        if prologue is not None and s == 0:
            _qk_norm_rope(res, ...)
        _store_rows(res, out, out_by_rank, members, rows, row_off, slice_rows, col, cols)

schedule lists every stationary tile in order, so the loads run ahead across chunk and gather boundaries, and load waits on a gather’s core_barrier the first time it reads it. A program’s segments are its one share of the columns, or its two for the prologue (see 6b). _matmul_tile accumulates over the contraction in PSUM per 512-column group (two accumulators for SwiGLU) and evacuates the token-major result once; _store_rows stores each slice’s rows. The MXFP8 path quantizes the rows before the gather and sends each chunk as one FP8 buffer, only the words and block scales the MX matmul reads (_mx_slice_layout); it loads the slices straight into the MX matmul’s layout and multiplies with _mx_matmul_tile instead.

Reduce-scatter: multiply a chunk, then send it#

for c, s in enumerate(_row_chunks(m)):
    for b in range(num_ranks):
        ...  # rows [b * m + off, + s) @ this program's columns into send[b * s : (b + 1) * s]
    if programs > 1:
        nisa.core_barrier(send, tuple(range(programs)))
    ncc.reduce_scatter(dsts=[recv], srcs=[send], op=nl.add, replica_group=group, collective_dim=0)
for c, (recv, off, s) in enumerate(received):
    ...  # recv -> out, or adaln_epilogue on this program's columns of the chunk's rows

Interface#

allgather_matmul(x, w, groups)
allgather_swiglu(x, w_gate, w_up, groups)
allgather_qkv_norm_rope(x, w, groups, q_gamma, k_gamma, num_heads, head_dim, eps, cos, sin)
matmul_reduce_scatter(a, w, groups, padded_rows, transpose_a=False,
                      adaln=None, residual=None, mul=None, add=None, gate=None,
                      row_indices=None)

Argument

Type/shape

Description

x

[m, K]

This rank’s rows. m must divide by the LNC program count.

w, w_gate, w_up

[K, N]

This rank’s weight columns. N must divide by the LNC program count; w_up matches w_gate.

a

[S, K], or [K, S] with transpose_a

This rank’s rank-partial input rows. S <= padded_rows.

groups

tuple of tuples of global ranks

Every replica group, in collective order.

q_gamma, k_gamma

[1, head_dim] FP32

One head’s QK RMSNorm weights, shared by the heads. w is [Q | K | V] with num_heads * head_dim columns each.

eps

float

The RMSNorm epsilon.

cos, sin

[R * m, rotary] BF16

RoPE tables over the gathered rows, the same rows as the output; RoPE rotates each head’s first rotary channels.

padded_rows

int

R * m for an R-rank group; rows S to padded_rows contribute zeros.

transpose_a

bool

a is given K-major.

adaln

AdaLNQuantKernelArgs

The epilogue’s norm and modulation, or None for the plain reduce-scatter. Needs residual; quantization is not supported.

residual

[m, N]

The rows the epilogue adds the gated scattered rows to.

mul, add, gate

[m, N], [1, N] or [N]

The epilogue’s modulation and its gate on the scattered rows; each may be None.

row_indices

[m, 1] int32

Table row per scattered row, or None. A multi-row mul / add / gate is then a [T, N] table the epilogue gathers from, as in adaln_quant_kernel.

allgather_matmul, allgather_swiglu and allgather_qkv_norm_rope return [R * m, N] in shared HBM, group rank i’s rows at [i * m, (i + 1) * m). matmul_reduce_scatter returns [m, N], this rank’s rows of the group sum, or with adaln the pair (residual_out, modulated), which hold the same rows when the epilogue neither normalizes nor modulates. A shape no plan fits fails a kernel_assert at trace time.

Dispatch and fallback in the current user. In minimax_h3_transformer.py, _can_use_sp_gather_kernel and _can_use_sp_scatter_kernel gate the sites and record each decision as minimax_h3_sp_qkv, minimax_h3_sp_out or minimax_h3_sp_ffn (and MiniMaxH3Attention._fuses_qk_prologue as minimax_h3_sp_qkv_norm_rope), as the Wan gates (_can_use_wan_mlp_kernel) do. They require a device that can run NKI kernels and batch 1, then check the shape with one condition and one reason each: the rows and columns split over the LNC cores, the PSUM banks, and the SBUF share, from _FGCC_* constants mirrored from _sbuf_bytes and _scatter_bytes (nl.tile_size.sbuf_fmax_bytes needs a kernel trace). A refused site takes the compiler path (sp_all_gather_seq and a matmul, NF.mlp, or o_proj and sp_exit). Only the platform fallback is marked by_design, so VLLM_OMNI_NEURON_REQUIRE_NKI_KERNELS=1 raises on a shape fallback and logs the platform one. _local_rows pads each sequence slice to a multiple of TP x LNC so the rows split across both programs.

Performance notes#

  • Wins: each projection’s collective runs behind its matmul except for the part of the first gather that the rank’s own rows do not cover, and the part of the last reduce-scatter chunk that the earlier chunks’ epilogues do not cover. In gather-only and reduce-scatter-only probes the in-kernel collectives were also faster than the compiler’s.

  • What bounds each kernel: an all-gather + matmul with a large K * N per row is bound by the matmul, and one with a small weight by the gather; a matmul + reduce-scatter with a small K runs at the reduce-scatter’s speed, so only fewer bytes make it faster.

  • Costs: LNC2 and batch 1 only, and the weight share must stay resident in SBUF — a shape that fails _weight_fits or _scatter_plan fails the kernel’s assert rather than running in column chunks, whose later passes would not overlap the collectives. Streaming a instead of keeping it resident is slower and has not been tuned. A SwiGLU and its down projection stay two kernels: their three weights rarely fit SBUF together.

Adapting this kernel#

  • Check the replica group’s topology first. Within one chip, a permute ring may be enough. Across chips on trn2, use the in-kernel all_gather and reduce_scatter.

  • Check the shape before you trace. A model’s gate mirrors _weight_fits and _scatter_plan in plain Python (see Interface); update its SBUF and PSUM constants before enabling another platform.

  • Confirm the kernel ran. A gate that logs its decision (as kernel_choice.py’s [nki_kernel] ... path=nki lines do) shows a shape fallback as path=torch.

  • Validation: compare each kernel to the compiler path bit for bit on every rank, at a replica group that spans chips, and in a graph that chains several blocks (register and ordering problems appear only there); then A/B the generated output end to end.

  • Recompile after a kernel change. Lite keys a kernel’s build on its @nki.jit entry’s source only, so a change to a helper alone runs as the old kernel: edit the entry (its docstring) too. Dynamo’s precompile packages under $VLLM_CACHE_ROOT/neuron/torch_compile replay a traced kernel the same way; use a fresh VLLM_CACHE_ROOT for each kernel version.

Common issues#

enc_init_comm ... must_use_ring or failed to build ring at init#

  • Possible solution: A collective_permute ring was built over a replica group that spans chips. Use the in-kernel ncc.all_gather or ncc.reduce_scatter over the whole group (see Design).

NCC_IGCA094 ... too many registers live concurrently on engine Pool#

  • Possible solution: Runtime offsets were held in registers (NkiScalar values used as scalar_offset), and their live ranges added up across the kernels of one graph; each engine sequencer has 64 registers. A single kernel can compile while a graph of several blocks fails. Store each runtime offset once into a 1x1 int32 SBUF tile (nisa.scalar_store) and pass the tile as scalar_offset (see 1b)).

kernel_assert on the weight share, the reduce-scatter plan or the LNC split#

  • Possible solution: The gate passed a shape the kernel refuses, so the gate’s mirrored limits and the kernel disagree. Check _weight_fits (SBUF and PSUM for the gather) and _scatter_plan (the weight share plus one row block of a) against the gate’s _FGCC_* constants and the per-program values the kernel derives, and that the rows are padded to a multiple of the group size x LNC.

RHS AP can only have one free dimension#

  • Possible solution: A multi-dimensional access pattern was passed as the stationary operand. It may have only one free dimension: copy a tile of several gathered slices K-major into one SBUF tile first, as _k_major does.

Collective operation ALLGATHER ... is currently not supported [SB2SB:1]#

  • Possible solution: An all-gather was issued from SBUF to SBUF at a size the runtime does not support. Gather into HBM and load the tiles from there.