Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
47 commits
Select commit Hold shift + click to select a range
8b35602
Add SuperKMeans k-means API with an unpruned fallback
sherylll Oct 26, 2026
e83a28f
Add SuperKMeans' fused first-filter cuTile kernel
sherylll Oct 26, 2026
19b3fb4
Add SuperKMeans' pruned assignment
sherylll Oct 26, 2026
443bb05
Order SuperKMeans' pruning by survivor count (LPT)
sherylll Oct 26, 2026
669fcc1
Run SuperKMeans' row batches on the handle's stream pool
sherylll Oct 26, 2026
844f2f0
Move SuperKMeans' pruned assignment into a pruned 1-NN distance
sherylll Oct 26, 2026
4bf9ccc
Prune survivor lists in place, out of shared memory
sherylll Oct 28, 2026
18779b1
Write one contiguous first-filter survivor list per row
sherylll Oct 28, 2026
e58ee5c
Prune only with dims past the first filter's; simplify the kernel
sherylll Oct 28, 2026
1edbba5
Return early from pruning rows with no survivors
sherylll Oct 28, 2026
75ea3ab
Overlap row batches on the main stream and one pool stream
sherylll Oct 28, 2026
fca97b1
Fix style: SuperKMeans API reference, formatting, copyright
sherylll Oct 28, 2026
2d869df
Compute the filter's norms from its FP16 values, with the FP16 copy
sherylll Oct 30, 2026
6a2ae57
Compute the pruning ratios from eps0 in the kernel, not from a device…
sherylll Nov 2, 2026
a57a157
Assign in full for half rows the filter can't read in place; document…
sherylll Nov 2, 2026
e7cb068
Load the pruning kernel's tiles in 16-byte loads; drop its launch bounds
sherylll Nov 2, 2026
0ee37a6
Add license
sherylll Nov 3, 2026
e02f9db
Replace custom warp reduce with cub::WarpReduceBatched
sherylll Nov 3, 2026
31b9674
Merge branch 'main' into superkmeans
sherylll Nov 4, 2026
6b3a662
Hardcode eps0
sherylll Nov 5, 2026
f2355d4
Halve pruned 1-NN centroid batch to 1024
sherylll Nov 6, 2026
9565eb9
Merge branch 'main' into superkmeans
sherylll Nov 6, 2026
4760f3b
Merge branch 'main' into superkmeans
sherylll Nov 8, 2026
79bdbba
Prepare SuperKMeans filter rows per batch
sherylll Nov 9, 2026
b3e9476
Require supported layouts for high-dimensional SuperKMeans pruning
sherylll Nov 9, 2026
a71429f
Size SuperKMeans row batches from workspace budget
sherylll Nov 9, 2026
3b2571b
Tune tile sizes for different arch (coarsely)
sherylll Nov 9, 2026
4c2585a
Fix style
sherylll Nov 9, 2026
26372e2
Add sm103 for completeness; update tile sizes based on measurements on
sherylll Nov 10, 2026
0bbf70c
Merge upstream/main into superkmeans
sherylll Nov 11, 2026
78d844a
Remove duplicate kmeans_type definition
sherylll Nov 11, 2026
5a45435
Small refactor
sherylll Nov 11, 2026
976b372
More refactoring: in F32 mode, use F32 data to calculate norm, even t…
sherylll Nov 11, 2026
f92bdc4
Use raft launch_kernel
sherylll Nov 12, 2026
6f9fb0a
Peel single-survivor tail from pruned nearest-neighbor search
sherylll Nov 13, 2026
91ee26a
Order pruning rows from each fused-filter tile
sherylll Nov 13, 2026
7054a3f
Small cleanup
sherylll Nov 16, 2026
3e2964b
Merge branch 'release/26.12' into superkmeans
sherylll Nov 16, 2026
e3a2550
Mark SuperKMeans API experimental
sherylll Nov 18, 2026
0a70f8c
Use RAFT warp primitives in pruned assignment
sherylll Nov 18, 2026
572253e
Support partial dimension tiles in pruned assignment
sherylll Nov 18, 2026
d2713a5
Remove redundant initial survivor check in prune
sherylll Nov 18, 2026
7fa7a8b
Merge branch 'release/26.12' into superkmeans
sherylll Nov 18, 2026
8cb98b7
Simplify prune survivor arguments and use RAFT warp helpers
sherylll Nov 18, 2026
29970b1
Use workspace memory and dry-run sizing in SuperKMeans
sherylll Nov 19, 2026
82ac907
Add NVTX ranges for pruned 1-NN filter and pruning
sherylll Nov 19, 2026
20e5fbb
Use dry-run execution and round up SuperKMeans batches
sherylll Nov 19, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Add SuperKMeans' fused first-filter cuTile kernel
The partial GEMM over the first d' dims fused with the first pruning
filter, from SuperKMeans' GPU k-means: per (row, centroid tile) it
keeps the centroids whose partial distance is under the row's bound
and packs them into fixed segments. FP16 only, as in SuperKMeans,
where float data is filtered on half copies. Exported next to the
fused 1-NN kernels, with a planner and launcher; not used yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • Loading branch information
sherylll and claude committed Nov 2, 2026
commit e83a28f02c0928daae4379fe803527129af90883
23 changes: 23 additions & 0 deletions cpp/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1234,6 +1234,26 @@ if(NOT BUILD_CPU_ONLY)
"${cutile_fused_1nn_tiles}" @ONLY
)
list(APPEND cutile_fused_1nn_files "${cutile_fused_1nn_tiles}")

