args_tools.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. import argparse
  2. import dataclasses
  3. from dataclasses import dataclass
  4. from typing import Optional, Tuple
  5. from aphrodite.common.config import (CacheConfig, ModelConfig, ParallelConfig,
  6. SchedulerConfig, LoRAConfig)
  7. @dataclass
  8. class EngineArgs:
  9. """Arguments for the Aphrodite engine."""
  10. model: str
  11. tokenizer: Optional[str] = None
  12. tokenizer_mode: str = 'auto'
  13. trust_remote_code: bool = False
  14. download_dir: Optional[str] = None
  15. load_format: str = 'auto'
  16. dtype: str = 'auto'
  17. kv_cache_dtype: str = 'auto'
  18. seed: int = 0
  19. max_model_len: Optional[int] = None
  20. worker_use_ray: bool = False
  21. pipeline_parallel_size: int = 1
  22. tensor_parallel_size: int = 1
  23. max_parallel_loading_workers: Optional[int] = None
  24. block_size: int = 16
  25. swap_space: int = 4 # GiB
  26. gpu_memory_utilization: float = 0.90
  27. max_num_batched_tokens: Optional[int] = None
  28. max_num_seqs: int = 256
  29. max_paddings: int = 256
  30. disable_log_stats: bool = False
  31. revision: Optional[str] = None
  32. tokenizer_revision: Optional[str] = None
  33. quantization: Optional[str] = None
  34. enforce_eager: bool = False
  35. max_context_len_to_capture: int = 8192
  36. disable_custom_all_reduce: bool = False
  37. enable_lora: bool = False
  38. max_loras: int = 1
  39. max_lora_rank: int = 16
  40. lora_extra_vocab_size: int = 256
  41. lora_dtype = 'auto'
  42. max_cpu_loras: Optional[int] = None
  43. def __post_init__(self):
  44. if self.tokenizer is None:
  45. self.tokenizer = self.model
  46. @staticmethod
  47. def add_cli_args(
  48. parser: argparse.ArgumentParser) -> argparse.ArgumentParser:
  49. """Shared CLI arguments for the Aphrodite engine."""
  50. # NOTE: If you update any of the arguments below, please also
  51. # make sure to update docs/source/models/engine_args.rst
  52. # Model arguments
  53. parser.add_argument(
  54. '--model',
  55. type=str,
  56. default='EleutherAI/pythia-70m-deduped',
  57. help='name or path of the huggingface model to use')
  58. parser.add_argument(
  59. '--tokenizer',
  60. type=str,
  61. default=EngineArgs.tokenizer,
  62. help='name or path of the huggingface tokenizer to use')
  63. parser.add_argument(
  64. '--revision',
  65. type=str,
  66. default=None,
  67. help='the specific model version to use. It can be a branch '
  68. 'name, a tag name, or a commit id. If unspecified, will use '
  69. 'the default version.')
  70. parser.add_argument(
  71. '--tokenizer-revision',
  72. type=str,
  73. default=None,
  74. help='the specific tokenizer version to use. It can be a branch '
  75. 'name, a tag name, or a commit id. If unspecified, will use '
  76. 'the default version.')
  77. parser.add_argument('--tokenizer-mode',
  78. type=str,
  79. default=EngineArgs.tokenizer_mode,
  80. choices=['auto', 'slow'],
  81. help='tokenizer mode. "auto" will use the fast '
  82. 'tokenizer if available, and "slow" will '
  83. 'always use the slow tokenizer.')
  84. parser.add_argument('--trust-remote-code',
  85. action='store_true',
  86. help='trust remote code from huggingface')
  87. parser.add_argument('--download-dir',
  88. type=str,
  89. default=EngineArgs.download_dir,
  90. help='directory to download and load the weights, '
  91. 'default to the default cache dir of '
  92. 'huggingface')
  93. parser.add_argument(
  94. '--load-format',
  95. type=str,
  96. default=EngineArgs.load_format,
  97. choices=['auto', 'pt', 'safetensors', 'npcache', 'dummy'],
  98. help='The format of the model weights to load. '
  99. '"auto" will try to load the weights in the safetensors format '
  100. 'and fall back to the pytorch bin format if safetensors format '
  101. 'is not available. '
  102. '"pt" will load the weights in the pytorch bin format. '
  103. '"safetensors" will load the weights in the safetensors format. '
  104. '"npcache" will load the weights in pytorch format and store '
  105. 'a numpy cache to speed up the loading. '
  106. '"dummy" will initialize the weights with random values, '
  107. 'which is mainly for profiling.')
  108. parser.add_argument(
  109. '--dtype',
  110. type=str,
  111. default=EngineArgs.dtype,
  112. choices=[
  113. 'auto', 'half', 'float16', 'bfloat16', 'float', 'float32'
  114. ],
  115. help='data type for model weights and activations. '
  116. 'The "auto" option will use FP16 precision '
  117. 'for FP32 and FP16 models, and BF16 precision '
  118. 'for BF16 models.')
  119. parser.add_argument(
  120. '--kv-cache-dtype',
  121. type=str,
  122. choices=['auto', 'fp8_e5m2'],
  123. default='auto',
  124. help='Data type for kv cache storage. If "auto", will use model '
  125. 'data type. Note FP8 is not supported when cuda version is '
  126. 'lower than 11.8.')
  127. parser.add_argument('--max-model-len',
  128. type=int,
  129. default=None,
  130. help='model context length. If unspecified, '
  131. 'will be automatically derived from the model.')
  132. # Parallel arguments
  133. parser.add_argument('--worker-use-ray',
  134. action='store_true',
  135. help='use Ray for distributed serving, will be '
  136. 'automatically set when using more than 1 GPU')
  137. parser.add_argument('--pipeline-parallel-size',
  138. '-pp',
  139. type=int,
  140. default=EngineArgs.pipeline_parallel_size,
  141. help='number of pipeline stages')
  142. parser.add_argument('--tensor-parallel-size',
  143. '-tp',
  144. type=int,
  145. default=EngineArgs.tensor_parallel_size,
  146. help='number of tensor parallel replicas')
  147. parser.add_argument(
  148. '--max-parallel-loading-workers',
  149. type=int,
  150. help='load model sequentially in multiple batches, '
  151. 'to avoid RAM OOM when using tensor '
  152. 'parallel and large models')
  153. # KV cache arguments
  154. parser.add_argument('--block-size',
  155. type=int,
  156. default=EngineArgs.block_size,
  157. choices=[8, 16, 32],
  158. help='token block size')
  159. # TODO: Support fine-grained seeds (e.g., seed per request).
  160. parser.add_argument('--seed',
  161. type=int,
  162. default=EngineArgs.seed,
  163. help='random seed')
  164. parser.add_argument('--swap-space',
  165. type=int,
  166. default=EngineArgs.swap_space,
  167. help='CPU swap space size (GiB) per GPU')
  168. parser.add_argument(
  169. '--gpu-memory-utilization',
  170. '-gmu',
  171. type=float,
  172. default=EngineArgs.gpu_memory_utilization,
  173. help='the fraction of GPU memory to be used for '
  174. 'the model executor, which can range from 0 to 1.'
  175. 'If unspecified, will use the default value of 0.9.')
  176. parser.add_argument('--max-num-batched-tokens',
  177. type=int,
  178. default=EngineArgs.max_num_batched_tokens,
  179. help='maximum number of batched tokens per '
  180. 'iteration')
  181. parser.add_argument('--max-num-seqs',
  182. type=int,
  183. default=EngineArgs.max_num_seqs,
  184. help='maximum number of sequences per iteration')
  185. parser.add_argument('--max-paddings',
  186. type=int,
  187. default=EngineArgs.max_paddings,
  188. help='maximum number of paddings in a batch')
  189. parser.add_argument('--disable-log-stats',
  190. action='store_true',
  191. help='disable logging statistics')
  192. # Quantization settings.
  193. parser.add_argument(
  194. '--quantization',
  195. '-q',
  196. type=str,
  197. choices=['awq', 'gguf', 'gptq', 'quip', 'squeezellm', None],
  198. default=None,
  199. help='Method used to quantize the weights. If '
  200. 'None, we first check the `quantization_config` '
  201. 'attribute in the model config file. If that is '
  202. 'None, we assume the model weights are not '
  203. 'quantized and use `dtype` to determine the data '
  204. 'type of the weights.')
  205. parser.add_argument('--enforce-eager',
  206. action='store_true',
  207. help='Always use eager-mode PyTorch. If False, '
  208. 'will use eager mode and CUDA graph in hybrid '
  209. 'for maximal performance and flexibility.')
  210. parser.add_argument('--max-context-len-to-capture',
  211. type=int,
  212. default=EngineArgs.max_context_len_to_capture,
  213. help='maximum context length covered by CUDA '
  214. 'graphs. When a sequence has context length '
  215. 'larger than this, we fall back to eager mode.')
  216. parser.add_argument('--disable-custom-all-reduce',
  217. action='store_true',
  218. default=EngineArgs.disable_custom_all_reduce,
  219. help='See ParallelConfig')
  220. # LoRA related configs
  221. parser.add_argument('--enable-lora',
  222. action='store_true',
  223. help='If True, enable handling of LoRA adapters.')
  224. parser.add_argument('--max-loras',
  225. type=int,
  226. default=EngineArgs.max_loras,
  227. help='Max number of LoRAs in a single batch.')
  228. parser.add_argument('--max-lora-rank',
  229. type=int,
  230. default=EngineArgs.max_lora_rank,
  231. help='Max LoRA rank.')
  232. parser.add_argument(
  233. '--lora-extra-vocab-size',
  234. type=int,
  235. default=EngineArgs.lora_extra_vocab_size,
  236. help=('Maximum size of extra vocabulary that can be '
  237. 'present in a LoRA adapter (added to the base '
  238. 'model vocabulary).'))
  239. parser.add_argument(
  240. '--lora-dtype',
  241. type=str,
  242. default=EngineArgs.lora_dtype,
  243. choices=['auto', 'float16', 'bfloat16', 'float32'],
  244. help=('Data type for LoRA. If auto, will default to '
  245. 'base model dtype.'))
  246. parser.add_argument(
  247. '--max-cpu-loras',
  248. type=int,
  249. default=EngineArgs.max_cpu_loras,
  250. help=('Maximum number of LoRAs to store in CPU memory. '
  251. 'Must be >= than max_num_seqs. '
  252. 'Defaults to max_num_seqs.'))
  253. return parser
  254. @classmethod
  255. def from_cli_args(cls, args: argparse.Namespace) -> 'EngineArgs':
  256. # Get the list of attributes of this dataclass.
  257. attrs = [attr.name for attr in dataclasses.fields(cls)]
  258. # Set the attributes from the parsed arguments.
  259. engine_args = cls(**{attr: getattr(args, attr) for attr in attrs})
  260. return engine_args
  261. def create_engine_configs(
  262. self,
  263. ) -> Tuple[ModelConfig, CacheConfig, ParallelConfig, SchedulerConfig,
  264. Optional[LoRAConfig]]:
  265. model_config = ModelConfig(self.model, self.tokenizer,
  266. self.tokenizer_mode, self.trust_remote_code,
  267. self.download_dir, self.load_format,
  268. self.dtype, self.seed, self.revision,
  269. self.tokenizer_revision, self.max_model_len,
  270. self.quantization, self.enforce_eager,
  271. self.max_context_len_to_capture)
  272. cache_config = CacheConfig(self.block_size,
  273. self.gpu_memory_utilization,
  274. self.swap_space, self.kv_cache_dtype,
  275. model_config.get_sliding_window())
  276. parallel_config = ParallelConfig(self.pipeline_parallel_size,
  277. self.tensor_parallel_size,
  278. self.worker_use_ray,
  279. self.max_parallel_loading_workers,
  280. self.disable_custom_all_reduce)
  281. scheduler_config = SchedulerConfig(self.max_num_batched_tokens,
  282. self.max_num_seqs,
  283. model_config.max_model_len,
  284. self.max_paddings)
  285. lora_config = LoRAConfig(
  286. max_lora_rank=self.max_lora_rank,
  287. max_loras=self.max_loras,
  288. lora_extra_vocab_size=self.lora_extra_vocab_size,
  289. lora_dtype=self.lora_dtype,
  290. max_cpu_loras=self.max_cpu_loras if self.max_cpu_loras
  291. and self.max_cpu_loras > 0 else None) if self.enable_lora else None
  292. return (model_config, cache_config, parallel_config, scheduler_config,
  293. lora_config)
  294. @dataclass
  295. class AsyncEngineArgs(EngineArgs):
  296. """Arguments for asynchronous Aphrodite engine."""
  297. engine_use_ray: bool = False
  298. disable_log_requests: bool = False
  299. max_log_len: Optional[int] = None
  300. @staticmethod
  301. def add_cli_args(
  302. parser: argparse.ArgumentParser) -> argparse.ArgumentParser:
  303. parser = EngineArgs.add_cli_args(parser)
  304. parser.add_argument('--engine-use-ray',
  305. action='store_true',
  306. help='use Ray to start the LLM engine in a '
  307. 'separate process as the server process.')
  308. parser.add_argument('--disable-log-requests',
  309. action='store_true',
  310. help='disable logging requests')
  311. parser.add_argument('--max-log-len',
  312. type=int,
  313. default=None,
  314. help='max number of prompt characters or prompt '
  315. 'ID numbers being printed in log. '
  316. 'Default: unlimited.')
  317. return parser