diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 38b6907b04d4..4f1de0999b77 100755 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -86,6 +86,7 @@ Changelog - Detect the first-projection quantization format and block size when restoring older fused-expert wrappers whose quantizers use the legacy ``gate_up_proj_weight_quantizers`` name. - GPT-OSS expert forwards now use replacement quantizers after configuration and clear cached quantized weights and execution flags when a forward fails. +- ``export_hf_checkpoint`` of a model saved with ``save_pretrained`` first no longer fails with ``Invalid device string: 'bfloat16'``. When every rank of a ``torch.distributed`` run exports a replicated model, rank 0 now writes the checkpoint, as ``save_pretrained`` does, and the other ranks no longer fail. *ONNX* diff --git a/modelopt/torch/export/unified_export_hf.py b/modelopt/torch/export/unified_export_hf.py index bcc6aecea1f8..18ed85fba160 100644 --- a/modelopt/torch/export/unified_export_hf.py +++ b/modelopt/torch/export/unified_export_hf.py @@ -113,6 +113,7 @@ is_fsdp2_model, recorded_distribution_plan, ) +from modelopt.torch.utils.distributed import rank as dist_rank from modelopt.torch.utils.fsdp2_utils import fsdp2_root_unsharded from modelopt.torch.utils.perf import maybe_clear_cuda_cache @@ -932,6 +933,11 @@ def _dispatch_export_handler(name: str, sub_module: nn.Module, ctx: ExportContex def _resolve_export_dtype(model: nn.Module, dtype: torch.dtype | None) -> torch.dtype: """Return the export dtype, defaulting to the model's own and warning on a mismatch.""" configured_dtype = getattr(model.config, "dtype", None) + # transformers' save_pretrained rewrites config.dtype in place as a string, e.g. "bfloat16". + if isinstance(configured_dtype, str): + configured_dtype = getattr(torch, configured_dtype.removeprefix("torch."), None) + if not isinstance(configured_dtype, torch.dtype): + configured_dtype = None if dtype is None: if configured_dtype is not None: return configured_dtype @@ -2237,7 +2243,10 @@ def export_hf_checkpoint( Under ``torch.distributed`` (e.g. FSDP2), all ranks participate in the collective state-dict gather inside ``_export_transformers_checkpoint``; - only rank 0 writes files. A final barrier syncs the other ranks. + only rank 0 writes files. A final barrier syncs the other ranks. A model + every rank holds whole (neither sharded nor offloaded) is written by rank 0 + alone, as ``save_pretrained`` does, and the other ranks return without + waiting for it. Args: model: The full torch model to export. The actual quantized model may be a submodule. @@ -2389,8 +2398,8 @@ def carried_over_names() -> list[str]: # The rank used to gate the single-writer steps below. It must be the real rank whenever the # checkpoint is written cooperatively -- under expert parallelism every process would otherwise # read 0 here, all of them would rewrite config.json at once, and one would truncate the file - # another was reading. A non-sharded export does write the whole checkpoint from every process, - # which is what the 0 is for. + # another was reading. The save_pretrained path below sets it to the real rank as well; the + # offloaded streaming path writes the whole checkpoint from every process. rank = torch.distributed.get_rank() if (is_fsdp2_sharded or is_ep_sharded) else 0 # Offloaded models take the streaming path: it materializes one layer at a time and # writes each straight to a shard file, so peak memory is one layer plus one shard @@ -2534,16 +2543,21 @@ def carried_over_names() -> list[str]: # above replaces it): it can't handle quantized state dicts (RuntimeError on 0-d scalar # scale tensors). Patch both the source and importing module since modeling_utils does # `from core_model_loading import revert_weight_conversion`. - _patches = _patch_revert_weight_conversion() - try: - model.save_pretrained( - export_dir, - state_dict=export_state_dict, - save_modelopt_state=save_modelopt_state, - max_shard_size=max_shard_size, - ) - finally: - _unpatch_revert_weight_conversion(_patches) + # Every rank holds the whole model, so rank 0 alone writes it, as save_pretrained does + # under torch.distributed (ModelOpt's save_pretrained hook would also write + # modelopt_state.pth on every rank). + rank = dist_rank() + if rank == 0: + _patches = _patch_revert_weight_conversion() + try: + model.save_pretrained( + export_dir, + state_dict=export_state_dict, + save_modelopt_state=save_modelopt_state, + max_shard_size=max_shard_size, + ) + finally: + _unpatch_revert_weight_conversion(_patches) if rank == 0: _write_hf_export_config(model, hf_quant_config, export_dir) diff --git a/tests/gpu/torch/export/test_distributed_hf_export.py b/tests/gpu/torch/export/test_distributed_hf_export.py index 844a46dd98e2..471995994c98 100644 --- a/tests/gpu/torch/export/test_distributed_hf_export.py +++ b/tests/gpu/torch/export/test_distributed_hf_export.py @@ -38,6 +38,7 @@ Run with >=2 GPUs so the expert axis and the FSDP2 shard axis are both actually split. """ +import copy import json import os from functools import partial @@ -46,8 +47,13 @@ import pytest import torch -from _test_utils.torch.transformers_models import create_tiny_qwen3_dir, create_tiny_qwen3_moe_dir +from _test_utils.torch.transformers_models import ( + create_tiny_qwen3_dir, + create_tiny_qwen3_moe_dir, + get_tiny_llama, +) +import modelopt.torch.opt as mto import modelopt.torch.quantization as mtq from modelopt.torch.export.unified_export_hf import export_hf_checkpoint from modelopt.torch.quantization.utils import patch_fsdp_mp_dtypes @@ -278,3 +284,39 @@ def test_fsdp2_distributed_export_is_complete(dist_workers, tmp_path, moe, quant json.loads((export_dir / "hf_quant_config.json").read_text())["quantization"]["quant_algo"] == algo ) + + +def _save_ptq_and_export(rank, size, *, root): + """Every rank saves, quantizes and exports its own replica of a model, as a data-parallel job.""" + # As in the main test process: its save_pretrained hook writes modelopt_state.pth. + mto.enable_huggingface_checkpointing() + model = get_tiny_llama().cuda() + # save_pretrained leaves config.dtype a string, "bfloat16". + model.save_pretrained(root / "src") + set_distribution_plan(model, DistributionPlan(size)) + quant_cfg = mtq.update_quant_cfg_with_kv_cache_quant( + copy.deepcopy(mtq.FP8_DEFAULT_CFG), copy.deepcopy(mtq.FP8_KV_CFG["quant_cfg"]) + ) + input_ids = torch.randint(0, model.config.vocab_size, (2, 8), device="cuda") + mtq.quantize(model, quant_cfg, lambda m: m(input_ids)) + # A directory per rank, so a rank that edits a config.json it never wrote fails every time. + export_dir = root / f"export_rank{rank}" + export_hf_checkpoint(model, export_dir=export_dir, save_modelopt_state=True) + if rank > 0: + assert not any(export_dir.iterdir()), sorted(p.name for p in export_dir.iterdir()) + + +def test_replicated_export_after_save_pretrained(dist_workers, tmp_path): + if torch.cuda.device_count() < 2: + pytest.skip("needs >=2 GPUs") + dist_workers.run(partial(_save_ptq_and_export, root=tmp_path)) + + # save_pretrained writes on rank 0 only, and so does the export. + export_dir = tmp_path / "export_rank0" + quantization = json.loads((export_dir / "hf_quant_config.json").read_text())["quantization"] + assert quantization["quant_algo"] == "FP8" + assert quantization["kv_cache_quant_algo"] == "FP8" + assert "quantization_config" in json.loads((export_dir / "config.json").read_text()) + exported = _safetensors_meta(export_dir) + assert exported["model.layers.0.mlp.down_proj.weight"][0] == "F8_E4M3" + assert (export_dir / "modelopt_state.pth").exists() diff --git a/tests/unit/torch/export/test_unified_export_hf.py b/tests/unit/torch/export/test_unified_export_hf.py index 56bda79877e8..937847242a84 100644 --- a/tests/unit/torch/export/test_unified_export_hf.py +++ b/tests/unit/torch/export/test_unified_export_hf.py @@ -123,6 +123,9 @@ def test_language_model_preparation_fails_closed_on_competing_roots(): (torch.bfloat16, None, torch.bfloat16, 0), (torch.bfloat16, torch.bfloat16, torch.bfloat16, 0), (torch.bfloat16, torch.float16, torch.float16, 1), + # As transformers' save_pretrained leaves it. + ("bfloat16", None, torch.bfloat16, 0), + ("bfloat16", torch.float16, torch.float16, 1), ], ) def test_resolve_export_dtype(configured_dtype, dtype, expected_dtype, warning_count, recwarn):