set(superkmeans_cutile_dir "${CMAKE_CURRENT_SOURCE_DIR}/src/cluster/detail/superkmeans/cutile")
set(cutile_superkmeans_generated_dir
"${CMAKE_CURRENT_BINARY_DIR}/generated_kernels/cluster/superkmeans/cutile"
)
generate_cutile_kernels(
cutile_superkmeans_files
KERNEL_DIR "${superkmeans_cutile_dir}"
KERNEL_BASENAME "superkmeans_fused_filter"
KERNEL_PYTHON "fused_filter_kernel.py"
EXPORT_SCRIPT "export_fused_filter.py"
OUTPUT_DIRECTORY "${cutile_superkmeans_generated_dir}"
MATRIX_JSON_FILE "${superkmeans_cutile_dir}/fused_filter_cutile_matrix.json"
PYTHON "${cutile_python}" BIN2C "${cutile_bin2c}"
FRAGMENT_TAG_FORMAT_CUBIN
"cuvs::cluster::kmeans::detail::superkmeans::fragment_tag_fused_filter_cubin<cuvs::neighbors::detail::tag_@data_abbrev@, cuvs::detail::jit_lto::@arch_tag@>"
FRAGMENT_TAG_HEADER_FILES
"<cuvs/detail/jit_lto/superkmeans/fused_filter_fragments.hpp>"
"<cuvs/detail/jit_lto/cutile_arch_tags.hpp>" "<cuvs/detail/jit_lto/common_fragments.hpp>"
)
endif()
# Note that this matrix contains an `arch_includes` placeholder, since we don't currently have a
# way to do an item-wise transform on a list after computing the matrix product and before
Expand Down Expand Up @@ -1572,6 +1592,8 @@ if(NOT BUILD_CPU_ONLY)
cuvs_objs
PRIVATE ${cutile_fused_1nn_files}
src/distance/detail/fused_distance_nn/cutile/fused_1nn_tile.cu ${cutile_smoke_files}
${cutile_superkmeans_files}
src/cluster/detail/superkmeans/cutile/fused_filter_tile.cu
)
endif()

Expand Down Expand Up @@ -1621,6 +1643,7 @@ if(NOT BUILD_CPU_ONLY)
INTERFACE "$<INSTALL_INTERFACE:include>"
PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src" "${CMAKE_CURRENT_BINARY_DIR}/src"
"${cutile_fused_1nn_generated_dir}" "${cutile_smoke_generated_dir}"
"${cutile_superkmeans_generated_dir}"
)

