main
cu 1,439 lines 63.8 KB
Raw
1 // SPDX-License-Identifier: Apache-2.0
2 // SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3 //
4 // HiSparse decode hot-buffer kernels for sparse MLA (GLM-5 / DeepSeek-V3.2).
5 //
6 // The swap-in algorithm is a port of SGLang's hisparse
7 // load_cache_to_device_buffer kernel (sgl jit_kernel/csrc/hisparse.cuh),
8 // adapted to vLLM addressing:
9 // - tokens are keyed by their global KV slot id (block_table-converted
10 // indexer output) instead of in-request positions, so no per-request
11 // host-location table is needed: host pool row i is global slot i.
12 // - each batch row owns a fixed region of `region_stride` hot rows;
13 // slots [0, hot_size) are LRU-managed, slot `hot_size` holds the row's
14 // newest token (written directly by the KV-cache update).
15 //
16 // The kernels only move bytes; they are dtype agnostic.
17
18 #include "torch_utils.h"
19 #include "ops.h"
20 #include "../cuda_utils.h"
21
22 #include <algorithm>
23 #include <cstdint>
24 #include <optional>
25
26 #include <torch/csrc/stable/c/shim.h>
27 #include <torch/csrc/stable/ops.h>
28 #include <torch/headeronly/version.h>
29
30 namespace {
31
32 constexpr int kWarpSize = 32;
33 // Empty key in the shared open-addressing table of host rows.
34 constexpr int32_t kHashEmpty = -1;
35
36 bool is_pinned_cpu_tensor(const torch::stable::Tensor& tensor) {
37 cudaPointerAttributes attributes{};
38 const auto status =
39 cudaPointerGetAttributes(&attributes, tensor.const_data_ptr());
40 if (status != cudaSuccess) {
41 cudaGetLastError();
42 return false;
43 }
44 return attributes.type == cudaMemoryTypeHost;
45 }
46
47 __device__ __forceinline__ int32_t hash_slot(int32_t key, int size) {
48 // Knuth multiplicative hash scaled onto [0, size) by a multiply-high, so
49 // the table can take any size without a division.
50 return static_cast<int32_t>(
51 __umulhi(static_cast<uint32_t>(key) * 2654435761u, size));
52 }
53
54 __device__ __forceinline__ int next_slot(int h, int size) {
55 return h + 1 == size ? 0 : h + 1;
56 }
57
58 // Copy one row of `row_bytes` bytes with a single warp. MLA rows take the
59 // 16-byte vectorized path; packed indexer rows use the scalar tail-safe path.
60 __device__ __forceinline__ void copy_row_warp(int lane_id, const char* src,
61 char* dst, int64_t row_bytes) {
62 const auto alignment = reinterpret_cast<uintptr_t>(src) |
63 reinterpret_cast<uintptr_t>(dst) |
64 static_cast<uintptr_t>(row_bytes);
65 if ((alignment & 15) == 0) {
66 const int64_t num_vec = row_bytes / 16;
67 const uint4* src4 = reinterpret_cast<const uint4*>(src);
68 uint4* dst4 = reinterpret_cast<uint4*>(dst);
69 for (int64_t j = lane_id; j < num_vec; j += kWarpSize) {
70 __stcg(dst4 + j, __ldcg(src4 + j));
71 }
72 return;
73 }
74
75 if ((alignment & 3) == 0) {
76 const int64_t num_words = row_bytes / 4;
77 const unsigned int* src_words = reinterpret_cast<const unsigned int*>(src);
78 unsigned int* dst_words = reinterpret_cast<unsigned int*>(dst);
79 for (int64_t j = lane_id; j < num_words; j += kWarpSize) {
80 __stcg(dst_words + j, __ldcg(src_words + j));
81 }
82 return;
83 }
84
85 for (int64_t j = lane_id; j < row_bytes; j += kWarpSize) {
86 __stcg(dst + j, __ldcg(src + j));
87 }
88 }
89
90 // Zero one row with a single warp (16B vectorized, L2-only stores), same
91 // addressing contract as copy_row_warp.
92 __device__ __forceinline__ void zero_row_warp(int lane_id, char* dst,
93 int64_t row_bytes) {
94 const auto alignment =
95 reinterpret_cast<uintptr_t>(dst) | static_cast<uintptr_t>(row_bytes);
96 if ((alignment & 15) == 0) {
97 const int64_t num_vec = row_bytes / 16;
98 uint64_t* dst8 = reinterpret_cast<uint64_t*>(dst);
99 for (int64_t j = lane_id; j < num_vec; j += kWarpSize) {
100 uint64_t* d = dst8 + j * 2;
101 asm volatile("st.global.cg.v2.b64 [%0],{%1,%2};" ::"l"(d), "l"(0ULL),
102 "l"(0ULL)
103 : "memory");
104 }
105 return;
106 }
107
108 if ((alignment & 3) == 0) {
109 const int64_t num_words = row_bytes / 4;
110 unsigned int* dst_words = reinterpret_cast<unsigned int*>(dst);
111 for (int64_t j = lane_id; j < num_words; j += kWarpSize) {
112 __stcg(dst_words + j, 0u);
113 }
114 return;
115 }
116
117 for (int64_t j = lane_id; j < row_bytes; j += kWarpSize) {
118 __stcg(dst + j, static_cast<char>(0));
119 }
120 }
121
122 __device__ __forceinline__ char* cache_row_ptr(char* cache, int64_t row,
123 int32_t block_size,
124 int64_t block_stride,
125 int64_t row_bytes) {
126 return cache + (row / block_size) * block_stride +
127 (row % block_size) * row_bytes;
128 }
129
130 __device__ __forceinline__ void zero_cache_row_warp(int lane_id, char* cache,
131 int64_t row,
132 int32_t block_size,
133 int64_t block_stride,
134 int64_t row_bytes) {
135 zero_row_warp(lane_id,
136 cache_row_ptr(cache, row, block_size, block_stride, row_bytes),
137 row_bytes);
138 }
139
140 // In-place inclusive scan over s_data[offset, count) performed by warp 0,
141 // carrying `accumulator` across calls. Returns the running total.
142 __device__ __forceinline__ int warp_inclusive_scan(int32_t* s_data, int lane_id,
143 int offset, int count,
144 int accumulator) {
145 int idx = lane_id + offset;
146 int val = (idx < count) ? s_data[idx] : 0;
147 #pragma unroll
148 for (int i = 1; i < 32; i *= 2) {
149 int n = __shfl_up_sync(0xffffffff, val, i);
150 if (lane_id >= i) val += n;
151 }
152 val += accumulator;
153 if (idx < count) {
154 s_data[idx] = val;
155 }
156 return __shfl_sync(0xffffffff, val, 31);
157 }
158
159 __device__ __forceinline__ int64_t
160 get_physical_hot_row(const int32_t* hot_block_table, int32_t row,
161 int64_t table_stride, int32_t block_size, int32_t slot) {
162 const int32_t block =
163 hot_block_table[static_cast<int64_t>(row) * table_stride +
164 slot / block_size];
165 return static_cast<int64_t>(block) * block_size + slot % block_size;
166 }
167
168 __device__ __forceinline__ void store_hot_index(
169 int32_t* hot_indices, int32_t* attention_indices, int32_t index,
170 int32_t physical_row, int32_t hot_block_size,
171 int64_t attention_block_stride) {
172 hot_indices[index] = physical_row;
173 if (attention_indices != nullptr) {
174 attention_indices[index] =
175 physical_row < 0
176 ? -1
177 : (physical_row / hot_block_size) * attention_block_stride +
178 physical_row % hot_block_size;
179 }
180 }
181
182 // A union entry's value holds its first (row, top-k) position until phase 2
183 // or 3 resolves it to a hot slot tagged with how it was resolved.
184 constexpr int32_t kEntryHit = 1 << 30;
185 constexpr int32_t kEntryMiss = 1 << 29;
186 constexpr int32_t kEntryInvalid = 1 << 28;
187 constexpr int32_t kEntrySlotMask = 0xFFFF;
188 constexpr int kResidencyCounters = 5;
189 // Per-request table entries per referenced top-k position (load <= 1/4
190 // until the hash_size cap).
191 constexpr int kHashLoadInverse = 4;
192
193 // Translate a request-relative top-k position to its resident GPU row (-1 when
194 // the page is not resident) and returns its host row (-1 when not host-backed).
195 __device__ __forceinline__ int32_t translate_topk_entry(
196 const int32_t token_index, const int32_t request_row,
197 const int32_t* __restrict__ source_block_table,
198 const int32_t* __restrict__ resident_block_table, const int64_t host_rows,
199 const int64_t source_bt_stride, const int32_t source_num_reqs,
200 const int32_t source_num_blocks, const int32_t source_block_size,
201 const int64_t resident_bt_stride, const int32_t resident_num_reqs,
202 const int32_t resident_num_blocks, const int32_t resident_block_size,
203 const int32_t resident_null_block, int32_t& resident_row) {
204 int32_t g = token_index;
205 resident_row = -1;
206 if (source_block_table != nullptr) {
207 const int32_t source_block =
208 token_index >= 0 ? token_index / source_block_size : -1;
209 if (request_row >= 0 && request_row < source_num_reqs &&
210 source_block >= 0 && source_block < source_num_blocks) {
211 const int32_t physical_block =
212 source_block_table[static_cast<int64_t>(request_row) *
213 source_bt_stride +
214 source_block];
215 g = physical_block > 0 ? physical_block * source_block_size +
216 token_index % source_block_size
217 : -1;
218 } else {
219 g = -1;
220 }
221 if (resident_block_table != nullptr) {
222 const int32_t resident_block =
223 token_index >= 0 ? token_index / resident_block_size : -1;
224 if (request_row >= 0 && request_row < resident_num_reqs &&
225 resident_block >= 0 && resident_block < resident_num_blocks) {
226 const int32_t physical_block =
227 resident_block_table[static_cast<int64_t>(request_row) *
228 resident_bt_stride +
229 resident_block];
230 if (physical_block != resident_null_block && physical_block >= 0) {
231 resident_row = physical_block * resident_block_size +
232 token_index % resident_block_size;
233 }
234 }
235 }
236 }
237 return g >= host_rows ? -1 : g;
238 }
239
240 // Write the hot index of one reference to a resolved union entry and tally it.
241 __device__ __forceinline__ void write_entry_index(
242 const int32_t entry, const int row, const int i, const int32_t top_k,
243 int32_t* __restrict__ hot_indices, int32_t* __restrict__ attention_indices,
244 const int64_t attention_row_stride, int32_t* __restrict__ miss_mask,
245 const int32_t* __restrict__ hot_block_table, const int request_row,
246 const int64_t hot_table_stride, const int32_t hot_block_size,
247 const int64_t attention_block_stride, const bool first_reference, int& hits,
248 int& misses) {
249 int32_t* row_out = hot_indices + static_cast<int64_t>(row) * top_k;
250 int32_t* row_attention =
251 attention_indices != nullptr
252 ? attention_indices + static_cast<int64_t>(row) * attention_row_stride
253 : nullptr;
254 if (entry & kEntryInvalid) {
255 store_hot_index(row_out, row_attention, i, -1, hot_block_size,
256 attention_block_stride);
257 return;
258 }
259 store_hot_index(row_out, row_attention, i,
260 static_cast<int32_t>(get_physical_hot_row(
261 hot_block_table, request_row, hot_table_stride,
262 hot_block_size, entry & kEntrySlotMask)),
263 hot_block_size, attention_block_stride);
264 // Only an entry's first reference loads it; later references reuse the
265 // slot like a hit.
266 if ((entry & kEntryMiss) && first_reference) {
267 if (miss_mask != nullptr) {
268 miss_mask[static_cast<int64_t>(row) * top_k + i] = 1;
269 }
270 ++misses;
271 } else {
272 ++hits;
273 }
274 }
275
276 // One block per request, launched per batch row. A request's rows (several
277 // with speculative decoding) are contiguous and share its hot-buffer state, so
278 // the block of its first row resolves the union of their host misses once and
279 // maps every row onto it; the other blocks exit. The union is bounded by the
280 // caller's max_union_rows (every decode query's top-k), which
281 // device_buffer_size covers; a larger union traps. Misses take eviction slots
282 // in (row, top-k) order of first reference, so the plan is deterministic.
283 //
284 // Shared memory layout (int32 region followed by int16 region):
285 // s_hash_keys[hash_size] open addressing: union of the rows' host ids
286 // s_hash_vals[hash_size] first position, then slot | kEntry* tag
287 // s_chunk_off[nbc + 1] prefix sums for hit, then miss, compaction
288 // s_evict_off[nbc + 1] prefix sums for evictable compaction
289 // s_counters[5] distinct hits, union size, per-row valid count,
290 // misses, per-entry hits
291 // s_done[nbc] positions phase 3 resolved, one word per chunk
292 // s_lru_out[hot_size] int16, compacted slots: [hits fwd | evict bwd]
293 // Valid global ids must be unique within each row.
294 __global__ __launch_bounds__(1024) void hisparse_resolve_residency_kernel(
295 const int32_t* __restrict__ hot_block_table, // [max_rows, hot_blocks]
296 const int32_t* __restrict__ global_indices, // global or request-relative
297 const int32_t* __restrict__ request_ids, // [num_rows] or nullptr
298 const int32_t* __restrict__ source_block_table, // [num_reqs, max_blocks]
299 const int32_t* __restrict__ resident_block_table,
300 int32_t* __restrict__ resolved_global_indices, // [num_rows, top_k]
301 int32_t* __restrict__ valid_counts, // [num_rows] or nullptr
302 int32_t* __restrict__ swap_host_physical_rows, // [num_rows, top_k]
303 int32_t* __restrict__ swap_device_physical_rows, // [num_rows, top_k]
304 int32_t* __restrict__ swap_counts, // [num_rows]
305 int32_t* __restrict__ hot_indices, // [num_rows, top_k]
306 int32_t* __restrict__ attention_indices, // [num_rows, top_k]
307 int32_t* __restrict__ miss_mask, // [num_rows, top_k] or nullptr
308 int32_t* __restrict__ device_global_indices, // [max_rows, region_stride]
309 int16_t* __restrict__ lru_slots, // [max_rows, hot_size]
310 unsigned long long* __restrict__ stats, // [2] hits,misses or nullptr
311 const int32_t* __restrict__ request_state_indices, // [num_requests] or
312 // nullptr
313 const int32_t request_state_count, const int64_t host_rows,
314 const int64_t hot_table_stride, const int32_t hot_block_size,
315 const int32_t top_k, const int32_t hot_size, const int32_t hash_size,
316 const int64_t region_stride, const int64_t attention_block_stride,
317 const int64_t source_bt_stride, const int32_t source_num_reqs,
318 const int32_t source_num_blocks, const int32_t source_block_size,
319 const int64_t resident_bt_stride, const int32_t resident_num_reqs,
320 const int32_t resident_num_blocks, const int32_t resident_block_size,
321 const int32_t resident_null_block, const int64_t input_row_stride,
322 const int64_t attention_row_stride, const int64_t valid_count_stride) {
323 const int NUM_WARPS = blockDim.x / kWarpSize;
324 const int num_buffer_chunks = (hot_size + kWarpSize - 1) / kWarpSize;
325
326 // The first row of each contiguous run of a request's rows leads it. FULL
327 // CUDA-graph padding rows map to request 0 after the real rows, forming a
328 // second run, but carry no valid top-k: that run returns before phase 2
329 // touches the request's shared state.
330 const int first_row = blockIdx.x;
331 const int request_row =
332 request_ids != nullptr ? request_ids[first_row] : first_row;
333 if (request_ids != nullptr && first_row > 0 &&
334 request_ids[first_row - 1] == request_row) {
335 return;
336 }
337 int end_row = first_row + 1;
338 if (request_ids != nullptr) {
339 while (end_row < static_cast<int>(gridDim.x) &&
340 request_ids[end_row] == request_row) {
341 ++end_row;
342 }
343 }
344 const int state_row =
345 request_state_indices != nullptr && request_row >= 0 &&
346 request_row < request_state_count
347 ? request_state_indices[request_row]
348 : (request_state_indices == nullptr ? request_row : -1);
349 // V2 publishes -1 for CUDA-graph padding rows.
350 if (state_row < 0) {
351 for (int row = first_row; row < end_row; ++row) {
352 for (int i = threadIdx.x; i < top_k; i += blockDim.x) {
353 const int64_t index = static_cast<int64_t>(row) * top_k + i;
354 hot_indices[index] = -1;
355 if (attention_indices != nullptr) {
356 attention_indices[static_cast<int64_t>(row) * attention_row_stride +
357 i] = -1;
358 }
359 if (resolved_global_indices != nullptr) {
360 resolved_global_indices[index] = -1;
361 }
362 }
363 if (valid_counts != nullptr && threadIdx.x == 0) {
364 valid_counts[static_cast<int64_t>(row) * valid_count_stride] = 0;
365 }
366 if (swap_counts != nullptr && threadIdx.x == 0) {
367 swap_counts[row] = 0;
368 }
369 }
370 return;
371 }
372 const int tid = threadIdx.x;
373 const int warp_id = tid / kWarpSize;
374 const int lane_id = tid % kWarpSize;
375 const unsigned int lanes_before = ((unsigned int)1 << lane_id) - 1;
376
377 int32_t* row_dgi =
378 device_global_indices + static_cast<int64_t>(state_row) * region_stride;
379 int16_t* row_lru = lru_slots + static_cast<int64_t>(state_row) * hot_size;
380
381 // A union within max_union_rows (hash_size - 1) and within the rows' top-k
382 // leaves an empty slot, so every probe sequence ends. Use a slice sized to
383 // this request's rows so single-row requests initialize a small table.
384 const int table_size =
385 min(hash_size, kHashLoadInverse * (end_row - first_row) * top_k);
386
387 extern __shared__ char smem_raw[];
388 int32_t* s_hash_keys = reinterpret_cast<int32_t*>(smem_raw);
389 int32_t* s_hash_vals = s_hash_keys + hash_size;
390 int32_t* s_chunk_off = s_hash_vals + hash_size;
391 int32_t* s_evict_off = s_chunk_off + (num_buffer_chunks + 1);
392 int32_t* s_counters = s_evict_off + (num_buffer_chunks + 1);
393 unsigned int* s_done =
394 reinterpret_cast<unsigned int*>(s_counters + kResidencyCounters);
395 int16_t* s_lru_out = reinterpret_cast<int16_t*>(s_done + num_buffer_chunks);
396
397 for (int i = tid; i < table_size; i += blockDim.x) {
398 s_hash_keys[i] = kHashEmpty;
399 s_hash_vals[i] = INT32_MAX;
400 }
401 for (int i = tid; i < num_buffer_chunks + 1; i += blockDim.x) {
402 s_chunk_off[i] = 0;
403 s_evict_off[i] = 0;
404 }
405 if (tid < kResidencyCounters) {
406 s_counters[tid] = 0;
407 }
408 __syncthreads();
409
410 // Phase 1: translate every row's request-relative positions, resolve
411 // resident rows directly, and collect the union of host rows.
412 for (int row = first_row; row < end_row; ++row) {
413 const int32_t* row_topk =
414 global_indices + static_cast<int64_t>(row) * input_row_stride;
415 int32_t* row_out = hot_indices + static_cast<int64_t>(row) * top_k;
416 int32_t* row_attention =
417 attention_indices != nullptr
418 ? attention_indices +
419 static_cast<int64_t>(row) * attention_row_stride
420 : nullptr;
421 int32_t* row_miss = miss_mask != nullptr
422 ? miss_mask + static_cast<int64_t>(row) * top_k
423 : nullptr;
424 for (int i = tid; i < top_k; i += blockDim.x) {
425 int32_t resident_row;
426 const int32_t g = translate_topk_entry(
427 row_topk[i], request_row, source_block_table, resident_block_table,
428 host_rows, source_bt_stride, source_num_reqs, source_num_blocks,
429 source_block_size, resident_bt_stride, resident_num_reqs,
430 resident_num_blocks, resident_block_size, resident_null_block,
431 resident_row);
432 if (resolved_global_indices != nullptr) {
433 resolved_global_indices[static_cast<int64_t>(row) * top_k + i] = g;
434 }
435 if (resident_row >= 0 || g >= 0) atomicAdd(&s_counters[2], 1);
436 if (row_miss != nullptr) row_miss[i] = 0;
437 if (resident_row >= 0) {
438 store_hot_index(row_out, row_attention, i, resident_row, hot_block_size,
439 attention_block_stride);
440 } else if (g < 0) {
441 store_hot_index(row_out, row_attention, i, -1, hot_block_size,
442 attention_block_stride);
443 } else {
444 int h = hash_slot(g, table_size);
445 bool inserted = false;
446 for (int probe = 0; probe < table_size; ++probe) {
447 const int32_t old = atomicCAS(&s_hash_keys[h], kHashEmpty, g);
448 if (old == kHashEmpty) {
449 atomicAdd(&s_counters[1], 1);
450 inserted = true;
451 break;
452 }
453 if (old == g) {
454 inserted = true;
455 break;
456 }
457 h = next_slot(h, table_size);
458 }
459 if (inserted) {
460 atomicMin(&s_hash_vals[h], (row - first_row) * top_k + i);
461 } else {
462 // A full table: push the union count past the cap so the check
463 // below traps.
464 atomicAdd(&s_counters[1], hash_size);
465 }
466 }
467 }
468 __syncthreads();
469 if (tid == 0) {
470 if (valid_counts != nullptr) {
471 valid_counts[static_cast<int64_t>(row) * valid_count_stride] =
472 s_counters[2];
473 }
474 s_counters[2] = 0;
475 }
476 __syncthreads();
477 }
478 // The table and eviction slots are sized for max_union_rows (hash_size - 1);
479 // a larger union would never reach an empty probe slot or run past s_lru_out.
480 if (s_counters[1] >= hash_size) {
481 if (tid == 0) {
482 printf(
483 "HiSparse residency: request %d resolves %d host rows, above the "
484 "configured bound of %d\n",
485 request_row, s_counters[1], hash_size - 1);
486 }
487 __trap();
488 }
489 // Fully resident rows need only request-relative page translation. Avoid
490 // scanning or rewriting the hot LRU when no selected row can consult it.
491 if (s_counters[1] == 0) {
492 for (int row = first_row + tid; row < end_row; row += blockDim.x) {
493 if (swap_counts != nullptr) swap_counts[row] = 0;
494 }
495 return;
496 }
497
498 // Phase 2: walk hot slots in LRU order, classify hit / evictable, and
499 // compact them (hits forward, evictables backward) into s_lru_out. A hit
500 // records its slot on the union entry.
501 const int iters_buffer = (num_buffer_chunks + NUM_WARPS - 1) / NUM_WARPS;
502 int total_hit_count = 0;
503 int total_evict_count = 0;
504 for (int iter = 0; iter < iters_buffer; iter++) {
505 const int chunk_idx = warp_id + iter * NUM_WARPS;
506 const bool has_valid_chunk = chunk_idx < num_buffer_chunks;
507
508 const int pos = chunk_idx * kWarpSize + lane_id;
509 const bool has_valid_pos = has_valid_chunk && (pos < hot_size);
510 const int16_t slot = has_valid_pos ? row_lru[pos] : int16_t(-1);
511 // Corruption tripwire: lru/dgi are long-lived device state; if some
512 // external writer (e.g. stray RDMA into reused VRAM) corrupts a slot
513 // out of [0, region_stride), treat it as no-hit so it degrades to a
514 // re-miss instead of an unbounded dgi read (phase 3 bounds the write
515 // side).
516 const int32_t cached_g =
517 (slot >= 0 && slot < region_stride) ? row_dgi[slot] : -1;
518
519 bool is_hit = false;
520 if (cached_g >= 0) {
521 int h = hash_slot(cached_g, table_size);
522 while (true) {
523 const int32_t k = s_hash_keys[h];
524 if (k == cached_g) {
525 s_hash_vals[h] = kEntryHit | slot;
526 is_hit = true;
527 break;
528 }
529 if (k == kHashEmpty) break;
530 h = next_slot(h, table_size);
531 }
532 }
533 const bool is_evictable = has_valid_pos && !is_hit;
534
535 int local_hit_off = 0;
536 int local_evict_off = 0;
537 if (has_valid_chunk) {
538 const unsigned int hit_mask = __ballot_sync(0xFFFFFFFF, is_hit);
539 const unsigned int evict_mask = __ballot_sync(0xFFFFFFFF, is_evictable);
540 local_hit_off = __popc(hit_mask & lanes_before);
541 local_evict_off = __popc(evict_mask & lanes_before);
542 if (lane_id == 0) {
543 s_chunk_off[chunk_idx + 1] = __popc(hit_mask);
544 s_evict_off[chunk_idx + 1] = __popc(evict_mask);
545 }
546 }
547 __syncthreads();
548
549 if (warp_id == 0) {
550 total_hit_count =
551 warp_inclusive_scan(s_chunk_off, lane_id, chunk_idx + 1,
552 num_buffer_chunks + 1, total_hit_count);
553 total_evict_count =
554 warp_inclusive_scan(s_evict_off, lane_id, chunk_idx + 1,
555 num_buffer_chunks + 1, total_evict_count);
556 if (tid == 0) {
557 s_counters[0] = total_hit_count;
558 }
559 }
560 __syncthreads();
561
562 if (is_hit) {
563 const int off = s_chunk_off[chunk_idx] + local_hit_off;
564 s_lru_out[off] = slot;
565 }
566 if (is_evictable) {
567 const int off = s_evict_off[chunk_idx] + local_evict_off;
568 s_lru_out[hot_size - 1 - off] = slot;
569 }
570 }
571 __syncthreads();
572
573 for (int i = tid; i < num_buffer_chunks + 1; i += blockDim.x) {
574 s_chunk_off[i] = 0;
575 }
576 __syncthreads();
577
578 // Phase 3: walk the rows' positions in (row, top-k) order; the first
579 // reference to a union entry no slot holds is a miss. Assign misses
580 // eviction slots (oldest first) and record the new ownership in
581 // device_global_indices. Swaps fill the rows' swap segments in order; the
582 // union never exceeds their combined capacity, and position chunks never
583 // exceed buffer chunks because hot_size covers every row's top-k.
584 const int num_positions = (end_row - first_row) * top_k;
585 const int num_position_chunks = (num_positions + kWarpSize - 1) / kWarpSize;
586 const int iters_position = (num_position_chunks + NUM_WARPS - 1) / NUM_WARPS;
587 int miss_running_total = 0;
588 int entry_hits = 0;
589 int entry_misses = 0;
590 for (int iter = 0; iter < iters_position; iter++) {
591 const int chunk_idx = warp_id + iter * NUM_WARPS;
592 const bool has_valid_chunk = chunk_idx < num_position_chunks;
593
594 const int position = chunk_idx * kWarpSize + lane_id;
595 int32_t g = -1;
596 int h = -1;
597 int32_t entry = 0;
598 bool is_miss = false;
599 if (has_valid_chunk && position < num_positions) {
600 const int row = first_row + position / top_k;
601 int32_t resident_row;
602 g = translate_topk_entry(
603 global_indices[static_cast<int64_t>(row) * input_row_stride +
604 position % top_k],
605 request_row, source_block_table, resident_block_table, host_rows,
606 source_bt_stride, source_num_reqs, source_num_blocks,
607 source_block_size, resident_bt_stride, resident_num_reqs,
608 resident_num_blocks, resident_block_size, resident_null_block,
609 resident_row);
610 if (resident_row < 0 && g >= 0) {
611 h = hash_slot(g, table_size);
612 while (s_hash_keys[h] != g) {
613 h = next_slot(h, table_size);
614 }
615 entry = s_hash_vals[h];
616 is_miss = entry == position;
617 }
618 }
619
620 int local_miss_off = 0;
621 if (has_valid_chunk) {
622 const unsigned int miss_mask_bits = __ballot_sync(0xFFFFFFFF, is_miss);
623 local_miss_off = __popc(miss_mask_bits & lanes_before);
624 if (lane_id == 0) {
625 s_chunk_off[chunk_idx + 1] = __popc(miss_mask_bits);
626 }
627 }
628 __syncthreads();
629
630 if (warp_id == 0) {
631 miss_running_total =
632 warp_inclusive_scan(s_chunk_off, lane_id, chunk_idx + 1,
633 num_position_chunks + 1, miss_running_total);
634 if (tid == 0) {
635 s_counters[3] = miss_running_total;
636 }
637 }
638 __syncthreads();
639
640 if (is_miss) {
641 const int m = s_chunk_off[chunk_idx] + local_miss_off;
642 const int16_t evict_slot = s_lru_out[hot_size - 1 - m];
643 const int64_t compact_index = static_cast<int64_t>(first_row) * top_k + m;
644 if (evict_slot < 0 || evict_slot >= region_stride) {
645 // Corruption tripwire: an out-of-range slot (corrupted lru state,
646 // see phase 2) must not become a hot-cache/dgi write. Resolve the
647 // entry as invalid (-1, masked by attention); it re-misses on a later
648 // step, and its copy is skipped.
649 s_hash_vals[h] = kEntryInvalid;
650 if (swap_host_physical_rows != nullptr) {
651 swap_host_physical_rows[compact_index] = g;
652 swap_device_physical_rows[compact_index] = -1;
653 }
654 } else {
655 s_hash_vals[h] = kEntryMiss | evict_slot;
656 if (swap_host_physical_rows != nullptr) {
657 swap_host_physical_rows[compact_index] = g;
658 swap_device_physical_rows[compact_index] =
659 static_cast<int32_t>(get_physical_hot_row(
660 hot_block_table, request_row, hot_table_stride,
661 hot_block_size, evict_slot));
662 }
663 row_dgi[evict_slot] = g;
664 }
665 entry = s_hash_vals[h];
666 }
667
668 // Hits, first references and references to entries resolved in an
669 // earlier chunk write their hot index now; later references to an entry
670 // resolved in this same chunk pass (only across rows) are left to phase 4.
671 const bool resolved =
672 h >= 0 && (entry & (kEntryHit | kEntryMiss | kEntryInvalid));
673 if (resolved) {
674 write_entry_index(
675 entry, first_row + position / top_k, position % top_k, top_k,
676 hot_indices, attention_indices, attention_row_stride, miss_mask,
677 hot_block_table, request_row, hot_table_stride, hot_block_size,
678 attention_block_stride, is_miss, entry_hits, entry_misses);
679 }
680 if (has_valid_chunk) {
681 const unsigned int done_bits = __ballot_sync(0xFFFFFFFF, resolved);
682 if (lane_id == 0) {
683 s_done[chunk_idx] = done_bits;
684 }
685 }
686 }
687 __syncthreads();
688
689 const int total_hits = s_counters[0];
690 const int total_misses = s_counters[3];
691 if (swap_counts != nullptr) {
692 for (int row = first_row + tid; row < end_row; row += blockDim.x) {
693 const int remaining = total_misses - (row - first_row) * top_k;
694 swap_counts[row] = max(0, min(top_k, remaining));
695 }
696 }
697
698 // Phase 4: references phase 3 left unresolved (later references across rows
699 // to entries loaded in the same chunk pass) map onto the union's slots.
700 // Single-row requests resolve everything in phase 3.
701 if (end_row - first_row > 1) {
702 for (int position = tid; position < num_positions; position += blockDim.x) {
703 if (s_done[position / kWarpSize] & (1u << (position % kWarpSize))) {
704 continue;
705 }
706 const int row = first_row + position / top_k;
707 int32_t resident_row;
708 const int32_t g = translate_topk_entry(
709 global_indices[static_cast<int64_t>(row) * input_row_stride +
710 position % top_k],
711 request_row, source_block_table, resident_block_table, host_rows,
712 source_bt_stride, source_num_reqs, source_num_blocks,
713 source_block_size, resident_bt_stride, resident_num_reqs,
714 resident_num_blocks, resident_block_size, resident_null_block,
715 resident_row);
716 if (resident_row >= 0 || g < 0) continue;
717 int h = hash_slot(g, table_size);
718 while (s_hash_keys[h] != g) {
719 h = next_slot(h, table_size);
720 }
721 write_entry_index(
722 s_hash_vals[h], row, position % top_k, top_k, hot_indices,
723 attention_indices, attention_row_stride, miss_mask, hot_block_table,
724 request_row, hot_table_stride, hot_block_size, attention_block_stride,
725 false, entry_hits, entry_misses);
726 }
727 }
728 if (stats != nullptr) {
729 atomicAdd(&s_counters[4], entry_hits);
730 atomicAdd(&s_counters[2], entry_misses);
731 __syncthreads();
732 if (tid == 0) {
733 atomicAdd(&stats[0], static_cast<unsigned long long>(s_counters[4]));
734 atomicAdd(&stats[1], static_cast<unsigned long long>(s_counters[2]));
735 }
736 }
737
738 // Phase 5: write back the LRU order: stale evictables at the front,
739 // freshly loaded misses next, then hits at MRU.
740 const int total_evictable = hot_size - total_hits;
741 const int remaining_evictable = total_evictable - total_misses;
742 for (int i = tid; i < hot_size; i += blockDim.x) {
743 if (i < remaining_evictable) {
744 row_lru[i] = s_lru_out[hot_size - 1 - total_misses - i];
745 } else if (i < remaining_evictable + total_misses) {
746 row_lru[i] = s_lru_out[hot_size - 1 - (i - remaining_evictable)];
747 } else {
748 row_lru[i] = s_lru_out[i - remaining_evictable - total_misses];
749 }
750 }
751 }
752
753 // Shared-layer plan replay. Given a plan (hot_indices + miss_mask) already
754 // computed by the group's index-producing layer, gather THIS
755 // layer's own missed KV rows into the planned hot slots. No LRU resolution:
756 // index-sharing shared layers see identical global_indices/hot_indices, so the
757 // slot assignment is identical -- only the per-layer bytes differ. Fixed shape
758 // (num_rows x top_k), so it is CUDA-graph-capture safe.
759 __global__ void hisparse_gather_plan_kernel(
760 const char* __restrict__ host_cache, // [host_rows, row_bytes]
761 char* __restrict__ hot_cache, // [hot_rows, row_bytes]
762 const int32_t* __restrict__ global_indices, // [num_rows, top_k]
763 const int32_t* __restrict__ hot_indices, // [num_rows, top_k] abs hot rows
764 const int32_t* __restrict__ miss_mask, // [num_rows, top_k]
765 int32_t* __restrict__ attention_indices, // [num_rows, top_k]
766 const int32_t* __restrict__ request_state_indices, // [num_rows] or nullptr
767 const int64_t host_rows, const int64_t hot_rows, const int64_t row_bytes,
768 const int64_t hot_block_stride, const int32_t hot_block_size,
769 const int32_t top_k, const int64_t attention_block_stride) {
770 const int NUM_WARPS = blockDim.x / kWarpSize;
771 // Columns are interleaved across gridDim.y blocks per row so few-row
772 // launches (local-prefill staging's single-row layout, small decode
773 // batches) still fill the device with outstanding host reads instead of
774 // starving on one block per row.
775 const int row = blockIdx.x;
776 const bool is_padding =
777 request_state_indices != nullptr && request_state_indices[row] < 0;
778 const int warp_id = threadIdx.x / kWarpSize;
779 const int lane_id = threadIdx.x % kWarpSize;
780 const int col_start = blockIdx.y * NUM_WARPS + warp_id;
781 const int col_stride = gridDim.y * NUM_WARPS;
782 const int64_t base = static_cast<int64_t>(row) * top_k;
783 for (int col = col_start; col < top_k; col += col_stride) {
784 const int32_t dst = hot_indices[base + col];
785 if (lane_id == 0 && attention_indices != nullptr) {
786 attention_indices[base + col] =
787 is_padding
788 ? -1
789 : (dst < 0 ? -1
790 : (dst / hot_block_size) * attention_block_stride +
791 dst % hot_block_size);
792 }
793 if (is_padding) {
794 continue;
795 }
796 if (miss_mask[base + col] == 0) {
797 continue;
798 }
799 const int32_t g = global_indices[base + col];
800 if (g < 0 || dst < 0 || dst >= hot_rows) {
801 continue;
802 }
803 if (g < host_rows) {
804 copy_row_warp(lane_id, host_cache + static_cast<int64_t>(g) * row_bytes,
805 cache_row_ptr(hot_cache, dst, hot_block_size,
806 hot_block_stride, row_bytes),
807 row_bytes);
808 } else {
809 // No source row for g: zero the planned slot rather than serving
810 // whatever bytes it held (see the swap-in kernel's phase 5).
811 zero_cache_row_warp(lane_id, hot_cache, dst, hot_block_size,
812 hot_block_stride, row_bytes);
813 }
814 }
815 }
816
817 // Copy the compact swap rows produced by the residency resolver.
818 __global__ void hisparse_gather_compact_kernel(
819 const char* __restrict__ host_cache, char* __restrict__ hot_cache,
820 const int32_t* __restrict__ miss_global_indices,
821 const int32_t* __restrict__ miss_hot_indices,
822 const int32_t* __restrict__ miss_counts, const int64_t host_rows,
823 const int64_t hot_rows, const int64_t row_bytes,
824 const int64_t hot_block_stride, const int32_t hot_block_size,
825 const int32_t top_k) {
826 const int NUM_WARPS = blockDim.x / kWarpSize;
827 const int row = blockIdx.x;
828 const int warp_id = threadIdx.x / kWarpSize;
829 const int lane_id = threadIdx.x % kWarpSize;
830 const int miss_count = min(max(miss_counts[row], 0), top_k);
831 const int col_start = blockIdx.y * NUM_WARPS + warp_id;
832 const int col_stride = gridDim.y * NUM_WARPS;
833 const int64_t base = static_cast<int64_t>(row) * top_k;
834 for (int col = col_start; col < miss_count; col += col_stride) {
835 const int32_t g = miss_global_indices[base + col];
836 const int32_t dst = miss_hot_indices[base + col];
837 if (g < 0 || dst < 0 || dst >= hot_rows) {
838 continue;
839 }
840 if (g < host_rows) {
841 copy_row_warp(lane_id, host_cache + static_cast<int64_t>(g) * row_bytes,
842 cache_row_ptr(hot_cache, dst, hot_block_size,
843 hot_block_stride, row_bytes),
844 row_bytes);
845 } else {
846 zero_cache_row_warp(lane_id, hot_cache, dst, hot_block_size,
847 hot_block_stride, row_bytes);
848 }
849 }
850 }
851
852 __global__ void hisparse_invalidate_written_slots_kernel(
853 int32_t* __restrict__ device_global_indices,
854 const int32_t* __restrict__ request_state_indices,
855 const int32_t* __restrict__ req_id_per_token,
856 const int64_t* __restrict__ written_slots, const int64_t num_tokens,
857 const int64_t num_request_ids, const int64_t num_state_rows,
858 const int64_t region_stride) {
859 const int64_t token_idx = blockIdx.x;
860 if (token_idx >= num_tokens) {
861 return;
862 }
863 const int32_t req_idx = req_id_per_token[token_idx];
864 if (req_idx < 0 || req_idx >= num_request_ids) {
865 return;
866 }
867 const int32_t state_idx = request_state_indices[req_idx];
868 const int64_t written_slot = written_slots[token_idx];
869 if (state_idx < 0 || state_idx >= num_state_rows || written_slot < 0) {
870 return;
871 }
872 int32_t* row = device_global_indices + state_idx * region_stride;
873 for (int64_t offset = threadIdx.x; offset < region_stride;
874 offset += blockDim.x) {
875 if (row[offset] == written_slot) {
876 row[offset] = -1;
877 }
878 }
879 }
880
881 int64_t check_2d_rows(const torch::stable::Tensor& t, const char* name,
882 int64_t row_bytes) {
883 STD_TORCH_CHECK(t.dim() == 2, name, " must be 2D");
884 STD_TORCH_CHECK(t.is_contiguous(), name, " must be contiguous");
885 STD_TORCH_CHECK(t.size(1) * t.element_size() == row_bytes, name,
886 " row width mismatch");
887 return t.size(0);
888 }
889
890 } // namespace
891
892 void hisparse_invalidate_written_slots(
893 torch::stable::Tensor& device_global_indices,
894 torch::stable::Tensor const& request_state_indices,
895 torch::stable::Tensor const& req_id_per_token,
896 torch::stable::Tensor const& written_slots) {
897 STD_TORCH_CHECK(device_global_indices.is_cuda() &&
898 request_state_indices.is_cuda() &&
899 req_id_per_token.is_cuda() && written_slots.is_cuda(),
900 "HiSparse invalidation tensors must be on CUDA");
901 STD_TORCH_CHECK(
902 device_global_indices.scalar_type() ==
903 torch::headeronly::ScalarType::Int &&
904 device_global_indices.dim() == 2 &&
905 device_global_indices.is_contiguous(),
906 "device_global_indices must be a contiguous 2D int32 CUDA tensor");
907 STD_TORCH_CHECK(
908 request_state_indices.scalar_type() ==
909 torch::headeronly::ScalarType::Int &&
910 request_state_indices.dim() == 1 &&
911 request_state_indices.is_contiguous(),
912 "request_state_indices must be a contiguous 1D int32 CUDA tensor");
913 STD_TORCH_CHECK(
914 req_id_per_token.scalar_type() == torch::headeronly::ScalarType::Int &&
915 req_id_per_token.dim() == 1 && req_id_per_token.is_contiguous(),
916 "req_id_per_token must be a contiguous 1D int32 CUDA tensor");
917 STD_TORCH_CHECK(
918 written_slots.scalar_type() == torch::headeronly::ScalarType::Long &&
919 written_slots.dim() == 1 && written_slots.is_contiguous(),
920 "written_slots must be a contiguous 1D int64 CUDA tensor");
921 STD_TORCH_CHECK(req_id_per_token.numel() == written_slots.numel(),
922 "req_id_per_token and written_slots must have equal length");
923 const int device_index = device_global_indices.get_device_index();
924 STD_TORCH_CHECK(
925 request_state_indices.get_device_index() == device_index &&
926 req_id_per_token.get_device_index() == device_index &&
927 written_slots.get_device_index() == device_index,
928 "HiSparse invalidation tensors must be on the same CUDA device");
929
930 const int64_t num_tokens = written_slots.numel();
931 const int64_t num_state_rows = device_global_indices.size(0);
932 const int64_t region_stride = device_global_indices.size(1);
933 if (num_tokens == 0 || num_state_rows == 0 || region_stride == 0) {
934 return;
935 }
936 STD_TORCH_CHECK(num_tokens <= INT32_MAX,
937 "HiSparse invalidation grid exceeds CUDA limits");
938
939 constexpr int kBlockSize = 256;
940 const torch::stable::accelerator::DeviceGuard device_guard(device_index);
941 const cudaStream_t stream = get_current_cuda_stream();
942 hisparse_invalidate_written_slots_kernel<<<static_cast<int>(num_tokens),
943 kBlockSize, 0, stream>>>(
944 device_global_indices.mutable_data_ptr<int32_t>(),
945 request_state_indices.const_data_ptr<int32_t>(),
946 req_id_per_token.const_data_ptr<int32_t>(),
947 written_slots.const_data_ptr<int64_t>(), num_tokens,
948 request_state_indices.numel(), num_state_rows, region_stride);
949 const cudaError_t launch_error = cudaGetLastError();
950 STD_TORCH_CHECK(launch_error == cudaSuccess,
951 "HiSparse invalidation kernel launch failed: ",
952 cudaGetErrorString(launch_error));
953 }
954
955 void hisparse_resolve_residency(
956 torch::stable::Tensor const& host_cache, torch::stable::Tensor& hot_cache,
957 torch::stable::Tensor const& hot_block_table,
958 torch::stable::Tensor const& global_indices,
959 torch::stable::Tensor& hot_indices,
960 torch::stable::Tensor& device_global_indices,
961 torch::stable::Tensor& lru_slots,
962 std::optional<torch::stable::Tensor> const& request_state_indices,
963 int64_t region_stride, int64_t max_union_rows,
964 std::optional<torch::stable::Tensor> const& miss_mask,
965 std::optional<torch::stable::Tensor> const& stats,
966 std::optional<torch::stable::Tensor> const& attention_indices,
967 int64_t attention_block_stride,
968 std::optional<torch::stable::Tensor> const& request_ids,
969 std::optional<torch::stable::Tensor> const& source_block_table,
970 int64_t source_block_size,
971 std::optional<torch::stable::Tensor> const& resolved_global_indices,
972 std::optional<torch::stable::Tensor> const& valid_counts,
973 std::optional<torch::stable::Tensor> const& swap_host_physical_rows,
974 std::optional<torch::stable::Tensor> const& swap_device_physical_rows,
975 std::optional<torch::stable::Tensor> const& swap_counts,
976 std::optional<torch::stable::Tensor> const& resident_block_table,
977 int64_t resident_block_size, int64_t resident_null_block) {
978 STD_TORCH_CHECK(
979 host_cache.device().is_cpu() && is_pinned_cpu_tensor(host_cache),
980 "host_cache must be pinned CPU memory");
981 STD_TORCH_CHECK(hot_cache.is_cuda(), "hot_cache must be on CUDA");
982 STD_TORCH_CHECK(
983 hot_block_table.is_cuda() &&
984 hot_block_table.scalar_type() == torch::headeronly::ScalarType::Int &&
985 hot_block_table.dim() == 2,
986 "hot_block_table must be a 2D int32 CUDA tensor");
987 STD_TORCH_CHECK(global_indices.is_cuda() && hot_indices.is_cuda() &&
988 device_global_indices.is_cuda() && lru_slots.is_cuda(),
989 "index tensors must be on CUDA");
990 STD_TORCH_CHECK(
991 global_indices.scalar_type() == torch::headeronly::ScalarType::Int &&
992 hot_indices.scalar_type() == torch::headeronly::ScalarType::Int,
993 "global_indices/hot_indices must be int32");
994 STD_TORCH_CHECK(
995 device_global_indices.scalar_type() == torch::headeronly::ScalarType::Int,
996 "device_global_indices must be int32");
997 STD_TORCH_CHECK(
998 lru_slots.scalar_type() == torch::headeronly::ScalarType::Short,
999 "lru_slots must be int16");
1000 STD_TORCH_CHECK(global_indices.dim() == 2 && global_indices.stride(1) == 1,
1001 "global_indices must be row-major 2D");
1002 const int64_t num_rows = global_indices.size(0);
1003 STD_TORCH_CHECK(num_rows >= 0 && num_rows <= INT32_MAX,
1004 "num_rows must fit the CUDA grid");
1005 STD_TORCH_CHECK(hot_indices.size(0) == num_rows &&
1006 hot_indices.size(1) == global_indices.size(1) &&
1007 hot_indices.is_contiguous(),
1008 "hot_indices must have one contiguous row per launch row");
1009 STD_TORCH_CHECK(
1010 device_global_indices.dim() == 2 && device_global_indices.is_contiguous(),
1011 "device_global_indices must be contiguous 2D");
1012 STD_TORCH_CHECK(
1013 lru_slots.dim() == 2 &&
1014 lru_slots.size(0) == device_global_indices.size(0) &&
1015 lru_slots.is_contiguous(),
1016 "lru_slots must be contiguous with one row per request state");
1017 STD_TORCH_CHECK(hot_cache.dim() == 3,
1018 "hot_cache must be [num_blocks, block_size, row_width]");
1019 const int64_t row_bytes = hot_cache.size(-1) * hot_cache.element_size();
1020 STD_TORCH_CHECK(row_bytes % 16 == 0, "KV rows must be 16-byte aligned");
1021 STD_TORCH_CHECK(hot_cache.stride(1) * hot_cache.element_size() == row_bytes,
1022 "hot-cache rows must be contiguous");
1023 const int64_t hot_block_size = hot_cache.size(1);
1024 const int64_t hot_rows = hot_cache.size(0) * hot_block_size;
1025 const int64_t hot_block_stride =
1026 hot_cache.stride(0) * hot_cache.element_size();
1027 const int64_t host_rows = check_2d_rows(host_cache, "host_cache", row_bytes);
1028 const auto launch_rows = static_cast<int32_t>(num_rows);
1029 const auto top_k = static_cast<int32_t>(global_indices.size(1));
1030 const auto hot_size = static_cast<int32_t>(lru_slots.size(1));
1031 STD_TORCH_CHECK(hot_size >= top_k, "hot buffer size must be >= top_k");
1032 STD_TORCH_CHECK(hot_size <= 32768, "hot buffer size must fit int16 slots");
1033 STD_TORCH_CHECK(region_stride == hot_size,
1034 "region_stride must match the LRU size");
1035 STD_TORCH_CHECK(device_global_indices.size(1) == region_stride,
1036 "device_global_indices must cover the full hot region");
1037 STD_TORCH_CHECK(hot_block_table.size(1) >=
1038 (region_stride + hot_block_size - 1) / hot_block_size,
1039 "hot_block_table has too few columns");
1040 STD_TORCH_CHECK(hot_rows < INT32_MAX, "hot indices must fit int32");
1041
1042 const int32_t* request_ids_ptr = nullptr;
1043 const int32_t* source_block_table_ptr = nullptr;
1044 int64_t source_bt_stride = 0;
1045 int32_t source_num_reqs = 0;
1046 int32_t source_num_blocks = 0;
1047 STD_TORCH_CHECK(
1048 request_ids.has_value() == source_block_table.has_value(),
1049 "request_ids and source_block_table must be provided together");
1050 if (source_block_table.has_value()) {
1051 auto const& req = request_ids.value();
1052 auto const& table = source_block_table.value();
1053 STD_TORCH_CHECK(
1054 req.is_cuda() &&
1055 req.scalar_type() == torch::headeronly::ScalarType::Int &&
1056 req.numel() >= launch_rows && req.is_contiguous(),
1057 "request_ids must be contiguous int32 on CUDA with one entry per row");
1058 STD_TORCH_CHECK(
1059 table.is_cuda() &&
1060 table.scalar_type() == torch::headeronly::ScalarType::Int &&
1061 table.dim() == 2 && table.stride(1) == 1,
1062 "source_block_table must be a row-major 2D int32 CUDA tensor");
1063 STD_TORCH_CHECK(source_block_size > 0,
1064 "source_block_size must be positive");
1065 request_ids_ptr = req.const_data_ptr<int32_t>();
1066 source_block_table_ptr = table.const_data_ptr<int32_t>();
1067 source_bt_stride = table.stride(0);
1068 source_num_reqs = static_cast<int32_t>(table.size(0));
1069 source_num_blocks = static_cast<int32_t>(table.size(1));
1070 }
1071 const int32_t required_hot_rows =
1072 request_ids_ptr != nullptr ? source_num_reqs : launch_rows;
1073 STD_TORCH_CHECK(hot_block_table.size(0) >= required_hot_rows,
1074 "hot_block_table has too few rows");
1075
1076 const int32_t* resident_block_table_ptr = nullptr;
1077 int64_t resident_bt_stride = 0;
1078 int32_t resident_num_reqs = 0;
1079 int32_t resident_num_blocks = 0;
1080 if (resident_block_table.has_value()) {
1081 auto const& table = resident_block_table.value();
1082 STD_TORCH_CHECK(
1083 source_block_table.has_value() && request_ids.has_value(),
1084 "resident lookup requires request_ids and source_block_table");
1085 STD_TORCH_CHECK(
1086 table.is_cuda() &&
1087 table.scalar_type() == torch::headeronly::ScalarType::Int &&
1088 table.dim() == 2 && table.stride(1) == 1,
1089 "resident_block_table must be a row-major 2D int32 CUDA tensor");
1090 STD_TORCH_CHECK(resident_block_size == hot_block_size,
1091 "resident and hot block sizes must match");
1092 STD_TORCH_CHECK(resident_null_block >= 0,
1093 "resident null block must be non-negative");
1094 resident_block_table_ptr = table.const_data_ptr<int32_t>();
1095 resident_bt_stride = table.stride(0);
1096 resident_num_reqs = static_cast<int32_t>(table.size(0));
1097 resident_num_blocks = static_cast<int32_t>(table.size(1));
1098 }
1099
1100 int32_t* resolved_global_indices_ptr = nullptr;
1101 if (resolved_global_indices.has_value()) {
1102 auto const& resolved = resolved_global_indices.value();
1103 STD_TORCH_CHECK(
1104 resolved.is_cuda() &&
1105 resolved.scalar_type() == torch::headeronly::ScalarType::Int &&
1106 resolved.dim() == 2 && resolved.size(0) == launch_rows &&
1107 resolved.size(1) == global_indices.size(1) &&
1108 resolved.is_contiguous(),
1109 "resolved_global_indices must be contiguous int32 matching indices");
1110 resolved_global_indices_ptr = resolved.mutable_data_ptr<int32_t>();
1111 }
1112
1113 int32_t* valid_counts_ptr = nullptr;
1114 if (valid_counts.has_value()) {
1115 auto const& counts = valid_counts.value();
1116 STD_TORCH_CHECK(
1117 counts.is_cuda() &&
1118 counts.scalar_type() == torch::headeronly::ScalarType::Int &&
1119 counts.dim() == 1 && counts.size(0) == launch_rows,
1120 "valid_counts must be int32 on CUDA with one entry per row");
1121 valid_counts_ptr = counts.mutable_data_ptr<int32_t>();
1122 }
1123
1124 int32_t* swap_host_physical_rows_ptr = nullptr;
1125 int32_t* swap_device_physical_rows_ptr = nullptr;
1126 int32_t* swap_counts_ptr = nullptr;
1127 const bool has_compact_swaps = swap_host_physical_rows.has_value();
1128 STD_TORCH_CHECK(has_compact_swaps == swap_device_physical_rows.has_value() &&
1129 has_compact_swaps == swap_counts.has_value(),
1130 "compact swap tensors must be provided together");
1131 if (has_compact_swaps) {
1132 auto const& globals = swap_host_physical_rows.value();
1133 auto const& hots = swap_device_physical_rows.value();
1134 auto const& counts = swap_counts.value();
1135 STD_TORCH_CHECK(
1136 globals.is_cuda() && hots.is_cuda() && counts.is_cuda() &&
1137 globals.scalar_type() == torch::headeronly::ScalarType::Int &&
1138 hots.scalar_type() == torch::headeronly::ScalarType::Int &&
1139 counts.scalar_type() == torch::headeronly::ScalarType::Int &&
1140 globals.dim() == 2 && hots.dim() == 2 &&
1141 globals.size(0) == launch_rows &&
1142 globals.size(1) == global_indices.size(1) &&
1143 hots.size(0) == launch_rows &&
1144 hots.size(1) == global_indices.size(1) &&
1145 counts.numel() >= launch_rows && globals.is_contiguous() &&
1146 hots.is_contiguous() && counts.is_contiguous(),
1147 "compact swaps must be contiguous int32 matching indices");
1148 swap_host_physical_rows_ptr = globals.mutable_data_ptr<int32_t>();
1149 swap_device_physical_rows_ptr = hots.mutable_data_ptr<int32_t>();
1150 swap_counts_ptr = counts.mutable_data_ptr<int32_t>();
1151 }
1152
1153 const int32_t* request_state_ptr = nullptr;
1154 int32_t request_state_count = 0;
1155 if (request_state_indices.has_value()) {
1156 auto const& state_indices = request_state_indices.value();
1157 STD_TORCH_CHECK(
1158 state_indices.is_cuda() &&
1159 state_indices.scalar_type() == torch::headeronly::ScalarType::Int &&
1160 state_indices.dim() == 1 && state_indices.is_contiguous() &&
1161 state_indices.numel() <= INT32_MAX,
1162 "request_state_indices must be contiguous 1D int32 on CUDA");
1163 request_state_ptr = state_indices.const_data_ptr<int32_t>();
1164 request_state_count = static_cast<int32_t>(state_indices.numel());
1165 } else {
1166 STD_TORCH_CHECK(device_global_indices.size(0) >= launch_rows,
1167 "device_global_indices has too few rows");
1168 }
1169
1170 // Optional output: 1 at columns requiring a host-to-device swap, 0 elsewhere.
1171 int32_t* miss_mask_ptr = nullptr;
1172 if (miss_mask.has_value()) {
1173 auto const& mm = miss_mask.value();
1174 STD_TORCH_CHECK(
1175 mm.is_cuda() &&
1176 mm.scalar_type() == torch::headeronly::ScalarType::Int &&
1177 mm.dim() == 2 && mm.is_contiguous() && mm.size(0) == launch_rows &&
1178 mm.size(1) == global_indices.size(1),
1179 "miss_mask must be a contiguous int32 CUDA tensor matching "
1180 "global_indices");
1181 miss_mask_ptr = mm.mutable_data_ptr<int32_t>();
1182 }
1183
1184 unsigned long long* stats_ptr = nullptr;
1185 if (stats.has_value()) {
1186 auto const& st = stats.value();
1187 STD_TORCH_CHECK(
1188 st.is_cuda() && st.is_contiguous() && st.dim() == 1 &&
1189 st.scalar_type() == torch::headeronly::ScalarType::UInt64 &&
1190 st.numel() == 2,
1191 "stats must be a contiguous two-element uint64 CUDA tensor");
1192 stats_ptr = static_cast<unsigned long long*>(st.mutable_data_ptr());
1193 }
1194
1195 int32_t* attention_indices_ptr = nullptr;
1196 if (attention_indices.has_value()) {
1197 auto const& indices = attention_indices.value();
1198 STD_TORCH_CHECK(
1199 indices.is_cuda() &&
1200 indices.scalar_type() == torch::headeronly::ScalarType::Int &&
1201 indices.dim() == 2 && indices.size(0) == launch_rows &&
1202 indices.stride(1) == 1 && indices.size(1) == global_indices.size(1),
1203 "attention_indices must be row-major int32 matching global_indices");
1204 STD_TORCH_CHECK(attention_block_stride >= hot_block_size,
1205 "attention block stride must cover one hot block");
1206 attention_indices_ptr = indices.mutable_data_ptr<int32_t>();
1207 }
1208
1209 if (launch_rows == 0 || top_k == 0) {
1210 return;
1211 }
1212
1213 constexpr int kBlockSize = 1024;
1214 STD_TORCH_CHECK(max_union_rows > 0 && max_union_rows <= hot_size,
1215 "max_union_rows must be in [1, hot_size], got ",
1216 max_union_rows);
1217 // One spare entry above the union bound keeps every probe sequence finite.
1218 const int hash_size = static_cast<int>(max_union_rows) + 1;
1219 const int num_buffer_chunks = (hot_size + kWarpSize - 1) / kWarpSize;
1220 const size_t smem_bytes =
1221 sizeof(int32_t) * (2 * hash_size + 2 * (num_buffer_chunks + 1) +
1222 kResidencyCounters + num_buffer_chunks) +
1223 sizeof(int16_t) * hot_size;
1224
1225 const torch::stable::accelerator::DeviceGuard device_guard(
1226 hot_cache.get_device_index());
1227 int max_smem_bytes = 0;
1228 STD_TORCH_CHECK(cudaDeviceGetAttribute(
1229 &max_smem_bytes, cudaDevAttrMaxSharedMemoryPerBlockOptin,
1230 hot_cache.get_device_index()) == cudaSuccess,
1231 "failed to query shared memory per block");
1232 STD_TORCH_CHECK(smem_bytes <= static_cast<size_t>(max_smem_bytes),
1233 "HiSparse device_buffer_size=", hot_size, " needs ",
1234 smem_bytes,
1235 " bytes of shared memory to resolve residency, "
1236 "but the device allows ",
1237 max_smem_bytes,
1238 "; lower device_buffer_size or the number of speculative "
1239 "tokens.");
1240 const cudaStream_t stream = get_current_cuda_stream();
1241 const int64_t attention_row_stride =
1242 attention_indices.has_value() ? attention_indices.value().stride(0) : 0;
1243 const int64_t valid_count_stride =
1244 valid_counts.has_value() ? valid_counts.value().stride(0) : 0;
1245 auto kernel = hisparse_resolve_residency_kernel;
1246 if (smem_bytes > 48 * 1024) {
1247 const cudaError_t attribute_error = cudaFuncSetAttribute(
1248 kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, smem_bytes);
1249 STD_TORCH_CHECK(attribute_error == cudaSuccess,
1250 "failed to configure HiSparse swap-in shared memory: ",
1251 cudaGetErrorString(attribute_error));
1252 }
1253 kernel<<<launch_rows, kBlockSize, smem_bytes, stream>>>(
1254 hot_block_table.const_data_ptr<int32_t>(),
1255 global_indices.const_data_ptr<int32_t>(), request_ids_ptr,
1256 source_block_table_ptr, resident_block_table_ptr,
1257 resolved_global_indices_ptr, valid_counts_ptr,
1258 swap_host_physical_rows_ptr, swap_device_physical_rows_ptr,
1259 swap_counts_ptr, hot_indices.mutable_data_ptr<int32_t>(),
1260 attention_indices_ptr, miss_mask_ptr,
1261 device_global_indices.mutable_data_ptr<int32_t>(),
1262 lru_slots.mutable_data_ptr<int16_t>(), stats_ptr, request_state_ptr,
1263 request_state_count, host_rows, hot_block_table.stride(0), hot_block_size,
1264 top_k, hot_size, hash_size, region_stride, attention_block_stride,
1265 source_bt_stride, source_num_reqs, source_num_blocks,
1266 static_cast<int32_t>(source_block_size), resident_bt_stride,
1267 resident_num_reqs, resident_num_blocks,
1268 static_cast<int32_t>(resident_block_size),
1269 static_cast<int32_t>(resident_null_block), global_indices.stride(0),
1270 attention_row_stride, valid_count_stride);
1271 const cudaError_t launch_error = cudaGetLastError();
1272 STD_TORCH_CHECK(launch_error == cudaSuccess,
1273 "HiSparse residency kernel launch failed: ",
1274 cudaGetErrorString(launch_error));
1275 }
1276
1277 void hisparse_gather_plan(
1278 torch::stable::Tensor const& host_cache, torch::stable::Tensor& hot_cache,
1279 torch::stable::Tensor const& global_indices,
1280 torch::stable::Tensor const& hot_indices,
1281 torch::stable::Tensor const& miss_mask,
1282 std::optional<torch::stable::Tensor> const& request_state_indices,
1283 std::optional<torch::stable::Tensor> const& attention_indices,
1284 int64_t attention_block_stride) {
1285 STD_TORCH_CHECK(
1286 host_cache.device().is_cpu() && is_pinned_cpu_tensor(host_cache),
1287 "host_cache must be pinned CPU memory");
1288 STD_TORCH_CHECK(hot_cache.is_cuda(), "hot_cache must be on CUDA");
1289 STD_TORCH_CHECK(
1290 global_indices.is_cuda() && hot_indices.is_cuda() && miss_mask.is_cuda(),
1291 "plan tensors must be on CUDA");
1292 STD_TORCH_CHECK(
1293 global_indices.scalar_type() == torch::headeronly::ScalarType::Int &&
1294 hot_indices.scalar_type() == torch::headeronly::ScalarType::Int &&
1295 miss_mask.scalar_type() == torch::headeronly::ScalarType::Int,
1296 "plan tensors must be int32");
1297 STD_TORCH_CHECK(global_indices.dim() == 2 && global_indices.is_contiguous(),
1298 "global_indices must be contiguous 2D");
1299 STD_TORCH_CHECK(
1300 hot_indices.size(0) == global_indices.size(0) &&
1301 hot_indices.size(1) == global_indices.size(1) &&
1302 miss_mask.size(0) == global_indices.size(0) &&
1303 miss_mask.size(1) == global_indices.size(1) &&
1304 hot_indices.is_contiguous() && miss_mask.is_contiguous(),
1305 "hot_indices/miss_mask must match contiguous 2D global_indices");
1306
1307 STD_TORCH_CHECK(hot_cache.dim() == 2 || hot_cache.dim() == 3,
1308 "hot_cache must be a 2D staging buffer or paged 3D cache");
1309 const int64_t row_bytes = hot_cache.size(-1) * hot_cache.element_size();
1310 STD_TORCH_CHECK(row_bytes % 16 == 0, "KV rows must be 16-byte aligned");
1311 STD_TORCH_CHECK(
1312 hot_cache.stride(hot_cache.dim() - 2) * hot_cache.element_size() ==
1313 row_bytes,
1314 "hot-cache rows must be contiguous");
1315 const int64_t host_rows = check_2d_rows(host_cache, "host_cache", row_bytes);
1316
1317 const auto num_rows = static_cast<int32_t>(global_indices.size(0));
1318 const auto top_k = static_cast<int32_t>(global_indices.size(1));
1319
1320 const int32_t* request_state_ptr = nullptr;
1321 if (request_state_indices.has_value()) {
1322 auto const& state_indices = request_state_indices.value();
1323 STD_TORCH_CHECK(
1324 state_indices.is_cuda() &&
1325 state_indices.scalar_type() == torch::headeronly::ScalarType::Int &&
1326 state_indices.numel() >= num_rows,
1327 "request_state_indices must be int32 on CUDA with one entry per row");
1328 request_state_ptr = state_indices.const_data_ptr<int32_t>();
1329 }
1330
1331 int32_t* attention_indices_ptr = nullptr;
1332 if (attention_indices.has_value()) {
1333 auto const& indices = attention_indices.value();
1334 STD_TORCH_CHECK(
1335 indices.is_cuda() &&
1336 indices.scalar_type() == torch::headeronly::ScalarType::Int &&
1337 indices.dim() == 2 && indices.is_contiguous() &&
1338 indices.size(0) == global_indices.size(0) &&
1339 indices.size(1) == global_indices.size(1),
1340 "attention_indices must be a contiguous int32 CUDA tensor matching "
1341 "global_indices");
1342 attention_indices_ptr = indices.mutable_data_ptr<int32_t>();
1343 }
1344
1345 if (num_rows == 0 || top_k == 0) {
1346 return;
1347 }
1348
1349 // Match the swap-in kernel's block size: the gather serves 3 of every 4
1350 // layers' misses (index-sharing replay), so per-row copy parallelism is
1351 // the throughput limiter on cold rows.
1352 constexpr int kBlockSize = 1024;
1353 constexpr int kNumWarps = kBlockSize / kWarpSize;
1354 // Interleave columns over enough blocks per row to cover the device even
1355 // for few-row launches (local-prefill staging's single-row layout, small
1356 // decode batches), keeping >= 1 column per warp.
1357 constexpr int kTargetBlocks = 256;
1358 const int max_chunks = std::max(1, (top_k + kNumWarps - 1) / kNumWarps);
1359 const int num_chunks =
1360 std::min(max_chunks, std::max(1, kTargetBlocks / num_rows));
1361 const dim3 grid(num_rows, num_chunks);
1362 const int32_t hot_block_size =
1363 hot_cache.dim() == 3 ? static_cast<int32_t>(hot_cache.size(1)) : 1;
1364 if (attention_indices.has_value()) {
1365 STD_TORCH_CHECK(attention_block_stride >= hot_block_size,
1366 "attention block stride must cover one hot block");
1367 }
1368 const int64_t hot_rows = hot_cache.size(0) * hot_block_size;
1369 const int64_t hot_block_stride =
1370 hot_cache.stride(0) * hot_cache.element_size();
1371 const torch::stable::accelerator::DeviceGuard device_guard(
1372 hot_cache.get_device_index());
1373 const cudaStream_t stream = get_current_cuda_stream();
1374 hisparse_gather_plan_kernel<<<grid, kBlockSize, 0, stream>>>(
1375 static_cast<const char*>(host_cache.const_data_ptr()),
1376 static_cast<char*>(hot_cache.mutable_data_ptr()),
1377 global_indices.const_data_ptr<int32_t>(),
1378 hot_indices.const_data_ptr<int32_t>(),
1379 miss_mask.const_data_ptr<int32_t>(), attention_indices_ptr,
1380 request_state_ptr, host_rows, hot_rows, row_bytes, hot_block_stride,
1381 hot_block_size, top_k, attention_block_stride);
1382 }
1383
1384 void hisparse_gather_compact(torch::stable::Tensor const& host_cache,
1385 torch::stable::Tensor& hot_cache,
1386 torch::stable::Tensor const& miss_global_indices,
1387 torch::stable::Tensor const& miss_hot_indices,
1388 torch::stable::Tensor const& miss_counts) {
1389 STD_TORCH_CHECK(
1390 host_cache.device().is_cpu() && is_pinned_cpu_tensor(host_cache),
1391 "host_cache must be pinned CPU memory");
1392 STD_TORCH_CHECK(hot_cache.is_cuda(), "hot_cache must be on CUDA");
1393 STD_TORCH_CHECK(
1394 miss_global_indices.is_cuda() && miss_hot_indices.is_cuda() &&
1395 miss_counts.is_cuda() &&
1396 miss_global_indices.scalar_type() ==
1397 torch::headeronly::ScalarType::Int &&
1398 miss_hot_indices.scalar_type() ==
1399 torch::headeronly::ScalarType::Int &&
1400 miss_counts.scalar_type() == torch::headeronly::ScalarType::Int &&
1401 miss_global_indices.dim() == 2 && miss_hot_indices.dim() == 2 &&
1402 miss_global_indices.size(0) == miss_hot_indices.size(0) &&
1403 miss_global_indices.size(1) == miss_hot_indices.size(1) &&
1404 miss_counts.numel() >= miss_global_indices.size(0) &&
1405 miss_global_indices.is_contiguous() &&
1406 miss_hot_indices.is_contiguous() && miss_counts.is_contiguous(),
1407 "compact miss plan must be matching contiguous int32 CUDA tensors");
1408 STD_TORCH_CHECK(hot_cache.dim() == 3,
1409 "hot_cache must be [num_blocks, block_size, row_width]");
1410 const int64_t row_bytes = hot_cache.size(-1) * hot_cache.element_size();
1411 STD_TORCH_CHECK(row_bytes % 16 == 0, "KV rows must be 16-byte aligned");
1412 STD_TORCH_CHECK(hot_cache.stride(1) * hot_cache.element_size() == row_bytes,
1413 "hot-cache rows must be contiguous");
1414 const int64_t host_rows = check_2d_rows(host_cache, "host_cache", row_bytes);
1415 const auto num_rows = static_cast<int32_t>(miss_global_indices.size(0));
1416 const auto top_k = static_cast<int32_t>(miss_global_indices.size(1));
1417 if (num_rows == 0 || top_k == 0) {
1418 return;
1419 }
1420
1421 constexpr int kBlockSize = 512;
1422 constexpr int kTargetBlocks = 64;
1423 const int num_chunks = std::min(8, std::max(1, kTargetBlocks / num_rows));
1424 const dim3 grid(num_rows, num_chunks);
1425 const int32_t hot_block_size = static_cast<int32_t>(hot_cache.size(1));
1426 const int64_t hot_rows = hot_cache.size(0) * hot_block_size;
1427 const int64_t hot_block_stride =
1428 hot_cache.stride(0) * hot_cache.element_size();
1429 const torch::stable::accelerator::DeviceGuard device_guard(
1430 hot_cache.get_device_index());
1431 const cudaStream_t stream = get_current_cuda_stream();
1432 hisparse_gather_compact_kernel<<<grid, kBlockSize, 0, stream>>>(
1433 static_cast<const char*>(host_cache.const_data_ptr()),
1434 static_cast<char*>(hot_cache.mutable_data_ptr()),
1435 miss_global_indices.const_data_ptr<int32_t>(),
1436 miss_hot_indices.const_data_ptr<int32_t>(),
1437 miss_counts.const_data_ptr<int32_t>(), host_rows, hot_rows, row_bytes,
1438 hot_block_stride, hot_block_size, top_k);
1439 }