Expand description
Rotary position embedding (RoPE, both the split-half apply_rope
and interleaved apply_rope_interleaved conventions) and
grouped-query causal attention (GQA). This is the “vanilla”
attention path used as the correctness baseline.
causal_mla_attention/causal_mla_attention_sparse add
DeepSeek-style latent attention and its DSA sparse-selection variant
(GLM-5.2, DeepSeek V3.2/V4); both mechanisms are now backed by real,
public reference implementations (see docs/MODELS.md).
ferrox_models::mla/ferrox_models::glm_dsa compose these
primitives into full RoPE-carrying MLA forward passes.
Structs§
- Yarn
Scaling - YaRN RoPE scaling exactly as a checkpoint declares it, in the shape
the reference reads out of
rope_scaling(FreeTokenpython/freetoken/layers/rotary.py:139, the"yarn"arm of_get_rope).beta_fast/beta_slow/truncatecarry that arm’s own defaults, because a real YaRN checkpoint usually declares onlyfactorandoriginal_max_position_embeddings.
Functions§
- apply_
rope - Applies rotary position embedding in place to a single head’s vector,
split-half (GPT-NeoX /
LLAMA_ROPE_TYPE_NEOX) style: each pair(i, i+half)is rotated together, for positionposwith basetheta. This is what llama.cpp calls NEOX-style RoPE (used by e.g. DeepSeek-V3.2’s lightning indexer); seeapply_rope_interleavedfor the other real convention. - apply_
rope_ back - Inverse of
apply_rope(split-half / NeoX): rotates each pair by-angle. DeepSeek V4 applies this (“derope” /ggml_rope_ext_back) to the rope slice of attention output before the groupedwo_aprojection — see.scratch/NOTES_DS4_INFERENCE.md. - apply_
rope_ interleaved - Applies rotary position embedding in place, interleaved (GPT-J /
llama.cpp’s
LLAMA_ROPE_TYPE_NORM) style: adjacent pairs(2*i, 2*i+1)are rotated together, rather thanapply_rope’s split-half pairing. GLM-5.2 uses this convention for both its main attention (rope_interleave: true) and its lightning indexer (indexer_rope_interleave: true) per its realconfig.json(huggingface.co/zai-org/GLM-5.2) — confirmed against llama.cpp PR #25407, which rotates the indexer withLLAMA_ROPE_TYPE_NORMwhere DeepSeek-V3.2’s PR #23346 usesLLAMA_ROPE_TYPE_NEOX. - apply_
rope_ interleaved_ back - Inverse of
apply_rope_interleaved(adjacent-pair / Norm RoPE). - apply_
rope_ interleaved_ with_ freq_ factors - Interleaved (GPT-J /
LLAMA_ROPE_TYPE_NORM) RoPE with Llama 3/3.1/3.2’s per-band frequency correction – the combination real llama.cpp uses forgeneral.architecture = "llama"checkpoints that carryrope_freqs.weight. Pairing is adjacent(2*i, 2*i+1)as inapply_rope_interleaved; each band’s angle is divided byfreq_factors[i]as inapply_rope_with_freq_factors.freq_factorsall-1.0is mathematically identical to plainapply_rope_interleaved(pinned byrope_interleaved_with_all_ones_freq_factors_matches_plain_interleaved). - apply_
rope_ with_ freq_ factors - Same split-half rotation as
apply_rope, but each frequency bandihas its angle divided byfreq_factors[i]before the rotation – Llama 3/3.1/3.2’s real per-band RoPE frequency correction (therope_freqs.weightGGUF tensor,n_rot/2elements,TENSOR_NOT_REQUIREDso most non-Llama-3 checkpoints don’t carry it). Confirmed against real llama.cpp source, not guessed:ggml_rope_cache_init(ggml/src/ggml-cpu/ops.cpp) computestheta/freq_factors[i0/2]per band beforerope_yarn.freq_factorsall-1.0is mathematically identical to plainapply_rope(pinned byrope_with_all_ones_freq_factors_matches_plain_rope). - causal_
gqa_ attention - Single-token causal attention for one query against all cached
key/value positions (0..=pos), grouped-query style:
n_kv_headsmay be fewer thann_heads, with each KV head shared byn_heads / n_kv_headsquery heads. - causal_
gqa_ attention_ paged - Same math as
causal_gqa_attention, but K/V positions are read through aPagedKvStoreblock table instead of one contiguous slice: positiontlives in blockblock_table[t / block_size]at offsett % block_size, so blocks need not be physically adjacent or in order. Must matchcausal_gqa_attentiongiven the same logical K/V contents (float noise only) — the block table is a storage-layout detail, not a math change. - causal_
gqa_ attention_ paged_ sinks causal_gqa_attention_pagedwith per-head attention sinks and an optional sliding window: the paged twin ofcausal_gqa_attention_sinks.- causal_
gqa_ attention_ prefill - Prefill (multi-query) causal GQA:
q/k_cache/v_cacheare all lengthseq_lenin the time dimension. Query at positiontattends only to keys/values0..=t(same math as loopingcausal_gqa_attentionper token). Layout: q/out[seq_len, n_heads, head_dim]; k/v[seq_len, n_kv_heads, head_dim]. Metal prefill kernels must match. - causal_
gqa_ attention_ prefill_ shared_ kv - Prefill attention parallelized over
(query, head)slots. Same math as callingcausal_gqa_attention_softcapper query; used by the decoder CPU pp path so Rayon owns the full[n_q × n_heads]grid instead of only the query axis (better for large-head models like Phi-4). - causal_
gqa_ attention_ prefill_ shared_ kv_ windowed causal_gqa_attention_prefill_shared_kvwith an optional sliding window, so SWA models (Gemma-2/3, Mistral, Qwen2-MoE) get the same blocked kernel instead of the per-querycausal_gqa_attention_windowed_softcapfallback.- causal_
gqa_ attention_ sinks - Single-query causal GQA with per-head attention sinks, optionally windowed.
- causal_
gqa_ attention_ softcap causal_gqa_attentionwith optional Gemma-2 attention logit softcap.- causal_
gqa_ attention_ windowed - Same computation as
causal_gqa_attention, but each query only attends to the lastwindowcached positions (inclusive of itself) instead of the full causal history – Mistral/Mixtral/Qwen2-family sliding-window attention. Confirmed against the realsliding_windowconfig field used by those models (realtransformerssource forQwen2MoeAttention/Mixtral’s equivalent) and against candle-transformers’mixtral.rs/qwen2_moe.rs, which both mask scores wherekey_pos + sliding_window < query_pos– i.e. only the most recentwindowpositions (including the query’s own) stay unmasked.window >= seq_lendegenerates to exactlycausal_gqa_attention’s full-causal behavior (pinned bywindowed_attention_with_window_covering_full_history_matches_full_causal). - causal_
gqa_ attention_ windowed_ softcap causal_gqa_attention_windowedwith optional attention logit softcap.- causal_
mla_ attention - Single-token causal attention for DeepSeek/Kimi-style Multi-head
Latent Attention (MLA): every query head has its own key/value (no
GQA-style grouping – verified directly against Kimi K3’s real
KimiMLAAttention.forward, wherekv_b_projexpands to the fullnum_headscount and thenum_key_value_heads/num_key_value_groupsfields computed in__init__go unused), but the key/query head dimension (qk_head_dim=qk_nope_head_dim + qk_rope_head_dim) can differ from the value head dimension (v_head_dim) – unlikecausal_gqa_attention, which assumes one sharedhead_dimfor both. - causal_
mla_ attention_ sinks causal_mla_attentionwith DeepSeek V4’s per-head attention sinks.- causal_
mla_ attention_ sparse - Same as
causal_mla_attentionfor a single query position, but attention is restricted to the explicitvisiblekey positions (ascending, a subset of0..seq_len) rather than the full causal history — the sparse-attention half of GLM-5.2/DeepSeek-V3.2’s DSA, applied afterlightning_indexer_topkselectsvisible. - causal_
mla_ attention_ sparse_ sinks causal_mla_attention_sparsewith per-head attention sinks.- lightning_
indexer_ topk - The DeepSeek-V3.2 / GLM-5.2 “lightning indexer” (arXiv 2512.02556;
real, merged, tested reference implementations in llama.cpp PR
#23346 and PR #25407): scores every causally-visible key position
against the query using a cheap multi-head dot-product indexer, then
keeps only the
top_khighest-scoring positions. - proportional_
freq_ factors - The reference’s
"proportional"arm (rotary.py:103), in the same per-band divisor form asyarn_freq_factors. - yarn_
correction_ range - The
[low, high]band range the YaRN ramp interpolates across, as the reference computes it (rotary.py:167-179): both ends from [yarn_correction_dim], floored / ceiled whentruncate,lowclamped up to0, and – the load-bearing detail, called out in the reference’s own comment atrotary.py:176–highclamped torotary_dim - 1, notrotary_dim / 2 - 1. - yarn_
freq_ factors - YaRN’s frequency rewrite, expressed as the per-band divisors
apply_rope_with_freq_factorsalready consumes: one entry per rotation band (rotary_dim / 2), each the number the band’s RoPE angle is divided by.