Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions tests/model_executor/model_loader/test_sharded_state_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,62 @@ def _capture(tensors, path, **kwargs):
]


@pytest.mark.parametrize(
"pattern,num_params",
[
("model-rank-{rank}.safetensors", 2),
("model-rank-{rank}-part-{{part}}.safetensors", 2),
("model-rank-{rank}-part-{part!s:.1}.safetensors", 11),
],
)
def test_save_model_rejects_colliding_parts(monkeypatch, tmp_path, pattern, num_params):
"""Part filenames must be distinct before any checkpoint is overwritten."""
_mock_pp_group(monkeypatch, 1)
model = torch.nn.ParameterList(
[torch.nn.Parameter(torch.tensor([float(i)])) for i in range(num_params)]
)
filename = ShardedStateLoader._render_default_pattern(pattern, part=0)
existing = tmp_path / filename
existing.write_bytes(b"existing checkpoint")

with pytest.raises(ValueError, match="distinct.*part"):
ShardedStateLoader.save_model(model, str(tmp_path), pattern=pattern, max_size=4)

assert existing.read_bytes() == b"existing checkpoint"
assert list(tmp_path.iterdir()) == [existing]


@pytest.mark.parametrize(
"pattern,max_size",
[
(None, 4),
("custom-rank-{rank}-part-{part}.safetensors", 4),
("model-rank-{rank}.safetensors", None),
("model-rank-{rank}.safetensors", 8),
],
)
def test_save_model_cpu_roundtrip(monkeypatch, tmp_path, pattern, max_size):
"""Split and single-file checkpoints preserve every tensor exactly."""
from vllm.config.load import LoadConfig

_mock_pp_group(monkeypatch, 1)
model = torch.nn.Linear(1, 1)
ShardedStateLoader.save_model(
model, str(tmp_path), pattern=pattern, max_size=max_size
)
restored = torch.nn.Linear(1, 1)
loader = ShardedStateLoader(
LoadConfig(
load_format="sharded_state", model_loader_extra_config={"pattern": pattern}
)
)
loader.load_weights(
restored, SimpleNamespace(model=str(tmp_path), model_weights=None)
)
for key, tensor in model.state_dict().items():
torch.testing.assert_close(restored.state_dict()[key], tensor, rtol=0, atol=0)


def test_save_model_rejects_bad_pattern_before_overwrite(monkeypatch, tmp_path):
"""An unsafe pattern is rejected before any shard file is written."""
_mock_pp_group(monkeypatch, 2, pp_rank=1, tp_rank=0, tp_world_size=2)
Expand Down
26 changes: 15 additions & 11 deletions vllm/model_executor/model_loader/sharded_state_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,29 +274,33 @@ def save_model(
) -> None:
from safetensors.torch import save_file

part_idx = 0
total_size = 0
state_dict = ShardedStateLoader._filter_subtensors(model.state_dict())
state_dict_parts: list[dict[str, torch.Tensor]] = []
state_dict_part: dict[str, torch.Tensor] = {}
for key, tensor in state_dict.items():
param_size = tensor.nelement() * tensor.element_size()
if max_size is not None and total_size + param_size > max_size:
filename = ShardedStateLoader._render_default_pattern(
pattern, part=part_idx
)
save_file(
state_dict_part,
os.path.join(path, filename),
)
part_idx += 1
state_dict_parts.append(state_dict_part)
total_size = 0
state_dict_part = {}
state_dict_part[key] = tensor
total_size += param_size
if len(state_dict_part) > 0:
filename = ShardedStateLoader._render_default_pattern(
pattern, part=part_idx
state_dict_parts.append(state_dict_part)

filenames = [
ShardedStateLoader._render_default_pattern(pattern, part=part_idx)
for part_idx in range(len(state_dict_parts))
]
if len(set(filenames)) != len(filenames):
raise ValueError(
f"Pattern {pattern!r} must produce a distinct filename for each "
"checkpoint part. Include an unescaped {part} field without "
"truncating its value."
)

for filename, state_dict_part in zip(filenames, state_dict_parts):
save_file(
state_dict_part,
os.path.join(path, filename),
Expand Down
Loading