| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | """Saves each worker's model state dict directly to a checkpoint, which enables a |
| 4 | fast load path for large tensor-parallel models where each worker only needs to |
| 5 | read its own shard rather than the entire checkpoint. |
| 6 | |
| 7 | Example usage: |
| 8 | |
| 9 | python save_sharded_state_offline.py \ |
| 10 | --model /path/to/load \ |
| 11 | --tensor-parallel-size 8 \ |
| 12 | --output /path/to/save |
| 13 | |
| 14 | Then, the model can be loaded with |
| 15 | |
| 16 | llm = LLM( |
| 17 | model="/path/to/save", |
| 18 | load_format="sharded_state", |
| 19 | tensor_parallel_size=8, |
| 20 | ) |
| 21 | """ |
| 22 | |
| 23 | import os |
| 24 | import shutil |
| 25 | from pathlib import Path |
| 26 | |
| 27 | from vllm import LLM, EngineArgs |
| 28 | from vllm.model_executor.model_loader import ShardedStateLoader |
| 29 | from vllm.utils.argparse_utils import FlexibleArgumentParser |
| 30 | |
| 31 | |
| 32 | def parse_args(): |
| 33 | parser = FlexibleArgumentParser() |
| 34 | EngineArgs.add_cli_args(parser) |
| 35 | parser.add_argument( |
| 36 | "--output", "-o", required=True, type=str, help="path to output checkpoint" |
| 37 | ) |
| 38 | parser.add_argument( |
| 39 | "--file-pattern", |
| 40 | type=str, |
| 41 | default=ShardedStateLoader.DEFAULT_PATTERN, |
| 42 | help="string pattern of saved filenames", |
| 43 | ) |
| 44 | parser.add_argument( |
| 45 | "--max-file-size", |
| 46 | type=int, |
| 47 | default=5 * 1024**3, |
| 48 | help="max size (in bytes) of each safetensors file", |
| 49 | ) |
| 50 | return parser.parse_args() |
| 51 | |
| 52 | |
| 53 | def main(args): |
| 54 | engine_args = EngineArgs.from_cli_args(args) |
| 55 | if engine_args.enable_lora: |
| 56 | raise ValueError("Saving with enable_lora=True is not supported!") |
| 57 | model_path = engine_args.model |
| 58 | if not Path(model_path).is_dir(): |
| 59 | raise ValueError("model path must be a local directory") |
| 60 | # Create LLM instance from arguments |
| 61 | llm = LLM.from_engine_args(engine_args) |
| 62 | # Prepare output directory |
| 63 | Path(args.output).mkdir(exist_ok=True) |
| 64 | # Dump worker states to output directory |
| 65 | |
| 66 | llm.llm_engine.engine_core.save_sharded_state( |
| 67 | path=args.output, pattern=args.file_pattern, max_size=args.max_file_size |
| 68 | ) |
| 69 | |
| 70 | # Copy metadata files to output directory |
| 71 | for file in os.listdir(model_path): |
| 72 | if os.path.splitext(file)[1] not in (".bin", ".pt", ".safetensors"): |
| 73 | if os.path.isdir(os.path.join(model_path, file)): |
| 74 | shutil.copytree( |
| 75 | os.path.join(model_path, file), os.path.join(args.output, file) |
| 76 | ) |
| 77 | else: |
| 78 | shutil.copy(os.path.join(model_path, file), args.output) |
| 79 | |
| 80 | |
| 81 | if __name__ == "__main__": |
| 82 | args = parse_args() |
| 83 | main(args) |