This document is relevant for: Trn2, Trn3

Kernel reference: fa2_paged_cache_attention_cp_gather paged FA2 cache attention#

This topic documents fa2_paged_cache_attention_cp_gather, the self-attention kernel of the LingBot-World-V2 causal DiT on Neuron. One launch computes exact attention of this rank’s query shard over two key ranges: the cached history, read straight out of a paged KV pool through a per-head block table and masked on chip to the model’s sink + recent window, and the current chunk, whose K/V the kernel all-gathers over the CP group while it works on the history. On the commit pass the same launch also writes the chunk’s K/V into the pool, in place, block by block. Read it for the kernel’s design and interface, or as a pattern for any chunked autoregressive model that attends to a paged cache.

Applies to#

  • Model/component: LingBot-World-V2 14B causal-fast DiT (robbyant/lingbot-world-v2-14b-causal-fast-diffusers), self-attention of all 40 layers, in the 4 denoising passes and the t = 0 commit pass of every chunk, at every CP size

  • Pattern: attend to a paged K/V cache without materializing the history: indirect DMAs follow the block table, a two-range mask from three runtime scalars reproduces the dense window exactly, and the commit writes whole pool blocks through vllm-neuron’s per-head slot mapping

  • Platforms: Trainium 2 and Trainium 3 (BF16), each at LNC 1 and LNC 2 (see Trainium 3)

  • Source: fa2_paged.py (the entry point, the paged streams, the mask row, the commit write), lnc_split.py (the LNC 2 work split), hardware.py (the per-generation engine plan), flash_attention_fwd.py (the FA2 software pipeline) and paged_attention.py (dispatch, launch and the torch reference). Tile views come from the installed NKI Library’s nkilib.experimental.neurotile (1.0.24838 or later)

Note: FlashAttentionFwd is one FA2 primitive for Trainium 2 and Trainium 3, and the paged driver is specific to LingBot; neither is byte-identical to anything in the NKI Library.

