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_budgettokens 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_partscheckpoint 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#
TP- or EP-sharded PLE n-gram table <-> |
|
Lazy |
|
Lazy shard aliases so import can resolve TP/EP ownership at the destination. |
|
Lazy standalone text namespace over a VL checkpoint, including its LM head. |
|
Bridge for the Qwen4-Exp vision-language model (Qwen3.8-Flash-Next). |
|
Bridge for text-only Qwen4-Exp checkpoints ( |
Functions#
Per-layer pattern (1 = Gated DeltaNet, 0 = (sparse) softmax attention). |
|
The language-model config of a unified (VL) or text-only Qwen4-Exp config. |
|
|
|
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,
Per-layer pattern (1 = Gated DeltaNet, 0 = (sparse) softmax attention).
Qwen4ExpTextConfig.__post_init__rewrites the checkpointâsfull_attentionentries toqwen_sparse_attention(older Transformers) orindexed_attention(current Transformers).
- bridge.models.qwen.qwen4_exp_bridge.get_qwen4_exp_text_config(
- hf_config: 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,
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,
Assemble one TP or EP rankâs rows of a row-sharded HF table.
Rank
rowns rows[r * rows_per_rank, (r + 1) * rows_per_rank)(theVocabParallelEmbeddinglayout); only the HF shards overlapping that range are loaded.- Parameters:
load_shard â
callable(shard_index) -> Tensorloading 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_partsHF shards.The HF checkpoint stores the table row-split into
ngram_embedding.shard_<i>.weighttensors (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 (thennum_shardsis required), or the already expanded{"shard_<i>": name}dict (the form :meth:resolvere-instantiates the mapping with).num_shards â Number of HF shards when
hf_paramis a pattern.
- _row_sharding(
- megatron_module: torch.nn.Module | None,
- hf_to_megatron(
- hf_weights: Mapping[str, torch.Tensor],
- megatron_module: torch.nn.Module,
Return this rankâs rows.
hf_weightsis 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],
Re-split the TP/EP rows into the checkpointâs shard layout, one shard at a time.
Returns a lazy mapping: shard
iis 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 adict(...)/.items()traversal preserves.
- gather_shard(
- local_rows: torch.Tensor,
- shard_index: int,
- *,
- megatron_module: torch.nn.Module | None = None,
Assemble one HF shard over the tableâs TP or EP group.
Rank
rowns 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.SafeTensorsStateSourceLazy 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.MegatronModelBridgeBridge 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,
Project a VLM checkpoint to the registered standalone text architecture.
- abstractmethod provider_bridge(
- hf_pretrained: megatron.bridge.models.hf_pretrained.causal_lm.PreTrainedCausalLM,
Require the builder-backed entrypoint for this model family.
- hf_config_to_model_config(
- hf_config: transformers.PretrainedConfig,
Convert text and optional vision settings into declarative model configs.
- static _hyper_connection_mappings(
- megatron_prefix: str,
- hf_prefix: str,
- with_inject: bool,
- static get_lm_mappings(
- hf_prefix: str,
- experts_packed: bool,
- text_config: transformers.PretrainedConfig,
- num_ple_shards: int,
- megatron_prefix: str = '',
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],
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.Qwen4ExpBridgeBridge 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,
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â, ââŠ