config.py 88 KB

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