config.py 74 KB

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