bridge.models.qwen.qwen4_exp_bridge#

Megatron Bridge for Qwen4-Exp (Qwen3.8-Flash-Next).

Qwen4-Exp is the Qwen3.5-MoE hybrid (3 x Gated DeltaNet + 1 x gated attention per block, 512-expert MoE with a gated shared expert) extended with

  • Gated Residual hyper connections: 4 residual streams, every sub-layer reads a sigmoid-gated mean of the per-stream RMS-normalized streams and writes back with per-stream scalar gates; the block output is a learned gated mix of the streams (hyper_connection_mixer);

  • Qwen Sparse Attention on the full-attention layers: an MQA indexer scores mean-pooled key blocks and every query attends to its top indexer_budget tokens plus its own block;

  • a Per-Layer (hashed n-gram) Embedding injected before one decoder layer, whose 51B-parameter table is stored as split_ngram_parts checkpoint shards;

  • a 1-layer MTP head (not bridged: MTP is disabled for the Megatron model).

The conditional-generation checkpoint includes the vision tower. text_only=True selects a standalone language checkpoint view and builds only the hybrid decoder.

Module Contents#

Classes#

PLENGramEmbeddingMapping

TP- or EP-sharded PLE n-gram table <-> split_ngram_parts HF shards.

_PLEShardExport

Lazy {hf_shard_name: tensor} view over a TP/EP-sharded PLE table.

_PLEHFShards

Lazy shard aliases so import can resolve TP/EP ownership at the destination.

_Qwen4TextStateSource

Lazy standalone text namespace over a VL checkpoint, including its LM head.

Qwen4ExpBridge

Bridge for the Qwen4-Exp vision-language model (Qwen3.8-Flash-Next).

Qwen4ExpTextBridge

Bridge for text-only Qwen4-Exp checkpoints (Qwen4ExpForCausalLM, model. prefix).

Functions#

linear_attention_pattern_from_hf

Per-layer pattern (1 = Gated DeltaNet, 0 = (sparse) softmax attention).

get_qwen4_exp_text_config

The language-model config of a unified (VL) or text-only Qwen4-Exp config.

get_qwen4_exp_hf_lm_prefix

model.language_model. for the VL checkpoint layout, model. for text-only ones.

ple_local_rows_from_shards

Assemble one TP or EP rank’s rows of a row-sharded HF table.

Data#

API#

bridge.models.qwen.qwen4_exp_bridge._LAYER_TYPE_TO_LINEAR#

None

bridge.models.qwen.qwen4_exp_bridge._PLE_SHARD_RE#

‘compile(
)’

bridge.models.qwen.qwen4_exp_bridge.linear_attention_pattern_from_hf(
text_config: transformers.PretrainedConfig,
) → list[int]#

Per-layer pattern (1 = Gated DeltaNet, 0 = (sparse) softmax attention).

Qwen4ExpTextConfig.__post_init__ rewrites the checkpoint’s full_attention entries to qwen_sparse_attention (older Transformers) or indexed_attention (current Transformers).

bridge.models.qwen.qwen4_exp_bridge.get_qwen4_exp_text_config(
hf_config: transformers.PretrainedConfig,
) → transformers.PretrainedConfig#

The language-model config of a unified (VL) or text-only Qwen4-Exp config.

bridge.models.qwen.qwen4_exp_bridge.get_qwen4_exp_hf_lm_prefix(
hf_config: transformers.PretrainedConfig,
) → str#

model.language_model. for the VL checkpoint layout, model. for text-only ones.

bridge.models.qwen.qwen4_exp_bridge.ple_local_rows_from_shards(
load_shard: Callable[[int], torch.Tensor],
num_shards: int,
num_rows_total: int,
shard_rows: int,
tp_rank: int,
tp_size: int,
) → torch.Tensor#

Assemble one TP or EP rank’s rows of a row-sharded HF table.

Rank r owns rows [r * rows_per_rank, (r + 1) * rows_per_rank) (the VocabParallelEmbedding layout); only the HF shards overlapping that range are loaded.

Parameters:
  • load_shard – callable(shard_index) -> Tensor loading one HF shard.

  • num_shards – Number of HF shards.

  • num_rows_total – Total (padded) row count of the table.

  • shard_rows – Rows per HF shard (all but possibly the last shard).

  • tp_size (tp_rank /) – Row-sharding coordinates (TP or EP).

