.. meta::
    :description: GLM sparse-attention indexer: Q/K projections, paged KV-cache write, context-parallel gather, scoring, and top-k.
    :date-modified: 11/30/2026

.. currentmodule:: nkilib.experimental.mla.glm

GLM Indexer Kernel API Reference
================================

GLM sparse-attention indexer: Q/K projections, paged KV-cache write, context-parallel gather, scoring, and top-k.

The row holds ``head_dim`` fp8 K values bitcast two-per-bf16 (``head_dim // 2`` containers), then one bf16 per-token dequant scale, then padding. Unlike the MLA cache there is no separate ``k_pe`` field: the indexer's whole ``head_dim`` (RoPE included) is quantized, matching vLLM, so the cache stays one contiguous row per token. GLM's ``head_dim=128`` gives ``64 + 1 = 65 -> 72`` bf16 (144 B).

Background
-----------

``glm_indexer_proj`` is the GLM sparse-attention indexer: it projects the latent Q and K, writes the quantized K into the paged cache, gathers K across the context-parallel ranks, scores the query tiles against the context, and selects each query's top-k positions.

API Reference
--------------

**Source code for this kernel API can be found at**: `glm_indexer.py <https://github.com/aws-neuron/nki-library/blob/2.34/src/nkilib_src/nkilib/experimental/mla/glm/glm_indexer.py>`_

glm_indexer_proj
^^^^^^^^^^^^^^^^

.. py:function:: glm_indexer_proj(x: nl.NkiTensor, qr: nl.NkiTensor, wq: nl.NkiTensor, wk: nl.NkiTensor, k_norm_gamma: nl.NkiTensor, k_norm_beta: nl.NkiTensor, cos: nl.NkiTensor, sin: nl.NkiTensor, slot_mapping: nl.NkiTensor, weights: nl.NkiTensor, q_pos: nl.NkiTensor, end_pos: int = 0, cp_degree: int = 1, replica_groups: tuple = None, topk_nseg: int = 0, roll_score: int = 0, emit_score: bool = False, emit_proj: bool = False, k_ctx: nl.NkiTensor = None, k_cache: nl.NkiTensor = None, zero_topk: bool = False, score_chunk: int = 0, block_table: nl.NkiTensor = None, block_size: int = 0, cp_interleave: int = 0, index_topk: int = 2048, kv_fp8: bool = False, kv_cache_fp8_dtype = nl.float8_e4m3)

   The GLM indexer: Q/K projections, paged cache write, CP gather, score, top-k.

   :param x: ``[s_local, dim]`` bf16 hidden states.
   :type x: ``nl.NkiTensor``
   :param qr: ``[s_local, q_lora_rank]`` bf16 latent Q.
   :type qr: ``nl.NkiTensor``
   :param wq: ``[q_lora_rank, n_heads * head_dim]`` bf16 Q weight.
   :type wq: ``nl.NkiTensor``
   :param wk: ``[dim, head_dim]`` bf16 K weight.
   :type wk: ``nl.NkiTensor``
   :param k_norm_gamma: ``[head_dim]`` fp32 LayerNorm scale for K.
   :type k_norm_gamma: ``nl.NkiTensor``
   :param k_norm_beta: ``[head_dim]`` fp32 LayerNorm bias for K.
   :type k_norm_beta: ``nl.NkiTensor``
   :param cos: ``[s_local, rope_head_dim // 2]`` fp32 RoPE cosine table.
   :type cos: ``nl.NkiTensor``
   :param sin: ``[s_local, rope_head_dim // 2]`` fp32 RoPE sine table.
   :type sin: ``nl.NkiTensor``
   :param slot_mapping: ``[s_local]`` int32 flat cache slot per token, ``-1`` for padding.
   :type slot_mapping: ``nl.NkiTensor``
   :param weights: ``[s_local, n_heads]`` fp32 per-head score weights.
   :type weights: ``nl.NkiTensor``
   :param q_pos: ``[s_local]`` fp32 global position of each local query; all-gathered to give the gathered K's positions.
   :type q_pos: ``nl.NkiTensor``
   :param end_pos: valid cache positions to score against, i.e. the filled prefix. 0 skips the score phase entirely ([Testing]).
   :type end_pos: ``int``
   :param cp_degree: CP ranks, so ``s_global = cp_degree * s_local``. 1 skips the collective.
   :type cp_degree: ``int``
   :param replica_groups: CP rank-lists for the in-kernel collectives, from the framework. None assumes a single group ``[0, cp_degree)``, which only holds for pure CP.
   :type replica_groups: ``tuple``
   :param topk_nseg: [Testing] force the top-k segment count; production derives it (0).
   :type topk_nseg: ``int``
   :param roll_score: [Testing] force the position-block loop rolled (1) or unrolled (-1); production derives it (0).
   :type roll_score: ``int``
   :param emit_score: [Testing] also return the full [s_local, T] score. O(s_local * s_global), so it does not fit in HBM at long context.
   :type emit_score: ``bool``
   :param k_ctx: [Testing] ``[s_global, head_dim]`` bf16 context supplied by the caller instead of gathered from peers, so one rank can stand in for a whole CP group.
   :type k_ctx: ``nl.NkiTensor``
   :param zero_topk: [Testing] return zeros for the top-k output instead of the picks.
   :type zero_topk: ``bool``
   :param block_table: ``[n_blocks]`` int32 page ids, logical block i -> cache block block_table[i]. The score then reads K through this table rather than from the gathered K, which is what lets a cached prefix participate. Requires block_size.
   :type block_table: ``nl.NkiTensor``
   :param block_size: tokens per cache page. Must divide POS_BLOCK.
   :type block_size: ``int``
   :param cp_interleave: CP interleave granularity of the cache in tokens; 0 means contiguous.
   :type cp_interleave: ``int``
   :param score_chunk: [Testing] force the score chunk width, or -1 to disable chunking; production derives it (0). Chunking is what bounds the score ring.
   :type score_chunk: ``int``
   :param index_topk: positions selected per query.
   :type index_topk: ``int``
   :param emit_proj: [Testing] also return the projected Q and the gathered K.
   :type emit_proj: ``bool``
   :param k_cache: paged K cache, owned by the caller and written in place. Its flattened leading dims are slots; the minor dim is ``head_dim`` (bf16) or, with ``kv_fp8``, the fused packed row width ``kv_row_bf16_width(head_dim)`` bf16 (fp8 K bitcast 2-per-bf16 + per-token scale). The block table addresses it on the read side.
   :type k_cache: ``nl.NkiTensor``
   :param kv_fp8: store the paged K cache in fp8, quantized per token over ``head_dim`` (RoPE included, matching vLLM) and packed into a bf16-container row alongside the per-token dequant scale. Halves cache and CP-collective bandwidth. The packed rows are unpacked to dense bf16 (``dequant_k_packed``) before the score: after the gather on the CP path, or after ``linearize_pages`` on the block-table / paged-cache (APC) path. False keeps the bf16 cache path unchanged.
   :type kv_fp8: ``bool``
   :param kv_cache_fp8_dtype: fp8 format for the K latent when ``kv_fp8`` -- ``nl.float8_e4m3`` (legacy, max 240, default) or the OCP ``nl.float8_e4m3fn`` (max 448, NeuronCore-v4).
