bridge.models.conversion.modelopt_utils#

Module Contents#

Classes#

Functions#

_same_storage

_direct_weight_name

_traces_rows

Whether the HF rows of a quantized weight come from tracing the mapping’s own megatron_to_hf.

_trace_rows

Rows of the TP-merged weight that land in each HF output, from the mapping’s own conversion.

_mapping_parallelism

_qkv_layout

_gdn_layout

_gdn_row_indices

Rows of the gathered in_proj that land in each HF projection, from the mapping’s own split.

_unquantized_outputs

_mamba_layout

_mamba_row_indices

Follow MambaInProjMapping’s component-wise TP gather for quantization state.

_validate_quantized_task

_capture_source_state

_capture_source_spec

_all_gather_objects

_raise_distributed_errors

_world_group

_sync_source_specs

_transform_source_spec

_mapping_names

_merge_states

_select_state

_gather_source_states

_transform_source_state

_local_expert_mapping

_stage_tensor_for_collective

_capture_current_source_state

_gather_expert_outputs

_compose_export_hooks

_make_export_hook

_make_oai_mxfp4_export_hook

_oai_mxfp4_quantization_config

OpenAI’s MXFP4 config, which keeps every layer but the experts in BF16.

build_modelopt_export_plan

Prepare canonical ModelOpt export state without encoding a quantization format.

prepare_modelopt_export_tasks

Attach fresh per-stream state capture hooks to a metadata-only plan.

_checkpoint_export_plan

Return plan writing KV-cache scales the way ModelOpt’s checkpoint exporters do.

_kv_finalizer

check_fused_sibling_scales

Reject per-tensor scales that differ within a group of projections deployments fuse.

check_exportable_quantizers

Fail on every rank when any rank holds an enabled quantizer the export would drop.

save_safetensors_shards

Stream tensors into HF safetensors shards of at most max_shard_size bytes each.

Data#

API#

bridge.models.conversion.modelopt_utils.HFExportHook#

None

class bridge.models.conversion.modelopt_utils.ModelOptExportPlan#

Bases: typing.NamedTuple

Prepared conversion tasks and stable canonical ModelOpt metadata.

conversion_tasks: list[megatron.bridge.models.conversion.model_bridge.WeightConversionTask]#

None

quantization_config: dict[str, Any]#

None

quantized_params: frozenset[str]#

None

local_quantization_specs: dict[str, object | None]#

None

traced_rows: dict[str, tuple[tuple[str, tuple[int, ...]], ...]]#

None

class bridge.models.conversion.modelopt_utils._SourceState#
state: object | None#

None

weight_shape: tuple[int, ...]#

None

parallelism: str | None#

None

qkv_layout: tuple[int, int, int, int, bool] | None#

None

weight_dtype: torch.dtype | None#

None

gdn_layout: tuple[int, int, int, int] | None#

None

mamba_layout: tuple[int, int, int, int, int] | None#

None

traced_rows: tuple[tuple[str, tuple[int, ...]], ...] | None#

None

bridge.models.conversion.modelopt_utils._GDN_UNQUANTIZED_OUTPUTS#

(‘b’, ‘a’)

bridge.models.conversion.modelopt_utils._OAI_MXFP4_FORMAT#

‘w4a16_mxfp4’

bridge.models.conversion.modelopt_utils._same_storage(left: object, right: object) → bool#
bridge.models.conversion.modelopt_utils._direct_weight_name(
module: torch.nn.Module,
weight: torch.Tensor,
) → str | None#
bridge.models.conversion.modelopt_utils._ROW_LAYOUT_MAPPINGS#

()

bridge.models.conversion.modelopt_utils._PLAIN_MAPPINGS#

()

bridge.models.conversion.modelopt_utils._traces_rows(mapping: Any) → bool#

Whether the HF rows of a quantized weight come from tracing the mapping’s own megatron_to_hf.

bridge.models.conversion.modelopt_utils._trace_rows(
task: megatron.bridge.models.conversion.model_bridge.WeightConversionTask,
parallelism: str,
) → tuple[tuple[str, tuple[int, ...]], ...]#

Rows of the TP-merged weight that land in each HF output, from the mapping’s own conversion.

Each element is labeled with its (row, column) in the merged weight, so the converted labels show where every element went. Only whole-row selections can reuse the weight’s quantization state.

bridge.models.conversion.modelopt_utils._mapping_parallelism(
mapping: Any,
module: torch.nn.Module,
) → str#
bridge.models.conversion.modelopt_utils._qkv_layout(
mapping: Any,
module: torch.nn.Module,
) → tuple[int, int, int, int, bool] | None#
bridge.models.conversion.modelopt_utils._gdn_layout(
mapping: Any,
module: torch.nn.Module,
) → tuple[int, int, int, int] | None#
bridge.models.conversion.modelopt_utils._gdn_row_indices(
layout: tuple[int, int, int, int],
rows: int,
tp_size: int,
) → dict[str, torch.Tensor]#

Rows of the gathered in_proj that land in each HF projection, from the mapping’s own split.

