config.py 90 KB

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