vllm-cpu-avx512bf16 0.9.0.post2__cp310-cp310-manylinux_2_17_x86_64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1175) hide show
  1. vllm/_C.abi3.so +0 -0
  2. vllm/__init__.py +170 -0
  3. vllm/_custom_ops.py +1742 -0
  4. vllm/_ipex_ops.py +243 -0
  5. vllm/_version.py +34 -0
  6. vllm/adapter_commons/__init__.py +0 -0
  7. vllm/adapter_commons/layers.py +15 -0
  8. vllm/adapter_commons/models.py +105 -0
  9. vllm/adapter_commons/request.py +25 -0
  10. vllm/adapter_commons/utils.py +92 -0
  11. vllm/adapter_commons/worker_manager.py +38 -0
  12. vllm/assets/__init__.py +0 -0
  13. vllm/assets/audio.py +44 -0
  14. vllm/assets/base.py +40 -0
  15. vllm/assets/image.py +33 -0
  16. vllm/assets/video.py +114 -0
  17. vllm/attention/__init__.py +19 -0
  18. vllm/attention/backends/__init__.py +0 -0
  19. vllm/attention/backends/abstract.py +306 -0
  20. vllm/attention/backends/blocksparse_attn.py +457 -0
  21. vllm/attention/backends/cpu_mla.py +305 -0
  22. vllm/attention/backends/dual_chunk_flash_attn.py +1494 -0
  23. vllm/attention/backends/flash_attn.py +999 -0
  24. vllm/attention/backends/flashinfer.py +1100 -0
  25. vllm/attention/backends/flashmla.py +242 -0
  26. vllm/attention/backends/hpu_attn.py +309 -0
  27. vllm/attention/backends/ipex_attn.py +394 -0
  28. vllm/attention/backends/mla/__init__.py +0 -0
  29. vllm/attention/backends/mla/common.py +1381 -0
  30. vllm/attention/backends/pallas.py +347 -0
  31. vllm/attention/backends/placeholder_attn.py +399 -0
  32. vllm/attention/backends/rocm_aiter_mla.py +435 -0
  33. vllm/attention/backends/rocm_flash_attn.py +970 -0
  34. vllm/attention/backends/torch_sdpa.py +691 -0
  35. vllm/attention/backends/triton_mla.py +113 -0
  36. vllm/attention/backends/utils.py +609 -0
  37. vllm/attention/backends/xformers.py +798 -0
  38. vllm/attention/layer.py +452 -0
  39. vllm/attention/ops/__init__.py +0 -0
  40. vllm/attention/ops/blocksparse_attention/__init__.py +0 -0
  41. vllm/attention/ops/blocksparse_attention/blocksparse_attention_kernel.py +432 -0
  42. vllm/attention/ops/blocksparse_attention/interface.py +238 -0
  43. vllm/attention/ops/blocksparse_attention/utils.py +245 -0
  44. vllm/attention/ops/chunked_prefill_paged_decode.py +367 -0
  45. vllm/attention/ops/flashmla.py +115 -0
  46. vllm/attention/ops/hpu_paged_attn.py +87 -0
  47. vllm/attention/ops/ipex_attn.py +194 -0
  48. vllm/attention/ops/merge_attn_states.py +42 -0
  49. vllm/attention/ops/nki_flash_attn.py +905 -0
  50. vllm/attention/ops/paged_attn.py +255 -0
  51. vllm/attention/ops/prefix_prefill.py +901 -0
  52. vllm/attention/ops/rocm_aiter_mla.py +99 -0
  53. vllm/attention/ops/rocm_aiter_paged_attn.py +101 -0
  54. vllm/attention/ops/triton_decode_attention.py +673 -0
  55. vllm/attention/ops/triton_flash_attention.py +1374 -0
  56. vllm/attention/ops/triton_merge_attn_states.py +96 -0
  57. vllm/attention/ops/triton_unified_attention.py +337 -0
  58. vllm/attention/selector.py +186 -0
  59. vllm/attention/utils/fa_utils.py +54 -0
  60. vllm/beam_search.py +82 -0
  61. vllm/benchmarks/__init__.py +0 -0
  62. vllm/benchmarks/datasets.py +921 -0
  63. vllm/benchmarks/endpoint_request_func.py +160 -0
  64. vllm/benchmarks/latency.py +184 -0
  65. vllm/benchmarks/serve.py +925 -0
  66. vllm/benchmarks/throughput.py +609 -0
  67. vllm/benchmarks/utils.py +69 -0
  68. vllm/collect_env.py +818 -0
  69. vllm/compilation/__init__.py +0 -0
  70. vllm/compilation/activation_quant_fusion.py +88 -0
  71. vllm/compilation/backends.py +560 -0
  72. vllm/compilation/base_piecewise_backend.py +71 -0
  73. vllm/compilation/collective_fusion.py +126 -0
  74. vllm/compilation/compiler_interface.py +533 -0
  75. vllm/compilation/counter.py +33 -0
  76. vllm/compilation/cuda_piecewise_backend.py +213 -0
  77. vllm/compilation/decorators.py +249 -0
  78. vllm/compilation/fix_functionalization.py +190 -0
  79. vllm/compilation/fusion.py +617 -0
  80. vllm/compilation/fx_utils.py +61 -0
  81. vllm/compilation/inductor_pass.py +114 -0
  82. vllm/compilation/monitor.py +38 -0
  83. vllm/compilation/multi_output_match.py +108 -0
  84. vllm/compilation/noop_elimination.py +136 -0
  85. vllm/compilation/pass_manager.py +77 -0
  86. vllm/compilation/sequence_parallelism.py +267 -0
  87. vllm/compilation/torch25_custom_graph_pass.py +41 -0
  88. vllm/compilation/vllm_inductor_pass.py +66 -0
  89. vllm/compilation/wrapper.py +129 -0
  90. vllm/config.py +4600 -0
  91. vllm/connections.py +173 -0
  92. vllm/core/__init__.py +0 -0
  93. vllm/core/block/__init__.py +0 -0
  94. vllm/core/block/block_table.py +398 -0
  95. vllm/core/block/common.py +370 -0
  96. vllm/core/block/cpu_gpu_block_allocator.py +440 -0
  97. vllm/core/block/interfaces.py +318 -0
  98. vllm/core/block/naive_block.py +465 -0
  99. vllm/core/block/prefix_caching_block.py +1134 -0
  100. vllm/core/block/utils.py +27 -0
  101. vllm/core/block_manager.py +520 -0
  102. vllm/core/evictor.py +156 -0
  103. vllm/core/interfaces.py +134 -0
  104. vllm/core/placeholder_block_space_manager.py +99 -0
  105. vllm/core/scheduler.py +2092 -0
  106. vllm/device_allocator/__init__.py +0 -0
  107. vllm/device_allocator/cumem.py +280 -0
  108. vllm/distributed/__init__.py +5 -0
  109. vllm/distributed/communication_op.py +40 -0
  110. vllm/distributed/device_communicators/__init__.py +0 -0
  111. vllm/distributed/device_communicators/all2all.py +126 -0
  112. vllm/distributed/device_communicators/base_device_communicator.py +260 -0
  113. vllm/distributed/device_communicators/cpu_communicator.py +144 -0
  114. vllm/distributed/device_communicators/cuda_communicator.py +167 -0
  115. vllm/distributed/device_communicators/cuda_wrapper.py +179 -0
  116. vllm/distributed/device_communicators/custom_all_reduce.py +303 -0
  117. vllm/distributed/device_communicators/custom_all_reduce_utils.py +258 -0
  118. vllm/distributed/device_communicators/hpu_communicator.py +45 -0
  119. vllm/distributed/device_communicators/neuron_communicator.py +19 -0
  120. vllm/distributed/device_communicators/pynccl.py +217 -0
  121. vllm/distributed/device_communicators/pynccl_wrapper.py +340 -0
  122. vllm/distributed/device_communicators/shm_broadcast.py +541 -0
  123. vllm/distributed/device_communicators/tpu_communicator.py +102 -0
  124. vllm/distributed/device_communicators/xpu_communicator.py +54 -0
  125. vllm/distributed/kv_events.py +296 -0
  126. vllm/distributed/kv_transfer/README.md +29 -0
  127. vllm/distributed/kv_transfer/__init__.py +11 -0
  128. vllm/distributed/kv_transfer/disagg_prefill_workflow.jpg +0 -0
  129. vllm/distributed/kv_transfer/kv_connector/__init__.py +0 -0
  130. vllm/distributed/kv_transfer/kv_connector/base.py +127 -0
  131. vllm/distributed/kv_transfer/kv_connector/factory.py +126 -0
  132. vllm/distributed/kv_transfer/kv_connector/lmcache_connector.py +98 -0
  133. vllm/distributed/kv_transfer/kv_connector/mooncake_store_connector.py +202 -0
  134. vllm/distributed/kv_transfer/kv_connector/simple_connector.py +328 -0
  135. vllm/distributed/kv_transfer/kv_connector/utils.py +91 -0
  136. vllm/distributed/kv_transfer/kv_connector/v1/__init__.py +5 -0
  137. vllm/distributed/kv_transfer/kv_connector/v1/base.py +259 -0
  138. vllm/distributed/kv_transfer/kv_connector/v1/lmcache_connector.py +133 -0
  139. vllm/distributed/kv_transfer/kv_connector/v1/multi_connector.py +189 -0
  140. vllm/distributed/kv_transfer/kv_connector/v1/nixl_connector.py +851 -0
  141. vllm/distributed/kv_transfer/kv_connector/v1/shared_storage_connector.py +383 -0
  142. vllm/distributed/kv_transfer/kv_connector_agent.py +76 -0
  143. vllm/distributed/kv_transfer/kv_lookup_buffer/__init__.py +0 -0
  144. vllm/distributed/kv_transfer/kv_lookup_buffer/base.py +174 -0
  145. vllm/distributed/kv_transfer/kv_lookup_buffer/mooncake_store.py +160 -0
  146. vllm/distributed/kv_transfer/kv_lookup_buffer/simple_buffer.py +236 -0
  147. vllm/distributed/kv_transfer/kv_pipe/__init__.py +0 -0
  148. vllm/distributed/kv_transfer/kv_pipe/base.py +66 -0
  149. vllm/distributed/kv_transfer/kv_pipe/mooncake_pipe.py +279 -0
  150. vllm/distributed/kv_transfer/kv_pipe/pynccl_pipe.py +279 -0
  151. vllm/distributed/kv_transfer/kv_transfer_state.py +70 -0
  152. vllm/distributed/parallel_state.py +1294 -0
  153. vllm/distributed/utils.py +520 -0
  154. vllm/engine/__init__.py +0 -0
  155. vllm/engine/arg_utils.py +1649 -0
  156. vllm/engine/async_llm_engine.py +1274 -0
  157. vllm/engine/async_timeout.py +191 -0
  158. vllm/engine/llm_engine.py +2153 -0
  159. vllm/engine/metrics.py +717 -0
  160. vllm/engine/metrics_types.py +96 -0
  161. vllm/engine/multiprocessing/__init__.py +188 -0
  162. vllm/engine/multiprocessing/client.py +755 -0
  163. vllm/engine/multiprocessing/engine.py +459 -0
  164. vllm/engine/output_processor/__init__.py +0 -0
  165. vllm/engine/output_processor/interfaces.py +74 -0
  166. vllm/engine/output_processor/multi_step.py +215 -0
  167. vllm/engine/output_processor/single_step.py +144 -0
  168. vllm/engine/output_processor/stop_checker.py +130 -0
  169. vllm/engine/output_processor/util.py +27 -0
  170. vllm/engine/protocol.py +310 -0
  171. vllm/entrypoints/__init__.py +0 -0
  172. vllm/entrypoints/api_server.py +177 -0
  173. vllm/entrypoints/chat_utils.py +1298 -0
  174. vllm/entrypoints/cli/__init__.py +0 -0
  175. vllm/entrypoints/cli/benchmark/__init__.py +0 -0
  176. vllm/entrypoints/cli/benchmark/base.py +38 -0
  177. vllm/entrypoints/cli/benchmark/latency.py +29 -0
  178. vllm/entrypoints/cli/benchmark/main.py +53 -0
  179. vllm/entrypoints/cli/benchmark/serve.py +29 -0
  180. vllm/entrypoints/cli/benchmark/throughput.py +29 -0
  181. vllm/entrypoints/cli/collect_env.py +34 -0
  182. vllm/entrypoints/cli/main.py +62 -0
  183. vllm/entrypoints/cli/openai.py +204 -0
  184. vllm/entrypoints/cli/serve.py +141 -0
  185. vllm/entrypoints/cli/types.py +24 -0
  186. vllm/entrypoints/launcher.py +146 -0
  187. vllm/entrypoints/llm.py +1503 -0
  188. vllm/entrypoints/logger.py +49 -0
  189. vllm/entrypoints/openai/__init__.py +0 -0
  190. vllm/entrypoints/openai/api_server.py +1376 -0
  191. vllm/entrypoints/openai/cli_args.py +306 -0
  192. vllm/entrypoints/openai/logits_processors.py +89 -0
  193. vllm/entrypoints/openai/protocol.py +1890 -0
  194. vllm/entrypoints/openai/run_batch.py +439 -0
  195. vllm/entrypoints/openai/serving_chat.py +1192 -0
  196. vllm/entrypoints/openai/serving_classification.py +159 -0
  197. vllm/entrypoints/openai/serving_completion.py +590 -0
  198. vllm/entrypoints/openai/serving_embedding.py +200 -0
  199. vllm/entrypoints/openai/serving_engine.py +985 -0
  200. vllm/entrypoints/openai/serving_models.py +314 -0
  201. vllm/entrypoints/openai/serving_pooling.py +231 -0
  202. vllm/entrypoints/openai/serving_score.py +432 -0
  203. vllm/entrypoints/openai/serving_tokenization.py +151 -0
  204. vllm/entrypoints/openai/serving_transcription.py +421 -0
  205. vllm/entrypoints/openai/tool_parsers/__init__.py +22 -0
  206. vllm/entrypoints/openai/tool_parsers/abstract_tool_parser.py +163 -0
  207. vllm/entrypoints/openai/tool_parsers/deepseekv3_tool_parser.py +369 -0
  208. vllm/entrypoints/openai/tool_parsers/granite_20b_fc_tool_parser.py +258 -0
  209. vllm/entrypoints/openai/tool_parsers/granite_tool_parser.py +236 -0
  210. vllm/entrypoints/openai/tool_parsers/hermes_tool_parser.py +370 -0
  211. vllm/entrypoints/openai/tool_parsers/internlm2_tool_parser.py +215 -0
  212. vllm/entrypoints/openai/tool_parsers/jamba_tool_parser.py +307 -0
  213. vllm/entrypoints/openai/tool_parsers/llama4_pythonic_tool_parser.py +302 -0
  214. vllm/entrypoints/openai/tool_parsers/llama_tool_parser.py +266 -0
  215. vllm/entrypoints/openai/tool_parsers/mistral_tool_parser.py +342 -0
  216. vllm/entrypoints/openai/tool_parsers/phi4mini_tool_parser.py +111 -0
  217. vllm/entrypoints/openai/tool_parsers/pythonic_tool_parser.py +296 -0
  218. vllm/entrypoints/openai/tool_parsers/utils.py +123 -0
  219. vllm/entrypoints/score_utils.py +49 -0
  220. vllm/entrypoints/ssl.py +74 -0
  221. vllm/entrypoints/utils.py +219 -0
  222. vllm/env_override.py +34 -0
  223. vllm/envs.py +896 -0
  224. vllm/executor/__init__.py +0 -0
  225. vllm/executor/executor_base.py +400 -0
  226. vllm/executor/mp_distributed_executor.py +243 -0
  227. vllm/executor/msgspec_utils.py +29 -0
  228. vllm/executor/multiproc_worker_utils.py +312 -0
  229. vllm/executor/ray_distributed_executor.py +700 -0
  230. vllm/executor/ray_utils.py +398 -0
  231. vllm/executor/uniproc_executor.py +138 -0
  232. vllm/forward_context.py +147 -0
  233. vllm/inputs/__init__.py +40 -0
  234. vllm/inputs/data.py +330 -0
  235. vllm/inputs/parse.py +150 -0
  236. vllm/inputs/preprocess.py +908 -0
  237. vllm/inputs/registry.py +214 -0
  238. vllm/jsontree.py +79 -0
  239. vllm/logger.py +211 -0
  240. vllm/logging_utils/__init__.py +7 -0
  241. vllm/logging_utils/dump_input.py +84 -0
  242. vllm/logging_utils/formatter.py +17 -0
  243. vllm/logits_process.py +118 -0
  244. vllm/lora/__init__.py +0 -0
  245. vllm/lora/fully_sharded_layers.py +354 -0
  246. vllm/lora/layers.py +1284 -0
  247. vllm/lora/lora.py +198 -0
  248. vllm/lora/models.py +817 -0
  249. vllm/lora/ops/__init__.py +0 -0
  250. vllm/lora/ops/torch_ops/__init__.py +15 -0
  251. vllm/lora/ops/torch_ops/lora_ops.py +115 -0
  252. vllm/lora/ops/triton_ops/__init__.py +11 -0
  253. vllm/lora/ops/triton_ops/kernel_utils.py +242 -0
  254. vllm/lora/ops/triton_ops/lora_expand_op.py +289 -0
  255. vllm/lora/ops/triton_ops/lora_kernel_metadata.py +147 -0
  256. vllm/lora/ops/triton_ops/lora_shrink_op.py +243 -0
  257. vllm/lora/ops/triton_ops/utils.py +119 -0
  258. vllm/lora/ops/xla_ops/__init__.py +6 -0
  259. vllm/lora/ops/xla_ops/lora_ops.py +106 -0
  260. vllm/lora/ops/xla_ops/pallas.py +133 -0
  261. vllm/lora/peft_helper.py +135 -0
  262. vllm/lora/punica_wrapper/__init__.py +9 -0
  263. vllm/lora/punica_wrapper/punica_base.py +484 -0
  264. vllm/lora/punica_wrapper/punica_cpu.py +348 -0
  265. vllm/lora/punica_wrapper/punica_gpu.py +289 -0
  266. vllm/lora/punica_wrapper/punica_hpu.py +144 -0
  267. vllm/lora/punica_wrapper/punica_selector.py +19 -0
  268. vllm/lora/punica_wrapper/punica_tpu.py +325 -0
  269. vllm/lora/punica_wrapper/utils.py +163 -0
  270. vllm/lora/request.py +98 -0
  271. vllm/lora/resolver.py +84 -0
  272. vllm/lora/utils.py +239 -0
  273. vllm/lora/worker_manager.py +253 -0
  274. vllm/model_executor/__init__.py +15 -0
  275. vllm/model_executor/custom_op.py +151 -0
  276. vllm/model_executor/guided_decoding/__init__.py +180 -0
  277. vllm/model_executor/guided_decoding/guidance_decoding.py +62 -0
  278. vllm/model_executor/guided_decoding/guidance_logits_processors.py +103 -0
  279. vllm/model_executor/guided_decoding/guided_fields.py +42 -0
  280. vllm/model_executor/guided_decoding/lm_format_enforcer_decoding.py +66 -0
  281. vllm/model_executor/guided_decoding/outlines_decoding.py +154 -0
  282. vllm/model_executor/guided_decoding/outlines_logits_processors.py +283 -0
  283. vllm/model_executor/guided_decoding/utils.py +241 -0
  284. vllm/model_executor/guided_decoding/xgrammar_decoding.py +425 -0
  285. vllm/model_executor/layers/__init__.py +0 -0
  286. vllm/model_executor/layers/activation.py +368 -0
  287. vllm/model_executor/layers/fused_moe/__init__.py +53 -0
  288. vllm/model_executor/layers/fused_moe/configs/E=1,N=14336,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a16.json +146 -0
  289. vllm/model_executor/layers/fused_moe/configs/E=1,N=14336,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  290. vllm/model_executor/layers/fused_moe/configs/E=1,N=1792,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a16.json +218 -0
  291. vllm/model_executor/layers/fused_moe/configs/E=1,N=1792,device_name=NVIDIA_A100-SXM4-80GB.json +218 -0
  292. vllm/model_executor/layers/fused_moe/configs/E=1,N=3072,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a16.json +218 -0
  293. vllm/model_executor/layers/fused_moe/configs/E=1,N=3072,device_name=NVIDIA_H100_80GB_HBM3,dtype=int8_w8a16.json +218 -0
  294. vllm/model_executor/layers/fused_moe/configs/E=1,N=3072,device_name=NVIDIA_H100_80GB_HBM3.json +218 -0
  295. vllm/model_executor/layers/fused_moe/configs/E=1,N=3584,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a16.json +218 -0
  296. vllm/model_executor/layers/fused_moe/configs/E=1,N=3584,device_name=NVIDIA_A100-SXM4-80GB.json +218 -0
  297. vllm/model_executor/layers/fused_moe/configs/E=1,N=7168,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a16.json +218 -0
  298. vllm/model_executor/layers/fused_moe/configs/E=1,N=7168,device_name=NVIDIA_A100-SXM4-80GB.json +218 -0
  299. vllm/model_executor/layers/fused_moe/configs/E=128,N=1024,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json +164 -0
  300. vllm/model_executor/layers/fused_moe/configs/E=128,N=1024,device_name=AMD_Instinct_MI300X.json +200 -0
  301. vllm/model_executor/layers/fused_moe/configs/E=128,N=192,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  302. vllm/model_executor/layers/fused_moe/configs/E=128,N=192,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  303. vllm/model_executor/layers/fused_moe/configs/E=128,N=192,device_name=NVIDIA_H20.json +146 -0
  304. vllm/model_executor/layers/fused_moe/configs/E=128,N=192,device_name=NVIDIA_H200.json +146 -0
  305. vllm/model_executor/layers/fused_moe/configs/E=128,N=384,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  306. vllm/model_executor/layers/fused_moe/configs/E=128,N=384,device_name=NVIDIA_H20,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  307. vllm/model_executor/layers/fused_moe/configs/E=128,N=384,device_name=NVIDIA_H20.json +146 -0
  308. vllm/model_executor/layers/fused_moe/configs/E=128,N=384,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  309. vllm/model_executor/layers/fused_moe/configs/E=128,N=384,device_name=NVIDIA_H200.json +146 -0
  310. vllm/model_executor/layers/fused_moe/configs/E=128,N=512,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  311. vllm/model_executor/layers/fused_moe/configs/E=128,N=768,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  312. vllm/model_executor/layers/fused_moe/configs/E=128,N=768,device_name=NVIDIA_H20,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  313. vllm/model_executor/layers/fused_moe/configs/E=128,N=768,device_name=NVIDIA_H20.json +146 -0
  314. vllm/model_executor/layers/fused_moe/configs/E=128,N=768,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  315. vllm/model_executor/layers/fused_moe/configs/E=128,N=768,device_name=NVIDIA_H200.json +146 -0
  316. vllm/model_executor/layers/fused_moe/configs/E=128,N=96,device_name=NVIDIA_H20.json +146 -0
  317. vllm/model_executor/layers/fused_moe/configs/E=16,N=1024,device_name=AMD_Instinct_MI300X.json +200 -0
  318. vllm/model_executor/layers/fused_moe/configs/E=16,N=1024,device_name=NVIDIA_H100.json +146 -0
  319. vllm/model_executor/layers/fused_moe/configs/E=16,N=1344,device_name=NVIDIA_A100-SXM4-40GB.json +146 -0
  320. vllm/model_executor/layers/fused_moe/configs/E=16,N=1344,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  321. vllm/model_executor/layers/fused_moe/configs/E=16,N=1344,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  322. vllm/model_executor/layers/fused_moe/configs/E=16,N=14336,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a16.json +146 -0
  323. vllm/model_executor/layers/fused_moe/configs/E=16,N=14336,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  324. vllm/model_executor/layers/fused_moe/configs/E=16,N=1792,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a16.json +218 -0
  325. vllm/model_executor/layers/fused_moe/configs/E=16,N=1792,device_name=NVIDIA_A100-SXM4-80GB.json +218 -0
  326. vllm/model_executor/layers/fused_moe/configs/E=16,N=2688,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  327. vllm/model_executor/layers/fused_moe/configs/E=16,N=2688,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  328. vllm/model_executor/layers/fused_moe/configs/E=16,N=3072,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a16.json +146 -0
  329. vllm/model_executor/layers/fused_moe/configs/E=16,N=3072,device_name=NVIDIA_H100_80GB_HBM3,dtype=int8_w8a16.json +146 -0
  330. vllm/model_executor/layers/fused_moe/configs/E=16,N=3200,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json +130 -0
  331. vllm/model_executor/layers/fused_moe/configs/E=16,N=3584,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a16.json +146 -0
  332. vllm/model_executor/layers/fused_moe/configs/E=16,N=3584,device_name=NVIDIA_A100-SXM4-80GB.json +218 -0
  333. vllm/model_executor/layers/fused_moe/configs/E=16,N=6400,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json +130 -0
  334. vllm/model_executor/layers/fused_moe/configs/E=16,N=7168,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a16.json +146 -0
  335. vllm/model_executor/layers/fused_moe/configs/E=16,N=7168,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  336. vllm/model_executor/layers/fused_moe/configs/E=16,N=7168,device_name=NVIDIA_H100_80GB_HBM3,dtype=int8_w8a16.json +146 -0
  337. vllm/model_executor/layers/fused_moe/configs/E=16,N=800,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json +130 -0
  338. vllm/model_executor/layers/fused_moe/configs/E=160,N=192,device_name=NVIDIA_A800-SXM4-80GB.json +146 -0
  339. vllm/model_executor/layers/fused_moe/configs/E=256,N=1024,device_name=AMD_Instinct_MI325X,block_shape=[128,128].json +200 -0
  340. vllm/model_executor/layers/fused_moe/configs/E=256,N=1024,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json +200 -0
  341. vllm/model_executor/layers/fused_moe/configs/E=256,N=128,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  342. vllm/model_executor/layers/fused_moe/configs/E=256,N=128,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a8.json +146 -0
  343. vllm/model_executor/layers/fused_moe/configs/E=256,N=128,device_name=NVIDIA_A800-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  344. vllm/model_executor/layers/fused_moe/configs/E=256,N=128,device_name=NVIDIA_A800-SXM4-80GB,dtype=int8_w8a8.json +146 -0
  345. vllm/model_executor/layers/fused_moe/configs/E=256,N=128,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  346. vllm/model_executor/layers/fused_moe/configs/E=256,N=128,device_name=NVIDIA_H20,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  347. vllm/model_executor/layers/fused_moe/configs/E=256,N=128,device_name=NVIDIA_L20Y,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  348. vllm/model_executor/layers/fused_moe/configs/E=256,N=256,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  349. vllm/model_executor/layers/fused_moe/configs/E=256,N=256,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json +200 -0
  350. vllm/model_executor/layers/fused_moe/configs/E=256,N=256,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json +200 -0
  351. vllm/model_executor/layers/fused_moe/configs/E=256,N=256,device_name=NVIDIA_B200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  352. vllm/model_executor/layers/fused_moe/configs/E=256,N=256,device_name=NVIDIA_H20,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  353. vllm/model_executor/layers/fused_moe/configs/E=256,N=256,device_name=NVIDIA_H20,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  354. vllm/model_executor/layers/fused_moe/configs/E=256,N=256,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  355. vllm/model_executor/layers/fused_moe/configs/E=256,N=256,device_name=NVIDIA_L20,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  356. vllm/model_executor/layers/fused_moe/configs/E=256,N=512,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json +200 -0
  357. vllm/model_executor/layers/fused_moe/configs/E=256,N=64,device_name=NVIDIA_A800-SXM4-80GB.json +146 -0
  358. vllm/model_executor/layers/fused_moe/configs/E=60,N=1408,device_name=AMD_Instinct_MI300X.json +200 -0
  359. vllm/model_executor/layers/fused_moe/configs/E=60,N=176,device_name=AMD_Instinct_MI300X.json +200 -0
  360. vllm/model_executor/layers/fused_moe/configs/E=60,N=352,device_name=AMD_Instinct_MI300X.json +200 -0
  361. vllm/model_executor/layers/fused_moe/configs/E=60,N=704,device_name=AMD_Instinct_MI300X.json +200 -0
  362. vllm/model_executor/layers/fused_moe/configs/E=64,N=1280,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  363. vllm/model_executor/layers/fused_moe/configs/E=64,N=1280,device_name=NVIDIA_A800-SXM4-80GB.json +146 -0
  364. vllm/model_executor/layers/fused_moe/configs/E=64,N=1280,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json +146 -0
  365. vllm/model_executor/layers/fused_moe/configs/E=64,N=1280,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  366. vllm/model_executor/layers/fused_moe/configs/E=64,N=1280,device_name=NVIDIA_H200,dtype=fp8_w8a8.json +146 -0
  367. vllm/model_executor/layers/fused_moe/configs/E=64,N=1280,device_name=NVIDIA_H200.json +146 -0
  368. vllm/model_executor/layers/fused_moe/configs/E=64,N=2560,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json +146 -0
  369. vllm/model_executor/layers/fused_moe/configs/E=64,N=2560,device_name=NVIDIA_H200,dtype=fp8_w8a8.json +146 -0
  370. vllm/model_executor/layers/fused_moe/configs/E=64,N=2560,device_name=NVIDIA_H200.json +146 -0
  371. vllm/model_executor/layers/fused_moe/configs/E=64,N=320,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json +146 -0
  372. vllm/model_executor/layers/fused_moe/configs/E=64,N=320,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  373. vllm/model_executor/layers/fused_moe/configs/E=64,N=320,device_name=NVIDIA_H200,dtype=fp8_w8a8.json +146 -0
  374. vllm/model_executor/layers/fused_moe/configs/E=64,N=320,device_name=NVIDIA_H200.json +146 -0
  375. vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  376. vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_A800-SXM4-80GB.json +146 -0
  377. vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_GeForce_RTX_4090,dtype=fp8_w8a8.json +146 -0
  378. vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json +146 -0
  379. vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  380. vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_H200,dtype=fp8_w8a8.json +146 -0
  381. vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_H200.json +146 -0
  382. vllm/model_executor/layers/fused_moe/configs/E=64,N=896,device_name=NVIDIA_H20.json +146 -0
  383. vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json +164 -0
  384. vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=AMD_Instinct_MI300X.json +200 -0
  385. vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json +164 -0
  386. vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=AMD_Instinct_MI325X.json +200 -0
  387. vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json +138 -0
  388. vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=NVIDIA_H200,dtype=fp8_w8a8.json +146 -0
  389. vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=NVIDIA_H200.json +146 -0
  390. vllm/model_executor/layers/fused_moe/configs/E=8,N=16384,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json +164 -0
  391. vllm/model_executor/layers/fused_moe/configs/E=8,N=16384,device_name=AMD_Instinct_MI300X.json +200 -0
  392. vllm/model_executor/layers/fused_moe/configs/E=8,N=16384,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json +164 -0
  393. vllm/model_executor/layers/fused_moe/configs/E=8,N=16384,device_name=AMD_Instinct_MI325X.json +200 -0
  394. vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json +164 -0
  395. vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=AMD_Instinct_MI300X.json +200 -0
  396. vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json +164 -0
  397. vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=AMD_Instinct_MI325X.json +200 -0
  398. vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_A100-SXM4-40GB.json +146 -0
  399. vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  400. vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  401. vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_H200,dtype=fp8_w8a8.json +146 -0
  402. vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_H200.json +146 -0
  403. vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json +164 -0
  404. vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=AMD_Instinct_MI300X.json +200 -0
  405. vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json +164 -0
  406. vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=AMD_Instinct_MI325X.json +200 -0
  407. vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  408. vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json +146 -0
  409. vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  410. vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_H200,dtype=fp8_w8a8.json +146 -0
  411. vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_H200.json +146 -0
  412. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json +164 -0
  413. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=AMD_Instinct_MI300X.json +200 -0
  414. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json +164 -0
  415. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=AMD_Instinct_MI325X.json +200 -0
  416. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_A100-SXM4-40GB.json +146 -0
  417. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  418. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_GeForce_RTX_4090,dtype=fp8_w8a8.json +146 -0
  419. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json +146 -0
  420. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  421. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_H200,dtype=fp8_w8a8.json +146 -0
  422. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_H200.json +146 -0
  423. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_L40S.json +173 -0
  424. vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json +164 -0
  425. vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=AMD_Instinct_MI300X.json +200 -0
  426. vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json +164 -0
  427. vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=AMD_Instinct_MI325X.json +200 -0
  428. vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  429. vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json +146 -0
  430. vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  431. vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_H200,dtype=fp8_w8a8.json +146 -0
  432. vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_H200.json +146 -0
  433. vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json +164 -0
  434. vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=AMD_Instinct_MI300X.json +200 -0
  435. vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json +164 -0
  436. vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=AMD_Instinct_MI325X.json +200 -0
  437. vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  438. vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json +146 -0
  439. vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  440. vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_H200,dtype=fp8_w8a8.json +146 -0
  441. vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_H200.json +146 -0
  442. vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json +164 -0
  443. vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=AMD_Instinct_MI300X.json +200 -0
  444. vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json +164 -0
  445. vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=AMD_Instinct_MI325X.json +200 -0
  446. vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json +146 -0
  447. vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=NVIDIA_H200,dtype=fp8_w8a8.json +146 -0
  448. vllm/model_executor/layers/fused_moe/configs/README +12 -0
  449. vllm/model_executor/layers/fused_moe/cutlass_moe.py +382 -0
  450. vllm/model_executor/layers/fused_moe/deep_gemm_moe.py +227 -0
  451. vllm/model_executor/layers/fused_moe/fused_batched_moe.py +755 -0
  452. vllm/model_executor/layers/fused_moe/fused_marlin_moe.py +231 -0
  453. vllm/model_executor/layers/fused_moe/fused_moe.py +1722 -0
  454. vllm/model_executor/layers/fused_moe/layer.py +1366 -0
  455. vllm/model_executor/layers/fused_moe/modular_kernel.py +364 -0
  456. vllm/model_executor/layers/fused_moe/moe_align_block_size.py +242 -0
  457. vllm/model_executor/layers/fused_moe/moe_pallas.py +83 -0
  458. vllm/model_executor/layers/fused_moe/moe_permute_unpermute.py +188 -0
  459. vllm/model_executor/layers/fused_moe/moe_torch_iterative.py +59 -0
  460. vllm/model_executor/layers/fused_moe/pplx_prepare_finalize.py +146 -0
  461. vllm/model_executor/layers/fused_moe/prepare_finalize.py +60 -0
  462. vllm/model_executor/layers/fused_moe/rocm_aiter_fused_moe.py +372 -0
  463. vllm/model_executor/layers/fused_moe/triton_deep_gemm_moe.py +112 -0
  464. vllm/model_executor/layers/fused_moe/utils.py +97 -0
  465. vllm/model_executor/layers/layernorm.py +287 -0
  466. vllm/model_executor/layers/lightning_attn.py +651 -0
  467. vllm/model_executor/layers/linear.py +1523 -0
  468. vllm/model_executor/layers/logits_processor.py +196 -0
  469. vllm/model_executor/layers/mamba/__init__.py +0 -0
  470. vllm/model_executor/layers/mamba/mamba2_metadata.py +124 -0
  471. vllm/model_executor/layers/mamba/mamba_mixer.py +244 -0
  472. vllm/model_executor/layers/mamba/mamba_mixer2.py +615 -0
  473. vllm/model_executor/layers/mamba/ops/__init__.py +0 -0
  474. vllm/model_executor/layers/mamba/ops/causal_conv1d.py +104 -0
  475. vllm/model_executor/layers/mamba/ops/mamba_ssm.py +413 -0
  476. vllm/model_executor/layers/mamba/ops/ssd_bmm.py +261 -0
  477. vllm/model_executor/layers/mamba/ops/ssd_chunk_scan.py +588 -0
  478. vllm/model_executor/layers/mamba/ops/ssd_chunk_state.py +750 -0
  479. vllm/model_executor/layers/mamba/ops/ssd_combined.py +231 -0
  480. vllm/model_executor/layers/mamba/ops/ssd_state_passing.py +205 -0
  481. vllm/model_executor/layers/pooler.py +343 -0
  482. vllm/model_executor/layers/quantization/__init__.py +156 -0
  483. vllm/model_executor/layers/quantization/aqlm.py +375 -0
  484. vllm/model_executor/layers/quantization/auto_round.py +308 -0
  485. vllm/model_executor/layers/quantization/awq.py +185 -0
  486. vllm/model_executor/layers/quantization/awq_marlin.py +518 -0
  487. vllm/model_executor/layers/quantization/awq_triton.py +319 -0
  488. vllm/model_executor/layers/quantization/base_config.py +150 -0
  489. vllm/model_executor/layers/quantization/bitblas.py +460 -0
  490. vllm/model_executor/layers/quantization/bitsandbytes.py +397 -0
  491. vllm/model_executor/layers/quantization/compressed_tensors/__init__.py +0 -0
  492. vllm/model_executor/layers/quantization/compressed_tensors/compressed_tensors.py +644 -0
  493. vllm/model_executor/layers/quantization/compressed_tensors/compressed_tensors_moe.py +1252 -0
  494. vllm/model_executor/layers/quantization/compressed_tensors/schemes/__init__.py +21 -0
  495. vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_24.py +357 -0
  496. vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_scheme.py +54 -0
  497. vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_w4a16_24.py +159 -0
  498. vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_w4a16_nvfp4.py +92 -0
  499. vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_w8a16_fp8.py +120 -0
  500. vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_w8a8_fp8.py +149 -0
  501. vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_w8a8_int8.py +110 -0
  502. vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_wNa16.py +200 -0
  503. vllm/model_executor/layers/quantization/compressed_tensors/triton_scaled_mm.py +205 -0
  504. vllm/model_executor/layers/quantization/compressed_tensors/utils.py +214 -0
  505. vllm/model_executor/layers/quantization/deepspeedfp.py +194 -0
  506. vllm/model_executor/layers/quantization/experts_int8.py +195 -0
  507. vllm/model_executor/layers/quantization/fbgemm_fp8.py +171 -0
  508. vllm/model_executor/layers/quantization/fp8.py +876 -0
  509. vllm/model_executor/layers/quantization/gguf.py +564 -0
  510. vllm/model_executor/layers/quantization/gptq.py +277 -0
  511. vllm/model_executor/layers/quantization/gptq_bitblas.py +444 -0
  512. vllm/model_executor/layers/quantization/gptq_marlin.py +647 -0
  513. vllm/model_executor/layers/quantization/gptq_marlin_24.py +296 -0
  514. vllm/model_executor/layers/quantization/hqq_marlin.py +331 -0
  515. vllm/model_executor/layers/quantization/ipex_quant.py +249 -0
  516. vllm/model_executor/layers/quantization/kernels/__init__.py +0 -0
  517. vllm/model_executor/layers/quantization/kernels/mixed_precision/MPLinearKernel.py +89 -0
  518. vllm/model_executor/layers/quantization/kernels/mixed_precision/__init__.py +82 -0
  519. vllm/model_executor/layers/quantization/kernels/mixed_precision/allspark.py +115 -0
  520. vllm/model_executor/layers/quantization/kernels/mixed_precision/bitblas.py +299 -0
  521. vllm/model_executor/layers/quantization/kernels/mixed_precision/exllama.py +142 -0
  522. vllm/model_executor/layers/quantization/kernels/mixed_precision/machete.py +119 -0
  523. vllm/model_executor/layers/quantization/kernels/mixed_precision/marlin.py +130 -0
  524. vllm/model_executor/layers/quantization/kernels/scaled_mm/ScaledMMLinearKernel.py +66 -0
  525. vllm/model_executor/layers/quantization/kernels/scaled_mm/__init__.py +86 -0
  526. vllm/model_executor/layers/quantization/kernels/scaled_mm/aiter.py +119 -0
  527. vllm/model_executor/layers/quantization/kernels/scaled_mm/cutlass.py +136 -0
  528. vllm/model_executor/layers/quantization/kernels/scaled_mm/triton.py +40 -0
  529. vllm/model_executor/layers/quantization/kernels/scaled_mm/xla.py +104 -0
  530. vllm/model_executor/layers/quantization/kv_cache.py +138 -0
  531. vllm/model_executor/layers/quantization/marlin.py +260 -0
  532. vllm/model_executor/layers/quantization/modelopt.py +734 -0
  533. vllm/model_executor/layers/quantization/moe_wna16.py +448 -0
  534. vllm/model_executor/layers/quantization/neuron_quant.py +68 -0
  535. vllm/model_executor/layers/quantization/ptpc_fp8.py +126 -0
  536. vllm/model_executor/layers/quantization/qqq.py +274 -0
  537. vllm/model_executor/layers/quantization/quark/__init__.py +0 -0
  538. vllm/model_executor/layers/quantization/quark/quark.py +440 -0
  539. vllm/model_executor/layers/quantization/quark/quark_moe.py +236 -0
  540. vllm/model_executor/layers/quantization/quark/schemes/__init__.py +8 -0
  541. vllm/model_executor/layers/quantization/quark/schemes/quark_scheme.py +54 -0
  542. vllm/model_executor/layers/quantization/quark/schemes/quark_w4a4_mxfp4.py +125 -0
  543. vllm/model_executor/layers/quantization/quark/schemes/quark_w8a8_fp8.py +145 -0
  544. vllm/model_executor/layers/quantization/quark/schemes/quark_w8a8_int8.py +121 -0
  545. vllm/model_executor/layers/quantization/quark/utils.py +104 -0
  546. vllm/model_executor/layers/quantization/schema.py +85 -0
  547. vllm/model_executor/layers/quantization/torchao.py +143 -0
  548. vllm/model_executor/layers/quantization/tpu_int8.py +120 -0
  549. vllm/model_executor/layers/quantization/utils/__init__.py +5 -0
  550. vllm/model_executor/layers/quantization/utils/allspark_utils.py +51 -0
  551. vllm/model_executor/layers/quantization/utils/bitblas_utils.py +207 -0
  552. vllm/model_executor/layers/quantization/utils/configs/N=1536,K=1536,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  553. vllm/model_executor/layers/quantization/utils/configs/N=1536,K=1536,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  554. vllm/model_executor/layers/quantization/utils/configs/N=1536,K=1536,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  555. vllm/model_executor/layers/quantization/utils/configs/N=1536,K=1536,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  556. vllm/model_executor/layers/quantization/utils/configs/N=1536,K=1536,device_name=NVIDIA_A800-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  557. vllm/model_executor/layers/quantization/utils/configs/N=1536,K=1536,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  558. vllm/model_executor/layers/quantization/utils/configs/N=1536,K=1536,device_name=NVIDIA_H20,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  559. vllm/model_executor/layers/quantization/utils/configs/N=1536,K=1536,device_name=NVIDIA_L20Y,dtype=fp8_w8a8,block_shape=[128,128].json +26 -0
  560. vllm/model_executor/layers/quantization/utils/configs/N=1536,K=7168,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  561. vllm/model_executor/layers/quantization/utils/configs/N=1536,K=7168,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  562. vllm/model_executor/layers/quantization/utils/configs/N=1536,K=7168,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  563. vllm/model_executor/layers/quantization/utils/configs/N=1536,K=7168,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  564. vllm/model_executor/layers/quantization/utils/configs/N=1536,K=7168,device_name=NVIDIA_A800-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  565. vllm/model_executor/layers/quantization/utils/configs/N=1536,K=7168,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  566. vllm/model_executor/layers/quantization/utils/configs/N=1536,K=7168,device_name=NVIDIA_H20,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  567. vllm/model_executor/layers/quantization/utils/configs/N=1536,K=7168,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  568. vllm/model_executor/layers/quantization/utils/configs/N=1536,K=7168,device_name=NVIDIA_L20,dtype=fp8_w8a8,block_shape=[128,128].json +26 -0
  569. vllm/model_executor/layers/quantization/utils/configs/N=1536,K=7168,device_name=NVIDIA_L20Y,dtype=fp8_w8a8,block_shape=[128,128].json +26 -0
  570. vllm/model_executor/layers/quantization/utils/configs/N=2048,K=512,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  571. vllm/model_executor/layers/quantization/utils/configs/N=2048,K=512,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  572. vllm/model_executor/layers/quantization/utils/configs/N=2048,K=512,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  573. vllm/model_executor/layers/quantization/utils/configs/N=2048,K=512,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  574. vllm/model_executor/layers/quantization/utils/configs/N=2048,K=512,device_name=NVIDIA_A800-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  575. vllm/model_executor/layers/quantization/utils/configs/N=2048,K=512,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  576. vllm/model_executor/layers/quantization/utils/configs/N=2048,K=512,device_name=NVIDIA_H20,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  577. vllm/model_executor/layers/quantization/utils/configs/N=2048,K=512,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  578. vllm/model_executor/layers/quantization/utils/configs/N=2048,K=512,device_name=NVIDIA_L20Y,dtype=fp8_w8a8,block_shape=[128,128].json +26 -0
  579. vllm/model_executor/layers/quantization/utils/configs/N=2304,K=7168,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  580. vllm/model_executor/layers/quantization/utils/configs/N=2304,K=7168,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  581. vllm/model_executor/layers/quantization/utils/configs/N=2304,K=7168,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  582. vllm/model_executor/layers/quantization/utils/configs/N=2304,K=7168,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  583. vllm/model_executor/layers/quantization/utils/configs/N=2304,K=7168,device_name=NVIDIA_A800-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  584. vllm/model_executor/layers/quantization/utils/configs/N=2304,K=7168,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  585. vllm/model_executor/layers/quantization/utils/configs/N=2304,K=7168,device_name=NVIDIA_H20,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  586. vllm/model_executor/layers/quantization/utils/configs/N=2304,K=7168,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  587. vllm/model_executor/layers/quantization/utils/configs/N=2304,K=7168,device_name=NVIDIA_L20Y,dtype=fp8_w8a8,block_shape=[128,128].json +26 -0
  588. vllm/model_executor/layers/quantization/utils/configs/N=24576,K=7168,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  589. vllm/model_executor/layers/quantization/utils/configs/N=24576,K=7168,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  590. vllm/model_executor/layers/quantization/utils/configs/N=24576,K=7168,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  591. vllm/model_executor/layers/quantization/utils/configs/N=24576,K=7168,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  592. vllm/model_executor/layers/quantization/utils/configs/N=24576,K=7168,device_name=NVIDIA_A800-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  593. vllm/model_executor/layers/quantization/utils/configs/N=24576,K=7168,device_name=NVIDIA_B200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  594. vllm/model_executor/layers/quantization/utils/configs/N=24576,K=7168,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  595. vllm/model_executor/layers/quantization/utils/configs/N=24576,K=7168,device_name=NVIDIA_H20,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  596. vllm/model_executor/layers/quantization/utils/configs/N=24576,K=7168,device_name=NVIDIA_H20,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  597. vllm/model_executor/layers/quantization/utils/configs/N=24576,K=7168,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  598. vllm/model_executor/layers/quantization/utils/configs/N=24576,K=7168,device_name=NVIDIA_L20,dtype=fp8_w8a8,block_shape=[128,128].json +26 -0
  599. vllm/model_executor/layers/quantization/utils/configs/N=24576,K=7168,device_name=NVIDIA_L20Y,dtype=fp8_w8a8,block_shape=[128,128].json +26 -0
  600. vllm/model_executor/layers/quantization/utils/configs/N=256,K=7168,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  601. vllm/model_executor/layers/quantization/utils/configs/N=256,K=7168,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  602. vllm/model_executor/layers/quantization/utils/configs/N=256,K=7168,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  603. vllm/model_executor/layers/quantization/utils/configs/N=256,K=7168,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  604. vllm/model_executor/layers/quantization/utils/configs/N=256,K=7168,device_name=NVIDIA_A800-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  605. vllm/model_executor/layers/quantization/utils/configs/N=256,K=7168,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  606. vllm/model_executor/layers/quantization/utils/configs/N=256,K=7168,device_name=NVIDIA_H20,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  607. vllm/model_executor/layers/quantization/utils/configs/N=256,K=7168,device_name=NVIDIA_L20Y,dtype=fp8_w8a8,block_shape=[128,128].json +26 -0
  608. vllm/model_executor/layers/quantization/utils/configs/N=3072,K=1536,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  609. vllm/model_executor/layers/quantization/utils/configs/N=3072,K=1536,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  610. vllm/model_executor/layers/quantization/utils/configs/N=3072,K=1536,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  611. vllm/model_executor/layers/quantization/utils/configs/N=3072,K=1536,device_name=NVIDIA_B200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  612. vllm/model_executor/layers/quantization/utils/configs/N=3072,K=1536,device_name=NVIDIA_H20,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  613. vllm/model_executor/layers/quantization/utils/configs/N=3072,K=1536,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  614. vllm/model_executor/layers/quantization/utils/configs/N=3072,K=1536,device_name=NVIDIA_L20,dtype=fp8_w8a8,block_shape=[128,128].json +26 -0
  615. vllm/model_executor/layers/quantization/utils/configs/N=3072,K=7168,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  616. vllm/model_executor/layers/quantization/utils/configs/N=3072,K=7168,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  617. vllm/model_executor/layers/quantization/utils/configs/N=3072,K=7168,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  618. vllm/model_executor/layers/quantization/utils/configs/N=3072,K=7168,device_name=NVIDIA_B200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  619. vllm/model_executor/layers/quantization/utils/configs/N=3072,K=7168,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  620. vllm/model_executor/layers/quantization/utils/configs/N=3072,K=7168,device_name=NVIDIA_H20,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  621. vllm/model_executor/layers/quantization/utils/configs/N=3072,K=7168,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  622. vllm/model_executor/layers/quantization/utils/configs/N=3072,K=7168,device_name=NVIDIA_L20,dtype=fp8_w8a8,block_shape=[128,128].json +26 -0
  623. vllm/model_executor/layers/quantization/utils/configs/N=32768,K=512,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  624. vllm/model_executor/layers/quantization/utils/configs/N=32768,K=512,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  625. vllm/model_executor/layers/quantization/utils/configs/N=32768,K=512,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  626. vllm/model_executor/layers/quantization/utils/configs/N=32768,K=512,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  627. vllm/model_executor/layers/quantization/utils/configs/N=32768,K=512,device_name=NVIDIA_A800-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  628. vllm/model_executor/layers/quantization/utils/configs/N=32768,K=512,device_name=NVIDIA_B200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  629. vllm/model_executor/layers/quantization/utils/configs/N=32768,K=512,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  630. vllm/model_executor/layers/quantization/utils/configs/N=32768,K=512,device_name=NVIDIA_H20,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  631. vllm/model_executor/layers/quantization/utils/configs/N=32768,K=512,device_name=NVIDIA_H20,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  632. vllm/model_executor/layers/quantization/utils/configs/N=32768,K=512,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  633. vllm/model_executor/layers/quantization/utils/configs/N=32768,K=512,device_name=NVIDIA_L20,dtype=fp8_w8a8,block_shape=[128,128].json +26 -0
  634. vllm/model_executor/layers/quantization/utils/configs/N=32768,K=512,device_name=NVIDIA_L20Y,dtype=fp8_w8a8,block_shape=[128,128].json +26 -0
  635. vllm/model_executor/layers/quantization/utils/configs/N=36864,K=7168,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  636. vllm/model_executor/layers/quantization/utils/configs/N=36864,K=7168,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  637. vllm/model_executor/layers/quantization/utils/configs/N=36864,K=7168,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  638. vllm/model_executor/layers/quantization/utils/configs/N=36864,K=7168,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  639. vllm/model_executor/layers/quantization/utils/configs/N=36864,K=7168,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  640. vllm/model_executor/layers/quantization/utils/configs/N=4096,K=512,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  641. vllm/model_executor/layers/quantization/utils/configs/N=4096,K=512,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  642. vllm/model_executor/layers/quantization/utils/configs/N=4096,K=512,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  643. vllm/model_executor/layers/quantization/utils/configs/N=4096,K=512,device_name=NVIDIA_B200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  644. vllm/model_executor/layers/quantization/utils/configs/N=4096,K=512,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  645. vllm/model_executor/layers/quantization/utils/configs/N=4096,K=512,device_name=NVIDIA_H20,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  646. vllm/model_executor/layers/quantization/utils/configs/N=4096,K=512,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  647. vllm/model_executor/layers/quantization/utils/configs/N=4096,K=512,device_name=NVIDIA_L20,dtype=fp8_w8a8,block_shape=[128,128].json +26 -0
  648. vllm/model_executor/layers/quantization/utils/configs/N=4608,K=7168,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  649. vllm/model_executor/layers/quantization/utils/configs/N=4608,K=7168,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  650. vllm/model_executor/layers/quantization/utils/configs/N=4608,K=7168,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  651. vllm/model_executor/layers/quantization/utils/configs/N=4608,K=7168,device_name=NVIDIA_B200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  652. vllm/model_executor/layers/quantization/utils/configs/N=4608,K=7168,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  653. vllm/model_executor/layers/quantization/utils/configs/N=4608,K=7168,device_name=NVIDIA_H20,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  654. vllm/model_executor/layers/quantization/utils/configs/N=4608,K=7168,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  655. vllm/model_executor/layers/quantization/utils/configs/N=4608,K=7168,device_name=NVIDIA_L20,dtype=fp8_w8a8,block_shape=[128,128].json +26 -0
  656. vllm/model_executor/layers/quantization/utils/configs/N=512,K=7168,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  657. vllm/model_executor/layers/quantization/utils/configs/N=512,K=7168,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  658. vllm/model_executor/layers/quantization/utils/configs/N=512,K=7168,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  659. vllm/model_executor/layers/quantization/utils/configs/N=512,K=7168,device_name=NVIDIA_B200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  660. vllm/model_executor/layers/quantization/utils/configs/N=512,K=7168,device_name=NVIDIA_H20,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  661. vllm/model_executor/layers/quantization/utils/configs/N=512,K=7168,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  662. vllm/model_executor/layers/quantization/utils/configs/N=512,K=7168,device_name=NVIDIA_L20,dtype=fp8_w8a8,block_shape=[128,128].json +26 -0
  663. vllm/model_executor/layers/quantization/utils/configs/N=576,K=7168,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  664. vllm/model_executor/layers/quantization/utils/configs/N=576,K=7168,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  665. vllm/model_executor/layers/quantization/utils/configs/N=576,K=7168,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  666. vllm/model_executor/layers/quantization/utils/configs/N=576,K=7168,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  667. vllm/model_executor/layers/quantization/utils/configs/N=576,K=7168,device_name=NVIDIA_A800-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  668. vllm/model_executor/layers/quantization/utils/configs/N=576,K=7168,device_name=NVIDIA_B200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  669. vllm/model_executor/layers/quantization/utils/configs/N=576,K=7168,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  670. vllm/model_executor/layers/quantization/utils/configs/N=576,K=7168,device_name=NVIDIA_H20,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  671. vllm/model_executor/layers/quantization/utils/configs/N=576,K=7168,device_name=NVIDIA_H20,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  672. vllm/model_executor/layers/quantization/utils/configs/N=576,K=7168,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  673. vllm/model_executor/layers/quantization/utils/configs/N=576,K=7168,device_name=NVIDIA_L20,dtype=fp8_w8a8,block_shape=[128,128].json +18 -0
  674. vllm/model_executor/layers/quantization/utils/configs/N=576,K=7168,device_name=NVIDIA_L20Y,dtype=fp8_w8a8,block_shape=[128,128].json +26 -0
  675. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=1024,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  676. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=1024,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  677. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=1024,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  678. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=1024,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  679. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=1024,device_name=NVIDIA_A800-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  680. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=1024,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  681. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=1024,device_name=NVIDIA_H20,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  682. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=1024,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  683. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=1024,device_name=NVIDIA_L20Y,dtype=fp8_w8a8,block_shape=[128,128].json +26 -0
  684. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=1152,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  685. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=1152,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  686. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=1152,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  687. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=1152,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  688. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=1152,device_name=NVIDIA_A800-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  689. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=1152,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  690. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=1152,device_name=NVIDIA_H20,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  691. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=1152,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  692. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=1152,device_name=NVIDIA_L20Y,dtype=fp8_w8a8,block_shape=[128,128].json +26 -0
  693. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=128,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  694. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=128,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  695. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=128,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  696. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=128,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  697. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=128,device_name=NVIDIA_A800-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  698. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=128,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  699. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=128,device_name=NVIDIA_H20,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  700. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=128,device_name=NVIDIA_L20Y,dtype=fp8_w8a8,block_shape=[128,128].json +26 -0
  701. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=16384,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  702. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=16384,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  703. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=16384,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  704. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=16384,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  705. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=16384,device_name=NVIDIA_A800-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  706. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=16384,device_name=NVIDIA_B200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  707. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=16384,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  708. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=16384,device_name=NVIDIA_H20,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  709. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=16384,device_name=NVIDIA_H20,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  710. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=16384,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  711. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=16384,device_name=NVIDIA_L20,dtype=fp8_w8a8,block_shape=[128,128].json +26 -0
  712. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=16384,device_name=NVIDIA_L20Y,dtype=fp8_w8a8,block_shape=[128,128].json +26 -0
  713. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=18432,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  714. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=18432,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  715. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=18432,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  716. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=18432,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  717. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=18432,device_name=NVIDIA_A800-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  718. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=18432,device_name=NVIDIA_B200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  719. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=18432,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  720. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=18432,device_name=NVIDIA_H20,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  721. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=18432,device_name=NVIDIA_H20,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  722. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=18432,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  723. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=18432,device_name=NVIDIA_L20,dtype=fp8_w8a8,block_shape=[128,128].json +26 -0
  724. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=18432,device_name=NVIDIA_L20Y,dtype=fp8_w8a8,block_shape=[128,128].json +26 -0
  725. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=2048,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  726. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=2048,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  727. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=2048,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  728. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=2048,device_name=NVIDIA_B200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  729. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=2048,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  730. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=2048,device_name=NVIDIA_H20,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  731. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=2048,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  732. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=2048,device_name=NVIDIA_L20,dtype=fp8_w8a8,block_shape=[128,128].json +26 -0
  733. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=2304,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  734. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=2304,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  735. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=2304,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  736. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=2304,device_name=NVIDIA_B200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  737. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=2304,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  738. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=2304,device_name=NVIDIA_H20,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  739. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=2304,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  740. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=2304,device_name=NVIDIA_L20,dtype=fp8_w8a8,block_shape=[128,128].json +26 -0
  741. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=256,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  742. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=256,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  743. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=256,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  744. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=256,device_name=NVIDIA_B200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  745. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=256,device_name=NVIDIA_H20,dtype=int8_w8a8,block_shape=[128,128].json +146 -0
  746. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=256,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  747. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=256,device_name=NVIDIA_L20,dtype=fp8_w8a8,block_shape=[128,128].json +26 -0
  748. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=8192,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  749. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=8192,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  750. vllm/model_executor/layers/quantization/utils/configs/N=7168,K=8192,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  751. vllm/model_executor/layers/quantization/utils/configs/N=8192,K=1536,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  752. vllm/model_executor/layers/quantization/utils/configs/N=8192,K=1536,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  753. vllm/model_executor/layers/quantization/utils/configs/N=8192,K=1536,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json +164 -0
  754. vllm/model_executor/layers/quantization/utils/fp8_utils.py +611 -0
  755. vllm/model_executor/layers/quantization/utils/gptq_utils.py +94 -0
  756. vllm/model_executor/layers/quantization/utils/int8_utils.py +484 -0
  757. vllm/model_executor/layers/quantization/utils/layer_utils.py +39 -0
  758. vllm/model_executor/layers/quantization/utils/machete_utils.py +32 -0
  759. vllm/model_executor/layers/quantization/utils/marlin_utils.py +475 -0
  760. vllm/model_executor/layers/quantization/utils/marlin_utils_fp4.py +277 -0
  761. vllm/model_executor/layers/quantization/utils/marlin_utils_fp8.py +324 -0
  762. vllm/model_executor/layers/quantization/utils/marlin_utils_test.py +164 -0
  763. vllm/model_executor/layers/quantization/utils/marlin_utils_test_24.py +463 -0
  764. vllm/model_executor/layers/quantization/utils/marlin_utils_test_qqq.py +125 -0
  765. vllm/model_executor/layers/quantization/utils/mxfp4_utils.py +44 -0
  766. vllm/model_executor/layers/quantization/utils/nvfp4_emulation_utils.py +61 -0
  767. vllm/model_executor/layers/quantization/utils/quant_utils.py +572 -0
  768. vllm/model_executor/layers/quantization/utils/w8a8_utils.py +404 -0
  769. vllm/model_executor/layers/rejection_sampler.py +405 -0
  770. vllm/model_executor/layers/resampler.py +269 -0
  771. vllm/model_executor/layers/rotary_embedding.py +1861 -0
  772. vllm/model_executor/layers/sampler.py +1203 -0
  773. vllm/model_executor/layers/spec_decode_base_sampler.py +258 -0
  774. vllm/model_executor/layers/typical_acceptance_sampler.py +165 -0
  775. vllm/model_executor/layers/utils.py +99 -0
  776. vllm/model_executor/layers/vocab_parallel_embedding.py +486 -0
  777. vllm/model_executor/model_loader/__init__.py +75 -0
  778. vllm/model_executor/model_loader/base_loader.py +24 -0
  779. vllm/model_executor/model_loader/bitsandbytes_loader.py +582 -0
  780. vllm/model_executor/model_loader/default_loader.py +295 -0
  781. vllm/model_executor/model_loader/dummy_loader.py +37 -0
  782. vllm/model_executor/model_loader/gguf_loader.py +113 -0
  783. vllm/model_executor/model_loader/neuron.py +475 -0
  784. vllm/model_executor/model_loader/neuronx_distributed.py +622 -0
  785. vllm/model_executor/model_loader/runai_streamer_loader.py +120 -0
  786. vllm/model_executor/model_loader/sharded_state_loader.py +211 -0
  787. vllm/model_executor/model_loader/tensorizer.py +632 -0
  788. vllm/model_executor/model_loader/tensorizer_loader.py +122 -0
  789. vllm/model_executor/model_loader/utils.py +301 -0
  790. vllm/model_executor/model_loader/weight_utils.py +781 -0
  791. vllm/model_executor/models/__init__.py +27 -0
  792. vllm/model_executor/models/adapters.py +247 -0
  793. vllm/model_executor/models/aimv2.py +199 -0
  794. vllm/model_executor/models/arctic.py +558 -0
  795. vllm/model_executor/models/aria.py +656 -0
  796. vllm/model_executor/models/aya_vision.py +461 -0
  797. vllm/model_executor/models/baichuan.py +473 -0
  798. vllm/model_executor/models/bamba.py +542 -0
  799. vllm/model_executor/models/bart.py +937 -0
  800. vllm/model_executor/models/bert.py +517 -0
  801. vllm/model_executor/models/bert_with_rope.py +714 -0
  802. vllm/model_executor/models/blip.py +338 -0
  803. vllm/model_executor/models/blip2.py +717 -0
  804. vllm/model_executor/models/bloom.py +372 -0
  805. vllm/model_executor/models/chameleon.py +1135 -0
  806. vllm/model_executor/models/chatglm.py +477 -0
  807. vllm/model_executor/models/clip.py +411 -0
  808. vllm/model_executor/models/commandr.py +471 -0
  809. vllm/model_executor/models/constant_size_cache.py +136 -0
  810. vllm/model_executor/models/dbrx.py +471 -0
  811. vllm/model_executor/models/deepseek.py +485 -0
  812. vllm/model_executor/models/deepseek_mtp.py +268 -0
  813. vllm/model_executor/models/deepseek_v2.py +842 -0
  814. vllm/model_executor/models/deepseek_vl2.py +647 -0
  815. vllm/model_executor/models/eagle.py +259 -0
  816. vllm/model_executor/models/exaone.py +550 -0
  817. vllm/model_executor/models/fairseq2_llama.py +153 -0
  818. vllm/model_executor/models/falcon.py +509 -0
  819. vllm/model_executor/models/falcon_h1.py +684 -0
  820. vllm/model_executor/models/florence2.py +1102 -0
  821. vllm/model_executor/models/fuyu.py +388 -0
  822. vllm/model_executor/models/gemma.py +424 -0
  823. vllm/model_executor/models/gemma2.py +424 -0
  824. vllm/model_executor/models/gemma3.py +532 -0
  825. vllm/model_executor/models/gemma3_mm.py +708 -0
  826. vllm/model_executor/models/glm.py +22 -0
  827. vllm/model_executor/models/glm4.py +304 -0
  828. vllm/model_executor/models/glm4v.py +647 -0
  829. vllm/model_executor/models/gpt2.py +327 -0
  830. vllm/model_executor/models/gpt_bigcode.py +334 -0
  831. vllm/model_executor/models/gpt_j.py +338 -0
  832. vllm/model_executor/models/gpt_neox.py +331 -0
  833. vllm/model_executor/models/granite.py +492 -0
  834. vllm/model_executor/models/granite_speech.py +778 -0
  835. vllm/model_executor/models/granitemoe.py +436 -0
  836. vllm/model_executor/models/granitemoehybrid.py +585 -0
  837. vllm/model_executor/models/granitemoeshared.py +340 -0
  838. vllm/model_executor/models/gritlm.py +223 -0
  839. vllm/model_executor/models/grok1.py +545 -0
  840. vllm/model_executor/models/h2ovl.py +545 -0
  841. vllm/model_executor/models/idefics2_vision_model.py +388 -0
  842. vllm/model_executor/models/idefics3.py +767 -0
  843. vllm/model_executor/models/interfaces.py +571 -0
  844. vllm/model_executor/models/interfaces_base.py +163 -0
  845. vllm/model_executor/models/intern_vit.py +475 -0
  846. vllm/model_executor/models/internlm2.py +454 -0
  847. vllm/model_executor/models/internlm2_ve.py +146 -0
  848. vllm/model_executor/models/internvl.py +1405 -0
  849. vllm/model_executor/models/jais.py +372 -0
  850. vllm/model_executor/models/jamba.py +591 -0
  851. vllm/model_executor/models/kimi_vl.py +576 -0
  852. vllm/model_executor/models/llama.py +643 -0
  853. vllm/model_executor/models/llama4.py +531 -0
  854. vllm/model_executor/models/llama_eagle.py +166 -0
  855. vllm/model_executor/models/llama_eagle3.py +257 -0
  856. vllm/model_executor/models/llava.py +865 -0
  857. vllm/model_executor/models/llava_next.py +585 -0
  858. vllm/model_executor/models/llava_next_video.py +470 -0
  859. vllm/model_executor/models/llava_onevision.py +955 -0
  860. vllm/model_executor/models/mamba.py +272 -0
  861. vllm/model_executor/models/mamba2.py +302 -0
  862. vllm/model_executor/models/mamba_cache.py +75 -0
  863. vllm/model_executor/models/medusa.py +218 -0
  864. vllm/model_executor/models/mimo.py +191 -0
  865. vllm/model_executor/models/mimo_mtp.py +284 -0
  866. vllm/model_executor/models/minicpm.py +590 -0
  867. vllm/model_executor/models/minicpm3.py +229 -0
  868. vllm/model_executor/models/minicpmo.py +758 -0
  869. vllm/model_executor/models/minicpmv.py +1286 -0
  870. vllm/model_executor/models/minimax_cache.py +35 -0
  871. vllm/model_executor/models/minimax_text_01.py +1303 -0
  872. vllm/model_executor/models/minimax_vl_01.py +363 -0
  873. vllm/model_executor/models/mistral3.py +603 -0
  874. vllm/model_executor/models/mixtral.py +487 -0
  875. vllm/model_executor/models/mixtral_quant.py +452 -0
  876. vllm/model_executor/models/mllama.py +1623 -0
  877. vllm/model_executor/models/mllama4.py +838 -0
  878. vllm/model_executor/models/mlp_speculator.py +205 -0
  879. vllm/model_executor/models/modernbert.py +329 -0
  880. vllm/model_executor/models/module_mapping.py +71 -0
  881. vllm/model_executor/models/molmo.py +1567 -0
  882. vllm/model_executor/models/moonvit.py +629 -0
  883. vllm/model_executor/models/mpt.py +330 -0
  884. vllm/model_executor/models/nemotron.py +507 -0
  885. vllm/model_executor/models/nemotron_nas.py +483 -0
  886. vllm/model_executor/models/nvlm_d.py +215 -0
  887. vllm/model_executor/models/olmo.py +388 -0
  888. vllm/model_executor/models/olmo2.py +413 -0
  889. vllm/model_executor/models/olmoe.py +446 -0
  890. vllm/model_executor/models/opt.py +411 -0
  891. vllm/model_executor/models/orion.py +348 -0
  892. vllm/model_executor/models/ovis.py +554 -0
  893. vllm/model_executor/models/paligemma.py +397 -0
  894. vllm/model_executor/models/persimmon.py +343 -0
  895. vllm/model_executor/models/phi.py +355 -0
  896. vllm/model_executor/models/phi3.py +18 -0
  897. vllm/model_executor/models/phi3_small.py +464 -0
  898. vllm/model_executor/models/phi3v.py +722 -0
  899. vllm/model_executor/models/phi4mm.py +1245 -0
  900. vllm/model_executor/models/phi4mm_audio.py +1232 -0
  901. vllm/model_executor/models/phi4mm_utils.py +1883 -0
  902. vllm/model_executor/models/phimoe.py +664 -0
  903. vllm/model_executor/models/pixtral.py +1315 -0
  904. vllm/model_executor/models/plamo2.py +737 -0
  905. vllm/model_executor/models/prithvi_geospatial_mae.py +231 -0
  906. vllm/model_executor/models/qwen.py +361 -0
  907. vllm/model_executor/models/qwen2.py +567 -0
  908. vllm/model_executor/models/qwen2_5_omni_thinker.py +903 -0
  909. vllm/model_executor/models/qwen2_5_vl.py +1171 -0
  910. vllm/model_executor/models/qwen2_audio.py +409 -0
  911. vllm/model_executor/models/qwen2_moe.py +539 -0
  912. vllm/model_executor/models/qwen2_rm.py +131 -0
  913. vllm/model_executor/models/qwen2_vl.py +1410 -0
  914. vllm/model_executor/models/qwen3.py +320 -0
  915. vllm/model_executor/models/qwen3_moe.py +534 -0
  916. vllm/model_executor/models/qwen_vl.py +784 -0
  917. vllm/model_executor/models/registry.py +618 -0
  918. vllm/model_executor/models/roberta.py +273 -0
  919. vllm/model_executor/models/siglip.py +523 -0
  920. vllm/model_executor/models/skyworkr1v.py +950 -0
  921. vllm/model_executor/models/smolvlm.py +51 -0
  922. vllm/model_executor/models/solar.py +505 -0
  923. vllm/model_executor/models/stablelm.py +342 -0
  924. vllm/model_executor/models/starcoder2.py +355 -0
  925. vllm/model_executor/models/telechat2.py +139 -0
  926. vllm/model_executor/models/teleflm.py +78 -0
  927. vllm/model_executor/models/transformers.py +507 -0
  928. vllm/model_executor/models/ultravox.py +655 -0
  929. vllm/model_executor/models/utils.py +730 -0
  930. vllm/model_executor/models/vision.py +146 -0
  931. vllm/model_executor/models/whisper.py +746 -0
  932. vllm/model_executor/models/zamba2.py +1008 -0
  933. vllm/model_executor/parameter.py +458 -0
  934. vllm/model_executor/pooling_metadata.py +71 -0
  935. vllm/model_executor/sampling_metadata.py +596 -0
  936. vllm/model_executor/utils.py +53 -0
  937. vllm/multimodal/__init__.py +32 -0
  938. vllm/multimodal/audio.py +105 -0
  939. vllm/multimodal/base.py +218 -0
  940. vllm/multimodal/hasher.py +117 -0
  941. vllm/multimodal/image.py +96 -0
  942. vllm/multimodal/inputs.py +872 -0
  943. vllm/multimodal/parse.py +460 -0
  944. vllm/multimodal/processing.py +1894 -0
  945. vllm/multimodal/profiling.py +273 -0
  946. vllm/multimodal/registry.py +330 -0
  947. vllm/multimodal/utils.py +392 -0
  948. vllm/multimodal/video.py +197 -0
  949. vllm/outputs.py +525 -0
  950. vllm/platforms/__init__.py +290 -0
  951. vllm/platforms/cpu.py +205 -0
  952. vllm/platforms/cuda.py +461 -0
  953. vllm/platforms/hpu.py +105 -0
  954. vllm/platforms/interface.py +492 -0
  955. vllm/platforms/neuron.py +152 -0
  956. vllm/platforms/rocm.py +388 -0
  957. vllm/platforms/tpu.py +215 -0
  958. vllm/platforms/xpu.py +155 -0
  959. vllm/plugins/__init__.py +86 -0
  960. vllm/plugins/lora_resolvers/README.md +15 -0
  961. vllm/plugins/lora_resolvers/__init__.py +0 -0
  962. vllm/plugins/lora_resolvers/filesystem_resolver.py +49 -0
  963. vllm/pooling_params.py +53 -0
  964. vllm/profiler/__init__.py +0 -0
  965. vllm/profiler/layerwise_profile.py +374 -0
  966. vllm/profiler/utils.py +147 -0
  967. vllm/prompt_adapter/__init__.py +0 -0
  968. vllm/prompt_adapter/layers.py +82 -0
  969. vllm/prompt_adapter/models.py +357 -0
  970. vllm/prompt_adapter/request.py +36 -0
  971. vllm/prompt_adapter/utils.py +97 -0
  972. vllm/prompt_adapter/worker_manager.py +178 -0
  973. vllm/py.typed +2 -0
  974. vllm/reasoning/__init__.py +14 -0
  975. vllm/reasoning/abs_reasoning_parsers.py +191 -0
  976. vllm/reasoning/deepseek_r1_reasoning_parser.py +172 -0
  977. vllm/reasoning/granite_reasoning_parser.py +362 -0
  978. vllm/reasoning/qwen3_reasoning_parser.py +150 -0
  979. vllm/sampling_params.py +590 -0
  980. vllm/scalar_type.py +346 -0
  981. vllm/scripts.py +14 -0
  982. vllm/sequence.py +1567 -0
  983. vllm/spec_decode/__init__.py +0 -0
  984. vllm/spec_decode/batch_expansion.py +505 -0
  985. vllm/spec_decode/draft_model_runner.py +349 -0
  986. vllm/spec_decode/interfaces.py +98 -0
  987. vllm/spec_decode/medusa_worker.py +137 -0
  988. vllm/spec_decode/metrics.py +212 -0
  989. vllm/spec_decode/mlp_speculator_worker.py +93 -0
  990. vllm/spec_decode/mqa_scorer.py +159 -0
  991. vllm/spec_decode/multi_step_worker.py +422 -0
  992. vllm/spec_decode/ngram_worker.py +195 -0
  993. vllm/spec_decode/proposer_worker_base.py +58 -0
  994. vllm/spec_decode/smaller_tp_proposer_worker.py +195 -0
  995. vllm/spec_decode/spec_decode_worker.py +1325 -0
  996. vllm/spec_decode/target_model_runner.py +44 -0
  997. vllm/spec_decode/top1_proposer.py +274 -0
  998. vllm/spec_decode/util.py +276 -0
  999. vllm/test_utils.py +129 -0
  1000. vllm/third_party/__init__.py +0 -0
  1001. vllm/third_party/pynvml.py +6139 -0
  1002. vllm/tracing.py +130 -0
  1003. vllm/transformers_utils/__init__.py +23 -0
  1004. vllm/transformers_utils/chat_templates/__init__.py +4 -0
  1005. vllm/transformers_utils/chat_templates/registry.py +59 -0
  1006. vllm/transformers_utils/chat_templates/template_basic.jinja +3 -0
  1007. vllm/transformers_utils/chat_templates/template_blip2.jinja +11 -0
  1008. vllm/transformers_utils/chat_templates/template_chatml.jinja +10 -0
  1009. vllm/transformers_utils/chat_templates/template_deepseek_vl2.jinja +23 -0
  1010. vllm/transformers_utils/chat_templates/template_fuyu.jinja +3 -0
  1011. vllm/transformers_utils/config.py +835 -0
  1012. vllm/transformers_utils/configs/__init__.py +58 -0
  1013. vllm/transformers_utils/configs/arctic.py +206 -0
  1014. vllm/transformers_utils/configs/chatglm.py +71 -0
  1015. vllm/transformers_utils/configs/cohere2.py +194 -0
  1016. vllm/transformers_utils/configs/dbrx.py +279 -0
  1017. vllm/transformers_utils/configs/deepseek_vl2.py +215 -0
  1018. vllm/transformers_utils/configs/eagle.py +84 -0
  1019. vllm/transformers_utils/configs/exaone.py +189 -0
  1020. vllm/transformers_utils/configs/falcon.py +89 -0
  1021. vllm/transformers_utils/configs/h2ovl.py +15 -0
  1022. vllm/transformers_utils/configs/internvl.py +53 -0
  1023. vllm/transformers_utils/configs/jais.py +237 -0
  1024. vllm/transformers_utils/configs/kimi_vl.py +36 -0
  1025. vllm/transformers_utils/configs/medusa.py +62 -0
  1026. vllm/transformers_utils/configs/minimax_text_01.py +69 -0
  1027. vllm/transformers_utils/configs/minimax_vl_01.py +70 -0
  1028. vllm/transformers_utils/configs/mllama.py +30 -0
  1029. vllm/transformers_utils/configs/mlp_speculator.py +67 -0
  1030. vllm/transformers_utils/configs/moonvit.py +32 -0
  1031. vllm/transformers_utils/configs/mpt.py +179 -0
  1032. vllm/transformers_utils/configs/nemotron.py +204 -0
  1033. vllm/transformers_utils/configs/nvlm_d.py +14 -0
  1034. vllm/transformers_utils/configs/ovis.py +183 -0
  1035. vllm/transformers_utils/configs/skyworkr1v.py +53 -0
  1036. vllm/transformers_utils/configs/solar.py +246 -0
  1037. vllm/transformers_utils/configs/telechat2.py +63 -0
  1038. vllm/transformers_utils/configs/ultravox.py +107 -0
  1039. vllm/transformers_utils/detokenizer.py +167 -0
  1040. vllm/transformers_utils/detokenizer_utils.py +188 -0
  1041. vllm/transformers_utils/processor.py +220 -0
  1042. vllm/transformers_utils/processors/__init__.py +7 -0
  1043. vllm/transformers_utils/processors/deepseek_vl2.py +362 -0
  1044. vllm/transformers_utils/processors/ovis.py +419 -0
  1045. vllm/transformers_utils/s3_utils.py +161 -0
  1046. vllm/transformers_utils/tokenizer.py +301 -0
  1047. vllm/transformers_utils/tokenizer_base.py +148 -0
  1048. vllm/transformers_utils/tokenizer_group.py +119 -0
  1049. vllm/transformers_utils/tokenizers/__init__.py +9 -0
  1050. vllm/transformers_utils/tokenizers/mistral.py +490 -0
  1051. vllm/transformers_utils/utils.py +98 -0
  1052. vllm/triton_utils/__init__.py +13 -0
  1053. vllm/triton_utils/importing.py +49 -0
  1054. vllm/usage/__init__.py +0 -0
  1055. vllm/usage/usage_lib.py +255 -0
  1056. vllm/utils.py +2844 -0
  1057. vllm/v1/__init__.py +0 -0
  1058. vllm/v1/attention/__init__.py +0 -0
  1059. vllm/v1/attention/backends/__init__.py +0 -0
  1060. vllm/v1/attention/backends/flash_attn.py +833 -0
  1061. vllm/v1/attention/backends/flashinfer.py +639 -0
  1062. vllm/v1/attention/backends/mla/__init__.py +0 -0
  1063. vllm/v1/attention/backends/mla/common.py +926 -0
  1064. vllm/v1/attention/backends/mla/flashmla.py +150 -0
  1065. vllm/v1/attention/backends/mla/rocm_aiter_mla.py +221 -0
  1066. vllm/v1/attention/backends/mla/triton_mla.py +118 -0
  1067. vllm/v1/attention/backends/pallas.py +235 -0
  1068. vllm/v1/attention/backends/triton_attn.py +279 -0
  1069. vllm/v1/attention/backends/utils.py +18 -0
  1070. vllm/v1/core/__init__.py +0 -0
  1071. vllm/v1/core/block_pool.py +328 -0
  1072. vllm/v1/core/encoder_cache_manager.py +149 -0
  1073. vllm/v1/core/kv_cache_manager.py +372 -0
  1074. vllm/v1/core/kv_cache_utils.py +748 -0
  1075. vllm/v1/core/sched/__init__.py +0 -0
  1076. vllm/v1/core/sched/interface.py +143 -0
  1077. vllm/v1/core/sched/output.py +153 -0
  1078. vllm/v1/core/sched/scheduler.py +1015 -0
  1079. vllm/v1/core/sched/utils.py +22 -0
  1080. vllm/v1/core/single_type_kv_cache_manager.py +358 -0
  1081. vllm/v1/engine/__init__.py +171 -0
  1082. vllm/v1/engine/async_llm.py +546 -0
  1083. vllm/v1/engine/core.py +801 -0
  1084. vllm/v1/engine/core_client.py +1020 -0
  1085. vllm/v1/engine/detokenizer.py +260 -0
  1086. vllm/v1/engine/exceptions.py +16 -0
  1087. vllm/v1/engine/llm_engine.py +316 -0
  1088. vllm/v1/engine/logprobs.py +198 -0
  1089. vllm/v1/engine/mm_input_cache.py +90 -0
  1090. vllm/v1/engine/output_processor.py +427 -0
  1091. vllm/v1/engine/parallel_sampling.py +132 -0
  1092. vllm/v1/engine/processor.py +398 -0
  1093. vllm/v1/executor/__init__.py +0 -0
  1094. vllm/v1/executor/abstract.py +112 -0
  1095. vllm/v1/executor/multiproc_executor.py +532 -0
  1096. vllm/v1/executor/ray_distributed_executor.py +61 -0
  1097. vllm/v1/kv_cache_interface.py +208 -0
  1098. vllm/v1/metrics/__init__.py +0 -0
  1099. vllm/v1/metrics/loggers.py +511 -0
  1100. vllm/v1/metrics/ray_wrappers.py +120 -0
  1101. vllm/v1/metrics/reader.py +245 -0
  1102. vllm/v1/metrics/stats.py +238 -0
  1103. vllm/v1/outputs.py +115 -0
  1104. vllm/v1/request.py +191 -0
  1105. vllm/v1/sample/__init__.py +0 -0
  1106. vllm/v1/sample/metadata.py +43 -0
  1107. vllm/v1/sample/ops/__init__.py +0 -0
  1108. vllm/v1/sample/ops/bad_words.py +38 -0
  1109. vllm/v1/sample/ops/penalties.py +58 -0
  1110. vllm/v1/sample/ops/topk_topp_sampler.py +292 -0
  1111. vllm/v1/sample/rejection_sampler.py +630 -0
  1112. vllm/v1/sample/sampler.py +270 -0
  1113. vllm/v1/sample/tpu/__init__.py +0 -0
  1114. vllm/v1/sample/tpu/metadata.py +123 -0
  1115. vllm/v1/sample/tpu/sampler.py +144 -0
  1116. vllm/v1/serial_utils.py +313 -0
  1117. vllm/v1/spec_decode/__init__.py +0 -0
  1118. vllm/v1/spec_decode/eagle.py +424 -0
  1119. vllm/v1/spec_decode/medusa.py +61 -0
  1120. vllm/v1/spec_decode/metadata.py +61 -0
  1121. vllm/v1/spec_decode/metrics.py +177 -0
  1122. vllm/v1/spec_decode/ngram_proposer.py +131 -0
  1123. vllm/v1/spec_decode/utils.py +45 -0
  1124. vllm/v1/structured_output/__init__.py +215 -0
  1125. vllm/v1/structured_output/backend_guidance.py +244 -0
  1126. vllm/v1/structured_output/backend_types.py +133 -0
  1127. vllm/v1/structured_output/backend_xgrammar.py +317 -0
  1128. vllm/v1/structured_output/request.py +85 -0
  1129. vllm/v1/structured_output/utils.py +174 -0
  1130. vllm/v1/utils.py +294 -0
  1131. vllm/v1/worker/__init__.py +0 -0
  1132. vllm/v1/worker/block_table.py +139 -0
  1133. vllm/v1/worker/gpu_input_batch.py +680 -0
  1134. vllm/v1/worker/gpu_model_runner.py +2084 -0
  1135. vllm/v1/worker/gpu_worker.py +373 -0
  1136. vllm/v1/worker/lora_model_runner_mixin.py +145 -0
  1137. vllm/v1/worker/tpu_model_runner.py +1510 -0
  1138. vllm/v1/worker/tpu_worker.py +276 -0
  1139. vllm/v1/worker/utils.py +74 -0
  1140. vllm/v1/worker/worker_base.py +64 -0
  1141. vllm/version.py +40 -0
  1142. vllm/vllm_flash_attn/.gitkeep +0 -0
  1143. vllm/worker/__init__.py +0 -0
  1144. vllm/worker/cache_engine.py +144 -0
  1145. vllm/worker/cpu_enc_dec_model_runner.py +326 -0
  1146. vllm/worker/cpu_model_runner.py +671 -0
  1147. vllm/worker/cpu_pooling_model_runner.py +125 -0
  1148. vllm/worker/cpu_worker.py +400 -0
  1149. vllm/worker/enc_dec_model_runner.py +555 -0
  1150. vllm/worker/hpu_model_runner.py +2319 -0
  1151. vllm/worker/hpu_worker.py +483 -0
  1152. vllm/worker/model_runner.py +2178 -0
  1153. vllm/worker/model_runner_base.py +281 -0
  1154. vllm/worker/multi_step_hpu_worker.py +122 -0
  1155. vllm/worker/multi_step_model_runner.py +910 -0
  1156. vllm/worker/multi_step_neuron_model_runner.py +84 -0
  1157. vllm/worker/multi_step_neuronx_distributed_model_runner.py +63 -0
  1158. vllm/worker/multi_step_tpu_worker.py +107 -0
  1159. vllm/worker/multi_step_worker.py +196 -0
  1160. vllm/worker/neuron_model_runner.py +418 -0
  1161. vllm/worker/neuron_worker.py +158 -0
  1162. vllm/worker/neuronx_distributed_model_runner.py +136 -0
  1163. vllm/worker/pooling_model_runner.py +211 -0
  1164. vllm/worker/tpu_model_runner.py +908 -0
  1165. vllm/worker/tpu_worker.py +336 -0
  1166. vllm/worker/utils.py +52 -0
  1167. vllm/worker/worker.py +574 -0
  1168. vllm/worker/worker_base.py +644 -0
  1169. vllm/worker/xpu_model_runner.py +606 -0
  1170. vllm/worker/xpu_worker.py +185 -0
  1171. vllm_cpu_avx512bf16-0.9.0.post2.dist-info/METADATA +335 -0
  1172. vllm_cpu_avx512bf16-0.9.0.post2.dist-info/RECORD +1175 -0
  1173. vllm_cpu_avx512bf16-0.9.0.post2.dist-info/WHEEL +5 -0
  1174. vllm_cpu_avx512bf16-0.9.0.post2.dist-info/entry_points.txt +5 -0
  1175. vllm_cpu_avx512bf16-0.9.0.post2.dist-info/top_level.txt +1 -0