What you should know before reading#

  • The NKI programming model: @nki.jit kernels over SBUF/PSUM tiles with explicit per-engine instructions (Tensor, Vector, Scalar, GpSimd, DMA queues).

  • FlashAttention-2 online softmax: keys stream in blocks; each query row carries a running max m, sum l and unnormalized output o, rescaled by exp(m - m') when a block raises the max. The result is exact, and the order in which key blocks are visited only changes summation order.

  • Paged KV caches: a pool of fixed-size blocks, a block table listing which blocks hold a sequence’s tokens, block 0 as the null block, and a slot mapping slot = block * block_size + offset for writes (vLLM, vllm-neuron).

  • Context parallelism: the chunk’s tokens are split contiguously over the CP group; see Context parallelism.

Overview#

LingBot generates video in chunks of 3 latent frames. At 832x480 a latent frame is 30 x 52 = 1,560 tokens, so a chunk is 4,680 tokens. Each chunk attends to its own tokens and to the clean K/V of earlier chunks: the first 9 frames (the sink, pinned) and the 6 most recent frames (the window). In steady state that is 15 frames = 23,400 history tokens. A chunk runs 4 denoising passes (“probes”, whose K/V are discarded) and one t = 0 pass on the clean latent (“commit”), whose K/V extend the history.

Per rank at TP8 x CP8: N = 5 heads, D = 128, Sq = S_local = 585 (gathered to S = 4,680), a pool block of one frame (1,560 tokens), 15 listed history blocks, a [5, 18] block table and [5, 4,680] commit indices. The history is replicated over CP: every CP rank holds the full history of its 5 TP heads and performs the identical commit, so attention needs no ring and no cross-rank softmax merge.

            one rank (tp t, cp c): 5 heads, 585 queries
   ┌────────────────────────────────────────────────────────────────────┐
   │ q [1, 585, 5, 128] ─▶ PE transpose ─▶ Q^T in SBUF (all 585 rows)   │
   │                                                                    │
   │ phase 0, every head:  paged history (15 x 1,560 tokens)            │
   │   block_table[h, 0:15] ──scalar_load──▶ indirect DMA ◀── K/V pool  │
   │   bounds ──iota+compare──▶ key bias row (0 | -29952)               │
   │   + issue all_gather(K_shard[h]), all_gather(V_shard[h]) over CP   │
   │                                                                    │
   │ phase 1, every head:  gathered chunk (4,680 tokens, all visible)   │
   │                                                                    │
   │ normalize ─▶ PE transpose ─▶ out [5, 128, 585] (d-major, o_proj)   │
   │ commit pass only: write the gathered K/V into the pool, one        │
   │                   whole block per (head, frame), in place          │
   └────────────────────────────────────────────────────────────────────┘

The kernel is reached from LingBotSelfAttention.forward (lingbot_transformer.py) through attend_over_paged_history. LingBotDiTRuntime binds one per-layer K/V view of a single pool into the compiled graphs once and, per pass, passes the KV manager’s block table, bounds and (on the commit) update indices. Probe and commit are the only two graph variants, for every chunk of every session.

Design#

A paged pool read in place, walked as a dense range#

The pool is allocated once and sliced into per-layer views (K [num_blocks, N, D, block], V [num_blocks, N, block, D]). Each listed block is DMA’d straight into SBUF; no dense copy of the history is made. Probes never write; the commit pass writes the chunk once, in the kernel.

The kernel does not tile per pool block. It walks the listed history as one contiguous range [0, Sh) with a dense kernel’s geometry, and each Sk block takes its rows from whichever pool blocks it overlaps. A 128-row tile that straddles a block boundary (1,560 = 12 x 128 + 24) is filled from both blocks, so the whole history costs one partial tile instead of 15. Only the DMA source addresses depend on the block table; the arithmetic is the dense kernel’s.

The block size is one latent frame, so every length the window uses (sink 9, window 6, chunk 3) is a whole number of blocks: eviction frees whole blocks, nothing is padded, and the commit always writes fresh blocks that no pass reads.

One graph for every chunk position#

The kernel is exact FA2 with a running max per row, and it handles a fully or partly masked history. Nothing that varies per chunk or session is a shape: the pool views are bound once, the block table is null-padded to a fixed width, bounds and the commit indices are runtime values. Warm-up (chunks 0-5, a partial or contiguous history) is handled by the mask alone: missing entries are the null block, masked by bounds. The kernel always computes all 15 listed blocks, so a warm-up chunk costs as much as a steady one.

RoPE is applied to K before it is cached, at the token’s absolute frame index, so cached keys never need re-rotation as the window slides.

The CP gather lives inside the kernel, overlapped with the history#

Each rank needs the whole chunk’s K/V but owns 1/8 of it. Gathering in torch before the kernel would put a 12 MB-per-layer collective on the critical path. The kernel instead stages its shard head-major in HBM and issues the per-head ncc.all_gathers (K and V) from the callback hook of the history pipelines. The loop is chunk-outer (all heads’ history, then all heads’ chunk), so by the time head 0 reaches its gathered chunk every gather has had most of the history phase to land. Each head’s online-softmax state stays resident in SBUF across the two phases.

Attention does not depend on the order in which all_gather stacks the CP blocks (on the device mesh it is not always rank order), so attention uses the arrival order directly. Only the commit cares, and it reads a gathered row of rank ids to fix it (see Commit write).

d-major K with a block commit#

FA2’s QK matmul contracts over D, so K must sit with D on partitions. The pool keeps K d-major ([nb, N, D, block]): history keys stream as [D, count] columns with no transpose. V is token-major, so MM2 reads it with Sk on partitions. The gathered chunk’s K is DMA-transposed on load.

The commit writes whole blocks: V as one [block, D] plane per (head, frame), K PE-transposed per 128-token tile into one [D, block] plane. That needs a commit covering whole pool blocks, which holds with one block per frame and frame-aligned chunks. The host checks every commit (commit_blocks_valid: whole blocks, in range, not the null block, no block twice, since two writers of one block would race across the two cores at LNC 2) and the runtime refuses a plan that fails it.

LNC 2: two cores per logical rank#

At LNC 2 each logical rank is two physical cores running the kernel as two SPMD programs. lnc_split.py (pure integer math) splits one launch:

Work

Split

LingBot TP8 (5 heads, 585 queries)

Attention

whole heads, N // 2 per core; an odd head’s query rows split at a 128-row tile boundary

core 0: heads 0, 1 + head 4 rows 0-255; core 1: heads 2, 3 + head 4 rows 256-584

Shard staging

over heads, into shared HBM, then a core_barrier

core 0 heads 0-2, core 1 heads 3-4

CP all-gathers

both cores issue every gather, in the same order (gather_slots)

slot 0: heads 0, 2; slot 1: heads 1, 3; slot 2: head 4

Commit write

over (head, block) items

15 blocks: core 0 8, core 1 7

  • Heads first, an odd head by rows. Five heads per rank is the normal case at TP8. Splitting the odd head’s rows gives each core ~2.5 heads of work; query rows are independent, so the output equals LNC 1’s. The split head’s history is read by both cores, the only duplicated traffic. A single-tile head (Sq <= 128) stays on core 0.

  • Collectives belong to the logical rank. Both programs trace every all_gather over the same buffers with the same replica groups and order, so their sources must be visible to both cores. Slot j gathers the heads of both cores’ j-th items, so each core’s first chunk-phase head is among the first gathered.

  • Every pool slot written once. Commit items are disjoint per core; the reordered chunk sits in shared HBM behind a barrier, since a core’s blocks can come from the other core’s copies.

At LNC 1 every split is the whole range on one core, and the kernel emits the one-core stream.

Trainium 3#

At trace time FlashAttentionFwd reads the NeuronCore version and picks an engine plan (hardware.py). Everything else (geometry, buffers, both matmuls, the mask, the paged streams, the CP gather, the commit, the LNC 2 split) is shared.

Stage

Trainium 2

Trainium 3

MM1 eviction (scale, chained row max)

Vector tensor_scalar_reduce

Scalar activate2 (the first point’s fill on Vector)

Exponential (chained row sum)

Scalar activation, bias = -max

Vector exponential, positive max

Row-sum merge

GpSimd, two tensor_tensor

GpSimd, one tensor_scalar

Drain P^T eviction

Vector

Scalar

The two reduce chains (MM1’s row max, the exp’s row sum) must sit on different engines, since each lives in one engine’s accumulator. Trainium 3’s activate2 and exponential move the max to Scalar and the exp to Vector; Trainium 2 has neither and swaps them. On Trainium 3 the kernel asserts both instructions at trace time.

Best practices#

  • Walk the logical range, page the DMA. Keep the compute walk identical to a dense kernel and make paging a property of the loads, so the arithmetic does not depend on where blocks live.

  • Make the mask a function of values, not shapes. Three int32 scalars cover empty, partial, contiguous and slid windows, and the graph never changes.

  • Hide collectives behind a pass you already pay for. The history pass is 5x longer than the chunk pass, so issuing the chunk gather from inside it costs nothing visible.

  • Let only the order-sensitive consumer pay for order. Attention takes the gather in arrival order; only the commit reads the gathered rank ids.

Implementation#

One @nki.jit entry point; everything else is private.

Loop structure#

At LNC 1, “this core’s items” are the N heads with all Sq rows each:

bt_sb   <- block_table [N, W] flattened onto one partition          (1 DMA)
bias    <- _history_bias_row(bounds, Sh)                            (on chip; not all_visible)
k_src, v_src [N, S_local, D] <- k_shard / v_shard per head          (head-major staging)

if write_only: issue every slot's all_gathers, skip to the commit
for sq_blk in Sq blocks:                         # 1 block at LingBot (5 tiles >= ceil(585/128))
    for item: Q^T <- PE transpose of q rows; fresh SBUF softmax state
    for phase in (history, chunk):               # chunk-outer
        for item a:
            history: K/V streams read the pool by block table; bias stream = mask row
                     (none with all_visible)
                     callback = the all_gathers of slot a (+ rank ids on a commit)
            chunk:   K/V streams over the gathered k_new[head], v_new[head]; no bias
            run_pipeline(Q^T, K, V, callback, bias)
    for item: normalize -> PE transpose -> out[head, :, rows] (d-major)
if commit: write k_new / v_new into the pools, block by block

All 585 queries form one Sq block, so each head’s history K/V are read from HBM exactly once per call. With sk_tile = 512 and sk_blk = 3,072, the history walk is 9 Sk blocks (270 pipeline steps) and the chunk walk 3 (90 steps). A trailing Sk block shorter than a 128 tile is cut off on its own, because V carries Sk on partitions.

Pipeline and engine assignment#

FlashAttentionFwd.run_pipeline walks the flat grid; a point is one (sk_blk, sq_tile) and spans 6 steps of 512 keys. Each stage runs a fixed number of steps ahead of MM2 (qk_offset = 24, max_update_offset = 18, exp_offset = 12, tp_offset = 1), so four points are in flight. On Trainium 2:

Stage

Engine

Work per step [128 q, 512 k]

MM1

Tensor

Q^T [128 d, 128 q] stationary, K [128 d, 512 k] moving -> PSUM fp32

Mask (history only)

Tensor

rank-1 ones[1, 128] x bias[1, 512] accumulated onto the scores

MM1 evict

Vector

PSUM -> SBUF fp32, x scale, chained row max

Max update (first tile of a point)

Vector + Scalar

new max; rescale exp(m - m'); negated max

Exponential

Scalar

exp(scores - max) -> bf16 probs, chained row sum

P-transpose

Tensor + Vector

4 x nc_transpose([128, 128]); one evict

MM2

Tensor

4 x P^T [128 k, 128 q] x V [128 k, 128 d]

Merge (last tile of a point)

Vector + GpSimd

o = o * rescale + block_out, l = l * rescale + block_sum

Scores stay fp32 from PSUM into the exponential; only the probabilities narrow to bf16.

SBUF and PSUM budget#

PSUM (8 banks of 2 KiB per partition): bank 0 the MM2 accumulator, banks 1-2 the P^T tiles (and, between pipelines, the Q, output and commit-K transposes), banks 3-7 five MM1 score tiles in flight. SBUF per partition at LingBot shapes, LNC 1:

Buffer

Bytes / partition

scores ring, 25 x [128, 512] fp32

51,200

key bias row, [1, 128 x 183] bf16 (one partition)

46,848

probs + probs_t rings

16,384

history K and V streams, double-buffered

24,576

softmax state + Q^T and O tiles, 5 heads

25,800

block-commit staging

12,896

The bias row (2 * Sh bytes) and the fp32 score ring dominate. At LNC 2 each core holds the state of its 3 items instead of 5.

The mask row from bounds#

bounds = (sink_end, window_start, kv_len) in listed-history positions; position p is visible iff p < sink_end or window_start <= p < kv_len. _history_bias_row builds the key bias once per launch:

pos[p, c] = p * 183 + c                    (iota on [128, 183] fp32, 183 = ceil(Sh / 128))
visible   = max(pos < sink_end, (pos >= window_start) * (pos < kv_len))
bias      = (visible - 1) * 29952          -> 0 or -29952, stored bf16
[128, 183] -> private HBM scratch -> one partition [1, 23,424], position order

The bias tile is added onto the scores in PSUM before the scale, so a masked score becomes about -2,650 and its exponential is exactly 0 in fp32. On chunk 0 every history key is masked; the running max is merely very negative (finite), and the chunk phase rescales the history’s contribution to 0. This relies on masked keys being finite: the pool is zeroed at allocation and the null block is never written.

Chunk

Listed (15 entries)

bounds (f = 1,560)

0

all null

(0, 0, 0)

1

3 blocks, 12 null

(3f, 3f, 3f)

5

15 contiguous

(15f, 15f, 15f)

6+

9 sink + 6 recent

(9f, 9f, 15f)

bounds need not fall on block boundaries; the mask stays exact mid-block.

From chunk 5 on every listed position is visible. The DiT then launches with all_visible=True (its steady-state graphs; the runtime checks the plan’s bounds on the host first), and the kernel builds no bias row and adds no bias matmul. A zero bias adds +0.0, so the result is bit-identical.

Commit write#

kv_cache_update_idx[h, j] is the pool slot (block * N + h) * block_size + offset of chunk token j in shard order (vllm-neuron’s build_per_head_slot_mapping). Gathered block i holds the shard of CP rank src_all[i, 0], gathered alongside the chunk on the commit, so its indices start at column src_all[i] * S_local. _commit_blocks then:

  1. puts the gathered chunk in update-index order: one HBM copy per (CP shard, head);

  2. reads every block’s first slot, kv_cache_update_idx[h, f * block];

  3. per (head, frame): writes V as one [block, D] DMA and K, PE-transposed per 128-token tile, as one [D, block] plane. A plane starts at element slot * D, so the scalar offset needs no division.

The kernel returns (out, k_pool, v_pool); returning the pools makes the compiler alias them to the inputs, so the write lands in the bound views in place. The write runs after all attention, so the commit’s attention output equals the probe’s.

With write_only=True (the commit pass’s last layer, whose attention output nothing reads) the kernel issues the CP gathers directly, in slot order on every core, and runs only the commit write: no query load, history read or attention. It returns (k_pool, v_pool).

Interface#

fa2_paged_cache_attention_cp_gather(
    q, k_shard, v_shard, k_pool, v_pool, block_table, bounds, rank_id,
    kv_cache_update_idx=None, replica_groups=(), cp_size=1, scale=1.0,
    num_history_blocks=1, gather=True, sq_tiles_per_blk=5, sk_tiles_per_blk=6,
    gather_dst_private=False, all_visible=False, write_only=False,
)

Argument

Type / shape

Description

q

bf16 [1, Sq, N, D]

This rank’s queries, token-major, not pre-scaled.

k_shard, v_shard

bf16 [1, S_local, N, D]

This rank’s shard of the chunk’s K/V (after QK-norm + RoPE). With gather=False, the whole chunk.

k_pool

bf16 [nb, N, D, block]

This layer’s d-major K view of the pool. Written in place on a commit.

v_pool

bf16 [nb, N, block, D]

This layer’s V view. Written in place on a commit.

block_table

int32 [N, W]

Per-head folded ids block * N + head; columns [0, num_history_blocks) are the listed history (null = block 0). Later columns are not read.

bounds

int32 [1, 3]

(sink_end, window_start, kv_len) over listed-history positions.

rank_id

fp32 [1, 128]

This rank’s index in its CP group, broadcast over 128 columns. Read only on a gathered commit.

kv_cache_update_idx

int32 [N, S] or None

Commit: the per-head pool slot of every chunk token, shard order. None = probe.

replica_groups

tuple of tuples

Every CP group of the world (SPMD needs the full partition).

cp_size

int

CP degree; S = S_local * cp_size when gathering.

scale

float

Softmax scale.

num_history_blocks

int, static

Listed history width; Sh = num_history_blocks * block.

gather

bool

All-gather the chunk over CP (default). False: no collective.

sq_tiles_per_blk, sk_tiles_per_blk

int

Tiling. sq_tiles_per_blk >= ceil(Sq / 128) reads each head’s history once; must exceed 3.

gather_dst_private

bool

Gather destinations in private HBM (LNC 1 only).

all_visible

bool, static

bounds masks no listed position (caller-verified): attend without the mask.

write_only

bool, static

Commit only: gather and write the chunk, no attention.

Returns: probe out bf16 [N, D, Sq] (d-major, the o-projection’s layout); commit (out, k_pool, v_pool); write_only commit (k_pool, v_pool).

Asserted at trace time: D == 128; MHA (k_shard/v_shard heads match q); pool shapes as above; block_table.shape[0] == N and num_history_blocks <= W; bounds.shape == (1, 3); Trainium 2 or later, with exponential and activate2 on Trainium 3; LNC 1 or 2 (at LNC 2 gather_dst_private=False); on a commit kv_cache_update_idx.shape == (N, S) and S a multiple of block; write_only only on a commit.

Not asserted (caller’s contract): block-table entries are valid plane ids < nb * N; masked listed blocks hold finite values; bounds < 2^24; each run of block tokens in index order maps to the consecutive slots of one distinct, non-null block inside the pool (the block writes have no range guard); commit blocks are not read in the same pass; with all_visible, bounds masks nothing. The DiT runtime checks the commit (commit_blocks_valid) and the all_visible bounds on the host before launch.

paged_attention.attend_over_paged_history(query, key_shard, value_shard, key_pool, value_pool, paged, scale, cp_group, replica_groups) takes a PagedAttentionInputs and returns [B, N, D, Sq]. It dispatches on capability, not configuration:

Condition

Path

on device, LNC 1 or 2, B == 1, D == 128, a non-empty listed history

this kernel (cp_size == 1: gather=False, no collective)

on device otherwise (LNC above 2, a NeuronCore without the instructions above, or a shape the kernel does not take)

nkilib attention_cte over the visible history gathered into a dense prefix (sink end and window start on block boundaries), then paged_commit_write_

CPU, fake-tensor tracing, NKI disabled

the torch reference (_torch_paged_attend, paged_commit_write_)

Performance notes#

  • Wins: on trn2.48xlarge at LNC 1 (TP8 x CP8, 40 layers) the kernel takes the DiT’s steady chunk from 1,231 ms with attention_cte over a gathered history to 872 ms. Kernel alone, per layer: probe 1.72 ms, commit 1.89 ms. The block-table reads cost about the same as dense reads, and the CP gather hides behind the history pass.

  • Costs: a call is ~42 GFLOP over ~75 MB, compute-bound, yet the matmuls run at about a quarter of BF16 dense peak: per history key the Tensor engine streams four passes (MM1, the bias matmul, the P-transpose, MM2) of which two carry FLOPs, and Vector makes two full-width passes per score. Warm-up chunks compute all 15 listed blocks even when masked. The history is replicated over CP, so pool memory per rank (4.15 GB for a 26-block session at 832x480) does not shrink with CP. At LNC 2 the split head’s history is read twice and each call adds a few core_barriers.

Adapting this kernel#

  • Block size. Any size works for the reads and the mask. Prefer one latent frame: whole-block eviction, no padding, and the block-aligned commit the write requires.

  • History length. The bias row takes 2 * Sh bytes per SBUF partition next to the 50 KB score ring and per-head state. Much beyond 23,400 tokens, generate the bias per Sk block or lower sk_tiles_per_blk. More heads per rank grow the resident state linearly.

  • Heads, head dim, GQA. D == 128 and MHA are asserted. For GQA, broadcast K/V heads before the call or let the per-head block table share planes between query heads.

  • CP size. Any size the mesh’s replica groups support. Keep sq_tiles_per_blk >= ceil(Sq / 128) so each head’s history is read once. Without CP the wrapper calls the kernel with gather=False (the whole chunk, no collective).

  • Masks. A key-only mask that is a union of ranges is an extension of _history_bias_row (more bounds columns). Query-dependent masks (causal inside the chunk) cannot go through the rank-1 key bias. Keep masked blocks finite.

  • Commit. Keep the slot convention (block * N + head) * block_size + offset and shard-ordered indices; the kernel fixes the gather’s arrival order itself. If CP shards are not contiguous in token order, the src * S_local offset rule changes.

  • LNC 2. A new split is a change to lnc_split.py only, as long as both cores issue every collective in the same order, each core’s history pipelines can issue their slot’s gathers, and every commit item lands on exactly one core.

  • Validate over a slid window. Compare against an fp32 attention over the visible history ++ chunk, and run past the first window slide (chunk 6 at LingBot), where window bugs first show.

Common issues#

NaN output on early chunks#

  • Possible solution: a listed, masked block holds NaN/Inf. Masking adds a bias, it does not select, so NaN - 29952 is still NaN. Zero the pool at allocation and keep block 0 unwritten.

Output wrong only from the first slid window (chunk 6 at LingBot)#

  • Possible solution: bounds and the listed slots disagree (sink slots vs recent slots). Check the read plan’s bounds against the KV manager’s visible slots.

Committed K/V land in the wrong positions on some ranks#

  • Possible solution: the update indices were read in gather order. They must be read at the gathered source rank’s offset, and rank_id must be the CP-group index, not the global rank.

ValueError “the commit does not cover whole pool blocks”#

  • Possible solution: every block consecutive tokens (in index order) must map to the consecutive slots of one block. Use frame-sized blocks and frame-aligned chunks.