agentleFS
Hugging FaceKnown publisherhuggingface/optimum-neuron/optimum/neuron/models/inference/backend/modules/attention/AGENTS.md

optimum-neuron / attention

AGENTS.md270 starsChanged 10 months agoApache-2.0View on GitHub

This directory contains the attention implementation for NxD inference models. For broader context see optimum/neuron/models/inference/AGENTS.md. - attention_base.py — NeuronAttentionBase: base class for all decoder attention layers. Handles TP-aware QKV/O projections, RoPE, flash attention dispatch, and KV cache management. - flash_attention_nki.py — Custom NKI kernel (flash_fwd_large_d) for models with head_dim > 128 (e.g. Gemma3-27B with head_dim=256). - gqa.py — Grouped Query Attention sharding strategies (GroupQueryAttention_QKV, GroupQueryAttention_O). - utils.py — Shared attention helpers (RoPE application, repeat_kv, manual softmax for token generation). NeuronAttentionBase.get_flash_attention_strategy()…

The file

We split this AGENTS.md into the rules it gives an agent

3 rules. About 0 are common, 0 are distinctive, and 3 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 3

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    All kernel calls forward sliding_window=self.sliding_window_size (default 0 = no window).

    line 31
  2. Very specific:

    No other changes are needed: get_flash_attention_strategy() automatically picks LARGE_D_* for head_dim > 128.

    line 93
  3. Very specific:

    Ensure your export seq_len is a multiple of 2048 (LNC2) or 4096 (LNC1) so the kernel is actually engaged.

    line 95

≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

Attention Module Guide

This directory contains the attention implementation for NxD inference models. For broader context see optimum/neuron/models/inference/AGENTS.md.

Key files

  • attention_base.py — NeuronAttentionBase: base class for all decoder attention layers. Handles TP-aware QKV/O projections, RoPE, flash attention dispatch, and KV cache management.
  • flash_attention_nki.py — Custom NKI kernel (flash_fwd_large_d) for models with head_dim > 128 (e.g. Gemma3-27B with head_dim=256).
  • gqa.py — Grouped Query Attention sharding strategies (GroupQueryAttention_QKV, GroupQueryAttention_O).
  • utils.py — Shared attention helpers (RoPE application, repeat_kv, manual softmax for token generation).

Flash Attention Dispatch

NeuronAttentionBase.get_flash_attention_strategy() selects one of five strategies at prefill time based on head_dim, seq_len, and logical_nc_config (LNC1 vs LNC2):

StrategyKernelWhen
NONECompiler-native matmul/softmaxseq_len too small or custom qk_scale
UNSHARDED_KERNELattention_isa_kernelLNC1, head_dim ≤ 128, seq_len ≥ 4096
SHARDED_KERNELattention_isa_kernel (SPMD)LNC2, head_dim ≤ 128, seq_len % 1024 == 0
LARGE_D_UNSHARDED_KERNELflash_fwd_large_dLNC1, head_dim > 128, seq_len ≥ 4096 and % 2048 == 0
LARGE_D_SHARDED_KERNELflash_fwd_large_d (SPMD)LNC2, head_dim > 128, seq_len ≥ 2048 and % 2048 == 0

All kernel calls forward sliding_window=self.sliding_window_size (default 0 = no window). Subclasses set self.sliding_window_size in __init__ for models that use sliding window attention (e.g. Gemma3).

flash_fwd_large_d — NKI kernel for head_dim > 128

Why it exists

The ISA reference kernel (attention_isa_kernel) uses par_dim(head_dim) for the QK matmul. The Neuron tensor engine caps par_dim at 128, so models with head_dim=256 (e.g. Gemma3-27B) cannot use the ISA kernel directly.

flash_fwd_large_d solves this with d-tiling: it splits head_dim into 128-element chunks and accumulates the QK result across tiles. The PV matmul is unaffected because head_dim sits in the free dimension there (max 512).

Constraints

ParameterConstraintReason
head_dim (d)Must be a multiple of 128, ≤ 512D-tiling tile size is fixed at 128; free dim limit is 512
seq_lenMust be a multiple of LARGE_TILE_SZK/V tiles must be evenly divisible
LARGE_TILE_SZ2048 when d=128, 1024 when d>128SBUF budget: extra d_n_tiles reduce the allowed tile size

SBUF budget

The main buffers that scale with tile size:

qk_res_buf:        (par_dim(128), LARGE_TILE_SZ)   -- QK results
p_local:           (par_dim(128), LARGE_TILE_SZ)   -- softmax numerator
p_local_transposed:(par_dim(128), LARGE_TILE_SZ)   -- transposed p for PV
k_tiles:           (d_n_tiles, par_dim(128), LARGE_TILE_SZ)
o_buffer:          (attn_core_tile_size, par_dim(128), d)

attn_core_tile_size = max(4, 64 // d_n_tiles) keeps o_buffer near ~4 MB. LARGE_TILE_SZ halves from 2048→1024 when d_n_tiles doubles from 1→2.

Sliding window

Two-level filtering avoids unnecessary computation:

  1. Large-tile level (outer loop): skip entire K large-tiles that are fully outside the window (forward_mask in flash_fwd_large_d).
  2. Position level (inner core): affine_select masks individual positions with two chained predicates — causal (q_pos >= k_pos) then window (k_pos >= q_pos - window + 1). affine_select only supports a single predicate so they are applied sequentially.

Numerical stability

m_buffer and l_buffer are initialized to -1e38 (sentinel for −∞). The unified online-softmax update path in _flash_attention_core_large_d handles both the "first tile" and "subsequent tiles" cases: when m = −1e38, the rescale factor α = exp(−1e38 − max) ≈ 0, so the stale o_buffer contribution is zeroed out automatically without a separate initialize flag.

Adding a new model with head_dim > 128

  1. Set self.sliding_window_size in your attention subclass __init__ if the model uses sliding window attention (0 otherwise — the base class default).
  2. No other changes are needed: get_flash_attention_strategy() automatically picks LARGE_D_* for head_dim > 128.
  3. Ensure your export seq_len is a multiple of 2048 (LNC2) or 4096 (LNC1) so the kernel is actually engaged; otherwise it falls back to NONE.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.