config.py 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371
  1. import enum
  2. import json
  3. import os
  4. from dataclasses import dataclass, field, fields
  5. from typing import TYPE_CHECKING, ClassVar, List, Optional, Tuple, Union
  6. import torch
  7. from loguru import logger
  8. from transformers import PretrainedConfig
  9. from aphrodite.common.utils import get_cpu_memory, is_cpu, is_hip, is_neuron
  10. from aphrodite.modeling.models import ModelRegistry
  11. from aphrodite.quantization import QUANTIZATION_METHODS
  12. from aphrodite.transformers_utils.config import get_config, get_hf_text_config
  13. if TYPE_CHECKING:
  14. from ray.util.placement_group import PlacementGroup
  15. from aphrodite.modeling.model_loader.loader import BaseModelLoader
  16. # If true, will load models from ModelScope instead of Hugging Face Hub.
  17. APHRODITE_USE_MODELSCOPE = os.environ.get("APHRODITE_USE_MODELSCOPE",
  18. "False").lower() == "true"
  19. _GB = 1 << 30
  20. _EMBEDDING_MODEL_MAX_NUM_BATCHED_TOKENS = 32768
  21. class ModelConfig:
  22. """Configuration for the model.
  23. Args:
  24. model: Name or path of the huggingface model to use.
  25. tokenizer: Name or path of the huggingface tokenizer to use.
  26. tokenizer_mode: Tokenizer mode. "auto" will use the fast tokenizer if
  27. available, and "slow" will always use the slow tokenizer.
  28. trust_remote_code: Trust remote code (e.g., from HuggingFace) when
  29. downloading the model and tokenizer.
  30. dtype: Data type for model weights and activations. The "auto" option
  31. will use FP16 precision for FP32 and FP16 models, and BF16 precision
  32. for BF16 models.
  33. seed: Random seed for reproducibility.
  34. revision: The specific model version to use. It can be a branch name,
  35. a tag name, or a commit id. If unspecified, will use the default
  36. version.
  37. code_revision: The specific revision to use for the model code on
  38. Hugging Face Hub. It can be a branch name, a tag name, or a
  39. commit id. If unspecified, will use the default version.
  40. rope_scaling: Dictionary containing the scaling configuration for the
  41. RoPE embeddings. When using this flag, don't update
  42. `max_position_embeddings` to the expected new maximum.
  43. tokenizer_revision: The specific tokenizer version to use. It can be a
  44. branch name, a tag name, or a commit id. If unspecified, will use
  45. the default version.
  46. max_model_len: Maximum length of a sequence (including prompt and
  47. output). If None, will be derived from the model.
  48. quantization: Quantization method that was used to quantize the model
  49. weights. If None, we assume the model weights are not quantized.
  50. load_in_4bit: Whether to load the FP16 model in bitsandbytes 4bit
  51. format. Works with AWQ models as well as FP16.
  52. load_in_8bit: Whether to load the FP16 model in 8bit format. Slower
  53. than load_in_smooth in terms of throughput.
  54. load_in_smooth: Whether to load the FP16 model in smoothquant format.
  55. deepspeed_fp_bits: Number of bits to use for DeepSpeed FP quantization.
  56. Supported number of bits are: 4, 6, 8, 12.
  57. quantization_param_path: Path to JSON file containing scaling factors.
  58. Used to load KV cache scaling factors into the model when KV cache
  59. type is FP8_E4M3 on ROCm (AMD GPU). In the future these will also
  60. be used to load activation and weight scaling factors when the
  61. model dtype is FP8_E4M3 on ROCm.
  62. enforce_eager: Whether to enforce eager execution. If True, we will
  63. disable CUDA graph and always execute the model in eager mode.
  64. If False, we will use CUDA graph and eager execution in hybrid.
  65. max_context_len_to_capture: Maximum context len covered by CUDA graphs.
  66. When a sequence has context length larger than this, we fall back
  67. to eager mode (DEPRECATED. Use max_seq_len_to_capture instead).
  68. max_seq_len_to_capture: Maximum sequence len covered by CUDA graphs.
  69. When a sequence has context length larger than this, we fall back
  70. to eager mode
  71. disable_sliding_window: Whether to disable sliding window. If True,
  72. we will disable the sliding window functionality of the model.
  73. If the model does not support sliding window, this argument is
  74. ignored.
  75. skip_tokenizer_init: If true, skip initialization of tokenizer and
  76. detokenizer.
  77. """
  78. def __init__(
  79. self,
  80. model: str,
  81. tokenizer: str,
  82. tokenizer_mode: str,
  83. trust_remote_code: bool,
  84. dtype: Union[str, torch.dtype],
  85. seed: int,
  86. revision: Optional[str] = None,
  87. code_revision: Optional[str] = None,
  88. rope_scaling: Optional[dict] = None,
  89. tokenizer_revision: Optional[str] = None,
  90. max_model_len: Optional[int] = None,
  91. quantization: Optional[str] = None,
  92. load_in_4bit: bool = False,
  93. load_in_8bit: bool = False,
  94. load_in_smooth: bool = False,
  95. deepspeed_fp_bits: Optional[int] = None,
  96. quantization_param_path: Optional[str] = None,
  97. enforce_eager: bool = True,
  98. max_context_len_to_capture: Optional[int] = None,
  99. max_seq_len_to_capture: Optional[int] = None,
  100. max_logprobs: int = 5,
  101. disable_sliding_window: bool = False,
  102. skip_tokenizer_init: bool = False,
  103. ) -> None:
  104. self.model = model
  105. self.tokenizer = tokenizer
  106. self.tokenizer_mode = tokenizer_mode
  107. self.trust_remote_code = trust_remote_code
  108. self.seed = seed
  109. self.revision = revision
  110. self.code_revision = code_revision
  111. self.rope_scaling = rope_scaling
  112. self.tokenizer_revision = tokenizer_revision
  113. self.quantization = quantization
  114. self.load_in_4bit = load_in_4bit
  115. self.load_in_8bit = load_in_8bit
  116. self.load_in_smooth = load_in_smooth
  117. self.deepspeed_fp_bits = deepspeed_fp_bits
  118. self.quantization_param_path = quantization_param_path
  119. self.enforce_eager = enforce_eager
  120. self.max_context_len_to_capture = max_context_len_to_capture
  121. if self.max_context_len_to_capture is not None:
  122. raise ValueError("`max_context_len_to_capture` is deprecated. "
  123. "Use `max_seq_len_to_capture` instead.")
  124. self.max_seq_len_to_capture = (max_seq_len_to_capture
  125. or max_context_len_to_capture)
  126. self.max_logprobs = max_logprobs
  127. self.disable_sliding_window = disable_sliding_window
  128. self.skip_tokenizer_init = skip_tokenizer_init
  129. self.hf_config = get_config(self.model, trust_remote_code, revision,
  130. code_revision, rope_scaling)
  131. self.hf_text_config = get_hf_text_config(self.hf_config)
  132. self.dtype = _get_and_verify_dtype(self.hf_text_config, dtype)
  133. self.max_model_len = _get_and_verify_max_len(
  134. hf_config=self.hf_text_config,
  135. max_model_len=max_model_len,
  136. disable_sliding_window=self.disable_sliding_window,
  137. sliding_window_len=self.get_hf_config_sliding_window())
  138. if (getattr(self.hf_config, "max_position_embeddings", 0) == 131072
  139. and getattr(self.hf_config, "rope_scaling", None) is None):
  140. self.hf_config.update({"rope_scaling": {
  141. "type": "extended",
  142. }})
  143. if not self.skip_tokenizer_init:
  144. self._verify_tokenizer_mode()
  145. self._verify_embedding_mode()
  146. self._verify_quantization()
  147. self._verify_cuda_graph()
  148. def _verify_tokenizer_mode(self) -> None:
  149. tokenizer_mode = self.tokenizer_mode.lower()
  150. if tokenizer_mode not in ["auto", "slow"]:
  151. raise ValueError(
  152. f"Unknown tokenizer mode: {self.tokenizer_mode}. Must be "
  153. "either 'auto' or 'slow'.")
  154. self.tokenizer_mode = tokenizer_mode
  155. def _verify_embedding_mode(self) -> None:
  156. architectures = getattr(self.hf_config, "architectures", [])
  157. self.embedding_mode = any(
  158. ModelRegistry.is_embedding_model(arch) for arch in architectures)
  159. def _verify_quantization(self) -> None:
  160. supported_quantization = [*QUANTIZATION_METHODS]
  161. rocm_supported_quantization = ["gptq", "squeezellm"]
  162. if self.quantization is not None:
  163. self.quantization = self.quantization.lower()
  164. # Parse quantization method from the HF model config, if available.
  165. quant_cfg = getattr(self.hf_config, "quantization_config", None)
  166. if quant_cfg is not None:
  167. quant_method = quant_cfg.get("quant_method", "").lower()
  168. # Detect which checkpoint is it
  169. for name, method in QUANTIZATION_METHODS.items():
  170. quantization_override = method.override_quantization_method(
  171. quant_cfg, self.quantization)
  172. if quantization_override:
  173. quant_method = quantization_override
  174. self.quantization = quantization_override
  175. break
  176. # Verify quantization configurations.
  177. if self.quantization is None:
  178. self.quantization = quant_method
  179. elif self.quantization != quant_method:
  180. raise ValueError(
  181. "Quantization method specified in the model config "
  182. f"({quant_method}) does not match the quantization "
  183. f"method specified in the `quantization` argument "
  184. f"({self.quantization}).")
  185. if self.load_in_4bit:
  186. # the kernels seem to not work with 4bit weight_only
  187. if torch.cuda.get_device_capability(0)[0] < 8:
  188. raise ValueError(
  189. "load_in_4bit quantization is not supported on GPUs with "
  190. "compute capability less than 8.0.")
  191. if self.quantization is None:
  192. self.quantization = "bnb"
  193. self.hf_config.quantization_config = {
  194. "bits": 4,
  195. "quant_mode": "weight_only",
  196. "quant_method": "bnb",
  197. "group_size": 128,
  198. "zero_point": True,
  199. "from_float": True
  200. }
  201. elif self.quantization == "awq":
  202. logger.warning("AWQ model is being loaded in 4bit bnb format.")
  203. self.quantization = "bnb"
  204. self.hf_config.quantization_config = {
  205. "zero_point": True,
  206. "q_group_size": 128,
  207. "w_bit": 4,
  208. "version": "gemm"
  209. }
  210. elif self.quantization != "bnb":
  211. raise ValueError("4bit quantization is not supported in "
  212. f"{self.quantization}.")
  213. if self.load_in_8bit:
  214. if self.quantization is None:
  215. self.quantization = "bnb"
  216. elif self.quantization != "bnb":
  217. raise ValueError("8bit quantization is not supported in "
  218. f"{self.quantization}.")
  219. self.hf_config.quantization_config = {
  220. "bits": 8,
  221. "quant_mode": "llm_int8",
  222. "quant_method": "bnb",
  223. "group_size": 128,
  224. "zero_point": True,
  225. "from_float": True
  226. }
  227. self.enforce_eager = True
  228. if self.load_in_smooth:
  229. if self.quantization is None:
  230. self.quantization = "bnb"
  231. elif self.quantization != "bnb":
  232. raise ValueError("Smooth quantization is not supported in "
  233. f"{self.quantization}.")
  234. self.hf_config.quantization_config = {
  235. "bits": 8,
  236. "quant_mode": "smoothquant",
  237. "quant_method": "bnb",
  238. "group_size": 128,
  239. "zero_point": True,
  240. "from_float": True
  241. }
  242. self.enforce_eager = True
  243. if self.quantization == "deepspeedfp":
  244. gs = 32 if self.deepspeed_fp_bits == 4 else 128
  245. self.hf_config.quantization_config = {
  246. "bits": self.deepspeed_fp_bits,
  247. "group_size": int(os.environ.get("DEEPSPEED_GROUP_SIZE", gs)),
  248. "quant_method": "deepspeedfp"
  249. }
  250. if self.quantization is not None:
  251. if self.quantization not in supported_quantization:
  252. raise ValueError(
  253. f"Unknown quantization method: {self.quantization}. Must "
  254. f"be one of {supported_quantization}.")
  255. if is_hip(
  256. ) and self.quantization not in rocm_supported_quantization:
  257. raise ValueError(
  258. f"{self.quantization} quantization is currently not "
  259. "supported in ROCm.")
  260. if (self.quantization
  261. not in ["marlin", "gptq_marlin_24", "gptq_marlin"]):
  262. logger.warning(
  263. f"{self.quantization} quantization is not fully "
  264. "optimized yet. The speed can be slower than "
  265. "non-quantized models.")
  266. if self.quantization == "deepspeedfp" and self.deepspeed_fp_bits \
  267. is None:
  268. raise ValueError(
  269. "deepspeed_fp_bits must be specified when using "
  270. "deepspeedfp quantization.")
  271. def _verify_cuda_graph(self) -> None:
  272. if self.max_seq_len_to_capture is None:
  273. self.max_seq_len_to_capture = self.max_model_len
  274. self.max_seq_len_to_capture = min(self.max_seq_len_to_capture,
  275. self.max_model_len)
  276. def verify_with_parallel_config(
  277. self,
  278. parallel_config: "ParallelConfig",
  279. ) -> None:
  280. total_num_attention_heads = self.hf_text_config.num_attention_heads
  281. tensor_parallel_size = parallel_config.tensor_parallel_size
  282. if total_num_attention_heads % tensor_parallel_size != 0:
  283. raise ValueError(
  284. f"Total number of attention heads ({total_num_attention_heads})"
  285. " must be divisible by tensor parallel size "
  286. f"({tensor_parallel_size}).")
  287. total_num_hidden_layers = self.hf_text_config.num_hidden_layers
  288. pipeline_parallel_size = parallel_config.pipeline_parallel_size
  289. if total_num_hidden_layers % pipeline_parallel_size != 0:
  290. raise ValueError(
  291. f"Total number of hidden layers ({total_num_hidden_layers}) "
  292. "must be divisible by pipeline parallel size "
  293. f"({pipeline_parallel_size}).")
  294. def get_hf_config_sliding_window(self) -> Optional[int]:
  295. """Get the sliding window size, or None if disabled.
  296. """
  297. # Some models, like Qwen2 and Qwen1.5, use `use_sliding_window` in
  298. # addition to sliding window size. We check if that field is present
  299. # and if it's False, return None.
  300. if (hasattr(self.hf_text_config, "use_sliding_window")
  301. and not self.hf_text_config.use_sliding_window):
  302. return None
  303. return getattr(self.hf_text_config, "sliding_window", None)
  304. def get_sliding_window(self) -> Optional[int]:
  305. """Get the sliding window size, or None if disabled.
  306. """
  307. # If user disables sliding window, return None.
  308. if self.disable_sliding_window:
  309. return None
  310. # Otherwise get the value from the hf config.
  311. return self.get_hf_config_sliding_window()
  312. def get_vocab_size(self) -> int:
  313. return self.hf_text_config.vocab_size
  314. def get_hidden_size(self) -> int:
  315. return self.hf_text_config.hidden_size
  316. def get_head_size(self) -> int:
  317. if hasattr(self.hf_text_config, "head_dim"):
  318. return self.hf_text_config.head_dim
  319. # FIXME: This may not be true for all models.
  320. return (self.hf_text_config.hidden_size //
  321. self.hf_text_config.num_attention_heads)
  322. def get_total_num_kv_heads(self) -> int:
  323. """Returns the total number of KV heads."""
  324. # For GPTBigCode & Falcon:
  325. # NOTE: for falcon, when new_decoder_architecture is True, the
  326. # multi_query flag is ignored and we use n_head_kv for the number of
  327. # KV heads.
  328. falcon_model_types = ["falcon", "RefinedWeb", "RefinedWebModel"]
  329. new_decoder_arch_falcon = (
  330. self.hf_config.model_type in falcon_model_types
  331. and getattr(self.hf_config, "new_decoder_architecture", False))
  332. if not new_decoder_arch_falcon and getattr(self.hf_text_config,
  333. "multi_query", False):
  334. # Multi-query attention, only one KV head.
  335. # Currently, tensor parallelism is not supported in this case.
  336. return 1
  337. # For DBRX and MPT
  338. if self.hf_config.model_type in ["dbrx", "mpt"]:
  339. return getattr(self.hf_config.attn_config, "kv_n_heads",
  340. self.hf_config.num_attention_heads)
  341. attributes = [
  342. # For Falcon:
  343. "n_head_kv",
  344. "num_kv_heads",
  345. # For LLaMA-2:
  346. "num_key_value_heads",
  347. # For ChatGLM:
  348. "multi_query_group_num",
  349. ]
  350. for attr in attributes:
  351. num_kv_heads = getattr(self.hf_text_config, attr, None)
  352. if num_kv_heads is not None:
  353. return num_kv_heads
  354. # For non-grouped-query attention models, the number of KV heads is
  355. # equal to the number of attention heads.
  356. return self.hf_text_config.num_attention_heads
  357. def get_num_kv_heads(self, parallel_config: "ParallelConfig") -> int:
  358. """Returns the number of KV heads per GPU."""
  359. total_num_kv_heads = self.get_total_num_kv_heads()
  360. # If tensor parallelism is used, we divide the number of KV heads by
  361. # the tensor parallel size. We will replicate the KV heads in the
  362. # case where the number of KV heads is smaller than the tensor
  363. # parallel size so each GPU has at least one KV head.
  364. return max(1,
  365. total_num_kv_heads // parallel_config.tensor_parallel_size)
  366. def get_num_attention_heads(self,
  367. parallel_config: "ParallelConfig") -> int:
  368. return self.hf_text_config.num_attention_heads // \
  369. parallel_config.tensor_parallel_size
  370. def get_num_layers(self, parallel_config: "ParallelConfig") -> int:
  371. total_num_hidden_layers = self.hf_text_config.num_hidden_layers
  372. return total_num_hidden_layers // parallel_config.pipeline_parallel_size
  373. class CacheConfig:
  374. """Configuration for the KV cache.
  375. Args:
  376. block_size: Size of a cache block in number of tokens.
  377. gpu_memory_utilization: Fraction of GPU memory to use for the
  378. Aphrodite execution.
  379. swap_space: Size of the CPU swap space per GPU (in GiB).
  380. cache_dtype: Data type for kv cache storage.
  381. num_gpu_blocks_override: Number of GPU blocks to use. This overrides the
  382. profiled num_gpu_blocks if specified. Does nothing if None.
  383. """
  384. def __init__(
  385. self,
  386. block_size: int,
  387. gpu_memory_utilization: float,
  388. swap_space: int,
  389. cache_dtype: str,
  390. num_gpu_blocks_override: Optional[int] = None,
  391. sliding_window: Optional[int] = None,
  392. enable_prefix_caching: bool = False,
  393. ) -> None:
  394. self.block_size = block_size
  395. self.gpu_memory_utilization = gpu_memory_utilization
  396. self.swap_space_bytes = swap_space * _GB
  397. self.num_gpu_blocks_override = num_gpu_blocks_override
  398. self.cache_dtype = cache_dtype
  399. self.sliding_window = sliding_window
  400. self.enable_prefix_caching = enable_prefix_caching
  401. self._verify_args()
  402. self._verify_cache_dtype()
  403. self._verify_prefix_caching()
  404. # Will be set after profiling.
  405. self.num_gpu_blocks = None
  406. self.num_cpu_blocks = None
  407. def metrics_info(self):
  408. # convert cache_config to dict(key: str, value: str) for prometheus
  409. # metrics info
  410. return {key: str(value) for key, value in self.__dict__.items()}
  411. def _verify_args(self) -> None:
  412. if self.gpu_memory_utilization > 1.0:
  413. raise ValueError(
  414. "GPU memory utilization must be less than 1.0. Got "
  415. f"{self.gpu_memory_utilization}.")
  416. def _verify_cache_dtype(self) -> None:
  417. if self.cache_dtype == "auto":
  418. pass
  419. elif self.cache_dtype in ("fp8", "fp8_e4m3", "fp8_e5m2"):
  420. logger.info(
  421. "Using fp8 data type to store kv cache. It reduces the GPU "
  422. "memory footprint and boosts the performance. "
  423. "Meanwhile, it may cause accuracy drop without a proper "
  424. "scaling factor")
  425. else:
  426. raise ValueError(f"Unknown kv cache dtype: {self.cache_dtype}")
  427. def _verify_prefix_caching(self) -> None:
  428. if not self.enable_prefix_caching:
  429. return
  430. if self.sliding_window is not None:
  431. raise NotImplementedError(
  432. "Prefix caching is not supported with sliding window. "
  433. "Run with --disable-sliding-window to use prefix caching.")
  434. if self.cache_dtype == "fp8":
  435. raise NotImplementedError(
  436. "Prefix caching is not supported for fp8 cache_dtype. "
  437. "Run with --kv-cache-dtype auto to use prefix caching.")
  438. def verify_with_parallel_config(
  439. self,
  440. parallel_config: "ParallelConfig",
  441. ) -> None:
  442. total_cpu_memory = get_cpu_memory()
  443. # FIXME: Here, it is assumed that the GPUs in a tensor parallel
  444. # group are in the same node. However, the GPUs may span multiple nodes.
  445. num_gpus_per_node = parallel_config.tensor_parallel_size
  446. cpu_memory_usage = self.swap_space_bytes * num_gpus_per_node
  447. msg = (f"{cpu_memory_usage / _GB:.2f} GiB out of "
  448. f"the {total_cpu_memory / _GB:.2f} GiB total CPU memory is "
  449. "allocated for the swap space.")
  450. if cpu_memory_usage > 0.7 * total_cpu_memory:
  451. raise ValueError("Too large swap space. " + msg)
  452. elif cpu_memory_usage > 0.4 * total_cpu_memory:
  453. logger.warning("Possibly too large swap space. " + msg)
  454. @dataclass
  455. class TokenizerPoolConfig:
  456. """Configuration for the tokenizer pool.
  457. Args:
  458. pool_size: Number of tokenizer workers in the pool.
  459. pool_type: Type of the pool.
  460. extra_config: Additional config for the pool.
  461. The way the config will be used depends on the
  462. pool type.
  463. """
  464. pool_size: int
  465. pool_type: str
  466. extra_config: dict
  467. def __post_init__(self):
  468. if self.pool_type not in ("ray", ):
  469. raise ValueError(f"Unknown pool type: {self.pool_type}")
  470. if not isinstance(self.extra_config, dict):
  471. raise ValueError("extra_config must be a dictionary.")
  472. @classmethod
  473. def create_config(
  474. cls, tokenizer_pool_size: int, tokenizer_pool_type: str,
  475. tokenizer_pool_extra_config: Optional[Union[str, dict]]
  476. ) -> Optional["TokenizerPoolConfig"]:
  477. """Create a TokenizerPoolConfig from the given parameters.
  478. If tokenizer_pool_size is 0, return None.
  479. Args:
  480. tokenizer_pool_size: Number of tokenizer workers in the pool.
  481. tokenizer_pool_type: Type of the pool.
  482. tokenizer_pool_extra_config: Additional config for the pool.
  483. The way the config will be used depends on the
  484. pool type. This can be a JSON string (will be parsed).
  485. """
  486. if tokenizer_pool_size:
  487. if isinstance(tokenizer_pool_extra_config, str):
  488. tokenizer_pool_extra_config_parsed = json.loads(
  489. tokenizer_pool_extra_config)
  490. else:
  491. tokenizer_pool_extra_config_parsed = (
  492. tokenizer_pool_extra_config or {})
  493. tokenizer_pool_config = cls(tokenizer_pool_size,
  494. tokenizer_pool_type,
  495. tokenizer_pool_extra_config_parsed)
  496. else:
  497. tokenizer_pool_config = None
  498. return tokenizer_pool_config
  499. class LoadFormat(str, enum.Enum):
  500. AUTO = "auto"
  501. PT = "pt"
  502. SAFETENSORS = "safetensors"
  503. NPCACHE = "npcache"
  504. DUMMY = "dummy"
  505. TENSORIZER = "tensorizer"
  506. SHARDED_STATE = "sharded_state"
  507. @dataclass
  508. class LoadConfig:
  509. """
  510. download_dir: Directory to download and load the weights, default to the
  511. default cache directory of huggingface.
  512. load_format: The format of the model weights to load:
  513. "auto" will try to load the weights in the safetensors format and
  514. fall back to the pytorch bin format if safetensors format is
  515. not available.
  516. "pt" will load the weights in the pytorch bin format.
  517. "safetensors" will load the weights in the safetensors format.
  518. "npcache" will load the weights in pytorch format and store
  519. a numpy cache to speed up the loading.
  520. "dummy" will initialize the weights with random values, which is
  521. mainly for profiling.
  522. "tensorizer" will use CoreWeave's tensorizer library for
  523. fast weight loading.
  524. """
  525. load_format: Union[str, LoadFormat, "BaseModelLoader"] = LoadFormat.AUTO
  526. download_dir: Optional[str] = None
  527. model_loader_extra_config: Optional[Union[str, dict]] = field(
  528. default_factory=dict)
  529. def __post_init__(self):
  530. model_loader_extra_config = self.model_loader_extra_config or {}
  531. if isinstance(model_loader_extra_config, str):
  532. self.model_loader_extra_config = json.loads(
  533. model_loader_extra_config)
  534. self._verify_load_format()
  535. def _verify_load_format(self) -> None:
  536. if not isinstance(self.load_format, str):
  537. return
  538. load_format = self.load_format.lower()
  539. self.load_format = LoadFormat(load_format)
  540. rocm_not_supported_load_format: List[str] = []
  541. if is_hip() and load_format in rocm_not_supported_load_format:
  542. rocm_supported_load_format = [
  543. f for f in LoadFormat.__members__
  544. if (f not in rocm_not_supported_load_format)
  545. ]
  546. raise ValueError(
  547. f"load format '{load_format}' is not supported in ROCm. "
  548. f"Supported load formats are "
  549. f"{rocm_supported_load_format}")
  550. class ParallelConfig:
  551. """Configuration for the distributed execution.
  552. Args:
  553. pipeline_parallel_size: Number of pipeline parallel groups.
  554. tensor_parallel_size: Number of tensor parallel groups.
  555. worker_use_ray: Deprecated, use distributed_executor_backend instead.
  556. max_parallel_loading_workers: Maximum number of multiple batches
  557. when load model sequentially. To avoid RAM OOM when using tensor
  558. parallel and large models.
  559. disable_custom_all_reduce: Disable the custom all-reduce kernel and
  560. fall back to NCCL.
  561. tokenizer_pool_config: Config for the tokenizer pool.
  562. If None, will use synchronous tokenization.
  563. ray_workers_use_nsight: Whether to profile Ray workers with nsight, see
  564. https://docs.ray.io/en/latest/ray-observability/user-guides/profiling.html#profiling-nsight-profiler.
  565. placement_group: ray distributed model workers placement group.
  566. distributed_executor_backend: Backend to use for distributed model
  567. workers, either "ray" or "mp" (multiprocessing). If either
  568. pipeline_parallel_size or tensor_parallel_size is greater than 1,
  569. will default to "ray" if Ray is installed or "mp" otherwise.
  570. """
  571. def __init__(
  572. self,
  573. pipeline_parallel_size: int,
  574. tensor_parallel_size: int,
  575. worker_use_ray: Optional[bool] = None,
  576. max_parallel_loading_workers: Optional[int] = None,
  577. disable_custom_all_reduce: bool = False,
  578. tokenizer_pool_config: Optional[TokenizerPoolConfig] = None,
  579. ray_workers_use_nsight: bool = False,
  580. placement_group: Optional["PlacementGroup"] = None,
  581. distributed_executor_backend: Optional[str] = None,
  582. ) -> None:
  583. self.pipeline_parallel_size = pipeline_parallel_size
  584. self.tensor_parallel_size = tensor_parallel_size
  585. self.distributed_executor_backend = distributed_executor_backend
  586. self.max_parallel_loading_workers = max_parallel_loading_workers
  587. self.disable_custom_all_reduce = disable_custom_all_reduce
  588. self.tokenizer_pool_config = tokenizer_pool_config
  589. self.ray_workers_use_nsight = ray_workers_use_nsight
  590. self.placement_group = placement_group
  591. self.world_size = pipeline_parallel_size * self.tensor_parallel_size
  592. if worker_use_ray:
  593. if self.distributed_executor_backend is None:
  594. self.distributed_executor_backend = "ray"
  595. elif self.distributed_executor_backend != "ray":
  596. raise ValueError(f"worker-use-ray can't be used with "
  597. f"distributed executor backend "
  598. f"'{self.distributed_executor_backend}'.")
  599. if self.distributed_executor_backend is None and self.world_size > 1:
  600. from aphrodite.executor import ray_utils
  601. ray_found = ray_utils.ray is not None
  602. self.distributed_executor_backend = "ray" if ray_found else "mp"
  603. self._verify_args()
  604. def _verify_args(self) -> None:
  605. if self.pipeline_parallel_size > 1:
  606. raise NotImplementedError(
  607. "Pipeline parallelism is not supported yet.")
  608. if self.distributed_executor_backend not in ("ray", "mp", None):
  609. raise ValueError(
  610. "Unrecognized distributed executor backend. Supported values "
  611. "are 'ray' or 'mp'.")
  612. if not self.disable_custom_all_reduce and self.world_size > 1:
  613. if is_hip():
  614. self.disable_custom_all_reduce = True
  615. logger.info(
  616. "Disabled the custom all-reduce kernel because it is not "
  617. "supported on AMD GPUs.")
  618. elif self.pipeline_parallel_size > 1:
  619. self.disable_custom_all_reduce = True
  620. logger.info(
  621. "Disabled the custom all-reduce kernel because it is not "
  622. "supported with pipeline parallelism.")
  623. if self.ray_workers_use_nsight and (
  624. not self.distributed_executor_backend == "ray"):
  625. raise ValueError("Unable to use nsight profiling unless workers "
  626. "run with Ray.")
  627. class SchedulerConfig:
  628. """Scheduler configuration.
  629. Args:
  630. max_num_batched_tokens: Maximum number of tokens to be processed in
  631. a single iteration.
  632. max_num_seqs: Maximum number of sequences to be processed in a single
  633. iteration.
  634. max_model_len: Maximum length of a sequence (including prompt
  635. and generated text).
  636. use_v2_block_manager: Whether to use the BlockSpaceManagerV2 or not.
  637. num_lookahead_slots: The number of slots to allocate per sequence per
  638. step, beyond the known token ids. This is used in speculative
  639. decoding to store KV activations of tokens which may or may not be
  640. accepted.
  641. delay_factor: Apply a delay (of delay factor multiplied by previous
  642. prompt latency) before scheduling next prompt.
  643. enable_chunked_prefill: If True, prefill requests can be chunked based
  644. on the remaining max_num_batched_tokens.
  645. embedding_mode: Whether the running model is for embedding.
  646. """
  647. def __init__(
  648. self,
  649. max_num_batched_tokens: Optional[int],
  650. max_num_seqs: int,
  651. max_model_len: int,
  652. use_v2_block_manager: bool = False,
  653. num_lookahead_slots: int = 0,
  654. delay_factor: float = 0.0,
  655. enable_chunked_prefill: bool = False,
  656. embedding_mode: Optional[bool] = None,
  657. ) -> None:
  658. if max_num_batched_tokens is not None:
  659. self.max_num_batched_tokens = max_num_batched_tokens
  660. else:
  661. if enable_chunked_prefill:
  662. # For chunked prefill, choose the well-tuned batch size.
  663. self.max_num_batched_tokens = 768
  664. elif embedding_mode:
  665. # For embedding, choose specific value for higher throughput
  666. self.max_num_batched_tokens = max(
  667. max_model_len, _EMBEDDING_MODEL_MAX_NUM_BATCHED_TOKENS)
  668. else:
  669. # If max_model_len is too short, use 2048 as the default value
  670. # for higher throughput.
  671. self.max_num_batched_tokens = max(max_model_len, 2048)
  672. if enable_chunked_prefill:
  673. logger.info("Chunked prefill is enabled (EXPERIMENTAL).")
  674. self.max_num_seqs = max_num_seqs
  675. self.max_model_len = max_model_len
  676. self.use_v2_block_manager = use_v2_block_manager
  677. self.num_lookahead_slots = num_lookahead_slots
  678. self.delay_factor = delay_factor
  679. self.chunked_prefill_enabled = enable_chunked_prefill
  680. self.embedding_mode = embedding_mode
  681. self._verify_args()
  682. def _verify_args(self) -> None:
  683. if (self.max_num_batched_tokens < self.max_model_len
  684. and not self.chunked_prefill_enabled):
  685. raise ValueError(
  686. f"max_num_batched_tokens ({self.max_num_batched_tokens}) is "
  687. f"smaller than max_model_len ({self.max_model_len}). "
  688. "This effectively limits the maximum sequence length to "
  689. "max_num_batched_tokens and makes Aphrodite reject longer "
  690. "sequences. Please increase max_num_batched_tokens or "
  691. "decrease max_model_len.")
  692. if self.max_num_batched_tokens < self.max_num_seqs:
  693. raise ValueError(
  694. f"max_num_batched_tokens ({self.max_num_batched_tokens}) must "
  695. "be greater than or equal to max_num_seqs "
  696. f"({self.max_num_seqs}).")
  697. if self.num_lookahead_slots < 0:
  698. raise ValueError(
  699. "num_lookahead_slots "
  700. f"({self.num_lookahead_slots}) must be greater than or "
  701. "equal to 0.")
  702. class DeviceConfig:
  703. def __init__(self, device: str = "auto") -> None:
  704. if device == "auto":
  705. # Automated device type detection
  706. if is_neuron():
  707. self.device_type = "neuron"
  708. elif is_cpu():
  709. self.device_type = "cpu"
  710. else:
  711. # We don't call torch.cuda.is_available() here to
  712. # avoid initializing CUDA before workers are forked
  713. self.device_type = "cuda"
  714. else:
  715. # Device type is assigned explicitly
  716. self.device_type = device
  717. # Some device types require processing inputs on CPU
  718. if self.device_type in ["neuron"]:
  719. self.device = torch.device("cpu")
  720. else:
  721. # Set device with device type
  722. self.device = torch.device(self.device_type)
  723. class SpeculativeConfig:
  724. """Configuration for speculative decoding.
  725. The configuration is currently specialized to draft-model speculative
  726. decoding with top-1 proposals.
  727. """
  728. @staticmethod
  729. def maybe_create_spec_config(
  730. target_model_config: ModelConfig,
  731. target_parallel_config: ParallelConfig,
  732. target_dtype: str,
  733. speculative_model: Optional[str],
  734. num_speculative_tokens: Optional[int],
  735. speculative_max_model_len: Optional[int],
  736. enable_chunked_prefill: bool,
  737. use_v2_block_manager: bool,
  738. speculative_disable_by_batch_size: Optional[int],
  739. ngram_prompt_lookup_max: Optional[int],
  740. ngram_prompt_lookup_min: Optional[int],
  741. ) -> Optional["SpeculativeConfig"]:
  742. """Create a SpeculativeConfig if possible, else return None.
  743. This function attempts to create a SpeculativeConfig object based on the
  744. provided parameters. If the necessary conditions are met, it returns an
  745. instance of SpeculativeConfig. Otherwise, it returns None.
  746. Args:
  747. target_model_config (ModelConfig): The configuration of the target
  748. model.
  749. target_parallel_config (ParallelConfig): The parallel configuration
  750. for the target model.
  751. target_dtype (str): The data type used for the target model.
  752. speculative_model (Optional[str]): The name of the speculative
  753. model, if provided.
  754. num_speculative_tokens (Optional[int]): The number of speculative
  755. tokens, if provided.
  756. speculative_max_model_len (Optional[int]): The maximum model len of
  757. the speculative model. Used when testing the ability to skip
  758. speculation for some sequences.
  759. enable_chunked_prefill (bool): Whether Aphrodite is configured to
  760. use chunked prefill or not. Used for raising an error since its
  761. not yet compatible with spec decode.
  762. use_v2_block_manager (bool): Whether Aphrodite is configured to
  763. use the v2 block manager or not. Used for raising an error
  764. since the v2 block manager is required with spec decode.
  765. speculative_disable_by_batch_size (Optional[int]): Disable
  766. speculative decoding for new incoming requests when the number
  767. of enqueue requests is larger than this value, if provided.
  768. ngram_prompt_lookup_max (Optional[int]): Max size of ngram token
  769. window, if provided.
  770. ngram_prompt_lookup_min (Optional[int]): Min size of ngram token
  771. window, if provided.
  772. Returns:
  773. Optional["SpeculativeConfig"]: An instance of SpeculativeConfig if
  774. the necessary conditions are met, else None.
  775. """
  776. if speculative_model is None and num_speculative_tokens is None:
  777. return None
  778. if speculative_model is not None and num_speculative_tokens is None:
  779. raise ValueError(
  780. "Expected both speculative_model and "
  781. "num_speculative_tokens to be provided, but found "
  782. f"{speculative_model=} and {num_speculative_tokens=}.")
  783. if (speculative_disable_by_batch_size is not None
  784. and speculative_disable_by_batch_size < 2):
  785. raise ValueError("Expected the batch size threshold of disabling "
  786. "speculative decoding is > 1, but got "
  787. f"{speculative_disable_by_batch_size=}")
  788. assert (speculative_model is not None
  789. and num_speculative_tokens is not None)
  790. if enable_chunked_prefill:
  791. raise ValueError(
  792. "Speculative decoding and chunked prefill are "
  793. f"currently mutually exclusive ({enable_chunked_prefill=}).")
  794. if not use_v2_block_manager:
  795. raise ValueError(
  796. "Speculative decoding requires usage of the V2 "
  797. "block manager. Enable it with --use-v2-block-manager.")
  798. # TODO: The user should be able to specify revision/quantization/max
  799. # model len for the draft model. It is not currently supported.
  800. draft_revision = None
  801. draft_code_revision = None
  802. draft_quantization = None
  803. if speculative_model == "[ngram]":
  804. if ngram_prompt_lookup_min is None:
  805. ngram_prompt_lookup_min = 1
  806. if ngram_prompt_lookup_max is None or ngram_prompt_lookup_max < 1:
  807. raise ValueError(f"{ngram_prompt_lookup_max=} must be > 0")
  808. if ngram_prompt_lookup_min < 1:
  809. raise ValueError(f"{ngram_prompt_lookup_min=} must be > 0")
  810. if ngram_prompt_lookup_min > ngram_prompt_lookup_max:
  811. raise ValueError(f"{ngram_prompt_lookup_min=} cannot be "
  812. f"larger than {ngram_prompt_lookup_max=}")
  813. # TODO: current we still need extract vocab_size from target model
  814. # config, in future, we may try refactoring it out, and set
  815. # draft related config as None here.
  816. draft_model_config = target_model_config
  817. draft_parallel_config = target_parallel_config
  818. else:
  819. ngram_prompt_lookup_max = 0
  820. ngram_prompt_lookup_min = 0
  821. draft_model_config = ModelConfig(
  822. model=speculative_model,
  823. tokenizer=target_model_config.tokenizer,
  824. tokenizer_mode=target_model_config.tokenizer_mode,
  825. trust_remote_code=target_model_config.trust_remote_code,
  826. dtype=target_model_config.dtype,
  827. seed=target_model_config.seed,
  828. revision=draft_revision,
  829. code_revision=draft_code_revision,
  830. tokenizer_revision=target_model_config.tokenizer_revision,
  831. max_model_len=None,
  832. quantization=draft_quantization,
  833. enforce_eager=target_model_config.enforce_eager,
  834. max_seq_len_to_capture=target_model_config.
  835. max_seq_len_to_capture,
  836. max_logprobs=target_model_config.max_logprobs,
  837. )
  838. draft_model_config.max_model_len = (
  839. SpeculativeConfig._maybe_override_draft_max_model_len(
  840. speculative_max_model_len,
  841. draft_model_config.max_model_len,
  842. target_model_config.max_model_len,
  843. ))
  844. draft_parallel_config = (
  845. SpeculativeConfig.create_draft_parallel_config(
  846. target_parallel_config))
  847. return SpeculativeConfig(draft_model_config, draft_parallel_config,
  848. num_speculative_tokens,
  849. speculative_disable_by_batch_size,
  850. ngram_prompt_lookup_max,
  851. ngram_prompt_lookup_min)
  852. @staticmethod
  853. def _maybe_override_draft_max_model_len(
  854. speculative_max_model_len: Optional[int],
  855. draft_max_model_len: int,
  856. target_max_model_len: int,
  857. ) -> int:
  858. """Determine the max sequence len for the draft model. This is usually
  859. the draft_max_model_len, but may be the target_max_model_len if it is
  860. less than the draft_max_model_len, or may be speculative_max_model_len
  861. if it is specified.
  862. This is necessary so that sequences do not exceed the capacity of the
  863. draft model or the target model.
  864. speculative_max_model_len is mainly used for testing that sequences can
  865. skip speculation.
  866. """
  867. if speculative_max_model_len is not None:
  868. if speculative_max_model_len > draft_max_model_len:
  869. raise ValueError(f"{speculative_max_model_len=} cannot be "
  870. f"larger than {draft_max_model_len=}")
  871. if speculative_max_model_len > target_max_model_len:
  872. raise ValueError(f"{speculative_max_model_len=} cannot be "
  873. f"larger than {target_max_model_len=}")
  874. return speculative_max_model_len
  875. return min(
  876. draft_max_model_len,
  877. target_max_model_len,
  878. )
  879. @staticmethod
  880. def create_draft_parallel_config(
  881. target_parallel_config: ParallelConfig) -> ParallelConfig:
  882. """Create a parallel config for use by the draft worker.
  883. This is mostly a copy of the target parallel config. In the future the
  884. draft worker can have a different parallel strategy, e.g. TP=1.
  885. """
  886. draft_parallel_config = ParallelConfig(
  887. pipeline_parallel_size=target_parallel_config.
  888. pipeline_parallel_size,
  889. tensor_parallel_size=target_parallel_config.tensor_parallel_size,
  890. distributed_executor_backend=target_parallel_config.
  891. distributed_executor_backend,
  892. max_parallel_loading_workers=target_parallel_config.
  893. max_parallel_loading_workers,
  894. disable_custom_all_reduce=target_parallel_config.
  895. disable_custom_all_reduce,
  896. tokenizer_pool_config=target_parallel_config.tokenizer_pool_config,
  897. ray_workers_use_nsight=target_parallel_config.
  898. ray_workers_use_nsight,
  899. placement_group=target_parallel_config.placement_group,
  900. )
  901. return draft_parallel_config
  902. def __init__(
  903. self,
  904. draft_model_config: ModelConfig,
  905. draft_parallel_config: ParallelConfig,
  906. num_speculative_tokens: int,
  907. speculative_disable_by_batch_size: Optional[int],
  908. ngram_prompt_lookup_max: Optional[int],
  909. ngram_prompt_lookup_min: Optional[int],
  910. ):
  911. """Create a SpeculativeConfig object.
  912. Args:
  913. draft_model_config: ModelConfig for the draft model.
  914. draft_parallel_config: ParallelConfig for the draft model.
  915. num_speculative_tokens: The number of tokens to sample from the
  916. draft model before scoring with the target model.
  917. speculative_disable_by_batch_size: Disable speculative
  918. decoding for new incoming requests when the number of
  919. enqueue requests is larger than this value.
  920. ngram_prompt_lookup_max: Max size of ngram token window.
  921. ngram_prompt_lookup_min: Min size of ngram token window.
  922. """
  923. self.draft_model_config = draft_model_config
  924. self.draft_parallel_config = draft_parallel_config
  925. self.num_speculative_tokens = num_speculative_tokens
  926. self.speculative_disable_by_batch_size = \
  927. speculative_disable_by_batch_size
  928. self.ngram_prompt_lookup_max = ngram_prompt_lookup_max or 0
  929. self.ngram_prompt_lookup_min = ngram_prompt_lookup_min or 0
  930. self._verify_args()
  931. def _verify_args(self) -> None:
  932. if self.num_speculative_tokens <= 0:
  933. raise ValueError("Expected num_speculative_tokens to be greater "
  934. f"than zero ({self.num_speculative_tokens}).")
  935. if self.draft_model_config:
  936. self.draft_model_config.verify_with_parallel_config(
  937. self.draft_parallel_config)
  938. @property
  939. def num_lookahead_slots(self) -> int:
  940. """The number of additional slots the scheduler should allocate per
  941. step, in addition to the slots allocated for each known token.
  942. This is equal to the number of speculative tokens, as each speculative
  943. token must be scored.
  944. """
  945. return self.num_speculative_tokens
  946. def __repr__(self) -> str:
  947. if self.ngram_prompt_lookup_max > 0:
  948. draft_model = "[ngram]"
  949. else:
  950. draft_model = self.draft_model_config.model
  951. num_spec_tokens = self.num_speculative_tokens
  952. return f"SpeculativeConfig({draft_model=}, {num_spec_tokens=})"
  953. @dataclass
  954. class LoRAConfig:
  955. max_lora_rank: int
  956. max_loras: int
  957. fully_sharded_loras: bool = False
  958. max_cpu_loras: Optional[int] = None
  959. lora_dtype: Optional[torch.dtype] = None
  960. lora_extra_vocab_size: int = 256
  961. # This is a constant.
  962. lora_vocab_padding_size: ClassVar[int] = 256
  963. long_lora_scaling_factors: Optional[Tuple[float]] = None
  964. def __post_init__(self):
  965. # Keep this in sync with kernels/punica/bgmv/bgmv_config.h
  966. possible_max_ranks = (8, 16, 32, 64)
  967. possible_lora_extra_vocab_size = (0, 256, 512)
  968. if self.max_lora_rank not in possible_max_ranks:
  969. raise ValueError(
  970. f"max_lora_rank ({self.max_lora_rank}) must be one of "
  971. f"{possible_max_ranks}.")
  972. if self.lora_extra_vocab_size not in possible_lora_extra_vocab_size:
  973. raise ValueError(
  974. f"lora_extra_vocab_size ({self.lora_extra_vocab_size}) "
  975. f"must be one of {possible_lora_extra_vocab_size}.")
  976. if self.max_loras < 1:
  977. raise ValueError(f"max_loras ({self.max_loras}) must be >= 1.")
  978. if self.max_cpu_loras is None:
  979. self.max_cpu_loras = self.max_loras
  980. elif self.max_cpu_loras < self.max_loras:
  981. raise ValueError(
  982. f"max_cpu_loras ({self.max_cpu_loras}) must be >= "
  983. f"max_loras ({self.max_loras})")
  984. def verify_with_model_config(self, model_config: ModelConfig):
  985. if self.lora_dtype in (None, "auto"):
  986. self.lora_dtype = model_config.dtype
  987. elif isinstance(self.lora_dtype, str):
  988. self.lora_dtype = getattr(torch, self.lora_dtype)
  989. if model_config.quantization and model_config.quantization not in [
  990. "awq", "gptq"
  991. ]:
  992. # TODO support all other quants
  993. logger.warning(f"{model_config.quantization} quantization is not "
  994. "tested with LoRA yet.")
  995. def verify_with_scheduler_config(self, scheduler_config: SchedulerConfig):
  996. if scheduler_config.max_num_batched_tokens > 65528:
  997. raise ValueError(
  998. "Due to limitations of the custom LoRA CUDA kernel, "
  999. "max_num_batched_tokens must be <= 65528 when "
  1000. "LoRA is enabled.")
  1001. @dataclass
  1002. class VisionLanguageConfig:
  1003. """Configs the input data format and how models should run for
  1004. vision language models."""
  1005. class ImageInputType(enum.Enum):
  1006. """Image input type into the vision language model.
  1007. An image roughly goes through the following transformation:
  1008. Raw image --> pixel values --> image features --> image embeddings.
  1009. The difference between different image input types is where the
  1010. image encoder (pixel values --> image features) is run.
  1011. Different image input types also correspond to different tensor shapes.
  1012. For example, for Llava, PIXEL_VALUES: (1, 3, 336, 336).
  1013. IMAGE_FEATURES: (1, 576, 1024).
  1014. """
  1015. PIXEL_VALUES = enum.auto()
  1016. IMAGE_FEATURES = enum.auto()
  1017. image_input_type: ImageInputType
  1018. # The input id corresponding to image token.
  1019. image_token_id: int
  1020. # Used for running `run_prefill_max_token`.
  1021. # For models that support varying resolution, this corresponds to
  1022. # worst case scenario (biggest supported resolution).
  1023. image_input_shape: tuple
  1024. image_feature_size: int
  1025. @classmethod
  1026. def get_image_input_enum_type(
  1027. cls, value: str) -> "VisionLanguageConfig.ImageInputType":
  1028. """Get the image input type from a string."""
  1029. try:
  1030. return cls.ImageInputType[value.upper()]
  1031. except KeyError as e:
  1032. raise ValueError(f"{value} is not a valid choice. "
  1033. f"Expecting to choose from "
  1034. f"{[x.name for x in cls.ImageInputType]}.") from e
  1035. _STR_DTYPE_TO_TORCH_DTYPE = {
  1036. "half": torch.float16,
  1037. "float16": torch.float16,
  1038. "float": torch.float32,
  1039. "float32": torch.float32,
  1040. "bfloat16": torch.bfloat16,
  1041. }
  1042. _ROCM_NOT_SUPPORTED_DTYPE = ["float", "float32"]
  1043. def _get_and_verify_dtype(
  1044. config: PretrainedConfig,
  1045. dtype: Union[str, torch.dtype],
  1046. ) -> torch.dtype:
  1047. # NOTE: getattr(config, "torch_dtype", torch.float32) is not correct
  1048. # because config.torch_dtype can be None.
  1049. config_dtype = getattr(config, "torch_dtype", None)
  1050. if config_dtype is None:
  1051. config_dtype = torch.float32
  1052. if isinstance(dtype, str):
  1053. dtype = dtype.lower()
  1054. if dtype == "auto":
  1055. if config_dtype == torch.float32:
  1056. # Following the common practice, we use float16 for float32
  1057. # models.
  1058. torch_dtype = torch.float16
  1059. else:
  1060. torch_dtype = config_dtype
  1061. else:
  1062. if dtype not in _STR_DTYPE_TO_TORCH_DTYPE:
  1063. raise ValueError(f"Unknown dtype: {dtype}")
  1064. torch_dtype = _STR_DTYPE_TO_TORCH_DTYPE[dtype]
  1065. elif isinstance(dtype, torch.dtype):
  1066. torch_dtype = dtype
  1067. else:
  1068. raise ValueError(f"Unknown dtype: {dtype}")
  1069. if is_hip() and torch_dtype == torch.float32:
  1070. rocm_supported_dtypes = [
  1071. k for k, v in _STR_DTYPE_TO_TORCH_DTYPE.items()
  1072. if (k not in _ROCM_NOT_SUPPORTED_DTYPE)
  1073. ]
  1074. raise ValueError(f"dtype '{dtype}' is not supported in ROCm. "
  1075. f"Supported dtypes are {rocm_supported_dtypes}")
  1076. # Verify the dtype.
  1077. if torch_dtype != config_dtype:
  1078. if torch_dtype == torch.float32:
  1079. # Upcasting to float32 is allowed.
  1080. pass
  1081. elif config_dtype == torch.float32:
  1082. # Downcasting from float32 to float16 or bfloat16 is allowed.
  1083. pass
  1084. else:
  1085. # Casting between float16 and bfloat16 is allowed with a warning.
  1086. logger.warning(f"Casting {config_dtype} to {torch_dtype}.")
  1087. return torch_dtype
  1088. def _get_and_verify_max_len(
  1089. hf_config: PretrainedConfig,
  1090. max_model_len: Optional[int],
  1091. disable_sliding_window: bool,
  1092. sliding_window_len: Optional[int],
  1093. ) -> int:
  1094. """Get and verify the model's maximum length."""
  1095. derived_max_model_len = float("inf")
  1096. possible_keys = [
  1097. # Cohere: needs to prioritize this over "max_position_embeddings"
  1098. "model_max_length",
  1099. # OPT
  1100. "max_position_embeddings",
  1101. # GPT-2
  1102. "n_positions",
  1103. # MPT
  1104. "max_seq_len",
  1105. # ChatGLM2
  1106. "seq_length",
  1107. # Command-R
  1108. "model_max_length",
  1109. # Others
  1110. "max_sequence_length",
  1111. "max_seq_length",
  1112. "seq_len",
  1113. ]
  1114. # Choose the smallest "max_length" from the possible keys.
  1115. max_len_key = None
  1116. for key in possible_keys:
  1117. max_len = getattr(hf_config, key, None)
  1118. if max_len is not None:
  1119. max_len_key = key if max_len < derived_max_model_len \
  1120. else max_len_key
  1121. derived_max_model_len = min(derived_max_model_len, max_len)
  1122. # If sliding window is manually disabled, max_length should be less
  1123. # than the sliding window length in the model config.
  1124. if disable_sliding_window and sliding_window_len is not None:
  1125. max_len_key = "sliding_window" \
  1126. if sliding_window_len < derived_max_model_len else max_len_key
  1127. derived_max_model_len = min(derived_max_model_len, sliding_window_len)
  1128. # If none of the keys were found in the config, use a default and
  1129. # log a warning.
  1130. if derived_max_model_len == float("inf"):
  1131. if max_model_len is not None:
  1132. # If max_model_len is specified, we use it.
  1133. return max_model_len
  1134. default_max_len = 2048
  1135. logger.warning(
  1136. "The model's config.json does not contain any of the following "
  1137. "keys to determine the original maximum length of the model: "
  1138. f"{possible_keys}. Assuming the model's maximum length is "
  1139. f"{default_max_len}.")
  1140. derived_max_model_len = default_max_len
  1141. rope_scaling = getattr(hf_config, "rope_scaling", None)
  1142. if rope_scaling is not None:
  1143. rope_type = rope_scaling.get("type", rope_scaling.get("rope_type"))
  1144. if rope_type not in {"su", "longrope", "llama3"}:
  1145. if disable_sliding_window:
  1146. # TODO: Find a model that supports rope_scaling
  1147. # with sliding window to see if this case should be allowed.
  1148. raise NotImplementedError(
  1149. "Disabling sliding window is not supported for models "
  1150. "with rope_scaling. Please raise an issue so we can "
  1151. "investigate.")
  1152. assert "factor" in rope_scaling
  1153. scaling_factor = rope_scaling["factor"]
  1154. if rope_type == "yarn":
  1155. derived_max_model_len = rope_scaling[
  1156. "original_max_position_embeddings"]
  1157. derived_max_model_len *= scaling_factor
  1158. if max_model_len is None:
  1159. max_model_len = derived_max_model_len
  1160. elif max_model_len > derived_max_model_len:
  1161. # hope this works
  1162. scaling_factor = max_model_len / derived_max_model_len
  1163. hf_config.rope_scaling = {"factor": scaling_factor, "type": "dynamic"}
  1164. logger.warning(
  1165. f"User-specified max_model_len {max_model_len} is higher than "
  1166. f"the original {derived_max_model_len}. "
  1167. "Attempting to use RoPE scaling.")
  1168. derived_max_model_len = max_model_len
  1169. return int(max_model_len)
  1170. @dataclass
  1171. class DecodingConfig:
  1172. """Dataclass which contains the decoding strategy of the engine"""
  1173. # Which guided decoding algo to use. 'outlines' / 'lm-format-enforcer'
  1174. guided_decoding_backend: str = 'outlines'
  1175. def __post_init__(self):
  1176. valid_guided_backends = ['outlines', 'lm-format-enforcer']
  1177. backend = self.guided_decoding_backend
  1178. if backend not in valid_guided_backends:
  1179. raise ValueError(f"Invalid guided_decoding_backend '{backend},"
  1180. f"must be one of {valid_guided_backends}")
  1181. @dataclass(frozen=True)
  1182. class EngineConfig:
  1183. """Dataclass which contains all engine-related configuration. This
  1184. simplifies passing around the distinct configurations in the codebase.
  1185. """
  1186. model_config: ModelConfig
  1187. cache_config: CacheConfig
  1188. parallel_config: ParallelConfig
  1189. scheduler_config: SchedulerConfig
  1190. device_config: DeviceConfig
  1191. load_config: LoadConfig
  1192. lora_config: Optional[LoRAConfig]
  1193. vision_language_config: Optional[VisionLanguageConfig]
  1194. speculative_config: Optional[SpeculativeConfig]
  1195. decoding_config: Optional[DecodingConfig]
  1196. def __post_init__(self):
  1197. """Verify configs are valid & consistent with each other.
  1198. """
  1199. self.model_config.verify_with_parallel_config(self.parallel_config)
  1200. self.cache_config.verify_with_parallel_config(self.parallel_config)
  1201. if self.lora_config:
  1202. self.lora_config.verify_with_model_config(self.model_config)
  1203. self.lora_config.verify_with_scheduler_config(
  1204. self.scheduler_config)
  1205. def to_dict(self):
  1206. """Return the configs as a dictionary, for use in **kwargs.
  1207. """
  1208. return dict(
  1209. (field.name, getattr(self, field.name)) for field in fields(self))