Integrating a New Architecture Operator Library: Attention and KV Cache in Practice
This article explains how to bring LLM inference to new hardware through an operator library. It covers where the library sits in the software stack, how to choose between hand-tuned kernels, DSLs, and kernel description languages, and how to define strict interface constraints for attention. It also covers sparse attention, paged KV cache layout, the differences between prefill and decode, numerical validation, performance profiling, and a staged rollout with rollback.
1. Why Integration Should Start with the Operator Library
LLM inference time concentrates in a few hot paths: the forward pass of attention, reading, writing, and layout management of the KV cache, matrix multiplication in the FFN, and sampling and logits processing. When moving to new hardware, the upper-level model code can usually stay the same. What must be rewritten are the low-level operators that depend closely on compute units, the memory hierarchy, and the compiler toolchain.
The operator library isolates these hardware differences in a middle layer. It exposes a stable calling interface upward and encapsulates hardware-specific implementations downward. With a well-designed interface, integration changes from rewriting models one by one to filling in missing operators and then assembling the model. Whether this change happens depends on two factors: whether the interface stays consistent across models, and whether the number of missing operators stays manageable.
2. Position in the Software Stack and How Operators Are Produced
An inference software stack typically has three layers:
Upper layer: inference serving framework / model implementation↓ calls the unified operator interfaceMiddle layer: core operator library↓ depends onLower layer: compiler toolchain, domain-specific language, graph compiler↓Hardware: accelerator card / GPU architecture
Four approaches typically coexist around the operator library:
- Core operator library: Mainly hand-tuned C/C++ kernels that cover high-frequency operators such as Attention, GEMM, Norm, and RoPE. It is the main source of performance.
- Domain-specific language (DSL): Developers describe blocked computation in Python-like syntax, including tiling, reduction, and memory access patterns. A compiler then generates kernels for the target architecture. This approach suits quick implementation of non-standard operators.
- General kernel description language: This language sits closer to the hardware. It directly describes parallelism and memory access strategies, so it suits custom operators with very high performance requirements. A DSL describes the shape of the computation and leaves parallelism and memory access details to the compiler. A general kernel description language requires developers to specify those details directly.
- Graph-level compiler: This compiler handles operator fusion, memory planning, and scheduling. It merges multiple fine-grained operators into larger execution units, which reduces memory access and launch overhead.
Use the table below to choose an approach. The criteria in the table require measured data. The measurement method appears in the rightmost column.
| Criterion | Leans toward core operator library | Leans toward DSL for fast implementation | Measurement method |
|---|---|---|---|
| Call frequency | Runs on every token | Appears only in some layers or some models | Count how many times the operator is called in a single inference step |
| Share of performance | High share of end-to-end latency | Low share, or the operator shape is not yet settled | Under a representative mix of requests, divide the sum of operator latencies by the end-to-end latency of a single step |
| Operator shape | Standard operator with a mature reference implementation | New or structurally variable operator | Check whether a public reference implementation exists and whether the input and output definitions are stable |
| Iteration frequency | Interface and implementation have largely stabilized | Still changing often | Count interface changes across recent versions |
In practice, the workflow goes like this: first get the new operator running with a DSL. After performance profiling confirms its share of latency, move the hot parts down into the core operator library.
Interface Example
The interface definition is the foundation for all later work. Below is a draft interface for an attention operator:
def attention_fwd(q: Tensor, # [total_tokens, num_heads, head_dim], dtype fp16 or bf16k_cache: Tensor, # Paged KV cache, layout described by block_tablev_cache: Tensor,block_table: Tensor, # [batch, max_blocks], dtype int32, invalid entries set to -1seq_lens: Tensor, # [batch], dtype int32, total KV length of each requestcu_seqlens_q: Tensor, # [batch + 1], prefix sum for variable-length batching, first entry is 0out: Tensor, # Same shape and dtype as q, preallocated by the caller) -> None:...
Every constraint must be written into the interface documentation. Constraints that are not listed can easily lead upper-layer callers to pass incompatible layouts, which produces silent errors. The table below is the minimum constraint checklist:
| Parameter | Constraint | Handling on violation |
|---|---|---|
| q, out | dtype is fp16 or bf16. out matches q in shape and dtype. The last dimension of out is contiguous (stride 1). | Raise an exception and do not write to out |
| Memory relationship between out and q | By default, in-place writes are not allowed, so the two do not share storage. | Raise an exception, unless the kernel explicitly supports in-place computation |
| head_dim | Meets the alignment requirement of the hardware vector width | Check at model load time. Reject loading the configuration if it fails. |
| block_size | Fixed within a single model. The value follows the hardware requirement. | Validate at model load time |
| block_table | int32. Valid entries range over [0, number of physical blocks). Invalid entries are -1. Within each row, valid entries must form a prefix. | Raise an exception if a valid entry is out of range, or if a -1 appears after a valid entry |
| seq_lens | int32. 0 ≤ seq_lens[i] ≤ max_blocks × block_size | Raise an exception if the value exceeds the upper limit |
| cu_seqlens_q | int32. The first entry is 0, the values are non-decreasing, and the last entry equals the first dimension of q. | Raise an exception if these conditions are not met |
| Length consistency | For each request, the query length cu_seqlens_q[i+1] − cu_seqlens_q[i] does not exceed seq_lens[i]. | Raise an exception |
| Accumulation precision | Softmax and output accumulation are fixed at fp32. | Not configurable. State this in the documentation. |
The first four checks should run at the operator call boundary. On a GPU, an out-of-bounds access on the device often gives no clear error. It produces wrong results or random crashes instead. Debug mode should therefore enable full checks. Production should keep at least lightweight checks on cu_seqlens_q and seq_lens.
3. Adapting the Key Computation Paths
3.1 Integrating Sparse Attention
The compute cost of dense attention grows with the square of the context length. Long-context models therefore commonly use sparse attention, so that each query block interacts with only a subset of KV blocks. This adds an index selection step to the operator pipeline. Integration involves three stages:
- Sparse index computation: Based on the query vectors and the metadata of each KV block (for example, a representative vector for each block), select the top-k KV blocks for each query block and output an index tensor.
- Index-driven gather: Collect the key and value blocks from the KV cache according to the indices. This step is a memory access operation, and its efficiency directly affects overall latency.
- Sparse attention kernel: Compute attention over non-contiguous KV blocks. The kernel must support variable-length and blocked input layouts.
The index selection stage must follow these rules:
- Value of k: The model configuration provides k, or the per-request budget determines it. A common formula is k = clamp(ceil(number of valid blocks × sparsity ratio), 1, number of valid blocks). This guarantees that k is at least 1 and does not exceed the number of valid blocks. Empty requests, which have zero valid blocks, skip index selection. Their output is set to zero, and the interface documentation must state this.
- Mask rules: The causal mask applies at the block level. A query block may select only KV blocks whose positions are not later than its own. The kernel handles token-level causality within a block. Whether to always keep the first block (the sink block) and the most recent several blocks (the local window) depends on how the model was trained. The integration must match the model implementation. The operator must not make this assumption on its own.
- Padding block handling: Before top-k, set the scores of padding blocks, and blocks beyond seq_lens, to negative infinity so that they are never selected. When the number of valid blocks is less than k, shrink k with the clamp rule. Padding blocks must not fill the gap.
- Invalid block handling: Treat entries of -1 in block_table as nonexistent. If a valid logical position maps to an index of -1, the caller has made an error. Raise an exception instead of skipping the entry silently.
- Out-of-range index handling: Every value in the index tensor must satisfy 0 ≤ idx < the number of valid blocks for that request. An out-of-range index is also a caller error, so handle it the same way as the previous rule.
3.2 KV Cache Read/Write and Paged Layout
The KV cache is organized into fixed-size blocks. Each request finds its physical blocks through block_table. The address for logical position pos is computed as follows:
- Physical block number = block_table[request, pos // block_size]
- Offset within the block = pos % block_size
- Write address (slot) = physical block number × block_size + offset within the block
Write path: Before writing the KV entries of a new token, check that the corresponding physical block number is not -1 and is within range. The upper-layer scheduler manages block allocation and release. The operator only reads and writes. It does not reclaim blocks. When a reclaimed block is reused, its old data may remain in memory. The read side must therefore rely on seq_lens for masking and must not assume that unwritten positions are zero.
Read path: The read range must not exceed seq_lens[i]. Positions beyond the valid length in the tail block must be masked, even if residual data remains in physical memory.
Layout choice: The kernel decides the layout. A common form is [number of physical blocks, block_size, number of KV heads, head_dim]. The layout must meet two requirements. The KV head data of a single token should be as contiguous as possible, and the head_dim dimension should be contiguous to allow vectorized memory access. The model configuration and the kernel layout must match, and the write side and the read side must share the same layout description.
GQA mapping: When the number of query heads differs from the number of KV heads (grouped-query attention), the mapping from query heads to KV heads must be written into the interface documentation. With contiguous grouping, the mapping is kv head = query head // (num_heads / num_kv_heads). Some models use interleaved grouping, which maps differently. Follow the model implementation in that case.
3.3 Differences Between Prefill and Decode Paths
Prefill and decode are two distinct computation patterns, so they need separate treatment during integration:
- Prefill: Processes multiple prompt tokens of a request at once. The query length is greater than 1, and the compute load is high. Performance is mainly limited by compute capacity. cu_seqlens_q describes the variable-length batch, and a causal mask is required.
- Decode: Each request generates one token per step. The query length is 1, but the path must read the full KV history. Performance is mainly limited by memory bandwidth. The memory access continuity of block_table and the length differences within a batch are the main factors affecting performance.
The two paths can share one interface, but their kernels and tuning parameters are usually separate. The prefill path focuses on tile partitioning. The decode path focuses on KV read continuity and load balancing.
If the optimal parameters for the two paths differ a lot, implement them separately. If one kernel reaches the target performance in both patterns, merge them. Base this decision on the latency of each path measured separately, not only on the combined total.
If the system uses chunked prefill and mixes prefill and decode requests in scheduling, a single batch will contain both long queries and queries of length 1. In this case, verify separately that cu_seqlens_q and the mask are correct for this mixed batch.
4. Numerical Validation and Integration Order
4.1 Numerical Validation
Reference implementation: Use a naive fp32 implementation as the baseline. Convert the inputs to fp32, compute softmax(QK^T / √d)V for each request and each head, and compare the result with the operator output.
Tolerance setting: Do not apply a fixed numerical tolerance directly. First, use a validated legacy implementation, or the fp32 reference, to compare results against the original precision on the same inputs. Measure the actual error range, then set the tolerance based on that baseline. For a coarse screen, start with atol and rtol each on the order of 1e-2. Then tighten the values according to the measured error for your model and dataset.
Comparison metrics: Maximum absolute error, L2 norm of the relative error, and cosine similarity of the outputs. Before comparing, check the output for NaN or Inf values. If any exist, the test fails.
The test matrix must cover at least the following cases:
- Batch size of 1, and mixed batches with multiple requests.
- Sequence lengths of 1, block_size − 1, block_size, and block_size + 1, plus a length close to the upper limit of max_blocks × block_size.
- Variable-length batches where each request has a different length.
- Batches that contain empty requests.
- With a sparsity ratio of 1, the sparse path results should match the dense path. This is the most direct way to verify the sparse index and gather logic.
Invalid input tests: Every violated condition in the constraint table needs a matching test case. Each case must assert that the expected exception is raised and that out was not written.
Long-context validation: Run the end-to-end pipeline on inputs close to the model’s maximum context length. Check whether the error accumulates noticeably with length.
4.2 Performance Profiling
Timing method: Run warm-up iterations before timing. Keep the input shape fixed. Run multiple times, then report the median and the P95. On a GPU, synchronize before and after timing. Without synchronization, the measurement captures only the kernel launch time.
Share measurement: Collect statistics under a representative request distribution, not with a single batch size. The share is the sum of operator latencies divided by the end-to-end latency of one step.
Decision rule: Operators with a stable share and high call frequency move into the core operator library. Operators with a low share, or with shapes that are still changing, stay in the DSL. The threshold for moving into the core library depends on your team’s performance targets. Do not apply numbers from other projects directly.
4.3 Integration Order and Rollback
Proceed in the following order:
- Fix the interface and the constraint table, write them into the documentation, and validate them when the model loads.
- Implement dense prefill and decode in the DSL. Pass the reference implementation tests and the invalid input tests.
- Integrate KV cache writes and reads. Verify the slot calculation and the out-of-range checks.
- Validate sparse att
