// Persistent TopK kernel for DeepSeek V3 sparse attention indexer. // See persistent_topk.cuh for kernel implementation. #include #include #include #include #include #include #include #include "ops.h" #include "torch_utils.h" #ifndef USE_ROCM #include "persistent_topk.cuh" #include "sampled_topk.cuh" #endif namespace { #ifndef USE_ROCM // --------------------------------------------------------------------------- // MERLIN_TOPK_EXACT_MEDIUM switch and its counters. // // The switch is resolved ONCE per process, not per launch, so it is a launch // constant: a cudagraph captures the value that was live at capture time and // every replay agrees with it. Default ON in this release; set // MERLIN_TOPK_EXACT_MEDIUM=0 for the A/B control arm, which restores v2.0.1 // behaviour exactly (the counters still record, so the control arm reports the // overflow incidence it is the control for). // --------------------------------------------------------------------------- // ------------------------------------------------------------------------- // MERLIN_TIE_DET: deterministic tie-break at the k-th cutoff in // persistent_topk. Resolved once per process, exactly like // exact_medium_enabled() below, so it is a launch constant that a cudagraph // bakes in at capture. // // Our own toggle rather than upstream's VLLM_BATCH_INVARIANT, which aborts // engine startup on GDN models (upstream #42960) and so can never reach this // kernel on Flash-Next. Default OFF -- promotion is a release decision. // // This std::getenv is the SINGLE source of truth; vllm/envs.py carries a raw // passthrough for validate_environ and the compile-factor hash only. // ------------------------------------------------------------------------- // MERLIN_TIE_RECENT -- the DIRECTION of the deterministic tie-break above. // Measured at 12k tokens on the reference host: oldest-wins costs -7.9 % decode, // most-recent-wins is +1.5 %. Both deterministic. Also the direction // medium_exact_restart() already implements, so setting this alongside // MERLIN_TIE_DET makes the medium path agree with itself on overflowing // rows. Only read when MERLIN_TIE_DET is set. Default OFF. bool tie_recent_enabled() { static const bool enabled = [] { const char* raw = std::getenv("MERLIN_TIE_RECENT"); return (raw != nullptr && raw[0] != '\0') ? (std::atoi(raw) != 0) : false; }(); return enabled; } bool det_ties_enabled() { static const bool enabled = [] { const char* raw = std::getenv("MERLIN_TIE_DET"); return (raw != nullptr && raw[0] != '\0') ? (std::atoi(raw) != 0) : false; }(); return enabled; } bool exact_medium_enabled() { static const bool enabled = [] { const char* raw = std::getenv("MERLIN_TOPK_EXACT_MEDIUM"); return (raw == nullptr || raw[0] == '\0') ? true : (std::atoi(raw) != 0); }(); return enabled; } // --------------------------------------------------------------------------- // MERLIN_TOPK_DET_LARGE switch. // // Same contract as the medium-path switch: resolved once per process, so it is a // launch constant and a cudagraph captures one value. Default ON on this // branch. MERLIN_TOPK_DET_LARGE=0 is the A/B control arm and runs the // v2.0.1 `radix_topk` tail verbatim -- the deterministic emission sits behind // one `if (det_large)` in front of it and touches nothing when off, including // the large-path counters, which is what makes the control arm the real baseline. // --------------------------------------------------------------------------- bool det_large_enabled() { static const bool enabled = [] { const char* raw = std::getenv("MERLIN_TOPK_DET_LARGE"); return (raw == nullptr || raw[0] == '\0') ? true : (std::atoi(raw) != 0); }(); return enabled; } // MERLIN_TOPK_EXACT_DECODE: repair an overflowing decode // row with the same exact restart the medium path uses. Resolved once per // process like the others, so it is a launch constant a cudagraph bakes in. // // Default OFF, unlike MERLIN_TOPK_EXACT_MEDIUM. The medium path's overflow // incidence was measured (0.1-0.2 % of medium rows at 38-51K) before that // switch defaulted on; the decode path's has never been measured at all, // which is precisely what the [10] counter now exists to establish. Detection // is unconditional and free; the repair waits on a number. bool exact_decode_enabled() { static const bool enabled = [] { const char* raw = std::getenv("MERLIN_TOPK_EXACT_DECODE"); return (raw != nullptr && raw[0] != '\0') ? (std::atoi(raw) != 0) : false; }(); 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; } // --------------------------------------------------------------------------- // MERLIN_TOPK_LARGE_FAULT_KIND. TEST ONLY, companion to // the variable above; ignored unless MERLIN_TOPK_LARGE_FAULT_INJECT names a // CTA. // // unset / "pre" (default) force the PRE-EMISSION predicate, caught at X3. // "emit" force the EMISSION-BOUND slot check, caught at X4. // // The two are mutually exclusive by construction: a pre-emission fault makes // `row_fault` nonzero, the emission block is skipped wholesale, and the X4 // code -- including `suffix_sum[6]`, the word whose concurrent non-atomic // write this change is about -- is never reached. The shipped injector could // therefore only ever exercise the arm that was already correct, which is why // the X4 arm had never been exercised. Resolved once per process like // every other switch here, so it is a launch constant a cudagraph bakes in. // --------------------------------------------------------------------------- bool large_fault_inject_emit() { static const bool emit = [] { const char* raw = std::getenv("MERLIN_TOPK_LARGE_FAULT_KIND"); if (raw == nullptr || raw[0] == '\0') return false; return std::strncmp(raw, "emit", 5) == 0; }(); return emit; } // --------------------------------------------------------------------------- // Say the effective tie policy out loud, once. // // "TIE_DET=1 TIE_RECENT=0" used to mean three different things on the three // paths, and nothing printed the difference. One stderr line at the first // launch of the process naming the policy the kernel will actually apply on // EVERY path. It is a plain fprintf on the host: no CUDA call, so it is safe // from a capturing thread, and the `static` initialiser makes it exactly once // per process regardless of how many workers share the log. // // The line covers all FIVE paths. The large // path is no longer a fixed rule: `radix_emit_deterministic` takes the same // `effective_tie_recent()` value as the medium restart, so `large=` reports // the real direction when MERLIN_TOPK_DET_LARGE is on and the inherited // v2.0.1 atomic-arrival race when it is off. The flag printed here is the // ENV value; a launch whose ctas_per_group overflows the staging row degrades // to atomic-arrival for that launch and leaves counter [4] at 0, which is the // separate warning below. // --------------------------------------------------------------------------- void report_tie_policy_once() { static const bool reported = [] { const bool det = det_ties_enabled(); const bool recent = vllm::persistent::effective_tie_recent(det, tie_recent_enabled()); const char* dir = recent ? "most-recent-wins" : "oldest-wins"; std::fprintf( stderr, "[merlin] persistent_topk tie policy: MERLIN_TIE_DET=%d " "MERLIN_TIE_RECENT=%d MERLIN_TOPK_EXACT_MEDIUM=%d " "MERLIN_TOPK_EXACT_DECODE=%d MERLIN_TOPK_DET_LARGE=%d -> " "decode-buffered=%s decode-restart=%s medium-buffered=%s " "medium-restart=%s large=%s\n", det ? 1 : 0, tie_recent_enabled() ? 1 : 0, exact_medium_enabled() ? 1 : 0, exact_decode_enabled() ? 1 : 0, det_large_enabled() ? 1 : 0, det ? dir : "atomic-arrival", exact_decode_enabled() ? dir : "n/a (detect-only; counter [10])", det ? dir : "atomic-arrival", exact_medium_enabled() ? dir : "n/a (exact restart disabled)", det_large_enabled() ? dir : "atomic-arrival (non-deterministic)"); return true; }(); (void)reported; } #if MERLIN_TOPK_DIAG_ANY // DIAGNOSTIC BUILD ONLY (persistent_topk.cuh, "DIAGNOSTIC BUILDS ONLY"). Say // so once per process, on stderr, before the first launch: the diagnostic-build tests // key on this line to prove which build they ran against, and the smoke's // startup-warning scan must reject any process that prints it. void report_diag_build_once() { static const bool reported = [] { std::fprintf(stderr, "[merlin] persistent_topk DIAGNOSTIC BUILD: " "MERLIN_TOPK_DIAG_DELAY=%lld MERLIN_TOPK_DIAG_PREREPAIR=%d " "MERLIN_TOPK_DIAG_FORCE_FAULT=%d " "MERLIN_TOPK_DIAG_FORCE_FAULT_CTA=%d -- NOT FOR SERVING\n", static_cast(MERLIN_TOPK_DIAG_DELAY), static_cast(MERLIN_TOPK_DIAG_PREREPAIR), static_cast(MERLIN_TOPK_DIAG_FORCE_FAULT), static_cast(MERLIN_TOPK_DIAG_FORCE_FAULT_CTA)); return true; }(); (void)reported; } #endif // 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. // // Allocation, however, is NOT capture-safe: cudaMalloc during stream capture // is at best not captured and at worst invalidates the capture. So: // - the allocation only ever happens on a call that is explicitly allowed to // allocate, which is a non-capturing launch or the reader op; // - a call made *during* capture never allocates and never latches a result, // so a capture that happens to be first does not permanently poison the // instrument; // - the launch path fails loudly if it is capturing with no counters, rather // than baking a graph that runs the patched kernel with no instrument at // all. A silently uninstrumented graph is the failure this is here to // prevent, so the check is deliberately not a warning. // Read (and, on the first call, allocate) with // torch.ops._C.persistent_topk_exact_counters, which is the explicit // pre-capture init path. constexpr int kMaxCounterDevices = 16; enum CounterState : int { kCountersUninit = 0, kCountersReady = 1, kCountersFailed = 2, }; // Atomics, not plain globals: the fast path reads these without the mutex, and // 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 g_exact_counters[kMaxCounterDevices] = {}; std::atomic g_exact_counters_state[kMaxCounterDevices] = {}; std::mutex g_exact_counters_mutex; // Lookup only. Never allocates, never blocks, safe from any context. 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) { return nullptr; } return g_exact_counters[device_index].load(std::memory_order_acquire); } // Allocate, zero, and publish. MUST NOT be called on a capturing stream, and // should be called in a quiescent lifecycle phase: it allocates and blocks, // and neither is safe while any thread in the process is capturing a graph. // `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 long long* ensure_exact_counters(int device_index, cudaStream_t stream) { if (device_index < 0 || device_index >= kMaxCounterDevices) return nullptr; const int state = g_exact_counters_state[device_index].load(std::memory_order_acquire); if (state == kCountersReady) { return g_exact_counters[device_index].load(std::memory_order_acquire); } // A previous attempt failed for real (OOM); do not retry on every launch. // Only a call that was actually allowed to allocate can reach this state, so // a capture-time call never latches it. if (state == kCountersFailed) return nullptr; std::lock_guard lock(g_exact_counters_mutex); // Re-check under the lock; another thread may have published meanwhile. const int locked_state = g_exact_counters_state[device_index].load(std::memory_order_relaxed); if (locked_state != kCountersUninit) { return (locked_state == kCountersReady) ? g_exact_counters[device_index].load(std::memory_order_acquire) : nullptr; } constexpr size_t bytes = 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 // with respect to the host, so publishing Ready straight after it would // let a first launch -- on this or any other stream -- increment counters // that had not been zeroed yet, or read uninitialised bytes. Zero on a // known stream and WAIT for it, so initialisation is complete before the // pointer becomes visible to any consumer. if (cudaMemsetAsync(ptr, 0, bytes, stream) != cudaSuccess || cudaStreamSynchronize(stream) != cudaSuccess) { cudaFree(ptr); ptr = nullptr; } } else { ptr = nullptr; } // A failed allocation leaves the error state set; clear it so the launch's // own cudaGetLastError() gate does not report this as a kernel failure. if (ptr == nullptr) cudaGetLastError(); g_exact_counters[device_index].store(ptr, std::memory_order_release); g_exact_counters_state[device_index].store( ptr != nullptr ? kCountersReady : kCountersFailed, std::memory_order_release); return ptr; } // True when the stream is mid-capture, in which case nothing on this path may // allocate. A query failure is treated as "capturing": the conservative // direction is to refuse to allocate, not to risk invalidating a capture. bool stream_is_capturing(cudaStream_t stream) { cudaStreamCaptureStatus status = cudaStreamCaptureStatusNone; if (cudaStreamIsCapturing(stream, &status) != cudaSuccess) { cudaGetLastError(); // do not leak this into the launch's error gate return true; } return status != cudaStreamCaptureStatusNone; } template void launch_persistent_topk(const torch::stable::Tensor& logits, const torch::stable::Tensor& lengths, torch::stable::Tensor& output, torch::stable::Tensor& workspace, int64_t max_seq_len) { namespace P = vllm::persistent; const torch::stable::accelerator::DeviceGuard device_guard( logits.get_device_index()); const int64_t num_rows = logits.size(0); const int64_t stride = logits.stride(0); const cudaStream_t stream = get_current_cuda_stream(); static int num_sms = 0; static int max_smem_per_block = 0; if (num_sms == 0) { const cudaDeviceProp* device_prop = get_device_prop(); num_sms = device_prop->multiProcessorCount; max_smem_per_block = device_prop->sharedMemPerBlockOptin; } // Allow static fallback storage in addition to the 128 KiB dynamic buffer. if (num_rows > 64 && max_seq_len >= vllm::sampled_topk::kMinSampledLength && max_smem_per_block >= 144 * 1024) { auto kernel = vllm::sampled_topk::sampled_topk_kernel; constexpr size_t smem_size = vllm::filtered_topk::FILTERED_TOPK_SMEM_DYNAMIC; cudaError_t status = cudaFuncSetAttribute( kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, smem_size); STD_TORCH_CHECK(status == cudaSuccess, "sampled_topk smem failed: ", cudaGetErrorString(status)); kernel<<>>( logits.const_data_ptr(), lengths.const_data_ptr(), output.mutable_data_ptr(), stride, static_cast(std::min(max_seq_len, logits.size(1)))); } else if (num_rows > 32 && max_smem_per_block >= 128 * 1024) { cudaError_t status = vllm::FilteredTopKRaggedTransform( logits.const_data_ptr(), output.mutable_data_ptr(), lengths.const_data_ptr(), static_cast(num_rows), static_cast(TopK), static_cast(stride), stream); STD_TORCH_CHECK(status == cudaSuccess, "FilteredTopK failed: ", cudaGetErrorString(status)); } else { STD_TORCH_CHECK(workspace.is_cuda(), "workspace must be CUDA tensor"); STD_TORCH_CHECK( workspace.scalar_type() == torch::headeronly::ScalarType::Byte, "workspace must be uint8"); int effective_max_smem; if (num_rows <= 4) { effective_max_smem = std::min(max_smem_per_block, static_cast(P::kSmemMedium)); } else if (num_rows <= 8) { constexpr int kSmemCapMedium = 48 * 1024; effective_max_smem = std::min(max_smem_per_block, kSmemCapMedium); } else { effective_max_smem = max_smem_per_block; } size_t available_for_ordered = static_cast(effective_max_smem) - P::kFixedSmemLarge; uint32_t max_chunk_elements = static_cast(available_for_ordered / sizeof(uint32_t)); uint32_t vec_size = 1; if (stride % 4 == 0) vec_size = 4; else if (stride % 2 == 0) vec_size = 2; max_chunk_elements = (max_chunk_elements / vec_size) * vec_size; uint32_t min_chunk = vec_size * P::kThreadsPerBlock; if (max_chunk_elements < min_chunk) max_chunk_elements = min_chunk; uint32_t ctas_per_group = (static_cast(stride) + max_chunk_elements - 1) / max_chunk_elements; uint32_t chunk_size = (static_cast(stride) + ctas_per_group - 1) / ctas_per_group; chunk_size = ((chunk_size + vec_size - 1) / vec_size) * vec_size; if (chunk_size > max_chunk_elements) chunk_size = max_chunk_elements; size_t smem_size = P::kFixedSmemLarge + chunk_size * sizeof(uint32_t); if (smem_size < P::kSmemMedium) smem_size = P::kSmemMedium; // Query occupancy for the instantiation that will actually launch; // overestimating it deadlocks the cooperative barrier. int occupancy = 1; cudaError_t occ_err = cudaSuccess; if (vec_size == 4) { occ_err = cudaOccupancyMaxActiveBlocksPerMultiprocessor( &occupancy, P::persistent_topk_kernel, P::kThreadsPerBlock, smem_size); } else if (vec_size == 2) { occ_err = cudaOccupancyMaxActiveBlocksPerMultiprocessor( &occupancy, P::persistent_topk_kernel, P::kThreadsPerBlock, smem_size); } else { occ_err = cudaOccupancyMaxActiveBlocksPerMultiprocessor( &occupancy, P::persistent_topk_kernel, P::kThreadsPerBlock, smem_size); } STD_TORCH_CHECK(occ_err == cudaSuccess, "persistent_topk occupancy query failed: ", cudaGetErrorString(occ_err)); if (occupancy < 1) occupancy = 1; // The cooperative spin-wait barrier only runs when at least one row hits // the radix path (seq_len > RADIX_THRESHOLD). Below that, non-CTA-0 CTAs // early-exit, so oversubscription can't deadlock and headroom is wasted. const bool needs_cooperative = static_cast(max_seq_len) > P::RADIX_THRESHOLD; const uint32_t hw_resident_cap = static_cast(num_sms) * static_cast(occupancy); uint32_t max_resident_ctas = hw_resident_cap; if (needs_cooperative) { // Reserve one CTA per SM when occupancy allows; fall back to a single // CTA when occupancy == 1 (the most deadlock-prone case — any straggler // kernel that takes the only slot on one SM hangs the barrier). Never // drop below one full group's worth. uint32_t headroom = (occupancy > 1) ? static_cast(num_sms) : 1u; if (max_resident_ctas >= headroom + ctas_per_group) { max_resident_ctas -= headroom; } } uint32_t num_groups = std::min(max_resident_ctas / ctas_per_group, static_cast(num_rows)); if (num_groups == 0) num_groups = 1; uint32_t total_ctas = num_groups * ctas_per_group; // If the cooperative launch wouldn't fit, use the generic decode kernel on // low-smem devices or FilteredTopK where its 128 KiB requirement is met. if (needs_cooperative && total_ctas > hw_resident_cap) { if (max_smem_per_block < 128 * 1024) { const int64_t next_n = lengths.dim() == 2 ? lengths.size(1) : 1; top_k_per_row_decode(logits, next_n, lengths, output, num_rows, logits.stride(0), logits.stride(1), TopK); return; } cudaError_t status = vllm::FilteredTopKRaggedTransform( logits.const_data_ptr(), output.mutable_data_ptr(), lengths.const_data_ptr(), static_cast(num_rows), static_cast(TopK), static_cast(stride), stream); STD_TORCH_CHECK(status == cudaSuccess, "FilteredTopK fallback failed: ", cudaGetErrorString(status)); return; } size_t state_bytes = num_groups * sizeof(P::RadixRowState); STD_TORCH_CHECK(workspace.size(0) >= static_cast(state_bytes), "workspace too small, need ", state_bytes, " bytes"); // Zero the per-group RadixRowState region before launch. // // Issued UNCONDITIONALLY so the memset is captured as its own node in // the cudagraph (a separate cudaMemsetAsync node, sequenced before the // persistent_topk_kernel launch on the same stream). The previous // host-side guard `if (needs_cooperative)` was evaluated at capture time; // when capture-time max_seq_len <= RADIX_THRESHOLD (always true under // FULL_DECODE_ONLY with max_model_len < 32 K) the memset would NOT be // captured, leaving the workspace state to accumulate across replays. // That's a latent correctness bug if the runtime data ever takes the // radix path, and removes one variable while debugging hangs in the // decode/medium paths. // // Cost is sub-microsecond: state_bytes = num_groups * sizeof(RadixRowState) // is ~3 KB per group, ~100 KB for the largest grids on this hardware. // // Why the memset is required (regardless of which path the kernel takes): // 1. arrival_counter accumulates within a launch and is never reset, // so a prior call leaves it at a large positive value. Without this // reset, the very first wait_ge in the next call sees counter >> // target and returns instantly, breaking the barrier. // 2. The previous in-kernel init only ran in CTA-0 with intra-CTA // __syncthreads(), so it had no happens-before edge to CTA-1+'s // first red_release. cudaMemsetAsync is stream-ordered: the zero // is globally visible before any CTA runs. { cudaError_t mz_err = cudaMemsetAsync( workspace.mutable_data_ptr(), 0, state_bytes, stream); STD_TORCH_CHECK(mz_err == cudaSuccess, "row_states memset failed: ", cudaGetErrorString(mz_err)); } P::PersistentTopKParams params; params.input = logits.const_data_ptr(); params.output = output.mutable_data_ptr(); params.lengths = lengths.const_data_ptr(); params.num_rows = static_cast(num_rows); params.stride = static_cast(stride); params.top_k = static_cast(TopK); params.chunk_size = chunk_size; params.row_states = reinterpret_cast( workspace.mutable_data_ptr()); params.ctas_per_group = ctas_per_group; params.max_seq_len = static_cast(max_seq_len); 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). 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 = 4u * ctas_per_group <= static_cast(P::RADIX); params.det_large = det_large_enabled() && det_large_fits; params.fault_inject_cta = large_fault_inject_cta(); params.fault_inject_emit = large_fault_inject_emit(); if (det_large_enabled() && !det_large_fits) { static std::atomic det_large_warned{false}; if (!det_large_warned.exchange(true)) { std::fprintf(stderr, "[vllm] MERLIN_TOPK_DET_LARGE is on but ctas_per_group=%u " "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, 4u * ctas_per_group, P::RADIX); } } if (params.fault_inject_cta >= 0) { static std::atomic inject_warned{false}; if (!inject_warned.exchange(true)) { std::fprintf(stderr, "[vllm] MERLIN_TOPK_LARGE_FAULT_INJECT=%d kind=%s is " "set: the large path FORCES a %s 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, params.fault_inject_emit ? "emit" : "pre", params.fault_inject_emit ? "emission-bound (X4)" : "pre-emission (X3)"); } } params.det_ties = det_ties_enabled(); params.tie_recent = tie_recent_enabled(); params.exact_decode = exact_decode_enabled(); report_tie_policy_once(); #if MERLIN_TOPK_DIAG_ANY report_diag_build_once(); #endif // Allocate only off the capture path; in the ordinary engine lifecycle the // eager warmup lands here first, long before capture. The explicit, // quiescent-phase entry point is the reader op. const int device_index = static_cast(logits.get_device_index()); params.exact_counters = stream_is_capturing(stream) ? get_exact_counters(device_index) : ensure_exact_counters(device_index, stream); // Note: this check is UNCONDITIONAL -- eager as well as // capturing, and in both arms. Previously only a capturing launch was // rejected, so an eager launch ran with nullptr and the reader then // reported [0,0,0,0,1]: an unavailable instrument encoded as healthy zero // counts, which is the exact failure the counters exist to prevent. // MERLIN_TOPK_EXACT_MEDIUM=0 is NOT an escape: the control arm's whole job // is to report the overflow incidence it is the control for, so it needs // the counters just as much. STD_TORCH_CHECK( params.exact_counters != nullptr, "persistent_topk: the medium-path exact-restart counters are unavailable on " "device ", device_index, " (not initialised before cudagraph capture, or the one-time " "allocation failed). Call " "torch.ops._C.persistent_topk_exact_counters(out, 0, 1) once per " "device in a quiescent phase before capture."); #define LAUNCH_PERSISTENT(TOPK_VAL, VS) \ do { \ auto kernel = &P::persistent_topk_kernel; \ cudaError_t err = cudaFuncSetAttribute( \ kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, smem_size); \ STD_TORCH_CHECK(err == cudaSuccess, \ "Failed to set smem: ", cudaGetErrorString(err)); \ kernel<<>>(params); \ } while (0) if (vec_size == 4) { LAUNCH_PERSISTENT(TopK, 4); } else if (vec_size == 2) { LAUNCH_PERSISTENT(TopK, 2); } else { LAUNCH_PERSISTENT(TopK, 1); } #undef LAUNCH_PERSISTENT } cudaError_t err = cudaGetLastError(); STD_TORCH_CHECK(err == cudaSuccess, "persistent_topk failed: ", cudaGetErrorString(err)); } #endif } // anonymous namespace void persistent_topk(const torch::stable::Tensor& logits, const torch::stable::Tensor& lengths, torch::stable::Tensor& output, torch::stable::Tensor& workspace, int64_t k, int64_t max_seq_len) { #ifndef USE_ROCM STD_TORCH_CHECK(logits.is_cuda(), "logits must be CUDA tensor"); STD_TORCH_CHECK(lengths.is_cuda(), "lengths must be CUDA tensor"); STD_TORCH_CHECK(output.is_cuda(), "output must be CUDA tensor"); STD_TORCH_CHECK(logits.scalar_type() == torch::headeronly::ScalarType::Float, "Only float32 supported"); STD_TORCH_CHECK(lengths.scalar_type() == torch::headeronly::ScalarType::Int, "lengths must be int32"); STD_TORCH_CHECK(output.scalar_type() == torch::headeronly::ScalarType::Int, "output must be int32"); STD_TORCH_CHECK(logits.dim() == 2, "logits must be 2D"); STD_TORCH_CHECK(lengths.dim() == 1 || lengths.dim() == 2, "lengths must be 1D or 2D"); STD_TORCH_CHECK(lengths.is_contiguous(), "lengths must be contiguous"); STD_TORCH_CHECK(output.dim() == 2, "output must be 2D"); const int64_t num_rows = logits.size(0); STD_TORCH_CHECK(lengths.numel() == num_rows, "lengths size mismatch"); STD_TORCH_CHECK(output.size(0) == num_rows && output.size(1) == k, "output size mismatch"); STD_TORCH_CHECK( k == 512 || k == 1024 || k == 2048, "persistent_topk supports k=512, k=1024, or k=2048, got k=", k); const torch::stable::accelerator::DeviceGuard device_guard( logits.get_device_index()); if (k == 512) { launch_persistent_topk<512>(logits, lengths, output, workspace, max_seq_len); } else if (k == 1024) { launch_persistent_topk<1024>(logits, lengths, output, workspace, max_seq_len); } else { launch_persistent_topk<2048>(logits, lengths, output, workspace, max_seq_len); } #else STD_TORCH_CHECK(false, "persistent_topk is not supported on ROCm"); #endif } // Read (and, on first call, allocate) the medium-path exact-restart // counters. This is also the explicit pre-capture init path: call it once per // device before any cudagraph capture. // // PROTOCOL VERSION 2 -- BREAKING. `out` is an **int64** // CUDA tensor with EXACTLY kNumTopKExactCounters (11) elements; int32, and any // other length, are REJECTED rather than 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. // // The layout is the UNION of the tie-determinism and large-path slot // maps -- the large path's ten slots plus the decode restart's [10] decode_overflow, eleven in all, // with nothing renumbered. The two switch flags are slots INSIDE the array at // [8] and [9], not two elements appended after it, so a probe sized to the // old ten- or five-element layout is rejected by the length check below rather // than being filled with the wrong meanings. Ask the build for its own answer // with `torch.ops._C.persistent_topk_exact_counters_slots()`. // // Everything that reads these counters must move together: the Python reader // `vllm/models/qwen4_exp/nvidia/ops/topk_counters.py` allocates int64 and // eleven slots, and the medium- and large-path tests do too. An int32 caller gets a loud // error rather than half a number. The OPERATOR SCHEMA is unchanged (dtype // and length are 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) // [3] exact restarts that could not complete (must stay 0) // [4] large-path rows emitted deterministically (0 in the control arm) // [5] large-path rows whose pivot-equal group was cut at the k-th value // [6] large-path pivot-equal elements discarded by those cuts // [7] large-path invariant violations (must stay 0) // [8] 1 if MERLIN_TOPK_EXACT_MEDIUM is on, else 0 (host-written) // [9] 1 if MERLIN_TOPK_DET_LARGE is on, else 0 (host-written) // [10] decode rows whose buffered candidates exceeded DBUF (3,708) // before deterministic ranking -- MUST be read before any decode-path // determinism claim // // COHERENCY -- stated precisely, because the earlier wording overclaimed. // With `sync == 0` the snapshot is ordered ONLY against work already enqueued // on the current stream; a kernel running on another stream can land // increments it misses. With `sync != 0` the call synchronizes the device // before the copy AND again after the copy/reset have been issued, so on // return every increment submitted before the call is included and any reset // has COMPLETED. That is still conditional on the CALLER HOLDING EXCLUSIVE // SUBMISSION OWNERSHIP: nothing stops another thread enqueueing work after the // leading synchronize, and no claim of unconditional global coherence is made // here. A stronger contract would need an event every later producer waits // on; this op deliberately implements the simpler half and says so. // // `reset != 0` REQUIRES `sync != 0`. Reset between measurements, never during // one. // // Must not be called during cudagraph capture (it allocates, synchronizes and // issues a host-to-device copy). It IS the explicit, quiescent-phase // initialization path: call it once per device before any capture. 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::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(persistent_topk_exact_counters_slots(), dtype=torch.int64)." " (int32 was protocol version 1 and is deliberately rejected.)"); // Element count alone is not enough. A CUDA scalar expanded // 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 " "written out of bounds or into the wrong elements)"); // EXACTLY the build's slot count, not "at least". `>=` accepted an // 11-element buffer on the ten-slot large-path build and quietly left the extra // element reading 0 -- a caller compiled against one layout got a plausible // answer from a build with another, which is the failure mode the // self-describing `..._slots` op exists to prevent. Ask the build, size the // buffer to what it says, and a mismatch is an error rather than a wrong // number. STD_TORCH_CHECK(out.numel() == vllm::persistent::kNumTopKExactCounters, "out must hold exactly ", vllm::persistent::kNumTopKExactCounters, " elements (this build's persistent_topk_exact_counters_" "slots(); the switch flags are slots inside the array, not " "appended after it), got ", out.numel()); STD_TORCH_CHECK( reset == 0 || sync != 0, "persistent_topk_exact_counters: reset requires sync != 0, otherwise the " "zeroing races in-flight kernel atomics and silently drops events"); const torch::stable::accelerator::DeviceGuard device_guard( out.get_device_index()); const cudaStream_t stream = get_current_cuda_stream(); STD_TORCH_CHECK(!stream_is_capturing(stream), "persistent_topk_exact_counters must not be called during " "cudagraph capture"); constexpr size_t bytes = vllm::persistent::kNumTopKExactCounters * sizeof(unsigned long long); int64_t* dst = out.mutable_data_ptr(); unsigned long long* src = ensure_exact_counters(static_cast(out.get_device_index()), stream); // An unavailable buffer used to be reported as four zeros // plus "enabled", i.e. an instrument failure indistinguishable from "no // medium work and no faults". Fail instead. STD_TORCH_CHECK(src != nullptr, "persistent_topk_exact_counters: the counter buffer could " "not be allocated on this device; the instrument is " "unavailable and its absence must not read as zero counts"); if (sync != 0) { // Everything that could still be adding to the block must have retired // before the snapshot (and before a reset) for the numbers to mean // anything across streams. STD_TORCH_CHECK(cudaDeviceSynchronize() == cudaSuccess, "exact counter synchronize failed"); } STD_TORCH_CHECK( cudaMemcpyAsync(dst, src, bytes, cudaMemcpyDeviceToDevice, stream) == cudaSuccess, "exact counter read failed"); if (reset != 0) { STD_TORCH_CHECK(cudaMemsetAsync(src, 0, bytes, stream) == cudaSuccess, "exact counter reset failed"); } // Static storage: the source of an async H2D copy must outlive the copy. // Written AFTER the device copy, which has already zeroed both slots: they // are slots [8] and [9] INSIDE the array and the device never touches them. // The large 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. kSlotSwitchLarge == kSlotSwitchMedium + 1, so one copy does // both. static_assert(vllm::persistent::kSlotSwitchLarge == vllm::persistent::kSlotSwitchMedium + 1, "the two host-written flags must stay adjacent for this copy"); static const int64_t enabled[2] = {exact_medium_enabled() ? 1 : 0, det_large_enabled() ? 1 : 0}; STD_TORCH_CHECK( cudaMemcpyAsync(dst + vllm::persistent::kSlotSwitchMedium, enabled, 2 * sizeof(int64_t), cudaMemcpyHostToDevice, stream) == cudaSuccess, "exact counter flag write failed"); if (sync != 0) { // The leading synchronize alone left the copy and the reset // merely ENQUEUED, so the caller could return and immediately race the // outstanding reset from another stream. Complete the handoff before // returning. STD_TORCH_CHECK(cudaDeviceSynchronize() == cudaSuccess, "exact counter completion synchronize failed"); } #else STD_TORCH_CHECK(false, "persistent_topk is not supported on ROCm"); #endif } // How many int32 slots THIS build's counter array carries. // // The Python reader used to guess from MERLIN_TOPK_COUNTER_SLOTS (default 5) // and name the slots by that length. The decode restart makes the array 11 and the large path makes // it 10, so a guess is now wrong on at least one branch, and a reader that // allocates the wrong length is rejected by the length check above -- the // instrument goes dark exactly when it starts mattering. Ask the build // instead. No CUDA call, no allocation, safe from anywhere. int64_t persistent_topk_exact_counters_slots() { #ifndef USE_ROCM return static_cast(vllm::persistent::kNumTopKExactCounters); #else return 0; #endif }