|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +"""Hugging Face checkpoint utility.""" |
| 17 | + |
| 18 | +import json |
| 19 | +import os |
| 20 | +import shutil |
| 21 | +from pathlib import Path |
| 22 | + |
| 23 | +import torch |
| 24 | +from safetensors.torch import safe_open |
| 25 | +from tqdm import tqdm |
| 26 | + |
| 27 | + |
| 28 | +def copy_remote_code( |
| 29 | + pretrained_model_path: str | os.PathLike, |
| 30 | + save_directory: str | os.PathLike, |
| 31 | +): |
| 32 | + """Copy remote code from pretrained model to save directory. |
| 33 | +
|
| 34 | + For models that keep configuration and modeling files as part of the checkpoint, |
| 35 | + we need to copy them to the export directory for seamless integration with inference |
| 36 | + frameworks. |
| 37 | +
|
| 38 | + Args: |
| 39 | + pretrained_model_path: Path to the pretrained model. |
| 40 | + save_directory: Path to the save directory. |
| 41 | +
|
| 42 | + Raises: |
| 43 | + ValueError: If the pretrained model path is not a directory. |
| 44 | + """ |
| 45 | + hf_checkpoint_path = Path(pretrained_model_path) |
| 46 | + save_dir = Path(save_directory) |
| 47 | + |
| 48 | + if not hf_checkpoint_path.is_dir(): |
| 49 | + raise ValueError( |
| 50 | + f"Invalid pretrained model path: {pretrained_model_path}. It should be a directory." |
| 51 | + ) |
| 52 | + |
| 53 | + for py_file in hf_checkpoint_path.glob("*.py"): |
| 54 | + if py_file.is_file(): |
| 55 | + shutil.copy(py_file, save_dir / py_file.name) |
| 56 | + |
| 57 | + |
| 58 | +def load_multimodal_components( |
| 59 | + pretrained_model_path: str | os.PathLike, |
| 60 | +) -> dict[str, torch.Tensor]: |
| 61 | + """Load multimodal components from safetensors file. |
| 62 | +
|
| 63 | + Args: |
| 64 | + pretrained_model_path: Path to the pretrained model. |
| 65 | +
|
| 66 | + Returns: |
| 67 | + A dictionary of multimodal components. |
| 68 | + """ |
| 69 | + hf_checkpoint_path = Path(pretrained_model_path) |
| 70 | + if not hf_checkpoint_path.is_dir(): |
| 71 | + raise ValueError( |
| 72 | + f"Invalid pretrained model path: {pretrained_model_path}. It should be a directory." |
| 73 | + ) |
| 74 | + |
| 75 | + safetensors_file = Path(hf_checkpoint_path) / "model.safetensors" |
| 76 | + safetensors_index_file = Path(hf_checkpoint_path) / "model.safetensors.index.json" |
| 77 | + |
| 78 | + multimodal_state_dict = {} |
| 79 | + |
| 80 | + if safetensors_file.is_file(): |
| 81 | + print(f"Loading multimodal components from single file: {safetensors_file}") |
| 82 | + with safe_open(safetensors_file, framework="pt") as f: |
| 83 | + multimodal_keys = [ |
| 84 | + key |
| 85 | + for key in f.keys() # noqa: SIM118 |
| 86 | + if key.startswith(("multi_modal_projector", "vision_model")) |
| 87 | + ] |
| 88 | + for key in tqdm(multimodal_keys, desc="Loading multimodal tensors"): |
| 89 | + multimodal_state_dict[key] = f.get_tensor(key) |
| 90 | + |
| 91 | + elif safetensors_index_file.is_file(): |
| 92 | + print(f"Loading multimodal components from sharded model: {hf_checkpoint_path}") |
| 93 | + with open(safetensors_index_file) as f: |
| 94 | + safetensors_index = json.load(f) |
| 95 | + |
| 96 | + # For multimodal models, vision_model and multi_modal_projector are in the first shard |
| 97 | + all_shard_files = sorted(set(safetensors_index["weight_map"].values())) |
| 98 | + first_shard_file = all_shard_files[0] # e.g., "model-00001-of-00050.safetensors" |
| 99 | + |
| 100 | + # Load multimodal components from the first shard file |
| 101 | + safetensors_filepath = Path(hf_checkpoint_path) / first_shard_file |
| 102 | + print(f"Loading multimodal components from {first_shard_file}") |
| 103 | + |
| 104 | + with safe_open(safetensors_filepath, framework="pt") as f: |
| 105 | + shard_keys = list(f.keys()) |
| 106 | + multimodal_keys_in_shard = [ |
| 107 | + k for k in shard_keys if k.startswith(("multi_modal_projector", "vision_model")) |
| 108 | + ] |
| 109 | + |
| 110 | + if multimodal_keys_in_shard: |
| 111 | + print( |
| 112 | + f"Found {len(multimodal_keys_in_shard)} multimodal tensors in {first_shard_file}" |
| 113 | + ) |
| 114 | + for key in tqdm(multimodal_keys_in_shard, desc="Loading multimodal tensors"): |
| 115 | + multimodal_state_dict[key] = f.get_tensor(key) |
| 116 | + else: |
| 117 | + print(f"No multimodal components found in {first_shard_file}") |
| 118 | + |
| 119 | + else: |
| 120 | + print(f"Warning: No safetensors files found in {hf_checkpoint_path}") |
| 121 | + |
| 122 | + print(f"Successfully loaded {len(multimodal_state_dict)} multimodal tensors") |
| 123 | + return multimodal_state_dict |
0 commit comments