diff --git a/inference/msa_v1/indexer/_common/topk_select/csrc/api/indexer_topk_api.cpp b/inference/msa_v1/indexer/_common/topk_select/csrc/api/indexer_topk_api.cpp index 0f75d68..71de23c 100644 --- a/inference/msa_v1/indexer/_common/topk_select/csrc/api/indexer_topk_api.cpp +++ b/inference/msa_v1/indexer/_common/topk_select/csrc/api/indexer_topk_api.cpp @@ -30,7 +30,9 @@ void check_sm100_family(torch::Tensor const &reference) { } // namespace torch::Tensor indexer_topk_run(torch::Tensor scores, torch::Tensor lengths, torch::Tensor output, - bool compact_grid) { + bool compact_grid, int64_t out_groups) { + TORCH_CHECK(out_groups >= 1 && scores.size(0) % out_groups == 0, + "out_groups must be positive and divide num_rows"); TORCH_CHECK(scores.is_cuda(), "scores must be a CUDA tensor"); TORCH_CHECK(scores.scalar_type() == at::kFloat, "scores must have dtype torch.float32"); TORCH_CHECK(scores.dim() == 2 && scores.size(0) > 0, @@ -62,7 +64,7 @@ torch::Tensor indexer_topk_run(torch::Tensor scores, torch::Tensor lengths, torc cudaError_t const status = launch_indexer_topk( scores.data_ptr(), lengths.data_ptr(), output.data_ptr(), static_cast(scores.size(1)), static_cast(scores.stride(0)), - static_cast(scores.size(0)), stream, compact_grid); + static_cast(scores.size(0)), stream, compact_grid, static_cast(out_groups)); TORCH_CHECK(status == cudaSuccess, "indexer TopK launch failed: ", cudaGetErrorString(status)); return output; } diff --git a/inference/msa_v1/indexer/_common/topk_select/csrc/api/indexer_topk_api.hpp b/inference/msa_v1/indexer/_common/topk_select/csrc/api/indexer_topk_api.hpp index 486a447..b2691e2 100644 --- a/inference/msa_v1/indexer/_common/topk_select/csrc/api/indexer_topk_api.hpp +++ b/inference/msa_v1/indexer/_common/topk_select/csrc/api/indexer_topk_api.hpp @@ -5,6 +5,6 @@ namespace minimax::msa_v1::indexer::topk { torch::Tensor indexer_topk_run(torch::Tensor scores, torch::Tensor lengths, torch::Tensor output, - bool compact_grid); + bool compact_grid, int64_t out_groups); } // namespace minimax::msa_v1::indexer::topk diff --git a/inference/msa_v1/indexer/_common/topk_select/csrc/api/indexer_topk_pybind.cpp b/inference/msa_v1/indexer/_common/topk_select/csrc/api/indexer_topk_pybind.cpp index f25bef0..28f3281 100644 --- a/inference/msa_v1/indexer/_common/topk_select/csrc/api/indexer_topk_pybind.cpp +++ b/inference/msa_v1/indexer/_common/topk_select/csrc/api/indexer_topk_pybind.cpp @@ -7,5 +7,5 @@ namespace py = pybind11; PYBIND11_MODULE(TORCH_EXTENSION_NAME, module) { using namespace minimax::msa_v1::indexer::topk; module.def("_run", &indexer_topk_run, py::arg("scores"), py::arg("lengths"), py::arg("out"), - py::arg("compact_grid") = false, "Run the standalone SM100-family indexer TopK"); + py::arg("compact_grid") = false, py::arg("out_groups") = 1, "Run the standalone SM100-family indexer TopK"); } diff --git a/inference/msa_v1/indexer/_common/topk_select/csrc/kernel/indexer_topk.cu b/inference/msa_v1/indexer/_common/topk_select/csrc/kernel/indexer_topk.cu index fe53c76..39e85e5 100644 --- a/inference/msa_v1/indexer/_common/topk_select/csrc/kernel/indexer_topk.cu +++ b/inference/msa_v1/indexer/_common/topk_select/csrc/kernel/indexer_topk.cu @@ -8,7 +8,7 @@ namespace minimax::msa_v1::indexer::topk { cudaError_t launch_indexer_topk(float const *scores, int32_t const *lengths, int32_t *output, int max_cols, int row_stride, int num_rows, cudaStream_t stream, - bool compact_grid) { + bool compact_grid, int out_groups) { if (compact_grid) { // Match the existing kernel's row mapping; only surplus CTAs are removed. int const rows_per_block = m3::m3_rows_per_block(max_cols); @@ -17,9 +17,9 @@ cudaError_t launch_indexer_topk(float const *scores, int32_t const *lengths, int // The warp family owns one row per warp; the block family uses the full CTA. int const threads = rows_per_block > 1 ? rows_per_block * kWarpThreads : m3::kThreads; m3::m3_topk_kernel<<>>(scores, lengths, output, max_cols, - row_stride, num_rows); + row_stride, num_rows, out_groups); } else { - m3::m3_launch(scores, lengths, output, max_cols, row_stride, num_rows, stream); + m3::m3_launch(scores, lengths, output, max_cols, row_stride, num_rows, stream, out_groups); } return cudaGetLastError(); } diff --git a/inference/msa_v1/indexer/_common/topk_select/csrc/kernel/indexer_topk_kernel.hpp b/inference/msa_v1/indexer/_common/topk_select/csrc/kernel/indexer_topk_kernel.hpp index e0dfc0f..cd1c035 100644 --- a/inference/msa_v1/indexer/_common/topk_select/csrc/kernel/indexer_topk_kernel.hpp +++ b/inference/msa_v1/indexer/_common/topk_select/csrc/kernel/indexer_topk_kernel.hpp @@ -8,6 +8,6 @@ namespace minimax::msa_v1::indexer::topk { cudaError_t launch_indexer_topk(float const *scores, int32_t const *lengths, int32_t *output, int max_cols, int row_stride, int num_rows, cudaStream_t stream, - bool compact_grid); + bool compact_grid, int out_groups = 1); } // namespace minimax::msa_v1::indexer::topk diff --git a/inference/msa_v1/indexer/_common/topk_select/csrc/kernel/m3/m3_topk.cuh b/inference/msa_v1/indexer/_common/topk_select/csrc/kernel/m3/m3_topk.cuh index 0e69229..f989c7d 100644 --- a/inference/msa_v1/indexer/_common/topk_select/csrc/kernel/m3/m3_topk.cuh +++ b/inference/msa_v1/indexer/_common/topk_select/csrc/kernel/m3/m3_topk.cuh @@ -75,16 +75,26 @@ inline int m3_max_n() { return kMaximumColumns; } // takes is uniform over that unit. // --------------------------------------------------------------------------- +// Score row r = g * (rows / out_groups) + i is written to output row i * out_groups + g; +// out_groups == 1 keeps the identity layout. +__device__ __forceinline__ int *out_row_ptr(int *__restrict__ out_ids, int row, int rows, + int out_groups) { + if (out_groups == 1) + return out_ids + row * kTopK; + const int rows_per_group = rows / out_groups; + return out_ids + ((row % rows_per_group) * out_groups + row / rows_per_group) * kTopK; +} + // This row's nvm = n-1, the count the select ranks -- or 0 once the row is // already written, which is every row of n <= kTopK: fewer columns than slots, // so the answer is the n ids in order padded with -1, and nothing is ranked. -__device__ __forceinline__ int row_nvm(const int *__restrict__ row_n, int *__restrict__ out_ids, +__device__ __forceinline__ int row_nvm(const int *__restrict__ row_n, int *__restrict__ out_row, int row, int slot) { const int n = __ldg(row_n + row); if (n > kTopK) return n - 1; // column n-1 is forced-selected, never ranked if (slot < kTopK) - out_ids[row * kTopK + slot] = (slot < n) ? slot : -1; + out_row[slot] = (slot < n) ? slot : -1; return 0; } @@ -176,7 +186,8 @@ inline int m3_rows_per_block(int n_max) { return ((n_max - 1) <= kThreads) ? kRo __global__ __launch_bounds__(kThreads) void m3_topk_kernel(const float *__restrict__ scores, const int *__restrict__ row_n, int *__restrict__ out_ids, int n_max, - int row_stride, int rows) { + int row_stride, int rows, + int out_groups = 1) { __shared__ SelectSmem s; const int tid = static_cast(threadIdx.x); @@ -193,12 +204,13 @@ __global__ __launch_bounds__(kThreads) void m3_topk_kernel(const float *__restri // short-row branch leaves -- so one test below covers all three cases. const bool owns_row = (warp < kRowsPerBlock) && (row < rows); + int *out_row = out_row_ptr(out_ids, row, rows, out_groups); if (n_max <= kTopK) { if (owns_row) - row_nvm(row_n, out_ids, row, lane); + row_nvm(row_n, out_row, row, lane); return; } - const int nvm = owns_row ? row_nvm(row_n, out_ids, row, lane) : 0; + const int nvm = owns_row ? row_nvm(row_n, out_row, row, lane) : 0; float pre[kWarpKeys]; #pragma unroll for (int i = 0; i < kWarpKeys; ++i) { @@ -206,14 +218,15 @@ __global__ __launch_bounds__(kThreads) void m3_topk_kernel(const float *__restri pre[i] = (idx < nvm) ? __ldcg(row_scores(scores, row, row_stride) + idx) : 0.0f; } if (nvm > 0) - warp_rank_row(nvm, pre, out_ids + row * kTopK); + warp_rank_row(nvm, pre, out_row); } else { // ---- block family: one row per CTA, so blockIdx.x IS the row and every // thread of the CTA reads the same n -- the branch below is CTA-uniform, // which is what keeps the __syncthreads() inside block_rank_row convergent. const int row = static_cast(blockIdx.x); const float *p = row_scores(scores, row, row_stride); - const int nvm = row_nvm(row_n, out_ids, row, tid); + int *out_row = out_row_ptr(out_ids, row, rows, out_groups); + const int nvm = row_nvm(row_n, out_row, row, tid); float pre[kPrefetchKeys]; #pragma unroll for (int i = 0; i < kPrefetchKeys; ++i) { @@ -221,7 +234,7 @@ __global__ __launch_bounds__(kThreads) void m3_topk_kernel(const float *__restri pre[i] = (id < nvm) ? __ldcg(p + id) : 0.0f; } if (nvm > 0) - block_rank_row<0>(nvm, p, pre, s, out_ids + row * kTopK); + block_rank_row<0>(nvm, p, pre, s, out_row); } } @@ -251,8 +264,9 @@ inline int m3_occ() { // +7 to +15% at 4096 rows, +31 to +45% at 8192. A caller working at that scale // wants the packed grid back. inline void m3_launch(const float *scores, const int *row_n, int *out, int n_max, int row_stride, - int rows, cudaStream_t st) { - m3_topk_kernel<<>>(scores, row_n, out, n_max, row_stride, rows); + int rows, cudaStream_t st, int out_groups = 1) { + m3_topk_kernel<<>>(scores, row_n, out, n_max, row_stride, rows, + out_groups); } } // namespace m3 diff --git a/inference/msa_v1/indexer/_common/topk_select/interface.py b/inference/msa_v1/indexer/_common/topk_select/interface.py index 778bab2..7723597 100644 --- a/inference/msa_v1/indexer/_common/topk_select/interface.py +++ b/inference/msa_v1/indexer/_common/topk_select/interface.py @@ -66,6 +66,7 @@ def _topk_select( *, out: torch.Tensor | None = None, compact_grid: bool = False, + out_groups: int = 1, ) -> torch.Tensor: """Select 15 historical columns and one forced tail from each row. @@ -83,4 +84,4 @@ def _topk_select( dtype=torch.int32, device=scores.device, ) - return load_extension()._run(scores, lengths, out, compact_grid) + return load_extension()._run(scores, lengths, out, compact_grid, out_groups) diff --git a/inference/msa_v1/indexer/decode/q8kv4/interface.py b/inference/msa_v1/indexer/decode/q8kv4/interface.py index 4850a0f..fb1e3f1 100644 --- a/inference/msa_v1/indexer/decode/q8kv4/interface.py +++ b/inference/msa_v1/indexer/decode/q8kv4/interface.py @@ -275,6 +275,10 @@ def run( class BatchDecodeIndexerWithPagedKVCacheWrapper: """Compose Q8KV4 proxy scores with the forced-tail TopK selection.""" + # run(out=...) also accepts the [H, batch * Q, 16] view of a contiguous + # [batch * Q, H, 16] buffer, which the Q8KV4 decode attention reads. + supports_head_minor_out = True + def __init__( self, workspace_buffer: torch.Tensor | None = None, @@ -365,14 +369,20 @@ def run( ): raise RuntimeError("plan() must be called before run()") topk_out = self._topk_indices if out is None else out + head_minor = ( + not topk_out.is_contiguous() + and topk_out.ndim == 3 + and topk_out.permute(1, 0, 2).is_contiguous() + ) if ( topk_out.shape != self._topk_indices.shape or topk_out.dtype is not torch.int32 or topk_out.device != self._topk_indices.device - or not topk_out.is_contiguous() + or not (topk_out.is_contiguous() or head_minor) ): raise ValueError( - "out must be contiguous int32 [H, batch * Q, 16] on the planned device" + "out must be int32 [H, batch * Q, 16] on the planned device, contiguous " + "or a permute(1, 0, 2) view of a contiguous [batch * Q, H, 16] tensor" ) proxy_scores = self._proxy_score.run( q, @@ -383,8 +393,11 @@ def run( _topk_select( proxy_scores.view(-1, proxy_scores.shape[-1]), self._num_valid_pages.view(-1), - out=topk_out.view(-1, _TOP_K), + out=( + topk_out.permute(1, 0, 2) if head_minor else topk_out + ).reshape(-1, _TOP_K), compact_grid=True, + out_groups=topk_out.shape[0] if head_minor else 1, ) return topk_out diff --git a/tests/inference/msa_v1/indexer/_common/topk_select/test_api_contract.py b/tests/inference/msa_v1/indexer/_common/topk_select/test_api_contract.py index ef58f98..459bcc5 100644 --- a/tests/inference/msa_v1/indexer/_common/topk_select/test_api_contract.py +++ b/tests/inference/msa_v1/indexer/_common/topk_select/test_api_contract.py @@ -30,6 +30,7 @@ def test_topk_select_is_the_only_package_entrypoint() -> None: "lengths", "out", "compact_grid", + "out_groups", ) for forbidden in ( "forward", diff --git a/tests/inference/msa_v1/indexer/decode/q8kv4/test_api_contract.py b/tests/inference/msa_v1/indexer/decode/q8kv4/test_api_contract.py index 85c5120..f57ba6a 100644 --- a/tests/inference/msa_v1/indexer/decode/q8kv4/test_api_contract.py +++ b/tests/inference/msa_v1/indexer/decode/q8kv4/test_api_contract.py @@ -72,6 +72,30 @@ def test_preallocated_output_and_shape() -> None: assert torch.equal(output.cpu(), expected.unsqueeze(0)) +@pytest.mark.parametrize("num_index_heads", [2, 4]) +def test_head_minor_out_matches_contiguous_out(num_index_heads: int) -> None: + """Top-k written as [batch * Q, H, 16] equals the default [H, batch * Q, 16].""" + device = torch.device("cuda") + q, packed_k, k_scale, page_table, seq_lens = make_inputs( + 3, + 40, + torch.tensor([40 * 128, 33 * 128 + 5, 17 * 128 + 77], dtype=torch.int32), + seed=4, + device=device, + num_index_heads=num_index_heads, + ) + wrapper = indexer.BatchDecodeIndexerWithPagedKVCacheWrapper() + assert wrapper.supports_head_minor_out + wrapper.plan(page_table, seq_lens, num_index_heads=num_index_heads) + expected = wrapper.run(q, packed_k, k_scale=k_scale).clone() + buffer = torch.full( + (3 * 8, num_index_heads, 16), -777, dtype=torch.int32, device=device + ) + result = wrapper.run(q, packed_k, k_scale=k_scale, out=buffer.permute(1, 0, 2)) + assert result.data_ptr() == buffer.data_ptr() + assert torch.equal(result, expected) + + def test_out_none_allocates_only_output() -> None: device = torch.device("cuda") inputs = make_inputs(