config.py 82 KB

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