[CUDA Backend] Optimize TopKV2 OP for CUDA backend - #4227
Conversation
…zed load to speed up TopK OP
wangzhaode
left a comment
There was a problem hiding this comment.
Code Review
1. Duplicated sift-down logic (Maintainability)
The sift-down heap logic is copy-pasted three times: in the unrolled loop, in the remainder loop, and in the heap-sort phase. This is a significant amount of duplicated device code. Consider extracting a __device__ inline helper function like SiftDown(valuesThread, indicesThread, parent, heapSize, descendFlag) to reduce duplication and maintenance burden.
2. Unrolled loop may not achieve vectorized loads as claimed (Comments accuracy)
The comments suggest the unrolling helps the compiler generate vectorized loads (LD.E.128). However, the access pattern uses a stride of gridDim.x * blockDim.x between consecutive elements in data[0..3], so these are not contiguous memory accesses. Vectorized loads like float4 require contiguous addresses. The unrolling still helps with instruction-level parallelism (ILP) and latency hiding, but the comments about vectorized loads are misleading. Consider correcting the comments to mention ILP benefits instead.
Reviewed by claude-opus-4-6
…rt and loop unrolling (alibaba#4227)
…rt and loop unrolling (alibaba#4227)
Motivation
I am benchmarking RT-DETRv4 and YOLO26 models using MNN and find that they are much slower than other models like YOLO11,
timeProfiletells that TopKV2 for CUDA is much slower than CPU, which is strange, so I checkedsource/backend/cuda/execution/TopKV2Execution.cuusing LLM and found insertion sort is used inTopKInThread, which is expensive as it's time complexity is O(K), especially for large K like 300 used in RT-DETRv4 and YOLO26.What's changed
Replace the insertion sort with heap sort to reduce the time complexity to O(log K), and use vectorized load if possible to speed up the TopKV2 OP on CUDA backend.
Comparision
run_test.out op/TopKV2Before
After
Note that the time cost print by
printTimeCost:0 s 19 ms0 s 3 msWhich is a huge improvement.
RT-DETRv4 benchmark
Before
After
For TopKV2 OP, it speeds up
26.968828/2.920069=9.23X faster.