|
| 1 | +# Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +from __future__ import annotations |
| 15 | + |
| 16 | +import json |
| 17 | +import os |
| 18 | +from functools import partial |
| 19 | + |
| 20 | +import numpy as np |
| 21 | +import paddle |
| 22 | +from tqdm import tqdm |
| 23 | + |
| 24 | +from paddlenlp.transformers import AutoConfig |
| 25 | +from paddlenlp.transformers.model_utils import _add_variant, load_state_dict |
| 26 | +from paddlenlp.transformers.utils import paddlenlp_load |
| 27 | +from paddlenlp.utils.env import ( |
| 28 | + PADDLE_WEIGHTS_INDEX_NAME, |
| 29 | + SAFE_MASTER_WEIGHTS_INDEX_NAME, |
| 30 | + SAFE_PEFT_WEIGHTS_INDEX_NAME, |
| 31 | + SAFE_WEIGHTS_INDEX_NAME, |
| 32 | +) |
| 33 | + |
| 34 | +try: |
| 35 | + from paddlenlp.utils.safetensors import fast_load_file as safe_load_file |
| 36 | + from paddlenlp.utils.safetensors import fast_safe_open as safe_open |
| 37 | +except: |
| 38 | + from safetensors import safe_open |
| 39 | + from safetensors.numpy import load_file as safe_load_file |
| 40 | + |
| 41 | + |
| 42 | +def load_sharded_checkpoint(folder, variant=None, return_numpy=False): |
| 43 | + """ |
| 44 | +
|
| 45 | + This load is performed efficiently: each checkpoint shard is loaded one by one in RAM and deleted after being |
| 46 | + loaded in the model. |
| 47 | +
|
| 48 | + Args: |
| 49 | + folder (`str` or `os.PathLike`): A path to a folder containing the sharded checkpoint. |
| 50 | + variant (`str`): The model variant. |
| 51 | + return_numpy (`bool`): Whether to return numpy array instead of paddle tensor. |
| 52 | +
|
| 53 | + """ |
| 54 | + # Load the index |
| 55 | + pdparams_file = os.path.join(folder, _add_variant("model_state.pdparams", variant)) |
| 56 | + lora_pdparams_file = os.path.join(folder, _add_variant("lora_model_state.pdparams", variant)) |
| 57 | + safetensors_file = os.path.join(folder, _add_variant("model.safetensors", variant)) |
| 58 | + if os.path.isfile(pdparams_file): |
| 59 | + return paddle.load(pdparams_file, return_numpy=return_numpy) |
| 60 | + if os.path.isfile(lora_pdparams_file): |
| 61 | + return paddle.load(lora_pdparams_file, return_numpy=return_numpy) |
| 62 | + if os.path.isfile(safetensors_file): |
| 63 | + state_dict = safe_load_file(safetensors_file) |
| 64 | + if not return_numpy: |
| 65 | + for key in list(state_dict.keys()): |
| 66 | + if isinstance(state_dict[key], np.ndarray): |
| 67 | + state_dict[key] = paddle.Tensor(state_dict.pop(key), zero_copy=True) |
| 68 | + return state_dict |
| 69 | + |
| 70 | + index_file = os.path.join(folder, _add_variant(PADDLE_WEIGHTS_INDEX_NAME, variant)) |
| 71 | + safe_index_file = os.path.join(folder, _add_variant(SAFE_WEIGHTS_INDEX_NAME, variant)) |
| 72 | + safe_master_file = os.path.join(folder, _add_variant(SAFE_MASTER_WEIGHTS_INDEX_NAME, variant)) |
| 73 | + safe_peft_file = os.path.join(folder, _add_variant(SAFE_PEFT_WEIGHTS_INDEX_NAME, variant)) |
| 74 | + |
| 75 | + index_present = os.path.isfile(index_file) |
| 76 | + safe_index_present = os.path.isfile(safe_index_file) |
| 77 | + safe_master_present = os.path.isfile(safe_master_file) |
| 78 | + safe_peft_present = os.path.isfile(safe_peft_file) |
| 79 | + |
| 80 | + load_safe = False |
| 81 | + load_index = None |
| 82 | + if safe_index_present: |
| 83 | + load_safe = True # load safe due to preference |
| 84 | + load_index = safe_index_file |
| 85 | + elif safe_master_present: |
| 86 | + load_safe = True |
| 87 | + load_index = safe_master_file |
| 88 | + elif index_present: |
| 89 | + load_index = index_file |
| 90 | + elif safe_peft_present: |
| 91 | + load_safe = True |
| 92 | + load_index = safe_peft_file |
| 93 | + else: |
| 94 | + raise ValueError(f"Could not find {index_file} or {safe_index_file} or {safe_peft_file}") |
| 95 | + |
| 96 | + with open(load_index, "r", encoding="utf-8") as f: |
| 97 | + index = json.load(f) |
| 98 | + |
| 99 | + shard_files = list(set(index["weight_map"].values())) |
| 100 | + loader = safe_load_file if load_safe else partial(paddlenlp_load, map_location="np" if return_numpy else "cpu") |
| 101 | + |
| 102 | + ret = {} |
| 103 | + for shard_file in tqdm(shard_files): |
| 104 | + state_dict = loader(os.path.join(folder, shard_file)) |
| 105 | + ret.update(state_dict) |
| 106 | + |
| 107 | + if not return_numpy: |
| 108 | + for key in list(ret.keys()): |
| 109 | + if isinstance(ret[key], np.ndarray): |
| 110 | + ret[key] = paddle.Tensor(ret.pop(key), zero_copy=True) |
| 111 | + |
| 112 | + return ret |
| 113 | + |
| 114 | + |
| 115 | +def load_tp_checkpoint(folder, cls, config, return_numpy=False): |
| 116 | + """ |
| 117 | +
|
| 118 | + This load is performed efficiently: Load tp checkpoint only from cpu, no need to init the model. |
| 119 | +
|
| 120 | + Args: |
| 121 | + folder (`str` or `os.PathLike`): A path to a folder containing the model checkpoint. |
| 122 | + cls (`str`): The model class. |
| 123 | + config (`AutoConfig`): The model config. |
| 124 | + return_numpy (bool): Whether load the tp checkpoint as numpy. |
| 125 | + """ |
| 126 | + |
| 127 | + config = AutoConfig.from_pretrained(folder) |
| 128 | + if config.tensor_parallel_degree == 1: |
| 129 | + return load_sharded_checkpoint(folder, return_numpy=return_numpy) |
| 130 | + else: |
| 131 | + rank_model_path = os.path.join(folder, f"model_state.tp0{config.tensor_parallel_rank}.pdparams") |
| 132 | + model_path = os.path.join(folder, "model_state.pdparams") |
| 133 | + safe_model_path = os.path.join(folder, "model.safetensors") |
| 134 | + if os.path.exists(rank_model_path): |
| 135 | + return paddle.load(rank_model_path, return_numpy=return_numpy) |
| 136 | + elif os.path.exists(model_path): |
| 137 | + state_dict = cls.convert_tensor_parallel(model_path, config) |
| 138 | + elif os.path.exists(safe_model_path): |
| 139 | + with safe_open(safe_model_path, framework="np", device="cpu") as f: |
| 140 | + loaded_keys = f.keys() |
| 141 | + tp_actions = cls.get_tensor_parallel_convert_actions(config, loaded_keys) |
| 142 | + state_dict = load_state_dict(safe_model_path, tp_actions) |
| 143 | + else: # shard files safetensors |
| 144 | + resolved_archive_file, resolved_sharded_files, sharded_metadata, is_sharded = cls._resolve_model_file_path( |
| 145 | + pretrained_model_name_or_path=folder, |
| 146 | + use_safetensors=True, |
| 147 | + ) |
| 148 | + if len(resolved_sharded_files) > 1: |
| 149 | + resolved_sharded_files = tqdm(resolved_sharded_files, desc="Loading checkpoint shards") |
| 150 | + loaded_state_dict_keys = sharded_metadata["all_checkpoint_keys"] |
| 151 | + tp_actions = cls.get_tensor_parallel_convert_actions(config, loaded_state_dict_keys, ignore_error=True) |
| 152 | + state_dict = {} |
| 153 | + for shard_file in resolved_sharded_files: |
| 154 | + shard_state_dict = load_state_dict( |
| 155 | + shard_file, |
| 156 | + tp_actions, |
| 157 | + loaded_state_dict_keys, |
| 158 | + ) |
| 159 | + state_dict.update(shard_state_dict) |
| 160 | + if return_numpy: |
| 161 | + for k in list(state_dict.keys()): |
| 162 | + if not isinstance(state_dict[k], np.ndarray): |
| 163 | + state_dict[k] = state_dict.pop(k).cpu().numpy() |
| 164 | + return state_dict |
0 commit comments