config.py 77 KB

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