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.
- sglang/bench_one_batch.py +7 -9
- sglang/bench_one_batch_server.py +321 -31
- sglang/bench_serving.py +10 -3
- sglang/global_config.py +2 -2
- sglang/lang/backend/runtime_endpoint.py +1 -1
- sglang/launch_server.py +14 -0
- sglang/profiler.py +2 -2
- sglang/srt/batch_invariant_ops/__init__.py +27 -0
- sglang/srt/batch_invariant_ops/batch_invariant_ops.py +549 -0
- sglang/srt/configs/__init__.py +4 -0
- sglang/srt/configs/dots_ocr.py +64 -0
- sglang/srt/configs/falcon_h1.py +360 -0
- sglang/srt/configs/load_config.py +8 -0
- sglang/srt/configs/model_config.py +160 -105
- sglang/srt/configs/qwen3_vl.py +586 -0
- sglang/srt/constrained/base_grammar_backend.py +1 -0
- sglang/srt/constrained/outlines_jump_forward.py +1 -1
- sglang/srt/constrained/xgrammar_backend.py +6 -4
- sglang/srt/debug_utils/dumper.py +10 -3
- sglang/srt/disaggregation/ascend/conn.py +2 -2
- sglang/srt/disaggregation/ascend/transfer_engine.py +47 -9
- sglang/srt/disaggregation/common/conn.py +266 -98
- sglang/srt/disaggregation/decode.py +50 -9
- sglang/srt/disaggregation/decode_kvcache_offload_manager.py +185 -0
- sglang/srt/disaggregation/decode_schedule_batch_mixin.py +25 -16
- sglang/srt/disaggregation/mooncake/conn.py +51 -541
- sglang/srt/disaggregation/nixl/conn.py +148 -39
- sglang/srt/disaggregation/prefill.py +31 -14
- sglang/srt/disaggregation/utils.py +36 -5
- sglang/srt/distributed/device_communicators/all_reduce_utils.py +16 -0
- sglang/srt/distributed/device_communicators/shm_broadcast.py +4 -2
- sglang/srt/distributed/device_communicators/symm_mem.py +164 -0
- sglang/srt/distributed/parallel_state.py +135 -80
- sglang/srt/entrypoints/engine.py +23 -3
- sglang/srt/entrypoints/grpc_request_manager.py +330 -55
- sglang/srt/entrypoints/grpc_server.py +232 -102
- sglang/srt/entrypoints/http_server.py +49 -9
- sglang/srt/entrypoints/openai/protocol.py +110 -5
- sglang/srt/entrypoints/openai/serving_base.py +25 -6
- sglang/srt/entrypoints/openai/serving_chat.py +178 -49
- sglang/srt/entrypoints/openai/serving_completions.py +5 -3
- sglang/srt/entrypoints/openai/serving_embedding.py +1 -0
- sglang/srt/entrypoints/openai/serving_responses.py +42 -0
- sglang/srt/environ.py +285 -0
- sglang/srt/eplb/expert_location.py +30 -5
- sglang/srt/function_call/function_call_parser.py +3 -2
- sglang/srt/function_call/glm4_moe_detector.py +3 -3
- sglang/srt/function_call/gpt_oss_detector.py +23 -0
- sglang/srt/function_call/json_array_parser.py +63 -0
- sglang/srt/function_call/kimik2_detector.py +17 -4
- sglang/srt/function_call/utils.py +96 -5
- sglang/srt/grpc/compile_proto.py +245 -0
- sglang/srt/grpc/sglang_scheduler_pb2.py +73 -68
- sglang/srt/grpc/sglang_scheduler_pb2.pyi +60 -53
- sglang/srt/grpc/sglang_scheduler_pb2_grpc.py +3 -0
- sglang/srt/layers/activation.py +7 -6
- sglang/srt/layers/attention/aiter_backend.py +14 -15
- sglang/srt/layers/attention/ascend_backend.py +108 -9
- sglang/srt/layers/attention/attention_registry.py +206 -0
- sglang/srt/layers/attention/base_attn_backend.py +12 -3
- sglang/srt/layers/attention/cutlass_mla_backend.py +3 -3
- sglang/srt/layers/attention/dual_chunk_flashattention_backend.py +1 -1
- sglang/srt/layers/attention/fla/chunk_scaled_dot_kkt.py +2 -2
- sglang/srt/layers/attention/fla/fused_recurrent.py +4 -4
- sglang/srt/layers/attention/fla/fused_sigmoid_gating_recurrent.py +2 -2
- sglang/srt/layers/attention/flashattention_backend.py +41 -8
- sglang/srt/layers/attention/flashinfer_backend.py +112 -194
- sglang/srt/layers/attention/flashinfer_mla_backend.py +11 -15
- sglang/srt/layers/attention/flashmla_backend.py +7 -5
- sglang/srt/layers/attention/hybrid_attn_backend.py +11 -3
- sglang/srt/layers/attention/hybrid_linear_attn_backend.py +72 -72
- sglang/srt/layers/attention/mamba/causal_conv1d.py +1 -0
- sglang/srt/layers/attention/mamba/causal_conv1d_triton.py +15 -98
- sglang/srt/layers/attention/mamba/mamba.py +566 -1
- sglang/srt/layers/attention/mamba/mamba_utils.py +81 -0
- sglang/srt/layers/attention/mamba/ops/__init__.py +2 -0
- sglang/srt/layers/attention/mamba/ops/layernorm_gated.py +172 -0
- sglang/srt/layers/attention/mamba/ops/mamba_ssm.py +442 -0
- sglang/srt/layers/attention/mamba/ops/ssd_bmm.py +264 -0
- sglang/srt/layers/attention/mamba/ops/ssd_chunk_scan.py +622 -0
- sglang/srt/layers/attention/mamba/ops/ssd_chunk_state.py +757 -0
- sglang/srt/layers/attention/mamba/ops/ssd_combined.py +262 -0
- sglang/srt/layers/attention/mamba/ops/ssd_state_passing.py +275 -0
- sglang/srt/layers/attention/npu_ops/mla_preprocess.py +393 -0
- sglang/srt/layers/attention/nsa/dequant_k_cache.py +163 -0
- sglang/srt/layers/attention/nsa/index_buf_accessor.py +354 -0
- sglang/srt/layers/attention/nsa/nsa_indexer.py +761 -0
- sglang/srt/layers/attention/nsa/quant_k_cache.py +255 -0
- sglang/srt/layers/attention/nsa/tilelang_kernel.py +785 -0
- sglang/srt/layers/attention/nsa/transform_index.py +144 -0
- sglang/srt/layers/attention/nsa/utils.py +24 -0
- sglang/srt/layers/attention/nsa_backend.py +887 -0
- sglang/srt/layers/attention/tbo_backend.py +6 -6
- sglang/srt/layers/attention/torch_flex_backend.py +325 -0
- sglang/srt/layers/attention/triton_backend.py +42 -9
- sglang/srt/layers/attention/trtllm_mha_backend.py +5 -7
- sglang/srt/layers/attention/trtllm_mla_backend.py +178 -34
- sglang/srt/layers/attention/vision.py +58 -0
- sglang/srt/layers/attention/wave_backend.py +4 -4
- sglang/srt/layers/communicator.py +8 -0
- sglang/srt/layers/dp_attention.py +11 -1
- sglang/srt/layers/elementwise.py +3 -1
- sglang/srt/layers/layernorm.py +2 -0
- sglang/srt/layers/linear.py +21 -4
- sglang/srt/layers/logits_processor.py +15 -2
- sglang/srt/layers/moe/ep_moe/kernels.py +1 -1
- sglang/srt/layers/moe/ep_moe/layer.py +147 -74
- sglang/srt/layers/moe/flashinfer_cutedsl_moe.py +52 -25
- 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
- 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
- sglang/srt/layers/moe/fused_moe_triton/configs/triton_3_4_0/E=512,N=256,device_name=NVIDIA_B200.json +146 -0
- sglang/srt/layers/moe/fused_moe_triton/fused_moe_triton_config.py +6 -2
- sglang/srt/layers/moe/fused_moe_triton/layer.py +11 -12
- sglang/srt/layers/moe/token_dispatcher/deepep.py +77 -19
- sglang/srt/layers/moe/utils.py +10 -0
- sglang/srt/layers/parameter.py +23 -6
- sglang/srt/layers/quantization/compressed_tensors/compressed_tensors.py +1 -0
- sglang/srt/layers/quantization/compressed_tensors/schemes/__init__.py +2 -0
- sglang/srt/layers/quantization/compressed_tensors/schemes/compressed_tensors_w8a8_int8.py +173 -0
- sglang/srt/layers/quantization/deep_gemm_wrapper/configurer.py +2 -10
- sglang/srt/layers/quantization/fp8.py +2 -2
- sglang/srt/layers/quantization/fp8_utils.py +1 -1
- sglang/srt/layers/quantization/modelopt_quant.py +44 -9
- sglang/srt/layers/quantization/mxfp4.py +12 -4
- sglang/srt/layers/quantization/quark/quark_moe.py +16 -3
- sglang/srt/layers/quantization/w4afp8.py +0 -4
- sglang/srt/layers/quantization/w8a8_int8.py +15 -3
- sglang/srt/layers/rotary_embedding.py +78 -31
- sglang/srt/layers/sampler.py +52 -4
- sglang/srt/layers/utils.py +23 -0
- sglang/srt/lora/backend/base_backend.py +3 -3
- sglang/srt/lora/backend/chunked_backend.py +348 -0
- sglang/srt/lora/backend/triton_backend.py +10 -4
- sglang/srt/lora/lora.py +7 -5
- sglang/srt/lora/lora_manager.py +17 -6
- sglang/srt/lora/mem_pool.py +1 -1
- sglang/srt/lora/triton_ops/__init__.py +4 -0
- sglang/srt/lora/triton_ops/chunked_sgmv_expand.py +214 -0
- sglang/srt/lora/triton_ops/chunked_sgmv_shrink.py +174 -0
- sglang/srt/lora/utils.py +7 -5
- sglang/srt/managers/cache_controller.py +42 -142
- sglang/srt/managers/data_parallel_controller.py +11 -46
- sglang/srt/managers/detokenizer_manager.py +11 -11
- sglang/srt/managers/io_struct.py +162 -118
- sglang/srt/managers/mm_utils.py +43 -6
- sglang/srt/managers/multi_tokenizer_mixin.py +17 -17
- sglang/srt/managers/multimodal_processor.py +1 -2
- sglang/srt/managers/overlap_utils.py +53 -0
- sglang/srt/managers/schedule_batch.py +167 -86
- sglang/srt/managers/schedule_policy.py +143 -16
- sglang/srt/managers/scheduler.py +359 -214
- sglang/srt/managers/scheduler_input_blocker.py +1 -1
- sglang/srt/managers/scheduler_metrics_mixin.py +98 -126
- sglang/srt/managers/scheduler_output_processor_mixin.py +21 -12
- sglang/srt/managers/scheduler_profiler_mixin.py +5 -5
- sglang/srt/managers/scheduler_update_weights_mixin.py +7 -0
- sglang/srt/managers/tokenizer_communicator_mixin.py +111 -5
- sglang/srt/managers/tokenizer_manager.py +84 -136
- sglang/srt/managers/tp_worker.py +39 -29
- sglang/srt/managers/tp_worker_overlap_thread.py +33 -41
- sglang/srt/managers/utils.py +1 -45
- sglang/srt/mem_cache/allocator.py +14 -20
- sglang/srt/mem_cache/allocator_ascend.py +41 -27
- sglang/srt/mem_cache/base_prefix_cache.py +1 -1
- sglang/srt/mem_cache/chunk_cache.py +8 -1
- sglang/srt/mem_cache/evict_policy.py +23 -0
- sglang/srt/mem_cache/hicache_storage.py +40 -1
- sglang/srt/mem_cache/hiradix_cache.py +119 -32
- sglang/srt/mem_cache/memory_pool.py +188 -10
- sglang/srt/mem_cache/memory_pool_host.py +134 -182
- sglang/srt/mem_cache/radix_cache.py +222 -71
- sglang/srt/mem_cache/radix_cache_cpp.py +11 -8
- sglang/srt/mem_cache/storage/__init__.py +10 -0
- sglang/srt/mem_cache/storage/aibrix_kvcache/aibrix_kvcache_storage.py +151 -0
- sglang/srt/mem_cache/storage/aibrix_kvcache/unit_test.py +109 -0
- sglang/srt/mem_cache/storage/backend_factory.py +223 -0
- sglang/srt/mem_cache/storage/eic/eic_storage.py +778 -0
- sglang/srt/mem_cache/storage/eic/test_unit.py +115 -0
- sglang/srt/mem_cache/storage/hf3fs/storage_hf3fs.py +173 -58
- sglang/srt/mem_cache/storage/lmcache/lmc_radix_cache.py +10 -6
- sglang/srt/mem_cache/storage/mooncake_store/mooncake_store.py +117 -10
- sglang/srt/mem_cache/swa_radix_cache.py +25 -34
- sglang/srt/metrics/collector.py +82 -120
- sglang/srt/metrics/func_timer.py +2 -7
- sglang/srt/metrics/utils.py +8 -1
- sglang/srt/model_executor/cpu_graph_runner.py +2 -2
- sglang/srt/model_executor/cuda_graph_runner.py +39 -32
- sglang/srt/model_executor/forward_batch_info.py +23 -38
- sglang/srt/model_executor/model_runner.py +131 -183
- sglang/srt/model_executor/npu_graph_runner.py +12 -5
- sglang/srt/model_loader/loader.py +14 -10
- sglang/srt/model_loader/weight_utils.py +156 -2
- sglang/srt/models/bailing_moe.py +27 -4
- sglang/srt/models/deepseek_nextn.py +6 -1
- sglang/srt/models/deepseek_v2.py +536 -153
- sglang/srt/models/dots_ocr.py +173 -0
- sglang/srt/models/falcon_h1.py +576 -0
- sglang/srt/models/gemma3_causal.py +0 -2
- sglang/srt/models/gemma3_mm.py +1 -1
- sglang/srt/models/gemma3n_mm.py +1 -1
- sglang/srt/models/glm4_moe.py +3 -3
- sglang/srt/models/glm4_moe_nextn.py +2 -2
- sglang/srt/models/glm4v.py +1 -1
- sglang/srt/models/glm4v_moe.py +1 -1
- sglang/srt/models/gpt_oss.py +7 -30
- sglang/srt/models/kimi_vl_moonvit.py +2 -2
- sglang/srt/models/llama.py +4 -0
- sglang/srt/models/longcat_flash.py +1 -1
- sglang/srt/models/longcat_flash_nextn.py +1 -1
- sglang/srt/models/mllama4.py +15 -4
- sglang/srt/models/qwen2.py +0 -7
- sglang/srt/models/qwen2_5_vl.py +2 -2
- sglang/srt/models/qwen2_audio.py +1 -1
- sglang/srt/models/qwen2_moe.py +64 -1
- sglang/srt/models/qwen2_vl.py +1 -1
- sglang/srt/models/qwen3.py +18 -3
- sglang/srt/models/qwen3_moe.py +31 -3
- sglang/srt/models/qwen3_next.py +36 -9
- sglang/srt/models/qwen3_vl.py +787 -0
- sglang/srt/models/qwen3_vl_moe.py +471 -0
- sglang/srt/models/registry.py +15 -3
- sglang/srt/models/sarashina2_vision.py +269 -0
- sglang/srt/models/solar.py +505 -0
- sglang/srt/models/starcoder2.py +357 -0
- sglang/srt/models/torch_native_llama.py +9 -2
- sglang/srt/models/utils.py +51 -0
- sglang/srt/multimodal/processors/base_processor.py +15 -7
- sglang/srt/multimodal/processors/dots_vlm.py +2 -3
- sglang/srt/multimodal/processors/internvl.py +20 -8
- sglang/srt/multimodal/processors/qwen_vl.py +8 -1
- sglang/srt/multimodal/processors/sarashina2_vision.py +81 -0
- sglang/srt/parser/jinja_template_utils.py +6 -0
- sglang/srt/sampling/sampling_batch_info.py +20 -2
- sglang/srt/sampling/sampling_params.py +7 -0
- sglang/srt/server_args.py +753 -295
- sglang/srt/server_args_config_parser.py +146 -0
- sglang/srt/single_batch_overlap.py +151 -0
- sglang/srt/speculative/cpp_ngram/ngram.cpp +374 -0
- sglang/srt/speculative/cpp_ngram/ngram.h +110 -0
- sglang/srt/speculative/cpp_ngram/ngram_cache.py +138 -0
- sglang/srt/speculative/cpp_ngram/ngram_cache_binding.cpp +43 -0
- sglang/srt/speculative/cpp_ngram/param.h +125 -0
- sglang/srt/speculative/cpp_ngram/queue.h +71 -0
- sglang/srt/speculative/eagle_draft_cuda_graph_runner.py +2 -1
- sglang/srt/speculative/eagle_draft_extend_cuda_graph_runner.py +3 -1
- sglang/srt/speculative/{eagle_utils.py → eagle_info.py} +207 -755
- sglang/srt/speculative/eagle_worker.py +57 -25
- sglang/srt/speculative/ngram_utils.py +428 -0
- sglang/srt/speculative/ngram_worker.py +245 -0
- sglang/srt/speculative/spec_info.py +47 -0
- sglang/srt/speculative/spec_utils.py +606 -0
- sglang/srt/torch_memory_saver_adapter.py +5 -7
- sglang/srt/tracing/trace.py +32 -6
- sglang/srt/two_batch_overlap.py +8 -5
- sglang/srt/utils/__init__.py +2 -0
- sglang/srt/{utils.py → utils/common.py} +399 -74
- sglang/srt/{hf_transformers_utils.py → utils/hf_transformers_utils.py} +49 -5
- sglang/srt/{patch_torch.py → utils/patch_torch.py} +8 -0
- sglang/srt/utils/rpd_utils.py +452 -0
- sglang/srt/utils/slow_rank_detector.py +71 -0
- sglang/srt/warmup.py +8 -4
- sglang/srt/weight_sync/utils.py +1 -1
- sglang/test/get_logits_ut.py +57 -0
- sglang/test/run_eval.py +79 -11
- sglang/test/runners.py +1 -1
- sglang/test/simple_eval_common.py +5 -2
- sglang/test/simple_eval_mmmu_vlm.py +441 -0
- sglang/test/test_block_fp8.py +2 -2
- sglang/test/test_deterministic.py +297 -0
- sglang/test/test_disaggregation_utils.py +12 -1
- sglang/test/test_programs.py +1 -1
- sglang/test/test_utils.py +355 -4
- sglang/utils.py +10 -1
- sglang/version.py +1 -1
- {sglang-0.5.3rc0.dist-info → sglang-0.5.3rc2.dist-info}/METADATA +34 -25
- {sglang-0.5.3rc0.dist-info → sglang-0.5.3rc2.dist-info}/RECORD +281 -210
- sglang/srt/mem_cache/lora_radix_cache.py +0 -421
- /sglang/srt/{remote_instance_weight_loader_utils.py → model_loader/remote_instance_weight_loader_utils.py} +0 -0
- /sglang/srt/{poll_based_barrier.py → utils/poll_based_barrier.py} +0 -0
- {sglang-0.5.3rc0.dist-info → sglang-0.5.3rc2.dist-info}/WHEEL +0 -0
- {sglang-0.5.3rc0.dist-info → sglang-0.5.3rc2.dist-info}/licenses/LICENSE +0 -0
- {sglang-0.5.3rc0.dist-info → sglang-0.5.3rc2.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
|