Challenges of Efficient Attention on NPUs and a Software-Hardware Co-Design Path

    NPUs can compute attention, but fused tiled attention only pays off when matrix math, online softmax, on-chip memory, layout, and pipelining are co-optimized. This article explains the bottlenecks, why tiling reduces off-chip traffic, implementation pitfalls, training versus inference differences, a practical rollout path, and how to judge a real win.

    1. The real issue: being able to compute is not the same as fusing efficiently

    Why can some neural processing units (NPUs) run matrix multiplies and normalization separately, yet struggle to implement tiled fused attention efficiently?

    The answer is not whether the attention algorithm is “compatible” with a given processor. It is whether three originally independent stages can cooperate tightly in limited on-chip memory:

    1. Compute affinities between queries and keys.
    2. Normalize scores row-wise.
    3. Aggregate value vectors with the normalized weights.

    When the stages run separately, a compiler can usually pick a mature path for each. After fusion, data layout, cache capacity, execution order, and synchronization must be optimized together. The problem upgrades from “can we run a single operator” to “can we schedule an entire compute pipeline efficiently.”

    A more accurate statement is: an NPU can in principle implement tiled fused attention, but stable gains depend on the specific architecture and on how well the compiler, runtime, and operator implementation work together.

    Here NPU means the general class of neural processors. It does not imply that every such device has the same memory hierarchy or instruction set.

    2. Where standard attention bottlenecks appear

    For discussion, consider a single attention head. Let the query, key, and value matrices be:

    [
    Q\in\mathbb{R}^{N_q\times d},\quad
    K\in\mathbb{R}^{N_k\times d},\quad
    V\in\mathbb{R}^{N_k\times d_v}
    ]

    (N_q) is query length, (N_k) is key/value sequence length, (d) is the query-key dimension, and (d_v) is the value dimension.

    The standard computation is:

    [
    S=\frac{QK^\top}{\sqrt d}+M
    ]

    [
    P=\operatorname{softmax}(S)
    ]

    [
    O=PV
    ]

    (M) is an optional mask or additive bias. Normalization is along the key sequence. The output satisfies:

    [
    O\in\mathbb{R}^{N_q\times d_v}
    ]

    In typical self-attention, (N_q=N_k=N), so both the score and probability matrices have (N^2) elements.

    Two issues should be separated:

    • Compute: the two main matrix multiplies still process a large number of query-key pairs.
    • Data movement: whether the intermediate score and probability matrices must be fully written to external memory and read back by the next operator.

    Tiled fused attention mainly targets the second issue. It usually does not change the math of dense attention, and it does not turn the core complexity into linear. It avoids materializing the full intermediate matrices off-chip, cutting transfer and intermediate storage cost.

    3. Why tiled fusion reduces off-chip access

    3.1 Split the full matrix into on-chip tiles

    Tile queries by rows and keys/values along the sequence. Each step computes only:

    [
    S{ij}=\frac{Q_iK_j^\top}{\sqrt d}+M{ij}
    ]

    Then complete the normalization-related work for that score tile on-chip and update the corresponding output accumulators.

    The point is not “keep the entire score matrix on-chip,” but:

    Keep only the score tile currently in flight, plus a small amount of per-query-row normalization state and output accumulation state.

    After a tile is consumed, its storage can be reused. There is no need to assemble a full (N_q\times N_k) matrix.

    3.2 Online normalization lets tiles merge correctly

    Row-wise softmax looks as if it needs the full row of scores first, but the same math can be obtained by updating a running maximum and a running sum of exponentials.

    For a query row, let the state of the processed prefix be:

    • (m): current maximum score
    • (l): sum of exponentials relative to that maximum
    • (a): output accumulator not yet divided by the softmax denominator

    Let the new score tile be (s_j) and the corresponding values (v_j). The update is:

    [
    m’=\max\left(m,\max_j s_j\right)
    ]

    [
    \alpha=\exp(m-m’)
    ]

    [
    p_j=\exp(s_j-m’)
    ]

    [
    l’=\alpha l+\sum_j p_j
    ]

    [
    a’=\alpha a+\sum_j p_jv_j
    ]

    After all key-value tiles:

    [
    o=\frac{a}{l}
    ]

    Rescaling old results to the new maximum keeps a consistent normalization baseline across tiles and avoids exponentiating overly large scores.

    In real arithmetic this matches standard softmax. With finite precision, a different summation order can change numerics, so a reasonable error budget is still required.

    3.3 Do not claim all off-chip traffic is linear

    After fusion, full reads and writes of the score and probability matrices go away. That is the main win. Whether queries, keys, values, and output state are moved repeatedly still depends on loop order, tile size, and on-chip capacity.

    For example, with query tiles as the outer loop, each query tile may scan all key-value tiles. If keys and values cannot stay resident or be reused well, they may be read many times.

    A more careful statement is:

    • Input and final output sizes typically grow linearly with sequence length.
    • Materializing large intermediate matrices off-chip can be eliminated.
    • Total off-chip traffic still depends on on-chip capacity, reuse, and parallelism; it cannot unconditionally be claimed to grow linearly with sequence length.

    4. Main difficulties of high-performance fused attention on NPUs

    4.1 Matrix throughput and vector throughput may not match

    NPUs usually emphasize matrix multiply-accumulate. Attention is not only GEMM.

    Softmax also needs max reduction, exponentiation, sums, division, and row-wise scaling. If those ops live on different units, matrix results must be handed to a vector or scalar path.

    Real bottlenecks can include:

    • Insufficient exponent throughput
    • Multiple synchronizations for row reductions
    • Matrix results not efficiently visible to the vector unit
    • Extra copies or layout conversion between units

    The matrix unit can be fast and still stall waiting for softmax, so overall utilization stays low.

    4.2 On-chip memory is limited in capacity and in how it can be accessed

    A fused tile must hold queries, keys, values, temporary scores, output accumulators, and softmax state. Double buffering needs space for the next batch as well.

    A rough capacity constraint is:

    [
    B_qd\,b_Q+B_kd\,b_K+B_kd_v\,b_V
    +B_qB_k\,b_S+B_qd_v\,b_A+\text{state and buffer overhead}
    \leq C
    ]

    (B_q) and (B_k) are query and key-value tile sizes, (b) is bytes per element, and (C) is usable on-chip capacity.

    This is only an estimate. Implementations may reuse scratch, or alignment, padding, and layout may consume more space.

    Tiles that are too large crowd out other workspace, reduce concurrency, or spill temporaries off-chip. Tiles that are too small increase movement, loop overhead, and syncs.

    On-chip memory may also be split into regions with different access rights, bandwidth, or alignment. Enough total capacity does not mean every unit can use every buffer directly.

    4.3 Layout must connect the two GEMMs

    The first GEMM typically emits scores in a layout suited to the matrix unit. Row-wise softmax wants contiguous access along a row. The second GEMM wants another input layout for the probability tile.

    If those layouts are incompatible, you need permute, transpose, or format conversion.

    For short sequences, small batches, and small head dimensions, layout conversion can dominate and wipe out the off-chip savings from fusion. Layout is not a late polish step; it should be decided with the tiling strategy.

    4.4 High-performance pipelines need async movement and fine-grained sync

    The ideal is: compute the current tile while prefetching the next key-value tile; overlap matrix work with some vector work; sync only where needed rather than serializing every stage.

    Hardware and software need to support:

    • Controllable prefetch
    • Double or multi buffering
    • Producer-consumer coordination
    • Fine-grained synchronization
    • Predictable buffer lifetimes

    If every step uses a global barrier, or the compiler cannot express a local pipeline, execution becomes “move—compute—wait—move again.”

    The algorithm is fused, but hardware never truly overlaps.

    4.5 The compiler must understand fused resource contention

    Graph-level fusion can cut operator launches without producing efficient tiled attention.

    Deeper optimization must handle:

    • On-chip buffer allocation
    • Accumulator lifetimes
    • Interleaving of matrix and vector instructions
    • Async copy dependencies
    • Boundary tiles
    • Specialization across shapes

    If the compiler spills state that should stay on-chip, or inserts extra syncs “to be safe,” fusion gains shrink.

    A single fused node in the graph is not the same as efficient fused execution underneath.

    5. Training and different inference phases need different designs

    5.1 Forward fusion does not mean the backward pass is optimized

    Training also needs gradients for queries, keys, and values. To avoid saving the full probability matrix, the backward pass can use forward softmax statistics and recompute some scores and probabilities.

    That trades extra compute for lower storage. Implementations still need gradient accumulation, conflict-free parallel writes, and recompute scheduling.

    With dropout, forward and backward random state must be reconstructed consistently, or gradients are wrong.

    A working forward operator only means the first hurdle is cleared.

    5.2 Long-sequence prefill and token-by-token decode have different bottlenecks

    In long prefill, queries and keys are both long, so avoiding large intermediate matrices is more likely to help.

    In decode, there may be one or a few query positions and a long KV cache. Intermediate scores are no longer a product of two long lengths; the bottleneck often shifts to KV-cache reads and insufficient parallelism.

    The same fused kernel may not fit both loads. Engineering usually dispatches on query length, key length, head dimension, and batch size rather than forcing one path for every case.

    Step 1: Build a trusted baseline

    Implement separate GEMM, numerically stable softmax, and output aggregation as a correctness baseline.

    Tests should at least cover:

    • Sequence lengths that are not tile-aligned
    • Different head and value dimensions
    • Causal and general masks
    • Extreme score ranges
    • Multiple data types
    • Fully masked rows

    For fully masked rows, define output semantics up front so online updates do not produce invalid infinities or divide-by-zero.

    Step 2: Stop materializing full intermediates

    Start with an easy-to-verify tiling scheme so score tiles, softmax state, and output accumulators are consumed and updated on-chip.

    Do not chase complex overlap yet. Confirm that the targeted off-chip accesses dropped, not merely that the graph has fewer operators.

    Step 3: Optimize from measured bottlenecks, not by blindly growing tiles

    Profile to separate:

    • Off-chip bandwidth
    • Matrix compute
    • Exp and reduction
    • Layout conversion
    • Sync and scheduling
    • Low concurrency from on-chip capacity

    Only then decide whether to increase reuse, retune tile size, fix layout, or add double buffering and finer parallelism.

    Step 4: Shape dispatch and fallback

    A high-performance implementation should cover common shapes and keep a general fallback.

    For tiny inputs, unusual masks, or configs that oversubscribe resources, a non-fused path can be safer. Fusion should be chosen by end-to-end cost, not by the assumption that fused is always faster.

    7. How to tell whether the implementation actually succeeded

    Do not judge by a single GEMM’s throughput or one ideal shape.

    Check together:

    1. Correctness: forward error, gradient error, and special-mask behavior.
    2. End-to-end latency: including layout conversion, scheduling, sync, and necessary copies.
    3. Off-chip traffic: whether full score and probability matrices are avoided.
    4. Workspace: whether peak memory dropped and scratch is bounded.
    5. Hardware utilization: whether matrix and vector units stall on each other.
    6. Shape coverage: whether gains hold across sequence lengths, batches, and head dimensions.
    7. Training completeness: whether forward savings are offset by backward recompute or gradient handling.

    8. Conclusion: the hard part is resource organization, not algorithm portability

    The core idea of tiled fused attention is general: online softmax and on-chip tiles avoid repeatedly reading and writing large intermediate matrices off-chip.

    High performance is not renaming three operators as one. It is a coordinated plan for matrix compute, vector reduction, data movement, layouts, and synchronization.

    For NPUs, the important work is not copying another chip’s schedule. It is answering, for your architecture: which data should stay on-chip, which compute can overlap, and which tiles balance reuse against concurrency.

    When those questions are answered systematically, fused attention can move from “functionally supported” to a stable, efficient, maintainable implementation.