bridge.models.qwen.modeling_qwen4_exp.qsa#

Qwen Sparse Attention (QSA) of Qwen4-Exp / Qwen3.8-Flash-Next.

QSA is grouped-query softmax attention whose key/value set is chosen per query by a lightweight indexer:

  • the indexer projects the layer input to n_heads query heads and one key head of width head_dim (index_qk_proj), RMS-normalizes them and applies the attention RoPE;

  • keys are mean-pooled over compress_ratio consecutive tokens (blocks aligned to the start of every sequence) before the norm and RoPE (the block is rotated with the position of its first token);

  • every query scores the complete blocks it can see with sum_h relu(q_h . k_block) / sqrt(d) and keeps the budget / compress_ratio best ones; the tokens of those blocks plus the tokens of its own, still incomplete, block form the attention set.

The selection is a hard top-k, so no gradient flows into the indexer from the language-model loss (as in the reference implementation). The attention itself is exact softmax attention over the selected tokens and is differentiable w.r.t. Q, K and V.

Sequences with at most budget + compress_ratio - 1 tokens select every visible token, so plain causal attention is exact for them and the dense core attention is used. Longer sequences run a block-sparse FlexAttention kernel driven by the per-query block selection.

Module Contents#

Classes#

QSASelection

Per-query block selection produced by :class:QSAIndexer.

_DenseQSASelection

Shape-proven causal selection, with no indexer tensors to materialize.

QSAIndexerSubmodules

Submodules of the QSA indexer.

QwenSparseSelfAttentionSubmodules

Self-attention submodules plus the QSA indexer.

QSAIndexer

Weight-light MQA indexer selecting the key blocks every query attends to.

QSACoreAttention

Core attention of QSA: dense causal attention when the selection is complete, otherwise block-sparse FlexAttention over the selected tokens.

QwenSparseSelfAttention

Gated GQA self-attention whose keys/values are selected per query by a QSA indexer.

Functions#

_sequence_layout

Document ids and in-document positions for every token.

_qsa_mask_mod_factory

Build the FlexAttention mask_mod for a :class:QSASelection.

_compiled_flex_attention

build_qsa_dense_mask

Materialize the [b, s, s] boolean attention mask of a selection (tests/reference).

Data#

API#

class bridge.models.qwen.modeling_qwen4_exp.qsa.QSASelection#

Per-query block selection produced by :class:QSAIndexer.

All tensors are indexed by the flattened token position of the (full, gathered) sequence. Positions and block ids are relative to the start of the token’s own sequence (document).

.. attribute:: doc_ids

[b, s] int32 document id of every token (packed sequences) or the batch row.

.. attribute:: positions

[b, s] int32 position of every token inside its document.

.. attribute:: selected_bits

Flat uint8 bitset [b * s * nbytes] over document-relative block ids: for query (b, q) bit j of byte (b * s + q) * nbytes + i is set when block 8 * i + j is selected. Flat so that the FlexAttention mask kernel indexes a 1-D buffer (its row stride is passed as a tensor scalar to avoid recompiling per shape).

.. attribute:: bits_per_row

nbytes (python int).

.. attribute:: bits_per_row_t

nbytes as a 0-dim int64 tensor for the mask kernel.

.. attribute:: compress_ratio

Tokens per block.

.. attribute:: all_selected

True when every query selected all of its visible complete blocks, i.e. the attention pattern is plain causal attention.

doc_ids: torch.Tensor#

None

positions: torch.Tensor#

None

selected_bits: torch.Tensor#

None

bits_per_row: int#

None

bits_per_row_t: torch.Tensor#

None

compress_ratio: int#

None

all_selected: bool#

None

class bridge.models.qwen.modeling_qwen4_exp.qsa._DenseQSASelection#

Shape-proven causal selection, with no indexer tensors to materialize.

bridge.models.qwen.modeling_qwen4_exp.qsa._DENSE_QSA_SELECTION#

‘_DenseQSASelection(…)’

class bridge.models.qwen.modeling_qwen4_exp.qsa.QSAIndexerSubmodules#

Submodules of the QSA indexer.

linear_qk: Union[megatron.core.transformer.spec_utils.ModuleSpec, type]#

None

q_layernorm: Union[megatron.core.transformer.spec_utils.ModuleSpec, type]#

None

k_layernorm: Union[megatron.core.transformer.spec_utils.ModuleSpec, type]#

None

class bridge.models.qwen.modeling_qwen4_exp.qsa.QwenSparseSelfAttentionSubmodules#

Bases: megatron.core.transformer.attention.SelfAttentionSubmodules

Self-attention submodules plus the QSA indexer.

indexer: Union[megatron.core.transformer.spec_utils.ModuleSpec, type]#

