config.py 52 KB

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