-
Notifications
You must be signed in to change notification settings - Fork 46
Stream safetensors checkpoints into models #411
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
gtong-nv
wants to merge
4
commits into
main
Choose a base branch
from
dev/gtong/stream-checkpoint
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,113 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| # | ||
| # 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 loading behavior tests.""" | ||
|
|
||
| import importlib | ||
| import json | ||
|
|
||
| import pytest | ||
| import torch | ||
| from safetensors.torch import save_file as save_safetensors_file | ||
|
|
||
| pytestmark = pytest.mark.ci_cpu | ||
|
|
||
|
|
||
| def test_local_safetensors_uses_file_backed_loader(monkeypatch, tmp_path) -> None: | ||
| """Load local safetensors without materializing the file as bytes.""" | ||
| checkpoint_load = importlib.import_module("flashdreams.core.checkpoint.load") | ||
| checkpoint_path = tmp_path / "weights.safetensors" | ||
| expected = {"weight": torch.ones(2)} | ||
| calls: list[tuple[str, str]] = [] | ||
|
|
||
| def fake_load_file(path: str, *, device: str) -> dict[str, torch.Tensor]: | ||
| calls.append((path, device)) | ||
| return expected | ||
|
|
||
| def reject_bytes_load(_data: bytes) -> dict[str, torch.Tensor]: | ||
| pytest.fail("safetensors checkpoints must use the file-backed loader") | ||
|
|
||
| monkeypatch.setattr(checkpoint_load, "load_safetensors_file", fake_load_file) | ||
| monkeypatch.setattr(checkpoint_load, "load_safetensors", reject_bytes_load) | ||
|
|
||
| actual = checkpoint_load.load_single_checkpoint( | ||
| str(checkpoint_path), map_location=torch.device("cpu") | ||
| ) | ||
|
|
||
| assert actual is expected | ||
| assert calls == [(str(checkpoint_path), "cpu")] | ||
|
|
||
|
|
||
| def test_safetensors_model_load_streams_without_full_state_dict( | ||
| monkeypatch, tmp_path | ||
| ) -> None: | ||
| """Stream safetensors tensors directly into a materialized model.""" | ||
| checkpoint_load = importlib.import_module("flashdreams.core.checkpoint.load") | ||
| checkpoint_path = tmp_path / "weights.safetensors" | ||
| expected = torch.arange(6, dtype=torch.float32).view(2, 3) | ||
| save_safetensors_file({"weight": expected}, checkpoint_path) | ||
| model = torch.nn.Linear(3, 2, bias=False) | ||
|
|
||
| def reject_full_load(*_args, **_kwargs) -> None: | ||
| pytest.fail("model loads must not materialize the complete state dict") | ||
|
|
||
| monkeypatch.setattr(checkpoint_load, "load_safetensors_file", reject_full_load) | ||
|
|
||
| actual = checkpoint_load.load_checkpoint(str(checkpoint_path), model=model) | ||
|
|
||
| assert actual is model | ||
| torch.testing.assert_close(model.weight, expected) | ||
|
|
||
|
|
||
| def test_sharded_safetensors_model_load_streams_without_merged_state_dict( | ||
| monkeypatch, tmp_path | ||
| ) -> None: | ||
| """Stream indexed safetensors shards into a model without merging first.""" | ||
| checkpoint_load = importlib.import_module("flashdreams.core.checkpoint.load") | ||
| shard_a = tmp_path / "model-00001-of-00002.safetensors" | ||
| shard_b = tmp_path / "model-00002-of-00002.safetensors" | ||
| index_path = tmp_path / "model.safetensors.index.json" | ||
| expected_weight = torch.arange(6, dtype=torch.float32).view(2, 3) | ||
| expected_bias = torch.tensor([3.0, 4.0], dtype=torch.float32) | ||
| save_safetensors_file({"weight": expected_weight}, shard_a) | ||
| save_safetensors_file({"bias": expected_bias}, shard_b) | ||
| index_path.write_text( | ||
| json.dumps( | ||
| { | ||
| "metadata": {"total_size": 0}, | ||
| "weight_map": { | ||
| "weight": shard_a.name, | ||
| "bias": shard_b.name, | ||
| }, | ||
| } | ||
| ), | ||
| encoding="utf-8", | ||
| ) | ||
| model = torch.nn.Linear(3, 2) | ||
|
|
||
| def reject_merge(*_args, **_kwargs) -> None: | ||
| pytest.fail("sharded model loads must not materialize a merged state dict") | ||
|
|
||
| monkeypatch.setattr( | ||
| checkpoint_load, | ||
| "_load_sharded_safetensors_index_checkpoint", | ||
| reject_merge, | ||
| ) | ||
|
|
||
| actual = checkpoint_load.load_checkpoint(str(index_path), model=model) | ||
|
|
||
| assert actual is model | ||
| torch.testing.assert_close(model.weight, expected_weight) | ||
| torch.testing.assert_close(model.bias, expected_bias) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.