None

bridge.models.qwen.modeling_qwen4_exp.qsa._sequence_layout(
batch_size: int,
seq_len: int,
packed_seq_params: Optional[megatron.core.packed_seq_params.PackedSeqParams],
device: torch.device,
) → Tuple[torch.Tensor, torch.Tensor, int]#

Document ids and in-document positions for every token.

Returns (doc_ids [b, s], positions [b, s], max_doc_len) as int32 tensors.

class bridge.models.qwen.modeling_qwen4_exp.qsa.QSAIndexer(
config: megatron.core.transformer.transformer_config.TransformerConfig,
submodules: bridge.models.qwen.modeling_qwen4_exp.qsa.QSAIndexerSubmodules,
layer_number: int,
pg_collection: Optional[megatron.core.process_groups_config.ProcessGroupCollection] = None,
)#

Bases: megatron.core.transformer.module.MegatronModule

Weight-light MQA indexer selecting the key blocks every query attends to.

Parameters are duplicated across tensor-parallel ranks (the projection is tiny); the indexer operates on the full, sequence-parallel-gathered sequence because the selection needs every key of the sequence.

Initialization

classmethod estimate_flops(
config: megatron.core.transformer.transformer_config.TransformerConfig,
*,
total_real_tokens_in_batch: float,
seqlen_squared_sum_in_batch: float,
) → float#

Count detached Q/K projections, excluding selection score work.

_rope_at_positions(
x: torch.Tensor,
freqs: torch.Tensor,
positions: torch.Tensor,
) → torch.Tensor#

Rotate x [N, D] with the frequencies of positions [N] (first rot_dim dims).

_pool_keys(
raw_keys: torch.Tensor,
doc_ids: torch.Tensor,
positions: torch.Tensor,
max_doc_len: int,
*,
num_docs: int | None = None,
) → Tuple[torch.Tensor, torch.Tensor, torch.Tensor]#

Mean-pool complete blocks of compress_ratio consecutive tokens per document.

Parameters:
  • raw_keys – [T, D] key of every token (flattened batch).

  • positions (doc_ids /) – [T] int32.

Returns:

(pooled [n_docs, n_blocks_max, D], block_positions [n_docs, n_blocks_max], block_valid [n_docs, n_blocks_max]). Only complete blocks are valid.

_select_blocks(
q: torch.Tensor,
pooled_keys: torch.Tensor,
block_valid: torch.Tensor,
doc_ids: torch.Tensor,
positions: torch.Tensor,
*,
unpacked_sequence_length: int | None = None,
) → Tuple[torch.Tensor, bool]#

Top-k complete blocks per query.

Parameters:
  • q – [T, H, D] normalized + rotated indexer queries.

  • pooled_keys – [n_docs, n_blocks_max, D] normalized + rotated block keys.

  • block_valid – [n_docs, n_blocks_max].

  • positions (doc_ids /) – [T] int32.

Returns:

(selected_bits [T, nbytes] uint8, all_selected).

forward(
hidden_states: torch.Tensor,
rotary_pos_emb: Optional[torch.Tensor],
packed_seq_params: Optional[megatron.core.packed_seq_params.PackedSeqParams] = None,
) → bridge.models.qwen.modeling_qwen4_exp.qsa.QSASelection#

Compute the block selection.

Parameters:
  • hidden_states – [s, b, H] layer input (sequence-parallel-sharded when SP is on).

  • rotary_pos_emb – [max_s, 1, 1, rot_dim] rotary frequencies of the attention layer.

  • packed_seq_params – THD packing parameters.

Returns:

class:

QSASelection over the full (gathered) sequence.

bridge.models.qwen.modeling_qwen4_exp.qsa._qsa_mask_mod_factory(
selection: bridge.models.qwen.modeling_qwen4_exp.qsa.QSASelection,
) → Callable[[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor], torch.Tensor]#

Build the FlexAttention mask_mod for a :class:QSASelection.

bridge.models.qwen.modeling_qwen4_exp.qsa._compiled_flex_attention() → Callable[..., torch.Tensor]#
class bridge.models.qwen.modeling_qwen4_exp.qsa.QSACoreAttention(
config: megatron.core.transformer.transformer_config.TransformerConfig,
layer_number: int,
attn_mask_type: megatron.core.transformer.enums.AttnMaskType,
attention_type: str,
dense_core_attention: type[torch.nn.Module],
cp_comm_type: Optional[str] = None,
softmax_scale: Optional[float] = None,
pg_collection: Optional[megatron.core.process_groups_config.ProcessGroupCollection] = None,
**kwargs: object,
)#

Bases: torch.nn.Module

Core attention of QSA: dense causal attention when the selection is complete, otherwise block-sparse FlexAttention over the selected tokens.

