config.py 73 KB

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