Skip to content

feat(acceleration): remove silent k>kMaxK clamping in CUDA HNSW kernel (v1.8.0, Issue #132) - #4320

Merged
makr-code merged 3 commits into
developfrom
copilot/remove-silent-k-clamping
Mar 18, 2026
Merged

makr-code merged 3 commits into
developfrom
copilot/remove-silent-k-clamping

Conversation

Copilot AI commented Mar 18, 2026 •

Copy link
Copy Markdown
Contributor

The CUDA HNSW launcher was silently clamping k > kMaxK to kMaxK=512, returning fewer results than requested with no indication to the caller. Re-ranking pipelines requesting k=512+ received silently truncated output.

Kernel Changes (cuda_hnsw_kernels.cu)

  • kMaxK 512 → 1024; result buffers (res_dist, res_id) moved from fixed-size local arrays to extern __shared__ dynamic shared memory, partitioned per-thread
  • computeThreadsPerBlock(k) computes block size via __builtin_clz to keep shared-memory usage ≤ 48 KB at any k: 1u << (31 - __builtin_clz(min(128, 49152 / (k*8))))
  • entry_node parameter added to support multi-pass launches from non-zero entry points
  • bool* h_overflow output flag — set and kernel not launched when k > kMaxK; assert() fires in debug builds instead of silent truncation

Traversal Engine (cuda_hnsw_graph_traversal.cpp)

  • k ≤ 1024: single-pass GPU path, checks h_overflow
  • k > 1024: ⌈k/1024⌉-pass host-merge strategy — each pass uses a spread entry node (pass * num_nodes / num_passes), results deduplicated by node ID then top-k selected via std::partial_sort; falls back to CPU if any GPU allocation fails

Backend Error Propagation (cuda_backend.cpp)

  • kHnswSinglePassMaxK = 1024u constant guards both annBatchSearch() and batchKnnSearch()
  • In release builds, k > 1024 calls setError(InvalidInputShape, ...) → getHealthStatus() automatically returns BackendHealthStatus::makeDegraded()

Tests & CI

  • tests/test_cuda_hnsw_large_k.cpp: 7 tests covering k=257, k=512, k=1024, k=1025 (multi-pass), health-degraded assertion (release-only), sort order, multiple queries — all run via CPU fallback, no GPU required
  • tests/CMakeLists.txt: test_cuda_hnsw_large_k_focused target; excluded from main suite when THEMIS_ENABLE_GPU=OFF
  • .github/workflows/02-feature-modules/acceleration/cuda-hnsw-large-k-ci.yml triggers on changes to kernel/traversal/backend/test files
  • src/acceleration/FUTURE_ENHANCEMENTS.md: all roadmap items marked [x]

Type of Change

  • Bug fix
  • New feature
  • Refactoring
  • Documentation
  • Other:

Testing

  • Unit tests added/updated
  • Integration tests added/updated
  • Manual testing performed

📚 Research & Knowledge (wenn applicable)

  • Diese PR basiert auf wissenschaftlichen Paper(s) oder Best Practices?
    • Falls JA: Research-Dateien in /docs/research/ angelegt?
    • Falls JA: Im Modul-README unter "Wissenschaftliche Grundlagen" verlinkt?
    • Falls JA: In /docs/research/implementation_influence/ eingetragen?

Relevante Quellen:

  • Paper:
  • Best Practice:
  • Architecture Decision:

Checklist

  • Code follows project style guidelines
  • Self-review completed
  • Documentation updated (if needed)
  • No new warnings introduced
Original prompt

This section details on the original issue you should resolve

<issue_title>CUDA HNSW Kernel: Remove Silent k > kMaxK Clamping</issue_title>
<issue_description>### Context

This issue implements the roadmap item 'CUDA HNSW Kernel: Remove Silent k > kMaxK Clamping' for the acceleration domain. It is sourced from the consolidated roadmap under 🟡 Medium Priority — Near-term (v1.5.0 – v1.8.0) and targets milestone v1.8.0.

Primary detail section: CUDA HNSW Kernel: Remove Silent k > kMaxK Clamping

Goal

Deliver the scoped changes for CUDA HNSW Kernel: Remove Silent k > kMaxK Clamping in src/acceleration/ and complete the linked detail section in a release-ready state for v1.8.0.

Detailed Scope

CUDA HNSW Kernel: Remove Silent k > kMaxK Clamping

Priority: Medium
Target Version: v1.8.0

cuda/cuda_hnsw_kernels.cu:25 defines static constexpr uint32_t kMaxK = 256u. The launch wrapper at line 325 silently clamps k to kMaxK before launching: if (k > kMaxK) k = kMaxK;. The caller in cuda_backend.cpp receives truncated results with no indication that fewer than the requested k neighbours were returned. For use cases requiring k > 256 (e.g., re-ranking pipelines requesting k=512 candidates), this produces silently wrong output.

Implementation Notes:

  • [ ] Replace the silent clamp in cuda/cuda_hnsw_kernels.cu:325 with an explicit error return: set cudaGetLastError() to a sentinel, or add a bool* d_overflow output flag that the host can check; propagate the overflow condition up through CUDAVectorBackend::buildHnswAnnIndex() / batchKnnSearchWithGraph() as an AccelerationErrorCode::InvalidInputShape error.
  • [ ] Increase kMaxK to 1024 by moving the per-query result buffers (res_dist[kMaxK], res_id[kMaxK]) from fixed-size shared memory arrays to dynamically allocated shared memory via extern __shared__; compute required shared memory as k * (sizeof(float) + sizeof(int32_t)) per thread and pass it as the third <<<>>> launch argument.
  • [ ] For k > 1024 (extreme re-ranking): fall through to a multi-pass strategy — run kMaxK-at-a-time passes over graph layers and merge on host using std::partial_sort.
  • [ ] Add static_assert or CUDA __trap() guard in debug builds when k > kMaxK is detected; surface as BackendHealthStatus::makeDegraded() in release builds.
  • [ ] Test: add tests/acceleration/test_cuda_hnsw_large_k.cpp with k=257, k=512, k=1024 asserting result count equals requested k.

Performance Targets:

  • k=256: no regression vs. current implementation.
  • k=1024 with dynamic shared memory: < 20 ms for 10K queries × 1M vectors on RTX 3090.

Acceptance Criteria

  • Replace the silent clamp in cuda/cuda_hnsw_kernels.cu:325 with an explicit error return: set cudaGetLastError() to a sentinel, or add a bool* d_overflow output flag that the host can check; propagate the overflow condition up through CUDAVectorBackend::buildHnswAnnIndex() / batchKnnSearchWithGraph() as an AccelerationErrorCode::InvalidInputShape error.
  • Increase kMaxK to 1024 by moving the per-query result buffers (res_dist[kMaxK], res_id[kMaxK]) from fixed-size shared memory arrays to dynamically allocated shared memory via extern __shared__; compute required shared memory as k * (sizeof(float) + sizeof(int32_t)) per thread and pass it as the third <<<>>> launch argument.
  • For k > 1024 (extreme re-ranking): fall through to a multi-pass strategy — run kMaxK-at-a-time passes over graph layers and merge on host using std::partial_sort.
  • Add static_assert or CUDA __trap() guard in debug builds when k > kMaxK is detected; surface as BackendHealthStatus::makeDegraded() in release builds.
  • Test: add tests/acceleration/test_cuda_hnsw_large_k.cpp with k=257, k=512, k=1024 asserting result count equals requested k.
  • k=256: no regression vs. current implementation.
  • k=1024 with dynamic shared memory: < 20 ms for 10K queries × 1M vectors on RTX 3090.

Relationships

References

  • src/ROADMAP.md
  • src/acceleration/FUTURE_ENHANCEMENTS.md#cuda-hnsw-kernel-remove-silent-k--kmaxk-clamping
  • Source key: roadmap:132:acceleration:v1.8.0:cuda-hnsw-kernel-remove-silent-k-kmaxk-clamping

Generated from the consolidated source roadmap. Keep the roadmap and issue in sync when scope changes.

</issue_description>

Comments on the Issue (you are @copilot in this section)

...


🔒 GitHub Advanced Security automatically protects Copilot coding agent pull requests. You can protect all pull requests by enabling Advanced Security for your repositories. Learn more about Advanced Security.

Copilot AI and others added 2 commits March 18, 2026 06:28
… 1024 with dynamic shared memory

Co-authored-by: makr-code <[email protected]>
…(), remove goto, use __builtin_clz

Co-authored-by: makr-code <[email protected]>
Copilot AI changed the title [WIP] [CUDA-xxx] Remove silent k > kMaxK clamping in HNSW kernel feat(acceleration): remove silent k>kMaxK clamping in CUDA HNSW kernel (v1.8.0, Issue #132) Mar 18, 2026
Copilot AI requested a review from makr-code March 18, 2026 06:34
@makr-code

Copy link
Copy Markdown
Owner

@copilot Review und Code Audit. Wurden alle Aufgaben des issue erfüllt?

@makr-code

Copy link
Copy Markdown
Owner

@copilot retry

@makr-code

Copy link
Copy Markdown
Owner

@copilot retry

@makr-code
makr-code marked this pull request as ready for review March 18, 2026 10:31
@makr-code
makr-code merged commit 6247574 into develop Mar 18, 2026
11 of 13 checks passed
Copilot AI requested a review from makr-code March 18, 2026 10:31
Copilot stopped work on behalf of makr-code due to an error March 18, 2026 10:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CUDA HNSW Kernel: Remove Silent k > kMaxK Clamping

2 participants