config.py 83 KB

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