[TopK] Large-path hardening

- Inline-PTX acquire/release helpers declare their memory effects.
- The fault verdict is aggregated across the CTA group before emission, so a
  faulted row is failed closed by every CTA.
- 64-bit device counters and an int64 reader (counter protocol v2).
- Tests: adversarial distributions, slot-residue coverage, an sm_90 gate for
  tests that need it.

Co-Authored-By: Hinata <hinata@idihore.id>
Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-10-09 19:55:59 +07:00
co-authored by Hinata
parent 63e2d8be20
commit 512ca2fc0b
3 changed files with 314 additions and 79 deletions
+88 -22
View File
@@ -56,6 +56,30 @@ bool det_large_enabled() {
return enabled;
}
// ---------------------------------------------------------------------------
// MERLIN_TOPK_LARGE_FAULT_INJECT. TEST ONLY.
//
// -1 (the default, and the value of an unset or negative variable) is off.
// Any other value names the `cta_in_group` whose CTA-LOCAL fault predicate the
// large path forces, which is the only way to reach the fail-closed arm: no
// legal input can make a CTA's own pivot-equal count disagree with the one it
// published, so those branches are otherwise untestable (as with the
// medium-path restart's own fault path). Resolved once per process, so
// it is a launch constant and a cudagraph captures one value. Setting it also
// suppresses __trap(), because the point of injecting is to OBSERVE the
// trap-off row-failure policy (all -1 row, counter += 1) without a second
// build.
// ---------------------------------------------------------------------------
int large_fault_inject_cta() {
static const int cta = [] {
const char* raw = std::getenv("MERLIN_TOPK_LARGE_FAULT_INJECT");
if (raw == nullptr || raw[0] == '\0') return -1;
const int v = std::atoi(raw);
return (v < 0) ? -1 : v;
}();
return cta;
}
// Process-lifetime device counters, one block per device. The kernel only
// ever atomicAdds into them, so the launch path needs no host sync and the
// values accumulate across cudagraph replays.
@@ -86,12 +110,12 @@ enum CounterState : int {
// a second host thread may be publishing them from the slow path. Release on
// publish, acquire on read, and the pointer is always published BEFORE the
// state that advertises it.
std::atomic<unsigned int*> g_exact_counters[kMaxCounterDevices] = {};
std::atomic<unsigned long long*> g_exact_counters[kMaxCounterDevices] = {};
std::atomic<int> g_exact_counters_state[kMaxCounterDevices] = {};
std::mutex g_exact_counters_mutex;
// Lookup only. Never allocates, never blocks, safe from any context.
unsigned int* get_exact_counters(int device_index) {
unsigned long long* get_exact_counters(int device_index) {
if (device_index < 0 || device_index >= kMaxCounterDevices) return nullptr;
if (g_exact_counters_state[device_index].load(std::memory_order_acquire) !=
kCountersReady) {
@@ -106,7 +130,7 @@ unsigned int* get_exact_counters(int device_index) {
// `stream_is_capturing` only proves the CALLING stream is idle of capture, so
// the intended entry point is the reader op called explicitly before capture;
// the non-capturing launch path calls this as a fallback.
unsigned int* ensure_exact_counters(int device_index, cudaStream_t stream) {
unsigned long long* ensure_exact_counters(int device_index, cudaStream_t stream) {
if (device_index < 0 || device_index >= kMaxCounterDevices) return nullptr;
const int state =
@@ -130,8 +154,8 @@ unsigned int* ensure_exact_counters(int device_index, cudaStream_t stream) {
}
constexpr size_t bytes =
vllm::persistent::kNumTopKExactCounters * sizeof(unsigned int);
unsigned int* ptr = nullptr;
vllm::persistent::kNumTopKExactCounters * sizeof(unsigned long long);
unsigned long long* ptr = nullptr;
if (cudaMalloc(&ptr, bytes) == cudaSuccess && ptr != nullptr) {
// Host acquire/release orders the HOST state word; it says
// nothing about the device. cudaMemset on device memory is asynchronous
@@ -377,17 +401,20 @@ void launch_persistent_topk(const torch::stable::Tensor& logits,
params.exact_medium = exact_medium_enabled();
// The per-CTA selected / pivot-equal counts are staged in ONE
// 256-slot RadixRowState histogram row (the slot round 3 has just finished
// reading), which holds 2 * ctas_per_group uint32s. That is the whole
// reason the workspace contract is unchanged, and it is also the only
// limit: above 128 CTAs per group the deterministic path cannot be
// reading). Two more per-CTA regions were added for the
// group-uniform fault verdicts, so the row now holds 4 * ctas_per_group
// uint32s. That is still the whole reason the workspace contract is
// unchanged, and it is also the only
// limit: above 64 CTAs per group the deterministic path cannot be
// expressed there, so the launch degrades to the v2.0.1 tail rather than
// failing. Unreachable at any shape this kernel serves (ctas_per_group is
// 2-3 across our 135K-262K band and <= 16 at the smallest chunk size), but
// a silent loss of determinism is exactly what this branch exists to stop,
// so say it once.
const bool det_large_fits =
2u * ctas_per_group <= static_cast<uint32_t>(P::RADIX);
4u * ctas_per_group <= static_cast<uint32_t>(P::RADIX);
params.det_large = det_large_enabled() && det_large_fits;
params.fault_inject_cta = large_fault_inject_cta();
if (det_large_enabled() && !det_large_fits) {
static std::atomic<bool> det_large_warned{false};
if (!det_large_warned.exchange(true)) {
@@ -396,7 +423,18 @@ void launch_persistent_topk(const torch::stable::Tensor& logits,
"needs %u of %d staging slots; the large path falls back "
"to nondeterministic placement at this shape (counter [4] "
"stays 0).\n",
ctas_per_group, 2u * ctas_per_group, P::RADIX);
ctas_per_group, 4u * ctas_per_group, P::RADIX);
}
}
if (params.fault_inject_cta >= 0) {
static std::atomic<bool> inject_warned{false};
if (!inject_warned.exchange(true)) {
std::fprintf(stderr,
"[vllm] MERLIN_TOPK_LARGE_FAULT_INJECT=%d is set: the "
"large path FORCES a fault in that CTA of every "
"deterministic large row and returns an all -1 row. This "
"is a test mode and must not be set in production.\n",
params.fault_inject_cta);
}
}
// Allocate only off the capture path; in the ordinary engine lifecycle the
@@ -503,7 +541,31 @@ void persistent_topk(const torch::stable::Tensor& logits,
// counters. This is also the explicit pre-capture init path: call it once per
// device before any cudagraph capture.
//
// `out` is an int32 CUDA tensor with at least 10 elements:
// PROTOCOL VERSION 2 -- BREAKING. `out` is an **int64**
// CUDA tensor with at least 10 elements; int32 is REJECTED, not silently
// accepted. The device counters are 64-bit unsigned and are copied D2D
// without conversion, so the reader's element width must match the device's.
//
// Why the break rather than a reinterpreting reader: the counters were u32
// copied into a SIGNED int32 tensor. At 65,536 columns with k=512 an
// all-equal row drops 65,024 ties, so [6] goes negative in Python after 33,027
// rows and wraps modulo 2^32 after 66,053 -- and a subtraction across the
// signed boundary gives a wrong delta, which is worse than a missing number
// because it looks like a measurement. Keeping u32 and reinterpreting in the
// reader would need an enforced per-window increment bound plus quiescent
// resets, i.e. a contract every future caller has to remember. 64-bit device
// counters make the failure unreachable instead: `atomicAdd(unsigned long
// long*)` is native on sm_86 (it is a single ATOM.E.ADD.S64, not a CAS loop),
// so the instrument costs the same, and a 64-bit slot cannot be driven to the
// signed boundary by any run this kernel will ever see.
//
// Everything that reads these counters must move together: the Python reader
// `vllm/models/qwen4_exp/nvidia/ops/topk_counters.py` now allocates int64, and
// the medium-path tests allocate int64. An int32 caller gets a loud error rather
// than half a number. The OPERATOR SCHEMA is unchanged (dtype is not part of
// it), so a stale caller fails at the check, not at the binding.
//
// Slots:
// [0] medium-path rows entered (denominator)
// [1] rows where a 4,096-slot guard would drop a candidate
// [2] rows that took the exact restart (0 in the control arm)
@@ -537,13 +599,17 @@ void persistent_topk_exact_counters(torch::stable::Tensor& out, int64_t reset,
int64_t sync) {
#ifndef USE_ROCM
STD_TORCH_CHECK(out.is_cuda(), "out must be a CUDA tensor");
STD_TORCH_CHECK(out.scalar_type() == torch::headeronly::ScalarType::Int,
"out must be int32");
STD_TORCH_CHECK(
out.scalar_type() == torch::headeronly::ScalarType::Long,
"out must be int64: the exact-restart counters are 64-bit as of the "
"large-path counter protocol change, and an int32 buffer would be filled "
"from half of each counter. Allocate torch.zeros(10, dtype=torch.int64)."
" (int32 was protocol version 1 and is deliberately rejected.)");
// Element count alone is not enough. A CUDA scalar expanded
// to five elements (stride 0) satisfies numel but owns one element's
// storage, and the five consecutive raw int32 writes below would run past
// it; an ordinary strided view would receive the values in the wrong slots.
// Require a contiguous 1-D buffer before taking the pointer.
// to ten elements (stride 0) satisfies numel but owns one element's storage,
// and the raw int64 writes below would run past it; an ordinary strided view
// would receive the values in the wrong slots. Require a contiguous 1-D
// buffer before taking the pointer.
STD_TORCH_CHECK(out.dim() == 1, "out must be 1-D");
STD_TORCH_CHECK(out.is_contiguous(),
"out must be contiguous (expanded or strided views would be "
@@ -563,10 +629,10 @@ void persistent_topk_exact_counters(torch::stable::Tensor& out, int64_t reset,
"persistent_topk_exact_counters must not be called during "
"cudagraph capture");
constexpr size_t bytes =
vllm::persistent::kNumTopKExactCounters * sizeof(unsigned int);
vllm::persistent::kNumTopKExactCounters * sizeof(unsigned long long);
int32_t* dst = out.mutable_data_ptr<int32_t>();
unsigned int* src =
int64_t* dst = out.mutable_data_ptr<int64_t>();
unsigned long long* src =
ensure_exact_counters(static_cast<int>(out.get_device_index()), stream);
// An unavailable buffer used to be reported as four zeros
@@ -600,11 +666,11 @@ void persistent_topk_exact_counters(torch::stable::Tensor& out, int64_t reset,
// flag reports the ENV value, not the per-launch effective value: a launch
// whose ctas_per_group overflowed the staging row still reports 1 here and
// leaves counter [4] at 0, which is how that degradation is diagnosed.
static const int32_t enabled[2] = {exact_medium_enabled() ? 1 : 0,
static const int64_t enabled[2] = {exact_medium_enabled() ? 1 : 0,
det_large_enabled() ? 1 : 0};
STD_TORCH_CHECK(
cudaMemcpyAsync(dst + vllm::persistent::kNumTopKExactCounters, enabled,
2 * sizeof(int32_t), cudaMemcpyHostToDevice,
2 * sizeof(int64_t), cudaMemcpyHostToDevice,
stream) == cudaSuccess,
"exact counter flag write failed");