# Copyright 2025 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Checkpoint tensor converter utilities for runtime weight format conversion. Models that need to convert HuggingFace checkpoint tensors at load time (e.g. MoE per-expert weights -> fused format) register a ``_create_checkpoint_tensor_converter`` class attribute. The helpers here retrieve and apply such converters during streaming weight load. Models that need to rename per-expert HF ``weight_map`` keys for sharded HF export register a ``_convert_fqn_to_index_mapping`` class attribute (same module as the tensor converter). Conversion runs at save time (and is cached on the model after load when an index mapping is supplied). """ import inspect import json from dataclasses import dataclass from typing import TYPE_CHECKING, Callable, Dict, Generator, List, Optional, Protocol, Tuple, Union import torch from torch import nn from torch.distributed.tensor import DTensor from veomni.distributed import parallel_state from veomni.utils import logging from veomni.utils.device import get_device_id, get_device_type if TYPE_CHECKING: from transformers import PreTrainedModel logger = logging.get_logger(__name__) @dataclass class ConvertedCheckpointTensor: """One converted checkpoint tensor ready for dispatch.""" name: str tensor: "torch.Tensor" class CheckpointTensorConverter(Protocol): """Per-tensor converter protocol for runtime checkpoint format conversion. Models register a converter via ``_create_checkpoint_tensor_converter`` to handle mismatches between HF safetensor layout and modeling layout (e.g. MoE per-expert keys -> fused format). Implementations consume one tensor at a time and can choose to: - emit a converted tensor immediately, or - return ``None`` to keep accumulating internal state until ready. """ def can_handle(self, name: str) -> bool: """Whether this converter should consume the incoming checkpoint key.""" ... def convert(self, name: str, tensor: "torch.Tensor") -> Optional["ConvertedCheckpointTensor"]: """Consume a tensor and optionally emit a converted result. Returns ``None`` when still accumulating (e.g. collecting per-expert tensors). """ ... def finalize(self) -> List["ConvertedCheckpointTensor"]: """Flush remaining buffered tensors after all shards are consumed. Called after all checkpoint shards have been iterated. Implementations should warn about any unexpected unflushed state. """ ... def checkpoint_row_counts(self) -> Dict[str, Tuple[int, int]]: """Optionally map weight FQNs to (checkpoint rows, padded runtime rows). Omit this method or return an empty dict when no row cropping is needed. The checkpoint planners consume this metadata without importing model code. Padding must be semantically inert; optimizer tensors keep runtime shapes. """ ... def is_dim0_zero_pad(self, name: str) -> bool: """Optional streaming capability: whether this converter's *only* transform for ``name`` is appending trailing zero rows on dim-0 (no fusion/reshape/dtype change). Zero-padding dim-0 commutes with a ``Shard(0)`` split, so a per-rank dim-0 streaming loader (:func:`load_model_weights_ep_sharded`) can read a rank's real-row slice straight from the checkpoint and zero-fill any tail past the checkpoint's real row count -- never materializing the whole tensor. A converter that fuses or otherwise needs the whole tensor set must return ``False`` (and its ``finalize`` may be non-empty). Implementing this method is optional; the loader treats a missing method as ``False``. CAUTION: only declare this for tensors whose padded rows are *semantically inert*, i.e. never read at runtime -- e.g. a vocab/embedding table padded past the real vocab (out-of-range ids are never looked up, so a zero row has no effect). It is NOT valid for MoE expert weights: an expert's dim-0 is the expert index, and the router selects over ALL rows via top-k. A zero-padded "expert" is an active, routable unit (its zero-padded router row yields a finite logit=0 that can win top-k), so a token routed to it silently gets a zeroed contribution -> wrong output. VeOmni EP therefore *requires* ``num_experts % ep == 0`` (the fused MoE kernels assert it) rather than padding experts; declaring this for experts would silently corrupt results. """ ... def dim0_rowwise_companion(self, name: str) -> Optional[str]: """Optional streaming capability: the checkpoint key ``name`` is converted together with, row by row -- or ``None``. Returning a key declares that row ``i`` of the converted ``name`` depends only on row ``i`` of ``name`` and of that companion (e.g. fp8 table rows and their per-row block scales, dequantized to bf16). Such a transform commutes with a ``Shard(0)`` split, so a per-rank streaming loader reads the same real-row slice of both keys, hands them to :meth:`convert_rows`, and zero-fills any rows past the checkpoint's. That loader then skips the companion's own key; a whole-tensor loader hands both keys to :meth:`convert`, so it must pair them there too. A key outside every ExtraParallel plan is read whole, with its whole companion. The loader asks for every key, claimed by :meth:`can_handle` or not, and only uses the companion when the checkpoint holds it; without it the key falls back to :meth:`is_dim0_zero_pad`. Implementing this method is optional and a missing method means ``None``. """ ... def convert_rows(self, name: str, rows: "torch.Tensor", companion_rows: "torch.Tensor") -> "torch.Tensor": """Convert matching row slices of ``name`` and its :meth:`dim0_rowwise_companion`.""" ... def should_skip_without_loading(self, name: str) -> bool: """Optional streaming capability: whether ``name`` can be discarded without materializing its checkpoint tensor. This is intended for checkpoint-only subtrees that the live model does not construct (for example an explicitly unsupported auxiliary head, or a sibling module's weights in a shared checkpoint). Every loader then calls :meth:`record_skip_without_loading` instead of reading the tensor and calling :meth:`convert`. Implementing this method is optional and a missing method means ``False``. """ ... def record_skip_without_loading(self, name: str) -> None: """Optional notification after a loader skipped ``name``. Converters can use this to retain their usual finalize-time accounting without forcing the tensor to be read. Implementing it is optional. """ ... def fused_expert_target(self, name: str) -> Optional[Tuple[str, int]]: """Optional streaming capability: ``(fused_name, expert_index)`` when ``name`` is one expert's tensor that this converter stacks into row ``expert_index`` (dim-0) of the fused parameter ``fused_name``; ``None`` for any other key. A per-rank dim-0 streaming loader uses it to read only the experts in its own ``Shard(0)`` range. Must be implemented together with :meth:`for_expert_range`; a missing method means the converter cannot be streamed. """ ... def for_expert_range(self, start: int, num_local: int) -> "CheckpointTensorConverter": """Optional streaming capability: a fresh converter that accepts only experts ``[start, start + num_local)`` and emits fused tensors of ``num_local`` rows, the rank-local ``Shard(0)`` slice of what this converter emits for all experts. """ ... def crop_hf_export_tensor(self, name: str, tensor: "torch.Tensor") -> "torch.Tensor": """Optional export hook: crop runtime dim-0 padding from a full unsharded tensor. ``name`` is the unprefixed weight FQN on the underlying model and ``tensor`` is the full unsharded matrix. Implementing this method is optional; a missing method leaves exported tensors unchanged. """ ... def checkpoint_converter_is_dim0_zero_pad( converter: Optional["CheckpointTensorConverter"], name: str, ) -> bool: """Safely query the optional :meth:`CheckpointTensorConverter.is_dim0_zero_pad`. Returns ``True`` only when *converter* both claims ``name`` (``can_handle``) and declares its transform is a pure dim-0 zero-pad. Any converter lacking the optional method is treated as not stream-safe (``False``). """ if converter is None or not converter.can_handle(name): return False fn = getattr(converter, "is_dim0_zero_pad", None) return bool(fn(name)) if callable(fn) else False def checkpoint_converter_dim0_rowwise_companion( converter: Optional["CheckpointTensorConverter"], name: str, ) -> Optional[str]: """Safely query the optional :meth:`CheckpointTensorConverter.dim0_rowwise_companion`. Not gated on ``can_handle``: a converter may claim a weight only by its content (``can_handle_tensor``), and the name alone is all a streaming loader has before reading. """ if converter is None: return None fn = getattr(converter, "dim0_rowwise_companion", None) return fn(name) if callable(fn) else None def checkpoint_converter_should_skip_without_loading( converter: Optional["CheckpointTensorConverter"], name: str, ) -> bool: """Whether a loader may discard ``name`` before reading it.""" if converter is None or not converter.can_handle(name): return False fn = getattr(converter, "should_skip_without_loading", None) return bool(fn(name)) if callable(fn) else False def checkpoint_converter_record_skip_without_loading( converter: Optional["CheckpointTensorConverter"], name: str, ) -> None: """Notify a converter that a loader skipped a tensor without reading it.""" if converter is None: return fn = getattr(converter, "record_skip_without_loading", None) if callable(fn): fn(name) def checkpoint_converter_supports_expert_streaming( converter: Optional["CheckpointTensorConverter"], ) -> bool: """Whether *converter* implements both per-expert streaming capabilities.""" if converter is None: return False return callable(getattr(converter, "fused_expert_target", None)) and callable( getattr(converter, "for_expert_range", None) ) def checkpoint_converter_fused_expert_target( converter: Optional["CheckpointTensorConverter"], name: str, ) -> Optional[Tuple[str, int]]: """Safely query the optional :meth:`CheckpointTensorConverter.fused_expert_target`. ``None`` unless *converter* claims ``name`` and implements both expert-streaming capabilities (``fused_expert_target`` and ``for_expert_range``). """ if ( converter is None or not converter.can_handle(name) or not checkpoint_converter_supports_expert_streaming(converter) ): return None return converter.fused_expert_target(name) def get_checkpoint_tensor_converter( model: Union["nn.Module", "PreTrainedModel"], ) -> Optional["CheckpointTensorConverter"]: """Return the checkpoint tensor converter registered on *model*, or ``None``.""" while isinstance(getattr(model, "module", None), nn.Module): model = model.module factory = getattr(model, "_create_checkpoint_tensor_converter", None) if factory is None: return None if not callable(factory): logger.warning_rank0("Ignore invalid `_create_checkpoint_tensor_converter`: not callable.") return None converter = factory(model) if converter is None: return None if not hasattr(converter, "can_handle") or not hasattr(converter, "convert"): logger.warning_rank0("Ignore invalid checkpoint tensor converter: missing can_handle/convert.") return None return converter FqnToIndexMappingConverter = Callable[[Dict[str, int]], Dict[str, int]] def shard_index_from_filename(filename: str) -> int: """Parse shard index from ``model-00003-of-00014.safetensors`` style names.""" return int(filename.split("-")[1]) def parse_fqn_to_index_mapping_from_json(safetensor_idx_path: str) -> Dict[str, int]: """Load ``weight_map`` from a HuggingFace ``model.safetensors.index.json`` file.""" with open(safetensor_idx_path) as f: weight_map = json.load(f)["weight_map"] return {fqn: shard_index_from_filename(filename) for fqn, filename in weight_map.items()} def _unwrap_model_for_fqn_mapping( model: Union["nn.Module", "PreTrainedModel"], ) -> Union["nn.Module", "PreTrainedModel"]: """Unwrap PEFT wrappers so class-level converters registered on the base model are found.""" if hasattr(model, "get_base_model"): return model.get_base_model() return model def get_fqn_to_index_mapping_converter( model: Union["nn.Module", "PreTrainedModel"], ) -> Optional[FqnToIndexMappingConverter]: """Return ``_convert_fqn_to_index_mapping`` registered on the model class, if any.""" model = _unwrap_model_for_fqn_mapping(model) for model_cls in type(model).__mro__: converter = getattr(model_cls, "_convert_fqn_to_index_mapping", None) if converter is not None and callable(converter): return converter return None def maybe_convert_fqn_to_index_mapping( fqn_to_index_mapping: Optional[Dict[str, int]], model: Optional[Union["nn.Module", "PreTrainedModel"]], ) -> Optional[Dict[str, int]]: """Convert HF index keys to match the live model's parameter names when needed.""" if not fqn_to_index_mapping or model is None: return fqn_to_index_mapping converter = get_fqn_to_index_mapping_converter(model) if converter is None: return fqn_to_index_mapping original_size = len(fqn_to_index_mapping) try: params = inspect.signature(converter).parameters accepts_model = "model" in params or any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values()) except (TypeError, ValueError): accepts_model = False converted = converter(fqn_to_index_mapping, model=model) if accepts_model else converter(fqn_to_index_mapping) if len(converted) != original_size: logger.info_rank0( f"Converted fqn_to_index_mapping for {type(model).__name__} ({original_size} -> {len(converted)} entries)." ) return converted def prepare_fqn_to_index_mapping_for_model( model: Union["nn.Module", "PreTrainedModel"], fqn_to_index_mapping: Optional[Dict[str, int]], ) -> Optional[Dict[str, int]]: """Convert and cache ``fqn_to_index_mapping`` on *model* for later HF export.""" prepared = maybe_convert_fqn_to_index_mapping(fqn_to_index_mapping, model) if prepared is not None: model._veomni_prepared_fqn_to_index_mapping = prepared model._veomni_fqn_to_index_mapping = fqn_to_index_mapping return prepared def resolve_fqn_to_index_mapping_for_save( model: Optional[Union["nn.Module", "PreTrainedModel"]], fqn_to_index_mapping: Optional[Dict[str, int]], ) -> Optional[Dict[str, int]]: """Resolve mapping for HF safetensor save: use cache from load, else convert now.""" if model is not None: cached = getattr(model, "_veomni_prepared_fqn_to_index_mapping", None) if cached is not None: return cached return maybe_convert_fqn_to_index_mapping(fqn_to_index_mapping, model) def maybe_convert_checkpoint_tensor( name: str, tensor: "torch.Tensor", converter: Optional["CheckpointTensorConverter"], ) -> Optional["ConvertedCheckpointTensor"]: """Apply converter if applicable, otherwise pass through. Returns: ``ConvertedCheckpointTensor`` if tensor is ready for dispatch (pass-through or converted). ``None`` if converter consumed the tensor but is still accumulating. """ if converter is None: return ConvertedCheckpointTensor(name=name, tensor=tensor) can_handle_tensor = getattr(converter, "can_handle_tensor", None) if callable(can_handle_tensor) and can_handle_tensor(name, tensor): return converter.convert(name, tensor) if not converter.can_handle(name): return ConvertedCheckpointTensor(name=name, tensor=tensor) return converter.convert(name, tensor) def _map_moe_params_common(name, tensor, ep_rank): num_experts_per_rank = tensor.size(0) for i in range(num_experts_per_rank): idx = ep_rank * num_experts_per_rank + i new_key = name.replace("mlp.experts.", f"mlp.experts.{idx}.") + ".weight" yield new_key, tensor[i].to(tensor.device, non_blocking=True) def split_moe_params(name, tensor, ep_rank=0): """Split a fused MoE expert tensor (``gate_up_proj`` or ``down_proj``) into per-expert ``(key, tensor)`` pairs.""" if "gate_up_proj" in name: gate, up = tensor.chunk(2, dim=1) params = { name.replace("gate_up_proj", "gate_proj"): gate, name.replace("gate_up_proj", "up_proj"): up, } else: params = {name: tensor} for key, value in params.items(): yield from _map_moe_params_common(key, value, ep_rank) _process_moe_params = split_moe_params def export_weights( model: torch.nn.Module, *, skip_frozen_ple: bool = False, ) -> Generator[tuple[str, torch.Tensor], None, None]: """ Export master weights from fully_sharded model, fused MoE weights are split into per-expert weights. Args: model: The fully_sharded model to export the master weights from. skip_frozen_ple: Omit frozen Qwen4-Exp PLE n-gram tables before unsharding ``DTensor`` shards. Disabled by default so checkpoint exports remain complete. Returns: A generator of tuples of the form (name, tensor). """ from veomni.models.frozen_ple import is_ple_table ps = parallel_state.get_parallel_state() while isinstance(getattr(model, "module", None), torch.nn.Module): next_model = model.module if next_model is model: break model = next_model params = model.state_dict() frozen_ple_names = ( {name for name, param in model.named_parameters() if is_ple_table(name) and not param.requires_grad} if skip_frozen_ple else set() ) converter = get_checkpoint_tensor_converter(model) crop_fn = getattr(converter, "crop_hf_export_tensor", None) if converter is not None else None device = None for name, param in params.items(): if name in frozen_ple_names: continue # With ``CPUOffloadPolicy`` the sharded DTensor local shard lives on CPU, so an # unstaged ``full_tensor()`` all-gathers over gloo and hands CPU tensors to the # consumers (EP broadcast, quantization kernels), which require device tensors. if isinstance(param, DTensor): if device is None: device_type = get_device_type() device = torch.device(device_type, get_device_id()) if device_type != "cpu" else torch.device("cpu") unsharded_tensor = param.to(device, non_blocking=True).full_tensor() else: unsharded_tensor = param is_expert_layer = "mlp.experts." in name is_proj = any(p in name for p in ["down_proj", "gate_proj", "up_proj", "gate_up_proj"]) if is_expert_layer and is_proj and ps.ep_enabled: ep_rank, ep_size = ps.ep_rank, ps.ep_size buffer = torch.empty_like(unsharded_tensor) # [num_experts/ep_size, H, I] for src_ep_rank in range(ep_size): tensor = unsharded_tensor if src_ep_rank == ep_rank else buffer torch.distributed.broadcast(tensor, group_src=src_ep_rank, group=ps.ep_group) yield from split_moe_params(name, tensor, ep_rank=src_ep_rank) else: if is_expert_layer: yield from split_moe_params(name, unsharded_tensor, ep_rank=0) else: if callable(crop_fn): unsharded_tensor = crop_fn(name, unsharded_tensor) yield name, unsharded_tensor