vllm-cpu 0.9.2.post2__cp311-cp311-manylinux_2_17_aarch64.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 (1236) hide show
  1. vllm/_C.abi3.so +0 -0
  2. vllm/__init__.py +214 -0
  3. vllm/_custom_ops.py +1915 -0
  4. vllm/_ipex_ops.py +350 -0
  5. vllm/_version.py +34 -0
  6. vllm/adapter_commons/__init__.py +0 -0
  7. vllm/adapter_commons/layers.py +16 -0
  8. vllm/adapter_commons/models.py +106 -0
  9. vllm/adapter_commons/request.py +26 -0
  10. vllm/adapter_commons/utils.py +93 -0
  11. vllm/adapter_commons/worker_manager.py +39 -0
  12. vllm/assets/__init__.py +0 -0
  13. vllm/assets/audio.py +45 -0
  14. vllm/assets/base.py +41 -0
  15. vllm/assets/image.py +34 -0
  16. vllm/assets/video.py +139 -0
  17. vllm/attention/__init__.py +20 -0
  18. vllm/attention/backends/__init__.py +0 -0
  19. vllm/attention/backends/abstract.py +325 -0
  20. vllm/attention/backends/blocksparse_attn.py +465 -0
  21. vllm/attention/backends/cpu_mla.py +307 -0
  22. vllm/attention/backends/dual_chunk_flash_attn.py +1506 -0
  23. vllm/attention/backends/flash_attn.py +1008 -0
  24. vllm/attention/backends/flashinfer.py +1107 -0
  25. vllm/attention/backends/flashmla.py +244 -0
  26. vllm/attention/backends/hpu_attn.py +318 -0
  27. vllm/attention/backends/ipex_attn.py +403 -0
  28. vllm/attention/backends/mla/__init__.py +0 -0
  29. vllm/attention/backends/mla/common.py +1391 -0
  30. vllm/attention/backends/pallas.py +356 -0
  31. vllm/attention/backends/placeholder_attn.py +400 -0
  32. vllm/attention/backends/rocm_aiter_mla.py +435 -0
  33. vllm/attention/backends/rocm_flash_attn.py +1015 -0
  34. vllm/attention/backends/torch_sdpa.py +707 -0
  35. vllm/attention/backends/triton_mla.py +115 -0
  36. vllm/attention/backends/utils.py +610 -0
  37. vllm/attention/backends/xformers.py +807 -0
  38. vllm/attention/layer.py +481 -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 +433 -0
  42. vllm/attention/ops/blocksparse_attention/interface.py +239 -0
  43. vllm/attention/ops/blocksparse_attention/utils.py +246 -0
  44. vllm/attention/ops/chunked_prefill_paged_decode.py +368 -0
  45. vllm/attention/ops/flashmla.py +116 -0
  46. vllm/attention/ops/hpu_paged_attn.py +88 -0
  47. vllm/attention/ops/ipex_attn.py +195 -0
  48. vllm/attention/ops/merge_attn_states.py +43 -0
  49. vllm/attention/ops/nki_flash_attn.py +903 -0
  50. vllm/attention/ops/paged_attn.py +256 -0
  51. vllm/attention/ops/pallas_kv_cache_update.py +120 -0
  52. vllm/attention/ops/prefix_prefill.py +902 -0
  53. vllm/attention/ops/rocm_aiter_mla.py +100 -0
  54. vllm/attention/ops/rocm_aiter_paged_attn.py +102 -0
  55. vllm/attention/ops/triton_decode_attention.py +674 -0
  56. vllm/attention/ops/triton_flash_attention.py +984 -0
  57. vllm/attention/ops/triton_merge_attn_states.py +97 -0
  58. vllm/attention/ops/triton_unified_attention.py +738 -0
  59. vllm/attention/selector.py +214 -0
  60. vllm/attention/utils/fa_utils.py +72 -0
  61. vllm/beam_search.py +87 -0
  62. vllm/benchmarks/__init__.py +0 -0
  63. vllm/benchmarks/datasets.py +1441 -0
  64. vllm/benchmarks/endpoint_request_func.py +393 -0
  65. vllm/benchmarks/latency.py +168 -0
  66. vllm/benchmarks/serve.py +1063 -0
  67. vllm/benchmarks/throughput.py +609 -0
  68. vllm/benchmarks/utils.py +70 -0
  69. vllm/collect_env.py +820 -0
  70. vllm/compilation/__init__.py +0 -0
  71. vllm/compilation/activation_quant_fusion.py +89 -0
  72. vllm/compilation/backends.py +610 -0
  73. vllm/compilation/base_piecewise_backend.py +72 -0
  74. vllm/compilation/collective_fusion.py +127 -0
  75. vllm/compilation/compiler_interface.py +564 -0
  76. vllm/compilation/counter.py +41 -0
  77. vllm/compilation/cuda_piecewise_backend.py +218 -0
  78. vllm/compilation/decorators.py +250 -0
  79. vllm/compilation/fix_functionalization.py +191 -0
  80. vllm/compilation/fusion.py +645 -0
  81. vllm/compilation/fusion_attn.py +166 -0
  82. vllm/compilation/fx_utils.py +84 -0
  83. vllm/compilation/inductor_pass.py +115 -0
  84. vllm/compilation/monitor.py +39 -0
  85. vllm/compilation/multi_output_match.py +109 -0
  86. vllm/compilation/noop_elimination.py +165 -0
  87. vllm/compilation/pass_manager.py +82 -0
  88. vllm/compilation/sequence_parallelism.py +482 -0
  89. vllm/compilation/torch25_custom_graph_pass.py +42 -0
  90. vllm/compilation/vllm_inductor_pass.py +70 -0
  91. vllm/compilation/wrapper.py +135 -0
  92. vllm/config.py +4913 -0
  93. vllm/connections.py +174 -0
  94. vllm/core/__init__.py +0 -0
  95. vllm/core/block/__init__.py +0 -0
  96. vllm/core/block/block_table.py +399 -0
  97. vllm/core/block/common.py +371 -0
  98. vllm/core/block/cpu_gpu_block_allocator.py +441 -0
  99. vllm/core/block/interfaces.py +319 -0
  100. vllm/core/block/naive_block.py +466 -0
  101. vllm/core/block/prefix_caching_block.py +1135 -0
  102. vllm/core/block/utils.py +28 -0
  103. vllm/core/block_manager.py +525 -0
  104. vllm/core/evictor.py +157 -0
  105. vllm/core/interfaces.py +139 -0
  106. vllm/core/placeholder_block_space_manager.py +103 -0
  107. vllm/core/scheduler.py +2126 -0
  108. vllm/device_allocator/__init__.py +0 -0
  109. vllm/device_allocator/cumem.py +281 -0
  110. vllm/distributed/__init__.py +6 -0
  111. vllm/distributed/communication_op.py +41 -0
  112. vllm/distributed/device_communicators/__init__.py +0 -0
  113. vllm/distributed/device_communicators/all2all.py +264 -0
  114. vllm/distributed/device_communicators/base_device_communicator.py +260 -0
  115. vllm/distributed/device_communicators/cpu_communicator.py +145 -0
  116. vllm/distributed/device_communicators/cuda_communicator.py +194 -0
  117. vllm/distributed/device_communicators/cuda_wrapper.py +180 -0
  118. vllm/distributed/device_communicators/custom_all_reduce.py +304 -0
  119. vllm/distributed/device_communicators/custom_all_reduce_utils.py +259 -0
  120. vllm/distributed/device_communicators/hpu_communicator.py +46 -0
  121. vllm/distributed/device_communicators/neuron_communicator.py +20 -0
  122. vllm/distributed/device_communicators/pynccl.py +218 -0
  123. vllm/distributed/device_communicators/pynccl_wrapper.py +349 -0
  124. vllm/distributed/device_communicators/quick_all_reduce.py +278 -0
  125. vllm/distributed/device_communicators/shm_broadcast.py +585 -0
  126. vllm/distributed/device_communicators/tpu_communicator.py +103 -0
  127. vllm/distributed/device_communicators/xpu_communicator.py +55 -0
  128. vllm/distributed/eplb/__init__.py +8 -0
  129. vllm/distributed/eplb/eplb_state.py +432 -0
  130. vllm/distributed/eplb/rebalance_algo.py +234 -0
  131. vllm/distributed/eplb/rebalance_execute.py +307 -0
  132. vllm/distributed/kv_events.py +356 -0
  133. vllm/distributed/kv_transfer/README.md +29 -0
  134. vllm/distributed/kv_transfer/__init__.py +12 -0
  135. vllm/distributed/kv_transfer/disagg_prefill_workflow.jpg +0 -0
  136. vllm/distributed/kv_transfer/kv_connector/__init__.py +0 -0
  137. vllm/distributed/kv_transfer/kv_connector/base.py +128 -0
  138. vllm/distributed/kv_transfer/kv_connector/factory.py +133 -0
  139. vllm/distributed/kv_transfer/kv_connector/lmcache_connector.py +99 -0
  140. vllm/distributed/kv_transfer/kv_connector/mooncake_store_connector.py +203 -0
  141. vllm/distributed/kv_transfer/kv_connector/simple_connector.py +329 -0
  142. vllm/distributed/kv_transfer/kv_connector/utils.py +109 -0
  143. vllm/distributed/kv_transfer/kv_connector/v1/__init__.py +6 -0
  144. vllm/distributed/kv_transfer/kv_connector/v1/base.py +283 -0
  145. vllm/distributed/kv_transfer/kv_connector/v1/lmcache_connector.py +167 -0
  146. vllm/distributed/kv_transfer/kv_connector/v1/multi_connector.py +201 -0
  147. vllm/distributed/kv_transfer/kv_connector/v1/nixl_connector.py +1103 -0
  148. vllm/distributed/kv_transfer/kv_connector/v1/p2p/__init__.py +0 -0
  149. vllm/distributed/kv_transfer/kv_connector/v1/p2p/p2p_nccl_connector.py +485 -0
  150. vllm/distributed/kv_transfer/kv_connector/v1/p2p/p2p_nccl_engine.py +533 -0
  151. vllm/distributed/kv_transfer/kv_connector/v1/p2p/tensor_memory_pool.py +265 -0
  152. vllm/distributed/kv_transfer/kv_connector/v1/shared_storage_connector.py +389 -0
  153. vllm/distributed/kv_transfer/kv_connector_agent.py +77 -0
  154. vllm/distributed/kv_transfer/kv_lookup_buffer/__init__.py +0 -0
  155. vllm/distributed/kv_transfer/kv_lookup_buffer/base.py +175 -0
  156. vllm/distributed/kv_transfer/kv_lookup_buffer/mooncake_store.py +161 -0
  157. vllm/distributed/kv_transfer/kv_lookup_buffer/simple_buffer.py +237 -0
  158. vllm/distributed/kv_transfer/kv_pipe/__init__.py +0 -0
  159. vllm/distributed/kv_transfer/kv_pipe/base.py +67 -0
  160. vllm/distributed/kv_transfer/kv_pipe/mooncake_pipe.py +290 -0
  161. vllm/distributed/kv_transfer/kv_pipe/pynccl_pipe.py +280 -0
  162. vllm/distributed/kv_transfer/kv_transfer_state.py +71 -0
  163. vllm/distributed/parallel_state.py +1385 -0
  164. vllm/distributed/tpu_distributed_utils.py +178 -0
  165. vllm/distributed/utils.py +536 -0
  166. vllm/engine/__init__.py +0 -0
  167. vllm/engine/arg_utils.py +1801 -0
  168. vllm/engine/async_llm_engine.py +1200 -0
  169. vllm/engine/async_timeout.py +173 -0
  170. vllm/engine/llm_engine.py +2101 -0
  171. vllm/engine/metrics.py +629 -0
  172. vllm/engine/metrics_types.py +94 -0
  173. vllm/engine/multiprocessing/__init__.py +148 -0
  174. vllm/engine/multiprocessing/client.py +681 -0
  175. vllm/engine/multiprocessing/engine.py +460 -0
  176. vllm/engine/output_processor/__init__.py +0 -0
  177. vllm/engine/output_processor/interfaces.py +75 -0
  178. vllm/engine/output_processor/multi_step.py +216 -0
  179. vllm/engine/output_processor/single_step.py +145 -0
  180. vllm/engine/output_processor/stop_checker.py +131 -0
  181. vllm/engine/output_processor/util.py +28 -0
  182. vllm/engine/protocol.py +326 -0
  183. vllm/entrypoints/__init__.py +0 -0
  184. vllm/entrypoints/api_server.py +178 -0
  185. vllm/entrypoints/chat_utils.py +1278 -0
  186. vllm/entrypoints/cli/__init__.py +12 -0
  187. vllm/entrypoints/cli/benchmark/__init__.py +0 -0
  188. vllm/entrypoints/cli/benchmark/base.py +25 -0
  189. vllm/entrypoints/cli/benchmark/latency.py +21 -0
  190. vllm/entrypoints/cli/benchmark/main.py +58 -0
  191. vllm/entrypoints/cli/benchmark/serve.py +21 -0
  192. vllm/entrypoints/cli/benchmark/throughput.py +21 -0
  193. vllm/entrypoints/cli/collect_env.py +36 -0
  194. vllm/entrypoints/cli/main.py +71 -0
  195. vllm/entrypoints/cli/openai.py +201 -0
  196. vllm/entrypoints/cli/run_batch.py +69 -0
  197. vllm/entrypoints/cli/serve.py +265 -0
  198. vllm/entrypoints/cli/types.py +29 -0
  199. vllm/entrypoints/launcher.py +147 -0
  200. vllm/entrypoints/llm.py +1599 -0
  201. vllm/entrypoints/logger.py +50 -0
  202. vllm/entrypoints/openai/__init__.py +0 -0
  203. vllm/entrypoints/openai/api_server.py +1495 -0
  204. vllm/entrypoints/openai/cli_args.py +331 -0
  205. vllm/entrypoints/openai/logits_processors.py +90 -0
  206. vllm/entrypoints/openai/protocol.py +2096 -0
  207. vllm/entrypoints/openai/run_batch.py +473 -0
  208. vllm/entrypoints/openai/serving_chat.py +1258 -0
  209. vllm/entrypoints/openai/serving_classification.py +160 -0
  210. vllm/entrypoints/openai/serving_completion.py +618 -0
  211. vllm/entrypoints/openai/serving_embedding.py +201 -0
  212. vllm/entrypoints/openai/serving_engine.py +988 -0
  213. vllm/entrypoints/openai/serving_models.py +315 -0
  214. vllm/entrypoints/openai/serving_pooling.py +234 -0
  215. vllm/entrypoints/openai/serving_score.py +431 -0
  216. vllm/entrypoints/openai/serving_tokenization.py +157 -0
  217. vllm/entrypoints/openai/serving_transcription.py +132 -0
  218. vllm/entrypoints/openai/speech_to_text.py +395 -0
  219. vllm/entrypoints/openai/tool_parsers/__init__.py +25 -0
  220. vllm/entrypoints/openai/tool_parsers/abstract_tool_parser.py +164 -0
  221. vllm/entrypoints/openai/tool_parsers/deepseekv3_tool_parser.py +370 -0
  222. vllm/entrypoints/openai/tool_parsers/granite_20b_fc_tool_parser.py +259 -0
  223. vllm/entrypoints/openai/tool_parsers/granite_tool_parser.py +237 -0
  224. vllm/entrypoints/openai/tool_parsers/hermes_tool_parser.py +371 -0
  225. vllm/entrypoints/openai/tool_parsers/internlm2_tool_parser.py +216 -0
  226. vllm/entrypoints/openai/tool_parsers/jamba_tool_parser.py +308 -0
  227. vllm/entrypoints/openai/tool_parsers/llama4_pythonic_tool_parser.py +316 -0
  228. vllm/entrypoints/openai/tool_parsers/llama_tool_parser.py +267 -0
  229. vllm/entrypoints/openai/tool_parsers/minimax_tool_parser.py +369 -0
  230. vllm/entrypoints/openai/tool_parsers/mistral_tool_parser.py +369 -0
  231. vllm/entrypoints/openai/tool_parsers/phi4mini_tool_parser.py +112 -0
  232. vllm/entrypoints/openai/tool_parsers/pythonic_tool_parser.py +308 -0
  233. vllm/entrypoints/openai/tool_parsers/utils.py +124 -0
  234. vllm/entrypoints/openai/tool_parsers/xlam_tool_parser.py +466 -0
  235. vllm/entrypoints/score_utils.py +50 -0
  236. vllm/entrypoints/ssl.py +75 -0
  237. vllm/entrypoints/utils.py +262 -0
  238. vllm/env_override.py +41 -0
  239. vllm/envs.py +1029 -0
  240. vllm/executor/__init__.py +0 -0
  241. vllm/executor/executor_base.py +401 -0
  242. vllm/executor/mp_distributed_executor.py +244 -0
  243. vllm/executor/msgspec_utils.py +30 -0
  244. vllm/executor/multiproc_worker_utils.py +313 -0
  245. vllm/executor/ray_distributed_executor.py +701 -0
  246. vllm/executor/ray_utils.py +399 -0
  247. vllm/executor/uniproc_executor.py +139 -0
  248. vllm/forward_context.py +185 -0
  249. vllm/inputs/__init__.py +41 -0
  250. vllm/inputs/data.py +331 -0
  251. vllm/inputs/parse.py +151 -0
  252. vllm/inputs/preprocess.py +924 -0
  253. vllm/inputs/registry.py +245 -0
  254. vllm/jsontree.py +80 -0
  255. vllm/logger.py +212 -0
  256. vllm/logging_utils/__init__.py +8 -0
  257. vllm/logging_utils/dump_input.py +81 -0
  258. vllm/logging_utils/formatter.py +18 -0
  259. vllm/logits_process.py +119 -0
  260. vllm/lora/__init__.py +0 -0
  261. vllm/lora/fully_sharded_layers.py +355 -0
  262. vllm/lora/layers.py +1285 -0
  263. vllm/lora/lora.py +199 -0
  264. vllm/lora/models.py +818 -0
  265. vllm/lora/ops/__init__.py +0 -0
  266. vllm/lora/ops/torch_ops/__init__.py +16 -0
  267. vllm/lora/ops/torch_ops/lora_ops.py +119 -0
  268. vllm/lora/ops/triton_ops/__init__.py +12 -0
  269. vllm/lora/ops/triton_ops/kernel_utils.py +243 -0
  270. vllm/lora/ops/triton_ops/lora_expand_op.py +290 -0
  271. vllm/lora/ops/triton_ops/lora_kernel_metadata.py +148 -0
  272. vllm/lora/ops/triton_ops/lora_shrink_op.py +244 -0
  273. vllm/lora/ops/triton_ops/utils.py +120 -0
  274. vllm/lora/ops/xla_ops/__init__.py +7 -0
  275. vllm/lora/ops/xla_ops/lora_ops.py +145 -0
  276. vllm/lora/peft_helper.py +136 -0
  277. vllm/lora/punica_wrapper/__init__.py +10 -0
  278. vllm/lora/punica_wrapper/punica_base.py +485 -0
  279. vllm/lora/punica_wrapper/punica_cpu.py +349 -0
  280. vllm/lora/punica_wrapper/punica_gpu.py +290 -0
  281. vllm/lora/punica_wrapper/punica_hpu.py +145 -0
  282. vllm/lora/punica_wrapper/punica_selector.py +20 -0
  283. vllm/lora/punica_wrapper/punica_tpu.py +405 -0
  284. vllm/lora/punica_wrapper/utils.py +164 -0
  285. vllm/lora/request.py +99 -0
  286. vllm/lora/resolver.py +85 -0
  287. vllm/lora/utils.py +240 -0
  288. vllm/lora/worker_manager.py +256 -0
  289. vllm/model_executor/__init__.py +16 -0
  290. vllm/model_executor/custom_op.py +208 -0
  291. vllm/model_executor/guided_decoding/__init__.py +181 -0
  292. vllm/model_executor/guided_decoding/guidance_decoding.py +63 -0
  293. vllm/model_executor/guided_decoding/guidance_logits_processors.py +104 -0
  294. vllm/model_executor/guided_decoding/guided_fields.py +41 -0
  295. vllm/model_executor/guided_decoding/lm_format_enforcer_decoding.py +67 -0
  296. vllm/model_executor/guided_decoding/outlines_decoding.py +155 -0
  297. vllm/model_executor/guided_decoding/outlines_logits_processors.py +284 -0
  298. vllm/model_executor/guided_decoding/utils.py +242 -0
  299. vllm/model_executor/guided_decoding/xgrammar_decoding.py +426 -0
  300. vllm/model_executor/layers/__init__.py +0 -0
  301. vllm/model_executor/layers/activation.py +420 -0
  302. vllm/model_executor/layers/fused_moe/__init__.py +78 -0
  303. vllm/model_executor/layers/fused_moe/batched_deep_gemm_moe.py +298 -0
  304. vllm/model_executor/layers/fused_moe/batched_triton_or_deep_gemm_moe.py +140 -0
  305. vllm/model_executor/layers/fused_moe/config.py +456 -0
  306. vllm/model_executor/layers/fused_moe/configs/E=1,N=14336,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a16.json +146 -0
  307. vllm/model_executor/layers/fused_moe/configs/E=1,N=14336,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  308. vllm/model_executor/layers/fused_moe/configs/E=1,N=1792,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a16.json +218 -0
  309. vllm/model_executor/layers/fused_moe/configs/E=1,N=1792,device_name=NVIDIA_A100-SXM4-80GB.json +218 -0
  310. vllm/model_executor/layers/fused_moe/configs/E=1,N=3072,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a16.json +218 -0
  311. vllm/model_executor/layers/fused_moe/configs/E=1,N=3072,device_name=NVIDIA_H100_80GB_HBM3,dtype=int8_w8a16.json +218 -0
  312. vllm/model_executor/layers/fused_moe/configs/E=1,N=3072,device_name=NVIDIA_H100_80GB_HBM3.json +218 -0
  313. vllm/model_executor/layers/fused_moe/configs/E=1,N=3584,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a16.json +218 -0
  314. vllm/model_executor/layers/fused_moe/configs/E=1,N=3584,device_name=NVIDIA_A100-SXM4-80GB.json +218 -0
  315. vllm/model_executor/layers/fused_moe/configs/E=1,N=7168,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a16.json +218 -0
  316. vllm/model_executor/layers/fused_moe/configs/E=1,N=7168,device_name=NVIDIA_A100-SXM4-80GB.json +218 -0
  317. vllm/model_executor/layers/fused_moe/configs/E=128,N=1024,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json +164 -0
  318. vllm/model_executor/layers/fused_moe/configs/E=128,N=1024,device_name=AMD_Instinct_MI300X.json +200 -0
  319. vllm/model_executor/layers/fused_moe/configs/E=128,N=192,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  320. vllm/model_executor/layers/fused_moe/configs/E=128,N=192,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  321. vllm/model_executor/layers/fused_moe/configs/E=128,N=192,device_name=NVIDIA_H20-3e.json +146 -0
  322. vllm/model_executor/layers/fused_moe/configs/E=128,N=192,device_name=NVIDIA_H20.json +146 -0
  323. vllm/model_executor/layers/fused_moe/configs/E=128,N=192,device_name=NVIDIA_H200.json +146 -0
  324. 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
  325. 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
  326. vllm/model_executor/layers/fused_moe/configs/E=128,N=384,device_name=NVIDIA_H20-3e,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  327. vllm/model_executor/layers/fused_moe/configs/E=128,N=384,device_name=NVIDIA_H20-3e.json +146 -0
  328. vllm/model_executor/layers/fused_moe/configs/E=128,N=384,device_name=NVIDIA_H20.json +146 -0
  329. 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
  330. vllm/model_executor/layers/fused_moe/configs/E=128,N=384,device_name=NVIDIA_H200.json +146 -0
  331. vllm/model_executor/layers/fused_moe/configs/E=128,N=512,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  332. 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
  333. vllm/model_executor/layers/fused_moe/configs/E=128,N=768,device_name=NVIDIA_B200,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  334. 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
  335. vllm/model_executor/layers/fused_moe/configs/E=128,N=768,device_name=NVIDIA_H20-3e,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  336. vllm/model_executor/layers/fused_moe/configs/E=128,N=768,device_name=NVIDIA_H20.json +146 -0
  337. 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
  338. vllm/model_executor/layers/fused_moe/configs/E=128,N=768,device_name=NVIDIA_H200.json +146 -0
  339. vllm/model_executor/layers/fused_moe/configs/E=128,N=96,device_name=NVIDIA_H20.json +146 -0
  340. vllm/model_executor/layers/fused_moe/configs/E=16,N=1024,device_name=AMD_Instinct_MI300X.json +200 -0
  341. vllm/model_executor/layers/fused_moe/configs/E=16,N=1024,device_name=NVIDIA_B200,dtype=fp8_w8a8.json +147 -0
  342. vllm/model_executor/layers/fused_moe/configs/E=16,N=1024,device_name=NVIDIA_B200.json +146 -0
  343. vllm/model_executor/layers/fused_moe/configs/E=16,N=1024,device_name=NVIDIA_H100.json +146 -0
  344. vllm/model_executor/layers/fused_moe/configs/E=16,N=1344,device_name=NVIDIA_A100-SXM4-40GB.json +146 -0
  345. vllm/model_executor/layers/fused_moe/configs/E=16,N=1344,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  346. vllm/model_executor/layers/fused_moe/configs/E=16,N=1344,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  347. vllm/model_executor/layers/fused_moe/configs/E=16,N=14336,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a16.json +146 -0
  348. vllm/model_executor/layers/fused_moe/configs/E=16,N=14336,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  349. vllm/model_executor/layers/fused_moe/configs/E=16,N=1792,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a16.json +218 -0
  350. vllm/model_executor/layers/fused_moe/configs/E=16,N=1792,device_name=NVIDIA_A100-SXM4-80GB.json +218 -0
  351. vllm/model_executor/layers/fused_moe/configs/E=16,N=2688,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  352. vllm/model_executor/layers/fused_moe/configs/E=16,N=2688,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  353. vllm/model_executor/layers/fused_moe/configs/E=16,N=3072,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a16.json +146 -0
  354. vllm/model_executor/layers/fused_moe/configs/E=16,N=3072,device_name=NVIDIA_H100_80GB_HBM3,dtype=int8_w8a16.json +146 -0
  355. vllm/model_executor/layers/fused_moe/configs/E=16,N=3200,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json +130 -0
  356. vllm/model_executor/layers/fused_moe/configs/E=16,N=3584,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a16.json +146 -0
  357. vllm/model_executor/layers/fused_moe/configs/E=16,N=3584,device_name=NVIDIA_A100-SXM4-80GB.json +218 -0
  358. vllm/model_executor/layers/fused_moe/configs/E=16,N=6400,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json +130 -0
  359. vllm/model_executor/layers/fused_moe/configs/E=16,N=7168,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a16.json +146 -0
  360. vllm/model_executor/layers/fused_moe/configs/E=16,N=7168,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  361. vllm/model_executor/layers/fused_moe/configs/E=16,N=7168,device_name=NVIDIA_H100_80GB_HBM3,dtype=int8_w8a16.json +146 -0
  362. vllm/model_executor/layers/fused_moe/configs/E=16,N=800,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json +130 -0
  363. vllm/model_executor/layers/fused_moe/configs/E=160,N=192,device_name=NVIDIA_A800-SXM4-80GB.json +146 -0
  364. vllm/model_executor/layers/fused_moe/configs/E=256,N=1024,device_name=AMD_Instinct_MI325X,block_shape=[128,128].json +200 -0
  365. 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
  366. 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
  367. vllm/model_executor/layers/fused_moe/configs/E=256,N=128,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a8.json +146 -0
  368. 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
  369. vllm/model_executor/layers/fused_moe/configs/E=256,N=128,device_name=NVIDIA_A800-SXM4-80GB,dtype=int8_w8a8.json +146 -0
  370. 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
  371. 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
  372. 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
  373. 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
  374. 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
  375. 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
  376. 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
  377. 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
  378. 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
  379. vllm/model_executor/layers/fused_moe/configs/E=256,N=256,device_name=NVIDIA_H20-3e,dtype=fp8_w8a8,block_shape=[128,128].json +146 -0
  380. 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
  381. 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
  382. 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
  383. vllm/model_executor/layers/fused_moe/configs/E=256,N=64,device_name=NVIDIA_A800-SXM4-80GB.json +146 -0
  384. vllm/model_executor/layers/fused_moe/configs/E=60,N=1408,device_name=AMD_Instinct_MI300X.json +200 -0
  385. vllm/model_executor/layers/fused_moe/configs/E=60,N=176,device_name=AMD_Instinct_MI300X.json +200 -0
  386. vllm/model_executor/layers/fused_moe/configs/E=60,N=352,device_name=AMD_Instinct_MI300X.json +200 -0
  387. vllm/model_executor/layers/fused_moe/configs/E=60,N=704,device_name=AMD_Instinct_MI300X.json +200 -0
  388. vllm/model_executor/layers/fused_moe/configs/E=64,N=1280,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  389. vllm/model_executor/layers/fused_moe/configs/E=64,N=1280,device_name=NVIDIA_A800-SXM4-80GB.json +146 -0
  390. vllm/model_executor/layers/fused_moe/configs/E=64,N=1280,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json +146 -0
  391. vllm/model_executor/layers/fused_moe/configs/E=64,N=1280,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  392. vllm/model_executor/layers/fused_moe/configs/E=64,N=1280,device_name=NVIDIA_H200,dtype=fp8_w8a8.json +146 -0
  393. vllm/model_executor/layers/fused_moe/configs/E=64,N=1280,device_name=NVIDIA_H200.json +146 -0
  394. vllm/model_executor/layers/fused_moe/configs/E=64,N=2560,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json +146 -0
  395. vllm/model_executor/layers/fused_moe/configs/E=64,N=2560,device_name=NVIDIA_H200,dtype=fp8_w8a8.json +146 -0
  396. vllm/model_executor/layers/fused_moe/configs/E=64,N=2560,device_name=NVIDIA_H200.json +146 -0
  397. vllm/model_executor/layers/fused_moe/configs/E=64,N=320,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json +146 -0
  398. vllm/model_executor/layers/fused_moe/configs/E=64,N=320,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  399. vllm/model_executor/layers/fused_moe/configs/E=64,N=320,device_name=NVIDIA_H200,dtype=fp8_w8a8.json +146 -0
  400. vllm/model_executor/layers/fused_moe/configs/E=64,N=320,device_name=NVIDIA_H200.json +146 -0
  401. vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  402. vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_A800-SXM4-80GB.json +146 -0
  403. vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_GeForce_RTX_4090,dtype=fp8_w8a8.json +146 -0
  404. vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json +146 -0
  405. vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  406. vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_H200,dtype=fp8_w8a8.json +146 -0
  407. vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_H200.json +146 -0
  408. vllm/model_executor/layers/fused_moe/configs/E=64,N=896,device_name=NVIDIA_H20.json +146 -0
  409. vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json +164 -0
  410. vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=AMD_Instinct_MI300X.json +200 -0
  411. vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json +164 -0
  412. vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=AMD_Instinct_MI325X.json +200 -0
  413. vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json +138 -0
  414. vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=NVIDIA_H200,dtype=fp8_w8a8.json +146 -0
  415. vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=NVIDIA_H200.json +146 -0
  416. vllm/model_executor/layers/fused_moe/configs/E=8,N=16384,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json +164 -0
  417. vllm/model_executor/layers/fused_moe/configs/E=8,N=16384,device_name=AMD_Instinct_MI300X.json +200 -0
  418. vllm/model_executor/layers/fused_moe/configs/E=8,N=16384,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json +164 -0
  419. vllm/model_executor/layers/fused_moe/configs/E=8,N=16384,device_name=AMD_Instinct_MI325X.json +200 -0
  420. vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json +164 -0
  421. vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=AMD_Instinct_MI300X.json +200 -0
  422. vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json +164 -0
  423. vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=AMD_Instinct_MI325X.json +200 -0
  424. vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_A100-SXM4-40GB.json +146 -0
  425. vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  426. vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  427. vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_H200,dtype=fp8_w8a8.json +146 -0
  428. vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_H200.json +146 -0
  429. vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json +164 -0
  430. vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=AMD_Instinct_MI300X.json +200 -0
  431. vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json +164 -0
  432. vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=AMD_Instinct_MI325X.json +200 -0
  433. vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  434. vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json +146 -0
  435. vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  436. vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_H200,dtype=fp8_w8a8.json +146 -0
  437. vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_H200.json +146 -0
  438. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json +164 -0
  439. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=AMD_Instinct_MI300X.json +200 -0
  440. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json +164 -0
  441. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=AMD_Instinct_MI325X.json +200 -0
  442. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_A100-SXM4-40GB.json +146 -0
  443. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  444. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_GeForce_RTX_4090,dtype=fp8_w8a8.json +146 -0
  445. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json +146 -0
  446. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  447. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_H200,dtype=fp8_w8a8.json +146 -0
  448. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_H200.json +146 -0
  449. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_L40S.json +173 -0
  450. vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json +164 -0
  451. vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=AMD_Instinct_MI300X.json +200 -0
  452. vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json +164 -0
  453. vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=AMD_Instinct_MI325X.json +200 -0
  454. vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  455. vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json +146 -0
  456. vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  457. vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_H200,dtype=fp8_w8a8.json +146 -0
  458. vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_H200.json +146 -0
  459. vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json +164 -0
  460. vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=AMD_Instinct_MI300X.json +200 -0
  461. vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json +164 -0
  462. vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=AMD_Instinct_MI325X.json +200 -0
  463. vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  464. vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json +146 -0
  465. vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  466. vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_H200,dtype=fp8_w8a8.json +146 -0
  467. vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_H200.json +146 -0
  468. vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json +164 -0
  469. vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=AMD_Instinct_MI300X.json +200 -0
  470. vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json +164 -0
  471. vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=AMD_Instinct_MI325X.json +200 -0
  472. vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json +146 -0
  473. vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=NVIDIA_H200,dtype=fp8_w8a8.json +146 -0
  474. vllm/model_executor/layers/fused_moe/configs/README +12 -0
  475. vllm/model_executor/layers/fused_moe/cpu_fused_moe.py +215 -0
  476. vllm/model_executor/layers/fused_moe/cutlass_moe.py +645 -0
  477. vllm/model_executor/layers/fused_moe/deep_gemm_moe.py +250 -0
  478. vllm/model_executor/layers/fused_moe/deepep_ht_prepare_finalize.py +231 -0
  479. vllm/model_executor/layers/fused_moe/deepep_ll_prepare_finalize.py +183 -0
  480. vllm/model_executor/layers/fused_moe/fused_batched_moe.py +1021 -0
  481. vllm/model_executor/layers/fused_moe/fused_marlin_moe.py +234 -0
  482. vllm/model_executor/layers/fused_moe/fused_moe.py +1734 -0
  483. vllm/model_executor/layers/fused_moe/layer.py +1528 -0
  484. vllm/model_executor/layers/fused_moe/modular_kernel.py +598 -0
  485. vllm/model_executor/layers/fused_moe/moe_align_block_size.py +224 -0
  486. vllm/model_executor/layers/fused_moe/moe_pallas.py +80 -0
  487. vllm/model_executor/layers/fused_moe/moe_permute_unpermute.py +190 -0
  488. vllm/model_executor/layers/fused_moe/moe_torch_iterative.py +60 -0
  489. vllm/model_executor/layers/fused_moe/pplx_prepare_finalize.py +233 -0
  490. vllm/model_executor/layers/fused_moe/prepare_finalize.py +66 -0
  491. vllm/model_executor/layers/fused_moe/rocm_aiter_fused_moe.py +429 -0
  492. vllm/model_executor/layers/fused_moe/triton_deep_gemm_moe.py +136 -0
  493. vllm/model_executor/layers/fused_moe/utils.py +144 -0
  494. vllm/model_executor/layers/layernorm.py +287 -0
  495. vllm/model_executor/layers/lightning_attn.py +652 -0
  496. vllm/model_executor/layers/linear.py +1547 -0
  497. vllm/model_executor/layers/logits_processor.py +197 -0
  498. vllm/model_executor/layers/mamba/__init__.py +0 -0
  499. vllm/model_executor/layers/mamba/mamba2_metadata.py +125 -0
  500. vllm/model_executor/layers/mamba/mamba_mixer.py +245 -0
  501. vllm/model_executor/layers/mamba/mamba_mixer2.py +731 -0
  502. vllm/model_executor/layers/mamba/ops/__init__.py +0 -0
  503. vllm/model_executor/layers/mamba/ops/causal_conv1d.py +105 -0
  504. vllm/model_executor/layers/mamba/ops/mamba_ssm.py +414 -0
  505. vllm/model_executor/layers/mamba/ops/ssd_bmm.py +262 -0
  506. vllm/model_executor/layers/mamba/ops/ssd_chunk_scan.py +589 -0
  507. vllm/model_executor/layers/mamba/ops/ssd_chunk_state.py +751 -0
  508. vllm/model_executor/layers/mamba/ops/ssd_combined.py +232 -0
  509. vllm/model_executor/layers/mamba/ops/ssd_state_passing.py +206 -0
  510. vllm/model_executor/layers/pooler.py +473 -0
  511. vllm/model_executor/layers/quantization/__init__.py +160 -0
  512. vllm/model_executor/layers/quantization/aqlm.py +376 -0
  513. vllm/model_executor/layers/quantization/auto_round.py +310 -0
  514. vllm/model_executor/layers/quantization/awq.py +228 -0
  515. vllm/model_executor/layers/quantization/awq_marlin.py +523 -0
  516. vllm/model_executor/layers/quantization/awq_triton.py +320 -0
  517. vllm/model_executor/layers/quantization/base_config.py +164 -0
  518. vllm/model_executor/layers/quantization/bitblas.py +462 -0
  519. vllm/model_executor/layers/quantization/bitsandbytes.py +396 -0
  520. vllm/model_executor/layers/quantization/compressed_tensors/__init__.py +0 -0
  521. vllm/model_executor/layers/quantization/compressed_tensors/compressed_tensors.py +694 -0
  522. vllm/model_executor/layers/quantization/compressed_tensors/compressed_tensors_moe.py +1613 -0
  523. vllm/model_executor/layers/quantization/compressed_tensors/schemes/__init__.py +24 -0
  524. vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_24.py +358 -0
  525. vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_scheme.py +55 -0
  526. vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_w4a16_24.py +160 -0
  527. vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_w4a16_nvfp4.py +105 -0
  528. vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_w4a4_nvfp4.py +149 -0
  529. vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_w8a16_fp8.py +121 -0
  530. vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_w8a8_fp8.py +150 -0
  531. vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_w8a8_int8.py +111 -0
  532. vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_wNa16.py +201 -0
  533. vllm/model_executor/layers/quantization/compressed_tensors/triton_scaled_mm.py +206 -0
  534. vllm/model_executor/layers/quantization/compressed_tensors/utils.py +216 -0
  535. vllm/model_executor/layers/quantization/deepgemm.py +83 -0
  536. vllm/model_executor/layers/quantization/deepspeedfp.py +195 -0
  537. vllm/model_executor/layers/quantization/experts_int8.py +204 -0
  538. vllm/model_executor/layers/quantization/fbgemm_fp8.py +172 -0
  539. vllm/model_executor/layers/quantization/fp8.py +950 -0
  540. vllm/model_executor/layers/quantization/gguf.py +577 -0
  541. vllm/model_executor/layers/quantization/gptq.py +278 -0
  542. vllm/model_executor/layers/quantization/gptq_bitblas.py +446 -0
  543. vllm/model_executor/layers/quantization/gptq_marlin.py +679 -0
  544. vllm/model_executor/layers/quantization/gptq_marlin_24.py +297 -0
  545. vllm/model_executor/layers/quantization/hqq_marlin.py +332 -0
  546. vllm/model_executor/layers/quantization/ipex_quant.py +250 -0
  547. vllm/model_executor/layers/quantization/kernels/__init__.py +0 -0
  548. vllm/model_executor/layers/quantization/kernels/mixed_precision/MPLinearKernel.py +90 -0
  549. vllm/model_executor/layers/quantization/kernels/mixed_precision/__init__.py +83 -0
  550. vllm/model_executor/layers/quantization/kernels/mixed_precision/allspark.py +116 -0
  551. vllm/model_executor/layers/quantization/kernels/mixed_precision/bitblas.py +300 -0
  552. vllm/model_executor/layers/quantization/kernels/mixed_precision/exllama.py +143 -0
  553. vllm/model_executor/layers/quantization/kernels/mixed_precision/machete.py +132 -0
  554. vllm/model_executor/layers/quantization/kernels/mixed_precision/marlin.py +131 -0
  555. vllm/model_executor/layers/quantization/kernels/scaled_mm/ScaledMMLinearKernel.py +67 -0
  556. vllm/model_executor/layers/quantization/kernels/scaled_mm/__init__.py +87 -0
  557. vllm/model_executor/layers/quantization/kernels/scaled_mm/aiter.py +120 -0
  558. vllm/model_executor/layers/quantization/kernels/scaled_mm/cutlass.py +137 -0
  559. vllm/model_executor/layers/quantization/kernels/scaled_mm/triton.py +41 -0
  560. vllm/model_executor/layers/quantization/kernels/scaled_mm/xla.py +105 -0
  561. vllm/model_executor/layers/quantization/kv_cache.py +139 -0
  562. vllm/model_executor/layers/quantization/marlin.py +263 -0
  563. vllm/model_executor/layers/quantization/modelopt.py +747 -0
  564. vllm/model_executor/layers/quantization/moe_wna16.py +457 -0
  565. vllm/model_executor/layers/quantization/neuron_quant.py +76 -0
  566. vllm/model_executor/layers/quantization/ptpc_fp8.py +127 -0
  567. vllm/model_executor/layers/quantization/qqq.py +275 -0
  568. vllm/model_executor/layers/quantization/quark/__init__.py +0 -0
  569. vllm/model_executor/layers/quantization/quark/quark.py +437 -0
  570. vllm/model_executor/layers/quantization/quark/quark_moe.py +245 -0
  571. vllm/model_executor/layers/quantization/quark/schemes/__init__.py +9 -0
  572. vllm/model_executor/layers/quantization/quark/schemes/quark_scheme.py +55 -0
  573. vllm/model_executor/layers/quantization/quark/schemes/quark_w4a4_mxfp4.py +126 -0
  574. vllm/model_executor/layers/quantization/quark/schemes/quark_w8a8_fp8.py +157 -0
  575. vllm/model_executor/layers/quantization/quark/schemes/quark_w8a8_int8.py +122 -0
  576. vllm/model_executor/layers/quantization/quark/utils.py +105 -0
  577. vllm/model_executor/layers/quantization/rtn.py +289 -0
  578. vllm/model_executor/layers/quantization/schema.py +86 -0
  579. vllm/model_executor/layers/quantization/torchao.py +212 -0
  580. vllm/model_executor/layers/quantization/tpu_int8.py +121 -0
  581. vllm/model_executor/layers/quantization/utils/__init__.py +6 -0
  582. vllm/model_executor/layers/quantization/utils/allspark_utils.py +52 -0
  583. vllm/model_executor/layers/quantization/utils/bitblas_utils.py +208 -0
  584. 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
  585. 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
  586. 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
  587. 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
  588. 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
  589. 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
  590. 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
  591. 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
  592. 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
  593. 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
  594. 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
  595. 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
  596. 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
  597. 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
  598. 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
  599. 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
  600. 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
  601. 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
  602. 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
  603. 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
  604. 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
  605. 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
  606. 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
  607. 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
  608. 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
  609. 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
  610. 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
  611. 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
  612. 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
  613. 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
  614. 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
  615. 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
  616. 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
  617. 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
  618. 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
  619. 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
  620. 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
  621. 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
  622. 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
  623. 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
  624. 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
  625. 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
  626. 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
  627. 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
  628. 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
  629. 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
  630. 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
  631. 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
  632. 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
  633. 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
  634. 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
  635. 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
  636. 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
  637. 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
  638. 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
  639. 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
  640. 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
  641. 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
  642. 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
  643. 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
  644. 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
  645. 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
  646. 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
  647. 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
  648. 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
  649. 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
  650. 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
  651. 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
  652. 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
  653. 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
  654. 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
  655. 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
  656. 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
  657. 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
  658. 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
  659. 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
  660. 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
  661. 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
  662. 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
  663. 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
  664. 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
  665. 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
  666. 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
  667. 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
  668. 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
  669. 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
  670. 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
  671. 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
  672. 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
  673. 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
  674. 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
  675. 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
  676. 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
  677. 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
  678. 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
  679. 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
  680. 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
  681. 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
  682. 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
  683. 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
  684. 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
  685. 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
  686. 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
  687. 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
  688. 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
  689. 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
  690. 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
  691. 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
  692. 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
  693. 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
  694. 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
  695. 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
  696. 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
  697. 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
  698. 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
  699. 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
  700. 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
  701. 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
  702. 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
  703. 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
  704. 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
  705. 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
  706. 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
  707. 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
  708. 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
  709. 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
  710. 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
  711. 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
  712. 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
  713. 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
  714. 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
  715. 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
  716. 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
  717. 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
  718. 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
  719. 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
  720. 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
  721. 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
  722. 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
  723. 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
  724. 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
  725. 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
  726. 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
  727. 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
  728. 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
  729. 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
  730. 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
  731. 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
  732. 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
  733. 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
  734. 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
  735. 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
  736. 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
  737. 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
  738. 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
  739. 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
  740. 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
  741. 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
  742. 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
  743. 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
  744. 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
  745. 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
  746. 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
  747. 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
  748. 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
  749. 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
  750. 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
  751. 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
  752. 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
  753. 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
  754. 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
  755. 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
  756. 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
  757. 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
  758. 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
  759. 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
  760. 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
  761. 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
  762. 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
  763. 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
  764. 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
  765. 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
  766. 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
  767. 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
  768. 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
  769. 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
  770. 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
  771. 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
  772. 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
  773. 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
  774. 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
  775. 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
  776. 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
  777. 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
  778. 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
  779. 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
  780. 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
  781. 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
  782. 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
  783. 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
  784. 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
  785. 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
  786. vllm/model_executor/layers/quantization/utils/fp8_utils.py +653 -0
  787. vllm/model_executor/layers/quantization/utils/gptq_utils.py +95 -0
  788. vllm/model_executor/layers/quantization/utils/int8_utils.py +485 -0
  789. vllm/model_executor/layers/quantization/utils/layer_utils.py +40 -0
  790. vllm/model_executor/layers/quantization/utils/machete_utils.py +50 -0
  791. vllm/model_executor/layers/quantization/utils/marlin_utils.py +476 -0
  792. vllm/model_executor/layers/quantization/utils/marlin_utils_fp4.py +283 -0
  793. vllm/model_executor/layers/quantization/utils/marlin_utils_fp8.py +325 -0
  794. vllm/model_executor/layers/quantization/utils/marlin_utils_test.py +165 -0
  795. vllm/model_executor/layers/quantization/utils/marlin_utils_test_24.py +464 -0
  796. vllm/model_executor/layers/quantization/utils/marlin_utils_test_qqq.py +126 -0
  797. vllm/model_executor/layers/quantization/utils/mxfp4_utils.py +45 -0
  798. vllm/model_executor/layers/quantization/utils/nvfp4_emulation_utils.py +146 -0
  799. vllm/model_executor/layers/quantization/utils/quant_utils.py +573 -0
  800. vllm/model_executor/layers/quantization/utils/w8a8_utils.py +405 -0
  801. vllm/model_executor/layers/rejection_sampler.py +406 -0
  802. vllm/model_executor/layers/resampler.py +270 -0
  803. vllm/model_executor/layers/rotary_embedding.py +2025 -0
  804. vllm/model_executor/layers/sampler.py +1204 -0
  805. vllm/model_executor/layers/spec_decode_base_sampler.py +259 -0
  806. vllm/model_executor/layers/typical_acceptance_sampler.py +166 -0
  807. vllm/model_executor/layers/utils.py +116 -0
  808. vllm/model_executor/layers/vocab_parallel_embedding.py +487 -0
  809. vllm/model_executor/model_loader/__init__.py +77 -0
  810. vllm/model_executor/model_loader/base_loader.py +43 -0
  811. vllm/model_executor/model_loader/bitsandbytes_loader.py +613 -0
  812. vllm/model_executor/model_loader/default_loader.py +282 -0
  813. vllm/model_executor/model_loader/dummy_loader.py +27 -0
  814. vllm/model_executor/model_loader/gguf_loader.py +120 -0
  815. vllm/model_executor/model_loader/neuron.py +476 -0
  816. vllm/model_executor/model_loader/neuronx_distributed.py +685 -0
  817. vllm/model_executor/model_loader/runai_streamer_loader.py +109 -0
  818. vllm/model_executor/model_loader/sharded_state_loader.py +201 -0
  819. vllm/model_executor/model_loader/tensorizer.py +602 -0
  820. vllm/model_executor/model_loader/tensorizer_loader.py +127 -0
  821. vllm/model_executor/model_loader/tpu.py +113 -0
  822. vllm/model_executor/model_loader/utils.py +315 -0
  823. vllm/model_executor/model_loader/weight_utils.py +782 -0
  824. vllm/model_executor/models/__init__.py +30 -0
  825. vllm/model_executor/models/adapters.py +375 -0
  826. vllm/model_executor/models/aimv2.py +246 -0
  827. vllm/model_executor/models/arctic.py +559 -0
  828. vllm/model_executor/models/aria.py +670 -0
  829. vllm/model_executor/models/aya_vision.py +486 -0
  830. vllm/model_executor/models/baichuan.py +474 -0
  831. vllm/model_executor/models/bamba.py +558 -0
  832. vllm/model_executor/models/bart.py +938 -0
  833. vllm/model_executor/models/bert.py +513 -0
  834. vllm/model_executor/models/bert_with_rope.py +617 -0
  835. vllm/model_executor/models/blip.py +339 -0
  836. vllm/model_executor/models/blip2.py +728 -0
  837. vllm/model_executor/models/bloom.py +373 -0
  838. vllm/model_executor/models/chameleon.py +1146 -0
  839. vllm/model_executor/models/chatglm.py +478 -0
  840. vllm/model_executor/models/clip.py +407 -0
  841. vllm/model_executor/models/commandr.py +471 -0
  842. vllm/model_executor/models/config.py +200 -0
  843. vllm/model_executor/models/constant_size_cache.py +137 -0
  844. vllm/model_executor/models/dbrx.py +472 -0
  845. vllm/model_executor/models/deepseek.py +486 -0
  846. vllm/model_executor/models/deepseek_mtp.py +281 -0
  847. vllm/model_executor/models/deepseek_v2.py +935 -0
  848. vllm/model_executor/models/deepseek_vl2.py +660 -0
  849. vllm/model_executor/models/dots1.py +536 -0
  850. vllm/model_executor/models/eagle.py +261 -0
  851. vllm/model_executor/models/ernie45.py +43 -0
  852. vllm/model_executor/models/ernie45_moe.py +583 -0
  853. vllm/model_executor/models/exaone.py +551 -0
  854. vllm/model_executor/models/fairseq2_llama.py +154 -0
  855. vllm/model_executor/models/falcon.py +510 -0
  856. vllm/model_executor/models/falcon_h1.py +708 -0
  857. vllm/model_executor/models/florence2.py +1113 -0
  858. vllm/model_executor/models/fuyu.py +406 -0
  859. vllm/model_executor/models/gemma.py +427 -0
  860. vllm/model_executor/models/gemma2.py +427 -0
  861. vllm/model_executor/models/gemma3.py +535 -0
  862. vllm/model_executor/models/gemma3_mm.py +729 -0
  863. vllm/model_executor/models/gemma3n.py +811 -0
  864. vllm/model_executor/models/glm.py +23 -0
  865. vllm/model_executor/models/glm4.py +305 -0
  866. vllm/model_executor/models/glm4_1v.py +1590 -0
  867. vllm/model_executor/models/glm4v.py +657 -0
  868. vllm/model_executor/models/gpt2.py +382 -0
  869. vllm/model_executor/models/gpt_bigcode.py +335 -0
  870. vllm/model_executor/models/gpt_j.py +339 -0
  871. vllm/model_executor/models/gpt_neox.py +332 -0
  872. vllm/model_executor/models/granite.py +493 -0
  873. vllm/model_executor/models/granite_speech.py +790 -0
  874. vllm/model_executor/models/granitemoe.py +437 -0
  875. vllm/model_executor/models/granitemoehybrid.py +653 -0
  876. vllm/model_executor/models/granitemoeshared.py +341 -0
  877. vllm/model_executor/models/gritlm.py +224 -0
  878. vllm/model_executor/models/grok1.py +546 -0
  879. vllm/model_executor/models/h2ovl.py +549 -0
  880. vllm/model_executor/models/hunyuan_v1_moe.py +897 -0
  881. vllm/model_executor/models/idefics2_vision_model.py +389 -0
  882. vllm/model_executor/models/idefics3.py +786 -0
  883. vllm/model_executor/models/interfaces.py +681 -0
  884. vllm/model_executor/models/interfaces_base.py +164 -0
  885. vllm/model_executor/models/intern_vit.py +480 -0
  886. vllm/model_executor/models/internlm2.py +455 -0
  887. vllm/model_executor/models/internlm2_ve.py +147 -0
  888. vllm/model_executor/models/internvl.py +1432 -0
  889. vllm/model_executor/models/jais.py +373 -0
  890. vllm/model_executor/models/jamba.py +592 -0
  891. vllm/model_executor/models/keye.py +1736 -0
  892. vllm/model_executor/models/kimi_vl.py +585 -0
  893. vllm/model_executor/models/llama.py +644 -0
  894. vllm/model_executor/models/llama4.py +531 -0
  895. vllm/model_executor/models/llama_eagle.py +165 -0
  896. vllm/model_executor/models/llama_eagle3.py +263 -0
  897. vllm/model_executor/models/llava.py +887 -0
  898. vllm/model_executor/models/llava_next.py +604 -0
  899. vllm/model_executor/models/llava_next_video.py +492 -0
  900. vllm/model_executor/models/llava_onevision.py +985 -0
  901. vllm/model_executor/models/mamba.py +273 -0
  902. vllm/model_executor/models/mamba2.py +320 -0
  903. vllm/model_executor/models/mamba_cache.py +76 -0
  904. vllm/model_executor/models/medusa.py +219 -0
  905. vllm/model_executor/models/mimo.py +192 -0
  906. vllm/model_executor/models/mimo_mtp.py +285 -0
  907. vllm/model_executor/models/minicpm.py +592 -0
  908. vllm/model_executor/models/minicpm3.py +230 -0
  909. vllm/model_executor/models/minicpm_eagle.py +391 -0
  910. vllm/model_executor/models/minicpmo.py +772 -0
  911. vllm/model_executor/models/minicpmv.py +1307 -0
  912. vllm/model_executor/models/minimax_cache.py +36 -0
  913. vllm/model_executor/models/minimax_text_01.py +1301 -0
  914. vllm/model_executor/models/minimax_vl_01.py +374 -0
  915. vllm/model_executor/models/mistral3.py +624 -0
  916. vllm/model_executor/models/mixtral.py +488 -0
  917. vllm/model_executor/models/mixtral_quant.py +453 -0
  918. vllm/model_executor/models/mllama.py +1682 -0
  919. vllm/model_executor/models/mllama4.py +947 -0
  920. vllm/model_executor/models/mlp_speculator.py +206 -0
  921. vllm/model_executor/models/modernbert.py +339 -0
  922. vllm/model_executor/models/module_mapping.py +72 -0
  923. vllm/model_executor/models/molmo.py +1576 -0
  924. vllm/model_executor/models/moonvit.py +630 -0
  925. vllm/model_executor/models/mpt.py +331 -0
  926. vllm/model_executor/models/nemotron.py +508 -0
  927. vllm/model_executor/models/nemotron_h.py +588 -0
  928. vllm/model_executor/models/nemotron_nas.py +484 -0
  929. vllm/model_executor/models/nvlm_d.py +216 -0
  930. vllm/model_executor/models/olmo.py +389 -0
  931. vllm/model_executor/models/olmo2.py +414 -0
  932. vllm/model_executor/models/olmoe.py +468 -0
  933. vllm/model_executor/models/opt.py +412 -0
  934. vllm/model_executor/models/orion.py +349 -0
  935. vllm/model_executor/models/ovis.py +577 -0
  936. vllm/model_executor/models/paligemma.py +419 -0
  937. vllm/model_executor/models/persimmon.py +344 -0
  938. vllm/model_executor/models/phi.py +356 -0
  939. vllm/model_executor/models/phi3.py +19 -0
  940. vllm/model_executor/models/phi3_small.py +465 -0
  941. vllm/model_executor/models/phi3v.py +733 -0
  942. vllm/model_executor/models/phi4mm.py +1258 -0
  943. vllm/model_executor/models/phi4mm_audio.py +1233 -0
  944. vllm/model_executor/models/phi4mm_utils.py +1884 -0
  945. vllm/model_executor/models/phimoe.py +674 -0
  946. vllm/model_executor/models/pixtral.py +1329 -0
  947. vllm/model_executor/models/plamo2.py +738 -0
  948. vllm/model_executor/models/prithvi_geospatial_mae.py +240 -0
  949. vllm/model_executor/models/qwen.py +362 -0
  950. vllm/model_executor/models/qwen2.py +501 -0
  951. vllm/model_executor/models/qwen2_5_omni_thinker.py +923 -0
  952. vllm/model_executor/models/qwen2_5_vl.py +1175 -0
  953. vllm/model_executor/models/qwen2_audio.py +420 -0
  954. vllm/model_executor/models/qwen2_moe.py +540 -0
  955. vllm/model_executor/models/qwen2_rm.py +122 -0
  956. vllm/model_executor/models/qwen2_vl.py +1513 -0
  957. vllm/model_executor/models/qwen3.py +325 -0
  958. vllm/model_executor/models/qwen3_moe.py +541 -0
  959. vllm/model_executor/models/qwen_vl.py +796 -0
  960. vllm/model_executor/models/registry.py +634 -0
  961. vllm/model_executor/models/roberta.py +271 -0
  962. vllm/model_executor/models/siglip.py +524 -0
  963. vllm/model_executor/models/skyworkr1v.py +961 -0
  964. vllm/model_executor/models/smolvlm.py +52 -0
  965. vllm/model_executor/models/solar.py +506 -0
  966. vllm/model_executor/models/stablelm.py +343 -0
  967. vllm/model_executor/models/starcoder2.py +356 -0
  968. vllm/model_executor/models/tarsier.py +652 -0
  969. vllm/model_executor/models/telechat2.py +140 -0
  970. vllm/model_executor/models/teleflm.py +79 -0
  971. vllm/model_executor/models/transformers.py +509 -0
  972. vllm/model_executor/models/ultravox.py +670 -0
  973. vllm/model_executor/models/utils.py +744 -0
  974. vllm/model_executor/models/vision.py +147 -0
  975. vllm/model_executor/models/whisper.py +886 -0
  976. vllm/model_executor/models/zamba2.py +1036 -0
  977. vllm/model_executor/parameter.py +459 -0
  978. vllm/model_executor/pooling_metadata.py +72 -0
  979. vllm/model_executor/sampling_metadata.py +597 -0
  980. vllm/model_executor/utils.py +80 -0
  981. vllm/multimodal/__init__.py +33 -0
  982. vllm/multimodal/audio.py +116 -0
  983. vllm/multimodal/base.py +219 -0
  984. vllm/multimodal/hasher.py +91 -0
  985. vllm/multimodal/image.py +103 -0
  986. vllm/multimodal/inputs.py +878 -0
  987. vllm/multimodal/parse.py +499 -0
  988. vllm/multimodal/processing.py +1948 -0
  989. vllm/multimodal/profiling.py +283 -0
  990. vllm/multimodal/registry.py +331 -0
  991. vllm/multimodal/utils.py +492 -0
  992. vllm/multimodal/video.py +227 -0
  993. vllm/outputs.py +516 -0
  994. vllm/platforms/__init__.py +291 -0
  995. vllm/platforms/cpu.py +281 -0
  996. vllm/platforms/cuda.py +568 -0
  997. vllm/platforms/hpu.py +106 -0
  998. vllm/platforms/interface.py +551 -0
  999. vllm/platforms/neuron.py +150 -0
  1000. vllm/platforms/rocm.py +453 -0
  1001. vllm/platforms/tpu.py +206 -0
  1002. vllm/platforms/xpu.py +192 -0
  1003. vllm/plugins/__init__.py +94 -0
  1004. vllm/plugins/lora_resolvers/README.md +15 -0
  1005. vllm/plugins/lora_resolvers/__init__.py +0 -0
  1006. vllm/plugins/lora_resolvers/filesystem_resolver.py +50 -0
  1007. vllm/pooling_params.py +64 -0
  1008. vllm/profiler/__init__.py +0 -0
  1009. vllm/profiler/layerwise_profile.py +375 -0
  1010. vllm/profiler/utils.py +148 -0
  1011. vllm/prompt_adapter/__init__.py +0 -0
  1012. vllm/prompt_adapter/layers.py +83 -0
  1013. vllm/prompt_adapter/models.py +358 -0
  1014. vllm/prompt_adapter/request.py +37 -0
  1015. vllm/prompt_adapter/utils.py +98 -0
  1016. vllm/prompt_adapter/worker_manager.py +179 -0
  1017. vllm/py.typed +2 -0
  1018. vllm/reasoning/__init__.py +15 -0
  1019. vllm/reasoning/abs_reasoning_parsers.py +192 -0
  1020. vllm/reasoning/deepseek_r1_reasoning_parser.py +173 -0
  1021. vllm/reasoning/granite_reasoning_parser.py +363 -0
  1022. vllm/reasoning/qwen3_reasoning_parser.py +151 -0
  1023. vllm/sampling_params.py +602 -0
  1024. vllm/scalar_type.py +347 -0
  1025. vllm/scripts.py +15 -0
  1026. vllm/sequence.py +1568 -0
  1027. vllm/spec_decode/__init__.py +0 -0
  1028. vllm/spec_decode/batch_expansion.py +506 -0
  1029. vllm/spec_decode/draft_model_runner.py +349 -0
  1030. vllm/spec_decode/interfaces.py +99 -0
  1031. vllm/spec_decode/medusa_worker.py +138 -0
  1032. vllm/spec_decode/metrics.py +213 -0
  1033. vllm/spec_decode/mlp_speculator_worker.py +94 -0
  1034. vllm/spec_decode/mqa_scorer.py +160 -0
  1035. vllm/spec_decode/multi_step_worker.py +423 -0
  1036. vllm/spec_decode/ngram_worker.py +196 -0
  1037. vllm/spec_decode/proposer_worker_base.py +59 -0
  1038. vllm/spec_decode/smaller_tp_proposer_worker.py +196 -0
  1039. vllm/spec_decode/spec_decode_worker.py +1326 -0
  1040. vllm/spec_decode/target_model_runner.py +45 -0
  1041. vllm/spec_decode/top1_proposer.py +275 -0
  1042. vllm/spec_decode/util.py +277 -0
  1043. vllm/test_utils.py +130 -0
  1044. vllm/third_party/__init__.py +0 -0
  1045. vllm/third_party/pynvml.py +6140 -0
  1046. vllm/tracing.py +131 -0
  1047. vllm/transformers_utils/__init__.py +24 -0
  1048. vllm/transformers_utils/chat_templates/__init__.py +5 -0
  1049. vllm/transformers_utils/chat_templates/registry.py +60 -0
  1050. vllm/transformers_utils/chat_templates/template_basic.jinja +3 -0
  1051. vllm/transformers_utils/chat_templates/template_blip2.jinja +11 -0
  1052. vllm/transformers_utils/chat_templates/template_chatml.jinja +10 -0
  1053. vllm/transformers_utils/chat_templates/template_deepseek_vl2.jinja +23 -0
  1054. vllm/transformers_utils/chat_templates/template_fuyu.jinja +3 -0
  1055. vllm/transformers_utils/config.py +922 -0
  1056. vllm/transformers_utils/configs/__init__.py +57 -0
  1057. vllm/transformers_utils/configs/arctic.py +207 -0
  1058. vllm/transformers_utils/configs/chatglm.py +72 -0
  1059. vllm/transformers_utils/configs/cohere2.py +195 -0
  1060. vllm/transformers_utils/configs/dbrx.py +280 -0
  1061. vllm/transformers_utils/configs/deepseek_vl2.py +216 -0
  1062. vllm/transformers_utils/configs/eagle.py +85 -0
  1063. vllm/transformers_utils/configs/exaone.py +190 -0
  1064. vllm/transformers_utils/configs/falcon.py +90 -0
  1065. vllm/transformers_utils/configs/jais.py +238 -0
  1066. vllm/transformers_utils/configs/kimi_vl.py +37 -0
  1067. vllm/transformers_utils/configs/medusa.py +63 -0
  1068. vllm/transformers_utils/configs/minimax_text_01.py +70 -0
  1069. vllm/transformers_utils/configs/minimax_vl_01.py +71 -0
  1070. vllm/transformers_utils/configs/mllama.py +31 -0
  1071. vllm/transformers_utils/configs/mlp_speculator.py +68 -0
  1072. vllm/transformers_utils/configs/moonvit.py +33 -0
  1073. vllm/transformers_utils/configs/mpt.py +180 -0
  1074. vllm/transformers_utils/configs/nemotron.py +205 -0
  1075. vllm/transformers_utils/configs/nemotron_h.py +259 -0
  1076. vllm/transformers_utils/configs/nvlm_d.py +31 -0
  1077. vllm/transformers_utils/configs/ovis.py +184 -0
  1078. vllm/transformers_utils/configs/skyworkr1v.py +54 -0
  1079. vllm/transformers_utils/configs/solar.py +247 -0
  1080. vllm/transformers_utils/configs/telechat2.py +64 -0
  1081. vllm/transformers_utils/configs/ultravox.py +108 -0
  1082. vllm/transformers_utils/detokenizer.py +168 -0
  1083. vllm/transformers_utils/detokenizer_utils.py +189 -0
  1084. vllm/transformers_utils/processor.py +221 -0
  1085. vllm/transformers_utils/processors/__init__.py +8 -0
  1086. vllm/transformers_utils/processors/deepseek_vl2.py +363 -0
  1087. vllm/transformers_utils/processors/ovis.py +420 -0
  1088. vllm/transformers_utils/s3_utils.py +162 -0
  1089. vllm/transformers_utils/tokenizer.py +302 -0
  1090. vllm/transformers_utils/tokenizer_base.py +149 -0
  1091. vllm/transformers_utils/tokenizer_group.py +120 -0
  1092. vllm/transformers_utils/tokenizers/__init__.py +10 -0
  1093. vllm/transformers_utils/tokenizers/mistral.py +493 -0
  1094. vllm/transformers_utils/utils.py +99 -0
  1095. vllm/triton_utils/__init__.py +14 -0
  1096. vllm/triton_utils/importing.py +94 -0
  1097. vllm/usage/__init__.py +0 -0
  1098. vllm/usage/usage_lib.py +259 -0
  1099. vllm/utils/__init__.py +3008 -0
  1100. vllm/v1/__init__.py +0 -0
  1101. vllm/v1/attention/__init__.py +0 -0
  1102. vllm/v1/attention/backends/__init__.py +0 -0
  1103. vllm/v1/attention/backends/cpu_attn.py +184 -0
  1104. vllm/v1/attention/backends/flash_attn.py +757 -0
  1105. vllm/v1/attention/backends/flashinfer.py +680 -0
  1106. vllm/v1/attention/backends/flex_attention.py +491 -0
  1107. vllm/v1/attention/backends/mamba_attn.py +192 -0
  1108. vllm/v1/attention/backends/mla/__init__.py +0 -0
  1109. vllm/v1/attention/backends/mla/common.py +978 -0
  1110. vllm/v1/attention/backends/mla/cutlass_mla.py +98 -0
  1111. vllm/v1/attention/backends/mla/flashmla.py +180 -0
  1112. vllm/v1/attention/backends/mla/rocm_aiter_mla.py +241 -0
  1113. vllm/v1/attention/backends/mla/triton_mla.py +177 -0
  1114. vllm/v1/attention/backends/pallas.py +320 -0
  1115. vllm/v1/attention/backends/rocm_aiter_fa.py +609 -0
  1116. vllm/v1/attention/backends/triton_attn.py +449 -0
  1117. vllm/v1/attention/backends/utils.py +310 -0
  1118. vllm/v1/core/__init__.py +0 -0
  1119. vllm/v1/core/block_pool.py +349 -0
  1120. vllm/v1/core/encoder_cache_manager.py +254 -0
  1121. vllm/v1/core/kv_cache_coordinator.py +369 -0
  1122. vllm/v1/core/kv_cache_manager.py +398 -0
  1123. vllm/v1/core/kv_cache_utils.py +999 -0
  1124. vllm/v1/core/sched/__init__.py +0 -0
  1125. vllm/v1/core/sched/interface.py +150 -0
  1126. vllm/v1/core/sched/output.py +157 -0
  1127. vllm/v1/core/sched/request_queue.py +224 -0
  1128. vllm/v1/core/sched/scheduler.py +1115 -0
  1129. vllm/v1/core/sched/utils.py +36 -0
  1130. vllm/v1/core/single_type_kv_cache_manager.py +444 -0
  1131. vllm/v1/engine/__init__.py +179 -0
  1132. vllm/v1/engine/async_llm.py +626 -0
  1133. vllm/v1/engine/coordinator.py +278 -0
  1134. vllm/v1/engine/core.py +1046 -0
  1135. vllm/v1/engine/core_client.py +1049 -0
  1136. vllm/v1/engine/detokenizer.py +292 -0
  1137. vllm/v1/engine/exceptions.py +17 -0
  1138. vllm/v1/engine/llm_engine.py +322 -0
  1139. vllm/v1/engine/logprobs.py +200 -0
  1140. vllm/v1/engine/mm_input_cache.py +91 -0
  1141. vllm/v1/engine/output_processor.py +477 -0
  1142. vllm/v1/engine/parallel_sampling.py +133 -0
  1143. vllm/v1/engine/processor.py +422 -0
  1144. vllm/v1/engine/utils.py +546 -0
  1145. vllm/v1/executor/__init__.py +0 -0
  1146. vllm/v1/executor/abstract.py +113 -0
  1147. vllm/v1/executor/multiproc_executor.py +532 -0
  1148. vllm/v1/executor/ray_distributed_executor.py +62 -0
  1149. vllm/v1/kv_cache_interface.py +223 -0
  1150. vllm/v1/metrics/__init__.py +0 -0
  1151. vllm/v1/metrics/loggers.py +557 -0
  1152. vllm/v1/metrics/prometheus.py +82 -0
  1153. vllm/v1/metrics/ray_wrappers.py +131 -0
  1154. vllm/v1/metrics/reader.py +246 -0
  1155. vllm/v1/metrics/stats.py +240 -0
  1156. vllm/v1/outputs.py +124 -0
  1157. vllm/v1/pool/__init__.py +0 -0
  1158. vllm/v1/pool/metadata.py +17 -0
  1159. vllm/v1/request.py +229 -0
  1160. vllm/v1/sample/__init__.py +0 -0
  1161. vllm/v1/sample/logits_processor.py +517 -0
  1162. vllm/v1/sample/metadata.py +43 -0
  1163. vllm/v1/sample/ops/__init__.py +0 -0
  1164. vllm/v1/sample/ops/bad_words.py +39 -0
  1165. vllm/v1/sample/ops/penalties.py +43 -0
  1166. vllm/v1/sample/ops/topk_topp_sampler.py +296 -0
  1167. vllm/v1/sample/rejection_sampler.py +631 -0
  1168. vllm/v1/sample/sampler.py +226 -0
  1169. vllm/v1/sample/tpu/__init__.py +0 -0
  1170. vllm/v1/sample/tpu/metadata.py +124 -0
  1171. vllm/v1/sample/tpu/sampler.py +145 -0
  1172. vllm/v1/serial_utils.py +315 -0
  1173. vllm/v1/spec_decode/__init__.py +0 -0
  1174. vllm/v1/spec_decode/eagle.py +441 -0
  1175. vllm/v1/spec_decode/medusa.py +64 -0
  1176. vllm/v1/spec_decode/metadata.py +62 -0
  1177. vllm/v1/spec_decode/metrics.py +178 -0
  1178. vllm/v1/spec_decode/ngram_proposer.py +132 -0
  1179. vllm/v1/spec_decode/utils.py +41 -0
  1180. vllm/v1/structured_output/__init__.py +227 -0
  1181. vllm/v1/structured_output/backend_guidance.py +245 -0
  1182. vllm/v1/structured_output/backend_types.py +134 -0
  1183. vllm/v1/structured_output/backend_xgrammar.py +318 -0
  1184. vllm/v1/structured_output/request.py +86 -0
  1185. vllm/v1/structured_output/utils.py +175 -0
  1186. vllm/v1/utils.py +377 -0
  1187. vllm/v1/worker/__init__.py +0 -0
  1188. vllm/v1/worker/block_table.py +142 -0
  1189. vllm/v1/worker/cpu_model_runner.py +91 -0
  1190. vllm/v1/worker/cpu_worker.py +153 -0
  1191. vllm/v1/worker/gpu_input_batch.py +757 -0
  1192. vllm/v1/worker/gpu_model_runner.py +2739 -0
  1193. vllm/v1/worker/gpu_worker.py +408 -0
  1194. vllm/v1/worker/lora_model_runner_mixin.py +177 -0
  1195. vllm/v1/worker/tpu_input_batch.py +585 -0
  1196. vllm/v1/worker/tpu_model_runner.py +1849 -0
  1197. vllm/v1/worker/tpu_worker.py +315 -0
  1198. vllm/v1/worker/utils.py +112 -0
  1199. vllm/v1/worker/worker_base.py +65 -0
  1200. vllm/v1/worker/xpu_model_runner.py +33 -0
  1201. vllm/v1/worker/xpu_worker.py +165 -0
  1202. vllm/version.py +41 -0
  1203. vllm/vllm_flash_attn/.gitkeep +0 -0
  1204. vllm/worker/__init__.py +0 -0
  1205. vllm/worker/cache_engine.py +145 -0
  1206. vllm/worker/cpu_enc_dec_model_runner.py +326 -0
  1207. vllm/worker/cpu_model_runner.py +671 -0
  1208. vllm/worker/cpu_pooling_model_runner.py +125 -0
  1209. vllm/worker/cpu_worker.py +452 -0
  1210. vllm/worker/enc_dec_model_runner.py +555 -0
  1211. vllm/worker/hpu_model_runner.py +2320 -0
  1212. vllm/worker/hpu_worker.py +484 -0
  1213. vllm/worker/model_runner.py +2178 -0
  1214. vllm/worker/model_runner_base.py +282 -0
  1215. vllm/worker/multi_step_hpu_worker.py +123 -0
  1216. vllm/worker/multi_step_model_runner.py +911 -0
  1217. vllm/worker/multi_step_neuron_model_runner.py +84 -0
  1218. vllm/worker/multi_step_neuronx_distributed_model_runner.py +63 -0
  1219. vllm/worker/multi_step_tpu_worker.py +108 -0
  1220. vllm/worker/multi_step_worker.py +197 -0
  1221. vllm/worker/neuron_model_runner.py +460 -0
  1222. vllm/worker/neuron_worker.py +193 -0
  1223. vllm/worker/neuronx_distributed_model_runner.py +294 -0
  1224. vllm/worker/pooling_model_runner.py +211 -0
  1225. vllm/worker/tpu_model_runner.py +909 -0
  1226. vllm/worker/tpu_worker.py +337 -0
  1227. vllm/worker/utils.py +53 -0
  1228. vllm/worker/worker.py +577 -0
  1229. vllm/worker/worker_base.py +646 -0
  1230. vllm/worker/xpu_model_runner.py +606 -0
  1231. vllm/worker/xpu_worker.py +186 -0
  1232. vllm_cpu-0.9.2.post2.dist-info/METADATA +339 -0
  1233. vllm_cpu-0.9.2.post2.dist-info/RECORD +1236 -0
  1234. vllm_cpu-0.9.2.post2.dist-info/WHEEL +5 -0
  1235. vllm_cpu-0.9.2.post2.dist-info/entry_points.txt +5 -0
  1236. vllm_cpu-0.9.2.post2.dist-info/top_level.txt +1 -0
