Skip to content

Layerwise HF export silently ignores save_modelopt_state=True #3040

Closed

Description

@yingguo-trt

Describe the bug

In the layerwise HF export path introduced by #2303, export_hf_checkpoint(..., save_modelopt_state=True) returns successfully without producing modelopt_state.pth and without warning that this option was ignored.

The ordinary export-form warning does not explain the unsupported option. This can mislead callers into believing that the requested ModelOpt state was saved.

Steps/Code to reproduce bug

Use a CUDA-capable environment with ModelOpt and its HF dependencies installed. From a source checkout (the script uses the repository's existing tiny-Llama test fixture), save the script below as repro_layerwise_save_state.py and run:

python repro_layerwise_save_state.py \
  --source /path/to/Model-Optimizer \
  --output /path/to/new-repro-output \
  --device cuda

The output directory must not already exist. The script creates a real two-layer Llama, calibrates it with FP8_DEFAULT_CFG and layerwise export enabled, then calls the public export API in two independent runs with the option set to False and True.

Reproduction script used for the CUDA experiment
"""Read-only source investigation; artifacts stay outside the repositories."""

import argparse
import copy
import importlib.metadata
import json
import subprocess
import sys
import warnings
from pathlib import Path

parser = argparse.ArgumentParser()
parser.add_argument("--source", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--device", choices=("cpu", "cuda"), required=True)
parser.add_argument("--source-commit", help="Commit recorded when source is a git archive")
args = parser.parse_args()
source = args.source.resolve()
sys.path.insert(0, str(source / "tests"))
sys.path.insert(0, str(source))

import torch
from _test_utils.torch.transformers_models import get_tiny_llama
from safetensors import safe_open

import modelopt.torch.opt as mto
import modelopt.torch.quantization as mtq
from modelopt.torch.export import export_hf_checkpoint
from modelopt.torch.export.layerwise_export import LAYERWISE_EXPORTER_ATTR

torch.set_num_threads(1)
mto.enable_huggingface_checkpointing()
args.output.mkdir(parents=True, exist_ok=False)
result = {
    "device": args.device,
    "source_commit": args.source_commit or subprocess.check_output(
        ["git", "-C", str(source), "rev-parse", "HEAD"], text=True
    ).strip(),
    "source_status": "git archive" if args.source_commit else subprocess.check_output(
        ["git", "-C", str(source), "status", "--porcelain"], text=True
    ).strip(),
    "modelopt_import": mtq.__file__,
    "versions": {
        name: importlib.metadata.version(name)
        for name in ("torch", "transformers", "nvidia-modelopt")
    },
    "runs": [],
}
for save_state in (False, True):
    run_dir = args.output / str(save_state).lower()
    export_dir = run_dir / "export"
    model = get_tiny_llama(num_hidden_layers=2).to(args.device).eval()
    model.config.architectures = ["LlamaForCausalLM"]
    torch.manual_seed(0)
    batches = [torch.randint(0, 32, (1, 16), device=args.device) for _ in range(2)]
    cfg = copy.deepcopy(mtq.FP8_DEFAULT_CFG)
    cfg["algorithm"] = {
        "method": "max",
        "layerwise": {
            "enable": True,
            "export_dir": str(export_dir),
            "checkpoint_dir": str(run_dir / "resume"),
            "calib_mutates_weights": False,
        },
    }

    def calibrate(module):
        for batch in batches:
            module(batch)

    with warnings.catch_warnings(record=True) as calibration_warnings:
        warnings.simplefilter("always")
        with torch.no_grad():
            mtq.quantize(model, cfg, calibrate)
    attached_before = getattr(model, LAYERWISE_EXPORTER_ATTR, None) is not None
    assert attached_before, "The real layerwise exporter was not attached"
    with warnings.catch_warnings(record=True) as export_warnings:
        warnings.simplefilter("always")
        export_hf_checkpoint(model, export_dir=export_dir, save_modelopt_state=save_state)
    required = ("model-tail.safetensors", "model.safetensors.index.json", "config.json")
    assert all((export_dir / name).is_file() for name in required)
    index = json.loads((export_dir / "model.safetensors.index.json").read_text())
    weight_map = index["weight_map"]
    assert weight_map
    for shard in set(weight_map.values()):
        with safe_open(str(export_dir / shard), framework="pt") as handle:
            keys = set(handle.keys())
        assert {key for key, value in weight_map.items() if value == shard} <= keys
    result["runs"].append(
        {
            "save_modelopt_state": save_state,
            "export_returned": True,
            "exporter_attached_before": attached_before,
            "exporter_attached_after": hasattr(model, LAYERWISE_EXPORTER_ATTR),
            "state_file_exists": (export_dir / "modelopt_state.pth").exists(),
            "export_files": sorted(path.name for path in export_dir.iterdir()),
            "index_entries": len(weight_map),
            "index_keys_resolve": True,
            "calibration_warnings": [str(item.message) for item in calibration_warnings],
            "export_warnings": [str(item.message) for item in export_warnings],
        }
    )
    del model
    print(json.dumps(result["runs"][-1], indent=2), flush=True)
summary = args.output / "evidence.json"
summary.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
print(f"Evidence: {summary}")

Observed behavior

save_modelopt_state Export returns modelopt_state.pth Export artifacts Index entries checked Unsupported-option warning
False Yes Absent 7 49 Absent
True Yes Absent 7 49 Absent

Both runs produced the layer shards, tail shard, index and config artifacts. All indexed keys were found in their referenced shards. The only export warning was that the converted in-memory model must not be used for inference.

Checkpoint reload, inference and numerical quality were not tested; this report does not claim that the deployment weights are corrupt.

Expected behavior

Do not silently ignore an explicitly requested option. If saving ModelOpt state is unsupported for layerwise export, emit an explicit unsupported-option warning, consistent with the existing streaming-offload export behavior, while preserving the completed checkpoint export.

This issue does not request implementing a new layerwise ModelOpt-state serialization format.

Source location

The layerwise branch calls exporter.finalize(...) and returns without checking save_modelopt_state:
unified_export_hf.py.

Related introduction: #2303.

System information

  • Execution: Linux, CUDA, B100; real calibration and export, not mocked.
  • Executed ModelOpt source: 5ff581d, based on upstream 378888145a223a03c99df4658449d92507da6177. The only delta was unrelated Diffusers option forwarding; the layerwise path was unchanged.
  • Package metadata reported nvidia-modelopt==0.48.0rc1, but imports used the source checkout above; this is not a claim that the released wheel was the executed code.
  • PyTorch: 2.13.0a0+9186a08b2c.nv26.7.59513937.
  • Transformers: 5.18.0.
  • Also inspected current upstream 0c4bf38e5bf6ffac10e7785e6fed0cd70abb5093: the same unchecked early return remains. That revision has not been GPU-rerun for this report.

Activity

  1. added
    bug
    on Oct 27, 2026
  2. added 2 commits that reference this issue on Oct 27, 2026
    839a78c
    7092db6
  3. self-assigned this
    on Nov 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions