config.py 60 KB

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