config.py 85 KB

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