class bridge.models.qwen.qwen4_exp_bridge.PLENGramEmbeddingMapping(
megatron_param: str,
hf_param: str | Dict[str, str],
num_shards: Optional[int] = None,
)#

Bases: megatron.bridge.models.conversion.param_mapping.MegatronParamMapping[typing.Mapping[str, torch.Tensor]]

TP- or EP-sharded PLE n-gram table <-> split_ngram_parts HF shards.

The HF checkpoint stores the table row-split into ngram_embedding.shard_<i>.weight tensors (concatenated along dim 0 they form the padded table). Megatron keeps the table as a

Class:

~megatron.core.tensor_parallel.layers.VocabParallelEmbedding, i.e. row-sharded across the tensor-parallel group, or a frozen table row-sharded across the expert-parallel group.

Import is rank-local: the lazy HF source reads only the shards that overlap the destination’s row range (:func:ple_local_rows_from_shards), so the 51B-parameter table is never materialized in full on any rank. Export streams the table back out one HF shard at a time (:class:_PLEShardExport): each shard is assembled from the TP or EP ranks’ rows when the export loop reaches it, so peak memory is one shard (~0.8 GB for Qwen3.8-Flash-Next), not the ~100 GB table.

Initialization

Parameters:
  • megatron_param – Megatron parameter name pattern.

  • hf_param – Either the HF shard-name pattern with a {} placeholder for the shard index (then num_shards is required), or the already expanded {"shard_<i>": name} dict (the form :meth:resolve re-instantiates the mapping with).

  • num_shards – Number of HF shards when hf_param is a pattern.

_row_sharding(
megatron_module: torch.nn.Module | None,
) → tuple[torch.distributed.ProcessGroup | None, int, int]#
hf_to_megatron(
hf_weights: Mapping[str, torch.Tensor],
megatron_module: torch.nn.Module,
) → torch.Tensor#

Return this rank’s rows.

hf_weights is a lazy shard mapping, a full shard dict, or a preloaded rank-local {"local_rows": Tensor}.

megatron_to_hf(
megatron_weights: Optional[torch.Tensor],
megatron_module: Optional[torch.nn.Module],
) → Mapping[str, torch.Tensor]#

Re-split the TP/EP rows into the checkpoint’s shard layout, one shard at a time.

Returns a lazy mapping: shard i is assembled over the row-sharding group when the export loop iterates to it, so all owners must consume the shards in the same order – which the export does, and which a dict(...) / .items() traversal preserves.

gather_shard(
local_rows: torch.Tensor,
shard_index: int,
*,
megatron_module: torch.nn.Module | None = None,
) → torch.Tensor#

Assemble one HF shard over the table’s TP or EP group.

Rank r owns rows [r * rows_per_rank, (r + 1) * rows_per_rank). EP owners broadcast their intersections without arithmetic, preserving the frozen table’s bits. The existing TP path sums zero-filled buffers with one owner per row.

class bridge.models.qwen.qwen4_exp_bridge._PLEShardExport(
mapping: bridge.models.qwen.qwen4_exp_bridge.PLENGramEmbeddingMapping,
local_rows: torch.Tensor,
module: torch.nn.Module | None = None,
)#

Bases: typing.Mapping[str, torch.Tensor]

Lazy {hf_shard_name: tensor} view over a TP/EP-sharded PLE table.

Initialization

__getitem__(name: str) → torch.Tensor#
__iter__() → Iterator[str]#
__len__() → int#
class bridge.models.qwen.qwen4_exp_bridge._PLEHFShards(
names: dict[str, str],
source: Mapping[str, torch.Tensor],
*,
block_size: tuple[int, int] | None,
)#

Bases: typing.Mapping[str, torch.Tensor]

Lazy shard aliases so import can resolve TP/EP ownership at the destination.

Initialization

__getitem__(name: str) → torch.Tensor#
__iter__() → Iterator[str]#
__len__() → int#
class bridge.models.qwen.qwen4_exp_bridge._Qwen4TextStateSource(
source: megatron.bridge.models.hf_pretrained.state.SafeTensorsStateSource,
)#

