config.py 81 KB

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