Constructed like the backend core-attention classes (config, layer_number, attn_mask_type, attention_type, cp_comm_type, softmax_scale, pg_collection) so it plugs into

Class:

~megatron.core.transformer.attention.Attention. dense_core_attention is the backend class used for the dense path. The selection is handed over by the owning

Class:

QwenSparseSelfAttention through :meth:set_selection right before the call.

Initialization

set_selection(
selection: bridge.models.qwen.modeling_qwen4_exp.qsa.QSASelection | bridge.models.qwen.modeling_qwen4_exp.qsa._DenseQSASelection | None,
) → None#

Register the block selection consumed by the next forward call.

_flex_forward(
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
selection: bridge.models.qwen.modeling_qwen4_exp.qsa.QSASelection,
is_thd: bool,
) → torch.Tensor#
_dense_masked_forward(
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
selection: bridge.models.qwen.modeling_qwen4_exp.qsa.QSASelection,
is_thd: bool,
) → torch.Tensor#

Reference path: materialize the boolean mask and run SDPA (O(s^2) memory).

forward(
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_mask: Optional[torch.Tensor],
attn_mask_type: Optional[megatron.core.transformer.enums.AttnMaskType] = None,
attention_bias: Optional[torch.Tensor] = None,
packed_seq_params: Optional[megatron.core.packed_seq_params.PackedSeqParams] = None,
) → torch.Tensor#

Attention over the selected tokens.

query/key/value are [s, b, h, d] (sbhd) or [t, h, d] (thd); the output is [s, b, h*d] / [t, h*d] like the backend core attention.

bridge.models.qwen.modeling_qwen4_exp.qsa.build_qsa_dense_mask(
selection: bridge.models.qwen.modeling_qwen4_exp.qsa.QSASelection,
seq_len: int,
) → torch.Tensor#

Materialize the [b, s, s] boolean attention mask of a selection (tests/reference).

class bridge.models.qwen.modeling_qwen4_exp.qsa.QwenSparseSelfAttention(
config: megatron.core.transformer.transformer_config.TransformerConfig,
submodules: bridge.models.qwen.modeling_qwen4_exp.qsa.QwenSparseSelfAttentionSubmodules,
layer_number: int,
attn_mask_type: megatron.core.transformer.enums.AttnMaskType = AttnMaskType.causal,
cp_comm_type: Optional[str] = None,
pg_collection: Optional[megatron.core.process_groups_config.ProcessGroupCollection] = None,
**kwargs: object,
)#

Bases: megatron.bridge.models.qwen_vl.modelling_qwen3_vl.attention.Qwen3VLSelfAttention

Gated GQA self-attention whose keys/values are selected per query by a QSA indexer.

The indexer runs unless the physical sequence shape proves dense selection; its result is handed to the

Class:

QSACoreAttention core-attention module, after which the standard

Class:

SelfAttention forward (QKV projection, QK-norm, RoPE, core attention, output gate, output projection) proceeds unchanged.

Initialization

classmethod estimate_flops(
config: megatron.core.transformer.transformer_config.TransformerConfig,
*,
total_real_tokens_in_batch: float,
seqlen_squared_sum_in_batch: float,
) → float#

Use Core’s causal dense surrogate; detached indexer work is separate.

_can_skip_indexer(hidden_states: torch.Tensor) → bool#

Prove every document fits the budget using only the physical sequence shape.

For THD this is deliberately conservative: the full packed length bounds every document, so no device scalar or document-boundary read is needed. The partial current block is always visible and does not consume top-k.

forward(
hidden_states: torch.Tensor,
attention_mask: torch.Tensor,
key_value_states: Optional[torch.Tensor] = None,
inference_context: megatron.core.inference.contexts.BaseInferenceContext | None = None,
rotary_pos_emb: Optional[Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]] = None,
rotary_pos_cos: Optional[torch.Tensor] = None,
rotary_pos_sin: Optional[torch.Tensor] = None,
rotary_pos_cos_sin: Optional[torch.Tensor] = None,
attention_bias: Optional[torch.Tensor] = None,
packed_seq_params: Optional[megatron.core.packed_seq_params.PackedSeqParams] = None,
sequence_len_offset: Optional[int] = None,
*,
inference_params: megatron.core.inference.contexts.BaseInferenceContext | None = None,
) → tuple[torch.Tensor, torch.Tensor | None]#

Register a shape-proven dense or indexed selection, then run regular attention.

bridge.models.qwen.modeling_qwen4_exp.qsa.__all__#

[‘QSACoreAttention’, ‘QSAIndexer’, ‘QSAIndexerSubmodules’, ‘QSASelection’, ‘QwenSparseSelfAttention’…