config.py 90 KB

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