# Endian detection
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/*
* SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/

#pragma once

namespace cuvs::cluster::kmeans::detail::superkmeans {

template <typename DataTag, typename ArchTag>
struct fragment_tag_fused_filter_cubin {
static constexpr int cc_major = ArchTag::cc_major;
static constexpr int cc_minor = ArchTag::cc_minor;
};

} // namespace cuvs::cluster::kmeans::detail::superkmeans
125 changes: 125 additions & 0 deletions cpp/src/cluster/detail/superkmeans/cutile/export_fused_filter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
# =============================================================================
# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
# =============================================================================
"""Export SuperKMeans' fused first-filter cuTile kernel to cubin."""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

import cuda.tile as ct
from cuda.tile.compilation import (
ArrayConstraint,
CallingConvention,
ConstantConstraint,
KernelSignature,
ScalarConstraint,
export_kernel,
)

# CI enables Python safe-path mode, so the script directory is not guaranteed
# to be importable even when this file is executed directly.
SCRIPT_DIR = Path(__file__).resolve().parent
if str(SCRIPT_DIR) not in sys.path:
sys.path.insert(0, str(SCRIPT_DIR))

from fused_filter_kernel import kernel_symbol, make_kernel # noqa: E402


def _matrix():
"""float16, row-major, unit last stride, 16-byte aligned base and row pitch."""
return ArrayConstraint(
ct.float16,
ndim=2,
index_dtype=ct.int32,
stride_lower_bound_incl=(0, None),
alias_groups=("read_only_inputs",),
may_alias_internally=False,
stride_constant=(None, 1),
stride_divisible_by=(8, 1),
base_addr_divisible_by=16,
)


def _vector(elem_dtype, alias_groups=()):
return ArrayConstraint(
elem_dtype,
ndim=1,
index_dtype=ct.int32,
stride_lower_bound_incl=(None,),
alias_groups=alias_groups,
may_alias_internally=False,
stride_constant=(1,),
base_addr_divisible_by=16,
)


def _segments():
return ArrayConstraint(
ct.int32,
ndim=2,
index_dtype=ct.int32,
stride_lower_bound_incl=(0, None),
alias_groups=(),
may_alias_internally=False,
stride_constant=(None, 1),
base_addr_divisible_by=16,
)


def _signature(data_type: str, tile_m: int, tile_n: int, tile_k: int):
# Argument order of the C++ launch: each array as (pointer, shape..., stride...), then the
# scalars; the tile sizes are compiled in.
read_only = ("read_only_inputs",)
return KernelSignature(
parameters=[
_matrix(), # rows (n_rows, d)
_matrix(), # centroids (n_centroids, d)
_vector(ct.float32, read_only), # row_norms: ||row||^2 over d'
_vector(ct.float32, read_only), # centroid_norms: ||centroid||^2 over d'
_vector(ct.float32, read_only), # best: each row's current distance
_vector(ct.int64), # packed survivors
_segments(), # seg_count (n_rows, n_col_tiles)
ScalarConstraint(ct.int32), # n_rows
ScalarConstraint(ct.int32), # n_centroids
ScalarConstraint(ct.float32), # ratio
ScalarConstraint(ct.int32), # d'
ConstantConstraint(tile_m),
ConstantConstraint(tile_n),
ConstantConstraint(tile_k),
],
calling_convention=CallingConvention.cutile_python_v1(),
).with_symbol(kernel_symbol(data_type))


def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("output_file", type=Path)
parser.add_argument("--format", choices=("cubin",), default="cubin")
parser.add_argument("--data-type", choices=("half",), required=True)
parser.add_argument("--metric", choices=("l2",), required=True)
parser.add_argument("--index-type", choices=("int32",), required=True)
parser.add_argument("--tile-m", type=int, required=True)
parser.add_argument("--tile-n", type=int, required=True)
parser.add_argument("--tile-k", type=int, required=True)
parser.add_argument("--gpu-code", required=True)
parser.add_argument("--occupancy", type=int)
args = parser.parse_args()

export_kernel(
kernel=make_kernel(gpu_code=args.gpu_code, occupancy=args.occupancy),
signatures=[
_signature(args.data_type, args.tile_m, args.tile_n, args.tile_k)
],
output_file=str(args.output_file),
gpu_code=args.gpu_code,
output_format=args.format,
)
return 0


if __name__ == "__main__":
raise SystemExit(main())
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[
{
"_data": [
{"data_type": "half", "data_abbrev": "h"}
],
"_metric": [{"metric": "l2", "metric_abbrev": "l2"}],
"_index": [{"index_type": "int32", "index_abbrev": "i32"}],
"_tile": [{"tile_m": 128, "tile_n": 128, "tile_k": 64, "occupancy": 2}],
"_export": [
{"output_format": "cubin", "register": "cubin", "gpu_code": "sm_80", "arch_tag": "cutile_arch_8_0", "artifact_basename": "@data_type@_@gpu_code@", "artifact_ext": "cubin"},
{"output_format": "cubin", "register": "cubin", "gpu_code": "sm_86", "arch_tag": "cutile_arch_8_6", "artifact_basename": "@data_type@_@gpu_code@", "artifact_ext": "cubin"},
{"output_format": "cubin", "register": "cubin", "gpu_code": "sm_90", "arch_tag": "cutile_arch_9_0", "artifact_basename": "@data_type@_@gpu_code@", "artifact_ext": "cubin"},
{"output_format": "cubin", "register": "cubin", "gpu_code": "sm_100", "arch_tag": "cutile_arch_10_0", "artifact_basename": "@data_type@_@gpu_code@", "artifact_ext": "cubin"},
{"output_format": "cubin", "register": "cubin", "gpu_code": "sm_107", "arch_tag": "cutile_arch_10_7", "artifact_basename": "@data_type@_@gpu_code@", "artifact_ext": "cubin"},
{"output_format": "cubin", "register": "cubin", "gpu_code": "sm_120", "arch_tag": "cutile_arch_12_0", "artifact_basename": "@data_type@_@gpu_code@", "artifact_ext": "cubin"}
]
}
]
111 changes: 111 additions & 0 deletions cpp/src/cluster/detail/superkmeans/cutile/fused_filter_kernel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
# =============================================================================
# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
# =============================================================================
"""SuperKMeans' first pruning filter: the partial GEMM over the first d' dims fused with the filter.

Each CTA owns TM rows and loops over the centroid tiles (TN wide). For each it computes the partial
distance ||row||^2 + ||centroid||^2 - 2 row.centroid over the first d' dims (FP16 tensor cores) and
keeps the pairs under the row's threshold best[row] * ratio, where best is the row's
distance to its current centroid.

Output, for n_rows rows against n_centroids centroids (n_col_tiles = ceil(n_centroids / TN)):

packed int64, one segment of TN slots per (row, centroid tile), at (row * n_col_tiles + tile) * TN:
slots 0 .. count-1 that tile's survivors for that row, in centroid order
slots count .. TN-1 not written
a survivor: (centroid index) << 32 | (the partial distance's float32 bits)
seg_count int32 (n_rows, n_col_tiles): count, how many slots of each segment are filled

A segment holds a whole tile, so it cannot overflow, and a survivor's slot is just its rank among
the row's survivors in that tile: no prefix sum across rows.

d' is a runtime argument and must be a multiple of TK.
"""

import cuda.tile as ct

ConstInt = ct.Constant[int]

# A survivor packed in one int64: the centroid index in the high 32 bits, the partial distance's
# float32 bits in the low 32. One scatter per survivor is the costly part of the kernel; separate
# 32-bit scatters per field are much slower.
ID_SHIFT = 32
LOW_32_BITS = (1 << 32) - 1


def kernel_symbol(data_type: str) -> str:
return {"half": "superkmeans_fused_filter_h"}[data_type]


def make_kernel(*, gpu_code: str, occupancy: int | None = None):
kernel_options = {}
if occupancy is not None:
kernel_options["occupancy"] = ct.ByTarget(**{gpu_code: occupancy})

@ct.kernel(**kernel_options)
def fused_filter(
rows,
centroids,
row_norms,
centroid_norms,
best,
packed,
seg_count,
n_rows,
n_centroids,
ratio,
dp,
tm: ConstInt,
tn: ConstInt,
tk: ConstInt,
):
row_tile = ct.bid(0)
zero_pad = ct.PaddingMode.ZERO
n_col_tiles = ct.num_tiles(centroids, axis=0, shape=(tn, tk))
row_ids = row_tile * tm + ct.arange(tm, dtype=ct.int32)[:, None]
row_norm = ct.load(
row_norms, index=(row_tile,), shape=(tm,), padding_mode=zero_pad
)[:, None]
threshold = (
ct.load(best, index=(row_tile,), shape=(tm,), padding_mode=zero_pad)[
:, None
]
* ratio
)
for centroid_tile in range(n_col_tiles):
acc = ct.full((tm, tn), 0, dtype=ct.float32)
for kk in range(dp // tk):
a = ct.load(
rows, index=(row_tile, kk), shape=(tm, tk), padding_mode=zero_pad
)
b = ct.load(
centroids,
index=(kk, centroid_tile),
shape=(tk, tn),
padding_mode=zero_pad,
order=(1, 0),
)
acc = ct.mma(a, b, acc)
centroid_norm = ct.load(
centroid_norms,
index=(centroid_tile,),
shape=(tn,),
padding_mode=zero_pad,
)[None, :]
dist = -2.0 * acc + row_norm + centroid_norm
centroid_ids = centroid_tile * tn + ct.arange(tn, dtype=ct.int32)[None, :]
keep = (dist < threshold) & (centroid_ids < n_centroids) & (row_ids < n_rows)
# Slot: the start of the (row, tile) segment plus the survivor's rank in the row
keep_i = keep.astype(ct.int32)
per_row = ct.sum(keep_i, axis=1, keepdims=True)
slot = (row_ids * n_col_tiles + centroid_tile) * tn + ct.cumsum(keep_i, 1) - 1
# The distance's bits are masked: widening a negative int32 (a negative float, e.g. a
# rounded-down 0) to int64 would sign-extend into the index
index = ct.broadcast_to(centroid_ids, (tm, tn)).astype(ct.int64)
dist_bits = ct.bitcast(dist, ct.int32).astype(ct.int64) & LOW_32_BITS
value = ct.bitwise_lshift(index, ID_SHIFT) | dist_bits
ct.scatter(packed, slot, value, mask=keep)
ct.store(seg_count, index=(row_tile, centroid_tile), tile=per_row)

return fused_filter
Loading