config.py 78 KB

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