sglang 0.5.3rc0__py3-none-any.whl → 0.5.3rc2__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 (282) hide show
  1. sglang/bench_one_batch.py +7 -9
  2. sglang/bench_one_batch_server.py +321 -31
  3. sglang/bench_serving.py +10 -3
  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 +4 -0
  11. sglang/srt/configs/dots_ocr.py +64 -0
  12. sglang/srt/configs/falcon_h1.py +360 -0
  13. sglang/srt/configs/load_config.py +8 -0
  14. sglang/srt/configs/model_config.py +160 -105
  15. sglang/srt/configs/qwen3_vl.py +586 -0
  16. sglang/srt/constrained/base_grammar_backend.py +1 -0
  17. sglang/srt/constrained/outlines_jump_forward.py +1 -1
  18. sglang/srt/constrained/xgrammar_backend.py +6 -4
  19. sglang/srt/debug_utils/dumper.py +10 -3
  20. sglang/srt/disaggregation/ascend/conn.py +2 -2
  21. sglang/srt/disaggregation/ascend/transfer_engine.py +47 -9
  22. sglang/srt/disaggregation/common/conn.py +266 -98
  23. sglang/srt/disaggregation/decode.py +50 -9
  24. sglang/srt/disaggregation/decode_kvcache_offload_manager.py +185 -0
  25. sglang/srt/disaggregation/decode_schedule_batch_mixin.py +25 -16
  26. sglang/srt/disaggregation/mooncake/conn.py +51 -541
  27. sglang/srt/disaggregation/nixl/conn.py +148 -39
  28. sglang/srt/disaggregation/prefill.py +31 -14
  29. sglang/srt/disaggregation/utils.py +36 -5
  30. sglang/srt/distributed/device_communicators/all_reduce_utils.py +16 -0
  31. sglang/srt/distributed/device_communicators/shm_broadcast.py +4 -2
  32. sglang/srt/distributed/device_communicators/symm_mem.py +164 -0
  33. sglang/srt/distributed/parallel_state.py +135 -80
  34. sglang/srt/entrypoints/engine.py +23 -3
  35. sglang/srt/entrypoints/grpc_request_manager.py +330 -55
  36. sglang/srt/entrypoints/grpc_server.py +232 -102
  37. sglang/srt/entrypoints/http_server.py +49 -9
  38. sglang/srt/entrypoints/openai/protocol.py +110 -5
  39. sglang/srt/entrypoints/openai/serving_base.py +25 -6
  40. sglang/srt/entrypoints/openai/serving_chat.py +178 -49
  41. sglang/srt/entrypoints/openai/serving_completions.py +5 -3
  42. sglang/srt/entrypoints/openai/serving_embedding.py +1 -0
  43. sglang/srt/entrypoints/openai/serving_responses.py +42 -0
  44. sglang/srt/environ.py +285 -0
  45. sglang/srt/eplb/expert_location.py +30 -5
  46. sglang/srt/function_call/function_call_parser.py +3 -2
  47. sglang/srt/function_call/glm4_moe_detector.py +3 -3
  48. sglang/srt/function_call/gpt_oss_detector.py +23 -0
  49. sglang/srt/function_call/json_array_parser.py +63 -0
  50. sglang/srt/function_call/kimik2_detector.py +17 -4
  51. sglang/srt/function_call/utils.py +96 -5
  52. sglang/srt/grpc/compile_proto.py +245 -0
  53. sglang/srt/grpc/sglang_scheduler_pb2.py +73 -68
  54. sglang/srt/grpc/sglang_scheduler_pb2.pyi +60 -53
  55. sglang/srt/grpc/sglang_scheduler_pb2_grpc.py +3 -0
  56. sglang/srt/layers/activation.py +7 -6
  57. sglang/srt/layers/attention/aiter_backend.py +14 -15
  58. sglang/srt/layers/attention/ascend_backend.py +108 -9
  59. sglang/srt/layers/attention/attention_registry.py +206 -0
  60. sglang/srt/layers/attention/base_attn_backend.py +12 -3
  61. sglang/srt/layers/attention/cutlass_mla_backend.py +3 -3
  62. sglang/srt/layers/attention/dual_chunk_flashattention_backend.py +1 -1
  63. sglang/srt/layers/attention/fla/chunk_scaled_dot_kkt.py +2 -2
  64. sglang/srt/layers/attention/fla/fused_recurrent.py +4 -4
  65. sglang/srt/layers/attention/fla/fused_sigmoid_gating_recurrent.py +2 -2
  66. sglang/srt/layers/attention/flashattention_backend.py +41 -8
  67. sglang/srt/layers/attention/flashinfer_backend.py +112 -194
  68. sglang/srt/layers/attention/flashinfer_mla_backend.py +11 -15
  69. sglang/srt/layers/attention/flashmla_backend.py +7 -5
  70. sglang/srt/layers/attention/hybrid_attn_backend.py +11 -3
  71. sglang/srt/layers/attention/hybrid_linear_attn_backend.py +72 -72
  72. sglang/srt/layers/attention/mamba/causal_conv1d.py +1 -0
  73. sglang/srt/layers/attention/mamba/causal_conv1d_triton.py +15 -98
  74. sglang/srt/layers/attention/mamba/mamba.py +566 -1
  75. sglang/srt/layers/attention/mamba/mamba_utils.py +81 -0
  76. sglang/srt/layers/attention/mamba/ops/__init__.py +2 -0
  77. sglang/srt/layers/attention/mamba/ops/layernorm_gated.py +172 -0
  78. sglang/srt/layers/attention/mamba/ops/mamba_ssm.py +442 -0
  79. sglang/srt/layers/attention/mamba/ops/ssd_bmm.py +264 -0
  80. sglang/srt/layers/attention/mamba/ops/ssd_chunk_scan.py +622 -0
  81. sglang/srt/layers/attention/mamba/ops/ssd_chunk_state.py +757 -0
  82. sglang/srt/layers/attention/mamba/ops/ssd_combined.py +262 -0
  83. sglang/srt/layers/attention/mamba/ops/ssd_state_passing.py +275 -0
  84. sglang/srt/layers/attention/npu_ops/mla_preprocess.py +393 -0
  85. sglang/srt/layers/attention/nsa/dequant_k_cache.py +163 -0
  86. sglang/srt/layers/attention/nsa/index_buf_accessor.py +354 -0
  87. sglang/srt/layers/attention/nsa/nsa_indexer.py +761 -0
  88. sglang/srt/layers/attention/nsa/quant_k_cache.py +255 -0
  89. sglang/srt/layers/attention/nsa/tilelang_kernel.py +785 -0
  90. sglang/srt/layers/attention/nsa/transform_index.py +144 -0
  91. sglang/srt/layers/attention/nsa/utils.py +24 -0
  92. sglang/srt/layers/attention/nsa_backend.py +887 -0
  93. sglang/srt/layers/attention/tbo_backend.py +6 -6
  94. sglang/srt/layers/attention/torch_flex_backend.py +325 -0
  95. sglang/srt/layers/attention/triton_backend.py +42 -9
  96. sglang/srt/layers/attention/trtllm_mha_backend.py +5 -7
  97. sglang/srt/layers/attention/trtllm_mla_backend.py +178 -34
  98. sglang/srt/layers/attention/vision.py +58 -0
  99. sglang/srt/layers/attention/wave_backend.py +4 -4
  100. sglang/srt/layers/communicator.py +8 -0
  101. sglang/srt/layers/dp_attention.py +11 -1
  102. sglang/srt/layers/elementwise.py +3 -1
  103. sglang/srt/layers/layernorm.py +2 -0
  104. sglang/srt/layers/linear.py +21 -4
  105. sglang/srt/layers/logits_processor.py +15 -2
  106. sglang/srt/layers/moe/ep_moe/kernels.py +1 -1
  107. sglang/srt/layers/moe/ep_moe/layer.py +147 -74
  108. sglang/srt/layers/moe/flashinfer_cutedsl_moe.py +52 -25
  109. 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
  110. 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
  111. sglang/srt/layers/moe/fused_moe_triton/configs/triton_3_4_0/E=512,N=256,device_name=NVIDIA_B200.json +146 -0
  112. sglang/srt/layers/moe/fused_moe_triton/fused_moe_triton_config.py +6 -2
  113. sglang/srt/layers/moe/fused_moe_triton/layer.py +11 -12
  114. sglang/srt/layers/moe/token_dispatcher/deepep.py +77 -19
  115. sglang/srt/layers/moe/utils.py +10 -0
  116. sglang/srt/layers/parameter.py +23 -6
  117. sglang/srt/layers/quantization/compressed_tensors/compressed_tensors.py +1 -0
  118. sglang/srt/layers/quantization/compressed_tensors/schemes/__init__.py +2 -0
  119. sglang/srt/layers/quantization/compressed_tensors/schemes/compressed_tensors_w8a8_int8.py +173 -0
  120. sglang/srt/layers/quantization/deep_gemm_wrapper/configurer.py +2 -10
  121. sglang/srt/layers/quantization/fp8.py +2 -2
  122. sglang/srt/layers/quantization/fp8_utils.py +1 -1
  123. sglang/srt/layers/quantization/modelopt_quant.py +44 -9
  124. sglang/srt/layers/quantization/mxfp4.py +12 -4
  125. sglang/srt/layers/quantization/quark/quark_moe.py +16 -3
  126. sglang/srt/layers/quantization/w4afp8.py +0 -4
  127. sglang/srt/layers/quantization/w8a8_int8.py +15 -3
  128. sglang/srt/layers/rotary_embedding.py +78 -31
  129. sglang/srt/layers/sampler.py +52 -4
  130. sglang/srt/layers/utils.py +23 -0
  131. sglang/srt/lora/backend/base_backend.py +3 -3
  132. sglang/srt/lora/backend/chunked_backend.py +348 -0
  133. sglang/srt/lora/backend/triton_backend.py +10 -4
  134. sglang/srt/lora/lora.py +7 -5
  135. sglang/srt/lora/lora_manager.py +17 -6
  136. sglang/srt/lora/mem_pool.py +1 -1
  137. sglang/srt/lora/triton_ops/__init__.py +4 -0
  138. sglang/srt/lora/triton_ops/chunked_sgmv_expand.py +214 -0
  139. sglang/srt/lora/triton_ops/chunked_sgmv_shrink.py +174 -0
  140. sglang/srt/lora/utils.py +7 -5
  141. sglang/srt/managers/cache_controller.py +42 -142
  142. sglang/srt/managers/data_parallel_controller.py +11 -46
  143. sglang/srt/managers/detokenizer_manager.py +11 -11
  144. sglang/srt/managers/io_struct.py +162 -118
  145. sglang/srt/managers/mm_utils.py +43 -6
  146. sglang/srt/managers/multi_tokenizer_mixin.py +17 -17
  147. sglang/srt/managers/multimodal_processor.py +1 -2
  148. sglang/srt/managers/overlap_utils.py +53 -0
  149. sglang/srt/managers/schedule_batch.py +167 -86
  150. sglang/srt/managers/schedule_policy.py +143 -16
  151. sglang/srt/managers/scheduler.py +359 -214
  152. sglang/srt/managers/scheduler_input_blocker.py +1 -1
  153. sglang/srt/managers/scheduler_metrics_mixin.py +98 -126
  154. sglang/srt/managers/scheduler_output_processor_mixin.py +21 -12
  155. sglang/srt/managers/scheduler_profiler_mixin.py +5 -5
  156. sglang/srt/managers/scheduler_update_weights_mixin.py +7 -0
  157. sglang/srt/managers/tokenizer_communicator_mixin.py +111 -5
  158. sglang/srt/managers/tokenizer_manager.py +84 -136
  159. sglang/srt/managers/tp_worker.py +39 -29
  160. sglang/srt/managers/tp_worker_overlap_thread.py +33 -41
  161. sglang/srt/managers/utils.py +1 -45
  162. sglang/srt/mem_cache/allocator.py +14 -20
  163. sglang/srt/mem_cache/allocator_ascend.py +41 -27
  164. sglang/srt/mem_cache/base_prefix_cache.py +1 -1
  165. sglang/srt/mem_cache/chunk_cache.py +8 -1
  166. sglang/srt/mem_cache/evict_policy.py +23 -0
  167. sglang/srt/mem_cache/hicache_storage.py +40 -1
  168. sglang/srt/mem_cache/hiradix_cache.py +119 -32
  169. sglang/srt/mem_cache/memory_pool.py +188 -10
  170. sglang/srt/mem_cache/memory_pool_host.py +134 -182
  171. sglang/srt/mem_cache/radix_cache.py +222 -71
  172. sglang/srt/mem_cache/radix_cache_cpp.py +11 -8
  173. sglang/srt/mem_cache/storage/__init__.py +10 -0
  174. sglang/srt/mem_cache/storage/aibrix_kvcache/aibrix_kvcache_storage.py +151 -0
  175. sglang/srt/mem_cache/storage/aibrix_kvcache/unit_test.py +109 -0
  176. sglang/srt/mem_cache/storage/backend_factory.py +223 -0
  177. sglang/srt/mem_cache/storage/eic/eic_storage.py +778 -0
  178. sglang/srt/mem_cache/storage/eic/test_unit.py +115 -0
  179. sglang/srt/mem_cache/storage/hf3fs/storage_hf3fs.py +173 -58
  180. sglang/srt/mem_cache/storage/lmcache/lmc_radix_cache.py +10 -6
  181. sglang/srt/mem_cache/storage/mooncake_store/mooncake_store.py +117 -10
  182. sglang/srt/mem_cache/swa_radix_cache.py +25 -34
  183. sglang/srt/metrics/collector.py +82 -120
  184. sglang/srt/metrics/func_timer.py +2 -7
  185. sglang/srt/metrics/utils.py +8 -1
  186. sglang/srt/model_executor/cpu_graph_runner.py +2 -2
  187. sglang/srt/model_executor/cuda_graph_runner.py +39 -32
  188. sglang/srt/model_executor/forward_batch_info.py +23 -38
  189. sglang/srt/model_executor/model_runner.py +131 -183
  190. sglang/srt/model_executor/npu_graph_runner.py +12 -5
  191. sglang/srt/model_loader/loader.py +14 -10
  192. sglang/srt/model_loader/weight_utils.py +156 -2
  193. sglang/srt/models/bailing_moe.py +27 -4
  194. sglang/srt/models/deepseek_nextn.py +6 -1
  195. sglang/srt/models/deepseek_v2.py +536 -153
  196. sglang/srt/models/dots_ocr.py +173 -0
  197. sglang/srt/models/falcon_h1.py +576 -0
  198. sglang/srt/models/gemma3_causal.py +0 -2
  199. sglang/srt/models/gemma3_mm.py +1 -1
  200. sglang/srt/models/gemma3n_mm.py +1 -1
  201. sglang/srt/models/glm4_moe.py +3 -3
  202. sglang/srt/models/glm4_moe_nextn.py +2 -2
  203. sglang/srt/models/glm4v.py +1 -1
  204. sglang/srt/models/glm4v_moe.py +1 -1
  205. sglang/srt/models/gpt_oss.py +7 -30
  206. sglang/srt/models/kimi_vl_moonvit.py +2 -2
  207. sglang/srt/models/llama.py +4 -0
  208. sglang/srt/models/longcat_flash.py +1 -1
  209. sglang/srt/models/longcat_flash_nextn.py +1 -1
  210. sglang/srt/models/mllama4.py +15 -4
  211. sglang/srt/models/qwen2.py +0 -7
  212. sglang/srt/models/qwen2_5_vl.py +2 -2
  213. sglang/srt/models/qwen2_audio.py +1 -1
  214. sglang/srt/models/qwen2_moe.py +64 -1
  215. sglang/srt/models/qwen2_vl.py +1 -1
  216. sglang/srt/models/qwen3.py +18 -3
  217. sglang/srt/models/qwen3_moe.py +31 -3
  218. sglang/srt/models/qwen3_next.py +36 -9
  219. sglang/srt/models/qwen3_vl.py +787 -0
  220. sglang/srt/models/qwen3_vl_moe.py +471 -0
  221. sglang/srt/models/registry.py +15 -3
  222. sglang/srt/models/sarashina2_vision.py +269 -0
  223. sglang/srt/models/solar.py +505 -0
  224. sglang/srt/models/starcoder2.py +357 -0
  225. sglang/srt/models/torch_native_llama.py +9 -2
  226. sglang/srt/models/utils.py +51 -0
  227. sglang/srt/multimodal/processors/base_processor.py +15 -7
  228. sglang/srt/multimodal/processors/dots_vlm.py +2 -3
  229. sglang/srt/multimodal/processors/internvl.py +20 -8
  230. sglang/srt/multimodal/processors/qwen_vl.py +8 -1
  231. sglang/srt/multimodal/processors/sarashina2_vision.py +81 -0
  232. sglang/srt/parser/jinja_template_utils.py +6 -0
  233. sglang/srt/sampling/sampling_batch_info.py +20 -2
  234. sglang/srt/sampling/sampling_params.py +7 -0
  235. sglang/srt/server_args.py +753 -295
  236. sglang/srt/server_args_config_parser.py +146 -0
  237. sglang/srt/single_batch_overlap.py +151 -0
  238. sglang/srt/speculative/cpp_ngram/ngram.cpp +374 -0
  239. sglang/srt/speculative/cpp_ngram/ngram.h +110 -0
  240. sglang/srt/speculative/cpp_ngram/ngram_cache.py +138 -0
  241. sglang/srt/speculative/cpp_ngram/ngram_cache_binding.cpp +43 -0
  242. sglang/srt/speculative/cpp_ngram/param.h +125 -0
  243. sglang/srt/speculative/cpp_ngram/queue.h +71 -0
  244. sglang/srt/speculative/eagle_draft_cuda_graph_runner.py +2 -1
  245. sglang/srt/speculative/eagle_draft_extend_cuda_graph_runner.py +3 -1
  246. sglang/srt/speculative/{eagle_utils.py → eagle_info.py} +207 -755
  247. sglang/srt/speculative/eagle_worker.py +57 -25
  248. sglang/srt/speculative/ngram_utils.py +428 -0
  249. sglang/srt/speculative/ngram_worker.py +245 -0
  250. sglang/srt/speculative/spec_info.py +47 -0
  251. sglang/srt/speculative/spec_utils.py +606 -0
  252. sglang/srt/torch_memory_saver_adapter.py +5 -7
  253. sglang/srt/tracing/trace.py +32 -6
  254. sglang/srt/two_batch_overlap.py +8 -5
  255. sglang/srt/utils/__init__.py +2 -0
  256. sglang/srt/{utils.py → utils/common.py} +399 -74
  257. sglang/srt/{hf_transformers_utils.py → utils/hf_transformers_utils.py} +49 -5
  258. sglang/srt/{patch_torch.py → utils/patch_torch.py} +8 -0
  259. sglang/srt/utils/rpd_utils.py +452 -0
  260. sglang/srt/utils/slow_rank_detector.py +71 -0
  261. sglang/srt/warmup.py +8 -4
  262. sglang/srt/weight_sync/utils.py +1 -1
  263. sglang/test/get_logits_ut.py +57 -0
  264. sglang/test/run_eval.py +79 -11
  265. sglang/test/runners.py +1 -1
  266. sglang/test/simple_eval_common.py +5 -2
  267. sglang/test/simple_eval_mmmu_vlm.py +441 -0
  268. sglang/test/test_block_fp8.py +2 -2
  269. sglang/test/test_deterministic.py +297 -0
  270. sglang/test/test_disaggregation_utils.py +12 -1
  271. sglang/test/test_programs.py +1 -1
  272. sglang/test/test_utils.py +355 -4
  273. sglang/utils.py +10 -1
  274. sglang/version.py +1 -1
  275. {sglang-0.5.3rc0.dist-info → sglang-0.5.3rc2.dist-info}/METADATA +34 -25
  276. {sglang-0.5.3rc0.dist-info → sglang-0.5.3rc2.dist-info}/RECORD +281 -210
  277. sglang/srt/mem_cache/lora_radix_cache.py +0 -421
  278. /sglang/srt/{remote_instance_weight_loader_utils.py → model_loader/remote_instance_weight_loader_utils.py} +0 -0
  279. /sglang/srt/{poll_based_barrier.py → utils/poll_based_barrier.py} +0 -0
  280. {sglang-0.5.3rc0.dist-info → sglang-0.5.3rc2.dist-info}/WHEEL +0 -0
  281. {sglang-0.5.3rc0.dist-info → sglang-0.5.3rc2.dist-info}/licenses/LICENSE +0 -0
  282. {sglang-0.5.3rc0.dist-info → sglang-0.5.3rc2.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,255 @@
1
+ import torch
2
+ import triton
3
+ import triton.language as tl
4
+
5
+ from sglang.srt.layers.attention.nsa.utils import NSA_QUANT_K_CACHE_FAST
6
+
7
+
8
+ def quantize_k_cache(cache_k):
9
+ # TODO upstream can skip concat([k_nope, k_pe]) since we split them here
10
+ if NSA_QUANT_K_CACHE_FAST:
11
+ return _quantize_k_cache_fast_wrapped(cache_k)
12
+ else:
13
+ return _quantize_k_cache_slow(cache_k)
14
+
15
+
16
+ # Copied from original
17
+ def _quantize_k_cache_slow(
18
+ input_k_cache: torch.Tensor, # (num_blocks, block_size, h_k, d)
19
+ dv: int = 512,
20
+ tile_size: int = 128,
21
+ ) -> torch.Tensor:
22
+ """
23
+ Quantize the k-cache
24
+ Return a tensor with shape (num_blocks, block_size, h_k, dv + 4(dv/tile_size) + t(d-dv)) of dtype uint8_t, where t = input_k_cache.element_size()
25
+ For more detail about the layout of K/V, please refer to comments in flash_mla_interface.py or README.md
26
+ """
27
+ assert dv % tile_size == 0
28
+ num_tiles = dv // tile_size
29
+ num_blocks, block_size, h_k, d = input_k_cache.shape
30
+ assert h_k == 1
31
+ input_k_cache = input_k_cache.squeeze(2) # [num_blocks, block_size, d]
32
+ input_elem_size = input_k_cache.element_size()
33
+
34
+ result = torch.empty(
35
+ (num_blocks, block_size, dv + num_tiles * 4 + input_elem_size * (d - dv)),
36
+ dtype=torch.float8_e4m3fn,
37
+ device=input_k_cache.device,
38
+ )
39
+ result_k_nope_part = result[..., :dv]
40
+ result_k_scale_factor = result[..., dv : dv + num_tiles * 4].view(torch.float32)
41
+ result_k_rope_part = result[..., dv + num_tiles * 4 :].view(input_k_cache.dtype)
42
+ result_k_rope_part[:] = input_k_cache[..., dv:]
43
+
44
+ for tile_idx in range(0, num_tiles):
45
+ cur_scale_factors_inv = (
46
+ torch.abs(
47
+ input_k_cache[..., tile_idx * tile_size : (tile_idx + 1) * tile_size]
48
+ )
49
+ .max(dim=-1)
50
+ .values
51
+ / 448.0
52
+ ) # [num_blocks, block_size]
53
+ result_k_scale_factor[:, :, tile_idx] = cur_scale_factors_inv
54
+
55
+ cur_scale_factors_inv.unsqueeze_(-1) # [num_blocks, block_size, 1]
56
+ cur_quantized_nope = (
57
+ input_k_cache[
58
+ ..., tile_idx * tile_size : (tile_idx + 1) * tile_size
59
+ ].float()
60
+ / cur_scale_factors_inv.float()
61
+ ).to(torch.float8_e4m3fn)
62
+ result_k_nope_part[..., tile_idx * tile_size : (tile_idx + 1) * tile_size] = (
63
+ cur_quantized_nope
64
+ )
65
+
66
+ result = result.view(num_blocks, block_size, 1, -1)
67
+ return result
68
+
69
+
70
+ def _quantize_k_cache_fast_wrapped(
71
+ input_k_cache: torch.Tensor,
72
+ dv: int = 512,
73
+ tile_size: int = 128,
74
+ ) -> torch.Tensor:
75
+ # TODO the final API may be 2D instead of 4D, thus we convert them here
76
+ num_blocks, block_size, _, dim_nope_and_rope = input_k_cache.shape
77
+ assert dv == 512
78
+ assert dim_nope_and_rope == 512 + 64
79
+ assert tile_size == 128
80
+ input_k_cache = input_k_cache.view((-1, dim_nope_and_rope))
81
+
82
+ # TODO deliberately split into two tensors, then upstream can provide the two tensors instead of concat into one
83
+ k_nope = input_k_cache[:, :dv]
84
+ k_rope = input_k_cache[:, dv:]
85
+
86
+ output = _quantize_k_cache_fast(k_nope=k_nope, k_rope=k_rope)
87
+
88
+ return output.view(num_blocks, block_size, 1, -1)
89
+
90
+
91
+ def _quantize_k_cache_fast(k_nope, k_rope, group_size: int = 128):
92
+ """
93
+ :param k_nope: (num_tokens, dim_nope 512)
94
+ :param k_rope: (num_tokens, dim_rope 64)
95
+ """
96
+
97
+ assert k_nope.dtype == torch.bfloat16
98
+ assert k_rope.dtype == torch.bfloat16
99
+
100
+ num_tokens, dim_nope = k_nope.shape
101
+ num_tokens_, dim_rope = k_rope.shape
102
+ assert num_tokens == num_tokens_
103
+ assert dim_nope == 512
104
+ assert dim_rope == 64
105
+ assert k_nope.dtype == k_rope.dtype
106
+ num_tiles = dim_nope // group_size
107
+
108
+ assert k_nope.stride(1) == 1
109
+ assert k_rope.stride(1) == 1
110
+
111
+ output = torch.empty(
112
+ (num_tokens, dim_nope + num_tiles * 4 + k_rope.element_size() * dim_rope),
113
+ dtype=torch.float8_e4m3fn,
114
+ device=k_nope.device,
115
+ )
116
+ output_nope_q = output[..., :dim_nope]
117
+ output_nope_s = output[..., dim_nope : dim_nope + num_tiles * 4].view(torch.float32)
118
+ output_rope = output[..., dim_nope + num_tiles * 4 :].view(torch.bfloat16)
119
+
120
+ num_blocks_per_token = triton.cdiv(dim_nope + dim_rope, group_size)
121
+ assert num_blocks_per_token == 5
122
+
123
+ assert dim_nope % group_size == 0
124
+ NUM_NOPE_BLOCKS = dim_nope // group_size
125
+
126
+ _quantize_k_cache_fast_kernel[(num_tokens, num_blocks_per_token)](
127
+ output_nope_q,
128
+ output_nope_s,
129
+ output_rope,
130
+ k_nope,
131
+ k_rope,
132
+ output_nope_q.stride(0),
133
+ output_nope_s.stride(0),
134
+ output_rope.stride(0),
135
+ k_nope.stride(0),
136
+ k_rope.stride(0),
137
+ NUM_NOPE_BLOCKS=NUM_NOPE_BLOCKS,
138
+ GROUP_SIZE=group_size,
139
+ DIM_NOPE=dim_nope,
140
+ DIM_ROPE=dim_rope,
141
+ FP8_MIN=torch.finfo(torch.float8_e4m3fn).min,
142
+ FP8_MAX=torch.finfo(torch.float8_e4m3fn).max,
143
+ )
144
+
145
+ return output
146
+
147
+
148
+ @triton.jit
149
+ def _quantize_k_cache_fast_kernel(
150
+ output_nope_q_ptr,
151
+ output_nope_s_ptr,
152
+ output_rope_ptr,
153
+ k_nope_ptr,
154
+ k_rope_ptr,
155
+ output_nope_q_stride_0: int,
156
+ output_nope_s_stride_0: int,
157
+ output_rope_stride_0: int,
158
+ k_nope_stride_0: int,
159
+ k_rope_stride_0: int,
160
+ NUM_NOPE_BLOCKS: tl.constexpr,
161
+ GROUP_SIZE: tl.constexpr,
162
+ DIM_NOPE: tl.constexpr,
163
+ DIM_ROPE: tl.constexpr,
164
+ FP8_MIN: tl.constexpr,
165
+ FP8_MAX: tl.constexpr,
166
+ ):
167
+ token_id = tl.program_id(0)
168
+ raw_block_id = tl.program_id(1)
169
+
170
+ if raw_block_id < NUM_NOPE_BLOCKS:
171
+ # a. quant nope
172
+ effective_block_id = raw_block_id
173
+
174
+ offs = effective_block_id * GROUP_SIZE + tl.arange(0, GROUP_SIZE)
175
+ mask = offs < DIM_NOPE
176
+ ptr = k_nope_ptr + token_id * k_nope_stride_0 + offs
177
+
178
+ y = tl.load(ptr, mask=mask, other=0.0).to(tl.float32)
179
+
180
+ # the ref impl do not have a `tl.maximum(... eps)`, so we remove it here
181
+ y_s = tl.max(tl.abs(y)) / FP8_MAX
182
+ y_s_inv = 1.0 / y_s
183
+ y_q = tl.clamp(y * y_s_inv, FP8_MIN, FP8_MAX).to(
184
+ output_nope_q_ptr.dtype.element_ty
185
+ )
186
+
187
+ dst_q_ptr = output_nope_q_ptr + token_id * output_nope_q_stride_0 + offs
188
+ dst_s_ptr = (
189
+ output_nope_s_ptr + token_id * output_nope_s_stride_0 + effective_block_id
190
+ )
191
+
192
+ tl.store(dst_q_ptr, y_q, mask=mask)
193
+ tl.store(dst_s_ptr, y_s)
194
+ else:
195
+ # b. copy rope
196
+ effective_block_id = raw_block_id - NUM_NOPE_BLOCKS
197
+
198
+ offs = effective_block_id * GROUP_SIZE + tl.arange(0, GROUP_SIZE)
199
+ mask = offs < DIM_ROPE
200
+
201
+ src_ptr = k_rope_ptr + token_id * k_rope_stride_0 + offs
202
+ dst_ptr = output_rope_ptr + token_id * output_rope_stride_0 + offs
203
+
204
+ data = tl.load(src_ptr, mask=mask)
205
+ tl.store(dst_ptr, data, mask=mask)
206
+
207
+
208
+ if __name__ == "__main__":
209
+ for num_blocks, block_size in [
210
+ (1, 1),
211
+ (10, 64),
212
+ ]:
213
+ dim_nope_and_rope = 512 + 64
214
+
215
+ input_k_cache = torch.randn(
216
+ (num_blocks, block_size, 1, dim_nope_and_rope),
217
+ dtype=torch.bfloat16,
218
+ device="cuda",
219
+ )
220
+ # temp debug
221
+ # input_k_cache = (576 - torch.arange(num_blocks * block_size * 1 * dim_nope_and_rope, device="cuda")).to(torch.bfloat16).reshape(num_blocks, block_size, 1, dim_nope_and_rope)
222
+
223
+ ref_quant = _quantize_k_cache_slow(input_k_cache)
224
+ actual_quant = _quantize_k_cache_fast_wrapped(input_k_cache)
225
+ # print(f"{input_k_cache=}")
226
+ # print(f"{ref_quant=}")
227
+ # print(f"{actual_quant=}")
228
+ # print(f"{ref_quant == actual_quant=}")
229
+ # print(f"{actual_quant.to(torch.float32) - ref_quant.to(torch.float32)=}")
230
+ # print(f"{ref_quant.view(torch.bfloat16)=}")
231
+ # print(f"{actual_quant.view(torch.bfloat16)=}")
232
+ # assert torch.all(ref_quant == actual_quant)
233
+
234
+ import dequant_k_cache
235
+
236
+ ref_ref_dequant = dequant_k_cache._dequantize_k_cache_slow(ref_quant)
237
+ ref_actual_dequant = dequant_k_cache._dequantize_k_cache_fast_wrapped(ref_quant)
238
+ actual_actual_dequant = dequant_k_cache._dequantize_k_cache_fast_wrapped(
239
+ actual_quant
240
+ )
241
+
242
+ print(f"{ref_ref_dequant=}")
243
+ print(f"{actual_actual_dequant=}")
244
+ print(f"{actual_actual_dequant - ref_ref_dequant=}")
245
+ print(f"{torch.mean(ref_ref_dequant - actual_actual_dequant)=}")
246
+
247
+ # TODO too different?
248
+ torch.testing.assert_close(
249
+ ref_ref_dequant, ref_actual_dequant, atol=0.2, rtol=0.2
250
+ )
251
+ torch.testing.assert_close(
252
+ ref_ref_dequant, actual_actual_dequant, atol=0.2, rtol=0.2
253
+ )
254
+
255
+ print("Passed")