bridge.models.qwen.modeling_qwen4_exp.per_layer_embedding#

Per-Layer (hashed n-gram) Embedding of Qwen4-Exp / Qwen3.8-Flash-Next.

A PLE module sits at the start of a decoder layer and adds a token-local lexical signal to every hyper-connection residual stream:

e      = concat_h  E_h[ hash_h(n-gram ending at t) ]          # [.., ple_embed_dim]
key    = GroupRMSNorm(W_k e)        (one key per residual stream)
value  = W_v e                       (shared across streams)
gate_j = signed_sqrt( <key_j, GroupRMSNorm(x)_j> / sqrt(C) )
g      = sigmoid(gate_j) * value                                # [.., n, C]
out    = g + silu( DilatedDepthwiseCausalConv1d( GroupRMSNorm(g) ) )

The hashed n-gram table is the bulk of the parameters (51B for Qwen3.8-Flash-Next) and is stored vocab-parallel across the tensor-parallel group with :class:VocabParallelEmbedding, or row-sharded across EP when the n-gram table is frozen.

The n-gram ids depend on the raw token ids, which decoder layers do not receive. Qwen4ExpHybridModel therefore calls :meth:PerLayerEmbedding.prepare with the token ids (and packed-sequence boundaries) before running the decoder; the module keeps them until the next prepare.

Module Contents#

Classes#

NGramEmbedding

Hashed n-gram embedding table of one PLE module (ple.ple_embedding in HF).

PerLayerEmbedding

Qwen4-Exp PLE layer: gate hashed n-gram values into every residual stream.

Functions#

_splitmix64

build_ngram_layer_multipliers

Deterministic odd hash multipliers for one PLE module (matches the HF reference).

_is_prime

find_nth_prime_after

Return the count-th prime strictly greater than start.

build_ngram_vocab_layout

Per-head prime vocabulary sizes, row offsets and the total row count of one PLE table.

ngram_segment_positions

Position of every token inside its n-gram segment.

shift_tokens_in_segment

Token shift steps back, or eos_token_id when that crosses a segment start.

Data#

API#

bridge.models.qwen.modeling_qwen4_exp.per_layer_embedding._MASK64#

None

bridge.models.qwen.modeling_qwen4_exp.per_layer_embedding._SPLITMIX_GAMMA#

11400714819323198485

bridge.models.qwen.modeling_qwen4_exp.per_layer_embedding._SPLITMIX_M1#

13787848793156543929

bridge.models.qwen.modeling_qwen4_exp.per_layer_embedding._SPLITMIX_M2#

10723151780598845931

bridge.models.qwen.modeling_qwen4_exp.per_layer_embedding._PLE_LAYER_PRIME#

10007

bridge.models.qwen.modeling_qwen4_exp.per_layer_embedding._splitmix64(value: int) → int#
bridge.models.qwen.modeling_qwen4_exp.per_layer_embedding.build_ngram_layer_multipliers(
unigram_vocab_size: int,
ngram_size: int,
ple_layer_index: int,
seed: int,
) → List[int]#

Deterministic odd hash multipliers for one PLE module (matches the HF reference).

bridge.models.qwen.modeling_qwen4_exp.per_layer_embedding._is_prime(value: int) → bool#
bridge.models.qwen.modeling_qwen4_exp.per_layer_embedding.find_nth_prime_after(start: int, count: int) → int#

Return the count-th prime strictly greater than start.

bridge.models.qwen.modeling_qwen4_exp.per_layer_embedding.build_ngram_vocab_layout(
ngram_vocab_size_base: int,
ngram_heads: int,
ple_layer_index: int,
) → Tuple[List[int], List[int], int]#

Per-head prime vocabulary sizes, row offsets and the total row count of one PLE table.

bridge.models.qwen.modeling_qwen4_exp.per_layer_embedding.ngram_segment_positions(
token_ids: torch.Tensor,
eos_token_id: int,
cu_seqlens: Optional[torch.Tensor] = None,
) → torch.Tensor#

