// Persistent TopK kernel for DeepSeek V3 sparse attention indexer. // See persistent_topk.cuh for kernel implementation. #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). // --------------------------------------------------------------------------- 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; } // 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 int* 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 int* 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 int); unsigned int* 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(); // 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. // // `out` is an int32 CUDA tensor with at least 5 elements: // [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] 1 if MERLIN_TOPK_EXACT_MEDIUM is on, else 0 // // 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::Int, "out must be int32"); // 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. 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)"); STD_TORCH_CHECK(out.numel() >= vllm::persistent::kNumTopKExactCounters + 1, "out must hold at least ", vllm::persistent::kNumTopKExactCounters + 1, " elements"); 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 int); int32_t* dst = out.mutable_data_ptr(); unsigned int* 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. static const int32_t enabled = exact_medium_enabled() ? 1 : 0; STD_TORCH_CHECK( cudaMemcpyAsync(dst + vllm::persistent::kNumTopKExactCounters, &enabled, sizeof(int32_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 }