vllm/config.py ADDED
@@ -0,0 +1,4600 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+
3
+ import ast
4
+ import copy
5
+ import enum
6
+ import hashlib
7
+ import inspect
8
+ import json
9
+ import textwrap
10
+ import uuid
11
+ import warnings
12
+ from collections import Counter
13
+ from contextlib import contextmanager
14
+ from dataclasses import (MISSING, Field, asdict, dataclass, field, fields,
15
+ is_dataclass, replace)
16
+ from functools import cached_property
17
+ from importlib.util import find_spec
18
+ from pathlib import Path
19
+ from typing import (TYPE_CHECKING, Any, Callable, ClassVar, Literal, Optional,
20
+ Protocol, TypeVar, Union, cast, get_args, get_origin)
21
+
22
+ import regex as re
23
+ import torch
24
+ from torch.distributed import ProcessGroup, ReduceOp
25
+ from transformers import PretrainedConfig
26
+ from typing_extensions import deprecated
27
+
28
+ import vllm.envs as envs
29
+ from vllm import version
30
+ from vllm.compilation.inductor_pass import CallableInductorPass, InductorPass
31
+ from vllm.logger import init_logger
32
+ from vllm.model_executor.layers.quantization import (QUANTIZATION_METHODS,
33
+ QuantizationMethods,
34
+ get_quantization_config)
35
+ from vllm.model_executor.models import ModelRegistry
36
+ from vllm.platforms import current_platform
37
+ from vllm.tracing import is_otel_available, otel_import_error_traceback
38
+ from vllm.transformers_utils.config import (
39
+ ConfigFormat, get_config, get_hf_image_processor_config,
40
+ get_hf_text_config, get_pooling_config,
41
+ get_sentence_transformer_tokenizer_config, is_encoder_decoder,
42
+ try_get_generation_config, uses_mrope)
43
+ from vllm.transformers_utils.s3_utils import S3Model
44
+ from vllm.transformers_utils.utils import is_s3, maybe_model_redirect
45
+ from vllm.utils import (DEFAULT_MAX_NUM_BATCHED_TOKENS,
46
+ MULTIMODAL_MODEL_MAX_NUM_BATCHED_TOKENS,
47
+ POOLING_MODEL_MAX_NUM_BATCHED_TOKENS, GiB_bytes,
48
+ LayerBlockType, cuda_device_count_stateless,
49
+ get_cpu_memory, get_open_port, is_torch_equal_or_newer,
50
+ random_uuid, resolve_obj_by_qualname)
51
+
52
+ if TYPE_CHECKING:
53
+ from _typeshed import DataclassInstance
54
+ from ray.util.placement_group import PlacementGroup
55
+
56
+ from vllm.executor.executor_base import ExecutorBase
57
+ from vllm.model_executor.layers.quantization.base_config import (
58
+ QuantizationConfig)
59
+ from vllm.model_executor.model_loader import BaseModelLoader
60
+
61
+ ConfigType = type[DataclassInstance]
62
+ else:
63
+ QuantizationConfig = Any
64
+ ConfigType = type
65
+
66
+ logger = init_logger(__name__)
67
+
68
+ ConfigT = TypeVar("ConfigT", bound=ConfigType)
69
+
70
+ TaskOption = Literal["auto", "generate", "embedding", "embed", "classify",
71
+ "score", "reward", "transcription"]
72
+
73
+ _ResolvedTask = Literal["generate", "embed", "classify", "score", "reward",
74
+ "draft", "transcription"]
75
+
76
+ RunnerType = Literal["generate", "pooling", "draft", "transcription"]
77
+
78
+ _RUNNER_TASKS: dict[RunnerType, list[_ResolvedTask]] = {
79
+ "generate": ["generate"],
80
+ "pooling": ["embed", "classify", "score", "reward"],
81
+ "draft": ["draft"],
82
+ "transcription": ["transcription"],
83
+ }
84
+
85
+ _TASK_RUNNER: dict[_ResolvedTask, RunnerType] = {
86
+ task: runner
87
+ for runner, tasks in _RUNNER_TASKS.items()
88
+ for task in tasks
89
+ }
90
+
91
+ HfOverrides = Union[dict[str, Any], Callable[[PretrainedConfig],
92
+ PretrainedConfig]]
93
+
94
+
95
+ class SupportsHash(Protocol):
96
+
97
+ def compute_hash(self) -> str:
98
+ ...
99
+
100
+
101
+ class SupportsMetricsInfo(Protocol):
102
+
103
+ def metrics_info(self) -> dict[str, str]:
104
+ ...
105
+
106
+
107
+ class ModelImpl(str, enum.Enum):
108
+ AUTO = "auto"
109
+ VLLM = "vllm"
110
+ TRANSFORMERS = "transformers"
111
+
112
+
113
+ def get_attr_docs(cls: type[Any]) -> dict[str, str]:
114
+ """
115
+ Get any docstrings placed after attribute assignments in a class body.
116
+
117
+ https://davidism.com/mit-license/
118
+ """
119
+
120
+ def pairwise(iterable):
121
+ """
122
+ Manually implement https://docs.python.org/3/library/itertools.html#itertools.pairwise
123
+
124
+ Can be removed when Python 3.9 support is dropped.
125
+ """
126
+ iterator = iter(iterable)
127
+ a = next(iterator, None)
128
+
129
+ for b in iterator:
130
+ yield a, b
131
+ a = b
132
+
133
+ cls_node = ast.parse(textwrap.dedent(inspect.getsource(cls))).body[0]
134
+
135
+ if not isinstance(cls_node, ast.ClassDef):
136
+ raise TypeError("Given object was not a class.")
137
+
138
+ out = {}
139
+
140
+ # Consider each pair of nodes.
141
+ for a, b in pairwise(cls_node.body):
142
+ # Must be an assignment then a constant string.
143
+ if (not isinstance(a, (ast.Assign, ast.AnnAssign))
144
+ or not isinstance(b, ast.Expr)
145
+ or not isinstance(b.value, ast.Constant)
146
+ or not isinstance(b.value.value, str)):
147
+ continue
148
+
149
+ doc = inspect.cleandoc(b.value.value)
150
+
151
+ # An assignment can have multiple targets (a = b = v), but an
152
+ # annotated assignment only has one target.
153
+ targets = a.targets if isinstance(a, ast.Assign) else [a.target]
154
+
155
+ for target in targets:
156
+ # Must be assigning to a plain name.
157
+ if not isinstance(target, ast.Name):
158
+ continue
159
+
160
+ out[target.id] = doc
161
+
162
+ return out
163
+
164
+
165
+ def config(cls: ConfigT) -> ConfigT:
166
+ """
167
+ A decorator that ensures all fields in a dataclass have default values
168
+ and that each field has a docstring.
169
+
170
+ If a `ConfigT` is used as a CLI argument itself, the default value provided
171
+ by `get_kwargs` will be the result parsing a JSON string as the kwargs
172
+ (i.e. `ConfigT(**json.loads(cli_arg))`). However, if a particular `ConfigT`
173
+ requires custom construction from CLI (i.e. `CompilationConfig`), it can
174
+ have a `from_cli` method, which will be called instead.
175
+ """
176
+ if not is_dataclass(cls):
177
+ raise TypeError("The decorated class must be a dataclass.")
178
+ attr_docs = get_attr_docs(cls)
179
+ for f in fields(cls):
180
+ if f.init and f.default is MISSING and f.default_factory is MISSING:
181
+ raise ValueError(
182
+ f"Field '{f.name}' in {cls.__name__} must have a default value."
183
+ )
184
+
185
+ if f.name not in attr_docs:
186
+ raise ValueError(
187
+ f"Field '{f.name}' in {cls.__name__} must have a docstring.")
188
+
189
+ if get_origin(f.type) is Union:
190
+ args = get_args(f.type)
191
+ literal_args = [arg for arg in args if get_origin(arg) is Literal]
192
+ if len(literal_args) > 1:
193
+ raise ValueError(
194
+ f"Field '{f.name}' in {cls.__name__} must use a single "
195
+ "Literal type. Please use 'Literal[Literal1, Literal2]' "
196
+ "instead of 'Union[Literal1, Literal2]'.")
197
+ return cls
198
+
199
+
200
+ def get_field(cls: ConfigType, name: str) -> Field:
201
+ """Get the default factory field of a dataclass by name. Used for getting
202
+ default factory fields in `EngineArgs`."""
203
+ if not is_dataclass(cls):
204
+ raise TypeError("The given class is not a dataclass.")
205
+ cls_fields = {f.name: f for f in fields(cls)}
206
+ if name not in cls_fields:
207
+ raise ValueError(f"Field '{name}' not found in {cls.__name__}.")
208
+ named_field: Field = cls_fields[name]
209
+ if (default_factory := named_field.default_factory) is not MISSING:
210
+ return field(default_factory=default_factory)
211
+ if (default := named_field.default) is not MISSING:
212
+ return field(default=default)
213
+ raise ValueError(
214
+ f"{cls.__name__}.{name} must have a default value or default factory.")
215
+
216
+
217
+ def is_init_field(cls: ConfigType, name: str) -> bool:
218
+ return next(f for f in fields(cls) if f.name == name).init
219
+
220
+
221
+ TokenizerMode = Literal["auto", "slow", "mistral", "custom"]
222
+ ModelDType = Literal["auto", "half", "float16", "bfloat16", "float", "float32"]
223
+
224
+
225
+ @config
226
+ @dataclass
227
+ class ModelConfig:
228
+ """Configuration for the model."""
229
+
230
+ model: str = "facebook/opt-125m"
231
+ """Name or path of the Hugging Face model to use. It is also used as the
232
+ content for `model_name` tag in metrics output when `served_model_name` is
233
+ not specified."""
234
+ task: Literal[TaskOption, Literal["draft"]] = "auto"
235
+ """The task to use the model for. Each vLLM instance only supports one
236
+ task, even if the same model can be used for multiple tasks. When the model
237
+ only supports one task, "auto" can be used to select it; otherwise, you
238
+ must specify explicitly which task to use."""
239
+ tokenizer: str = None # type: ignore
240
+ """Name or path of the Hugging Face tokenizer to use. If unspecified, model
241
+ name or path will be used."""
242
+ tokenizer_mode: TokenizerMode = "auto"
243
+ """Tokenizer mode:\n
244
+ - "auto" will use the fast tokenizer if available.\n
245
+ - "slow" will always use the slow tokenizer.\n
246
+ - "mistral" will always use the tokenizer from `mistral_common`.\n
247
+ - "custom" will use --tokenizer to select the preregistered tokenizer."""
248
+ trust_remote_code: bool = False
249
+ """Trust remote code (e.g., from HuggingFace) when downloading the model
250
+ and tokenizer."""
251
+ dtype: Union[ModelDType, torch.dtype] = "auto"
252
+ """Data type for model weights and activations:\n
253
+ - "auto" will use FP16 precision for FP32 and FP16 models, and BF16
254
+ precision for BF16 models.\n
255
+ - "half" for FP16. Recommended for AWQ quantization.\n
256
+ - "float16" is the same as "half".\n
257
+ - "bfloat16" for a balance between precision and range.\n
258
+ - "float" is shorthand for FP32 precision.\n
259
+ - "float32" for FP32 precision."""
260
+ seed: Optional[int] = None
261
+ """Random seed for reproducibility. Initialized to None in V0, but
262
+ initialized to 0 in V1."""
263
+ hf_config_path: Optional[str] = None
264
+ """Name or path of the Hugging Face config to use. If unspecified, model
265
+ name or path will be used."""
266
+ allowed_local_media_path: str = ""
267
+ """Allowing API requests to read local images or videos from directories
268
+ specified by the server file system. This is a security risk. Should only
269
+ be enabled in trusted environments."""
270
+ revision: Optional[str] = None
271
+ """The specific model version to use. It can be a branch name, a tag name,
272
+ or a commit id. If unspecified, will use the default version."""
273
+ code_revision: Optional[str] = None
274
+ """The specific revision to use for the model code on the Hugging Face Hub.
275
+ It can be a branch name, a tag name, or a commit id. If unspecified, will
276
+ use the default version."""
277
+ rope_scaling: dict[str, Any] = field(default_factory=dict)
278
+ """RoPE scaling configuration. For example,
279
+ `{"rope_type":"dynamic","factor":2.0}`."""
280
+ rope_theta: Optional[float] = None
281
+ """RoPE theta. Use with `rope_scaling`. In some cases, changing the RoPE
282
+ theta improves the performance of the scaled model."""
283
+ tokenizer_revision: Optional[str] = None
284
+ """The specific revision to use for the tokenizer on the Hugging Face Hub.
285
+ It can be a branch name, a tag name, or a commit id. If unspecified, will
286
+ use the default version."""
287
+ max_model_len: int = None # type: ignore
288
+ """Model context length (prompt and output). If unspecified, will be
289
+ automatically derived from the model config.
290
+
291
+ When passing via `--max-model-len`, supports k/m/g/K/M/G in human-readable
292
+ format. Examples:\n
293
+ - 1k -> 1000\n
294
+ - 1K -> 1024\n
295
+ - 25.6k -> 25,600"""
296
+ spec_target_max_model_len: Optional[int] = None
297
+ """Specify the maximum length for spec decoding draft models."""
298
+ quantization: Optional[QuantizationMethods] = None
299
+ """Method used to quantize the weights. If `None`, we first check the
300
+ `quantization_config` attribute in the model config file. If that is
301
+ `None`, we assume the model weights are not quantized and use `dtype` to
302
+ determine the data type of the weights."""
303
+ enforce_eager: bool = False
304
+ """Whether to always use eager-mode PyTorch. If True, we will disable CUDA
305
+ graph and always execute the model in eager mode. If False, we will use
306
+ CUDA graph and eager execution in hybrid for maximal performance and
307
+ flexibility."""
308
+ max_seq_len_to_capture: int = 8192
309
+ """Maximum sequence len covered by CUDA graphs. When a sequence has context
310
+ length larger than this, we fall back to eager mode. Additionally for
311
+ encoder-decoder models, if the sequence length of the encoder input is
312
+ larger than this, we fall back to the eager mode."""
313
+ max_logprobs: int = 20
314
+ """Maximum number of log probabilities to return when `logprobs` is
315
+ specified in `SamplingParams`. The default value comes the default for the
316
+ OpenAI Chat Completions API."""
317
+ disable_sliding_window: bool = False
318
+ """Whether to disable sliding window. If True, we will disable the sliding
319
+ window functionality of the model, capping to sliding window size. If the
320
+ model does not support sliding window, this argument is ignored."""
321
+ disable_cascade_attn: bool = False
322
+ """Disable cascade attention for V1. While cascade attention does not
323
+ change the mathematical correctness, disabling it could be useful for
324
+ preventing potential numerical issues. Note that even if this is set to
325
+ False, cascade attention will be only used when the heuristic tells that
326
+ it's beneficial."""
327
+ skip_tokenizer_init: bool = False
328
+ """Skip initialization of tokenizer and detokenizer. Expects valid
329
+ `prompt_token_ids` and `None` for prompt from the input. The generated
330
+ output will contain token ids."""
331
+ enable_prompt_embeds: bool = False
332
+ """If `True`, enables passing text embeddings as inputs via the
333
+ `prompt_embeds` key. Note that enabling this will double the time required
334
+ for graph compilation."""
335
+ served_model_name: Optional[Union[str, list[str]]] = None
336
+ """The model name(s) used in the API. If multiple names are provided, the
337
+ server will respond to any of the provided names. The model name in the
338
+ model field of a response will be the first name in this list. If not
339
+ specified, the model name will be the same as the `--model` argument. Noted
340
+ that this name(s) will also be used in `model_name` tag content of
341
+ prometheus metrics, if multiple names provided, metrics tag will take the
342
+ first one."""
343
+ limit_mm_per_prompt: dict[str, int] = field(default_factory=dict)
344
+ """Maximum number of data items per modality per prompt. Only applicable
345
+ for multimodal models."""
346
+ use_async_output_proc: bool = True
347
+ """Whether to use async output processor."""
348
+ config_format: Union[str, ConfigFormat] = ConfigFormat.AUTO.value
349
+ """The format of the model config to load:\n
350
+ - "auto" will try to load the config in hf format if available else it
351
+ will try to load in mistral format.\n
352
+ - "hf" will load the config in hf format.\n
353
+ - "mistral" will load the config in mistral format."""
354
+ hf_token: Optional[Union[bool, str]] = None
355
+ """The token to use as HTTP bearer authorization for remote files . If
356
+ `True`, will use the token generated when running `huggingface-cli login`
357
+ (stored in `~/.huggingface`)."""
358
+ hf_overrides: HfOverrides = field(default_factory=dict)
359
+ """If a dictionary, contains arguments to be forwarded to the Hugging Face
360
+ config. If a callable, it is called to update the HuggingFace config."""
361
+ mm_processor_kwargs: Optional[dict[str, Any]] = None
362
+ """Arguments to be forwarded to the model's processor for multi-modal data,
363
+ e.g., image processor. Overrides for the multi-modal processor obtained
364
+ from `AutoProcessor.from_pretrained`. The available overrides depend on the
365
+ model that is being run. For example, for Phi-3-Vision: `{"num_crops": 4}`.
366
+ """
367
+ disable_mm_preprocessor_cache: bool = False
368
+ """If `True`, disable caching of the multi-modal preprocessor/mapper (not
369
+ recommended)."""
370
+ override_neuron_config: dict[str, Any] = field(default_factory=dict)
371
+ """Initialize non-default neuron config or override default neuron config
372
+ that are specific to Neuron devices, this argument will be used to
373
+ configure the neuron config that can not be gathered from the vllm
374
+ arguments. e.g. `{"cast_logits_dtype": "bloat16"}`."""
375
+ pooler_config: Optional["PoolerConfig"] = field(init=False)
376
+ """Pooler config which controls the behaviour of output pooling in pooling
377
+ models."""
378
+ override_pooler_config: Optional[Union[dict, "PoolerConfig"]] = None
379
+ """Initialize non-default pooling config or override default pooling config
380
+ for the pooling model. e.g. `{"pooling_type": "mean", "normalize": false}`.
381
+ """
382
+ logits_processor_pattern: Optional[str] = None
383
+ """Optional regex pattern specifying valid logits processor qualified names
384
+ that can be passed with the `logits_processors` extra completion argument.
385
+ Defaults to `None`, which allows no processors."""
386
+ generation_config: str = "auto"
387
+ """The folder path to the generation config. Defaults to `"auto"`, the
388
+ generation config will be loaded from model path. If set to `"vllm"`, no
389
+ generation config is loaded, vLLM defaults will be used. If set to a folder
390
+ path, the generation config will be loaded from the specified folder path.
391
+ If `max_new_tokens` is specified in generation config, then it sets a
392
+ server-wide limit on the number of output tokens for all requests."""
393
+ override_generation_config: dict[str, Any] = field(default_factory=dict)
394
+ """Overrides or sets generation config. e.g. `{"temperature": 0.5}`. If
395
+ used with `--generation-config auto`, the override parameters will be
396
+ merged with the default config from the model. If used with
397
+ `--generation-config vllm`, only the override parameters are used."""
398
+ enable_sleep_mode: bool = False
399
+ """Enable sleep mode for the engine (only cuda platform is supported)."""
400
+ model_impl: Union[str, ModelImpl] = ModelImpl.AUTO.value
401
+ """Which implementation of the model to use:\n
402
+ - "auto" will try to use the vLLM implementation, if it exists, and fall
403
+ back to the Transformers implementation if no vLLM implementation is
404
+ available.\n
405
+ - "vllm" will use the vLLM model implementation.\n
406
+ - "transformers" will use the Transformers model implementation."""
407
+
408
+ def compute_hash(self) -> str:
409
+ """
410
+ WARNING: Whenever a new field is added to this config,
411
+ ensure that it is included in the factors list if
412
+ it affects the computation graph.
413
+
414
+ Provide a hash that uniquely identifies all the configs
415
+ that affect the structure of the computation
416
+ graph from input ids/embeddings to the final hidden states,
417
+ excluding anything before input ids/embeddings and after
418
+ the final hidden states.
419
+ """
420
+ factors: list[Any] = []
421
+ factors.append(self.model)
422
+ factors.append(self.dtype)
423
+ factors.append(self.quantization)
424
+ factors.append(self.revision)
425
+ factors.append(self.code_revision)
426
+ factors.append(self.max_model_len)
427
+ factors.append(self.max_logprobs)
428
+ factors.append(self.disable_sliding_window)
429
+ factors.append(self.trust_remote_code)
430
+ factors.append(self.generation_config)
431
+ factors.append(self.model_impl)
432
+ factors.append(self.override_generation_config)
433
+ factors.append(self.rope_scaling)
434
+ factors.append(self.rope_theta)
435
+ # hf_config can control how the model looks!
436
+ factors.append(self.hf_config.to_json_string())
437
+ str_factors = str(factors)
438
+ assert_hashable(str_factors)
439
+ return hashlib.sha256(str(factors).encode()).hexdigest()
440
+
441
+ def __post_init__(self) -> None:
442
+ # Set the default seed to 0 in V1.
443
+ # NOTE(woosuk): In V0, we set the default seed to None because the
444
+ # driver worker shares the same process as the user process, and thus
445
+ # setting a seed affects the user process as well.
446
+ # In V1, we use separate processes for workers (unless
447
+ # VLLM_ENABLE_V1_MULTIPROCESSING=0), so setting a seed here
448
+ # doesn't affect the user process. However, without a consistent seed,
449
+ # different tensor parallel workers would sample different tokens,
450
+ # leading to inconsistent results.
451
+ if envs.VLLM_USE_V1 and self.seed is None:
452
+ self.seed = 0
453
+ if not envs.VLLM_ENABLE_V1_MULTIPROCESSING:
454
+ logger.warning(
455
+ "The global random seed is set to %d. Since "
456
+ "VLLM_ENABLE_V1_MULTIPROCESSING is set to False, this may "
457
+ "affect the random state of the Python process that "
458
+ "launched vLLM.", self.seed)
459
+
460
+ self.model = maybe_model_redirect(self.model)
461
+ # The tokenizer is consistent with the model by default.
462
+ if self.tokenizer is None:
463
+ self.tokenizer = self.model
464
+ if self.tokenizer_revision is None:
465
+ self.tokenizer_revision = self.revision
466
+ self.tokenizer = maybe_model_redirect(self.tokenizer)
467
+
468
+ if isinstance(self.hf_config_path, str):
469
+ self.hf_config_path = maybe_model_redirect(self.hf_config_path)
470
+
471
+ if callable(self.hf_overrides):
472
+ hf_overrides_kw = {}
473
+ hf_overrides_fn = self.hf_overrides
474
+ else:
475
+ hf_overrides_kw = self.hf_overrides
476
+ hf_overrides_fn = None
477
+
478
+ if self.rope_scaling:
479
+ hf_override: dict[str, Any] = {"rope_scaling": self.rope_scaling}
480
+ hf_overrides_kw.update(hf_override)
481
+ hf_overrides_str = json.dumps(hf_overrides_kw)
482
+ msg = (
483
+ "`--rope-scaling` will be removed in a future release. "
484
+ f"'Please instead use `--hf-overrides '{hf_overrides_str}'`")
485
+ warnings.warn(DeprecationWarning(msg), stacklevel=2)
486
+ if self.rope_theta is not None:
487
+ hf_override = {"rope_theta": self.rope_theta}
488
+ hf_overrides_kw.update(hf_override)
489
+ hf_overrides_str = json.dumps(hf_overrides_kw)
490
+ msg = (
491
+ "`--rope-theta` will be removed in a future release. "
492
+ f"'Please instead use `--hf-overrides '{hf_overrides_str}'`")
493
+ warnings.warn(DeprecationWarning(msg), stacklevel=2)
494
+
495
+ self.maybe_pull_model_tokenizer_for_s3(self.model, self.tokenizer)
496
+
497
+ if (backend := envs.VLLM_ATTENTION_BACKEND
498
+ ) and backend == "FLASHINFER" and find_spec("flashinfer") is None:
499
+ raise ValueError(
500
+ "VLLM_ATTENTION_BACKEND is set to FLASHINFER, but flashinfer "
501
+ "module was not found. See "
502
+ "https://github.com/vllm-project/vllm/blob/main/docker/Dockerfile " # noqa: E501
503
+ "for instructions on how to install it.")
504
+
505
+ from vllm.platforms import current_platform
506
+
507
+ if (self.enable_sleep_mode
508
+ and not current_platform.is_sleep_mode_available()):
509
+ raise ValueError(
510
+ "Sleep mode is not supported on current platform.")
511
+
512
+ if isinstance(self.config_format, str):
513
+ self.config_format = ConfigFormat(self.config_format)
514
+
515
+ hf_config = get_config(self.hf_config_path or self.model,
516
+ self.trust_remote_code, self.revision,
517
+ self.code_revision, self.config_format)
518
+
519
+ if hf_overrides_kw:
520
+ logger.info("Overriding HF config with %s", hf_overrides_kw)
521
+ hf_config.update(hf_overrides_kw)
522
+ if hf_overrides_fn:
523
+ logger.info("Overriding HF config with %s", hf_overrides_fn)
524
+ hf_config = hf_overrides_fn(hf_config)
525
+
526
+ self.hf_config = hf_config
527
+
528
+ self.hf_text_config = get_hf_text_config(self.hf_config)
529
+ self.attention_chunk_size = getattr(self.hf_text_config,
530
+ "attention_chunk_size", None)
531
+ self.encoder_config = self._get_encoder_config()
532
+ self.hf_image_processor_config = get_hf_image_processor_config(
533
+ self.model, hf_token=self.hf_token, revision=self.revision)
534
+ self.dtype = _get_and_verify_dtype(self.hf_config, self.dtype)
535
+
536
+ # Workaround for Gemma 2 which uses interleaved sliding window
537
+ # attention, but it's not specified in its config. TODO: remove this
538
+ # when Gemma 2 is fixed in Transformers.
539
+ if self.hf_text_config.model_type == "gemma2":
540
+ self.hf_text_config.sliding_window_pattern = 2
541
+
542
+ sliding_window = getattr(self.hf_text_config, "sliding_window", None)
543
+ sliding_window_pattern = getattr(self.hf_text_config,
544
+ "sliding_window_pattern", None)
545
+ has_interleaved_attention = sliding_window_pattern is not None or (
546
+ isinstance(sliding_window, list))
547
+
548
+ if not self.disable_sliding_window and has_interleaved_attention:
549
+ if (backend :=
550
+ envs.VLLM_ATTENTION_BACKEND) in ("XFORMERS", "FLASHINFER"):
551
+ sliding_window_len_min = get_min_sliding_window(
552
+ self.hf_text_config.sliding_window)
553
+
554
+ logger.warning_once(
555
+ "%s has interleaved attention, which is currently not supported by the %s backend. Disabling sliding window and capping the max length to the sliding window size (%d).", # noqa: E501
556
+ self.hf_text_config.model_type,
557
+ backend,
558
+ sliding_window_len_min,
559
+ )
560
+ self.disable_sliding_window = True
561
+ else:
562
+ # for a model with interleaved attention,
563
+ # the scheduler and the model treat it as full attention
564
+ # (i.e., not dropping any tokens outside the window).
565
+ # only the attention layer itself is aware of the sliding
566
+ # window, and use the window size to compute the attention.
567
+ self.hf_text_config.interleaved_sliding_window = sliding_window
568
+
569
+ if hasattr(self.hf_text_config, "sliding_window"):
570
+ delattr(self.hf_text_config, "sliding_window")
571
+
572
+ sliding_window = None
573
+
574
+ self.max_model_len = _get_and_verify_max_len(
575
+ hf_config=self.hf_text_config,
576
+ max_model_len=self.max_model_len,
577
+ disable_sliding_window=self.disable_sliding_window,
578
+ sliding_window_len=self.get_hf_config_sliding_window(),
579
+ spec_target_max_model_len=self.spec_target_max_model_len,
580
+ encoder_config=self.encoder_config)
581
+ self.served_model_name = get_served_model_name(self.model,
582
+ self.served_model_name)
583
+ self.multimodal_config = self._init_multimodal_config()
584
+ if not self.skip_tokenizer_init:
585
+ self._verify_tokenizer_mode()
586
+
587
+ self.is_attention_free = self._init_attention_free()
588
+ self.is_hybrid = self._init_is_hybrid()
589
+ self.has_noops = self._init_has_noops()
590
+ self.has_inner_state = self._init_has_inner_state()
591
+
592
+ if (not current_platform.is_neuron() and self.override_neuron_config):
593
+ raise ValueError(
594
+ "`override_neuron_config` is only supported on Neuron.")
595
+
596
+ supported_tasks, task = self._resolve_task(self.task)
597
+ self.supported_tasks = supported_tasks
598
+ self.task = task
599
+ if self.task in ("draft", "generate"):
600
+ self.truncation_side = "left"
601
+ else:
602
+ self.truncation_side = "right"
603
+
604
+ self.pooler_config = self._init_pooler_config()
605
+
606
+ self._verify_quantization()
607
+ self._verify_cuda_graph()
608
+ self._verify_bnb_config()
609
+
610
+ @property
611
+ def registry(self):
612
+ return ModelRegistry
613
+
614
+ @property
615
+ def architectures(self) -> list[str]:
616
+ return getattr(self.hf_config, "architectures", [])
617
+
618
+ def maybe_pull_model_tokenizer_for_s3(self, model: str,
619
+ tokenizer: str) -> None:
620
+ """Pull model/tokenizer from S3 to temporary directory when needed.
621
+
622
+ Args:
623
+ model: Model name or path
624
+ tokenizer: Tokenizer name or path
625
+ """
626
+ if not (is_s3(model) or is_s3(tokenizer)):
627
+ return
628
+
629
+ if is_s3(model):
630
+ s3_model = S3Model()
631
+ s3_model.pull_files(model,
632
+ allow_pattern=["*.model", "*.py", "*.json"])
633
+ self.model_weights = model
634
+ self.model = s3_model.dir
635
+
636
+ # If tokenizer is same as model, download to same directory
637
+ if model == tokenizer:
638
+ s3_model.pull_files(
639
+ model, ignore_pattern=["*.pt", "*.safetensors", "*.bin"])
640
+ self.tokenizer = s3_model.dir
641
+ return
642
+
643
+ # Only download tokenizer if needed and not already handled
644
+ if is_s3(tokenizer):
645
+ s3_tokenizer = S3Model()
646
+ s3_tokenizer.pull_files(
647
+ model, ignore_pattern=["*.pt", "*.safetensors", "*.bin"])
648
+ self.tokenizer = s3_tokenizer.dir
649
+
650
+ def _init_multimodal_config(self) -> Optional["MultiModalConfig"]:
651
+ if self.registry.is_multimodal_model(self.architectures):
652
+ return MultiModalConfig(
653
+ limit_per_prompt=self.limit_mm_per_prompt,
654
+ mm_processor_kwargs=self.mm_processor_kwargs,
655
+ disable_mm_preprocessor_cache=self.
656
+ disable_mm_preprocessor_cache)
657
+
658
+ if self.limit_mm_per_prompt:
659
+ raise ValueError("`limit_mm_per_prompt` is only supported for "
660
+ "multimodal models.")
661
+ if self.mm_processor_kwargs:
662
+ raise ValueError("`mm_processor_kwargs` is only supported for "
663
+ "multimodal models.")
664
+ if self.disable_mm_preprocessor_cache:
665
+ raise ValueError("`disable_mm_preprocessor_cache` is only "
666
+ "supported for multimodal models.")
667
+
668
+ return None
669
+
670
+ def _get_encoder_config(self):
671
+ return get_sentence_transformer_tokenizer_config(
672
+ self.model, self.revision)
673
+
674
+ def _init_pooler_config(self) -> Optional["PoolerConfig"]:
675
+
676
+ if self.runner_type == "pooling":
677
+ if isinstance(self.override_pooler_config, dict):
678
+ self.override_pooler_config = PoolerConfig(
679
+ **self.override_pooler_config)
680
+
681
+ pooler_config = self.override_pooler_config or PoolerConfig()
682
+
683
+ base_config = get_pooling_config(self.model, self.revision)
684
+ if base_config is not None:
685
+ # Only set values that are not overridden by the user
686
+ for k, v in base_config.items():
687
+ if getattr(pooler_config, k) is None:
688
+ setattr(pooler_config, k, v)
689
+
690
+ if self.is_matryoshka:
691
+ if pooler_config.normalize is None:
692
+ pooler_config.normalize = True
693
+ elif not pooler_config.normalize:
694
+ raise ValueError(
695
+ "`normalize` must be enabled (set to True) "
696
+ "for models that are compatible with "
697
+ "Matryoshka Representation.")
698
+
699
+ return pooler_config
700
+
701
+ return None
702
+
703
+ def _init_attention_free(self) -> bool:
704
+ return self.registry.is_attention_free_model(self.architectures)
705
+
706
+ def _init_is_hybrid(self) -> bool:
707
+ return self.registry.is_hybrid_model(self.architectures)
708
+
709
+ def _init_has_noops(self) -> bool:
710
+ architectures = getattr(self.hf_config, "architectures", [])
711
+ return self.registry.is_noops_model(architectures)
712
+
713
+ def _init_has_inner_state(self) -> bool:
714
+ return self.registry.model_has_inner_state(self.architectures)
715
+
716
+ def _verify_tokenizer_mode(self) -> None:
717
+ tokenizer_mode = cast(TokenizerMode, self.tokenizer_mode.lower())
718
+ if tokenizer_mode not in get_args(TokenizerMode):
719
+ raise ValueError(
720
+ f"Unknown tokenizer mode: {self.tokenizer_mode}. Must be "
721
+ f"one of {get_args(TokenizerMode)}.")
722
+ self.tokenizer_mode = tokenizer_mode
723
+
724
+ def _get_preferred_task(
725
+ self,
726
+ architectures: list[str],
727
+ supported_tasks: set[_ResolvedTask],
728
+ ) -> Optional[_ResolvedTask]:
729
+ model_id = self.model
730
+ if get_pooling_config(model_id, self.revision):
731
+ return "embed"
732
+ if self.registry.is_cross_encoder_model(architectures):
733
+ return "score"
734
+ if self.registry.is_transcription_model(architectures):
735
+ return "transcription"
736
+
737
+ suffix_to_preferred_task: list[tuple[str, _ResolvedTask]] = [
738
+ # Other models follow this pattern
739
+ ("ForCausalLM", "generate"),
740
+ ("ForConditionalGeneration", "generate"),
741
+ ("ForSequenceClassification", "classify"),
742
+ ("ChatModel", "generate"),
743
+ ("LMHeadModel", "generate"),
744
+ ("EmbeddingModel", "embed"),
745
+ ("RewardModel", "reward"),
746
+ ]
747
+ _, arch = self.registry.inspect_model_cls(architectures)
748
+
749
+ for suffix, pref_task in suffix_to_preferred_task:
750
+ if arch.endswith(suffix) and pref_task in supported_tasks:
751
+ return pref_task
752
+
753
+ return None
754
+
755
+ def _resolve_task(
756
+ self,
757
+ task_option: Literal[TaskOption, Literal["draft"]],
758
+ ) -> tuple[set[_ResolvedTask], _ResolvedTask]:
759
+ if task_option == "draft":
760
+ return {"draft"}, "draft"
761
+
762
+ registry = self.registry
763
+ architectures = self.architectures
764
+
765
+ runner_support: dict[RunnerType, bool] = {
766
+ # NOTE: Listed from highest to lowest priority,
767
+ # in case the model supports multiple of them
768
+ "transcription": registry.is_transcription_model(architectures),
769
+ "generate": registry.is_text_generation_model(architectures),
770
+ "pooling": registry.is_pooling_model(architectures),
771
+ }
772
+ supported_runner_types_lst: list[RunnerType] = [
773
+ runner_type
774
+ for runner_type, is_supported in runner_support.items()
775
+ if is_supported
776
+ ]
777
+
778
+ supported_tasks_lst: list[_ResolvedTask] = [
779
+ task for runner_type in supported_runner_types_lst
780
+ for task in _RUNNER_TASKS[runner_type]
781
+ ]
782
+ supported_tasks = set(supported_tasks_lst)
783
+
784
+ if task_option == "auto":
785
+ selected_task = next(iter(supported_tasks_lst))
786
+
787
+ if len(supported_tasks_lst) > 1:
788
+ preferred_task = self._get_preferred_task(
789
+ architectures, supported_tasks)
790
+ if preferred_task is not None:
791
+ selected_task = preferred_task
792
+
793
+ logger.info(
794
+ "This model supports multiple tasks: %s. "
795
+ "Defaulting to '%s'.", supported_tasks, selected_task)
796
+ else:
797
+ # Aliases
798
+ if task_option == "embedding":
799
+ preferred_task = self._get_preferred_task(
800
+ architectures, supported_tasks)
801
+ if preferred_task != "embed":
802
+ msg = ("The 'embedding' task will be restricted to "
803
+ "embedding models in a future release. Please "
804
+ "pass `--task classify`, `--task score`, or "
805
+ "`--task reward` explicitly for other pooling "
806
+ "models.")
807
+ warnings.warn(msg, DeprecationWarning, stacklevel=2)
808
+
809
+ task_option = preferred_task or "embed"
810
+
811
+ if task_option not in supported_tasks:
812
+ msg = (
813
+ f"This model does not support the '{task_option}' task. "
814
+ f"Supported tasks: {supported_tasks}")
815
+ raise ValueError(msg)
816
+
817
+ selected_task = task_option
818
+
819
+ return supported_tasks, selected_task
820
+
821
+ def _parse_quant_hf_config(self):
822
+ quant_cfg = getattr(self.hf_config, "quantization_config", None)
823
+ if quant_cfg is None:
824
+ # compressed-tensors uses a "compression_config" key
825
+ quant_cfg = getattr(self.hf_config, "compression_config", None)
826
+ return quant_cfg
827
+
828
+ def _verify_quantization(self) -> None:
829
+ supported_quantization = QUANTIZATION_METHODS
830
+ optimized_quantization_methods = [
831
+ "fp8", "marlin", "modelopt", "gptq_marlin_24", "gptq_marlin",
832
+ "awq_marlin", "fbgemm_fp8", "compressed-tensors", "experts_int8",
833
+ "quark", "modelopt_fp4", "bitblas", "gptq_bitblas"
834
+ ]
835
+ if self.quantization is not None:
836
+ self.quantization = cast(QuantizationMethods,
837
+ self.quantization.lower())
838
+
839
+ # Parse quantization method from the HF model config, if available.
840
+ quant_cfg = self._parse_quant_hf_config()
841
+
842
+ if quant_cfg is not None:
843
+ quant_method = quant_cfg.get("quant_method", "").lower()
844
+ quant_method = quant_method.replace("compressed_tensors",
845
+ "compressed-tensors")
846
+ quant_cfg["quant_method"] = quant_method
847
+
848
+ # Quantization methods which are overrides (i.e. they have a
849
+ # `override_quantization_method` method) must be checked in order
850
+ # of preference (this is particularly important for GPTQ).
851
+ overrides = [
852
+ "marlin",
853
+ "bitblas",
854
+ "gptq_marlin_24",
855
+ "gptq_marlin",
856
+ "gptq_bitblas",
857
+ "awq_marlin",
858
+ "ipex",
859
+ "moe_wna16",
860
+ ]
861
+ quantization_methods = [
862
+ q for q in supported_quantization if q not in overrides
863
+ ]
864
+ # Any custom overrides will be in quantization_methods so we place
865
+ # them at the start of the list so custom overrides have preference
866
+ # over the built in ones.
867
+ quantization_methods = quantization_methods + overrides
868
+
869
+ # Detect which checkpoint is it
870
+ for name in quantization_methods:
871
+ method = get_quantization_config(name)
872
+ quantization_override = method.override_quantization_method(
873
+ quant_cfg, self.quantization)
874
+ if quantization_override is not None:
875
+ # Raise error if the override is not custom (custom would
876
+ # be in QUANTIZATION_METHODS but not QuantizationMethods)
877
+ # and hasn't been added to the overrides list.
878
+ if (name in get_args(QuantizationMethods)
879
+ and name not in overrides):
880
+ raise ValueError(
881
+ f"Quantization method {name} is an override but "
882
+ "is has not been added to the `overrides` list "
883
+ "above. This is necessary to ensure that the "
884
+ "overrides are checked in order of preference.")
885
+ quant_method = quantization_override
886
+ self.quantization = quantization_override
887
+ break
888
+
889
+ # Verify quantization configurations.
890
+ if self.quantization is None:
891
+ self.quantization = quant_method
892
+ elif self.quantization != quant_method:
893
+ raise ValueError(
894
+ "Quantization method specified in the model config "
895
+ f"({quant_method}) does not match the quantization "
896
+ f"method specified in the `quantization` argument "
897
+ f"({self.quantization}).")
898
+
899
+ if self.quantization is not None:
900
+ if self.quantization not in supported_quantization:
901
+ raise ValueError(
902
+ f"Unknown quantization method: {self.quantization}. Must "
903
+ f"be one of {supported_quantization}.")
904
+ from vllm.platforms import current_platform
905
+ current_platform.verify_quantization(self.quantization)
906
+ if self.quantization not in optimized_quantization_methods:
907
+ logger.warning(
908
+ "%s quantization is not fully "
909
+ "optimized yet. The speed can be slower than "
910
+ "non-quantized models.", self.quantization)
911
+
912
+ def _verify_cuda_graph(self) -> None:
913
+ self.max_seq_len_to_capture = min(self.max_seq_len_to_capture,
914
+ self.max_model_len)
915
+ # CUDAGraph capture not supported for enc-dec models and mllama on ROCm
916
+ ROCM_UNSUPPORTED_MODELS = ['mllama']
917
+ unsupported_rocm = (self.hf_config.model_type
918
+ in ROCM_UNSUPPORTED_MODELS
919
+ or self.is_encoder_decoder)
920
+
921
+ if (unsupported_rocm and not self.enforce_eager
922
+ and current_platform.is_rocm()):
923
+ logger.warning(
924
+ "CUDA graph is not supported for %s on ROCm yet, fallback "
925
+ "to eager mode.", self.hf_config.model_type)
926
+ self.enforce_eager = True
927
+
928
+ def _verify_bnb_config(self) -> None:
929
+ """
930
+ The current version of bitsandbytes (0.45.3) with 8-bit models does not
931
+ yet support CUDA graph.
932
+ # TODO Remove this when bitsandbytes supports.
933
+ """
934
+ is_bitsandbytes = self.quantization == "bitsandbytes"
935
+ has_quantization_config = (getattr(self.hf_config,
936
+ "quantization_config", None)
937
+ is not None)
938
+ is_8bit = (self.hf_config.quantization_config.get(
939
+ "load_in_8bit", False) if has_quantization_config else False)
940
+ if all([
941
+ is_bitsandbytes,
942
+ has_quantization_config,
943
+ is_8bit,
944
+ not self.enforce_eager,
945
+ ]):
946
+ logger.warning(
947
+ "CUDA graph is not supported on BitsAndBytes 8bit yet, "
948
+ "fallback to the eager mode.")
949
+
950
+ self.enforce_eager = True
951
+
952
+ def _verify_with_expert_parallelism(self) -> None:
953
+ num_expert_names = [
954
+ "moe_num_experts", # Dbrx
955
+ "num_experts", # Jamba
956
+ "n_routed_experts", # DeepSeek
957
+ "num_local_experts", # Mixtral
958
+ ]
959
+ num_experts = 0
960
+ for name in num_expert_names:
961
+ num_experts = getattr(self.hf_text_config, name, 0)
962
+ if num_experts > 0:
963
+ break
964
+ if num_experts < 1:
965
+ raise ValueError(
966
+ "Number of experts in the model must be greater than 0 "
967
+ "when expert parallelism is enabled.")
968
+
969
+ def verify_dual_chunk_attention_config(
970
+ self,
971
+ load_config: "LoadConfig",
972
+ ) -> None:
973
+ if hasattr(self.hf_config, "dual_chunk_attention_config"):
974
+ # Try loading the sparse attention config
975
+ from vllm.model_executor.model_loader.weight_utils import (
976
+ get_sparse_attention_config)
977
+ sparse_attn_config = get_sparse_attention_config(self, load_config)
978
+ if sparse_attn_config:
979
+ self.hf_config.dual_chunk_attention_config[
980
+ "sparse_attention_config"] = sparse_attn_config
981
+ if "sparse_attention_enabled" not in \
982
+ self.hf_config.dual_chunk_attention_config:
983
+ self.hf_config.dual_chunk_attention_config[
984
+ "sparse_attention_enabled"] = True
985
+
986
+ def verify_async_output_proc(self, parallel_config, speculative_config,
987
+ device_config) -> None:
988
+ if not self.use_async_output_proc:
989
+ # Nothing to check
990
+ return
991
+
992
+ if parallel_config.pipeline_parallel_size > 1:
993
+ self.use_async_output_proc = False
994
+ return
995
+
996
+ # Reminder: Please update docs/features/compatibility_matrix.md
997
+ # If the feature combo become valid
998
+ from vllm.platforms import current_platform
999
+ if not current_platform.is_async_output_supported(self.enforce_eager):
1000
+ self.use_async_output_proc = False
1001
+ return
1002
+
1003
+ if envs.VLLM_USE_RAY_SPMD_WORKER:
1004
+ self.use_async_output_proc = False
1005
+ return
1006
+
1007
+ # Async postprocessor is not necessary for pooling models
1008
+ # since there is no token generation
1009
+ if self.runner_type == "pooling":
1010
+ self.use_async_output_proc = False
1011
+
1012
+ # Reminder: Please update docs/features/compatibility_matrix.md
1013
+ # If the feature combo become valid
1014
+ if speculative_config:
1015
+ self.use_async_output_proc = False
1016
+
1017
+ def verify_with_parallel_config(
1018
+ self,
1019
+ parallel_config: "ParallelConfig",
1020
+ ) -> None:
1021
+
1022
+ if parallel_config.distributed_executor_backend == "external_launcher":
1023
+ assert self.seed is not None, (
1024
+ "Seed must be set when using external launcher backend to "
1025
+ "make sure sampling results are the same across workers.")
1026
+
1027
+ total_num_attention_heads = getattr(self.hf_text_config,
1028
+ "num_attention_heads", 0)
1029
+ tensor_parallel_size = parallel_config.tensor_parallel_size
1030
+ if total_num_attention_heads % tensor_parallel_size != 0:
1031
+ raise ValueError(
1032
+ f"Total number of attention heads ({total_num_attention_heads})"
1033
+ " must be divisible by tensor parallel size "
1034
+ f"({tensor_parallel_size}).")
1035
+
1036
+ if parallel_config.enable_expert_parallel:
1037
+ self._verify_with_expert_parallelism()
1038
+
1039
+ pipeline_parallel_size = parallel_config.pipeline_parallel_size
1040
+ if pipeline_parallel_size > 1:
1041
+ if not self.registry.is_pp_supported_model(self.architectures):
1042
+ raise NotImplementedError(
1043
+ "Pipeline parallelism is not supported for this model. "
1044
+ "Supported models implement the `SupportsPP` interface.")
1045
+
1046
+ if self.use_async_output_proc:
1047
+ self.use_async_output_proc = False
1048
+
1049
+ def get_hf_config_sliding_window(
1050
+ self) -> Union[Optional[int], list[Optional[int]]]:
1051
+ """Get the sliding window size, or None if disabled."""
1052
+
1053
+ # Some models, like Qwen2 and Qwen1.5, use `use_sliding_window` in
1054
+ # addition to sliding window size. We check if that field is present
1055
+ # and if it's False, return None.
1056
+ if (hasattr(self.hf_text_config, "use_sliding_window")
1057
+ and not self.hf_text_config.use_sliding_window):
1058
+ return None
1059
+ return getattr(self.hf_text_config, "sliding_window", None)
1060
+
1061
+ def get_sliding_window(self) -> Optional[Union[int, list[Optional[int]]]]:
1062
+ """Get the sliding window size, or None if disabled.
1063
+ """
1064
+ # If user disables sliding window, return None.
1065
+ if self.disable_sliding_window:
1066
+ return None
1067
+ # Otherwise get the value from the hf config.
1068
+ return self.get_hf_config_sliding_window()
1069
+
1070
+ def get_vocab_size(self) -> int:
1071
+ return self.hf_text_config.vocab_size
1072
+
1073
+ def get_hidden_size(self) -> int:
1074
+ return self.hf_text_config.hidden_size
1075
+
1076
+ @property
1077
+ def is_deepseek_mla(self) -> bool:
1078
+ if not hasattr(self.hf_text_config, "model_type"):
1079
+ return False
1080
+ elif self.hf_text_config.model_type in \
1081
+ ('deepseek_v2', 'deepseek_v3', 'deepseek_mtp'):
1082
+ return self.hf_text_config.kv_lora_rank is not None
1083
+ elif self.hf_text_config.model_type == 'eagle':
1084
+ # if the model is an EAGLE module, check for the
1085
+ # underlying architecture
1086
+ return self.hf_text_config.model.model_type in \
1087
+ ('deepseek_v2', 'deepseek_v3') \
1088
+ and self.hf_text_config.kv_lora_rank is not None
1089
+ return False
1090
+
1091
+ def get_head_size(self) -> int:
1092
+ # TODO remove hard code
1093
+ if self.is_deepseek_mla:
1094
+ qk_rope_head_dim = getattr(self.hf_text_config, "qk_rope_head_dim",
1095
+ 0)
1096
+ if self.use_mla:
1097
+ return self.hf_text_config.kv_lora_rank + qk_rope_head_dim
1098
+ else:
1099
+ qk_nope_head_dim = getattr(self.hf_text_config,
1100
+ "qk_nope_head_dim", 0)
1101
+ if qk_rope_head_dim and qk_nope_head_dim:
1102
+ return qk_rope_head_dim + qk_nope_head_dim
1103
+
1104
+ if hasattr(self.hf_text_config,
1105
+ "model_type") and (self.hf_text_config.model_type
1106
+ == "zamba2"):
1107
+ return self.hf_text_config.attention_head_dim
1108
+
1109
+ if self.is_attention_free:
1110
+ return 0
1111
+
1112
+ # NOTE: Some configs may set head_dim=None in the config
1113
+ if getattr(self.hf_text_config, "head_dim", None) is not None:
1114
+ return self.hf_text_config.head_dim
1115
+
1116
+ # FIXME(woosuk): This may not be true for all models.
1117
+ return (self.hf_text_config.hidden_size //
1118
+ self.hf_text_config.num_attention_heads)
1119
+
1120
+ def get_total_num_kv_heads(self) -> int:
1121
+ """Returns the total number of KV heads."""
1122
+ # For GPTBigCode & Falcon:
1123
+ # NOTE: for falcon, when new_decoder_architecture is True, the
1124
+ # multi_query flag is ignored and we use n_head_kv for the number of
1125
+ # KV heads.
1126
+ falcon_model_types = ["falcon", "RefinedWeb", "RefinedWebModel"]
1127
+ new_decoder_arch_falcon = (
1128
+ self.hf_config.model_type in falcon_model_types
1129
+ and getattr(self.hf_config, "new_decoder_architecture", False))
1130
+ if not new_decoder_arch_falcon and getattr(self.hf_text_config,
1131
+ "multi_query", False):
1132
+ # Multi-query attention, only one KV head.
1133
+ # Currently, tensor parallelism is not supported in this case.
1134
+ return 1
1135
+
1136
+ # For DBRX and MPT
1137
+ if self.hf_config.model_type == "mpt":
1138
+ if "kv_n_heads" in self.hf_config.attn_config:
1139
+ return self.hf_config.attn_config["kv_n_heads"]
1140
+ return self.hf_config.num_attention_heads
1141
+ if self.hf_config.model_type == "dbrx":
1142
+ return getattr(self.hf_config.attn_config, "kv_n_heads",
1143
+ self.hf_config.num_attention_heads)
1144
+
1145
+ if self.hf_config.model_type == "nemotron-nas":
1146
+ for block in self.hf_config.block_configs:
1147
+ if not block.attention.no_op:
1148
+ return self.hf_config.num_attention_heads \
1149
+ // block.attention.n_heads_in_group
1150
+
1151
+ raise RuntimeError("Couldn't determine number of kv heads")
1152
+
1153
+ if self.is_attention_free:
1154
+ return 0
1155
+
1156
+ attributes = [
1157
+ # For Falcon:
1158
+ "n_head_kv",
1159
+ "num_kv_heads",
1160
+ # For LLaMA-2:
1161
+ "num_key_value_heads",
1162
+ # For ChatGLM:
1163
+ "multi_query_group_num",
1164
+ ]
1165
+ for attr in attributes:
1166
+ num_kv_heads = getattr(self.hf_text_config, attr, None)
1167
+ if num_kv_heads is not None:
1168
+ return num_kv_heads
1169
+
1170
+ # For non-grouped-query attention models, the number of KV heads is
1171
+ # equal to the number of attention heads.
1172
+ return self.hf_text_config.num_attention_heads
1173
+
1174
+ def get_num_kv_heads(self, parallel_config: "ParallelConfig") -> int:
1175
+ """Returns the number of KV heads per GPU."""
1176
+ if self.use_mla:
1177
+ # When using MLA during decode it becomes MQA
1178
+ return 1
1179
+
1180
+ total_num_kv_heads = self.get_total_num_kv_heads()
1181
+ # If tensor parallelism is used, we divide the number of KV heads by
1182
+ # the tensor parallel size. We will replicate the KV heads in the
1183
+ # case where the number of KV heads is smaller than the tensor
1184
+ # parallel size so each GPU has at least one KV head.
1185
+ return max(1,
1186
+ total_num_kv_heads // parallel_config.tensor_parallel_size)
1187
+
1188
+ def get_num_attention_heads(self,
1189
+ parallel_config: "ParallelConfig") -> int:
1190
+ num_heads = getattr(self.hf_text_config, "num_attention_heads", 0)
1191
+ return num_heads // parallel_config.tensor_parallel_size
1192
+
1193
+ def get_layers_start_end_indices(
1194
+ self, parallel_config: "ParallelConfig") -> tuple[int, int]:
1195
+ from vllm.distributed.utils import get_pp_indices
1196
+ if (self.hf_text_config.model_type == "deepseek_mtp"
1197
+ or self.hf_config.model_type == "mimo_mtp"):
1198
+ total_num_hidden_layers = getattr(self.hf_text_config,
1199
+ "num_nextn_predict_layers", 0)
1200
+ else:
1201
+ total_num_hidden_layers = getattr(self.hf_text_config,
1202
+ "num_hidden_layers", 0)
1203
+ # the layout order is: DP x PP x TP
1204
+ pp_rank = (parallel_config.rank // parallel_config.tensor_parallel_size
1205
+ ) % parallel_config.pipeline_parallel_size
1206
+ pp_size = parallel_config.pipeline_parallel_size
1207
+ start, end = get_pp_indices(total_num_hidden_layers, pp_rank, pp_size)
1208
+ return start, end
1209
+
1210
+ def get_num_layers(self, parallel_config: "ParallelConfig") -> int:
1211
+ start, end = self.get_layers_start_end_indices(parallel_config)
1212
+ return end - start
1213
+
1214
+ def get_num_layers_by_block_type(
1215
+ self,
1216
+ parallel_config: "ParallelConfig",
1217
+ block_type: LayerBlockType = LayerBlockType.attention,
1218
+ ) -> int:
1219
+ # This function relies on 'layers_block_type' in hf_config,
1220
+ # for w/o this attribute, we will need to have workarounds like so
1221
+ attn_block_type = block_type == LayerBlockType.attention
1222
+ is_transformer = not self.is_hybrid and \
1223
+ not self.has_noops and \
1224
+ not self.is_attention_free
1225
+ start, end = self.get_layers_start_end_indices(parallel_config)
1226
+
1227
+ if is_transformer:
1228
+ # Handle the basic case first
1229
+ return end - start if attn_block_type else 0
1230
+ elif self.is_attention_free:
1231
+ # Attention free
1232
+ # Note that this code assumes there
1233
+ # is only one type of attention-free block type.
1234
+ return 0 if attn_block_type else end - start
1235
+ elif self.has_noops:
1236
+ block_configs = self.hf_config.block_configs
1237
+ return sum(not bc.attention.no_op
1238
+ for bc in block_configs[start:end])
1239
+ else:
1240
+ # Hybrid model Jamba
1241
+ layers_block_type_value = getattr(self.hf_config,
1242
+ "layers_block_type", None)
1243
+ if layers_block_type_value is not None:
1244
+ if hasattr(self.hf_text_config,
1245
+ "model_type") and (self.hf_text_config.model_type
1246
+ == "zamba2"):
1247
+ if attn_block_type:
1248
+ return sum(t == "hybrid"
1249
+ for t in layers_block_type_value[start:end])
1250
+ else:
1251
+ return self.get_num_layers(parallel_config)
1252
+ return sum(t == block_type.value
1253
+ for t in layers_block_type_value[start:end])
1254
+
1255
+ # Hybrid model Minimax
1256
+ attn_type_list = getattr(self.hf_config, "attn_type_list", None)
1257
+ if attn_type_list:
1258
+ return sum(t == 1 for t in attn_type_list[start:end])
1259
+
1260
+ if layers_block_type_value is None and attn_type_list is None:
1261
+ raise ValueError(
1262
+ "The model is an hybrid without a"
1263
+ "layers_block_type or an attn_type_list in the hf_config,"
1264
+ "cannot determine the num of "
1265
+ f"{block_type.value} layers")
1266
+
1267
+ return sum(t == 1 for t in attn_type_list[start:end])
1268
+
1269
+ def get_multimodal_config(self) -> "MultiModalConfig":
1270
+ """
1271
+ Get the multimodal configuration of the model.
1272
+
1273
+ Raises:
1274
+ ValueError: If the model is not multimodal.
1275
+ """
1276
+ if self.multimodal_config is None:
1277
+ raise ValueError("The model is not multimodal.")
1278
+
1279
+ return self.multimodal_config
1280
+
1281
+ def try_get_generation_config(self) -> dict[str, Any]:
1282
+ if self.generation_config in ("auto", "vllm"):
1283
+ config = try_get_generation_config(
1284
+ self.hf_config_path or self.model,
1285
+ trust_remote_code=self.trust_remote_code,
1286
+ revision=self.revision,
1287
+ )
1288
+ else:
1289
+ config = try_get_generation_config(
1290
+ self.generation_config,
1291
+ trust_remote_code=self.trust_remote_code,
1292
+ )
1293
+
1294
+ if config is None:
1295
+ return {}
1296
+
1297
+ return config.to_diff_dict()
1298
+
1299
+ def get_diff_sampling_param(self) -> dict[str, Any]:
1300
+ """
1301
+ This method returns a dictionary containing the parameters
1302
+ that differ from the default sampling parameters. If
1303
+ `generation_config` is `"vllm"`, an empty dictionary is returned.
1304
+
1305
+ Returns:
1306
+ dict[str, Any]: A dictionary with the differing sampling
1307
+ parameters, if `generation_config` is `"vllm"` an empty dictionary.
1308
+ """
1309
+ if self.generation_config == "vllm":
1310
+ config = {}
1311
+ else:
1312
+ config = self.try_get_generation_config()
1313
+
1314
+ # Overriding with given generation config
1315
+ config.update(self.override_generation_config)
1316
+
1317
+ available_params = [
1318
+ "repetition_penalty",
1319
+ "temperature",
1320
+ "top_k",
1321
+ "top_p",
1322
+ "min_p",
1323
+ "max_new_tokens",
1324
+ ]
1325
+ if any(p in config for p in available_params):
1326
+ diff_sampling_param = {
1327
+ p: config.get(p)
1328
+ for p in available_params if config.get(p) is not None
1329
+ }
1330
+ # Huggingface definition of max_new_tokens is equivalent
1331
+ # to vLLM's max_tokens
1332
+ if "max_new_tokens" in diff_sampling_param:
1333
+ diff_sampling_param["max_tokens"] = diff_sampling_param.pop(
1334
+ "max_new_tokens")
1335
+ else:
1336
+ diff_sampling_param = {}
1337
+
1338
+ if diff_sampling_param:
1339
+ logger.warning_once(
1340
+ "Default sampling parameters have been overridden by the "
1341
+ "model's Hugging Face generation config recommended from the "
1342
+ "model creator. If this is not intended, please relaunch "
1343
+ "vLLM instance with `--generation-config vllm`.")
1344
+ return diff_sampling_param
1345
+
1346
+ @property
1347
+ def is_encoder_decoder(self) -> bool:
1348
+ """Extract the HF encoder/decoder model flag."""
1349
+ return is_encoder_decoder(self.hf_config)
1350
+
1351
+ @property
1352
+ def uses_mrope(self) -> bool:
1353
+ return uses_mrope(self.hf_config)
1354
+
1355
+ @property
1356
+ def is_multimodal_model(self) -> bool:
1357
+ return self.multimodal_config is not None
1358
+
1359
+ @property
1360
+ def is_cross_encoder(self) -> bool:
1361
+ return self.registry.is_cross_encoder_model(self.architectures)
1362
+
1363
+ @property
1364
+ def use_mla(self) -> bool:
1365
+ return self.is_deepseek_mla and not envs.VLLM_MLA_DISABLE
1366
+
1367
+ @property
1368
+ def supported_runner_types(self) -> set[RunnerType]:
1369
+ return {_TASK_RUNNER[task] for task in self.supported_tasks}
1370
+
1371
+ @property
1372
+ def runner_type(self) -> RunnerType:
1373
+ return _TASK_RUNNER[cast(_ResolvedTask, self.task)]
1374
+
1375
+ @property
1376
+ def is_v1_compatible(self) -> bool:
1377
+ architectures = getattr(self.hf_config, "architectures", [])
1378
+ return ModelRegistry.is_v1_compatible(architectures)
1379
+
1380
+ @property
1381
+ def is_matryoshka(self) -> bool:
1382
+ return (hasattr(self.hf_config, "matryoshka_dimensions")
1383
+ or getattr(self.hf_config, "is_matryoshka", False))
1384
+
1385
+ @property
1386
+ def matryoshka_dimensions(self):
1387
+ return getattr(self.hf_config, "matryoshka_dimensions", None)
1388
+
1389
+
1390
+ BlockSize = Literal[1, 8, 16, 32, 64, 128]
1391
+ CacheDType = Literal["auto", "fp8", "fp8_e4m3", "fp8_e5m2"]
1392
+ PrefixCachingHashAlgo = Literal["builtin", "sha256"]
1393
+
1394
+
1395
+ @config
1396
+ @dataclass
1397
+ class CacheConfig:
1398
+ """Configuration for the KV cache."""
1399
+
1400
+ block_size: BlockSize = None # type: ignore
1401
+ """Size of a contiguous cache block in number of tokens. This is ignored on
1402
+ neuron devices and set to `--max-model-len`. On CUDA devices, only block
1403
+ sizes up to 32 are supported. On HPU devices, block size defaults to 128.
1404
+
1405
+ This config has no static default. If left unspecified by the user, it will
1406
+ be set in `Platform.check_and_update_configs()` based on the current
1407
+ platform."""
1408
+ gpu_memory_utilization: float = 0.9
1409
+ """The fraction of GPU memory to be used for the model executor, which can
1410
+ range from 0 to 1. For example, a value of 0.5 would imply 50% GPU memory
1411
+ utilization. If unspecified, will use the default value of 0.9. This is a
1412
+ per-instance limit, and only applies to the current vLLM instance. It does
1413
+ not matter if you have another vLLM instance running on the same GPU. For
1414
+ example, if you have two vLLM instances running on the same GPU, you can
1415
+ set the GPU memory utilization to 0.5 for each instance."""
1416
+ swap_space: float = 4
1417
+ """Size of the CPU swap space per GPU (in GiB)."""
1418
+ cache_dtype: CacheDType = "auto"
1419
+ """Data type for kv cache storage. If "auto", will use model data type.
1420
+ CUDA 11.8+ supports fp8 (=fp8_e4m3) and fp8_e5m2. ROCm (AMD GPU) supports
1421
+ fp8 (=fp8_e4m3)."""
1422
+ is_attention_free: bool = False
1423
+ """Whether the model is attention-free. This is primarily set in
1424
+ `ModelConfig` and that value should be manually duplicated here."""
1425
+ num_gpu_blocks_override: Optional[int] = None
1426
+ """Number of GPU blocks to use. This overrides the profiled `num_gpu_blocks`
1427
+ if specified. Does nothing if `None`. Used for testing preemption."""
1428
+ sliding_window: Optional[int] = None
1429
+ """Sliding window size for the KV cache. This is primarily set in
1430
+ `ModelConfig` and that value should be manually duplicated here."""
1431
+ enable_prefix_caching: Optional[bool] = None
1432
+ """Whether to enable prefix caching. Disabled by default for V0. Enabled by
1433
+ default for V1."""
1434
+ prefix_caching_hash_algo: PrefixCachingHashAlgo = "builtin"
1435
+ """Set the hash algorithm for prefix caching:\n
1436
+ - "builtin" is Python's built-in hash.\n
1437
+ - "sha256" is collision resistant but with certain overheads."""
1438
+ cpu_offload_gb: float = 0
1439
+ """The space in GiB to offload to CPU, per GPU. Default is 0, which means
1440
+ no offloading. Intuitively, this argument can be seen as a virtual way to
1441
+ increase the GPU memory size. For example, if you have one 24 GB GPU and
1442
+ set this to 10, virtually you can think of it as a 34 GB GPU. Then you can
1443
+ load a 13B model with BF16 weight, which requires at least 26GB GPU memory.
1444
+ Note that this requires fast CPU-GPU interconnect, as part of the model is
1445
+ loaded from CPU memory to GPU memory on the fly in each model forward pass.
1446
+ """
1447
+ calculate_kv_scales: bool = False
1448
+ """This enables dynamic calculation of `k_scale` and `v_scale` when
1449
+ kv_cache_dtype is fp8. If `False`, the scales will be loaded from the model
1450
+ checkpoint if available. Otherwise, the scales will default to 1.0."""
1451
+
1452
+ # Will be set after profiling.
1453
+ num_gpu_blocks: Optional[int] = field(default=None, init=False)
1454
+ """The number of blocks to allocate for GPU memory."""
1455
+ num_cpu_blocks: Optional[int] = field(default=None, init=False)
1456
+ """The number of blocks to allocate for CPU memory."""
1457
+
1458
+ def compute_hash(self) -> str:
1459
+ """
1460
+ WARNING: Whenever a new field is added to this config,
1461
+ ensure that it is included in the factors list if
1462
+ it affects the computation graph.
1463
+
1464
+ Provide a hash that uniquely identifies all the configs
1465
+ that affect the structure of the computation
1466
+ graph from input ids/embeddings to the final hidden states,
1467
+ excluding anything before input ids/embeddings and after
1468
+ the final hidden states.
1469
+ """
1470
+ factors: list[Any] = []
1471
+ factors.append(self.cache_dtype)
1472
+ # `cpu_offload_gb` does not use `torch.compile` yet.
1473
+ hash_str = hashlib.md5(str(factors).encode(),
1474
+ usedforsecurity=False).hexdigest()
1475
+ return hash_str
1476
+
1477
+ def __post_init__(self) -> None:
1478
+ self.swap_space_bytes = self.swap_space * GiB_bytes
1479
+
1480
+ self._verify_args()
1481
+ self._verify_cache_dtype()
1482
+ self._verify_prefix_caching()
1483
+
1484
+ def metrics_info(self):
1485
+ # convert cache_config to dict(key: str, value: str) for prometheus
1486
+ # metrics info
1487
+ return {key: str(value) for key, value in self.__dict__.items()}
1488
+
1489
+ def _verify_args(self) -> None:
1490
+ if self.cpu_offload_gb < 0:
1491
+ raise ValueError("CPU offload space must be non-negative"
1492
+ f", but got {self.cpu_offload_gb}")
1493
+
1494
+ if self.gpu_memory_utilization > 1.0:
1495
+ raise ValueError(
1496
+ "GPU memory utilization must be less than 1.0. Got "
1497
+ f"{self.gpu_memory_utilization}.")
1498
+
1499
+ def _verify_cache_dtype(self) -> None:
1500
+ if self.cache_dtype == "auto":
1501
+ pass
1502
+ elif self.cache_dtype in get_args(CacheDType):
1503
+ logger.info(
1504
+ "Using fp8 data type to store kv cache. It reduces the GPU "
1505
+ "memory footprint and boosts the performance. "
1506
+ "Meanwhile, it may cause accuracy drop without a proper "
1507
+ "scaling factor")
1508
+ else:
1509
+ raise ValueError(f"Unknown kv cache dtype: {self.cache_dtype}")
1510
+
1511
+ def _verify_prefix_caching(self) -> None:
1512
+ if not self.enable_prefix_caching:
1513
+ return
1514
+
1515
+ if self.sliding_window is not None and not envs.VLLM_USE_V1:
1516
+ raise NotImplementedError(
1517
+ "Prefix caching is not supported with sliding window. "
1518
+ "Run with --disable-sliding-window to use prefix caching.")
1519
+
1520
+ if (self.enable_prefix_caching and self.prefix_caching_hash_algo
1521
+ not in get_args(PrefixCachingHashAlgo)):
1522
+ raise ValueError(
1523
+ "Unknown prefix caching hash algorithm: "
1524
+ f"{self.prefix_caching_hash_algo}. Must be one of "
1525
+ f"{get_args(PrefixCachingHashAlgo)}.")
1526
+
1527
+ def verify_with_parallel_config(
1528
+ self,
1529
+ parallel_config: "ParallelConfig",
1530
+ ) -> None:
1531
+ total_cpu_memory = get_cpu_memory()
1532
+ # FIXME(woosuk): Here, it is assumed that the GPUs in a tensor parallel
1533
+ # group are in the same node. However, the GPUs may span multiple nodes.
1534
+ num_gpus_per_node = parallel_config.tensor_parallel_size
1535
+ cpu_memory_usage = self.swap_space_bytes * num_gpus_per_node
1536
+
1537
+ msg = (f"{cpu_memory_usage / GiB_bytes:.2f} GiB out of the "
1538
+ f"{total_cpu_memory / GiB_bytes:.2f} GiB total CPU memory "
1539
+ "is allocated for the swap space.")
1540
+ if cpu_memory_usage > 0.7 * total_cpu_memory:
1541
+ raise ValueError("Too large swap space. " + msg)
1542
+ elif cpu_memory_usage > 0.4 * total_cpu_memory:
1543
+ logger.warning("Possibly too large swap space. %s", msg)
1544
+
1545
+
1546
+ @config
1547
+ @dataclass
1548
+ class TokenizerPoolConfig:
1549
+ """This config is deprecated and will be removed in a future release.
1550
+
1551
+ Passing these parameters will have no effect. Please remove them from your
1552
+ configurations.
1553
+ """
1554
+
1555
+ pool_size: int = 0
1556
+ """This parameter is deprecated and will be removed in a future release.
1557
+ Passing this parameter will have no effect. Please remove it from your
1558
+ configurations."""
1559
+ pool_type: str = "ray"
1560
+ """This parameter is deprecated and will be removed in a future release.
1561
+ Passing this parameter will have no effect. Please remove it from your
1562
+ configurations."""
1563
+ extra_config: dict = field(default_factory=dict)
1564
+ """This parameter is deprecated and will be removed in a future release.
1565
+ Passing this parameter will have no effect. Please remove it from your
1566
+ configurations."""
1567
+
1568
+ def __post_init__(self) -> None:
1569
+ logger.warning_once(
1570
+ "TokenizerPoolConfig is deprecated and will be removed in a "
1571
+ "future release. Passing this parameter will have no effect. "
1572
+ "Please remove it from your configurations.")
1573
+
1574
+
1575
+ class LoadFormat(str, enum.Enum):
1576
+ AUTO = "auto"
1577
+ PT = "pt"
1578
+ SAFETENSORS = "safetensors"
1579
+ NPCACHE = "npcache"
1580
+ DUMMY = "dummy"
1581
+ TENSORIZER = "tensorizer"
1582
+ SHARDED_STATE = "sharded_state"
1583
+ GGUF = "gguf"
1584
+ BITSANDBYTES = "bitsandbytes"
1585
+ MISTRAL = "mistral"
1586
+ RUNAI_STREAMER = "runai_streamer"
1587
+ RUNAI_STREAMER_SHARDED = "runai_streamer_sharded"
1588
+ FASTSAFETENSORS = "fastsafetensors"
1589
+
1590
+
1591
+ @config
1592
+ @dataclass
1593
+ class LoadConfig:
1594
+ """Configuration for loading the model weights."""
1595
+
1596
+ load_format: Union[str, LoadFormat,
1597
+ "BaseModelLoader"] = LoadFormat.AUTO.value
1598
+ """The format of the model weights to load:\n
1599
+ - "auto" will try to load the weights in the safetensors format and fall
1600
+ back to the pytorch bin format if safetensors format is not available.\n
1601
+ - "pt" will load the weights in the pytorch bin format.\n
1602
+ - "safetensors" will load the weights in the safetensors format.\n
1603
+ - "npcache" will load the weights in pytorch format and store a numpy cache
1604
+ to speed up the loading.\n
1605
+ - "dummy" will initialize the weights with random values, which is mainly
1606
+ for profiling.\n
1607
+ - "tensorizer" will use CoreWeave's tensorizer library for fast weight
1608
+ loading. See the Tensorize vLLM Model script in the Examples section for
1609
+ more information.\n
1610
+ - "runai_streamer" will load the Safetensors weights using Run:ai Model
1611
+ Streamer.\n
1612
+ - "bitsandbytes" will load the weights using bitsandbytes quantization.\n
1613
+ - "sharded_state" will load weights from pre-sharded checkpoint files,
1614
+ supporting efficient loading of tensor-parallel models.\n
1615
+ - "gguf" will load weights from GGUF format files (details specified in
1616
+ https://github.com/ggml-org/ggml/blob/master/docs/gguf.md).\n
1617
+ - "mistral" will load weights from consolidated safetensors files used by
1618
+ Mistral models."""
1619
+ download_dir: Optional[str] = None
1620
+ """Directory to download and load the weights, default to the default
1621
+ cache directory of Hugging Face."""
1622
+ model_loader_extra_config: dict = field(default_factory=dict)
1623
+ """Extra config for model loader. This will be passed to the model loader
1624
+ corresponding to the chosen load_format."""
1625
+ ignore_patterns: Optional[Union[list[str], str]] = None
1626
+ """The list of patterns to ignore when loading the model. Default to
1627
+ "original/**/*" to avoid repeated loading of llama's checkpoints."""
1628
+ use_tqdm_on_load: bool = True
1629
+ """Whether to enable tqdm for showing progress bar when loading model
1630
+ weights."""
1631
+ pt_load_map_location: Union[str, dict[str, str]] = "cpu"
1632
+ """
1633
+ pt_load_map_location: the map location for loading pytorch checkpoint, to
1634
+ support loading checkpoints can only be loaded on certain devices like
1635
+ "cuda", this is equivalent to {"": "cuda"}. Another supported format is
1636
+ mapping from different devices like from GPU 1 to GPU 0:
1637
+ {"cuda:1": "cuda:0"}. Note that when passed from command line, the strings
1638
+ in dictionary needs to be double quoted for json parsing. For more details,
1639
+ see original doc for `map_location` in https://pytorch.org/docs/stable/generated/torch.load.html
1640
+ """
1641
+
1642
+ def compute_hash(self) -> str:
1643
+ """
1644
+ WARNING: Whenever a new field is added to this config,
1645
+ ensure that it is included in the factors list if
1646
+ it affects the computation graph.
1647
+
1648
+ Provide a hash that uniquely identifies all the configs
1649
+ that affect the structure of the computation
1650
+ graph from input ids/embeddings to the final hidden states,
1651
+ excluding anything before input ids/embeddings and after
1652
+ the final hidden states.
1653
+ """
1654
+ # no factors to consider.
1655
+ # this config will not affect the computation graph.
1656
+ factors: list[Any] = []
1657
+ hash_str = hashlib.md5(str(factors).encode(),
1658
+ usedforsecurity=False).hexdigest()
1659
+ return hash_str
1660
+
1661
+ def __post_init__(self):
1662
+ if isinstance(self.load_format, str):
1663
+ load_format = self.load_format.lower()
1664
+ self.load_format = LoadFormat(load_format)
1665
+
1666
+ if self.ignore_patterns is not None and len(self.ignore_patterns) > 0:
1667
+ logger.info(
1668
+ "Ignoring the following patterns when downloading weights: %s",
1669
+ self.ignore_patterns)
1670
+ else:
1671
+ self.ignore_patterns = ["original/**/*"]
1672
+
1673
+
1674
+ DistributedExecutorBackend = Literal["ray", "mp", "uni", "external_launcher"]
1675
+
1676
+
1677
+ @config
1678
+ @dataclass
1679
+ class ParallelConfig:
1680
+ """Configuration for the distributed execution."""
1681
+
1682
+ pipeline_parallel_size: int = 1
1683
+ """Number of pipeline parallel groups."""
1684
+ tensor_parallel_size: int = 1
1685
+ """Number of tensor parallel groups."""
1686
+ data_parallel_size: int = 1
1687
+ """Number of data parallel groups. MoE layers will be sharded according to
1688
+ the product of the tensor parallel size and data parallel size."""
1689
+ data_parallel_size_local: int = 1
1690
+ """Number of local data parallel groups."""
1691
+ data_parallel_rank: int = 0
1692
+ """Rank of the data parallel group."""
1693
+ data_parallel_rank_local: Optional[int] = None
1694
+ """Local rank of the data parallel group,
1695
+ set only in SPMD mode."""
1696
+ data_parallel_master_ip: str = "127.0.0.1"
1697
+ """IP of the data parallel master."""
1698
+ data_parallel_rpc_port: int = 29550
1699
+ """Port for data parallel messaging."""
1700
+ data_parallel_master_port: int = 29500
1701
+ """Port of the data parallel master."""
1702
+ enable_expert_parallel: bool = False
1703
+ """Use expert parallelism instead of tensor parallelism for MoE layers."""
1704
+ max_parallel_loading_workers: Optional[int] = None
1705
+ """Maximum number of parallel loading workers when loading model
1706
+ sequentially in multiple batches. To avoid RAM OOM when using tensor
1707
+ parallel and large models."""
1708
+
1709
+ disable_custom_all_reduce: bool = False
1710
+ """Disable the custom all-reduce kernel and fall back to NCCL."""
1711
+
1712
+ tokenizer_pool_config: Optional[TokenizerPoolConfig] = None
1713
+ """This parameter is deprecated and will be removed in a future release.
1714
+ Please remove it from your configs"""
1715
+
1716
+ ray_workers_use_nsight: bool = False
1717
+ """Whether to profile Ray workers with nsight, see https://docs.ray.io/en/latest/ray-observability/user-guides/profiling.html#profiling-nsight-profiler."""
1718
+
1719
+ placement_group: Optional["PlacementGroup"] = None
1720
+ """ray distributed model workers placement group."""
1721
+
1722
+ distributed_executor_backend: Optional[Union[DistributedExecutorBackend,
1723
+ type["ExecutorBase"]]] = None
1724
+ """Backend to use for distributed model
1725
+ workers, either "ray" or "mp" (multiprocessing). If the product
1726
+ of pipeline_parallel_size and tensor_parallel_size is less than
1727
+ or equal to the number of GPUs available, "mp" will be used to
1728
+ keep processing on a single host. Otherwise, this will default
1729
+ to "ray" if Ray is installed and fail otherwise. Note that tpu
1730
+ and hpu only support Ray for distributed inference."""
1731
+
1732
+ worker_cls: str = "auto"
1733
+ """The full name of the worker class to use. If "auto", the worker class
1734
+ will be determined based on the platform."""
1735
+ sd_worker_cls: str = "auto"
1736
+ """The full name of the worker class to use for speculative decofing.
1737
+ If "auto", the worker class will be determined based on the platform."""
1738
+ worker_extension_cls: str = ""
1739
+ """The full name of the worker extension class to use. The worker extension
1740
+ class is dynamically inherited by the worker class. This is used to inject
1741
+ new attributes and methods to the worker class for use in collective_rpc
1742
+ calls."""
1743
+
1744
+ world_size: int = field(init=False)
1745
+ """world_size is TPxPP, it affects the number of workers we create."""
1746
+
1747
+ rank: int = 0
1748
+ """Global rank in distributed setup."""
1749
+
1750
+ @property
1751
+ def world_size_across_dp(self) -> int:
1752
+ """world_size_across_dp is TPxPPxDP, it is the size of the world
1753
+ including data parallelism."""
1754
+ return self.world_size * self.data_parallel_size
1755
+
1756
+ def get_next_dp_init_port(self) -> int:
1757
+ """
1758
+ We might need to initialize process groups in multiple
1759
+ processes that is related to data parallelism,
1760
+ e.g. both in the worker and in the engine, which
1761
+ can live in different processes. To avoid port conflicts, we
1762
+ increment the port number each time we need to initialize a
1763
+ new process group related to data parallelism.
1764
+ """
1765
+ answer = self.data_parallel_master_port
1766
+ self.data_parallel_master_port += 1
1767
+ return answer
1768
+
1769
+ def stateless_init_dp_group(self) -> "ProcessGroup":
1770
+ from vllm.distributed.utils import (
1771
+ stateless_init_torch_distributed_process_group)
1772
+
1773
+ # use gloo since the engine process might not have cuda device
1774
+ dp_group = stateless_init_torch_distributed_process_group(
1775
+ self.data_parallel_master_ip,
1776
+ self.get_next_dp_init_port(),
1777
+ self.data_parallel_rank,
1778
+ self.data_parallel_size,
1779
+ backend="gloo")
1780
+
1781
+ return dp_group
1782
+
1783
+ @staticmethod
1784
+ def has_unfinished_dp(dp_group: "ProcessGroup",
1785
+ has_unfinished: bool) -> bool:
1786
+ tensor = torch.tensor([has_unfinished],
1787
+ dtype=torch.int32,
1788
+ device="cpu")
1789
+ # dp rank 0: has_unfinished_seqs=True
1790
+ # dp rank 1: has_unfinished_seqs=False
1791
+ # aggregated: has_unfinished_seqs=True
1792
+ # so this is an OR operation, i.e. MAX in integers
1793
+ torch.distributed.all_reduce(tensor, op=ReduceOp.MAX, group=dp_group)
1794
+ aggregated_has_unfinished = bool(tensor.item())
1795
+ return aggregated_has_unfinished
1796
+
1797
+ def compute_hash(self):
1798
+ """
1799
+ Provide a hash that uniquely identifies all the configs
1800
+ that affect the structure of the computation
1801
+ graph from input ids/embeddings to the final hidden states,
1802
+ excluding anything before input ids/embeddings and after
1803
+ the final hidden states.
1804
+ """
1805
+ factors: list[Any] = []
1806
+ factors.append(self.pipeline_parallel_size)
1807
+ factors.append(self.tensor_parallel_size)
1808
+ factors.append(self.enable_expert_parallel)
1809
+ return hashlib.sha256(str(factors).encode()).hexdigest()
1810
+
1811
+ def __post_init__(self) -> None:
1812
+ self.world_size = self.pipeline_parallel_size * \
1813
+ self.tensor_parallel_size
1814
+
1815
+ if self.data_parallel_size_local > self.data_parallel_size:
1816
+ raise ValueError(
1817
+ f"data_parallel_size_local ({self.data_parallel_size_local}) "
1818
+ f"must be <= data_parallel_size ({self.data_parallel_size})")
1819
+
1820
+ if self.data_parallel_size > 1 or self.data_parallel_size_local == 0:
1821
+ # Data parallel was specified in the engine args.
1822
+ self.data_parallel_master_port = get_open_port()
1823
+ else:
1824
+ # Otherwise fall back to env vars (e.g. for offline SPMD case).
1825
+ self.data_parallel_size = envs.VLLM_DP_SIZE
1826
+ self.data_parallel_rank = envs.VLLM_DP_RANK
1827
+ self.data_parallel_rank_local = envs.VLLM_DP_RANK_LOCAL
1828
+ self.data_parallel_master_ip = envs.VLLM_DP_MASTER_IP
1829
+ self.data_parallel_master_port = envs.VLLM_DP_MASTER_PORT
1830
+
1831
+ if self.distributed_executor_backend == "external_launcher":
1832
+ import os
1833
+ os.environ["VLLM_ENABLE_V1_MULTIPROCESSING"] = "0"
1834
+ logger.info("Disabling V1 multiprocessing for external launcher.")
1835
+
1836
+ ray_only_devices: list[str] = []
1837
+ from vllm.platforms import current_platform
1838
+ if (current_platform.device_type in ray_only_devices
1839
+ and self.world_size > 1):
1840
+ if self.distributed_executor_backend is None:
1841
+ self.distributed_executor_backend = "ray"
1842
+ if self.distributed_executor_backend != "ray":
1843
+ raise ValueError(
1844
+ f"{current_platform.device_type.upper()} backend only "
1845
+ "supports Ray for distributed inference.")
1846
+
1847
+ if self.distributed_executor_backend is None and self.world_size > 1:
1848
+ # We use multiprocessing by default if world_size fits on the
1849
+ # current node and we aren't in a ray placement group.
1850
+
1851
+ from vllm.executor import ray_utils
1852
+ backend: DistributedExecutorBackend = "mp"
1853
+ ray_found = ray_utils.ray_is_available()
1854
+ if current_platform.is_neuron():
1855
+ # neuron uses single process to control multiple devices
1856
+ backend = "uni"
1857
+ elif (current_platform.is_cuda()
1858
+ and cuda_device_count_stateless() < self.world_size):
1859
+ if not ray_found:
1860
+ raise ValueError("Unable to load Ray which is "
1861
+ "required for multi-node inference, "
1862
+ "please install Ray with `pip install "
1863
+ "ray`.") from ray_utils.ray_import_err
1864
+ backend = "ray"
1865
+ elif ray_found:
1866
+ if self.placement_group:
1867
+ backend = "ray"
1868
+ else:
1869
+ from ray import is_initialized as ray_is_initialized
1870
+ if ray_is_initialized():
1871
+ from ray.util import get_current_placement_group
1872
+ if get_current_placement_group():
1873
+ backend = "ray"
1874
+ self.distributed_executor_backend = backend
1875
+ logger.info("Defaulting to use %s for distributed inference",
1876
+ backend)
1877
+
1878
+ if self.distributed_executor_backend is None and self.world_size == 1:
1879
+ self.distributed_executor_backend = "uni"
1880
+
1881
+ self._verify_args()
1882
+
1883
+ @property
1884
+ def use_ray(self) -> bool:
1885
+ return self.distributed_executor_backend == "ray" or (
1886
+ isinstance(self.distributed_executor_backend, type)
1887
+ and self.distributed_executor_backend.uses_ray)
1888
+
1889
+ def _verify_args(self) -> None:
1890
+ # Lazy import to avoid circular import
1891
+ from vllm.executor.executor_base import ExecutorBase
1892
+ from vllm.platforms import current_platform
1893
+ if self.distributed_executor_backend not in (
1894
+ "ray", "mp", "uni",
1895
+ "external_launcher", None) and not (isinstance(
1896
+ self.distributed_executor_backend, type) and issubclass(
1897
+ self.distributed_executor_backend, ExecutorBase)):
1898
+ raise ValueError(
1899
+ "Unrecognized distributed executor backend "
1900
+ f"{self.distributed_executor_backend}. Supported "
1901
+ "values are 'ray', 'mp' 'uni', 'external_launcher' or"
1902
+ " custom ExecutorBase subclass.")
1903
+ if self.use_ray:
1904
+ from vllm.executor import ray_utils
1905
+ ray_utils.assert_ray_available()
1906
+
1907
+ if not current_platform.use_custom_allreduce():
1908
+ self.disable_custom_all_reduce = True
1909
+ logger.info(
1910
+ "Disabled the custom all-reduce kernel because it is not "
1911
+ "supported on current platform.")
1912
+ if self.ray_workers_use_nsight and not self.use_ray:
1913
+ raise ValueError("Unable to use nsight profiling unless workers "
1914
+ "run with Ray.")
1915
+
1916
+ assert isinstance(self.worker_extension_cls, str), (
1917
+ "worker_extension_cls must be a string (qualified class name).")
1918
+
1919
+
1920
+ PreemptionMode = Literal["swap", "recompute"]
1921
+ SchedulerPolicy = Literal["fcfs", "priority"]
1922
+
1923
+
1924
+ @config
1925
+ @dataclass
1926
+ class SchedulerConfig:
1927
+ """Scheduler configuration."""
1928
+
1929
+ runner_type: RunnerType = "generate"
1930
+ """The runner type to launch for the model."""
1931
+
1932
+ max_num_batched_tokens: int = None # type: ignore
1933
+ """Maximum number of tokens to be processed in a single iteration.
1934
+
1935
+ This config has no static default. If left unspecified by the user, it will
1936
+ be set in `EngineArgs.create_engine_config` based on the usage context."""
1937
+
1938
+ max_num_seqs: int = None # type: ignore
1939
+ """Maximum number of sequences to be processed in a single iteration.
1940
+
1941
+ This config has no static default. If left unspecified by the user, it will
1942
+ be set in `EngineArgs.create_engine_config` based on the usage context."""
1943
+
1944
+ max_model_len: int = None # type: ignore
1945
+ """Maximum length of a sequence (including prompt and generated text). This
1946
+ is primarily set in `ModelConfig` and that value should be manually
1947
+ duplicated here."""
1948
+
1949
+ max_num_partial_prefills: int = 1
1950
+ """For chunked prefill, the maximum number of sequences that can be
1951
+ partially prefilled concurrently."""
1952
+
1953
+ max_long_partial_prefills: int = 1
1954
+ """For chunked prefill, the maximum number of prompts longer than
1955
+ long_prefill_token_threshold that will be prefilled concurrently. Setting
1956
+ this less than max_num_partial_prefills will allow shorter prompts to jump
1957
+ the queue in front of longer prompts in some cases, improving latency."""
1958
+
1959
+ long_prefill_token_threshold: int = 0
1960
+ """For chunked prefill, a request is considered long if the prompt is
1961
+ longer than this number of tokens."""
1962
+
1963
+ num_lookahead_slots: int = 0
1964
+ """The number of slots to allocate per sequence per
1965
+ step, beyond the known token ids. This is used in speculative
1966
+ decoding to store KV activations of tokens which may or may not be
1967
+ accepted.
1968
+
1969
+ NOTE: This will be replaced by speculative config in the future; it is
1970
+ present to enable correctness tests until then."""
1971
+
1972
+ cuda_graph_sizes: list[int] = field(default_factory=lambda: [512])
1973
+ """Cuda graph capture sizes, default is 512.
1974
+ 1. if one value is provided, then the capture list would follow the
1975
+ pattern: [1, 2, 4] + [i for i in range(8, cuda_graph_sizes + 1, 8)]
1976
+ 2. more than one value (e.g. 1 2 128) is provided, then the capture list
1977
+ will follow the provided list."""
1978
+
1979
+ delay_factor: float = 0.0
1980
+ """Apply a delay (of delay factor multiplied by previous
1981
+ prompt latency) before scheduling next prompt."""
1982
+
1983
+ enable_chunked_prefill: bool = None # type: ignore
1984
+ """If True, prefill requests can be chunked based
1985
+ on the remaining max_num_batched_tokens."""
1986
+
1987
+ is_multimodal_model: bool = False
1988
+ """True if the model is multimodal."""
1989
+
1990
+ # TODO (ywang96): Make this configurable.
1991
+ max_num_encoder_input_tokens: int = field(init=False)
1992
+ """Multimodal encoder compute budget, only used in V1.
1993
+
1994
+ NOTE: This is not currently configurable. It will be overridden by
1995
+ max_num_batched_tokens in case max multimodal embedding size is larger."""
1996
+
1997
+ # TODO (ywang96): Make this configurable.
1998
+ encoder_cache_size: int = field(init=False)
1999
+ """Multimodal encoder cache size, only used in V1.
2000
+
2001
+ NOTE: This is not currently configurable. It will be overridden by
2002
+ max_num_batched_tokens in case max multimodal embedding size is larger."""
2003
+
2004
+ preemption_mode: Optional[PreemptionMode] = None
2005
+ """Whether to perform preemption by swapping or
2006
+ recomputation. If not specified, we determine the mode as follows:
2007
+ We use recomputation by default since it incurs lower overhead than
2008
+ swapping. However, when the sequence group has multiple sequences
2009
+ (e.g., beam search), recomputation is not currently supported. In
2010
+ such a case, we use swapping instead."""
2011
+
2012
+ num_scheduler_steps: int = 1
2013
+ """Maximum number of forward steps per scheduler call."""
2014
+
2015
+ multi_step_stream_outputs: bool = True
2016
+ """If False, then multi-step will stream outputs at the end of all steps"""
2017
+
2018
+ send_delta_data: bool = False
2019
+ """Private API. If used, scheduler sends delta data to
2020
+ workers instead of an entire data. It should be enabled only
2021
+ when SPMD worker architecture is enabled. I.e.,
2022
+ VLLM_USE_RAY_SPMD_WORKER=1"""
2023
+
2024
+ policy: SchedulerPolicy = "fcfs"
2025
+ """The scheduling policy to use:\n
2026
+ - "fcfs" means first come first served, i.e. requests are handled in order
2027
+ of arrival.\n
2028
+ - "priority" means requests are handled based on given priority (lower
2029
+ value means earlier handling) and time of arrival deciding any ties)."""
2030
+
2031
+ chunked_prefill_enabled: bool = field(init=False)
2032
+ """True if chunked prefill is enabled."""
2033
+
2034
+ disable_chunked_mm_input: bool = False
2035
+ """If set to true and chunked prefill is enabled, we do not want to
2036
+ partially schedule a multimodal item. Only used in V1
2037
+ This ensures that if a request has a mixed prompt
2038
+ (like text tokens TTTT followed by image tokens IIIIIIIIII) where only
2039
+ some image tokens can be scheduled (like TTTTIIIII, leaving IIIII),
2040
+ it will be scheduled as TTTT in one step and IIIIIIIIII in the next."""
2041
+
2042
+ # scheduler class or path. "vllm.core.scheduler.Scheduler" (default)
2043
+ # or "mod.custom_class".
2044
+ scheduler_cls: Union[str, type[object]] = "vllm.core.scheduler.Scheduler"
2045
+ """The scheduler class to use. "vllm.core.scheduler.Scheduler" is the
2046
+ default scheduler. Can be a class directly or the path to a class of form
2047
+ "mod.custom_class"."""
2048
+
2049
+ def compute_hash(self) -> str:
2050
+ """
2051
+ WARNING: Whenever a new field is added to this config,
2052
+ ensure that it is included in the factors list if
2053
+ it affects the computation graph.
2054
+
2055
+ Provide a hash that uniquely identifies all the configs
2056
+ that affect the structure of the computation
2057
+ graph from input ids/embeddings to the final hidden states,
2058
+ excluding anything before input ids/embeddings and after
2059
+ the final hidden states.
2060
+ """
2061
+ # no factors to consider.
2062
+ # this config will not affect the computation graph.
2063
+ factors: list[Any] = []
2064
+ hash_str = hashlib.md5(str(factors).encode(),
2065
+ usedforsecurity=False).hexdigest()
2066
+ return hash_str
2067
+
2068
+ def __post_init__(self) -> None:
2069
+ if self.max_model_len is None:
2070
+ self.max_model_len = 8192
2071
+
2072
+ if self.max_num_seqs is None:
2073
+ self.max_num_seqs = 128
2074
+
2075
+ if self.max_num_batched_tokens is None:
2076
+ if self.enable_chunked_prefill:
2077
+ if self.num_scheduler_steps > 1:
2078
+ # Multi-step Chunked-Prefill doesn't allow prompt-chunking
2079
+ # for now. Have max_num_batched_tokens set to max_model_len
2080
+ # so we don't reject sequences on account of a short
2081
+ # max_num_batched_tokens.
2082
+ self.max_num_batched_tokens = max(
2083
+ self.max_model_len, DEFAULT_MAX_NUM_BATCHED_TOKENS)
2084
+ else:
2085
+ self.max_num_batched_tokens = (
2086
+ DEFAULT_MAX_NUM_BATCHED_TOKENS)
2087
+ else:
2088
+ # If max_model_len is too short, use
2089
+ # DEFAULT_MAX_NUM_BATCHED_TOKENS as the default value
2090
+ # for higher throughput.
2091
+ self.max_num_batched_tokens = max(
2092
+ self.max_model_len, DEFAULT_MAX_NUM_BATCHED_TOKENS)
2093
+
2094
+ if self.runner_type == "pooling":
2095
+ # Choose specific value for higher throughput
2096
+ self.max_num_batched_tokens = max(
2097
+ self.max_num_batched_tokens,
2098
+ POOLING_MODEL_MAX_NUM_BATCHED_TOKENS,
2099
+ )
2100
+ if self.is_multimodal_model:
2101
+ # The value needs to be at least the number of multimodal tokens
2102
+ self.max_num_batched_tokens = max(
2103
+ self.max_num_batched_tokens,
2104
+ MULTIMODAL_MODEL_MAX_NUM_BATCHED_TOKENS,
2105
+ )
2106
+
2107
+ # When using default settings,
2108
+ # Ensure max_num_batched_tokens does not exceed model limit.
2109
+ # Some models (e.g., Whisper) have embeddings tied to max length.
2110
+ self.max_num_batched_tokens = min(
2111
+ self.max_num_seqs * self.max_model_len,
2112
+ self.max_num_batched_tokens)
2113
+
2114
+ self.max_num_encoder_input_tokens = self.max_num_batched_tokens
2115
+ self.encoder_cache_size = self.max_num_batched_tokens
2116
+
2117
+ if self.enable_chunked_prefill:
2118
+ logger.info(
2119
+ "Chunked prefill is enabled with max_num_batched_tokens=%d.",
2120
+ self.max_num_batched_tokens)
2121
+
2122
+ self.chunked_prefill_enabled = self.enable_chunked_prefill
2123
+ if self.max_num_partial_prefills > 1:
2124
+ if self.long_prefill_token_threshold == 0:
2125
+ self.long_prefill_token_threshold = int(self.max_model_len *
2126
+ 0.04)
2127
+
2128
+ logger.info(
2129
+ "Concurrent partial prefills enabled with "
2130
+ "max_num_partial_prefills=%d, max_long_partial_prefills=%d, "
2131
+ "long_prefill_token_threshold=%d",
2132
+ self.max_num_partial_prefills, self.max_long_partial_prefills,
2133
+ self.long_prefill_token_threshold)
2134
+
2135
+ self._verify_args()
2136
+
2137
+ def _verify_args(self) -> None:
2138
+ if (self.max_num_batched_tokens < self.max_model_len
2139
+ and not self.chunked_prefill_enabled):
2140
+ raise ValueError(
2141
+ f"max_num_batched_tokens ({self.max_num_batched_tokens}) is "
2142
+ f"smaller than max_model_len ({self.max_model_len}). "
2143
+ "This effectively limits the maximum sequence length to "
2144
+ "max_num_batched_tokens and makes vLLM reject longer "
2145
+ "sequences. Please increase max_num_batched_tokens or "
2146
+ "decrease max_model_len.")
2147
+
2148
+ if self.max_num_batched_tokens < self.max_num_seqs:
2149
+ raise ValueError(
2150
+ f"max_num_batched_tokens ({self.max_num_batched_tokens}) must "
2151
+ "be greater than or equal to max_num_seqs "
2152
+ f"({self.max_num_seqs}).")
2153
+
2154
+ if self.max_num_batched_tokens > self.max_num_seqs * self.max_model_len:
2155
+ logger.warning(
2156
+ "max_num_batched_tokens (%d) exceeds max_num_seqs"
2157
+ "* max_model_len (%d). This may lead to unexpected behavior.",
2158
+ self.max_num_batched_tokens,
2159
+ self.max_num_seqs * self.max_model_len)
2160
+
2161
+ if self.num_lookahead_slots < 0:
2162
+ raise ValueError(
2163
+ "num_lookahead_slots "
2164
+ f"({self.num_lookahead_slots}) must be greater than or "
2165
+ "equal to 0.")
2166
+
2167
+ if self.num_scheduler_steps < 1:
2168
+ raise ValueError(
2169
+ "num_scheduler_steps "
2170
+ f"({self.num_scheduler_steps}) must be greater than or "
2171
+ "equal to 1.")
2172
+
2173
+ if self.max_num_partial_prefills < 1:
2174
+ raise ValueError(
2175
+ f"max_num_partial_prefills ({self.max_num_partial_prefills}) "
2176
+ "must be greater than or equal to 1.")
2177
+ elif self.max_num_partial_prefills > 1:
2178
+ if not self.chunked_prefill_enabled:
2179
+ raise ValueError("Chunked prefill must be enabled to set "
2180
+ "max_num_partial_prefills > 1.")
2181
+
2182
+ if self.long_prefill_token_threshold > self.max_model_len:
2183
+ raise ValueError(
2184
+ "long_prefill_token_threshold "
2185
+ f"({self.long_prefill_token_threshold}) cannot be greater "
2186
+ f"than the max_model_len ({self.max_model_len}).")
2187
+
2188
+ if (self.max_long_partial_prefills
2189
+ < 1) or (self.max_long_partial_prefills
2190
+ > self.max_num_partial_prefills):
2191
+ raise ValueError(
2192
+ f"max_long_partial_prefills ({self.max_long_partial_prefills}) "
2193
+ "must be greater than or equal to 1 and less than or equal to "
2194
+ f"max_num_partial_prefills ({self.max_num_partial_prefills}).")
2195
+
2196
+ @property
2197
+ def is_multi_step(self) -> bool:
2198
+ return self.num_scheduler_steps > 1
2199
+
2200
+
2201
+ Device = Literal["auto", "cuda", "neuron", "cpu", "tpu", "xpu", "hpu"]
2202
+
2203
+
2204
+ @config
2205
+ @dataclass
2206
+ class DeviceConfig:
2207
+ """Configuration for the device to use for vLLM execution."""
2208
+
2209
+ device: Union[Device, torch.device] = "auto"
2210
+ """Device type for vLLM execution.
2211
+ This parameter is deprecated and will be
2212
+ removed in a future release.
2213
+ It will now be set automatically based
2214
+ on the current platform."""
2215
+ device_type: str = field(init=False)
2216
+ """Device type from the current platform. This is set in
2217
+ `__post_init__`."""
2218
+
2219
+ def compute_hash(self) -> str:
2220
+ """
2221
+ WARNING: Whenever a new field is added to this config,
2222
+ ensure that it is included in the factors list if
2223
+ it affects the computation graph.
2224
+
2225
+ Provide a hash that uniquely identifies all the configs
2226
+ that affect the structure of the computation
2227
+ graph from input ids/embeddings to the final hidden states,
2228
+ excluding anything before input ids/embeddings and after
2229
+ the final hidden states.
2230
+ """
2231
+ # no factors to consider.
2232
+ # the device/platform information will be summarized
2233
+ # by torch/vllm automatically.
2234
+ factors: list[Any] = []
2235
+ hash_str = hashlib.md5(str(factors).encode(),
2236
+ usedforsecurity=False).hexdigest()
2237
+ return hash_str
2238
+
2239
+ def __post_init__(self):
2240
+ if self.device == "auto":
2241
+ # Automated device type detection
2242
+ from vllm.platforms import current_platform
2243
+ self.device_type = current_platform.device_type
2244
+ if not self.device_type:
2245
+ raise RuntimeError(
2246
+ "Failed to infer device type, please set "
2247
+ "the environment variable `VLLM_LOGGING_LEVEL=DEBUG` "
2248
+ "to turn on verbose logging to help debug the issue.")
2249
+ else:
2250
+ # Device type is assigned explicitly
2251
+ self.device_type = self.device
2252
+
2253
+ # Some device types require processing inputs on CPU
2254
+ if self.device_type in ["neuron"]:
2255
+ self.device = torch.device("cpu")
2256
+ elif self.device_type in ["tpu"]:
2257
+ self.device = None
2258
+ else:
2259
+ # Set device with device type
2260
+ self.device = torch.device(self.device_type)
2261
+
2262
+
2263
+ SpeculativeMethod = Literal["ngram", "eagle", "medusa", "mlp_speculator",
2264
+ "draft_model", "deepseek_mtp"]
2265
+ SpeculativeAcceptanceMethod = Literal["rejection_sampler",
2266
+ "typical_acceptance_sampler"]
2267
+
2268
+
2269
+ @config
2270
+ @dataclass
2271
+ class SpeculativeConfig:
2272
+ """Configuration for speculative decoding."""
2273
+
2274
+ # General speculative decoding control
2275
+ num_speculative_tokens: int = field(default=None,
2276
+ init=True) # type: ignore
2277
+ """The number of speculative tokens, if provided. It will default to the
2278
+ number in the draft model config if present, otherwise, it is required."""
2279
+ model: Optional[str] = None
2280
+ """The name of the draft model, eagle head, or additional weights, if
2281
+ provided."""
2282
+ method: Optional[SpeculativeMethod] = None
2283
+ """The name of the speculative method to use. If users provide and set the
2284
+ `model` param, the speculative method type will be detected automatically
2285
+ if possible, if `model` param is not provided, the method name must be
2286
+ provided.
2287
+
2288
+ If using `ngram` method, the related configuration `prompt_lookup_max` and
2289
+ `prompt_lookup_min` should be considered."""
2290
+ acceptance_method: SpeculativeAcceptanceMethod = "rejection_sampler"
2291
+ """The method to use for accepting draft tokens:\n
2292
+ - "rejection_sampler" maps to `RejectionSampler`.\n
2293
+ - "typical_acceptance_sampler" maps to `TypicalAcceptanceSampler`.
2294
+
2295
+ If using `typical_acceptance_sampler`, the related configuration
2296
+ `posterior_threshold` and `posterior_alpha` should be considered."""
2297
+ draft_tensor_parallel_size: Optional[int] = None
2298
+ """The degree of the tensor parallelism for the draft model. Can only be 1
2299
+ or the same as the target model's tensor parallel size."""
2300
+ disable_logprobs: bool = True
2301
+ """If set to True, token log probabilities are not returned during
2302
+ speculative decoding. If set to False, token log probabilities are returned
2303
+ according to the log probability settings in SamplingParams."""
2304
+
2305
+ # Draft model configuration
2306
+ quantization: Optional[QuantizationMethods] = None
2307
+ """Quantization method that was used to quantize the draft model weights.
2308
+ If `None`, we assume the model weights are not quantized. Note that it only
2309
+ takes effect when using the draft model-based speculative method."""
2310
+ max_model_len: Optional[int] = None
2311
+ """The maximum model length of the draft model. Used when testing the
2312
+ ability to skip speculation for some sequences."""
2313
+ revision: Optional[str] = None
2314
+ """The specific model version to use for the draft model. It can be a
2315
+ branch name, a tag name, or a commit id. If unspecified, will use the
2316
+ default version."""
2317
+ code_revision: Optional[str] = None
2318
+ """The specific revision to use for the draft model code on Hugging Face
2319
+ Hub. It can be a branch name, a tag name, or a commit id. If unspecified,
2320
+ will use the default version."""
2321
+
2322
+ # Advanced control
2323
+ disable_mqa_scorer: bool = False
2324
+ """Disable the MQA scorer and fall back to batch expansion for scoring
2325
+ proposals."""
2326
+ disable_by_batch_size: Optional[int] = None
2327
+ """Disable speculative decoding for new incoming requests when the number
2328
+ of enqueued requests is larger than this value, if provided."""
2329
+
2330
+ # Ngram proposer configuration
2331
+ prompt_lookup_max: Optional[int] = None
2332
+ """Maximum size of ngram token window when using Ngram proposer, required
2333
+ when method is set to ngram."""
2334
+ prompt_lookup_min: Optional[int] = None
2335
+ """Minimum size of ngram token window when using Ngram proposer, if
2336
+ provided. Defaults to 1."""
2337
+
2338
+ # Typical acceptance sampler configuration
2339
+ posterior_threshold: Optional[float] = None
2340
+ """A threshold value that sets a lower bound on the posterior probability
2341
+ of a token in the target model for it to be accepted. This threshold is
2342
+ used only when we use the `TypicalAcceptanceSampler` for token acceptance.
2343
+ """
2344
+ posterior_alpha: Optional[float] = None
2345
+ """Scaling factor for entropy-based threshold, applied when using
2346
+ `TypicalAcceptanceSampler`."""
2347
+
2348
+ speculative_token_tree: Optional[str] = None
2349
+ """Specifies the tree structure for speculative token generation.
2350
+ """
2351
+ # required configuration params passed from engine
2352
+ target_model_config: ModelConfig = field(default=None,
2353
+ init=True) # type: ignore
2354
+ """The configuration of the target model."""
2355
+ target_parallel_config: ParallelConfig = field(default=None,
2356
+ init=True) # type: ignore
2357
+ """The parallel configuration for the target model."""
2358
+ enable_chunked_prefill: bool = field(default=None,
2359
+ init=True) # type: ignore
2360
+ """Whether vLLM is configured to use chunked prefill or not. Used for
2361
+ raising an error since it's not yet compatible with speculative decode."""
2362
+ disable_log_stats: bool = field(default=None, init=True) # type: ignore
2363
+ """Whether to disable the periodic printing of stage times in speculative
2364
+ decoding."""
2365
+
2366
+ # params generated in the post-init stage
2367
+ draft_model_config: ModelConfig = field(default=None,
2368
+ init=True) # type: ignore
2369
+ """The configuration of the draft model initialized internal."""
2370
+ draft_parallel_config: ParallelConfig = field(default=None,
2371
+ init=True) # type: ignore
2372
+ """The parallel configuration for the draft model initialized internal."""
2373
+
2374
+ def compute_hash(self) -> str:
2375
+ """
2376
+ WARNING: Whenever a new field is added to this config,
2377
+ ensure that it is included in the factors list if
2378
+ it affects the computation graph.
2379
+
2380
+ Provide a hash that uniquely identifies all the configs
2381
+ that affect the structure of the computation
2382
+ graph from input ids/embeddings to the final hidden states,
2383
+ excluding anything before input ids/embeddings and after
2384
+ the final hidden states.
2385
+ """
2386
+ factors: list[Any] = []
2387
+ # Eagle3 affects the computation graph because it returns intermediate
2388
+ # hidden states in addition to the final hidden state.
2389
+ factors.append(self.method == "eagle3")
2390
+ hash_str = hashlib.md5(str(factors).encode(),
2391
+ usedforsecurity=False).hexdigest()
2392
+ return hash_str
2393
+
2394
+ @classmethod
2395
+ def from_dict(cls, dict_value: dict) -> "SpeculativeConfig":
2396
+ """Parse the CLI value for the speculative config."""
2397
+ return cls(**dict_value)
2398
+
2399
+ @staticmethod
2400
+ def hf_config_override(hf_config: PretrainedConfig) -> PretrainedConfig:
2401
+ if hf_config.model_type == "deepseek_v3":
2402
+ hf_config.model_type = "deepseek_mtp"
2403
+ if hf_config.model_type == "deepseek_mtp":
2404
+ n_predict = getattr(hf_config, "num_nextn_predict_layers", None)
2405
+ hf_config.update({
2406
+ "n_predict": n_predict,
2407
+ "architectures": ["DeepSeekMTPModel"]
2408
+ })
2409
+
2410
+ if hf_config.architectures[0] == "MiMoForCausalLM":
2411
+ hf_config.model_type = "mimo_mtp"
2412
+ n_predict = getattr(hf_config, "num_nextn_predict_layers", None)
2413
+ hf_config.update({
2414
+ "num_hidden_layers": 0,
2415
+ "n_predict": n_predict,
2416
+ "architectures": ["MiMoMTPModel"]
2417
+ })
2418
+ return hf_config
2419
+
2420
+ return hf_config
2421
+
2422
+ def __post_init__(self):
2423
+
2424
+ # Note: "method" is a new parameter that helps to extend the
2425
+ # configuration of non-model-based proposers, and the "model" parameter
2426
+ # will be used to set the draft model, eagle head, or additional weight
2427
+ # when needed. If users do not specify "method", the speculative method
2428
+ # will be detected automatically if possible. If the speculative method
2429
+ # can not be detected, it will be considered as the "draft_model" by
2430
+ # default.
2431
+
2432
+ if self.model is None and self.num_speculative_tokens is not None:
2433
+ # TODO(Shangming): Refactor mtp configuration logic when supporting
2434
+ # mtp acceleration for more models besides deepseek_v3
2435
+ if self.target_model_config and \
2436
+ (self.target_model_config.hf_text_config.model_type \
2437
+ == "deepseek_v3" or
2438
+ self.target_model_config.hf_text_config.model_type \
2439
+ == "mimo"):
2440
+ # use the draft model from the same model:
2441
+ self.model = self.target_model_config.model
2442
+ elif self.method in ("ngram", "[ngram]"):
2443
+ self.model = "ngram"
2444
+ else:
2445
+ raise ValueError("num_speculative_tokens was provided without "
2446
+ "speculative model.")
2447
+
2448
+ # Automatically configure the method for ngram when "model" is used
2449
+ # instead of "method"
2450
+ if self.method is None and (self.model is not None
2451
+ and self.model in ("ngram", "[ngram]")):
2452
+ self.method = "ngram"
2453
+
2454
+ if self.method in ("ngram", "[ngram]"):
2455
+ # Unified to "ngram" internally
2456
+ self.method = "ngram"
2457
+ # Set default values if not provided
2458
+ if (self.prompt_lookup_min is None
2459
+ and self.prompt_lookup_max is None):
2460
+ # TODO(woosuk): Tune these values. They are arbitrarily chosen.
2461
+ self.prompt_lookup_min = 5
2462
+ self.prompt_lookup_max = 5
2463
+ elif self.prompt_lookup_min is None:
2464
+ assert self.prompt_lookup_max is not None
2465
+ self.prompt_lookup_min = self.prompt_lookup_max
2466
+ elif self.prompt_lookup_max is None:
2467
+ assert self.prompt_lookup_min is not None
2468
+ self.prompt_lookup_max = self.prompt_lookup_min
2469
+
2470
+ # Validate values
2471
+ if self.prompt_lookup_min < 1:
2472
+ raise ValueError(
2473
+ f"prompt_lookup_min={self.prompt_lookup_min} must be > 0")
2474
+ if self.prompt_lookup_max < 1:
2475
+ raise ValueError(
2476
+ f"prompt_lookup_max={self.prompt_lookup_max} must be > 0")
2477
+ if self.prompt_lookup_min > self.prompt_lookup_max:
2478
+ raise ValueError(
2479
+ f"prompt_lookup_min={self.prompt_lookup_min} must "
2480
+ f"be <= prompt_lookup_max={self.prompt_lookup_max}")
2481
+
2482
+ # TODO: current we still need extract vocab_size from target model
2483
+ # config, in future, we may try refactor it out, and set
2484
+ # draft related config as None here.
2485
+ self.draft_model_config = self.target_model_config
2486
+ self.draft_parallel_config = self.target_parallel_config
2487
+ else:
2488
+ self.prompt_lookup_max = 0
2489
+ self.prompt_lookup_min = 0
2490
+
2491
+ if self.model is not None:
2492
+ self.draft_model_config = ModelConfig(
2493
+ model=self.model,
2494
+ task="draft",
2495
+ tokenizer=self.target_model_config.tokenizer,
2496
+ tokenizer_mode=self.target_model_config.tokenizer_mode,
2497
+ trust_remote_code=self.target_model_config.
2498
+ trust_remote_code,
2499
+ allowed_local_media_path=self.target_model_config.
2500
+ allowed_local_media_path,
2501
+ dtype=self.target_model_config.dtype,
2502
+ seed=self.target_model_config.seed,
2503
+ revision=self.revision,
2504
+ code_revision=self.code_revision,
2505
+ tokenizer_revision=self.target_model_config.
2506
+ tokenizer_revision,
2507
+ spec_target_max_model_len=self.target_model_config.
2508
+ max_model_len,
2509
+ quantization=self.quantization,
2510
+ enforce_eager=self.target_model_config.enforce_eager,
2511
+ max_seq_len_to_capture=self.target_model_config.
2512
+ max_seq_len_to_capture,
2513
+ max_logprobs=self.target_model_config.max_logprobs,
2514
+ hf_overrides=SpeculativeConfig.hf_config_override,
2515
+ )
2516
+
2517
+ # Automatically detect the method
2518
+ if self.method in ('eagle', 'eagle3'):
2519
+ pass
2520
+ elif "eagle-" in self.draft_model_config.model.lower() or \
2521
+ "eagle3-" in self.draft_model_config.model.lower():
2522
+ self.method = "eagle"
2523
+ elif self.draft_model_config.hf_config.model_type == "medusa":
2524
+ self.method = "medusa"
2525
+ elif (self.draft_model_config.hf_config.model_type ==
2526
+ "mlp_speculator"):
2527
+ self.method = "mlp_speculator"
2528
+ elif (self.draft_model_config.hf_config.model_type ==
2529
+ "deepseek_mtp"):
2530
+ self.method = "deepseek_mtp"
2531
+ if self.num_speculative_tokens > 1:
2532
+ logger.warning(
2533
+ "All Deepseek MTP models only have " \
2534
+ "one layer. Might need some code changes " \
2535
+ "to support multiple layers."
2536
+ )
2537
+ else:
2538
+ self.method = "draft_model"
2539
+
2540
+ # Replace hf_config for EAGLE draft_model
2541
+ if self.method in ("eagle", "eagle3"):
2542
+ if self.enable_chunked_prefill and not envs.VLLM_USE_V1:
2543
+ raise ValueError(
2544
+ "Chunked prefill and EAGLE are not compatible "
2545
+ "when using V0.")
2546
+
2547
+ from vllm.transformers_utils.configs.eagle import (
2548
+ EAGLEConfig)
2549
+ if isinstance(self.draft_model_config.hf_config,
2550
+ EAGLEConfig):
2551
+ pass
2552
+ else:
2553
+ eagle_config = EAGLEConfig(
2554
+ self.draft_model_config.hf_config,
2555
+ method=self.method)
2556
+ self.draft_model_config.hf_config = eagle_config
2557
+
2558
+ if (self.num_speculative_tokens is not None
2559
+ and hasattr(self.draft_model_config.hf_config,
2560
+ "num_lookahead_tokens")):
2561
+ self.draft_model_config.hf_config.num_lookahead_tokens = \
2562
+ self.num_speculative_tokens
2563
+
2564
+ n_predict = getattr(self.draft_model_config.hf_config,
2565
+ "n_predict", None)
2566
+ if n_predict is not None:
2567
+ if self.num_speculative_tokens is None:
2568
+ # Default to max value defined in draft model config.
2569
+ self.num_speculative_tokens = n_predict
2570
+ elif self.num_speculative_tokens > n_predict and \
2571
+ self.num_speculative_tokens % n_predict != 0:
2572
+ # Ensure divisibility for MTP module reuse.
2573
+ raise ValueError(
2574
+ f"num_speculative_tokens:{self.num_speculative_tokens}"
2575
+ f" must be divisible by {n_predict=}")
2576
+
2577
+ self.draft_tensor_parallel_size = \
2578
+ SpeculativeConfig._verify_and_get_draft_tp(
2579
+ self.target_parallel_config,
2580
+ self.draft_tensor_parallel_size,
2581
+ self.draft_model_config.hf_config
2582
+ )
2583
+
2584
+ self.draft_model_config.max_model_len = (
2585
+ SpeculativeConfig._maybe_override_draft_max_model_len(
2586
+ self.max_model_len,
2587
+ self.draft_model_config.max_model_len,
2588
+ self.target_model_config.max_model_len,
2589
+ ))
2590
+
2591
+ self.draft_parallel_config = (
2592
+ SpeculativeConfig.create_draft_parallel_config(
2593
+ self.target_parallel_config,
2594
+ self.draft_tensor_parallel_size))
2595
+
2596
+ if self.acceptance_method == "typical_acceptance_sampler":
2597
+ if self.posterior_threshold is None:
2598
+ self.posterior_threshold = 0.09
2599
+ if self.posterior_alpha is None:
2600
+ self.posterior_alpha = 0.3
2601
+
2602
+ self._verify_args()
2603
+
2604
+ @staticmethod
2605
+ def _maybe_override_draft_max_model_len(
2606
+ speculative_max_model_len: Optional[int],
2607
+ draft_max_model_len: int,
2608
+ target_max_model_len: int,
2609
+ ) -> int:
2610
+ """Determine the max sequence len for the draft model. This is usually
2611
+ the draft_max_model_len, but may be the target_max_model_len if it is
2612
+ less than the draft_max_model_len, or may be speculative_max_model_len
2613
+ if it is specified.
2614
+
2615
+ This is necessary so that sequences do not exceed the capacity of the
2616
+ draft model or the target model.
2617
+
2618
+ speculative_max_model_len is mainly used for testing that sequences can
2619
+ skip speculation.
2620
+ """
2621
+
2622
+ if speculative_max_model_len is not None:
2623
+
2624
+ if speculative_max_model_len > draft_max_model_len:
2625
+ raise ValueError(f"{speculative_max_model_len=} cannot be "
2626
+ f"larger than {draft_max_model_len=}")
2627
+
2628
+ if speculative_max_model_len > target_max_model_len:
2629
+ raise ValueError(f"{speculative_max_model_len=} cannot be "
2630
+ f"larger than {target_max_model_len=}")
2631
+
2632
+ return speculative_max_model_len
2633
+
2634
+ return min(
2635
+ draft_max_model_len,
2636
+ target_max_model_len,
2637
+ )
2638
+
2639
+ @staticmethod
2640
+ def _verify_and_get_draft_tp(
2641
+ target_parallel_config: ParallelConfig,
2642
+ speculative_draft_tensor_parallel_size: Optional[int],
2643
+ draft_hf_config: PretrainedConfig) -> int:
2644
+ """
2645
+ Verifies and adjusts the tensor parallel size for a draft model
2646
+ specified using speculative_draft_tensor_parallel_size.
2647
+ """
2648
+ # If speculative_draft_tensor_parallel_size is unset then set it
2649
+ # appropriately else verify that it is set correctly.
2650
+ if speculative_draft_tensor_parallel_size is None:
2651
+ if draft_hf_config.model_type == "mlp_speculator":
2652
+ speculative_draft_tensor_parallel_size = 1
2653
+ if target_parallel_config.tensor_parallel_size > 1:
2654
+ logger.warning(
2655
+ "%s cannot currently be run with tp>1; "
2656
+ "setting speculative_draft_tensor_parallel_size=1",
2657
+ draft_hf_config.model_type)
2658
+ else:
2659
+ speculative_draft_tensor_parallel_size = \
2660
+ target_parallel_config.tensor_parallel_size
2661
+ elif speculative_draft_tensor_parallel_size not in (
2662
+ 1, target_parallel_config.tensor_parallel_size):
2663
+ raise ValueError(
2664
+ f"{speculative_draft_tensor_parallel_size=} cannot be "
2665
+ f"other value than 1 or target model tensor_parallel_size")
2666
+ return speculative_draft_tensor_parallel_size
2667
+
2668
+ @staticmethod
2669
+ def create_draft_parallel_config(
2670
+ target_parallel_config: ParallelConfig,
2671
+ speculative_draft_tensor_parallel_size: int,
2672
+ ) -> ParallelConfig:
2673
+ """Create a parallel config for use by the draft worker.
2674
+
2675
+ This is mostly a copy of the target parallel config, except the tp_size.
2676
+ """
2677
+ draft_parallel_config = ParallelConfig(
2678
+ pipeline_parallel_size=target_parallel_config.
2679
+ pipeline_parallel_size,
2680
+ tensor_parallel_size=speculative_draft_tensor_parallel_size,
2681
+ distributed_executor_backend=target_parallel_config.
2682
+ distributed_executor_backend,
2683
+ max_parallel_loading_workers=target_parallel_config.
2684
+ max_parallel_loading_workers,
2685
+ disable_custom_all_reduce=target_parallel_config.
2686
+ disable_custom_all_reduce,
2687
+ ray_workers_use_nsight=target_parallel_config.
2688
+ ray_workers_use_nsight,
2689
+ placement_group=target_parallel_config.placement_group,
2690
+ )
2691
+
2692
+ return draft_parallel_config
2693
+
2694
+ def _verify_args(self) -> None:
2695
+ if self.num_speculative_tokens is None:
2696
+ raise ValueError(
2697
+ "num_speculative_tokens must be provided with "
2698
+ "speculative model unless the draft model config contains an "
2699
+ "n_predict parameter.")
2700
+
2701
+ if self.num_speculative_tokens <= 0:
2702
+ raise ValueError("Expected num_speculative_tokens to be greater "
2703
+ f"than zero ({self.num_speculative_tokens}).")
2704
+
2705
+ if self.draft_model_config:
2706
+ self.draft_model_config.verify_with_parallel_config(
2707
+ self.draft_parallel_config)
2708
+ # Validate and set draft token acceptance related settings.
2709
+
2710
+ if self.acceptance_method is None:
2711
+ raise ValueError("acceptance_method is not set. "
2712
+ "Expected values are rejection_sampler or "
2713
+ "typical_acceptance_sampler.")
2714
+
2715
+ if (self.acceptance_method != 'rejection_sampler'
2716
+ and self.acceptance_method != 'typical_acceptance_sampler'):
2717
+ raise ValueError(
2718
+ "Expected acceptance_method to be either "
2719
+ "rejection_sampler or typical_acceptance_sampler. Instead it "
2720
+ f"is {self.acceptance_method}")
2721
+
2722
+ if self.acceptance_method == "typical_acceptance_sampler" and (
2723
+ (self.posterior_threshold is not None
2724
+ and self.posterior_threshold < 0) or
2725
+ (self.posterior_alpha is not None and self.posterior_alpha < 0)):
2726
+ raise ValueError(
2727
+ "Expected the posterior_threshold and posterior_alpha of "
2728
+ "typical_acceptance_sampler to be > 0. "
2729
+ "Instead found posterior_threshold = "
2730
+ f"{self.posterior_threshold} and posterior_alpha = "
2731
+ f"{self.posterior_alpha}")
2732
+
2733
+ if (self.disable_by_batch_size is not None
2734
+ and self.disable_by_batch_size < 2):
2735
+ raise ValueError("Expect the batch size threshold of disabling "
2736
+ "speculative decoding is > 1, but got "
2737
+ f"{self.disable_by_batch_size=}")
2738
+
2739
+ if self.method == "eagle3" and self.target_model_config and \
2740
+ "llama" not in self.target_model_config.hf_text_config.model_type:
2741
+ raise ValueError(
2742
+ "Eagle3 is only supported for Llama models. "
2743
+ f"Got {self.target_model_config.hf_text_config.model_type=}")
2744
+
2745
+ @property
2746
+ def num_lookahead_slots(self) -> int:
2747
+ """The number of additional slots the scheduler should allocate per
2748
+ step, in addition to the slots allocated for each known token.
2749
+
2750
+ This is equal to the number of speculative tokens, as each speculative
2751
+ token must be scored.
2752
+ """
2753
+ return self.num_speculative_tokens
2754
+
2755
+ def use_eagle(self) -> bool:
2756
+ return self.method in ("eagle", "eagle3", "deepseek_mtp")
2757
+
2758
+ def __repr__(self) -> str:
2759
+ method = self.method
2760
+ model = None if method == "ngram" else self.draft_model_config.model
2761
+ num_spec_tokens = self.num_speculative_tokens
2762
+ return f"SpeculativeConfig({method=}, {model=}, {num_spec_tokens=})"
2763
+
2764
+
2765
+ LoRADType = Literal["auto", "float16", "bfloat16"]
2766
+
2767
+
2768
+ @config
2769
+ @dataclass
2770
+ class LoRAConfig:
2771
+ """Configuration for LoRA."""
2772
+
2773
+ max_lora_rank: int = 16
2774
+ """Max LoRA rank."""
2775
+ max_loras: int = 1
2776
+ """Max number of LoRAs in a single batch."""
2777
+ fully_sharded_loras: bool = False
2778
+ """By default, only half of the LoRA computation is sharded with tensor
2779
+ parallelism. Enabling this will use the fully sharded layers. At high
2780
+ sequence length, max rank or tensor parallel size, this is likely faster.
2781
+ """
2782
+ max_cpu_loras: Optional[int] = None
2783
+ """Maximum number of LoRAs to store in CPU memory. Must be >= than
2784
+ `max_loras`."""
2785
+ lora_dtype: Union[torch.dtype, LoRADType] = "auto"
2786
+ """Data type for LoRA. If auto, will default to base model dtype."""
2787
+ lora_extra_vocab_size: int = 256
2788
+ """Maximum size of extra vocabulary that can be present in a LoRA adapter
2789
+ (added to the base model vocabulary)."""
2790
+ lora_vocab_padding_size: ClassVar[int] = current_platform\
2791
+ .get_lora_vocab_padding_size()
2792
+ long_lora_scaling_factors: Optional[tuple[float, ...]] = None
2793
+ """Specify multiple scaling factors (which can be different from base model
2794
+ scaling factor - see eg. Long LoRA) to allow for multiple LoRA adapters
2795
+ trained with those scaling factors to be used at the same time. If not
2796
+ specified, only adapters trained with the base model scaling factor are
2797
+ allowed."""
2798
+ bias_enabled: bool = False
2799
+ """Enable bias for LoRA adapters."""
2800
+
2801
+ def compute_hash(self) -> str:
2802
+ """
2803
+ WARNING: Whenever a new field is added to this config,
2804
+ ensure that it is included in the factors list if
2805
+ it affects the computation graph.
2806
+
2807
+ Provide a hash that uniquely identifies all the configs
2808
+ that affect the structure of the computation
2809
+ graph from input ids/embeddings to the final hidden states,
2810
+ excluding anything before input ids/embeddings and after
2811
+ the final hidden states.
2812
+ """
2813
+ factors: list[Any] = []
2814
+ factors.append(self.max_lora_rank)
2815
+ factors.append(self.max_loras)
2816
+ factors.append(self.fully_sharded_loras)
2817
+ factors.append(self.lora_dtype)
2818
+ factors.append(self.lora_extra_vocab_size)
2819
+ factors.append(self.lora_vocab_padding_size)
2820
+ factors.append(self.long_lora_scaling_factors)
2821
+ factors.append(self.bias_enabled)
2822
+ hash_str = hashlib.md5(str(factors).encode(),
2823
+ usedforsecurity=False).hexdigest()
2824
+ return hash_str
2825
+
2826
+ def __post_init__(self):
2827
+ # Setting the maximum rank to 512 should be able to satisfy the vast
2828
+ # majority of applications.
2829
+ possible_max_ranks = (8, 16, 32, 64, 128, 256, 320, 512)
2830
+ possible_lora_extra_vocab_size = (256, 512)
2831
+ if self.max_lora_rank not in possible_max_ranks:
2832
+ raise ValueError(
2833
+ f"max_lora_rank ({self.max_lora_rank}) must be one of "
2834
+ f"{possible_max_ranks}.")
2835
+ if self.lora_extra_vocab_size not in possible_lora_extra_vocab_size:
2836
+ raise ValueError(
2837
+ f"lora_extra_vocab_size ({self.lora_extra_vocab_size}) "
2838
+ f"must be one of {possible_lora_extra_vocab_size}.")
2839
+ if self.max_loras < 1:
2840
+ raise ValueError(f"max_loras ({self.max_loras}) must be >= 1.")
2841
+ if self.max_cpu_loras is None:
2842
+ self.max_cpu_loras = self.max_loras
2843
+ elif self.max_cpu_loras < self.max_loras:
2844
+ raise ValueError(
2845
+ f"max_cpu_loras ({self.max_cpu_loras}) must be >= "
2846
+ f"max_loras ({self.max_loras})")
2847
+
2848
+ def verify_with_cache_config(self, cache_config: CacheConfig):
2849
+ if cache_config.cpu_offload_gb > 0 and not envs.VLLM_USE_V1:
2850
+ raise ValueError(
2851
+ "V0 LoRA does not support CPU offload, please use V1.")
2852
+
2853
+ def verify_with_model_config(self, model_config: ModelConfig):
2854
+ if self.lora_dtype in (None, "auto"):
2855
+ self.lora_dtype = model_config.dtype
2856
+ elif isinstance(self.lora_dtype, str):
2857
+ self.lora_dtype = getattr(torch, self.lora_dtype)
2858
+
2859
+ def verify_lora_support(self):
2860
+ if self.long_lora_scaling_factors is not None and envs.VLLM_USE_V1:
2861
+ raise ValueError(
2862
+ "V1 LoRA does not support long LoRA, please use V0.")
2863
+
2864
+
2865
+ @config
2866
+ @dataclass
2867
+ class PromptAdapterConfig:
2868
+ """Configuration for PromptAdapters."""
2869
+
2870
+ max_prompt_adapters: int = 1
2871
+ """Max number of PromptAdapters in a batch."""
2872
+ max_prompt_adapter_token: int = 0
2873
+ """Max number of PromptAdapters tokens."""
2874
+ max_cpu_prompt_adapters: Optional[int] = None
2875
+ """Maximum number of PromptAdapters to store in CPU memory. Must be >= than
2876
+ `max_prompt_adapters`."""
2877
+ prompt_adapter_dtype: Union[torch.dtype, str] = "auto"
2878
+ """Data type for PromptAdapter. If auto, will default to base model dtype.
2879
+ """
2880
+
2881
+ def compute_hash(self) -> str:
2882
+ """
2883
+ WARNING: Whenever a new field is added to this config,
2884
+ ensure that it is included in the factors list if
2885
+ it affects the computation graph.
2886
+
2887
+ Provide a hash that uniquely identifies all the configs
2888
+ that affect the structure of the computation
2889
+ graph from input ids/embeddings to the final hidden states,
2890
+ excluding anything before input ids/embeddings and after
2891
+ the final hidden states.
2892
+ """
2893
+ # no factors to consider.
2894
+ # this config will not affect the computation graph.
2895
+ factors: list[Any] = []
2896
+ hash_str = hashlib.md5(str(factors).encode(),
2897
+ usedforsecurity=False).hexdigest()
2898
+ return hash_str
2899
+
2900
+ def __post_init__(self):
2901
+
2902
+ if self.max_prompt_adapters < 1:
2903
+ raise ValueError(f"max_prompt_adapters "
2904
+ f"({self.max_prompt_adapters}) must be >= 1.")
2905
+ if self.max_prompt_adapter_token == 0:
2906
+ raise ValueError("max_prompt_adapter_token must be set.")
2907
+ if self.max_cpu_prompt_adapters is None:
2908
+ self.max_cpu_prompt_adapters = self.max_prompt_adapters
2909
+
2910
+ def verify_with_model_config(self, model_config: ModelConfig):
2911
+ if self.prompt_adapter_dtype == "auto":
2912
+ self.prompt_adapter_dtype = model_config.dtype
2913
+ elif isinstance(self.prompt_adapter_dtype, str):
2914
+ self.prompt_adapter_dtype = getattr(torch,
2915
+ self.prompt_adapter_dtype)
2916
+
2917
+
2918
+ @config
2919
+ @dataclass
2920
+ class MultiModalConfig:
2921
+ """Controls the behavior of multimodal models."""
2922
+
2923
+ limit_per_prompt: dict[str, int] = \
2924
+ cast(dict[str, int], get_field(ModelConfig, "limit_mm_per_prompt"))
2925
+ """
2926
+ The maximum number of input items allowed per prompt for each modality.
2927
+ Defaults to 1 (V0) or 999 (V1) for each modality.
2928
+
2929
+ For example, to allow up to 16 images and 2 videos per prompt:
2930
+ `{"images": 16, "videos": 2}`
2931
+ """
2932
+
2933
+ mm_processor_kwargs: Optional[dict[str, object]] = None
2934
+ """
2935
+ Overrides for the multi-modal processor obtained from
2936
+ `transformers.AutoProcessor.from_pretrained`.
2937
+
2938
+ The available overrides depend on the model that is being run.
2939
+
2940
+ For example, for Phi-3-Vision:
2941
+ `{"num_crops": 4}`.
2942
+ """
2943
+
2944
+ disable_mm_preprocessor_cache: bool = False
2945
+ """
2946
+ If `True`, disable caching of the processed multi-modal inputs.
2947
+ """
2948
+
2949
+ def compute_hash(self) -> str:
2950
+ """
2951
+ WARNING: Whenever a new field is added to this config,
2952
+ ensure that it is included in the factors list if
2953
+ it affects the computation graph.
2954
+
2955
+ Provide a hash that uniquely identifies all the configs
2956
+ that affect the structure of the computation
2957
+ graph from input ids/embeddings to the final hidden states,
2958
+ excluding anything before input ids/embeddings and after
2959
+ the final hidden states.
2960
+ """
2961
+ # no factors to consider.
2962
+ # this config will not affect the computation graph.
2963
+ factors: list[Any] = []
2964
+ hash_str = hashlib.md5(str(factors).encode(),
2965
+ usedforsecurity=False).hexdigest()
2966
+ return hash_str
2967
+
2968
+ def get_limit_per_prompt(self, modality: str) -> int:
2969
+ """
2970
+ Get the maximum number of input items allowed per prompt
2971
+ for the given modality.
2972
+ """
2973
+ return self.limit_per_prompt.get(
2974
+ modality,
2975
+ 999 if envs.VLLM_USE_V1 else 1,
2976
+ )
2977
+
2978
+ # TODO: Add configs to init vision tower or not.
2979
+
2980
+
2981
+ @config
2982
+ @dataclass
2983
+ class PoolerConfig:
2984
+ """Controls the behavior of output pooling in pooling models."""
2985
+
2986
+ pooling_type: Optional[str] = None
2987
+ """
2988
+ The pooling method of the pooling model. This should be a key in
2989
+ [`vllm.model_executor.layers.pooler.PoolingType`][].
2990
+ """
2991
+
2992
+ normalize: Optional[bool] = None
2993
+ """
2994
+ Whether to normalize the pooled outputs. Usually, this should be set to
2995
+ ``True`` for embedding outputs.
2996
+ """
2997
+
2998
+ softmax: Optional[bool] = None
2999
+ """
3000
+ Whether to apply softmax to the pooled outputs. Usually, this should be set
3001
+ to ``True`` for classification outputs.
3002
+ """
3003
+
3004
+ step_tag_id: Optional[int] = None
3005
+ """
3006
+ If set, only the score corresponding to the ``step_tag_id`` in the
3007
+ generated sentence should be returned. Otherwise, the scores for all tokens
3008
+ are returned.
3009
+ """
3010
+
3011
+ returned_token_ids: Optional[list[int]] = None
3012
+ """
3013
+ A list of indices for the vocabulary dimensions to be extracted,
3014
+ such as the token IDs of ``good_token`` and ``bad_token`` in the
3015
+ ``math-shepherd-mistral-7b-prm`` model.
3016
+ """
3017
+
3018
+ def compute_hash(self) -> str:
3019
+ """
3020
+ WARNING: Whenever a new field is added to this config,
3021
+ ensure that it is included in the factors list if
3022
+ it affects the computation graph.
3023
+
3024
+ Provide a hash that uniquely identifies all the configs
3025
+ that affect the structure of the computation
3026
+ graph from input ids/embeddings to the final hidden states,
3027
+ excluding anything before input ids/embeddings and after
3028
+ the final hidden states.
3029
+ """
3030
+ # no factors to consider.
3031
+ # this config will not affect the computation graph.
3032
+ factors: list[Any] = []
3033
+ hash_str = hashlib.md5(str(factors).encode(),
3034
+ usedforsecurity=False).hexdigest()
3035
+ return hash_str
3036
+
3037
+
3038
+ _STR_DTYPE_TO_TORCH_DTYPE = {
3039
+ "half": torch.float16,
3040
+ "float16": torch.float16,
3041
+ "float": torch.float32,
3042
+ "float32": torch.float32,
3043
+ "bfloat16": torch.bfloat16,
3044
+ }
3045
+
3046
+ _ROCM_NOT_SUPPORTED_DTYPE: list[str] = [] #
3047
+
3048
+
3049
+ def _get_and_verify_dtype(
3050
+ config: PretrainedConfig,
3051
+ dtype: Union[str, torch.dtype],
3052
+ ) -> torch.dtype:
3053
+ # NOTE: getattr(config, "torch_dtype", torch.float32) is not correct
3054
+ # because config.torch_dtype can be None.
3055
+ config_dtype = getattr(config, "torch_dtype", None)
3056
+
3057
+ # Fallbacks for multi-modal models if the root config
3058
+ # does not define torch_dtype
3059
+ if config_dtype is None:
3060
+ config_dtype = getattr(config.get_text_config(), "torch_dtype", None)
3061
+ if config_dtype is None and hasattr(config, "vision_config"):
3062
+ config_dtype = getattr(config.vision_config, "torch_dtype", None)
3063
+
3064
+ if config_dtype is None:
3065
+ config_dtype = torch.float32
3066
+
3067
+ if isinstance(dtype, str):
3068
+ dtype = dtype.lower()
3069
+ if dtype == "auto":
3070
+ # Set default dtype from model config
3071
+ if config_dtype == torch.float32:
3072
+ # Following common practice, we use float16 for float32 models
3073
+ torch_dtype = torch.float16
3074
+ else:
3075
+ torch_dtype = config_dtype
3076
+
3077
+ if config.model_type == "plamo2":
3078
+ logger.warning(
3079
+ "For PLaMo2, we cast models to bfloat16 instead of using "
3080
+ "float16 by default. This is because float16 does not work."
3081
+ )
3082
+ torch_dtype = torch.bfloat16
3083
+
3084
+ # Deal with torch dtype fallback for device compatibility.
3085
+ from vllm.platforms import current_platform
3086
+ if torch_dtype not in current_platform.supported_dtypes:
3087
+ device_name = current_platform.get_device_name()
3088
+
3089
+ if ((capability := current_platform.get_device_capability())
3090
+ is None):
3091
+ compute_str = ""
3092
+ else:
3093
+ version_str = capability.as_version_str()
3094
+ compute_str = f" (with compute capability {version_str})"
3095
+ fallback_dtype = current_platform.supported_dtypes[0]
3096
+ logger.warning(
3097
+ "Your %s device%s doesn't support %s. " \
3098
+ "Falling back to %s for compatibility.",
3099
+ device_name, compute_str, torch_dtype, fallback_dtype
3100
+ )
3101
+ torch_dtype = fallback_dtype
3102
+
3103
+ if current_platform.is_hpu() and torch_dtype == torch.float16:
3104
+ logger.warning(
3105
+ "For HPU, we cast models to bfloat16 instead of "
3106
+ "using float16 by default. Please specify `dtype` if you "
3107
+ "want to use float16.")
3108
+ torch_dtype = torch.bfloat16
3109
+ elif dtype == "float16" and config.model_type == "plamo2":
3110
+ logger.warning(
3111
+ "For PLaMo2, using float16 is unstable and might cause "
3112
+ "unexpected behavior. Please use bfloat16 or float32 instead.")
3113
+ torch_dtype = torch.float16
3114
+ else:
3115
+ if dtype not in _STR_DTYPE_TO_TORCH_DTYPE:
3116
+ raise ValueError(f"Unknown dtype: {dtype}")
3117
+ torch_dtype = _STR_DTYPE_TO_TORCH_DTYPE[dtype]
3118
+ elif isinstance(dtype, torch.dtype):
3119
+ torch_dtype = dtype
3120
+ else:
3121
+ raise ValueError(f"Unknown dtype: {dtype}")
3122
+
3123
+ # Verify the dtype.
3124
+ if torch_dtype != config_dtype:
3125
+ if torch_dtype == torch.float32:
3126
+ # Upcasting to float32 is allowed.
3127
+ logger.info("Upcasting %s to %s.", config_dtype, torch_dtype)
3128
+ pass
3129
+ elif config_dtype == torch.float32:
3130
+ # Downcasting from float32 to float16 or bfloat16 is allowed.
3131
+ logger.info("Downcasting %s to %s.", config_dtype, torch_dtype)
3132
+ pass
3133
+ else:
3134
+ # Casting between float16 and bfloat16 is allowed with a warning.
3135
+ logger.warning("Casting %s to %s.", config_dtype, torch_dtype)
3136
+
3137
+ return torch_dtype
3138
+
3139
+
3140
+ def _get_and_verify_max_len(
3141
+ hf_config: PretrainedConfig,
3142
+ max_model_len: Optional[int],
3143
+ disable_sliding_window: bool,
3144
+ sliding_window_len: Optional[Union[int, list[Optional[int]]]],
3145
+ spec_target_max_model_len: Optional[int] = None,
3146
+ encoder_config: Optional[Any] = None,
3147
+ ) -> int:
3148
+ """Get and verify the model's maximum length."""
3149
+ derived_max_model_len = float("inf")
3150
+ possible_keys = [
3151
+ # OPT
3152
+ "max_position_embeddings",
3153
+ # GPT-2
3154
+ "n_positions",
3155
+ # MPT
3156
+ "max_seq_len",
3157
+ # ChatGLM2
3158
+ "seq_length",
3159
+ # Command-R
3160
+ "model_max_length",
3161
+ # Whisper
3162
+ "max_target_positions",
3163
+ # Others
3164
+ "max_sequence_length",
3165
+ "max_seq_length",
3166
+ "seq_len",
3167
+ ]
3168
+ # Choose the smallest "max_length" from the possible keys.
3169
+ max_len_key = None
3170
+ for key in possible_keys:
3171
+ max_len = getattr(hf_config, key, None)
3172
+ if max_len is not None:
3173
+ max_len_key = key if max_len < derived_max_model_len \
3174
+ else max_len_key
3175
+ derived_max_model_len = min(derived_max_model_len, max_len)
3176
+ # For Command-R / Cohere, Cohere2 / Aya Vision models
3177
+ if tmp_max_len := getattr(hf_config, "model_max_length", None):
3178
+ max_len_key = "model_max_length"
3179
+ derived_max_model_len = tmp_max_len
3180
+
3181
+ # If sliding window is manually disabled, max_length should be less
3182
+ # than the sliding window length in the model config.
3183
+ if disable_sliding_window and sliding_window_len is not None:
3184
+
3185
+ sliding_window_len_min = get_min_sliding_window(sliding_window_len)
3186
+ max_len_key = "sliding_window" \
3187
+ if sliding_window_len_min < derived_max_model_len else max_len_key
3188
+ derived_max_model_len = min(derived_max_model_len,
3189
+ sliding_window_len_min)
3190
+
3191
+ # If none of the keys were found in the config, use a default and
3192
+ # log a warning.
3193
+ if derived_max_model_len == float("inf"):
3194
+ if max_model_len is not None:
3195
+ # If max_model_len is specified, we use it.
3196
+ return max_model_len
3197
+
3198
+ if spec_target_max_model_len is not None:
3199
+ # If this is a speculative draft model, we use the max model len
3200
+ # from the target model.
3201
+ return spec_target_max_model_len
3202
+
3203
+ default_max_len = 2048
3204
+ logger.warning(
3205
+ "The model's config.json does not contain any of the following "
3206
+ "keys to determine the original maximum length of the model: "
3207
+ "%s. Assuming the model's maximum length is %d.", possible_keys,
3208
+ default_max_len)
3209
+ derived_max_model_len = default_max_len
3210
+
3211
+ rope_scaling = getattr(hf_config, "rope_scaling", None)
3212
+ # NOTE(woosuk): Gemma3's max_model_len (128K) is already scaled by RoPE
3213
+ # scaling, so we skip applying the scaling factor again.
3214
+ if rope_scaling is not None and "gemma3" not in hf_config.model_type:
3215
+ # No need to consider "type" key because of patch_rope_scaling when
3216
+ # loading HF config
3217
+ rope_type = rope_scaling["rope_type"]
3218
+
3219
+ if rope_type not in ("su", "longrope", "llama3"):
3220
+ if disable_sliding_window:
3221
+ # TODO(robertgshaw): Find a model that supports rope_scaling
3222
+ # with sliding window to see if this case should be allowed.
3223
+ raise NotImplementedError(
3224
+ "Disabling sliding window is not supported for models "
3225
+ "with rope_scaling. Please raise an issue so we can "
3226
+ "investigate.")
3227
+
3228
+ # NOTE: rope_type == "default" does not define factor
3229
+ # https://github.com/huggingface/transformers/blob/v4.45.2/src/transformers/modeling_rope_utils.py
3230
+ scaling_factor = rope_scaling.get("factor", 1.0)
3231
+
3232
+ if rope_type == "yarn":
3233
+ derived_max_model_len = rope_scaling[
3234
+ "original_max_position_embeddings"]
3235
+ derived_max_model_len *= scaling_factor
3236
+
3237
+ if encoder_config and "max_seq_length" in encoder_config:
3238
+ derived_max_model_len = encoder_config["max_seq_length"]
3239
+
3240
+ # If the user specified a max length, make sure it is smaller than the
3241
+ # derived length from the HF model config.
3242
+ if max_model_len is None:
3243
+ max_model_len = int(derived_max_model_len)
3244
+ if current_platform.is_tpu():
3245
+ logger.warning(
3246
+ "--max-model-len is not specified, "
3247
+ "it's currently using model's default length %s, "
3248
+ "which might be too large."
3249
+ "Please input with --max-model-len based on your "
3250
+ "request input length and output length, to avoid "
3251
+ "unnecessary degradation.", max_model_len)
3252
+ elif max_model_len > derived_max_model_len:
3253
+ # Some models might have a separate key for specifying model_max_length
3254
+ # that will be bigger than derived_max_model_len. We compare user input
3255
+ # with model_max_length and allow this override when it's smaller.
3256
+ model_max_length = getattr(hf_config, "model_max_length", None)
3257
+ if model_max_length is not None and max_model_len <= model_max_length:
3258
+ if disable_sliding_window:
3259
+ # TODO(robertgshaw): Find a model that has model_max_length
3260
+ # with sliding window to see if this case should be allowed.
3261
+ raise NotImplementedError(
3262
+ "Disabling sliding window is not supported for models "
3263
+ "model_max_length in the config. Please raise an issue "
3264
+ "so we can investigate.")
3265
+ else:
3266
+ msg = (
3267
+ f"User-specified max_model_len ({max_model_len}) is greater "
3268
+ f"than the derived max_model_len ({max_len_key}="
3269
+ f"{derived_max_model_len} or model_max_length="
3270
+ f"{model_max_length} in model's config.json). This may lead "
3271
+ "to incorrect model outputs or CUDA errors.")
3272
+ if envs.VLLM_ALLOW_LONG_MAX_MODEL_LEN:
3273
+ logger.warning(
3274
+ "%s Make sure the value is correct and within the "
3275
+ "model context size.", msg)
3276
+ else:
3277
+ raise ValueError(
3278
+ f"{msg} To allow overriding this maximum, set "
3279
+ "the env var VLLM_ALLOW_LONG_MAX_MODEL_LEN=1")
3280
+ return int(max_model_len)
3281
+
3282
+
3283
+ def get_min_sliding_window(
3284
+ sliding_window: Union[int, list[Optional[int]]]) -> int:
3285
+ if isinstance(sliding_window, list):
3286
+ return min(s for s in sliding_window if s is not None)
3287
+
3288
+ return sliding_window
3289
+
3290
+
3291
+ def get_served_model_name(model: str,
3292
+ served_model_name: Optional[Union[str, list[str]]]):
3293
+ """
3294
+ If the input is a non-empty list, the first model_name in
3295
+ `served_model_name` is taken.
3296
+ If the input is a non-empty string, it is used directly.
3297
+ For cases where the input is either an empty string or an
3298
+ empty list, the fallback is to use `self.model`.
3299
+ """
3300
+ if not served_model_name:
3301
+ return model
3302
+ if isinstance(served_model_name, list):
3303
+ return served_model_name[0]
3304
+ return served_model_name
3305
+
3306
+
3307
+ GuidedDecodingBackendV0 = Literal["auto", "outlines", "lm-format-enforcer",
3308
+ "xgrammar", "guidance"]
3309
+ GuidedDecodingBackendV1 = Literal["auto", "xgrammar", "guidance"]
3310
+ GuidedDecodingBackend = Literal[GuidedDecodingBackendV0,
3311
+ GuidedDecodingBackendV1]
3312
+
3313
+
3314
+ @config
3315
+ @dataclass
3316
+ class DecodingConfig:
3317
+ """Dataclass which contains the decoding strategy of the engine."""
3318
+
3319
+ @property
3320
+ @deprecated(
3321
+ "`guided_decoding_backend` is deprecated and has been renamed to "
3322
+ "`backend`. This will be removed in v0.10.0. Please use the "
3323
+ "`backend` argument instead.")
3324
+ def guided_decoding_backend(self) -> GuidedDecodingBackend:
3325
+ return self.backend
3326
+
3327
+ @guided_decoding_backend.setter
3328
+ def guided_decoding_backend(self, value: GuidedDecodingBackend):
3329
+ self.backend = value
3330
+
3331
+ backend: GuidedDecodingBackend = "auto" if envs.VLLM_USE_V1 else "xgrammar"
3332
+ """Which engine will be used for guided decoding (JSON schema / regex etc)
3333
+ by default. With "auto", we will make opinionated choices based on request
3334
+ contents and what the backend libraries currently support, so the behavior
3335
+ is subject to change in each release."""
3336
+
3337
+ disable_fallback: bool = False
3338
+ """If `True`, vLLM will not fallback to a different backend on error."""
3339
+
3340
+ disable_any_whitespace: bool = False
3341
+ """If `True`, the model will not generate any whitespace during guided
3342
+ decoding. This is only supported for xgrammar and guidance backends."""
3343
+
3344
+ disable_additional_properties: bool = False
3345
+ """If `True`, the `guidance` backend will not use `additionalProperties`
3346
+ in the JSON schema. This is only supported for the `guidance` backend and
3347
+ is used to better align its behaviour with `outlines` and `xgrammar`."""
3348
+
3349
+ reasoning_backend: str = ""
3350
+ """Select the reasoning parser depending on the model that you're using.
3351
+ This is used to parse the reasoning content into OpenAI API format."""
3352
+
3353
+ def compute_hash(self) -> str:
3354
+ """
3355
+ WARNING: Whenever a new field is added to this config,
3356
+ ensure that it is included in the factors list if
3357
+ it affects the computation graph.
3358
+
3359
+ Provide a hash that uniquely identifies all the configs
3360
+ that affect the structure of the computation
3361
+ graph from input ids/embeddings to the final hidden states,
3362
+ excluding anything before input ids/embeddings and after
3363
+ the final hidden states.
3364
+ """
3365
+ # no factors to consider.
3366
+ # this config will not affect the computation graph.
3367
+ factors: list[Any] = []
3368
+ hash_str = hashlib.md5(str(factors).encode(),
3369
+ usedforsecurity=False).hexdigest()
3370
+ return hash_str
3371
+
3372
+ def __post_init__(self):
3373
+ if ":" in self.backend:
3374
+ self._extract_backend_options()
3375
+
3376
+ if envs.VLLM_USE_V1:
3377
+ valid_guided_backends = get_args(GuidedDecodingBackendV1)
3378
+ else:
3379
+ valid_guided_backends = get_args(GuidedDecodingBackendV0)
3380
+ if self.backend not in valid_guided_backends:
3381
+ raise ValueError(f"Invalid backend '{self.backend}',"
3382
+ f" must be one of {valid_guided_backends}")
3383
+ if (self.disable_any_whitespace
3384
+ and self.backend not in ("xgrammar", "guidance")):
3385
+ raise ValueError("disable_any_whitespace is only supported for "
3386
+ "xgrammar and guidance backends.")
3387
+ if (self.disable_additional_properties and self.backend != "guidance"):
3388
+ raise ValueError("disable_additional_properties is only supported "
3389
+ "for the guidance backend.")
3390
+
3391
+ @deprecated(
3392
+ "Passing guided decoding backend options inside backend in the format "
3393
+ "'backend:...' is deprecated. This will be removed in v0.10.0. Please "
3394
+ "use the dedicated arguments '--disable-fallback', "
3395
+ "'--disable-any-whitespace' and '--disable-additional-properties' "
3396
+ "instead.")
3397
+ def _extract_backend_options(self):
3398
+ """Extract backend options from the backend string."""
3399
+ backend, options = self.backend.split(":")
3400
+ self.backend = cast(GuidedDecodingBackend, backend)
3401
+ options_set = set(options.strip().split(","))
3402
+ if "no-fallback" in options_set:
3403
+ self.disable_fallback = True
3404
+ if "disable-any-whitespace" in options_set:
3405
+ self.disable_any_whitespace = True
3406
+ if "no-additional-properties" in options_set:
3407
+ self.disable_additional_properties = True
3408
+
3409
+
3410
+ DetailedTraceModules = Literal["model", "worker", "all"]
3411
+
3412
+
3413
+ @config
3414
+ @dataclass
3415
+ class ObservabilityConfig:
3416
+ """Configuration for observability - metrics and tracing."""
3417
+
3418
+ show_hidden_metrics_for_version: Optional[str] = None
3419
+ """Enable deprecated Prometheus metrics that have been hidden since the
3420
+ specified version. For example, if a previously deprecated metric has been
3421
+ hidden since the v0.7.0 release, you use
3422
+ `--show-hidden-metrics-for-version=0.7` as a temporary escape hatch while
3423
+ you migrate to new metrics. The metric is likely to be removed completely
3424
+ in an upcoming release."""
3425
+
3426
+ @cached_property
3427
+ def show_hidden_metrics(self) -> bool:
3428
+ """Check if the hidden metrics should be shown."""
3429
+ if self.show_hidden_metrics_for_version is None:
3430
+ return False
3431
+ return version._prev_minor_version_was(
3432
+ self.show_hidden_metrics_for_version)
3433
+
3434
+ otlp_traces_endpoint: Optional[str] = None
3435
+ """Target URL to which OpenTelemetry traces will be sent."""
3436
+
3437
+ collect_detailed_traces: Optional[list[DetailedTraceModules]] = None
3438
+ """It makes sense to set this only if `--otlp-traces-endpoint` is set. If
3439
+ set, it will collect detailed traces for the specified modules. This
3440
+ involves use of possibly costly and or blocking operations and hence might
3441
+ have a performance impact.
3442
+
3443
+ Note that collecting detailed timing information for each request can be
3444
+ expensive."""
3445
+
3446
+ @cached_property
3447
+ def collect_model_forward_time(self) -> bool:
3448
+ """Whether to collect model forward time for the request."""
3449
+ return (self.collect_detailed_traces is not None
3450
+ and ("model" in self.collect_detailed_traces
3451
+ or "all" in self.collect_detailed_traces))
3452
+
3453
+ @cached_property
3454
+ def collect_model_execute_time(self) -> bool:
3455
+ """Whether to collect model execute time for the request."""
3456
+ return (self.collect_detailed_traces is not None
3457
+ and ("worker" in self.collect_detailed_traces
3458
+ or "all" in self.collect_detailed_traces))
3459
+
3460
+ def compute_hash(self) -> str:
3461
+ """
3462
+ WARNING: Whenever a new field is added to this config,
3463
+ ensure that it is included in the factors list if
3464
+ it affects the computation graph.
3465
+
3466
+ Provide a hash that uniquely identifies all the configs
3467
+ that affect the structure of the computation
3468
+ graph from input ids/embeddings to the final hidden states,
3469
+ excluding anything before input ids/embeddings and after
3470
+ the final hidden states.
3471
+ """
3472
+ # no factors to consider.
3473
+ # this config will not affect the computation graph.
3474
+ factors: list[Any] = []
3475
+ hash_str = hashlib.md5(str(factors).encode(),
3476
+ usedforsecurity=False).hexdigest()
3477
+ return hash_str
3478
+
3479
+ def __post_init__(self):
3480
+ if (self.collect_detailed_traces is not None
3481
+ and len(self.collect_detailed_traces) == 1
3482
+ and "," in self.collect_detailed_traces[0]):
3483
+ self._parse_collect_detailed_traces()
3484
+
3485
+ if not is_otel_available() and self.otlp_traces_endpoint is not None:
3486
+ raise ValueError(
3487
+ "OpenTelemetry is not available. Unable to configure "
3488
+ "'otlp_traces_endpoint'. Ensure OpenTelemetry packages are "
3489
+ f"installed. Original error:\n{otel_import_error_traceback}")
3490
+
3491
+ def _parse_collect_detailed_traces(self):
3492
+ assert isinstance(self.collect_detailed_traces, list)
3493
+ self.collect_detailed_traces = cast(
3494
+ list[DetailedTraceModules],
3495
+ self.collect_detailed_traces[0].split(","))
3496
+
3497
+
3498
+ KVProducer = Literal["kv_producer", "kv_both"]
3499
+ KVConsumer = Literal["kv_consumer", "kv_both"]
3500
+ KVRole = Literal[KVProducer, KVConsumer]
3501
+
3502
+
3503
+ @config
3504
+ @dataclass
3505
+ class KVTransferConfig:
3506
+ """Configuration for distributed KV cache transfer."""
3507
+
3508
+ kv_connector: Optional[str] = None
3509
+ """The KV connector for vLLM to transmit KV caches between vLLM instances.
3510
+ """
3511
+
3512
+ engine_id: Optional[str] = None
3513
+ """The engine id for KV transfers."""
3514
+
3515
+ kv_buffer_device: Optional[str] = "cuda"
3516
+ """The device used by kv connector to buffer the KV cache.
3517
+ Currently only support 'cuda'."""
3518
+
3519
+ kv_buffer_size: float = 1e9
3520
+ """The buffer size for TorchDistributedConnector. Measured in number of
3521
+ bytes. Recommended value: 1e9 (about 1GB)."""
3522
+
3523
+ kv_role: Optional[KVRole] = None
3524
+ """Whether this vLLM instance produces, consumes KV cache, or both. Choices
3525
+ are 'kv_producer', 'kv_consumer', and 'kv_both'."""
3526
+
3527
+ kv_rank: Optional[int] = None
3528
+ """The rank of this vLLM instance in the KV cache transfer. Typical value:
3529
+ 0 for prefill instance, 1 for decode instance.
3530
+ Currently only 1P1D is supported."""
3531
+
3532
+ kv_parallel_size: int = 1
3533
+ """The number of parallel instances for KV cache transfer. For
3534
+ PyNcclConnector, this should be 2."""
3535
+
3536
+ kv_ip: str = "127.0.0.1"
3537
+ """The KV connector ip, used to build distributed connection."""
3538
+
3539
+ kv_port: int = 14579
3540
+ """The KV connector port, used to build distributed connection."""
3541
+
3542
+ kv_connector_extra_config: dict[str, Any] = field(default_factory=dict)
3543
+ """any extra config that the connector may need."""
3544
+
3545
+ kv_connector_module_path: Optional[str] = None
3546
+ """The Python module path to dynamically load the KV connector from.
3547
+ Only supported in V1."""
3548
+
3549
+ def compute_hash(self) -> str:
3550
+ """
3551
+ WARNING: Whenever a new field is added to this config,
3552
+ ensure that it is included in the factors list if
3553
+ it affects the computation graph.
3554
+
3555
+ Provide a hash that uniquely identifies all the configs
3556
+ that affect the structure of the computation
3557
+ graph from input ids/embeddings to the final hidden states,
3558
+ excluding anything before input ids/embeddings and after
3559
+ the final hidden states.
3560
+ """
3561
+ # no factors to consider.
3562
+ # this config will not affect the computation graph.
3563
+ factors: list[Any] = []
3564
+ hash_str = hashlib.md5(str(factors).encode(),
3565
+ usedforsecurity=False).hexdigest()
3566
+ return hash_str
3567
+
3568
+ def __post_init__(self) -> None:
3569
+ if self.engine_id is None:
3570
+ self.engine_id = str(uuid.uuid4())
3571
+
3572
+ if self.kv_role is not None and self.kv_role not in get_args(KVRole):
3573
+ raise ValueError(f"Unsupported kv_role: {self.kv_role}. "
3574
+ f"Supported roles are {get_args(KVRole)}")
3575
+
3576
+ if self.kv_connector is not None and self.kv_role is None:
3577
+ raise ValueError("Please specify kv_disagg_role when kv_connector "
3578
+ f"is set, supported roles are {get_args(KVRole)}")
3579
+
3580
+ @property
3581
+ def is_kv_transfer_instance(self) -> bool:
3582
+ return self.kv_connector is not None and \
3583
+ self.kv_role in get_args(KVRole)
3584
+
3585
+ @property
3586
+ def is_kv_producer(self) -> bool:
3587
+ return self.kv_connector is not None and \
3588
+ self.kv_role in get_args(KVProducer)
3589
+
3590
+ @property
3591
+ def is_kv_consumer(self) -> bool:
3592
+ return self.kv_connector is not None and \
3593
+ self.kv_role in get_args(KVConsumer)
3594
+
3595
+ def get_from_extra_config(self, key, default) -> Any:
3596
+ return self.kv_connector_extra_config.get(key, default)
3597
+
3598
+
3599
+ @config
3600
+ @dataclass
3601
+ class KVEventsConfig:
3602
+ """Configuration for KV event publishing."""
3603
+
3604
+ enable_kv_cache_events: bool = False
3605
+ """If True, enable KV cache events for tracking block storage and removal.
3606
+ Events can be published externally by zmq using the event publisher config.
3607
+ """
3608
+
3609
+ publisher: str = "null"
3610
+ """The publisher to use for publishing kv events. Can be "null", "zmq".
3611
+ """
3612
+
3613
+ endpoint: str = "tcp://*:5557"
3614
+ """The zmq endpoint to use for publishing kv events.
3615
+ """
3616
+
3617
+ replay_endpoint: Optional[str] = None
3618
+ """The zmq endpoint to use for replaying kv events.
3619
+ """
3620
+
3621
+ buffer_steps: int = 10_000
3622
+ """The number of steps to cache for replay endpoint. Will only save
3623
+ events from the last N steps for the replay endpoint.
3624
+ """
3625
+
3626
+ hwm: int = 100_000
3627
+ """The zmq high water mark for the event publisher. After queueing N events,
3628
+ events will start dropping if the consumer is not keeping up.
3629
+ """
3630
+
3631
+ max_queue_size: int = 100_000
3632
+ """The maximum number of events to queue while waiting for publishing.
3633
+ """
3634
+
3635
+ topic: str = ""
3636
+ """The topic to use for the event publisher. Consumers can subscribe to
3637
+ this topic to receive events.
3638
+ """
3639
+
3640
+
3641
+ class CompilationLevel:
3642
+ # constants for the levels of the compilation process
3643
+ NO_COMPILATION = 0
3644
+ DYNAMO_AS_IS = 1
3645
+ DYNAMO_ONCE = 2
3646
+ PIECEWISE = 3
3647
+
3648
+
3649
+ @config
3650
+ @dataclass
3651
+ class PassConfig:
3652
+ """Configuration for custom Inductor passes.
3653
+
3654
+ This is separate from general `CompilationConfig` so that inductor passes
3655
+ don't all have access to full configuration - that would create a cycle as
3656
+ the `PassManager` is set as a property of config."""
3657
+
3658
+ dump_graph_stages: list[str] = field(default_factory=list)
3659
+ """List of stages for which we want to dump the graph. Each pass defines
3660
+ its own stages (before, after, maybe in-between)."""
3661
+ dump_graph_dir: Path = Path(".")
3662
+ """Directory to dump the graphs."""
3663
+ # TODO(luka) better pass enabling system.
3664
+ enable_fusion: bool = True
3665
+ """Whether to enable the custom fusion pass."""
3666
+ enable_noop: bool = True
3667
+ """Whether to enable the custom no-op elimination pass."""
3668
+ enable_sequence_parallelism: bool = False
3669
+ """Whether to enable sequence parallelism."""
3670
+ enable_async_tp: bool = False
3671
+ """Whether to enable async TP."""
3672
+
3673
+ def uuid(self):
3674
+ """
3675
+ Produces a hash unique to the pass configuration.
3676
+ Any new fields that affect compilation should be added to the hash.
3677
+ Do not include dump_graph_* in the hash - they don't affect
3678
+ compilation.
3679
+ """
3680
+ include = {
3681
+ "enable_fusion", "enable_noop", "enable_sequence_parallelism",
3682
+ "enable_async_tp"
3683
+ }
3684
+ dict_ = {k: v for k, v in asdict(self).items() if k in include}
3685
+ return InductorPass.hash_dict(dict_)
3686
+
3687
+ def __post_init__(self) -> None:
3688
+ if not self.enable_noop and self.enable_fusion:
3689
+ logger.warning_once(
3690
+ "Fusion enabled but reshape elimination disabled. "
3691
+ "RMSNorm + quant (fp8) fusion might not work")
3692
+
3693
+
3694
+ @config
3695
+ @dataclass
3696
+ class CompilationConfig:
3697
+ """Configuration for compilation. It has three parts:
3698
+
3699
+ - Top-level Compilation control:
3700
+ - [`level`][vllm.config.CompilationConfig.level]
3701
+ - [`debug_dump_path`][vllm.config.CompilationConfig.debug_dump_path]
3702
+ - [`cache_dir`][vllm.config.CompilationConfig.cache_dir]
3703
+ - [`backend`][vllm.config.CompilationConfig.backend]
3704
+ - [`custom_ops`][vllm.config.CompilationConfig.custom_ops]
3705
+ - [`splitting_ops`][vllm.config.CompilationConfig.splitting_ops]
3706
+ - CudaGraph capture:
3707
+ - [`use_cudagraph`][vllm.config.CompilationConfig.use_cudagraph]
3708
+ - [`cudagraph_capture_sizes`]
3709
+ [vllm.config.CompilationConfig.cudagraph_capture_sizes]
3710
+ - [`cudagraph_num_of_warmups`]
3711
+ [vllm.config.CompilationConfig.cudagraph_num_of_warmups]
3712
+ - [`cudagraph_copy_inputs`]
3713
+ [vllm.config.CompilationConfig.cudagraph_copy_inputs]
3714
+ - [`full_cuda_graph`][vllm.config.CompilationConfig.full_cuda_graph]
3715
+ - Inductor compilation:
3716
+ - [`use_inductor`][vllm.config.CompilationConfig.use_inductor]
3717
+ - [`compile_sizes`][vllm.config.CompilationConfig.compile_sizes]
3718
+ - [`inductor_compile_config`]
3719
+ [vllm.config.CompilationConfig.inductor_compile_config]
3720
+ - [`inductor_passes`][vllm.config.CompilationConfig.inductor_passes]
3721
+ - custom inductor passes
3722
+
3723
+ Why we have different sizes for cudagraph and inductor:
3724
+ - cudagraph: a cudagraph captured for a specific size can only be used
3725
+ for the same size. We need to capture all the sizes we want to use.
3726
+ - inductor: a graph compiled by inductor for a general shape can be used
3727
+ for different sizes. Inductor can also compile for specific sizes,
3728
+ where it can have more information to optimize the graph with fully
3729
+ static shapes. However, we find the general shape compilation is
3730
+ sufficient for most cases. It might be beneficial to compile for
3731
+ certain small batchsizes, where inductor is good at optimizing.
3732
+ """
3733
+ # Top-level Compilation control
3734
+ level: int = 0
3735
+ """The level of compilation:
3736
+
3737
+ - 0: no compilation.
3738
+ - 1: dynamo as is.
3739
+ - 2: dynamo once.
3740
+ - 3: piecewise compilation."""
3741
+ debug_dump_path: str = ""
3742
+ """The path to dump the debug information."""
3743
+ cache_dir: str = ""
3744
+ """The directory to store the compiled graph, to accelerate Inductor
3745
+ compilation. By default, it will use model-related information to generate
3746
+ a cache directory."""
3747
+ backend: str = ""
3748
+ """The backend for compilation. It needs to be a string:
3749
+
3750
+ - "" (empty string): use the default backend.
3751
+ - "eager"/"openxla"/...: use the specified backend registered in PyTorch.
3752
+ - "full.module.name": a qualified name which can be used to import the
3753
+
3754
+ backend function.
3755
+ We use string to avoid serialization issues when using compilation in a
3756
+ distributed setting. When the compilation level is 1 or 2, the backend is
3757
+ used for the compilation directly (it sees the whole graph). When the
3758
+ compilation level is 3, the backend is used for the piecewise compilation
3759
+ (it sees a part of the graph)."""
3760
+ custom_ops: list[str] = field(default_factory=list)
3761
+ """Fine-grained control over which custom ops to enable/disable. Use 'all'
3762
+ to enable all, 'none' to disable all. Also specify a list of custom op
3763
+ names to enable (prefixed with a '+'), or disable (prefixed with a '-').
3764
+ Examples:
3765
+
3766
+ - 'all,-op1' to enable all except op1
3767
+ - 'none,+op1,+op2' to enable only op1 and op2
3768
+
3769
+ By default, all custom ops are enabled when running without Inductor and
3770
+ disabled when running with Inductor (compile_level >= Inductor)."""
3771
+ splitting_ops: list[str] = field(default_factory=list)
3772
+ """A list of ops to split the full graph into subgraphs, used in piecewise
3773
+ compilation."""
3774
+
3775
+ # Inductor capture
3776
+ use_inductor: bool = True
3777
+ """Whether to use inductor compilation:
3778
+
3779
+ - False: inductor compilation is not used. graph runs in eager.
3780
+ - True: inductor compilation is used. one graph for symbolic shape
3781
+ is compiled. In addition, compile for compile_sizes,
3782
+ using configurations in inductor_compile_config."""
3783
+ compile_sizes: Optional[list[Union[int, str]]] = None
3784
+ """Sizes to compile for inductor. In addition
3785
+ to integers, it also supports "cudagraph_capture_sizes" to
3786
+ specify the sizes for cudagraph capture."""
3787
+ inductor_compile_config: dict = field(default_factory=dict)
3788
+ """Additional configurations for inductor.
3789
+ - None: use default configurations."""
3790
+ inductor_passes: dict[str, str] = field(default_factory=dict)
3791
+ """Additional passes for inductor. It is a dictionary
3792
+ from pass name to pass function qualified name. We use function
3793
+ name because the config uses JSON format. If we pass the config
3794
+ from Python, functions can also be passed directly via Python object
3795
+ constructor, e.g. `CompilationConfig(inductor_passes={"a": func})`."""
3796
+
3797
+ # CudaGraph compilation
3798
+ use_cudagraph: bool = False
3799
+ """Whether to use cudagraph inside compilation.
3800
+ - False: cudagraph inside compilation is not used.
3801
+ - True: cudagraph inside compilation is used. It requires
3802
+ that all input buffers have fixed addresses, and all
3803
+ splitting ops write their outputs to input buffers.
3804
+ Note that this is orthogonal to the cudagraph capture logic
3805
+ outside of compilation.
3806
+ TODO: move outside cudagraph logic into compilation.
3807
+ torch.compile will handle cudagraph capture logic in the future."""
3808
+ cudagraph_num_of_warmups: int = 0
3809
+ """Number of warmup runs for cudagraph.
3810
+ It means the first several runs will be treated as warmup runs.
3811
+ Only after that, the execution will be recorded, and the recorded
3812
+ cudagraph will be used for subsequent runs."""
3813
+ cudagraph_capture_sizes: Optional[list[int]] = None
3814
+ """Sizes to capture cudagraph.
3815
+ - None (default): capture sizes are inferred from vllm config.
3816
+ - list[int]: capture sizes are specified as given."""
3817
+ cudagraph_copy_inputs: bool = False
3818
+ """Whether to copy input tensors for
3819
+ cudagraph. If the caller can guarantee that the same input buffers
3820
+ are always used, it can set this to False. Otherwise, it should
3821
+ set this to True, and the compiler will copy the input to an
3822
+ internally managed buffer. Default is False."""
3823
+ full_cuda_graph: bool = False
3824
+ """whether to use a full cuda graph for the entire forward pass rather than
3825
+ splitting certain operations such as attention into subgraphs. Thus this
3826
+ flag cannot be used together with splitting_ops. This may provide
3827
+ performance benefits for smaller models."""
3828
+
3829
+ pass_config: PassConfig = field(default_factory=PassConfig)
3830
+ """Custom inductor passes, see PassConfig for more details"""
3831
+
3832
+ max_capture_size: int = field(default=None, init=False) # type: ignore
3833
+ """not configurable, computed after init"""
3834
+ local_cache_dir: str = field(default=None, init=False) # type: ignore
3835
+ """local cache dir for each rank"""
3836
+ bs_to_padded_graph_size: list[int] = field(
3837
+ default=None, # type: ignore
3838
+ init=False)
3839
+ """optimization:
3840
+ Intuitively, bs_to_padded_graph_size should be dict[int, int].
3841
+ since we know all keys are in a range [0, max_capture_size],
3842
+ we can optimize it to list[int] for better lookup performance."""
3843
+
3844
+ # keep track of enabled and disabled custom ops
3845
+ enabled_custom_ops: Counter[str] = field(default_factory=Counter,
3846
+ init=False)
3847
+ """custom ops that are enabled"""
3848
+ disabled_custom_ops: Counter[str] = field(default_factory=Counter,
3849
+ init=False)
3850
+ """custom ops that are disabled"""
3851
+ traced_files: set[str] = field(default_factory=set, init=False)
3852
+ """files that are traced for compilation"""
3853
+ compilation_time: float = field(default=0.0, init=False)
3854
+ """time taken for compilation"""
3855
+
3856
+ static_forward_context: dict[str, Any] = field(default_factory=dict,
3857
+ init=False)
3858
+ """Per-model forward context
3859
+ Map from layer name to layer objects that need to be accessed outside
3860
+ model code, e.g., Attention, FusedMOE when dp_size>1."""
3861
+
3862
+ def compute_hash(self) -> str:
3863
+ """
3864
+ WARNING: Whenever a new field is added to this config,
3865
+ ensure that it is included in the factors list if
3866
+ it affects the computation graph.
3867
+
3868
+ Provide a hash that uniquely identifies all the configs
3869
+ that affect the structure of the computation
3870
+ graph from input ids/embeddings to the final hidden states,
3871
+ excluding anything before input ids/embeddings and after
3872
+ the final hidden states.
3873
+ """
3874
+ factors: list[Any] = []
3875
+ factors.append(self.level)
3876
+ factors.append(self.backend)
3877
+ factors.append(self.custom_ops)
3878
+ factors.append(self.splitting_ops)
3879
+ factors.append(self.use_inductor)
3880
+ factors.append(self.inductor_compile_config)
3881
+ factors.append(self.inductor_passes)
3882
+ factors.append(self.pass_config.uuid())
3883
+ return hashlib.sha256(str(factors).encode()).hexdigest()
3884
+
3885
+ def __repr__(self) -> str:
3886
+ exclude = {
3887
+ "static_forward_context",
3888
+ "enabled_custom_ops",
3889
+ "disabled_custom_ops",
3890
+ "compilation_time",
3891
+ "bs_to_padded_graph_size",
3892
+ "pass_config",
3893
+ "traced_files",
3894
+ }
3895
+ include = dict()
3896
+ for k, v in asdict(self).items():
3897
+ if k in exclude:
3898
+ continue
3899
+ f = get_field(CompilationConfig, k)
3900
+ if (d := f.default) is not MISSING and d == v:
3901
+ continue
3902
+ if (df := f.default_factory) is not MISSING and df() == v:
3903
+ continue
3904
+ include[k] = v
3905
+ return json.dumps(include)
3906
+
3907
+ __str__ = __repr__
3908
+
3909
+ @classmethod
3910
+ def from_cli(cls, cli_value: str) -> "CompilationConfig":
3911
+ """Parse the CLI value for the compilation config."""
3912
+ if cli_value in ["0", "1", "2", "3"]:
3913
+ return cls(level=int(cli_value))
3914
+ return cls(**json.loads(cli_value))
3915
+
3916
+ def __post_init__(self) -> None:
3917
+ count_none = self.custom_ops.count("none")
3918
+ count_all = self.custom_ops.count("all")
3919
+ assert count_none + count_all <= 1, "Can only specify 'none' or 'all'"
3920
+
3921
+ # TODO(zou3519/luka): There are 2 issues with auto-functionalization V2:
3922
+ # 1. A bug in PyTorch, fixed in 2.7:
3923
+ # https://github.com/pytorch/pytorch/issues/147924
3924
+ # 2. Custom passes (fusion) rely on auto-functionalization V1 and don't
3925
+ # work with V2. Addressing this will take extra engineering effort
3926
+ # and it is not yet a priority. RFC here:
3927
+ # https://github.com/vllm-project/vllm/issues/14703
3928
+
3929
+ if is_torch_equal_or_newer("2.6"):
3930
+ KEY = 'enable_auto_functionalized_v2'
3931
+ if KEY not in self.inductor_compile_config:
3932
+ self.inductor_compile_config[KEY] = False
3933
+
3934
+ for k, v in self.inductor_passes.items():
3935
+ if not isinstance(v, str):
3936
+ assert callable(v), (
3937
+ f"pass {k} should be callable or a qualified name")
3938
+ self.inductor_compile_config[k] = v if isinstance(
3939
+ v, InductorPass) else CallableInductorPass(v)
3940
+ continue
3941
+
3942
+ # resolve function from qualified name
3943
+ names = v.split(".")
3944
+ module = ".".join(names[:-1])
3945
+ func_name = names[-1]
3946
+ func = __import__(module).__dict__[func_name]
3947
+ self.inductor_compile_config[k] = func if isinstance(
3948
+ func, InductorPass) else CallableInductorPass(func)
3949
+
3950
+ if isinstance(self.pass_config, dict):
3951
+ self.pass_config = PassConfig(**self.pass_config)
3952
+
3953
+ def init_backend(self, vllm_config: "VllmConfig") -> Union[str, Callable]:
3954
+ if self.level == CompilationLevel.NO_COMPILATION:
3955
+ raise ValueError("No compilation level is set.")
3956
+
3957
+ from torch._dynamo.backends.registry import list_backends
3958
+ torch_backends = list_backends(exclude_tags=tuple())
3959
+ if self.level in [
3960
+ CompilationLevel.DYNAMO_AS_IS, CompilationLevel.DYNAMO_ONCE
3961
+ ]:
3962
+ if self.backend == "":
3963
+ return "eager"
3964
+ if self.backend in torch_backends:
3965
+ return self.backend
3966
+ return resolve_obj_by_qualname(self.backend)
3967
+
3968
+ # TODO: pass user-specified backend to piecewise compilation
3969
+ # merge with the config use_inductor
3970
+ assert self.level == CompilationLevel.PIECEWISE
3971
+
3972
+ from vllm.compilation.backends import VllmBackend
3973
+ return VllmBackend(vllm_config)
3974
+
3975
+ def init_with_cudagraph_sizes(self,
3976
+ cudagraph_capture_sizes: list[int]) -> None:
3977
+ """To complete the initialization of config,
3978
+ we need to know the cudagraph sizes."""
3979
+
3980
+ if self.cudagraph_capture_sizes is None:
3981
+ self.cudagraph_capture_sizes = cudagraph_capture_sizes
3982
+ else:
3983
+ # de-duplicate the sizes provided by the config
3984
+ dedup_sizes = list(set(self.cudagraph_capture_sizes))
3985
+ if len(dedup_sizes) < len(self.cudagraph_capture_sizes):
3986
+ logger.info(("cudagraph sizes specified by model runner"
3987
+ " %s is overridden by config %s"),
3988
+ cudagraph_capture_sizes, dedup_sizes)
3989
+ self.cudagraph_capture_sizes = dedup_sizes
3990
+
3991
+ computed_compile_sizes = []
3992
+ if self.compile_sizes is not None:
3993
+ # de-duplicate the sizes provided by the config
3994
+ self.compile_sizes = list(set(self.compile_sizes))
3995
+ for x in self.compile_sizes:
3996
+ if isinstance(x, str):
3997
+ assert x == "cudagraph_capture_sizes", \
3998
+ "Unrecognized size type in compile_sizes, " \
3999
+ f"expect 'cudagraph_capture_sizes', got {x}"
4000
+ computed_compile_sizes.extend(self.cudagraph_capture_sizes)
4001
+ else:
4002
+ assert isinstance(x, int)
4003
+ computed_compile_sizes.append(x)
4004
+ self.compile_sizes = computed_compile_sizes # type: ignore
4005
+
4006
+ # sort to make sure cudagraph capture sizes are in descending order
4007
+ self.cudagraph_capture_sizes.sort(reverse=True)
4008
+ self.max_capture_size = self.cudagraph_capture_sizes[
4009
+ 0] if self.cudagraph_capture_sizes else 0
4010
+
4011
+ # pre-compute the mapping from batch size to padded graph size
4012
+ self.bs_to_padded_graph_size = [
4013
+ 0 for i in range(self.max_capture_size + 1)
4014
+ ]
4015
+ for end, start in zip(self.cudagraph_capture_sizes,
4016
+ self.cudagraph_capture_sizes[1:] + [0]):
4017
+ for bs in range(start, end):
4018
+ if bs == start:
4019
+ self.bs_to_padded_graph_size[bs] = start
4020
+ else:
4021
+ self.bs_to_padded_graph_size[bs] = end
4022
+ self.bs_to_padded_graph_size[
4023
+ self.max_capture_size] = self.max_capture_size
4024
+
4025
+ def set_splitting_ops_for_v1(self):
4026
+ # NOTE: this function needs to be called
4027
+ if self.splitting_ops and self.full_cuda_graph:
4028
+ raise ValueError("full_cuda_graph cannot be used together with "
4029
+ "splitting_ops, as Full CUDA graph will override "
4030
+ f"the splitting_ops: {self.splitting_ops}")
4031
+
4032
+ if not self.splitting_ops:
4033
+ self.splitting_ops = [] if self.full_cuda_graph else [
4034
+ "vllm.unified_attention",
4035
+ "vllm.unified_attention_with_output",
4036
+ ]
4037
+
4038
+
4039
+ @config
4040
+ @dataclass
4041
+ class VllmConfig:
4042
+ """Dataclass which contains all vllm-related configuration. This
4043
+ simplifies passing around the distinct configurations in the codebase.
4044
+ """
4045
+
4046
+ # TODO: use default_factory once default constructing ModelConfig doesn't
4047
+ # try to download a model
4048
+ model_config: ModelConfig = None # type: ignore
4049
+ """Model configuration."""
4050
+ cache_config: CacheConfig = field(default_factory=CacheConfig)
4051
+ """Cache configuration."""
4052
+ parallel_config: ParallelConfig = field(default_factory=ParallelConfig)
4053
+ """Parallel configuration."""
4054
+ scheduler_config: SchedulerConfig = field(default_factory=SchedulerConfig)
4055
+ """Scheduler configuration."""
4056
+ device_config: DeviceConfig = field(default_factory=DeviceConfig)
4057
+ """Device configuration."""
4058
+ load_config: LoadConfig = field(default_factory=LoadConfig)
4059
+ """Load configuration."""
4060
+ lora_config: Optional[LoRAConfig] = None
4061
+ """LoRA configuration."""
4062
+ speculative_config: Optional[SpeculativeConfig] = None
4063
+ """Speculative decoding configuration."""
4064
+ decoding_config: DecodingConfig = field(default_factory=DecodingConfig)
4065
+ """Decoding configuration."""
4066
+ observability_config: Optional[ObservabilityConfig] = None
4067
+ """Observability configuration."""
4068
+ prompt_adapter_config: Optional[PromptAdapterConfig] = None
4069
+ """Prompt adapter configuration."""
4070
+ quant_config: Optional[QuantizationConfig] = None
4071
+ """Quantization configuration."""
4072
+ compilation_config: CompilationConfig = field(
4073
+ default_factory=CompilationConfig)
4074
+ """`torch.compile` configuration for the model.
4075
+
4076
+ When it is a number (0, 1, 2, 3), it will be interpreted as the
4077
+ optimization level.
4078
+
4079
+ NOTE: level 0 is the default level without any optimization. level 1 and 2
4080
+ are for internal testing only. level 3 is the recommended level for
4081
+ production.
4082
+
4083
+ Following the convention of traditional compilers, using `-O` without space
4084
+ is also supported. `-O3` is equivalent to `-O 3`.
4085
+
4086
+ You can specify the full compilation config like so:
4087
+ `{"level": 3, "cudagraph_capture_sizes": [1, 2, 4, 8]}`
4088
+ """
4089
+ kv_transfer_config: Optional[KVTransferConfig] = None
4090
+ """The configurations for distributed KV cache transfer."""
4091
+ kv_events_config: Optional[KVEventsConfig] = None
4092
+ """The configurations for event publishing."""
4093
+ # some opaque config, only used to provide additional information
4094
+ # for the hash computation, mainly used for testing, debugging or out of
4095
+ # tree config registration.
4096
+ additional_config: Union[dict, SupportsHash] = field(default_factory=dict)
4097
+ """Additional config for specified platform. Different platforms may
4098
+ support different configs. Make sure the configs are valid for the platform
4099
+ you are using. Contents must be hashable."""
4100
+ instance_id: str = ""
4101
+ """The ID of the vLLM instance."""
4102
+
4103
+ def compute_hash(self) -> str:
4104
+ """
4105
+ WARNING: Whenever a new field is added to this config,
4106
+ ensure that it is included in the factors list if
4107
+ it affects the computation graph.
4108
+
4109
+ Provide a hash that uniquely identifies all the configs
4110
+ that affect the structure of the computation
4111
+ graph from input ids/embeddings to the final hidden states,
4112
+ excluding anything before input ids/embeddings and after
4113
+ the final hidden states.
4114
+ """
4115
+ factors: list[Any] = []
4116
+
4117
+ # summarize vllm config
4118
+ vllm_factors: list[Any] = []
4119
+ from vllm import __version__
4120
+ vllm_factors.append(__version__)
4121
+ vllm_factors.append(envs.VLLM_USE_V1)
4122
+ if self.model_config:
4123
+ vllm_factors.append(self.model_config.compute_hash())
4124
+ else:
4125
+ vllm_factors.append("None")
4126
+ if self.cache_config:
4127
+ vllm_factors.append(self.cache_config.compute_hash())
4128
+ else:
4129
+ vllm_factors.append("None")
4130
+ if self.parallel_config:
4131
+ vllm_factors.append(self.parallel_config.compute_hash())
4132
+ else:
4133
+ vllm_factors.append("None")
4134
+ if self.scheduler_config:
4135
+ vllm_factors.append(self.scheduler_config.compute_hash())
4136
+ else:
4137
+ vllm_factors.append("None")
4138
+ if self.device_config:
4139
+ vllm_factors.append(self.device_config.compute_hash())
4140
+ else:
4141
+ vllm_factors.append("None")
4142
+ if self.load_config:
4143
+ vllm_factors.append(self.load_config.compute_hash())
4144
+ else:
4145
+ vllm_factors.append("None")
4146
+ if self.lora_config:
4147
+ vllm_factors.append(self.lora_config.compute_hash())
4148
+ # LoRA creates static buffers based on max_num_batched_tokens.
4149
+ # The tensor sizes and strides get captured in the torch.compile
4150
+ # graph explicitly.
4151
+ vllm_factors.append(
4152
+ str(self.scheduler_config.max_num_batched_tokens))
4153
+ else:
4154
+ vllm_factors.append("None")
4155
+ if self.speculative_config:
4156
+ vllm_factors.append(self.speculative_config.compute_hash())
4157
+ else:
4158
+ vllm_factors.append("None")
4159
+ if self.decoding_config:
4160
+ vllm_factors.append(self.decoding_config.compute_hash())
4161
+ else:
4162
+ vllm_factors.append("None")
4163
+ if self.observability_config:
4164
+ vllm_factors.append(self.observability_config.compute_hash())
4165
+ else:
4166
+ vllm_factors.append("None")
4167
+ if self.prompt_adapter_config:
4168
+ vllm_factors.append(self.prompt_adapter_config.compute_hash())
4169
+ else:
4170
+ vllm_factors.append("None")
4171
+ if self.quant_config:
4172
+ pass # should be captured by model_config.quantization
4173
+ if self.compilation_config:
4174
+ vllm_factors.append(self.compilation_config.compute_hash())
4175
+ else:
4176
+ vllm_factors.append("None")
4177
+ if self.kv_transfer_config:
4178
+ vllm_factors.append(self.kv_transfer_config.compute_hash())
4179
+ else:
4180
+ vllm_factors.append("None")
4181
+ if self.additional_config:
4182
+ if isinstance(additional_config := self.additional_config, dict):
4183
+ additional_config_hash = hashlib.md5(
4184
+ json.dumps(additional_config, sort_keys=True).encode(),
4185
+ usedforsecurity=False,
4186
+ ).hexdigest()
4187
+ else:
4188
+ additional_config_hash = additional_config.compute_hash()
4189
+ vllm_factors.append(additional_config_hash)
4190
+ else:
4191
+ vllm_factors.append("None")
4192
+ factors.append(vllm_factors)
4193
+
4194
+ hash_str = hashlib.md5(str(factors).encode(),
4195
+ usedforsecurity=False).hexdigest()[:10]
4196
+ return hash_str
4197
+
4198
+ def pad_for_cudagraph(self, batch_size: int) -> int:
4199
+ # if batch_size > self.compilation_config.max_capture_size,
4200
+ # it should raise an IndexError.
4201
+ # the caller should make sure the batch_size is within the range,
4202
+ # i.e., batch_size <= self.compilation_config.max_capture_size
4203
+ return self.compilation_config.bs_to_padded_graph_size[batch_size]
4204
+
4205
+ @staticmethod
4206
+ def _get_quantization_config(
4207
+ model_config: ModelConfig,
4208
+ load_config: LoadConfig) -> Optional[QuantizationConfig]:
4209
+ """Get the quantization config."""
4210
+ from vllm.platforms import current_platform
4211
+ if model_config.quantization is not None:
4212
+ from vllm.model_executor.model_loader.weight_utils import (
4213
+ get_quant_config)
4214
+ quant_config = get_quant_config(model_config, load_config)
4215
+ capability_tuple = current_platform.get_device_capability()
4216
+
4217
+ if capability_tuple is not None:
4218
+ capability = capability_tuple.to_int()
4219
+ if capability < quant_config.get_min_capability():
4220
+ raise ValueError(
4221
+ f"The quantization method {model_config.quantization} "
4222
+ "is not supported for the current GPU. Minimum "
4223
+ f"capability: {quant_config.get_min_capability()}. "
4224
+ f"Current capability: {capability}.")
4225
+ supported_dtypes = quant_config.get_supported_act_dtypes()
4226
+ if model_config.dtype not in supported_dtypes:
4227
+ raise ValueError(
4228
+ f"{model_config.dtype} is not supported for quantization "
4229
+ f"method {model_config.quantization}. Supported dtypes: "
4230
+ f"{supported_dtypes}")
4231
+ return quant_config
4232
+ return None
4233
+
4234
+ @staticmethod
4235
+ def get_quantization_config(
4236
+ model_config: ModelConfig,
4237
+ load_config: LoadConfig) -> Optional[QuantizationConfig]:
4238
+ import copy
4239
+
4240
+ # For some reason, the _ version of this modifies the model_config
4241
+ # object, so using deepcopy to avoid this problem.
4242
+ return VllmConfig._get_quantization_config(copy.deepcopy(model_config),
4243
+ load_config)
4244
+
4245
+ def with_hf_config(
4246
+ self,
4247
+ hf_config: PretrainedConfig,
4248
+ architectures: Optional[list[str]] = None,
4249
+ ) -> "VllmConfig":
4250
+ if architectures is not None:
4251
+ hf_config = copy.deepcopy(hf_config)
4252
+ hf_config.architectures = architectures
4253
+
4254
+ model_config = copy.deepcopy(self.model_config)
4255
+ model_config.hf_config = hf_config
4256
+
4257
+ return replace(self, model_config=model_config)
4258
+
4259
+ def __post_init__(self):
4260
+ """Verify configs are valid & consistent with each other.
4261
+ """
4262
+ if self.model_config is not None:
4263
+ self.model_config.verify_async_output_proc(self.parallel_config,
4264
+ self.speculative_config,
4265
+ self.device_config)
4266
+ self.model_config.verify_with_parallel_config(self.parallel_config)
4267
+ self.model_config.verify_dual_chunk_attention_config(
4268
+ self.load_config)
4269
+
4270
+ if self.cache_config is not None:
4271
+ self.cache_config.verify_with_parallel_config(self.parallel_config)
4272
+
4273
+ if self.lora_config:
4274
+ self.lora_config.verify_with_cache_config(self.cache_config)
4275
+ self.lora_config.verify_with_model_config(self.model_config)
4276
+ self.lora_config.verify_lora_support()
4277
+ if self.prompt_adapter_config:
4278
+ self.prompt_adapter_config.verify_with_model_config(
4279
+ self.model_config)
4280
+
4281
+ if self.quant_config is None and \
4282
+ self.model_config is not None and self.load_config is not None:
4283
+ self.quant_config = VllmConfig._get_quantization_config(
4284
+ self.model_config, self.load_config)
4285
+
4286
+ from vllm.platforms import current_platform
4287
+ if self.scheduler_config is not None and \
4288
+ self.model_config is not None and \
4289
+ self.scheduler_config.chunked_prefill_enabled and \
4290
+ self.model_config.dtype == torch.float32 and \
4291
+ current_platform.get_device_capability() == (7, 5):
4292
+ logger.warning_once(
4293
+ "Turing devices tensor cores do not support float32 matmul. "
4294
+ "To workaround this limitation, vLLM will set 'ieee' input "
4295
+ "precision for chunked prefill triton kernels.")
4296
+
4297
+ if self.compilation_config is None:
4298
+ self.compilation_config = CompilationConfig()
4299
+
4300
+ # async tp is built on top of sequence parallelism
4301
+ # and requires it to be enabled.
4302
+ if self.compilation_config.pass_config.enable_async_tp:
4303
+ self.compilation_config.pass_config.enable_sequence_parallelism = \
4304
+ True
4305
+ if self.compilation_config.pass_config.enable_sequence_parallelism:
4306
+ self.compilation_config.custom_ops.append("+rms_norm")
4307
+ if envs.VLLM_USE_V1 and self.model_config is not None and \
4308
+ not self.model_config.enforce_eager:
4309
+ # NOTE(woosuk): Currently, we use inductor because the piecewise
4310
+ # CUDA graphs do not work properly with the custom CUDA kernels.
4311
+ # FIXME(woosuk): Disable inductor to reduce the compilation time
4312
+ # and avoid any potential issues with the inductor.
4313
+ # FIXME(rob): Add function to set all of these.
4314
+ if not self.compilation_config.custom_ops:
4315
+ self.compilation_config.custom_ops = ["none"]
4316
+ self.compilation_config.use_cudagraph = True
4317
+ self.compilation_config.use_inductor = True
4318
+ self.compilation_config.cudagraph_num_of_warmups = 1
4319
+ self.compilation_config.pass_config.enable_fusion = False
4320
+ self.compilation_config.pass_config.enable_noop = False
4321
+ self.compilation_config.level = CompilationLevel.PIECEWISE
4322
+ self.compilation_config.set_splitting_ops_for_v1()
4323
+
4324
+ self._set_cudagraph_sizes()
4325
+
4326
+ if self.cache_config is not None and \
4327
+ self.cache_config.cpu_offload_gb > 0 and \
4328
+ self.compilation_config.level != CompilationLevel.NO_COMPILATION \
4329
+ and not envs.VLLM_USE_V1:
4330
+ logger.warning(
4331
+ "CPU offload is not supported with `torch.compile` in v0 yet."
4332
+ " Disabling `torch.compile`.")
4333
+ self.compilation_config.level = CompilationLevel.NO_COMPILATION
4334
+
4335
+ if ((not envs.VLLM_USE_V1) and self.lora_config is not None
4336
+ and self.compilation_config.level
4337
+ != CompilationLevel.NO_COMPILATION):
4338
+ logger.warning(
4339
+ "LoRA for V0 is not supported with `torch.compile` yet. "
4340
+ "Disabling `torch.compile`.")
4341
+ self.compilation_config.level = CompilationLevel.NO_COMPILATION
4342
+
4343
+ if self.compilation_config.full_cuda_graph and \
4344
+ not self.model_config.disable_cascade_attn:
4345
+ logger.warning_once(
4346
+ "full_cuda_graph is not supported with "
4347
+ "cascade attention. Disabling cascade attention.")
4348
+ self.model_config.disable_cascade_attn = True
4349
+ if self.cache_config is not None:
4350
+ self.cache_config.enable_prefix_caching = False
4351
+
4352
+ if (self.kv_events_config
4353
+ and self.kv_events_config.enable_kv_cache_events
4354
+ and not self.cache_config.enable_prefix_caching):
4355
+ logger.warning(
4356
+ "KV cache events are on, but prefix caching is not enabled."
4357
+ "Use --enable-prefix-caching to enable.")
4358
+ if (self.kv_events_config and self.kv_events_config.publisher != "null"
4359
+ and not self.kv_events_config.enable_kv_cache_events):
4360
+ logger.warning("KV cache events are disabled,"
4361
+ "but the scheduler is configured to publish them."
4362
+ "Modify KVEventsConfig.enable_kv_cache_events"
4363
+ "to True to enable.")
4364
+ current_platform.check_and_update_config(self)
4365
+
4366
+ if not self.instance_id:
4367
+ self.instance_id = random_uuid()[:5]
4368
+
4369
+ def update_sizes_for_sequence_parallelism(self,
4370
+ possible_sizes: list) -> list:
4371
+ # remove the sizes that not multiple of tp_size when
4372
+ # enable sequence parallelism
4373
+ removed_sizes = [
4374
+ size for size in possible_sizes
4375
+ if size % self.parallel_config.tensor_parallel_size != 0
4376
+ ]
4377
+ if removed_sizes:
4378
+ logger.warning(
4379
+ "Batch sizes %s are removed because they are not "
4380
+ "multiple of tp_size %d when "
4381
+ "sequence parallelism is enabled", removed_sizes,
4382
+ self.parallel_config.tensor_parallel_size)
4383
+
4384
+ return [
4385
+ size for size in possible_sizes
4386
+ if size % self.parallel_config.tensor_parallel_size == 0
4387
+ ]
4388
+
4389
+ def _set_cudagraph_sizes(self):
4390
+ """
4391
+ cudagraph batchsize padding logic:
4392
+
4393
+ `[1, 2, 4] + [8 * i for i in range(1, 1025)]` is a list of all possible
4394
+ batch sizes that cudagraph will capture.
4395
+
4396
+ Depending on the engine's configuration of `max_num_seqs`, the
4397
+ candidate batch sizes to capture cudagraph will shrink to the subset
4398
+ which just cover the range of `[1, max_num_seqs]`. In the common case,
4399
+ `max_num_seqs` is 256, and the cudagraph batch sizes will be
4400
+ `[1, 2, 4, 8, 16, 24, 32, 40, ..., 256]`.
4401
+
4402
+ However, if users specify the cudagraph capture sizes through
4403
+ compilation config, we will use the specified sizes instead.
4404
+
4405
+ In the end, `vllm_config.compilation_config.cudagraph_capture_sizes`
4406
+ will be the final sizes to capture cudagraph (in descending order).
4407
+
4408
+ During runtime, if batchsize is larger than
4409
+ `vllm_config.compilation_config.cudagraph_capture_sizes`,
4410
+ no cudagraph will be used.
4411
+ If the batch size is no larger than
4412
+ `vllm_config.compilation_config.cudagraph_capture_sizes`,
4413
+ we can quickly find the padded graph size for a given batch size by
4414
+ looking up `vllm_config.compilation_config.bs_to_padded_graph_size`.
4415
+ """
4416
+
4417
+ # calculate the default `batch_size_capture_list`
4418
+ if not envs.VLLM_USE_V1:
4419
+ batch_size_capture_list = []
4420
+ max_batchsize_to_capture = 0
4421
+ if self.scheduler_config is not None and \
4422
+ self.model_config is not None and \
4423
+ not self.model_config.enforce_eager:
4424
+
4425
+ possible_sizes = [1, 2, 4] + [8 * i for i in range(1, 1025)]
4426
+ if self.parallel_config.tensor_parallel_size > 1 and \
4427
+ self.compilation_config.pass_config.enable_sequence_parallelism:
4428
+ possible_sizes = self.update_sizes_for_sequence_parallelism(
4429
+ possible_sizes)
4430
+
4431
+ # find the minimum size that is larger than max_num_seqs,
4432
+ # which then becomes the max_batchsize_to_capture
4433
+ larger_sizes = [
4434
+ x for x in possible_sizes
4435
+ if x >= self.scheduler_config.max_num_seqs
4436
+ ]
4437
+ if larger_sizes:
4438
+ max_batchsize_to_capture = larger_sizes[0]
4439
+ else:
4440
+ max_batchsize_to_capture = possible_sizes[-1]
4441
+
4442
+ # filter out the sizes that are
4443
+ # larger than max_batchsize_to_capture
4444
+ batch_size_capture_list = [
4445
+ size for size in possible_sizes
4446
+ if size <= max_batchsize_to_capture
4447
+ ]
4448
+ else:
4449
+ batch_size_capture_list = []
4450
+ if self.model_config is not None and \
4451
+ not self.model_config.enforce_eager:
4452
+ cuda_graph_sizes = self.scheduler_config.cuda_graph_sizes
4453
+ if len(cuda_graph_sizes) == 1:
4454
+ batch_size_capture_list = [1, 2, 4] + [
4455
+ i for i in range(8, cuda_graph_sizes[0] + 1, 8)
4456
+ ]
4457
+ elif len(cuda_graph_sizes) > 1:
4458
+ batch_size_capture_list = sorted(cuda_graph_sizes)
4459
+ else:
4460
+ raise TypeError(f"Invalid value for {cuda_graph_sizes=}.")
4461
+ if self.parallel_config.tensor_parallel_size > 1 and \
4462
+ self.compilation_config.pass_config.enable_sequence_parallelism:
4463
+ batch_size_capture_list = \
4464
+ self.update_sizes_for_sequence_parallelism(batch_size_capture_list)
4465
+ max_num_tokens = self.scheduler_config.max_num_batched_tokens
4466
+ batch_size_capture_list = [
4467
+ size for size in batch_size_capture_list
4468
+ if size <= max_num_tokens
4469
+ ]
4470
+
4471
+ self.compilation_config.init_with_cudagraph_sizes(
4472
+ batch_size_capture_list)
4473
+
4474
+ def __str__(self):
4475
+ return (
4476
+ f"model={self.model_config.model!r},"
4477
+ f" speculative_config={self.speculative_config!r},"
4478
+ f" tokenizer={self.model_config.tokenizer!r}, "
4479
+ f"skip_tokenizer_init={self.model_config.skip_tokenizer_init},"
4480
+ f" tokenizer_mode={self.model_config.tokenizer_mode}, "
4481
+ f"revision={self.model_config.revision}, "
4482
+ f"override_neuron_config={self.model_config.override_neuron_config},"
4483
+ f" tokenizer_revision={self.model_config.tokenizer_revision}, "
4484
+ f"trust_remote_code={self.model_config.trust_remote_code}, "
4485
+ f"dtype={self.model_config.dtype}, "
4486
+ f"max_seq_len={self.model_config.max_model_len},"
4487
+ f" download_dir={self.load_config.download_dir!r}, "
4488
+ f"load_format={self.load_config.load_format}, "
4489
+ f"tensor_parallel_size={self.parallel_config.tensor_parallel_size},"
4490
+ f" pipeline_parallel_size={self.parallel_config.pipeline_parallel_size}, " # noqa
4491
+ f"disable_custom_all_reduce={self.parallel_config.disable_custom_all_reduce}, " # noqa
4492
+ f"quantization={self.model_config.quantization}, "
4493
+ f"enforce_eager={self.model_config.enforce_eager}, "
4494
+ f"kv_cache_dtype={self.cache_config.cache_dtype}, "
4495
+ f" device_config={self.device_config.device}, "
4496
+ f"decoding_config={self.decoding_config!r}, "
4497
+ f"observability_config={self.observability_config!r}, "
4498
+ f"seed={self.model_config.seed}, "
4499
+ f"served_model_name={self.model_config.served_model_name}, "
4500
+ f"num_scheduler_steps={self.scheduler_config.num_scheduler_steps}, "
4501
+ f"multi_step_stream_outputs={self.scheduler_config.multi_step_stream_outputs}, " # noqa
4502
+ f"enable_prefix_caching={self.cache_config.enable_prefix_caching}, "
4503
+ f"chunked_prefill_enabled={self.scheduler_config.chunked_prefill_enabled}, " # noqa
4504
+ f"use_async_output_proc={self.model_config.use_async_output_proc}, "
4505
+ f"pooler_config={self.model_config.pooler_config!r}, "
4506
+ f"compilation_config={self.compilation_config!r}")
4507
+
4508
+
4509
+ _current_vllm_config: Optional[VllmConfig] = None
4510
+
4511
+
4512
+ @contextmanager
4513
+ def set_current_vllm_config(vllm_config: VllmConfig, check_compile=False):
4514
+ """
4515
+ Temporarily set the current vLLM config.
4516
+ Used during model initialization.
4517
+ We save the current vLLM config in a global variable,
4518
+ so that all modules can access it, e.g. custom ops
4519
+ can access the vLLM config to determine how to dispatch.
4520
+ """
4521
+ global _current_vllm_config
4522
+ old_vllm_config = _current_vllm_config
4523
+ from vllm.compilation.counter import compilation_counter
4524
+ num_models_seen = compilation_counter.num_models_seen
4525
+ try:
4526
+ _current_vllm_config = vllm_config
4527
+ yield
4528
+ except Exception:
4529
+ raise
4530
+ else:
4531
+ logger.debug("enabled custom ops: %s",
4532
+ vllm_config.compilation_config.enabled_custom_ops)
4533
+ logger.debug("disabled custom ops: %s",
4534
+ vllm_config.compilation_config.disabled_custom_ops)
4535
+ if check_compile and \
4536
+ vllm_config.compilation_config.level == CompilationLevel.PIECEWISE \
4537
+ and compilation_counter.num_models_seen == num_models_seen:
4538
+ # If the model supports compilation,
4539
+ # compilation_counter.num_models_seen should be increased
4540
+ # by at least 1.
4541
+ # If it is not increased, it means the model does not support
4542
+ # compilation (does not have @support_torch_compile decorator).
4543
+ logger.warning(
4544
+ "`torch.compile` is turned on, but the model %s"
4545
+ " does not support it. Please open an issue on GitHub"
4546
+ " if you want it to be supported.",
4547
+ vllm_config.model_config.model)
4548
+ finally:
4549
+ _current_vllm_config = old_vllm_config
4550
+
4551
+
4552
+ def get_current_vllm_config() -> VllmConfig:
4553
+ if _current_vllm_config is None:
4554
+ # in ci, usually when we test custom ops/modules directly,
4555
+ # we don't set the vllm config. In that case, we set a default
4556
+ # config.
4557
+ logger.warning("Current vLLM config is not set.")
4558
+ from vllm.config import VllmConfig
4559
+ return VllmConfig()
4560
+ return _current_vllm_config
4561
+
4562
+
4563
+ def contains_object_print(text):
4564
+ """
4565
+ Check if the text looks like a printed Python object, e.g.
4566
+ contains any substring matching the pattern: "at 0xFFFFFFF>"
4567
+ We match against 0x followed by 2-16 hex chars (there's
4568
+ a max of 16 on a 64 bit system).
4569
+
4570
+ Args:
4571
+ text (str): The text to check
4572
+
4573
+ Returns:
4574
+ result (bool): `True` if a match is found, `False` otherwise.
4575
+ """
4576
+ pattern = r'at 0x[a-fA-F0-9]{2,16}>'
4577
+ match = re.search(pattern, text)
4578
+ return match is not None
4579
+
4580
+
4581
+ def assert_hashable(text):
4582
+ if not contains_object_print(text):
4583
+ return True
4584
+ raise AssertionError(
4585
+ f"vLLM tried to hash some configs that may have Python objects ids "
4586
+ f"in them. This is a bug, please file an issue. "
4587
+ f"Text being hashed: {text}")
4588
+
4589
+
4590
+ T = TypeVar("T")
4591
+
4592
+
4593
+ def get_layers_from_vllm_config(vllm_config: VllmConfig,
4594
+ layer_type: type[T]) -> dict[str, T]:
4595
+ return {
4596
+ layer_name: layer
4597
+ for layer_name, layer in
4598
+ vllm_config.compilation_config.static_forward_context.items()
4599
+ if isinstance(layer, layer_type)
4600
+ }