config.py 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938
  1. import enum
  2. import json
  3. import os
  4. from dataclasses import dataclass, field, fields
  5. from typing import (TYPE_CHECKING, Any, ClassVar, Dict, List, Mapping,
  6. Optional, Tuple, Type, Union)
  7. import torch
  8. from loguru import logger
  9. from transformers import PretrainedConfig
  10. import aphrodite.common.envs as envs
  11. from aphrodite.common.utils import (STR_NOT_IMPL_ENC_DEC_CUDAGRAPH, GiB_bytes,
  12. cuda_device_count_stateless,
  13. get_cpu_memory, is_cpu, is_hip, is_neuron,
  14. is_openvino, is_xpu, print_warning_once)
  15. from aphrodite.distributed import get_current_tp_rank_partition_size
  16. from aphrodite.modeling.models import ModelRegistry
  17. from aphrodite.platforms import current_platform
  18. from aphrodite.quantization import QUANTIZATION_METHODS
  19. from aphrodite.transformers_utils.config import (ConfigFormat, get_config,
  20. get_hf_text_config)
  21. from aphrodite.triton_utils import HAS_TRITON
  22. if TYPE_CHECKING:
  23. from ray.util.placement_group import PlacementGroup
  24. from aphrodite.executor.executor_base import ExecutorBase
  25. from aphrodite.modeling.model_loader.loader import BaseModelLoader
  26. from aphrodite.transformers_utils.tokenizer_group.base_tokenizer_group import ( # noqa: E501
  27. BaseTokenizerGroup)
  28. # If true, will load models from ModelScope instead of Hugging Face Hub.
  29. APHRODITE_USE_MODELSCOPE = envs.APHRODITE_USE_MODELSCOPE
  30. _EMBEDDING_MODEL_MAX_NUM_BATCHED_TOKENS = 32768
  31. _PP_SUPPORTED_MODELS = [
  32. "AquilaModel",
  33. "AquilaForCausalLM",
  34. "InternLMForCausalLM",
  35. "LlamaForCausalLM",
  36. "LLaMAForCausalLM",
  37. "MistralForCausalLM",
  38. "Phi3ForCausalLM",
  39. "MixtralForCausalLM",
  40. "NemotronForCausalLM",
  41. "Qwen2ForCausalLM",
  42. "Qwen2MoeForCausalLM",
  43. ]
  44. _OPTIMIZED_QUANTS = [
  45. "fp2",
  46. "fp3",
  47. "fp4",
  48. "fp5",
  49. "fp6",
  50. "fp7",
  51. "fp8",
  52. "marlin",
  53. "gptq_marlin_24",
  54. "gptq_marlin",
  55. "awq_marlin",
  56. "fbgemm_fp8",
  57. "compressed-tensors",
  58. "compressed_tensors",
  59. "experts_int8",
  60. "quant_llm",
  61. ]
  62. class ModelConfig:
  63. """Configuration for the model.
  64. Args:
  65. model: Name or path of the huggingface model to use.
  66. It is also used as the content for `model_name` tag in metrics
  67. output when `served_model_name` is not specified.
  68. tokenizer: Name or path of the huggingface tokenizer to use.
  69. tokenizer_mode: Tokenizer mode. "auto" will use the fast tokenizer if
  70. available, "slow" will always use the slow tokenizer, and
  71. "mistral" will always use the tokenizer from `mistral_common`.
  72. trust_remote_code: Trust remote code (e.g., from HuggingFace) when
  73. downloading the model and tokenizer.
  74. dtype: Data type for model weights and activations. The "auto" option
  75. will use FP16 precision for FP32 and FP16 models, and BF16 precision
  76. for BF16 models.
  77. seed: Random seed for reproducibility.
  78. revision: The specific model version to use. It can be a branch name,
  79. a tag name, or a commit id. If unspecified, will use the default
  80. version.
  81. code_revision: The specific revision to use for the model code on
  82. Hugging Face Hub. It can be a branch name, a tag name, or a
  83. commit id. If unspecified, will use the default version.
  84. rope_scaling: Dictionary containing the scaling configuration for the
  85. RoPE embeddings. When using this flag, don't update
  86. `max_position_embeddings` to the expected new maximum.
  87. tokenizer_revision: The specific tokenizer version to use. It can be a
  88. branch name, a tag name, or a commit id. If unspecified, will use
  89. the default version.
  90. max_model_len: Maximum length of a sequence (including prompt and
  91. output). If None, will be derived from the model.
  92. quantization: Quantization method that was used to quantize the model
  93. weights. If None, we assume the model weights are not quantized.
  94. deepspeed_fp_bits: Number of bits to use for DeepSpeed FP quantization.
  95. Supported number of bits are: 4, 6, 8, 12.
  96. quant_llm_fp_bits: Number of bits to use for QuantLLM FP quantization.
  97. Supported number of bits are: 5, 6, 7.
  98. quantization_param_path: Path to JSON file containing scaling factors.
  99. Used to load KV cache scaling factors into the model when KV cache
  100. type is FP8_E4M3 on ROCm (AMD GPU). In the future these will also
  101. be used to load activation and weight scaling factors when the
  102. model dtype is FP8_E4M3 on ROCm.
  103. enforce_eager: Whether to enforce eager execution. If True, we will
  104. disable CUDA graph and always execute the model in eager mode.
  105. If False, we will use CUDA graph and eager execution in hybrid.
  106. If None, the user did not specify, so default to False -
  107. except for encoder/decoder models, which currently require
  108. eager mode.
  109. max_context_len_to_capture: Maximum context len covered by CUDA graphs.
  110. When a sequence has context length larger than this, we fall back
  111. to eager mode (DEPRECATED. Use max_seq_len_to_capture instead).
  112. max_seq_len_to_capture: Maximum sequence len covered by CUDA graphs.
  113. When a sequence has context length larger than this, we fall back
  114. to eager mode
  115. disable_sliding_window: Whether to disable sliding window. If True,
  116. we will disable the sliding window functionality of the model.
  117. If the model does not support sliding window, this argument is
  118. ignored.
  119. skip_tokenizer_init: If true, skip initialization of tokenizer and
  120. detokenizer.
  121. served_model_name: The model name used in metrics tag `model_name`,
  122. matches the model name exposed via the APIs. If multiple model
  123. names provided, the first name will be used. If not specified,
  124. the model name will be the same as `model`.
  125. limit_mm_per_prompt: Maximum number of data instances per modality
  126. per prompt. Only applicable for multimodal models.
  127. config_format: The config format which will be loaded. Defaults to
  128. 'auto' which defaults to 'hf'.
  129. """
  130. def __init__(
  131. self,
  132. model: str,
  133. tokenizer: str,
  134. tokenizer_mode: str,
  135. trust_remote_code: bool,
  136. dtype: Union[str, torch.dtype],
  137. seed: int,
  138. revision: Optional[str] = None,
  139. code_revision: Optional[str] = None,
  140. rope_scaling: Optional[dict] = None,
  141. rope_theta: Optional[float] = None,
  142. tokenizer_revision: Optional[str] = None,
  143. max_model_len: Optional[int] = None,
  144. spec_target_max_model_len: Optional[int] = None,
  145. quantization: Optional[str] = None,
  146. deepspeed_fp_bits: Optional[int] = None,
  147. quant_llm_fp_bits: Optional[int] = None,
  148. quant_llm_exp_bits: Optional[int] = None,
  149. quantization_param_path: Optional[str] = None,
  150. enforce_eager: Optional[bool] = None,
  151. max_context_len_to_capture: Optional[int] = None,
  152. max_seq_len_to_capture: Optional[int] = None,
  153. max_logprobs: int = 5,
  154. disable_sliding_window: bool = False,
  155. skip_tokenizer_init: bool = False,
  156. served_model_name: Optional[Union[str, List[str]]] = None,
  157. limit_mm_per_prompt: Optional[Mapping[str, int]] = None,
  158. config_format: ConfigFormat = ConfigFormat.AUTO,
  159. ) -> None:
  160. self.model = model
  161. self.tokenizer = tokenizer
  162. self.tokenizer_mode = tokenizer_mode
  163. self.trust_remote_code = trust_remote_code
  164. self.seed = seed
  165. self.revision = revision
  166. self.code_revision = code_revision
  167. self.rope_scaling = rope_scaling
  168. self.rope_theta = rope_theta
  169. # The tokenizer version is consistent with the model version by default.
  170. if tokenizer_revision is None:
  171. self.tokenizer_revision = revision
  172. else:
  173. self.tokenizer_revision = tokenizer_revision
  174. self.quantization = quantization
  175. self.deepspeed_fp_bits = deepspeed_fp_bits
  176. self.quant_llm_fp_bits = quant_llm_fp_bits
  177. self.quant_llm_exp_bits = quant_llm_exp_bits
  178. self.quantization_param_path = quantization_param_path
  179. self.enforce_eager = enforce_eager
  180. self.max_context_len_to_capture = max_context_len_to_capture
  181. if self.max_context_len_to_capture is not None:
  182. raise ValueError("`max_context_len_to_capture` is deprecated. "
  183. "Use `max_seq_len_to_capture` instead.")
  184. self.max_seq_len_to_capture = (max_seq_len_to_capture
  185. or max_context_len_to_capture)
  186. self.max_logprobs = max_logprobs
  187. self.disable_sliding_window = disable_sliding_window
  188. self.skip_tokenizer_init = skip_tokenizer_init
  189. self.hf_config = get_config(self.model, trust_remote_code, revision,
  190. code_revision, rope_scaling, rope_theta,
  191. config_format)
  192. self.hf_text_config = get_hf_text_config(self.hf_config)
  193. self.dtype = _get_and_verify_dtype(self.hf_text_config, dtype)
  194. # Choose a default enforce_eager value if the user did not specify
  195. # a value (enforce_eager is None)
  196. if getattr(self.hf_config, 'is_encoder_decoder', False):
  197. if self.enforce_eager is None:
  198. # *Only for encoder/decoder models* and
  199. # *only if enforce_eager is unset*, override
  200. # to enforce_eager=True
  201. #
  202. # Add a logger message since it is *somewhat* non-intuitive that
  203. # enforce_eager is True when the user has not specified its
  204. # value.
  205. logger.info("Forcing enforce_eager == True because "
  206. "enforce_eager setting was unspecified and "
  207. "CUDAGraph is not supported with encoder/ "
  208. "decoder models.")
  209. self.enforce_eager = True
  210. if not self.enforce_eager:
  211. # Eager mode explicitly disabled by user for an encoder/
  212. # decoder model; however CUDAGRAPH + encoder/decoder is
  213. # not currently supported
  214. raise ValueError(STR_NOT_IMPL_ENC_DEC_CUDAGRAPH)
  215. elif self.enforce_eager is None:
  216. # *Only for decoder-only models*, enforce_eager
  217. # defaults to False if unset. This is intuitive
  218. # so no logging message needed.
  219. self.enforce_eager = False
  220. sliding_window = getattr(self.hf_text_config, "sliding_window", None)
  221. has_interleaved_attention = (sliding_window is not None) and (
  222. isinstance(sliding_window, list) or
  223. (self.hf_text_config.model_type in ["gemma2"]))
  224. if (not self.disable_sliding_window and has_interleaved_attention):
  225. sliding_window_len_min = get_min_sliding_window(
  226. self.hf_text_config.sliding_window)
  227. print_warning_once(
  228. f"{self.hf_text_config.model_type} has interleaved attention, "
  229. "which is currently not supported by vLLM. Disabling sliding "
  230. "window and capping the max length to the sliding window size "
  231. f"({sliding_window_len_min}).")
  232. self.disable_sliding_window = True
  233. self.max_model_len = _get_and_verify_max_len(
  234. hf_config=self.hf_text_config,
  235. max_model_len=max_model_len,
  236. disable_sliding_window=self.disable_sliding_window,
  237. sliding_window_len=self.get_hf_config_sliding_window(),
  238. spec_target_max_model_len=spec_target_max_model_len,
  239. rope_scaling_arg=self.rope_scaling)
  240. self.served_model_name = get_served_model_name(model,
  241. served_model_name)
  242. self.multimodal_config = self._init_multimodal_config(
  243. limit_mm_per_prompt)
  244. if not self.skip_tokenizer_init:
  245. self._verify_tokenizer_mode()
  246. self._verify_embedding_mode()
  247. self._verify_quantization()
  248. self._verify_cuda_graph()
  249. def _init_multimodal_config(
  250. self, limit_mm_per_prompt: Optional[Mapping[str, int]]
  251. ) -> Optional["MultiModalConfig"]:
  252. architectures = getattr(self.hf_config, "architectures", [])
  253. if any(
  254. ModelRegistry.is_multimodal_model(arch)
  255. for arch in architectures):
  256. return MultiModalConfig(limit_per_prompt=limit_mm_per_prompt or {})
  257. else:
  258. if limit_mm_per_prompt:
  259. raise ValueError(
  260. "limit_mm_per_prompt is only supported for multimodal "
  261. "models.")
  262. return None
  263. def _verify_tokenizer_mode(self) -> None:
  264. tokenizer_mode = self.tokenizer_mode.lower()
  265. if tokenizer_mode not in ["auto", "slow", "mistral"]:
  266. raise ValueError(
  267. f"Unknown tokenizer mode: {self.tokenizer_mode}. Must be "
  268. "either 'auto', 'slow' or 'mistral'.")
  269. self.tokenizer_mode = tokenizer_mode
  270. def _verify_embedding_mode(self) -> None:
  271. architectures = getattr(self.hf_config, "architectures", [])
  272. self.embedding_mode = any(
  273. ModelRegistry.is_embedding_model(arch) for arch in architectures)
  274. def _parse_quant_hf_config(self):
  275. quant_cfg = getattr(self.hf_config, "quantization_config", None)
  276. if quant_cfg is None:
  277. # compress-tensors uses a "compression_config" key
  278. quant_cfg = getattr(self.hf_config, "compression_config", None)
  279. return quant_cfg
  280. def _verify_quantization(self) -> None:
  281. supported_quantization = [*QUANTIZATION_METHODS]
  282. rocm_supported_quantization = ["gptq", "squeezellm", "fp8"]
  283. tpu_supported_quantization = ["tpu_int8"]
  284. if self.quantization is not None:
  285. self.quantization = self.quantization.lower()
  286. # Parse quantization method from the HF model config, if available.
  287. quant_cfg = self._parse_quant_hf_config()
  288. if quant_cfg is not None:
  289. quant_method = quant_cfg.get("quant_method", "").lower()
  290. # Detect which checkpoint is it
  291. for _, method in QUANTIZATION_METHODS.items():
  292. quantization_override = method.override_quantization_method(
  293. quant_cfg, self.quantization)
  294. if quantization_override:
  295. if quantization_override == "awq_marlin":
  296. quant_method = quant_method
  297. logger.warning(
  298. "awq_marlin kernels are temporarily disabled, "
  299. "they will be re-enabled with a future release. "
  300. "Falling back to AWQ kernels.")
  301. else:
  302. quant_method = quantization_override
  303. self.quantization = quantization_override
  304. break
  305. # Verify quantization configurations.
  306. if self.quantization is None:
  307. self.quantization = quant_method
  308. elif self.quantization != quant_method:
  309. raise ValueError(
  310. "Quantization method specified in the model config "
  311. f"({quant_method}) does not match the quantization "
  312. f"method specified in the `quantization` argument "
  313. f"({self.quantization}).")
  314. if self.quantization == "deepspeedfp":
  315. gs = 32 if self.deepspeed_fp_bits == 4 else 128
  316. self.hf_config.quantization_config = {
  317. "bits": self.deepspeed_fp_bits,
  318. "group_size": int(os.environ.get("DEEPSPEED_GROUP_SIZE", gs)),
  319. "quant_method": "deepspeedfp"
  320. }
  321. VALID_QUANT_LLM_FP_BITS = [2, 3, 4, 5, 6, 7]
  322. VALID_QUANT_LLM_EXPONENTS = [1, 2, 3, 4, 5]
  323. # The formula is mantissa_bits = fp_bits - exp_bits - 1
  324. # The default exp_bits for each fp_bits are as follows:
  325. DEFAULT_EXP_BITS = {
  326. 2: 1,
  327. 3: 2,
  328. 4: 2,
  329. 5: 2,
  330. 6: 2,
  331. 7: 3,
  332. }
  333. if self.quantization == "quant_llm":
  334. if self.quant_llm_fp_bits is None:
  335. raise ValueError(
  336. "quant_llm_fp_bits must be specified when using "
  337. "quant_llm quantization."
  338. )
  339. if self.quant_llm_fp_bits not in VALID_QUANT_LLM_FP_BITS:
  340. raise ValueError(
  341. f"Invalid quant_llm_fp_bits: {self.quant_llm_fp_bits}. "
  342. f"Must be one of {VALID_QUANT_LLM_FP_BITS}."
  343. )
  344. if self.quant_llm_exp_bits is None:
  345. self.quant_llm_exp_bits = DEFAULT_EXP_BITS[
  346. self.quant_llm_fp_bits]
  347. else:
  348. if self.quant_llm_exp_bits not in VALID_QUANT_LLM_EXPONENTS:
  349. raise ValueError(
  350. f"Invalid exponent bits: {self.quant_llm_exp_bits}. "
  351. f"Must be one of {VALID_QUANT_LLM_EXPONENTS}."
  352. )
  353. self.hf_config.quantization_config = {
  354. "bits": self.quant_llm_fp_bits,
  355. "exp_bits": self.quant_llm_exp_bits,
  356. "quant_method": "quant_llm"
  357. }
  358. online_quant_methods = ["fp2", "fp3", "fp4", "fp5", "fp6", "fp7"]
  359. if self.quantization is not None and self.quantization in \
  360. online_quant_methods:
  361. fp_bits = int(self.quantization[2])
  362. if fp_bits not in VALID_QUANT_LLM_FP_BITS:
  363. raise ValueError(
  364. f"Invalid quant_llm_fp_bits: {fp_bits}. "
  365. f"Must be one of {VALID_QUANT_LLM_FP_BITS}."
  366. )
  367. if fp_bits in [2, 3]:
  368. logger.warning("FP2 and FP3 quantization methods lead to "
  369. "significant accuracy loss. Use them with "
  370. "caution. Model may be incoherent.")
  371. exp_bits = DEFAULT_EXP_BITS[fp_bits]
  372. self.hf_config.quantization_config = {
  373. "bits": fp_bits,
  374. "exp_bits": exp_bits,
  375. "quant_method": self.quantization
  376. }
  377. self.dtype = torch.float16
  378. self.enforce_eager = True
  379. if self.quantization is not None:
  380. if self.quantization not in supported_quantization:
  381. raise ValueError(
  382. f"Unknown quantization method: {self.quantization}. Must "
  383. f"be one of {supported_quantization}.")
  384. if is_hip(
  385. ) and self.quantization not in rocm_supported_quantization:
  386. raise ValueError(
  387. f"{self.quantization} quantization is currently not "
  388. "supported in ROCm.")
  389. if current_platform.is_tpu(
  390. ) and self.quantization not in tpu_supported_quantization:
  391. raise ValueError(
  392. f"{self.quantization} quantization is currently not "
  393. f"supported in TPU Backend.")
  394. if self.quantization not in _OPTIMIZED_QUANTS:
  395. logger.warning(
  396. f"{self.quantization} quantization is not fully "
  397. "optimized yet. The speed can be slower than "
  398. "non-quantized models.")
  399. if self.quantization == "deepspeedfp" and self.deepspeed_fp_bits \
  400. is None:
  401. raise ValueError(
  402. "deepspeed_fp_bits must be specified when using "
  403. "deepspeedfp quantization.")
  404. def _verify_cuda_graph(self) -> None:
  405. if self.max_seq_len_to_capture is None:
  406. self.max_seq_len_to_capture = self.max_model_len
  407. self.max_seq_len_to_capture = min(self.max_seq_len_to_capture,
  408. self.max_model_len)
  409. def verify_with_parallel_config(
  410. self,
  411. parallel_config: "ParallelConfig",
  412. ) -> None:
  413. total_num_attention_heads = getattr(self.hf_text_config,
  414. "num_attention_heads", 0)
  415. tensor_parallel_size = parallel_config.tensor_parallel_size
  416. if (total_num_attention_heads % tensor_parallel_size != 0
  417. and self.quantization is not None):
  418. raise ValueError(
  419. f"Total number of attention heads "
  420. f"({total_num_attention_heads})"
  421. " must be divisible by tensor parallel size "
  422. f"({tensor_parallel_size}) when quantization is used.")
  423. pipeline_parallel_size = parallel_config.pipeline_parallel_size
  424. architectures = getattr(self.hf_config, "architectures", [])
  425. if not all(arch in _PP_SUPPORTED_MODELS
  426. for arch in architectures) and pipeline_parallel_size > 1:
  427. raise NotImplementedError(
  428. "Pipeline parallelism is only supported for the following "
  429. f" architectures: {_PP_SUPPORTED_MODELS}.")
  430. if self.quantization == "bitsandbytes" and (
  431. parallel_config.tensor_parallel_size > 1
  432. or parallel_config.pipeline_parallel_size > 1):
  433. raise ValueError(
  434. "BitsAndBytes quantization with TP/PP is not supported yet.")
  435. if self.quantization == "bitsandbytes" and self.enforce_eager is False:
  436. raise ValueError(
  437. "BitsAndBytes with enforce_eager=False is not supported yet.")
  438. def is_attention_free(self) -> bool:
  439. """Returns True if the model has no attention, i.e. the model has no
  440. state that grows with the size of the context.
  441. """
  442. # Return true if the model is mamba.
  443. # This check should be augmented with more models in the future,
  444. # and made more robust if possible.
  445. if hasattr(self.hf_text_config,
  446. "model_type") and self.hf_text_config.model_type == 'mamba':
  447. return True
  448. return False
  449. def get_hf_config_sliding_window(
  450. self) -> Union[Optional[int], List[Optional[int]]]:
  451. """Get the sliding window size, or None if disabled.
  452. """
  453. # Some models, like Qwen2 and Qwen1.5, use `use_sliding_window` in
  454. # addition to sliding window size. We check if that field is present
  455. # and if it's False, return None.
  456. if (hasattr(self.hf_text_config, "use_sliding_window")
  457. and not self.hf_text_config.use_sliding_window):
  458. return None
  459. return getattr(self.hf_text_config, "sliding_window", None)
  460. def get_sliding_window(self) -> Optional[Union[int, List[Optional[int]]]]:
  461. """Get the sliding window size, or None if disabled.
  462. """
  463. # If user disables sliding window, return None.
  464. if self.disable_sliding_window:
  465. return None
  466. # Otherwise get the value from the hf config.
  467. return self.get_hf_config_sliding_window()
  468. def get_vocab_size(self) -> int:
  469. return self.hf_text_config.vocab_size
  470. def get_hidden_size(self) -> int:
  471. return self.hf_text_config.hidden_size
  472. def get_head_size(self) -> int:
  473. # TODO remove hard code
  474. if hasattr(self.hf_text_config, "model_type"
  475. ) and self.hf_text_config.model_type == 'deepseek_v2':
  476. # FlashAttention supports only head_size 32, 64, 128, 256,
  477. # we need to pad head_size 192 to 256
  478. return 256
  479. if self.is_attention_free():
  480. return 0
  481. if hasattr(self.hf_text_config, "head_dim"):
  482. return self.hf_text_config.head_dim
  483. # FIXME: This may not be true for all models.
  484. return (self.hf_text_config.hidden_size //
  485. self.hf_text_config.num_attention_heads)
  486. def get_total_num_kv_heads(self) -> int:
  487. """Returns the total number of KV heads."""
  488. # For GPTBigCode & Falcon:
  489. # NOTE: for falcon, when new_decoder_architecture is True, the
  490. # multi_query flag is ignored and we use n_head_kv for the number of
  491. # KV heads.
  492. falcon_model_types = ["falcon", "RefinedWeb", "RefinedWebModel"]
  493. new_decoder_arch_falcon = (
  494. self.hf_config.model_type in falcon_model_types
  495. and getattr(self.hf_config, "new_decoder_architecture", False))
  496. if not new_decoder_arch_falcon and getattr(self.hf_text_config,
  497. "multi_query", False):
  498. # Multi-query attention, only one KV head.
  499. # Currently, tensor parallelism is not supported in this case.
  500. return 1
  501. # For DBRX and MPT
  502. if self.hf_config.model_type == "mpt":
  503. if "kv_n_heads" in self.hf_config.attn_config:
  504. return self.hf_config.attn_config["kv_n_heads"]
  505. return self.hf_config.num_attention_heads
  506. if self.hf_config.model_type == "dbrx":
  507. return getattr(self.hf_config.attn_config, "kv_n_heads",
  508. self.hf_config.num_attention_heads)
  509. if self.is_attention_free():
  510. return 0
  511. attributes = [
  512. # For Falcon:
  513. "n_head_kv",
  514. "num_kv_heads",
  515. # For LLaMA-2:
  516. "num_key_value_heads",
  517. # For ChatGLM:
  518. "multi_query_group_num",
  519. ]
  520. for attr in attributes:
  521. num_kv_heads = getattr(self.hf_text_config, attr, None)
  522. if num_kv_heads is not None:
  523. return num_kv_heads
  524. # For non-grouped-query attention models, the number of KV heads is
  525. # equal to the number of attention heads.
  526. return self.hf_text_config.num_attention_heads
  527. def get_num_kv_heads(self,
  528. parallel_config: "ParallelConfig",
  529. tp_rank: int = 0) -> int:
  530. """Returns the number of KV heads per GPU."""
  531. total_num_kv_heads = self.get_total_num_kv_heads()
  532. # If tensor parallelism is used, we divide the number of KV heads by
  533. # the tensor parallel size. We will replicate the KV heads in the
  534. # case where the number of KV heads is smaller than the tensor
  535. # parallel size so each GPU has at least one KV head.
  536. result = get_current_tp_rank_partition_size(
  537. total_num_kv_heads, tp_rank, parallel_config.tensor_parallel_size)
  538. return max(1, result)
  539. def get_num_attention_heads(self,
  540. parallel_config: "ParallelConfig",
  541. tp_rank: int = 0) -> int:
  542. if getattr(self.hf_text_config, "num_attention_heads", None) is None:
  543. return 0
  544. num_total_kv_heads = self.get_total_num_kv_heads()
  545. num_kv_heads = self.get_num_kv_heads(parallel_config, tp_rank)
  546. num_total_attention_heads = self.hf_text_config.num_attention_heads
  547. num_heads_per_kv_head = num_total_attention_heads // num_total_kv_heads
  548. # For GQA attention we make sure the whole attention head group is
  549. # together on the same GPU.
  550. return num_kv_heads * num_heads_per_kv_head
  551. def get_num_layers(self, parallel_config: "ParallelConfig") -> int:
  552. from aphrodite.distributed.utils import get_pp_indices
  553. total_num_hidden_layers = getattr(self.hf_text_config,
  554. "num_hidden_layers", 0)
  555. pp_rank = parallel_config.rank // parallel_config.tensor_parallel_size
  556. pp_size = parallel_config.pipeline_parallel_size
  557. start, end = get_pp_indices(total_num_hidden_layers, pp_rank, pp_size)
  558. return end - start
  559. def contains_seqlen_agnostic_layers(
  560. self, parallel_config: "ParallelConfig") -> bool:
  561. """True for Mamba/SSM models (Jamba)"""
  562. return self._get_num_seqlen_agnostic_layers(parallel_config) > 0
  563. def get_layers_block_type(self,
  564. parallel_config: "ParallelConfig") -> List[str]:
  565. num_layers = self.get_num_layers(parallel_config)
  566. if self.is_attention_free():
  567. assert (self.hf_config.model_type == "mamba")
  568. return ["mamba"] * num_layers
  569. # Transformers supports layers_block_type @property
  570. return getattr(self.hf_config, "layers_block_type",
  571. ["attention"] * num_layers)
  572. def get_num_attention_layers(self,
  573. parallel_config: "ParallelConfig") -> int:
  574. return len([
  575. t for t in self.get_layers_block_type(parallel_config)
  576. if t == "attention"
  577. ])
  578. def _get_num_seqlen_agnostic_layers(
  579. self, parallel_config: "ParallelConfig") -> int:
  580. return len([
  581. t for t in self.get_layers_block_type(parallel_config)
  582. if t != "attention"
  583. ])
  584. def get_multimodal_config(self) -> "MultiModalConfig":
  585. """
  586. Get the multimodal configuration of the model.
  587. Raises:
  588. ValueError: If the model is not multimodal.
  589. """
  590. if self.multimodal_config is None:
  591. raise ValueError("The model is not multimodal.")
  592. return self.multimodal_config
  593. @property
  594. def is_encoder_decoder_model(self) -> bool:
  595. """Extract the HF encoder/decoder model flag."""
  596. return getattr(self.hf_config, "is_encoder_decoder", False)
  597. @property
  598. def is_embedding_model(self) -> bool:
  599. """Extract the embedding model flag."""
  600. return self.embedding_mode
  601. class CacheConfig:
  602. """Configuration for the KV cache.
  603. Args:
  604. block_size: Size of a cache block in number of tokens.
  605. gpu_memory_utilization: Fraction of GPU memory to use for the
  606. Aphrodite execution.
  607. swap_space: Size of the CPU swap space per GPU (in GiB).
  608. cache_dtype: Data type for kv cache storage.
  609. num_gpu_blocks_override: Number of GPU blocks to use. This overrides the
  610. profiled num_gpu_blocks if specified. Does nothing if None.
  611. """
  612. def __init__(
  613. self,
  614. block_size: int,
  615. gpu_memory_utilization: float,
  616. swap_space: float,
  617. cache_dtype: str,
  618. is_attention_free: bool = False,
  619. num_gpu_blocks_override: Optional[int] = None,
  620. sliding_window: Optional[int] = None,
  621. enable_prefix_caching: bool = False,
  622. cpu_offload_gb: float = 0.0,
  623. ) -> None:
  624. self.block_size = block_size
  625. self.gpu_memory_utilization = gpu_memory_utilization
  626. self.swap_space_bytes = swap_space * GiB_bytes
  627. self.num_gpu_blocks_override = num_gpu_blocks_override
  628. self.cache_dtype = cache_dtype
  629. self.is_attention_free = is_attention_free
  630. self.sliding_window = sliding_window
  631. self.enable_prefix_caching = enable_prefix_caching
  632. self.cpu_offload_gb = cpu_offload_gb
  633. self._verify_args()
  634. self._verify_cache_dtype()
  635. self._verify_prefix_caching()
  636. # Will be set after profiling.
  637. self.num_gpu_blocks = None
  638. self.num_cpu_blocks = None
  639. def metrics_info(self):
  640. # convert cache_config to dict(key: str, value: str) for prometheus
  641. # metrics info
  642. return {key: str(value) for key, value in self.__dict__.items()}
  643. def _verify_args(self) -> None:
  644. if self.gpu_memory_utilization > 1.0:
  645. raise ValueError(
  646. "GPU memory utilization must be less than 1.0. Got "
  647. f"{self.gpu_memory_utilization}.")
  648. def _verify_cache_dtype(self) -> None:
  649. if self.cache_dtype == "auto":
  650. pass
  651. elif self.cache_dtype in ("fp8", "fp8_e4m3", "fp8_e5m2"):
  652. logger.info(
  653. "Using fp8 data type to store kv cache. It reduces the GPU "
  654. "memory footprint and boosts the performance. "
  655. "Meanwhile, it may cause accuracy drop without a proper "
  656. "scaling factor")
  657. else:
  658. raise ValueError(f"Unknown kv cache dtype: {self.cache_dtype}")
  659. def _verify_prefix_caching(self) -> None:
  660. if not self.enable_prefix_caching:
  661. return
  662. if self.sliding_window is not None:
  663. raise NotImplementedError(
  664. "Prefix caching is not supported with sliding window. "
  665. "Run with --disable-sliding-window to use prefix caching.")
  666. if self.cache_dtype == "fp8":
  667. capability = current_platform.get_device_capability()
  668. capability = capability[0] * 10 + capability[1]
  669. if capability < 89:
  670. raise NotImplementedError(
  671. "FP8 KV cache with prefix caching is only supported on "
  672. "GPUs with compute capability 8.9 or higher (e.g., "
  673. "4090, H100). Your GPU has compute capability "
  674. f"{capability}")
  675. if not HAS_TRITON and self.enable_prefix_caching:
  676. raise ValueError("Triton is not installed, "
  677. "prefix caching will not work.")
  678. def verify_with_parallel_config(
  679. self,
  680. parallel_config: "ParallelConfig",
  681. ) -> None:
  682. total_cpu_memory = get_cpu_memory()
  683. # FIXME: Here, it is assumed that the GPUs in a tensor parallel
  684. # group are in the same node. However, the GPUs may span multiple nodes.
  685. num_gpus_per_node = parallel_config.tensor_parallel_size
  686. cpu_memory_usage = self.swap_space_bytes * num_gpus_per_node
  687. msg = (f"{cpu_memory_usage / GiB_bytes:.2f} GiB out of the "
  688. f"{total_cpu_memory / GiB_bytes:.2f} GiB total CPU memory "
  689. "is allocated for the swap space.")
  690. if cpu_memory_usage > 0.7 * total_cpu_memory:
  691. raise ValueError("Too large swap space. " + msg)
  692. elif cpu_memory_usage > 0.4 * total_cpu_memory:
  693. logger.warning("Possibly too large swap space. " + msg)
  694. @dataclass
  695. class TokenizerPoolConfig:
  696. """Configuration for the tokenizer pool.
  697. Args:
  698. pool_size: Number of tokenizer workers in the pool.
  699. pool_type: Type of the pool.
  700. extra_config: Additional config for the pool.
  701. The way the config will be used depends on the
  702. pool type.
  703. """
  704. pool_size: int
  705. pool_type: Union[str, Type["BaseTokenizerGroup"]]
  706. extra_config: dict
  707. def __post_init__(self):
  708. if self.pool_type not in ("ray", ) and not isinstance(
  709. self.pool_type, type):
  710. raise ValueError(f"Unknown pool type: {self.pool_type}")
  711. if not isinstance(self.extra_config, dict):
  712. raise ValueError("extra_config must be a dictionary.")
  713. @classmethod
  714. def create_config(
  715. cls, tokenizer_pool_size: int, tokenizer_pool_type: str,
  716. tokenizer_pool_extra_config: Optional[Union[str, dict]]
  717. ) -> Optional["TokenizerPoolConfig"]:
  718. """Create a TokenizerPoolConfig from the given parameters.
  719. If tokenizer_pool_size is 0, return None.
  720. Args:
  721. tokenizer_pool_size: Number of tokenizer workers in the pool.
  722. tokenizer_pool_type: Type of the pool.
  723. tokenizer_pool_extra_config: Additional config for the pool.
  724. The way the config will be used depends on the
  725. pool type. This can be a JSON string (will be parsed).
  726. """
  727. if tokenizer_pool_size:
  728. if isinstance(tokenizer_pool_extra_config, str):
  729. tokenizer_pool_extra_config_parsed = json.loads(
  730. tokenizer_pool_extra_config)
  731. else:
  732. tokenizer_pool_extra_config_parsed = (
  733. tokenizer_pool_extra_config or {})
  734. tokenizer_pool_config = cls(tokenizer_pool_size,
  735. tokenizer_pool_type,
  736. tokenizer_pool_extra_config_parsed)
  737. else:
  738. tokenizer_pool_config = None
  739. return tokenizer_pool_config
  740. class LoadFormat(str, enum.Enum):
  741. AUTO = "auto"
  742. PT = "pt"
  743. SAFETENSORS = "safetensors"
  744. NPCACHE = "npcache"
  745. DUMMY = "dummy"
  746. TENSORIZER = "tensorizer"
  747. SHARDED_STATE = "sharded_state"
  748. GGUF = "gguf"
  749. BITSANDBYTES = "bitsandbytes"
  750. MISTRAL = "mistral"
  751. @dataclass
  752. class LoadConfig:
  753. """
  754. download_dir: Directory to download and load the weights, default to the
  755. default cache directory of huggingface.
  756. load_format: The format of the model weights to load:
  757. "auto" will try to load the weights in the safetensors format and
  758. fall back to the pytorch bin format if safetensors format is
  759. not available.
  760. "pt" will load the weights in the pytorch bin format.
  761. "safetensors" will load the weights in the safetensors format.
  762. "npcache" will load the weights in pytorch format and store
  763. a numpy cache to speed up the loading.
  764. "dummy" will initialize the weights with random values, which is
  765. mainly for profiling.
  766. "tensorizer" will use CoreWeave's tensorizer library for
  767. fast weight loading.
  768. ignore_patterns: The list of patterns to ignore when loading the model.
  769. Default to "original/**/*" to avoid repeated loading of llama's
  770. checkpoints.
  771. """
  772. load_format: Union[str, LoadFormat, "BaseModelLoader"] = LoadFormat.AUTO
  773. download_dir: Optional[str] = None
  774. model_loader_extra_config: Optional[Union[str, dict]] = field(
  775. default_factory=dict)
  776. ignore_patterns: Optional[Union[List[str], str]] = None
  777. def __post_init__(self):
  778. model_loader_extra_config = self.model_loader_extra_config or {}
  779. if isinstance(model_loader_extra_config, str):
  780. self.model_loader_extra_config = json.loads(
  781. model_loader_extra_config)
  782. self._verify_load_format()
  783. if self.ignore_patterns is not None and len(self.ignore_patterns) > 0:
  784. logger.info(
  785. "Ignoring the following patterns when downloading weights: "
  786. f"{self.ignore_patterns}")
  787. else:
  788. self.ignore_patterns = ["original/**/*"]
  789. def _verify_load_format(self) -> None:
  790. if not isinstance(self.load_format, str):
  791. return
  792. load_format = self.load_format.lower()
  793. self.load_format = LoadFormat(load_format)
  794. rocm_not_supported_load_format: List[str] = []
  795. if is_hip() and load_format in rocm_not_supported_load_format:
  796. rocm_supported_load_format = [
  797. f for f in LoadFormat.__members__
  798. if (f not in rocm_not_supported_load_format)
  799. ]
  800. raise ValueError(
  801. f"load format '{load_format}' is not supported in ROCm. "
  802. f"Supported load formats are "
  803. f"{rocm_supported_load_format}")
  804. class ParallelConfig:
  805. """Configuration for the distributed execution.
  806. Args:
  807. pipeline_parallel_size: Number of pipeline parallel groups.
  808. tensor_parallel_size: Number of tensor parallel groups.
  809. worker_use_ray: Deprecated, use distributed_executor_backend instead.
  810. max_parallel_loading_workers: Maximum number of multiple batches
  811. when load model sequentially. To avoid RAM OOM when using tensor
  812. parallel and large models.
  813. disable_custom_all_reduce: Disable the custom all-reduce kernel and
  814. fall back to NCCL.
  815. tokenizer_pool_config: Config for the tokenizer pool.
  816. If None, will use synchronous tokenization.
  817. ray_workers_use_nsight: Whether to profile Ray workers with nsight, see
  818. https://docs.ray.io/en/latest/ray-observability/user-guides/profiling.html#profiling-nsight-profiler.
  819. placement_group: ray distributed model workers placement group.
  820. distributed_executor_backend: Backend to use for distributed model
  821. workers, either "ray" or "mp" (multiprocessing). If either
  822. pipeline_parallel_size or tensor_parallel_size is greater than 1,
  823. will default to "ray" if Ray is installed or "mp" otherwise.
  824. """
  825. def __init__(
  826. self,
  827. pipeline_parallel_size: int,
  828. tensor_parallel_size: int,
  829. worker_use_ray: Optional[bool] = None,
  830. max_parallel_loading_workers: Optional[int] = None,
  831. disable_custom_all_reduce: bool = False,
  832. tokenizer_pool_config: Optional[TokenizerPoolConfig] = None,
  833. ray_workers_use_nsight: bool = False,
  834. placement_group: Optional["PlacementGroup"] = None,
  835. distributed_executor_backend: Optional[Union[
  836. str, Type["ExecutorBase"]]] = None,
  837. ) -> None:
  838. self.pipeline_parallel_size = pipeline_parallel_size
  839. self.tensor_parallel_size = tensor_parallel_size
  840. self.distributed_executor_backend = distributed_executor_backend
  841. self.max_parallel_loading_workers = max_parallel_loading_workers
  842. self.disable_custom_all_reduce = disable_custom_all_reduce
  843. self.tokenizer_pool_config = tokenizer_pool_config
  844. self.ray_workers_use_nsight = ray_workers_use_nsight
  845. self.placement_group = placement_group
  846. self.world_size = pipeline_parallel_size * self.tensor_parallel_size
  847. if worker_use_ray:
  848. if self.distributed_executor_backend is None:
  849. self.distributed_executor_backend = "ray"
  850. elif not self.use_ray:
  851. raise ValueError(f"worker-use-ray can't be used with "
  852. f"distributed executor backend "
  853. f"'{self.distributed_executor_backend}'.")
  854. if self.distributed_executor_backend is None and self.world_size > 1:
  855. # We use multiprocessing by default if world_size fits on the
  856. # current node and we aren't in a ray placement group.
  857. from aphrodite.executor import ray_utils
  858. backend = "mp"
  859. ray_found = ray_utils.ray_is_available()
  860. if cuda_device_count_stateless() < self.world_size:
  861. if not ray_found:
  862. raise ValueError("Unable to load Ray which is "
  863. "required for multi-node inference, "
  864. "please install Ray with `pip install "
  865. "ray`.") from ray_utils.ray_import_err
  866. backend = "ray"
  867. elif ray_found:
  868. if self.placement_group:
  869. backend = "ray"
  870. else:
  871. from ray import is_initialized as ray_is_initialized
  872. if ray_is_initialized():
  873. from ray.util import get_current_placement_group
  874. if get_current_placement_group():
  875. backend = "ray"
  876. self.distributed_executor_backend = backend
  877. logger.info(
  878. f"Defaulting to use {backend} for distributed inference.")
  879. self._verify_args()
  880. self.rank = 0
  881. @property
  882. def use_ray(self) -> bool:
  883. return self.distributed_executor_backend == "ray" or (
  884. isinstance(self.distributed_executor_backend, type)
  885. and self.distributed_executor_backend.uses_ray)
  886. def _verify_args(self) -> None:
  887. # Lazy import to avoid circular import
  888. from aphrodite.executor.executor_base import ExecutorBase
  889. if self.distributed_executor_backend not in (
  890. "ray", "mp", None) and not (isinstance(
  891. self.distributed_executor_backend, type) and issubclass(
  892. self.distributed_executor_backend, ExecutorBase)):
  893. raise ValueError(
  894. "Unrecognized distributed executor backend "
  895. f"{self.distributed_executor_backend}. Supported "
  896. "values are 'ray', 'mp' or custom ExecutorBase subclass.")
  897. if self.use_ray:
  898. from aphrodite.executor import ray_utils
  899. ray_utils.assert_ray_available()
  900. if is_hip():
  901. self.disable_custom_all_reduce = True
  902. logger.info(
  903. "Disabled the custom all-reduce kernel because it is not "
  904. "supported on AMD GPUs.")
  905. if self.ray_workers_use_nsight and not self.use_ray:
  906. raise ValueError("Unable to use nsight profiling unless workers "
  907. "run with Ray.")
  908. class SchedulerConfig:
  909. """Scheduler configuration.
  910. Args:
  911. max_num_batched_tokens: Maximum number of tokens to be processed in
  912. a single iteration.
  913. max_num_seqs: Maximum number of sequences to be processed in a single
  914. iteration.
  915. max_model_len: Maximum length of a sequence (including prompt
  916. and generated text).
  917. is_attention_free: True if the running model does not have state that
  918. grows as the context size increases.
  919. use_v2_block_manager: Whether to use the BlockSpaceManagerV2 or not.
  920. num_lookahead_slots: The number of slots to allocate per sequence per
  921. step, beyond the known token ids. This is used in speculative
  922. decoding to store KV activations of tokens which may or may not be
  923. accepted.
  924. delay_factor: Apply a delay (of delay factor multiplied by previous
  925. prompt latency) before scheduling next prompt.
  926. enable_chunked_prefill: If True, prefill requests can be chunked based
  927. on the remaining max_num_batched_tokens.
  928. embedding_mode: Whether the running model is for embedding.
  929. preemption_mode: Whether to perform preemption by swapping or
  930. recomputation. If not specified, we determine the mode as follows:
  931. We use recomputation by default since it incurs lower overhead than
  932. swapping. However, when the sequence group has multiple sequences
  933. (e.g., beam search), recomputation is not currently supported. In
  934. such a case, we use swapping instead.
  935. send_delta_data: Private API. If used, scheduler sends delta data to
  936. workers instead of an entire data. It should be enabled only
  937. when SPMD worker architecture is enabled. I.e.,
  938. APHRODITE_USE_RAY_SPMD_WORKER=1
  939. """
  940. def __init__(self,
  941. max_num_batched_tokens: Optional[int],
  942. max_num_seqs: int,
  943. max_model_len: int,
  944. is_attention_free: bool = False,
  945. use_v2_block_manager: bool = False,
  946. num_lookahead_slots: int = 0,
  947. delay_factor: float = 0.0,
  948. enable_chunked_prefill: bool = False,
  949. embedding_mode: Optional[bool] = False,
  950. preemption_mode: Optional[str] = None,
  951. num_scheduler_steps: int = 1,
  952. send_delta_data: bool = False) -> None:
  953. if max_num_batched_tokens is not None:
  954. self.max_num_batched_tokens = max_num_batched_tokens
  955. else:
  956. if enable_chunked_prefill:
  957. if not HAS_TRITON:
  958. raise ValueError("Triton is not installed, "
  959. "chunked prefill will not work.")
  960. # For chunked prefill, choose the well-tuned batch size.
  961. self.max_num_batched_tokens = 768
  962. elif embedding_mode:
  963. # For embedding, choose specific value for higher throughput
  964. self.max_num_batched_tokens = max(
  965. max_model_len, _EMBEDDING_MODEL_MAX_NUM_BATCHED_TOKENS)
  966. else:
  967. # If max_model_len is too short, use 2048 as the default value
  968. # for higher throughput.
  969. self.max_num_batched_tokens = max(max_model_len, 2048)
  970. if enable_chunked_prefill:
  971. logger.info(
  972. "Chunked prefill is enabled with "
  973. f"max_num_batched_tokens={self.max_num_batched_tokens}.")
  974. self.max_num_seqs = max_num_seqs
  975. self.max_model_len = max_model_len
  976. self.is_attention_free = is_attention_free
  977. self.use_v2_block_manager = use_v2_block_manager
  978. self.num_lookahead_slots = num_lookahead_slots
  979. self.delay_factor = delay_factor
  980. self.chunked_prefill_enabled = enable_chunked_prefill
  981. self.embedding_mode = embedding_mode
  982. self.preemption_mode = preemption_mode
  983. self.num_scheduler_steps = num_scheduler_steps
  984. self.send_delta_data = send_delta_data
  985. self._verify_args()
  986. def _verify_args(self) -> None:
  987. if (self.max_num_batched_tokens < self.max_model_len
  988. and not self.chunked_prefill_enabled):
  989. raise ValueError(
  990. f"max_num_batched_tokens ({self.max_num_batched_tokens}) is "
  991. f"smaller than max_model_len ({self.max_model_len}). "
  992. "This effectively limits the maximum sequence length to "
  993. "max_num_batched_tokens and makes Aphrodite reject longer "
  994. "sequences. Please increase max_num_batched_tokens or "
  995. "decrease max_model_len.")
  996. if self.max_num_batched_tokens < self.max_num_seqs:
  997. raise ValueError(
  998. f"max_num_batched_tokens ({self.max_num_batched_tokens}) must "
  999. "be greater than or equal to max_num_seqs "
  1000. f"({self.max_num_seqs}).")
  1001. if self.num_lookahead_slots < 0:
  1002. raise ValueError(
  1003. "num_lookahead_slots "
  1004. f"({self.num_lookahead_slots}) must be greater than or "
  1005. "equal to 0.")
  1006. if self.num_scheduler_steps < 1:
  1007. raise ValueError(
  1008. "num_scheduler_steps "
  1009. f"({self.num_scheduler_steps}) must be greater than or "
  1010. "equal to 1.")
  1011. @property
  1012. def is_multi_step(self) -> bool:
  1013. return self.num_scheduler_steps > 1
  1014. class DeviceConfig:
  1015. def __init__(self, device: str = "auto") -> None:
  1016. if device == "auto":
  1017. # Automated device type detection
  1018. if is_neuron():
  1019. self.device_type = "neuron"
  1020. elif is_openvino():
  1021. self.device_type = "openvino"
  1022. elif current_platform.is_tpu():
  1023. self.device_type = "tpu"
  1024. elif is_cpu():
  1025. self.device_type = "cpu"
  1026. elif is_xpu():
  1027. self.device_type = "xpu"
  1028. else:
  1029. # We don't call torch.cuda.is_available() here to
  1030. # avoid initializing CUDA before workers are forked
  1031. self.device_type = "cuda"
  1032. else:
  1033. # Device type is assigned explicitly
  1034. self.device_type = device
  1035. # Some device types require processing inputs on CPU
  1036. if self.device_type in ["neuron", "openvino"]:
  1037. self.device = torch.device("cpu")
  1038. elif self.device_type in ["tpu"]:
  1039. self.device = None
  1040. else:
  1041. # Set device with device type
  1042. self.device = torch.device(self.device_type)
  1043. class SpeculativeConfig:
  1044. """Configuration for speculative decoding.
  1045. The configuration is currently specialized to draft-model speculative
  1046. decoding with top-1 proposals.
  1047. """
  1048. @staticmethod
  1049. def maybe_create_spec_config(
  1050. target_model_config: ModelConfig,
  1051. target_parallel_config: ParallelConfig,
  1052. target_dtype: str,
  1053. speculative_model: Optional[str],
  1054. speculative_model_quantization: Optional[str],
  1055. speculative_draft_tensor_parallel_size: Optional[int],
  1056. num_speculative_tokens: Optional[int],
  1057. speculative_max_model_len: Optional[int],
  1058. enable_chunked_prefill: bool,
  1059. use_v2_block_manager: bool,
  1060. disable_log_stats: bool,
  1061. speculative_disable_by_batch_size: Optional[int],
  1062. ngram_prompt_lookup_max: Optional[int],
  1063. ngram_prompt_lookup_min: Optional[int],
  1064. draft_token_acceptance_method: str,
  1065. typical_acceptance_sampler_posterior_threshold: Optional[float],
  1066. typical_acceptance_sampler_posterior_alpha: Optional[float],
  1067. disable_logprobs: Optional[bool],
  1068. ) -> Optional["SpeculativeConfig"]:
  1069. """Create a SpeculativeConfig if possible, else return None.
  1070. This function attempts to create a SpeculativeConfig object based on the
  1071. provided parameters. If the necessary conditions are met, it returns an
  1072. instance of SpeculativeConfig. Otherwise, it returns None.
  1073. Args:
  1074. target_model_config (ModelConfig): The configuration of the target
  1075. model.
  1076. target_parallel_config (ParallelConfig): The parallel configuration
  1077. for the target model.
  1078. target_dtype (str): The data type used for the target model.
  1079. speculative_model (Optional[str]): The name of the speculative
  1080. model, if provided.
  1081. num_speculative_tokens (Optional[int]): The number of speculative
  1082. tokens, if provided. Will default to the number in the draft
  1083. model config if present, otherwise is required.
  1084. speculative_model_quantization (Optional[str]): Quantization method
  1085. that was used to quantize the speculative model weights. If
  1086. None, we assume the model weights are not quantized.
  1087. speculative_draft_tensor_parallel_size (Optional[int]): The degree
  1088. of the tensor parallelism for the draft model.
  1089. speculative_max_model_len (Optional[int]): The maximum model len of
  1090. the speculative model. Used when testing the ability to skip
  1091. speculation for some sequences.
  1092. enable_chunked_prefill (bool): Whether Aphrodite is configured to
  1093. use chunked prefill or not. Used for raising an error since its
  1094. not yet compatible with spec decode.
  1095. use_v2_block_manager (bool): Whether Aphrodite is configured to
  1096. use the v2 block manager or not. Used for raising an error
  1097. since the v2 block manager is required with spec decode.
  1098. speculative_disable_by_batch_size (Optional[int]): Disable
  1099. speculative decoding for new incoming requests when the number
  1100. of enqueue requests is larger than this value, if provided.
  1101. ngram_prompt_lookup_max (Optional[int]): Max size of ngram token
  1102. window, if provided.
  1103. ngram_prompt_lookup_min (Optional[int]): Min size of ngram token
  1104. window, if provided.
  1105. draft_token_acceptance_method (str): The method to use for
  1106. accepting draft tokens. This can take two possible
  1107. values 'rejection_sampler' and 'typical_acceptance_sampler'
  1108. for RejectionSampler and TypicalAcceptanceSampler
  1109. respectively.
  1110. typical_acceptance_sampler_posterior_threshold (Optional[float]):
  1111. A threshold value that sets a lower bound on the posterior
  1112. probability of a token in the target model for it to be
  1113. accepted. This threshold is used only when we use the
  1114. TypicalAcceptanceSampler for token acceptance.
  1115. typical_acceptance_sampler_posterior_alpha (Optional[float]):
  1116. A scaling factor for the entropy-based threshold in the
  1117. TypicalAcceptanceSampler.
  1118. disable_logprobs (Optional[bool]): If set to True, token log
  1119. probabilities are not returned during speculative decoding.
  1120. If set to False, token log probabilities are returned
  1121. according to the log probability settings in SamplingParams.
  1122. If not specified, it defaults to True.
  1123. Returns:
  1124. Optional["SpeculativeConfig"]: An instance of SpeculativeConfig if
  1125. the necessary conditions are met, else None.
  1126. """
  1127. if speculative_model is None:
  1128. if num_speculative_tokens is not None:
  1129. raise ValueError("num_speculative_tokens was provided without "
  1130. "speculative_model.")
  1131. return None
  1132. if (speculative_disable_by_batch_size is not None
  1133. and speculative_disable_by_batch_size < 2):
  1134. raise ValueError("Expected the batch size threshold of disabling "
  1135. "speculative decoding is > 1, but got "
  1136. f"{speculative_disable_by_batch_size=}")
  1137. if enable_chunked_prefill:
  1138. raise ValueError(
  1139. "Speculative decoding and chunked prefill are "
  1140. f"currently mutually exclusive ({enable_chunked_prefill=}).")
  1141. if not use_v2_block_manager:
  1142. raise ValueError(
  1143. "Speculative decoding requires usage of the V2 "
  1144. "block manager. Enable it with --use-v2-block-manager.")
  1145. # TODO: The user should be able to specify revision/max model len
  1146. # for the draft model. It is not currently supported.
  1147. draft_revision = None
  1148. draft_code_revision = None
  1149. draft_quantization = speculative_model_quantization
  1150. if speculative_model == "[ngram]":
  1151. if ngram_prompt_lookup_min is None:
  1152. ngram_prompt_lookup_min = 1
  1153. if ngram_prompt_lookup_max is None or ngram_prompt_lookup_max < 1:
  1154. raise ValueError(f"{ngram_prompt_lookup_max=} must be > 0")
  1155. if ngram_prompt_lookup_min < 1:
  1156. raise ValueError(f"{ngram_prompt_lookup_min=} must be > 0")
  1157. if ngram_prompt_lookup_min > ngram_prompt_lookup_max:
  1158. raise ValueError(f"{ngram_prompt_lookup_min=} cannot be "
  1159. f"larger than {ngram_prompt_lookup_max=}")
  1160. # TODO: current we still need extract vocab_size from target model
  1161. # config, in future, we may try refactoring it out, and set
  1162. # draft related config as None here.
  1163. draft_model_config = target_model_config
  1164. draft_parallel_config = target_parallel_config
  1165. else:
  1166. ngram_prompt_lookup_max = 0
  1167. ngram_prompt_lookup_min = 0
  1168. draft_model_config = ModelConfig(
  1169. model=speculative_model,
  1170. tokenizer=target_model_config.tokenizer,
  1171. tokenizer_mode=target_model_config.tokenizer_mode,
  1172. trust_remote_code=target_model_config.trust_remote_code,
  1173. dtype=target_model_config.dtype,
  1174. seed=target_model_config.seed,
  1175. revision=draft_revision,
  1176. code_revision=draft_code_revision,
  1177. tokenizer_revision=target_model_config.tokenizer_revision,
  1178. max_model_len=None,
  1179. spec_target_max_model_len=target_model_config.max_model_len,
  1180. quantization=draft_quantization,
  1181. enforce_eager=target_model_config.enforce_eager,
  1182. max_seq_len_to_capture=target_model_config.
  1183. max_seq_len_to_capture,
  1184. max_logprobs=target_model_config.max_logprobs,
  1185. )
  1186. draft_hf_config = draft_model_config.hf_config
  1187. if (num_speculative_tokens is not None
  1188. and hasattr(draft_hf_config, "num_lookahead_tokens")):
  1189. draft_hf_config.num_lookahead_tokens = num_speculative_tokens
  1190. n_predict = getattr(draft_hf_config, "n_predict", None)
  1191. if n_predict is not None:
  1192. if num_speculative_tokens is None:
  1193. # Default to max value defined in draft model config.
  1194. num_speculative_tokens = n_predict
  1195. elif num_speculative_tokens > n_predict:
  1196. # Verify provided value doesn't exceed the maximum
  1197. # supported by the draft model.
  1198. raise ValueError(
  1199. "This speculative model supports a maximum of "
  1200. f"num_speculative_tokens={n_predict}, but "
  1201. f"{num_speculative_tokens=} was provided.")
  1202. draft_model_config.max_model_len = (
  1203. SpeculativeConfig._maybe_override_draft_max_model_len(
  1204. speculative_max_model_len,
  1205. draft_model_config.max_model_len,
  1206. target_model_config.max_model_len,
  1207. ))
  1208. draft_parallel_config = (
  1209. SpeculativeConfig.create_draft_parallel_config(
  1210. target_parallel_config,
  1211. speculative_draft_tensor_parallel_size))
  1212. if num_speculative_tokens is None:
  1213. raise ValueError(
  1214. "num_speculative_tokens must be provided with "
  1215. "speculative_model unless the draft model config contains an "
  1216. "n_predict parameter.")
  1217. if typical_acceptance_sampler_posterior_threshold is None:
  1218. typical_acceptance_sampler_posterior_threshold = 0.09
  1219. if typical_acceptance_sampler_posterior_alpha is None:
  1220. typical_acceptance_sampler_posterior_alpha = 0.3
  1221. if disable_logprobs is None:
  1222. disable_logprobs = True
  1223. return SpeculativeConfig(
  1224. draft_model_config,
  1225. draft_parallel_config,
  1226. num_speculative_tokens,
  1227. speculative_disable_by_batch_size,
  1228. ngram_prompt_lookup_max,
  1229. ngram_prompt_lookup_min,
  1230. draft_token_acceptance_method=draft_token_acceptance_method,
  1231. typical_acceptance_sampler_posterior_threshold=\
  1232. typical_acceptance_sampler_posterior_threshold,
  1233. typical_acceptance_sampler_posterior_alpha=\
  1234. typical_acceptance_sampler_posterior_alpha,
  1235. disable_logprobs=disable_logprobs,
  1236. disable_log_stats=disable_log_stats,
  1237. )
  1238. @staticmethod
  1239. def _maybe_override_draft_max_model_len(
  1240. speculative_max_model_len: Optional[int],
  1241. draft_max_model_len: int,
  1242. target_max_model_len: int,
  1243. ) -> int:
  1244. """Determine the max sequence len for the draft model. This is usually
  1245. the draft_max_model_len, but may be the target_max_model_len if it is
  1246. less than the draft_max_model_len, or may be speculative_max_model_len
  1247. if it is specified.
  1248. This is necessary so that sequences do not exceed the capacity of the
  1249. draft model or the target model.
  1250. speculative_max_model_len is mainly used for testing that sequences can
  1251. skip speculation.
  1252. """
  1253. if speculative_max_model_len is not None:
  1254. if speculative_max_model_len > draft_max_model_len:
  1255. raise ValueError(f"{speculative_max_model_len=} cannot be "
  1256. f"larger than {draft_max_model_len=}")
  1257. if speculative_max_model_len > target_max_model_len:
  1258. raise ValueError(f"{speculative_max_model_len=} cannot be "
  1259. f"larger than {target_max_model_len=}")
  1260. return speculative_max_model_len
  1261. return min(
  1262. draft_max_model_len,
  1263. target_max_model_len,
  1264. )
  1265. @staticmethod
  1266. def create_draft_parallel_config(
  1267. target_parallel_config: ParallelConfig,
  1268. speculative_draft_tensor_parallel_size: Optional[int]
  1269. ) -> ParallelConfig:
  1270. """Create a parallel config for use by the draft worker.
  1271. This is mostly a copy of the target parallel config, except the tp_size.
  1272. """
  1273. if speculative_draft_tensor_parallel_size is None:
  1274. speculative_draft_tensor_parallel_size = \
  1275. target_parallel_config.tensor_parallel_size
  1276. elif speculative_draft_tensor_parallel_size != 1:
  1277. # TODO: allow tp values larger than 1
  1278. raise ValueError(
  1279. f"{speculative_draft_tensor_parallel_size=} cannot be "
  1280. f"other value than 1")
  1281. draft_parallel_config = ParallelConfig(
  1282. pipeline_parallel_size=target_parallel_config.
  1283. pipeline_parallel_size,
  1284. tensor_parallel_size=speculative_draft_tensor_parallel_size,
  1285. distributed_executor_backend=target_parallel_config.
  1286. distributed_executor_backend,
  1287. max_parallel_loading_workers=target_parallel_config.
  1288. max_parallel_loading_workers,
  1289. disable_custom_all_reduce=target_parallel_config.
  1290. disable_custom_all_reduce,
  1291. tokenizer_pool_config=target_parallel_config.tokenizer_pool_config,
  1292. ray_workers_use_nsight=target_parallel_config.
  1293. ray_workers_use_nsight,
  1294. placement_group=target_parallel_config.placement_group,
  1295. )
  1296. return draft_parallel_config
  1297. def __init__(
  1298. self,
  1299. draft_model_config: ModelConfig,
  1300. draft_parallel_config: ParallelConfig,
  1301. num_speculative_tokens: int,
  1302. speculative_disable_by_batch_size: Optional[int],
  1303. ngram_prompt_lookup_max: Optional[int],
  1304. ngram_prompt_lookup_min: Optional[int],
  1305. draft_token_acceptance_method: str,
  1306. typical_acceptance_sampler_posterior_threshold: float,
  1307. typical_acceptance_sampler_posterior_alpha: float,
  1308. disable_logprobs: bool,
  1309. disable_log_stats: bool,
  1310. ):
  1311. """Create a SpeculativeConfig object.
  1312. Args:
  1313. draft_model_config: ModelConfig for the draft model.
  1314. draft_parallel_config: ParallelConfig for the draft model.
  1315. num_speculative_tokens: The number of tokens to sample from the
  1316. draft model before scoring with the target model.
  1317. speculative_disable_by_batch_size: Disable speculative
  1318. decoding for new incoming requests when the number of
  1319. enqueue requests is larger than this value.
  1320. ngram_prompt_lookup_max: Max size of ngram token window.
  1321. ngram_prompt_lookup_min: Min size of ngram token window.
  1322. draft_token_acceptance_method (str): The method to use for
  1323. accepting draft tokens. This can take two possible
  1324. values 'rejection_sampler' and 'typical_acceptance_sampler'
  1325. for RejectionSampler and TypicalAcceptanceSampler
  1326. respectively.
  1327. typical_acceptance_sampler_posterior_threshold (Optional[float]):
  1328. A threshold value that sets a lower bound on the posterior
  1329. probability of a token in the target model for it to be
  1330. accepted. This threshold is used only when we use the
  1331. TypicalAcceptanceSampler for token acceptance.
  1332. typical_acceptance_sampler_posterior_alpha (Optional[float]):
  1333. A scaling factor for the entropy-based threshold in the
  1334. TypicalAcceptanceSampler.
  1335. disable_logprobs: If set to True, token log probabilities will not
  1336. be returned even if requested by sampling parameters. This
  1337. reduces latency by skipping logprob calculation in proposal
  1338. sampling, target sampling, and after accepted tokens are
  1339. determined. If set to False, log probabilities will be
  1340. returned.
  1341. disable_log_stats: Whether to disable periodic printing of stage
  1342. times in speculative decoding.
  1343. """
  1344. self.draft_model_config = draft_model_config
  1345. self.draft_parallel_config = draft_parallel_config
  1346. self.num_speculative_tokens = num_speculative_tokens
  1347. self.speculative_disable_by_batch_size = \
  1348. speculative_disable_by_batch_size
  1349. self.ngram_prompt_lookup_max = ngram_prompt_lookup_max or 0
  1350. self.ngram_prompt_lookup_min = ngram_prompt_lookup_min or 0
  1351. self.draft_token_acceptance_method = draft_token_acceptance_method
  1352. self.typical_acceptance_sampler_posterior_threshold = \
  1353. typical_acceptance_sampler_posterior_threshold
  1354. self.typical_acceptance_sampler_posterior_alpha = \
  1355. typical_acceptance_sampler_posterior_alpha
  1356. self.disable_logprobs = disable_logprobs
  1357. self.disable_log_stats = disable_log_stats
  1358. self._verify_args()
  1359. def _verify_args(self) -> None:
  1360. if self.num_speculative_tokens <= 0:
  1361. raise ValueError("Expected num_speculative_tokens to be greater "
  1362. f"than zero ({self.num_speculative_tokens}).")
  1363. if self.draft_model_config:
  1364. self.draft_model_config.verify_with_parallel_config(
  1365. self.draft_parallel_config)
  1366. # Validate and set draft token acceptance related settings.
  1367. if (self.draft_token_acceptance_method is None):
  1368. raise ValueError("draft_token_acceptance_method is not set. "
  1369. "Expected values are rejection_sampler or "
  1370. "typical_acceptance_sampler.")
  1371. if (self.draft_token_acceptance_method != 'rejection_sampler'
  1372. and self.draft_token_acceptance_method !=
  1373. 'typical_acceptance_sampler'):
  1374. raise ValueError(
  1375. "Expected draft_token_acceptance_method to be either "
  1376. "rejection_sampler or typical_acceptance_sampler. Instead it "
  1377. f"is {self.draft_token_acceptance_method}")
  1378. if (self.typical_acceptance_sampler_posterior_threshold < 0
  1379. or self.typical_acceptance_sampler_posterior_alpha < 0):
  1380. raise ValueError(
  1381. "Expected typical_acceptance_sampler_posterior_threshold "
  1382. "and typical_acceptance_sampler_posterior_alpha to be > 0. "
  1383. "Instead found "
  1384. f"typical_acceptance_sampler_posterior_threshold = "
  1385. f"{self.typical_acceptance_sampler_posterior_threshold} and "
  1386. f"typical_acceptance_sampler_posterior_alpha = "
  1387. f"{self.typical_acceptance_sampler_posterior_alpha}")
  1388. @property
  1389. def num_lookahead_slots(self) -> int:
  1390. """The number of additional slots the scheduler should allocate per
  1391. step, in addition to the slots allocated for each known token.
  1392. This is equal to the number of speculative tokens, as each speculative
  1393. token must be scored.
  1394. """
  1395. return self.num_speculative_tokens
  1396. def __repr__(self) -> str:
  1397. if self.ngram_prompt_lookup_max > 0:
  1398. draft_model = "[ngram]"
  1399. else:
  1400. draft_model = self.draft_model_config.model
  1401. num_spec_tokens = self.num_speculative_tokens
  1402. return f"SpeculativeConfig({draft_model=}, {num_spec_tokens=})"
  1403. @dataclass
  1404. class LoRAConfig:
  1405. max_lora_rank: int
  1406. max_loras: int
  1407. fully_sharded_loras: bool = False
  1408. max_cpu_loras: Optional[int] = None
  1409. lora_dtype: Optional[torch.dtype] = None
  1410. lora_extra_vocab_size: int = 256
  1411. # This is a constant.
  1412. lora_vocab_padding_size: ClassVar[int] = 256
  1413. long_lora_scaling_factors: Optional[Tuple[float]] = None
  1414. def __post_init__(self):
  1415. # Setting the maximum rank to 256 should be able to satisfy the vast
  1416. # majority of applications.
  1417. possible_max_ranks = (8, 16, 32, 64, 128, 256)
  1418. possible_lora_extra_vocab_size = (0, 256, 512)
  1419. if self.max_lora_rank not in possible_max_ranks:
  1420. raise ValueError(
  1421. f"max_lora_rank ({self.max_lora_rank}) must be one of "
  1422. f"{possible_max_ranks}.")
  1423. if self.lora_extra_vocab_size not in possible_lora_extra_vocab_size:
  1424. raise ValueError(
  1425. f"lora_extra_vocab_size ({self.lora_extra_vocab_size}) "
  1426. f"must be one of {possible_lora_extra_vocab_size}.")
  1427. if self.max_loras < 1:
  1428. raise ValueError(f"max_loras ({self.max_loras}) must be >= 1.")
  1429. if self.max_cpu_loras is None:
  1430. self.max_cpu_loras = self.max_loras
  1431. elif self.max_cpu_loras < self.max_loras:
  1432. raise ValueError(
  1433. f"max_cpu_loras ({self.max_cpu_loras}) must be >= "
  1434. f"max_loras ({self.max_loras})")
  1435. def verify_with_model_config(self, model_config: ModelConfig):
  1436. if self.lora_dtype in (None, "auto"):
  1437. self.lora_dtype = model_config.dtype
  1438. elif isinstance(self.lora_dtype, str):
  1439. self.lora_dtype = getattr(torch, self.lora_dtype)
  1440. if model_config.quantization and model_config.quantization not in [
  1441. "awq", "gptq"
  1442. ]:
  1443. # TODO support all other quants
  1444. logger.warning(f"{model_config.quantization} quantization is not "
  1445. "tested with LoRA yet.")
  1446. def verify_with_scheduler_config(self, scheduler_config: SchedulerConfig):
  1447. if scheduler_config.chunked_prefill_enabled:
  1448. logger.warning(
  1449. "Chunked Prefill with LoRA is not rigorously tested.")
  1450. def verify_with_parallel_config(self, parallel_config: ParallelConfig):
  1451. if self.lora_vocab_padding_size % parallel_config.world_size != 0:
  1452. raise ValueError("LoRA vocab padding size must be divisible "
  1453. "by world size.")
  1454. @dataclass
  1455. class PromptAdapterConfig:
  1456. max_prompt_adapters: int
  1457. max_prompt_adapter_token: int
  1458. max_cpu_prompt_adapters: Optional[int] = None
  1459. prompt_adapter_dtype: Optional[torch.dtype] = None
  1460. def __post_init__(self):
  1461. library_name = 'peft'
  1462. try:
  1463. __import__(library_name)
  1464. except ImportError as e:
  1465. raise ImportError(
  1466. f"'{library_name}' is not installed for prompt adapter support."
  1467. f"Please install it using 'pip install {library_name}'."
  1468. ) from e
  1469. if self.max_prompt_adapters < 1:
  1470. raise ValueError(f"max_prompt_adapters "
  1471. f"({self.max_prompt_adapters}) must be >= 1.")
  1472. if self.max_prompt_adapter_token == 0:
  1473. raise ValueError("max_prompt_adapter_token must be set.")
  1474. if self.max_cpu_prompt_adapters is None:
  1475. self.max_cpu_prompt_adapters = self.max_prompt_adapters
  1476. def verify_with_model_config(self, model_config: ModelConfig):
  1477. if self.prompt_adapter_dtype in (None, "auto"):
  1478. self.prompt_adapter_dtype = model_config.dtype
  1479. elif isinstance(self.prompt_adapter_dtype, str):
  1480. self.prompt_adapter_dtype = getattr(torch,
  1481. self.prompt_adapter_dtype)
  1482. @dataclass
  1483. class MultiModalConfig:
  1484. """Controls the behavior of multimodal models."""
  1485. limit_per_prompt: Mapping[str, int] = field(default_factory=dict)
  1486. """
  1487. The maximum number of multi-modal input instances allowed per prompt
  1488. for each :class:`~aphrodite.multimodal.MultiModalPlugin`.
  1489. """
  1490. # TODO: Add configs to init vision tower or not.
  1491. _STR_DTYPE_TO_TORCH_DTYPE = {
  1492. "half": torch.float16,
  1493. "float16": torch.float16,
  1494. "float": torch.float32,
  1495. "float32": torch.float32,
  1496. "bfloat16": torch.bfloat16,
  1497. }
  1498. _ROCM_NOT_SUPPORTED_DTYPE = ["float", "float32"]
  1499. def _get_and_verify_dtype(
  1500. config: PretrainedConfig,
  1501. dtype: Union[str, torch.dtype],
  1502. ) -> torch.dtype:
  1503. # NOTE: getattr(config, "torch_dtype", torch.float32) is not correct
  1504. # because config.torch_dtype can be None.
  1505. config_dtype = getattr(config, "torch_dtype", None)
  1506. if config_dtype is None:
  1507. config_dtype = torch.float32
  1508. if isinstance(dtype, str):
  1509. dtype = dtype.lower()
  1510. if dtype == "auto":
  1511. if config_dtype == torch.float32:
  1512. if config.model_type == "gemma2":
  1513. logger.info(
  1514. "For Gemma 2, we downcast float32 to bfloat16 instead "
  1515. "of float16 by default. Please specify `dtype` if you "
  1516. "want to use float16.")
  1517. torch_dtype = torch.bfloat16
  1518. else:
  1519. # Following the common practice, we use float16 for float32
  1520. # models.
  1521. torch_dtype = torch.float16
  1522. else:
  1523. torch_dtype = config_dtype
  1524. else:
  1525. if dtype not in _STR_DTYPE_TO_TORCH_DTYPE:
  1526. raise ValueError(f"Unknown dtype: {dtype}")
  1527. torch_dtype = _STR_DTYPE_TO_TORCH_DTYPE[dtype]
  1528. elif isinstance(dtype, torch.dtype):
  1529. torch_dtype = dtype
  1530. else:
  1531. raise ValueError(f"Unknown dtype: {dtype}")
  1532. if is_hip() and torch_dtype == torch.float32:
  1533. rocm_supported_dtypes = [
  1534. k for k, v in _STR_DTYPE_TO_TORCH_DTYPE.items()
  1535. if (k not in _ROCM_NOT_SUPPORTED_DTYPE)
  1536. ]
  1537. raise ValueError(f"dtype '{dtype}' is not supported in ROCm. "
  1538. f"Supported dtypes are {rocm_supported_dtypes}")
  1539. # Verify the dtype.
  1540. if torch_dtype != config_dtype:
  1541. if torch_dtype == torch.float32:
  1542. # Upcasting to float32 is allowed.
  1543. pass
  1544. elif config_dtype == torch.float32:
  1545. # Downcasting from float32 to float16 or bfloat16 is allowed.
  1546. pass
  1547. else:
  1548. # Casting between float16 and bfloat16 is allowed with a warning.
  1549. logger.warning(f"Casting {config_dtype} to {torch_dtype}.")
  1550. return torch_dtype
  1551. def _get_and_verify_max_len(
  1552. hf_config: PretrainedConfig,
  1553. max_model_len: Optional[int],
  1554. disable_sliding_window: bool,
  1555. sliding_window_len: Optional[Union[int, List[Optional[int]]]],
  1556. rope_scaling_arg: Optional[Dict[str, Any]],
  1557. spec_target_max_model_len: Optional[int] = None,
  1558. ) -> int:
  1559. """Get and verify the model's maximum length."""
  1560. derived_max_model_len = float("inf")
  1561. possible_keys = [
  1562. # Cohere: needs to prioritize this over "max_position_embeddings"
  1563. "model_max_length",
  1564. # OPT
  1565. "max_position_embeddings",
  1566. # GPT-2
  1567. "n_positions",
  1568. # MPT
  1569. "max_seq_len",
  1570. # ChatGLM2
  1571. "seq_length",
  1572. # Command-R
  1573. "model_max_length",
  1574. # Others
  1575. "max_sequence_length",
  1576. "max_seq_length",
  1577. "seq_len",
  1578. ]
  1579. # Choose the smallest "max_length" from the possible keys.
  1580. max_len_key = None
  1581. for key in possible_keys:
  1582. max_len = getattr(hf_config, key, None)
  1583. if max_len is not None:
  1584. max_len_key = key if max_len < derived_max_model_len \
  1585. else max_len_key
  1586. derived_max_model_len = min(derived_max_model_len, max_len)
  1587. # If sliding window is manually disabled, max_length should be less
  1588. # than the sliding window length in the model config.
  1589. if disable_sliding_window and sliding_window_len is not None:
  1590. sliding_window_len_min = get_min_sliding_window(sliding_window_len)
  1591. max_len_key = "sliding_window" \
  1592. if sliding_window_len_min < derived_max_model_len else max_len_key
  1593. derived_max_model_len = min(derived_max_model_len,
  1594. sliding_window_len_min)
  1595. # If none of the keys were found in the config, use a default and
  1596. # log a warning.
  1597. if derived_max_model_len == float("inf"):
  1598. if max_model_len is not None:
  1599. # If max_model_len is specified, we use it.
  1600. return max_model_len
  1601. if spec_target_max_model_len is not None:
  1602. # If this is a speculative draft model, we use the max model len
  1603. # from the target model.
  1604. return spec_target_max_model_len
  1605. default_max_len = 2048
  1606. logger.warning(
  1607. "The model's config.json does not contain any of the following "
  1608. "keys to determine the original maximum length of the model: "
  1609. f"{possible_keys}. Assuming the model's maximum length is "
  1610. f"{default_max_len}.")
  1611. derived_max_model_len = default_max_len
  1612. rope_scaling = getattr(hf_config, "rope_scaling", None)
  1613. if rope_scaling is not None:
  1614. rope_type = rope_scaling.get("type", rope_scaling.get("rope_type"))
  1615. if rope_type not in {"su", "longrope", "llama3"}:
  1616. if disable_sliding_window:
  1617. # TODO: Find a model that supports rope_scaling
  1618. # with sliding window to see if this case should be allowed.
  1619. raise NotImplementedError(
  1620. "Disabling sliding window is not supported for models "
  1621. "with rope_scaling. Please raise an issue so we can "
  1622. "investigate.")
  1623. if rope_type == "mrope" or (
  1624. rope_type == "default" and "mrope_section" in rope_scaling):
  1625. scaling_factor = 1
  1626. else:
  1627. assert "factor" in rope_scaling
  1628. scaling_factor = rope_scaling["factor"]
  1629. if rope_type == "yarn":
  1630. derived_max_model_len = rope_scaling[
  1631. "original_max_position_embeddings"]
  1632. derived_max_model_len *= scaling_factor
  1633. # If the user specified a max length, make sure it is smaller than the
  1634. # derived length from the HF model config.
  1635. if max_model_len is None:
  1636. max_model_len = int(derived_max_model_len)
  1637. elif max_model_len > derived_max_model_len:
  1638. # Some models might have a separate key for specifying model_max_length
  1639. # that will be bigger than derived_max_model_len. We compare user input
  1640. # with model_max_length and allow this override when it's smaller.
  1641. model_max_length = getattr(hf_config, "model_max_length", None)
  1642. if envs.APHRODITE_DYNAMIC_ROPE_SCALING:
  1643. scaling_factor = max_model_len / derived_max_model_len
  1644. hf_config.rope_scaling = {"factor": scaling_factor,
  1645. "type": "dynamic"}
  1646. logger.info(
  1647. "Using dynamic RoPE scaling to extend the model's max context "
  1648. f"length from {derived_max_model_len} to {max_model_len}.")
  1649. derived_max_model_len = max_model_len
  1650. elif model_max_length is not None and max_model_len <= model_max_length:
  1651. if disable_sliding_window:
  1652. # TODO: Find a model that has model_max_length
  1653. # with sliding window to see if this case should be allowed.
  1654. raise NotImplementedError(
  1655. "Disabling sliding window is not supported for models "
  1656. "model_max_length in the config. Please raise an issue "
  1657. "so we can investigate.")
  1658. else:
  1659. raise ValueError(
  1660. f"User-specified max_model_len ({max_model_len}) is greater "
  1661. f"than the derived max_model_len ({max_len_key}="
  1662. f"{derived_max_model_len} or model_max_length="
  1663. f"{model_max_length} in model's config.json). To allow "
  1664. "greater lengths, please set the env var "
  1665. "APHRODITE_DYNAMIC_ROPE_SCALING=1")
  1666. return int(max_model_len)
  1667. def get_min_sliding_window(
  1668. sliding_window: Union[int, List[Optional[int]]]) -> int:
  1669. if isinstance(sliding_window, list):
  1670. return min(s for s in sliding_window if s is not None)
  1671. return sliding_window
  1672. def get_served_model_name(model: str,
  1673. served_model_name: Optional[Union[str, List[str]]]):
  1674. """
  1675. If the input is a non-empty list, the first model_name in
  1676. `served_model_name` is taken.
  1677. If the input is a non-empty string, it is used directly.
  1678. For cases where the input is either an empty string or an
  1679. empty list, the fallback is to use `self.model`.
  1680. """
  1681. if not served_model_name:
  1682. return model
  1683. if isinstance(served_model_name, list):
  1684. return served_model_name[0]
  1685. return served_model_name
  1686. @dataclass
  1687. class DecodingConfig:
  1688. """Dataclass which contains the decoding strategy of the engine"""
  1689. # Which guided decoding algo to use. 'outlines' / 'lm-format-enforcer'
  1690. guided_decoding_backend: str = 'lm-format-enforcer'
  1691. def __post_init__(self):
  1692. valid_guided_backends = ['outlines', 'lm-format-enforcer']
  1693. backend = self.guided_decoding_backend
  1694. if backend not in valid_guided_backends:
  1695. raise ValueError(f"Invalid guided_decoding_backend '{backend},"
  1696. f"must be one of {valid_guided_backends}")
  1697. @dataclass(frozen=True)
  1698. class EngineConfig:
  1699. """Dataclass which contains all engine-related configuration. This
  1700. simplifies passing around the distinct configurations in the codebase.
  1701. """
  1702. model_config: ModelConfig
  1703. cache_config: CacheConfig
  1704. parallel_config: ParallelConfig
  1705. scheduler_config: SchedulerConfig
  1706. device_config: DeviceConfig
  1707. load_config: LoadConfig
  1708. lora_config: Optional[LoRAConfig]
  1709. speculative_config: Optional[SpeculativeConfig]
  1710. decoding_config: Optional[DecodingConfig]
  1711. prompt_adapter_config: Optional[PromptAdapterConfig]
  1712. def __post_init__(self):
  1713. """Verify configs are valid & consistent with each other.
  1714. """
  1715. self.model_config.verify_with_parallel_config(self.parallel_config)
  1716. self.cache_config.verify_with_parallel_config(self.parallel_config)
  1717. if self.lora_config:
  1718. self.lora_config.verify_with_model_config(self.model_config)
  1719. self.lora_config.verify_with_scheduler_config(
  1720. self.scheduler_config)
  1721. self.lora_config.verify_with_parallel_config(self.parallel_config)
  1722. if self.prompt_adapter_config:
  1723. self.prompt_adapter_config.verify_with_model_config(
  1724. self.model_config)
  1725. def to_dict(self):
  1726. """Return the configs as a dictionary, for use in **kwargs.
  1727. """
  1728. return dict(
  1729. (field.name, getattr(self, field.name)) for field in fields(self))