config.py 89 KB

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