-
Notifications
You must be signed in to change notification settings - Fork 43
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -157,6 +157,9 @@ class Wan21TransformerConfig(TransformerConfig): | |
| """Pre-load state-dict remap (e.g. Self-Forcing's | ||
| ``generator_ema.model.…`` layout).""" | ||
|
|
||
| stream_checkpoint: bool = False | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If |
||
| """Load cached safetensors directly into the model with bounded host residency.""" | ||
|
|
||
| batch_shape: tuple[int, ...] = (1,) | ||
| """Batch dims of the latent (excluding the L, D dims).""" | ||
|
|
||
|
|
@@ -279,13 +282,24 @@ def __init__(self, config: Wan21TransformerConfig) -> None: | |
| self.network.set_context_parallel_group(cp_group=self._cp_group) | ||
|
|
||
| if config.checkpoint_path is not None: | ||
| state_dict = load_checkpoint( | ||
| config.checkpoint_path, | ||
| checkpoint_min_free_gb=config.checkpoint_min_free_gb, | ||
| ) | ||
| if config.state_dict_transform is not None: | ||
| state_dict = config.state_dict_transform(state_dict) | ||
| self.network.load_state_dict(state_dict) | ||
| if config.stream_checkpoint: | ||
| if config.state_dict_transform is not None: | ||
| raise ValueError( | ||
| "stream_checkpoint does not support state_dict_transform" | ||
| ) | ||
| load_checkpoint( | ||
| config.checkpoint_path, | ||
| model=self.network, | ||
| checkpoint_min_free_gb=config.checkpoint_min_free_gb, | ||
| ) | ||
| else: | ||
| state_dict = load_checkpoint( | ||
| config.checkpoint_path, | ||
| checkpoint_min_free_gb=config.checkpoint_min_free_gb, | ||
| ) | ||
| if config.state_dict_transform is not None: | ||
| state_dict = config.state_dict_transform(state_dict) | ||
| self.network.load_state_dict(state_dict) | ||
| self.network.update_parameters_after_loading_checkpoint() | ||
|
|
||
| if config.compile_network: | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| # 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 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) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -76,6 +76,7 @@ | |
| in_dim=16 + 4 + 16, | ||
| ), | ||
| checkpoint_path=LINGBOT_WORLD_V1_CHECKPOINT_PATH, | ||
| stream_checkpoint=True, | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We likely want this config option for all demos. Unsure if we should make this change now or if this change will be something we implement during a larger refactor.
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. For smaller model or system with large RAM, this option is not helpful and will add some overhead when loading. |
||
| # Single-rollout layout: tensors flow through the stack as | ||
| # ``[T, C, H, W]`` (or ``[T, ...]``) with no leading batch/view dim. | ||
| batch_shape=(), | ||
|
|
@@ -136,7 +137,8 @@ | |
| ) | ||
|
|
||
| # LingBot-World v2 uses the same architecture and runtime as v1. The | ||
| # transformer checkpoint is the only model-level substitution. | ||
| # transformer checkpoint is the only model-level substitution; it inherits | ||
| # the bounded checkpoint loader from the v1 base config. | ||
| PIPELINE_LINGBOT_WORLD_V2_14B_CAUSAL_FAST = derive_config( | ||
| PIPELINE_LINGBOT_WORLD_FAST, | ||
| name="lingbot-world-v2-14b-causal-fast", | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When an installation resolves safetensors 0.4 through 0.7 as permitted by the package metadata, this call passes an unsupported
backendkeyword, causing model initialization to raiseTypeErrorfor streamed LingBot and other direct-to-model checkpoint loads.Knowledge Base Used: Core Engine (
flashdreams/flashdreams/core/)