OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[GPU] Radix TopK for dynamic shapes, long rows, index order and argmax (#38845)
Igor Margulisff7809835d30
diff --git a/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/arg_max_min_axis.cl b/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/arg_max_min_axis.clindex f7d2ec05b45..3715ed67e99 100644--- a/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/arg_max_min_axis.cl+++ b/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/arg_max_min_axis.cl@@ -25,19 +25,39 @@#define AXIS 4#endif+// Value order shared with arg_max_min_topk_radix: NaN ranks above +inf as in PyTorch, and -0.0+// equals +0.0. Plain float comparisons are false for NaN, so with them a NaN ranks first and races+// with the true maximum for the same output position.+#if INPUT0_IS_FP+ #define ORDER_LT(a, b) (isnan(b) ? !isnan(a) : (a) < (b))+ #define ORDER_LE(a, b) (isnan(b) || (a) <= (b))+#else+ #define ORDER_LT(a, b) ((a) < (b))+ #define ORDER_LE(a, b) ((a) <= (b))+#endif+#define ORDER_GT(a, b) ORDER_LT(b, a)+#define ORDER_GE(a, b) ORDER_LE(b, a)++// The parallel sort ranks the work-item's own value a, which is not NaN there, by counting the+// values b before it that rank at or above a (SIGN_1) and the later ones that rank above it+// (SIGN_2). Ordered comparisons are false for a NaN b, which ranks above every number, so MIN+// counts those values directly, while MAX counts the complement and PARALLEL_RANK subtracts it+// from the number of compared values. A NaN check per comparison would be slower.#ifdef MAX_OUT- #define COMPARE_SIGN <- #define COMPARE_PARTIAL_SIGN >=- #define COMPARE_MERGE_SIGN >- #define COMPARE_PARALLEL_SIGN_1 <=- #define COMPARE_PARALLEL_SIGN_2 <+ #define COMPARE_SIGN ORDER_LT+ #define COMPARE_PARTIAL_SIGN ORDER_GE+ #define COMPARE_MERGE_SIGN ORDER_GT+ #define COMPARE_PARALLEL_SIGN_1(a, b) ((b) < (a))+ #define COMPARE_PARALLEL_SIGN_2(a, b) ((b) <= (a))+ #define PARALLEL_RANK(counted, compared) ((compared) - (counted))#define INPUT0_FILL_VAL INPUT0_VAL_MIN#else- #define COMPARE_SIGN >- #define COMPARE_PARTIAL_SIGN <=- #define COMPARE_MERGE_SIGN <- #define COMPARE_PARALLEL_SIGN_1 >=- #define COMPARE_PARALLEL_SIGN_2 >+ #define COMPARE_SIGN ORDER_GT+ #define COMPARE_PARTIAL_SIGN ORDER_LE+ #define COMPARE_MERGE_SIGN ORDER_LT+ #define COMPARE_PARALLEL_SIGN_1(a, b) ((a) >= (b))+ #define COMPARE_PARALLEL_SIGN_2(a, b) ((a) > (b))+ #define PARALLEL_RANK(counted, compared) (counted)#define INPUT0_FILL_VAL INPUT0_VAL_MAX#endif@@ -164,63 +184,140 @@ KERNEL(arg_max_min_modified)(result.value = input[FUNC_CALL(get_input_index)(OPTIONAL_SHAPE_INFO_TENSOR indices[0], indices[1], 0, indices[2], indices[3], indices[4])];result.index = sort_idx;- for (uint i = 0; i < sort_idx / 8; i++) {+ // Values before sort_idx rank ahead when they rank at or above this one, later values when+ // they rank above it.+ uint head_end = sort_idx;+ uint tail_begin = sort_idx + 1;+ uint counted = 0;+#if INPUT0_IS_FP+ // The comparisons below need a number. A NaN ranks above every number and after the NaNs+ // before it, so its position is counted separately.+ if (isnan(result.value)) {+#ifdef MAX_OUT+ for (uint i = 0; i < sort_idx && sort_position < TOP_K; i++) {+ indices[AXIS] = i;+ sort_position += isnan(input[FUNC_CALL(get_input_index)(OPTIONAL_SHAPE_INFO_TENSOR indices[0], indices[1], 0, indices[2], indices[3], indices[4])]) ? 1 : 0;+ }+#else+ sort_position = sort_idx;+ for (uint i = sort_idx + 1; i < VALUES_NUM && sort_position < TOP_K; i++) {+ indices[AXIS] = i;+ sort_position += isnan(input[FUNC_CALL(get_input_index)(OPTIONAL_SHAPE_INFO_TENSOR indices[0], indices[1], 0, indices[2], indices[3], indices[4])]) ? 0 : 1;+ }+#endif+ head_end = 0;+ tail_begin = VALUES_NUM;+ }+#endif++ for (uint i = 0; i < head_end / 8; i++) {uint index_offset = i * 8;indices[AXIS] = index_offset;INPUT0_TYPE test_value = input[FUNC_CALL(get_input_index)(OPTIONAL_SHAPE_INFO_TENSOR indices[0], indices[1], 0, indices[2], indices[3], indices[4])];- if (result.value COMPARE_PARALLEL_SIGN_1 test_value)- sort_position++;+ if (COMPARE_PARALLEL_SIGN_1(result.value, test_value))+ counted++;indices[AXIS] = index_offset + 1;test_value = input[FUNC_CALL(get_input_index)(OPTIONAL_SHAPE_INFO_TENSOR indices[0], indices[1], 0, indices[2], indices[3], indices[4])];- if (result.value COMPARE_PARALLEL_SIGN_1 test_value)- sort_position++;+ if (COMPARE_PARALLEL_SIGN_1(result.value, test_value))+ counted++;indices[AXIS] = index_offset + 2;test_value = input[FUNC_CALL(get_input_index)(OPTIONAL_SHAPE_INFO_TENSOR indices[0], indices[1], 0, indices[2], indices[3], indices[4])];- if (result.value COMPARE_PARALLEL_SIGN_1 test_value)- sort_position++;+ if (COMPARE_PARALLEL_SIGN_1(result.value, test_value))+ counted++;indices[AXIS] = index_offset + 3;test_value = input[FUNC_CALL(get_input_index)(OPTIONAL_SHAPE_INFO_TENSOR indices[0], indices[1], 0, indices[2], indices[3], indices[4])];- if (result.value COMPARE_PARALLEL_SIGN_1 test_value)- sort_position++;+ if (COMPARE_PARALLEL_SIGN_1(result.value, test_value))+ counted++;indices[AXIS] = index_offset + 4;test_value = input[FUNC_CALL(get_input_index)(OPTIONAL_SHAPE_INFO_TENSOR indices[0], indices[1], 0, indices[2], indices[3], indices[4])];- if (result.value COMPARE_PARALLEL_SIGN_1 test_value)- sort_position++;+ if (COMPARE_PARALLEL_SIGN_1(result.value, test_value))+ counted++;indices[AXIS] = index_offset + 5;test_value = input[FUNC_CALL(get_input_index)(OPTIONAL_SHAPE_INFO_TENSOR indices[0], indices[1], 0, indices[2], indices[3], indices[4])];- if (result.value COMPARE_PARALLEL_SIGN_1 test_value)- sort_position++;+ if (COMPARE_PARALLEL_SIGN_1(result.value, test_value))+ counted++;indices[AXIS] = index_offset + 6;test_value = input[FUNC_CALL(get_input_index)(OPTIONAL_SHAPE_INFO_TENSOR indices[0], indices[1], 0, indices[2], indices[3], indices[4])];- if (result.value COMPARE_PARALLEL_SIGN_1 test_value)- sort_position++;+ if (COMPARE_PARALLEL_SIGN_1(result.value, test_value))+ counted++;indices[AXIS] = index_offset + 7;test_value = input[FUNC_CALL(get_input_index)(OPTIONAL_SHAPE_INFO_TENSOR indices[0], indices[1], 0, indices[2], indices[3], indices[4])];- if (result.value COMPARE_PARALLEL_SIGN_1 test_value)- sort_position++;- if (sort_position >= TOP_K)+ if (COMPARE_PARALLEL_SIGN_1(result.value, test_value))+ counted++;+ if (sort_position + PARALLEL_RANK(counted, index_offset + 8) >= TOP_K)return;}- for (uint i = (sort_idx / 8) * 8; i < sort_idx; i++) {+ for (uint i = (head_end / 8) * 8; i < head_end; i++) {indices[AXIS] = i;INPUT0_TYPE test_value = input[FUNC_CALL(get_input_index)(OPTIONAL_SHAPE_INFO_TENSOR indices[0], indices[1], 0, indices[2], indices[3], indices[4])];- if (result.value COMPARE_PARALLEL_SIGN_1 test_value)- sort_position++;+ if (COMPARE_PARALLEL_SIGN_1(result.value, test_value))+ counted++;}+ sort_position += PARALLEL_RANK(counted, head_end);if (sort_position >= TOP_K)return;- for (uint i = sort_idx + 1; i < VALUES_NUM; i++) {+ // As in the head loop, the unrolled blocks start at multiples of 8: f16 blocks at other offsets+ // load much slower.+ counted = 0;+ const uint tail_aligned = min((tail_begin + 7) / 8 * 8, (uint)VALUES_NUM);+ for (uint i = tail_begin; i < tail_aligned; i++) {indices[AXIS] = i;INPUT0_TYPE test_value = input[FUNC_CALL(get_input_index)(OPTIONAL_SHAPE_INFO_TENSOR indices[0], indices[1], 0, indices[2], indices[3], indices[4])];- if (result.value COMPARE_PARALLEL_SIGN_2 test_value)- sort_position++;- if (sort_position >= TOP_K)+ if (COMPARE_PARALLEL_SIGN_2(result.value, test_value))+ counted++;+ }+ for (uint i = tail_aligned / 8; i < VALUES_NUM / 8; i++) {+ uint index_offset = i * 8;+ indices[AXIS] = index_offset;+ INPUT0_TYPE test_value = input[FUNC_CALL(get_input_index)(OPTIONAL_SHAPE_INFO_TENSOR indices[0], indices[1], 0, indices[2], indices[3], indices[4])];+ if (COMPARE_PARALLEL_SIGN_2(result.value, test_value))+ counted++;+ indices[AXIS] = index_offset + 1;+ test_value = input[FUNC_CALL(get_input_index)(OPTIONAL_SHAPE_INFO_TENSOR indices[0], indices[1], 0, indices[2], indices[3], indices[4])];+ if (COMPARE_PARALLEL_SIGN_2(result.value, test_value))+ counted++;+ indices[AXIS] = index_offset + 2;+ test_value = input[FUNC_CALL(get_input_index)(OPTIONAL_SHAPE_INFO_TENSOR indices[0], indices[1], 0, indices[2], indices[3], indices[4])];+ if (COMPARE_PARALLEL_SIGN_2(result.value, test_value))+ counted++;+ indices[AXIS] = index_offset + 3;+ test_value = input[FUNC_CALL(get_input_index)(OPTIONAL_SHAPE_INFO_TENSOR indices[0], indices[1], 0, indices[2], indices[3], indices[4])];+ if (COMPARE_PARALLEL_SIGN_2(result.value, test_value))+ counted++;+ indices[AXIS] = index_offset + 4;+ test_value = input[FUNC_CALL(get_input_index)(OPTIONAL_SHAPE_INFO_TENSOR indices[0], indices[1], 0, indices[2], indices[3], indices[4])];+ if (COMPARE_PARALLEL_SIGN_2(result.value, test_value))+ counted++;+ indices[AXIS] = index_offset + 5;+ test_value = input[FUNC_CALL(get_input_index)(OPTIONAL_SHAPE_INFO_TENSOR indices[0], indices[1], 0, indices[2], indices[3], indices[4])];+ if (COMPARE_PARALLEL_SIGN_2(result.value, test_value))+ counted++;+ indices[AXIS] = index_offset + 6;+ test_value = input[FUNC_CALL(get_input_index)(OPTIONAL_SHAPE_INFO_TENSOR indices[0], indices[1], 0, indices[2], indices[3], indices[4])];+ if (COMPARE_PARALLEL_SIGN_2(result.value, test_value))+ counted++;+ indices[AXIS] = index_offset + 7;+ test_value = input[FUNC_CALL(get_input_index)(OPTIONAL_SHAPE_INFO_TENSOR indices[0], indices[1], 0, indices[2], indices[3], indices[4])];+ if (COMPARE_PARALLEL_SIGN_2(result.value, test_value))+ counted++;+ if (sort_position + PARALLEL_RANK(counted, index_offset + 8 - tail_begin) >= TOP_K)return;}+ for (uint i = max(tail_aligned, (uint)(VALUES_NUM / 8) * 8); i < VALUES_NUM; i++) {+ indices[AXIS] = i;+ INPUT0_TYPE test_value = input[FUNC_CALL(get_input_index)(OPTIONAL_SHAPE_INFO_TENSOR indices[0], indices[1], 0, indices[2], indices[3], indices[4])];+ if (COMPARE_PARALLEL_SIGN_2(result.value, test_value))+ counted++;+ }++ sort_position += PARALLEL_RANK(counted, VALUES_NUM - tail_begin);+ if (sort_position >= TOP_K)+ return;+// Using simple sorting for sorting by indices and when TOP_K == 1#elif TOP_K == 1INPUT0_TYPE val = input[FUNC_CALL(get_input_index)(OPTIONAL_SHAPE_INFO_TENSOR indices[0], indices[1], 0, indices[2], indices[3], indices[4])];@@ -243,7 +340,7 @@ KERNEL(arg_max_min_modified)(indices[AXIS] = i;INPUT0_TYPE in_data = input[FUNC_CALL(get_input_index)(OPTIONAL_SHAPE_INFO_TENSOR indices[0], indices[1], 0, indices[2], indices[3], indices[4])];- if (val COMPARE_SIGN in_data) {+ if (COMPARE_SIGN(val, in_data)) {result[top_k].index = i;result[top_k].value = in_data;val = in_data;@@ -288,7 +385,7 @@ KERNEL(arg_max_min_modified)(if (right_end > VALUES_NUM) right_end = VALUES_NUM;m = i = left; j = right;while ((i < right) && (j < right_end)) {- if (result[i].value COMPARE_PARTIAL_SIGN result[j].value) {+ if (COMPARE_PARTIAL_SIGN(result[i].value, result[j].value)) {temp_buf[m++] = result[i++];} else {temp_buf[m++] = result[j++];@@ -339,7 +436,7 @@ KERNEL(arg_max_min_modified)(if (right_end > group_size) right_end = group_size;m = i = left; j = right;while ((i < right) && (j < right_end)) {- if (temp_buf[group_offset + i].value COMPARE_PARTIAL_SIGN temp_buf[group_offset + j].value) {+ if (COMPARE_PARTIAL_SIGN(temp_buf[group_offset + i].value, temp_buf[group_offset + j].value)) {result[group_offset + (m++)] = temp_buf[group_offset + (i++)];} else {result[group_offset + (m++)] = temp_buf[group_offset + (j++)];@@ -363,7 +460,7 @@ KERNEL(arg_max_min_modified)(if (right_end > last_group_size) right_end = last_group_size;m = i = left; j = right;while ((i < right) && (j < right_end)) {- if (temp_buf[last_group_offset + i].value COMPARE_PARTIAL_SIGN temp_buf[last_group_offset + j].value) {+ if (COMPARE_PARTIAL_SIGN(temp_buf[last_group_offset + i].value, temp_buf[last_group_offset + j].value)) {result[last_group_offset + (m++)] = temp_buf[last_group_offset + (i++)];} else {result[last_group_offset + (m++)] = temp_buf[last_group_offset + (j++)];@@ -417,7 +514,7 @@ KERNEL(arg_max_min_modified)(continue;}- if (temp_buf[test_index].value COMPARE_MERGE_SIGN merge_buf.value) {+ if (COMPARE_MERGE_SIGN(temp_buf[test_index].value, merge_buf.value)) {merge_buf = temp_buf[test_index];merge_buf_index = j;}@@ -480,6 +577,11 @@ KERNEL(arg_max_min_modified)(#undef COMPARE_MERGE_SIGN#undef COMPARE_PARALLEL_SIGN_1#undef COMPARE_PARALLEL_SIGN_2+#undef PARALLEL_RANK+#undef ORDER_LT+#undef ORDER_LE+#undef ORDER_GT+#undef ORDER_GE#undef INPUT0_FILL_VAL#undef AXIS#undef VALUES_NUMdiff --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.clindex 3823289e935..c1585bd78f4 100644--- 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@@ -7,14 +7,24 @@// 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 3: Bitonic sort in SLM (45 barriers for K<=512 vs 3000+ for iterative),+// by value or, without SORT_BY_VALUE, by index// Phase 4: Write sorted results to output//+// Chunked mode (RADIX_CHUNK_STAGE + RADIX_MERGE_STAGE kernels):+// One work-group per operation leaves most of the GPU idle when there are only a few+// long rows. The chunk stage runs the algorithm above on RADIX_CHUNKS slices of each+// row and stores every slice's top-K keys and indices. The merge stage runs it again+// on the RADIX_CANDIDATES_NUM survivors of each row and writes the outputs. Survivors+// are laid out by chunk and sorted with the same (key, index) ordering, so among equal+// keys their position order matches the original index order.+//// Design principles:-// - Read input exactly ONCE to avoid GPU cache inconsistency+// - Read input exactly ONCE to avoid GPU cache inconsistency; Phase 4 only reads back selected+// zeros and NaNs, whose keys do not keep the sign or payload// - 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)+// - Total SLM: ~6KB (histogram 1KB + tie counters 1KB + sort buffers 4KB)//#include "include/fetch_utils.cl"@@ -48,25 +58,33 @@#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+#define BUCKET_GROUPS (NUM_BUCKETS / BUCKET_GROUP_SIZE)+#define TIE_GROUPS (WG_SIZE / TIE_GROUP_SIZE)// Coarse-to-fine radix select: one 8-bit digit per pass, MSD first.#define NUM_PASSES (SORTABLE_BITS / 8)-// Ordering of (key, index) pairs. Equal values are broken by the smallest original index,-// matching TF/ONNX TopK behaviour.-#ifdef MAX_OUT- #define PAIR_GT(key_a, idx_a, key_b, idx_b) ((key_a) != (key_b) ? (key_a) > (key_b) : (idx_a) < (idx_b))+// Ordering of (key, index) pairs; the sort puts the "greatest" pair first for MAX and last for MIN.+// Equal values are broken by the smallest original index, matching TF/ONNX TopK behaviour.+// Without SORT_BY_VALUE the selected elements are ordered by index only.+#ifdef SORT_BY_VALUE+ #ifdef MAX_OUT+ #define PAIR_GT(key_a, idx_a, key_b, idx_b) ((key_a) != (key_b) ? (key_a) > (key_b) : (idx_a) < (idx_b))+ #else+ #define PAIR_GT(key_a, idx_a, key_b, idx_b) ((key_a) != (key_b) ? (key_a) > (key_b) : (idx_a) > (idx_b))+ #endif+#else+ #ifdef MAX_OUT+ #define PAIR_GT(key_a, idx_a, key_b, idx_b) ((idx_a) < (idx_b))+ #else+ #define PAIR_GT(key_a, idx_a, key_b, idx_b) ((idx_a) > (idx_b))+ #endif+#endif+// Ordering by index alone can't tell surplus threshold ties from better elements, so only K are gathered.+#ifdef SORT_BY_VALUE+ #define GATHER_LIMIT PADDED_K#else- #define PAIR_GT(key_a, idx_a, key_b, idx_b) ((key_a) != (key_b) ? (key_a) > (key_b) : (idx_a) > (idx_b))+ #define GATHER_LIMIT TOP_K#endif#define FILL_IDX 0xFFFFFFFFu@@ -113,12 +131,19 @@ inline void FUNC(get_indices_from_dims)(OPTIONAL_SHAPE_INFO_ARG// Convert a float value to a monotonically increasing unsigned integer:// for positive values the bit pattern is already ordered, so only the sign bit is flipped;-// for negative values all bits are flipped.+// for negative values all bits are flipped. -0.0 gets the key of +0.0 so equal values keep+// index order, and every NaN gets the largest key: like PyTorch, NaN ranks above +inf.+// Only these two keys stand for more than one bit pattern.#if SORTABLE_BITS == 16+#define ZERO_KEY 0x8000u+#define NAN_KEY 0xFFFFu+inline uint FUNC(to_sortable)(INPUT0_TYPE val) {- ushort bits = as_ushort(convert_half(val));+ const half h = convert_half(val);+ ushort bits = as_ushort(h);ushort mask = (bits >> 15) ? (ushort)0xFFFF : (ushort)0x8000;- return (uint)(bits ^ mask);+ const uint key = (uint)(bits ^ mask);+ return isnan(h) ? NAN_KEY : (h == (half)0 ? ZERO_KEY : key);}inline INPUT0_TYPE FUNC(from_sortable)(uint sortable) {@@ -127,10 +152,15 @@ inline INPUT0_TYPE FUNC(from_sortable)(uint sortable) {return TO_INPUT0_TYPE(as_half((ushort)(bits ^ mask)));}#else+#define ZERO_KEY 0x80000000u+#define NAN_KEY 0xFFFFFFFFu+inline uint FUNC(to_sortable)(INPUT0_TYPE val) {- uint bits = as_uint(convert_float(val));+ const float f = convert_float(val);+ uint bits = as_uint(f);uint mask = (bits >> 31) ? 0xFFFFFFFFu : 0x80000000u;- return bits ^ mask;+ const uint key = bits ^ mask;+ return isnan(f) ? NAN_KEY : (f == 0.0f ? ZERO_KEY : key);}inline INPUT0_TYPE FUNC(from_sortable)(uint sortable) {@@ -139,48 +169,71 @@ inline INPUT0_TYPE FUNC(from_sortable)(uint sortable) {}#endif-REQD_SUB_GROUP_SIZE(16)+REQD_SUB_GROUP_SIZE(SUB_GROUP_SIZE)KERNEL(arg_max_min_topk_radix)(+ OPTIONAL_SHAPE_INFO_ARGconst __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+#if defined(RADIX_CHUNK_STAGE) || defined(RADIX_MERGE_STAGE)+ ,__global uint* candidate_keys // Per-chunk top-K keys: RADIX_CANDIDATES_NUM per operation+ ,__global uint* candidate_idxs // Original indices of candidate_keys+#endif){const uint lid = (uint)get_local_id(0);+#ifdef RADIX_CHUNK_STAGE+ const uint chunk_group_idx = (uint)get_group_id(0);+ const uint output_idx = chunk_group_idx / RADIX_CHUNKS;+ const uint chunk_begin = (chunk_group_idx % RADIX_CHUNKS) * RADIX_CHUNK_SIZE;+ const uint values_count = min((uint)RADIX_CHUNK_SIZE, (uint)VALUES_NUM - chunk_begin);+ __global uint* my_sortable = sortable_buf + chunk_group_idx * RADIX_CHUNK_SIZE;+#elif defined(RADIX_MERGE_STAGE)+ const uint output_idx = (uint)get_group_id(0);+ const uint values_count = RADIX_CANDIDATES_NUM;+ // Keys were already converted by the chunk stage; positions index candidate_idxs.+ const __global uint* my_sortable = candidate_keys + output_idx * RADIX_CANDIDATES_NUM;+#elseconst uint output_idx = (uint)get_group_id(0);+ const uint chunk_begin = 0;+ const uint values_count = VALUES_NUM;+ __global uint* my_sortable = sortable_buf + output_idx * VALUES_NUM;+#endifuint 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+ // Validate() in arg_max_min_kernel_topk_radix.cpp checks their total size; update it with them.// ============================================================__local uint histogram[NUM_BUCKETS]; // 1KB+ __local uint bucket_group_counts[BUCKET_GROUPS];+ __local uint tie_counts[WG_SIZE]; // per work-item tie counts for ordered tie gathering+ __local uint tie_group_counts[TIE_GROUPS];__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 gather_count;+#ifndef RADIX_MERGE_STAGE// ============================================================// Phase 0: Read input ONCE, convert to sortable keys, cache in global buffer// ============================================================- for (uint i = lid; i < VALUES_NUM; i += WG_SIZE) {- base_indices[AXIS] = i;+ for (uint i = lid; i < values_count; i += WG_SIZE) {+ base_indices[AXIS] = chunk_begin + i;INPUT0_TYPE val = input[FUNC_CALL(get_input_index)(OPTIONAL_SHAPE_INFO_TENSORbase_indices[0], base_indices[1], 0, base_indices[2], base_indices[3], base_indices[4])];my_sortable[i] = FUNC_CALL(to_sortable)(val);}barrier(CLK_LOCAL_MEM_FENCE | CLK_GLOBAL_MEM_FENCE);+#endif// ============================================================// Phase 1: MSD radix select - resolve the K-th key one byte at a time.@@ -199,7 +252,7 @@ KERNEL(arg_max_min_topk_radix)(}barrier(CLK_LOCAL_MEM_FENCE);- for (uint i = lid; i < VALUES_NUM; i += WG_SIZE) {+ for (uint i = lid; i < values_count; i += WG_SIZE) {uint sortable = my_sortable[i];uint hi = (hi_shift >= SORTABLE_BITS) ? 0u : (sortable >> hi_shift);if (hi == prefix) {@@ -208,10 +261,25 @@ KERNEL(arg_max_min_topk_radix)(}barrier(CLK_LOCAL_MEM_FENCE);+ // Two-level search for the threshold bucket: group sums first, then buckets of one group.+ if (lid < BUCKET_GROUPS) {+ uint group_count = 0;+ for (uint j = 0; j < BUCKET_GROUP_SIZE; j++) {+ group_count += histogram[lid * BUCKET_GROUP_SIZE + j];+ }+ bucket_group_counts[lid] = group_count;+ }+ barrier(CLK_LOCAL_MEM_FENCE);+if (lid == 0) {uint cumulative = already_above;#ifdef MAX_OUT- for (int b = NUM_BUCKETS - 1; b >= 0; b--) {+ int group = BUCKET_GROUPS - 1;+ while (group > 0 && cumulative + bucket_group_counts[group] < TOP_K) {+ cumulative += bucket_group_counts[group];+ group--;+ }+ for (int b = (group + 1) * BUCKET_GROUP_SIZE - 1; b >= 0; b--) {cumulative += histogram[b];if (cumulative >= TOP_K) {threshold_bucket = (uint)b;@@ -220,7 +288,12 @@ KERNEL(arg_max_min_topk_radix)(}}#else- for (uint b = 0; b < NUM_BUCKETS; b++) {+ uint group = 0;+ while (group < BUCKET_GROUPS - 1 && cumulative + bucket_group_counts[group] < TOP_K) {+ cumulative += bucket_group_counts[group];+ group++;+ }+ for (uint b = group * BUCKET_GROUP_SIZE; b < NUM_BUCKETS; b++) {cumulative += histogram[b];if (cumulative >= TOP_K) {threshold_bucket = b;@@ -261,7 +334,7 @@ KERNEL(arg_max_min_topk_radix)(// Phase 2a: Gather elements strictly ABOVE threshold into SLM// Read from cached sortable buffer// ============================================================- for (uint i = lid; i < VALUES_NUM; i += WG_SIZE) {+ for (uint i = lid; i < values_count; i += WG_SIZE) {uint sortable = my_sortable[i];bool is_above;#ifdef MAX_OUT@@ -282,47 +355,72 @@ KERNEL(arg_max_min_topk_radix)(// ============================================================// 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)+ // - Fast path: all fit. parallel atomic_add (no correctness issue)+ // - Ordered path: overflow. Each work-item owns a contiguous index block, so a+ // prefix sum of per-block tie counts places the smallest indices first+ // (matching TF/ONNX behavior) without a single work-item scan.// histogram[threshold & 0xFF] still holds the fine histogram count from Phase 1.// ============================================================- uint current_count = min(gather_count, (uint)PADDED_K);+ uint current_count = min(gather_count, (uint)GATHER_LIMIT);if (lid == 0) {gather_count = current_count;}barrier(CLK_LOCAL_MEM_FENCE);- if (current_count < PADDED_K) {+ if (current_count < GATHER_LIMIT) {uint at_count = histogram[threshold & 0xFF];- uint available_slots = PADDED_K - current_count;+ uint available_slots = GATHER_LIMIT - 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) {+ for (uint i = lid; i < values_count; i += WG_SIZE) {uint sortable = my_sortable[i];if (sortable == threshold) {uint pos = atomic_add(&gather_count, 1);- if (pos < PADDED_K) {+ if (pos < GATHER_LIMIT) {sort_keys[pos] = sortable;sort_idxs[pos] = i;}}}} else {- // Slow path: more at-threshold elements than slots,- // sequential scan ensures smallest indices are selected first- if (lid == 0) {+ const uint block_size = (values_count + WG_SIZE - 1) / WG_SIZE;+ const uint block_begin = min(lid * block_size, values_count);+ const uint block_end = min(block_begin + block_size, values_count);++ uint block_ties = 0;+ for (uint i = block_begin; i < block_end; i++) {+ block_ties += (my_sortable[i] == threshold) ? 1u : 0u;+ }+ tie_counts[lid] = block_ties;+ barrier(CLK_LOCAL_MEM_FENCE);++ const uint tie_group = lid / TIE_GROUP_SIZE;+ if (lid < TIE_GROUPS) {+ uint group_ties = 0;+ for (uint j = 0; j < TIE_GROUP_SIZE; j++) {+ group_ties += tie_counts[lid * TIE_GROUP_SIZE + j];+ }+ tie_group_counts[lid] = group_ties;+ }+ barrier(CLK_LOCAL_MEM_FENCE);++ if (block_ties != 0) {uint pos = current_count;- for (uint i = 0; i < VALUES_NUM && pos < PADDED_K; i++) {- uint sortable = my_sortable[i];- if (sortable == threshold) {- sort_keys[pos] = sortable;+ for (uint g = 0; g < tie_group; g++) {+ pos += tie_group_counts[g];+ }+ for (uint j = tie_group * TIE_GROUP_SIZE; j < lid; j++) {+ pos += tie_counts[j];+ }++ for (uint i = block_begin; i < block_end && pos < GATHER_LIMIT; i++) {+ if (my_sortable[i] == threshold) {+ sort_keys[pos] = threshold;sort_idxs[pos] = i;pos++;}}- gather_count = pos;}}}@@ -359,12 +457,33 @@ KERNEL(arg_max_min_topk_radix)(}}+#ifdef RADIX_CHUNK_STAGE+ // ============================================================+ // Phase 4: Store this chunk's sorted top-K as merge candidates+ // ============================================================+ for (uint k = lid; k < TOP_K; k += WG_SIZE) {+ candidate_keys[chunk_group_idx * TOP_K + k] = sort_keys[k];+ candidate_idxs[chunk_group_idx * TOP_K + k] = chunk_begin + sort_idxs[k];+ }+#else// ============================================================// Phase 4: Write sorted top-K results to output+ // Zero and NaN values are reloaded from the input, because their keys drop the sign of zero+ // and the NaN payload.// ============================================================for (uint k = lid; k < TOP_K; k += WG_SIZE) {- INPUT0_TYPE val = FUNC_CALL(from_sortable)(sort_keys[k]);+#ifdef RADIX_MERGE_STAGE+ uint idx = candidate_idxs[output_idx * RADIX_CANDIDATES_NUM + sort_idxs[k]];+#elseuint idx = sort_idxs[k];+#endif+ const uint key = sort_keys[k];+ INPUT0_TYPE val = FUNC_CALL(from_sortable)(key);+ if ((key == ZERO_KEY || key == NAN_KEY) && idx < VALUES_NUM) {+ base_indices[AXIS] = idx;+ 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])];+ }base_indices[AXIS] = k;uint out_offset = FUNC_CALL(get_output_index)(OPTIONAL_SHAPE_INFO_TENSOR@@ -383,6 +502,7 @@ KERNEL(arg_max_min_topk_radix)(#endif#endif}+#endif}#undef COMPARE_SIGN@@ -392,7 +512,14 @@ KERNEL(arg_max_min_topk_radix)(#undef WG_SIZE#undef PADDED_K#undef NUM_BUCKETS+#undef BUCKET_GROUP_SIZE+#undef BUCKET_GROUPS+#undef TIE_GROUP_SIZE+#undef TIE_GROUPS#undef SORTABLE_BITS+#undef ZERO_KEY+#undef NAN_KEY#undef NUM_PASSES#undef PAIR_GT+#undef GATHER_LIMIT#undef FILL_IDXdiff --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.cppindex 18a6957c97d..e9feee325e0 100644--- 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@@ -4,13 +4,35 @@#include "arg_max_min_kernel_topk_radix.h"#include <kernel_selector_utils.h>+#include "common_tools.h"#include <cstdlib>namespace kernel_selector {namespace {+// The kernel gets these as JIT constants, and Validate sizes its SLM from them.constexpr size_t kWgSize = 256;+constexpr size_t kSubGroupSize = 16;+constexpr size_t kNumBuckets = 256;+constexpr size_t kBucketGroupSize = 16;+constexpr size_t kTieGroupSize = 16;+static_assert(kNumBuckets == 256, "The kernel resolves 8-bit digits: NUM_PASSES and its 0xFF masks assume 256 buckets");+static_assert(kNumBuckets % kBucketGroupSize == 0 && kWgSize % kTieGroupSize == 0,+ "Bucket and tie groups must evenly divide the buckets and the work-group");++constexpr size_t kTargetChunkSize = 8192;+constexpr size_t kMinChunkedSortSize = 2 * kTargetChunkSize;+constexpr size_t kMaxCandidatesShare = 8;+constexpr size_t kMergeBalance = 2;+constexpr size_t kMinChunkSize = 1024;+constexpr size_t kMinFewRowsSortSize = 4096;+constexpr size_t kFewRowsFillDivisor = 2;++struct ChunkConfig {+ size_t chunks = 1;+ size_t chunk_size = 0;+};size_t GetOperationNumber(const arg_max_min_params& params) {switch (params.argMaxMinAxis) {@@ -47,6 +69,79 @@ size_t GetSortSize(const arg_max_min_params& params) {}}+bool IsSortSizeDynamic(const arg_max_min_params& params) {+ switch (params.argMaxMinAxis) {+ case ArgMaxMinAxis::BATCH: return params.inputs[0].Batch().is_dynamic;+ case ArgMaxMinAxis::FEATURE: return params.inputs[0].Feature().is_dynamic;+ case ArgMaxMinAxis::Z: return params.inputs[0].Z().is_dynamic;+ case ArgMaxMinAxis::Y: return params.inputs[0].Y().is_dynamic;+ case ArgMaxMinAxis::X: return params.inputs[0].X().is_dynamic;+ default: throw std::invalid_argument("Unsupported axis");+ }+}++// Work-groups of kWgSize work-items that the device keeps resident at once.+size_t GetResidentWorkGroups(const arg_max_min_params& params) {+ return std::max<size_t>(1, params.engineInfo.maxThreadsPerDevice / (kWgSize / kSubGroupSize));+}++// Splits long rows so that a few operations still occupy many work-groups. By default the chunk+// count only depends on the static sort size, so dynamic operation counts reuse the same kernels.+// When the operation count is known at compile time and fills less than half of the resident+// work-groups, rows of kMinFewRowsSortSize or more values are split further, into chunks of at+// least kMinChunkSize values. Dynamic operation counts keep the default, because short chunks+// are slower than unchunked rows once many rows fill the device.+ChunkConfig GetChunkConfig(const arg_max_min_params& params, bool static_operation_num) {+ ChunkConfig config;+ if (IsSortSizeDynamic(params)) {+ return config;+ }++ const size_t sort_size = GetSortSize(params);+ const size_t top_k = params.topK;+ size_t chunks = sort_size >= kMinChunkedSortSize ? CeilDiv(sort_size, kTargetChunkSize) : 1;+ if (static_operation_num && sort_size >= kMinFewRowsSortSize) {+ const size_t ops_num = GetOperationNumber(params);+ const size_t target_work_groups = GetResidentWorkGroups(params) / kFewRowsFillDivisor;+ if (ops_num * chunks < target_work_groups) {+ chunks = std::max(chunks, std::min(CeilDiv(target_work_groups, ops_num), sort_size / kMinChunkSize));+ }+ }++ for (; chunks > 1; --chunks) {+ const size_t chunk_size = CeilDiv(sort_size, chunks);+ if (chunk_size * (chunks - 1) >= sort_size || sort_size - chunk_size * (chunks - 1) < top_k) {+ continue;+ }+ // The merge stage selects again from chunks * top_k candidates, so large K needs long chunks:+ // every chunk holds kMaxCandidatesShare * top_k values, and the merge input stays within+ // 1 / kMergeBalance of a chunk.+ if (chunks * top_k * kMaxCandidatesShare > sort_size || chunks * chunks * top_k * kMergeBalance > sort_size) {+ continue;+ }+ config.chunks = chunks;+ config.chunk_size = chunk_size;+ break;+ }+ return config;+}++void SetInternalBuffers(const arg_max_min_params& params, const ChunkConfig& config, KernelData& kd) {+ const size_t ops_num = GetOperationNumber(params);+ kd.internalBuffers.clear();+ if (config.chunks == 1) {+ // Sortable keys: VALUES_NUM per operation+ kd.internalBuffers.push_back(sizeof(uint32_t) * GetSortSize(params) * ops_num);+ } else {+ // Sortable keys per chunk, then top-K keys and indices of every chunk+ const size_t candidates_size = sizeof(uint32_t) * config.chunks * params.topK * ops_num;+ kd.internalBuffers.push_back(sizeof(uint32_t) * config.chunks * config.chunk_size * ops_num);+ kd.internalBuffers.push_back(candidates_size);+ kd.internalBuffers.push_back(candidates_size);+ }+ kd.internalBufferDataType = Datatype::UINT32;+}+} // namespaceParamsKey ArgMaxMinKernelTopKRadix::GetSupportedKey() const {@@ -69,6 +164,7 @@ ParamsKey ArgMaxMinKernelTopKRadix::GetSupportedKey() const {k.EnableBatching();k.EnableTensorPitches();k.EnableTensorOffset();+ k.EnableDynamicShapesSupport();return k;}@@ -84,10 +180,6 @@ bool ArgMaxMinKernelTopKRadix::Validate(const Params& p) const {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) {@@ -95,12 +187,13 @@ bool ArgMaxMinKernelTopKRadix::Validate(const Params& p) const {}// PADDED_K (next power of 2 >= topK) must fit in SLM:- // sort_keys[PADDED_K] + sort_idxs[PADDED_K] + histogram[256] + scalars+ // sort_keys[PADDED_K] + sort_idxs[PADDED_K] + histogram[NUM_BUCKETS] + bucket/tie counters + scalarssize_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;+ const size_t counters = kNumBuckets / kBucketGroupSize + kWgSize + kWgSize / kTieGroupSize;+ const size_t slm_needed = (padded_k * 2 + kNumBuckets + counters) * sizeof(uint32_t) + 24;if (slm_needed > params.engineInfo.maxLocalMemSize) {DO_NOT_USE_THIS_KERNEL(p.layerID);}@@ -126,16 +219,25 @@ 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);+ OPENVINO_ASSERT(kd.kernels.size() == 1 || kd.kernels.size() == 2,+ "[GPU] Invalid kernels size for update dispatch data func");+ // Only dynamic implementations get here, and their chunk config ignores the operation count.+ // A dynamic sort axis disables chunking at compile time, so the kernel count decides the mode.+ const ChunkConfig config = kd.kernels.size() == 1 ? ChunkConfig{} : GetChunkConfig(prim_params, false);+ OPENVINO_ASSERT(kd.kernels.size() == 1 || config.chunks > 1, "[GPU] Unexpected radix TopK chunk config");++ const bool skip_execution = KernelData::SkipKernelExecution(prim_params);+ for (size_t i = 0; i < kd.kernels.size(); ++i) {+ auto gws = dispatchData.gws;+ if (i == 0 && config.chunks > 1) {+ gws[0] *= config.chunks;+ }+ kd.kernels[i].params.workGroups.global = gws;+ kd.kernels[i].params.workGroups.local = dispatchData.lws;+ kd.kernels[i].skip_execution = skip_execution;+ }++ SetInternalBuffers(prim_params, config, kd);};}@@ -143,6 +245,10 @@ JitConstants ArgMaxMinKernelTopKRadix::GetJitConstants(const arg_max_min_params&auto jit = ArgMaxMinKernelBase::GetJitConstants(params);jit.AddConstant(MakeJitConstant("WG_SIZE", kWgSize));+ jit.AddConstant(MakeJitConstant("SUB_GROUP_SIZE", kSubGroupSize));+ jit.AddConstant(MakeJitConstant("NUM_BUCKETS", kNumBuckets));+ jit.AddConstant(MakeJitConstant("BUCKET_GROUP_SIZE", kBucketGroupSize));+ jit.AddConstant(MakeJitConstant("TIE_GROUP_SIZE", kTieGroupSize));jit.AddConstant(MakeJitConstant("SORTABLE_BITS", params.inputs[0].GetDType() == Datatype::F16 ? 16 : 32));// PADDED_K: next power of 2 >= TOP_K (for bitonic sort)@@ -173,26 +279,44 @@ KernelsData ArgMaxMinKernelTopKRadix::GetKernelsData(const Params& params) const}const auto& orgParams = static_cast<const arg_max_min_params&>(params);- auto dispatchData = SetDefault(orgParams);- KernelData kd = KernelData::Default<arg_max_min_params>(params);+ const ChunkConfig config = GetChunkConfig(orgParams, !orgParams.has_dynamic_tensors());+ const bool chunked = config.chunks > 1;+ const size_t kernels_num = chunked ? 2 : 1;+ const uint32_t internal_buffers_num = chunked ? 3 : 1;++ KernelData kd = KernelData::Default<arg_max_min_params>(params, kernels_num);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;+ const auto base_jit = GetJitConstants(orgParams);+ for (size_t i = 0; i < kernels_num; ++i) {+ auto dispatchData = SetDefault(orgParams);+ auto cldnn_jit = base_jit;+ if (chunked) {+ cldnn_jit.AddConstants({+ MakeJitConstant(i == 0 ? "RADIX_CHUNK_STAGE" : "RADIX_MERGE_STAGE", 1),+ MakeJitConstant("RADIX_CHUNKS", config.chunks),+ MakeJitConstant("RADIX_CHUNK_SIZE", config.chunk_size),+ MakeJitConstant("RADIX_CANDIDATES_NUM", config.chunks * orgParams.topK),+ });+ if (i == 0) {+ dispatchData.gws[0] *= config.chunks;+ }+ }++ auto entry_point = GetEntryPoint(kernelName, orgParams.layerID, params, i);+ auto jit = CreateJit(kernelName, cldnn_jit, entry_point);++ auto& kernel = kd.kernels[i];+ FillCLKernelData(kernel, dispatchData, params.engineInfo, kernelName, jit, entry_point,+ EXE_MODE_DEFAULT, false, false, 1,+ GetFusedPrimitiveInputsCount(params), orgParams.outputs_num,+ orgParams.is_shape_agnostic);+ for (uint32_t buffer = 0; buffer < internal_buffers_num; ++buffer) {+ kernel.params.arguments.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, buffer});+ }+ }++ SetInternalBuffers(orgParams, config, kd);return {kd};}@@ -202,10 +326,10 @@ KernelsPriority ArgMaxMinKernelTopKRadix::GetKernelsPriority(const Params& p) coconst size_t sort_size = GetSortSize(params);// Radix sort excels at large sort sizes with large k (e.g., N=8400+, k=300).- // For k=1 (pure argmax/argmin) or small sort sizes, the axis kernel's- // simple reduction is more efficient — especially when there are many- // independent operations that amplify per-WG overhead.- if (params.topK == 1 || sort_size < 256) {+ // For small sort sizes, and for k=1 (pure argmax/argmin) below 1024 values,+ // the axis kernel's simple reduction is more efficient — especially when there+ // are many independent operations that amplify per-WG overhead.+ if (sort_size < 256 || (params.topK == 1 && sort_size < 1024)) {return FORCE_PRIORITY_5;}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.cppindex 0b85408635e..2ba9b1da2d1 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@@ -10,11 +10,18 @@#include <intel_gpu/primitives/mutable_data.hpp>#include <arg_max_min_inst.h>#include "arg_max_min/arg_max_min_kernel_axis.h"+#include "arg_max_min/arg_max_min_kernel_topk_radix.h"#include "intel_gpu/runtime/internal_properties.hpp"#include "test_utils.h"#include "program_wrapper.h"+#include <cmath>+#include <cstring>+#include <functional>+#include <limits>+#include <numeric>+using namespace cldnn;using namespace ::tests;@@ -1124,7 +1131,7 @@ TEST(arg_max_min_test, check_second_output_data_type) {// =============================================================================// Tests for arg_max_min_topk_radix kernel-// Conditions: f16/f32 input, SORT_VALUES, N >= 2, N <= 65535, SLM fits+// Conditions: f16/f32 input, N >= 2, SLM fits// =============================================================================inline ExecutionConfig get_radix_topk_config(const cldnn::engine& engine, format::type fmt = format::bfyx) {@@ -1142,6 +1149,79 @@ inline void assert_radix_topk_selected(const cldnn::network& net) {<< "Expected arg_max_min_topk_radix, got: " << info;}+TEST(arg_max_gpu_topk_radix, dynamic_f32_dflash_shape_transitions_use_radix) {+ constexpr int32_t batch_num = 1;+ constexpr int32_t vocab_size = 248320;+ constexpr int32_t top_k = 16;+ auto& engine = get_test_engine();++ auto input_layout_dynamic = layout{+ ov::PartialShape{ov::Dimension::dynamic(), ov::Dimension::dynamic(), vocab_size, 1},+ data_types::f32,+ format::bfyx};+ const std::vector<float> sorted_values = {+ 4.4388075f,+ 4.3951770f,+ 4.2429514f,+ 4.2423444f,+ 4.2085915f,+ 4.1768341f,+ 4.0288038f,+ 3.9938712f,+ 3.9857004f,+ 3.9501023f,+ 3.9219890f,+ 3.8840609f,+ 3.8789275f,+ 3.8753984f,+ 3.7988553f,+ 3.7939982f,+ };++ topology topology;+ topology.add(input_layout("input", input_layout_dynamic));+ topology.add(arg_max_min("arg_max",+ {input_info("input")},+ ov::op::TopKMode::MAX,+ top_k,+ 2,+ ov::op::TopKSortType::SORT_VALUES,+ true,+ false,+ data_types::f32,+ 2));++ auto config = get_test_default_config(engine);+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));+ network network(engine, topology, config);+ ASSERT_NO_FATAL_FAILURE(assert_radix_topk_selected(network));++ for (const int32_t feature_num : {1, 7, 15, 7, 1}) {+ auto input_layout_static =+ layout{ov::PartialShape{batch_num, feature_num, vocab_size, 1}, data_types::f32, format::bfyx};+ auto input = engine.allocate_memory(input_layout_static);+ std::vector<float> input_values(batch_num * feature_num * vocab_size, -1.0f);+ for (int32_t feature = 0; feature < feature_num; ++feature) {+ for (int32_t rank = 0; rank < top_k; ++rank) {+ input_values[feature * vocab_size + rank * 7919] = sorted_values[rank] + feature;+ }+ }+ set_values(input, input_values);++ network.set_input_data("input", input);+ auto outputs = network.execute();+ auto output = outputs.at("arg_max").get_memory();+ cldnn::mem_lock<float, mem_lock_type::read> output_ptr(output, get_test_stream());+ for (int32_t feature = 0; feature < feature_num; ++feature) {+ for (int32_t rank = 0; rank < top_k; ++rank) {+ EXPECT_FLOAT_EQ(output_ptr[feature * top_k + rank],+ sorted_values[rank] + feature)+ << "value mismatch at feature_num=" << feature_num << ", feature=" << feature << ", rank=" << rank;+ }+ }+ }+}+namespace {// The radix kernel supports both floating point input types, so every case below runs for both.using topk_radix_data_types = ::testing::Types<ov::float16, float>;@@ -1622,6 +1702,493 @@ TYPED_TEST(arg_max_gpu_topk_radix, byxf_matches_bfyx_reference) {}}+namespace {+// Ordering key of the GPU TopK kernels: -0.0 equals +0.0 and NaN ranks above +inf, as in PyTorch.+uint32_t topk_radix_order_key(float value) {+ if (std::isnan(value)) {+ return 0xFFFFFFFFu;+ }+ uint32_t bits = 0;+ if (value != 0.0f) {+ std::memcpy(&bits, &value, sizeof(bits));+ }+ return (bits >> 31) ? ~bits : (bits | 0x80000000u);+}++// Rows are contiguous in `values`; equal values are ordered by the smallest index. Without+// SORT_VALUES the selected indices are expected in ascending order.+std::vector<int32_t> topk_radix_reference_indices(const std::vector<float>& values,+ size_t rows,+ size_t row_size,+ size_t top_k,+ ov::op::TopKMode mode,+ ov::op::TopKSortType sort) {+ std::vector<int32_t> result;+ result.reserve(rows * top_k);+ std::vector<uint32_t> keys(row_size);+ std::vector<int32_t> order(row_size);+ for (size_t row = 0; row < rows; ++row) {+ for (size_t i = 0; i < row_size; ++i) {+ keys[i] = topk_radix_order_key(values[row * row_size + i]);+ }+ std::iota(order.begin(), order.end(), 0);+ std::stable_sort(order.begin(), order.end(), [&](int32_t a, int32_t b) {+ return mode == ov::op::TopKMode::MAX ? keys[a] > keys[b] : keys[a] < keys[b];+ });+ if (sort != ov::op::TopKSortType::SORT_VALUES) {+ std::sort(order.begin(), order.begin() + top_k);+ }+ result.insert(result.end(), order.begin(), order.begin() + top_k);+ }+ return result;+}++// TopK copies its values from the input, so they must keep their bits, including the sign of zero.+bool topk_radix_same_value(float expected, float actual) {+ if (std::isnan(expected)) {+ return std::isnan(actual);+ }+ return expected == actual && std::signbit(expected) == std::signbit(actual);+}++template <typename T>+std::vector<float> topk_radix_rounded(const std::vector<float>& values) {+ std::vector<float> rounded(values.size());+ for (size_t i = 0; i < values.size(); ++i) {+ rounded[i] = static_cast<float>(static_cast<T>(values[i]));+ }+ return rounded;+}++// Runs TopK on `shapes` one after another, with networks built for `network_shape`, and checks that+// `kernel` ran, that the indices match the reference and that every value is the input element at+// its index. The kernel is forced unless `force_kernel` is false, which checks the default choice.+template <typename T>+void run_topk_radix_case(const ov::PartialShape& network_shape,+ const std::vector<ov::PartialShape>& shapes,+ int64_t axis,+ ov::op::TopKMode mode,+ int32_t top_k,+ const std::function<std::vector<float>(size_t rows, size_t row_size)>& generate,+ ov::op::TopKSortType sort = ov::op::TopKSortType::SORT_VALUES,+ const std::string& kernel = "arg_max_min_topk_radix",+ bool force_kernel = true) {+ auto& engine = get_test_engine();+ const data_types dt = ov::element::from<T>();++ auto config = get_test_default_config(engine);+ if (force_kernel) {+ ov::intel_gpu::ImplementationDesc impl = {format::bfyx, kernel, impl_types::ocl};+ config.set_property(ov::intel_gpu::force_implementations(ov::intel_gpu::ImplForcingMap{{"arg_max", impl}}));+ }+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));++ // A single-output TopK returns either the values or the indices.+ auto make_network = [&](bool values) {+ topology topology;+ topology.add(input_layout("input", layout{network_shape, dt, format::bfyx}));+ topology.add(arg_max_min("arg_max",+ {input_info("input")},+ mode,+ top_k,+ axis,+ sort,+ values,+ false,+ values ? dt : data_types::i32));+ return std::make_shared<cldnn::network>(engine, topology, config);+ };+ auto indices_network = make_network(false);+ auto values_network = make_network(true);++ for (const auto& shape : shapes) {+ const size_t row_size = static_cast<size_t>(shape[static_cast<size_t>(axis)].get_length());+ const size_t rows = ov::shape_size(shape.to_shape()) / row_size;+ const auto values = topk_radix_rounded<T>(generate(rows, row_size));+ const auto expected = topk_radix_reference_indices(values, rows, row_size, top_k, mode, sort);++ auto input = engine.allocate_memory(layout{shape, dt, format::bfyx});+ set_values(input, topk_radix_typed_vec<T>(values));+ indices_network->set_input_data("input", input);+ values_network->set_input_data("input", input);+ auto indices_outputs = indices_network->execute();+ auto values_outputs = values_network->execute();+ for (const auto& net : {indices_network, values_network}) {+ const auto info = net->get_primitive_info("arg_max");+ ASSERT_NE(info.find(kernel), std::string::npos) << "Expected " << kernel << ", got: " << info;+ }++ auto indices = indices_outputs.at("arg_max").get_memory();+ auto out_values = values_outputs.at("arg_max").get_memory();+ ASSERT_EQ(indices->get_layout().count(), expected.size());+ ASSERT_EQ(out_values->get_layout().count(), expected.size());+ cldnn::mem_lock<int32_t, mem_lock_type::read> indices_ptr(indices, get_test_stream());+ cldnn::mem_lock<T, mem_lock_type::read> values_ptr(out_values, get_test_stream());+ for (size_t i = 0; i < expected.size(); ++i) {+ ASSERT_EQ(indices_ptr[i], expected[i])+ << "index mismatch for shape " << shape << " at row=" << i / top_k << ", rank=" << i % top_k;+ const float expected_value = values[(i / top_k) * row_size + static_cast<size_t>(expected[i])];+ ASSERT_TRUE(topk_radix_same_value(expected_value, static_cast<float>(values_ptr[i])))+ << "value mismatch for shape " << shape << " at row=" << i / top_k << ", rank=" << i % top_k+ << ": expected " << expected_value << ", got " << static_cast<float>(values_ptr[i]);+ }+ }+}++// Few distinct levels, so many equal values compete for the last top-K slots.+std::vector<float> topk_radix_tied_values(size_t rows, size_t row_size, int levels, uint32_t seed) {+ std::mt19937 rng(seed);+ std::uniform_int_distribution<int> dist(0, levels - 1);+ std::vector<float> values(rows * row_size);+ for (auto& value : values) {+ value = static_cast<float>(dist(rng)) * 0.25f;+ }+ return values;+}++std::vector<float> topk_radix_random_values(size_t rows, size_t row_size, uint32_t seed) {+ std::mt19937 rng(seed);+ std::normal_distribution<float> dist(0.f, 2.5f);+ std::vector<float> values(rows * row_size);+ for (auto& value : values) {+ value = dist(rng);+ }+ return values;+}++// Every row of at least 64 values holds NaNs of both signs, both infinities and a block of+// alternating -0.0 and +0.0. The other values lie on the losing side of zero, so the top-K+// reaches into the zeros.+std::vector<float> topk_radix_special_values(size_t rows, size_t row_size, ov::op::TopKMode mode) {+ const float nan = std::numeric_limits<float>::quiet_NaN();+ const float inf = std::numeric_limits<float>::infinity();+ const float losing_sign = mode == ov::op::TopKMode::MAX ? -1.f : 1.f;+ const size_t zeros_begin = std::max<size_t>(16, row_size / 8);+ const size_t zeros_end = zeros_begin + std::min<size_t>(40, row_size / 4);+ auto values = topk_radix_random_values(rows, row_size, 17);+ for (size_t row = 0; row < rows; ++row) {+ float* row_values = values.data() + row * row_size;+ for (size_t i = 0; i < row_size; ++i) {+ row_values[i] = losing_sign * (1.f + std::fabs(row_values[i]));+ }+ for (size_t i = zeros_begin; i < zeros_end; ++i) {+ row_values[i] = std::copysign(0.f, i % 2 ? 1.f : -1.f);+ }+ row_values[5] = nan;+ row_values[row_size * 3 / 4] = std::copysign(nan, -1.f);+ row_values[row_size - 1] = nan;+ row_values[7] = inf;+ row_values[9] = -inf;+ }+ return values;+}+} // namespace++// Chunked mode with dynamic rows: the maximum level repeats in every chunk, so the first+// top-K indices come from equal values spread over several chunks.+TYPED_TEST(arg_max_gpu_topk_radix, chunked_dynamic_rows_tied_indices) {+ using T = TypeParam;+ constexpr int32_t vocab_size = 248320;+ run_topk_radix_case<T>(+ ov::PartialShape{ov::Dimension::dynamic(), ov::Dimension::dynamic(), vocab_size, 1},+ {{1, 1, vocab_size, 1}, {1, 7, vocab_size, 1}, {1, 3, vocab_size, 1}},+ 2,+ ov::op::TopKMode::MAX,+ 16,+ [](size_t rows, size_t row_size) {+ return topk_radix_tied_values(rows, row_size, 2000, 7);+ });+}++// Chunked mode with distinct random values, checked against the exact reference order.+TYPED_TEST(arg_max_gpu_topk_radix, chunked_dynamic_rows_random_indices) {+ using T = TypeParam;+ constexpr int32_t vocab_size = 248320;+ run_topk_radix_case<T>(+ ov::PartialShape{ov::Dimension::dynamic(), ov::Dimension::dynamic(), vocab_size, 1},+ {{1, 7, vocab_size, 1}, {1, 15, vocab_size, 1}},+ 2,+ ov::op::TopKMode::MAX,+ 16,+ [](size_t rows, size_t row_size) {+ return topk_radix_random_values(rows, row_size, 11);+ });+}++// Chunked MIN mode on the feature axis, where the last chunk is shorter than the others.+TYPED_TEST(arg_max_gpu_topk_radix, chunked_static_min_tied_indices) {+ using T = TypeParam;+ constexpr int32_t sort_size = 40001;+ run_topk_radix_case<T>(+ ov::PartialShape{2, sort_size, 1, 1},+ {{2, sort_size, 1, 1}},+ 1,+ ov::op::TopKMode::MIN,+ 20,+ [](size_t rows, size_t row_size) {+ return topk_radix_tied_values(rows, row_size, 64, 3);+ });+}++// Single-stage mode where the threshold value overflows the remaining slots in many blocks.+TYPED_TEST(arg_max_gpu_topk_radix, single_stage_ordered_ties) {+ using T = TypeParam;+ constexpr int32_t sort_size = 10000;+ run_topk_radix_case<T>(+ ov::PartialShape{3, sort_size, 1, 1},+ {{3, sort_size, 1, 1}},+ 1,+ ov::op::TopKMode::MAX,+ 64,+ [](size_t rows, size_t row_size) {+ return topk_radix_tied_values(rows, row_size, 8, 5);+ });+}++// NaN ranks above +inf and -0.0 ties with +0.0, in single-stage, chunked and dynamic-rows mode.+TYPED_TEST(arg_max_gpu_topk_radix, nan_and_signed_zero_order) {+ using T = TypeParam;+ constexpr int32_t vocab_size = 248320;+ for (const auto mode : {ov::op::TopKMode::MAX, ov::op::TopKMode::MIN}) {+ SCOPED_TRACE(mode == ov::op::TopKMode::MAX ? "MAX" : "MIN");+ const auto generate = [mode](size_t rows, size_t row_size) {+ return topk_radix_special_values(rows, row_size, mode);+ };+ ASSERT_NO_FATAL_FAILURE(+ run_topk_radix_case<T>(ov::PartialShape{2, 4096, 1, 1}, {{2, 4096, 1, 1}}, 1, mode, 16, generate));+ ASSERT_NO_FATAL_FAILURE(+ run_topk_radix_case<T>(ov::PartialShape{1, 40000, 1, 1}, {{1, 40000, 1, 1}}, 1, mode, 16, generate));+ ASSERT_NO_FATAL_FAILURE(run_topk_radix_case<T>(ov::PartialShape{ov::Dimension::dynamic(), vocab_size, 1, 1},+ {{3, vocab_size, 1, 1}},+ 1,+ mode,+ 16,+ generate));+ }+}++// The axis kernel orders NaN and signed zeros like radix in all of its sorting paths.+TYPED_TEST(arg_max_gpu_topk_radix, axis_kernel_nan_and_signed_zero_order) {+ using T = TypeParam;+ const std::string axis_kernel = "arg_max_min_axis";+ for (const auto mode : {ov::op::TopKMode::MAX, ov::op::TopKMode::MIN}) {+ SCOPED_TRACE(mode == ov::op::TopKMode::MAX ? "MAX" : "MIN");+ const auto generate = [mode](size_t rows, size_t row_size) {+ return topk_radix_special_values(rows, row_size, mode);+ };+ for (const auto sort : {ov::op::TopKSortType::SORT_VALUES, ov::op::TopKSortType::SORT_INDICES}) {+ SCOPED_TRACE(sort == ov::op::TopKSortType::SORT_VALUES ? "SORT_VALUES" : "SORT_INDICES");+ // Rank-based, partial and merge sorting, the k=1 search, and K=N, where MIN also selects the NaNs+ for (const auto& [row_size, top_k] :+ std::vector<std::pair<int32_t, int32_t>>{{4096, 16}, {64, 40}, {4096, 1}, {64, 64}}) {+ ASSERT_NO_FATAL_FAILURE(run_topk_radix_case<T>(ov::PartialShape{2, row_size, 1, 1},+ {{2, row_size, 1, 1}},+ 1,+ mode,+ top_k,+ generate,+ sort,+ axis_kernel));+ }+ }+ // Short MoE router rows keep the axis kernel by default+ ASSERT_NO_FATAL_FAILURE(run_topk_radix_case<T>(ov::PartialShape{ov::Dimension::dynamic(), 128, 1, 1},+ {{64, 128, 1, 1}},+ 1,+ mode,+ 8,+ generate,+ ov::op::TopKSortType::SORT_VALUES,+ axis_kernel,+ false));+ }+}++// Without SORT_VALUES the selected elements come out in index order. SORT_NONE is treated as SORT_INDICES.+TYPED_TEST(arg_max_gpu_topk_radix, sort_by_indices) {+ using T = TypeParam;+ constexpr int32_t vocab_size = 248320;+ for (const auto sort : {ov::op::TopKSortType::SORT_INDICES, ov::op::TopKSortType::NONE}) {+ SCOPED_TRACE(sort == ov::op::TopKSortType::NONE ? "NONE" : "SORT_INDICES");+ ASSERT_NO_FATAL_FAILURE(run_topk_radix_case<T>(+ ov::PartialShape{3, 10000, 1, 1}, {{3, 10000, 1, 1}}, 1, ov::op::TopKMode::MAX, 64,+ [](size_t rows, size_t row_size) { return topk_radix_tied_values(rows, row_size, 8, 5); },+ sort));+ ASSERT_NO_FATAL_FAILURE(run_topk_radix_case<T>(+ ov::PartialShape{2, 40001, 1, 1}, {{2, 40001, 1, 1}}, 1, ov::op::TopKMode::MIN, 20,+ [](size_t rows, size_t row_size) { return topk_radix_tied_values(rows, row_size, 64, 3); },+ sort));+ ASSERT_NO_FATAL_FAILURE(run_topk_radix_case<T>(+ ov::PartialShape{ov::Dimension::dynamic(), ov::Dimension::dynamic(), vocab_size, 1},+ {{1, 1, vocab_size, 1}, {1, 7, vocab_size, 1}},+ 2,+ ov::op::TopKMode::MAX,+ 16,+ [](size_t rows, size_t row_size) { return topk_radix_tied_values(rows, row_size, 2000, 7); },+ sort));+ }+}++// Index-ordered output when 30 values tie at the K-th value ahead of 18 better values in the middle of+// the row: every better value is selected, and only the ties with the smallest indices fill the rest.+TYPED_TEST(arg_max_gpu_topk_radix, sort_by_indices_ties_before_better_values) {+ using T = TypeParam;+ for (const auto mode : {ov::op::TopKMode::MAX, ov::op::TopKMode::MIN}) {+ SCOPED_TRACE(mode == ov::op::TopKMode::MAX ? "MAX" : "MIN");+ const float sign = mode == ov::op::TopKMode::MAX ? 1.f : -1.f;+ const auto generate = [sign](size_t rows, size_t row_size) {+ std::vector<float> values(rows * row_size, -2.f * sign);+ for (size_t row = 0; row < rows; ++row) {+ float* row_values = values.data() + row * row_size;+ std::fill_n(row_values, 30, sign);+ std::fill_n(row_values + row_size / 2, 18, 2.f * sign);+ }+ return values;+ };+ for (const auto sort : {ov::op::TopKSortType::SORT_INDICES, ov::op::TopKSortType::NONE}) {+ SCOPED_TRACE(sort == ov::op::TopKSortType::NONE ? "NONE" : "SORT_INDICES");+ ASSERT_NO_FATAL_FAILURE(+ run_topk_radix_case<T>(ov::PartialShape{2, 1000, 1, 1}, {{2, 1000, 1, 1}}, 1, mode, 20, generate, sort));+ ASSERT_NO_FATAL_FAILURE(+ run_topk_radix_case<T>(ov::PartialShape{1, 40000, 1, 1}, {{1, 40000, 1, 1}}, 1, mode, 20, generate, sort));+ ASSERT_NO_FATAL_FAILURE(run_topk_radix_case<T>(+ ov::PartialShape{ov::Dimension::dynamic(), 40000, 1, 1}, {{3, 40000, 1, 1}}, 1, mode, 20, generate, sort));+ }+ }+}++// Index-ordered output when 30 ties at indices 0..29 come before 18 better zeros at 500..517, K=20. The+// 20000-value row is chunked on every device, with the ties and the zeros in its first chunk; the+// 1000-value row runs in a single stage.+TYPED_TEST(arg_max_gpu_topk_radix, sort_by_indices_ties_before_better_zeros) {+ using T = TypeParam;+ for (const auto mode : {ov::op::TopKMode::MAX, ov::op::TopKMode::MIN}) {+ SCOPED_TRACE(mode == ov::op::TopKMode::MAX ? "MAX" : "MIN");+ const auto generate = [mode](size_t rows, size_t row_size) {+ const float sign = mode == ov::op::TopKMode::MAX ? -1.0f : 1.0f;+ std::vector<float> values(rows * row_size, sign);+ for (size_t row = 0; row < rows; ++row) {+ std::fill_n(values.begin() + row * row_size, 30, 0.25f * sign);+ std::fill_n(values.begin() + row * row_size + 500, 18, 0.0f);+ }+ return values;+ };+ for (const auto sort : {ov::op::TopKSortType::SORT_INDICES, ov::op::TopKSortType::NONE}) {+ SCOPED_TRACE(sort == ov::op::TopKSortType::NONE ? "NONE" : "SORT_INDICES");+ for (const int32_t row_size : {1000, 20000}) {+ ASSERT_NO_FATAL_FAILURE(run_topk_radix_case<T>(ov::PartialShape{2, row_size, 1, 1},+ {{2, row_size, 1, 1}},+ 1,+ mode,+ 20,+ generate,+ sort));+ }+ }+ }+}++// Rows of 1024 values or more use radix for k=1 by default, with equal maxima resolved to the smallest index.+TYPED_TEST(arg_max_gpu_topk_radix, topk1_selects_radix_from_1024_values) {+ using T = TypeParam;+ constexpr int32_t vocab_size = 248320;+ const std::string radix_kernel = "arg_max_min_topk_radix";+ ASSERT_NO_FATAL_FAILURE(run_topk_radix_case<T>(+ ov::PartialShape{3, 32000, 1, 1}, {{3, 32000, 1, 1}}, 1, ov::op::TopKMode::MAX, 1,+ [](size_t rows, size_t row_size) { return topk_radix_tied_values(rows, row_size, 3, 9); },+ ov::op::TopKSortType::SORT_VALUES, radix_kernel, false));+ ASSERT_NO_FATAL_FAILURE(run_topk_radix_case<T>(+ ov::PartialShape{ov::Dimension::dynamic(), ov::Dimension::dynamic(), vocab_size, 1},+ {{1, 1, vocab_size, 1}, {1, 4, vocab_size, 1}},+ 2,+ ov::op::TopKMode::MIN,+ 1,+ [](size_t rows, size_t row_size) { return topk_radix_random_values(rows, row_size, 13); },+ ov::op::TopKSortType::SORT_VALUES, radix_kernel, false));+ ASSERT_NO_FATAL_FAILURE(run_topk_radix_case<T>(+ ov::PartialShape{4, 1024, 1, 1}, {{4, 1024, 1, 1}}, 1, ov::op::TopKMode::MAX, 1,+ [](size_t rows, size_t row_size) { return topk_radix_random_values(rows, row_size, 15); },+ ov::op::TopKSortType::SORT_VALUES, radix_kernel, false));+ ASSERT_NO_FATAL_FAILURE(run_topk_radix_case<T>(+ ov::PartialShape{4, 1023, 1, 1}, {{4, 1023, 1, 1}}, 1, ov::op::TopKMode::MAX, 1,+ [](size_t rows, size_t row_size) { return topk_radix_random_values(rows, row_size, 15); },+ ov::op::TopKSortType::SORT_VALUES, "arg_max_min_axis", false));+}++// Static shapes whose chunk count depends on the device and the row count, plus large K where+// the merge stage needs long chunks.+TYPED_TEST(arg_max_gpu_topk_radix, static_chunk_configs) {+ using T = TypeParam;+ const auto random = [](size_t rows, size_t row_size) { return topk_radix_random_values(rows, row_size, 21); };+ const auto tied = [](size_t rows, size_t row_size) { return topk_radix_tied_values(rows, row_size, 40, 23); };+ ASSERT_NO_FATAL_FAILURE(+ run_topk_radix_case<T>(ov::PartialShape{1, 8192, 1, 1}, {{1, 8192, 1, 1}}, 1, ov::op::TopKMode::MAX, 16, random));+ ASSERT_NO_FATAL_FAILURE(+ run_topk_radix_case<T>(ov::PartialShape{1, 16383, 1, 1}, {{1, 16383, 1, 1}}, 1, ov::op::TopKMode::MAX, 16, tied));+ ASSERT_NO_FATAL_FAILURE(+ run_topk_radix_case<T>(ov::PartialShape{2, 5000, 1, 1}, {{2, 5000, 1, 1}}, 1, ov::op::TopKMode::MIN, 32, tied));+ ASSERT_NO_FATAL_FAILURE(+ run_topk_radix_case<T>(ov::PartialShape{2, 81900, 1, 1}, {{2, 81900, 1, 1}}, 1, ov::op::TopKMode::MAX, 300, tied));+ ASSERT_NO_FATAL_FAILURE(+ run_topk_radix_case<T>(ov::PartialShape{1, 262144, 1, 1}, {{1, 262144, 1, 1}}, 1, ov::op::TopKMode::MAX, 2048, random));+ ASSERT_NO_FATAL_FAILURE(run_topk_radix_case<T>(ov::PartialShape{ov::Dimension::dynamic(), 81900, 1, 1},+ {{2, 81900, 1, 1}, {5, 81900, 1, 1}},+ 1,+ ov::op::TopKMode::MAX,+ 300,+ tied));+}++// The chunk count follows the device size and a static row count, and large K limits it.+TEST(arg_max_gpu_topk_radix, chunk_config_follows_device_rows_and_k) {+ struct chunk_case {+ size_t rows;+ size_t sort_size;+ size_t top_k;+ uint32_t threads;+ size_t chunks;+ };+ // 960 threads keep 60 work-groups of 256 SIMD16 work-items resident, as on a 96-EU Xe3 iGPU+ const std::vector<chunk_case> cases = {+ {1, 8192, 16, 960, 8}, // a single row is split to fill the device, down to 1024 values per chunk+ {1, 8192, 16, 0, 1}, // unknown device size: below the default chunking threshold+ {64, 8192, 16, 960, 1}, // the rows alone fill the device+ {1, 4000, 16, 960, 1}, // too short to split+ {1, 8192, 1024, 960, 1}, // chunks could not hold 8 * K values+ {1, 262144, 2048, 960, 8}, // the merge input of chunks * K candidates stays within half a chunk+ {1, 248320, 16, 0, 31}, // default chunks of about 8192 values+ };+ for (const auto& c : cases) {+ SCOPED_TRACE(std::to_string(c.rows) + "x" + std::to_string(c.sort_size) + " k=" + std::to_string(c.top_k) ++ " threads=" + std::to_string(c.threads));+ kernel_selector::arg_max_min_params params;+ params.inputs[0] = kernel_selector::DataTensor(std::vector<size_t>{c.sort_size, c.rows, 1, 1},+ kernel_selector::Datatype::F32,+ kernel_selector::DataLayout::bfyx);+ params.outputs[0] = kernel_selector::DataTensor(std::vector<size_t>{c.top_k, c.rows, 1, 1},+ kernel_selector::Datatype::F32,+ kernel_selector::DataLayout::bfyx);+ params.argMaxMinAxis = kernel_selector::ArgMaxMinAxis::X;+ params.argMaxMinOut = kernel_selector::ArgMaxMinOut::MAX;+ params.argMaxMinSortType = kernel_selector::ArgMaxMinSortType::VALUE;+ params.topK = static_cast<uint32_t>(c.top_k);+ params.outputs_num = 1;+ params.engineInfo.maxWorkGroupSize = 256;+ params.engineInfo.maxLocalMemSize = 65536;+ params.engineInfo.maxThreadsPerDevice = c.threads;++ kernel_selector::ArgMaxMinKernelTopKRadix kernel;+ auto kernels_data = kernel.GetKernelsData(params);+ ASSERT_EQ(kernels_data.size(), size_t(1));+ const auto& kd = kernels_data[0];+ ASSERT_EQ(kd.kernels.size(), c.chunks > 1 ? size_t(2) : size_t(1));+ if (c.chunks > 1) {+ ASSERT_EQ(kd.internalBuffers.size(), size_t(3));+ ASSERT_EQ(kd.internalBuffers[1].byte_count, sizeof(uint32_t) * c.chunks * c.top_k * c.rows);+ }+ }+}+// Verify that arg_max_min_axis is selected over radix for small sort_size and k=1TEST(arg_max_gpu_topk_radix, fallback_to_axis_for_small_sort_size_and_topk1) {auto& engine = get_test_engine();