Bases: megatron.bridge.models.hf_pretrained.state.SafeTensorsStateSource

Lazy standalone text namespace over a VL checkpoint, including its LM head.

Initialization

property key_to_filename_map: dict[str, str]#

Preserve source shard filenames while excluding vision and MTP weights.

static _text_key(key: str) → str#
get_all_keys() → list[str]#

List the standalone language checkpoint keys without loading tensors.

load_tensors(keys_to_load: list[str]) → dict[str, torch.Tensor]#

Read only requested language tensors from the original VL shards.

class bridge.models.qwen.qwen4_exp_bridge.Qwen4ExpBridge#

Bases: megatron.bridge.models.conversion.model_bridge.MegatronModelBridge

Bridge for the Qwen4-Exp vision-language model (Qwen3.8-Flash-Next).

.. rubric:: Example

from megatron.bridge import AutoBridge bridge = AutoBridge.from_hf_pretrained(“Qwen/Qwen3.8-Flash-Next”) config = bridge.get_model_config()

MODEL_CONFIG_CLASS#

None

USE_MODEL_CONFIG_FOR_CONVERSION#

True

text_only_pretrained(
hf_pretrained: megatron.bridge.models.hf_pretrained.causal_lm.PreTrainedCausalLM,
) → megatron.bridge.models.hf_pretrained.causal_lm.PreTrainedCausalLM#

Project a VLM checkpoint to the registered standalone text architecture.

abstractmethod provider_bridge(
hf_pretrained: megatron.bridge.models.hf_pretrained.causal_lm.PreTrainedCausalLM,
) → megatron.bridge.models.qwen.modeling_qwen4_exp.model_config.Qwen4ExpModelConfig#

Require the builder-backed entrypoint for this model family.

hf_config_to_model_config(
hf_config: transformers.PretrainedConfig,
) → megatron.bridge.models.qwen.modeling_qwen4_exp.model_config.Qwen4ExpModelConfig#

Convert text and optional vision settings into declarative model configs.

static _hyper_connection_mappings(
megatron_prefix: str,
hf_prefix: str,
with_inject: bool,
) → list[megatron.bridge.models.conversion.param_mapping.ReplicatedMapping]#
static get_lm_mappings(
hf_prefix: str,
experts_packed: bool,
text_config: transformers.PretrainedConfig,
num_ple_shards: int,
megatron_prefix: str = '',
) → list[megatron.bridge.models.conversion.param_mapping.MegatronParamMapping[torch.Tensor] | megatron.bridge.models.conversion.param_mapping.MegatronParamMapping[dict[str, torch.Tensor]]]#

Parameter mappings for standalone or VLM-nested hybrid language decoders.

_num_ple_shards(text_config: transformers.PretrainedConfig) → int#

Number of shard_<i> tensors per PLE table, from the checkpoint keys when available.

mapping_registry() → megatron.bridge.models.conversion.mapping_registry.MegatronMappingRegistry#

Map the hybrid language model and, for VLM checkpoints, the vision tower.

_load_hf_weights(
hf_param: str | dict[str, str],
hf_state_dict: Mapping[str, torch.Tensor],
) → torch.Tensor | Mapping[str, torch.Tensor]#

Load and dequantize PLE shards only after destination ownership is known.

The generic loader inspects every mapping value for FP8 tensors. PLE instead applies that preprocessing to each shard when it is requested.

class bridge.models.qwen.qwen4_exp_bridge.Qwen4ExpTextBridge#

Bases: bridge.models.qwen.qwen4_exp_bridge.Qwen4ExpBridge

Bridge for text-only Qwen4-Exp checkpoints (Qwen4ExpForCausalLM, model. prefix).

MODEL_CONFIG_CLASS#

None

text_only_pretrained(
hf_pretrained: megatron.bridge.models.hf_pretrained.causal_lm.PreTrainedCausalLM,
) → megatron.bridge.models.hf_pretrained.causal_lm.PreTrainedCausalLM#

A standalone text checkpoint already contains only language weights.

bridge.models.qwen.qwen4_exp_bridge.__all__#

[‘PLENGramEmbeddingMapping’, ‘Qwen4ExpBridge’, ‘Qwen4ExpTextBridge’, ‘get_qwen4_exp_hf_lm_prefix’, ‘