Position of every token inside its n-gram segment.

A segment starts after an eos_token_id token and at every packed-sequence boundary (cu_seqlens, THD layout with token_ids of shape [1, T]).

Parameters:
  • token_ids – [b, s] token ids.

  • eos_token_id – Reset token id.

  • cu_seqlens – Optional cumulative sequence lengths of packed sequences.

Returns:

[b, s] int64 positions within the segment (0 for the first token of a segment).

bridge.models.qwen.modeling_qwen4_exp.per_layer_embedding.shift_tokens_in_segment(
token_ids: torch.Tensor,
position_in_segment: torch.Tensor,
shift: int,
eos_token_id: int,
) → torch.Tensor#

Token shift steps back, or eos_token_id when that crosses a segment start.

class bridge.models.qwen.modeling_qwen4_exp.per_layer_embedding.NGramEmbedding(
config: megatron.core.transformer.transformer_config.TransformerConfig,
embedding_dim: int,
ple_layer_index: int,
*,
pg_collection: megatron.core.process_groups_config.ProcessGroupCollection,
)#

Bases: megatron.core.transformer.module.MegatronModule

Hashed n-gram embedding table of one PLE module (ple.ple_embedding in HF).

Every n-gram order (bigrams, trigrams, …) owns heads_per_ngram independently hashed heads; each head indexes its own prime-sized slice of a single vocab-parallel table whose rows are embedding_dim // ngram_heads wide. The concatenation of all heads is the embedding.

Initialization

compute_ngram_ids(
token_ids: torch.Tensor,
cu_seqlens: Optional[torch.Tensor] = None,
) → torch.Tensor#

Hashed table rows for every token and head.

Parameters:
  • token_ids – [b, s] token ids.

  • cu_seqlens – Optional packed-sequence boundaries (THD).

Returns:

[b, s, ngram_heads] int64 row ids into the (global) n-gram table.

forward(ngram_ids: torch.Tensor) → torch.Tensor#

Look up [b, s, heads] ids -> [s_local, b, embedding_dim] (sequence-first).

With sequence parallelism the output covers this rank’s s // tp tokens. TP tables reduce-scatter embeddings; EP tables route only this SP rank’s requests.

class bridge.models.qwen.modeling_qwen4_exp.per_layer_embedding.PerLayerEmbedding(
config: megatron.core.transformer.transformer_config.TransformerConfig,
layer_number: int,
*,
pg_collection: megatron.core.process_groups_config.ProcessGroupCollection,
)#

Bases: megatron.core.transformer.module.MegatronModule

Qwen4-Exp PLE layer: gate hashed n-gram values into every residual stream.

Built from a per_layer_embedding layer-spec slot; layer_number (one-indexed) selects the PLE index through config.ple_layer_ids.

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 trainable key/value projections; lookup tables have no matrix FLOPs.

prepare(
token_ids: torch.Tensor,
cu_seqlens: Optional[torch.Tensor] = None,
) → None#

Stash the n-gram ids and positions for the next forward pass.

Parameters:
  • token_ids – [b, s] raw token ids of the full (not sequence-parallel-sharded) batch.

  • cu_seqlens – Packed-sequence boundaries for THD inputs ([1, T] token ids).

_local_positions(seq_len_local: int) → torch.Tensor#

[s_local, b] positions (within their document) of this rank’s tokens.

_causal_dilated_conv(
x: torch.Tensor,
positions: torch.Tensor,
) → torch.Tensor#

Depthwise causal conv with dilation over the sequence dim of x [s_local, b, D].

Taps that reach before the token’s document start read zeros. Under sequence parallelism the halo rows preceding this rank’s chunk are fetched from the previous tensor-parallel rank.

forward(hidden_states: torch.Tensor) → torch.Tensor#

[s_local, b, nC] streams -> [s_local, b, nC] PLE update (to be added by the layer).