diff --git a/.github/workflows/build-check.yml b/.github/workflows/build-check.yml index d73a929bd..9e8b965fa 100644 --- a/.github/workflows/build-check.yml +++ b/.github/workflows/build-check.yml @@ -56,6 +56,7 @@ jobs: then export AS_PLATFORM="cuda" export AS_CUDA_SM="'70;75;80;86;89;90a'" + export AS_BUILD_R2SK_SAMPLING=ON bash scripts/release/cpp_build_cuda.sh else export AS_PLATFORM="x86" @@ -63,6 +64,13 @@ jobs: fi fi + - name: Verify R2S-K CUDA test binaries (compile only) + if: matrix.enable_cuda == 1 + shell: bash + run: | + test -x build/bin/cpp_r2sk_sampling_test + test -x build/bin/cpp_r2sk_decode_graph_test + build-wheels: strategy: diff --git a/.github/workflows/r2sk-gpu.yml b/.github/workflows/r2sk-gpu.yml new file mode 100644 index 000000000..c8e263073 --- /dev/null +++ b/.github/workflows/r2sk-gpu.yml @@ -0,0 +1,38 @@ +# SPDX-License-Identifier: Apache-2.0 +name: R2S-K GPU correctness + +on: + workflow_dispatch: + +permissions: + contents: read + +jobs: + r2sk-gpu: + runs-on: [self-hosted, Linux, X64, gpu] + container: + image: docker.cnb.cool/thinksrc/dashinfer/dev-ubi8-cu124:latest + options: --gpus all + steps: + - uses: actions/checkout@v4 + with: + lfs: true + - name: Build and run R2S-K on a CUDA device + shell: bash + run: | + git config --global --add safe.directory "$GITHUB_WORKSPACE" + source /root/.bashrc + if [ -f /miniconda/etc/profile.d/conda.sh ]; then + source /miniconda/etc/profile.d/conda.sh + fi + source activate ds_py + nvidia-smi + export AS_PLATFORM=cuda + export AS_CUDA_SM='80;86;89;90a' + export AS_BUILD_R2SK_SAMPLING=ON + export AS_BUILD_PACKAGE=OFF + bash scripts/release/cpp_build_cuda.sh + # Executing directly makes a no-device return of 77 fail this job. + build/bin/cpp_r2sk_sampling_test + build/bin/cpp_r2sk_sampling_test --graph-test + build/bin/cpp_r2sk_decode_graph_test diff --git a/CMakeLists.txt b/CMakeLists.txt index e5be69b25..1686718f7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -63,6 +63,10 @@ option(ENABLE_ARM_V84_V9 "enable v8.4-a or higher version of Arm instructions, s option(ENABLE_FP16 "build with fp16 mode" ON) option(ENABLE_BF16 "build with bf16 mode" ON) +option(ENABLE_R2SK_SAMPLING "build the experimental BF16 R2S-K sampling backend" OFF) +if(ENABLE_R2SK_SAMPLING AND NOT (ENABLE_CUDA AND ENABLE_BF16)) + message(FATAL_ERROR "ENABLE_R2SK_SAMPLING requires ENABLE_CUDA and ENABLE_BF16") +endif() option(ENABLE_FP8 "build with fp8 mode" ON) option(ENABLE_SPARSE "build with sparse mode" ON) option(ENABLE_CUSPARSELT "build with CUSPARSELT lib" OFF) @@ -200,6 +204,9 @@ endif() if (ENABLE_BF16) list(APPEND ALLSPARK_DEFINITION "-DENABLE_BF16") endif() +if (ENABLE_R2SK_SAMPLING) + list(APPEND ALLSPARK_DEFINITION "-DENABLE_R2SK_SAMPLING") +endif() if (ALWAYS_READ_LOAD_MODEL) list(APPEND ALLSPARK_DEFINITION "-DALWAYS_READ_LOAD_MODEL") diff --git a/HIE-DNN/dnn/cuda/prefix_scan/tiled_scan_d1.cuh b/HIE-DNN/dnn/cuda/prefix_scan/tiled_scan_d1.cuh index 5e85b619e..f9c8b13fb 100644 --- a/HIE-DNN/dnn/cuda/prefix_scan/tiled_scan_d1.cuh +++ b/HIE-DNN/dnn/cuda/prefix_scan/tiled_scan_d1.cuh @@ -396,11 +396,10 @@ hiednnStatus_t TiledPrefixSum( } TilePrefixT *tilePrefix; - DeviceWsGuard wsGuard(handle); - wsGuard.GetWorkspace(&tilePrefix, tilePrefixSize * sizeof(TilePrefixT)); - if (tilePrefix == nullptr) { - return HIEDNN_STATUS_INTERNAL_ERROR; - } + DeviceWsGuard wsGuard(handle, true); + auto status = wsGuard.GetWorkspace(&tilePrefix, + tilePrefixSize * sizeof(TilePrefixT)); + if (status != HIEDNN_STATUS_SUCCESS) return status; TilePrefixInit<1, TILE_PREFIX_PADDING, TilePrefixT>( handle.stream, tilePrefix, tilePrefixSize); @@ -429,11 +428,10 @@ hiednnStatus_t TiledPrefixSum( int64_t tilePrefixSize = tilePrefixSizeX * tilePrefixSizeY; TilePrefixT *tilePrefix; - DeviceWsGuard wsGuard(handle); - wsGuard.GetWorkspace(&tilePrefix, tilePrefixSize * sizeof(TilePrefixT)); - if (tilePrefix == nullptr) { - return HIEDNN_STATUS_INTERNAL_ERROR; - } + DeviceWsGuard wsGuard(handle, true); + auto status = wsGuard.GetWorkspace(&tilePrefix, + tilePrefixSize * sizeof(TilePrefixT)); + if (status != HIEDNN_STATUS_SUCCESS) return status; TilePrefixInit<2, TILE_PREFIX_PADDING, TilePrefixT>( handle.stream, tilePrefix, tilePrefixSizeX, m); diff --git a/HIE-DNN/dnn/include/cuda/cuda_handle.hpp b/HIE-DNN/dnn/include/cuda/cuda_handle.hpp index c5e1f4515..c8e1f23f7 100644 --- a/HIE-DNN/dnn/include/cuda/cuda_handle.hpp +++ b/HIE-DNN/dnn/include/cuda/cuda_handle.hpp @@ -21,17 +21,28 @@ struct HiednnCudaHandle { // DeviceWsLock must be called after DeviceWsUnlock template - hiednnStatus_t DeviceWsLock(T **ws, size_t size) const { + hiednnStatus_t DeviceWsLock(T **ws, size_t size, bool capture) const { if (size > deviceWsSize) { *ws = nullptr; return HIEDNN_STATUS_INTERNAL_ERROR; } *ws = static_cast(deviceWs); - CHECK_CUDA_RETURN(cudaStreamWaitEvent(stream, wsMutex, 0)); + unsigned int flags = 0; +#if CUDART_VERSION >= 12000 + if (capture) flags = cudaEventWaitExternal; +#endif + CHECK_CUDA_RETURN(cudaStreamWaitEvent(stream, wsMutex, flags)); return HIEDNN_STATUS_SUCCESS; } - hiednnStatus_t DeviceWsUnlock() const { + hiednnStatus_t DeviceWsUnlock(bool capture) const { +#if CUDART_VERSION >= 12000 + if (capture) { + CHECK_CUDA_RETURN(cudaEventRecordWithFlags( + wsMutex, stream, cudaEventRecordExternal)); + return HIEDNN_STATUS_SUCCESS; + } +#endif CHECK_CUDA_RETURN(cudaEventRecord(wsMutex, stream)); return HIEDNN_STATUS_SUCCESS; } @@ -48,21 +59,33 @@ namespace cuda { */ struct DeviceWsGuard { const HiednnCudaHandle *handle; + bool captureAware; + bool capture = false; bool lock = false; - explicit DeviceWsGuard(const HiednnCudaHandle &cudaHandle) - : handle(&cudaHandle) {} + explicit DeviceWsGuard(const HiednnCudaHandle &cudaHandle, + bool captureAware = false) + : handle(&cudaHandle), captureAware(captureAware) {} template hiednnStatus_t GetWorkspace(T **ws, size_t size) { - auto stat = handle->DeviceWsLock(ws, size); +#if CUDART_VERSION >= 12000 + if (captureAware) { + // This event serializes shared workspace between graph and eager + // calls. Preserve it as an event node during capture. + cudaStreamCaptureStatus status; + CHECK_CUDA_RETURN(cudaStreamIsCapturing(handle->stream, &status)); + capture = status == cudaStreamCaptureStatusActive; + } +#endif + auto stat = handle->DeviceWsLock(ws, size, capture); lock = (stat == HIEDNN_STATUS_SUCCESS); return stat; } ~DeviceWsGuard() { if (lock) { - handle->DeviceWsUnlock(); + handle->DeviceWsUnlock(capture); } } }; diff --git a/build.sh b/build.sh index 7f851ba9e..dca0a8dc6 100755 --- a/build.sh +++ b/build.sh @@ -89,6 +89,7 @@ if [ "${with_platform,,}" == "cuda" ]; then -DNCCL_VERSION=${NCCL_VERSION} \ -DCUDA_VERSION=${cuda_version} \ -DCMAKE_CUDA_ARCHITECTURES="${cuda_sm}" \ + -DENABLE_R2SK_SAMPLING="${AS_BUILD_R2SK_SAMPLING:-OFF}" \ -DUSE_SYSTEM_NV_LIB=${system_nv_lib} \ -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \ -DENABLE_NV_STATIC_LIB=${cuda_static} \ diff --git a/csrc/core/kernel/CMakeLists.txt b/csrc/core/kernel/CMakeLists.txt index 8cda9a959..3a4a3b18a 100644 --- a/csrc/core/kernel/CMakeLists.txt +++ b/csrc/core/kernel/CMakeLists.txt @@ -119,6 +119,10 @@ if (ENABLE_CUDA) file(GLOB_RECURSE CUDA_MOE_SRC cuda/moe/*.cu) list(APPEND KERNEL_SRC ${CUDA_COMMON_KERNEL_SRC} ${CUDA_XFORMER_SRC} ${CUDA_MOE_SRC}) + if (ENABLE_R2SK_SAMPLING) + list(APPEND KERNEL_SRC cuda/topk_r2sk/r2sk.cu cuda/topk_r2sk/sampling.cu + cuda/topk_r2sk/decode_graph.cu) + endif() endif() if (ENABLE_JSON_MODE) @@ -137,6 +141,9 @@ message(STATUS "ALLSPARK_PUBLIC_DEFINITIONS:${ALLSPARK_PUBLIC_DEFINITIONS}") add_library(allspark_kernel STATIC ${KERNEL_SRC}) set_target_properties(allspark_kernel PROPERTIES CXX_STANDARD ${CXX_STD}) +if (ENABLE_R2SK_SAMPLING) + target_compile_features(allspark_kernel PRIVATE cuda_std_17) +endif() target_compile_definitions( diff --git a/csrc/core/kernel/cuda/topk_r2sk/LICENSE.RadiK b/csrc/core/kernel/cuda/topk_r2sk/LICENSE.RadiK new file mode 100644 index 000000000..61878ba36 --- /dev/null +++ b/csrc/core/kernel/cuda/topk_r2sk/LICENSE.RadiK @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023-present Alibaba Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/csrc/core/kernel/cuda/topk_r2sk/bfloat16_graph.cuh b/csrc/core/kernel/cuda/topk_r2sk/bfloat16_graph.cuh new file mode 100644 index 000000000..67e4cf5c0 --- /dev/null +++ b/csrc/core/kernel/cuda/topk_r2sk/bfloat16_graph.cuh @@ -0,0 +1,355 @@ +// SPDX-License-Identifier: Apache-2.0 +// Included in the CUDA translation unit to reuse the packed radix primitives. + +namespace { + +using GraphJob = KernelJobT; +using GraphBuffer = ValueBuffer; +constexpr int kGraphPlanThreads = 128; +constexpr int kGraphFirstBins = 4096; +constexpr int kGraphLastBins = 16; +constexpr int kGraphHistogramStride = kGraphFirstBins + 1; +constexpr uint32_t kGraphMaxSort = 1024; + +struct GraphSort { + GraphBuffer source; + GraphBuffer output; + uint32_t count; + uint32_t keep; +}; + +struct GraphStorage { + GraphJob* first; + GraphJob* last; + Decision* decisions; + uint32_t* histogram; + uint32_t* counters; + GraphSort* first_sort; + GraphSort* last_sort; + GraphBuffer candidate; + GraphBuffer potential; +}; + +struct GraphLayout { + detail::ArenaRegion first, last, decisions, histogram, counters; + detail::ArenaRegion first_sort, last_sort, candidate_values, + candidate_indices; + detail::ArenaRegion potential_values, potential_indices; + uint64_t bytes; +}; + +GraphLayout graph_layout(BFloat16GraphShape s) { + if (!s.batch || s.batch > 65535 || s.vocabulary < 2 || + s.vocabulary > 0x7fffffffu || !s.k || s.k > 256 || s.k > s.vocabulary || + s.sort_limit < s.k || s.sort_limit > kGraphMaxSort || + (s.sort_limit & (s.sort_limit - 1)) || !s.block_cap || + s.block_cap > 65535) { + throw std::invalid_argument("invalid BF16 graph shape or launch limits"); + } + + const uint64_t batch = s.batch; + detail::ArenaPlanner planner; + return { + planner.add(batch, sizeof(GraphJob)), + planner.add(batch, sizeof(GraphJob)), + planner.add(batch, sizeof(Decision)), + planner.add(batch * kGraphHistogramStride + 1, sizeof(uint32_t)), + planner.add(batch * 2, sizeof(uint32_t)), + planner.add(batch, sizeof(GraphSort)), + planner.add(batch, sizeof(GraphSort)), + planner.add(batch * s.vocabulary, sizeof(BFloat16)), + planner.add(batch * s.vocabulary, sizeof(uint32_t)), + planner.add(batch * s.sort_limit, sizeof(BFloat16)), + planner.add(batch * s.sort_limit, sizeof(uint32_t)), + planner.finish(), + }; +} + +template +T* graph_region(void* arena, detail::ArenaRegion region) { + return reinterpret_cast(static_cast(arena) + + region.offset); +} + +__device__ GraphBuffer row_buffer(GraphBuffer buffer, uint64_t offset) { + return {buffer.v + offset, buffer.i + offset}; +} + +__global__ void init_graph_jobs(BFloat16GraphShape shape, const BFloat16* input, + GraphStorage storage) { + const uint32_t row = blockIdx.x * blockDim.x + threadIdx.x; + if (row >= shape.batch) return; + GraphJob first{}; + first.src.v = input + uint64_t(row) * shape.vocabulary; + first.n = shape.vocabulary; + first.rank = shape.k; + first.hist = storage.histogram + uint64_t(row) * kGraphHistogramStride; + first.scale_unsafe = first.hist + kGraphFirstBins; + first.decision = storage.decisions + row; + first.counters = storage.counters + uint64_t(row) * 2; + storage.first[row] = first; +} + +__global__ void plan_graph_partition(BFloat16GraphShape shape, + GraphStorage storage, GraphBuffer output, + BFloat16GraphRow* rows) { + const uint32_t row = blockIdx.x * blockDim.x + threadIdx.x; + if (row >= shape.batch) return; + GraphJob first = storage.first[row]; + const Decision decision = storage.decisions[row]; + GraphJob last{}; + GraphSort sort{}; + GraphRoute route = GraphRoute::invalid_nan; + + if (decision.scale_unsafe) { + first.n = 0; + } else { + const auto destination = row_buffer(output, uint64_t(row) * shape.k); + const auto potential = + row_buffer(storage.potential, uint64_t(row) * shape.sort_limit); + const uint32_t retained = decision.h + decision.B; + first.boundary = static_cast(decision.bin); + first.gcap = decision.h; + first.ecap = decision.B; + if (retained <= shape.sort_limit) { + route = retained == shape.k ? GraphRoute::exact : GraphRoute::early_sort; + first.G = potential; + first.E = row_buffer(potential, decision.h); + sort = {potential, destination, retained, shape.k}; + } else { + route = GraphRoute::refine; + const auto candidate = + row_buffer(storage.candidate, uint64_t(row) * shape.vocabulary); + first.G = destination; + first.E = candidate; + sort = {destination, destination, decision.h, decision.h}; + last.src = {candidate.v, candidate.i}; + last.n = decision.B; + last.rank = shape.k - decision.h; + last.pass = 1; + // The first 12 bits select one sign. In the next original digit + // the low eight bits are constant for every BF16 key in this group. + last.boundary = first.boundary < 2048 ? 255 : 0; + last.hist = first.hist; + last.counters = first.counters; + last.G = row_buffer(destination, decision.h); + + // An all-retained row can directly reuse the source and its indices. + if (decision.B == first.n) { + last.src = first.src; + first.n = 0; + } + for (int bin = 0; bin < kGraphLastBins; ++bin) last.hist[bin] = 0; + } + } + first.counters[0] = 0; + first.counters[1] = 0; + storage.first[row] = first; + storage.last[row] = last; + storage.first_sort[row] = sort; + if (rows) { + uint32_t passes = route == GraphRoute::refine ? 2 : 1; + rows[row] = {route, decision.h, decision.B, passes}; + } +} + +__global__ void plan_graph_tail(BFloat16GraphShape shape, + GraphStorage storage) { + const uint32_t row = blockIdx.x * blockDim.x + threadIdx.x; + if (row >= shape.batch) return; + GraphJob last = storage.last[row]; + GraphSort sort{}; + if (last.n) { + uint32_t above = 0; + uint32_t ties = 0; + int bin = kGraphLastBins - 1; + for (; bin >= 0; --bin) { + ties = last.hist[bin]; + if (above + ties >= last.rank) break; + above += ties; + } + const auto potential = + row_buffer(storage.potential, uint64_t(row) * shape.sort_limit); + sort = {potential, last.G, last.rank, last.rank}; + last.G = potential; + last.E = row_buffer(potential, above); + last.gcap = above; + last.ecap = last.rank - above; + last.boundary |= static_cast(bin) << 8; + // The top bin covers the whole input. Any rank occurrences are valid. + if (ties == last.n) last.n = last.rank; + last.counters[0] = 0; + last.counters[1] = 0; + storage.last[row] = last; + } + storage.last_sort[row] = sort; +} + +__global__ void sort_graph_run(const GraphSort* jobs) { + const GraphSort job = jobs[blockIdx.x]; + if (!job.count) return; + if (job.count == 1) { + if (threadIdx.x == 0 && job.source.v != job.output.v) { + job.output.v[0] = job.source.v[0]; + job.output.i[0] = job.source.i[0]; + } + return; + } + + extern __shared__ uint32_t storage[]; + const uint32_t width = 1u << (32 - __clz(job.count - 1)); + uint32_t* keys = storage; + uint32_t* indices = storage + width; + for (uint32_t i = threadIdx.x; i < width; i += blockDim.x) { + const bool valid = i < job.count; + keys[i] = valid ? ordered_key(job.source.v[i]) >> 16 : 0; + indices[i] = valid ? job.source.i[i] : 0; + } + __syncthreads(); + for (uint32_t size = 2; size <= width; size <<= 1) { + for (uint32_t stride = size >> 1; stride; stride >>= 1) { + for (uint32_t i = threadIdx.x; i < width; i += blockDim.x) { + const uint32_t other = i ^ stride; + if (other > i) { + const bool descending = (i & size) == 0; + const uint32_t a = keys[i], b = keys[other]; + if (descending ? a < b : a > b) { + keys[i] = b; + keys[other] = a; + const uint32_t index = indices[i]; + indices[i] = indices[other]; + indices[other] = index; + } + } + } + __syncthreads(); + } + } + for (uint32_t i = threadIdx.x; i < job.keep; i += blockDim.x) { + const uint32_t key = keys[i]; + const uint32_t mask = key & 0x8000u ? 0x8000u : 0xffffu; + job.output.v[i].bits = static_cast(key ^ mask); + job.output.i[i] = indices[i]; + } +} + +GraphStorage bind_graph_storage(void* arena, uint64_t bytes, + const GraphLayout& layout) { + const auto address = reinterpret_cast(arena); + if (!arena || address % detail::ArenaPlanner::alignment || + bytes < layout.bytes || layout.bytes > UINTPTR_MAX - address) { + throw std::invalid_argument("invalid BF16 selection arena"); + } + return { + graph_region(arena, layout.first), + graph_region(arena, layout.last), + graph_region(arena, layout.decisions), + graph_region(arena, layout.histogram), + graph_region(arena, layout.counters), + graph_region(arena, layout.first_sort), + graph_region(arena, layout.last_sort), + {graph_region(arena, layout.candidate_values), + graph_region(arena, layout.candidate_indices)}, + {graph_region(arena, layout.potential_values), + graph_region(arena, layout.potential_indices)}, + }; +} + +dim3 graph_grid(BFloat16GraphShape shape, int threads) { + const uint32_t row_cap = std::max(1u, shape.block_cap / shape.batch); + return dim3(primitive_blocks(shape.vocabulary, row_cap, PrimitiveMode::radik, + threads), + shape.batch); +} +} // namespace + +uint64_t bfloat16_graph_bytes(BFloat16GraphShape shape) { + return graph_layout(shape).bytes; +} + +void begin_bfloat16_selection(BFloat16GraphShape shape, const void* input, + void* arena, uint64_t bytes, cudaStream_t stream, + uint32_t* pinned_nonfinite) { + if (!input) throw std::invalid_argument("missing BF16 selection input"); + const auto layout = graph_layout(shape); + const auto storage = bind_graph_storage(arena, bytes, layout); + const uint32_t plan_blocks = + (shape.batch + kGraphPlanThreads - 1) / kGraphPlanThreads; + CK(cudaMemsetAsync(storage.histogram, 0, layout.histogram.bytes, stream)); + init_graph_jobs<<>>( + shape, static_cast(input), storage); + if (pinned_nonfinite) { + auto* flag = + storage.histogram + uint64_t(shape.batch) * kGraphHistogramStride; + count_packed<4096, 1024, true, BFloat16, true, true> + <<>>( + {}, 0, 0, nullptr, storage.first, nullptr, flag); + CK(cudaMemcpyAsync(pinned_nonfinite, flag, sizeof(*flag), + cudaMemcpyDeviceToHost, stream)); + } else { + count_packed<4096, 1024, true, BFloat16, true> + <<>>({}, 0, 0, nullptr, + storage.first); + } + CK(cudaGetLastError()); +} + +void finish_bfloat16_selection(BFloat16GraphShape shape, void* values, + uint32_t* indices, void* arena, uint64_t bytes, + cudaStream_t stream, BFloat16GraphFork fork, + BFloat16GraphRow* rows) { + if (!values || !indices) + throw std::invalid_argument("missing BF16 selection output"); + if ((fork.stream && (!fork.ready || !fork.done || fork.ready == fork.done || + fork.stream == stream)) || + (!fork.stream && (fork.ready || fork.done))) { + throw std::invalid_argument("invalid BF16 selection fork"); + } + const auto storage = bind_graph_storage(arena, bytes, graph_layout(shape)); + const uint32_t plan_blocks = + (shape.batch + kGraphPlanThreads - 1) / kGraphPlanThreads; + const uint32_t gather_bytes = gather_shared_bytes(shape.k, true, true); + const uint32_t sort_bytes = shape.sort_limit * 2 * sizeof(uint32_t); + const GraphBuffer output{static_cast(values), indices}; + select_bin_warp<4096, true, false, BFloat16> + <<>>(nullptr, 0, nullptr, + storage.first); + plan_graph_partition<<>>( + shape, storage, output, rows); + gather_packed + <<>>( + {}, 0, 0, 0, {}, 0, {}, 0, nullptr, storage.first); + + const auto sort_stream = fork.stream ? fork.stream : stream; + if (fork.stream) { + CK(cudaEventRecord(fork.ready, stream)); + CK(cudaStreamWaitEvent(fork.stream, fork.ready, 0)); + } + sort_graph_run<<>>( + storage.first_sort); + if (fork.stream) CK(cudaEventRecord(fork.done, fork.stream)); + + count_packed<16, BLOCK, true, BFloat16, true> + <<>>({}, 0, 1, nullptr, + storage.last); + plan_graph_tail<<>>(shape, + storage); + gather_packed + <<>>( + {}, 0, 1, 0, {}, 0, {}, 0, nullptr, storage.last); + sort_graph_run<<>>(storage.last_sort); + + // Pass-one sorts write a row's prefix. Final sorts write only its tail, + // and rows that ended early never touch their potential buffer again. + if (fork.stream) CK(cudaStreamWaitEvent(stream, fork.done, 0)); + CK(cudaGetLastError()); +} + +void enqueue_bfloat16_graph(BFloat16GraphShape shape, const void* input, + void* values, uint32_t* indices, void* arena, + uint64_t bytes, cudaStream_t stream, + BFloat16GraphFork fork, BFloat16GraphRow* rows) { + begin_bfloat16_selection(shape, input, arena, bytes, stream); + finish_bfloat16_selection(shape, values, indices, arena, bytes, stream, fork, + rows); +} diff --git a/csrc/core/kernel/cuda/topk_r2sk/decode_graph.cu b/csrc/core/kernel/cuda/topk_r2sk/decode_graph.cu new file mode 100644 index 000000000..c0cf4f7f9 --- /dev/null +++ b/csrc/core/kernel/cuda/topk_r2sk/decode_graph.cu @@ -0,0 +1,205 @@ +// SPDX-License-Identifier: Apache-2.0 +#include "decode_graph.h" + +#include "core/kernel/cuda/cuda_kernel.h" +#include "r2sk/bfloat16_graph.hpp" +#include "r2sk/cuda.hpp" + +#include +#include +#include +#include + +namespace allspark::cuda { +namespace { + +constexpr uint32_t kThreads = 256; +constexpr int kMaxGraphs = 24; + +auto Arguments(const DecodeGraphArgs& a) { + return std::tie(a.logits, a.scores, a.temp_probs, a.indices, a.tokens, + a.rng_states, a.counts, a.top_p, a.temperature, a.scratch, + a.scratch_bytes, a.workspace_bytes, a.hiednn, a.stream, + a.batch, a.vocabulary, a.k); +} + +r2sk::BFloat16GraphShape Shape(const DecodeGraphArgs& a) { + return {static_cast(a.batch), static_cast(a.vocabulary), + static_cast(a.k)}; +} + +__global__ void FindNonfinite(const uint16_t* logits, uint64_t count, + uint32_t* nonfinite) { + int bad = 0; + for (uint64_t i = uint64_t(blockIdx.x) * blockDim.x + threadIdx.x; i < count; + i += uint64_t(gridDim.x) * blockDim.x) { + bad |= (logits[i] & 0x7f80u) == 0x7f80u; + } + if (__syncthreads_or(bad) && threadIdx.x == 0) atomicOr(nonfinite, 1u); +} + +void Enqueue(const DecodeGraphArgs& a, r2sk::BFloat16GraphFork fork) { + using Bf16 = hie::bfloat16; + static_assert(sizeof(Bf16) == 2 && sizeof(int) == sizeof(uint32_t)); + r2sk::enqueue_bfloat16_graph(Shape(a), a.logits, a.scores, + reinterpret_cast(a.indices), + a.scratch, a.scratch_bytes, a.stream, fork); + auto* scores = static_cast(a.scores); + TopPSoftmaxLauncher( + a.counts, scores, a.indices, static_cast(scores), a.top_p, + a.temperature, static_cast(a.temp_probs), a.scratch, + a.workspace_bytes, a.batch, a.k, true, a.hiednn, a.stream); + SampleKernelLauncher(a.tokens, a.rng_states, scores, a.indices, a.batch, + a.counts, a.k, a.stream, nullptr); + r2sk::cuda_check(cudaGetLastError(), "enqueue graph sampler"); +} + +cudaGraphExec_t Capture(const DecodeGraphArgs& a, + r2sk::BFloat16GraphFork fork) { + cudaGraph_t graph = nullptr; + r2sk::cuda_check( + cudaStreamBeginCapture(a.stream, cudaStreamCaptureModeThreadLocal), + "begin decode sampling capture"); + try { + Enqueue(a, fork); + } catch (...) { + cudaStreamEndCapture(a.stream, &graph); + if (graph) cudaGraphDestroy(graph); + throw; + } + r2sk::cuda_check(cudaStreamEndCapture(a.stream, &graph), + "end decode sampling capture"); + cudaGraphExec_t executable = nullptr; + const auto result = cudaGraphInstantiate(&executable, graph, 0); + cudaGraphDestroy(graph); + r2sk::cuda_check(result, "instantiate decode sampling graph"); + return executable; +} + +} // namespace + +struct R2skDecodeGraph::State { + explicit State(int device_id) + : device(device_id), + trace(std::getenv("AS_TRACE_R2SK_DECODE_GRAPH") != nullptr) {} + + ~State() { + if (!fork.stream && !flag && !done) return; + int previous = device; + const bool restore = + cudaGetDevice(&previous) == cudaSuccess && previous != device; + if (restore) cudaSetDevice(device); + if (prepared.logits) cudaStreamSynchronize(prepared.stream); + if (pending) cudaEventSynchronize(done); + for (auto& entry : graphs) cudaGraphExecDestroy(entry.exec); + if (done) cudaEventDestroy(done); + if (fork.ready) cudaEventDestroy(fork.ready); + if (fork.done) cudaEventDestroy(fork.done); + if (fork.stream) cudaStreamDestroy(fork.stream); + if (flag) cudaFreeHost(flag); + if (restore) cudaSetDevice(previous); + } + + void Initialize() { + if (flag) return; + r2sk::cuda_check( + cudaStreamCreateWithFlags(&fork.stream, cudaStreamNonBlocking), + "create decode graph winner stream"); + r2sk::cuda_check( + cudaEventCreateWithFlags(&fork.ready, cudaEventDisableTiming), + "create decode graph ready event"); + r2sk::cuda_check( + cudaEventCreateWithFlags(&fork.done, cudaEventDisableTiming), + "create decode graph join event"); + r2sk::cuda_check(cudaEventCreateWithFlags(&done, cudaEventDisableTiming), + "create decode graph completion event"); + r2sk::cuda_check( + cudaMallocHost(reinterpret_cast(&flag), sizeof(*flag)), + "allocate decode graph input status"); + graphs.reserve(kMaxGraphs); + } + + struct Entry { + DecodeGraphArgs args; + cudaGraphExec_t exec; + }; + + int device; + bool trace; + uint32_t* flag = nullptr; + cudaEvent_t done = nullptr; + r2sk::BFloat16GraphFork fork; + std::vector graphs; + DecodeGraphArgs prepared{}; + bool pending = false; +}; + +R2skDecodeGraph::R2skDecodeGraph(int device) + : state_(std::make_unique(device)) {} +R2skDecodeGraph::~R2skDecodeGraph() = default; + +bool R2skDecodeGraph::Prepare(const DecodeGraphArgs& a) { + auto& s = *state_; + s.prepared = {}; + if (a.batch < 1 || a.batch > 65535 || a.k < 2 || a.k > 256 || + a.vocabulary <= a.k || !a.scratch || + reinterpret_cast(a.scratch) % 256 || + a.scratch_bytes < r2sk::bfloat16_graph_bytes(Shape(a))) { + return false; + } + cudaStreamCaptureStatus status; + r2sk::cuda_check(cudaStreamIsCapturing(a.stream, &status), + "query decode sampling stream"); + if (status != cudaStreamCaptureStatusNone) return false; + s.Initialize(); + auto* flag = static_cast(a.scratch); + const uint64_t count = uint64_t(a.batch) * a.vocabulary; + const uint32_t blocks = + std::min((count + kThreads - 1) / kThreads, 256); + r2sk::cuda_check(cudaMemsetAsync(flag, 0, sizeof(*flag), a.stream), + "reset decode graph input status"); + FindNonfinite<<>>( + static_cast(a.logits), count, flag); + r2sk::cuda_check(cudaGetLastError(), "check decode graph logits"); + r2sk::cuda_check(cudaMemcpyAsync(s.flag, flag, sizeof(*flag), + cudaMemcpyDeviceToHost, a.stream), + "read decode graph input status"); + s.prepared = a; + return true; +} + +bool R2skDecodeGraph::LaunchPrepared() { + auto& s = *state_; + const auto a = s.prepared; + s.prepared = {}; + if (!a.logits || *s.flag) return false; + + auto entry = std::find_if( + s.graphs.begin(), s.graphs.end(), + [&](const auto& e) { return Arguments(e.args) == Arguments(a); }); + const bool cached = entry != s.graphs.end(); + if (!cached) { + cudaGraphExec_t executable = Capture(a, s.fork); + if (s.graphs.size() == kMaxGraphs) { + // Prepare's synchronization also completed previous uses of this cache. + cudaGraphExecDestroy(s.graphs.front().exec); + s.graphs.erase(s.graphs.begin()); + } + s.graphs.push_back({a, executable}); + entry = s.graphs.end() - 1; + } + + r2sk::cuda_check(cudaGraphLaunch(entry->exec, a.stream), + "launch decode sampler graph"); + const auto result = cudaEventRecord(s.done, a.stream); + if (result != cudaSuccess) cudaStreamSynchronize(a.stream); + r2sk::cuda_check(result, "record decode sampler completion"); + s.pending = true; + if (s.trace) { + LOG(INFO) << "R2SK_DECODE_GRAPH cached=" << cached << " batch=" << a.batch + << " k=" << a.k; + } + return true; +} + +} // namespace allspark::cuda diff --git a/csrc/core/kernel/cuda/topk_r2sk/decode_graph.h b/csrc/core/kernel/cuda/topk_r2sk/decode_graph.h new file mode 100644 index 000000000..cc8ac843c --- /dev/null +++ b/csrc/core/kernel/cuda/topk_r2sk/decode_graph.h @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +#include +#include + +#include +#include +#include + +namespace allspark::cuda { + +// Post-logits preparation and pre-token-history device buffers for one batch. +struct DecodeGraphArgs { + const void* logits; + void* scores; + void* temp_probs; + int* indices; + int64_t* tokens; + void** rng_states; + int* counts; + const float* top_p; + const float* temperature; + void* scratch; + size_t scratch_bytes; + size_t workspace_bytes; + hiednnCudaHandle_t hiednn; + cudaStream_t stream; + int batch; + int vocabulary; + int k; +}; + +class R2skDecodeGraph { + public: + explicit R2skDecodeGraph(int device); + ~R2skDecodeGraph(); + + // Enqueue a finite-input check before the caller's existing synchronization. + // Returns false for unsupported shapes, leaving the caller's buffers intact. + bool Prepare(const DecodeGraphArgs& args); + + // Call only after synchronization of Prepare. Nonfinite input falls back + // before any sampling outputs or RNG states are touched. + bool LaunchPrepared(); + + private: + struct State; + std::unique_ptr state_; +}; + +} // namespace allspark::cuda diff --git a/csrc/core/kernel/cuda/topk_r2sk/primitives.cuh b/csrc/core/kernel/cuda/topk_r2sk/primitives.cuh new file mode 100644 index 000000000..6ade72c22 --- /dev/null +++ b/csrc/core/kernel/cuda/topk_r2sk/primitives.cuh @@ -0,0 +1,293 @@ +// SPDX-License-Identifier: Apache-2.0 AND MIT +// Optimized primitive paths adapted from the ideas in RadiK's countBinEx, +// selectCandidateEx, selectBin and warpPrefixSum, pinned at +// c934b15d45655bec1cf4fdc4fcb04ba4f31511cf. +// Copyright (c) 2023-present Alibaba Inc. MIT license: LICENSE.RadiK. +// Rewritten here: bounded dual destinations, carried indices, safe scalar +// alignment peel/tail, two-level warp scan and independently selectable modes. +// Included inside r2sk's anonymous namespace, after KernelJobT is +// declared. + +// Keep four logical values per lane in both storage modes. BF16 packs are +// 8-byte aligned uint2 reads; FP32 keeps the original 16-byte float4 read. +struct FourValues { + float values[4]; +}; +template +__device__ FourValues load_four(const Value* input) { + if constexpr (std::is_same::value) { + float4 x = *reinterpret_cast(input); + return {{x.x, x.y, x.z, x.w}}; + } else { + static_assert(std::is_same::value, + "supported storage type"); + uint2 x = *reinterpret_cast(input); + return {{__uint_as_float((x.x & 0xffffu) << 16), + __uint_as_float(x.x & 0xffff0000u), + __uint_as_float((x.y & 0xffffu) << 16), + __uint_as_float(x.y & 0xffff0000u)}}; + } +} + +template +__global__ void __launch_bounds__(THREADS) + count_packed(ValueView src, uint32_t n, int pass, uint32_t* hist, + const KernelJobT* jobs = nullptr, + uint32_t* scale_unsafe = nullptr, + uint32_t* batch_nonfinite = nullptr) { + if constexpr (BATCHED) { + auto job = jobs[blockIdx.y]; + src = job.src; + n = job.n; + pass = job.pass; + hist = job.hist; + scale_unsafe = job.scale_unsafe; + } + if constexpr (GRAPH_BF16) { + if (uint64_t(blockIdx.x) * THREADS * 4 >= n) return; + } + __shared__ uint32_t local[BINS]; + float reference = + src.shift_reference && pass < 3 ? *src.shift_reference : 0.f; + for (int j = threadIdx.x; j < BINS; j += THREADS) local[j] = 0; + __syncthreads(); + bool shifted = src.shift_reference && pass < 3; + int unsafe = 0; + auto update = [&](float value) { + float key_value = shifted ? shift_value(value, reference) : value; + uint32_t bin = digit(key_value, pass); + if constexpr (GRAPH_BF16 && BINS == 16) bin >>= 8; + atomicAdd(local + bin, 1u); + if constexpr (GRAPH_BF16) { + constexpr uint32_t max_valid = + CHECK_NONFINITE ? 0x7f7fffffu : 0x7f800000u; + if (scale_unsafe && (float_bits(value) & 0x7fffffffu) > max_valid) + unsafe = 1; + } else if (scale_unsafe && + (shifted ? !shift_reversible(value, key_value, reference) + : !finite_key(value))) + unsafe = 1; + }; + auto plan = value_pack_plan(reinterpret_cast(src.v), n); + const Value* input = src.v + plan.peel; + for (uint64_t q = uint64_t(blockIdx.x) * THREADS + threadIdx.x; + q < plan.packs; q += uint64_t(gridDim.x) * THREADS) { + auto packed = load_four(input + 4 * q); + const float* values = packed.values; +#pragma unroll + for (int j = 0; j < 4; ++j) update(values[j]); + } + if (blockIdx.x == 0 && threadIdx.x < plan.peel + plan.tail) { + uint32_t t = threadIdx.x; + uint32_t j = t < plan.peel ? t : plan.tail_begin() + t - plan.peel; + update(src.v[j]); + } + if (scale_unsafe) { + int bad = __syncthreads_or(unsafe); + if (threadIdx.x == 0 && bad) { + atomicOr(scale_unsafe, 1u); + if constexpr (CHECK_NONFINITE) atomicOr(batch_nonfinite, 1u); + } + } else + __syncthreads(); + for (int j = threadIdx.x; j < BINS; j += THREADS) + if (local[j]) atomicAdd(hist + j, local[j]); +} + +template +__global__ void select_bin_warp(const uint32_t* hist, uint32_t rank, + Decision* d, + const KernelJobT* jobs = nullptr, + const uint32_t* captured_hist = nullptr, + const uint32_t* captured_count = nullptr, + const uint32_t* scale_unsafe = nullptr) { + constexpr int THREADS = BINS == 4096 ? 1024 : 256; + constexpr int ITEMS = BINS / THREADS, WARPS = THREADS / 32; + if constexpr (BATCHED) { + auto job = jobs[blockIdx.y]; + hist = job.hist; + rank = job.rank; + d = job.decision; + scale_unsafe = job.scale_unsafe; + } + __shared__ uint32_t warp_prefix[WARPS]; + uint32_t counts[ITEMS], own = 0; +#pragma unroll + for (int j = 0; j < ITEMS; ++j) { + counts[j] = hist[BINS - 1 - (threadIdx.x * ITEMS + j)]; + own += counts[j]; + } + int lane = threadIdx.x & 31, warp = threadIdx.x / 32; + uint32_t inclusive = own; +#pragma unroll + for (int delta = 1; delta < 32; delta *= 2) { + uint32_t other = __shfl_up_sync(0xffffffffu, inclusive, delta); + if (lane >= delta) inclusive += other; + } + if (lane == 31) warp_prefix[warp] = inclusive; + __syncthreads(); + if (warp == 0) { + uint32_t value = lane < WARPS ? warp_prefix[lane] : 0; +#pragma unroll + for (int delta = 1; delta < 32; delta *= 2) { + uint32_t other = __shfl_up_sync(0xffffffffu, value, delta); + if (lane >= delta) value += other; + } + if (lane < WARPS) warp_prefix[lane] = value; + } + __syncthreads(); + uint32_t before = inclusive - own + (warp ? warp_prefix[warp - 1] : 0); + if (threadIdx.x == 0) { + d->total = warp_prefix[WARPS - 1]; + d->scale_unsafe = scale_unsafe ? *scale_unsafe : 0; + if constexpr (!CAPTURE) { + d->captured = 0; + d->captured_retained = 0; + } + } + if (before < rank && rank <= before + own) { +#pragma unroll + for (int j = 0; j < ITEMS; ++j) { + if (rank <= before + counts[j]) { + d->bin = BINS - 1 - (threadIdx.x * ITEMS + j); + d->h = before; + d->B = counts[j]; + break; + } + before += counts[j]; + } + } + if constexpr (CAPTURE) { + __syncthreads(); + if (threadIdx.x == 0) { + uint32_t retained = 0; + for (int bin = d->bin; bin < BINS; ++bin) retained += captured_hist[bin]; + d->captured = *captured_count; + d->captured_retained = retained; + } + } +} + +template +struct GatherCache { + static constexpr uint32_t CAPACITY = packed_tile_values * (BUFFERED ? 2 : 1); + ValueView src; + ValueBuffer G, E; + uint32_t boundary, pass, gcap, ecap, gslots; + float reference; + float* gv; + float* ev; + uint32_t* gi; + uint32_t* ei; + uint32_t *gc, *ec, *gb, *eb, *counters; + __device__ void stage(float value, uint32_t j) { + uint32_t d = + FILTER ? ordered_key(value) + : digit(value, pass, reference, src.shift_reference != nullptr); + if (d > boundary && G.v) { + uint32_t pos = atomicAdd(gc, 1u); + gv[pos] = value; + if constexpr (INDEXED) gi[pos] = src.i ? src.i[j] : j; + } else if (d == boundary) { + uint32_t pos = atomicAdd(ec, 1u); + ev[pos] = value; + if constexpr (INDEXED) ei[pos] = src.i ? src.i[j] : j; + } + } + // Every thread executes every barrier, even in partial vector tiles. + __device__ void flush(bool force) { + __syncthreads(); + uint32_t ng = *gc, ne = *ec; + bool fg = flush_cache(ng, gslots, packed_tile_values, force || !BUFFERED); + bool fe = flush_cache(ne, CAPACITY, packed_tile_values, force || !BUFFERED); + if (threadIdx.x == 0) { + *gb = fg ? atomicAdd(counters, ng) : 0; + *eb = fe ? atomicAdd(counters + 1, ne) : 0; + } + __syncthreads(); + if (fg) + for (uint32_t t = threadIdx.x; t < ng; t += BLOCK) + if (*gb + t < gcap) { + G.v[*gb + t] = gv[t]; + if constexpr (INDEXED) G.i[*gb + t] = gi[t]; + } + if (fe) + for (uint32_t t = threadIdx.x; t < ne; t += BLOCK) + if (*eb + t < ecap) { + E.v[*eb + t] = ev[t]; + if constexpr (INDEXED) E.i[*eb + t] = ei[t]; + } + __syncthreads(); + if (threadIdx.x == 0) { + if (fg) *gc = 0; + if (fe) *ec = 0; + } + __syncthreads(); + } +}; + +template +__global__ void __launch_bounds__(BLOCK) + gather_packed(ValueView src, uint32_t n, int pass, uint32_t boundary, + ValueBuffer G, uint32_t gcap, ValueBuffer E, + uint32_t ecap, uint32_t* counters, + const KernelJobT* jobs = nullptr) { + if constexpr (BATCHED) { + auto job = jobs[blockIdx.y]; + src = job.src; + n = job.n; + pass = job.pass; + boundary = + FILTER && job.pivot.v ? ordered_key(job.pivot.v[0]) : job.boundary; + G = job.G; + gcap = job.gcap; + E = job.E; + ecap = job.ecap; + counters = job.counters; + } + if constexpr (GRAPH_BF16) { + if (uint64_t(blockIdx.x) * BLOCK * 4 >= n) return; + } + using Cache = GatherCache; + uint32_t gslots = gcap < Cache::CAPACITY ? gcap : Cache::CAPACITY; + extern __shared__ uint32_t storage[]; + float* gv = reinterpret_cast(storage); + float* ev = gv + gslots; + uint32_t* gi = storage + gslots + Cache::CAPACITY; + uint32_t* ei = gi + (INDEXED ? gslots : 0); + __shared__ uint32_t gc, ec, gb, eb; + float reference = + src.shift_reference && pass < 3 ? *src.shift_reference : 0.f; + if (threadIdx.x == 0) { + gc = 0; + ec = 0; + } + __syncthreads(); + Cache cache{src, G, E, boundary, uint32_t(pass), + gcap, ecap, gslots, reference, gv, + ev, gi, ei, &gc, &ec, + &gb, &eb, counters}; + auto plan = value_pack_plan(reinterpret_cast(src.v), n); + const Value* input = src.v + plan.peel; + for (uint64_t base = uint64_t(blockIdx.x) * BLOCK; base < plan.packs; + base += uint64_t(gridDim.x) * BLOCK) { + uint64_t q = base + threadIdx.x; + if (q < plan.packs) { + auto packed = load_four(input + 4 * q); + const float* values = packed.values; +#pragma unroll + for (int t = 0; t < 4; ++t) + cache.stage(values[t], plan.peel + uint32_t(q) * 4 + t); + } + cache.flush(false); + } + if (blockIdx.x == 0 && threadIdx.x < plan.peel + plan.tail) { + uint32_t t = threadIdx.x, + j = t < plan.peel ? t : plan.tail_begin() + t - plan.peel; + cache.stage(src.v[j], j); + } + cache.flush(true); +} diff --git a/csrc/core/kernel/cuda/topk_r2sk/r2sk.cu b/csrc/core/kernel/cuda/topk_r2sk/r2sk.cu new file mode 100644 index 000000000..2b674d5f4 --- /dev/null +++ b/csrc/core/kernel/cuda/topk_r2sk/r2sk.cu @@ -0,0 +1,1469 @@ +// SPDX-License-Identifier: Apache-2.0 AND MIT +// Histogram and staged compaction adapted from ideas in RadiK. +// Copyright (c) 2023-present Alibaba Inc. MIT license: LICENSE.RadiK. +// Kernels below are rewritten for single/batched rows, bounded dual +// destinations, scalar/packed loads, reusable allocations, and optional carried +// indices. +#include "r2sk/cuda.hpp" +#include "r2sk/bfloat16_graph.hpp" +#include "r2sk/primitive_plan.hpp" +#include "r2sk/workspace_plan.hpp" +#include +#include +#include +#include + +namespace r2sk { +void cuda_check(cudaError_t e, const char* op) { + if (e != cudaSuccess) + throw std::runtime_error(std::string(op) + ": " + cudaGetErrorString(e)); +} +#define CK(x) cuda_check((x), #x) +namespace { +constexpr int BLOCK = 256; +template +using KernelJobT = detail::KernelJobT; +#include "primitives.cuh" +template +__device__ void put(ValueView src, uint32_t j, ValueBuffer dst, + uint32_t pos) { + dst.v[pos] = src.v[j]; + if (INDEXED) dst.i[pos] = src.i ? src.i[j] : j; +} +template +__global__ void count_bin(ValueView src, uint32_t n, int pass, + uint32_t* hist, + const KernelJobT* jobs = nullptr, + uint32_t* scale_unsafe = nullptr) { + if constexpr (BATCHED) { + auto job = jobs[blockIdx.y]; + src = job.src; + n = job.n; + pass = job.pass; + hist = job.hist; + scale_unsafe = job.scale_unsafe; + } + __shared__ uint32_t local[BINS]; + float reference = + src.shift_reference && pass < 3 ? *src.shift_reference : 0.f; + for (int j = threadIdx.x; j < BINS; j += BLOCK) local[j] = 0; + __syncthreads(); + int unsafe = 0; + bool shifted = src.shift_reference && pass < 3; + for (uint64_t j = uint64_t(blockIdx.x) * BLOCK + threadIdx.x; j < n; + j += uint64_t(gridDim.x) * BLOCK) { + float value = src.v[j], + key_value = shifted ? shift_value(value, reference) : value; + atomicAdd(local + digit(key_value, pass), 1u); + if (scale_unsafe && + (shifted ? !shift_reversible(value, key_value, reference) + : !finite_key(value))) + unsafe = 1; + } + if (scale_unsafe) { + int bad = __syncthreads_or(unsafe); + if (threadIdx.x == 0 && bad) atomicOr(scale_unsafe, 1u); + } else + __syncthreads(); + for (int j = threadIdx.x; j < BINS; j += BLOCK) + if (local[j]) atomicAdd(hist + j, local[j]); +} +// Optional capture retains upper bins of each disjoint 256-value tile while +// every loaded float is still in a register. Logical counts include overflow; +// no truncated capture can pass the subsequent coverage check. +template +__global__ void count_capture(ValueView src, uint32_t n, int pass, + uint32_t* hist, uint32_t* captured_hist, + ValueBuffer captured, uint32_t capacity, + uint32_t* total, uint32_t local_rank, + uint32_t* scale_unsafe = nullptr) { + __shared__ uint32_t local[BINS], warp_max[BLOCK / 32], nibble[16]; + __shared__ uint32_t cutoff, residual, accepted, write_base; + __shared__ float values[BLOCK]; + __shared__ uint32_t indices[INDEXED ? BLOCK : 1], digits[BLOCK]; + float reference = + src.shift_reference && pass < 3 ? *src.shift_reference : 0.f; + for (int j = threadIdx.x; j < BINS; j += BLOCK) local[j] = 0; + __syncthreads(); + int unsafe = 0; + bool shifted = src.shift_reference && pass < 3; + for (uint64_t base = uint64_t(blockIdx.x) * BLOCK; base < n; + base += uint64_t(gridDim.x) * BLOCK) { + uint64_t j = base + threadIdx.x; + bool valid = j < n; + float value = valid ? src.v[j] : 0.f, + key_value = shifted ? shift_value(value, reference) : value; + uint32_t d = valid ? digit(key_value, pass) : 0; + if (valid && scale_unsafe && !shift_reversible(value, key_value, reference)) + unsafe = 1; + if (valid) atomicAdd(local + d, 1u); + if (local_rank == 1) { + uint32_t maximum = d; + for (int delta = 16; delta; delta >>= 1) { + uint32_t other = __shfl_down_sync(0xffffffffu, maximum, delta); + maximum = maximum > other ? maximum : other; + } + if ((threadIdx.x & 31) == 0) warp_max[threadIdx.x / 32] = maximum; + __syncthreads(); + if (threadIdx.x == 0) { + cutoff = 0; + for (int w = 0; w < BLOCK / 32; ++w) + cutoff = cutoff > warp_max[w] ? cutoff : warp_max[w]; + } + __syncthreads(); + } else { + // A small radix select on DIGITS, not values. Three four-bit + // rounds (two for pass 3) find the q-th digit, preserving bin ties. + if (threadIdx.x == 0) { + cutoff = 0; + uint32_t remaining = uint32_t(n - base); + residual = local_rank < remaining ? local_rank : remaining; + } + __syncthreads(); + for (int shift = digit_width(pass) - 4; shift >= 0; shift -= 4) { + if (threadIdx.x < 16) nibble[threadIdx.x] = 0; + __syncthreads(); + if (valid && (d >> (shift + 4)) == cutoff) + atomicAdd(nibble + ((d >> shift) & 15u), 1u); + __syncthreads(); + if (threadIdx.x == 0) { + for (int bin = 15; bin >= 0; --bin) { + if (residual <= nibble[bin]) { + cutoff = (cutoff << 4) | uint32_t(bin); + break; + } + residual -= nibble[bin]; + } + } + __syncthreads(); + } + } + if (threadIdx.x == 0) accepted = 0; + __syncthreads(); + if (valid && d >= cutoff) { + uint32_t position = atomicAdd(&accepted, 1u); + values[position] = value; + digits[position] = d; + if (INDEXED) indices[position] = src.i ? src.i[j] : uint32_t(j); + } + __syncthreads(); + if (threadIdx.x == 0) { + write_base = atomicAdd(total, accepted); + if (local_rank == 1) atomicAdd(captured_hist + cutoff, accepted); + } + __syncthreads(); + uint32_t t = threadIdx.x; + if (t < accepted) { + if (local_rank != 1) atomicAdd(captured_hist + digits[t], 1u); + if (write_base + t < capacity) { + captured.v[write_base + t] = values[t]; + if (INDEXED) captured.i[write_base + t] = indices[t]; + } + } + __syncthreads(); // staging and cutoff can be reused only after every + // reader finishes + } + if (scale_unsafe) { + int bad = __syncthreads_or(unsafe); + if (threadIdx.x == 0 && bad) atomicOr(scale_unsafe, 1u); + } + for (int j = threadIdx.x; j < BINS; j += BLOCK) + if (local[j]) atomicAdd(hist + j, local[j]); +} +// Reversed inclusive scan: scan[i] counts bins >= BINS-1-i. +// All threads participate in every barrier, including partial input tiles. +template +__global__ void select_bin(const uint32_t* hist, uint32_t rank, Decision* d, + const KernelJobT* jobs = nullptr, + const uint32_t* captured_hist = nullptr, + const uint32_t* captured_count = nullptr, + const uint32_t* scale_unsafe = nullptr) { + if constexpr (BATCHED) { + auto job = jobs[blockIdx.y]; + hist = job.hist; + rank = job.rank; + d = job.decision; + scale_unsafe = job.scale_unsafe; + } + __shared__ uint32_t scan[BINS]; + for (int j = threadIdx.x; j < BINS; j += BLOCK) scan[j] = hist[BINS - 1 - j]; + __syncthreads(); + for (int step = 1; step < BINS; step <<= 1) { + uint32_t tmp[BINS / BLOCK]; +#pragma unroll + for (int t = 0; t < BINS / BLOCK; ++t) { + int j = threadIdx.x + t * BLOCK; + tmp[t] = scan[j] + (j >= step ? scan[j - step] : 0u); + } + __syncthreads(); +#pragma unroll + for (int t = 0; t < BINS / BLOCK; ++t) + scan[threadIdx.x + t * BLOCK] = tmp[t]; + __syncthreads(); + } + if (threadIdx.x == 0) { + d->total = scan[BINS - 1]; + d->scale_unsafe = scale_unsafe ? *scale_unsafe : 0; + if constexpr (!CAPTURE) { + d->captured = 0; + d->captured_retained = 0; + } + } + for (int j = threadIdx.x; j < BINS; j += BLOCK) { + uint32_t before = j ? scan[j - 1] : 0; + if (before < rank && rank <= scan[j]) { + d->bin = BINS - 1 - j; + d->h = before; + d->B = scan[j] - before; + } + } + if constexpr (CAPTURE) { + __syncthreads(); + if (threadIdx.x == 0) { + uint32_t retained = 0; + for (int bin = d->bin; bin < BINS; ++bin) retained += captured_hist[bin]; + d->captured = *captured_count; + d->captured_retained = retained; + } + } +} +// Two shared staging arrays. Each tile reserves at most one global range per +// destination; no global atomic per accepted value. Reservations count ALL E, +// but writes are bounded by ecap (terminal ties only). Null G discards winners. +template +__global__ void gather(ValueView src, uint32_t n, int pass, + uint32_t boundary, ValueBuffer G, uint32_t gcap, + ValueBuffer E, uint32_t ecap, uint32_t* counters, + const KernelJobT* jobs = nullptr) { + if constexpr (BATCHED) { + auto job = jobs[blockIdx.y]; + src = job.src; + n = job.n; + pass = job.pass; + boundary = + FILTER && job.pivot.v ? ordered_key(job.pivot.v[0]) : job.boundary; + G = job.G; + gcap = job.gcap; + E = job.E; + ecap = job.ecap; + counters = job.counters; + } + __shared__ float gv[BLOCK], ev[BLOCK]; + __shared__ uint32_t gi[INDEXED ? BLOCK : 1], ei[INDEXED ? BLOCK : 1]; + __shared__ uint32_t gc, ec, gb, eb; + float reference = + src.shift_reference && pass < 3 ? *src.shift_reference : 0.f; + for (uint64_t base = uint64_t(blockIdx.x) * BLOCK; base < n; + base += uint64_t(gridDim.x) * BLOCK) { + if (threadIdx.x == 0) { + gc = 0; + ec = 0; + } + __syncthreads(); + uint64_t j = base + threadIdx.x; + if (j < n) { + float v = src.v[j]; + uint32_t d = + FILTER ? ordered_key(v) + : digit(v, pass, reference, src.shift_reference != nullptr); + if (d > boundary && G.v) { + uint32_t pos = atomicAdd(&gc, 1u); + gv[pos] = v; + if (INDEXED) gi[pos] = src.i ? src.i[j] : uint32_t(j); + } else if (d == boundary) { + uint32_t pos = atomicAdd(&ec, 1u); + ev[pos] = v; + if (INDEXED) ei[pos] = src.i ? src.i[j] : uint32_t(j); + } + } + __syncthreads(); + if (threadIdx.x == 0) { + gb = gc ? atomicAdd(counters, gc) : 0; + eb = ec ? atomicAdd(counters + 1, ec) : 0; + } + __syncthreads(); + uint32_t t = threadIdx.x; + if (t < gc && gb + t < gcap) { + G.v[gb + t] = gv[t]; + if (INDEXED) G.i[gb + t] = gi[t]; + } + if (t < ec && eb + t < ecap) { + E.v[eb + t] = ev[t]; + if (INDEXED) E.i[eb + t] = ei[t]; + } + __syncthreads(); // staging may be reused by the next tile + } +} +// Host launch helpers are shared by the single-array and batched backends. +int histogram_threads(PrimitiveMode mode, int pass) { + return mode == PrimitiveMode::radik && pass == 0 ? 1024 : BLOCK; +} +bool buffered_mode(PrimitiveMode mode) { + return mode >= PrimitiveMode::buffered; +} +uint32_t primitive_blocks(uint32_t n, uint32_t cap, PrimitiveMode mode, + int threads = BLOCK) { + uint32_t tile = uint32_t(threads) * (mode == PrimitiveMode::scalar ? 1u : 4u); + return std::min(cap, std::max(1u, (n + tile - 1) / tile)); +} +template +void launch_histogram(ValueView src, uint32_t n, int pass, + uint32_t* hist, const KernelJobT* jobs, dim3 shape, + PrimitiveMode mode, cudaStream_t stream, + uint32_t* scale_unsafe = nullptr) { + if (mode == PrimitiveMode::scalar) { + if (digit_width(pass) == 8) + count_bin<256, BATCHED, Value> + <<>>(src, n, pass, hist, jobs, scale_unsafe); + else + count_bin<4096, BATCHED, Value> + <<>>(src, n, pass, hist, jobs, scale_unsafe); + } else if (histogram_threads(mode, pass) == 1024) { + count_packed<4096, 1024, BATCHED, Value> + <<>>(src, n, pass, hist, jobs, scale_unsafe); + } else { + if (digit_width(pass) == 8) + count_packed<256, BLOCK, BATCHED, Value> + <<>>(src, n, pass, hist, jobs, scale_unsafe); + else + count_packed<4096, BLOCK, BATCHED, Value> + <<>>(src, n, pass, hist, jobs, scale_unsafe); + } +} +template +void launch_selection(const uint32_t* hist, uint32_t rank, Decision* d, + const KernelJobT* jobs, int pass, dim3 shape, + PrimitiveMode mode, cudaStream_t stream, + const uint32_t* captured_hist = nullptr, + const uint32_t* captured_count = nullptr, + const uint32_t* scale_unsafe = nullptr) { + if (mode >= PrimitiveMode::scan) { + if (digit_width(pass) == 8) + select_bin_warp<256, BATCHED, CAPTURE, Value><<>>( + hist, rank, d, jobs, captured_hist, captured_count, scale_unsafe); + else + select_bin_warp<4096, BATCHED, CAPTURE, Value> + <<>>(hist, rank, d, jobs, captured_hist, + captured_count, scale_unsafe); + } else { + if (digit_width(pass) == 8) + select_bin<256, BATCHED, CAPTURE, Value><<>>( + hist, rank, d, jobs, captured_hist, captured_count, scale_unsafe); + else + select_bin<4096, BATCHED, CAPTURE, Value><<>>( + hist, rank, d, jobs, captured_hist, captured_count, scale_unsafe); + } +} +template +void launch_partition(ValueView src, uint32_t n, int pass, uint32_t bin, + ValueBuffer G, uint32_t gc, ValueBuffer E, + uint32_t ec, uint32_t* counters, + const KernelJobT* jobs, dim3 shape, + uint32_t max_gcap, PrimitiveMode mode, + cudaStream_t stream) { + if (mode == PrimitiveMode::scalar) { + gather<<>>( + src, n, pass, bin, G, gc, E, ec, counters, jobs); + } else { + uint32_t bytes = + gather_shared_bytes(max_gcap, INDEXED, buffered_mode(mode)); + if (buffered_mode(mode)) + gather_packed + <<>>(src, n, pass, bin, G, gc, E, ec, + counters, jobs); + else + gather_packed + <<>>(src, n, pass, bin, G, gc, E, ec, + counters, jobs); + } +} +template +__global__ void copy_items(ValueView src, uint32_t n, + ValueBuffer dst, + const KernelJobT* jobs = nullptr) { + if constexpr (BATCHED) { + auto job = jobs[blockIdx.y]; + src = job.src; + n = job.n; + dst = job.G; + } + for (uint64_t j = uint64_t(blockIdx.x) * BLOCK + threadIdx.x; j < n; + j += uint64_t(gridDim.x) * BLOCK) + put(src, uint32_t(j), dst, uint32_t(j)); +} +template +__global__ void sort_tiles(ValueBuffer data, uint32_t n, uint32_t tile, + const KernelJobT* jobs = nullptr) { + if constexpr (BATCHED) { + auto job = jobs[blockIdx.y]; + data = job.G; + n = job.n; + tile = job.tile; + } + extern __shared__ uint32_t smem[]; + float* v = reinterpret_cast(smem); + uint32_t* ix = smem + tile; + uint64_t base = uint64_t(blockIdx.x) * tile; + if (base >= n) return; // uniform CTA exit, before any barrier + for (uint32_t t = threadIdx.x; t < tile; t += BLOCK) { + bool valid = base + t < n; + v[t] = valid ? data.v[base + t] : -CUDART_INF_F; + if (INDEXED) ix[t] = valid ? data.i[base + t] : 0xffffffffu; + } + __syncthreads(); + for (uint32_t size = 2; size <= tile; size <<= 1) + for (uint32_t stride = size >> 1; stride; stride >>= 1) { + for (uint32_t t = threadIdx.x; t < tile; t += BLOCK) { + uint32_t other = t ^ stride; + if (other > t) { + bool descending = (t & size) == 0; + bool swap = descending ? v[t] < v[other] : v[t] > v[other]; + if (swap) { + float tmp = v[t]; + v[t] = v[other]; + v[other] = tmp; + if (INDEXED) { + uint32_t z = ix[t]; + ix[t] = ix[other]; + ix[other] = z; + } + } + } + } + __syncthreads(); + } + for (uint32_t t = threadIdx.x; t < tile; t += BLOCK) + if (base + t < n) { + data.v[base + t] = v[t]; + if (INDEXED) data.i[base + t] = ix[t]; + } +} +// Correct general fallback: parallel binary-rank merge of adjacent sorted runs. +// Equal values from the left run precede the right run, yielding unique ranks. +template +__global__ void merge_runs(ValueView src, ValueBuffer dst, + uint32_t n, uint32_t width, + const KernelJobT* jobs = nullptr) { + if constexpr (BATCHED) { + auto job = jobs[blockIdx.y]; + src = job.src; + dst = job.G; + n = job.n; + width = job.width; + } + for (uint64_t pos = uint64_t(blockIdx.x) * BLOCK + threadIdx.x; pos < n; + pos += uint64_t(gridDim.x) * BLOCK) { + uint64_t base = (pos / (2ull * width)) * (2ull * width); + uint64_t mid = base + width < n ? base + width : n; + uint64_t end = base + 2ull * width < n ? base + 2ull * width : n; + bool left = pos < mid; + uint64_t lo = left ? mid : base, hi = left ? end : mid; + uint64_t other_base = lo; + float value = src.v[pos]; + while (lo < hi) { + uint64_t m = (lo + hi) / 2; + bool before = left ? src.v[m] > value : src.v[m] >= value; + if (before) + lo = m + 1; + else + hi = m; + } + uint64_t rank = (pos - (left ? base : mid)) + (lo - other_base); + put(src, uint32_t(pos), dst, uint32_t(base + rank)); + } +} +struct Allocation { + void* ptr = nullptr; + bool owned = true; + ~Allocation() { + if (ptr && owned) cudaFree(ptr); + } + void allocate(size_t bytes) { + if (bytes) CK(cudaMalloc(&ptr, bytes)); + } + void borrow(void* arena, detail::ArenaRegion region) { + if (ptr && owned) + throw std::logic_error("cannot replace owned storage with arena storage"); + owned = false; + ptr = region.bytes ? static_cast(arena) + region.offset : nullptr; + } +}; +template +struct DeviceBufferT { + Allocation values, indices; + void allocate(uint64_t n, bool indexed) { + values.allocate(uint64_t(sizeof(Value)) * n); + if (indexed) indices.allocate(4ull * n); + } + ValueBuffer get() { + return {static_cast(values.ptr), + static_cast(indices.ptr)}; + } +}; +using KernelJob = KernelJobT; +using DeviceBuffer = DeviceBufferT; +} // namespace + +struct Workspace::Impl { + uint32_t max_n, max_k, max_limit; + bool indexed, run_resources, capture_resources; + DeviceBuffer c[2], w, p, scratch, winner_scratch; + Allocation hist, meta, counters, captured_hist; + Decision* host = nullptr; + uint32_t* host_counts = nullptr; + cudaEvent_t start = nullptr, end = nullptr; + cudaEvent_t ready[6]{}, done[6]{}, winner_start = nullptr, + winner_end = nullptr; + cudaStream_t winner_stream = nullptr; + uint32_t run_slot = 0; + int pending_winner = -1; + cudaStream_t stream = nullptr; + Options options; + Stats* stats = nullptr; + Impl(uint32_t n, uint32_t k, uint32_t limit, bool idx, bool enable_runs, + bool enable_capture) + : max_n(n), + max_k(k), + max_limit(limit), + indexed(idx), + run_resources(enable_runs), + capture_resources(enable_capture) { + Options o; + o.sort_limit = limit; + validate(n, k, o); + try { + int dev = 0; + cudaDeviceProp prop{}; + CK(cudaGetDevice(&dev)); + CK(cudaGetDeviceProperties(&prop, dev)); + if (prop.sharedMemPerBlock < 4096u * 4u * (idx ? 2u : 1u)) + throw std::runtime_error("insufficient small-sort shared memory"); + for (auto& b : c) b.allocate(n, idx); + w.allocate(k, idx); + p.allocate(std::max(k, limit), idx); + scratch.allocate(std::max(k, limit), idx); + hist.allocate(4097 * 4); + meta.allocate(sizeof(Decision)); + counters.allocate(2 * 4); + if (capture_resources) captured_hist.allocate(4096 * 4); + CK(cudaMallocHost(reinterpret_cast(&host), + sizeof(Decision) + 2 * 4)); + host_counts = reinterpret_cast(host + 1); + CK(cudaEventCreate(&start)); + CK(cudaEventCreate(&end)); + if (run_resources) { + winner_scratch.allocate(k, idx); + CK(cudaStreamCreateWithFlags(&winner_stream, cudaStreamNonBlocking)); + for (uint32_t j = 0; j < 6; ++j) { + CK(cudaEventCreateWithFlags(&ready[j], cudaEventDisableTiming)); + CK(cudaEventCreateWithFlags(&done[j], cudaEventDisableTiming)); + } + CK(cudaEventCreate(&winner_start)); + CK(cudaEventCreate(&winner_end)); + } + } catch (...) { + cleanup(); + throw; + } + } + void cleanup() { + if (winner_stream) { + cudaStreamSynchronize(winner_stream); + cudaStreamDestroy(winner_stream); + } + for (uint32_t j = 0; j < 6; ++j) { + if (ready[j]) cudaEventDestroy(ready[j]); + if (done[j]) cudaEventDestroy(done[j]); + } + if (winner_start) cudaEventDestroy(winner_start); + if (winner_end) cudaEventDestroy(winner_end); + if (start) cudaEventDestroy(start); + if (end) cudaEventDestroy(end); + if (host) cudaFreeHost(host); + } + ~Impl() { cleanup(); } + uint32_t blocks(uint32_t n) const { + return std::min(options.block_cap, (n + BLOCK - 1) / BLOCK); + } + template + void stage(const char* label, F f) { + if (options.instrument) CK(cudaEventRecord(start, stream)); + f(); + CK(cudaGetLastError()); + if (options.instrument) { + CK(cudaEventRecord(end, stream)); + CK(cudaEventSynchronize(end)); + float ms; + CK(cudaEventElapsedTime(&ms, start, end)); + stats->stages.push_back({label, ms}); + } + } + void begin(Options o, Stats* s) { + options = o; + stats = s; + run_slot = 0; + pending_winner = -1; + } + Buffer candidate(int j) { return c[j].get(); } + Buffer winners() { return w.get(); } + Buffer potential() { return p.get(); } + uint32_t* scale_flag(View src, int pass) { + return src.shift_reference && pass == 2 + ? static_cast(hist.ptr) + 4096 + : nullptr; + } + Decision histogram(View src, uint32_t n, int pass, uint32_t rank) { + auto unsafe = scale_flag(src, pass); + stage("histogram", [&] { + CK(cudaMemsetAsync(hist.ptr, 0, (1u << digit_width(pass)) * 4, stream)); + if (unsafe) CK(cudaMemsetAsync(unsafe, 0, 4, stream)); + auto mode = options.primitives; + dim3 shape(primitive_blocks(n, options.block_cap, mode, + histogram_threads(mode, pass))); + launch_histogram(src, n, pass, + static_cast(hist.ptr), nullptr, + shape, mode, stream, unsafe); + }); + stage("select_and_metadata", [&] { + launch_selection( + static_cast(hist.ptr), rank, + static_cast(meta.ptr), nullptr, pass, dim3(1), + options.primitives, stream, nullptr, nullptr, unsafe); + CK(cudaMemcpyAsync(host, meta.ptr, sizeof(Decision), + cudaMemcpyDeviceToHost, stream)); + CK(cudaStreamSynchronize(stream)); + }); + return *host; + } + template + void capture_kernel(View src, uint32_t n, int pass, Buffer dst, + uint32_t capacity, uint32_t q) { + if (indexed) + count_capture<<>>( + src, n, pass, static_cast(hist.ptr), + static_cast(captured_hist.ptr), dst, capacity, + static_cast(counters.ptr), q, scale_flag(src, pass)); + else + count_capture<<>>( + src, n, pass, static_cast(hist.ptr), + static_cast(captured_hist.ptr), dst, capacity, + static_cast(counters.ptr), q, scale_flag(src, pass)); + } + Decision capture_histogram(View src, uint32_t n, int pass, uint32_t rank, + Buffer dst, uint32_t capacity, uint32_t q) { + if (src.v == dst.v) + throw std::logic_error("capture source aliases destination"); + if (options.debug && capacity < max_n) { + CK(cudaMemsetAsync(dst.v + capacity, 0xa5, 4, stream)); + if (indexed) CK(cudaMemsetAsync(dst.i + capacity, 0xa5, 4, stream)); + } + stage("histogram_capture", [&] { + size_t bytes = (1u << digit_width(pass)) * 4; + CK(cudaMemsetAsync(hist.ptr, 0, bytes, stream)); + CK(cudaMemsetAsync(captured_hist.ptr, 0, bytes, stream)); + if (auto unsafe = scale_flag(src, pass)) + CK(cudaMemsetAsync(unsafe, 0, 4, stream)); + CK(cudaMemsetAsync(counters.ptr, 0, 8, stream)); + if (digit_width(pass) == 8) + capture_kernel<256>(src, n, pass, dst, capacity, q); + else + capture_kernel<4096>(src, n, pass, dst, capacity, q); + }); + stage("select_capture_and_metadata", [&] { + launch_selection( + static_cast(hist.ptr), rank, + static_cast(meta.ptr), nullptr, pass, dim3(1), + options.primitives, stream, static_cast(captured_hist.ptr), + static_cast(counters.ptr), scale_flag(src, pass)); + CK(cudaMemcpyAsync(host, meta.ptr, sizeof(Decision), + cudaMemcpyDeviceToHost, stream)); + CK(cudaStreamSynchronize(stream)); + }); + if (options.debug && capacity < max_n) { + uint32_t guard = 0, index_guard = 0xa5a5a5a5; + CK(cudaMemcpyAsync(&guard, dst.v + capacity, 4, cudaMemcpyDeviceToHost, + stream)); + if (indexed) + CK(cudaMemcpyAsync(&index_guard, dst.i + capacity, 4, + cudaMemcpyDeviceToHost, stream)); + CK(cudaStreamSynchronize(stream)); + if (guard != 0xa5a5a5a5 || index_guard != 0xa5a5a5a5) + throw std::logic_error("capture write exceeded capacity"); + } + return *host; + } + template + void launch_gather(View src, uint32_t n, int pass, uint32_t bin, Buffer G, + uint32_t gc, Buffer E, uint32_t ec) { + CK(cudaMemsetAsync(counters.ptr, 0, 8, stream)); + // Pivot-only reference candidates do not need indices: its final input + // filter derives them. Winner-preserving paths must carry them. + dim3 shape(primitive_blocks(n, options.block_cap, options.primitives)); + if (indexed && (FILTER || options.method != Method::reference)) + launch_partition( + src, n, pass, bin, G, gc, E, ec, static_cast(counters.ptr), + nullptr, shape, gc, options.primitives, stream); + else + launch_partition( + src, n, pass, bin, G, gc, E, ec, static_cast(counters.ptr), + nullptr, shape, gc, options.primitives, stream); + } + void check_counts(uint32_t g, uint32_t e) { + if (!options.debug) return; + CK(cudaMemcpyAsync(host_counts, counters.ptr, 8, cudaMemcpyDeviceToHost, + stream)); + CK(cudaStreamSynchronize(stream)); + if (host_counts[0] != g || host_counts[1] != e) + throw std::logic_error("GPU gather count invariant"); + } + void partition(View src, uint32_t n, int pass, int bin, Buffer G, uint32_t gc, + Buffer E, uint32_t ec, uint32_t eg, uint32_t ee) { + stage("partition", [&] { + launch_gather(src, n, pass, uint32_t(bin), G, gc, E, ec); + }); + check_counts(G.v ? eg : 0, ee); + } + void filter(View src, uint32_t n, uint32_t pivot, uint32_t greater, + uint32_t ties, Buffer dst) { + stage("original_filter", [&] { + launch_gather(src, n, 0, pivot, dst, greater, offset(dst, greater), + ties); + }); + // Equal count can exceed the number required. Check G and E's lower bound. + if (options.debug) { + CK(cudaMemcpyAsync(host_counts, counters.ptr, 8, cudaMemcpyDeviceToHost, + stream)); + CK(cudaStreamSynchronize(stream)); + if (host_counts[0] != greater || host_counts[1] < ties) + throw std::logic_error("GPU filter invariant"); + } + } + void launch_copy(View src, uint32_t n, Buffer dst, cudaStream_t target) { + if (indexed) + copy_items<<>>(src, n, dst); + else + copy_items<<>>(src, n, dst); + } + void copy(View src, uint32_t n, Buffer dst) { + if (!n) return; + stage("copy", [&] { launch_copy(src, n, dst, stream); }); + } + uint32_t first_key(View src) { + float value; + stage("pivot_metadata", [&] { + CK(cudaMemcpyAsync(&value, src.v, 4, cudaMemcpyDeviceToHost, stream)); + CK(cudaStreamSynchronize(stream)); + }); + return ordered_key(value); + } + Buffer sort_buffer(Buffer src, uint32_t n, Buffer dst, cudaStream_t target) { + uint32_t tile = std::min(4096u, padded(n)); + uint32_t grid = (n + tile - 1) / tile; + size_t smem = tile * 4 * (indexed ? 2 : 1); + if (indexed) + sort_tiles<<>>(src, n, tile); + else + sort_tiles<<>>(src, n, tile); + CK(cudaGetLastError()); + for (uint64_t width = tile; width < n; width *= 2) { + if (indexed) + merge_runs + <<>>(src, dst, n, uint32_t(width)); + else + merge_runs + <<>>(src, dst, n, uint32_t(width)); + CK(cudaGetLastError()); + std::swap(src, dst); + } + return src; + } + void sort(Buffer src, uint32_t n, Buffer out, uint32_t k) { + stage("sort", [&] { src = sort_buffer(src, n, scratch.get(), stream); }); + copy(src, k, out); + } + void sort_winner_run(uint32_t base, uint32_t n) { + if (n < 2) + return; // one occurrence is already sorted; its write stays on the main + // stream + if (!run_resources || run_slot >= 6) + throw std::logic_error("winner-run workspace capacity"); + cudaStream_t target = + options.winner_sort == WinnerSort::overlap ? winner_stream : stream; + uint32_t slot = run_slot++; + if (options.winner_sort == WinnerSort::overlap) { + // G/E are produced together. Only after this dependency is satisfied + // may sorting read G; future E work has no dependency on the sort. + CK(cudaEventRecord(ready[slot], stream)); + CK(cudaStreamWaitEvent(target, ready[slot], 0)); + } + if (options.instrument) CK(cudaEventRecord(winner_start, target)); + Buffer region = offset(winners(), base); + Buffer sorted = sort_buffer(region, n, winner_scratch.get(), target); + if (sorted.v != region.v) launch_copy(sorted, n, region, target); + CK(cudaGetLastError()); + if (options.instrument) { + CK(cudaEventRecord(winner_end, target)); + CK(cudaEventSynchronize(winner_end)); + float ms; + CK(cudaEventElapsedTime(&ms, winner_start, winner_end)); + stats->stages.push_back({"winner_run_sort", ms}); + } + if (options.winner_sort == WinnerSort::overlap) { + CK(cudaEventRecord(done[slot], target)); + pending_winner = int(slot); + } + } + void join_winners() { + if (pending_winner >= 0) + stage("winner_join", + [&] { CK(cudaStreamWaitEvent(stream, done[pending_winner], 0)); }); + } + std::vector values(View src, uint32_t n) { + std::vector x(n); + if (n) + CK(cudaMemcpyAsync(x.data(), src.v, 4ull * n, cudaMemcpyDeviceToHost, + stream)); + CK(cudaStreamSynchronize(stream)); + return x; + } + void audit(View original, uint32_t n, View C, uint32_t count, uint32_t wn, + uint32_t r, uint32_t k, uint32_t better, Method method) { + auto top = [](std::vector x, uint32_t length) { + if (length < x.size()) + std::nth_element(x.begin(), x.begin() + length, x.end(), + std::greater()); + x.resize(length); + std::sort(x.begin(), x.end(), std::greater()); + return x; + }; + if (!r || r > count) throw std::logic_error("debug residual bounds"); + auto expected = top(values(original, n), k), + remaining = top(values(C, count), r); + if (method == Method::reference) { + if (better + r != k || !std::equal(remaining.begin(), remaining.end(), + expected.begin() + better)) + throw std::logic_error("debug reference boundary invariant"); + } else { + auto saved = values(winners(), wn); + if (options.winner_sort != WinnerSort::deferred && + !std::is_sorted(saved.begin(), saved.end(), std::greater())) + throw std::logic_error("debug sorted winner-prefix invariant"); + remaining.insert(remaining.end(), saved.begin(), saved.end()); + std::sort(remaining.begin(), remaining.end(), std::greater()); + if (wn + r != k || remaining != expected) + throw std::logic_error("debug W + top-r(C) invariant"); + } + } +}; +Workspace::Workspace(uint32_t n, uint32_t k, uint32_t limit, bool idx, + bool enable_runs, bool enable_capture) + : impl_(new Impl(n, k, limit, idx, enable_runs, enable_capture)) {} +Workspace::~Workspace() = default; +uint64_t Workspace::device_bytes() const { + auto& b = *impl_; + uint64_t factor = b.indexed ? 8 : 4; + return factor * + (2ull * b.max_n + b.max_k + 2ull * std::max(b.max_k, b.max_limit) + + (b.run_resources ? b.max_k : 0)) + + 4096 * 4 * (b.capture_resources ? 2 : 1) + 4 + sizeof(Decision) + 8; +} +uint64_t Workspace::pinned_bytes() const { return sizeof(Decision) + 8; } +Stats topk(const float* input, uint32_t n, uint32_t k, float* output, + uint32_t* indices, Workspace& w, Options o, cudaStream_t stream) { + validate(n, k, o); + auto& b = *w.impl_; + if (!input || !output || input == output || + b.indexed != (indices != nullptr) || n > b.max_n || k > b.max_k || + o.sort_limit > b.max_limit || + (o.winner_sort != WinnerSort::deferred && !b.run_resources) || + (o.capture_rank && !b.capture_resources)) + throw std::invalid_argument( + "pointer, indexed mode, or workspace capacity mismatch"); + b.stream = stream; + return run(b, {input, nullptr}, n, k, {output, indices}, o); +} + +template +struct BatchBackend { + using View = ValueView; + using Buffer = ValueBuffer; + using KernelJob = KernelJobT; + using DeviceBuffer = DeviceBufferT; + using HistJob = HistJobT; + using CopyJob = CopyJobT; + using PartitionJob = PartitionJobT; + using FilterJob = FilterJobT; + using SortJob = SortJobT; + + // Each upload has a distinct slot until stream completion. Reusing one + // pinned descriptor array between asynchronous copies would race the DMA. + // At most six rounds, each with <=19 merge levels (INT_MAX / 4096), + // on each of the main and winner streams, plus uploads/copies/filters. + // Distinct slots keep both pinned DMA sources and device descriptors live + // until the caller's main-stream completion (which joins the winner stream). + static constexpr uint32_t MAX_SLOTS = 512; + uint32_t max_batch, max_n, max_k, max_limit, slot = 0, descriptor_slots = 0; + bool indexed, run_resources, borrowed = false; + detail::BatchArenaLayout arena_layout{}; + DeviceBuffer c[2], w, p, scratch, winner_scratch; + Allocation histogram_data, metadata, counter_data, job_data; + KernelJob* host_jobs = nullptr; + Decision* host_meta = nullptr; + uint32_t* host_counts = nullptr; + cudaEvent_t start = nullptr, end = nullptr; + cudaEvent_t ready[6]{}, done[6]{}; + cudaStream_t winner_stream = nullptr; + uint32_t run_slot = 0; + int pending_winner = -1; + cudaStream_t stream = nullptr; + Options options; + BatchStats* stats = nullptr; + BatchBackend(uint32_t batch, uint32_t n, uint32_t k, uint32_t limit, bool idx, + bool runs, void* arena = nullptr, uint64_t arena_bytes = 0) + : max_batch(batch), + max_n(n), + max_k(k), + max_limit(limit), + indexed(idx), + run_resources(runs), + borrowed(arena != nullptr) { + if (!batch || batch > 65535) + throw std::invalid_argument("batch capacity must be in [1,65535]"); + Options o; + o.sort_limit = limit; + validate(n, k, o); + // Conservative per-round bound: up to three sorts (tile + merges + + // copy), two entry copies, histogram, partition, filter and W copy. + // One final prefix copy. Usually 128 slots; 512 only at extreme k. + descriptor_slots = detail::batch_descriptor_slots(k, limit); + if (descriptor_slots > MAX_SLOTS) + throw std::logic_error("batch descriptor bound"); + if (arena_bytes && !arena) + throw std::invalid_argument("null borrowed arena"); + if (borrowed) { + arena_layout = + detail::batch_arena_layout(batch, n, k, limit, idx, runs); + bind_arena(arena, arena_bytes); + } + try { + int device; + cudaDeviceProp prop{}; + CK(cudaGetDevice(&device)); + CK(cudaGetDeviceProperties(&prop, device)); + if (prop.sharedMemPerBlock < 4096u * 4u * (idx ? 2u : 1u)) + throw std::runtime_error("insufficient batch sort shared memory"); + if (!borrowed) { + for (auto& b : c) b.allocate(uint64_t(batch) * n, idx); + w.allocate(uint64_t(batch) * k, idx); + p.allocate(uint64_t(batch) * std::max(k, limit), idx); + scratch.allocate(uint64_t(batch) * std::max(k, limit), idx); + histogram_data.allocate(uint64_t(batch) * 4097 * 4); + metadata.allocate(uint64_t(batch) * sizeof(Decision)); + counter_data.allocate(uint64_t(batch) * 8); + job_data.allocate(uint64_t(descriptor_slots) * batch * + sizeof(KernelJob)); + if (run_resources) winner_scratch.allocate(uint64_t(batch) * k, idx); + } + CK(cudaMallocHost( + reinterpret_cast(&host_jobs), + uint64_t(descriptor_slots) * batch * sizeof(KernelJob))); + for (uint64_t j = 0; j < uint64_t(descriptor_slots) * batch; ++j) + new (host_jobs + j) KernelJob{}; + CK(cudaMallocHost(reinterpret_cast(&host_meta), + uint64_t(batch) * sizeof(Decision))); + for (uint32_t j = 0; j < batch; ++j) new (host_meta + j) Decision{}; + CK(cudaMallocHost(reinterpret_cast(&host_counts), + uint64_t(batch) * 8)); + CK(cudaEventCreate(&start)); + CK(cudaEventCreate(&end)); + if (run_resources) { + CK(cudaStreamCreateWithFlags(&winner_stream, cudaStreamNonBlocking)); + for (int j = 0; j < 6; ++j) { + CK(cudaEventCreateWithFlags(ready + j, cudaEventDisableTiming)); + CK(cudaEventCreateWithFlags(done + j, cudaEventDisableTiming)); + } + } + } catch (...) { + cleanup(); + throw; + } + } + void cleanup() { + if (start) cudaEventDestroy(start); + if (end) cudaEventDestroy(end); + for (int j = 0; j < 6; ++j) { + if (ready[j]) cudaEventDestroy(ready[j]); + if (done[j]) cudaEventDestroy(done[j]); + } + if (winner_stream) cudaStreamDestroy(winner_stream); + if (host_jobs) cudaFreeHost(host_jobs); + if (host_meta) cudaFreeHost(host_meta); + if (host_counts) cudaFreeHost(host_counts); + } + ~BatchBackend() { cleanup(); } + void bind_arena(void* arena, uint64_t bytes) { + if (!borrowed) + throw std::logic_error("workspace does not borrow device storage"); + detail::validate_arena(arena, bytes, arena_layout); + DeviceBuffer* buffers[] = {&c[0], &c[1], &w, &p, &scratch, &winner_scratch}; + for (size_t j = 0; j < 6; ++j) { + buffers[j]->values.borrow(arena, arena_layout.values[j]); + buffers[j]->indices.borrow(arena, arena_layout.indices[j]); + } + histogram_data.borrow(arena, arena_layout.histogram); + metadata.borrow(arena, arena_layout.metadata); + counter_data.borrow(arena, arena_layout.counters); + job_data.borrow(arena, arena_layout.jobs); + } + void begin(Options o, BatchStats* s) { + options = o; + stats = s; + slot = 0; + run_slot = 0; + pending_winner = -1; + } + Buffer candidate(uint32_t t, int j) { + return offset(c[j].get(), uint64_t(t) * max_n); + } + Buffer winners(uint32_t t) { return offset(w.get(), uint64_t(t) * max_k); } + Buffer potential(uint32_t t) { + return offset(p.get(), uint64_t(t) * std::max(max_k, max_limit)); + } + Buffer temporary(uint32_t t) { + return offset(scratch.get(), uint64_t(t) * std::max(max_k, max_limit)); + } + dim3 grid(uint32_t n, size_t jobs, bool packed = false, int threads = BLOCK) { + uint32_t cap = std::max(1u, options.block_cap / uint32_t(jobs)); + return dim3(primitive_blocks( + n, cap, packed ? options.primitives : PrimitiveMode::scalar, + threads), + uint32_t(jobs)); + } + const KernelJob* upload(const std::vector& jobs, + cudaStream_t target) { + if (jobs.empty() || jobs.size() > max_batch || slot >= descriptor_slots) + throw std::logic_error("batch descriptor capacity"); + uint64_t base = uint64_t(slot++) * max_batch; + std::copy(jobs.begin(), jobs.end(), host_jobs + base); + auto dst = static_cast(job_data.ptr) + base; + CK(cudaMemcpyAsync(dst, host_jobs + base, jobs.size() * sizeof(KernelJob), + cudaMemcpyHostToDevice, target)); + return dst; + } + const KernelJob* upload(const std::vector& jobs) { + return upload(jobs, stream); + } + template + void stage_on(const char* label, cudaStream_t target, F fn) { + if (options.instrument) CK(cudaEventRecord(start, target)); + fn(); + CK(cudaGetLastError()); + if (options.instrument) { + CK(cudaEventRecord(end, target)); + CK(cudaEventSynchronize(end)); + float ms; + CK(cudaEventElapsedTime(&ms, start, end)); + stats->stages.push_back({label, ms}); + } + } + template + void stage(const char* label, F fn) { + stage_on(label, stream, fn); + } + std::vector histograms(const std::vector& requests) { + std::vector jobs; + uint32_t largest = 0; + int pass = requests.front().pass; + for (auto& r : requests) { + if (r.pass != pass) throw std::logic_error("mixed batch digits"); + KernelJob j; + j.src = r.src; + j.n = r.n; + j.pass = r.pass; + j.rank = r.rank; + j.hist = + static_cast(histogram_data.ptr) + uint64_t(r.task) * 4097; + // The extra histogram word carries either the entry finite-input + // check or the final shifted-digit round-trip check. + if ((options.reject_nonfinite && r.pass == 0) || + (r.src.shift_reference && r.pass == 2)) + j.scale_unsafe = j.hist + 4096; + j.decision = static_cast(metadata.ptr) + r.task; + jobs.push_back(j); + largest = std::max(largest, r.n); + } + const KernelJob* device_jobs = nullptr; + stage("batch_histogram", [&] { + device_jobs = upload(jobs); + CK(cudaMemsetAsync(histogram_data.ptr, 0, uint64_t(max_batch) * 4097 * 4, + stream)); + launch_histogram( + {}, 0, pass, nullptr, device_jobs, + grid(largest, jobs.size(), true, + histogram_threads(options.primitives, pass)), + options.primitives, stream); + }); + stage("batch_select_and_metadata", [&] { + dim3 shape(1, uint32_t(jobs.size())); + launch_selection(nullptr, 0, nullptr, device_jobs, + pass, shape, options.primitives, + stream); + CK(cudaMemcpyAsync(host_meta, metadata.ptr, + uint64_t(max_batch) * sizeof(Decision), + cudaMemcpyDeviceToHost, stream)); + CK(cudaStreamSynchronize(stream)); + }); + std::vector result; + for (auto& r : requests) { + if (options.reject_nonfinite && pass == 0 && + host_meta[r.task].scale_unsafe) + throw NonFiniteInput{}; + result.push_back(host_meta[r.task]); + } + return result; + } + void copies_on(const std::vector& requests, cudaStream_t target, + const char* label) { + if (requests.empty()) return; + std::vector jobs; + uint32_t largest = 0; + for (auto& r : requests) { + if (!r.n) continue; + KernelJob j; + j.src = r.src; + j.n = r.n; + j.G = r.dst; + jobs.push_back(j); + largest = std::max(largest, r.n); + } + if (jobs.empty()) return; + stage_on(label, target, [&] { + auto device_jobs = upload(jobs, target); + if (indexed) + copy_items + <<>>({}, 0, {}, + device_jobs); + else + copy_items + <<>>({}, 0, {}, + device_jobs); + }); + } + void copies(const std::vector& requests) { + copies_on(requests, stream, "batch_copy"); + } + template + void launch_gathers(const std::vector& jobs, uint32_t largest) { + auto device_jobs = upload(jobs); + CK(cudaMemsetAsync(counter_data.ptr, 0, uint64_t(max_batch) * 8, stream)); + uint32_t max_gcap = 0; + for (auto& job : jobs) max_gcap = std::max(max_gcap, job.gcap); + if (indexed && (FILTER || options.method != Method::reference)) + launch_partition( + {}, 0, 0, 0, {}, 0, {}, 0, nullptr, device_jobs, + grid(largest, jobs.size(), true), max_gcap, options.primitives, + stream); + else + launch_partition( + {}, 0, 0, 0, {}, 0, {}, 0, nullptr, device_jobs, + grid(largest, jobs.size(), true), max_gcap, options.primitives, + stream); + } + void read_counts() { + CK(cudaMemcpyAsync(host_counts, counter_data.ptr, uint64_t(max_batch) * 8, + cudaMemcpyDeviceToHost, stream)); + CK(cudaStreamSynchronize(stream)); + } + void partitions(const std::vector& requests) { + if (requests.empty()) return; + std::vector jobs; + uint32_t largest = 0; + for (auto& r : requests) { + KernelJob j; + j.src = r.src; + j.n = r.n; + j.pass = r.pass; + j.boundary = r.bin; + j.G = r.G; + j.gcap = r.gcap; + j.E = r.E; + j.ecap = r.ecap; + j.counters = + static_cast(counter_data.ptr) + uint64_t(r.task) * 2; + jobs.push_back(j); + largest = std::max(largest, r.n); + } + stage("batch_partition", [&] { launch_gathers(jobs, largest); }); + if (options.debug) { + read_counts(); + for (auto& r : requests) + if (host_counts[2 * r.task] != (r.G.v ? r.expected_g : 0) || + host_counts[2 * r.task + 1] != r.expected_e) + throw std::logic_error("batch partition counts"); + } + } + void filters(const std::vector& requests) { + if (requests.empty()) return; + std::vector jobs; + uint32_t largest = 0; + for (auto& r : requests) { + KernelJob j; + j.src = r.src; + j.n = r.n; + j.boundary = r.pivot; + j.pivot = r.pivot_value; + j.G = r.dst; + j.gcap = r.greater; + j.E = offset(r.dst, r.greater); + j.ecap = r.ties; + j.counters = + static_cast(counter_data.ptr) + uint64_t(r.task) * 2; + jobs.push_back(j); + largest = std::max(largest, r.n); + } + stage("batch_original_filter", + [&] { launch_gathers(jobs, largest); }); + if (options.debug) { + read_counts(); + for (auto& r : requests) + if (host_counts[2 * r.task] != r.greater || + host_counts[2 * r.task + 1] < r.ties) + throw std::logic_error("batch filter counts"); + } + } + void sorts_on(const std::vector& requests, cudaStream_t target, + bool winner) { + if (requests.empty()) return; + auto active = requests; + stage_on(winner ? "batch_winner_run_sort" : "batch_sort", target, [&] { + std::vector jobs; + uint32_t tiles = 0, max_tile = 0, max_length = 0; + for (auto& r : active) { + KernelJob j; + j.G = r.src; + j.n = r.n; + j.tile = std::min(4096u, padded(r.n)); + tiles = std::max(tiles, (r.n + j.tile - 1) / j.tile); + max_tile = std::max(max_tile, j.tile); + max_length = std::max(max_length, r.n); + jobs.push_back(j); + } + auto device_jobs = upload(jobs, target); + dim3 shape(tiles, uint32_t(jobs.size())); + size_t smem = max_tile * 4 * (indexed ? 2 : 1); + if (indexed) + sort_tiles + <<>>({}, 0, 0, device_jobs); + else + sort_tiles + <<>>({}, 0, 0, device_jobs); + CK(cudaGetLastError()); + std::vector destinations; + for (auto& r : active) + destinations.push_back( + winner ? offset(winner_scratch.get(), uint64_t(r.task) * max_k) + : temporary(r.task)); + for (uint64_t width = 4096; width < max_length; width *= 2) { + jobs.clear(); + uint32_t largest = 0; + for (size_t t = 0; t < active.size(); ++t) { + auto& r = active[t]; + if (r.n <= width) continue; + KernelJob j; + j.src = r.src; + j.G = destinations[t]; + j.n = r.n; + j.width = uint32_t(width); + jobs.push_back(j); + largest = std::max(largest, r.n); + std::swap(r.src, destinations[t]); + } + device_jobs = upload(jobs, target); + if (indexed) + merge_runs + <<>>({}, {}, 0, 0, + device_jobs); + else + merge_runs + <<>>({}, {}, 0, 0, + device_jobs); + CK(cudaGetLastError()); + } + }); + std::vector output; + for (auto& r : active) + if (r.src.v != r.out.v || r.src.i != r.out.i) + output.push_back({r.task, r.src, r.k, r.out}); + copies_on(output, target, winner ? "batch_winner_copy" : "batch_copy"); + } + void sorts(const std::vector& requests) { + sorts_on(requests, stream, false); + } + void winner_sorts(const std::vector& requests) { + std::vector jobs; + for (auto& r : requests) + if (r.n > 1) { + auto region = offset(winners(r.task), r.base); + jobs.push_back({r.task, region, r.n, region, r.n}); + } + if (jobs.empty()) return; + if (!run_resources || run_slot >= 6) + throw std::logic_error("batch winner-run workspace capacity"); + uint32_t j = run_slot++; + cudaStream_t target = + options.winner_sort == WinnerSort::overlap ? winner_stream : stream; + if (options.winner_sort == WinnerSort::overlap) { + CK(cudaEventRecord(ready[j], stream)); + CK(cudaStreamWaitEvent(target, ready[j], 0)); + } + sorts_on(jobs, target, true); + if (options.winner_sort == WinnerSort::overlap) { + CK(cudaEventRecord(done[j], target)); + pending_winner = int(j); + } + } + void join_winners() { + if (pending_winner >= 0) + stage("batch_winner_join", + [&] { CK(cudaStreamWaitEvent(stream, done[pending_winner], 0)); }); + } + std::vector values(View src, uint32_t n) { + std::vector raw(n); + if (n) + CK(cudaMemcpyAsync(raw.data(), src.v, uint64_t(sizeof(Value)) * n, + cudaMemcpyDeviceToHost, stream)); + CK(cudaStreamSynchronize(stream)); + return std::vector(raw.begin(), raw.end()); + } + void audit(uint32_t t, View original, uint32_t n, View C, uint32_t count, + uint32_t wn, uint32_t r, uint32_t k, uint32_t better, + Method method) { + auto top = [](std::vector x, uint32_t length) { + if (length < x.size()) + std::nth_element(x.begin(), x.begin() + length, x.end(), + std::greater()); + x.resize(length); + std::sort(x.begin(), x.end(), std::greater()); + return x; + }; + auto expected = top(values(original, n), k), + remaining = top(values(C, count), r); + if (method == Method::reference) { + if (better + r != k || !std::equal(remaining.begin(), remaining.end(), + expected.begin() + better)) + throw std::logic_error("batch reference audit"); + } else { + auto saved = values(winners(t), wn); + remaining.insert(remaining.end(), saved.begin(), saved.end()); + std::sort(remaining.begin(), remaining.end(), std::greater()); + if (wn + r != k || remaining != expected) + throw std::logic_error("batch winner audit"); + } + } +}; +struct BatchWorkspace::Impl : BatchBackend { + using BatchBackend::BatchBackend; +}; +struct BFloat16BatchWorkspace::Impl : BatchBackend { + using BatchBackend::BatchBackend; +}; +template +uint64_t batch_device_bytes(const BatchBackend& b) { + if (b.borrowed) return b.arena_layout.bytes; + return (sizeof(Value) + (b.indexed ? 4ull : 0ull)) * b.max_batch * + (2ull * b.max_n + b.max_k + 2ull * std::max(b.max_k, b.max_limit) + + (b.run_resources ? b.max_k : 0)) + + uint64_t(b.max_batch) * + (4097 * 4 + sizeof(Decision) + 8 + + b.descriptor_slots * sizeof(KernelJobT)); +} +template +uint64_t batch_pinned_bytes(const BatchBackend& b) { + return uint64_t(b.max_batch) * + (sizeof(Decision) + 8 + + b.descriptor_slots * sizeof(KernelJobT)); +} +template +BatchStats topk_batch_impl(BatchBackend& b, const Value* input, + const uint32_t* lengths, uint32_t batch, uint32_t k, + Value* output, uint32_t* indices, Options options, + cudaStream_t stream) { + if (!input || !output || input == output || !lengths || !batch || + batch > b.max_batch || k > b.max_k || options.sort_limit > b.max_limit || + b.indexed != (indices != nullptr) || + (options.winner_sort != WinnerSort::deferred && !b.run_resources)) + throw std::invalid_argument("batch pointer or workspace mismatch"); + if (options.reject_nonfinite && + (options.entry_sort || options.scale != ScaleMode::off)) + throw std::invalid_argument( + "finite input guard requires the unshifted entry histogram"); + std::vector shape(lengths, lengths + batch); + batch_offsets(shape, k, options); + for (auto n : shape) + if (n > b.max_n) throw std::invalid_argument("batch row exceeds workspace"); + b.stream = stream; + return run_batch(b, ValueView{input, nullptr}, shape, k, + ValueBuffer{output, indices}, options); +} +BatchWorkspace::BatchWorkspace(uint32_t b, uint32_t n, uint32_t k, + uint32_t limit, bool indexed, bool runs) + : impl_(new Impl(b, n, k, limit, indexed, runs)) {} +BatchWorkspace::~BatchWorkspace() = default; +uint64_t BatchWorkspace::device_bytes() const { + return batch_device_bytes(*impl_); +} +uint64_t BatchWorkspace::pinned_bytes() const { + return batch_pinned_bytes(*impl_); +} +BatchStats topk_batch(const float* input, const uint32_t* lengths, + uint32_t batch, uint32_t k, float* output, + uint32_t* indices, BatchWorkspace& workspace, + Options options, cudaStream_t stream) { + return topk_batch_impl(*workspace.impl_, input, lengths, batch, k, + output, indices, options, stream); +} +BFloat16BatchWorkspace::BFloat16BatchWorkspace(uint32_t b, uint32_t n, + uint32_t k, uint32_t limit, + bool indexed, bool runs) + : impl_(new Impl(b, n, k, limit, indexed, runs)) {} +BFloat16BatchWorkspace::BFloat16BatchWorkspace(uint32_t b, uint32_t n, + uint32_t k, uint32_t limit, + bool indexed, bool runs, + void* storage, uint64_t bytes) + : impl_(nullptr) { + if (!storage) throw std::invalid_argument("null borrowed storage"); + impl_.reset(new Impl(b, n, k, limit, indexed, runs, storage, bytes)); +} +uint64_t BFloat16BatchWorkspace::required_device_bytes(uint32_t b, uint32_t n, + uint32_t k, + uint32_t limit, + bool indexed, + bool runs) { + return detail::batch_arena_layout(b, n, k, limit, indexed, runs) + .bytes; +} +void BFloat16BatchWorkspace::bind_device_storage(void* storage, + uint64_t bytes) { + impl_->bind_arena(storage, bytes); +} +uint64_t BFloat16BatchWorkspace::owned_device_bytes() const { + return impl_->borrowed ? 0 : device_bytes(); +} +BFloat16BatchWorkspace::~BFloat16BatchWorkspace() = default; +uint64_t BFloat16BatchWorkspace::device_bytes() const { + return batch_device_bytes(*impl_); +} +uint64_t BFloat16BatchWorkspace::pinned_bytes() const { + return batch_pinned_bytes(*impl_); +} +BatchStats topk_batch_bf16(const BFloat16* input, const uint32_t* lengths, + uint32_t batch, uint32_t k, BFloat16* output, + uint32_t* indices, BFloat16BatchWorkspace& workspace, + Options options, cudaStream_t stream) { + return topk_batch_impl(*workspace.impl_, input, lengths, batch, k, + output, indices, options, stream); +} +#include "bfloat16_graph.cuh" + +} // namespace r2sk diff --git a/csrc/core/kernel/cuda/topk_r2sk/r2sk/batch_core.hpp b/csrc/core/kernel/cuda/topk_r2sk/r2sk/batch_core.hpp new file mode 100644 index 000000000..62fb07966 --- /dev/null +++ b/csrc/core/kernel/cuda/topk_r2sk/r2sk/batch_core.hpp @@ -0,0 +1,270 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once +#include "core.hpp" + +namespace r2sk { +struct BatchStats { + std::vector tasks; + std::vector stages; // whole batch phases, not sums of task timings + uint32_t decision_rounds = 0; +}; +template +struct HistJobT { + uint32_t task; + ValueView src; + uint32_t n; + int pass; + uint32_t rank; +}; +template +struct CopyJobT { + uint32_t task; + ValueView src; + uint32_t n; + ValueBuffer dst; +}; +template +struct PartitionJobT { + uint32_t task; + ValueView src; + uint32_t n; + int pass; + uint32_t bin; + ValueBuffer G; + uint32_t gcap; + ValueBuffer E; + uint32_t ecap; + uint32_t expected_g, expected_e; +}; +template +struct FilterJobT { + uint32_t task; + ValueView src; + uint32_t n, pivot; + ValueView + pivot_value; // nonnull: singleton gathered on device, no scalar D2H + uint32_t greater, ties; + ValueBuffer dst; +}; +template +struct SortJobT { + uint32_t task; + ValueBuffer src; + uint32_t n; + ValueBuffer out; + uint32_t k; +}; +using HistJob = HistJobT; +using CopyJob = CopyJobT; +using PartitionJob = PartitionJobT; +using FilterJob = FilterJobT; +using SortJob = SortJobT; +struct WinnerJob { + uint32_t task, base, n; +}; +inline std::vector batch_offsets(const std::vector& lengths, + uint32_t k, Options o) { + if (lengths.empty() || lengths.size() > 65535) + throw std::invalid_argument("batch size must be in [1,65535]"); + std::vector offsets(lengths.size() + 1, 0); + for (size_t t = 0; t < lengths.size(); ++t) { + validate(lengths[t], k, o); + offsets[t + 1] = offsets[t] + lengths[t]; + } + return offsets; +} +// Independent states, shared rounds. Backend methods consume whole job lists; +// the CUDA backend launches grid.y over jobs, never calls topk() per row. +template +BatchStats run_batch(Backend& b, ValueView input, + const std::vector& lengths, uint32_t k, + ValueBuffer output, Options o) { + using View = ValueView; + using Buffer = ValueBuffer; + using HistJob = HistJobT; + using CopyJob = CopyJobT; + using PartitionJob = PartitionJobT; + using FilterJob = FilterJobT; + using SortJob = SortJobT; + if (o.capture_rank || o.capture_capacity) + throw std::invalid_argument( + "local capture supports single-array calls only"); + auto offsets = batch_offsets(lengths, k, o); + BatchStats result; + result.tasks.resize(lengths.size()); + b.begin(o, &result); + struct State { + View original, C; + Buffer output; + uint32_t n, count, w = 0, r, better = 0, prefix = 0; + int next = 0; + bool done = false; + }; + std::vector states; + for (uint32_t t = 0; t < lengths.size(); ++t) { + View row{input.v + offsets[t], input.i ? input.i + offsets[t] : nullptr}; + row.shift_reference = o.scale == ScaleMode::shift ? row.v : nullptr; + states.push_back({row, row, offset(output, uint64_t(t) * k), lengths[t], + lengths[t], 0, k, 0, 0, 0, false}); + } + std::vector copies; + std::vector sorts; + std::vector prefixes; + const bool sorted_runs = o.winner_sort != WinnerSort::deferred; + auto finish = [&](uint32_t t, uint32_t m, uint32_t prefix = 0) { + result.tasks[t].final_sorted = m; + result.tasks[t].estimated_value_bytes += (2ull * sizeof(Value)) * k; + result.tasks[t].sorted_values += m; + sorts.push_back( + {t, b.potential(t), m, offset(states[t].output, prefix), k - prefix}); + if (prefix) prefixes.push_back({t, b.winners(t), prefix, states[t].output}); + states[t].done = true; + }; + const int passes = o.scale == ScaleMode::shift ? 6 : 3; + for (int pass = 0; pass < passes; ++pass) { + const bool shifted = o.scale == ScaleMode::shift && pass < 3; + std::vector hist; + std::vector entry_winners; + for (uint32_t t = 0; t < states.size(); ++t) { + auto& x = states[t]; + if (x.done) continue; + if (pass == 3) x.prefix = 0; + if (!x.r || x.r > x.count || + (o.method != Method::reference && x.w + x.r != k)) + throw std::logic_error("batch entry invariant"); + if (o.method == Method::early && o.entry_sort && + uint64_t(x.w) + x.count <= o.sort_limit) { + uint32_t prefix = sorted_runs ? x.w : 0; + if (!sorted_runs && x.w) + entry_winners.push_back({t, b.winners(t), x.w, b.potential(t)}); + copies.push_back( + {t, x.C, x.count, offset(b.potential(t), x.w - prefix)}); + result.tasks[t].estimated_value_bytes += + (2ull * sizeof(Value)) * (x.w - prefix + x.count); + result.tasks[t].trace.push_back({x.count, x.w, x.r, pass, -1, 0, + x.count, x.w + x.count, "entry_sort"}); + finish(t, x.w - prefix + x.count, prefix); + continue; + } + hist.push_back({t, x.C, x.count, pass, x.r}); + } + b.copies(entry_winners); + b.copies(copies); + b.sorts(sorts); + copies.clear(); + sorts.clear(); + if (hist.empty()) break; + auto decisions = b.histograms(hist); + if (decisions.size() != hist.size()) + throw std::logic_error("batch metadata size"); + ++result.decision_rounds; + std::vector partitions; + std::vector filters; + std::vector winner_jobs; + for (size_t j = 0; j < hist.size(); ++j) { + uint32_t t = hist[j].task; + auto& x = states[t]; + auto& s = result.tasks[t]; + auto d = decisions[j]; + if (d.total != x.count || d.bin < 0 || !d.B || d.h >= x.r || + x.r > d.h + d.B) + throw std::logic_error("batch histogram invariant"); + ++s.histogram_passes; + s.estimated_value_bytes += uint64_t(sizeof(Value)) * x.count; + if (pass >= 3) ++s.raw_refinement_passes; + x.prefix |= uint32_t(d.bin) << digit_low(pass); + uint32_t M = x.w + d.h + d.B; + Pass trace{x.count, x.w, x.r, pass, d.bin, d.h, d.B, M, "refine"}; + trace.gather_count = x.count; + trace.shifted = shifted; + trace.scale_unsafe = d.scale_unsafe != 0; + const bool exhausted = pass % 3 == 2 && (!shifted || !d.scale_unsafe); + if (shifted && pass == 2 && d.scale_unsafe) trace.route = "raw_refine"; + auto partition = [&](Buffer G, uint32_t gc, Buffer E, uint32_t ec) { + partitions.push_back( + {t, x.C, x.count, pass, uint32_t(d.bin), G, gc, E, ec, d.h, d.B}); + s.estimated_value_bytes += + uint64_t(sizeof(Value)) * x.count + + uint64_t(sizeof(Value)) * ((G.v ? gc : 0) + ec); + }; + if (o.method == Method::reference) { + x.better += d.h; + x.r -= d.h; + trace.potential = 0; + if (exhausted || d.B == 1) { + View pivot{}; + if (shifted || (d.B == 1 && pass % 3 != 2)) { + partition({}, 0, b.candidate(t, x.next), 1); + pivot = b.candidate(t, x.next); + } + filters.push_back({t, x.original, x.n, x.prefix, pivot, x.better, x.r, + b.potential(t)}); + s.estimated_value_bytes += + uint64_t(sizeof(Value)) * x.n + uint64_t(sizeof(Value)) * k; + trace.route = "pivot_filter"; + finish(t, k); + } else { + partition({}, 0, b.candidate(t, x.next), d.B); + x.C = b.candidate(t, x.next); + x.C.shift_reference = x.original.shift_reference; + x.count = d.B; + x.next ^= 1; + } + } else { + bool exact = d.h + d.B == x.r, + small = o.method == Method::early && M <= o.sort_limit; + if (exact || small || exhausted) { + uint32_t ec = exhausted && !exact && !small ? x.r - d.h : d.B; + uint32_t prefix = sorted_runs ? x.w : 0; + if (!sorted_runs && x.w) { + copies.push_back({t, b.winners(t), x.w, b.potential(t)}); + s.estimated_value_bytes += (2ull * sizeof(Value)) * x.w; + } + partition(offset(b.potential(t), x.w - prefix), d.h, + offset(b.potential(t), x.w - prefix + d.h), ec); + trace.route = exact ? "exact" : small ? "early_sort" : "ties"; + finish(t, x.w - prefix + d.h + ec, prefix); + } else { + partition(offset(b.winners(t), x.w), d.h, b.candidate(t, x.next), + d.B); + if (sorted_runs && d.h) { + winner_jobs.push_back({t, x.w, d.h}); + s.winner_runs.push_back(d.h); + s.sorted_values += d.h; + } + x.w += d.h; + x.r -= d.h; + x.C = b.candidate(t, x.next); + x.C.shift_reference = x.original.shift_reference; + x.count = d.B; + x.next ^= 1; + } + } + s.trace.push_back(trace); + } + b.copies(copies); + b.partitions(partitions); + b.winner_sorts(winner_jobs); + b.filters(filters); + b.sorts(sorts); + copies.clear(); + sorts.clear(); + if (o.debug) { + b.join_winners(); + for (uint32_t t = 0; t < states.size(); ++t) { + auto& x = states[t]; + if (!x.done) + b.audit(t, x.original, x.n, x.C, x.count, x.w, x.r, k, x.better, + o.method); + } + } + } + for (auto& x : states) + if (!x.done) throw std::logic_error("batch failed to terminate"); + // Finished rows may wait for other rows without blocking their refinement. + // All winner-prefix copies occur after the final cross-stream dependency. + b.join_winners(); + b.copies(prefixes); + return result; +} +} // namespace r2sk diff --git a/csrc/core/kernel/cuda/topk_r2sk/r2sk/bfloat16.hpp b/csrc/core/kernel/cuda/topk_r2sk/r2sk/bfloat16.hpp new file mode 100644 index 000000000..d94761a1d --- /dev/null +++ b/csrc/core/kernel/cuda/topk_r2sk/r2sk/bfloat16.hpp @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once +#include "core.hpp" +#include + +namespace r2sk { +// Storage for raw IEEE BF16 bits; no BF16 arithmetic or SM80 instructions. +// Finite inputs only. This type does NOT round arbitrary FP32 inputs to BF16. +struct BFloat16 { + uint16_t bits = 0; + R2SK_HD operator float() const { + uint32_t word = uint32_t(bits) << 16; +#ifdef __CUDA_ARCH__ + return __uint_as_float(word); +#else + float value; + std::memcpy(&value, &word, sizeof(value)); + return value; +#endif + } + // Internal sorting/staging stores only values loaded from BF16, or an + // exactly representable padding sentinel. Their low 16 FP32 bits are zero. + R2SK_HD BFloat16& operator=(float exact) { + bits = uint16_t(float_bits(exact) >> 16); + return *this; + } +}; +static_assert(sizeof(BFloat16) == 2 && alignof(BFloat16) == 2, + "BF16 storage layout"); +static_assert(std::is_trivially_copyable::value, "BF16 raw copies"); +} // namespace r2sk diff --git a/csrc/core/kernel/cuda/topk_r2sk/r2sk/bfloat16_graph.hpp b/csrc/core/kernel/cuda/topk_r2sk/r2sk/bfloat16_graph.hpp new file mode 100644 index 000000000..37af80055 --- /dev/null +++ b/csrc/core/kernel/cuda/topk_r2sk/r2sk/bfloat16_graph.hpp @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +#include + +#include + +namespace r2sk { + +struct BFloat16GraphShape { + uint32_t batch; + uint32_t vocabulary; + uint32_t k; + uint32_t sort_limit = 1024; + uint32_t block_cap = 1280; +}; + +enum class GraphRoute : uint32_t { exact, early_sort, refine, invalid_nan }; + +struct BFloat16GraphRow { + GraphRoute route; + uint32_t first_winners; + uint32_t first_boundary; + uint32_t passes; +}; + +// Resources are created before capture and kept alive for graph replay. +// Leaving these handles null selects the same schedule on one stream. +struct BFloat16GraphFork { + cudaStream_t stream = nullptr; + cudaEvent_t ready = nullptr; + cudaEvent_t done = nullptr; +}; + +uint64_t bfloat16_graph_bytes(BFloat16GraphShape shape); + +// Start a selection and optionally copy the batch-wide nonfinite flag into +// pinned host memory. With that option, synchronize the stream and decline +// on a nonzero flag before finishing. The same arena, shape and stream must +// be used for both calls. +void begin_bfloat16_selection(BFloat16GraphShape shape, const void* input, + void* arena, uint64_t arena_bytes, + cudaStream_t stream, + uint32_t* pinned_nonfinite = nullptr); +void finish_bfloat16_selection(BFloat16GraphShape shape, void* values, + uint32_t* indices, void* arena, + uint64_t arena_bytes, cudaStream_t stream, + BFloat16GraphFork fork = {}, + BFloat16GraphRow* rows = nullptr); + +// Dense BF16 [batch,vocabulary] in, descending BF16 [batch,k] and +// row-relative indices out. Signed zeros compare as equal numerically. +// Infinities are ordered numerically. NaN rows leave both outputs untouched +// and report invalid_nan. Callers omitting rows must ensure no NaNs. +// Buffers must be disjoint and survive until the graph or stream is done. +// The arena is borrowed, 256-byte aligned, and exclusive to an in-flight call. +void enqueue_bfloat16_graph(BFloat16GraphShape shape, const void* input, + void* values, uint32_t* indices, void* arena, + uint64_t arena_bytes, cudaStream_t stream, + BFloat16GraphFork fork = {}, + BFloat16GraphRow* rows = nullptr); + +} // namespace r2sk diff --git a/csrc/core/kernel/cuda/topk_r2sk/r2sk/core.hpp b/csrc/core/kernel/cuda/topk_r2sk/r2sk/core.hpp new file mode 100644 index 000000000..b8f4e5e08 --- /dev/null +++ b/csrc/core/kernel/cuda/topk_r2sk/r2sk/core.hpp @@ -0,0 +1,366 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once +#include +#include +#include +#include +#include +#include + +namespace r2sk { +// Finite FP32 only. Zeros may be ordered by their key; they are numeric ties. +#ifdef __CUDACC__ +#define R2SK_HD __host__ __device__ +#else +#define R2SK_HD +#endif +R2SK_HD inline uint32_t float_bits(float value) { + uint32_t bits; +#ifdef __CUDA_ARCH__ + bits = __float_as_uint(value); +#else + std::memcpy(&bits, &value, sizeof(bits)); +#endif + return bits; +} +R2SK_HD inline uint32_t ordered_key(float value) { + uint32_t bits = float_bits(value); + return bits ^ ((0u - (bits >> 31)) | 0x80000000u); +} +R2SK_HD inline bool finite_key(float value) { + return (float_bits(value) & 0x7f800000u) != 0x7f800000u; +} +struct NonFiniteInput {}; +R2SK_HD inline float shift_value(float value, float reference) { +#ifdef __CUDA_ARCH__ + return __fsub_rn(value, reference); +#else + volatile float result = value - reference; + return result; +#endif +} +// A bit-exact round trip is a sufficient injectivity certificate. Checking +// only the current candidates at the last shifted digit is conservative. +R2SK_HD inline bool shift_reversible(float value, float shifted, + float reference) { +#ifdef __CUDA_ARCH__ + float recovered = __fadd_rn(shifted, reference); +#else + volatile float recovered = shifted + reference; +#endif + return float_bits(recovered) == float_bits(value); +} +R2SK_HD inline int digit_low(int pass) { + return pass % 3 == 0 ? 20 : pass % 3 == 1 ? 8 : 0; +} +R2SK_HD inline int digit_width(int pass) { return pass % 3 == 2 ? 8 : 12; } +R2SK_HD inline uint32_t digit(float x, int pass, float reference = 0.f, + bool shifted = false) { + if (shifted && pass < 3) x = shift_value(x, reference); + return (ordered_key(x) >> digit_low(pass)) & ((1u << digit_width(pass)) - 1u); +} +inline uint32_t padded(uint32_t n) { + uint32_t p = 1; + while (p < n) p <<= 1; + return p; +} +enum class Method { reference, winners, early }; +enum class WinnerSort { deferred, serial, overlap }; +enum class ScaleMode { off, shift }; +inline const char* name(ScaleMode mode) { + return mode == ScaleMode::off ? "off" : "shift"; +} +// Cumulative primitive ablations. The device API keeps its original default; +// benchmark runners explicitly select radik and compare all winner modes. +enum class PrimitiveMode { scalar, packed, buffered, scan, radik }; +inline const char* name(PrimitiveMode mode) { + switch (mode) { + case PrimitiveMode::scalar: + return "scalar"; + case PrimitiveMode::packed: + return "packed"; + case PrimitiveMode::buffered: + return "buffered"; + case PrimitiveMode::scan: + return "scan"; + case PrimitiveMode::radik: + return "radik"; + } + return "invalid"; +} +inline const char* name(WinnerSort mode) { + return mode == WinnerSort::deferred ? "deferred" + : mode == WinnerSort::serial ? "serial" + : "overlap"; +} +inline const char* name(Method m) { + return m == Method::reference ? "our_reference_filter" + : m == Method::winners ? "r2sk_winners" + : "r2sk_early"; +} +struct Options { + bool reject_nonfinite = false; // batch-only guard, before any output writes + Method method = Method::early; + uint32_t sort_limit = + 1024; // actual superset M, padded to a supported capacity + uint32_t block_cap = 1280; + bool entry_sort = true; + bool debug = false; + bool instrument = false; + WinnerSort winner_sort = + WinnerSort::deferred; // saved-group sorting; optional workspace + // resources required + uint32_t capture_rank = + 0; // 0: off; otherwise retain bins >= each 256-value tile's q-th digit + uint32_t capture_capacity = 0; // 0: current candidate count; smaller values + // exercise overflow fallback + PrimitiveMode primitives = PrimitiveMode::scalar; + ScaleMode scale = + ScaleMode::off; // key-only x-input[0]; raw floats stay in all buffers +}; +inline void validate(uint32_t n, uint32_t k, const Options& o) { + if (!n || !k || k > n || n > 0x7fffffffu) + throw std::invalid_argument("require 1 <= k <= N <= INT_MAX"); + if (!o.block_cap || o.block_cap > 65535) + throw std::invalid_argument("block_cap must be in [1,65535]"); + if (!o.sort_limit || o.sort_limit > 4096 || + padded(o.sort_limit) != o.sort_limit) + throw std::invalid_argument( + "sort_limit must be a power of two in [1,4096]"); + if (o.method == Method::reference && o.winner_sort != WinnerSort::deferred) + throw std::invalid_argument( + "winner-run sorting requires a winner-preserving method"); + if (o.capture_rank > 256 || (o.method == Method::reference && o.capture_rank)) + throw std::invalid_argument( + "capture requires a winner-preserving method and rank in [1,256]"); + if (!o.capture_rank && o.capture_capacity) + throw std::invalid_argument( + "capture capacity requires capture to be enabled"); + if (o.primitives < PrimitiveMode::scalar || + o.primitives > PrimitiveMode::radik) + throw std::invalid_argument("unknown primitive mode"); + if (o.scale != ScaleMode::off && o.scale != ScaleMode::shift) + throw std::invalid_argument("unknown scale mode"); +} +template +struct ValueView { + const Value* v = nullptr; + const uint32_t* i = nullptr; // null means implicit original positions + const Value* shift_reference = + nullptr; // original input[0], never a compacted C[0] +}; +template +struct ValueBuffer { + Value* v = nullptr; + uint32_t* i = nullptr; + operator ValueView() const { return {v, i}; } +}; +using View = ValueView; +using Buffer = ValueBuffer; +template +inline ValueBuffer offset(ValueBuffer b, uint64_t n) { + return {b.v + n, b.i ? b.i + n : nullptr}; +} +struct Decision { + int bin = -1; + uint32_t h = 0, B = 0, total = 0; + uint32_t captured = 0, + captured_retained = 0; // logical counts include overflowed stores + uint32_t scale_unsafe = + 0; // final shifted histogram: some C failed the bit-exact round trip +}; +struct Pass { + uint32_t candidates, winners, residual; + int digit, bin; + uint32_t h, boundary, potential; + std::string route; + uint32_t captured = 0, captured_retained = 0, capture_capacity = 0, + gather_count = 0; + bool capture_attempted = false, capture_success = false, + capture_overflow = false; + bool shifted = false, scale_unsafe = false; +}; +struct Stage { + std::string name; + float ms; +}; +struct Stats { + std::vector trace; + std::vector stages; + uint32_t final_sorted = 0; + uint32_t histogram_passes = 0; + uint64_t estimated_value_bytes = + 0; // analytical, excludes histogram, indices, sort + uint64_t sorted_values = + 0; // sum of sort input lengths, including trivial one-value runs + std::vector + winner_runs; // nonempty G groups sorted before the final tail + uint32_t capture_attempts = 0, capture_hits = 0, capture_fallbacks = 0, + capture_overflows = 0; + uint64_t captured_values = 0, capture_gather_values = 0; + uint32_t raw_refinement_passes = 0; +}; + +// Backend owns allocation, primitives, and optional audits. This controller is +// used unchanged by the CUDA implementation and executable CPU state model. +template +Stats run(Backend& b, View original, uint32_t n, uint32_t k, Buffer out, + Options o) { + validate(n, k, o); + Stats s; + b.begin(o, &s); + original.shift_reference = o.scale == ScaleMode::shift ? original.v : nullptr; + View C = original; // no initializing N-element copy + uint32_t count = n, w = 0, r = k, prior_better = 0, prefix = 0; + int next = 0; + const bool sorted_runs = o.winner_sort != WinnerSort::deferred; + auto finish = [&](uint32_t m, uint32_t prefix = 0) { + s.final_sorted = m; + s.sorted_values += m; + b.sort(b.potential(), m, offset(out, prefix), k - prefix); + if (prefix) { + b.join_winners(); + b.copy(b.winners(), prefix, out); + } + s.estimated_value_bytes += + 8ull * k; // final output extraction, excludes sorting + }; + const int passes = o.scale == ScaleMode::shift ? 6 : 3; + for (int pass = 0; pass < passes; ++pass) { + const bool shifted = o.scale == ScaleMode::shift && pass < 3; + if (pass == 3) prefix = 0; // collision refinement uses ORIGINAL key bits + if (!(r > 0 && r <= count) || (o.method != Method::reference && w + r != k)) + throw std::logic_error("entry rank invariant"); + if (o.method == Method::early && o.entry_sort && + uint64_t(w) + count <= o.sort_limit) { + uint32_t prefix = sorted_runs ? w : 0; + if (!sorted_runs) b.copy(b.winners(), w, b.potential()); + b.copy(C, count, offset(b.potential(), w - prefix)); + s.estimated_value_bytes += 8ull * (w - prefix + count); + s.trace.push_back( + {count, w, r, pass, -1, 0, count, w + count, "entry_sort"}); + finish(w - prefix + count, prefix); + return s; + } + uint32_t capture_cap = + o.capture_capacity ? std::min(count, o.capture_capacity) : count; + Decision d = o.capture_rank + ? b.capture_histogram(C, count, pass, r, b.candidate(next), + capture_cap, o.capture_rank) + : b.histogram(C, count, pass, r); + ++s.histogram_passes; + if (pass >= 3) ++s.raw_refinement_passes; + s.estimated_value_bytes += 4ull * count; + if (d.total != count || d.bin < 0 || !d.B || d.h >= r || r > d.h + d.B) + throw std::logic_error("histogram/rank invariant"); + uint32_t M = w + d.h + d.B; + prefix |= uint32_t(d.bin) << digit_low(pass); + Pass record{count, w, r, pass, d.bin, d.h, d.B, M, "refine"}; + record.shifted = shifted; + record.scale_unsafe = d.scale_unsafe != 0; + const bool exhausted = pass % 3 == 2 && (!shifted || !d.scale_unsafe); + if (shifted && pass == 2 && d.scale_unsafe) record.route = "raw_refine"; + View gather_src = C; + uint32_t gather_count = count; + int destination = next; + record.gather_count = count; + if (o.capture_rank) { + if (d.captured > count || d.captured_retained > d.h + d.B || + d.captured_retained > d.captured) + throw std::logic_error("capture population invariant"); + record.capture_attempted = true; + record.captured = d.captured; + record.captured_retained = d.captured_retained; + record.capture_capacity = capture_cap; + record.capture_overflow = d.captured > capture_cap; + record.capture_success = + !record.capture_overflow && d.captured_retained == d.h + d.B; + ++s.capture_attempts; + s.captured_values += d.captured; + s.estimated_value_bytes += 4ull * std::min(d.captured, capture_cap); + if (record.capture_success) { + ++s.capture_hits; + gather_src = b.candidate(next); + gather_count = d.captured; + gather_src.shift_reference = original.shift_reference; + // The captured source occupies next. The old candidate buffer + // can become the destination only AFTER coverage succeeds. + destination = next ^ 1; + s.capture_gather_values += gather_count; + } else { + ++s.capture_fallbacks; + if (record.capture_overflow) ++s.capture_overflows; + } + record.gather_count = gather_count; + } + if (o.method == Method::reference) { + prior_better += d.h; + r -= d.h; + record.potential = 0; // W is not preserved in the reference + if (exhausted || d.B == 1) { + uint32_t pivot = prefix; + if (shifted || (d.B == 1 && pass % 3 != 2)) { + b.partition(C, count, pass, d.bin, {}, 0, b.candidate(next), 1, d.h, + d.B); + s.estimated_value_bytes += 4ull * count + 4ull; + pivot = b.first_key(b.candidate(next)); + } + b.filter(original, n, pivot, prior_better, r, b.potential()); + s.estimated_value_bytes += 4ull * n + 4ull * k; + record.route = "pivot_filter"; + s.trace.push_back(record); + finish(k); + return s; + } + b.partition(C, count, pass, d.bin, {}, 0, b.candidate(next), d.B, d.h, + d.B); + s.estimated_value_bytes += 4ull * count + 4ull * d.B; + C = b.candidate(next); + C.shift_reference = original.shift_reference; + count = d.B; + next ^= 1; + } else { + const bool exact = d.h + d.B == r; + const bool small = o.method == Method::early && M <= o.sort_limit; + if (exact || small || exhausted) { + // Last digit: all E keys are identical. Keep exactly r-h + // occurrences without sorting or materializing a huge E. + uint32_t keep_e = exhausted && !small && !exact ? r - d.h : d.B; + uint32_t prefix = sorted_runs ? w : 0; + uint32_t m = w - prefix + d.h + keep_e; + if (!sorted_runs) b.copy(b.winners(), w, b.potential()); + b.partition(gather_src, gather_count, pass, d.bin, + offset(b.potential(), w - prefix), d.h, + offset(b.potential(), w - prefix + d.h), keep_e, d.h, d.B); + s.estimated_value_bytes += + 4ull * gather_count + 4ull * (d.h + keep_e + 2ull * (w - prefix)); + record.route = exact ? "exact" : small ? "early_sort" : "ties"; + s.trace.push_back(record); + finish(m, prefix); + return s; + } + b.partition(gather_src, gather_count, pass, d.bin, offset(b.winners(), w), + d.h, b.candidate(destination), d.B, d.h, d.B); + if (sorted_runs && d.h) { + b.sort_winner_run(w, d.h); + s.winner_runs.push_back(d.h); + s.sorted_values += d.h; + } + s.estimated_value_bytes += 4ull * gather_count + 4ull * (d.h + d.B); + w += d.h; + r -= d.h; + C = b.candidate(destination); + C.shift_reference = original.shift_reference; + count = d.B; + next = destination ^ 1; + } + s.trace.push_back(record); + if (o.debug) { + if (sorted_runs) + b.join_winners(); // validation may read W; excluded from timing + b.audit(original, n, C, count, w, r, k, prior_better, o.method); + } + } + throw std::logic_error("unreachable: all configured key digits exhausted"); +} +} // namespace r2sk diff --git a/csrc/core/kernel/cuda/topk_r2sk/r2sk/cuda.hpp b/csrc/core/kernel/cuda/topk_r2sk/r2sk/cuda.hpp new file mode 100644 index 000000000..287e1edf3 --- /dev/null +++ b/csrc/core/kernel/cuda/topk_r2sk/r2sk/cuda.hpp @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once +#include +#include "core.hpp" +#include "batch_core.hpp" +#include "bfloat16.hpp" +#include + +namespace r2sk { +void cuda_check(cudaError_t error, const char* operation); +// One workspace per concurrent call/stream. Reserve outside timed calls. +// N <= INT_MAX; finite FP32 input and disjoint output/workspace required. +// Indices are uint32 original offsets, not tie-break priorities. +class Workspace { + public: + // enable_winner_runs reserves a separate k-element sort scratch buffer, + // nonblocking stream and dependency events for serial/overlap experiments. + // enable_capture adds a 4096-counter histogram; captured values reuse the + // existing candidate ping-pong buffers. Defaults preserve the original API. + Workspace(uint32_t max_n, uint32_t max_k, uint32_t max_sort_limit, + bool indexed, bool enable_winner_runs = false, + bool enable_capture = false); + ~Workspace(); + Workspace(const Workspace&) = delete; + Workspace& operator=(const Workspace&) = delete; + uint64_t device_bytes() const; + uint64_t pinned_bytes() const; + + private: + struct Impl; + std::unique_ptr impl_; + friend Stats topk(const float*, uint32_t, uint32_t, float*, uint32_t*, + Workspace&, Options, cudaStream_t); +}; +// Host-controlled call: synchronizes for decisions, enqueues final sorting and +// output copy on stream. Caller must synchronize before consuming output or +// releasing/reusing buffers. No cudaMalloc/cudaFree during topk(). +Stats topk(const float* device_input, uint32_t n, uint32_t k, + float* device_output, uint32_t* device_indices, Workspace& workspace, + Options options = {}, cudaStream_t stream = nullptr); + +class BatchWorkspace { + public: + BatchWorkspace(uint32_t max_batch, uint32_t max_n, uint32_t max_k, + uint32_t max_sort_limit, bool indexed, + bool enable_winner_runs = false); + ~BatchWorkspace(); + BatchWorkspace(const BatchWorkspace&) = delete; + BatchWorkspace& operator=(const BatchWorkspace&) = delete; + uint64_t device_bytes() const; + uint64_t pinned_bytes() const; + + private: + struct Impl; + std::unique_ptr impl_; + friend BatchStats topk_batch(const float*, const uint32_t*, uint32_t, + uint32_t, float*, uint32_t*, BatchWorkspace&, + Options, cudaStream_t); +}; +// Concatenated input rows, HOST lengths[batch], common k; output is [batch,k]. +// Indices are relative to each original row. Arbitrary row lengths/offsets are +// supported, including unaligned packed loads. Shifting samples input[0] of +// EACH row. enable_winner_runs reserves a separate per-row sort scratch and +// one shared nonblocking winner stream for serial/overlap controls. +// One workspace per in-flight call; synchronize +// stream before reuse/release. No device allocations inside topk_batch(). +BatchStats topk_batch(const float* device_input, const uint32_t* host_lengths, + uint32_t batch, uint32_t k, float* device_output, + uint32_t* device_indices, BatchWorkspace& workspace, + Options options = {}, cudaStream_t stream = nullptr); + +// Same batch controller, radix digits and primitives, with raw BF16 payloads +// in every global value buffer. Keys/comparisons expand only in registers or +// shared sort staging. No full-array conversion or final BF16 gather is used. +// IEEE BF16 device storage must be contiguous, finite, and aligned to 2 bytes. +// As with BatchWorkspace: one workspace per in-flight call; disjoint output; +// synchronize the caller stream before reuse/destruction. No per-call +// cudaMalloc. +class BFloat16BatchWorkspace { + public: + BFloat16BatchWorkspace(uint32_t max_batch, uint32_t max_n, uint32_t max_k, + uint32_t max_sort_limit, bool indexed, + bool enable_winner_runs = false); + // Borrow device storage owned by the engine. It must be 256-byte aligned, + // disjoint from inputs/outputs and remain live through caller-stream + // completion. This object owns only pinned host metadata/events/streams. + BFloat16BatchWorkspace(uint32_t max_batch, uint32_t max_n, uint32_t max_k, + uint32_t max_sort_limit, bool indexed, + bool enable_winner_runs, void* device_storage, + uint64_t storage_bytes); + static uint64_t required_device_bytes(uint32_t max_batch, uint32_t max_n, + uint32_t max_k, uint32_t max_sort_limit, + bool indexed, + bool enable_winner_runs = false); + // Only after the previous call's caller stream has completed. This never + // frees the old storage and cannot convert an owning workspace to borrowed. + void bind_device_storage(void* device_storage, uint64_t storage_bytes); + uint64_t owned_device_bytes() const; + ~BFloat16BatchWorkspace(); + BFloat16BatchWorkspace(const BFloat16BatchWorkspace&) = delete; + BFloat16BatchWorkspace& operator=(const BFloat16BatchWorkspace&) = delete; + uint64_t device_bytes() const; + uint64_t pinned_bytes() const; + + private: + struct Impl; + std::unique_ptr impl_; + friend BatchStats topk_batch_bf16(const BFloat16*, const uint32_t*, uint32_t, + uint32_t, BFloat16*, uint32_t*, + BFloat16BatchWorkspace&, Options, + cudaStream_t); +}; +BatchStats topk_batch_bf16(const BFloat16* device_input, + const uint32_t* host_lengths, uint32_t batch, + uint32_t k, BFloat16* device_output, + uint32_t* device_indices, + BFloat16BatchWorkspace& workspace, + Options options = {}, cudaStream_t stream = nullptr); +} // namespace r2sk diff --git a/csrc/core/kernel/cuda/topk_r2sk/r2sk/primitive_plan.hpp b/csrc/core/kernel/cuda/topk_r2sk/r2sk/primitive_plan.hpp new file mode 100644 index 000000000..9a8df4645 --- /dev/null +++ b/csrc/core/kernel/cuda/topk_r2sk/r2sk/primitive_plan.hpp @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once +#include "core.hpp" + +namespace r2sk { +// Scalar peel + aligned float4 interior + scalar tail. Never round the input +// pointer down: the caller need not own any values before device_input. +struct PackPlan { + uint32_t peel, packs, tail; + R2SK_HD uint32_t tail_begin() const { return peel + 4 * packs; } +}; +template +R2SK_HD inline PackPlan value_pack_plan(uint64_t address, uint32_t n) { + constexpr uint32_t alignment = 4 * sizeof(Value); + uint32_t peel = + uint32_t((alignment - (address & (alignment - 1))) & (alignment - 1)) / + sizeof(Value); + if (peel > n) peel = n; + uint32_t packs = (n - peel) / 4; + return {peel, packs, n - peel - 4 * packs}; +} +R2SK_HD inline PackPlan pack_plan(uint64_t address, uint32_t n) { + return value_pack_plan(address, n); +} +constexpr uint32_t packed_tile_values = 256 * 4; +R2SK_HD inline bool flush_cache(uint32_t count, uint32_t capacity, + uint32_t next_tile, bool force) { + return count && + (force || capacity < next_tile || count > capacity - next_tile); +} +inline uint32_t gather_shared_bytes(uint32_t gcap, bool indexed, + bool buffered) { + uint32_t capacity = packed_tile_values * (buffered ? 2u : 1u); + uint32_t gslots = std::min(gcap, capacity); + return (gslots + capacity) * 4 * (indexed ? 2u : 1u); +} +} // namespace r2sk diff --git a/csrc/core/kernel/cuda/topk_r2sk/r2sk/workspace_plan.hpp b/csrc/core/kernel/cuda/topk_r2sk/r2sk/workspace_plan.hpp new file mode 100644 index 000000000..5acb56fcb --- /dev/null +++ b/csrc/core/kernel/cuda/topk_r2sk/r2sk/workspace_plan.hpp @@ -0,0 +1,90 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once +#include "batch_core.hpp" +#include +#include + +namespace r2sk { +namespace detail { +template +struct KernelJobT { + ValueView src{}, pivot{}; + ValueBuffer G{}, E{}; + uint32_t n = 0, rank = 0, boundary = 0, gcap = 0, ecap = 0, tile = 0, + width = 0; + int pass = 0; + uint32_t* hist = nullptr; + uint32_t* counters = nullptr; + uint32_t* scale_unsafe = nullptr; + Decision* decision = nullptr; +}; +inline uint32_t batch_descriptor_slots(uint32_t k, uint32_t limit) { + uint32_t levels = 0; + for (uint64_t width = 4096; width < std::max(k, limit); width *= 2) ++levels; + return padded(6 * (12 + 3 * levels) + 1); +} +struct ArenaRegion { + uint64_t offset = 0, bytes = 0; +}; +struct ArenaPlanner { + static constexpr uint64_t alignment = 256; + uint64_t bytes = 0; + ArenaRegion add(uint64_t count, uint64_t element) { + const auto max = std::numeric_limits::max(); + if (bytes > max - (alignment - 1) || (element && count > max / element)) + throw std::overflow_error("workspace size overflow"); + uint64_t start = (bytes + alignment - 1) & ~(alignment - 1), + size = count * element; + if (size > max - start) + throw std::overflow_error("workspace size overflow"); + bytes = start + size; + return {start, size}; + } + uint64_t finish() { + add(0, 1); + return bytes; + } +}; +struct BatchArenaLayout { + // c[0], c[1], winners, potential, sort scratch, winner sort scratch. + std::array values{}, indices{}; + ArenaRegion histogram, metadata, counters, jobs; + uint64_t bytes = 0; + uint32_t descriptor_slots = 0; +}; +template +BatchArenaLayout batch_arena_layout(uint32_t batch, uint32_t n, uint32_t k, + uint32_t limit, bool indexed, bool runs) { + if (!batch || batch > 65535) + throw std::invalid_argument("batch capacity must be in [1,65535]"); + Options o; + o.sort_limit = limit; + validate(n, k, o); + BatchArenaLayout result; + ArenaPlanner p; + result.descriptor_slots = batch_descriptor_slots(k, limit); + uint64_t b = batch, m = std::max(k, limit); + std::array counts{ + {b * n, b * n, b * k, b * m, b * m, runs ? b * k : 0}}; + for (size_t j = 0; j < counts.size(); ++j) { + result.values[j] = p.add(counts[j], sizeof(Value)); + result.indices[j] = p.add(indexed ? counts[j] : 0, sizeof(uint32_t)); + } + result.histogram = p.add(b * 4097, sizeof(uint32_t)); + result.metadata = p.add(b, sizeof(Decision)); + result.counters = p.add(b * 2, sizeof(uint32_t)); + result.jobs = p.add(b * result.descriptor_slots, sizeof(KernelJobT)); + result.bytes = p.finish(); + return result; +} +inline void validate_arena(void* ptr, uint64_t bytes, + const BatchArenaLayout& layout) { + auto address = reinterpret_cast(ptr); + if (!ptr || (address & (ArenaPlanner::alignment - 1)) || + bytes < layout.bytes || + layout.bytes > std::numeric_limits::max() - address) + throw std::invalid_argument( + "workspace arena must be 256-byte aligned and sufficiently large"); +} +} // namespace detail +} // namespace r2sk diff --git a/csrc/core/kernel/cuda/topk_r2sk/sampling.cu b/csrc/core/kernel/cuda/topk_r2sk/sampling.cu new file mode 100644 index 000000000..534ecf4bd --- /dev/null +++ b/csrc/core/kernel/cuda/topk_r2sk/sampling.cu @@ -0,0 +1,183 @@ +// SPDX-License-Identifier: Apache-2.0 +#include "sampling.h" + +#include + +#include +#include +#include + +#include "r2sk/bfloat16_graph.hpp" +#include "r2sk/cuda.hpp" + +namespace allspark::cuda { + +struct R2skSampling::State { + explicit State(int device_id) + : device(device_id), + trace(std::getenv("AS_TRACE_R2SK_EAGER") != nullptr) {} + + ~State() { + if (!fork.stream && !complete && !nonfinite) return; + int previous = device; + const bool restore = + cudaGetDevice(&previous) == cudaSuccess && previous != device; + if (restore) cudaSetDevice(device); + if (prepared.arena) cudaStreamSynchronize(prepared.stream); + if (pending) cudaEventSynchronize(complete); + if (complete) cudaEventDestroy(complete); + if (fork.ready) cudaEventDestroy(fork.ready); + if (fork.done) cudaEventDestroy(fork.done); + if (fork.stream) cudaStreamDestroy(fork.stream); + if (nonfinite) cudaFreeHost(nonfinite); + if (restore) cudaSetDevice(previous); + } + + void Initialize() { + if (nonfinite) return; + if (!fork.stream) + r2sk::cuda_check( + cudaStreamCreateWithFlags(&fork.stream, cudaStreamNonBlocking), + "create eager R2S-K winner stream"); + if (!fork.ready) + r2sk::cuda_check( + cudaEventCreateWithFlags(&fork.ready, cudaEventDisableTiming), + "create eager R2S-K ready event"); + if (!fork.done) + r2sk::cuda_check( + cudaEventCreateWithFlags(&fork.done, cudaEventDisableTiming), + "create eager R2S-K join event"); + if (!complete) + r2sk::cuda_check( + cudaEventCreateWithFlags(&complete, cudaEventDisableTiming), + "create eager R2S-K completion event"); + r2sk::cuda_check(cudaMallocHost(reinterpret_cast(&nonfinite), + sizeof(*nonfinite)), + "allocate eager R2S-K input status"); + } + + struct Selection { + r2sk::BFloat16GraphShape shape; + void* values; + int* indices; + void* arena; + size_t bytes; + cudaStream_t stream; + }; + + int device; + bool trace; + int batch = 0; + int vocabulary = 0; + size_t bytes = 0; + uint32_t* nonfinite = nullptr; + r2sk::BFloat16GraphFork fork; + cudaEvent_t complete = nullptr; + cudaStream_t last_stream = nullptr; + bool pending = false; + Selection prepared{}; +}; + +R2skSampling::R2skSampling(int device) + : state_(std::make_unique(device)) {} +R2skSampling::~R2skSampling() = default; + +size_t R2skSampling::ReserveBytes(int max_batch, int vocabulary) { + auto& s = *state_; + if (s.batch != max_batch || s.vocabulary != vocabulary) { + Wait(); + s.bytes = + max_batch < 1 || max_batch > 65535 || vocabulary <= 2 + ? 0 + : r2sk::bfloat16_graph_bytes({static_cast(max_batch), + static_cast(vocabulary), + static_cast(std::min( + kMaxEagerRank, vocabulary - 1))}); + s.batch = max_batch; + s.vocabulary = vocabulary; + } + return s.bytes; +} + +void R2skSampling::Wait() { + auto& s = *state_; + if (s.prepared.arena) { + r2sk::cuda_check(cudaStreamSynchronize(s.prepared.stream), + "wait for eager R2S-K preparation"); + s.prepared = {}; + } + if (s.pending) { + r2sk::cuda_check(cudaEventSynchronize(s.complete), + "wait for R2S-K scratch"); + s.pending = false; + } +} + +bool R2skSampling::Prepare(const void* logits, void* values, int* indices, + int batch, int vocabulary, int k, void* arena, + size_t arena_bytes, cudaStream_t stream) { + auto& s = *state_; + if (!s.bytes || batch < 1 || batch > s.batch || vocabulary != s.vocabulary || + k < 2 || k > kMaxEagerRank || k >= vocabulary || !logits || !values || + !indices || !arena || reinterpret_cast(arena) % 256 || + arena_bytes < s.bytes) { + return false; + } + cudaStreamCaptureStatus capture; + r2sk::cuda_check(cudaStreamIsCapturing(stream, &capture), + "query R2S-K stream capture status"); + if (capture != cudaStreamCaptureStatusNone) return false; + + if (s.prepared.arena || (s.pending && s.last_stream != stream)) Wait(); + s.Initialize(); + const r2sk::BFloat16GraphShape shape{static_cast(batch), + static_cast(vocabulary), + static_cast(k)}; + // Retain the preparation binding until the stream has completed its flag + // copy. + s.prepared = {shape, values, indices, arena, arena_bytes, stream}; + r2sk::begin_bfloat16_selection(shape, logits, arena, arena_bytes, stream, + s.nonfinite); + return true; +} + +bool R2skSampling::FinishPrepared() { + auto& s = *state_; + const auto a = s.prepared; + s.prepared = {}; + if (!a.arena || *s.nonfinite) return false; + + static_assert(sizeof(int) == sizeof(uint32_t)); + try { + r2sk::finish_bfloat16_selection(a.shape, a.values, + reinterpret_cast(a.indices), + a.arena, a.bytes, a.stream, s.fork); + r2sk::cuda_check(cudaEventRecord(s.complete, a.stream), + "record eager R2S-K completion"); + s.last_stream = a.stream; + s.pending = true; + } catch (...) { + // A launch failure may leave work on either stream. + cudaDeviceSynchronize(); + throw; + } + if (s.trace) { + LOG(INFO) << "R2SK_DEVICE_EAGER batch=" << a.shape.batch + << " k=" << a.shape.k; + } + return true; +} + +bool R2skSampling::Try(const void* logits, void* values, int* indices, + int batch, int vocabulary, int k, void* arena, + size_t arena_bytes, cudaStream_t stream) { + if (!Prepare(logits, values, indices, batch, vocabulary, k, arena, + arena_bytes, stream)) { + return false; + } + r2sk::cuda_check(cudaStreamSynchronize(stream), + "read eager R2S-K input status"); + return FinishPrepared(); +} + +} // namespace allspark::cuda diff --git a/csrc/core/kernel/cuda/topk_r2sk/sampling.h b/csrc/core/kernel/cuda/topk_r2sk/sampling.h new file mode 100644 index 000000000..fa9b37064 --- /dev/null +++ b/csrc/core/kernel/cuda/topk_r2sk/sampling.h @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +#include + +#include +#include + +namespace allspark::cuda { + +// One instance per GenerateOp. Calls are serialized by that operator. +// Device storage is borrowed from the engine's top-k/top-p scratch arena. +class R2skSampling { + public: + static constexpr int kMaxEagerRank = 256; + + explicit R2skSampling(int device); + ~R2skSampling(); + + size_t ReserveBytes(int max_batch, int vocabulary); + void Wait(); + + // Start the first histogram without touching the outputs. Synchronize + // stream before FinishPrepared, which leaves outputs untouched on fallback. + bool Prepare(const void* logits, void* values, int* indices, int batch, + int vocabulary, int k, void* arena, size_t arena_bytes, + cudaStream_t stream); + bool FinishPrepared(); + + // True means the output is enqueued on stream. False leaves the output + // untouched and lets the caller invoke RadiK on that same stream. + bool Try(const void* logits, void* values, int* indices, int batch, + int vocabulary, int k, void* arena, size_t arena_bytes, + cudaStream_t stream); + + private: + struct State; + std::unique_ptr state_; +}; + +} // namespace allspark::cuda diff --git a/csrc/core/operator/generate_opt/generate/generate_impl_cpu.hpp b/csrc/core/operator/generate_opt/generate/generate_impl_cpu.hpp index f25447ba7..89d3ec0f7 100644 --- a/csrc/core/operator/generate_opt/generate/generate_impl_cpu.hpp +++ b/csrc/core/operator/generate_opt/generate/generate_impl_cpu.hpp @@ -124,7 +124,8 @@ AsStatus gen_sample_cpu(DataType dtype, int64_t* total_out_tokens, int max_k, int length, int* k_arr_list, float* p_arr_list, float* temperature_arr_unused, const DeviceContext* ctx, RuntimeContext* runtime_ctx, - void* ws_ptr, size_t ws_bytes, void* device_prop) { + void* ws_ptr, size_t ws_bytes, void* device_prop, + bool) { constexpr int batch_size = 1; for (int i = 0; i < total_batch_size; i++) { GenerateContext* gen_ctx; diff --git a/csrc/core/operator/generate_opt/generate/generate_impl_gpu.hpp b/csrc/core/operator/generate_opt/generate/generate_impl_gpu.hpp index badc6ba37..0709c873b 100644 --- a/csrc/core/operator/generate_opt/generate/generate_impl_gpu.hpp +++ b/csrc/core/operator/generate_opt/generate/generate_impl_gpu.hpp @@ -10,6 +10,8 @@ #include #include +#include +#include #include #include @@ -117,7 +119,8 @@ AsStatus gen_sample_gpu(DataType dtype, int64_t* out_tokens, void* topk_value, int length, int* k_arr, float* p_arr, float* temperature_arr, const DeviceContext* ctx, RuntimeContext* runtime_ctx, void* ws_ptr, - size_t ws_bytes, void* device_prop) { + size_t ws_bytes, void* device_prop, + bool topk_preselected) { if (max_k > length) { LOG(ERROR) << "Top-k: max_k should not exceed length" << std::endl; return AsStatus::ALLSPARK_RUNTIME_ERROR; @@ -134,6 +137,7 @@ AsStatus gen_sample_gpu(DataType dtype, int64_t* out_tokens, void* topk_value, } bool use_torch_sample = ctx->GetUseTorchSample(); + AsStatus status = AsStatus::ALLSPARK_SUCCESS; auto functor = [&]() { cudaStream_t gpu_stream = static_cast(ctx)->GetStream(); T* typed_topk_value = static_cast(topk_value); @@ -159,10 +163,11 @@ AsStatus gen_sample_gpu(DataType dtype, int64_t* out_tokens, void* topk_value, bool topp_input_is_sorted = false; if (max_k != length) { #ifdef CONFIG_ENABLE_RADIX_TOPK - /* radix-based top-k */ - cuda::TopKRadixKernelLauncher(typed_topk_value, topk_indice, - typed_in_logits, ws_ptr, batch_size, - length, max_k, gpu_stream); + if (!topk_preselected) { + cuda::TopKRadixKernelLauncher(typed_topk_value, topk_indice, + typed_in_logits, ws_ptr, batch_size, + length, max_k, gpu_stream); + } #else /* heap-based top-k */ cuda::TopKKernelLauncher(typed_topk_value, topk_indice, typed_in_logits, @@ -196,7 +201,7 @@ AsStatus gen_sample_gpu(DataType dtype, int64_t* out_tokens, void* topk_value, // update each gen_ctx.sample_state by sample_states }; DispatchCUDA(dtype, functor); - return AsStatus::ALLSPARK_SUCCESS; + return status; } void gen_sample_init_gpu(void* sample_states, unsigned long long seed, diff --git a/csrc/core/operator/generate_opt/generate/generate_op.cpp b/csrc/core/operator/generate_opt/generate/generate_op.cpp index fdf288e7c..601f369fc 100644 --- a/csrc/core/operator/generate_opt/generate/generate_op.cpp +++ b/csrc/core/operator/generate_opt/generate/generate_op.cpp @@ -5,10 +5,17 @@ #include "generate_op.h" // NOLINT +#ifdef ENABLE_R2SK_SAMPLING +#include +#include +#endif + #include #include #include +#include +#include #include #ifdef ENABLE_CUDA #include @@ -137,6 +144,25 @@ AsStatus GenerateOp::Init(const OperatorProto& op_proto, rank_info_.rank_id); const CUDAContext* cuda_ctx = static_cast(ctx_); +#ifdef ENABLE_R2SK_SAMPLING + const char* enable_r2sk = std::getenv("AS_ENABLE_R2SK_SAMPLING"); + if (dtype_ == DataType::BFLOAT16 && enable_r2sk && + std::strcmp(enable_r2sk, "1") == 0) { + // The BF16 sampling experiment targets Ampere and newer devices. + int device = cuda_ctx->GetDeviceId(); + int major = 0; + AS_CHECK_CUDA(cudaDeviceGetAttribute( + &major, cudaDevAttrComputeCapabilityMajor, device)); + if (major >= 8) { + r2sk_sampling_ = std::make_shared(device); + const char* graph = std::getenv("AS_ENABLE_R2SK_DECODE_GRAPH"); + if (graph && std::strcmp(graph, "1") == 0) { + r2sk_decode_graph_ = + std::make_shared(device); + } + } + } +#endif rank_id_ = cuda_ctx->GetRank(); nrank_ = cuda_ctx->GetNranks(); break; @@ -410,6 +436,20 @@ AsStatus GenerateOp::Reshape(RuntimeContext* runtime_ctx) { cuda::TopKRadixGetWorkspaceSize(&topk_ws_bytes, max_batch, vocab_size_); }); +#ifdef ENABLE_R2SK_SAMPLING + if (r2sk_sampling_) { + try { + // The workspace tensor may move during SetShape below. + r2sk_sampling_->Wait(); + const size_t r2sk_bytes = + r2sk_sampling_->ReserveBytes(max_batch, vocab_size_); + topk_ws_bytes = std::max(topk_ws_bytes, r2sk_bytes); + } catch (const std::exception& error) { + LOG(ERROR) << "R2S-K workspace planning failed: " << error.what(); + return AsStatus::ALLSPARK_RUNTIME_ERROR; + } + } +#endif if (topk_ws_bytes > std::numeric_limits::max()) { LOG(ERROR) << "radix top-k workspace size too large in " "SampleOp::Reshape()"; @@ -585,15 +625,85 @@ AsStatus GenerateOp::RunSample(RuntimeContext* runtime_ctx) { } #endif // ENABLE_JSON_MODE - // don't remove this sync, otherwise wrong token will generate. +#ifdef ENABLE_R2SK_SAMPLING + bool graph_prepared = false; + if (r2sk_decode_graph_ && !runtime_ctx->is_context && !need_logprobs_ && + nrank_ == 1 && !ctx_->GetUseTorchSample()) { + const auto scratch = reinterpret_cast(ws_ptr); + const auto scores = reinterpret_cast(topk_value_ptr_); + if (scores >= scratch && scores - scratch <= ws_bytes) { + const auto* cuda_ctx = static_cast(ctx_); + try { + graph_prepared = r2sk_decode_graph_->Prepare( + {in_ptr, topk_value_ptr_, topp_value_ptr_, + static_cast(topk_indice_ptr_), + static_cast(out_ptr), sample_states, + static_cast(topk_list_->GetDataPtr()), + static_cast(topp_list_->GetDataPtr()), + static_cast(temperature_list_->GetDataPtr()), ws_ptr, + scores - scratch, ws_bytes, cuda_ctx->GetHiednnHandle(), + cuda_ctx->GetStream(), batch_size_, vocab_size_, max_k_}); + } catch (const std::exception& error) { + LOG(ERROR) << "Failed to prepare decode graph: " << error.what(); + return AsStatus::ALLSPARK_RUNTIME_ERROR; + } + } + } +#endif + +#if defined(ENABLE_R2SK_SAMPLING) && defined(CONFIG_ENABLE_RADIX_TOPK) + bool eager_prepared = false; + if (r2sk_sampling_ && !graph_prepared) { + const auto scratch = reinterpret_cast(ws_ptr); + const auto scores = reinterpret_cast(topk_value_ptr_); + if (scores >= scratch && scores - scratch <= ws_bytes) { + try { + eager_prepared = r2sk_sampling_->Prepare( + in_ptr, topk_value_ptr_, static_cast(topk_indice_ptr_), + batch_size_, vocab_size_, max_k_, ws_ptr, scores - scratch, + static_cast(ctx_)->GetStream()); + } catch (const std::exception& error) { + LOG(ERROR) << "Failed to prepare eager R2S-K: " << error.what(); + return AsStatus::ALLSPARK_RUNTIME_ERROR; + } + } + } +#endif + + // Synchronize per-step host preparation before capture or eager sampling. ctx_->Synchronize(); - kernel_launcher(dtype_, static_cast(out_ptr), topk_value_ptr_, - topp_value_ptr_, static_cast(topk_indice_ptr_), in_ptr, - sample_states, batch_size_, max_k_, vocab_size_, - static_cast(topk_list_->GetDataPtr()), - static_cast(topp_list_->GetDataPtr()), - static_cast(temperature_list_->GetDataPtr()), ctx_, - runtime_ctx, ws_ptr, ws_bytes, device_prop_ptr); + bool sampled = false; + bool topk_preselected = false; +#ifdef ENABLE_R2SK_SAMPLING + if (graph_prepared) { + try { + sampled = r2sk_decode_graph_->LaunchPrepared(); + } catch (const std::exception& error) { + LOG(ERROR) << "Failed to replay decode graph: " << error.what(); + return AsStatus::ALLSPARK_RUNTIME_ERROR; + } + } +#endif +#if defined(ENABLE_R2SK_SAMPLING) && defined(CONFIG_ENABLE_RADIX_TOPK) + if (eager_prepared) { + try { + topk_preselected = r2sk_sampling_->FinishPrepared(); + } catch (const std::exception& error) { + LOG(ERROR) << "Failed to finish eager R2S-K: " << error.what(); + return AsStatus::ALLSPARK_RUNTIME_ERROR; + } + } +#endif + if (!sampled) { + AS_CHECK_STATUS(kernel_launcher( + dtype_, static_cast(out_ptr), topk_value_ptr_, + topp_value_ptr_, static_cast(topk_indice_ptr_), in_ptr, + sample_states, batch_size_, max_k_, vocab_size_, + static_cast(topk_list_->GetDataPtr()), + static_cast(topp_list_->GetDataPtr()), + static_cast(temperature_list_->GetDataPtr()), ctx_, runtime_ctx, + ws_ptr, ws_bytes, device_prop_ptr, topk_preselected)); + } if (need_logprobs_) { logprobs_launcher(dtype_, in_ptr, static_cast(out_ptr), diff --git a/csrc/core/operator/generate_opt/generate/generate_op.h b/csrc/core/operator/generate_opt/generate/generate_op.h index 24bb93d62..e9e948ec3 100644 --- a/csrc/core/operator/generate_opt/generate/generate_op.h +++ b/csrc/core/operator/generate_opt/generate/generate_op.h @@ -6,6 +6,11 @@ #pragma once #include namespace allspark { +namespace cuda { +class R2skSampling; +class R2skDecodeGraph; +} // namespace cuda + class GenerateOp : public AsOperator { public: explicit GenerateOp(const std::string& op_type = "") @@ -39,6 +44,8 @@ class GenerateOp : public AsOperator { int eos_token_id_ = -1; int min_length_ = 10; bool need_logprobs_ = false; + std::shared_ptr r2sk_sampling_; + std::shared_ptr r2sk_decode_graph_; /* deprecated basic params int k_=1; */ @@ -119,14 +126,12 @@ class GenerateOp : public AsOperator { #endif void build_batch_gencfg(RuntimeContext* runtime_ctx, BatchGencfg& batch_gencfg, const DeviceContext* ctx); - AsStatus (*kernel_launcher)(DataType dtype, int64_t* out_tokens, - void* topk_value, void* topp_value, - int* topk_indice, void* in_logits, - void** sample_states, int batch_size, int max_k, - int length, int* k_arr, float* p_arr, - float* temperature_arr, const DeviceContext* ctx, - RuntimeContext* runtime_ctx, void* ws_ptr, - size_t ws_bytes, void* device_prop) = nullptr; + AsStatus (*kernel_launcher)( + DataType dtype, int64_t* out_tokens, void* topk_value, void* topp_value, + int* topk_indice, void* in_logits, void** sample_states, int batch_size, + int max_k, int length, int* k_arr, float* p_arr, float* temperature_arr, + const DeviceContext* ctx, RuntimeContext* runtime_ctx, void* ws_ptr, + size_t ws_bytes, void* device_prop, bool topk_preselected) = nullptr; void (*beam_init_launcher)(DataType dtype, void* beam_score, void* hyps_beam_score, int64_t* hyps_beam_idx, diff --git a/docs/EN/r2sk_cuda_graph.md b/docs/EN/r2sk_cuda_graph.md new file mode 100644 index 000000000..f99b639d8 --- /dev/null +++ b/docs/EN/r2sk_cuda_graph.md @@ -0,0 +1,67 @@ + + +# BF16 R2S-K CUDA Graph experiment + +This branch adds a selector API for a fixed shape and stable device addresses. +It uses the same packed histogram and partition primitives as the ordinary +BF16 path. All route decisions and descriptors stay in device memory and +are rebuilt for every invocation. The caller creates the optional split +stream and its dependency events before capture. + +Pass one consumes the high 12 bits of the ordered BF16 key. If the retained +superset fits the sort limit, a CTA sorts it and writes exactly k outputs. +Otherwise, a packed gather writes confirmed winners to the output prefix and +the boundary candidates to a single scratch buffer. The winner stream sorts +the prefix while the main stream refines the candidates using the last four +BF16 key bits. A final CTA sorts just the selected tail and writes it after +the prefix. The caller stream joins the winner sort before using the output +or recycling scratch. Completed rows skip the second pass using their +device descriptors. The single-stream control uses the same schedule. + +The selector handles finite BF16, signed zeros and infinities. It preserves +raw values and row-relative occurrence indices. NaN rows leave output +untouched and expose an invalid flag through the optional device report. +Callers omitting the report must ensure there are no NaNs. + +## Experimental decode integration + +Set `AS_ENABLE_R2SK_SAMPLING=1` and `AS_ENABLE_R2SK_DECODE_GRAPH=1` on +an R2S-K-enabled build. Eligible single-GPU BF16 decode steps using the +native sampler and `2 <= max_k <= 256` capture the selector, sorted +top-p/softmax, and token draw together. Prefill, log-probability requests, +the Torch-compatible sampler, and unsupported ranks retain existing dispatch. +Before capture or replay, `Prepare()` checks the logits on the GPU and +copies a nonfinite flag to the host. The existing pre-sampling host +synchronization completes that readback. + +GenerateOp still updates the device logits, top-p parameters and RNG +pointer table between launches. Cached graphs are keyed by the active +shape and addresses. Each graph reads the current buffers on replay. The +request bookkeeping and generated-token copy stay outside the graph. The +integration owns this sampler graph. Both `Prepare()` and eager `Try()` +decline when the caller is already capturing, so whole-decode capture cannot +dispatch R2S-K through these entry points. The model forward pass and host +scheduler also remain outside the sampler graph. +HIE-DNN uses external CUDA event nodes for the prefix-sum workspace dependency +so eager calls and graph replays can share the same handle. + +`AS_TRACE_R2SK_DECODE_GRAPH=1` reports graph creation and cache hits. The +decode graph test compares the graph with the eager RadiK plus native +sampling pipeline using matched RNG state and changing logits, temperatures +and top-p cutoffs. + +With a build configured for CUDA and `ENABLE_R2SK_SAMPLING=ON`: + +```sh +ctest --test-dir build -R '^cpp_r2sk_graph_test$' --output-on-failure +ctest --test-dir build -R '^cpp_r2sk_decode_graph_test$' --output-on-failure +compute-sanitizer --tool memcheck --error-exitcode 1 build/bin/cpp_r2sk_sampling_test --graph-test +build/bin/cpp_r2sk_sampling_test --graph-replay /path/to/capture.bin 1 151936 20 +``` + +The test replays different data through one instantiated graph for each +shape and schedule, including concurrent rows that finish on different +passes. The benchmark compares eager RadiK, the engine's device-controlled +eager wrapper, a bare device selector benchmark, and R2S-K graph replay +with and without winner overlap. The engine's eager wrapper handles ranks +through 256. See the [historical results and limits](r2sk_review_validation.md). diff --git a/docs/EN/r2sk_review_validation.md b/docs/EN/r2sk_review_validation.md new file mode 100644 index 000000000..cdd565782 --- /dev/null +++ b/docs/EN/r2sk_review_validation.md @@ -0,0 +1,211 @@ + + +# R2S-K review validation on H100 and B200 + +## Device-controlled eager on H100 + +The opt-in eager sampling path in `b65f08df24bfb2d037a058b1b79c7d270869d411` +uses the two-pass BF16 device controller through `max_k=256`. The first +histogram collects the nonfinite flag, and DashInfer reads it during its +existing pre-sampling synchronization. Nonfinite inputs fall back to RadiK. +The separate sampler graph still requires its own opt-in. + +### Selector sweep + +One NVIDIA H100 80 GB HBM3 ran the CUDA 12.4.131 build targeting `sm_90a`. +The sweep used the reviewer's shape matrix with independently generated, +seed-42 Gaussian and uniform BF16 logits. Vocabulary sizes were 151,936 +and 248,320, batch sizes were 1, 16, 64 and 256, and ranks were 20, 50 +and 256. Every case passed the CPU oracle for descending values and +row-relative occurrence indices. + +| k | Cases | RadiK median / integrated eager median | +| ---: | ---: | ---: | +| 20 | 16 | 1.55–2.18× | +| 50 | 16 | 1.45–2.14× | +| 256 | 16 | 1.31–1.96× | +| All | 48 | 1.31–2.18× (median ratio 1.65×) | + +Each method used 51 complete host-call timings after 12 warmups with +stream completion and preallocated scratch. The integrated eager arm +includes the first histogram's finite check and the flag synchronization. +Its timing IQR was below RadiK's in all 48 cases, and its selector scratch +was 24.0–24.5% smaller. For example, Gaussian logits at vocabulary 151,936, +batch 16 and `k=256` took 98.125 µs with RadiK and 56.498 µs with integrated +eager R2S-K. These are selector results on Hopper. The GB300 retest remains +open. + +To replay the matrix, build the CUDA test binary with +[`ENABLE_R2SK_SAMPLING=ON`](r2sk_sampling.md#validate-and-replay). +The loop below writes a CSV for each case. + +```sh +set -e +mkdir -p results-r2sk-review +for distribution in gaussian uniform; do + for vocabulary in 151936 248320; do + for batch in 1 16 64 256; do + for k in 20 50 256; do + build/bin/cpp_r2sk_sampling_test --graph-replay \ + "$distribution" "$batch" "$vocabulary" "$k" \ + > "results-r2sk-review/${distribution}_n${vocabulary}_b${batch}_k${k}.csv" + done + done + done +done +``` + +The `radik_eager` and `r2sk_device_eager` rows are the matched eager +comparison. The `device_eager` and graph rows measure the bare selector. + +### Streaming Qwen generation + +The same H100 ran Qwen2.5-1.5B-Instruct BF16 at model revision +`989aa7980e4cf806f80c7fef2b1adb7bc71aa306`. Arms used the same source build, +prompts, weights, and sampling settings (top-p 0.8, temperature 0.7, +repetition penalty 1.1). Each configuration had 20 timed cohorts across +four blocks with rotated order and 96 output tokens per request. TTFT +and TPOT use engine result-queue delivery timestamps. + +| k | Concurrency | Backend | TTFT p50 ms | TPOT p50 ms | Cohort p50 ms | Output tokens/s | +| ---: | ---: | --- | ---: | ---: | ---: | ---: | +| 20 | 1 | Eager RadiK | 4.789 | 3.893 | 374.587 | 256.3 | +| 20 | 1 | Eager R2S-K | 4.803 | 3.880 | 373.565 | 257.0 | +| 20 | 1 | Graph R2S-K | 4.650 | 3.764 | 362.303 | 265.0 | +| 20 | 16 | Eager RadiK | 55.644 | 4.468 | 510.178 | 3010.7 | +| 20 | 16 | Eager R2S-K | 52.508 | 4.352 | 495.128 | 3102.2 | +| 20 | 16 | Graph R2S-K | 52.213 | 4.331 | 497.491 | 3087.5 | +| 256 | 1 | Eager RadiK | 4.641 | 3.810 | 366.699 | 261.8 | +| 256 | 1 | Eager R2S-K | 4.560 | 3.771 | 362.798 | 264.6 | +| 256 | 1 | Graph R2S-K | 4.586 | 3.740 | 359.968 | 266.7 | +| 256 | 16 | Eager RadiK | 52.034 | 4.398 | 502.603 | 3056.1 | +| 256 | 16 | Eager R2S-K | 50.721 | 4.331 | 493.792 | 3110.6 | +| 256 | 16 | Graph R2S-K | 54.455 | 4.382 | 500.222 | 3070.6 | + +At `k=20`, concurrency 16, eager R2S-K reduced median cohort latency by +2.95%, with lower medians in all four blocks and separated cohort timing +IQRs. The eager-vs-eager cohort timing IQRs overlap in the other three +configurations. Separate traces confirmed the new eager selector and +sampler graph both dispatched at active batches 1 and 16 for `k=256`. +The serving trial excludes HTTP transport and did not measure answer +quality for this revision. + +The eager selector, graph replay and decode sampling parity tests all +passed on the same H100. The [Modal run](https://modal.com/apps/siraajr/main/ap-TmaWgTSrJkrMAUOZ4D56W4) +stored the 12,240 selector timing samples and 2,040 per-request timing +rows under `dash-decode-20261125T085342Z` in the `r2sk-results` volume. +The exact model prompts and serving runner are in the separate +`radik-design` workspace. + +## Earlier H100 validation + +The earlier H100 model tests used DashInfer commit `71592904387d42e792bd3dd296525cbb89f454b8`, +CUDA 12.4.1 targeting `sm_90a`, and one NVIDIA H100 80 GB HBM3. The model +was Qwen2.5-1.5B-Instruct BF16 at revision +`989aa7980e4cf806f80c7fef2b1adb7bc71aa306`. Each backend used the same DashInfer +binary and model files. All backends used `top_k=20`, `top_p=0.8`, temperature +`0.7`, and repetition penalty `1.1`. + +### Full request latency + +Each sample measured warmed request submission through completion, including +prefill, decode, and sampling. Every request generated 96 tokens. Prefix +caching, early stopping, and dispatch tracing were disabled during timing. +Each arm had 20 measured cohorts across four blocks with rotated arm order. +Separate traces verified cache-hit graph launches at active batch 1 and 16. + +| Concurrent requests | Backend | Median ms | Middle 50% ms | Output tokens/s | +| ---: | --- | ---: | ---: | ---: | +| 1 | Native RadiK | 396.65 | 394.83–404.46 | 242.0 | +| 1 | Eager R2S-K | 390.05 | 386.96–395.63 | 246.1 | +| 1 | Graph R2S-K | 389.09 | 386.91–390.47 | 246.7 | +| 16 | Native RadiK | 584.18 | 575.11–596.18 | 2629.3 | +| 16 | Eager R2S-K | 577.21 | 571.32–593.42 | 2661.1 | +| 16 | Graph R2S-K | 578.62 | 571.44–589.80 | 2654.6 | + +Graph R2S-K reduced median latency relative to RadiK by 1.90% at batch 1 and +0.95% at batch 16. It had lower medians in four of four and three of four +paired blocks, respectively. The batch-16 IQRs overlap, and eager R2S-K had +the lowest batch-16 median by 1.4 ms. This run leaves a graph-specific +end-to-end improvement over eager R2S-K unresolved. + +### Sampled GSM8K accuracy + +The matched evaluation used 200 questions and two seeds, 1234 and 5678, with +requested concurrency 16. Native A and B were independent runs of the same +RadiK backend. Output was scored by the same automatic numeric extractor in +every arm. The extractor was fixed before generation. Unresolved answers +counted as incorrect. The graph arm recorded 3,182 cached launches at active +batch 16 during GSM8K generation. + +| Backend | Correct | Accuracy | Unresolved answers | +| --- | ---: | ---: | ---: | +| Native A | 174/400 | 43.50% | 35 | +| Native B | 183/400 | 45.75% | 38 | +| Graph R2S-K | 177/400 | 44.25% | 27 | + +Graph R2S-K differed from native A by +0.75 percentage points (95% paired +question-bootstrap interval −2.50 to +3.75) and from native B by −1.50 +points (−5.25 to +2.25). Native B differed from native A by +2.25 points +(−0.50 to +5.00). These intervals leave both regression and improvement +possible. Quality equivalence remains unverified. + +## Build and CI + +The CUDA package CI matrix enables `ENABLE_R2SK_SAMPLING` and verifies the +selector and decode parity executables were built. This is compile-only +coverage. The earlier CPU builder marked the selector CTests as skipped. +The standalone selector, selector graph, and integrated sampler parity tests +passed on Modal H100. + +The manually dispatched **R2S-K GPU correctness** workflow targets a +self-hosted `gpu` runner with NVIDIA container support and an Ampere, Ada or +Hopper GPU. It directly runs all three test entry points, so a skipped test +fails the job. GPU execution in GitHub Actions remains unverified. + +The selector and graph sources passed the repository's clang-format rules. +Clang's raw token streams matched before and after formatting for all 11 +changed sources. Prior HIE-DNN mixed-count initcheck findings remain open. + +## H100 model experiment artifacts + +The historical full-model experiment used a separate `radik-design` runner +and cached public Qwen and GSM8K inputs. Its exact prompt set, runner and +raw artifacts are outside this checkout. The [selector reproduction](r2sk_sampling.md#validate-and-replay) +uses generated inputs and runs from this repository. + +The [Modal run](https://modal.com/apps/siraajr/main/ap-RQTqTAc3MEhBQQP9pP9xla) +saved build logs, all 120 timing samples, and all 1,200 scored responses under +`dash-decode-20261124T040747Z` in the `r2sk-results` volume. + +## Historical large-k selector validation on B200 + +The standalone selector suite ran on one B200 with CUDA 13.1.115 targeting +`sm_100`, from source revision `779a20e267ea9077d389d7939999448f20dcb5ce`. +The standalone build omitted an unused NCCL include from the shared CUDA +header. The selector and graph correctness tests completed, and each timed +variant passed the CPU oracle for sorted BF16 scores and indices. + +Inputs were BF16 Gaussian logits generated with seed 42, vocabulary 151,936, +and `k=256`. Results are complete-call host medians in microseconds, with +51 repetitions per method after 12 warmups. Median timings include stream +completion. Graph instantiation is outside the timed region. + +| Batch | Native RadiK | Original eager R2S-K | Device-controlled eager R2S-K | Graph R2S-K with overlap | +| ---: | ---: | ---: | ---: | ---: | +| 1 | 86.357 | 65.821 | 37.507 | 32.473 | +| 16 | 93.605 | 97.485 | 48.158 | 43.569 | +| 64 | 122.300 | 150.834 | 86.600 | 82.565 | + +Before the dispatch cutoff, eager `R2skSampling::Try` was 4.1% slower than +RadiK at batch 16 and 23.3% slower at batch 64 on this workload. Commit +`a4cd8ce` capped the old eager path at 50 to avoid that regression. +The device-controlled eager column measured the bare selector. It reduced latency +relative to eager RadiK by 56.6%, 48.6%, and 29.2% at batches 1, 16, and +64, respectively, with separated timing IQRs and about 24% less selector +scratch. + +The graph column compares R2S-K replay with eager RadiK. The newer eager +engine wrapper reuses this device controller and includes a finite-input +check in its first histogram. The B200 numbers above predate that wrapper. +The reviewer's GB300 retest remains outstanding. diff --git a/docs/EN/r2sk_sampling.md b/docs/EN/r2sk_sampling.md new file mode 100644 index 000000000..ea6703d58 --- /dev/null +++ b/docs/EN/r2sk_sampling.md @@ -0,0 +1,102 @@ + + +# Experimental R2S-K token sampling + +R2S-K refines a radix boundary while saving confirmed winners. When the +complete set of possible results fits a block sort, it sorts the set and +returns the first k entries. The backend produces descending BF16 values and +row-relative 32-bit token indices for DashInfer's existing top-p sampler. +Equal values may have different token order or membership at the cutoff. + +## Enable it + +On a Linux CUDA development machine, follow the [source build setup](installation.md#build-from-source). +Set `ENABLE_R2SK_SAMPLING=ON` in CMake, or build with the following environment. +Set `AS_CUDA_VERSION` and `AS_CUDA_SM` to match your toolkit and GPU. This example +targets an L40S with CUDA 12.4. + +```sh +AS_BUILD_R2SK_SAMPLING=ON AS_CUDA_VERSION=12.4 AS_CUDA_SM=89 bash build.sh +``` + +Set `AS_ENABLE_R2SK_SAMPLING=1` before starting the source-built engine and +loading a BF16 model. Leave it unset for the RadiK default in the same build. +The eager backend applies to token sampling with compute capability 8.0 or +newer, finite BF16 logits, and `2 <= max_k <= 256` where +`max_k < vocabulary`. The bound applies to the largest requested k in +the active batch. The existing launcher uses RadiK when eager R2S-K +declines the call. +The first histogram checks for NaN and infinities and sends that batch to +RadiK before writing any R2S-K output. Greedy, full-vocabulary and non-BF16 +requests retain the existing dispatch. + +The operator borrows the shared top-k/top-p arena and reserves space for +its configured maximum batch. The eager path runs the BF16 selector's two +radix passes with per-row device decisions. Its first histogram checks +input finiteness, and the flag is read during the engine's existing +pre-sampling synchronization. A nonfinite flag leaves the output untouched +for RadiK fallback. A pinned flag, winner stream and events are allocated +on first use. The caller stream joins the winner stream before reusing scratch. + +Set `AS_ENABLE_R2SK_DECODE_GRAPH=1` in addition to the build and runtime +opt-ins to enable the [experimental sampler graph](r2sk_cuda_graph.md). +The graph applies to eligible single-GPU decode with the native sampler +and no requested log probabilities, with `2 <= max_k <= 256`. +All three settings default to off. + +## Validate and replay + +Build with `BUILD_UTEST=ON`, then run: + +```sh +ctest --test-dir build --no-tests=error -R '^cpp_r2sk_(sampling|graph|decode_graph)_test$' --output-on-failure +compute-sanitizer --tool memcheck --error-exitcode 1 build/bin/cpp_r2sk_sampling_test +compute-sanitizer --tool synccheck --error-exitcode 1 build/bin/cpp_r2sk_sampling_test +``` + +Run the source-built engine on a BF16 generation request with `top_k=20`, +first with `AS_ENABLE_R2SK_SAMPLING=1`, then with the variable unset. Exercise +concurrent requests with different k and a log-probability request as separate +integration checks. A source-built Python run needs bindings from the same +checkout if the application uses Python. + +For the B200 selector workload, run the standalone build and benchmark on +a Linux CUDA machine with `nvcc`, `protoc`, protobuf development headers +and libraries, and glog development headers and libraries. Pass the CUDA +target for the GPU, such as `90` for H100 or `100` for B200. + +```sh +bash scripts/bench_r2sk_selector.sh 100 results-b200 +``` + +The harness generates BF16 Gaussian logits with seed 42 for `k=256` and +batches 1, 16 and 64. It checks eager dispatch and selector graph replay, +then saves raw timing CSVs for eager RadiK, integrated eager R2S-K, the +bare device selector, and graph replay with and without overlap. The +earlier host-controlled eager arm is recorded in the historical results. +This benchmark runs without model downloads, external fixtures or a Modal +account. + +The same test binary can replay captured pre-top-k logits for eager-eligible +shapes as a dense, little-endian `[batch,vocabulary]` array of BF16 words. +It validates both outputs before timing and reports complete host call +latency including stream completion, plus the scratch requirement for each +selector. Use a capture you provide and pass its shape: + +```sh +build/bin/cpp_r2sk_sampling_test --replay /path/to/capture_0.bin 1 151936 20 > replay.csv +``` + +The source-built replay measures selection only. Full generation also +includes the model forward pass, top-p and token sampling. + +## Attribution + +The controller and CUDA primitives are ported from Siraaj Rizvi's private +`radik-design` prototype, revision +`eae1d0c25341e47b0b76970e24c6bb8731e6d4d9`. The prototype has no +repository-wide license. The code contributed here carries DashInfer's +Apache-2.0 license. The low-level histogram, scan and compaction primitives +were informed by RadiK revision +`c934b15d45655bec1cf4fdc4fcb04ba4f31511cf`. See the retained Alibaba copyright +and MIT notice in `csrc/core/kernel/cuda/topk_r2sk/LICENSE.RadiK`. diff --git a/scripts/bench_r2sk_selector.sh b/scripts/bench_r2sk_selector.sh new file mode 100644 index 000000000..3d23be395 --- /dev/null +++ b/scripts/bench_r2sk_selector.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: Apache-2.0 +set -euo pipefail + +if [[ $# != 2 || ! $1 =~ ^[0-9]+[a-z]?$ ]]; then + echo "Usage: bash $0 " >&2 + exit 2 +fi +src=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd) +arch=$1 +mkdir -- "$2" +out=$(cd -- "$2" && pwd) +build="$out/build" +mkdir -p "$build/utility" + +{ + for tool in nvcc nvidia-smi protoc; do + command -v "$tool" >/dev/null || { echo "Missing required tool: $tool" >&2; exit 1; } + done + git -C "$src" rev-parse HEAD + printf 'CUDA target sm_%s\nCUDA_VISIBLE_DEVICES=%s\n' "$arch" "${CUDA_VISIBLE_DEVICES:-}" + nvidia-smi --query-gpu=name,compute_cap,driver_version --format=csv + nvcc --version + protoc --version + + # The single-GPU selector doesn't use NCCL. Override the include in a + # build-local copy so no NCCL headers or library are needed. + sed '/^#include $/d' "$src/csrc/utility/check_cuda.h" > "$build/utility/check_cuda.h" + protoc -I "$src/csrc/proto" --cpp_out="$build" "$src/csrc/proto/allspark.proto" + + kernel="$src/csrc/core/kernel/cuda" + flags=(-std=c++17 -O3 -DENABLE_CUDA -DENABLE_BF16 "-arch=sm_$arch" + "-I$build" "-I$src/csrc" "-I$src/csrc/common" "-I$src/csrc/device" + "-I$src/csrc/device/cuda" "-I$src/csrc/utility" "-I$src/HIE-DNN/include" "-I$kernel/..") + objects=() + for source in topk_r2sk/r2sk.cu topk_r2sk/sampling.cu topk_radix/topk_radix_bf16.cu; do + obj="$build/${source##*/}.o" + nvcc "${flags[@]}" --extended-lambda --expt-relaxed-constexpr -lineinfo \ + -c "$kernel/$source" -o "$obj" + objects+=("$obj") + done + binary="$build/cpp_r2sk_sampling_test" + nvcc "${flags[@]}" -cudart=shared "$src/tests/cpp/kernel/cuda_r2sk_sampling_test.cpp" \ + "${objects[@]}" -lglog -lprotobuf -o "$binary" + + "$binary" + "$binary" --graph-test + for batch in 1 16 64; do + echo "Checking and timing BF16 Gaussian, batch=$batch, vocab=151936, k=256" + "$binary" --graph-replay gaussian "$batch" 151936 256 > "$out/b${batch}_n151936_k256.csv" + done +} 2>&1 | tee "$out/run.log" diff --git a/tests/cpp/CMakeLists.txt b/tests/cpp/CMakeLists.txt index 2c3e5a9f7..6dad786a8 100644 --- a/tests/cpp/CMakeLists.txt +++ b/tests/cpp/CMakeLists.txt @@ -117,3 +117,26 @@ add_test(NAME cpp_interface_test add_test(NAME cpp_operator_test COMMAND ${CMAKE_BINARY_DIR}/bin/cpp_operator_test) add_test(NAME cpp_model_test COMMAND ${CMAKE_BINARY_DIR}/bin/cpp_model_test) +if (ENABLE_R2SK_SAMPLING) + add_executable(cpp_r2sk_sampling_test kernel/cuda_r2sk_sampling_test.cpp) + set_target_properties(cpp_r2sk_sampling_test PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin") + target_link_libraries(cpp_r2sk_sampling_test PRIVATE allspark_kernel + ${AS_CUDA_CUDART} ${AS_CUDA_CUBLAS} ${HIEDNN_LIBRARY} + CONAN_PKG::glog CONAN_PKG::protobuf) + add_dependencies(cpp_r2sk_sampling_test protobuf_target project_hiednn) + add_test(NAME cpp_r2sk_sampling_test COMMAND cpp_r2sk_sampling_test) + set_tests_properties(cpp_r2sk_sampling_test PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME cpp_r2sk_graph_test COMMAND cpp_r2sk_sampling_test --graph-test) + set_tests_properties(cpp_r2sk_graph_test PROPERTIES SKIP_RETURN_CODE 77) + add_executable(cpp_r2sk_decode_graph_test kernel/cuda_r2sk_decode_graph_test.cu) + set_target_properties(cpp_r2sk_decode_graph_test PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin") + target_compile_features(cpp_r2sk_decode_graph_test PRIVATE cuda_std_17) + target_link_libraries(cpp_r2sk_decode_graph_test PRIVATE allspark_kernel + ${AS_CUDA_CUDART} ${AS_CUDA_CUBLAS} ${HIEDNN_LIBRARY} + CONAN_PKG::glog CONAN_PKG::protobuf) + add_dependencies(cpp_r2sk_decode_graph_test protobuf_target project_hiednn) + add_test(NAME cpp_r2sk_decode_graph_test COMMAND cpp_r2sk_decode_graph_test) + set_tests_properties(cpp_r2sk_decode_graph_test PROPERTIES SKIP_RETURN_CODE 77) +endif() diff --git a/tests/cpp/kernel/cuda_r2sk_decode_graph_test.cu b/tests/cpp/kernel/cuda_r2sk_decode_graph_test.cu new file mode 100644 index 000000000..052c115ec --- /dev/null +++ b/tests/cpp/kernel/cuda_r2sk_decode_graph_test.cu @@ -0,0 +1,219 @@ +// SPDX-License-Identifier: Apache-2.0 +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +using Bf16 = hie::bfloat16; +constexpr int kBatch = 2; +constexpr int kVocab = 2053; +constexpr int kRank = 20; + +void Check(cudaError_t result) { + if (result != cudaSuccess) + throw std::runtime_error(cudaGetErrorString(result)); +} +void Require(bool value, const char* message) { + if (!value) throw std::runtime_error(message); +} +void CheckHie(hiednnStatus_t result) { + Require(result == HIEDNN_STATUS_SUCCESS, "HIE-DNN status"); +} + +struct Stream { + Stream() { Check(cudaStreamCreateWithFlags(&value, cudaStreamNonBlocking)); } + ~Stream() { cudaStreamDestroy(value); } + cudaStream_t value; +}; + +struct HieHandle { + explicit HieHandle(cudaStream_t stream) { + CheckHie(hiednnCreateCudaHandle(&value)); + CheckHie(hiednnSetCudaStream(value, stream)); + } + ~HieHandle() { hiednnDestroyCudaHandle(value); } + hiednnCudaHandle_t value; +}; + +template +struct Buffer { + explicit Buffer(size_t count) { + Check(cudaMalloc(reinterpret_cast(&data), sizeof(T) * count)); + } + ~Buffer() { cudaFree(data); } + T* data = nullptr; +}; + +template +void Upload(Buffer& buffer, const T* data, size_t count, + cudaStream_t stream) { + Check(cudaMemcpyAsync(buffer.data, data, sizeof(T) * count, + cudaMemcpyHostToDevice, stream)); +} + +template +std::vector Read(const Buffer& buffer, size_t count) { + std::vector data(count); + Check(cudaMemcpy(data.data(), buffer.data, count * sizeof(T), + cudaMemcpyDeviceToHost)); + return data; +} + +struct Arm { + explicit Arm(size_t bytes) : scratch(bytes) {} + Buffer scores{kBatch * kRank}; + Buffer tmp{kBatch * kRank}; + Buffer indices{kBatch * kRank}, counts{kBatch}; + Buffer tokens{kBatch}; + Buffer state{kBatch}; + Buffer rng{kBatch}; + Buffer scratch; +}; + +void Run(int device) { + using namespace allspark::cuda; + Stream queue; + const auto stream = queue.value; + HieHandle handle(stream); + Buffer logits(kBatch * kVocab); + Buffer p(kBatch), temperature(kBatch); + size_t radik_bytes = 0, topp_bytes = 0; + TopKRadixGetWorkspaceSize(&radik_bytes, kBatch, kVocab); + TopPSoftmaxGetWorkspaceSize(&topp_bytes, kBatch, kRank, true); + size_t bytes = std::max({radik_bytes, topp_bytes, + static_cast(r2sk::bfloat16_graph_bytes( + {kBatch, kVocab, kRank}))}); + Arm eager(bytes), graph(bytes); + Buffer alternate_tmp(kBatch * kRank); + R2skDecodeGraph selector(device); + for (auto* a : {&eager, &graph}) { + for (int row = 0; row < kBatch; ++row) { + SampleKernelInitLauncher(a->state.data + row, 1234 + row, 1, stream); + } + } + + std::vector input(kBatch * kVocab); + const std::array initial_counts{kRank, kRank - 3}; + int graph_launches = 0; + for (int step = 0; step < 20; ++step) { + std::fill(input.begin(), input.end(), uint16_t{0x3f80}); + for (int j = 0; j < kRank + 7; ++j) { + input[(step * 7 + j) % kVocab] = 0x4000 + j; + } + for (int j = 0; j < 24; ++j) { + // Row one has nine higher-bin winners, fifteen distinct upper-boundary + // values, and a large boundary bin. Its sorted selected values are + // unique. + input[kVocab + (step * 13 + j) % kVocab] = + j < 9 ? 0x4000 + j : 0x3f81 + j - 9; + } + const bool invalid = step == 8 || step == 12; + if (step == 8) input.back() = 0x7fc1u; + if (step == 12) input.back() = 0xff80u; + Upload(logits, input.data(), input.size(), stream); + const std::array top_p{0.70f + (step % 3) * 0.1f, 0.85f}; + const std::array temp{0.65f, 0.85f + (step % 2) * 0.2f}; + Upload(p, top_p.data(), top_p.size(), stream); + Upload(temperature, temp.data(), temp.size(), stream); + for (auto* a : {&eager, &graph}) { + // Pointer table stays in place across graph launches. Swap its contents + // to model active requests changing slots in the packed decode batch. + const int first = step >= 10 ? 1 : 0; + const std::array states{a->state.data + first, + a->state.data + (1 - first)}; + Upload(a->rng, states.data(), states.size(), stream); + Upload(a->counts, initial_counts.data(), initial_counts.size(), stream); + Check(cudaMemsetAsync(a->tokens.data, 0xcc, kBatch * sizeof(int64_t), + stream)); + // Host arrays above may go out of scope after completion of these copies. + Check(cudaStreamSynchronize(stream)); + } + // Switch buffers to capture a second graph after eager work used the + // handle. + auto* temp_probs = step % 2 ? alternate_tmp.data : graph.tmp.data; + Require(selector.Prepare( + {logits.data, graph.scores.data, temp_probs, graph.indices.data, + graph.tokens.data, graph.rng.data, graph.counts.data, p.data, + temperature.data, graph.scratch.data, bytes, bytes, + handle.value, stream, kBatch, kVocab, kRank}), + "valid graph shape failed preflight"); + Check(cudaStreamSynchronize(stream)); + Require(selector.LaunchPrepared() == !invalid, "preflight result mismatch"); + Check(cudaStreamSynchronize(stream)); + if (invalid) { + Require(Read(graph.tokens, kBatch) == Read(eager.tokens, kBatch), + "rejected graph changed its tokens"); + continue; + } + ++graph_launches; + + auto* scores = reinterpret_cast(eager.scores.data); + TopKRadixKernelLauncher(scores, eager.indices.data, + reinterpret_cast(logits.data), + eager.scratch.data, kBatch, kVocab, kRank, stream); + TopPSoftmaxLauncher( + eager.counts.data, scores, eager.indices.data, + static_cast(scores), p.data, temperature.data, + reinterpret_cast(eager.tmp.data), eager.scratch.data, bytes, + kBatch, kRank, true, handle.value, stream); + SampleKernelLauncher(eager.tokens.data, eager.rng.data, scores, + eager.indices.data, kBatch, eager.counts.data, kRank, + stream, nullptr); + Check(cudaStreamSynchronize(stream)); + + const auto counts = Read(graph.counts, kBatch); + Require(counts == Read(eager.counts, kBatch), "top-p counts differ"); + const auto ids = Read(graph.indices, kBatch * kRank); + Require(ids == Read(eager.indices, kBatch * kRank), + "top-k ranked IDs differ"); + const auto logits_graph = Read(graph.scores, kBatch * kRank); + const auto logits_eager = Read(eager.scores, kBatch * kRank); + for (int row = 0; row < kBatch; ++row) { + for (int rank = 0; rank < counts[row]; ++rank) { + const int j = row * kRank + rank; + Require(logits_graph[j] == logits_eager[j], + "top-p probabilities differ"); + } + } + Require(Read(graph.tokens, kBatch) == Read(eager.tokens, kBatch), + "graph and eager sampled tokens differ"); + } + Require(graph_launches == 18, "unexpected replay count"); + std::cout << "PASS decode sampling parity: 18 graph calls, two captured " + "bindings, changing logits, top-p, " + "temperatures and RNG pointers, exact probabilities and tokens, " + "NaN and infinity fallback.\n"; +} + +} // namespace + +int main() { + try { + int devices = 0; + const auto status = cudaGetDeviceCount(&devices); + if (status == cudaErrorNoDevice || status == cudaErrorInsufficientDriver || + (status == cudaSuccess && devices == 0)) { + std::cout << "R2S-K decode graph tests require a visible CUDA device\n"; + return 77; + } + Check(status); + int device = 0, major = 0; + Check(cudaGetDevice(&device)); + Check(cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, + device)); + if (major < 8) return 77; + Run(device); + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/tests/cpp/kernel/cuda_r2sk_sampling_test.cpp b/tests/cpp/kernel/cuda_r2sk_sampling_test.cpp new file mode 100644 index 000000000..6e2ca47b3 --- /dev/null +++ b/tests/cpp/kernel/cuda_r2sk_sampling_test.cpp @@ -0,0 +1,597 @@ +// SPDX-License-Identifier: Apache-2.0 +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +void Check(cudaError_t status) { + if (status != cudaSuccess) + throw std::runtime_error(cudaGetErrorString(status)); +} + +void Require(bool condition, const char* message) { + if (!condition) throw std::runtime_error(message); +} + +struct Stream { + Stream() { Check(cudaStreamCreateWithFlags(&value, cudaStreamNonBlocking)); } + ~Stream() { cudaStreamDestroy(value); } + cudaStream_t value; +}; + +template +struct DeviceBuffer { + explicit DeviceBuffer(size_t count) { + Check(cudaMalloc(reinterpret_cast(&data), sizeof(T) * count)); + } + ~DeviceBuffer() { cudaFree(data); } + T* data; +}; + +float Decode(uint16_t bf16) { + const uint32_t bits = static_cast(bf16) << 16; + float value; + std::memcpy(&value, &bits, sizeof(value)); + return value; +} + +void TestSampling(int device, cudaStream_t stream) { + constexpr int n = + 2053; // Odd length exercises packed tails and row alignment. + constexpr int max_batch = 3; + constexpr int max_k = 256; + std::vector input(max_batch * n, 0x3f80); // All-tied first row. + for (int i = 0; i < n; ++i) { + input[n + i] = static_cast(0xbf80 + (i * 23) % 128); + input[2 * n + i] = (i % 2 == 0) ? 0 : 0x8000; + } + // Sparse maxima in the negative row exercise an early sort. + for (int i = 0; i < 31; ++i) input[n + 37 * i] = 0x3f00 + i; + // Enough positive zeros remain to force refinement while the saved + // positive winners in this row can be sorted on the second stream. + for (int i = 0; i < 5; ++i) input[2 * n + i] = 0x4000 + i; + + allspark::cuda::R2skSampling selector(device); + const size_t bytes = selector.ReserveBytes(max_batch, n); + Require(bytes > 0, "missing R2S-K scratch requirement"); + DeviceBuffer logits(input.size()); + DeviceBuffer values(max_batch * max_k + 2); + DeviceBuffer indices(max_batch * max_k + 2); + DeviceBuffer first(bytes), second(bytes); + Check(cudaMemcpy(logits.data, input.data(), input.size() * sizeof(uint16_t), + cudaMemcpyHostToDevice)); + + for (int batch : {3, 1, 2, 3}) { + for (int k : {2, 20, 50, 51, 256}) { + auto* scratch = k == 20 ? first.data : second.data; + std::vector selected(batch * k + 2); + std::vector ids(batch * k + 2); + Check(cudaMemsetAsync(values.data, 0xcc, + selected.size() * sizeof(uint16_t), stream)); + Check(cudaMemsetAsync(indices.data, 0xcc, ids.size() * sizeof(int), + stream)); + Require(selector.Prepare(logits.data, values.data + 1, indices.data + 1, + batch, n, k, scratch, bytes, stream), + "BF16 preparation fell back unexpectedly"); + Check(cudaStreamSynchronize(stream)); + Require(selector.FinishPrepared(), "finite BF16 selection fell back"); + Require(!selector.FinishPrepared(), "preparation was consumed twice"); + // The real top-p stage also reuses this storage on the caller stream. + Check(cudaMemsetAsync(scratch, 0xa5, bytes, stream)); + Check(cudaMemcpyAsync(selected.data(), values.data, + selected.size() * sizeof(uint16_t), + cudaMemcpyDeviceToHost, stream)); + Check(cudaMemcpyAsync(ids.data(), indices.data, ids.size() * sizeof(int), + cudaMemcpyDeviceToHost, stream)); + Check(cudaStreamSynchronize(stream)); + Require(selected.front() == 0xcccc && selected.back() == 0xcccc && + static_cast(ids.front()) == 0xcccccccc && + static_cast(ids.back()) == 0xcccccccc, + "output guards were overwritten"); + for (int row = 0; row < batch; ++row) { + std::vector expected(n); + std::vector used(n); + for (int j = 0; j < n; ++j) expected[j] = Decode(input[row * n + j]); + std::partial_sort(expected.begin(), expected.begin() + k, + expected.end(), std::greater{}); + for (int j = 0; j < k; ++j) { + const int out = 1 + row * k + j; + const int id = ids[out]; + Require(id >= 0 && id < n && !used[id], "invalid or duplicate index"); + used[id] = true; + Require(selected[out] == input[row * n + id], "key/index mismatch"); + Require(Decode(selected[out]) == expected[j], + "incorrect sorted top-k"); + } + } + } + } + std::vector saved(input.size()); + Check(cudaMemcpy(saved.data(), logits.data, saved.size() * sizeof(uint16_t), + cudaMemcpyDeviceToHost)); + Require(saved == input, "selection modified its input"); + + auto check_fallback = [&](int batch, int k, const char* message) { + const int count = batch * k; + std::vector untouched(count); + std::vector untouched_ids(count); + Check(cudaMemsetAsync(values.data, 0xcc, count * sizeof(uint16_t), stream)); + Check(cudaMemsetAsync(indices.data, 0xcc, count * sizeof(int), stream)); + Require(!selector.Try(logits.data, values.data, indices.data, batch, n, k, + first.data, bytes, stream), + message); + Check(cudaMemcpyAsync(untouched.data(), values.data, + count * sizeof(uint16_t), cudaMemcpyDeviceToHost, + stream)); + Check(cudaMemcpyAsync(untouched_ids.data(), indices.data, + count * sizeof(int), cudaMemcpyDeviceToHost, stream)); + Check(cudaStreamSynchronize(stream)); + for (int j = 0; j < count; ++j) { + Require(untouched[j] == 0xcccc && + static_cast(untouched_ids[j]) == 0xcccccccc, + "fallback changed the output"); + } + }; + for (int k : {257, 512}) { + check_fallback(1, k, "rank above the eager cutoff must fall back"); + } + for (uint16_t nonfinite : + {uint16_t{0xff80}, uint16_t{0x7f80}, uint16_t{0x7fc0}}) { + // Put the value in a different row and at the last element of a partial + // tile. + Check(cudaMemcpy(logits.data + input.size() - 1, &nonfinite, + sizeof(nonfinite), cudaMemcpyHostToDevice)); + check_fallback(3, 20, "nonfinite input must fall back"); + } + Require(!selector.Try(logits.data, values.data, indices.data, 1, n, 20, + first.data, bytes - 1, stream), + "short arena must fall back"); + Check(cudaStreamBeginCapture(stream, cudaStreamCaptureModeThreadLocal)); + const bool captured = selector.Try(logits.data, values.data, indices.data, 1, + n, 20, first.data, bytes, stream); + cudaGraph_t graph; + Check(cudaStreamEndCapture(stream, &graph)); + Check(cudaGraphDestroy(graph)); + Require(!captured, "R2S-K must defer to the existing capture path"); +} + +// A matched complete-call replay against the RadiK compiled into this tree. +// The input is dense little-endian BF16 words from a pre-top-k capture. +void Replay(int device, cudaStream_t stream, const char* path, int batch, int n, + int k) { + Require(batch >= 1 && batch <= 65535 && k > 1 && + k <= allspark::cuda::R2skSampling::kMaxEagerRank && k < n, + "unsupported replay shape"); + const size_t count = static_cast(batch) * n; + std::vector input(count); + std::ifstream file(path, std::ios::binary); + Require(static_cast(file.read(reinterpret_cast(input.data()), + count * sizeof(uint16_t))) && + file.peek() == std::ifstream::traits_type::eof(), + "capture size must match batch * vocabulary * 2"); + Require(std::none_of(input.begin(), input.end(), + [](uint16_t key) { return (key & 0x7f80u) == 0x7f80u; }), + "replay requires finite logits"); + const size_t output_count = static_cast(batch) * k; + std::vector reference(output_count), selected(output_count); + std::vector ids(output_count); + std::vector expected(output_count); + for (int row = 0; row < batch; ++row) { + const auto begin = input.begin() + static_cast(row) * n; + std::vector oracle(n); + std::transform(begin, begin + n, oracle.begin(), Decode); + const auto result = expected.begin() + static_cast(row) * k; + std::partial_sort_copy(oracle.begin(), oracle.end(), result, result + k, + std::greater{}); + } + size_t native_bytes = 0; + using Bf16 = hie::bfloat16; + static_assert(sizeof(Bf16) == sizeof(uint16_t)); + allspark::cuda::TopKRadixGetWorkspaceSize(&native_bytes, batch, n); + allspark::cuda::R2skSampling selector(device); + const size_t r2sk_bytes = selector.ReserveBytes(batch, n); + const size_t bytes = std::max(native_bytes, r2sk_bytes); + DeviceBuffer scratch(bytes); + DeviceBuffer logits(count), out(output_count); + DeviceBuffer indices(output_count); + Check(cudaMemcpy(logits.data, input.data(), count * sizeof(uint16_t), + cudaMemcpyHostToDevice)); + auto invoke = [&](bool r2sk) { + if (r2sk) { + Require(selector.Try(logits.data, out.data, indices.data, batch, n, k, + scratch.data, bytes, stream), + "replay fell back to RadiK"); + } else { + allspark::cuda::TopKRadixKernelLauncher( + reinterpret_cast(out.data), indices.data, + reinterpret_cast(logits.data), scratch.data, batch, n, k, + stream); + } + Check(cudaStreamSynchronize(stream)); + }; + for (bool r2sk : {false, true}) { + Check( + cudaMemsetAsync(indices.data, 0xff, ids.size() * sizeof(int), stream)); + invoke(r2sk); + auto& keys = r2sk ? selected : reference; + Check(cudaMemcpy(keys.data(), out.data, keys.size() * sizeof(uint16_t), + cudaMemcpyDeviceToHost)); + Check(cudaMemcpy(ids.data(), indices.data, ids.size() * sizeof(int), + cudaMemcpyDeviceToHost)); + for (int row = 0; row < batch; ++row) { + std::vector used(n); + for (int j = 0; j < k; ++j) { + const size_t pos = static_cast(row) * k + j; + const int id = ids[pos]; + Require(id >= 0 && id < n && !used[id], "invalid replay index"); + used[id] = true; + Require(keys[pos] == input[static_cast(row) * n + id] && + Decode(keys[pos]) == expected[pos], + "incorrect replay output"); + } + } + } + for (int i = 0; i < 10; ++i) { + invoke(false); + invoke(true); + } + std::cout << "rep,method,batch,n,k,required_scratch_bytes,host_us\n"; + for (int rep = 0; rep < 101; ++rep) { + for (int order = 0; order < 2; ++order) { + const bool r2sk = (rep + order) % 2 != 0; + const auto start = std::chrono::steady_clock::now(); + invoke(r2sk); + const auto elapsed = std::chrono::steady_clock::now() - start; + std::cout << rep << ',' << (r2sk ? "r2sk" : "radik") << ',' << batch + << ',' << n << ',' << k << ',' + << (r2sk ? r2sk_bytes : native_bytes) << ',' + << std::chrono::duration(elapsed).count() + << '\n'; + } + } +} + +struct Event { + explicit Event(unsigned flags = cudaEventDisableTiming) { + Check(cudaEventCreateWithFlags(&value, flags)); + } + ~Event() { cudaEventDestroy(value); } + cudaEvent_t value; +}; + +struct CapturedSelector { + ~CapturedSelector() { + if (exec) cudaGraphExecDestroy(exec); + if (graph) cudaGraphDestroy(graph); + } + void Finish(cudaStream_t stream) { + Check(cudaStreamEndCapture(stream, &graph)); + Check(cudaGraphInstantiate(&exec, graph, 0)); + } + cudaGraph_t graph = nullptr; + cudaGraphExec_t exec = nullptr; +}; + +bool IsNan(uint16_t value) { return (value & 0x7fffu) > 0x7f80u; } + +void CheckGraphOutput(const std::vector& input, + const std::vector& values, + const std::vector& indices, + r2sk::BFloat16GraphShape shape, size_t guard = 0) { + for (uint32_t row = 0; row < shape.batch; ++row) { + const auto begin = input.begin() + size_t(row) * shape.vocabulary; + const auto end = begin + shape.vocabulary; + if (std::any_of(begin, end, IsNan)) { + for (uint32_t j = 0; j < shape.k; ++j) { + const size_t pos = size_t(row) * shape.k + j + guard; + Require(values[pos] == 0xccccu && indices[pos] == 0xccccccccu, + "NaN row modified output"); + } + continue; + } + std::vector expected(shape.vocabulary); + std::transform(begin, end, expected.begin(), Decode); + std::partial_sort(expected.begin(), expected.begin() + shape.k, + expected.end(), std::greater{}); + std::vector used(shape.vocabulary); + for (uint32_t j = 0; j < shape.k; ++j) { + const size_t pos = size_t(row) * shape.k + j + guard; + const uint32_t index = indices[pos]; + Require(index < shape.vocabulary && !used[index], "invalid graph index"); + used[index] = true; + Require(begin[index] == values[pos] && Decode(values[pos]) == expected[j], + "incorrect graph value or occurrence"); + } + } +} + +void TestGraph(cudaStream_t main) { + using r2sk::GraphRoute; + Stream winners; + Event ready, done; + const r2sk::BFloat16GraphFork fork{winners.value, ready.value, done.value}; + for (const r2sk::BFloat16GraphShape shape : { + r2sk::BFloat16GraphShape{4, 2053, 20}, + r2sk::BFloat16GraphShape{1, 2, 2}, + r2sk::BFloat16GraphShape{3, 2099, 256}, + }) { + const auto bytes = r2sk::bfloat16_graph_bytes(shape); + DeviceBuffer scratch(bytes); + const size_t n = shape.vocabulary; + const size_t output_count = size_t(shape.batch) * shape.k; + std::vector input(n * shape.batch), saved(input.size()); + std::vector out(output_count + 2); + std::vector indices(output_count + 2); + std::vector reports(shape.batch); + DeviceBuffer logits(input.size()), values(out.size()); + DeviceBuffer ids(indices.size()); + DeviceBuffer device_reports(shape.batch); + + for (auto resources : {fork, r2sk::BFloat16GraphFork{}}) { + static_assert(sizeof(uint16_t) == 2); + CapturedSelector captured; + Check(cudaStreamBeginCapture(main, cudaStreamCaptureModeGlobal)); + r2sk::enqueue_bfloat16_graph(shape, logits.data, values.data + 1, + ids.data + 1, scratch.data, bytes, main, + resources, device_reports.data); + // The output consumer may reuse the arena immediately after the join. + Check(cudaMemsetAsync(scratch.data, 0xa5, bytes, main)); + captured.Finish(main); + for (uint32_t rep = 0; rep < 18; ++rep) { + for (uint32_t row = 0; row < shape.batch; ++row) { + auto* src = input.data() + row * n; + uint32_t pattern = (row + rep) % 6; + std::fill_n(src, n, uint16_t{0xbf80}); + if (pattern == 0 || pattern == 1) { + const uint32_t high = + std::min(shape.vocabulary, shape.k + (pattern == 1 ? 9 : 0)); + for (uint32_t j = 0; j < high; ++j) src[j] = 0x4000u + j % 16; + } else if (pattern == 2) { + for (size_t j = 0; j < n; ++j) src[j] = 0xbf8fu - j % 16; + for (size_t j = 0; j < std::min(n, size_t{5}); ++j) + src[j] = 0x4000u + j; + } else if (pattern == 3) { + src[n - 1] = 0x7fc1u; + } else if (pattern == 4) { + for (size_t j = 0; j < n; ++j) src[j] = j % 2 ? 0x8000u : 0; + } else { + std::fill_n(src, n, uint16_t{0xff80}); + if (rep % 2 == 1) src[n - 1] = 0x7f80u; + } + } + Check(cudaMemcpyAsync(logits.data, input.data(), input.size() * 2, + cudaMemcpyHostToDevice, main)); + Check(cudaMemsetAsync(values.data, 0xcc, out.size() * 2, main)); + Check(cudaMemsetAsync(ids.data, 0xcc, indices.size() * 4, main)); + Check(cudaGraphLaunch(captured.exec, main)); + Check(cudaStreamSynchronize(main)); + Check(cudaMemcpy(out.data(), values.data, out.size() * 2, + cudaMemcpyDeviceToHost)); + Check(cudaMemcpy(indices.data(), ids.data, indices.size() * 4, + cudaMemcpyDeviceToHost)); + Check(cudaMemcpy(saved.data(), logits.data, saved.size() * 2, + cudaMemcpyDeviceToHost)); + Check(cudaMemcpy(reports.data(), device_reports.data, + reports.size() * sizeof(reports[0]), + cudaMemcpyDeviceToHost)); + Require(saved == input, "graph modified its input"); + Require(out.front() == 0xcccc && out.back() == 0xcccc && + indices.front() == 0xcccccccc && + indices.back() == 0xcccccccc, + "graph output overrun"); + CheckGraphOutput(input, out, indices, shape, 1); + for (uint32_t row = 0; row < shape.batch; ++row) { + const auto pattern = (row + rep) % 6; + const auto& report = reports[row]; + if (pattern == 0) + Require(report.route == GraphRoute::exact, "expected exact route"); + if (pattern == 1 && n > 1024) + Require(report.route == GraphRoute::early_sort, + "expected early sort"); + if (pattern == 2 && n > 1024) + Require(report.route == GraphRoute::refine && + report.first_winners == 5 && report.passes == 2, + "expected refine with independent winners"); + if (pattern == 3) + Require(report.route == GraphRoute::invalid_nan, + "expected NaN rejection"); + } + } + } + } + std::cout + << "PASS graph BF16: 108 captured replays, changed routes and logits, " + "both schedules, mixed rows, signed zeros, infinities, NaN, guards " + "and arena reuse.\n"; +} + +void BenchGraph(int device, cudaStream_t stream, + const std::string& input_source, + r2sk::BFloat16GraphShape shape) { + const size_t count = size_t(shape.batch) * shape.vocabulary; + const size_t kept = size_t(shape.batch) * shape.k; + std::vector input(count), values(kept); + std::vector indices(kept); + if (input_source == "gaussian" || input_source == "uniform") { + std::mt19937 rng(42); + std::normal_distribution normal; + std::uniform_real_distribution uniform; + for (auto& w : input) { + float value = input_source == "gaussian" ? normal(rng) : uniform(rng); + uint32_t bits; + std::memcpy(&bits, &value, sizeof(bits)); + w = static_cast(bits >> 16); + } + } else { + std::ifstream file(input_source, std::ios::binary); + Require(static_cast( + file.read(reinterpret_cast(input.data()), count * 2)) && + file.peek() == std::ifstream::traits_type::eof(), + "graph fixture size"); + } + + size_t radik_bytes = 0; + using Bf16 = hie::bfloat16; + allspark::cuda::TopKRadixGetWorkspaceSize(&radik_bytes, shape.batch, + shape.vocabulary); + allspark::cuda::R2skSampling eager(device); + const size_t eager_bytes = eager.ReserveBytes(shape.batch, shape.vocabulary); + const auto graph_bytes = r2sk::bfloat16_graph_bytes(shape); + const size_t bytes = + std::max({radik_bytes, eager_bytes, size_t(graph_bytes)}); + DeviceBuffer scratch(bytes); + DeviceBuffer logits(count), out(kept); + DeviceBuffer ids(kept); + Stream winners; + Event ready, done; + const r2sk::BFloat16GraphFork fork{winners.value, ready.value, done.value}; + Check( + cudaMemcpy(logits.data, input.data(), count * 2, cudaMemcpyHostToDevice)); + auto enqueue = [&](r2sk::BFloat16GraphFork resources) { + r2sk::enqueue_bfloat16_graph(shape, logits.data, out.data, ids.data, + scratch.data, bytes, stream, resources); + }; + CapturedSelector overlap, serial; + for (auto* captured : {&overlap, &serial}) { + Check(cudaStreamBeginCapture(stream, cudaStreamCaptureModeGlobal)); + enqueue(captured == &overlap ? fork : r2sk::BFloat16GraphFork{}); + captured->Finish(stream); + } + auto invoke = [&](int method) { + switch (method) { + case 0: + allspark::cuda::TopKRadixKernelLauncher( + reinterpret_cast(out.data), reinterpret_cast(ids.data), + reinterpret_cast(logits.data), scratch.data, + shape.batch, shape.vocabulary, shape.k, stream); + break; + case 1: + Require( + eager.Try(logits.data, out.data, reinterpret_cast(ids.data), + shape.batch, shape.vocabulary, shape.k, scratch.data, + bytes, stream), + "integrated eager R2S-K declined benchmark"); + break; + case 2: + enqueue(fork); + break; + case 3: + Check(cudaGraphLaunch(overlap.exec, stream)); + break; + case 4: + Check(cudaGraphLaunch(serial.exec, stream)); + break; + } + }; + std::vector methods{0, 2, 3, 4}; + if (shape.k > 1 && shape.k <= allspark::cuda::R2skSampling::kMaxEagerRank && + shape.k < shape.vocabulary) { + methods.insert(methods.begin() + 1, 1); + } + for (int method : methods) { + Check(cudaMemsetAsync(ids.data, 0xff, kept * 4, stream)); + invoke(method); + Check(cudaStreamSynchronize(stream)); + Check( + cudaMemcpy(values.data(), out.data, kept * 2, cudaMemcpyDeviceToHost)); + Check( + cudaMemcpy(indices.data(), ids.data, kept * 4, cudaMemcpyDeviceToHost)); + CheckGraphOutput(input, values, indices, shape); + } + const char* names[] = {"radik_eager", "r2sk_device_eager", "device_eager", + "graph_overlap", "graph_serial"}; + const size_t arena_bytes[] = {radik_bytes, eager_bytes, size_t(graph_bytes), + size_t(graph_bytes), size_t(graph_bytes)}; + for (int rep = 0; rep < 12; ++rep) + for (int method : methods) { + invoke(method); + Check(cudaStreamSynchronize(stream)); + } + Event start(cudaEventDefault), stop(cudaEventDefault); + std::cout << "rep,method,batch,n,k,scratch_bytes,host_us,event_us\n"; + for (int rep = 0; rep < 51; ++rep) { + for (size_t position = 0; position < methods.size(); ++position) { + const int method = methods[(position + rep) % methods.size()]; + const auto tick = std::chrono::steady_clock::now(); + invoke(method); + Check(cudaStreamSynchronize(stream)); + const auto elapsed = std::chrono::steady_clock::now() - tick; + // Measure a second complete call for device timing so the host result + // excludes the event API cost and each arm has identical accounting. + Check(cudaEventRecord(start.value, stream)); + invoke(method); + Check(cudaEventRecord(stop.value, stream)); + Check(cudaEventSynchronize(stop.value)); + float gpu_ms; + Check(cudaEventElapsedTime(&gpu_ms, start.value, stop.value)); + std::cout << rep << ',' << names[method] << ',' << shape.batch << ',' + << shape.vocabulary << ',' << shape.k << ',' + << arena_bytes[method] << ',' + << std::chrono::duration(elapsed).count() + << ',' << gpu_ms * 1000 << '\n'; + } + } +} + +} // namespace + +int main(int argc, char** argv) { + try { + int devices = 0; + const auto status = cudaGetDeviceCount(&devices); + if (status == cudaErrorNoDevice || status == cudaErrorInsufficientDriver || + (status == cudaSuccess && devices == 0)) { + std::cout << "R2S-K sampling tests require a visible CUDA device\n"; + return 77; + } + Check(status); + int device; + Check(cudaGetDevice(&device)); + int major; + Check(cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, + device)); + if (major < 8) { + std::cout + << "R2S-K sampling tests require compute capability 8.0 or newer\n"; + return 77; + } + Stream stream; + if (argc == 6 && std::string(argv[1]) == "--replay") { + Replay(device, stream.value, argv[2], std::stoi(argv[3]), + std::stoi(argv[4]), std::stoi(argv[5])); + return 0; + } + if (argc == 2 && std::string(argv[1]) == "--graph-test") { + TestGraph(stream.value); + return 0; + } + if (argc == 6 && std::string(argv[1]) == "--graph-replay") { + BenchGraph(device, stream.value, argv[2], + {static_cast(std::stoul(argv[3])), + static_cast(std::stoul(argv[4])), + static_cast(std::stoul(argv[5]))}); + return 0; + } + Require(argc == 1, + "usage: cpp_r2sk_sampling_test [--graph-test | --graph-replay FILE " + "B N K | --replay FILE B N K]"); + TestSampling(device, stream.value); + std::cout << "R2S-K sampling tests passed\n"; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +}