Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[GPU] Add optimized TopK kernel using radix histogram and bitonic sort. (#34539)

hyunback kim0febc2802a5e
diff --git a/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/arg_max_min_topk_radix.cl b/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/arg_max_min_topk_radix.cl
new file mode 100644
index 00000000000..2c20ebe727b
--- /dev/null
+++ b/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/arg_max_min_topk_radix.cl
@@ -0,0 +1,414 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+// Radix/Histogram Select + Bitonic Sort TopK
+//
+// Algorithm:
+// Phase 0: Read input ONCE -> cache sortable keys in global buffer
+// Phase 1: Two-level histogram in SLM to find the K-th threshold value
+// Phase 2: Gather top-K elements directly into SLM
+// Phase 3: Bitonic sort in SLM (45 barriers for K<=512 vs 3000+ for iterative)
+// Phase 4: Write sorted results to output
+//
+// Design principles:
+// - Read input exactly ONCE to avoid GPU cache inconsistency
+// - Single global buffer for sortable keys (N * 4 bytes per operation)
+// - SLM bitonic sort for Phase 3 (fast, no global memory for sorting)
+// - Total SLM: ~5KB (histogram 1KB + sort buffers 4KB)
+//
+
+#include "include/fetch_utils.cl"
+
+#ifdef BATCH_AXIS
+ #define VALUES_NUM INPUT0_BATCH_NUM
+ #define AXIS 0
+#endif
+#ifdef FEATURE_AXIS
+ #define VALUES_NUM INPUT0_FEATURE_NUM
+ #define AXIS 1
+#endif
+#ifdef Z_AXIS
+ #define VALUES_NUM INPUT0_SIZE_Z
+ #define AXIS 2
+#endif
+#ifdef Y_AXIS
+ #define VALUES_NUM INPUT0_SIZE_Y
+ #define AXIS 3
+#endif
+#ifdef X_AXIS
+ #define VALUES_NUM INPUT0_SIZE_X
+ #define AXIS 4
+#endif
+
+#ifdef MAX_OUT
+ #define COMPARE_SIGN >
+ #define INPUT0_FILL_VAL INPUT0_VAL_MIN
+#else
+ #define COMPARE_SIGN <
+ #define INPUT0_FILL_VAL INPUT0_VAL_MAX
+#endif
+
+#ifndef WG_SIZE
+ #define WG_SIZE 256
+#endif
+
+#ifndef PADDED_K
+ #define PADDED_K 512
+#endif
+
+#define NUM_BUCKETS 256
+
+inline void FUNC(get_indices_from_dims)(OPTIONAL_SHAPE_INFO_ARG
+ const uint output_idx,
+ uint* indices)
+{
+#ifdef BATCH_AXIS
+ const uint out_first_dim = output_idx / (INPUT0_SIZE_Z * INPUT0_SIZE_Y * INPUT0_SIZE_X);
+ const uint out_second_dim = output_idx / (INPUT0_SIZE_Y * INPUT0_SIZE_X) % INPUT0_SIZE_Z;
+ const uint out_third_dim = output_idx / INPUT0_SIZE_X % INPUT0_SIZE_Y;
+ const uint out_fourth_dim = output_idx % INPUT0_SIZE_X;
+ indices[1] = out_first_dim; indices[2] = out_second_dim; indices[3] = out_third_dim; indices[4] = out_fourth_dim;
+#endif
+#ifdef FEATURE_AXIS
+ const uint out_first_dim = output_idx / (INPUT0_SIZE_Z * INPUT0_SIZE_Y * INPUT0_SIZE_X);
+ const uint out_second_dim = output_idx / (INPUT0_SIZE_Y * INPUT0_SIZE_X) % INPUT0_SIZE_Z;
+ const uint out_third_dim = output_idx / INPUT0_SIZE_X % INPUT0_SIZE_Y;
+ const uint out_fourth_dim = output_idx % INPUT0_SIZE_X;
+ indices[0] = out_first_dim; indices[2] = out_second_dim; indices[3] = out_third_dim; indices[4] = out_fourth_dim;
+#endif
+#ifdef Z_AXIS
+ const uint out_first_dim = output_idx / (INPUT0_FEATURE_NUM * INPUT0_SIZE_Y * INPUT0_SIZE_X);
+ const uint out_second_dim = output_idx / (INPUT0_SIZE_Y * INPUT0_SIZE_X) % INPUT0_FEATURE_NUM;
+ const uint out_third_dim = output_idx / INPUT0_SIZE_X % INPUT0_SIZE_Y;
+ const uint out_fourth_dim = output_idx % INPUT0_SIZE_X;
+ indices[0] = out_first_dim; indices[1] = out_second_dim; indices[3] = out_third_dim; indices[4] = out_fourth_dim;
+#endif
+#ifdef Y_AXIS
+ const uint out_first_dim = output_idx / (INPUT0_FEATURE_NUM * INPUT0_SIZE_Z * INPUT0_SIZE_X);
+ const uint out_second_dim = output_idx / (INPUT0_SIZE_Z * INPUT0_SIZE_X) % INPUT0_FEATURE_NUM;
+ const uint out_third_dim = output_idx / INPUT0_SIZE_X % INPUT0_SIZE_Z;
+ const uint out_fourth_dim = output_idx % INPUT0_SIZE_X;
+ indices[0] = out_first_dim; indices[1] = out_second_dim; indices[2] = out_third_dim; indices[4] = out_fourth_dim;
+#endif
+#ifdef X_AXIS
+ const uint out_first_dim = output_idx / (INPUT0_FEATURE_NUM * INPUT0_SIZE_Z * INPUT0_SIZE_Y);
+ const uint out_second_dim = output_idx / (INPUT0_SIZE_Z * INPUT0_SIZE_Y) % INPUT0_FEATURE_NUM;
+ const uint out_third_dim = output_idx / INPUT0_SIZE_Y % INPUT0_SIZE_Z;
+ const uint out_fourth_dim = output_idx % INPUT0_SIZE_Y;
+ indices[0] = out_first_dim; indices[1] = out_second_dim; indices[2] = out_third_dim; indices[3] = out_fourth_dim;
+#endif
+}
+
+// Convert f16 to a sortable uint16:
+// For positive f16: the bit pattern is already sortable (larger value = larger uint)
+// For negative f16: flip all bits
+// This gives a monotonically increasing uint16 mapping
+inline uint FUNC(f16_to_sortable)(INPUT0_TYPE val) {
+ // Use as_ushort to get the bit pattern of f16
+ ushort bits = as_ushort(convert_half(val));
+ // If sign bit is set (negative), flip all bits
+ // If sign bit is clear (positive), flip only sign bit
+ // This maps f16 range to 0..65535 monotonically
+ ushort mask = (bits >> 15) ? (ushort)0xFFFF : (ushort)0x8000;
+ return (uint)(bits ^ mask);
+}
+
+inline INPUT0_TYPE FUNC(sortable_to_f16)(uint sortable) {
+ ushort bits = (ushort)sortable;
+ ushort mask = (bits & 0x8000) ? (ushort)0x8000 : (ushort)0xFFFF;
+ bits = bits ^ mask;
+ return convert_float(as_half(bits));
+}
+
+REQD_SUB_GROUP_SIZE(16)
+KERNEL(arg_max_min_topk_radix)(
+ const __global INPUT0_TYPE* input
+ ,__global OUTPUT_TYPE* output
+#ifdef OUTPUT1_TYPE
+ ,__global OUTPUT1_TYPE* second_output
+#endif
+ ,__global uint* sortable_buf // Cached sortable keys: VALUES_NUM per operation
+)
+{
+ const uint lid = (uint)get_local_id(0);
+ const uint output_idx = (uint)get_group_id(0);
+
+ uint base_indices[] = { 0, 0, 0, 0, 0 };
+ if (OPERATION_NUM > 1) {
+ FUNC_CALL(get_indices_from_dims)(OPTIONAL_SHAPE_INFO_TENSOR output_idx, base_indices);
+ }
+
+ // Global buffer pointer for this operation's sortable keys
+ __global uint* my_sortable = sortable_buf + output_idx * VALUES_NUM;
+
+ // ============================================================
+ // SLM declarations (all at outermost kernel scope)
+ // Total SLM: 256*4 + 512*4 + 512*4 + ~20 ~= 5KB
+ // ============================================================
+ __local uint histogram[NUM_BUCKETS]; // 1KB
+ __local uint sort_keys[PADDED_K]; // sortable uint keys for bitonic sort
+ __local uint sort_idxs[PADDED_K]; // original indices
+ __local uint threshold_bucket;
+ __local uint count_above;
+ __local uint fine_threshold;
+ __local uint total_above_threshold;
+ __local uint gather_count;
+
+ // ============================================================
+ // Phase 0: Read input ONCE, convert to sortable keys, cache in global buffer
+ // Also compute coarse histogram in the same pass
+ // ============================================================
+ if (lid < NUM_BUCKETS) {
+ histogram[lid] = 0;
+ }
+ barrier(CLK_LOCAL_MEM_FENCE);
+
+ for (uint i = lid; i < VALUES_NUM; i += WG_SIZE) {
+ base_indices[AXIS] = i;
+ INPUT0_TYPE val = input[FUNC_CALL(get_input_index)(OPTIONAL_SHAPE_INFO_TENSOR
+ base_indices[0], base_indices[1], 0, base_indices[2], base_indices[3], base_indices[4])];
+ uint sortable = FUNC_CALL(f16_to_sortable)(val);
+ my_sortable[i] = sortable;
+ uint bucket = sortable >> 8;
+ atomic_add(&histogram[bucket], 1);
+ }
+ barrier(CLK_LOCAL_MEM_FENCE | CLK_GLOBAL_MEM_FENCE);
+
+ // Find coarse bucket containing K-th element
+ if (lid == 0) {
+ uint cumulative = 0;
+#ifdef MAX_OUT
+ for (int b = NUM_BUCKETS - 1; b >= 0; b--) {
+ cumulative += histogram[b];
+ if (cumulative >= TOP_K) {
+ threshold_bucket = (uint)b;
+ count_above = cumulative - histogram[b];
+ break;
+ }
+ }
+#else
+ for (uint b = 0; b < NUM_BUCKETS; b++) {
+ cumulative += histogram[b];
+ if (cumulative >= TOP_K) {
+ threshold_bucket = b;
+ count_above = cumulative - histogram[b];
+ break;
+ }
+ }
+#endif
+ }
+ barrier(CLK_LOCAL_MEM_FENCE);
+
+ uint coarse_bucket = threshold_bucket;
+ uint already_above = count_above;
+
+ // ============================================================
+ // Phase 1b: Fine histogram (bottom 8 bits within coarse bucket)
+ // Read from cached sortable buffer (consistent data)
+ // ============================================================
+ if (lid < NUM_BUCKETS) {
+ histogram[lid] = 0;
+ }
+ barrier(CLK_LOCAL_MEM_FENCE);
+
+ for (uint i = lid; i < VALUES_NUM; i += WG_SIZE) {
+ uint sortable = my_sortable[i];
+ if ((sortable >> 8) == coarse_bucket) {
+ atomic_add(&histogram[sortable & 0xFF], 1);
+ }
+ }
+ barrier(CLK_LOCAL_MEM_FENCE);
+
+ // Find exact threshold
+ if (lid == 0) {
+ uint cumulative = already_above;
+#ifdef MAX_OUT
+ for (int b = NUM_BUCKETS - 1; b >= 0; b--) {
+ cumulative += histogram[b];
+ if (cumulative >= TOP_K) {
+ fine_threshold = (coarse_bucket << 8) | (uint)b;
+ total_above_threshold = cumulative - histogram[b];
+ break;
+ }
+ }
+#else
+ for (uint b = 0; b < NUM_BUCKETS; b++) {
+ cumulative += histogram[b];
+ if (cumulative >= TOP_K) {
+ fine_threshold = (coarse_bucket << 8) | b;
+ total_above_threshold = cumulative - histogram[b];
+ break;
+ }
+ }
+#endif
+ gather_count = 0;
+ }
+ barrier(CLK_LOCAL_MEM_FENCE);
+
+ uint threshold = fine_threshold;
+
+ // ============================================================
+ // Initialize SLM sort buffers with fill values
+ // Combined key = (sortable << 16) | tiebreaker
+ // For MAX_OUT (descending): fill=0 so unused slots sort to end
+ // For MIN_OUT (ascending): fill=0xFFFFFFFF so unused slots sort to end
+ // ============================================================
+ for (uint i = lid; i < PADDED_K; i += WG_SIZE) {
+#ifdef MAX_OUT
+ sort_keys[i] = 0;
+#else
+ sort_keys[i] = 0xFFFFFFFF;
+#endif
+ sort_idxs[i] = 0;
+ }
+ barrier(CLK_LOCAL_MEM_FENCE);
+
+ // ============================================================
+ // Phase 2a: Gather elements strictly ABOVE threshold into SLM
+ // Use combined key: (sortable << 16) | tiebreaker(index) for deterministic ordering
+ // Read from cached sortable buffer
+ // ============================================================
+ for (uint i = lid; i < VALUES_NUM; i += WG_SIZE) {
+ uint sortable = my_sortable[i];
+ bool is_above;
+#ifdef MAX_OUT
+ is_above = (sortable > threshold);
+#else
+ is_above = (sortable < threshold);
+#endif
+ if (is_above) {
+ uint pos = atomic_add(&gather_count, 1);
+ if (pos < PADDED_K) {
+ // Combined key encodes value and index for deterministic tiebreak
+#ifdef MAX_OUT
+ sort_keys[pos] = (sortable << 16) | (0xFFFF - (i & 0xFFFF));
+#else
+ sort_keys[pos] = (sortable << 16) | (i & 0xFFFF);
+#endif
+ sort_idxs[pos] = i;
+ }
+ }
+ }
+ barrier(CLK_LOCAL_MEM_FENCE);
+
+ // ============================================================
+ // Phase 2b: Gather elements AT threshold into SLM
+ // Strategy: check if all at-threshold elements fit in remaining slots.
+ // - Fast path (common): all fit. parallel atomic_add (no correctness issue)
+ // - Slow path (rare): overflow. single WI sequential scan for deterministic
+ // index ordering (smallest indices first, matching TF/ONNX behavior)
+ // histogram[threshold & 0xFF] still holds the fine histogram count from Phase 1.
+ // ============================================================
+ uint current_count = min(gather_count, (uint)PADDED_K);
+ if (lid == 0) {
+ gather_count = current_count;
+ }
+ barrier(CLK_LOCAL_MEM_FENCE);
+
+ if (current_count < PADDED_K) {
+ uint at_count = histogram[threshold & 0xFF];
+ uint available_slots = PADDED_K - current_count;
+
+ if (at_count <= available_slots) {
+ // Fast path: all at-threshold elements fit, parallel gather is safe
+ for (uint i = lid; i < VALUES_NUM; i += WG_SIZE) {
+ uint sortable = my_sortable[i];
+ if (sortable == threshold) {
+ uint pos = atomic_add(&gather_count, 1);
+ if (pos < PADDED_K) {
+#ifdef MAX_OUT
+ sort_keys[pos] = (sortable << 16) | (0xFFFF - (i & 0xFFFF));
+#else
+ sort_keys[pos] = (sortable << 16) | (i & 0xFFFF);
+#endif
+ sort_idxs[pos] = i;
+ }
+ }
+ }
+ } else {
+ // Slow path: more at-threshold elements than slots,
+ // sequential scan ensures smallest indices are selected first
+ if (lid == 0) {
+ uint pos = current_count;
+ for (uint i = 0; i < VALUES_NUM && pos < PADDED_K; i++) {
+ uint sortable = my_sortable[i];
+ if (sortable == threshold) {
+#ifdef MAX_OUT
+ sort_keys[pos] = (sortable << 16) | (0xFFFF - (i & 0xFFFF));
+#else
+ sort_keys[pos] = (sortable << 16) | (i & 0xFFFF);
+#endif
+ sort_idxs[pos] = i;
+ pos++;
+ }
+ }
+ gather_count = pos;
+ }
+ }
+ }
+ barrier(CLK_LOCAL_MEM_FENCE);
+
+ // ============================================================
+ // Phase 3: Bitonic sort in SLM
+ // For PADDED_K=512: 9*(9+1)/2 = 45 barrier passes
+ // ============================================================
+ for (uint bk = 2; bk <= PADDED_K; bk <<= 1) {
+ for (uint bj = bk >> 1; bj > 0; bj >>= 1) {
+ for (uint i = lid; i < PADDED_K; i += WG_SIZE) {
+ uint partner = i ^ bj;
+ if (partner > i) {
+ uint ki = sort_keys[i];
+ uint kp = sort_keys[partner];
+ bool ascending = ((i & bk) == 0);
+#ifdef MAX_OUT
+ ascending = !ascending;
+#endif
+ bool need_swap = ascending ? (ki > kp) : (ki < kp);
+ if (need_swap) {
+ sort_keys[i] = kp;
+ sort_keys[partner] = ki;
+ uint ti = sort_idxs[i];
+ sort_idxs[i] = sort_idxs[partner];
+ sort_idxs[partner] = ti;
+ }
+ }
+ }
+ barrier(CLK_LOCAL_MEM_FENCE);
+ }
+ }
+
+ // ============================================================
+ // Phase 4: Write sorted top-K results to output
+ // sort_keys contains combined key: (sortable << 16) | tiebreaker
+ // Extract upper 16 bits to recover the sortable value
+ // ============================================================
+ for (uint k = lid; k < TOP_K; k += WG_SIZE) {
+ INPUT0_TYPE val = FUNC_CALL(sortable_to_f16)(sort_keys[k] >> 16);
+ uint idx = sort_idxs[k];
+
+ base_indices[AXIS] = k;
+ uint out_offset = FUNC_CALL(get_output_index)(OPTIONAL_SHAPE_INFO_TENSOR
+ base_indices[0], base_indices[1], 0, base_indices[2], base_indices[3], base_indices[4]);
+
+#ifdef TOP_K_ORDER
+ output[out_offset] = TO_OUTPUT_TYPE(val);
+#else
+ output[out_offset] = TO_OUTPUT_TYPE(idx);
+#endif
+#ifdef OUTPUT1_TYPE
+ #ifdef TOP_K_ORDER
+ second_output[out_offset] = TO_OUTPUT1_TYPE(idx);
+ #else
+ second_output[out_offset] = TO_OUTPUT1_TYPE(val);
+ #endif
+#endif
+ }
+}
+
+#undef COMPARE_SIGN
+#undef INPUT0_FILL_VAL
+#undef AXIS
+#undef VALUES_NUM
+#undef WG_SIZE
+#undef PADDED_K
+#undef NUM_BUCKETS
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/arg_max_min/arg_max_min_kernel_selector.cpp b/src/plugins/intel_gpu/src/kernel_selector/kernels/arg_max_min/arg_max_min_kernel_selector.cpp
index 0fe08a87868..4dc8ed0495a 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/kernels/arg_max_min/arg_max_min_kernel_selector.cpp
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/arg_max_min/arg_max_min_kernel_selector.cpp
@@ -6,6 +6,7 @@
#include "arg_max_min_kernel_gpu_ref.h"
#include "arg_max_min_kernel_opt.h"
#include "arg_max_min_kernel_axis.h"
+#include "arg_max_min_kernel_topk_radix.h"
namespace kernel_selector {
@@ -13,6 +14,7 @@ arg_max_min_kernel_selector::arg_max_min_kernel_selector() {
Attach<ArgMaxMinKernelGPURef>();
// Attach<ArgMaxMinKernelOpt>(); not yet implemented
Attach<ArgMaxMinKernelAxis>();
+ Attach<ArgMaxMinKernelTopKRadix>();
}
KernelsData arg_max_min_kernel_selector::GetBestKernels(const Params& params) const {
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/arg_max_min/arg_max_min_kernel_topk_radix.cpp b/src/plugins/intel_gpu/src/kernel_selector/kernels/arg_max_min/arg_max_min_kernel_topk_radix.cpp
new file mode 100644
index 00000000000..d662e5c55e8
--- /dev/null
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/arg_max_min/arg_max_min_kernel_topk_radix.cpp
@@ -0,0 +1,195 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "arg_max_min_kernel_topk_radix.h"
+#include <kernel_selector_utils.h>
+#include <cstdlib>
+
+namespace kernel_selector {
+
+namespace {
+
+constexpr size_t kWgSize = 256;
+
+size_t GetOperationNumber(const arg_max_min_params& params) {
+ switch (params.argMaxMinAxis) {
+ case ArgMaxMinAxis::BATCH: return params.outputs[0].Feature().v * params.outputs[0].Z().v * params.outputs[0].Y().v * params.outputs[0].X().v;
+ case ArgMaxMinAxis::FEATURE: return params.outputs[0].Batch().v * params.outputs[0].Z().v * params.outputs[0].Y().v * params.outputs[0].X().v;
+ case ArgMaxMinAxis::Z: return params.outputs[0].Batch().v * params.outputs[0].Feature().v * params.outputs[0].Y().v * params.outputs[0].X().v;
+ case ArgMaxMinAxis::Y: return params.outputs[0].Batch().v * params.outputs[0].Feature().v * params.outputs[0].Z().v * params.outputs[0].X().v;
+ case ArgMaxMinAxis::X: return params.outputs[0].Batch().v * params.outputs[0].Feature().v * params.outputs[0].Z().v * params.outputs[0].Y().v;
+ default: throw std::invalid_argument("Unsupported axis");
+ }
+}
+
+std::string GetOperationNumberString(const arg_max_min_params& params) {
+ const auto& output = params.outputs[0];
+ DimensionAccessHelperJit dims(output);
+ switch (params.argMaxMinAxis) {
+ case ArgMaxMinAxis::BATCH: return toVectorMulString({dims.x(), dims.y(), dims.z(), dims.f()});
+ case ArgMaxMinAxis::FEATURE: return toVectorMulString({dims.x(), dims.y(), dims.z(), dims.b()});
+ case ArgMaxMinAxis::Z: return toVectorMulString({dims.y(), dims.z(), dims.f(), dims.b()});
+ case ArgMaxMinAxis::Y: return toVectorMulString({dims.x(), dims.z(), dims.f(), dims.b()});
+ case ArgMaxMinAxis::X: return toVectorMulString({dims.y(), dims.z(), dims.f(), dims.b()});
+ default: throw std::invalid_argument("Unsupported axis");
+ }
+}
+
+size_t GetSortSize(const arg_max_min_params& params) {
+ switch (params.argMaxMinAxis) {
+ case ArgMaxMinAxis::BATCH: return params.inputs[0].Batch().v;
+ case ArgMaxMinAxis::FEATURE: return params.inputs[0].Feature().v;
+ case ArgMaxMinAxis::Z: return params.inputs[0].Z().v;
+ case ArgMaxMinAxis::Y: return params.inputs[0].Y().v;
+ case ArgMaxMinAxis::X: return params.inputs[0].X().v;
+ default: throw std::invalid_argument("Unsupported axis");
+ }
+}
+
+} // namespace
+
+ParamsKey ArgMaxMinKernelTopKRadix::GetSupportedKey() const {
+ ParamsKey k;
+ k.EnableInputDataType(Datatype::F16);
+ k.EnableAllOutputDataType();
+ k.EnableInputLayout(DataLayout::bfyx);
+ k.EnableOutputLayout(DataLayout::bfyx);
+ k.EnableInputLayout(DataLayout::bfzyx);
+ k.EnableOutputLayout(DataLayout::bfzyx);
+ k.EnableArgMaxMinAxis(ArgMaxMinAxis::BATCH);
+ k.EnableArgMaxMinAxis(ArgMaxMinAxis::X);
+ k.EnableArgMaxMinAxis(ArgMaxMinAxis::Y);
+ k.EnableArgMaxMinAxis(ArgMaxMinAxis::Z);
+ k.EnableArgMaxMinAxis(ArgMaxMinAxis::FEATURE);
+ k.EnableDifferentTypes();
+ k.EnableBatching();
+ k.EnableTensorPitches();
+ k.EnableTensorOffset();
+ return k;
+}
+
+bool ArgMaxMinKernelTopKRadix::Validate(const Params& p) const {
+ if (!ArgMaxMinKernelBase::Validate(p))
+ DO_NOT_USE_THIS_KERNEL(p.layerID);
+
+ const auto& params = static_cast<const arg_max_min_params&>(p);
+
+ // Only f16 input for radix approach (bit manipulation)
+ if (params.inputs[0].GetDType() != Datatype::F16)
+ DO_NOT_USE_THIS_KERNEL(p.layerID);
+
+ if (params.argMaxMinSortType != ArgMaxMinSortType::VALUE)
+ DO_NOT_USE_THIS_KERNEL(p.layerID);
+
+ const size_t sort_size = GetSortSize(params);
+
+ if (sort_size < 2)
+ DO_NOT_USE_THIS_KERNEL(p.layerID);
+
+ // Combined key uses (i & 0xFFFF) as tiebreaker, so N must fit in 16 bits
+ if (sort_size > 65535)
+ DO_NOT_USE_THIS_KERNEL(p.layerID);
+
+ // PADDED_K (next power of 2 >= topK) must fit in SLM:
+ // sort_keys[PADDED_K] + sort_idxs[PADDED_K] + histogram[256] + scalars
+ size_t padded_k = 1;
+ while (padded_k < params.topK)
+ padded_k <<= 1;
+ const size_t slm_needed = padded_k * 2 * sizeof(uint32_t) + 256 * sizeof(uint32_t) + 24;
+ if (slm_needed > params.engineInfo.maxLocalMemSize)
+ DO_NOT_USE_THIS_KERNEL(p.layerID);
+
+ return true;
+}
+
+ArgMaxMinKernelBase::DispatchData ArgMaxMinKernelTopKRadix::SetDefault(const arg_max_min_params& params) const {
+ DispatchData dispatchData;
+
+ size_t ops_size = 1;
+ if (!params.has_dynamic_tensors()) {
+ ops_size = GetOperationNumber(params);
+ }
+
+ dispatchData.gws = { ops_size * kWgSize, 1, 1 };
+ dispatchData.lws = { kWgSize, 1, 1 };
+
+ return dispatchData;
+}
+
+void ArgMaxMinKernelTopKRadix::GetUpdateDispatchDataFunc(KernelData& kd) const {
+ kd.update_dispatch_data_func = [this](const Params& params, KernelData& kd) {
+ const auto& prim_params = static_cast<const arg_max_min_params&>(params);
+ auto dispatchData = SetDefault(prim_params);
+ OPENVINO_ASSERT(kd.kernels.size() == 1, "[GPU] Invalid kernels size for update dispatch data func");
+ kd.kernels[0].params.workGroups.global = dispatchData.gws;
+ kd.kernels[0].params.workGroups.local = dispatchData.lws;
+ kd.kernels[0].skip_execution = KernelData::SkipKernelExecution(prim_params);
+
+ // Sortable keys buffer: VALUES_NUM * sizeof(uint) per operation
+ const size_t sort_size = GetSortSize(prim_params);
+ const size_t ops_num = GetOperationNumber(prim_params);
+ kd.internalBuffers.clear();
+ kd.internalBuffers.push_back(4 * sort_size * ops_num);
+ };
+}
+
+JitConstants ArgMaxMinKernelTopKRadix::GetJitConstants(const arg_max_min_params& params) const {
+ auto jit = ArgMaxMinKernelBase::GetJitConstants(params);
+
+ jit.AddConstant(MakeJitConstant("WG_SIZE", kWgSize));
+
+ // PADDED_K: next power of 2 >= TOP_K (for bitonic sort)
+ size_t padded_k = 1;
+ while (padded_k < params.topK) padded_k <<= 1;
+ jit.AddConstant(MakeJitConstant("PADDED_K", padded_k));
+
+ if (params.has_dynamic_tensors()) {
+ jit.AddConstant(MakeJitConstant("OPERATION_NUM", GetOperationNumberString(params)));
+ } else {
+ jit.AddConstant(MakeJitConstant("OPERATION_NUM", GetOperationNumber(params)));
+ }
+
+ if (params.argMaxMinSortType == ArgMaxMinSortType::VALUE)
+ jit.AddConstant(MakeJitConstant("SORT_BY_VALUE", 1));
+
+ if (params.values_first)
+ jit.AddConstant(MakeJitConstant("TOP_K_ORDER", 1));
+
+ return jit;
+}
+
+KernelsData ArgMaxMinKernelTopKRadix::GetKernelsData(const Params& params) const {
+ if (!Validate(params))
+ return {};
+
+ const auto& orgParams = static_cast<const arg_max_min_params&>(params);
+ auto dispatchData = SetDefault(orgParams);
+ KernelData kd = KernelData::Default<arg_max_min_params>(params);
+ GetUpdateDispatchDataFunc(kd);
+
+ auto cldnn_jit = GetJitConstants(orgParams);
+ auto entry_point = GetEntryPoint(kernelName, orgParams.layerID, params);
+ auto jit = CreateJit(kernelName, cldnn_jit, entry_point);
+
+ auto& kernel = kd.kernels[0];
+ FillCLKernelData(kernel, dispatchData, params.engineInfo, kernelName, jit, entry_point,
+ EXE_MODE_DEFAULT, false, false, 1,
+ GetFusedPrimitiveInputsCount(params), orgParams.outputs_num,
+ orgParams.is_shape_agnostic);
+
+ // Add internal buffer for sortable keys (VALUES_NUM * sizeof(uint) per operation)
+ const size_t sort_size = GetSortSize(orgParams);
+ const size_t ops_num = GetOperationNumber(orgParams);
+ kernel.params.arguments.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, 0});
+ kd.internalBuffers.push_back(4 * sort_size * ops_num);
+ kd.internalBufferDataType = Datatype::UINT32;
+
+ return {kd};
+}
+
+KernelsPriority ArgMaxMinKernelTopKRadix::GetKernelsPriority(const Params&) const {
+ return FORCE_PRIORITY_1;
+}
+
+} // namespace kernel_selector
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/arg_max_min/arg_max_min_kernel_topk_radix.h b/src/plugins/intel_gpu/src/kernel_selector/kernels/arg_max_min/arg_max_min_kernel_topk_radix.h
new file mode 100644
index 00000000000..8ec83914a4a
--- /dev/null
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/arg_max_min/arg_max_min_kernel_topk_radix.h
@@ -0,0 +1,27 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "arg_max_min_kernel_base.h"
+
+namespace kernel_selector {
+
+class ArgMaxMinKernelTopKRadix : public ArgMaxMinKernelBase {
+public:
+ ArgMaxMinKernelTopKRadix() : ArgMaxMinKernelBase("arg_max_min_topk_radix") {}
+ virtual ~ArgMaxMinKernelTopKRadix() {}
+
+ JitConstants GetJitConstants(const arg_max_min_params& params) const override;
+ DispatchData SetDefault(const arg_max_min_params& params) const override;
+ KernelsData GetKernelsData(const Params& params) const override;
+ KernelsPriority GetKernelsPriority(const Params& params) const override;
+ ParamsKey GetSupportedKey() const override;
+
+private:
+ bool Validate(const Params&) const override;
+ void GetUpdateDispatchDataFunc(KernelData& kd) const override;
+};
+
+} // namespace kernel_selector
diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/arg_max_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/arg_max_gpu_test.cpp
index 915e6e38bb1..50c7c947e8f 100644
--- a/src/plugins/intel_gpu/tests/unit/test_cases/arg_max_gpu_test.cpp
+++ b/src/plugins/intel_gpu/tests/unit/test_cases/arg_max_gpu_test.cpp
@@ -9,6 +9,7 @@
#include <intel_gpu/primitives/input_layout.hpp>
#include <intel_gpu/primitives/mutable_data.hpp>
#include <arg_max_min_inst.h>
+#include "intel_gpu/runtime/internal_properties.hpp"
#include "test_utils.h"
#include "program_wrapper.h"
@@ -1019,3 +1020,297 @@ TEST(arg_max_min_test, check_second_output_data_type) {
auto second_output_layout = arg_max_min_node.get_output_layout(false, 1);
ASSERT_EQ(second_output_layout.data_type, data_types::i32);
}
+
+// =============================================================================
+// Tests for arg_max_min_topk_radix kernel
+// Conditions: f16 input, SORT_VALUES, N >= 2, N <= 65535, SLM fits
+// =============================================================================
+
+// Helper: create ExecutionConfig that forces the radix TopK kernel
+inline ExecutionConfig get_radix_topk_config(const cldnn::engine& engine) {
+ auto config = get_test_default_config(engine);
+ ov::intel_gpu::ImplementationDesc radix_impl = {format::bfyx, "arg_max_min_topk_radix", impl_types::ocl};
+ config.set_property(ov::intel_gpu::force_implementations(
+ ov::intel_gpu::ImplForcingMap{{"arg_max", radix_impl}}));
+ return config;
+}
+
+// --------------------------------------------------------------------------
+// Parameterized test: value-only verification with various configurations
+// --------------------------------------------------------------------------
+struct TopKRadixValueTestParam {
+ ov::op::TopKMode mode; // MAX or MIN
+ int32_t batch_num;
+ int32_t feature_num;
+ int top_k;
+ int axis;
+ std::vector<ov::float16> input_vec;
+ std::vector<float> ref_values; // expected top-K values in sorted order
+ std::string name;
+};
+
+class TopKRadixValueTest : public testing::TestWithParam<TopKRadixValueTestParam> {};
+
+TEST_P(TopKRadixValueTest, values_match) {
+ const auto& p = GetParam();
+ auto& engine = get_test_engine();
+
+ auto input = engine.allocate_memory({data_types::f16, format::bfyx,
+ {p.batch_num, p.feature_num, 1, 1}});
+ set_values(input, p.input_vec);
+
+ topology topology;
+ topology.add(input_layout("input", input->get_layout()));
+ topology.add(arg_max_min("arg_max",
+ {input_info("input")},
+ p.mode,
+ p.top_k,
+ p.axis,
+ ov::op::TopKSortType::SORT_VALUES,
+ true,
+ false,
+ data_types::f16,
+ 2));
+
+ network network(engine, topology, get_radix_topk_config(engine));
+ network.set_input_data("input", input);
+ auto outputs = network.execute();
+
+ auto output = outputs.at("arg_max").get_memory();
+ cldnn::mem_lock<ov::float16> output_ptr(output, get_test_stream());
+ for (size_t i = 0; i < p.ref_values.size(); i++) {
+ float val = static_cast<float>(output_ptr[i]);
+ ASSERT_NEAR(val, p.ref_values[i], 0.02f) << "value mismatch at i=" << i;
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(arg_max_gpu_topk_radix, TopKRadixValueTest,
+ testing::Values(
+ TopKRadixValueTestParam{
+ ov::op::TopKMode::MAX, 1, 16, 4, 1,
+ {ov::float16(1.0f), ov::float16(5.0f), ov::float16(3.0f), ov::float16(9.0f),
+ ov::float16(2.0f), ov::float16(7.0f), ov::float16(4.0f), ov::float16(8.0f),
+ ov::float16(6.0f), ov::float16(0.5f), ov::float16(10.0f), ov::float16(0.1f),
+ ov::float16(15.0f), ov::float16(12.0f), ov::float16(11.0f), ov::float16(0.2f)},
+ {15.0f, 12.0f, 11.0f, 10.0f},
+ "f16_max_axis_feature"
+ },
+ TopKRadixValueTestParam{
+ ov::op::TopKMode::MIN, 1, 16, 4, 1,
+ {ov::float16(1.0f), ov::float16(5.0f), ov::float16(3.0f), ov::float16(9.0f),
+ ov::float16(2.0f), ov::float16(7.0f), ov::float16(4.0f), ov::float16(8.0f),
+ ov::float16(6.0f), ov::float16(0.5f), ov::float16(-1.0f), ov::float16(0.1f),
+ ov::float16(15.0f), ov::float16(12.0f), ov::float16(11.0f), ov::float16(-2.0f)},
+ {-2.0f, -1.0f, 0.1f, 0.5f},
+ "f16_min_axis_feature"
+ },
+ TopKRadixValueTestParam{
+ ov::op::TopKMode::MAX, 1, 8, 3, 1,
+ {ov::float16(-5.0f), ov::float16(-1.0f), ov::float16(-8.0f), ov::float16(-0.5f),
+ ov::float16(-3.0f), ov::float16(-10.0f), ov::float16(-2.0f), ov::float16(-0.1f)},
+ {-0.1f, -0.5f, -1.0f},
+ "f16_max_negatives"
+ }
+ ),
+ [](const testing::TestParamInfo<TopKRadixValueTestParam>& info) { return info.param.name; }
+);
+
+// Separate parameterized case for large N on batch axis (generated input)
+TEST(arg_max_gpu_topk_radix, f16_max_large_n_axis_batch) {
+ static const int32_t batch_num = 1000;
+ auto& engine = get_test_engine();
+ const int top_k = 10;
+ auto input = engine.allocate_memory({data_types::f16, format::bfyx, {batch_num, 1, 1, 1}});
+
+ std::vector<ov::float16> input_vec(batch_num);
+ for (int i = 0; i < batch_num; i++) {
+ input_vec[i] = ov::float16(static_cast<float>(i) * 0.01f);
+ }
+ set_values(input, input_vec);
+
+ topology topology;
+ topology.add(input_layout("input", input->get_layout()));
+ topology.add(arg_max_min("arg_max",
+ {input_info("input")},
+ ov::op::TopKMode::MAX,
+ top_k,
+ 0,
+ ov::op::TopKSortType::SORT_VALUES,
+ true, false, data_types::f16));
+
+ network network(engine, topology, get_radix_topk_config(engine));
+ network.set_input_data("input", input);
+ auto outputs = network.execute();
+
+ auto output = outputs.at("arg_max").get_memory();
+ cldnn::mem_lock<ov::float16> output_ptr(output, get_test_stream());
+ for (int i = 0; i < top_k; i++) {
+ float expected = static_cast<float>(batch_num - 1 - i) * 0.01f;
+ ASSERT_NEAR(static_cast<float>(output_ptr[i]), expected, 0.02f) << "mismatch at i=" << i;
+ }
+}
+
+// --------------------------------------------------------------------------
+// Non-parameterized tests: each has unique verification logic
+// --------------------------------------------------------------------------
+
+// Radix test: f16 MAX, second output (indices), axis=feature(1)
+TEST(arg_max_gpu_topk_radix, f16_max_second_output_indices) {
+ static const int32_t feature_num = 32;
+ auto& engine = get_test_engine();
+ const int top_k = 8;
+ auto input = engine.allocate_memory({data_types::f16, format::bfyx, {1, feature_num, 1, 1}});
+ auto top_k_input = engine.allocate_memory({data_types::f16, format::bfyx, {1, 1, 1, 1}});
+ auto second_output = engine.allocate_memory({data_types::f32, format::bfyx, {1, top_k, 1, 1}});
+
+ std::vector<ov::float16> input_vec(feature_num);
+ for (int i = 0; i < feature_num; i++)
+ input_vec[i] = ov::float16(static_cast<float>(i * 3 % 17));
+ set_values(input, input_vec);
+
+ topology topology;
+ topology.add(input_layout("input", input->get_layout()));
+ topology.add(cldnn::data("const", top_k_input));
+ topology.add(mutable_data("second_output", second_output));
+ topology.add(arg_max_min("arg_max",
+ {input_info("input"), input_info("const"), input_info("second_output")},
+ ov::op::TopKMode::MAX, top_k, 1,
+ ov::op::TopKSortType::SORT_VALUES, true, false, data_types::f16));
+
+ network network(engine, topology, get_radix_topk_config(engine));
+ network.set_input_data("input", input);
+ auto outputs = network.execute();
+
+ auto output = outputs.at("arg_max").get_memory();
+ cldnn::mem_lock<ov::float16> output_ptr(output, get_test_stream());
+ for (int i = 1; i < top_k; i++) {
+ ASSERT_GE(static_cast<float>(output_ptr[i - 1]), static_cast<float>(output_ptr[i]))
+ << "values not sorted descending at i=" << i;
+ }
+ ASSERT_NEAR(static_cast<float>(output_ptr[0]), 16.0f, 0.01f);
+
+ cldnn::mem_lock<float> idx_ptr(second_output, get_test_stream());
+ ASSERT_EQ(static_cast<int>(idx_ptr[0]), 11); // first 16 is at idx=11
+}
+
+// Radix test: duplicate values tiebreaking (smaller index first)
+TEST(arg_max_gpu_topk_radix, f16_max_duplicate_values_tiebreak) {
+ auto& engine = get_test_engine();
+ const int top_k = 5;
+ auto input = engine.allocate_memory({data_types::f16, format::bfyx, {1, 10, 1, 1}});
+ auto top_k_input = engine.allocate_memory({data_types::f16, format::bfyx, {1, 1, 1, 1}});
+ auto second_output = engine.allocate_memory({data_types::f32, format::bfyx, {1, top_k, 1, 1}});
+
+ // 5,5,5,5,5,3,3,3,1,1 — top5 are all 5.0, indices 0..4
+ set_values(input, {ov::float16(5.0f), ov::float16(5.0f), ov::float16(5.0f), ov::float16(5.0f), ov::float16(5.0f),
+ ov::float16(3.0f), ov::float16(3.0f), ov::float16(3.0f), ov::float16(1.0f), ov::float16(1.0f)});
+
+ topology topology;
+ topology.add(input_layout("input", input->get_layout()));
+ topology.add(cldnn::data("const", top_k_input));
+ topology.add(mutable_data("second_output", second_output));
+ topology.add(arg_max_min("arg_max",
+ {input_info("input"), input_info("const"), input_info("second_output")},
+ ov::op::TopKMode::MAX, top_k, 1,
+ ov::op::TopKSortType::SORT_VALUES, true, false, data_types::f16));
+
+ network network(engine, topology, get_radix_topk_config(engine));
+ network.set_input_data("input", input);
+ auto outputs = network.execute();
+
+ auto output = outputs.at("arg_max").get_memory();
+ cldnn::mem_lock<ov::float16> output_ptr(output, get_test_stream());
+ for (int i = 0; i < top_k; i++)
+ ASSERT_NEAR(static_cast<float>(output_ptr[i]), 5.0f, 0.01f) << "value mismatch at i=" << i;
+
+ cldnn::mem_lock<float> idx_ptr(second_output, get_test_stream());
+ for (int i = 0; i < top_k; i++)
+ ASSERT_EQ(static_cast<int>(idx_ptr[i]), i) << "index tiebreak mismatch at i=" << i;
+}
+
+// Radix test: YOLOv26n-like scenario (N=8400, K=300, axis=feature)
+TEST(arg_max_gpu_topk_radix, f16_max_yolov26n_like) {
+ static const int32_t feature_num = 8400;
+ auto& engine = get_test_engine();
+ const int top_k = 300;
+ auto input = engine.allocate_memory({data_types::f16, format::bfyx, {1, feature_num, 1, 1}});
+
+ std::vector<ov::float16> input_vec(feature_num);
+ for (int i = 0; i < feature_num; i++)
+ input_vec[i] = ov::float16(static_cast<float>(i % 100) * 0.01f);
+ for (int i = 0; i < 300; i++)
+ input_vec[i * 28] = ov::float16(100.0f + static_cast<float>(300 - i) * 0.1f);
+ set_values(input, input_vec);
+
+ topology topology;
+ topology.add(input_layout("input", input->get_layout()));
+ topology.add(arg_max_min("arg_max",
+ {input_info("input")},
+ ov::op::TopKMode::MAX, top_k, 1,
+ ov::op::TopKSortType::SORT_VALUES, true, false, data_types::f16));
+
+ network network(engine, topology, get_radix_topk_config(engine));
+ network.set_input_data("input", input);
+ auto outputs = network.execute();
+
+ auto output = outputs.at("arg_max").get_memory();
+ cldnn::mem_lock<ov::float16> output_ptr(output, get_test_stream());
+ for (int i = 1; i < top_k; i++) {
+ ASSERT_GE(static_cast<float>(output_ptr[i - 1]), static_cast<float>(output_ptr[i]))
+ << "values not sorted descending at i=" << i;
+ }
+ ASSERT_NEAR(static_cast<float>(output_ptr[0]), 130.0f, 0.2f);
+ ASSERT_GT(static_cast<float>(output_ptr[top_k - 1]), 50.0f);
+}
+
+// Radix test: CI failure reproducer - many duplicate values, verify indices tiebreaking
+TEST(arg_max_gpu_topk_radix, f16_max_duplicates_n70_k5_indices_tiebreak) {
+ static const int32_t batch_num = 4, feature_num = 70;
+ auto& engine = get_test_engine();
+ const int top_k = 5;
+ auto input = engine.allocate_memory({data_types::f16, format::bfyx, {batch_num, feature_num, 1, 1}});
+ auto top_k_input = engine.allocate_memory({data_types::f16, format::bfyx, {1, 1, 1, 1}});
+ auto second_output = engine.allocate_memory({data_types::f32, format::bfyx, {batch_num, top_k, 1, 1}});
+
+ std::vector<ov::float16> input_vec(batch_num * feature_num);
+ std::mt19937 rng(42);
+ std::uniform_int_distribution<int> dist(0, 14);
+ for (size_t i = 0; i < input_vec.size(); i++)
+ input_vec[i] = ov::float16(static_cast<float>(dist(rng)));
+ set_values(input, input_vec);
+
+ topology topology;
+ topology.add(input_layout("input", input->get_layout()));
+ topology.add(cldnn::data("const", top_k_input));
+ topology.add(mutable_data("second_output", second_output));
+ topology.add(arg_max_min("arg_max",
+ {input_info("input"), input_info("const"), input_info("second_output")},
+ ov::op::TopKMode::MAX, top_k, 1,
+ ov::op::TopKSortType::SORT_VALUES, true, false, data_types::f16));
+
+ network network(engine, topology, get_radix_topk_config(engine));
+ network.set_input_data("input", input);
+ auto outputs = network.execute();
+
+ auto output = outputs.at("arg_max").get_memory();
+ cldnn::mem_lock<ov::float16> val_ptr(output, get_test_stream());
+ cldnn::mem_lock<float> idx_ptr(second_output, get_test_stream());
+
+ for (int b = 0; b < batch_num; b++) {
+ int input_offset = b * feature_num;
+ int out_offset = b * top_k;
+
+ std::vector<std::pair<float, int>> ref;
+ for (int i = 0; i < feature_num; i++)
+ ref.push_back({static_cast<float>(input_vec[input_offset + i]), i});
+ std::stable_sort(ref.begin(), ref.end(),
+ [](const auto& a, const auto& b) { return a.first > b.first; });
+
+ for (int k = 0; k < top_k; k++) {
+ ASSERT_NEAR(static_cast<float>(val_ptr[out_offset + k]), ref[k].first, 0.01f)
+ << "value mismatch at b=" << b << " k=" << k;
+ ASSERT_EQ(static_cast<int>(idx_ptr[out_offset + k]), ref[k].second)
+ << "index mismatch at b=" << b << " k=" << k;
+ }
+ }
+}