sglang 0.5.2rc2__py3-none-any.whl → 0.5.3__py3-none-any.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 (377) hide show
  1. sglang/bench_one_batch.py +7 -9
  2. sglang/bench_one_batch_server.py +330 -31
  3. sglang/bench_serving.py +267 -32
  4. sglang/global_config.py +2 -2
  5. sglang/lang/backend/runtime_endpoint.py +1 -1
  6. sglang/launch_server.py +14 -0
  7. sglang/profiler.py +2 -2
  8. sglang/srt/batch_invariant_ops/__init__.py +27 -0
  9. sglang/srt/batch_invariant_ops/batch_invariant_ops.py +549 -0
  10. sglang/srt/configs/__init__.py +8 -0
  11. sglang/srt/configs/device_config.py +3 -1
  12. sglang/srt/configs/dots_ocr.py +64 -0
  13. sglang/srt/configs/dots_vlm.py +139 -0
  14. sglang/srt/configs/falcon_h1.py +360 -0
  15. sglang/srt/configs/load_config.py +9 -0
  16. sglang/srt/configs/model_config.py +181 -82
  17. sglang/srt/configs/qwen3_next.py +326 -0
  18. sglang/srt/configs/qwen3_vl.py +586 -0
  19. sglang/srt/connector/__init__.py +8 -1
  20. sglang/srt/connector/remote_instance.py +82 -0
  21. sglang/srt/constrained/base_grammar_backend.py +49 -12
  22. sglang/srt/constrained/llguidance_backend.py +0 -1
  23. sglang/srt/constrained/outlines_backend.py +0 -1
  24. sglang/srt/constrained/outlines_jump_forward.py +1 -1
  25. sglang/srt/constrained/xgrammar_backend.py +30 -9
  26. sglang/srt/custom_op.py +11 -1
  27. sglang/srt/debug_utils/dump_comparator.py +81 -44
  28. sglang/srt/debug_utils/dump_loader.py +97 -0
  29. sglang/srt/debug_utils/dumper.py +21 -6
  30. sglang/srt/debug_utils/text_comparator.py +73 -11
  31. sglang/srt/disaggregation/ascend/conn.py +2 -2
  32. sglang/srt/disaggregation/ascend/transfer_engine.py +47 -9
  33. sglang/srt/disaggregation/base/conn.py +1 -1
  34. sglang/srt/disaggregation/common/conn.py +279 -108
  35. sglang/srt/disaggregation/decode.py +71 -19
  36. sglang/srt/disaggregation/decode_kvcache_offload_manager.py +185 -0
  37. sglang/srt/disaggregation/decode_schedule_batch_mixin.py +29 -17
  38. sglang/srt/disaggregation/fake/conn.py +1 -1
  39. sglang/srt/disaggregation/mini_lb.py +6 -445
  40. sglang/srt/disaggregation/mooncake/conn.py +55 -537
  41. sglang/srt/disaggregation/nixl/conn.py +326 -53
  42. sglang/srt/disaggregation/prefill.py +36 -17
  43. sglang/srt/disaggregation/utils.py +40 -54
  44. sglang/srt/distributed/device_communicators/all_reduce_utils.py +16 -0
  45. sglang/srt/distributed/device_communicators/shm_broadcast.py +4 -2
  46. sglang/srt/distributed/device_communicators/symm_mem.py +164 -0
  47. sglang/srt/distributed/parallel_state.py +156 -80
  48. sglang/srt/entrypoints/engine.py +59 -18
  49. sglang/srt/entrypoints/grpc_request_manager.py +855 -0
  50. sglang/srt/entrypoints/grpc_server.py +810 -0
  51. sglang/srt/entrypoints/http_server.py +130 -59
  52. sglang/srt/entrypoints/openai/protocol.py +112 -4
  53. sglang/srt/entrypoints/openai/serving_base.py +65 -3
  54. sglang/srt/entrypoints/openai/serving_chat.py +204 -55
  55. sglang/srt/entrypoints/openai/serving_completions.py +14 -3
  56. sglang/srt/entrypoints/openai/serving_embedding.py +9 -3
  57. sglang/srt/entrypoints/openai/serving_rerank.py +3 -1
  58. sglang/srt/entrypoints/openai/serving_responses.py +48 -3
  59. sglang/srt/entrypoints/openai/serving_score.py +1 -0
  60. sglang/srt/environ.py +285 -0
  61. sglang/srt/eplb/eplb_manager.py +2 -2
  62. sglang/srt/eplb/expert_distribution.py +26 -13
  63. sglang/srt/eplb/expert_location.py +38 -8
  64. sglang/srt/eplb/expert_location_updater.py +1 -1
  65. sglang/srt/function_call/base_format_detector.py +3 -6
  66. sglang/srt/function_call/ebnf_composer.py +11 -9
  67. sglang/srt/function_call/function_call_parser.py +9 -2
  68. sglang/srt/function_call/glm4_moe_detector.py +4 -4
  69. sglang/srt/function_call/gpt_oss_detector.py +23 -0
  70. sglang/srt/function_call/json_array_parser.py +63 -0
  71. sglang/srt/function_call/kimik2_detector.py +17 -4
  72. sglang/srt/function_call/qwen3_coder_detector.py +1 -1
  73. sglang/srt/function_call/utils.py +96 -5
  74. sglang/srt/grpc/__init__.py +1 -0
  75. sglang/srt/grpc/compile_proto.py +245 -0
  76. sglang/srt/grpc/sglang_scheduler_pb2.py +111 -0
  77. sglang/srt/grpc/sglang_scheduler_pb2.pyi +434 -0
  78. sglang/srt/grpc/sglang_scheduler_pb2_grpc.py +239 -0
  79. sglang/srt/layers/activation.py +143 -9
  80. sglang/srt/layers/attention/aiter_backend.py +14 -15
  81. sglang/srt/layers/attention/ascend_backend.py +115 -9
  82. sglang/srt/layers/attention/attention_registry.py +206 -0
  83. sglang/srt/layers/attention/base_attn_backend.py +12 -3
  84. sglang/srt/layers/attention/cutlass_mla_backend.py +3 -3
  85. sglang/srt/layers/attention/dual_chunk_flashattention_backend.py +1 -1
  86. sglang/srt/layers/attention/fla/chunk.py +242 -0
  87. sglang/srt/layers/attention/fla/chunk_delta_h.py +314 -0
  88. sglang/srt/layers/attention/fla/chunk_o.py +178 -0
  89. sglang/srt/layers/attention/fla/chunk_scaled_dot_kkt.py +151 -0
  90. sglang/srt/layers/attention/fla/cumsum.py +300 -0
  91. sglang/srt/layers/attention/fla/fused_recurrent.py +640 -0
  92. sglang/srt/layers/attention/fla/fused_sigmoid_gating_recurrent.py +232 -0
  93. sglang/srt/layers/attention/fla/index.py +37 -0
  94. sglang/srt/layers/attention/fla/l2norm.py +150 -0
  95. sglang/srt/layers/attention/fla/layernorm_gated.py +326 -0
  96. sglang/srt/layers/attention/fla/op.py +66 -0
  97. sglang/srt/layers/attention/fla/solve_tril.py +465 -0
  98. sglang/srt/layers/attention/fla/utils.py +331 -0
  99. sglang/srt/layers/attention/fla/wy_fast.py +158 -0
  100. sglang/srt/layers/attention/flashattention_backend.py +41 -8
  101. sglang/srt/layers/attention/flashinfer_backend.py +118 -198
  102. sglang/srt/layers/attention/flashinfer_mla_backend.py +27 -27
  103. sglang/srt/layers/attention/flashmla_backend.py +7 -5
  104. sglang/srt/layers/attention/hybrid_attn_backend.py +68 -53
  105. sglang/srt/layers/attention/hybrid_linear_attn_backend.py +602 -0
  106. sglang/srt/layers/attention/intel_amx_backend.py +3 -0
  107. sglang/srt/layers/attention/mamba/causal_conv1d.py +129 -0
  108. sglang/srt/layers/attention/mamba/causal_conv1d_triton.py +969 -0
  109. sglang/srt/layers/attention/mamba/mamba.py +629 -0
  110. sglang/srt/layers/attention/mamba/mamba_utils.py +81 -0
  111. sglang/srt/layers/attention/mamba/ops/__init__.py +2 -0
  112. sglang/srt/layers/attention/mamba/ops/layernorm_gated.py +172 -0
  113. sglang/srt/layers/attention/mamba/ops/mamba_ssm.py +442 -0
  114. sglang/srt/layers/attention/mamba/ops/ssd_bmm.py +264 -0
  115. sglang/srt/layers/attention/mamba/ops/ssd_chunk_scan.py +622 -0
  116. sglang/srt/layers/attention/mamba/ops/ssd_chunk_state.py +757 -0
  117. sglang/srt/layers/attention/mamba/ops/ssd_combined.py +262 -0
  118. sglang/srt/layers/attention/mamba/ops/ssd_state_passing.py +275 -0
  119. sglang/srt/layers/attention/npu_ops/mla_preprocess.py +393 -0
  120. sglang/srt/layers/attention/nsa/dequant_k_cache.py +163 -0
  121. sglang/srt/layers/attention/nsa/index_buf_accessor.py +354 -0
  122. sglang/srt/layers/attention/nsa/nsa_indexer.py +761 -0
  123. sglang/srt/layers/attention/nsa/quant_k_cache.py +255 -0
  124. sglang/srt/layers/attention/nsa/tilelang_kernel.py +785 -0
  125. sglang/srt/layers/attention/nsa/transform_index.py +144 -0
  126. sglang/srt/layers/attention/nsa/utils.py +24 -0
  127. sglang/srt/layers/attention/nsa_backend.py +887 -0
  128. sglang/srt/layers/attention/tbo_backend.py +6 -6
  129. sglang/srt/layers/attention/torch_flex_backend.py +325 -0
  130. sglang/srt/layers/attention/torch_native_backend.py +12 -6
  131. sglang/srt/layers/attention/triton_backend.py +57 -7
  132. sglang/srt/layers/attention/trtllm_mha_backend.py +5 -7
  133. sglang/srt/layers/attention/trtllm_mla_backend.py +276 -39
  134. sglang/srt/layers/attention/vision.py +58 -0
  135. sglang/srt/layers/attention/wave_backend.py +4 -4
  136. sglang/srt/layers/attention/wave_ops/decode_attention.py +2 -4
  137. sglang/srt/layers/attention/wave_ops/extend_attention.py +1 -3
  138. sglang/srt/layers/communicator.py +8 -0
  139. sglang/srt/layers/dp_attention.py +41 -2
  140. sglang/srt/layers/elementwise.py +3 -1
  141. sglang/srt/layers/layernorm.py +34 -15
  142. sglang/srt/layers/linear.py +55 -7
  143. sglang/srt/layers/logits_processor.py +44 -12
  144. sglang/srt/layers/moe/__init__.py +2 -1
  145. sglang/srt/layers/moe/cutlass_w4a8_moe.py +3 -3
  146. sglang/srt/layers/moe/ep_moe/kernels.py +2 -2
  147. sglang/srt/layers/moe/ep_moe/layer.py +256 -63
  148. sglang/srt/layers/moe/flashinfer_cutedsl_moe.py +183 -0
  149. sglang/srt/layers/moe/fused_moe_native.py +5 -3
  150. sglang/srt/layers/moe/fused_moe_triton/configs/{triton_3_4_0/E=128,N=768,device_name=NVIDIA_B200,dtype=fp8_w8a8,block_shape=[128, 128].json → triton_3_3_1/E=128,N=768,device_name=NVIDIA_H20,dtype=fp8_w8a8,block_shape=[128, 128].json } +35 -35
  151. sglang/srt/layers/moe/fused_moe_triton/configs/triton_3_4_0/E=128,N=352,device_name=NVIDIA_RTX_5880_Ada_Generation,dtype=fp8_w8a8.json +146 -0
  152. sglang/srt/layers/moe/fused_moe_triton/configs/triton_3_4_0/E=256,N=256,device_name=NVIDIA_H800,dtype=fp8_w8a8,block_shape=[128, 128].json +146 -0
  153. sglang/srt/layers/moe/fused_moe_triton/configs/triton_3_4_0/E=256,N=512,device_name=NVIDIA_H20.json +146 -0
  154. sglang/srt/layers/moe/fused_moe_triton/configs/triton_3_4_0/E=512,N=128,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  155. sglang/srt/layers/moe/fused_moe_triton/configs/triton_3_4_0/E=512,N=128,device_name=NVIDIA_H20-3e.json +146 -0
  156. sglang/srt/layers/moe/fused_moe_triton/configs/triton_3_4_0/E=512,N=128,device_name=NVIDIA_H200.json +146 -0
  157. sglang/srt/layers/moe/fused_moe_triton/configs/triton_3_4_0/E=512,N=128,device_name=NVIDIA_H800,dtype=fp8_w8a8,block_shape=[128, 128].json +146 -0
  158. sglang/srt/layers/moe/fused_moe_triton/configs/triton_3_4_0/E=512,N=256,device_name=NVIDIA_B200.json +146 -0
  159. sglang/srt/layers/moe/fused_moe_triton/configs/triton_3_4_0/E=512,N=256,device_name=NVIDIA_H20-3e.json +146 -0
  160. sglang/srt/layers/moe/fused_moe_triton/configs/triton_3_4_0/E=512,N=256,device_name=NVIDIA_H200.json +146 -0
  161. sglang/srt/layers/moe/fused_moe_triton/configs/triton_3_4_0/E=512,N=64,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  162. sglang/srt/layers/moe/fused_moe_triton/configs/triton_3_4_0/E=512,N=64,device_name=NVIDIA_H200.json +146 -0
  163. sglang/srt/layers/moe/fused_moe_triton/fused_moe.py +5 -2
  164. sglang/srt/layers/moe/fused_moe_triton/fused_moe_triton_config.py +7 -3
  165. sglang/srt/layers/moe/fused_moe_triton/fused_moe_triton_kernels.py +23 -20
  166. sglang/srt/layers/moe/fused_moe_triton/layer.py +71 -70
  167. sglang/srt/layers/moe/moe_runner/__init__.py +2 -1
  168. sglang/srt/layers/moe/moe_runner/base.py +274 -1
  169. sglang/srt/layers/moe/moe_runner/runner.py +80 -0
  170. sglang/srt/layers/moe/moe_runner/triton.py +448 -0
  171. sglang/srt/layers/moe/token_dispatcher/__init__.py +16 -4
  172. sglang/srt/layers/moe/token_dispatcher/{base_dispatcher.py → base.py} +67 -17
  173. sglang/srt/layers/moe/token_dispatcher/deepep.py +118 -56
  174. sglang/srt/layers/moe/token_dispatcher/standard.py +44 -2
  175. sglang/srt/layers/moe/topk.py +30 -9
  176. sglang/srt/layers/moe/utils.py +22 -6
  177. sglang/srt/layers/parameter.py +23 -6
  178. sglang/srt/layers/quantization/awq.py +19 -7
  179. sglang/srt/layers/quantization/base_config.py +11 -6
  180. sglang/srt/layers/quantization/blockwise_int8.py +38 -27
  181. sglang/srt/layers/quantization/compressed_tensors/compressed_tensors.py +1 -0
  182. sglang/srt/layers/quantization/compressed_tensors/compressed_tensors_moe.py +50 -30
  183. sglang/srt/layers/quantization/compressed_tensors/schemes/__init__.py +2 -0
  184. sglang/srt/layers/quantization/compressed_tensors/schemes/compressed_tensors_w8a8_fp8.py +13 -1
  185. sglang/srt/layers/quantization/compressed_tensors/schemes/compressed_tensors_w8a8_int8.py +173 -0
  186. sglang/srt/layers/quantization/deep_gemm_wrapper/configurer.py +2 -10
  187. sglang/srt/layers/quantization/deep_gemm_wrapper/entrypoint.py +27 -0
  188. sglang/srt/layers/quantization/fp8.py +78 -49
  189. sglang/srt/layers/quantization/fp8_utils.py +51 -32
  190. sglang/srt/layers/quantization/gptq.py +25 -17
  191. sglang/srt/layers/quantization/modelopt_quant.py +190 -55
  192. sglang/srt/layers/quantization/moe_wna16.py +21 -18
  193. sglang/srt/layers/quantization/mxfp4.py +74 -42
  194. sglang/srt/layers/quantization/quark/quark_moe.py +48 -30
  195. sglang/srt/layers/quantization/unquant.py +135 -47
  196. sglang/srt/layers/quantization/w4afp8.py +26 -17
  197. sglang/srt/layers/quantization/w8a8_fp8.py +35 -20
  198. sglang/srt/layers/quantization/w8a8_int8.py +91 -41
  199. sglang/srt/layers/rotary_embedding.py +78 -31
  200. sglang/srt/layers/sampler.py +213 -21
  201. sglang/srt/layers/utils.py +23 -0
  202. sglang/srt/lora/backend/base_backend.py +50 -8
  203. sglang/srt/lora/backend/chunked_backend.py +348 -0
  204. sglang/srt/lora/backend/triton_backend.py +99 -5
  205. sglang/srt/lora/layers.py +32 -0
  206. sglang/srt/lora/lora.py +8 -3
  207. sglang/srt/lora/lora_manager.py +52 -118
  208. sglang/srt/lora/mem_pool.py +25 -11
  209. sglang/srt/lora/triton_ops/__init__.py +4 -0
  210. sglang/srt/lora/triton_ops/chunked_sgmv_expand.py +214 -0
  211. sglang/srt/lora/triton_ops/chunked_sgmv_shrink.py +174 -0
  212. sglang/srt/lora/utils.py +22 -11
  213. sglang/srt/managers/async_dynamic_batch_tokenizer.py +170 -0
  214. sglang/srt/managers/cache_controller.py +199 -301
  215. sglang/srt/managers/data_parallel_controller.py +115 -80
  216. sglang/srt/managers/detokenizer_manager.py +19 -15
  217. sglang/srt/managers/disagg_service.py +46 -0
  218. sglang/srt/managers/io_struct.py +340 -109
  219. sglang/srt/managers/mm_utils.py +44 -6
  220. sglang/srt/managers/multi_tokenizer_mixin.py +357 -407
  221. sglang/srt/managers/multimodal_processor.py +1 -2
  222. sglang/srt/managers/overlap_utils.py +53 -0
  223. sglang/srt/managers/schedule_batch.py +240 -138
  224. sglang/srt/managers/schedule_policy.py +144 -17
  225. sglang/srt/managers/scheduler.py +502 -209
  226. sglang/srt/managers/scheduler_input_blocker.py +1 -1
  227. sglang/srt/managers/scheduler_metrics_mixin.py +99 -126
  228. sglang/srt/managers/scheduler_output_processor_mixin.py +75 -22
  229. sglang/srt/managers/scheduler_profiler_mixin.py +6 -6
  230. sglang/srt/managers/scheduler_update_weights_mixin.py +7 -0
  231. sglang/srt/managers/tokenizer_communicator_mixin.py +675 -0
  232. sglang/srt/managers/tokenizer_manager.py +320 -632
  233. sglang/srt/managers/tp_worker.py +81 -22
  234. sglang/srt/managers/tp_worker_overlap_thread.py +71 -56
  235. sglang/srt/managers/utils.py +1 -45
  236. sglang/srt/mem_cache/allocator.py +14 -20
  237. sglang/srt/mem_cache/allocator_ascend.py +41 -27
  238. sglang/srt/mem_cache/base_prefix_cache.py +1 -1
  239. sglang/srt/mem_cache/chunk_cache.py +8 -1
  240. sglang/srt/mem_cache/evict_policy.py +23 -0
  241. sglang/srt/mem_cache/hicache_storage.py +43 -24
  242. sglang/srt/mem_cache/hiradix_cache.py +222 -75
  243. sglang/srt/mem_cache/memory_pool.py +535 -58
  244. sglang/srt/mem_cache/memory_pool_host.py +239 -228
  245. sglang/srt/mem_cache/radix_cache.py +222 -73
  246. sglang/srt/mem_cache/radix_cache_cpp.py +11 -8
  247. sglang/srt/mem_cache/storage/__init__.py +10 -0
  248. sglang/srt/mem_cache/storage/aibrix_kvcache/aibrix_kvcache_storage.py +151 -0
  249. sglang/srt/mem_cache/storage/aibrix_kvcache/unit_test.py +109 -0
  250. sglang/srt/mem_cache/storage/backend_factory.py +223 -0
  251. sglang/srt/mem_cache/storage/eic/eic_storage.py +778 -0
  252. sglang/srt/mem_cache/storage/eic/test_unit.py +115 -0
  253. sglang/srt/mem_cache/storage/hf3fs/hf3fs_client.py +164 -0
  254. sglang/srt/mem_cache/storage/hf3fs/{client_hf3fs.py → hf3fs_usrbio_client.py} +5 -1
  255. sglang/srt/mem_cache/storage/hf3fs/storage_hf3fs.py +259 -62
  256. sglang/srt/mem_cache/storage/lmcache/lmc_radix_cache.py +284 -0
  257. sglang/srt/mem_cache/storage/lmcache/unit_test.py +121 -0
  258. sglang/srt/mem_cache/storage/mooncake_store/mooncake_store.py +166 -17
  259. sglang/srt/mem_cache/swa_radix_cache.py +25 -36
  260. sglang/srt/metrics/collector.py +511 -132
  261. sglang/srt/metrics/func_timer.py +2 -7
  262. sglang/srt/metrics/startup_func_log_and_timer.py +150 -0
  263. sglang/srt/metrics/utils.py +8 -1
  264. sglang/srt/model_executor/cpu_graph_runner.py +640 -0
  265. sglang/srt/model_executor/cuda_graph_runner.py +52 -37
  266. sglang/srt/model_executor/forward_batch_info.py +82 -40
  267. sglang/srt/model_executor/model_runner.py +432 -157
  268. sglang/srt/model_executor/npu_graph_runner.py +12 -5
  269. sglang/srt/model_loader/__init__.py +9 -3
  270. sglang/srt/model_loader/loader.py +133 -5
  271. sglang/srt/model_loader/remote_instance_weight_loader_utils.py +69 -0
  272. sglang/srt/model_loader/weight_utils.py +158 -3
  273. sglang/srt/models/apertus.py +686 -0
  274. sglang/srt/models/bailing_moe.py +820 -217
  275. sglang/srt/models/bailing_moe_nextn.py +168 -0
  276. sglang/srt/models/deepseek_nextn.py +6 -1
  277. sglang/srt/models/deepseek_v2.py +607 -130
  278. sglang/srt/models/dots_ocr.py +173 -0
  279. sglang/srt/models/dots_vlm.py +174 -0
  280. sglang/srt/models/dots_vlm_vit.py +337 -0
  281. sglang/srt/models/ernie4.py +1 -1
  282. sglang/srt/models/falcon_h1.py +576 -0
  283. sglang/srt/models/gemma3_causal.py +0 -2
  284. sglang/srt/models/gemma3_mm.py +1 -1
  285. sglang/srt/models/gemma3n_mm.py +2 -2
  286. sglang/srt/models/glm4_moe.py +4 -4
  287. sglang/srt/models/glm4_moe_nextn.py +2 -2
  288. sglang/srt/models/glm4v.py +5 -3
  289. sglang/srt/models/glm4v_moe.py +4 -1
  290. sglang/srt/models/gpt_oss.py +8 -31
  291. sglang/srt/models/kimi_vl_moonvit.py +2 -2
  292. sglang/srt/models/llama.py +4 -0
  293. sglang/srt/models/llama4.py +9 -0
  294. sglang/srt/models/llama_eagle3.py +13 -0
  295. sglang/srt/models/longcat_flash.py +3 -3
  296. sglang/srt/models/longcat_flash_nextn.py +1 -1
  297. sglang/srt/models/mllama4.py +40 -4
  298. sglang/srt/models/opt.py +637 -0
  299. sglang/srt/models/qwen2_5_vl.py +29 -5
  300. sglang/srt/models/qwen2_audio.py +1 -1
  301. sglang/srt/models/qwen2_moe.py +120 -13
  302. sglang/srt/models/qwen2_vl.py +1 -1
  303. sglang/srt/models/qwen3.py +18 -3
  304. sglang/srt/models/qwen3_moe.py +32 -4
  305. sglang/srt/models/qwen3_next.py +1069 -0
  306. sglang/srt/models/qwen3_next_mtp.py +112 -0
  307. sglang/srt/models/qwen3_vl.py +787 -0
  308. sglang/srt/models/qwen3_vl_moe.py +471 -0
  309. sglang/srt/models/registry.py +15 -3
  310. sglang/srt/models/sarashina2_vision.py +269 -0
  311. sglang/srt/models/solar.py +505 -0
  312. sglang/srt/models/starcoder2.py +357 -0
  313. sglang/srt/models/step3_vl.py +1 -1
  314. sglang/srt/models/torch_native_llama.py +9 -2
  315. sglang/srt/models/utils.py +51 -0
  316. sglang/srt/multimodal/processors/base_processor.py +15 -7
  317. sglang/srt/multimodal/processors/dots_vlm.py +98 -0
  318. sglang/srt/multimodal/processors/glm4v.py +9 -9
  319. sglang/srt/multimodal/processors/internvl.py +153 -129
  320. sglang/srt/multimodal/processors/qwen_vl.py +23 -6
  321. sglang/srt/multimodal/processors/sarashina2_vision.py +81 -0
  322. sglang/srt/offloader.py +27 -3
  323. sglang/srt/parser/jinja_template_utils.py +6 -0
  324. sglang/srt/sampling/sampling_batch_info.py +38 -17
  325. sglang/srt/sampling/sampling_params.py +7 -0
  326. sglang/srt/server_args.py +966 -267
  327. sglang/srt/server_args_config_parser.py +146 -0
  328. sglang/srt/single_batch_overlap.py +151 -0
  329. sglang/srt/speculative/cpp_ngram/ngram.cpp +374 -0
  330. sglang/srt/speculative/cpp_ngram/ngram.h +110 -0
  331. sglang/srt/speculative/cpp_ngram/ngram_cache.py +138 -0
  332. sglang/srt/speculative/cpp_ngram/ngram_cache_binding.cpp +43 -0
  333. sglang/srt/speculative/cpp_ngram/param.h +125 -0
  334. sglang/srt/speculative/cpp_ngram/queue.h +71 -0
  335. sglang/srt/speculative/eagle_draft_cuda_graph_runner.py +7 -1
  336. sglang/srt/speculative/eagle_draft_extend_cuda_graph_runner.py +13 -2
  337. sglang/srt/speculative/{eagle_utils.py → eagle_info.py} +207 -757
  338. sglang/srt/speculative/eagle_worker.py +99 -28
  339. sglang/srt/speculative/ngram_utils.py +428 -0
  340. sglang/srt/speculative/ngram_worker.py +245 -0
  341. sglang/srt/speculative/spec_info.py +52 -0
  342. sglang/srt/speculative/spec_utils.py +606 -0
  343. sglang/srt/speculative/standalone_worker.py +109 -0
  344. sglang/srt/torch_memory_saver_adapter.py +5 -7
  345. sglang/srt/tracing/trace.py +578 -0
  346. sglang/srt/two_batch_overlap.py +8 -5
  347. sglang/srt/utils/__init__.py +2 -0
  348. sglang/srt/{utils.py → utils/common.py} +433 -77
  349. sglang/srt/{hf_transformers_utils.py → utils/hf_transformers_utils.py} +53 -5
  350. sglang/srt/{patch_torch.py → utils/patch_torch.py} +8 -0
  351. sglang/srt/utils/rpd_utils.py +452 -0
  352. sglang/srt/utils/slow_rank_detector.py +71 -0
  353. sglang/srt/warmup.py +8 -4
  354. sglang/srt/weight_sync/utils.py +2 -2
  355. sglang/test/attention/test_trtllm_mla_backend.py +169 -5
  356. sglang/test/get_logits_ut.py +57 -0
  357. sglang/test/run_eval.py +79 -11
  358. sglang/test/runners.py +5 -1
  359. sglang/test/simple_eval_common.py +5 -2
  360. sglang/test/simple_eval_mmmu_vlm.py +441 -0
  361. sglang/test/test_block_fp8.py +2 -2
  362. sglang/test/test_cutlass_moe.py +24 -6
  363. sglang/test/test_deterministic.py +297 -0
  364. sglang/test/test_disaggregation_utils.py +77 -0
  365. sglang/test/test_fp4_moe.py +370 -1
  366. sglang/test/test_programs.py +1 -1
  367. sglang/test/test_utils.py +383 -5
  368. sglang/utils.py +21 -1
  369. sglang/version.py +1 -1
  370. {sglang-0.5.2rc2.dist-info → sglang-0.5.3.dist-info}/METADATA +69 -124
  371. {sglang-0.5.2rc2.dist-info → sglang-0.5.3.dist-info}/RECORD +375 -245
  372. sglang/srt/disaggregation/launch_lb.py +0 -118
  373. sglang/srt/mem_cache/lora_radix_cache.py +0 -421
  374. /sglang/srt/{poll_based_barrier.py → utils/poll_based_barrier.py} +0 -0
  375. {sglang-0.5.2rc2.dist-info → sglang-0.5.3.dist-info}/WHEEL +0 -0
  376. {sglang-0.5.2rc2.dist-info → sglang-0.5.3.dist-info}/licenses/LICENSE +0 -0
  377. {sglang-0.5.2rc2.dist-info → sglang-0.5.3.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,785 @@
1
+ from typing import Optional, Tuple
2
+
3
+ import tilelang
4
+ import tilelang.language as T
5
+ import torch
6
+
7
+ from sglang.srt.utils import is_hip
8
+
9
+ tilelang.set_log_level("WARNING")
10
+
11
+ pass_configs = {
12
+ tilelang.PassConfigKey.TL_DISABLE_WARP_SPECIALIZED: True,
13
+ tilelang.PassConfigKey.TL_DISABLE_TMA_LOWER: True,
14
+ tilelang.PassConfigKey.TL_DISABLE_FAST_MATH: True,
15
+ }
16
+
17
+ BF16 = "bfloat16"
18
+ FP8 = "float8_e4m3"
19
+ FP32 = "float32"
20
+
21
+ _is_hip = is_hip()
22
+
23
+
24
+ def fast_log2_ceil(x):
25
+ bits_x = T.reinterpret("uint32", x)
26
+ exp_x = (bits_x >> 23) & 0xFF
27
+ man_bits = bits_x & ((1 << 23) - 1)
28
+ return T.Cast("int32", exp_x - 127 + T.if_then_else(man_bits != 0, 1, 0))
29
+
30
+
31
+ def fast_pow2(x):
32
+ bits_x = (x + 127) << 23
33
+ return T.reinterpret("float32", bits_x)
34
+
35
+
36
+ def fast_round_scale(amax, fp8_max_inv):
37
+ return fast_pow2(fast_log2_ceil(amax * fp8_max_inv))
38
+
39
+
40
+ @tilelang.jit(pass_configs=pass_configs)
41
+ def act_quant_kernel(
42
+ N, in_dtype=BF16, out_dtype=FP8, scale_dtype=FP32, round_scale=False
43
+ ):
44
+ M = T.symbolic("M")
45
+ fp8_min = -448.0
46
+ fp8_max = 448.0
47
+ fp8_max_inv = 1 / fp8_max
48
+ num_stages = 0 if round_scale else 2
49
+ blk_m = 32
50
+ group_size = 128
51
+
52
+ @T.prim_func
53
+ def act_quant_kernel_(
54
+ X: T.Tensor[(M, N), in_dtype],
55
+ Y: T.Tensor[(M, N), out_dtype],
56
+ S: T.Tensor[(M, T.ceildiv(N, group_size)), scale_dtype],
57
+ ):
58
+ with T.Kernel(T.ceildiv(M, blk_m), T.ceildiv(N, group_size), threads=128) as (
59
+ pid_m,
60
+ pid_n,
61
+ ):
62
+ x_shared = T.alloc_shared((blk_m, group_size), in_dtype)
63
+ x_local = T.alloc_fragment((blk_m, group_size), in_dtype)
64
+ amax_local = T.alloc_fragment((blk_m,), scale_dtype)
65
+ s_local = T.alloc_fragment((blk_m,), scale_dtype)
66
+ y_local = T.alloc_fragment((blk_m, group_size), out_dtype)
67
+ y_shared = T.alloc_shared((blk_m, group_size), out_dtype)
68
+
69
+ for _ in T.Pipelined(1, num_stages=num_stages):
70
+ T.copy(X[pid_m * blk_m, pid_n * group_size], x_shared)
71
+ T.copy(x_shared, x_local)
72
+ T.reduce_absmax(x_local, amax_local, dim=1)
73
+ for i in T.Parallel(blk_m):
74
+ amax_local[i] = T.max(amax_local[i], 1e-4)
75
+ if round_scale:
76
+ s_local[i] = fast_round_scale(amax_local[i], fp8_max_inv)
77
+ else:
78
+ s_local[i] = amax_local[i] * fp8_max_inv
79
+ for i, j in T.Parallel(blk_m, group_size):
80
+ y_local[i, j] = T.clamp(
81
+ x_local[i, j] / s_local[i], fp8_min, fp8_max
82
+ )
83
+ for i in T.Parallel(blk_m):
84
+ S[pid_m * blk_m + i, pid_n] = s_local[i]
85
+ T.copy(y_local, y_shared)
86
+ T.copy(y_shared, Y[pid_m * blk_m, pid_n * group_size])
87
+
88
+ return act_quant_kernel_
89
+
90
+
91
+ def act_quant(
92
+ x: torch.Tensor, block_size: int = 128, scale_fmt: Optional[str] = None
93
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
94
+ """
95
+ Quantizes the input tensor `x` using block-wise quantization.
96
+
97
+ Args:
98
+ x (torch.Tensor): The input tensor to be quantized. Must be contiguous and its last dimension size must be divisible by `block_size`.
99
+ block_size (int, optional): The size of the blocks to be used for quantization. Default is 128.
100
+ scale_fmt (Optional[str], optional): The format of the scale. Default is None.
101
+ Returns:
102
+ Tuple[torch.Tensor, torch.Tensor]: A tuple containing:
103
+ - The quantized tensor with dtype `torch.float8_e4m3fn`.
104
+ - A tensor of scaling factors with dtype `torch.float32`.
105
+ """
106
+ assert x.is_contiguous(), "Input tensor must be contiguous"
107
+ assert (
108
+ x.size(-1) % block_size == 0
109
+ ), f"Last dimension size must be divisible by block_size (block_size={block_size})"
110
+ N = x.size(-1)
111
+ y = torch.empty_like(x, dtype=torch.float8_e4m3fn)
112
+ s = x.new_empty(*x.size()[:-1], N // block_size, dtype=torch.float32)
113
+ kernel = act_quant_kernel(N, round_scale=scale_fmt is not None)
114
+ kernel(x.view(-1, N), y.view(-1, N), s.view(-1, N // block_size))
115
+ return y, s
116
+
117
+
118
+ @tilelang.jit(out_idx=[4], pass_configs=pass_configs)
119
+ def fp8_index_kernel(h: int, d: int, clear_accum=True):
120
+ b = T.symbolic("b")
121
+ m = T.symbolic("m")
122
+ n = T.symbolic("n")
123
+
124
+ blk_n1 = 512
125
+ blk_n2 = 128
126
+
127
+ @T.prim_func
128
+ def fp8_index_kernel_(
129
+ q: T.Tensor[(b, m, h, d), FP8],
130
+ q_s: T.Tensor[(b, m, h), FP32],
131
+ k: T.Tensor[(b, n, d), FP8],
132
+ k_s: T.Tensor[(b, n), FP32],
133
+ o: T.Tensor[(b, m, n), FP32],
134
+ ) -> None:
135
+ with T.Kernel(b, m, T.ceildiv(n, blk_n1)) as (i_b, i_m, i1_n):
136
+ q_smem = T.alloc_shared((h, d), FP8)
137
+ T.copy(q[i_b, i_m, 0, 0], q_smem)
138
+
139
+ q_s_frag = T.alloc_fragment(h, FP32)
140
+ T.copy(q_s[i_b, i_m, 0], q_s_frag)
141
+
142
+ for i2_n in T.Pipelined(blk_n1 // blk_n2, num_stages=2):
143
+ k_smem = T.alloc_shared((blk_n2, d), FP8)
144
+ T.copy(k[i_b, i1_n * blk_n1 + i2_n * blk_n2, 0], k_smem)
145
+
146
+ k_s_frag = T.alloc_fragment(blk_n2, FP32)
147
+ T.copy(k_s[i_b, i1_n * blk_n1 + i2_n * blk_n2], k_s_frag)
148
+
149
+ logits = T.alloc_fragment((blk_n2, h), FP32)
150
+ T.gemm(
151
+ k_smem,
152
+ q_smem,
153
+ logits,
154
+ transpose_A=False,
155
+ transpose_B=True,
156
+ clear_accum=clear_accum,
157
+ )
158
+
159
+ for i_h, i3_n in T.Parallel(h, blk_n2):
160
+ logits[i3_n, i_h] = T.max(logits[i3_n, i_h], 0) * q_s_frag[i_h]
161
+
162
+ logits_sum = T.alloc_fragment(blk_n2, FP32)
163
+ T.reduce_sum(logits, logits_sum, dim=1)
164
+
165
+ for i3_n in T.Parallel(blk_n2):
166
+ logits_sum[i3_n] *= k_s_frag[i3_n]
167
+
168
+ T.copy(logits_sum, o[i_b, i_m, i1_n * blk_n1 + i2_n * blk_n2])
169
+
170
+ return fp8_index_kernel_
171
+
172
+
173
+ def fp8_index(
174
+ q: torch.Tensor,
175
+ q_s: torch.Tensor,
176
+ k: torch.Tensor,
177
+ k_s: torch.Tensor,
178
+ ) -> torch.Tensor:
179
+ """
180
+ Perform index score using FP8 precision.
181
+
182
+ Args:
183
+ q (torch.Tensor): The Q tensor, must be contiguous.
184
+ q_s (torch.Tensor): The scaling factor for Q (float), must be contiguous.
185
+ k (torch.Tensor): The K tensor, must be contiguous.
186
+ k_s (torch.Tensor): The scaling factor for K (e8m0 here), must be contiguous.
187
+
188
+ fp8 q @ fp8 k -> fp32 logits
189
+ relu(fp32 logits) * q_s (weights) -> fp32 logits
190
+ fp32 logits -> fp32 logits_sum
191
+ fp32 logits_sum * k_s (e8m0) -> fp32 index_score
192
+ """
193
+ if _is_hip:
194
+ return fp8_index_kernel(q.shape[2], q.shape[3], False)(q, q_s, k, k_s)
195
+ else:
196
+ return fp8_index_kernel(q.shape[2], q.shape[3])(q, q_s, k, k_s)
197
+
198
+
199
+ @tilelang.jit(
200
+ out_idx=[-1],
201
+ pass_configs={
202
+ tilelang.PassConfigKey.TL_DISABLE_TMA_LOWER: True,
203
+ tilelang.PassConfigKey.TL_DISABLE_WARP_SPECIALIZED: True,
204
+ },
205
+ )
206
+ def sparse_attention_fwd_kernel_v1(
207
+ num_heads,
208
+ dim,
209
+ tail_dim,
210
+ topk,
211
+ *,
212
+ kv_group=1,
213
+ sm_scale=None,
214
+ is_causal=True,
215
+ block_I=64,
216
+ num_stages=2,
217
+ threads=256,
218
+ ):
219
+ assert dim == tilelang.math.next_power_of_2(
220
+ dim
221
+ ), f"haven't check padding correctness yet, dim={dim}"
222
+ assert tail_dim == tilelang.math.next_power_of_2(
223
+ tail_dim
224
+ ), f"haven't check padding correctness yet, dim={tail_dim}"
225
+ assert is_causal == True, "non-casual is not supported"
226
+ assert (
227
+ topk % block_I == 0
228
+ ), "otherwise will load some index=0 thus causing wrong kv to be loaded"
229
+ if sm_scale is None:
230
+ sm_scale = (1.0 / (dim + tail_dim)) ** 0.5 * 1.44269504 # log2(e)
231
+ else:
232
+ sm_scale = sm_scale * 1.44269504 # log2(e)
233
+
234
+ batch = T.symbolic("batch")
235
+ seq_len = T.symbolic("seq_len")
236
+ seq_len_kv = T.symbolic("seq_len_kv")
237
+
238
+ head_kv = num_heads // kv_group
239
+ q_shape = [batch, seq_len, num_heads, dim + tail_dim]
240
+ kv_shape = [batch, seq_len_kv, kv_group, dim + tail_dim]
241
+ o_shape = [batch, seq_len, num_heads, dim]
242
+ indices_shape = [batch, seq_len, kv_group, topk]
243
+ indices_dtype = "int32"
244
+ dtype = "bfloat16"
245
+ accum_dtype = "float"
246
+
247
+ H = head_kv
248
+ padded_H = max(tilelang.math.next_power_of_2(head_kv), 16)
249
+ if padded_H != H:
250
+ assert kv_group == 1
251
+ BI = block_I
252
+ NI = tilelang.cdiv(topk, block_I)
253
+ D = dim
254
+ D_tail = tail_dim
255
+
256
+ if head_kv > 64:
257
+ assert head_kv % 64 == 0, "head_kv should be a multiple of 64"
258
+ REPLICATE_H = head_kv // 64
259
+ else:
260
+ REPLICATE_H = 1
261
+
262
+ H_per_block = padded_H if REPLICATE_H == 1 else 64
263
+
264
+ @T.prim_func
265
+ def main(
266
+ Q: T.Tensor(q_shape, dtype), # type: ignore
267
+ KV: T.Tensor(kv_shape, dtype), # type: ignore
268
+ Indices: T.Tensor(indices_shape, indices_dtype), # type: ignore
269
+ Output: T.Tensor(o_shape, dtype), # type: ignore
270
+ ):
271
+ with T.Kernel(seq_len * REPLICATE_H, batch, kv_group, threads=threads) as (
272
+ bx,
273
+ by,
274
+ bz,
275
+ ):
276
+ Q_shared = T.alloc_shared([H_per_block, D], dtype)
277
+ Q_tail_shared = T.alloc_shared([H_per_block, D_tail], dtype)
278
+ KV_shared = T.alloc_shared([BI, D], dtype)
279
+ K_tail_shared = T.alloc_shared([BI, D_tail], dtype)
280
+ O_shared = T.alloc_shared([H_per_block, D], dtype)
281
+ mask = T.alloc_fragment([BI], "bool")
282
+
283
+ acc_o = T.alloc_fragment([H_per_block, D], accum_dtype)
284
+ acc_s = T.alloc_fragment([H_per_block, BI], accum_dtype)
285
+ S_shared = T.alloc_shared([H_per_block, BI], dtype)
286
+ sumexp = T.alloc_fragment([H_per_block], accum_dtype)
287
+ sumexp_i = T.alloc_fragment([H_per_block], accum_dtype)
288
+ alpha = T.alloc_fragment([H_per_block], accum_dtype)
289
+ m_i = T.alloc_fragment([H_per_block], accum_dtype)
290
+ m_i_prev = T.alloc_fragment([H_per_block], accum_dtype)
291
+
292
+ T.fill(acc_o, 0)
293
+ T.fill(sumexp, 0)
294
+ T.fill(m_i, -(2**30)) # avoid -inf - inf to cause nan
295
+
296
+ b_i, g_i = by, bz
297
+ s_i = bx if REPLICATE_H == 1 else (bx // REPLICATE_H)
298
+ q_i = s_i
299
+ max_kv_i = q_i
300
+
301
+ H0 = g_i * padded_H + (0 if REPLICATE_H == 1 else (bx % REPLICATE_H) * 64)
302
+ H1 = H0 + H_per_block
303
+
304
+ T.copy(Q[b_i, s_i, H0:H1, :D], Q_shared)
305
+ T.copy(Q[b_i, s_i, H0:H1, D:], Q_tail_shared)
306
+
307
+ for i_i in T.Pipelined(NI, num_stages=num_stages):
308
+
309
+ for bi_i in T.Parallel(BI):
310
+ mask[bi_i] = Indices[b_i, s_i, g_i, i_i * BI + bi_i] >= 0
311
+
312
+ for bi_i, d_i in T.Parallel(BI, D):
313
+ KV_shared[bi_i, d_i] = KV[
314
+ b_i, Indices[b_i, s_i, g_i, i_i * BI + bi_i], g_i, d_i
315
+ ]
316
+ for bi_i, d_i in T.Parallel(BI, D_tail):
317
+ K_tail_shared[bi_i, d_i] = KV[
318
+ b_i, Indices[b_i, s_i, g_i, i_i * BI + bi_i], g_i, D + d_i
319
+ ]
320
+
321
+ for h_i, bi_i in T.Parallel(H_per_block, BI):
322
+ acc_s[h_i, bi_i] = T.if_then_else(
323
+ mask[bi_i], 0, -T.infinity(acc_s.dtype)
324
+ )
325
+ T.gemm(
326
+ Q_shared,
327
+ KV_shared,
328
+ acc_s,
329
+ transpose_B=True,
330
+ policy=T.GemmWarpPolicy.FullCol,
331
+ )
332
+ T.gemm(
333
+ Q_tail_shared,
334
+ K_tail_shared,
335
+ acc_s,
336
+ transpose_B=True,
337
+ policy=T.GemmWarpPolicy.FullCol,
338
+ )
339
+ T.copy(m_i, m_i_prev)
340
+ T.reduce_max(acc_s, m_i, dim=1, clear=False)
341
+ for h_i in T.Parallel(H_per_block):
342
+ alpha[h_i] = T.exp2((m_i_prev[h_i] - m_i[h_i]) * sm_scale)
343
+ for h_i, bi_i in T.Parallel(H_per_block, BI):
344
+ acc_s[h_i, bi_i] = T.exp2(
345
+ acc_s[h_i, bi_i] * sm_scale - m_i[h_i] * sm_scale
346
+ )
347
+ T.reduce_sum(acc_s, sumexp_i, dim=1) # is this a accumulate operator?
348
+ for h_i in T.Parallel(H_per_block):
349
+ sumexp[h_i] = sumexp[h_i] * alpha[h_i] + sumexp_i[h_i]
350
+ for h_i, d_i in T.Parallel(H_per_block, D):
351
+ acc_o[h_i, d_i] = acc_o[h_i, d_i] * alpha[h_i]
352
+
353
+ T.copy(acc_s, S_shared)
354
+ T.gemm(S_shared, KV_shared, acc_o, policy=T.GemmWarpPolicy.FullCol)
355
+
356
+ # Rescale
357
+ for h_i, d_i in T.Parallel(H_per_block, D):
358
+ acc_o[h_i, d_i] /= sumexp[h_i]
359
+ for h_i in T.Parallel(H_per_block):
360
+ sumexp[h_i] = T.log2(sumexp[h_i]) + m_i[h_i] * sm_scale
361
+
362
+ T.copy(acc_o, O_shared)
363
+ T.copy(acc_o, Output[b_i, s_i, H0:H1, :])
364
+
365
+ return main
366
+
367
+
368
+ @tilelang.jit(
369
+ out_idx=[-1],
370
+ compile_flags=[
371
+ "-O3",
372
+ "-Wno-deprecated-declarations",
373
+ "-U__CUDA_NO_HALF_OPERATORS__",
374
+ "-U__CUDA_NO_HALF_CONVERSIONS__",
375
+ "-U__CUDA_NO_HALF2_OPERATORS__",
376
+ "-U__CUDA_NO_BFLOAT16_CONVERSIONS__",
377
+ "--expt-relaxed-constexpr",
378
+ "--expt-extended-lambda",
379
+ "--ptxas-options=-v,--register-usage-level=10",
380
+ "-DNDEBUG",
381
+ ],
382
+ ) # type: ignore
383
+ def sparse_attention_fwd_kernel_v2(
384
+ num_heads: int,
385
+ dim: int,
386
+ tail_dim: int,
387
+ topk: int,
388
+ *,
389
+ kv_group: int = 1,
390
+ sm_scale: Optional[float] = None,
391
+ block_I: int = 64,
392
+ ):
393
+ assert dim == tilelang.math.next_power_of_2(
394
+ dim
395
+ ), f"haven't check padding correctness yet, dim={dim}"
396
+ assert tail_dim == tilelang.math.next_power_of_2(
397
+ tail_dim
398
+ ), f"haven't check padding correctness yet, dim={tail_dim}"
399
+ assert (
400
+ topk % block_I == 0
401
+ ), "otherwise will load some index=0 thus causing wrong kv to be loaded"
402
+ if sm_scale is None:
403
+ sm_scale = (1.0 / (dim + tail_dim)) ** 0.5 * 1.44269504 # log2(e)
404
+ else:
405
+ sm_scale = sm_scale * 1.44269504 # log2(e)
406
+ threads = 384
407
+
408
+ batch = T.symbolic("batch")
409
+ qo_len = T.symbolic("seq_len")
410
+ num_pages = T.symbolic("num_pages")
411
+
412
+ q_shape = [batch, qo_len, num_heads, dim + tail_dim]
413
+ kv_shape = [batch, num_pages, kv_group, dim + tail_dim]
414
+ o_shape = [batch, qo_len, num_heads, dim]
415
+ indices_shape = [batch, qo_len, kv_group, topk]
416
+
417
+ indices_dtype = "int32"
418
+ dtype = "bfloat16"
419
+ accum_dtype = "float"
420
+
421
+ H = num_heads
422
+ padded_H = max(tilelang.math.next_power_of_2(num_heads), 16)
423
+ if padded_H != H:
424
+ assert kv_group == 1
425
+ BI = block_I
426
+ NI = tilelang.cdiv(topk, block_I)
427
+ assert NI % 2 == 0, "NI should be a multiple of 2"
428
+ D = dim
429
+ D_tail = tail_dim
430
+ if num_heads > 64:
431
+ assert num_heads % 64 == 0, "head_kv should be a multiple of 64"
432
+ REPLICATE_H = num_heads // 64
433
+ else:
434
+ REPLICATE_H = 1
435
+
436
+ H_per_block = padded_H if REPLICATE_H == 1 else 64
437
+
438
+ @T.prim_func
439
+ def main(
440
+ Q: T.Tensor(q_shape, dtype), # type: ignore
441
+ KV: T.Tensor(kv_shape, dtype), # type: ignore
442
+ Indices: T.Tensor(indices_shape, indices_dtype), # type: ignore
443
+ Output: T.Tensor(o_shape, dtype), # type: ignore
444
+ ):
445
+ """
446
+ Q: [b, qo_len, H, D + D_tail] (bfloat16)
447
+ KV: [b, num_pages, kv_group, D + D_tail] (bfloat16)
448
+ Indices: [b, qo_len, kv_group, topk] (int32)
449
+ """
450
+
451
+ with T.Kernel(qo_len * REPLICATE_H, batch, 1, threads=threads) as (bx, by, bz): # type: ignore
452
+ Q_shared_l = T.alloc_shared([H_per_block, D // 2], dtype)
453
+ Q_shared_r = T.alloc_shared([H_per_block, D // 2], dtype)
454
+ Q_tail_shared = T.alloc_shared([H_per_block, D_tail], dtype)
455
+ KV_shared_0_l = T.alloc_shared([BI, D // 2], dtype)
456
+ KV_shared_0_r = T.alloc_shared([BI, D // 2], dtype)
457
+ KV_shared_1_l = T.alloc_shared([BI, D // 2], dtype)
458
+ KV_shared_1_r = T.alloc_shared([BI, D // 2], dtype)
459
+ K_tail_shared_0 = T.alloc_shared([BI, D_tail], dtype)
460
+ K_tail_shared_1 = T.alloc_shared([BI, D_tail], dtype)
461
+ O_shared_l = Q_shared_l
462
+ O_shared_r = Q_shared_r
463
+ is_kv_valid_0 = T.alloc_shared([BI], "bool", scope="shared")
464
+ is_kv_valid_1 = T.alloc_shared([BI], "bool", scope="shared")
465
+
466
+ acc_o_l = T.alloc_fragment([H_per_block, D // 2], accum_dtype)
467
+ acc_o_r = T.alloc_fragment([H_per_block, D // 2], accum_dtype)
468
+ acc_s = T.alloc_fragment([H_per_block, BI], accum_dtype)
469
+ S_shared = T.alloc_shared([H_per_block, BI], dtype)
470
+ sumexp = T.alloc_fragment([H_per_block], accum_dtype)
471
+ sum_exp_shared = T.alloc_shared([H_per_block], accum_dtype)
472
+ sumexp_i = T.alloc_fragment([H_per_block], accum_dtype)
473
+ alpha_shared = T.alloc_shared([H_per_block], accum_dtype, scope="shared")
474
+ alpha_local = T.alloc_fragment([H_per_block], accum_dtype)
475
+ m_i = T.alloc_fragment([H_per_block], accum_dtype)
476
+ m_i_prev = T.alloc_fragment([H_per_block], accum_dtype)
477
+ indices_local = T.alloc_local([1], indices_dtype)
478
+ indices_tmp = T.alloc_local([1], indices_dtype)
479
+
480
+ bar_q = T.alloc_barrier(arrive_count=384)
481
+ bar_k_0_ready = T.alloc_barrier(arrive_count=128)
482
+ bar_k_1_ready = T.alloc_barrier(arrive_count=128)
483
+ bar_k_0_free = T.alloc_barrier(arrive_count=256)
484
+ bar_k_1_free = T.alloc_barrier(arrive_count=256)
485
+ bar_sScale_and_sS_ready = T.alloc_barrier(arrive_count=256)
486
+ bar_sScale_and_sS_free = T.alloc_barrier(arrive_count=256)
487
+
488
+ bar_0_128 = T.alloc_barrier(arrive_count=128)
489
+ bar_1_128 = T.alloc_barrier(arrive_count=128)
490
+ bar_2_128 = T.alloc_barrier(arrive_count=128)
491
+ bar_final = T.alloc_barrier(arrive_count=128)
492
+
493
+ b_i, g_i = by, bz
494
+ s_i = bx if REPLICATE_H == 1 else bx // REPLICATE_H
495
+
496
+ H0 = g_i * padded_H + (0 if REPLICATE_H == 1 else (bx % REPLICATE_H) * 64)
497
+ H1 = H0 + H_per_block
498
+
499
+ tx = T.get_thread_binding()
500
+
501
+ T.copy(Q[b_i, s_i, H0:H1, 0 : D // 2], Q_shared_l)
502
+ T.copy(Q[b_i, s_i, H0:H1, D // 2 : D], Q_shared_r)
503
+ T.copy(Q[b_i, s_i, H0:H1, D:], Q_tail_shared)
504
+ T.barrier_arrive(bar_q)
505
+
506
+ if tx < 128:
507
+ T.set_max_nreg(240, 1)
508
+ T.fill(sumexp, 0)
509
+ T.fill(m_i, -(2**30)) # avoid -inf - inf to cause nan
510
+ T.fill(acc_o_l, 0)
511
+ T.barrier_wait(bar_q, 0)
512
+
513
+ for i_i in T.serial(T.ceildiv(NI, 2)):
514
+ # Buffer 0
515
+ # with sync_at(bar_0_128, 0):
516
+ T.barrier_wait(bar_k_0_ready[0], (i_i & 1))
517
+ T.barrier_arrive(bar_0_128)
518
+ T.barrier_wait(bar_0_128, 0)
519
+
520
+ for h_i, bi_i in T.Parallel(H_per_block, BI):
521
+ acc_s[h_i, bi_i] = T.if_then_else(
522
+ is_kv_valid_0[bi_i], 0, -T.infinity(acc_s.dtype)
523
+ )
524
+ T.gemm(
525
+ Q_shared_l, KV_shared_0_l, acc_s, transpose_B=True, wg_wait=-1
526
+ )
527
+ T.gemm(
528
+ Q_shared_r, KV_shared_0_r, acc_s, transpose_B=True, wg_wait=-1
529
+ )
530
+ T.gemm(
531
+ Q_tail_shared,
532
+ K_tail_shared_0,
533
+ acc_s,
534
+ transpose_B=True,
535
+ wg_wait=-1,
536
+ )
537
+
538
+ T.wait_wgmma(0)
539
+
540
+ if i_i != 0:
541
+ T.barrier_arrive(bar_sScale_and_sS_free)
542
+ T.barrier_wait(bar_sScale_and_sS_free, ((i_i * 2) & 1) ^ 1)
543
+
544
+ T.copy(m_i, m_i_prev)
545
+ T.reduce_max(acc_s, m_i, dim=1, clear=False)
546
+ for h_i in T.Parallel(H_per_block):
547
+ alpha_local[h_i] = T.exp2((m_i_prev[h_i] - m_i[h_i]) * sm_scale)
548
+ for h_i, bi_i in T.Parallel(H_per_block, BI):
549
+ acc_s[h_i, bi_i] = T.exp2(
550
+ acc_s[h_i, bi_i] * sm_scale - m_i[h_i] * sm_scale
551
+ )
552
+ T.reduce_sum(
553
+ acc_s, sumexp_i, dim=1
554
+ ) # is this a accumulate operator?
555
+ for h_i in T.Parallel(H_per_block):
556
+ sumexp[h_i] = sumexp[h_i] * alpha_local[h_i] + sumexp_i[h_i]
557
+ for h_i, d_i in T.Parallel(H_per_block, D // 2):
558
+ acc_o_l[h_i, d_i] *= alpha_local[h_i]
559
+ T.copy(alpha_local, alpha_shared)
560
+
561
+ T.copy(acc_s, S_shared)
562
+ T.gemm(S_shared, KV_shared_0_l, acc_o_l)
563
+
564
+ T.barrier_arrive(bar_sScale_and_sS_ready)
565
+ T.barrier_arrive(bar_k_0_free[0])
566
+
567
+ # Buffer 1
568
+ T.barrier_wait(bar_k_1_ready[0], (i_i & 1))
569
+ T.barrier_arrive(bar_0_128)
570
+ T.barrier_wait(bar_0_128, 1)
571
+
572
+ for h_i, bi_i in T.Parallel(H_per_block, BI):
573
+ acc_s[h_i, bi_i] = T.if_then_else(
574
+ is_kv_valid_1[bi_i], 0, -T.infinity(acc_s.dtype)
575
+ )
576
+ T.gemm(
577
+ Q_shared_l, KV_shared_1_l, acc_s, transpose_B=True, wg_wait=-1
578
+ )
579
+ T.gemm(
580
+ Q_shared_r, KV_shared_1_r, acc_s, transpose_B=True, wg_wait=-1
581
+ )
582
+ T.gemm(
583
+ Q_tail_shared,
584
+ K_tail_shared_1,
585
+ acc_s,
586
+ transpose_B=True,
587
+ wg_wait=-1,
588
+ )
589
+
590
+ T.wait_wgmma(0)
591
+
592
+ T.barrier_arrive(bar_sScale_and_sS_free)
593
+ T.barrier_wait(bar_sScale_and_sS_free, ((i_i * 2 + 1) & 1) ^ 1)
594
+
595
+ T.copy(m_i, m_i_prev)
596
+ T.reduce_max(acc_s, m_i, dim=1, clear=False)
597
+ for h_i in T.Parallel(H_per_block):
598
+ alpha_local[h_i] = T.exp2((m_i_prev[h_i] - m_i[h_i]) * sm_scale)
599
+ for h_i, bi_i in T.Parallel(H_per_block, BI):
600
+ acc_s[h_i, bi_i] = T.exp2(
601
+ acc_s[h_i, bi_i] * sm_scale - m_i[h_i] * sm_scale
602
+ )
603
+ T.reduce_sum(
604
+ acc_s, sumexp_i, dim=1
605
+ ) # is this a accumulate operator?
606
+ for h_i in T.Parallel(H_per_block):
607
+ sumexp[h_i] = sumexp[h_i] * alpha_local[h_i] + sumexp_i[h_i]
608
+ for h_i, d_i in T.Parallel(H_per_block, D // 2):
609
+ acc_o_l[h_i, d_i] *= alpha_local[h_i]
610
+ T.copy(alpha_local, alpha_shared)
611
+
612
+ T.copy(acc_s, S_shared)
613
+ T.gemm(S_shared, KV_shared_1_l, acc_o_l)
614
+
615
+ T.barrier_arrive(bar_sScale_and_sS_ready)
616
+ T.barrier_arrive(bar_k_1_free[0])
617
+
618
+ # Rescale
619
+ for h_i in T.Parallel(H_per_block):
620
+ sum_exp_shared[h_i] = sumexp[h_i]
621
+ T.barrier_arrive(bar_final)
622
+ for h_i, d_i in T.Parallel(H_per_block, D // 2):
623
+ acc_o_l[h_i, d_i] /= sumexp[h_i]
624
+ for h_i in T.Parallel(H_per_block):
625
+ sumexp[h_i] = T.log2(sumexp[h_i]) + m_i[h_i] * sm_scale
626
+ T.copy(acc_o_l, O_shared_l)
627
+ T.copy(O_shared_l, Output[b_i, s_i, H0:H1, 0 : D // 2])
628
+ elif tx >= 128 and tx < 256:
629
+ # T.set_max_nreg(168, 1)
630
+ T.fill(acc_o_r, 0)
631
+ for i_i in T.serial(T.ceildiv(NI, 2)):
632
+ # Buffer 0
633
+ T.barrier_arrive(bar_sScale_and_sS_ready)
634
+ T.barrier_wait(bar_sScale_and_sS_ready, ((i_i * 2) & 1))
635
+ T.barrier_arrive(bar_1_128)
636
+ T.barrier_wait(bar_1_128, 0)
637
+ for h_i, d_i in T.Parallel(H_per_block, D // 2):
638
+ acc_o_r[h_i, d_i] *= alpha_shared[h_i]
639
+ T.gemm(S_shared, KV_shared_0_r, acc_o_r)
640
+ T.barrier_arrive(bar_k_0_free[0])
641
+ T.barrier_arrive(bar_sScale_and_sS_free)
642
+
643
+ # Buffer 1
644
+ T.barrier_arrive(bar_sScale_and_sS_ready)
645
+ T.barrier_wait(bar_sScale_and_sS_ready, ((i_i * 2 + 1) & 1))
646
+ T.barrier_arrive(bar_1_128)
647
+ T.barrier_wait(bar_1_128, 1)
648
+ for h_i, d_i in T.Parallel(H_per_block, D // 2):
649
+ acc_o_r[h_i, d_i] *= alpha_shared[h_i]
650
+ T.gemm(S_shared, KV_shared_1_r, acc_o_r)
651
+ T.barrier_arrive(bar_k_1_free[0])
652
+ if i_i != T.ceildiv(NI, 2) - 1:
653
+ T.barrier_arrive(bar_sScale_and_sS_free)
654
+
655
+ # Rescale
656
+ T.barrier_wait(bar_final, 0)
657
+ for h_i, d_i in T.Parallel(H_per_block, D // 2):
658
+ acc_o_r[h_i, d_i] /= sum_exp_shared[h_i]
659
+
660
+ T.copy(acc_o_r, O_shared_r)
661
+ T.copy(O_shared_r, Output[b_i, s_i, H0:H1, D // 2 : D])
662
+ elif tx >= 256:
663
+ # producer
664
+ T.set_max_nreg(80, 0)
665
+ indices_local[0] = 0
666
+ for i_i in T.serial(T.ceildiv(NI, 2)):
667
+ # Buffer 0
668
+ T.barrier_wait(bar_k_0_free[0], ((i_i & 1) ^ 1))
669
+ T.barrier_arrive(bar_2_128)
670
+ T.barrier_wait(bar_2_128, 0)
671
+
672
+ for r in T.serial(4):
673
+ indices_tmp[0] = Indices[
674
+ b_i, s_i, g_i, (i_i * 2) * BI + r * 16 + (tx - 256) // 8
675
+ ]
676
+ is_kv_valid_0[r * 16 + (tx - 256) // 8] = indices_tmp[0] >= 0
677
+ if is_kv_valid_0[r * 16 + (tx - 256) // 8]:
678
+ indices_local[0] = indices_tmp[0]
679
+
680
+ with T.attr("default", "async_scope", 1): # type: ignore
681
+ for u in T.serial(4):
682
+ for v in T.vectorized(8):
683
+ KV_shared_0_l[
684
+ r * 16 + (tx - 256) // 8,
685
+ 64 * u + (tx - 256) % 8 * 8 + v,
686
+ ] = KV[
687
+ b_i,
688
+ indices_local[0],
689
+ g_i,
690
+ 64 * u + (tx - 256) % 8 * 8 + v,
691
+ ]
692
+ KV_shared_0_r[
693
+ r * 16 + (tx - 256) // 8,
694
+ 64 * u + (tx - 256) % 8 * 8 + v,
695
+ ] = KV[
696
+ b_i,
697
+ indices_local[0],
698
+ g_i,
699
+ D // 2 + 64 * u + (tx - 256) % 8 * 8 + v,
700
+ ]
701
+ with T.attr("default", "async_scope", 1): # type: ignore
702
+ for v in T.vectorized(8):
703
+ K_tail_shared_0[
704
+ r * 16 + (tx - 256) // 8, (tx - 256) % 8 * 8 + v
705
+ ] = KV[
706
+ b_i,
707
+ indices_local[0],
708
+ g_i,
709
+ D + (tx - 256) % 8 * 8 + v,
710
+ ]
711
+
712
+ T.cp_async_barrier_noinc(bar_k_0_ready[0])
713
+
714
+ # Buffer 1
715
+ T.barrier_wait(bar_k_1_free[0], ((i_i & 1) ^ 1))
716
+ T.barrier_arrive(bar_2_128)
717
+ T.barrier_wait(bar_2_128, 1)
718
+
719
+ for r in T.serial(4):
720
+ indices_tmp[0] = Indices[
721
+ b_i, s_i, g_i, (i_i * 2 + 1) * BI + r * 16 + (tx - 256) // 8
722
+ ]
723
+ is_kv_valid_1[r * 16 + (tx - 256) // 8] = indices_tmp[0] >= 0
724
+ if is_kv_valid_1[r * 16 + (tx - 256) // 8]:
725
+ indices_local[0] = indices_tmp[0]
726
+
727
+ with T.attr("default", "async_scope", 1): # type: ignore
728
+ for u in T.serial(4):
729
+ for v in T.vectorized(8):
730
+ KV_shared_1_l[
731
+ r * 16 + (tx - 256) // 8,
732
+ 64 * u + (tx - 256) % 8 * 8 + v,
733
+ ] = KV[
734
+ b_i,
735
+ indices_local[0],
736
+ g_i,
737
+ 64 * u + (tx - 256) % 8 * 8 + v,
738
+ ]
739
+ KV_shared_1_r[
740
+ r * 16 + (tx - 256) // 8,
741
+ 64 * u + (tx - 256) % 8 * 8 + v,
742
+ ] = KV[
743
+ b_i,
744
+ indices_local[0],
745
+ g_i,
746
+ D // 2 + 64 * u + (tx - 256) % 8 * 8 + v,
747
+ ]
748
+ with T.attr("default", "async_scope", 1): # type: ignore
749
+ for v in T.vectorized(8):
750
+ K_tail_shared_1[
751
+ r * 16 + (tx - 256) // 8, (tx - 256) % 8 * 8 + v
752
+ ] = KV[
753
+ b_i,
754
+ indices_local[0],
755
+ g_i,
756
+ D + (tx - 256) % 8 * 8 + v,
757
+ ]
758
+
759
+ T.cp_async_barrier_noinc(bar_k_1_ready[0])
760
+
761
+ return main
762
+
763
+
764
+ def tilelang_sparse_fwd(
765
+ q: torch.Tensor,
766
+ kv: torch.Tensor,
767
+ indices: torch.Tensor,
768
+ sm_scale: float,
769
+ d_v: int = 512,
770
+ ) -> torch.Tensor:
771
+ assert q.dim() == 3 and kv.dim() == 3 and indices.dim() == 3
772
+ num_heads = q.shape[1]
773
+ dim = q.shape[2]
774
+ tail_dim = dim - d_v
775
+ topk = indices.shape[-1]
776
+ assert topk == 2048
777
+ if _is_hip:
778
+ kernel = sparse_attention_fwd_kernel_v1(
779
+ num_heads, d_v, tail_dim, topk, sm_scale=sm_scale, num_stages=1
780
+ )
781
+ else:
782
+ kernel = sparse_attention_fwd_kernel_v2(
783
+ num_heads, d_v, tail_dim, topk, sm_scale=sm_scale
784
+ )
785
+ return kernel(q.unsqueeze(0), kv.unsqueeze(0), indices.unsqueeze(0)) # type: ignore