-
Notifications
You must be signed in to change notification settings - Fork 368
fix incomplete mapping of safetensors in generated puzzletron checkpoint #1330
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
grzegorz-k-karch
wants to merge
12
commits into
main
Choose a base branch
from
gkarch/fix-incomplete-tensor-mapping
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.
+214
−2
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
f74ab04
fix incomplete mapping of safetensors in generated puzzletron checkpoint
grzegorz-k-karch 1e8e25a
moved imports to top of file
grzegorz-k-karch 84d68a3
📝 Add docstrings to `gkarch/fix-incomplete-tensor-mapping` (#1331)
coderabbitai[bot] f23bfa6
Merge branch 'main' into gkarch/fix-incomplete-tensor-mapping
grzegorz-k-karch ff2afe1
fix: CodeRabbit auto-fixes for PR #1330 (#1339)
coderabbitai[bot] f10fc53
new line at eof
grzegorz-k-karch 2136ab7
Update modelopt/torch/puzzletron/tools/checkpoint_utils_hf.py
grzegorz-k-karch 0006fd2
Merge branch 'main' into gkarch/fix-incomplete-tensor-mapping
grzegorz-k-karch 77b094d
fixed double condition line
grzegorz-k-karch 80a41ca
added test for save_checkpoint_from_shads
grzegorz-k-karch 830d258
formatting
grzegorz-k-karch 604ea3b
ruff feedback
grzegorz-k-karch 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
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
163 changes: 163 additions & 0 deletions
163
tests/gpu/torch/puzzletron/tools/test_save_ckpt_from_shards.py
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,163 @@ | ||||||||||||||||||||||||||||||||||||||
| # SPDX-FileCopyrightText: Copyright (c) 2024 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. | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| """Tests for save_checkpoint_from_shards in checkpoint_utils_hf.""" | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| import json | ||||||||||||||||||||||||||||||||||||||
| from functools import partial | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| import pytest | ||||||||||||||||||||||||||||||||||||||
| import torch | ||||||||||||||||||||||||||||||||||||||
| from _test_utils.torch.distributed.utils import spawn_multiprocess_job | ||||||||||||||||||||||||||||||||||||||
| from safetensors.torch import load_file as safe_load_file | ||||||||||||||||||||||||||||||||||||||
| from transformers import AutoModelForCausalLM, LlamaConfig | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| from modelopt.torch.puzzletron.anymodel.models.llama.llama_model_descriptor import ( | ||||||||||||||||||||||||||||||||||||||
| LlamaModelDescriptor, | ||||||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||||||
| from modelopt.torch.puzzletron.tools.checkpoint_utils_hf import ( | ||||||||||||||||||||||||||||||||||||||
| SAFE_WEIGHTS_INDEX_NAME, | ||||||||||||||||||||||||||||||||||||||
| SAFETENSORS_SUBBLOCKS_DIR_NAME, | ||||||||||||||||||||||||||||||||||||||
| save_checkpoint_from_shards, | ||||||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| TINY_LLAMA_CONFIG = { | ||||||||||||||||||||||||||||||||||||||
| "hidden_size": 32, | ||||||||||||||||||||||||||||||||||||||
| "intermediate_size": 64, | ||||||||||||||||||||||||||||||||||||||
| "num_hidden_layers": 2, | ||||||||||||||||||||||||||||||||||||||
| "num_attention_heads": 4, | ||||||||||||||||||||||||||||||||||||||
| "num_key_value_heads": 2, | ||||||||||||||||||||||||||||||||||||||
| "max_position_embeddings": 32, | ||||||||||||||||||||||||||||||||||||||
| "vocab_size": 32, | ||||||||||||||||||||||||||||||||||||||
| "tie_word_embeddings": False, | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| def _make_tiny_llama(**overrides) -> AutoModelForCausalLM: | ||||||||||||||||||||||||||||||||||||||
| cfg = {**TINY_LLAMA_CONFIG, **overrides} | ||||||||||||||||||||||||||||||||||||||
| return AutoModelForCausalLM.from_config(LlamaConfig(**cfg)) | ||||||||||||||||||||||||||||||||||||||
|
Comment on lines
+36
to
+50
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.
Suggested change
|
||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| class TestSaveCheckpointFromShardsSingleProcess: | ||||||||||||||||||||||||||||||||||||||
|
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. I think many of these tests can be combined into one to avoid creating and saving model again and again separately
kevalmorabia97 marked this conversation as resolved.
|
||||||||||||||||||||||||||||||||||||||
| """Tests that run without torch.distributed (world_size=1 path).""" | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| def test_creates_index_and_subblocks(self, tmp_path): | ||||||||||||||||||||||||||||||||||||||
| model = _make_tiny_llama() | ||||||||||||||||||||||||||||||||||||||
| save_checkpoint_from_shards(model, tmp_path, LlamaModelDescriptor) | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| index_path = tmp_path / SAFE_WEIGHTS_INDEX_NAME | ||||||||||||||||||||||||||||||||||||||
| assert index_path.exists(), "safetensors index file was not written" | ||||||||||||||||||||||||||||||||||||||
| index = json.loads(index_path.read_text()) | ||||||||||||||||||||||||||||||||||||||
| assert "weight_map" in index | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| subblocks_dir = tmp_path / SAFETENSORS_SUBBLOCKS_DIR_NAME | ||||||||||||||||||||||||||||||||||||||
| assert subblocks_dir.is_dir(), "subblocks directory was not created" | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| shard_files = list(subblocks_dir.glob("*.safetensors")) | ||||||||||||||||||||||||||||||||||||||
| assert len(shard_files) > 0, "no safetensors shard files were saved" | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| def test_weight_map_covers_all_state_dict_keys(self, tmp_path): | ||||||||||||||||||||||||||||||||||||||
| model = _make_tiny_llama() | ||||||||||||||||||||||||||||||||||||||
| expected_keys = set(model.state_dict().keys()) | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| save_checkpoint_from_shards(model, tmp_path, LlamaModelDescriptor) | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| index = json.loads((tmp_path / SAFE_WEIGHTS_INDEX_NAME).read_text()) | ||||||||||||||||||||||||||||||||||||||
| mapped_keys = set(index["weight_map"].keys()) | ||||||||||||||||||||||||||||||||||||||
| assert mapped_keys == expected_keys | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| def test_saved_weights_match_original(self, tmp_path): | ||||||||||||||||||||||||||||||||||||||
| model = _make_tiny_llama() | ||||||||||||||||||||||||||||||||||||||
| original_sd = {k: v.clone().cpu() for k, v in model.state_dict().items()} | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| save_checkpoint_from_shards(model, tmp_path, LlamaModelDescriptor) | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| reloaded_sd = {} | ||||||||||||||||||||||||||||||||||||||
| for shard in (tmp_path / SAFETENSORS_SUBBLOCKS_DIR_NAME).glob("*.safetensors"): | ||||||||||||||||||||||||||||||||||||||
| reloaded_sd.update(safe_load_file(str(shard))) | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| assert set(reloaded_sd.keys()) == set(original_sd.keys()) | ||||||||||||||||||||||||||||||||||||||
| for key in original_sd: | ||||||||||||||||||||||||||||||||||||||
| torch.testing.assert_close(reloaded_sd[key], original_sd[key]) | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| def test_config_json_saved(self, tmp_path): | ||||||||||||||||||||||||||||||||||||||
| model = _make_tiny_llama() | ||||||||||||||||||||||||||||||||||||||
| save_checkpoint_from_shards(model, tmp_path, LlamaModelDescriptor) | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| config_path = tmp_path / "config.json" | ||||||||||||||||||||||||||||||||||||||
| assert config_path.exists(), "config.json was not saved" | ||||||||||||||||||||||||||||||||||||||
| cfg = json.loads(config_path.read_text()) | ||||||||||||||||||||||||||||||||||||||
| assert cfg["num_hidden_layers"] == TINY_LLAMA_CONFIG["num_hidden_layers"] | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| def test_tie_word_embeddings_excluded(self, tmp_path): | ||||||||||||||||||||||||||||||||||||||
| model = _make_tiny_llama(tie_word_embeddings=True) | ||||||||||||||||||||||||||||||||||||||
| save_checkpoint_from_shards(model, tmp_path, LlamaModelDescriptor) | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| index = json.loads((tmp_path / SAFE_WEIGHTS_INDEX_NAME).read_text()) | ||||||||||||||||||||||||||||||||||||||
| assert "lm_head.weight" not in index["weight_map"] | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| reloaded_sd = {} | ||||||||||||||||||||||||||||||||||||||
| for shard in (tmp_path / SAFETENSORS_SUBBLOCKS_DIR_NAME).glob("*.safetensors"): | ||||||||||||||||||||||||||||||||||||||
| reloaded_sd.update(safe_load_file(str(shard))) | ||||||||||||||||||||||||||||||||||||||
| assert "lm_head.weight" not in reloaded_sd | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| def test_subblock_filenames_follow_descriptor_groups(self, tmp_path): | ||||||||||||||||||||||||||||||||||||||
| model = _make_tiny_llama() | ||||||||||||||||||||||||||||||||||||||
| save_checkpoint_from_shards(model, tmp_path, LlamaModelDescriptor) | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| index = json.loads((tmp_path / SAFE_WEIGHTS_INDEX_NAME).read_text()) | ||||||||||||||||||||||||||||||||||||||
| filenames = set(index["weight_map"].values()) | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| expected_substrings = {"embeddings", "lm_head", "block_0_ffn", "block_0_attention"} | ||||||||||||||||||||||||||||||||||||||
| for substr in expected_substrings: | ||||||||||||||||||||||||||||||||||||||
| assert any(substr in f for f in filenames), f"no shard filename contains '{substr}'" | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| def _distributed_save_worker(rank, world_size, checkpoint_dir): | ||||||||||||||||||||||||||||||||||||||
| """Worker that shards a model's state dict across ranks and saves.""" | ||||||||||||||||||||||||||||||||||||||
| model = _make_tiny_llama() | ||||||||||||||||||||||||||||||||||||||
| full_sd = model.state_dict() | ||||||||||||||||||||||||||||||||||||||
| keys = sorted(full_sd.keys()) | ||||||||||||||||||||||||||||||||||||||
| per_rank = len(keys) // world_size | ||||||||||||||||||||||||||||||||||||||
| start = rank * per_rank | ||||||||||||||||||||||||||||||||||||||
| end = start + per_rank if rank < world_size - 1 else len(keys) | ||||||||||||||||||||||||||||||||||||||
| shard_keys = keys[start:end] | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| # Zero out keys not owned by this rank so gather reconstructs the full dict. | ||||||||||||||||||||||||||||||||||||||
| for k in keys: | ||||||||||||||||||||||||||||||||||||||
| if k not in shard_keys: | ||||||||||||||||||||||||||||||||||||||
| full_sd[k] = torch.zeros_like(full_sd[k]) | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| model.load_state_dict(full_sd) | ||||||||||||||||||||||||||||||||||||||
| save_checkpoint_from_shards(model, checkpoint_dir, LlamaModelDescriptor) | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| @pytest.mark.skipif(torch.cuda.device_count() < 2, reason="need >=2 GPUs for multi-rank test") | ||||||||||||||||||||||||||||||||||||||
| class TestSaveCheckpointFromShardsMultiProcess: | ||||||||||||||||||||||||||||||||||||||
| """Tests that exercise the distributed gather path (world_size > 1).""" | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| def test_distributed_save_creates_valid_checkpoint(self, tmp_path): | ||||||||||||||||||||||||||||||||||||||
| spawn_multiprocess_job(2, partial(_distributed_save_worker, checkpoint_dir=tmp_path)) | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| index_path = tmp_path / SAFE_WEIGHTS_INDEX_NAME | ||||||||||||||||||||||||||||||||||||||
| assert index_path.exists() | ||||||||||||||||||||||||||||||||||||||
| index = json.loads(index_path.read_text()) | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| model = _make_tiny_llama() | ||||||||||||||||||||||||||||||||||||||
| expected_keys = set(model.state_dict().keys()) | ||||||||||||||||||||||||||||||||||||||
| assert set(index["weight_map"].keys()) == expected_keys | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| shard_files = list((tmp_path / SAFETENSORS_SUBBLOCKS_DIR_NAME).glob("*.safetensors")) | ||||||||||||||||||||||||||||||||||||||
| assert len(shard_files) > 0 | ||||||||||||||||||||||||||||||||||||||
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.