config.py 62 KB

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