|
17 | 17 | import argparse |
18 | 18 | import json |
19 | 19 | import os |
| 20 | +import re |
20 | 21 |
|
| 22 | +import numpy as np |
21 | 23 | import paddle |
22 | 24 | from paddleformers.transformers.model_utils import shard_checkpoint |
23 | 25 | from paddleformers.utils.env import SAFE_WEIGHTS_INDEX_NAME, SAFE_WEIGHTS_NAME |
@@ -46,6 +48,28 @@ def parse_args(): |
46 | 48 | return parser.parse_args() |
47 | 49 |
|
48 | 50 |
|
| 51 | +def dtype_byte_size(dtype): |
| 52 | + """ |
| 53 | + Returns the size (in bytes) occupied by one parameter of type `dtype`. |
| 54 | +
|
| 55 | + Example: |
| 56 | +
|
| 57 | + ```py |
| 58 | + >>> dtype_byte_size(paddle.float32) |
| 59 | + 4 |
| 60 | + ``` |
| 61 | + """ |
| 62 | + if str(dtype) in {"paddle.bool", "bool"}: |
| 63 | + return 1 / 8 |
| 64 | + if str(dtype) in {"paddle.float8_e4m3fn", "paddle.float8_e5m2", "float8_e4m3fn", "float8_e5m2"}: |
| 65 | + return 1 |
| 66 | + bit_search = re.search(r"[^\d](\d+)$", str(dtype)) |
| 67 | + if bit_search is None: |
| 68 | + raise ValueError(f"`dtype` is not a valid dtype: {dtype}.") |
| 69 | + bit_size = int(bit_search.groups()[0]) |
| 70 | + return bit_size // 8 |
| 71 | + |
| 72 | + |
49 | 73 | def extract_mtp_weights(input_dir: str) -> dict: |
50 | 74 | """ |
51 | 75 | Load all MTP-related weights from safetensors files in input_dir. |
@@ -103,6 +127,18 @@ def save_safetensors(state_dict: dict, output_dir: str): |
103 | 127 | logger.info(f"Saving shard: {save_path}") |
104 | 128 | safe_save_file(shard, save_path, metadata={"format": "np"}) |
105 | 129 |
|
| 130 | + # If only one shard is returned, SAFE_WEIGHTS_INDEX_NAME will be null |
| 131 | + if len(shards) == 1: |
| 132 | + logger.info("Generate index file for single shard") |
| 133 | + weight_size = 0 |
| 134 | + for key, weight in shards["model.safetensors"].items(): |
| 135 | + weight_size += np.prod(weight.shape) * dtype_byte_size(weight.dtype) |
| 136 | + |
| 137 | + index = { |
| 138 | + "metadata": {"total_size": int(weight_size)}, |
| 139 | + "weight_map": {k: "model.safetensors" for k in shards["model.safetensors"].keys()}, |
| 140 | + } |
| 141 | + |
106 | 142 | index_path = os.path.join(output_dir, SAFE_WEIGHTS_INDEX_NAME) |
107 | 143 | with open(index_path, "w", encoding="utf-8") as f: |
108 | 144 | json.dump(index, f, indent=2) |
|
0 commit comments