config.py 85 KB

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