bridge.models.conversion.modelopt_utils._unquantized_outputs(mapping: Any) → set[str]#
bridge.models.conversion.modelopt_utils._mamba_layout(
mapping: Any,
module: torch.nn.Module,
) → tuple[int, int, int, int, int] | None#
bridge.models.conversion.modelopt_utils._mamba_row_indices(
shards: list[bridge.models.conversion.modelopt_utils._SourceState],
tp_size: int,
) → torch.Tensor#

Follow MambaInProjMapping’s component-wise TP gather for quantization state.

bridge.models.conversion.modelopt_utils._validate_quantized_task(
task: megatron.bridge.models.conversion.model_bridge.WeightConversionTask,
) → None#
bridge.models.conversion.modelopt_utils._capture_source_state(
task: megatron.bridge.models.conversion.model_bridge.WeightConversionTask,
) → bridge.models.conversion.modelopt_utils._SourceState | None#
bridge.models.conversion.modelopt_utils._capture_source_spec(
task: megatron.bridge.models.conversion.model_bridge.WeightConversionTask,
) → bridge.models.conversion.modelopt_utils._SourceState | None#
bridge.models.conversion.modelopt_utils._all_gather_objects(
value: Any,
group: Any,
) → list[Any]#
bridge.models.conversion.modelopt_utils._raise_distributed_errors(
error: str | None,
group: Any,
context: str,
) → None#
bridge.models.conversion.modelopt_utils._world_group() → Any#
bridge.models.conversion.modelopt_utils._sync_source_specs(
local_states: dict[str, bridge.models.conversion.modelopt_utils._SourceState],
group: Any,
) → dict[str, bridge.models.conversion.modelopt_utils._SourceState]#
bridge.models.conversion.modelopt_utils._transform_source_spec(
task: megatron.bridge.models.conversion.model_bridge.WeightConversionTask,
source: bridge.models.conversion.modelopt_utils._SourceState,
) → dict[str, object | None]#
bridge.models.conversion.modelopt_utils._mapping_names(
mapping: Any,
traced_rows: tuple[tuple[str, tuple[int, ...]], ...] | None = None,
) → dict[str, str]#
bridge.models.conversion.modelopt_utils._merge_states(states: list[object], weight_dim: int) → object#
bridge.models.conversion.modelopt_utils._select_state(
state: object,
weight_dim: int,
indices: torch.Tensor,
) → object#
bridge.models.conversion.modelopt_utils._gather_source_states(
source: bridge.models.conversion.modelopt_utils._SourceState | None,
mapping: Any,
capture_error: str | None = None,
) → list[bridge.models.conversion.modelopt_utils._SourceState]#
bridge.models.conversion.modelopt_utils._transform_source_state(
task: megatron.bridge.models.conversion.model_bridge.WeightConversionTask,
source: bridge.models.conversion.modelopt_utils._SourceState | None,
capture_error: str | None = None,
traced_rows: tuple[tuple[str, tuple[int, ...]], ...] | None = None,
) → dict[str, object | None]#
class bridge.models.conversion.modelopt_utils._LocalExpertMappingMixin#
property tp_group#
property is_expert: bool#
class bridge.models.conversion.modelopt_utils._LocalExpertColumnMapping#

Bases: bridge.models.conversion.modelopt_utils._LocalExpertMappingMixin, megatron.bridge.models.conversion.param_mapping.ColumnParallelMapping

class bridge.models.conversion.modelopt_utils._LocalExpertRowMapping#

Bases: bridge.models.conversion.modelopt_utils._LocalExpertMappingMixin, megatron.bridge.models.conversion.param_mapping.RowParallelMapping

class bridge.models.conversion.modelopt_utils._LocalExpertReplicatedMapping#

Bases: bridge.models.conversion.modelopt_utils._LocalExpertMappingMixin, megatron.bridge.models.conversion.param_mapping.ReplicatedMapping

class bridge.models.conversion.modelopt_utils._LocalExpertAutoMapping#

Bases: bridge.models.conversion.modelopt_utils._LocalExpertMappingMixin, megatron.bridge.models.conversion.param_mapping.AutoMapping

_get_or_create_mapping(parallelism_type: str)#
class bridge.models.conversion.modelopt_utils._LocalExpertGatedMLPMapping#

Bases: bridge.models.conversion.modelopt_utils._LocalExpertMappingMixin, megatron.bridge.models.conversion.param_mapping.GatedMLPMapping