vllm/utils/__init__.py ADDED
@@ -0,0 +1,3008 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+
4
+ from __future__ import annotations
5
+
6
+ import asyncio
7
+ import concurrent
8
+ import contextlib
9
+ import datetime
10
+ import enum
11
+ import gc
12
+ import getpass
13
+ import hashlib
14
+ import importlib
15
+ import importlib.metadata
16
+ import importlib.util
17
+ import inspect
18
+ import ipaddress
19
+ import json
20
+ import multiprocessing
21
+ import os
22
+ import pickle
23
+ import signal
24
+ import socket
25
+ import subprocess
26
+ import sys
27
+ import tempfile
28
+ import textwrap
29
+ import threading
30
+ import time
31
+ import traceback
32
+ import types
33
+ import uuid
34
+ import warnings
35
+ import weakref
36
+ from argparse import (Action, ArgumentDefaultsHelpFormatter, ArgumentParser,
37
+ ArgumentTypeError, RawDescriptionHelpFormatter,
38
+ _ArgumentGroup)
39
+ from asyncio import FIRST_COMPLETED, AbstractEventLoop, Task
40
+ from collections import UserDict, defaultdict
41
+ from collections.abc import (AsyncGenerator, Awaitable, Collection, Generator,
42
+ Hashable, Iterable, Iterator, KeysView, Mapping,
43
+ Sequence)
44
+ from concurrent.futures.process import ProcessPoolExecutor
45
+ from dataclasses import dataclass, field
46
+ from functools import cache, lru_cache, partial, wraps
47
+ from types import MappingProxyType
48
+ from typing import (TYPE_CHECKING, Any, Callable, Generic, Literal, NamedTuple,
49
+ Optional, Tuple, TypeVar, Union, cast, overload)
50
+ from urllib.parse import urlparse
51
+ from uuid import uuid4
52
+
53
+ import cachetools
54
+ import cloudpickle
55
+ import numpy as np
56
+ import numpy.typing as npt
57
+ import psutil
58
+ import regex as re
59
+ import torch
60
+ import torch.types
61
+ import yaml
62
+ import zmq
63
+ import zmq.asyncio
64
+ from packaging import version
65
+ from packaging.version import Version
66
+ from torch.library import Library
67
+ from typing_extensions import Never, ParamSpec, TypeIs, assert_never
68
+
69
+ import vllm.envs as envs
70
+ from vllm.logger import enable_trace_function_call, init_logger
71
+
72
+ if TYPE_CHECKING:
73
+ from argparse import Namespace
74
+
75
+ from vllm.config import ModelConfig, VllmConfig
76
+
77
+ logger = init_logger(__name__)
78
+
79
+ # This value is chosen to have a balance between ITL and TTFT. Note it is
80
+ # not optimized for throughput.
81
+ DEFAULT_MAX_NUM_BATCHED_TOKENS = 2048
82
+ POOLING_MODEL_MAX_NUM_BATCHED_TOKENS = 32768
83
+ MULTIMODAL_MODEL_MAX_NUM_BATCHED_TOKENS = 5120
84
+
85
+ # Exception strings for non-implemented encoder/decoder scenarios
86
+
87
+ # Reminder: Please update docs/features/compatibility_matrix.md
88
+ # If the feature combo become valid
89
+
90
+ STR_NOT_IMPL_ENC_DEC_SWA = \
91
+ "Sliding window attention for encoder/decoder models " + \
92
+ "is not currently supported."
93
+
94
+ STR_NOT_IMPL_ENC_DEC_PREFIX_CACHE = \
95
+ "Prefix caching for encoder/decoder models " + \
96
+ "is not currently supported."
97
+
98
+ STR_NOT_IMPL_ENC_DEC_CHUNKED_PREFILL = \
99
+ "Chunked prefill for encoder/decoder models " + \
100
+ "is not currently supported."
101
+
102
+ STR_NOT_IMPL_ENC_DEC_LOGIT_SOFTCAP = (
103
+ "Models with logits_soft_cap "
104
+ "require FlashInfer backend, which is "
105
+ "currently not supported for encoder/decoder "
106
+ "models.")
107
+
108
+ STR_NOT_IMPL_ENC_DEC_LORA = ("LoRA is not currently "
109
+ "supported with encoder/decoder "
110
+ "models.")
111
+
112
+ STR_NOT_IMPL_ENC_DEC_PP = ("Pipeline parallelism is not "
113
+ "currently supported with "
114
+ "encoder/decoder models.")
115
+
116
+ STR_NOT_IMPL_ENC_DEC_MM = ("Multimodal is not currently "
117
+ "supported with encoder/decoder "
118
+ "models.")
119
+
120
+ STR_NOT_IMPL_ENC_DEC_SPEC_DEC = ("Speculative decoding is not "
121
+ "currently supported with encoder/"
122
+ "decoder models.")
123
+
124
+ STR_NOT_IMPL_ENC_DEC_BACKEND = ("XFormers and Flash-Attention are the only "
125
+ "backends currently supported with encoder/"
126
+ "decoder models.")
127
+
128
+ STR_NOT_IMPL_ENC_DEC_PROMPT_ADAPTER = ("Prompt adapters are not "
129
+ "currently supported with encoder/"
130
+ "decoder models.")
131
+
132
+ # Efficiently import all enc/dec error strings
133
+ # rather than having to import all of the above
134
+ STR_NOT_IMPL_ENC_DEC_ERR_STRS = {
135
+ "STR_NOT_IMPL_ENC_DEC_SWA": STR_NOT_IMPL_ENC_DEC_SWA,
136
+ "STR_NOT_IMPL_ENC_DEC_PREFIX_CACHE": STR_NOT_IMPL_ENC_DEC_PREFIX_CACHE,
137
+ "STR_NOT_IMPL_ENC_DEC_CHUNKED_PREFILL":
138
+ STR_NOT_IMPL_ENC_DEC_CHUNKED_PREFILL,
139
+ "STR_NOT_IMPL_ENC_DEC_LOGIT_SOFTCAP": STR_NOT_IMPL_ENC_DEC_LOGIT_SOFTCAP,
140
+ "STR_NOT_IMPL_ENC_DEC_LORA": STR_NOT_IMPL_ENC_DEC_LORA,
141
+ "STR_NOT_IMPL_ENC_DEC_PP": STR_NOT_IMPL_ENC_DEC_PP,
142
+ "STR_NOT_IMPL_ENC_DEC_MM": STR_NOT_IMPL_ENC_DEC_MM,
143
+ "STR_NOT_IMPL_ENC_DEC_SPEC_DEC": STR_NOT_IMPL_ENC_DEC_SPEC_DEC,
144
+ "STR_NOT_IMPL_ENC_DEC_BACKEND": STR_NOT_IMPL_ENC_DEC_BACKEND,
145
+ "STR_NOT_IMPL_ENC_DEC_PROMPT_ADAPTER": STR_NOT_IMPL_ENC_DEC_PROMPT_ADAPTER,
146
+ }
147
+
148
+ # Constants related to forcing the attention backend selection
149
+
150
+ # String name of register which may be set in order to
151
+ # force auto-selection of attention backend by Attention
152
+ # wrapper
153
+ STR_BACKEND_ENV_VAR: str = "VLLM_ATTENTION_BACKEND"
154
+
155
+ # Possible string values of STR_BACKEND_ENV_VAR
156
+ # register, corresponding to possible backends
157
+ STR_FLASHINFER_ATTN_VAL: str = "FLASHINFER"
158
+ STR_TORCH_SDPA_ATTN_VAL: str = "TORCH_SDPA"
159
+ STR_ROCM_FLASH_ATTN_VAL: str = "ROCM_FLASH"
160
+ STR_XFORMERS_ATTN_VAL: str = "XFORMERS"
161
+ STR_FLASH_ATTN_VAL: str = "FLASH_ATTN"
162
+ STR_DUAL_CHUNK_FLASH_ATTN_VAL: str = "DUAL_CHUNK_FLASH_ATTN"
163
+ STR_INVALID_VAL: str = "INVALID"
164
+
165
+ GB_bytes = 1_000_000_000
166
+ """The number of bytes in one gigabyte (GB)."""
167
+
168
+ GiB_bytes = 1 << 30
169
+ """The number of bytes in one gibibyte (GiB)."""
170
+
171
+ STR_DTYPE_TO_TORCH_DTYPE = {
172
+ "half": torch.half,
173
+ "bfloat16": torch.bfloat16,
174
+ "float": torch.float,
175
+ "fp8": torch.uint8,
176
+ "fp8_e4m3": torch.uint8,
177
+ "fp8_e5m2": torch.uint8,
178
+ "int8": torch.int8,
179
+ }
180
+
181
+ TORCH_DTYPE_TO_NUMPY_DTYPE = {
182
+ torch.float16: np.float16,
183
+ torch.float32: np.float32,
184
+ torch.float64: np.float64,
185
+ torch.uint8: np.uint8,
186
+ torch.int32: np.int32,
187
+ torch.int64: np.int64,
188
+ }
189
+
190
+
191
+ @contextlib.contextmanager
192
+ def set_default_torch_num_threads(num_threads: int):
193
+ """Sets the default number of threads for PyTorch to the given value."""
194
+ old_num_threads = torch.get_num_threads()
195
+ torch.set_num_threads(num_threads)
196
+ yield
197
+ torch.set_num_threads(old_num_threads)
198
+
199
+
200
+ P = ParamSpec('P')
201
+ T = TypeVar("T")
202
+ U = TypeVar("U")
203
+
204
+ _K = TypeVar("_K", bound=Hashable)
205
+ _V = TypeVar("_V")
206
+ _T = TypeVar("_T")
207
+
208
+
209
+ class _Sentinel:
210
+ ...
211
+
212
+
213
+ ALL_PINNED_SENTINEL = _Sentinel()
214
+
215
+
216
+ class Device(enum.Enum):
217
+ GPU = enum.auto()
218
+ CPU = enum.auto()
219
+
220
+
221
+ class LayerBlockType(enum.Enum):
222
+ attention = "attention"
223
+ mamba = "mamba"
224
+
225
+
226
+ class Counter:
227
+
228
+ def __init__(self, start: int = 0) -> None:
229
+ self.counter = start
230
+
231
+ def __next__(self) -> int:
232
+ i = self.counter
233
+ self.counter += 1
234
+ return i
235
+
236
+ def reset(self) -> None:
237
+ self.counter = 0
238
+
239
+
240
+ class _MappingOrderCacheView(UserDict[_K, _V]):
241
+
242
+ def __init__(self, data: Mapping[_K, _V], ordered_keys: Mapping[_K, None]):
243
+ super().__init__(data)
244
+ self.ordered_keys = ordered_keys
245
+
246
+ def __iter__(self) -> Iterator[_K]:
247
+ return iter(self.ordered_keys)
248
+
249
+ def keys(self) -> KeysView[_K]:
250
+ return KeysView(self.ordered_keys)
251
+
252
+
253
+ class CacheInfo(NamedTuple):
254
+ hits: int
255
+ total: int
256
+
257
+ @property
258
+ def hit_ratio(self) -> float:
259
+ if self.total == 0:
260
+ return 0
261
+
262
+ return self.hits / self.total
263
+
264
+ def __sub__(self, other: CacheInfo):
265
+ return CacheInfo(
266
+ hits=self.hits - other.hits,
267
+ total=self.total - other.total,
268
+ )
269
+
270
+
271
+ class LRUCache(cachetools.LRUCache[_K, _V], Generic[_K, _V]):
272
+
273
+ def __init__(self,
274
+ capacity: float,
275
+ getsizeof: Optional[Callable[[_V], float]] = None):
276
+ super().__init__(capacity, getsizeof)
277
+
278
+ self.pinned_items = set[_K]()
279
+
280
+ self._hits = 0
281
+ self._total = 0
282
+ self._last_info = CacheInfo(hits=0, total=0)
283
+
284
+ def __getitem__(self, key: _K, *, update_info: bool = True) -> _V:
285
+ value = super().__getitem__(key)
286
+
287
+ if update_info:
288
+ self._hits += 1
289
+ self._total += 1
290
+
291
+ return value
292
+
293
+ def __delitem__(self, key: _K) -> None:
294
+ run_on_remove = key in self
295
+ value = self.__getitem__(key,
296
+ update_info=False) # type: ignore[call-arg]
297
+ super().__delitem__(key)
298
+ if key in self.pinned_items:
299
+ # Todo: add warning to inform that del pinned item
300
+ self._unpin(key)
301
+ if run_on_remove:
302
+ self._on_remove(key, value)
303
+
304
+ @property
305
+ def cache(self) -> Mapping[_K, _V]:
306
+ """Return the internal cache dictionary in order (read-only)."""
307
+ return _MappingOrderCacheView(
308
+ self._Cache__data, # type: ignore
309
+ self.order)
310
+
311
+ @property
312
+ def order(self) -> Mapping[_K, None]:
313
+ """Return the internal order dictionary (read-only)."""
314
+ return MappingProxyType(self._LRUCache__order) # type: ignore
315
+
316
+ @property
317
+ def capacity(self) -> float:
318
+ return self.maxsize
319
+
320
+ @property
321
+ def usage(self) -> float:
322
+ if self.maxsize == 0:
323
+ return 0
324
+
325
+ return self.currsize / self.maxsize
326
+
327
+ def stat(self, *, delta: bool = False) -> CacheInfo:
328
+ """
329
+ Gets the cumulative number of hits and queries against this cache.
330
+
331
+ If `delta=True`, instead gets these statistics
332
+ since the last call that also passed `delta=True`.
333
+ """
334
+ info = CacheInfo(hits=self._hits, total=self._total)
335
+
336
+ if delta:
337
+ info_delta = info - self._last_info
338
+ self._last_info = info
339
+ info = info_delta
340
+
341
+ return info
342
+
343
+ def touch(self, key: _K) -> None:
344
+ try:
345
+ self._LRUCache__order.move_to_end(key) # type: ignore
346
+ except KeyError:
347
+ self._LRUCache__order[key] = None # type: ignore
348
+
349
+ @overload
350
+ def get(self, key: _K, /) -> Optional[_V]:
351
+ ...
352
+
353
+ @overload
354
+ def get(self, key: _K, /, default: Union[_V, _T]) -> Union[_V, _T]:
355
+ ...
356
+
357
+ def get(self,
358
+ key: _K,
359
+ /,
360
+ default: Optional[Union[_V,
361
+ _T]] = None) -> Optional[Union[_V, _T]]:
362
+ value: Optional[Union[_V, _T]]
363
+ if key in self:
364
+ value = self.__getitem__(
365
+ key, update_info=False) # type: ignore[call-arg]
366
+
367
+ self._hits += 1
368
+ else:
369
+ value = default
370
+
371
+ self._total += 1
372
+ return value
373
+
374
+ @overload
375
+ def pop(self, key: _K) -> _V:
376
+ ...
377
+
378
+ @overload
379
+ def pop(self, key: _K, default: Union[_V, _T]) -> Union[_V, _T]:
380
+ ...
381
+
382
+ def pop(self,
383
+ key: _K,
384
+ default: Optional[Union[_V,
385
+ _T]] = None) -> Optional[Union[_V, _T]]:
386
+ value: Optional[Union[_V, _T]]
387
+ if key not in self:
388
+ return default
389
+
390
+ value = self.__getitem__(key,
391
+ update_info=False) # type: ignore[call-arg]
392
+ self.__delitem__(key)
393
+ return value
394
+
395
+ def put(self, key: _K, value: _V) -> None:
396
+ self.__setitem__(key, value)
397
+
398
+ def pin(self, key: _K) -> None:
399
+ """
400
+ Pins a key in the cache preventing it from being
401
+ evicted in the LRU order.
402
+ """
403
+ if key not in self:
404
+ raise ValueError(f"Cannot pin key: {key} not in cache.")
405
+ self.pinned_items.add(key)
406
+
407
+ def _unpin(self, key: _K) -> None:
408
+ """
409
+ Unpins a key in the cache allowing it to be
410
+ evicted in the LRU order.
411
+ """
412
+ self.pinned_items.remove(key)
413
+
414
+ def _on_remove(self, key: _K, value: Optional[_V]) -> None:
415
+ pass
416
+
417
+ def remove_oldest(self, *, remove_pinned: bool = False) -> None:
418
+ if len(self) == 0:
419
+ return
420
+
421
+ self.popitem(remove_pinned=remove_pinned)
422
+
423
+ def _remove_old_if_needed(self) -> None:
424
+ while self.currsize > self.capacity:
425
+ self.remove_oldest()
426
+
427
+ def popitem(self, remove_pinned: bool = False):
428
+ """Remove and return the `(key, value)` pair least recently used."""
429
+ if not remove_pinned:
430
+ # pop the oldest item in the cache that is not pinned
431
+ lru_key = next(
432
+ (key for key in self.order if key not in self.pinned_items),
433
+ ALL_PINNED_SENTINEL)
434
+ if lru_key is ALL_PINNED_SENTINEL:
435
+ raise RuntimeError("All items are pinned, "
436
+ "cannot remove oldest from the cache.")
437
+ else:
438
+ lru_key = next(iter(self.order))
439
+ value = self.pop(cast(_K, lru_key))
440
+ return (lru_key, value)
441
+
442
+ def clear(self) -> None:
443
+ while len(self) > 0:
444
+ self.remove_oldest(remove_pinned=True)
445
+
446
+ self._hits = 0
447
+ self._total = 0
448
+ self._last_info = CacheInfo(hits=0, total=0)
449
+
450
+
451
+ class PyObjectCache:
452
+ """Used to cache python objects to avoid object allocations
453
+ across scheduler iterations.
454
+ """
455
+
456
+ def __init__(self, obj_builder):
457
+ self._obj_builder = obj_builder
458
+ self._index = 0
459
+
460
+ self._obj_cache = []
461
+ for _ in range(128):
462
+ self._obj_cache.append(self._obj_builder())
463
+
464
+ def _grow_cache(self):
465
+ # Double the size of the cache
466
+ num_objs = len(self._obj_cache)
467
+ for _ in range(num_objs):
468
+ self._obj_cache.append(self._obj_builder())
469
+
470
+ def get_object(self):
471
+ """Returns a pre-allocated cached object. If there is not enough
472
+ objects, then the cache size will double.
473
+ """
474
+ if self._index >= len(self._obj_cache):
475
+ self._grow_cache()
476
+ assert self._index < len(self._obj_cache)
477
+
478
+ obj = self._obj_cache[self._index]
479
+ self._index += 1
480
+
481
+ return obj
482
+
483
+ def reset(self):
484
+ """Makes all cached-objects available for the next scheduler iteration.
485
+ """
486
+ self._index = 0
487
+
488
+
489
+ @cache
490
+ def get_max_shared_memory_bytes(gpu: int = 0) -> int:
491
+ """Returns the maximum shared memory per thread block in bytes."""
492
+ from vllm import _custom_ops as ops
493
+ max_shared_mem = (
494
+ ops.get_max_shared_memory_per_block_device_attribute(gpu))
495
+ # value 0 will cause MAX_SEQ_LEN become negative and test_attention.py
496
+ # will fail
497
+ assert max_shared_mem > 0, "max_shared_mem can not be zero"
498
+ return int(max_shared_mem)
499
+
500
+
501
+ def get_cpu_memory() -> int:
502
+ """Returns the total CPU memory of the node in bytes."""
503
+ return psutil.virtual_memory().total
504
+
505
+
506
+ def random_uuid() -> str:
507
+ return str(uuid.uuid4().hex)
508
+
509
+
510
+ def make_async(
511
+ func: Callable[P, T],
512
+ executor: Optional[concurrent.futures.Executor] = None
513
+ ) -> Callable[P, Awaitable[T]]:
514
+ """Take a blocking function, and run it on in an executor thread.
515
+
516
+ This function prevents the blocking function from blocking the
517
+ asyncio event loop.
518
+ The code in this function needs to be thread safe.
519
+ """
520
+
521
+ def _async_wrapper(*args: P.args, **kwargs: P.kwargs) -> asyncio.Future:
522
+ loop = asyncio.get_event_loop()
523
+ p_func = partial(func, *args, **kwargs)
524
+ return loop.run_in_executor(executor=executor, func=p_func)
525
+
526
+ return _async_wrapper
527
+
528
+
529
+ def _next_task(iterator: AsyncGenerator[T, None],
530
+ loop: AbstractEventLoop) -> Task:
531
+ # Can use anext() in python >= 3.10
532
+ return loop.create_task(iterator.__anext__()) # type: ignore[arg-type]
533
+
534
+
535
+ async def merge_async_iterators(
536
+ *iterators: AsyncGenerator[T,
537
+ None], ) -> AsyncGenerator[tuple[int, T], None]:
538
+ """Merge multiple asynchronous iterators into a single iterator.
539
+
540
+ This method handle the case where some iterators finish before others.
541
+ When it yields, it yields a tuple (i, item) where i is the index of the
542
+ iterator that yields the item.
543
+ """
544
+ if len(iterators) == 1:
545
+ # Fast-path single iterator case.
546
+ async for item in iterators[0]:
547
+ yield 0, item
548
+ return
549
+
550
+ loop = asyncio.get_running_loop()
551
+
552
+ awaits = {_next_task(pair[1], loop): pair for pair in enumerate(iterators)}
553
+ try:
554
+ while awaits:
555
+ done, _ = await asyncio.wait(awaits.keys(),
556
+ return_when=FIRST_COMPLETED)
557
+ for d in done:
558
+ pair = awaits.pop(d)
559
+ try:
560
+ item = await d
561
+ i, it = pair
562
+ awaits[_next_task(it, loop)] = pair
563
+ yield i, item
564
+ except StopAsyncIteration:
565
+ pass
566
+ finally:
567
+ # Cancel any remaining iterators
568
+ for f, (_, it) in awaits.items():
569
+ with contextlib.suppress(BaseException):
570
+ f.cancel()
571
+ await it.aclose()
572
+
573
+
574
+ async def collect_from_async_generator(
575
+ iterator: AsyncGenerator[T, None]) -> list[T]:
576
+ """Collect all items from an async generator into a list."""
577
+ items = []
578
+ async for item in iterator:
579
+ items.append(item)
580
+ return items
581
+
582
+
583
+ def get_ip() -> str:
584
+ host_ip = envs.VLLM_HOST_IP
585
+ if "HOST_IP" in os.environ and "VLLM_HOST_IP" not in os.environ:
586
+ logger.warning(
587
+ "The environment variable HOST_IP is deprecated and ignored, as"
588
+ " it is often used by Docker and other software to"
589
+ " interact with the container's network stack. Please "
590
+ "use VLLM_HOST_IP instead to set the IP address for vLLM processes"
591
+ " to communicate with each other.")
592
+ if host_ip:
593
+ return host_ip
594
+
595
+ # IP is not set, try to get it from the network interface
596
+
597
+ # try ipv4
598
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
599
+ try:
600
+ s.connect(("8.8.8.8", 80)) # Doesn't need to be reachable
601
+ return s.getsockname()[0]
602
+ except Exception:
603
+ pass
604
+
605
+ # try ipv6
606
+ try:
607
+ s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
608
+ # Google's public DNS server, see
609
+ # https://developers.google.com/speed/public-dns/docs/using#addresses
610
+ s.connect(("2001:4860:4860::8888", 80)) # Doesn't need to be reachable
611
+ return s.getsockname()[0]
612
+ except Exception:
613
+ pass
614
+
615
+ warnings.warn(
616
+ "Failed to get the IP address, using 0.0.0.0 by default."
617
+ "The value can be set by the environment variable"
618
+ " VLLM_HOST_IP or HOST_IP.",
619
+ stacklevel=2)
620
+ return "0.0.0.0"
621
+
622
+
623
+ def is_valid_ipv6_address(address: str) -> bool:
624
+ try:
625
+ ipaddress.IPv6Address(address)
626
+ return True
627
+ except ValueError:
628
+ return False
629
+
630
+
631
+ def split_host_port(host_port: str) -> Tuple[str, int]:
632
+ # ipv6
633
+ if host_port.startswith('['):
634
+ host, port = host_port.rsplit(']', 1)
635
+ host = host[1:]
636
+ port = port.split(':')[1]
637
+ return host, int(port)
638
+ else:
639
+ host, port = host_port.split(':')
640
+ return host, int(port)
641
+
642
+
643
+ def join_host_port(host: str, port: int) -> str:
644
+ if is_valid_ipv6_address(host):
645
+ return f"[{host}]:{port}"
646
+ else:
647
+ return f"{host}:{port}"
648
+
649
+
650
+ def get_distributed_init_method(ip: str, port: int) -> str:
651
+ return get_tcp_uri(ip, port)
652
+
653
+
654
+ def get_tcp_uri(ip: str, port: int) -> str:
655
+ if is_valid_ipv6_address(ip):
656
+ return f"tcp://[{ip}]:{port}"
657
+ else:
658
+ return f"tcp://{ip}:{port}"
659
+
660
+
661
+ def get_open_zmq_ipc_path() -> str:
662
+ base_rpc_path = envs.VLLM_RPC_BASE_PATH
663
+ return f"ipc://{base_rpc_path}/{uuid4()}"
664
+
665
+
666
+ def get_open_zmq_inproc_path() -> str:
667
+ return f"inproc://{uuid4()}"
668
+
669
+
670
+ def get_open_port() -> int:
671
+ """
672
+ Get an open port for the vLLM process to listen on.
673
+ An edge case to handle, is when we run data parallel,
674
+ we need to avoid ports that are potentially used by
675
+ the data parallel master process.
676
+ Right now we reserve 10 ports for the data parallel master
677
+ process. Currently it uses 2 ports.
678
+ """
679
+ if "VLLM_DP_MASTER_PORT" in os.environ:
680
+ dp_master_port = envs.VLLM_DP_MASTER_PORT
681
+ reserved_port_range = range(dp_master_port, dp_master_port + 10)
682
+ while True:
683
+ candidate_port = _get_open_port()
684
+ if candidate_port not in reserved_port_range:
685
+ return candidate_port
686
+ return _get_open_port()
687
+
688
+
689
+ def _get_open_port() -> int:
690
+ port = envs.VLLM_PORT
691
+ if port is not None:
692
+ while True:
693
+ try:
694
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
695
+ s.bind(("", port))
696
+ return port
697
+ except OSError:
698
+ port += 1 # Increment port number if already in use
699
+ logger.info("Port %d is already in use, trying port %d",
700
+ port - 1, port)
701
+ # try ipv4
702
+ try:
703
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
704
+ s.bind(("", 0))
705
+ return s.getsockname()[1]
706
+ except OSError:
707
+ # try ipv6
708
+ with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s:
709
+ s.bind(("", 0))
710
+ return s.getsockname()[1]
711
+
712
+
713
+ def find_process_using_port(port: int) -> Optional[psutil.Process]:
714
+ # TODO: We can not check for running processes with network
715
+ # port on macOS. Therefore, we can not have a full graceful shutdown
716
+ # of vLLM. For now, let's not look for processes in this case.
717
+ # Ref: https://www.florianreinhard.de/accessdenied-in-psutil/
718
+ if sys.platform.startswith("darwin"):
719
+ return None
720
+
721
+ for conn in psutil.net_connections():
722
+ if conn.laddr.port == port:
723
+ try:
724
+ return psutil.Process(conn.pid)
725
+ except psutil.NoSuchProcess:
726
+ return None
727
+ return None
728
+
729
+
730
+ def update_environment_variables(envs: dict[str, str]):
731
+ for k, v in envs.items():
732
+ if k in os.environ and os.environ[k] != v:
733
+ logger.warning(
734
+ "Overwriting environment variable %s "
735
+ "from '%s' to '%s'", k, os.environ[k], v)
736
+ os.environ[k] = v
737
+
738
+
739
+ def chunk_list(lst: list[T], chunk_size: int):
740
+ """Yield successive chunk_size chunks from lst."""
741
+ for i in range(0, len(lst), chunk_size):
742
+ yield lst[i:i + chunk_size]
743
+
744
+
745
+ def cdiv(a: int, b: int) -> int:
746
+ """Ceiling division."""
747
+ return -(a // -b)
748
+
749
+
750
+ def next_power_of_2(n) -> int:
751
+ """The next power of 2 (inclusive)"""
752
+ if n < 1:
753
+ return 1
754
+ return 1 << (n - 1).bit_length()
755
+
756
+
757
+ def round_up(x: int, y: int) -> int:
758
+ return ((x + y - 1) // y) * y
759
+
760
+
761
+ def round_down(x: int, y: int) -> int:
762
+ return (x // y) * y
763
+
764
+
765
+ def _generate_random_fp8(
766
+ tensor: torch.Tensor,
767
+ low: float,
768
+ high: float,
769
+ ) -> None:
770
+ # NOTE(zhaoyang): Due to NaN and Inf representation for fp8 data type,
771
+ # it may occur Inf or NaN if we directly use torch.randint
772
+ # to generate random data for fp8 data.
773
+ # For example, s.11111.00 in fp8e5m2 format represents Inf.
774
+ # | E4M3 | E5M2
775
+ # -----|-------------|-------------------
776
+ # Inf | N/A | s.11111.00
777
+ # NaN | s.1111.111 | s.11111.{01,10,11}
778
+ from vllm import _custom_ops as ops
779
+ tensor_tmp = torch.empty_like(tensor, dtype=torch.float16)
780
+ tensor_tmp.uniform_(low, high)
781
+ ops.convert_fp8(tensor, tensor_tmp)
782
+ del tensor_tmp
783
+
784
+
785
+ def get_kv_cache_torch_dtype(
786
+ cache_dtype: Optional[Union[str, torch.dtype]],
787
+ model_dtype: Optional[Union[str, torch.dtype]] = None) -> torch.dtype:
788
+ if isinstance(cache_dtype, str):
789
+ if cache_dtype == "auto":
790
+ if isinstance(model_dtype,
791
+ str) and model_dtype in STR_DTYPE_TO_TORCH_DTYPE:
792
+ torch_dtype = STR_DTYPE_TO_TORCH_DTYPE[model_dtype]
793
+ elif isinstance(model_dtype, torch.dtype):
794
+ torch_dtype = model_dtype
795
+ else:
796
+ raise ValueError(f"Invalid model dtype: {model_dtype}")
797
+ elif cache_dtype in STR_DTYPE_TO_TORCH_DTYPE:
798
+ torch_dtype = STR_DTYPE_TO_TORCH_DTYPE[cache_dtype]
799
+ else:
800
+ raise ValueError(f"Invalid kv cache dtype: {cache_dtype}")
801
+ elif isinstance(cache_dtype, torch.dtype):
802
+ torch_dtype = cache_dtype
803
+ else:
804
+ raise ValueError(f"Invalid kv cache dtype: {cache_dtype}")
805
+ return torch_dtype
806
+
807
+
808
+ def create_kv_caches_with_random_flash(
809
+ num_blocks: int,
810
+ block_size: int,
811
+ num_layers: int,
812
+ num_heads: int,
813
+ head_size: int,
814
+ cache_dtype: Optional[Union[str, torch.dtype]],
815
+ model_dtype: Optional[Union[str, torch.dtype]] = None,
816
+ seed: Optional[int] = None,
817
+ device: Optional[str] = "cuda",
818
+ cache_layout: Optional[str] = "NHD",
819
+ ) -> tuple[list[torch.Tensor], list[torch.Tensor]]:
820
+ from vllm.platforms import current_platform
821
+ current_platform.seed_everything(seed)
822
+
823
+ torch_dtype = get_kv_cache_torch_dtype(cache_dtype, model_dtype)
824
+ generic_kv_cache_shape = (num_blocks, 2, block_size, num_heads, head_size)
825
+ assert cache_layout in ("NHD", "HND")
826
+ stride_order = (0, 1, 2, 3, 4) if cache_layout == "NHD" else (0, 1, 3, 2,
827
+ 4)
828
+
829
+ kv_cache_allocation_shape = tuple(generic_kv_cache_shape[i]
830
+ for i in stride_order)
831
+ scale = head_size**-0.5
832
+
833
+ key_caches: list[torch.Tensor] = []
834
+ value_caches: list[torch.Tensor] = []
835
+
836
+ for _ in range(num_layers):
837
+ key_value_cache = torch.empty(size=kv_cache_allocation_shape,
838
+ dtype=torch_dtype,
839
+ device=device).permute(*stride_order)
840
+ if cache_dtype in ["auto", "half", "bfloat16", "float"]:
841
+ key_value_cache.uniform_(-scale, scale)
842
+ elif cache_dtype == 'fp8':
843
+ _generate_random_fp8(key_value_cache, -scale, scale)
844
+ else:
845
+ raise ValueError(
846
+ f"Does not support key cache of type {cache_dtype}")
847
+ key_caches.append(key_value_cache[:, 0])
848
+ value_caches.append(key_value_cache[:, 1])
849
+ return key_caches, value_caches
850
+
851
+
852
+ def create_kv_caches_with_random(
853
+ num_blocks: int,
854
+ block_size: int,
855
+ num_layers: int,
856
+ num_heads: int,
857
+ head_size: int,
858
+ cache_dtype: Optional[Union[str, torch.dtype]],
859
+ model_dtype: Optional[Union[str, torch.dtype]] = None,
860
+ seed: Optional[int] = None,
861
+ device: Optional[str] = "cuda",
862
+ ) -> tuple[list[torch.Tensor], list[torch.Tensor]]:
863
+ if cache_dtype == "fp8" and head_size % 16:
864
+ raise ValueError(
865
+ f"Does not support key cache of type fp8 with head_size {head_size}"
866
+ )
867
+ from vllm.platforms import current_platform
868
+ current_platform.seed_everything(seed)
869
+
870
+ torch_dtype = get_kv_cache_torch_dtype(cache_dtype, model_dtype)
871
+
872
+ scale = head_size**-0.5
873
+ x = 16 // torch.tensor([], dtype=torch_dtype).element_size()
874
+ key_cache_shape = (num_blocks, num_heads, head_size // x, block_size, x)
875
+ key_caches: list[torch.Tensor] = []
876
+ for _ in range(num_layers):
877
+ key_cache = torch.empty(size=key_cache_shape,
878
+ dtype=torch_dtype,
879
+ device=device)
880
+ if cache_dtype in ["auto", "half", "bfloat16", "float"]:
881
+ key_cache.uniform_(-scale, scale)
882
+ elif cache_dtype == 'fp8':
883
+ _generate_random_fp8(key_cache, -scale, scale)
884
+ else:
885
+ raise ValueError(
886
+ f"Does not support key cache of type {cache_dtype}")
887
+ key_caches.append(key_cache)
888
+
889
+ value_cache_shape = (num_blocks, num_heads, head_size, block_size)
890
+ value_caches: list[torch.Tensor] = []
891
+ for _ in range(num_layers):
892
+ value_cache = torch.empty(size=value_cache_shape,
893
+ dtype=torch_dtype,
894
+ device=device)
895
+ if cache_dtype in ["auto", "half", "bfloat16", "float"]:
896
+ value_cache.uniform_(-scale, scale)
897
+ elif cache_dtype == 'fp8':
898
+ _generate_random_fp8(value_cache, -scale, scale)
899
+ else:
900
+ raise ValueError(
901
+ f"Does not support value cache of type {cache_dtype}")
902
+ value_caches.append(value_cache)
903
+ return key_caches, value_caches
904
+
905
+
906
+ @cache
907
+ def is_pin_memory_available() -> bool:
908
+ from vllm.platforms import current_platform
909
+ return current_platform.is_pin_memory_available()
910
+
911
+
912
+ @cache
913
+ def is_uva_available() -> bool:
914
+ """Check if Unified Virtual Addressing (UVA) is available."""
915
+ # UVA requires pinned memory.
916
+ # TODO: Add more requirements for UVA if needed.
917
+ return is_pin_memory_available()
918
+
919
+
920
+ class DeviceMemoryProfiler:
921
+
922
+ def __init__(self, device: Optional[torch.types.Device] = None):
923
+ self.device = device
924
+
925
+ def current_memory_usage(self) -> float:
926
+ # Return the memory usage in bytes.
927
+ from vllm.platforms import current_platform
928
+ gc.collect()
929
+ return current_platform.get_current_memory_usage(self.device)
930
+
931
+ def __enter__(self):
932
+ self.initial_memory = self.current_memory_usage()
933
+ # This allows us to call methods of the context manager if needed
934
+ return self
935
+
936
+ def __exit__(self, exc_type, exc_val, exc_tb):
937
+ self.final_memory = self.current_memory_usage()
938
+ self.consumed_memory = self.final_memory - self.initial_memory
939
+
940
+ # Force garbage collection
941
+ gc.collect()
942
+
943
+
944
+ def make_ndarray_with_pad(
945
+ x: list[list[T]],
946
+ pad: T,
947
+ dtype: npt.DTypeLike,
948
+ *,
949
+ max_len: Optional[int] = None,
950
+ ) -> npt.NDArray:
951
+ """
952
+ Make a padded array from 2D inputs.
953
+
954
+ The padding is applied to the end of each inner list until it reaches
955
+ `max_len`.
956
+ """
957
+ if max_len is None:
958
+ # Unlike for most functions, map is faster than a genexpr over `len`
959
+ max_len = max(map(len, x), default=0)
960
+
961
+ padded_x = np.full((len(x), max_len), pad, dtype=dtype)
962
+ for ind, blocktb in enumerate(x):
963
+ assert len(blocktb) <= max_len
964
+ padded_x[ind, :len(blocktb)] = blocktb
965
+
966
+ return padded_x
967
+
968
+
969
+ def make_tensor_with_pad(
970
+ x: list[list[T]],
971
+ pad: T,
972
+ dtype: torch.dtype,
973
+ *,
974
+ max_len: Optional[int] = None,
975
+ device: Optional[Union[str, torch.device]] = None,
976
+ pin_memory: bool = False,
977
+ ) -> torch.Tensor:
978
+ """
979
+ Make a padded tensor from 2D inputs.
980
+
981
+ The padding is applied to the end of each inner list until it reaches
982
+ `max_len`.
983
+ """
984
+ np_dtype = TORCH_DTYPE_TO_NUMPY_DTYPE[dtype]
985
+ padded_x = make_ndarray_with_pad(x, pad, np_dtype, max_len=max_len)
986
+
987
+ tensor = torch.from_numpy(padded_x).to(device)
988
+ if pin_memory:
989
+ tensor = tensor.pin_memory()
990
+
991
+ return tensor
992
+
993
+
994
+ def async_tensor_h2d(
995
+ data: list,
996
+ dtype: torch.dtype,
997
+ target_device: Union[str, torch.device],
998
+ pin_memory: bool,
999
+ ) -> torch.Tensor:
1000
+ """Asynchronously create a tensor and copy it from host to device."""
1001
+ t = torch.tensor(data, dtype=dtype, pin_memory=pin_memory, device="cpu")
1002
+ return t.to(device=target_device, non_blocking=True)
1003
+
1004
+
1005
+ def get_dtype_size(dtype: torch.dtype) -> int:
1006
+ """Get the size of the data type in bytes."""
1007
+ return torch.tensor([], dtype=dtype).element_size()
1008
+
1009
+
1010
+ # bool = 0, int = 1, float = 2, complex = 3
1011
+ def _get_precision_level(dtype: torch.dtype) -> int:
1012
+ # NOTE: Complex dtypes return `is_floating_point=False`
1013
+ return ((dtype != torch.bool) + dtype.is_floating_point +
1014
+ dtype.is_complex * 2)
1015
+
1016
+
1017
+ def is_lossless_cast(src_dtype: torch.dtype, tgt_dtype: torch.dtype):
1018
+ """
1019
+ Test whether it is lossless to cast a tensor from
1020
+ `src_dtype` to `tgt_dtype`.
1021
+ """
1022
+ if src_dtype == tgt_dtype:
1023
+ return True
1024
+
1025
+ src_level = _get_precision_level(src_dtype)
1026
+ tgt_level = _get_precision_level(tgt_dtype)
1027
+
1028
+ if src_level < tgt_level:
1029
+ return True
1030
+ if src_level > tgt_level:
1031
+ return False
1032
+
1033
+ # Compare integral types
1034
+ if not src_dtype.is_floating_point and not src_dtype.is_complex:
1035
+ src_info = torch.iinfo(src_dtype)
1036
+ tgt_info = torch.iinfo(tgt_dtype)
1037
+ return src_info.min >= tgt_info.min and src_info.max <= tgt_info.max
1038
+
1039
+ # Compare floating-point types
1040
+ src_info = torch.finfo(src_dtype)
1041
+ tgt_info = torch.finfo(tgt_dtype)
1042
+ return (src_info.min >= tgt_info.min and src_info.max <= tgt_info.max
1043
+ and src_info.resolution >= tgt_info.resolution)
1044
+
1045
+
1046
+ def common_broadcastable_dtype(dtypes: Collection[torch.dtype]):
1047
+ """
1048
+ Get the common `dtype` where all of the other `dtypes` can be
1049
+ cast to it without losing any information.
1050
+ """
1051
+ return max(
1052
+ dtypes,
1053
+ key=lambda dtype: sum(is_lossless_cast(dt, dtype) for dt in dtypes),
1054
+ )
1055
+
1056
+
1057
+ # `collections` helpers
1058
+ def is_list_of(
1059
+ value: object,
1060
+ typ: Union[type[T], tuple[type[T], ...]],
1061
+ *,
1062
+ check: Literal["first", "all"] = "first",
1063
+ ) -> TypeIs[list[T]]:
1064
+ if not isinstance(value, list):
1065
+ return False
1066
+
1067
+ if check == "first":
1068
+ return len(value) == 0 or isinstance(value[0], typ)
1069
+ elif check == "all":
1070
+ return all(isinstance(v, typ) for v in value)
1071
+
1072
+ assert_never(check)
1073
+
1074
+
1075
+ def flatten_2d_lists(lists: Iterable[Iterable[T]]) -> list[T]:
1076
+ """Flatten a list of lists to a single list."""
1077
+ return [item for sublist in lists for item in sublist]
1078
+
1079
+
1080
+ def full_groupby(values: Iterable[_V], *, key: Callable[[_V], _K]):
1081
+ """
1082
+ Unlike [`itertools.groupby`][], groups are not broken by
1083
+ non-contiguous data.
1084
+ """
1085
+ groups = defaultdict[_K, list[_V]](list)
1086
+
1087
+ for value in values:
1088
+ groups[key(value)].append(value)
1089
+
1090
+ return groups.items()
1091
+
1092
+
1093
+ # TODO: This function can be removed if transformer_modules classes are
1094
+ # serialized by value when communicating between processes
1095
+ def init_cached_hf_modules() -> None:
1096
+ """
1097
+ Lazy initialization of the Hugging Face modules.
1098
+ """
1099
+ from transformers.dynamic_module_utils import init_hf_modules
1100
+ init_hf_modules()
1101
+
1102
+
1103
+ @cache
1104
+ def find_library(lib_name: str) -> str:
1105
+ """
1106
+ Find the library file in the system.
1107
+ `lib_name` is full filename, with both prefix and suffix.
1108
+ This function resolves `lib_name` to the full path of the library.
1109
+ """
1110
+ # Adapted from https://github.com/openai/triton/blob/main/third_party/nvidia/backend/driver.py#L19 # noqa
1111
+ # According to https://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard
1112
+ # `/sbin/ldconfig` should exist in all Linux systems.
1113
+ # `/sbin/ldconfig` searches the library in the system
1114
+ libs = subprocess.check_output(["/sbin/ldconfig", "-p"]).decode()
1115
+ # each line looks like the following:
1116
+ # libcuda.so.1 (libc6,x86-64) => /lib/x86_64-linux-gnu/libcuda.so.1
1117
+ locs = [line.split()[-1] for line in libs.splitlines() if lib_name in line]
1118
+ # `LD_LIBRARY_PATH` searches the library in the user-defined paths
1119
+ env_ld_library_path = envs.LD_LIBRARY_PATH
1120
+ if not locs and env_ld_library_path:
1121
+ locs = [
1122
+ os.path.join(dir, lib_name)
1123
+ for dir in env_ld_library_path.split(":")
1124
+ if os.path.exists(os.path.join(dir, lib_name))
1125
+ ]
1126
+ if not locs:
1127
+ raise ValueError(f"Cannot find {lib_name} in the system.")
1128
+ return locs[0]
1129
+
1130
+
1131
+ def find_nccl_library() -> str:
1132
+ """
1133
+ We either use the library file specified by the `VLLM_NCCL_SO_PATH`
1134
+ environment variable, or we find the library file brought by PyTorch.
1135
+ After importing `torch`, `libnccl.so.2` or `librccl.so.1` can be
1136
+ found by `ctypes` automatically.
1137
+ """
1138
+ so_file = envs.VLLM_NCCL_SO_PATH
1139
+
1140
+ # manually load the nccl library
1141
+ if so_file:
1142
+ logger.info(
1143
+ "Found nccl from environment variable VLLM_NCCL_SO_PATH=%s",
1144
+ so_file)
1145
+ else:
1146
+ if torch.version.cuda is not None:
1147
+ so_file = "libnccl.so.2"
1148
+ elif torch.version.hip is not None:
1149
+ so_file = "librccl.so.1"
1150
+ else:
1151
+ raise ValueError("NCCL only supports CUDA and ROCm backends.")
1152
+ logger.info("Found nccl from library %s", so_file)
1153
+ return so_file
1154
+
1155
+
1156
+ prev_set_stream = torch.cuda.set_stream
1157
+
1158
+ _current_stream = None
1159
+
1160
+
1161
+ def _patched_set_stream(stream: torch.cuda.Stream) -> None:
1162
+ global _current_stream
1163
+ _current_stream = stream
1164
+ prev_set_stream(stream)
1165
+
1166
+
1167
+ torch.cuda.set_stream = _patched_set_stream
1168
+
1169
+
1170
+ def current_stream() -> torch.cuda.Stream:
1171
+ """
1172
+ replace `torch.cuda.current_stream()` with `vllm.utils.current_stream()`.
1173
+ it turns out that `torch.cuda.current_stream()` is quite expensive,
1174
+ as it will construct a new stream object at each call.
1175
+ here we patch `torch.cuda.set_stream` to keep track of the current stream
1176
+ directly, so that we can avoid calling `torch.cuda.current_stream()`.
1177
+
1178
+ the underlying hypothesis is that we do not call `torch._C._cuda_setStream`
1179
+ from C/C++ code.
1180
+ """
1181
+ from vllm.platforms import current_platform
1182
+ global _current_stream
1183
+ if _current_stream is None:
1184
+ # when this function is called before any stream is set,
1185
+ # we return the default stream.
1186
+ # On ROCm using the default 0 stream in combination with RCCL
1187
+ # is hurting performance. Therefore creating a dedicated stream
1188
+ # per process
1189
+ _current_stream = torch.cuda.Stream() if current_platform.is_rocm(
1190
+ ) else torch.cuda.current_stream()
1191
+ return _current_stream
1192
+
1193
+
1194
+ def enable_trace_function_call_for_thread(vllm_config: VllmConfig) -> None:
1195
+ """Set up function tracing for the current thread,
1196
+ if enabled via the VLLM_TRACE_FUNCTION environment variable
1197
+ """
1198
+
1199
+ if envs.VLLM_TRACE_FUNCTION:
1200
+ tmp_dir = tempfile.gettempdir()
1201
+ # add username to tmp_dir to avoid permission issues
1202
+ tmp_dir = os.path.join(tmp_dir, getpass.getuser())
1203
+ filename = (f"VLLM_TRACE_FUNCTION_for_process_{os.getpid()}"
1204
+ f"_thread_{threading.get_ident()}_"
1205
+ f"at_{datetime.datetime.now()}.log").replace(" ", "_")
1206
+ log_path = os.path.join(tmp_dir, "vllm",
1207
+ f"vllm-instance-{vllm_config.instance_id}",
1208
+ filename)
1209
+ os.makedirs(os.path.dirname(log_path), exist_ok=True)
1210
+ enable_trace_function_call(log_path)
1211
+
1212
+
1213
+ # `functools` helpers
1214
+ def identity(value: T, **kwargs) -> T:
1215
+ """Returns the first provided value."""
1216
+ return value
1217
+
1218
+
1219
+ F = TypeVar('F', bound=Callable[..., Any])
1220
+
1221
+
1222
+ def deprecate_args(
1223
+ start_index: int,
1224
+ is_deprecated: Union[bool, Callable[[], bool]] = True,
1225
+ additional_message: Optional[str] = None,
1226
+ ) -> Callable[[F], F]:
1227
+ if not callable(is_deprecated):
1228
+ is_deprecated = partial(identity, is_deprecated)
1229
+
1230
+ def wrapper(fn: F) -> F:
1231
+
1232
+ params = inspect.signature(fn).parameters
1233
+ pos_types = (
1234
+ inspect.Parameter.POSITIONAL_ONLY,
1235
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
1236
+ )
1237
+ pos_kws = [
1238
+ kw for kw, param in params.items() if param.kind in pos_types
1239
+ ]
1240
+
1241
+ @wraps(fn)
1242
+ def inner(*args, **kwargs):
1243
+ if is_deprecated():
1244
+ deprecated_args = pos_kws[start_index:len(args)]
1245
+ if deprecated_args:
1246
+ msg = (
1247
+ f"The positional arguments {deprecated_args} are "
1248
+ "deprecated and will be removed in a future update.")
1249
+ if additional_message is not None:
1250
+ msg += f" {additional_message}"
1251
+
1252
+ warnings.warn(
1253
+ DeprecationWarning(msg),
1254
+ stacklevel=3, # The inner function takes up one level
1255
+ )
1256
+
1257
+ return fn(*args, **kwargs)
1258
+
1259
+ return inner # type: ignore
1260
+
1261
+ return wrapper
1262
+
1263
+
1264
+ def deprecate_kwargs(
1265
+ *kws: str,
1266
+ is_deprecated: Union[bool, Callable[[], bool]] = True,
1267
+ additional_message: Optional[str] = None,
1268
+ ) -> Callable[[F], F]:
1269
+ deprecated_kws = set(kws)
1270
+
1271
+ if not callable(is_deprecated):
1272
+ is_deprecated = partial(identity, is_deprecated)
1273
+
1274
+ def wrapper(fn: F) -> F:
1275
+
1276
+ @wraps(fn)
1277
+ def inner(*args, **kwargs):
1278
+ if is_deprecated():
1279
+ deprecated_kwargs = kwargs.keys() & deprecated_kws
1280
+ if deprecated_kwargs:
1281
+ msg = (
1282
+ f"The keyword arguments {deprecated_kwargs} are "
1283
+ "deprecated and will be removed in a future update.")
1284
+ if additional_message is not None:
1285
+ msg += f" {additional_message}"
1286
+
1287
+ warnings.warn(
1288
+ DeprecationWarning(msg),
1289
+ stacklevel=3, # The inner function takes up one level
1290
+ )
1291
+
1292
+ return fn(*args, **kwargs)
1293
+
1294
+ return inner # type: ignore
1295
+
1296
+ return wrapper
1297
+
1298
+
1299
+ @lru_cache(maxsize=8)
1300
+ def _cuda_device_count_stateless(
1301
+ cuda_visible_devices: Optional[str] = None) -> int:
1302
+ # Note: cuda_visible_devices is not used, but we keep it as an argument for
1303
+ # LRU Cache purposes.
1304
+
1305
+ # Code below is based on
1306
+ # https://github.com/pytorch/pytorch/blob/
1307
+ # c1cd946818442aca8c7f812b16d187ce1586c3bc/
1308
+ # torch/cuda/__init__.py#L831C1-L831C17
1309
+ import torch.cuda
1310
+ import torch.version
1311
+
1312
+ from vllm.platforms import current_platform
1313
+ if not torch.cuda._is_compiled():
1314
+ return 0
1315
+ if current_platform.is_rocm():
1316
+ # ROCm uses amdsmi instead of nvml for stateless device count
1317
+ # This requires a sufficiently modern version of Torch 2.4.0
1318
+ raw_count = torch.cuda._device_count_amdsmi() if (hasattr(
1319
+ torch.cuda, "_device_count_amdsmi")) else -1
1320
+ else:
1321
+ raw_count = torch.cuda._device_count_nvml()
1322
+ r = torch._C._cuda_getDeviceCount() if raw_count < 0 else raw_count
1323
+ return r
1324
+
1325
+
1326
+ def cuda_device_count_stateless() -> int:
1327
+ """Get number of CUDA devices, caching based on the value of
1328
+ CUDA_VISIBLE_DEVICES at the time of call.
1329
+
1330
+ This should be used instead of torch.cuda.device_count()
1331
+ unless CUDA_VISIBLE_DEVICES has already been set to the desired
1332
+ value."""
1333
+
1334
+ # This can be removed and simply replaced with torch.cuda.get_device_count
1335
+ # after https://github.com/pytorch/pytorch/pull/122815 is released.
1336
+ return _cuda_device_count_stateless(envs.CUDA_VISIBLE_DEVICES)
1337
+
1338
+
1339
+ def cuda_is_initialized() -> bool:
1340
+ """Check if CUDA is initialized."""
1341
+ if not torch.cuda._is_compiled():
1342
+ return False
1343
+ return torch.cuda.is_initialized()
1344
+
1345
+
1346
+ def cuda_get_device_properties(device,
1347
+ names: Sequence[str],
1348
+ init_cuda=False) -> tuple[Any, ...]:
1349
+ """Get specified CUDA device property values without initializing CUDA in
1350
+ the current process."""
1351
+ if init_cuda or cuda_is_initialized():
1352
+ props = torch.cuda.get_device_properties(device)
1353
+ return tuple(getattr(props, name) for name in names)
1354
+
1355
+ # Run in subprocess to avoid initializing CUDA as a side effect.
1356
+ mp_ctx = multiprocessing.get_context("fork")
1357
+ with ProcessPoolExecutor(max_workers=1, mp_context=mp_ctx) as executor:
1358
+ return executor.submit(cuda_get_device_properties, device, names,
1359
+ True).result()
1360
+
1361
+
1362
+ def weak_bind(bound_method: Callable[..., Any], ) -> Callable[..., None]:
1363
+ """Make an instance method that weakly references
1364
+ its associated instance and no-ops once that
1365
+ instance is collected."""
1366
+ ref = weakref.ref(bound_method.__self__) # type: ignore[attr-defined]
1367
+ unbound = bound_method.__func__ # type: ignore[attr-defined]
1368
+
1369
+ def weak_bound(*args, **kwargs) -> None:
1370
+ if inst := ref():
1371
+ unbound(inst, *args, **kwargs)
1372
+
1373
+ return weak_bound
1374
+
1375
+
1376
+ # From: https://stackoverflow.com/a/4104188/2749989
1377
+ def run_once(f: Callable[P, None]) -> Callable[P, None]:
1378
+
1379
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> None:
1380
+ if not wrapper.has_run: # type: ignore[attr-defined]
1381
+ wrapper.has_run = True # type: ignore[attr-defined]
1382
+ return f(*args, **kwargs)
1383
+
1384
+ wrapper.has_run = False # type: ignore[attr-defined]
1385
+ return wrapper
1386
+
1387
+
1388
+ class StoreBoolean(Action):
1389
+
1390
+ def __call__(self, parser, namespace, values, option_string=None):
1391
+ if values.lower() == "true":
1392
+ setattr(namespace, self.dest, True)
1393
+ elif values.lower() == "false":
1394
+ setattr(namespace, self.dest, False)
1395
+ else:
1396
+ raise ValueError(f"Invalid boolean value: {values}. "
1397
+ "Expected 'true' or 'false'.")
1398
+
1399
+
1400
+ class SortedHelpFormatter(ArgumentDefaultsHelpFormatter,
1401
+ RawDescriptionHelpFormatter):
1402
+ """SortedHelpFormatter that sorts arguments by their option strings."""
1403
+
1404
+ def _split_lines(self, text, width):
1405
+ """
1406
+ 1. Sentences split across lines have their single newlines removed.
1407
+ 2. Paragraphs and explicit newlines are split into separate lines.
1408
+ 3. Each line is wrapped to the specified width (width of terminal).
1409
+ """
1410
+ # The patterns also include whitespace after the newline
1411
+ single_newline = re.compile(r"(?<!\n)\n(?!\n)\s*")
1412
+ multiple_newlines = re.compile(r"\n{2,}\s*")
1413
+ text = single_newline.sub(' ', text)
1414
+ lines = re.split(multiple_newlines, text)
1415
+ return sum([textwrap.wrap(line, width) for line in lines], [])
1416
+
1417
+ def add_arguments(self, actions):
1418
+ actions = sorted(actions, key=lambda x: x.option_strings)
1419
+ super().add_arguments(actions)
1420
+
1421
+
1422
+ class FlexibleArgumentParser(ArgumentParser):
1423
+ """ArgumentParser that allows both underscore and dash in names."""
1424
+
1425
+ _deprecated: set[Action] = set()
1426
+
1427
+ def __init__(self, *args, **kwargs):
1428
+ # Set the default 'formatter_class' to SortedHelpFormatter
1429
+ if 'formatter_class' not in kwargs:
1430
+ kwargs['formatter_class'] = SortedHelpFormatter
1431
+ super().__init__(*args, **kwargs)
1432
+
1433
+ if sys.version_info < (3, 13):
1434
+ # Enable the deprecated kwarg for Python 3.12 and below
1435
+
1436
+ def parse_known_args(self, args=None, namespace=None):
1437
+ namespace, args = super().parse_known_args(args, namespace)
1438
+ for action in FlexibleArgumentParser._deprecated:
1439
+ if (hasattr(namespace, dest := action.dest)
1440
+ and getattr(namespace, dest) != action.default):
1441
+ logger.warning_once("argument '%s' is deprecated", dest)
1442
+ return namespace, args
1443
+
1444
+ def add_argument(self, *args, **kwargs):
1445
+ deprecated = kwargs.pop("deprecated", False)
1446
+ action = super().add_argument(*args, **kwargs)
1447
+ if deprecated:
1448
+ FlexibleArgumentParser._deprecated.add(action)
1449
+ return action
1450
+
1451
+ class _FlexibleArgumentGroup(_ArgumentGroup):
1452
+
1453
+ def add_argument(self, *args, **kwargs):
1454
+ deprecated = kwargs.pop("deprecated", False)
1455
+ action = super().add_argument(*args, **kwargs)
1456
+ if deprecated:
1457
+ FlexibleArgumentParser._deprecated.add(action)
1458
+ return action
1459
+
1460
+ def add_argument_group(self, *args, **kwargs):
1461
+ group = self._FlexibleArgumentGroup(self, *args, **kwargs)
1462
+ self._action_groups.append(group)
1463
+ return group
1464
+
1465
+ def parse_args( # type: ignore[override]
1466
+ self,
1467
+ args: list[str] | None = None,
1468
+ namespace: Namespace | None = None,
1469
+ ):
1470
+ if args is None:
1471
+ args = sys.argv[1:]
1472
+
1473
+ # Check for --model in command line arguments first
1474
+ if args and args[0] == "serve":
1475
+ model_in_cli_args = any(arg == '--model' for arg in args)
1476
+
1477
+ if model_in_cli_args:
1478
+ raise ValueError(
1479
+ "With `vllm serve`, you should provide the model as a "
1480
+ "positional argument or in a config file instead of via "
1481
+ "the `--model` option.")
1482
+
1483
+ if '--config' in args:
1484
+ args = self._pull_args_from_config(args)
1485
+
1486
+ def repl(match: re.Match) -> str:
1487
+ """Replaces underscores with dashes in the matched string."""
1488
+ return match.group(0).replace("_", "-")
1489
+
1490
+ # Everything between the first -- and the first .
1491
+ pattern = re.compile(r"(?<=--)[^\.]*")
1492
+
1493
+ # Convert underscores to dashes and vice versa in argument names
1494
+ processed_args = list[str]()
1495
+ for i, arg in enumerate(args):
1496
+ if arg.startswith('--'):
1497
+ if '=' in arg:
1498
+ key, value = arg.split('=', 1)
1499
+ key = pattern.sub(repl, key, count=1)
1500
+ processed_args.append(f'{key}={value}')
1501
+ else:
1502
+ key = pattern.sub(repl, arg, count=1)
1503
+ processed_args.append(key)
1504
+ elif arg.startswith('-O') and arg != '-O' and arg[2] != '.':
1505
+ # allow -O flag to be used without space, e.g. -O3 or -Odecode
1506
+ # -O.<...> handled later
1507
+ # also handle -O=<level> here
1508
+ level = arg[3:] if arg[2] == '=' else arg[2:]
1509
+ processed_args.append(f'-O.level={level}')
1510
+ elif arg == '-O' and i + 1 < len(args) and args[i + 1] in {
1511
+ "0", "1", "2", "3"
1512
+ }:
1513
+ # Convert -O <n> to -O.level <n>
1514
+ processed_args.append('-O.level')
1515
+ else:
1516
+ processed_args.append(arg)
1517
+
1518
+ def create_nested_dict(keys: list[str], value: str) -> dict[str, Any]:
1519
+ """Creates a nested dictionary from a list of keys and a value.
1520
+
1521
+ For example, `keys = ["a", "b", "c"]` and `value = 1` will create:
1522
+ `{"a": {"b": {"c": 1}}}`
1523
+ """
1524
+ nested_dict: Any = value
1525
+ for key in reversed(keys):
1526
+ nested_dict = {key: nested_dict}
1527
+ return nested_dict
1528
+
1529
+ def recursive_dict_update(
1530
+ original: dict[str, Any],
1531
+ update: dict[str, Any],
1532
+ ) -> set[str]:
1533
+ """Recursively updates a dictionary with another dictionary.
1534
+ Returns a set of duplicate keys that were overwritten.
1535
+ """
1536
+ duplicates = set[str]()
1537
+ for k, v in update.items():
1538
+ if isinstance(v, dict) and isinstance(original.get(k), dict):
1539
+ nested_duplicates = recursive_dict_update(original[k], v)
1540
+ duplicates |= {f"{k}.{d}" for d in nested_duplicates}
1541
+ elif isinstance(v, list) and isinstance(original.get(k), list):
1542
+ original[k] += v
1543
+ else:
1544
+ if k in original:
1545
+ duplicates.add(k)
1546
+ original[k] = v
1547
+ return duplicates
1548
+
1549
+ delete = set[int]()
1550
+ dict_args = defaultdict[str, dict[str, Any]](dict)
1551
+ duplicates = set[str]()
1552
+ for i, processed_arg in enumerate(processed_args):
1553
+ if i in delete: # skip if value from previous arg
1554
+ continue
1555
+
1556
+ if processed_arg.startswith("-") and "." in processed_arg:
1557
+ if "=" in processed_arg:
1558
+ processed_arg, value_str = processed_arg.split("=", 1)
1559
+ if "." not in processed_arg:
1560
+ # False positive, '.' was only in the value
1561
+ continue
1562
+ else:
1563
+ value_str = processed_args[i + 1]
1564
+ delete.add(i + 1)
1565
+
1566
+ if processed_arg.endswith("+"):
1567
+ processed_arg = processed_arg[:-1]
1568
+ value_str = json.dumps(list(value_str.split(",")))
1569
+
1570
+ key, *keys = processed_arg.split(".")
1571
+ try:
1572
+ value = json.loads(value_str)
1573
+ except json.decoder.JSONDecodeError:
1574
+ value = value_str
1575
+
1576
+ # Merge all values with the same key into a single dict
1577
+ arg_dict = create_nested_dict(keys, value)
1578
+ arg_duplicates = recursive_dict_update(dict_args[key],
1579
+ arg_dict)
1580
+ duplicates |= {f'{key}.{d}' for d in arg_duplicates}
1581
+ delete.add(i)
1582
+ # Filter out the dict args we set to None
1583
+ processed_args = [
1584
+ a for i, a in enumerate(processed_args) if i not in delete
1585
+ ]
1586
+ if duplicates:
1587
+ logger.warning("Found duplicate keys %s", ", ".join(duplicates))
1588
+
1589
+ # Add the dict args back as if they were originally passed as JSON
1590
+ for dict_arg, dict_value in dict_args.items():
1591
+ processed_args.append(dict_arg)
1592
+ processed_args.append(json.dumps(dict_value))
1593
+
1594
+ return super().parse_args(processed_args, namespace)
1595
+
1596
+ def check_port(self, value):
1597
+ try:
1598
+ value = int(value)
1599
+ except ValueError:
1600
+ msg = "Port must be an integer"
1601
+ raise ArgumentTypeError(msg) from None
1602
+
1603
+ if not (1024 <= value <= 65535):
1604
+ raise ArgumentTypeError("Port must be between 1024 and 65535")
1605
+
1606
+ return value
1607
+
1608
+ def _pull_args_from_config(self, args: list[str]) -> list[str]:
1609
+ """Method to pull arguments specified in the config file
1610
+ into the command-line args variable.
1611
+
1612
+ The arguments in config file will be inserted between
1613
+ the argument list.
1614
+
1615
+ example:
1616
+ ```yaml
1617
+ port: 12323
1618
+ tensor-parallel-size: 4
1619
+ ```
1620
+ ```python
1621
+ $: vllm {serve,chat,complete} "facebook/opt-12B" \
1622
+ --config config.yaml -tp 2
1623
+ $: args = [
1624
+ "serve,chat,complete",
1625
+ "facebook/opt-12B",
1626
+ '--config', 'config.yaml',
1627
+ '-tp', '2'
1628
+ ]
1629
+ $: args = [
1630
+ "serve,chat,complete",
1631
+ "facebook/opt-12B",
1632
+ '--port', '12323',
1633
+ '--tensor-parallel-size', '4',
1634
+ '-tp', '2'
1635
+ ]
1636
+ ```
1637
+
1638
+ Please note how the config args are inserted after the sub command.
1639
+ this way the order of priorities is maintained when these are args
1640
+ parsed by super().
1641
+ """
1642
+ assert args.count(
1643
+ '--config') <= 1, "More than one config file specified!"
1644
+
1645
+ index = args.index('--config')
1646
+ if index == len(args) - 1:
1647
+ raise ValueError("No config file specified! \
1648
+ Please check your command-line arguments.")
1649
+
1650
+ file_path = args[index + 1]
1651
+
1652
+ config_args = self._load_config_file(file_path)
1653
+
1654
+ # 0th index is for {serve,chat,complete}
1655
+ # optionally followed by model_tag (only for serve)
1656
+ # followed by config args
1657
+ # followed by rest of cli args.
1658
+ # maintaining this order will enforce the precedence
1659
+ # of cli > config > defaults
1660
+ if args[0] == "serve":
1661
+ model_in_cli = len(args) > 1 and not args[1].startswith('-')
1662
+ model_in_config = any(arg == '--model' for arg in config_args)
1663
+
1664
+ if not model_in_cli and not model_in_config:
1665
+ raise ValueError(
1666
+ "No model specified! Please specify model either "
1667
+ "as a positional argument or in a config file.")
1668
+
1669
+ if model_in_cli:
1670
+ # Model specified as positional arg, keep CLI version
1671
+ args = [args[0]] + [
1672
+ args[1]
1673
+ ] + config_args + args[2:index] + args[index + 2:]
1674
+ else:
1675
+ # No model in CLI, use config if available
1676
+ args = [args[0]
1677
+ ] + config_args + args[1:index] + args[index + 2:]
1678
+ else:
1679
+ args = [args[0]] + config_args + args[1:index] + args[index + 2:]
1680
+
1681
+ return args
1682
+
1683
+ def _load_config_file(self, file_path: str) -> list[str]:
1684
+ """Loads a yaml file and returns the key value pairs as a
1685
+ flattened list with argparse like pattern
1686
+ ```yaml
1687
+ port: 12323
1688
+ tensor-parallel-size: 4
1689
+ ```
1690
+ returns:
1691
+ processed_args: list[str] = [
1692
+ '--port': '12323',
1693
+ '--tensor-parallel-size': '4'
1694
+ ]
1695
+ """
1696
+ extension: str = file_path.split('.')[-1]
1697
+ if extension not in ('yaml', 'yml'):
1698
+ raise ValueError(
1699
+ "Config file must be of a yaml/yml type.\
1700
+ %s supplied", extension)
1701
+
1702
+ # only expecting a flat dictionary of atomic types
1703
+ processed_args: list[str] = []
1704
+
1705
+ config: dict[str, Union[int, str]] = {}
1706
+ try:
1707
+ with open(file_path) as config_file:
1708
+ config = yaml.safe_load(config_file)
1709
+ except Exception as ex:
1710
+ logger.error(
1711
+ "Unable to read the config file at %s. \
1712
+ Make sure path is correct", file_path)
1713
+ raise ex
1714
+
1715
+ store_boolean_arguments = [
1716
+ action.dest for action in self._actions
1717
+ if isinstance(action, StoreBoolean)
1718
+ ]
1719
+
1720
+ for key, value in config.items():
1721
+ if isinstance(value, bool) and key not in store_boolean_arguments:
1722
+ if value:
1723
+ processed_args.append('--' + key)
1724
+ else:
1725
+ processed_args.append('--' + key)
1726
+ processed_args.append(str(value))
1727
+
1728
+ return processed_args
1729
+
1730
+
1731
+ async def _run_task_with_lock(task: Callable, lock: asyncio.Lock, *args,
1732
+ **kwargs):
1733
+ """Utility function to run async task in a lock"""
1734
+ async with lock:
1735
+ return await task(*args, **kwargs)
1736
+
1737
+
1738
+ def supports_kw(
1739
+ callable: Callable[..., object],
1740
+ kw_name: str,
1741
+ *,
1742
+ requires_kw_only: bool = False,
1743
+ allow_var_kwargs: bool = True,
1744
+ ) -> bool:
1745
+ """Check if a keyword is a valid kwarg for a callable; if requires_kw_only
1746
+ disallows kwargs names that can also be positional arguments.
1747
+ """
1748
+ params = inspect.signature(callable).parameters
1749
+ if not params:
1750
+ return False
1751
+
1752
+ param_val = params.get(kw_name)
1753
+
1754
+ # Types where the it may be valid, i.e., explicitly defined & nonvariadic
1755
+ passable_kw_types = set((inspect.Parameter.POSITIONAL_ONLY,
1756
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
1757
+ inspect.Parameter.KEYWORD_ONLY))
1758
+
1759
+ if param_val:
1760
+ is_sig_param = param_val.kind in passable_kw_types
1761
+ # We want kwargs only, but this is passable as a positional arg
1762
+ if (requires_kw_only and is_sig_param
1763
+ and param_val.kind != inspect.Parameter.KEYWORD_ONLY):
1764
+ return False
1765
+ if ((requires_kw_only
1766
+ and param_val.kind == inspect.Parameter.KEYWORD_ONLY)
1767
+ or (not requires_kw_only and is_sig_param)):
1768
+ return True
1769
+
1770
+ # If we're okay with var-kwargs, it's supported as long as
1771
+ # the kw_name isn't something like *args, **kwargs
1772
+ if allow_var_kwargs:
1773
+ # Get the last param; type is ignored here because params is a proxy
1774
+ # mapping, but it wraps an ordered dict, and they appear in order.
1775
+ # Ref: https://docs.python.org/3/library/inspect.html#inspect.Signature.parameters
1776
+ last_param = params[next(reversed(params))] # type: ignore
1777
+ return (last_param.kind == inspect.Parameter.VAR_KEYWORD
1778
+ and last_param.name != kw_name)
1779
+
1780
+ return False
1781
+
1782
+
1783
+ def resolve_mm_processor_kwargs(
1784
+ init_kwargs: Optional[Mapping[str, object]],
1785
+ inference_kwargs: Optional[Mapping[str, object]],
1786
+ callable: Callable[..., object],
1787
+ *,
1788
+ requires_kw_only: bool = True,
1789
+ allow_var_kwargs: bool = False,
1790
+ ) -> dict[str, Any]:
1791
+ """Applies filtering to eliminate invalid mm_processor_kwargs, i.e.,
1792
+ those who are not explicit keywords to the given callable (of one is
1793
+ given; otherwise no filtering is done), then merges the kwarg dicts,
1794
+ giving priority to inference_kwargs if there are any collisions.
1795
+
1796
+ In the case that no kwarg overrides are provided, returns an empty
1797
+ dict so that it can still be kwarg expanded into the callable later on.
1798
+
1799
+ If allow_var_kwargs=True, allows for things that can be expanded into
1800
+ kwargs as long as they aren't naming collision for var_kwargs or potential
1801
+ positional arguments.
1802
+ """
1803
+ # Filter inference time multimodal processor kwargs provided
1804
+ runtime_mm_kwargs = get_allowed_kwarg_only_overrides(
1805
+ callable,
1806
+ overrides=inference_kwargs,
1807
+ requires_kw_only=requires_kw_only,
1808
+ allow_var_kwargs=allow_var_kwargs,
1809
+ )
1810
+
1811
+ # Filter init time multimodal processor kwargs provided
1812
+ init_mm_kwargs = get_allowed_kwarg_only_overrides(
1813
+ callable,
1814
+ overrides=init_kwargs,
1815
+ requires_kw_only=requires_kw_only,
1816
+ allow_var_kwargs=allow_var_kwargs,
1817
+ )
1818
+
1819
+ # Merge the final processor kwargs, prioritizing inference
1820
+ # time values over the initialization time values.
1821
+ mm_processor_kwargs = {**init_mm_kwargs, **runtime_mm_kwargs}
1822
+
1823
+ return mm_processor_kwargs
1824
+
1825
+
1826
+ def get_allowed_kwarg_only_overrides(
1827
+ callable: Callable[..., object],
1828
+ overrides: Optional[Mapping[str, object]],
1829
+ *,
1830
+ requires_kw_only: bool = True,
1831
+ allow_var_kwargs: bool = False,
1832
+ ) -> dict[str, Any]:
1833
+ """
1834
+ Given a callable which has one or more keyword only params and a dict
1835
+ mapping param names to values, drop values that can be not be kwarg
1836
+ expanded to overwrite one or more keyword-only args. This is used in a
1837
+ few places to handle custom processor overrides for multimodal models,
1838
+ e.g., for profiling when processor options provided by the user
1839
+ may affect the number of mm tokens per instance.
1840
+
1841
+ Args:
1842
+ callable: Callable which takes 0 or more keyword only arguments.
1843
+ If None is provided, all overrides names are allowed.
1844
+ overrides: Potential overrides to be used when invoking the callable.
1845
+ allow_var_kwargs: Allows overrides that are expandable for var kwargs.
1846
+
1847
+ Returns:
1848
+ Dictionary containing the kwargs to be leveraged which may be used
1849
+ to overwrite one or more keyword only arguments when invoking the
1850
+ callable.
1851
+ """
1852
+ if not overrides:
1853
+ return {}
1854
+
1855
+ # Drop any mm_processor_kwargs provided by the user that
1856
+ # are not kwargs, unless it can fit it var_kwargs param
1857
+ filtered_overrides = {
1858
+ kwarg_name: val
1859
+ for kwarg_name, val in overrides.items()
1860
+ if supports_kw(callable,
1861
+ kwarg_name,
1862
+ requires_kw_only=requires_kw_only,
1863
+ allow_var_kwargs=allow_var_kwargs)
1864
+ }
1865
+
1866
+ # If anything is dropped, log a warning
1867
+ dropped_keys = overrides.keys() - filtered_overrides.keys()
1868
+ if dropped_keys:
1869
+ if requires_kw_only:
1870
+ logger.warning(
1871
+ "The following intended overrides are not keyword-only args "
1872
+ "and will be dropped: %s", dropped_keys)
1873
+ else:
1874
+ logger.warning(
1875
+ "The following intended overrides are not keyword args "
1876
+ "and will be dropped: %s", dropped_keys)
1877
+
1878
+ return filtered_overrides
1879
+
1880
+
1881
+ # Using dynamo with vLLM doesn't really work well with PyTorch versions < 2.4.0.
1882
+ # In particular, the FakeScalarType is not supported for earlier versions of
1883
+ # PyTorch which breaks dynamo for any ops registered using ScalarType.
1884
+ def supports_dynamo() -> bool:
1885
+ base_torch_version = Version(Version(torch.__version__).base_version)
1886
+ return base_torch_version >= Version("2.4.0")
1887
+
1888
+
1889
+ # Some backends use pytorch version < 2.4.0 which doesn't
1890
+ # support `torch.library.custom_op`.
1891
+ def supports_custom_op() -> bool:
1892
+ return hasattr(torch.library, "custom_op")
1893
+
1894
+
1895
+ class AtomicCounter:
1896
+ """An atomic, thread-safe counter"""
1897
+
1898
+ def __init__(self, initial=0):
1899
+ """Initialize a new atomic counter to given initial value"""
1900
+ self._value = initial
1901
+ self._lock = threading.Lock()
1902
+
1903
+ def inc(self, num=1):
1904
+ """Atomically increment the counter by num and return the new value"""
1905
+ with self._lock:
1906
+ self._value += num
1907
+ return self._value
1908
+
1909
+ def dec(self, num=1):
1910
+ """Atomically decrement the counter by num and return the new value"""
1911
+ with self._lock:
1912
+ self._value -= num
1913
+ return self._value
1914
+
1915
+ @property
1916
+ def value(self):
1917
+ return self._value
1918
+
1919
+
1920
+ # Adapted from: https://stackoverflow.com/a/47212782/5082708
1921
+ class LazyDict(Mapping[str, T], Generic[T]):
1922
+
1923
+ def __init__(self, factory: dict[str, Callable[[], T]]):
1924
+ self._factory = factory
1925
+ self._dict: dict[str, T] = {}
1926
+
1927
+ def __getitem__(self, key: str) -> T:
1928
+ if key not in self._dict:
1929
+ if key not in self._factory:
1930
+ raise KeyError(key)
1931
+ self._dict[key] = self._factory[key]()
1932
+ return self._dict[key]
1933
+
1934
+ def __setitem__(self, key: str, value: Callable[[], T]):
1935
+ self._factory[key] = value
1936
+
1937
+ def __iter__(self):
1938
+ return iter(self._factory)
1939
+
1940
+ def __len__(self):
1941
+ return len(self._factory)
1942
+
1943
+
1944
+ class ClassRegistry(UserDict[type[T], _V]):
1945
+
1946
+ def __getitem__(self, key: type[T]) -> _V:
1947
+ for cls in key.mro():
1948
+ if cls in self.data:
1949
+ return self.data[cls]
1950
+
1951
+ raise KeyError(key)
1952
+
1953
+ def __contains__(self, key: object) -> bool:
1954
+ return self.contains(key)
1955
+
1956
+ def contains(self, key: object, *, strict: bool = False) -> bool:
1957
+ if not isinstance(key, type):
1958
+ return False
1959
+
1960
+ if strict:
1961
+ return key in self.data
1962
+
1963
+ return any(cls in self.data for cls in key.mro())
1964
+
1965
+
1966
+ def weak_ref_tensor(tensor: Any) -> Any:
1967
+ """
1968
+ Create a weak reference to a tensor.
1969
+ The new tensor will share the same data as the original tensor,
1970
+ but will not keep the original tensor alive.
1971
+ """
1972
+ if isinstance(tensor, torch.Tensor):
1973
+ return torch.ops._C.weak_ref_tensor(tensor)
1974
+ else:
1975
+ return tensor
1976
+
1977
+
1978
+ def weak_ref_tensors(
1979
+ tensors: Union[torch.Tensor, list[torch.Tensor], tuple[torch.Tensor]]
1980
+ ) -> Union[torch.Tensor, list[Any], tuple[Any], Any]:
1981
+ """
1982
+ Convenience function to create weak references to tensors,
1983
+ for single tensor, list of tensors or tuple of tensors.
1984
+ """
1985
+ if isinstance(tensors, torch.Tensor):
1986
+ return weak_ref_tensor(tensors)
1987
+ if isinstance(tensors, list):
1988
+ return [weak_ref_tensor(t) for t in tensors]
1989
+ if isinstance(tensors, tuple):
1990
+ return tuple(weak_ref_tensor(t) for t in tensors)
1991
+ raise ValueError("Invalid type for tensors")
1992
+
1993
+
1994
+ def get_cuda_view_from_cpu_tensor(cpu_tensor: torch.Tensor) -> torch.Tensor:
1995
+ """
1996
+ Get a CUDA view of a CPU tensor using Unified Virtual Addressing (UVA).
1997
+ """
1998
+ assert cpu_tensor.is_pinned(), "CPU tensor must be pinned"
1999
+ return torch.ops._C.get_cuda_view_from_cpu_tensor(cpu_tensor)
2000
+
2001
+
2002
+ def import_from_path(module_name: str, file_path: Union[str, os.PathLike]):
2003
+ """
2004
+ Import a Python file according to its file path.
2005
+
2006
+ Based on the official recipe:
2007
+ https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
2008
+ """
2009
+ spec = importlib.util.spec_from_file_location(module_name, file_path)
2010
+ if spec is None:
2011
+ raise ModuleNotFoundError(f"No module named '{module_name}'")
2012
+
2013
+ assert spec.loader is not None
2014
+
2015
+ module = importlib.util.module_from_spec(spec)
2016
+ sys.modules[module_name] = module
2017
+ spec.loader.exec_module(module)
2018
+ return module
2019
+
2020
+
2021
+ @cache
2022
+ def get_vllm_optional_dependencies():
2023
+ metadata = importlib.metadata.metadata("vllm")
2024
+ requirements = metadata.get_all("Requires-Dist", [])
2025
+ extras = metadata.get_all("Provides-Extra", [])
2026
+
2027
+ return {
2028
+ extra: [
2029
+ re.split(r";|>=|<=|==", req)[0] for req in requirements
2030
+ if req.endswith(f'extra == "{extra}"')
2031
+ ]
2032
+ for extra in extras
2033
+ }
2034
+
2035
+
2036
+ class _PlaceholderBase:
2037
+ """
2038
+ Disallows downstream usage of placeholder modules.
2039
+
2040
+ We need to explicitly override each dunder method because
2041
+ [`__getattr__`][vllm.utils._PlaceholderBase.__getattr__]
2042
+ is not called when they are accessed.
2043
+
2044
+ Info:
2045
+ [Special method lookup](https://docs.python.org/3/reference/datamodel.html#special-lookup)
2046
+ """
2047
+
2048
+ def __getattr__(self, key: str) -> Never:
2049
+ """
2050
+ The main class should implement this to throw an error
2051
+ for attribute accesses representing downstream usage.
2052
+ """
2053
+ raise NotImplementedError
2054
+
2055
+ # [Basic customization]
2056
+
2057
+ def __lt__(self, other: object):
2058
+ return self.__getattr__("__lt__")
2059
+
2060
+ def __le__(self, other: object):
2061
+ return self.__getattr__("__le__")
2062
+
2063
+ def __eq__(self, other: object):
2064
+ return self.__getattr__("__eq__")
2065
+
2066
+ def __ne__(self, other: object):
2067
+ return self.__getattr__("__ne__")
2068
+
2069
+ def __gt__(self, other: object):
2070
+ return self.__getattr__("__gt__")
2071
+
2072
+ def __ge__(self, other: object):
2073
+ return self.__getattr__("__ge__")
2074
+
2075
+ def __hash__(self):
2076
+ return self.__getattr__("__hash__")
2077
+
2078
+ def __bool__(self):
2079
+ return self.__getattr__("__bool__")
2080
+
2081
+ # [Callable objects]
2082
+
2083
+ def __call__(self, *args: object, **kwargs: object):
2084
+ return self.__getattr__("__call__")
2085
+
2086
+ # [Container types]
2087
+
2088
+ def __len__(self):
2089
+ return self.__getattr__("__len__")
2090
+
2091
+ def __getitem__(self, key: object):
2092
+ return self.__getattr__("__getitem__")
2093
+
2094
+ def __setitem__(self, key: object, value: object):
2095
+ return self.__getattr__("__setitem__")
2096
+
2097
+ def __delitem__(self, key: object):
2098
+ return self.__getattr__("__delitem__")
2099
+
2100
+ # __missing__ is optional according to __getitem__ specification,
2101
+ # so it is skipped
2102
+
2103
+ # __iter__ and __reversed__ have a default implementation
2104
+ # based on __len__ and __getitem__, so they are skipped.
2105
+
2106
+ # [Numeric Types]
2107
+
2108
+ def __add__(self, other: object):
2109
+ return self.__getattr__("__add__")
2110
+
2111
+ def __sub__(self, other: object):
2112
+ return self.__getattr__("__sub__")
2113
+
2114
+ def __mul__(self, other: object):
2115
+ return self.__getattr__("__mul__")
2116
+
2117
+ def __matmul__(self, other: object):
2118
+ return self.__getattr__("__matmul__")
2119
+
2120
+ def __truediv__(self, other: object):
2121
+ return self.__getattr__("__truediv__")
2122
+
2123
+ def __floordiv__(self, other: object):
2124
+ return self.__getattr__("__floordiv__")
2125
+
2126
+ def __mod__(self, other: object):
2127
+ return self.__getattr__("__mod__")
2128
+
2129
+ def __divmod__(self, other: object):
2130
+ return self.__getattr__("__divmod__")
2131
+
2132
+ def __pow__(self, other: object, modulo: object = ...):
2133
+ return self.__getattr__("__pow__")
2134
+
2135
+ def __lshift__(self, other: object):
2136
+ return self.__getattr__("__lshift__")
2137
+
2138
+ def __rshift__(self, other: object):
2139
+ return self.__getattr__("__rshift__")
2140
+
2141
+ def __and__(self, other: object):
2142
+ return self.__getattr__("__and__")
2143
+
2144
+ def __xor__(self, other: object):
2145
+ return self.__getattr__("__xor__")
2146
+
2147
+ def __or__(self, other: object):
2148
+ return self.__getattr__("__or__")
2149
+
2150
+ # r* and i* methods have lower priority than
2151
+ # the methods for left operand so they are skipped
2152
+
2153
+ def __neg__(self):
2154
+ return self.__getattr__("__neg__")
2155
+
2156
+ def __pos__(self):
2157
+ return self.__getattr__("__pos__")
2158
+
2159
+ def __abs__(self):
2160
+ return self.__getattr__("__abs__")
2161
+
2162
+ def __invert__(self):
2163
+ return self.__getattr__("__invert__")
2164
+
2165
+ # __complex__, __int__ and __float__ have a default implementation
2166
+ # based on __index__, so they are skipped.
2167
+
2168
+ def __index__(self):
2169
+ return self.__getattr__("__index__")
2170
+
2171
+ def __round__(self, ndigits: object = ...):
2172
+ return self.__getattr__("__round__")
2173
+
2174
+ def __trunc__(self):
2175
+ return self.__getattr__("__trunc__")
2176
+
2177
+ def __floor__(self):
2178
+ return self.__getattr__("__floor__")
2179
+
2180
+ def __ceil__(self):
2181
+ return self.__getattr__("__ceil__")
2182
+
2183
+ # [Context managers]
2184
+
2185
+ def __enter__(self):
2186
+ return self.__getattr__("__enter__")
2187
+
2188
+ def __exit__(self, *args: object, **kwargs: object):
2189
+ return self.__getattr__("__exit__")
2190
+
2191
+
2192
+ class PlaceholderModule(_PlaceholderBase):
2193
+ """
2194
+ A placeholder object to use when a module does not exist.
2195
+
2196
+ This enables more informative errors when trying to access attributes
2197
+ of a module that does not exists.
2198
+ """
2199
+
2200
+ def __init__(self, name: str) -> None:
2201
+ super().__init__()
2202
+
2203
+ # Apply name mangling to avoid conflicting with module attributes
2204
+ self.__name = name
2205
+
2206
+ def placeholder_attr(self, attr_path: str):
2207
+ return _PlaceholderModuleAttr(self, attr_path)
2208
+
2209
+ def __getattr__(self, key: str):
2210
+ name = self.__name
2211
+
2212
+ try:
2213
+ importlib.import_module(name)
2214
+ except ImportError as exc:
2215
+ for extra, names in get_vllm_optional_dependencies().items():
2216
+ if name in names:
2217
+ msg = f"Please install vllm[{extra}] for {extra} support"
2218
+ raise ImportError(msg) from exc
2219
+
2220
+ raise exc
2221
+
2222
+ raise AssertionError("PlaceholderModule should not be used "
2223
+ "when the original module can be imported")
2224
+
2225
+
2226
+ class _PlaceholderModuleAttr(_PlaceholderBase):
2227
+
2228
+ def __init__(self, module: PlaceholderModule, attr_path: str) -> None:
2229
+ super().__init__()
2230
+
2231
+ # Apply name mangling to avoid conflicting with module attributes
2232
+ self.__module = module
2233
+ self.__attr_path = attr_path
2234
+
2235
+ def placeholder_attr(self, attr_path: str):
2236
+ return _PlaceholderModuleAttr(self.__module,
2237
+ f"{self.__attr_path}.{attr_path}")
2238
+
2239
+ def __getattr__(self, key: str):
2240
+ getattr(self.__module, f"{self.__attr_path}.{key}")
2241
+
2242
+ raise AssertionError("PlaceholderModule should not be used "
2243
+ "when the original module can be imported")
2244
+
2245
+
2246
+ # create a library to hold the custom op
2247
+ vllm_lib = Library("vllm", "FRAGMENT") # noqa
2248
+
2249
+
2250
+ def direct_register_custom_op(
2251
+ op_name: str,
2252
+ op_func: Callable,
2253
+ mutates_args: list[str],
2254
+ fake_impl: Optional[Callable] = None,
2255
+ target_lib: Optional[Library] = None,
2256
+ dispatch_key: str = "CUDA",
2257
+ tags: tuple[torch.Tag, ...] = (),
2258
+ ):
2259
+ """
2260
+ `torch.library.custom_op` can have significant overhead because it
2261
+ needs to consider complicated dispatching logic. This function
2262
+ directly registers a custom op and dispatches it to the CUDA backend.
2263
+ See https://gist.github.com/youkaichao/ecbea9ec9fc79a45d2adce1784d7a9a5
2264
+ for more details.
2265
+
2266
+ By default, the custom op is registered to the vLLM library. If you
2267
+ want to register it to a different library, you can pass the library
2268
+ object to the `target_lib` argument.
2269
+
2270
+ IMPORTANT: the lifetime of the operator is tied to the lifetime of the
2271
+ library object. If you want to bind the operator to a different library,
2272
+ make sure the library object is alive when the operator is used.
2273
+ """
2274
+ if not supports_custom_op():
2275
+ from vllm.platforms import current_platform
2276
+ assert not current_platform.is_cuda_alike(), (
2277
+ "cuda platform needs torch>=2.4 to support custom op, "
2278
+ "chances are you are using an old version of pytorch "
2279
+ "or a custom build of pytorch. It is recommended to "
2280
+ "use vLLM in a fresh new environment and let it install "
2281
+ "the required dependencies.")
2282
+ return
2283
+
2284
+ import torch.library
2285
+ if hasattr(torch.library, "infer_schema"):
2286
+ schema_str = torch.library.infer_schema(op_func,
2287
+ mutates_args=mutates_args)
2288
+ else:
2289
+ # for pytorch 2.4
2290
+ import torch._custom_op.impl
2291
+ schema_str = torch._custom_op.impl.infer_schema(op_func, mutates_args)
2292
+ my_lib = target_lib or vllm_lib
2293
+ my_lib.define(op_name + schema_str, tags=tags)
2294
+ my_lib.impl(op_name, op_func, dispatch_key=dispatch_key)
2295
+ if fake_impl is not None:
2296
+ my_lib._register_fake(op_name, fake_impl)
2297
+
2298
+
2299
+ def resolve_obj_by_qualname(qualname: str) -> Any:
2300
+ """
2301
+ Resolve an object by its fully qualified name.
2302
+ """
2303
+ module_name, obj_name = qualname.rsplit(".", 1)
2304
+ module = importlib.import_module(module_name)
2305
+ return getattr(module, obj_name)
2306
+
2307
+
2308
+ def kill_process_tree(pid: int):
2309
+ """
2310
+ Kills all descendant processes of the given pid by sending SIGKILL.
2311
+
2312
+ Args:
2313
+ pid (int): Process ID of the parent process
2314
+ """
2315
+ try:
2316
+ parent = psutil.Process(pid)
2317
+ except psutil.NoSuchProcess:
2318
+ return
2319
+
2320
+ # Get all children recursively
2321
+ children = parent.children(recursive=True)
2322
+
2323
+ # Send SIGKILL to all children first
2324
+ for child in children:
2325
+ with contextlib.suppress(ProcessLookupError):
2326
+ os.kill(child.pid, signal.SIGKILL)
2327
+
2328
+ # Finally kill the parent
2329
+ with contextlib.suppress(ProcessLookupError):
2330
+ os.kill(pid, signal.SIGKILL)
2331
+
2332
+
2333
+ @dataclass
2334
+ class MemorySnapshot:
2335
+ """Memory snapshot."""
2336
+ torch_peak: int = 0
2337
+ free_memory: int = 0
2338
+ total_memory: int = 0
2339
+ cuda_memory: int = 0
2340
+ torch_memory: int = 0
2341
+ non_torch_memory: int = 0
2342
+ timestamp: float = 0.0
2343
+ auto_measure: bool = True
2344
+
2345
+ def __post_init__(self):
2346
+ if self.auto_measure:
2347
+ self.measure()
2348
+
2349
+ def measure(self):
2350
+ # we measure the torch peak memory usage via allocated_bytes,
2351
+ # rather than `torch.cuda.memory_reserved()` .
2352
+ # After `torch.cuda.reset_peak_memory_stats()`,
2353
+ # `torch.cuda.memory_reserved()` will keep growing, and only shrink
2354
+ # when we call `torch.cuda.empty_cache()` or OOM happens.
2355
+ self.torch_peak = torch.cuda.memory_stats().get(
2356
+ "allocated_bytes.all.peak", 0)
2357
+
2358
+ self.free_memory, self.total_memory = torch.cuda.mem_get_info()
2359
+ self.cuda_memory = self.total_memory - self.free_memory
2360
+
2361
+ # torch.cuda.memory_reserved() is how many bytes
2362
+ # PyTorch gets from cuda (by calling cudaMalloc, etc.)
2363
+ # this is used to measure the non-torch memory usage
2364
+ self.torch_memory = torch.cuda.memory_reserved()
2365
+
2366
+ self.non_torch_memory = self.cuda_memory - self.torch_memory
2367
+ self.timestamp = time.time()
2368
+
2369
+ def __sub__(self, other: MemorySnapshot) -> MemorySnapshot:
2370
+ return MemorySnapshot(
2371
+ torch_peak=self.torch_peak - other.torch_peak,
2372
+ free_memory=self.free_memory - other.free_memory,
2373
+ total_memory=self.total_memory - other.total_memory,
2374
+ cuda_memory=self.cuda_memory - other.cuda_memory,
2375
+ torch_memory=self.torch_memory - other.torch_memory,
2376
+ non_torch_memory=self.non_torch_memory - other.non_torch_memory,
2377
+ timestamp=self.timestamp - other.timestamp,
2378
+ auto_measure=False,
2379
+ )
2380
+
2381
+
2382
+ @dataclass
2383
+ class MemoryProfilingResult:
2384
+ """Memory profiling result. All numbers are in bytes.
2385
+ """
2386
+ non_kv_cache_memory: int = 0
2387
+ torch_peak_increase: int = 0
2388
+ non_torch_increase: int = 0
2389
+ weights_memory: float = 0
2390
+ before_create: MemorySnapshot = field(default_factory=MemorySnapshot)
2391
+ before_profile: MemorySnapshot = field(default_factory=MemorySnapshot)
2392
+ after_profile: MemorySnapshot = field(default_factory=MemorySnapshot)
2393
+ profile_time: float = 0.0
2394
+
2395
+ def __repr__(self) -> str:
2396
+ return (f"Memory profiling takes {self.profile_time:.2f} seconds. "
2397
+ f"Total non KV cache memory: "
2398
+ f"{(self.non_kv_cache_memory / GiB_bytes):.2f}GiB; "
2399
+ f"torch peak memory increase: "
2400
+ f"{(self.torch_peak_increase / GiB_bytes):.2f}GiB; "
2401
+ f"non-torch forward increase memory: "
2402
+ f"{(self.non_torch_increase / GiB_bytes):.2f}GiB; "
2403
+ f"weights memory: {(self.weights_memory / GiB_bytes):.2f}GiB.")
2404
+
2405
+
2406
+ @contextlib.contextmanager
2407
+ def memory_profiling(
2408
+ baseline_snapshot: MemorySnapshot,
2409
+ weights_memory: int) -> Generator[MemoryProfilingResult, None, None]:
2410
+ """Memory profiling context manager.
2411
+ baseline_snapshot: the memory snapshot before the current vLLM instance.
2412
+ weights_memory: memory used by PyTorch when loading the model weights.
2413
+ Note that, before loading the model weights, we also initialize the device
2414
+ and distributed environment, which may consume some memory. This part is not
2415
+ included in the weights_memory because PyTorch does not control it.
2416
+
2417
+ The memory in one GPU can be classified into 3 categories:
2418
+ 1. memory used by anything other than the current vLLM instance.
2419
+ 2. memory used by torch in the current vLLM instance.
2420
+ 3. memory used in the current vLLM instance, but not by torch.
2421
+
2422
+ A quantitive example:
2423
+
2424
+ Before creating the current vLLM instance:
2425
+ category 1: 1 GiB
2426
+ category 2: 0 GiB
2427
+ category 3: 0 GiB
2428
+
2429
+ After creating the current vLLM instance and loading the model,
2430
+ (i.e. before profiling):
2431
+ category 1: 1 GiB
2432
+ category 2: 2 GiB (model weights take 2 GiB)
2433
+ category 3: 0.5 GiB (memory used by NCCL)
2434
+
2435
+ During profiling (peak):
2436
+ category 1: 1 GiB
2437
+ category 2: 4 GiB (peak activation tensors take 2 GiB)
2438
+ category 3: 1 GiB (memory used by NCCL + buffers for some attention backends)
2439
+
2440
+ After profiling:
2441
+ category 1: 1 GiB
2442
+ category 2: 3 GiB (after garbage-collecting activation tensors)
2443
+ category 3: 1 GiB (memory used by NCCL + buffers for some attention backends)
2444
+
2445
+ In this case, non-kv cache takes 5 GiB in total, including:
2446
+ a. 2 GiB used by the model weights (category 2)
2447
+ b. 2 GiB reserved for the peak activation tensors (category 2)
2448
+ c. 1 GiB used by non-torch components (category 3)
2449
+
2450
+ The memory used for loading weights (a.) is directly given from the argument `weights_memory`.
2451
+
2452
+ The increase of `torch.cuda.memory_stats()["allocated_bytes.all.peak"]` during profiling gives (b.).
2453
+
2454
+ The increase of `non_torch_memory` from creating the current vLLM instance until after profiling to get (c.).
2455
+ """ # noqa
2456
+ gc.collect()
2457
+ torch.cuda.empty_cache()
2458
+ torch.cuda.reset_peak_memory_stats()
2459
+
2460
+ result = MemoryProfilingResult()
2461
+
2462
+ result.before_create = baseline_snapshot
2463
+ # the part of memory used for holding the model weights
2464
+ result.weights_memory = weights_memory
2465
+
2466
+ result.before_profile.measure()
2467
+
2468
+ yield result
2469
+
2470
+ gc.collect()
2471
+ torch.cuda.empty_cache()
2472
+
2473
+ result.after_profile.measure()
2474
+
2475
+ diff_profile = result.after_profile - result.before_profile
2476
+ diff_from_create = result.after_profile - result.before_create
2477
+ result.torch_peak_increase = diff_profile.torch_peak
2478
+ result.non_torch_increase = diff_from_create.non_torch_memory
2479
+ result.profile_time = diff_profile.timestamp
2480
+ result.non_kv_cache_memory = result.non_torch_increase + result.torch_peak_increase + result.weights_memory # noqa
2481
+
2482
+
2483
+ # Adapted from: https://github.com/sgl-project/sglang/blob/v0.4.1/python/sglang/srt/utils.py#L630 # noqa: E501
2484
+ def set_ulimit(target_soft_limit=65535):
2485
+ if sys.platform.startswith('win'):
2486
+ logger.info("Windows detected, skipping ulimit adjustment.")
2487
+ return
2488
+
2489
+ import resource
2490
+ resource_type = resource.RLIMIT_NOFILE
2491
+ current_soft, current_hard = resource.getrlimit(resource_type)
2492
+
2493
+ if current_soft < target_soft_limit:
2494
+ try:
2495
+ resource.setrlimit(resource_type,
2496
+ (target_soft_limit, current_hard))
2497
+ except ValueError as e:
2498
+ logger.warning(
2499
+ "Found ulimit of %s and failed to automatically increase "
2500
+ "with error %s. This can cause fd limit errors like "
2501
+ "`OSError: [Errno 24] Too many open files`. Consider "
2502
+ "increasing with ulimit -n", current_soft, e)
2503
+
2504
+
2505
+ # Adapted from: https://github.com/sgl-project/sglang/blob/v0.4.1/python/sglang/utils.py#L28 # noqa: E501
2506
+ def get_exception_traceback():
2507
+ etype, value, tb = sys.exc_info()
2508
+ err_str = "".join(traceback.format_exception(etype, value, tb))
2509
+ return err_str
2510
+
2511
+
2512
+ def split_zmq_path(path: str) -> tuple[str, str, str]:
2513
+ """Split a zmq path into its parts."""
2514
+ parsed = urlparse(path)
2515
+ if not parsed.scheme:
2516
+ raise ValueError(f"Invalid zmq path: {path}")
2517
+
2518
+ scheme = parsed.scheme
2519
+ host = parsed.hostname or ""
2520
+ port = str(parsed.port or "")
2521
+
2522
+ if scheme == "tcp" and not all((host, port)):
2523
+ # The host and port fields are required for tcp
2524
+ raise ValueError(f"Invalid zmq path: {path}")
2525
+
2526
+ if scheme != "tcp" and port:
2527
+ # port only makes sense with tcp
2528
+ raise ValueError(f"Invalid zmq path: {path}")
2529
+
2530
+ return scheme, host, port
2531
+
2532
+
2533
+ def make_zmq_path(scheme: str, host: str, port: Optional[int] = None) -> str:
2534
+ """Make a ZMQ path from its parts.
2535
+
2536
+ Args:
2537
+ scheme: The ZMQ transport scheme (e.g. tcp, ipc, inproc).
2538
+ host: The host - can be an IPv4 address, IPv6 address, or hostname.
2539
+ port: Optional port number, only used for TCP sockets.
2540
+
2541
+ Returns:
2542
+ A properly formatted ZMQ path string.
2543
+ """
2544
+ if port is None:
2545
+ return f"{scheme}://{host}"
2546
+ if is_valid_ipv6_address(host):
2547
+ return f"{scheme}://[{host}]:{port}"
2548
+ return f"{scheme}://{host}:{port}"
2549
+
2550
+
2551
+ # Adapted from: https://github.com/sgl-project/sglang/blob/v0.4.1/python/sglang/srt/utils.py#L783 # noqa: E501
2552
+ def make_zmq_socket(
2553
+ ctx: Union[zmq.asyncio.Context, zmq.Context], # type: ignore[name-defined]
2554
+ path: str,
2555
+ socket_type: Any,
2556
+ bind: Optional[bool] = None,
2557
+ identity: Optional[bytes] = None,
2558
+ linger: Optional[int] = None,
2559
+ ) -> Union[zmq.Socket, zmq.asyncio.Socket]: # type: ignore[name-defined]
2560
+ """Make a ZMQ socket with the proper bind/connect semantics."""
2561
+
2562
+ mem = psutil.virtual_memory()
2563
+ socket = ctx.socket(socket_type)
2564
+
2565
+ # Calculate buffer size based on system memory
2566
+ total_mem = mem.total / 1024**3
2567
+ available_mem = mem.available / 1024**3
2568
+ # For systems with substantial memory (>32GB total, >16GB available):
2569
+ # - Set a large 0.5GB buffer to improve throughput
2570
+ # For systems with less memory:
2571
+ # - Use system default (-1) to avoid excessive memory consumption
2572
+ if total_mem > 32 and available_mem > 16:
2573
+ buf_size = int(0.5 * 1024**3) # 0.5GB in bytes
2574
+ else:
2575
+ buf_size = -1 # Use system default buffer size
2576
+
2577
+ if bind is None:
2578
+ bind = socket_type not in (zmq.PUSH, zmq.SUB, zmq.XSUB)
2579
+
2580
+ if socket_type in (zmq.PULL, zmq.DEALER, zmq.ROUTER):
2581
+ socket.setsockopt(zmq.RCVHWM, 0)
2582
+ socket.setsockopt(zmq.RCVBUF, buf_size)
2583
+
2584
+ if socket_type in (zmq.PUSH, zmq.DEALER, zmq.ROUTER):
2585
+ socket.setsockopt(zmq.SNDHWM, 0)
2586
+ socket.setsockopt(zmq.SNDBUF, buf_size)
2587
+
2588
+ if identity is not None:
2589
+ socket.setsockopt(zmq.IDENTITY, identity)
2590
+
2591
+ if linger is not None:
2592
+ socket.setsockopt(zmq.LINGER, linger)
2593
+
2594
+ # Determine if the path is a TCP socket with an IPv6 address.
2595
+ # Enable IPv6 on the zmq socket if so.
2596
+ scheme, host, _ = split_zmq_path(path)
2597
+ if scheme == "tcp" and is_valid_ipv6_address(host):
2598
+ socket.setsockopt(zmq.IPV6, 1)
2599
+
2600
+ if bind:
2601
+ socket.bind(path)
2602
+ else:
2603
+ socket.connect(path)
2604
+
2605
+ return socket
2606
+
2607
+
2608
+ @contextlib.contextmanager
2609
+ def zmq_socket_ctx(
2610
+ path: str,
2611
+ socket_type: Any,
2612
+ bind: Optional[bool] = None,
2613
+ linger: int = 0,
2614
+ identity: Optional[bytes] = None,
2615
+ ) -> Iterator[zmq.Socket]:
2616
+ """Context manager for a ZMQ socket"""
2617
+
2618
+ ctx = zmq.Context() # type: ignore[attr-defined]
2619
+ try:
2620
+ yield make_zmq_socket(ctx,
2621
+ path,
2622
+ socket_type,
2623
+ bind=bind,
2624
+ identity=identity)
2625
+ except KeyboardInterrupt:
2626
+ logger.debug("Got Keyboard Interrupt.")
2627
+
2628
+ finally:
2629
+ ctx.destroy(linger=linger)
2630
+
2631
+
2632
+ def is_in_ray_actor():
2633
+ """Check if we are in a Ray actor."""
2634
+
2635
+ try:
2636
+ import ray
2637
+ return (ray.is_initialized()
2638
+ and ray.get_runtime_context().get_actor_id() is not None)
2639
+ except ImportError:
2640
+ return False
2641
+
2642
+
2643
+ def _maybe_force_spawn():
2644
+ """Check if we need to force the use of the `spawn` multiprocessing start
2645
+ method.
2646
+ """
2647
+ if os.environ.get("VLLM_WORKER_MULTIPROC_METHOD") == "spawn":
2648
+ return
2649
+
2650
+ reason = None
2651
+ if cuda_is_initialized():
2652
+ reason = "CUDA is initialized"
2653
+ elif is_in_ray_actor():
2654
+ # even if we choose to spawn, we need to pass the ray address
2655
+ # to the subprocess so that it knows how to connect to the ray cluster.
2656
+ # env vars are inherited by subprocesses, even if we use spawn.
2657
+ import ray
2658
+ os.environ["RAY_ADDRESS"] = ray.get_runtime_context().gcs_address
2659
+ reason = "In a Ray actor and can only be spawned"
2660
+
2661
+ if reason is not None:
2662
+ logger.warning(
2663
+ "We must use the `spawn` multiprocessing start method. "
2664
+ "Overriding VLLM_WORKER_MULTIPROC_METHOD to 'spawn'. "
2665
+ "See https://docs.vllm.ai/en/latest/usage/"
2666
+ "troubleshooting.html#python-multiprocessing "
2667
+ "for more information. Reason: %s", reason)
2668
+ os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
2669
+
2670
+
2671
+ def get_mp_context():
2672
+ """Get a multiprocessing context with a particular method (spawn or fork).
2673
+ By default we follow the value of the VLLM_WORKER_MULTIPROC_METHOD to
2674
+ determine the multiprocessing method (default is fork). However, under
2675
+ certain conditions, we may enforce spawn and override the value of
2676
+ VLLM_WORKER_MULTIPROC_METHOD.
2677
+ """
2678
+ _maybe_force_spawn()
2679
+ mp_method = envs.VLLM_WORKER_MULTIPROC_METHOD
2680
+ return multiprocessing.get_context(mp_method)
2681
+
2682
+
2683
+ def bind_kv_cache(
2684
+ ctx: dict[str, Any],
2685
+ kv_cache: list[list[torch.Tensor]], # [virtual_engine][layer_index]
2686
+ ) -> None:
2687
+ # Bind the kv_cache tensor to Attention modules, similar to
2688
+ # ctx[layer_name].kv_cache[ve]=kv_cache[ve][extract_layer_index(layer_name)]
2689
+ # Special things handled here:
2690
+ # 1. Some models have non-attention layers, e.g., Jamba
2691
+ # 2. Pipeline parallelism, each rank only has a subset of layers
2692
+ # 3. Encoder attention has no kv cache
2693
+ # 4. Encoder-decoder models, encoder-decoder attention and decoder-only
2694
+ # attention of the same layer (e.g., bart's decoder.layers.1.self_attn
2695
+ # and decoder.layers.1.encoder_attn) is mapped to the same kv cache
2696
+ # tensor
2697
+ from vllm.attention import AttentionType
2698
+ from vllm.model_executor.models.utils import extract_layer_index
2699
+ layer_need_kv_cache = [
2700
+ layer_name for layer_name in ctx
2701
+ if (hasattr(ctx[layer_name], 'attn_type') and ctx[layer_name].attn_type
2702
+ in (AttentionType.DECODER, AttentionType.ENCODER_DECODER))
2703
+ ]
2704
+ layer_index_sorted = sorted(
2705
+ set(
2706
+ extract_layer_index(layer_name)
2707
+ for layer_name in layer_need_kv_cache))
2708
+ for layer_name in layer_need_kv_cache:
2709
+ kv_cache_idx = layer_index_sorted.index(
2710
+ extract_layer_index(layer_name))
2711
+ forward_ctx = ctx[layer_name]
2712
+ assert len(forward_ctx.kv_cache) == len(kv_cache)
2713
+ for ve, ve_kv_cache in enumerate(kv_cache):
2714
+ forward_ctx.kv_cache[ve] = ve_kv_cache[kv_cache_idx]
2715
+
2716
+
2717
+ def run_method(obj: Any, method: Union[str, bytes, Callable], args: tuple[Any],
2718
+ kwargs: dict[str, Any]) -> Any:
2719
+ """
2720
+ Run a method of an object with the given arguments and keyword arguments.
2721
+ If the method is string, it will be converted to a method using getattr.
2722
+ If the method is serialized bytes and will be deserialized using
2723
+ cloudpickle.
2724
+ If the method is a callable, it will be called directly.
2725
+ """
2726
+ if isinstance(method, bytes):
2727
+ func = partial(cloudpickle.loads(method), obj)
2728
+ elif isinstance(method, str):
2729
+ try:
2730
+ func = getattr(obj, method)
2731
+ except AttributeError:
2732
+ raise NotImplementedError(f"Method {method!r} is not"
2733
+ " implemented.") from None
2734
+ else:
2735
+ func = partial(method, obj) # type: ignore
2736
+ return func(*args, **kwargs)
2737
+
2738
+
2739
+ def import_pynvml():
2740
+ """
2741
+ Historical comments:
2742
+
2743
+ libnvml.so is the library behind nvidia-smi, and
2744
+ pynvml is a Python wrapper around it. We use it to get GPU
2745
+ status without initializing CUDA context in the current process.
2746
+ Historically, there are two packages that provide pynvml:
2747
+ - `nvidia-ml-py` (https://pypi.org/project/nvidia-ml-py/): The official
2748
+ wrapper. It is a dependency of vLLM, and is installed when users
2749
+ install vLLM. It provides a Python module named `pynvml`.
2750
+ - `pynvml` (https://pypi.org/project/pynvml/): An unofficial wrapper.
2751
+ Prior to version 12.0, it also provides a Python module `pynvml`,
2752
+ and therefore conflicts with the official one. What's worse,
2753
+ the module is a Python package, and has higher priority than
2754
+ the official one which is a standalone Python file.
2755
+ This causes errors when both of them are installed.
2756
+ Starting from version 12.0, it migrates to a new module
2757
+ named `pynvml_utils` to avoid the conflict.
2758
+ It is so confusing that many packages in the community use the
2759
+ unofficial one by mistake, and we have to handle this case.
2760
+ For example, `nvcr.io/nvidia/pytorch:24.12-py3` uses the unofficial
2761
+ one, and it will cause errors, see the issue
2762
+ https://github.com/vllm-project/vllm/issues/12847 for example.
2763
+ After all the troubles, we decide to copy the official `pynvml`
2764
+ module to our codebase, and use it directly.
2765
+ """
2766
+ import vllm.third_party.pynvml as pynvml
2767
+ return pynvml
2768
+
2769
+
2770
+ def warn_for_unimplemented_methods(cls: type[T]) -> type[T]:
2771
+ """
2772
+ A replacement for `abc.ABC`.
2773
+ When we use `abc.ABC`, subclasses will fail to instantiate
2774
+ if they do not implement all abstract methods.
2775
+ Here, we only require `raise NotImplementedError` in the
2776
+ base class, and log a warning if the method is not implemented
2777
+ in the subclass.
2778
+ """
2779
+
2780
+ original_init = cls.__init__
2781
+
2782
+ def find_unimplemented_methods(self: object):
2783
+ unimplemented_methods = []
2784
+ for attr_name in dir(self):
2785
+ # bypass inner method
2786
+ if attr_name.startswith('_'):
2787
+ continue
2788
+
2789
+ try:
2790
+ attr = getattr(self, attr_name)
2791
+ # get the func of callable method
2792
+ if callable(attr):
2793
+ attr_func = attr.__func__
2794
+ except AttributeError:
2795
+ continue
2796
+ src = inspect.getsource(attr_func)
2797
+ if "NotImplementedError" in src:
2798
+ unimplemented_methods.append(attr_name)
2799
+ if unimplemented_methods:
2800
+ method_names = ','.join(unimplemented_methods)
2801
+ msg = (f"Methods {method_names} not implemented in {self}")
2802
+ logger.debug(msg)
2803
+
2804
+ @wraps(original_init)
2805
+ def wrapped_init(self, *args, **kwargs) -> None:
2806
+ original_init(self, *args, **kwargs)
2807
+ find_unimplemented_methods(self)
2808
+
2809
+ type.__setattr__(cls, '__init__', wrapped_init)
2810
+ return cls
2811
+
2812
+
2813
+ class LazyLoader(types.ModuleType):
2814
+ """
2815
+ LazyLoader module borrowed from Tensorflow
2816
+ https://github.com/tensorflow/tensorflow/blob/main/tensorflow/python/util/lazy_loader.py
2817
+ with a addition of "module caching".
2818
+
2819
+ Lazily import a module, mainly to avoid pulling in large dependencies.
2820
+ Modules such as `xgrammar` might do additional side effects, so we
2821
+ only want to use this when it is needed, delaying all eager effects
2822
+ """
2823
+
2824
+ def __init__(
2825
+ self,
2826
+ local_name: str,
2827
+ parent_module_globals: dict[str, Any],
2828
+ name: str,
2829
+ ):
2830
+ self._local_name = local_name
2831
+ self._parent_module_globals = parent_module_globals
2832
+ self._module: types.ModuleType | None = None
2833
+
2834
+ super().__init__(str(name))
2835
+
2836
+ def _load(self) -> types.ModuleType:
2837
+ # Import the target module and insert it into the parent's namespace
2838
+ try:
2839
+ module = importlib.import_module(self.__name__)
2840
+ self._parent_module_globals[self._local_name] = module
2841
+ # The additional add to sys.modules
2842
+ # ensures library is actually loaded.
2843
+ sys.modules[self._local_name] = module
2844
+ except ModuleNotFoundError as err:
2845
+ raise err from None
2846
+
2847
+ # Update this object's dict so that if someone keeps a
2848
+ # reference to the LazyLoader, lookups are efficient
2849
+ # (__getattr__ is only called on lookups that fail).
2850
+ self.__dict__.update(module.__dict__)
2851
+ return module
2852
+
2853
+ def __getattr__(self, item: Any) -> Any:
2854
+ if self._module is None:
2855
+ self._module = self._load()
2856
+ return getattr(self._module, item)
2857
+
2858
+ def __dir__(self) -> list[str]:
2859
+ if self._module is None:
2860
+ self._module = self._load()
2861
+ return dir(self._module)
2862
+
2863
+
2864
+ def swap_dict_values(obj: dict[_K, _V], key1: _K, key2: _K) -> None:
2865
+ """
2866
+ Helper function to swap values for two keys
2867
+ """
2868
+ v1 = obj.get(key1)
2869
+ v2 = obj.get(key2)
2870
+ if v1 is not None:
2871
+ obj[key2] = v1
2872
+ else:
2873
+ obj.pop(key2, None)
2874
+ if v2 is not None:
2875
+ obj[key1] = v2
2876
+ else:
2877
+ obj.pop(key1, None)
2878
+
2879
+
2880
+ @contextlib.contextmanager
2881
+ def cprofile_context(save_file: Optional[str] = None):
2882
+ """Run a cprofile
2883
+
2884
+ Args:
2885
+ save_file: path to save the profile result. "1" or
2886
+ None will result in printing to stdout.
2887
+ """
2888
+ import cProfile
2889
+
2890
+ prof = cProfile.Profile()
2891
+ prof.enable()
2892
+
2893
+ try:
2894
+ yield
2895
+ finally:
2896
+ prof.disable()
2897
+ if save_file and save_file != "1":
2898
+ prof.dump_stats(save_file)
2899
+ else:
2900
+ prof.print_stats(sort="cumtime")
2901
+
2902
+
2903
+ def cprofile(save_file: Optional[str] = None, enabled: bool = True):
2904
+ """Decorator to profile a Python method using cProfile.
2905
+
2906
+ Args:
2907
+ save_file: Path to save the profile result.
2908
+ If "1", None, or "", results will be printed to stdout.
2909
+ enabled: Set to false to turn this into a no-op
2910
+ """
2911
+
2912
+ def decorator(func: Callable):
2913
+
2914
+ @wraps(func)
2915
+ def wrapper(*args, **kwargs):
2916
+ if not enabled:
2917
+ # If profiling is disabled, just call the function directly.
2918
+ return func(*args, **kwargs)
2919
+
2920
+ with cprofile_context(save_file):
2921
+ return func(*args, **kwargs)
2922
+
2923
+ return wrapper
2924
+
2925
+ return decorator
2926
+
2927
+
2928
+ # Only relevant for models using ALiBi (e.g, MPT)
2929
+ def check_use_alibi(model_config: ModelConfig) -> bool:
2930
+ cfg = model_config.hf_text_config
2931
+ return (getattr(cfg, "alibi", False) # Falcon
2932
+ or ("BloomForCausalLM" in getattr(model_config.hf_config,
2933
+ "architectures", [])) # Bloom
2934
+ or getattr(cfg, "position_encoding_type", "") ==
2935
+ "alibi" # codellm_1b_alibi
2936
+ or (hasattr(cfg, "attn_config") # MPT
2937
+ and ((isinstance(cfg.attn_config, dict)
2938
+ and cfg.attn_config.get("alibi", False)) or
2939
+ (not isinstance(cfg.attn_config, dict)
2940
+ and getattr(cfg.attn_config, "alibi", False)))))
2941
+
2942
+
2943
+ def sha256(input) -> int:
2944
+ """Hash any picklable Python object using SHA-256.
2945
+
2946
+ The input is serialized using pickle before hashing, which allows
2947
+ arbitrary Python objects to be used. Note that this function does
2948
+ not use a hash seed—if you need one, prepend it explicitly to the input.
2949
+
2950
+ Args:
2951
+ input: Any picklable Python object.
2952
+
2953
+ Returns:
2954
+ An integer representing the SHA-256 hash of the serialized input.
2955
+ """
2956
+ input_bytes = pickle.dumps(input, protocol=pickle.HIGHEST_PROTOCOL)
2957
+ return int.from_bytes(hashlib.sha256(input_bytes).digest(),
2958
+ byteorder="big")
2959
+
2960
+
2961
+ def is_torch_equal_or_newer(target: str) -> bool:
2962
+ """Check if the installed torch version is >= the target version.
2963
+
2964
+ Args:
2965
+ target: a version string, like "2.6.0".
2966
+
2967
+ Returns:
2968
+ Whether the condition meets.
2969
+ """
2970
+ try:
2971
+ return _is_torch_equal_or_newer(str(torch.__version__), target)
2972
+ except Exception:
2973
+ # Fallback to PKG-INFO to load the package info, needed by the doc gen.
2974
+ return Version(importlib.metadata.version('torch')) >= Version(target)
2975
+
2976
+
2977
+ # Helper function used in testing.
2978
+ def _is_torch_equal_or_newer(torch_version: str, target: str) -> bool:
2979
+ torch_version = version.parse(torch_version)
2980
+ return torch_version >= version.parse(target)
2981
+
2982
+
2983
+ @cache
2984
+ def _has_module(module_name: str) -> bool:
2985
+ """Return True if *module_name* can be found in the current environment.
2986
+
2987
+ The result is cached so that subsequent queries for the same module incur
2988
+ no additional overhead.
2989
+ """
2990
+ return importlib.util.find_spec(module_name) is not None
2991
+
2992
+
2993
+ def has_pplx() -> bool:
2994
+ """Whether the optional `pplx_kernels` package is available."""
2995
+
2996
+ return _has_module("pplx_kernels")
2997
+
2998
+
2999
+ def has_deep_ep() -> bool:
3000
+ """Whether the optional `deep_ep` package is available."""
3001
+
3002
+ return _has_module("deep_ep")
3003
+
3004
+
3005
+ def has_deep_gemm() -> bool:
3006
+ """Whether the optional `deep_gemm` package is available."""
3007
+
3008
+ return _has_module("deep_gemm")