Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3,001 changes: 3,001 additions & 0 deletions csrc/kda/cake_flashkda_bf16_piece_persistent_m128.cu

Large diffs are not rendered by default.

187 changes: 187 additions & 0 deletions csrc/kda/cake_flashkda_bf16_piece_persistent_m128_binding.cu
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
/*
* Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#include "flashkda_binding_common.cuh"

#define uint8_t flashkda_generated_uint8_t
#define uint16_t flashkda_generated_uint16_t
#define uint32_t flashkda_generated_uint32_t
#define uint64_t flashkda_generated_uint64_t
#define int32_t flashkda_generated_int32_t
#define int16_t flashkda_generated_int16_t
#define FlashKDATensorMap flashkda_generated_FlashKDATensorMap
#define FlashKDATensorMapPack flashkda_generated_FlashKDATensorMapPack
#define CUtensorMap flashkda_generated_CUtensorMap
#include "cake_flashkda_bf16_piece_persistent_m128.cu"
#undef CUtensorMap
#undef FlashKDATensorMapPack
#undef FlashKDATensorMap
#undef uint8_t
#undef uint16_t
#undef uint32_t
#undef uint64_t
#undef int32_t
#undef int16_t

namespace flashinfer {
namespace flash_kda {

static_assert(THREADS == 1024);
static_assert(SMEM_TOTAL == 221696);

void RunPiecePersistentM128(TensorView q, TensorView k, TensorView v, TensorView g, TensorView beta,
TensorView beta_tma, TensorView A_log, TensorView dt_bias,
TensorView cu_seqlens, TensorView seq_order, TensorView task_ids,
TensorView task_offsets, TensorView task_token_starts,
TensorView task_token_counts, TensorView task_state_sources,
TensorView task_state_destinations, TensorView mid_state,
TensorView mid_state_ready, TensorView initial_state, TensorView out,
TensorView final_state, TensorView descriptor_storage,
int64_t prepare_descriptors, int64_t num_heads,
int64_t use_initial_state, int64_t store_final_state, double scale,
double lower_bound, int64_t cuda_stream) {
TVM_FFI_ICHECK(cuda_stream >= 0) << "cuda_stream must be a non-negative stream handle";
TVM_FFI_ICHECK(q.device().device_type == kDLCUDA) << "q must be a CUDA tensor";
const int32_t device_id = q.device().device_id;
ffi::CUDADeviceGuard device_guard(device_id);
CheckFlashKDATarget(device_id);

const int64_t num_seqs =
CheckCommonInputs(q, k, v, g, beta, beta_tma, A_log, dt_bias, cu_seqlens, seq_order,
initial_state, out, final_state, descriptor_storage, prepare_descriptors,
num_heads, use_initial_state, store_final_state, scale, lower_bound);
for (const auto& named : {std::pair<const TensorView*, const char*>{&task_ids, "task_ids"},
{&task_offsets, "task_offsets"},
{&task_token_starts, "task_token_starts"},
{&task_token_counts, "task_token_counts"},
{&task_state_sources, "task_state_sources"},
{&task_state_destinations, "task_state_destinations"},
{&mid_state, "mid_state"},
{&mid_state_ready, "mid_state_ready"}}) {
CheckCudaTensor(*named.first, named.second, device_id);
}
for (const auto& named : {std::pair<const TensorView*, const char*>{&task_ids, "task_ids"},
{&task_offsets, "task_offsets"},
{&task_token_starts, "task_token_starts"},
{&task_token_counts, "task_token_counts"},
{&task_state_sources, "task_state_sources"},
{&task_state_destinations, "task_state_destinations"}}) {
CheckDtype(*named.first, named.second, dl_int32);
}
CheckDtype(mid_state, "mid_state", dl_bfloat16);
CheckDtype(mid_state_ready, "mid_state_ready", dl_uint32);

const int64_t total_tasks = num_seqs * num_heads;
const int64_t entry_count = task_ids.numel();
TVM_FFI_ICHECK(task_ids.ndim() == 1 && entry_count > total_tasks)
<< "task_ids must contain more than N * H entries for split recurrence chains";
for (const auto& named :
{std::pair<const TensorView*, const char*>{&task_token_starts, "task_token_starts"},
{&task_token_counts, "task_token_counts"},
{&task_state_sources, "task_state_sources"},
{&task_state_destinations, "task_state_destinations"}}) {
TVM_FFI_ICHECK(named.first->ndim() == 1 && named.first->numel() == entry_count)
<< named.second << " must contain one value per task entry";
}
TVM_FFI_ICHECK(task_offsets.ndim() == 1 && task_offsets.numel() >= 2)
<< "task_offsets must contain one entry per worker plus its terminal offset";
const int64_t worker_count = task_offsets.numel() - 1;
int32_t sm_count = 0;
CheckCuda(cudaDeviceGetAttribute(&sm_count, cudaDevAttrMultiProcessorCount, device_id),
"cudaDeviceGetAttribute(multiProcessorCount)");
TVM_FFI_ICHECK(sm_count == 148 || sm_count == 152)
<< "piece-persistent FlashKDA is validated only on 148-SM or 152-SM Blackwell; got "
<< sm_count << " SMs";
TVM_FFI_ICHECK(worker_count == sm_count)
<< "piece-persistent FlashKDA requires one resident worker per physical SM";
TVM_FFI_ICHECK(use_initial_state == 1 && store_final_state == 1 &&
initial_state.data_ptr() == final_state.data_ptr())
<< "piece-persistent FlashKDA requires one caller-owned in-place state tensor";

const int64_t handoff_count = mid_state_ready.numel();
TVM_FFI_ICHECK(handoff_count > 0 && mid_state_ready.ndim() == 1)
<< "mid_state_ready must contain at least one handoff counter";
TVM_FFI_ICHECK(mid_state.ndim() == 3 && mid_state.size(0) == handoff_count &&
mid_state.size(1) == kHeadDim && mid_state.size(2) == kHeadDim)
<< "mid_state must have shape [handoff_count, 128, 128]";

for (const auto& metadata : {std::pair<const TensorView*, const char*>{&task_ids, "task_ids"},
{&task_offsets, "task_offsets"},
{&task_token_starts, "task_token_starts"},
{&task_token_counts, "task_token_counts"},
{&task_state_sources, "task_state_sources"},
{&task_state_destinations, "task_state_destinations"}}) {
CheckNoOverlap(*metadata.first, metadata.second, mid_state, "mid_state");
CheckNoOverlap(*metadata.first, metadata.second, mid_state_ready, "mid_state_ready");
CheckNoOverlap(*metadata.first, metadata.second, initial_state, "initial_state");
CheckNoOverlap(*metadata.first, metadata.second, out, "out");
CheckNoOverlap(*metadata.first, metadata.second, descriptor_storage, "descriptor_storage");
}
CheckNoOverlap(mid_state, "mid_state", mid_state_ready, "mid_state_ready");
CheckNoOverlap(mid_state, "mid_state", initial_state, "initial_state");
CheckNoOverlap(mid_state, "mid_state", out, "out");
CheckNoOverlap(mid_state, "mid_state", descriptor_storage, "descriptor_storage");
CheckNoOverlap(mid_state_ready, "mid_state_ready", initial_state, "initial_state");
CheckNoOverlap(mid_state_ready, "mid_state_ready", out, "out");
CheckNoOverlap(mid_state_ready, "mid_state_ready", descriptor_storage, "descriptor_storage");

constexpr int32_t kSmemBytes = SMEM_TOTAL;
CheckDynamicSmemCapacity(device_id, kSmemBytes);
CheckCuda(cudaFuncSetAttribute(kernel_flashkda_bf16_persistent_m128,
cudaFuncAttributeMaxDynamicSharedMemorySize, kSmemBytes),
"cudaFuncSetAttribute(kernel_flashkda_bf16_persistent_m128)");

const dim3 grid(static_cast<uint32_t>(worker_count), 1, 1);
const dim3 block(THREADS, 1, 1);
const cudaStream_t stream = reinterpret_cast<cudaStream_t>(static_cast<uintptr_t>(cuda_stream));
const TmaPointers tma = EncodeTmaPointers<128, 32>(q, k, v, g, beta_tma, out, descriptor_storage,
prepare_descriptors, stream);
PackBetaForTmaIfNeeded(beta, beta_tma, num_heads, beta.stride(beta.ndim() - 2), stream);

kernel_flashkda_bf16_persistent_m128<<<grid, block, kSmemBytes, stream>>>(
reinterpret_cast<__nv_bfloat16*>(q.data_ptr()),
reinterpret_cast<flashkda_generated_FlashKDATensorMap const*>(tma.q),
reinterpret_cast<__nv_bfloat16*>(k.data_ptr()),
reinterpret_cast<flashkda_generated_FlashKDATensorMap const*>(tma.k),
reinterpret_cast<__nv_bfloat16*>(v.data_ptr()),
reinterpret_cast<flashkda_generated_FlashKDATensorMap const*>(tma.v),
reinterpret_cast<__nv_bfloat16*>(g.data_ptr()),
reinterpret_cast<flashkda_generated_FlashKDATensorMap const*>(tma.g),
reinterpret_cast<__nv_bfloat16*>(beta.data_ptr()),
reinterpret_cast<flashkda_generated_FlashKDATensorMap const*>(tma.beta),
reinterpret_cast<float*>(A_log.data_ptr()), reinterpret_cast<float*>(dt_bias.data_ptr()),
reinterpret_cast<long long*>(cu_seqlens.data_ptr()),
reinterpret_cast<int*>(seq_order.data_ptr()), reinterpret_cast<int*>(task_ids.data_ptr()),
reinterpret_cast<int*>(task_offsets.data_ptr()),
reinterpret_cast<int*>(task_token_starts.data_ptr()),
reinterpret_cast<int*>(task_token_counts.data_ptr()),
reinterpret_cast<int*>(task_state_sources.data_ptr()),
reinterpret_cast<int*>(task_state_destinations.data_ptr()),
reinterpret_cast<__nv_bfloat16*>(mid_state.data_ptr()),
reinterpret_cast<flashkda_generated_uint32_t*>(mid_state_ready.data_ptr()),
reinterpret_cast<__nv_bfloat16*>(initial_state.data_ptr()),
reinterpret_cast<__nv_bfloat16*>(out.data_ptr()),
reinterpret_cast<flashkda_generated_FlashKDATensorMap const*>(tma.out),
reinterpret_cast<__nv_bfloat16*>(final_state.data_ptr()), static_cast<int32_t>(num_heads),
static_cast<int32_t>(use_initial_state), static_cast<int32_t>(store_final_state),
static_cast<float>(scale), static_cast<float>(lower_bound));
CheckCuda(cudaGetLastError(), "kernel_flashkda_bf16_persistent_m128 launch");
}

} // namespace flash_kda
} // namespace flashinfer

TVM_FFI_DLL_EXPORT_TYPED_FUNC(run, flashinfer::flash_kda::RunPiecePersistentM128);
27 changes: 21 additions & 6 deletions docs/api/kda_prefill.rst
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,22 @@ CUDA 12.8 predates the family target, so CC 10.0 uses legacy exact
``sm_100a`` modules. With CUDA 12.9 or newer, JIT and AOT compile one
``sm_100f`` module per schedule for both CC 10.0 and CC 10.3. Cache keys also
include the frozen module identity so an older schedule cannot satisfy a
refreshed request. Runtime routing remains device-specific: persistent M128
is restricted to measured 148/152-SM CC 10.0 devices. CC 10.3 uses the direct
schedules, with a tensor-core state-decay specialization for uniform, complete
refreshed request. Runtime routing remains device-specific. The legacy
head-grouped and mixed-length persistent M128 routes remain restricted to
measured 148/152-SM CC 10.0 devices. On validated 148/152-SM CC 10.0 or CC 10.3
devices, eligible uniform eager calls with a caller-owned in-place initial and
final state may instead split only the recurrence chains that create a partial
final device wave. An occupancy and roofline model
uses the live SM count plus the frozen schedule's thread, shared-memory,
tensor-memory, BF16, HBM, state-transfer, and refill costs; it selects
recurrence pieces only when their dependency-DAG critical path is shorter than
direct M128. Intermediate BF16 states use device-scope release/acquire
handoffs, and each consumer CTA resets its ready counter before it completes so
subsequent eager launches start from the same state. This route is not selected
when the caller supplies an explicit workspace or ``seq_order``; CUDA Graph
capture therefore continues through the existing non-piece routes.

CC 10.3 also has a tensor-core state-decay specialization for uniform, complete
N32 work when there are at least 64 heads, at least 96 sequence/head tasks,
and the maximum sequence length is a multiple of 32 and at least 256. Mixed or
partial N32 tails retain scalar state decay. On either capability, fixed-layout
Expand Down Expand Up @@ -130,9 +143,11 @@ BT16 prepare/chain route: dense fixed ``B=1,H=60..64`` inputs qualify from
M128 shapes qualify from 65,536 tokens for one to eight sequence/head tasks,
or from 4,096 tokens for nine to 32 tasks when two CTAs per task fit. N16
alternatives additionally depend on SM count, chain waves, and sequence
length. Supplying ``seq_order`` disables persistent host task-bin planning but
does not suppress BT16 or otherwise force direct M128. Remaining eligible
inputs select the shape-appropriate non-persistent or general M128 schedule.
length. Uniform work may use the recurrence-piece route described above when
its modeled critical path wins. Supplying ``seq_order`` disables persistent
host task-bin planning but does not suppress BT16 or otherwise force direct
M128. Remaining eligible inputs select the shape-appropriate non-persistent or
general M128 schedule.
The scalar-prepare/S8 BT16 pair is submitted by one native Cake binding, which
performs both launch plans before enqueueing either kernel so the dependent
launches do not expose a Python/FFI inter-kernel gap. CUDA Graph capture still
Expand Down
2 changes: 2 additions & 0 deletions flashinfer/aot.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@
gen_flash_kda_m128_n16_checkpoint_module,
gen_flash_kda_m128_n16_module,
gen_flash_kda_m128_n16_short_module,
gen_flash_kda_piece_persistent_m128_module,
gen_flash_kda_persistent_m128_module,
gen_flash_kda_small_bh_m128_module,
)
Expand Down Expand Up @@ -619,6 +620,7 @@ def gen_all_modules(
gen_flash_kda_m128_n16_module(flash_kda_target),
gen_flash_kda_m128_n16_checkpoint_module(flash_kda_target),
gen_flash_kda_m128_n16_short_module(flash_kda_target),
gen_flash_kda_piece_persistent_m128_module(flash_kda_target),
gen_flash_kda_small_bh_m128_module(flash_kda_target),
gen_flash_kda_bt16_prepare_module(flash_kda_target),
gen_flash_kda_bt16_prepare_beta_tma_module(flash_kda_target),
Expand Down
18 changes: 18 additions & 0 deletions flashinfer/jit/flash_kda.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"m128_n16_checkpoint",
"m128_n16_short",
"persistent_m128",
"piece_persistent_m128",
"small_bh_m128",
"bt16_prepare",
"bt16_prepare_beta_tma",
Expand All @@ -57,6 +58,7 @@
"m128_n16_checkpoint",
"m128_n16_short",
"persistent_m128",
"piece_persistent_m128",
"small_bh_m128",
"bt16_prepare",
"bt16_prepare_beta_tma",
Expand Down Expand Up @@ -91,6 +93,7 @@
"m128_n16_checkpoint": "2c3342ae17",
"m128_n16_short": "71bc4450bf",
"persistent_m128": "e57cec87a0",
"piece_persistent_m128": "3ac5764753",
"small_bh_m128": "87ee851220",
"bt16_prepare": "2c6cc4c1f6",
"bt16_prepare_beta_tma": "d9394ce430",
Expand All @@ -110,6 +113,7 @@
"m128_n16_checkpoint": "flashkda_bf16_fused_m128_n16_checkpoint",
"m128_n16_short": "cake_flashkda_bf16_fused_m128_n16",
"persistent_m128": "cake_flashkda_bf16_persistent_m128",
"piece_persistent_m128": "cake_flashkda_bf16_piece_persistent_m128",
"small_bh_m128": "cake_flashkda_bf16_small_bh_m128",
"bt16_prepare": "cake_flashkda_bf16_bt16_prepare",
"bt16_prepare_beta_tma": "cake_flashkda_bf16_bt16_prepare_beta_tma",
Expand Down Expand Up @@ -281,6 +285,12 @@ def gen_flash_kda_persistent_m128_module(target: FlashKDATarget) -> JitSpec:
return gen_flash_kda_module("persistent_m128", target)


def gen_flash_kda_piece_persistent_m128_module(target: FlashKDATarget) -> JitSpec:
"""Generate the recurrence-piece persistent M128 module."""

return gen_flash_kda_module("piece_persistent_m128", target)


def gen_flash_kda_small_bh_m128_module(target: FlashKDATarget) -> JitSpec:
"""Generate the fixed-layout small-BH owner/helper M128 module."""

Expand Down Expand Up @@ -382,6 +392,12 @@ def load_flash_kda_persistent_m128_module(target: FlashKDATarget):
return load_flash_kda_module("persistent_m128", target)


def load_flash_kda_piece_persistent_m128_module(target: FlashKDATarget):
"""Load the recurrence-piece persistent M128 module."""

return load_flash_kda_module("piece_persistent_m128", target)


def load_flash_kda_small_bh_m128_module(target: FlashKDATarget):
"""Load the fixed-layout small-BH owner/helper M128 module."""

Expand Down Expand Up @@ -436,6 +452,7 @@ def get_flash_kda_prefill_module(variant: FlashKDAVariant, target: FlashKDATarge
"gen_flash_kda_m128_n16_module",
"gen_flash_kda_m128_n16_checkpoint_module",
"gen_flash_kda_m128_n16_short_module",
"gen_flash_kda_piece_persistent_m128_module",
"gen_flash_kda_persistent_m128_module",
"gen_flash_kda_small_bh_m128_module",
"gen_flash_kda_module",
Expand All @@ -448,6 +465,7 @@ def get_flash_kda_prefill_module(variant: FlashKDAVariant, target: FlashKDATarge
"load_flash_kda_m128_h12_long_module",
"load_flash_kda_m128_n16_module",
"load_flash_kda_m128_n16_short_module",
"load_flash_kda_piece_persistent_m128_module",
"load_flash_kda_persistent_m128_module",
"load_flash_kda_small_bh_m128_module",
"load_flash_kda_bt16_chain_m64_s7_module",
Expand Down
Loading
Loading