bridge.models.conversion.modelopt_utils._local_expert_mapping(
mapping: Any,
global_param_name: str,
pg_collection: Any,
) → Any | None#
bridge.models.conversion.modelopt_utils._stage_tensor_for_collective(
tensor: torch.Tensor,
group: Any,
) → torch.Tensor#
bridge.models.conversion.modelopt_utils._capture_current_source_state(
task: megatron.bridge.models.conversion.model_bridge.WeightConversionTask,
) → tuple[bridge.models.conversion.modelopt_utils._SourceState | None, str | None]#
bridge.models.conversion.modelopt_utils._gather_expert_outputs(
outputs: collections.abc.Iterable[megatron.bridge.models.conversion.model_bridge.HFWeightTuple],
group: Any,
) → collections.abc.Iterable[megatron.bridge.models.conversion.model_bridge.HFWeightTuple]#
bridge.models.conversion.modelopt_utils._compose_export_hooks(
exporter: bridge.models.conversion.modelopt_utils.HFExportHook,
finalizer: collections.abc.Callable[[collections.abc.Iterable[megatron.bridge.models.conversion.model_bridge.HFWeightTuple]], collections.abc.Iterable[megatron.bridge.models.conversion.model_bridge.HFWeightTuple]] | None,
) → bridge.models.conversion.modelopt_utils.HFExportHook#
bridge.models.conversion.modelopt_utils._make_export_hook(
task: megatron.bridge.models.conversion.model_bridge.WeightConversionTask,
traced_rows: tuple[tuple[str, tuple[int, ...]], ...] | None = None,
) → bridge.models.conversion.modelopt_utils.HFExportHook#
bridge.models.conversion.modelopt_utils._make_oai_mxfp4_export_hook(
task: megatron.bridge.models.conversion.model_bridge.WeightConversionTask,
) → bridge.models.conversion.modelopt_utils.HFExportHook#
bridge.models.conversion.modelopt_utils._oai_mxfp4_quantization_config(
named_specs: dict[str, object | None],
expert_names: set[str],
) → dict[str, Any]#

OpenAI’s MXFP4 config, which keeps every layer but the experts in BF16.

bridge.models.conversion.modelopt_utils.build_modelopt_export_plan(
conversion_tasks: list[megatron.bridge.models.conversion.model_bridge.WeightConversionTask | None],
*,
model: list[torch.nn.Module],
tied_weight_aliases: dict[str, str] | None = None,
) → bridge.models.conversion.modelopt_utils.ModelOptExportPlan#

Prepare canonical ModelOpt export state without encoding a quantization format.

Parameters:
  • conversion_tasks – Weight conversion tasks, including remote pipeline-stage tasks.

  • model – Megatron model chunks used to capture quantization state.

  • tied_weight_aliases – HF alias-to-source weight names that share export specifications even when the alias has no separate conversion task.

bridge.models.conversion.modelopt_utils.prepare_modelopt_export_tasks(
plan: bridge.models.conversion.modelopt_utils.ModelOptExportPlan,
) → list[megatron.bridge.models.conversion.model_bridge.WeightConversionTask]#

Attach fresh per-stream state capture hooks to a metadata-only plan.

bridge.models.conversion.modelopt_utils._checkpoint_export_plan(
plan: bridge.models.conversion.modelopt_utils.ModelOptExportPlan,
) → bridge.models.conversion.modelopt_utils.ModelOptExportPlan#

Return plan writing KV-cache scales the way ModelOpt’s checkpoint exporters do.

bridge.models.conversion.modelopt_utils._kv_finalizer(
hook: megatron.bridge.models.conversion._modelopt_kv._KVExportHook,
) → collections.abc.Callable[[collections.abc.Iterable[megatron.bridge.models.conversion.model_bridge.HFWeightTuple]], collections.abc.Iterable[megatron.bridge.models.conversion.model_bridge.HFWeightTuple]]#
bridge.models.conversion.modelopt_utils._FUSED_SIBLING_PROJECTIONS#

()

bridge.models.conversion.modelopt_utils._SHARED_SIBLING_SCALES#

(‘weight_scale_2’, ‘input_scale’)

bridge.models.conversion.modelopt_utils._EXPORTED_QUANTIZER#

‘compile(…)’

bridge.models.conversion.modelopt_utils._WEIGHT_QUANTIZER#

‘compile(…)’

bridge.models.conversion.modelopt_utils.check_fused_sibling_scales(
tensors: collections.abc.Mapping[str, torch.Tensor],
) → None#

Reject per-tensor scales that differ within a group of projections deployments fuse.

Parameters:

tensors – Exported HF tensors; only the weight_scale_2 and input_scale entries are read.

Raises:

ValueError – If siblings such as q_proj / k_proj / v_proj carry different scales.

bridge.models.conversion.modelopt_utils.check_exportable_quantizers(model: list[torch.nn.Module]) → None#

Fail on every rank when any rank holds an enabled quantizer the export would drop.

Only weight, input and attention BMM (KV-cache) quantizers become checkpoint tensors; e.g. output quantizers have no deployment format here yet, and an input quantizer is exported only with its layer’s weight quantizer.

bridge.models.conversion.modelopt_utils.save_safetensors_shards(
tensors: collections.abc.Iterable[megatron.bridge.models.conversion.model_bridge.HFWeightTuple],
path: pathlib.Path,
*,
max_shard_size: int,
) → set[str]#

Stream tensors into HF safetensors shards of at most max_shard_size bytes each.

Unlike the source-checkpoint layout, this accepts tensors the source does not have, such as quantization scales. A single shard is written as model.safetensors without an index.

Returns:

Names of the files written, relative to path.