ai.onnx.TopK
ai.onnx · standard ONNX operator · ONNX opset ≥ 11
Description
Retrieves the top-k largest or smallest elements along the selected axis, returning values and stable lower-index tie-breaking indices.
See the ONNX TopK spec for the reference semantics.
Differences from the ONNX spec
- Input
K: Passed as thekruntime argument instead of a tensor input. - Attribute
sorted: ONNX requires sorted output when this attribute is 1 and permits any order when it is 0. This package returns sorted values for both settings.
Inputs
| Name | Upstream name | Logical dtype | Rank | Shape | Description | Presence |
|---|---|---|---|---|---|---|
x |
X |
T |
— | — | Values from which the top k entries are selected along axis. |
required |
Outputs
| Name | Upstream name | Logical dtype | WebGPU storage | Rank | Shape | Description | Presence |
|---|---|---|---|---|---|---|---|
values |
Values |
T |
runtime-selected; narrow integers and bool use 32-bit slots | same as x |
derived | Selected values; the reduced axis has length k. |
required |
indices |
Indices |
I |
uint32 |
same as x |
derived | Logical int64 indices of the selected values along the reduced axis; WebGPU stores these bounded indices as uint32. | required |
Runtime arguments
| Name | Kind | Description | Presence |
|---|---|---|---|
k |
u32 |
Number of values to select along axis: ONNX's one-element K input, passed as a scalar. |
required |
Attributes
Default values (overridable per request):
| Attribute | Default | Description |
|---|---|---|
axis |
-1 |
Axis to reduce; negative values count from the back. |
largest |
1 |
Select largest values when 1, smallest values when 0. |
sorted |
1 |
Sort selected values when 1. A sorted result is also valid when output order is unspecified (sorted=0). |
Type constraints
| Variable | Allowed dtypes |
|---|---|
T |
float32, float16, int8, int16, int32, uint8, uint32 |
I |
int64 |
Implementation variants
One implementation is selected per call from the device capabilities, the request shapes and the dtypes; these notes say what each one covers.
last_axis_atomic_top1— Selects one exact integer winner from long contiguous rows with subgroup packed score/index atomics, then gathers its original input value. The packed key keeps stable lower-index ties and one eight-byte winner per row. Floating inputs take the variants that order NaN values, and runtimes without both optional features select portable variants.axis_smallk_tournament— Scans a strided non-last axis with one workgroup per output position and retains only a short candidate list instead of sorting the whole axis. It is selected when many independent outputs amortize the strided scan, and it is the variant used when the axis does not fit in workgroup memory.last_axis_large_top1— Finds one winner on rows too wide for the single-workgroup shared-memory variant by reducing blocks to candidates in a temporary buffer. A second pass selects the final candidate.rank_count_int— Integer selection for an axis too long for a merge workgroup, as a full sort of more than 2048 values is: each element counts the elements ordered before it, a better value or an equal one at a lower index, streaming the axis through workgroup memory, and an element of rank belowkwrites itself to that output slot. Ties keep the lower index first.axis_bitonic— Shared bitonic selection for arbitrary axes; floating inputs encode order keys once and gather original values after sorting, preserving stable ties and value bits.subgroup_rows_smallk— Packs rows into 32-lane XOR reductions when the actual subgroup count proves full populations. Partial partitions use a synchronized shared bitonic fallback; selected NaN prefixes retain lower global indices.subgroup_min_rows_smallk— A ballot confirms that lanes 0..15 are all active before an XOR reduction is used. Other subgroup partitions use a synchronized shared bitonic fallback; its workgroup storage is bounded by the padded row width.portable_rows_smallk— Each workgroup merges strided local candidate lists in shared memory, retaining only K winners. A selected NaN prefix preserves original lower global indices.small_rows_batched— Each invocation selects a small number of winners from one short row, batching independent rows within each workgroup.large_one_merge,large_two_merge,last_axis_large_three_merge— Staged stable TopK with bounded candidate buffers. Floating inputs encode order keys on load and gather selected source values after the final merge; integer inputs retain exact integer keys.subgroup_verified_rows_smallk32— One workgroup owns one row. Ballot participation proves when subgroup key/index reduction covers the row; split groups and NaNs use a global-index bitonic fallback.pinned_moderate_rows— Gives each moderate-width row (a multiple of the subgroup size, fixed withsubgroup-size-control) to one subgroup, found by itssubgroup_id, and reduces integer-encoded keys; results, including NaN handling, match a serial per-row scan.last_axis_large_two_merge_pairwise— Merges sorted candidate runs by bounded binary partition, after checking on the GPU that each run is sorted; runs that contain NaN or are not sorted use the stable bitonic merge instead.
Device requirements
Some implementation variants require atomic-vec2u-min-max, subgroup-size-control, and subgroups. Other variants run without them; which variant runs also depends on the request's shapes and dtypes.
Files
metadata.json— kernel metadata (id, file digests, manifest spec, provenance)manifest.json— the op contract (source of truth)test.json— correctness casesbench.json— benchmark casesreduce-arg-atomic-gather.wgsl.jinjareduce-arg-atomic-row.wgsl.jinjatopk-axis.wgsl.jinjatopk-large-block-pairwise.wgsl.jinjatopk-large-block.wgsl.jinjatopk-noop.wgsl.jinjatopk-pinned-reduce.wgsl.jinjatopk-portable-rows-smallk.wgsl.jinjatopk-rank-count.wgsl.jinjatopk-small-rows-batched.wgsl.jinjatopk-strided-smallk.wgsl.jinjatopk-subgroup-dense-shared-row.wgsl.jinjatopk-subgroup-rows.wgsl.jinjatopk-subgroup-verified-row.wgsl.jinjatopk-top1-last-axis.wgsl.jinja
Use with @huggingface/kernels
npm install --save-exact @huggingface/kernels@0.0.1-preview.4
Paste the example into a browser app that resolves npm imports. Serve the app over HTTPS or localhost with WebGPU available.
Required output shapes and logical data types are inferred from the supplied inputs and attributes; result tensors are allocated automatically.
The version: 1 option selects the published kernel contract; it is independent of any operator opset, contrib since_version, or model version.
It follows the v1 branch as fixes land. To pin exact artifact bytes, pass a 40-character commit revision instead of version.
import { getKernel } from "@huggingface/kernels";
const kernel = await getKernel("webgpu-kernels/ai.onnx.TopK", { version: 1 });
const xData = Float32Array.of(-1e-40, 0, 1e-40);
const { values, indices } = await kernel({ x: { data: xData, shape: [1, 3] }, k: 1 });
console.log({ values, indices });
- Downloads last month
- -
Requires WebGPU support. See the compatibility table.