From 21668c6b5c0146b40a2d3168c6e447b194f6540a Mon Sep 17 00:00:00 2001 From: Songhao Jia Date: Mon, 23 Nov 2026 19:23:14 -0800 Subject: [PATCH 1/3] [CUDA] Grow batched-sequence KV columns at runtime Grow physical session columns on admission using the default five-field sequence interface, preserving live KV and rebinding CUDA graphs after storage moves. Cover failed admission recovery and exact mini-model logits; keep shrinking as a separate follow-up. Authored with OpenAI Codex assistance. --- .../tests/test_muse_glimmer_batching_ci.py | 11 + .github/workflows/cuda.yml | 20 +- backends/cuda/CMakeLists.txt | 5 + backends/cuda/batching/cuda_executor.cpp | 4 + backends/cuda/batching/cuda_executor.h | 9 +- backends/cuda/passes/lower_offgraph_kv.py | 23 +- backends/cuda/runtime/cuda_backend.cpp | 28 +- backends/cuda/runtime/cuda_delegate_handle.h | 12 + backends/cuda/runtime/cuda_kv_cache.cpp | 241 +++++- backends/cuda/runtime/cuda_kv_cache.h | 32 +- backends/cuda/runtime/cuda_kv_pool.cpp | 170 +++- backends/cuda/runtime/cuda_kv_pool.h | 28 +- .../test/test_cuda_backend_execute.cpp | 183 +++- .../cuda/runtime/test/test_cuda_kv_cache.cpp | 813 +++++++++++++++++- backends/cuda/tests/bench_sdpa_varlen.py | 2 +- .../test_offgraph_kv_batched_sequence.py | 245 +++++- backends/cuda/tests/test_sdpa_varlen.py | 52 +- backends/cuda/triton/kernels/sdpa_varlen.py | 51 +- examples/models/muse-glimmer/CMakeLists.txt | 28 + .../models/muse-glimmer/export/export_solo.py | 6 +- .../tests/check_runtime_kv_columns.py | 234 +++++ .../tests/runtime_kv_columns_probe.cpp | 307 +++++++ extension/llm/cache/cache.h | 7 +- 23 files changed, 2373 insertions(+), 138 deletions(-) create mode 100644 examples/models/muse-glimmer/tests/check_runtime_kv_columns.py create mode 100644 examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp diff --git a/.ci/scripts/tests/test_muse_glimmer_batching_ci.py b/.ci/scripts/tests/test_muse_glimmer_batching_ci.py index 5c8fcead860..a7922f4c6f4 100644 --- a/.ci/scripts/tests/test_muse_glimmer_batching_ci.py +++ b/.ci/scripts/tests/test_muse_glimmer_batching_ci.py @@ -23,6 +23,17 @@ class MuseGlimmerBatchingCITest(unittest.TestCase): + def test_runtime_columns_probe_runs_in_cuda_ci(self): + workflow = (ROOT / ".github/workflows/cuda.yml").read_text() + job = workflow.split(" unittest-cuda-muse-glimmer-batching:", 1)[1].split( + " unittest-cuda-quantized-gemm:", 1 + )[0] + self.assertIn("-DMUSE_GLIMMER_BUILD_RUNTIME_KV_PROBE=ON", job) + self.assertIn("muse_glimmer_runtime_kv_probe --parallel", job) + self.assertIn("tests/check_runtime_kv_columns.py", job) + self.assertIn("-DEXECUTORCH_ENABLE_LOGGING=OFF", job) + self.assertIn("cmake --build --preset llm-release-cuda-install", job) + def test_e2e_builds_smoke_before_running_it(self): script = (SCRIPTS / "test_model_e2e.sh").read_text() build = script.index("bash .ci/scripts/build_muse_glimmer_batching_smoke.sh") diff --git a/.github/workflows/cuda.yml b/.github/workflows/cuda.yml index 03b39180db4..f97d0c652cd 100644 --- a/.github/workflows/cuda.yml +++ b/.github/workflows/cuda.yml @@ -695,13 +695,19 @@ jobs: # The normal serving binaries and the opt-in correctness tool share # CudaExecutor; MG preparation tests also run on Linux. - make muse-glimmer-batching-cuda + # Capture qualification uses native counters in the release build. + cmake --preset llm-release-cuda -DEXECUTORCH_ENABLE_LOGGING=OFF + cmake --build --preset llm-release-cuda-install BATCHING_BIN_DIR="${PWD}/cmake-out/examples/models/muse-glimmer-batching" - cmake -S "${PWD}/examples/models/muse-glimmer" -B "${BATCHING_BIN_DIR}" \ - -DMUSE_GLIMMER_BUILD_BATCHING_TESTS=ON + cmake -S "${PWD}/examples/models/muse-glimmer" --preset muse-glimmer-cuda \ + -B "${BATCHING_BIN_DIR}" -DMUSE_GLIMMER_BUILD_BATCHING=ON \ + -DMUSE_GLIMMER_BUILD_BATCHING_TESTS=ON \ + -DMUSE_GLIMMER_BUILD_RUNTIME_KV_PROBE=ON bash .ci/scripts/build_muse_glimmer_batching_smoke.sh "${BATCHING_BIN_DIR}" cmake --build "${BATCHING_BIN_DIR}" \ - --target muse_glimmer_batching_test muse_glimmer_cuda_dflash_test --parallel + --target muse_glimmer_batching_runner muse_glimmer_batching_worker \ + muse_glimmer_batching_test muse_glimmer_cuda_dflash_test \ + muse_glimmer_runtime_kv_probe --parallel ctest --test-dir "${BATCHING_BIN_DIR}" \ -R '^muse_glimmer_batching$' --output-on-failure --no-tests=error test -x "${BATCHING_BIN_DIR}/muse_glimmer_batching_runner" @@ -710,6 +716,10 @@ jobs: # The batching export on a tiny model, and the CLI's backend dispatch. pip install gguf + python examples/models/muse-glimmer/tests/check_runtime_kv_columns.py \ + --probe "${BATCHING_BIN_DIR}/muse_glimmer_runtime_kv_probe" \ + --output-dir "${RUNNER_TEMP:-/tmp}/muse_glimmer_runtime_kv_columns" + python -m pytest -v -o "addopts=" \ examples/models/muse-glimmer/tests/test_cuda_batching_pipeline.py \ examples/models/muse-glimmer/tests/test_cuda_dflash_packed.py \ @@ -806,7 +816,7 @@ jobs: backends/cuda/tests/test_merge_ptes.py \ -v -o "addopts=" - cmake --preset llm-release-cuda -DEXECUTORCH_BUILD_TESTS=ON + cmake --preset llm-release-cuda -DEXECUTORCH_BUILD_TESTS=ON -DEXECUTORCH_ENABLE_LOGGING=OFF cmake --build cmake-out --target test_cuda_allocator test_cuda_allocator_exit test_cuda_mutable_state test_cuda_weight_cache test_cuda_output_copy test_cuda_backend_execute test_cuda_sort_rand test_cuda_current_stream test_cuda_kv_cache test_cuda_guard test_cuda_stream_guard test_step_plan test_cuda_executor -j$(nproc) ctest --test-dir cmake-out -R test_cuda_allocator --output-on-failure -V ctest --test-dir cmake-out -R test_cuda_mutable_state --output-on-failure -V diff --git a/backends/cuda/CMakeLists.txt b/backends/cuda/CMakeLists.txt index 9715234c1ad..a5169fa6c48 100644 --- a/backends/cuda/CMakeLists.txt +++ b/backends/cuda/CMakeLists.txt @@ -506,6 +506,11 @@ if(BUILD_TESTING) runtime/test/test_cuda_backend_execute.cpp EXTRA_LIBS aoti_cuda_backend ) target_compile_definitions(test_cuda_backend_execute PRIVATE CUDA_AVAILABLE=1) + if(EXECUTORCH_BUILD_EXTENSION_LLM) + target_compile_definitions( + test_cuda_backend_execute PRIVATE EXECUTORCH_BUILD_EXTENSION_LLM + ) + endif() # sort.cu and rand.cu are compiled only under this condition (see # _aoti_cuda_shim_sources), so the test that calls them is too. if(NOT EXECUTORCH_BUILD_ROCM AND CMAKE_CUDA_COMPILER) diff --git a/backends/cuda/batching/cuda_executor.cpp b/backends/cuda/batching/cuda_executor.cpp index b33cb492fbf..7e494338418 100644 --- a/backends/cuda/batching/cuda_executor.cpp +++ b/backends/cuda/batching/cuda_executor.cpp @@ -1089,6 +1089,10 @@ OffGraphKVMetrics CudaExecutor::kv_metrics() const { return kv_->metrics(); } +CudaGraphMetrics CudaExecutor::graph_metrics(std::string_view method) const { + return kv_->graph_metrics(method); +} + std::vector CudaExecutor::method_calls() const { std::vector calls; calls.reserve(methods_.size() + 1); diff --git a/backends/cuda/batching/cuda_executor.h b/backends/cuda/batching/cuda_executor.h index 4e0cf7bc7da..7250150e174 100644 --- a/backends/cuda/batching/cuda_executor.h +++ b/backends/cuda/batching/cuda_executor.h @@ -17,6 +17,8 @@ // and optionally one dynamic `forward_others` for anything wider. Each forward // runs the method with the smallest width that holds it; a static method's // extra rows are padding. +// All execution and session calls are confined to the engine +// thread, matching Executor. execute_raw rejects re-entrant execution. #include #include @@ -24,6 +26,7 @@ #include #include #include +#include #include #include @@ -227,9 +230,9 @@ class ET_EXPERIMENTAL CudaExecutor : public llm_batching::Executor { // The cache's pool usage, for memory reporting. OffGraphKVMetrics kv_metrics() const; - - // Every method, narrowest first, with how many forwards it ran. Read it - // between executes, not while one runs. + // Sequence-layout counters; read between executes, on the engine thread. + CudaGraphMetrics graph_metrics(std::string_view method) const; + // Forward-call counters, read on the engine thread. std::vector method_calls() const; // Whether tokens are sampled on the device rather than on the host. diff --git a/backends/cuda/passes/lower_offgraph_kv.py b/backends/cuda/passes/lower_offgraph_kv.py index b12f4ea5c34..bc0aa595085 100644 --- a/backends/cuda/passes/lower_offgraph_kv.py +++ b/backends/cuda/passes/lower_offgraph_kv.py @@ -147,6 +147,16 @@ def parse_offgraph_kv_manifest(value: bytes) -> dict[str, Any]: # noqa: C901 return manifest +def offgraph_kv_constant_methods(value: bytes) -> dict[str, int]: + """Runtime sequence metadata derived from the lowering manifest.""" + manifest = parse_offgraph_kv_manifest(value) + if manifest["layout"] != "batched-sequence": + return {} + return { + "get_offgraph_kv_max_seqs": manifest["max_seqs"], + } + + def ring_attention_mask( position: torch.Tensor, buf_size: int, window: int ) -> torch.Tensor: @@ -310,7 +320,8 @@ def batched_sequence_step( """Write this step's K/V into each sequence's column, then attend. The storage is declared ``[1, rows * columns, H, D]``: row ``r`` of - column ``c`` is slot ``r * columns + c``, so it is ``[rows, columns, H, D]`` + column ``c`` is slot ``r * pitch + c``, where ``pitch`` comes from + ``seq_info[0, 4]``. It is ``[rows, pitch, H, D]`` and grows by whole rows, as the sequence layout's does. Token ``i`` lands in column ``seq_cols[i]`` at row ``position % rows`` (a ring layer's rows wrap; a flat layer's never do). ``seq_info`` names each segment's query @@ -321,9 +332,12 @@ def batched_sequence_step( ``context_window`` gives every draft block query the same retained context before the block; ``symmetric_window`` uses strict per-query distance as in DFlash. Ordinary attention uses each query's own past-window bound. + Five-field ``seq_info`` supplies the physical pitch for writes and attention; + ``columns`` remains the declared maximum. """ position = position.reshape(-1) - slots = (position % rows) * columns + seq_cols[: k.shape[2]] + pitch = seq_info[0, 4].to(torch.int64) + slots = (position % rows) * pitch + seq_cols[: k.shape[2]] _write(k_storage, slots, k) _write(v_storage, slots, v) heads, dim = k_storage.shape[2], k_storage.shape[3] @@ -750,7 +764,10 @@ def _lower_batched_sequence( seq_info = self._cell_buffer( exported_program, OFFGRAPH_KV_SEQ_INFO_FQN, - (self._manifest["max_segments"], 4), + ( + self._manifest["max_segments"], + 5, + ), torch.int32, device, ) diff --git a/backends/cuda/runtime/cuda_backend.cpp b/backends/cuda/runtime/cuda_backend.cpp index b105363f310..c551cdc0c73 100644 --- a/backends/cuda/runtime/cuda_backend.cpp +++ b/backends/cuda/runtime/cuda_backend.cpp @@ -791,6 +791,16 @@ class ET_EXPERIMENTAL CudaBackend final // the step is driven from here rather than by the runner. int64_t kv_step_width = 0; #if defined(EXECUTORCH_BUILD_EXTENSION_LLM) + bool kv_prepared = false; + executorch::backends::aoti::ScopeGuard abort_kv_step([&]() noexcept { + if (kv_prepared) { + const Error error = handle->kv_cache->abort_step(); + ET_CHECK_OR_LOG_ERROR( + error == Error::Ok, + "offgraph_kv: failed to abort prepared forward"); + (void)error; + } + }); if (handle->kv_cache != nullptr) { const auto step_width = read_offgraph_kv_step_width( handle->kv_step_width, Span(args.data(), n_inputs)); @@ -802,10 +812,20 @@ class ET_EXPERIMENTAL CudaBackend final ET_CHECK_OK_OR_RETURN_ERROR(step_stream.error()); ET_CHECK_OK_OR_RETURN_ERROR( handle->kv_cache->prepare_step(kv_step_width, step_stream.get())); + kv_prepared = true; ET_CHECK_OK_OR_RETURN_ERROR(handle->kv_cache->rebind_for_execute(handle)); } #endif ET_CHECK_OK_OR_RETURN_ERROR(mutable_state_rebind_for_execute(handle)); + const auto commit_kv_step = [&]() { + const Error error = commit_offgraph_kv_step(handle, kv_step_width); +#if defined(EXECUTORCH_BUILD_EXTENSION_LLM) + if (error == Error::Ok) { + kv_prepared = false; + } +#endif + return error; + }; // --------------------------------------------------------------- // CUDA graph REPLAY path — skip all tensor setup and just replay @@ -854,6 +874,7 @@ class ET_EXPERIMENTAL CudaBackend final Internal, "cudaGraphLaunch failed: %s", cudaGetErrorString(gerr)); + ++handle->cuda_graph_state.metrics.replays; // Copy outputs from static buffers into the planned GPU ET buffers (D2D) for (size_t i = 0; i < n_outputs; i++) { @@ -867,7 +888,7 @@ class ET_EXPERIMENTAL CudaBackend final } ET_CUDA_CHECK_OR_RETURN_ERROR(cudaStreamSynchronize(cs)); - return commit_offgraph_kv_step(handle, kv_step_width); + return commit_kv_step(); } const bool is_capture_step = @@ -877,6 +898,7 @@ class ET_EXPERIMENTAL CudaBackend final Error error = run_once( handle, args, n_inputs, n_outputs, is_capture_step, graph_launched); if (error != Error::Ok && is_capture_step && !graph_launched) { + ++handle->cuda_graph_state.metrics.capture_failures; // A capture records kernels without running them, so until the new graph // runs, the inputs and any state the program updates are untouched. A // program that keeps state in host memory, where host code does run @@ -897,7 +919,7 @@ class ET_EXPERIMENTAL CudaBackend final graph_launched); } ET_CHECK_OK_OR_RETURN_ERROR(error); - return commit_offgraph_kv_step(handle, kv_step_width); + return commit_kv_step(); } void destroy(DelegateHandle* handle_) const override { @@ -1298,6 +1320,7 @@ class ET_EXPERIMENTAL CudaBackend final } handle->cuda_graph_state.phase = CudaGraphPhase::Replay; + ++handle->cuda_graph_state.metrics.captures; ET_LOG( Info, "CUDA graph: captured and instantiated for '%s'", @@ -1310,6 +1333,7 @@ class ET_EXPERIMENTAL CudaBackend final Internal, "cudaGraphLaunch (first replay) failed: %s", cudaGetErrorString(gerr)); + ++handle->cuda_graph_state.metrics.replays; graph_launched = true; handle->cuda_graph_state.note_graph_allocations(); diff --git a/backends/cuda/runtime/cuda_delegate_handle.h b/backends/cuda/runtime/cuda_delegate_handle.h index 4c4093e9eb5..2db0f86f876 100644 --- a/backends/cuda/runtime/cuda_delegate_handle.h +++ b/backends/cuda/runtime/cuda_delegate_handle.h @@ -132,10 +132,18 @@ enum class CudaGraphPhase { Replay = 2, }; +struct CudaGraphMetrics { + uint64_t captures{0}; + uint64_t replays{0}; + uint64_t capture_failures{0}; +}; + // All CUDA graph related state grouped into a single struct. struct CudaGraphState { CudaGraphPhase phase = CudaGraphPhase::Disabled; int warmup_remaining = 0; + // Lifetime counts survive release/recapture; read between executions. + CudaGraphMetrics metrics; // Captured graph and executable instance cudaGraph_t graph = nullptr; @@ -259,6 +267,7 @@ struct CudaGraphState { CudaGraphState(CudaGraphState&& other) noexcept : phase(other.phase), warmup_remaining(other.warmup_remaining), + metrics(other.metrics), graph(other.graph), graph_exec(other.graph_exec), static_input_ptrs(std::move(other.static_input_ptrs)), @@ -269,6 +278,7 @@ struct CudaGraphState { graph_allocations(std::move(other.graph_allocations)) { other.graph = nullptr; other.graph_exec = nullptr; + other.metrics = {}; } CudaGraphState& operator=(CudaGraphState&& other) noexcept { @@ -277,6 +287,7 @@ struct CudaGraphState { phase = other.phase; warmup_remaining = other.warmup_remaining; + metrics = other.metrics; graph = other.graph; graph_exec = other.graph_exec; static_input_ptrs = std::move(other.static_input_ptrs); @@ -288,6 +299,7 @@ struct CudaGraphState { other.graph = nullptr; other.graph_exec = nullptr; + other.metrics = {}; } return *this; } diff --git a/backends/cuda/runtime/cuda_kv_cache.cpp b/backends/cuda/runtime/cuda_kv_cache.cpp index 98bc447449c..cb076018fd5 100644 --- a/backends/cuda/runtime/cuda_kv_cache.cpp +++ b/backends/cuda/runtime/cuda_kv_cache.cpp @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -190,7 +191,7 @@ class CudaSequenceKVCache final : public cache::SequenceCache, ET_CHECK_OR_RETURN_ERROR( step.has_value(), InvalidArgument, "offgraph_kv: uncommittable step"); cache::SequenceCache::commit(*step); - return pool_.mark_step_done(); + return pool_.mark_step_done(pool_.stream()); } OffGraphKVMetrics metrics() const override { @@ -442,7 +443,7 @@ class CudaCellCache final : public cache::CellCache, public CudaKVCache { ET_CHECK_OR_RETURN_ERROR( !poisoned_ && (!dflash_block_size_ || pending_width_ == 0), InvalidState, - "offgraph_kv: uncommitted or failed draft co-batch; clear required"); + "offgraph_kv: uncommitted step or failed cache operation; clear required"); if (!validated_) { const Error valid = pool_.validate(); if (valid != Error::Ok) { @@ -532,13 +533,13 @@ class CudaCellCache final : public cache::CellCache, public CudaKVCache { write_length > 0, InvalidArgument, "write length must be positive"); ET_CHECK_OK_OR_RETURN_ERROR(error_); if (!dflash_block_size_) { - return pool_.mark_step_done(); + return pool_.mark_step_done(pool_.stream()); } if (poisoned_ || pending_width_ == 0 || write_length != pending_width_) { poisoned_ = true; return Error::InvalidState; } - const Error marked = pool_.mark_step_done(); + const Error marked = pool_.mark_step_done(pool_.stream()); const Error fenced = marked == Error::Ok ? pool_.synchronize() : marked; if (fenced != Error::Ok) { poisoned_ = true; @@ -802,17 +803,20 @@ class CudaCellCache final : public cache::CellCache, public CudaKVCache { // Batched-sequence layout: every sequence keeps a private history in its own // column of each layer's storage, as MLX's batched-sequence cache keeps one // buffer per sequence. A layer's storage is [rows, columns, H, D] (declared -// [1, rows * columns, H, D]): row = the position, or position % rows on a ring -// layer, so each sequence is contiguous by position and attention reads only -// its own column, bounded by its own length. The last column is scratch, +// [1, rows * declared_columns, H, D]): seq_info supplies the physical row +// pitch in its fifth field. Row = the position, or position % rows on a ring +// layer. Attention reads only its own column, bounded by its own length. +// The last column is scratch, // written by static-width padding and never read. // // The neutral SequenceCache plans each sequence: admission against its // capacity, ring limits, and rewind floors. The pool owns the bytes; rows grow // together for every column. Before each forward, prepare_step writes each -// token's column (seq_cols) and one (q_start, q_len, column, length) row per +// token's column (seq_cols) and one +// (q_start, q_len, column, length, physical_columns) row per // run of one sequence's query rows (seq_info) into buffers the program reads // at fixed addresses, so a captured CUDA graph serves any mix of sequences. +// Owner columns grow on admission and reserve a final scratch column. // // A DFlash draft step declares, per owner, its new context then its block; // only the block is queried, it sees all of that owner's history, and it is @@ -821,6 +825,7 @@ constexpr char kSeqColsFqn[] = "__et_offgraph_kv_seq_cols"; constexpr char kSeqInfoFqn[] = "__et_offgraph_kv_seq_info"; constexpr size_t kSeqColsBuffer = 0; constexpr size_t kSeqInfoBuffer = 1; +constexpr int kSequenceInfoFields = 5; class CudaBatchedSequenceCache final : public cache::Cache, public cache::BatchControl, @@ -829,22 +834,27 @@ class CudaBatchedSequenceCache final : public cache::Cache, CudaBatchedSequenceCache( const cache::CacheGeometry& geometry, const cache::CacheConfig& cfg, - slimc10::ScalarType storage_dtype) + slimc10::ScalarType storage_dtype, + bool grow_columns) : geometry_(geometry), cfg_(cfg), max_seqs_(*cfg.max_seqs), - columns_(*cfg.max_seqs + 1), + grow_columns_(grow_columns), max_write_(*cfg.max_write), max_segments_(batched_sequence_max_segments(*cfg.max_seqs)), dflash_block_size_(geometry.dflash_block_size), + columns_(grow_columns ? 2 : *cfg.max_seqs + 1), pool_( pool_layers(geometry, cfg), {{kSeqColsFqn, slimc10::ScalarType::Long, {*cfg.max_write}}, {kSeqInfoFqn, slimc10::ScalarType::Int, - {batched_sequence_max_segments(*cfg.max_seqs), 4}}}, + {batched_sequence_max_segments(*cfg.max_seqs), + kSequenceInfoFields}}}, storage_dtype, - static_cast(cfg.initial_capacity) * (*cfg.max_seqs + 1)) { + static_cast(cfg.initial_capacity) * (*cfg.max_seqs + 1), + *cfg.max_seqs + 1, + grow_columns ? 2 : *cfg.max_seqs + 1) { for (const cache::LayerGeometry& layer : geometry.layers) { layer_rows_.push_back(rows_of(layer, cfg)); } @@ -874,7 +884,7 @@ class CudaBatchedSequenceCache final : public cache::Cache, // nor invalidates captured graphs. void clear() override { std::lock_guard guard(mutex_); - if (dflash_block_size_ && pool_.allocated()) { + if ((dflash_block_size_ || grow_columns_) && pool_.allocated()) { // A failed forward can be abandoned by a different host thread. Fence // the originating stream before reusing its sequence columns. if (pool_.synchronize(/*all_streams=*/true) != Error::Ok) { @@ -888,6 +898,7 @@ class CudaBatchedSequenceCache final : public cache::Cache, step_seq_ids_.clear(); pending_owners_.clear(); poisoned_ = false; + inflight_ = false; } bool declare_step(const std::vector& seq_ids) override { @@ -929,13 +940,23 @@ class CudaBatchedSequenceCache final : public cache::Cache, std::optional seq_new() override { std::lock_guard guard(mutex_); - const auto column = free_column(); - if (!column) { + const auto id = free_sequence_id(); + if (!id || poisoned_ || (grow_columns_ && inflight_)) { + return std::nullopt; + } + const int column = grow_columns_ ? -1 : *id; + seqs_.emplace(*id, Sequence{column, cache::SequenceCache(geometry_, cfg_)}); + bool admitted = false; + aoti::ScopeGuard rollback([&]() noexcept { + if (!admitted) { + seqs_.erase(*id); + } + }); + if (grow_columns_ && ensure_columns(cudaStreamPerThread) != Error::Ok) { return std::nullopt; } - seqs_.emplace( - *column, Sequence{*column, cache::SequenceCache(geometry_, cfg_)}); - return *column; + admitted = true; + return *id; } // Copies the retained prefix into a free column: a sequence's history is @@ -944,8 +965,9 @@ class CudaBatchedSequenceCache final : public cache::Cache, override { std::lock_guard guard(mutex_); const auto source = seqs_.find(src); - const auto column = free_column(); - if (source == seqs_.end() || !column || !pool_.allocated()) { + const auto id = free_sequence_id(); + if (source == seqs_.end() || !id || !pool_.allocated() || poisoned_ || + (grow_columns_ && inflight_)) { return std::nullopt; } // The copies below run on this thread's stream, which may not be the @@ -958,17 +980,44 @@ class CudaBatchedSequenceCache final : public cache::Cache, const int length = source->second.plan.length(); const int keep = std::min(upto.value_or(length), length); cache::SequenceCache plan(source->second.plan); - if (keep <= 0 || !plan.rewind(keep) || - copy_column(source->second.column, *column, keep) != Error::Ok || - pool_.mark_step_done() != Error::Ok) { + if (keep <= 0 || !plan.rewind(keep)) { + return std::nullopt; + } + const int column = grow_columns_ ? -1 : *id; + seqs_.emplace(*id, Sequence{column, std::move(plan)}); + bool admitted = false; + aoti::ScopeGuard rollback([&]() noexcept { + if (!admitted) { + seqs_.erase(*id); + } + }); + if (grow_columns_ && ensure_columns(cudaStreamPerThread) != Error::Ok) { + return std::nullopt; + } + const cudaStream_t stream = + grow_columns_ ? cudaStreamPerThread : pool_.stream(); + if (copy_column( + source->second.column, seqs_.at(*id).column, keep, stream) != + Error::Ok || + pool_.mark_step_done(stream) != Error::Ok) { + // A failed copy must finish before its column can be reused. + if (grow_columns_ && + pool_.synchronize(/*all_streams=*/true) != Error::Ok) { + poisoned_ = true; + } return std::nullopt; } - seqs_.emplace(*column, Sequence{*column, std::move(plan)}); - return *column; + admitted = true; + return *id; } bool seq_rm(int32_t seq_id) override { std::lock_guard guard(mutex_); + if (std::find(step_seq_ids_.begin(), step_seq_ids_.end(), seq_id) != + step_seq_ids_.end()) { + step_seq_ids_.clear(); + } + // Logical removal does not free storage; verbs run between forwards. return seqs_.erase(seq_id) > 0; } @@ -1019,7 +1068,9 @@ class CudaBatchedSequenceCache final : public cache::Cache, ET_CHECK_OR_RETURN_ERROR( !poisoned_ && (!dflash_block_size_ || pending_owners_.empty()), InvalidState, - "offgraph_kv: uncommitted or failed draft co-batch; clear required"); + "offgraph_kv: uncommitted step or failed cache operation; clear required"); + ET_CHECK_OR_RETURN_ERROR( + !inflight_, InvalidState, "offgraph_kv: a forward is still prepared"); if (!validated_) { const Error valid = pool_.validate(); if (valid != Error::Ok) { @@ -1066,6 +1117,19 @@ class CudaBatchedSequenceCache final : public cache::Cache, for (const auto& [seq_id, end] : ends) { required = std::max(required, end); } + if (grow_columns_) { + ET_CHECK_OR_RETURN_ERROR( + static_cast(seqs_.size()) < columns_, + InvalidState, + "offgraph_kv: admission must provide every owner a column"); + } + bool prepared = false; + aoti::ScopeGuard fence_failed_prepare([&]() noexcept { + if (grow_columns_ && !prepared && + pool_.synchronize(/*all_streams=*/true) != Error::Ok) { + poisoned_ = true; + } + }); ET_CHECK_OK_OR_RETURN_ERROR(pool_.prepare( std::min(required, cfg_.capacity) * columns_, live * columns_, @@ -1073,17 +1137,21 @@ class CudaBatchedSequenceCache final : public cache::Cache, ET_CHECK_OK_OR_RETURN_ERROR(reserve_staging( static_cast(max_write_) * sizeof(int64_t) + - static_cast(max_segments_) * 4 * sizeof(int32_t))); + static_cast(max_segments_) * kSequenceInfoFields * + sizeof(int32_t))); auto* cols = reinterpret_cast(staging_); auto* info = reinterpret_cast(cols + max_write_); - std::fill(cols, cols + write_length, static_cast(max_seqs_)); - std::fill(info, info + max_segments_ * 4, 0); + std::fill(cols, cols + write_length, static_cast(columns_ - 1)); + std::fill(info, info + max_segments_ * kSequenceInfoFields, 0); + for (int index = 0; index < max_segments_; ++index) { + info[index * kSequenceInfoFields + 4] = columns_; + } int q_start = 0; for (size_t index = 0; index < runs.size(); ++index) { const Run& run = runs[index]; const int column = seqs_.at(run.seq_id).column; std::fill(cols + run.start, cols + run.start + run.length, column); - int32_t* row = info + index * 4; + int32_t* row = info + index * kSequenceInfoFields; const int end = next[run.seq_id] + run.length; next[run.seq_id] = end; // A draft queries only each owner's block, packed owner by owner. @@ -1112,6 +1180,8 @@ class CudaBatchedSequenceCache final : public cache::Cache, } } step_seq_ids_.clear(); + inflight_ = grow_columns_; + prepared = true; return Error::Ok; } @@ -1119,12 +1189,17 @@ class CudaBatchedSequenceCache final : public cache::Cache, std::lock_guard guard(mutex_); ET_CHECK_OR_RETURN_ERROR( write_length > 0, InvalidArgument, "write length must be positive"); + ET_CHECK_OR_RETURN_ERROR( + !grow_columns_ || inflight_, + InvalidState, + "offgraph_kv: no prepared forward to commit"); ET_CHECK_OK_OR_RETURN_ERROR(error_); ET_CHECK_OR_RETURN_ERROR( !poisoned_, InvalidState, - "offgraph_kv: uncommitted or failed draft co-batch; clear required"); - ET_CHECK_OK_OR_RETURN_ERROR(pool_.mark_step_done()); + "offgraph_kv: uncommitted step or failed cache operation; clear required"); + ET_CHECK_OK_OR_RETURN_ERROR(pool_.mark_step_done(pool_.stream())); + inflight_ = false; // A draft's block is scratch: the next draft rewrites it. for (const int32_t owner : pending_owners_) { const auto it = seqs_.find(owner); @@ -1139,6 +1214,20 @@ class CudaBatchedSequenceCache final : public cache::Cache, return Error::Ok; } + Error abort_step() override { + std::lock_guard guard(mutex_); + if (!inflight_) { + return Error::Ok; + } + const Error error = pool_.synchronize(/*all_streams=*/true); + if (error != Error::Ok) { + poisoned_ = true; + return error; + } + inflight_ = false; + return Error::Ok; + } + // logical_length is the longest sequence: every column holds that many rows. OffGraphKVMetrics metrics() const override { std::lock_guard guard(mutex_); @@ -1151,9 +1240,18 @@ class CudaBatchedSequenceCache final : public cache::Cache, std::min(pool_.rows() / columns_, cfg_.capacity); metrics.growth_count = pool_.growth_count(); metrics.allocated_bytes = pool_.allocated_bytes(); + metrics.physical_columns = columns_; + metrics.declared_columns = max_seqs_ + 1; + metrics.live_sequences = seqs_.size(); + metrics.column_resize_count = pool_.column_resize_count(); return metrics; } + CudaGraphMetrics graph_metrics(std::string_view method) const override { + std::lock_guard guard(mutex_); + return pool_.graph_metrics(method); + } + protected: void* face(cache::FaceId id) override { return cache::expose(this, id); @@ -1193,21 +1291,69 @@ class CudaBatchedSequenceCache final : public cache::Cache, return layers; } - std::optional free_column() const { - for (int column = 0; column < max_seqs_; ++column) { - if (seqs_.count(column) == 0) { - return column; + std::optional free_sequence_id() const { + for (int id = 0; id < max_seqs_; ++id) { + if (seqs_.count(id) == 0) { + return id; } } return std::nullopt; } + Error ensure_columns(cudaStream_t stream) { + const int live = static_cast(seqs_.size()); + const int target = live + 1 <= columns_ + ? columns_ + : static_cast(std::min( + max_seqs_ + 1LL, + std::max(live + 1LL, 2LL * (columns_ - 1) + 1))); + std::map next; + std::unordered_set used; + for (const auto& [id, sequence] : seqs_) { + if (sequence.column >= 0) { + ET_CHECK_OR_RETURN_ERROR( + sequence.column < target - 1 && used.insert(sequence.column).second, + InvalidState, + "offgraph_kv: invalid physical owner mapping"); + next.emplace(id, sequence.column); + } + } + for (const auto& [id, sequence] : seqs_) { + if (next.count(id) != 0) { + continue; + } + int column = 0; + while (used.count(column) != 0) { + ++column; + } + ET_CHECK_OR_RETURN_ERROR( + column < target - 1, + InvalidState, + "offgraph_kv: missing physical column"); + next.emplace(id, column); + used.insert(column); + } + if (target != columns_) { + int live_rows = 0; + for (const auto& [id, sequence] : seqs_) { + live_rows = std::max(live_rows, sequence.plan.length()); + } + ET_CHECK_OK_OR_RETURN_ERROR( + pool_.resize_columns(target, live_rows, stream)); + columns_ = target; + } + for (auto& [id, sequence] : seqs_) { + sequence.column = next.at(id); + } + return Error::Ok; + } + // Copies rows [0, keep) of every flat layer, and a ring layer's whole ring, // from one column to another, ordered behind the previous step: the copies // run on this thread's stream, which may not be the stream that step wrote // on. - Error copy_column(int from, int to, int keep) { - ET_CHECK_OK_OR_RETURN_ERROR(pool_.follow_previous_step(pool_.stream())); + Error copy_column(int from, int to, int keep, cudaStream_t stream) { + ET_CHECK_OK_OR_RETURN_ERROR(pool_.follow_previous_step(stream)); for (size_t index = 0; index < geometry_.layers.size(); ++index) { const cache::LayerGeometry& layer = geometry_.layers[index]; const size_t slot = static_cast(layer.n_kv_heads) * @@ -1227,12 +1373,12 @@ class CudaBatchedSequenceCache final : public cache::Cache, slot, static_cast(rows), cudaMemcpyDeviceToDevice, - pool_.stream()); + stream); if (error != cudaSuccess) { // Earlier layers may already have queued copies into the free // column. Fence them before a failed clone lets that column be // reused. - (void)pool_.synchronize(); + (void)cudaStreamSynchronize(stream); ET_LOG( Error, "offgraph_kv: cannot copy a sequence's history: %s", @@ -1257,7 +1403,8 @@ class CudaBatchedSequenceCache final : public cache::Cache, std::tuple{ kSeqInfoBuffer, cols_bytes, - static_cast(max_segments_) * 4 * sizeof(int32_t)}}) { + static_cast(max_segments_) * kSequenceInfoFields * + sizeof(int32_t)}}) { const cudaError_t error = cudaMemcpyAsync( pool_.side_buffer(index), staging_ + offset, @@ -1331,10 +1478,12 @@ class CudaBatchedSequenceCache final : public cache::Cache, const cache::CacheGeometry geometry_; const cache::CacheConfig cfg_; const int max_seqs_; - const int columns_; + const bool grow_columns_; const int max_write_; const int max_segments_; const std::optional dflash_block_size_; + int columns_; + bool inflight_{false}; std::vector layer_rows_; CudaKVPool pool_; std::map seqs_; @@ -1344,8 +1493,7 @@ class CudaBatchedSequenceCache final : public cache::Cache, size_t staging_bytes_{0}; cudaEvent_t staged_{nullptr}; bool validated_{false}; - // Set when a clear() fence fails; prepare/commit refuse until a later - // clear() fences cleanly. + // A failed device fence requires a successful clear(). bool poisoned_{false}; Error error_{Error::Ok}; }; @@ -1428,7 +1576,8 @@ std::shared_ptr make_cuda_batched_sequence_kv_cache( return nullptr; } // The storage is one column per sequence and the step buffers are declared - // [max_write] and [segments, 4]; all are fixed by the program. + // [max_write] and [segments, 5]. The program declares the maximum width; + // runtime admission determines the allocated physical width. if (!cfg.max_seqs || !cfg.max_write || *cfg.max_write > cfg.capacity || (geometry.dflash_block_size && (*geometry.dflash_block_size <= 0 || @@ -1440,7 +1589,7 @@ std::shared_ptr make_cuda_batched_sequence_kv_cache( return nullptr; } return std::make_shared( - geometry, cfg, storage_dtype); + geometry, cfg, storage_dtype, !geometry.dflash_block_size.has_value()); } runtime::Error attach_offgraph_kv_cache( diff --git a/backends/cuda/runtime/cuda_kv_cache.h b/backends/cuda/runtime/cuda_kv_cache.h index 82430e40e3e..139a1db7313 100644 --- a/backends/cuda/runtime/cuda_kv_cache.h +++ b/backends/cuda/runtime/cuda_kv_cache.h @@ -30,10 +30,16 @@ struct OffGraphKVMetrics { int64_t logical_length{0}; // Rows currently allocated for each flat layer. int64_t flat_capacity{0}; - // Times flat storage has been reallocated. Every growth moves the storage, - // so this also identifies the addresses a compiled program was bound to. + // Times flat row storage has grown. Column resizes are counted separately. int64_t growth_count{0}; + // Live K/V allocations, excluding step buffers and allocator retention. int64_t allocated_bytes{0}; + // Physical/declared widths include the final scratch column. + int64_t physical_columns{0}; + int64_t declared_columns{0}; + // Logical owners, including cloned prefix owners. + int64_t live_sequences{0}; + int64_t column_resize_count{0}; }; // Backend face of the off-graph KV cache: what the CUDA delegate needs from @@ -82,7 +88,20 @@ class CudaKVCache { cudaStream_t stream) = 0; virtual runtime::Error commit_step(int64_t write_length) = 0; + // A prepared forward failed. Fence its queued work before permitting + // storage to move again. Claimed logical rows are not rolled back. + virtual runtime::Error abort_step() { + return runtime::Error::Ok; + } + virtual OffGraphKVMetrics metrics() const = 0; + + // Sequence-layout captures/launches and failed captures for a named method. + // Other layouts do not expose these counters. + // Read between executes under the executor's engine-thread contract. + virtual CudaGraphMetrics graph_metrics(std::string_view) const { + return {}; + } }; // Compile spec naming where a method's inputs carry the step width. @@ -194,7 +213,7 @@ std::shared_ptr make_cuda_cell_kv_cache( const cache::CacheConfig& cfg); // Segments of a batched-sequence step: runs of one sequence's query rows. The -// program declares its seq_info buffer [segments, 4] from the same rule. +// program declares seq_info [segments, 5]. inline int batched_sequence_max_segments(int max_seqs) { return 2 * max_seqs; } @@ -208,7 +227,12 @@ inline int batched_sequence_max_segments(int max_seqs) { // fix shapes the program declared, so they must match the export exactly. // Every layer starts at cfg.initial_capacity rows and grows geometrically: a // flat layer to cfg.capacity, a ring layer to min(capacity, window + -// max_write - 1). +// max_write - 1). Physical owner columns start at one and grow on admission +// up to cfg.max_seqs, with one additional scratch column. DFlash retains its +// declared width; both paths use the same five-field sequence metadata. +// A column resize temporarily holds both the old and replacement storage. +// Admission can therefore fail below max_seqs if there is insufficient free +// device memory; the existing owners and their KV remain usable. std::shared_ptr make_cuda_batched_sequence_kv_cache( const cache::CacheGeometry& geometry, const cache::CacheConfig& cfg); diff --git a/backends/cuda/runtime/cuda_kv_pool.cpp b/backends/cuda/runtime/cuda_kv_pool.cpp index 74fcf6a2be8..30fcc255182 100644 --- a/backends/cuda/runtime/cuda_kv_pool.cpp +++ b/backends/cuda/runtime/cuda_kv_pool.cpp @@ -56,14 +56,18 @@ CudaKVPool::CudaKVPool( std::vector layers, std::vector side_buffers, slimc10::ScalarType storage_dtype, - int64_t initial_rows) + int64_t initial_rows, + int declared_columns, + int initial_columns) : layers_(std::move(layers)), side_specs_(std::move(side_buffers)), storage_dtype_(storage_dtype), - initial_rows_(initial_rows) { + initial_rows_(initial_rows / declared_columns * initial_columns), + declared_columns_(declared_columns), + columns_(initial_columns) { for (const Layer& layer : layers_) { if (layer.growable) { - max_rows_ = std::max(max_rows_, layer.declared_rows); + max_rows_ = std::max(max_rows_, physical_limit(layer)); } } } @@ -161,7 +165,7 @@ Error CudaKVPool::prepare( return Error::Ok; } -Error CudaKVPool::mark_step_done() { +Error CudaKVPool::mark_step_done(cudaStream_t stream) { const auto device = CUDAGuard::create(device_); ET_CHECK_OK_OR_RETURN_ERROR(device.error()); if (last_step_done_ == nullptr) { @@ -173,12 +177,13 @@ Error CudaKVPool::mark_step_done() { "offgraph_kv: cannot create the step event: %s", cudaGetErrorString(error)); } - const cudaError_t error = cudaEventRecord(last_step_done_, stream_); + const cudaError_t error = cudaEventRecord(last_step_done_, stream); ET_CHECK_OR_RETURN_ERROR( error == cudaSuccess, Internal, "offgraph_kv: cannot record the step event: %s", cudaGetErrorString(error)); + stream_ = stream; return Error::Ok; } @@ -220,6 +225,10 @@ size_t CudaKVPool::row_bytes(const Layer& layer) const { slimc10::elementSize(storage_dtype_); } +int64_t CudaKVPool::physical_limit(const Layer& layer) const { + return layer.declared_rows / declared_columns_ * columns_; +} + // BSHD at the declared rows: no stride depends on the rows, so the storage // behind it may hold fewer. std::vector CudaKVPool::layer_sizes(const Layer& layer) { @@ -295,7 +304,7 @@ Error CudaKVPool::allocate_initial(int64_t required_rows, cudaStream_t stream) { }; for (const Layer& layer : layers_) { const int64_t rows = layer.growable - ? std::min(growable_rows, layer.declared_rows) + ? std::min(growable_rows, physical_limit(layer)) : layer.declared_rows; Allocation allocation; const Error error = allocate_layer(layer, rows, stream, allocation); @@ -377,7 +386,7 @@ Error CudaKVPool::grow( }; for (size_t index = 0; index < layers_.size(); ++index) { const Layer& layer = layers_[index]; - const int64_t rows = std::min(new_rows, layer.declared_rows); + const int64_t rows = std::min(new_rows, physical_limit(layer)); if (!layer.growable || rows <= allocations_.at(index).rows) { continue; } @@ -418,6 +427,32 @@ Error CudaKVPool::grow( } rows_ = new_rows; growth_count_++; + invalidate_bindings(); + ET_LOG( + Info, + "offgraph_kv: grew flat_capacity=%lld->%lld allocated_bytes=%lld " + "growth_count=%lld", + static_cast(old_rows), + static_cast(new_rows), + static_cast(allocated_bytes_), + static_cast(growth_count_)); + return Error::Ok; +} + +CudaGraphMetrics CudaKVPool::graph_metrics(std::string_view method) const { + CudaGraphMetrics result; + for (const auto& [handle, descriptors] : descriptors_) { + if (handle->method_name == method) { + const auto& metrics = handle->cuda_graph_state.metrics; + result.captures += metrics.captures; + result.replays += metrics.replays; + result.capture_failures += metrics.capture_failures; + } + } + return result; +} + +void CudaKVPool::invalidate_bindings() { // Every program sharing this pool now points at freed storage: drop the // bindings so each rebinds before its next run, and any captured CUDA graph // so it is captured again against the new storage. Prefill usually grows @@ -437,14 +472,123 @@ Error CudaKVPool::grow( graph.warmup_remaining = std::max(graph.warmup_remaining, 1); } } +} + +Error CudaKVPool::resize_columns( + int columns, + int64_t live_rows, + cudaStream_t stream) { + ET_CHECK_OR_RETURN_ERROR( + declared_columns_ > 1 && columns >= columns_ && + columns <= declared_columns_ && live_rows >= 0, + InvalidArgument, + "offgraph_kv: invalid physical columns %d/%d", + columns, + declared_columns_); + for (const Layer& layer : layers_) { + ET_CHECK_OR_RETURN_ERROR( + layer.growable && layer.declared_rows % declared_columns_ == 0, + InvalidArgument, + "offgraph_kv: physical-column resizing needs growable whole-row layers"); + } + if (!allocated_) { + initial_rows_ = initial_rows_ / columns_ * columns; + max_rows_ = max_rows_ / columns_ * columns; + columns_ = columns; + return Error::Ok; + } + if (columns == columns_) { + return Error::Ok; + } + const auto device = CUDAGuard::create(device_); + ET_CHECK_OK_OR_RETURN_ERROR(device.error()); + // Fence the pool's previous work, including another thread's PTDS, without + // waiting for unrelated work on the device. + ET_CHECK_OK_OR_RETURN_ERROR(follow_previous_step(stream)); + ET_CHECK_OR_RETURN_ERROR( + cudaStreamSynchronize(stream) == cudaSuccess, + Internal, + "offgraph_kv: cannot finish the previous column step"); + stream_ = stream; + const int old_columns = columns_; + std::vector replacements; + replacements.reserve(layers_.size()); + auto roll_back = [&]() { + for (size_t index = 0; index < replacements.size(); ++index) { + discard(layers_[index], replacements[index], stream); + } + (void)cudaStreamSynchronize(stream); + }; + for (size_t index = 0; index < layers_.size(); ++index) { + const int64_t logical_rows = allocations_[index].rows / old_columns; + Allocation replacement; + const Error error = allocate_layer( + layers_[index], logical_rows * columns, stream, replacement); + if (error != Error::Ok) { + roll_back(); + return error; + } + replacements.push_back(replacement); + } + for (size_t index = 0; index < layers_.size(); ++index) { + const Allocation& current = allocations_[index]; + const Allocation& replacement = replacements[index]; + const size_t slot = row_bytes(layers_[index]); + const size_t logical_rows = + static_cast(std::min(live_rows, current.rows / old_columns)); + if (logical_rows == 0) { + continue; + } + for (const auto& [dst, src] : + {std::pair{replacement.k, current.k}, + std::pair{replacement.v, current.v}}) { + const cudaError_t error = cudaMemcpy2DAsync( + dst, + slot * columns, + src, + slot * old_columns, + slot * (old_columns - 1), + logical_rows, + cudaMemcpyDeviceToDevice, + stream); + if (error != cudaSuccess) { + ET_LOG( + Error, + "offgraph_kv: column copy failed: %s", + cudaGetErrorString(error)); + roll_back(); + return Error::Internal; + } + } + } + + const cudaError_t synchronize_error = cudaStreamSynchronize(stream); + if (synchronize_error != cudaSuccess) { + ET_LOG( + Error, + "offgraph_kv: column copy fence failed: %s", + cudaGetErrorString(synchronize_error)); + roll_back(); + return Error::Internal; + } + invalidate_bindings(); + for (size_t index = 0; index < layers_.size(); ++index) { + discard(layers_[index], allocations_[index], stream); + } + allocations_ = std::move(replacements); + rows_ = rows_ / old_columns * columns; + initial_rows_ = initial_rows_ / old_columns * columns; + max_rows_ = max_rows_ / old_columns * columns; + columns_ = columns; + column_resize_count_++; ET_LOG( Info, - "offgraph_kv: grew flat_capacity=%lld->%lld allocated_bytes=%lld " - "growth_count=%lld", - static_cast(old_rows), - static_cast(new_rows), + "offgraph_kv: resized columns=%d->%d " + "allocated_bytes=%lld column_resize_count=%lld", + old_columns, + columns_, static_cast(allocated_bytes_), - static_cast(growth_count_)); + static_cast(column_resize_count_)); return Error::Ok; } @@ -573,7 +717,7 @@ Error CudaKVPool::check_compiled( InvalidProgram, "offgraph_kv: %s is compiled with shape %s but the cache declares %s; " "the cache's capacity, max_write, window or head geometry does not " - "match the program", + "match the program, or the program needs re-export for this runtime", name.c_str(), shape_string(compiled_sizes->second).data(), shape_string(sizes).data()); diff --git a/backends/cuda/runtime/cuda_kv_pool.h b/backends/cuda/runtime/cuda_kv_pool.h index c78f85431bd..dcf3debca17 100644 --- a/backends/cuda/runtime/cuda_kv_pool.h +++ b/backends/cuda/runtime/cuda_kv_pool.h @@ -11,8 +11,10 @@ #include #include #include +#include #include #include +#include #include #include @@ -57,7 +59,9 @@ class CudaKVPool final { std::vector layers, std::vector side_buffers, ::executorch::backends::aoti::slim::c10::ScalarType storage_dtype, - int64_t initial_rows); + int64_t initial_rows, + int declared_columns = 1, + int initial_columns = 1); CudaKVPool(const CudaKVPool&) = delete; CudaKVPool& operator=(const CudaKVPool&) = delete; @@ -82,9 +86,16 @@ class CudaKVPool final { runtime::Error prepare(int64_t required_rows, int64_t live_rows, cudaStream_t stream); + // Flattened row counts remain multiples of the current physical width. + // Copies the old owner columns in place; the scratch column is not retained. + // live_rows is the logical prefix, capped by each ring. Growth commits only + // after all copies pass; smaller widths are rejected. + runtime::Error + resize_columns(int columns, int64_t live_rows, cudaStream_t stream); + // Records where the step's work ends on its stream, for the next step to // follow if it runs on another. - runtime::Error mark_step_done(); + runtime::Error mark_step_done(cudaStream_t stream); // Orders `stream` behind the previous step's stream, so work issued on // another host thread (where cudaStreamPerThread names another stream) still @@ -94,6 +105,8 @@ class CudaKVPool final { // Host fence on the pool's device before cells can be reclaimed or reset. runtime::Error synchronize(bool all_streams = false); + CudaGraphMetrics graph_metrics(std::string_view method) const; + // Points `handle`'s constants at the current storage. Cached until storage // moves. Precondition: allocated(). runtime::Error bind(CudaDelegateHandle* handle); @@ -127,6 +140,12 @@ class CudaKVPool final { int64_t growth_count() const { return growth_count_; } + int columns() const { + return columns_; + } + int64_t column_resize_count() const { + return column_resize_count_; + } private: struct Allocation { @@ -150,6 +169,8 @@ class CudaKVPool final { }; size_t row_bytes(const Layer& layer) const; + int64_t physical_limit(const Layer& layer) const; + void invalidate_bindings(); static std::vector layer_sizes(const Layer& layer); runtime::Error allocate_layer( const Layer& layer, @@ -174,6 +195,9 @@ class CudaKVPool final { ::executorch::backends::aoti::slim::c10::ScalarType storage_dtype_; int64_t initial_rows_; int64_t max_rows_{0}; + const int declared_columns_; + int columns_; + int64_t column_resize_count_{0}; int device_{0}; bool device_known_{false}; diff --git a/backends/cuda/runtime/test/test_cuda_backend_execute.cpp b/backends/cuda/runtime/test/test_cuda_backend_execute.cpp index ecdaef11f7e..0c7d99a3fed 100644 --- a/backends/cuda/runtime/test/test_cuda_backend_execute.cpp +++ b/backends/cuda/runtime/test/test_cuda_backend_execute.cpp @@ -8,6 +8,9 @@ #include #include +#if defined(EXECUTORCH_BUILD_EXTENSION_LLM) +#include +#endif #include #include @@ -20,6 +23,7 @@ using namespace ::executorch::backends::cuda; namespace { bool program_ran = false; +Error program_error = Error::Ok; Error one_tensor(aoti::AOTInductorModelContainerHandle, size_t* count) { *count = 1; @@ -40,7 +44,7 @@ Error fake_run( for (size_t i = 0; i < num_inputs; ++i) { delete reinterpret_cast(inputs[i]); } - return Error::Ok; + return program_error; } class CudaBackendExecuteTest : public ::testing::Test { @@ -59,6 +63,7 @@ class CudaBackendExecuteTest : public ::testing::Test { ASSERT_EQ(cudaMalloc(&input_, sizeof(float) * 4), cudaSuccess); ASSERT_EQ(cudaMalloc(&output_, sizeof(float) * 4), cudaSuccess); program_ran = false; + program_error = Error::Ok; } void TearDown() override { @@ -124,4 +129,180 @@ TEST_F(CudaBackendExecuteTest, OutputWithBufferRuns) { EXPECT_TRUE(program_ran); } +TEST_F( + CudaBackendExecuteTest, + GraphMetricsCountCapturesAndReplayAcrossRecapture) { + if (!handle_.cuda_graph_state.start_warmup()) { + GTEST_SKIP() << "CUDA graph allocator unavailable"; + } + for (int i = 0; i < 8; ++i) { + ASSERT_EQ(execute(input_, output_), Error::Ok); + } + const auto first = handle_.cuda_graph_state.metrics; + EXPECT_EQ(first.captures, 1); + EXPECT_GT(first.replays, first.captures); + EXPECT_EQ(first.capture_failures, 0); + handle_.cuda_graph_state.recapture(); + for (int i = 0; i < 4; ++i) { + ASSERT_EQ(execute(input_, output_), Error::Ok); + } + EXPECT_EQ(handle_.cuda_graph_state.metrics.captures, 2); + EXPECT_GT(handle_.cuda_graph_state.metrics.replays, first.replays); + EXPECT_EQ(handle_.cuda_graph_state.metrics.capture_failures, 0); +} + +TEST(CudaGraphStateTest, MetricsSurviveMoveAndResourceRelease) { + CudaGraphState source; + source.metrics = {2, 11, 1}; + CudaGraphState moved(std::move(source)); + EXPECT_EQ(source.metrics.captures, 0); + EXPECT_EQ(moved.metrics.captures, 2); + moved.release(); + EXPECT_EQ(moved.metrics.replays, 11); + CudaGraphState assigned; + assigned = std::move(moved); + EXPECT_EQ(moved.metrics.replays, 0); + EXPECT_EQ(assigned.metrics.captures, 2); + EXPECT_EQ(assigned.metrics.replays, 11); + EXPECT_EQ(assigned.metrics.capture_failures, 1); +} + +#if defined(EXECUTORCH_BUILD_EXTENSION_LLM) +class PreparedCache final : public CudaKVCache { + public: + Result note_handle(CudaDelegateHandle*) override { + return false; + } + void forget_handle(CudaDelegateHandle*) override {} + Error rebind_for_execute(CudaDelegateHandle*) override { + return rebind_error; + } + Error prepare_step(int64_t width, cudaStream_t) override { + ++prepares; + EXPECT_EQ(width, 4); + if (prepared) { + return Error::InvalidState; + } + prepared = prepare_error == Error::Ok; + return prepare_error; + } + Error commit_step(int64_t width) override { + ++commits; + EXPECT_EQ(width, 4); + if (commit_error == Error::Ok) { + prepared = false; + } + return commit_error; + } + Error abort_step() override { + ++aborts; + if (abort_error == Error::Ok) { + prepared = false; + } + return abort_error; + } + OffGraphKVMetrics metrics() const override { + return {}; + } + + bool prepared = false; + int prepares = 0; + int commits = 0; + int aborts = 0; + Error prepare_error = Error::Ok; + Error rebind_error = Error::Ok; + Error commit_error = Error::Ok; + Error abort_error = Error::Ok; +}; + +TEST_F(CudaBackendExecuteTest, FailedPreparationDoesNotAbort) { + PreparedCache cache; + handle_.kv_cache = &cache; + cache.prepare_error = Error::MemoryAllocationFailed; + EXPECT_EQ(execute(input_, output_), Error::MemoryAllocationFailed); + EXPECT_FALSE(program_ran); + EXPECT_FALSE(cache.prepared); + EXPECT_EQ(cache.prepares, 1); + EXPECT_EQ(cache.commits, 0); + EXPECT_EQ(cache.aborts, 0); +} + +TEST_F(CudaBackendExecuteTest, FailedRebindAbortsAndAllowsNextForward) { + PreparedCache cache; + handle_.kv_cache = &cache; + cache.rebind_error = Error::InvalidArgument; + EXPECT_EQ(execute(input_, output_), Error::InvalidArgument); + EXPECT_FALSE(program_ran); + EXPECT_FALSE(cache.prepared); + EXPECT_EQ(cache.aborts, 1); + EXPECT_EQ(cache.commits, 0); + + cache.rebind_error = Error::Ok; + EXPECT_EQ(execute(input_, output_), Error::Ok); + EXPECT_TRUE(program_ran); + EXPECT_FALSE(cache.prepared); + EXPECT_EQ(cache.prepares, 2); + EXPECT_EQ(cache.commits, 1); + EXPECT_EQ(cache.aborts, 1); +} + +TEST_F(CudaBackendExecuteTest, FailedProgramAbortsAndAllowsNextForward) { + PreparedCache cache; + handle_.kv_cache = &cache; + program_error = Error::Internal; + EXPECT_EQ(execute(input_, output_), Error::Internal); + EXPECT_TRUE(program_ran); + EXPECT_FALSE(cache.prepared); + EXPECT_EQ(cache.commits, 0); + EXPECT_EQ(cache.aborts, 1); + + program_error = Error::Ok; + EXPECT_EQ(execute(input_, output_), Error::Ok); + EXPECT_FALSE(cache.prepared); + EXPECT_EQ(cache.prepares, 2); + EXPECT_EQ(cache.commits, 1); + EXPECT_EQ(cache.aborts, 1); +} + +TEST_F(CudaBackendExecuteTest, FailedCommitAbortsAndAllowsNextForward) { + PreparedCache cache; + handle_.kv_cache = &cache; + cache.commit_error = Error::Internal; + EXPECT_EQ(execute(input_, output_), Error::Internal); + EXPECT_TRUE(program_ran); + EXPECT_FALSE(cache.prepared); + EXPECT_EQ(cache.commits, 1); + EXPECT_EQ(cache.aborts, 1); + + cache.commit_error = Error::Ok; + EXPECT_EQ(execute(input_, output_), Error::Ok); + EXPECT_FALSE(cache.prepared); + EXPECT_EQ(cache.prepares, 2); + EXPECT_EQ(cache.commits, 2); + EXPECT_EQ(cache.aborts, 1); +} + +TEST_F(CudaBackendExecuteTest, SuccessfulForwardCommitsWithoutAbort) { + PreparedCache cache; + handle_.kv_cache = &cache; + EXPECT_EQ(execute(input_, output_), Error::Ok); + EXPECT_TRUE(program_ran); + EXPECT_FALSE(cache.prepared); + EXPECT_EQ(cache.prepares, 1); + EXPECT_EQ(cache.commits, 1); + EXPECT_EQ(cache.aborts, 0); +} + +TEST_F(CudaBackendExecuteTest, FailedAbortPreservesOriginalError) { + PreparedCache cache; + handle_.kv_cache = &cache; + cache.rebind_error = Error::InvalidArgument; + cache.abort_error = Error::Internal; + EXPECT_EQ(execute(input_, output_), Error::InvalidArgument); + EXPECT_FALSE(program_ran); + EXPECT_TRUE(cache.prepared); + EXPECT_EQ(cache.aborts, 1); +} +#endif + } // namespace diff --git a/backends/cuda/runtime/test/test_cuda_kv_cache.cpp b/backends/cuda/runtime/test/test_cuda_kv_cache.cpp index 5e4881224f7..1e6287f0e51 100644 --- a/backends/cuda/runtime/test/test_cuda_kv_cache.cpp +++ b/backends/cuda/runtime/test/test_cuda_kv_cache.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -21,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -1230,7 +1232,7 @@ TEST_F(CudaKVPoolTest, SideBuffersBindAtFixedAddressesAcrossGrowth) { cudaMemcpyDeviceToHost), cudaSuccess); EXPECT_EQ(cells_host, std::vector(16, 0)); - ASSERT_EQ(pool->mark_step_done(), Error::Ok); + ASSERT_EQ(pool->mark_step_done(pool->stream()), Error::Ok); // Growth moves only the growable layer. ASSERT_EQ(pool->prepare(5, 3, cudaStreamPerThread), Error::Ok); @@ -1259,7 +1261,7 @@ TEST_F(CudaKVPoolTest, GrowthCarriesLiveRowsAndCapsAtDeclaredRows) { history.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), cudaSuccess); - ASSERT_EQ(pool->mark_step_done(), Error::Ok); + ASSERT_EQ(pool->mark_step_done(pool->stream()), Error::Ok); // Asking past twice the rows grows straight to what is asked; past the // declared rows it is capped there. @@ -2197,8 +2199,16 @@ class CudaBatchedSequenceCacheTest : public CudaKVCacheTest { std::optional block_size = std::nullopt) { auto geometry = flat_and_ring(kWindow); geometry.dflash_block_size = block_size; - return cu::make_cuda_batched_sequence_kv_cache( + auto result = cu::make_cuda_batched_sequence_kv_cache( geometry, sequence_config(initial)); + if (result && !block_size) { + auto* control = result->as(); + for (int index = 0; index < kMaxSeqs; ++index) { + EXPECT_TRUE(control->seq_new().has_value()); + } + control->clear(); + } + return result; } // What a program lowered in the batched-sequence layout declares for make(). @@ -2229,7 +2239,7 @@ class CudaBatchedSequenceCacheTest : public CudaKVCacheTest { container, "__et_offgraph_kv_seq_info", slimc10::ScalarType::Int, - {kSegments, 4}); + {kSegments, 5}); return container; } @@ -2245,9 +2255,9 @@ class CudaBatchedSequenceCacheTest : public CudaKVCacheTest { return values; } - using Info = std::vector>; + using Info = std::vector>; static Info read_info(void* device, int rows) { - std::vector flat(kSegments * 4); + std::vector flat(kSegments * 5); EXPECT_EQ( cudaMemcpy( flat.data(), @@ -2257,8 +2267,8 @@ class CudaBatchedSequenceCacheTest : public CudaKVCacheTest { cudaSuccess); Info out(rows); for (int i = 0; i < rows; ++i) { - for (int j = 0; j < 4; ++j) { - out[i][j] = flat[i * 4 + j]; + for (int j = 0; j < 5; ++j) { + out[i][j] = flat[i * 5 + j]; } } return out; @@ -2306,7 +2316,10 @@ TEST_F(CudaBatchedSequenceCacheTest, EachSequenceWritesItsOwnColumn) { std::vector({0, 0, 0, 1, 1, kMaxSeqs, kMaxSeqs})); EXPECT_EQ( read_info(fake.bound["seq_info"].data, 3), - Info({{0, 3, 0, 3}, {3, 2, 1, 2}, {0, 0, 0, 0}})); + Info( + {{0, 3, 0, 3, kColumns}, + {3, 2, 1, 2, kColumns}, + {0, 0, 0, 0, kColumns}})); EXPECT_EQ( fake.bound["f_k"].sizes, std::vector({1, kCapacity * kColumns, kHeads, kDim})); @@ -2319,7 +2332,7 @@ TEST_F(CudaBatchedSequenceCacheTest, EachSequenceWritesItsOwnColumn) { read_cols(fake.bound["seq_cols"].data, 2), std::vector({1, 0})); EXPECT_EQ( read_info(fake.bound["seq_info"].data, 2), - Info({{0, 1, 1, 3}, {1, 1, 0, 4}})); + Info({{0, 1, 1, 3, kColumns}, {1, 1, 0, 4, kColumns}})); EXPECT_EQ(control->pos(a), 4); EXPECT_EQ(control->pos(b), 3); EXPECT_EQ(kv->metrics().logical_length, 4); @@ -2406,7 +2419,9 @@ TEST_F(CudaBatchedSequenceCacheTest, CloneCopiesThePrefixIntoAFreeColumn) { } // The clone continues at its own length. ASSERT_EQ(step(*cache_ptr, handle, {*c}), Error::Ok); - EXPECT_EQ(read_info(fake.bound["seq_info"].data, 1), Info({{0, 1, *c, 4}})); + EXPECT_EQ( + read_info(fake.bound["seq_info"].data, 1), + Info({{0, 1, *c, 4, kColumns}})); EXPECT_FALSE(control->seq_clone(99, std::nullopt).has_value()); kv->forget_handle(&handle); } @@ -2429,6 +2444,25 @@ TEST_F(CudaBatchedSequenceCacheTest, ClearRecoversAbandonedDFlashStep) { kv->forget_handle(&handle); } +TEST_F(CudaBatchedSequenceCacheTest, PendingDFlashOwnerCanClose) { + auto cache_ptr = make(kCapacity, 2); + auto* control = cache_ptr->as(); + auto* kv = cache_ptr->as(); + auto fake = container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + const auto id = control->seq_new(); + ASSERT_TRUE(id.has_value()); + ASSERT_TRUE(control->declare_step({*id, *id, *id})); + ASSERT_EQ(kv->prepare_step(3, cudaStreamPerThread), Error::Ok); + ASSERT_TRUE(control->seq_rm(*id)); + EXPECT_EQ(kv->commit_step(3), Error::Ok); + EXPECT_EQ(control->seq_new(), id); + EXPECT_EQ(control->pos(*id), 0); + ASSERT_EQ(step(*cache_ptr, handle, {*id, *id, *id}), Error::Ok); + kv->forget_handle(&handle); +} + TEST_F(CudaBatchedSequenceCacheTest, CloneOnAnotherStreamWaitsForTheCopy) { auto cache_ptr = make(kCapacity); auto* control = cache_ptr->as(); @@ -2716,7 +2750,7 @@ TEST_F(CudaBatchedSequenceCacheTest, DFlashQueriesOnlyEachOwnersBlock) { // Queries pack block by block; each sees its context and its block. EXPECT_EQ( read_info(fake.bound["seq_info"].data, 2), - Info({{0, kBlock, 0, 5}, {kBlock, kBlock, 1, 3}})); + Info({{0, kBlock, 0, 5, kColumns}, {kBlock, kBlock, 1, 3, kColumns}})); // The blocks are dropped after the forward. EXPECT_EQ(control->pos(a), 3); EXPECT_EQ(control->pos(b), 1); @@ -2726,6 +2760,761 @@ TEST_F(CudaBatchedSequenceCacheTest, DFlashQueriesOnlyEachOwnersBlock) { kv->forget_handle(&handle); } +namespace { + +class CudaRuntimeColumnCacheTest : public CudaKVCacheTest { + protected: + static constexpr int kCapacity = 64; + static constexpr int kMaxWrite = 32; + static constexpr int kMaxSeqs = 21; + static constexpr int kDeclaredColumns = kMaxSeqs + 1; + static constexpr int kSegments = 2 * kMaxSeqs; + + static std::shared_ptr make() { + auto cfg = config(kCapacity, 4, kMaxWrite); + cfg.max_seqs = kMaxSeqs; + return cu::make_cuda_batched_sequence_kv_cache(flat_and_ring(2), cfg); + } + + static FakeContainer container(int info_width = 5) { + auto fake = flat_and_ring_container(); + fake.internal_names.insert( + fake.internal_names.end(), {"seq_cols", "seq_info"}); + fake.fqns.insert( + fake.fqns.end(), + {"__et_offgraph_kv_seq_cols", "__et_offgraph_kv_seq_info"}); + for (size_t index = 0; index < 4; ++index) { + declare( + fake, + fake.fqns[index], + slimc10::ScalarType::BFloat16, + {1, + (index < 2 ? kCapacity : kMaxWrite + 1) * kDeclaredColumns, + kHeads, + kDim}); + } + declare(fake, fake.fqns[4], slimc10::ScalarType::Long, {kMaxWrite}); + declare( + fake, fake.fqns[5], slimc10::ScalarType::Int, {kSegments, info_width}); + return fake; + } + + static Error step( + cache::Cache& cache, + cu::CudaDelegateHandle& handle, + const std::vector& ids, + int width = 0) { + auto* control = cache.as(); + auto* kv = cache.as(); + if (!control->declare_step(ids)) { + return Error::InvalidArgument; + } + width = width == 0 ? static_cast(ids.size()) : width; + ET_CHECK_OK_OR_RETURN_ERROR(kv->prepare_step(width, cudaStreamPerThread)); + ET_CHECK_OK_OR_RETURN_ERROR(kv->rebind_for_execute(&handle)); + return kv->commit_step(width); + } + + static std::vector + read_column(void* data, int rows, int columns, int column) { + std::vector out(rows * kRow); + EXPECT_EQ( + cudaMemcpy2D( + out.data(), + kRow * sizeof(uint16_t), + static_cast(data) + column * kRow, + columns * kRow * sizeof(uint16_t), + kRow * sizeof(uint16_t), + rows, + cudaMemcpyDeviceToHost), + cudaSuccess); + return out; + } + + static void seed(FakeContainer& fake, int rows, int columns) { + for (size_t layer = 0; layer < 4; ++layer) { + std::vector values(rows * columns * kRow); + for (int row = 0; row < rows; ++row) { + for (int column = 0; column < columns; ++column) { + for (int element = 0; element < kRow; ++element) { + values[(row * columns + column) * kRow + element] = + static_cast( + 1000 * layer + 100 * row + 20 * column + element); + } + } + } + EXPECT_EQ( + cudaMemcpy( + fake.bound[fake.internal_names[layer]].data, + values.data(), + values.size() * sizeof(uint16_t), + cudaMemcpyHostToDevice), + cudaSuccess); + } + } +}; + +} // namespace + +TEST_F(CudaRuntimeColumnCacheTest, GrowthAndSparseIdsPreserveAllKV) { + auto cache_ptr = make(); + ASSERT_NE(cache_ptr, nullptr); + auto* control = cache_ptr->as(); + auto* kv = cache_ptr->as(); + auto fake = container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + std::vector ids; + int old_columns = 0; + for (const int sessions : {1, 2, 4, 8, 16}) { + const int live_rows = ids.empty() ? 0 : control->pos(ids.front()); + std::vector, 4>> retained(ids.size()); + if (old_columns != 0) { + seed(fake, live_rows, old_columns); + for (size_t owner = 0; owner < retained.size(); ++owner) { + for (size_t layer = 0; layer < 4; ++layer) { + retained[owner][layer] = read_column( + fake.bound[fake.internal_names[layer]].data, + live_rows, + old_columns, + owner); + } + } + } + while (ids.size() < static_cast(sessions)) { + const auto id = control->seq_new(); + ASSERT_TRUE(id.has_value()); + ids.push_back(*id); + } + ASSERT_EQ(step(*cache_ptr, handle, ids), Error::Ok); + const auto metrics = kv->metrics(); + EXPECT_EQ(metrics.physical_columns, sessions + 1); + EXPECT_EQ(metrics.declared_columns, kDeclaredColumns); + EXPECT_EQ(metrics.live_sequences, sessions); + EXPECT_EQ(control->max_seqs(), kMaxSeqs); + EXPECT_EQ( + fake.bound["flat_k"].sizes, + std::vector({1, kCapacity * kDeclaredColumns, kHeads, kDim})); + if (old_columns != 0) { + for (size_t owner = 0; owner < retained.size(); ++owner) { + for (size_t layer = 0; layer < 4; ++layer) { + EXPECT_EQ( + read_column( + fake.bound[fake.internal_names[layer]].data, + live_rows, + sessions + 1, + owner), + retained[owner][layer]); + } + } + } + old_columns = sessions + 1; + } + + // Closing other owners preserves the survivor and the allocated width. + const int32_t survivor = ids[5]; + const int rows = control->pos(survivor); + seed(fake, rows, old_columns); + std::array, 4> retained; + for (size_t layer = 0; layer < 4; ++layer) { + retained[layer] = read_column( + fake.bound[fake.internal_names[layer]].data, rows, old_columns, 5); + } + const int position = control->pos(survivor); + const auto before = kv->metrics(); + for (const int32_t id : ids) { + if (id != survivor) { + ASSERT_TRUE(control->seq_rm(id)); + } + } + const auto after = kv->metrics(); + EXPECT_EQ(after.physical_columns, old_columns); + EXPECT_EQ(after.live_sequences, 1); + EXPECT_EQ(after.flat_capacity, before.flat_capacity); + EXPECT_EQ(control->pos(survivor), position); + EXPECT_EQ(after.allocated_bytes, before.allocated_bytes); + ASSERT_EQ(step(*cache_ptr, handle, {survivor}, 4), Error::Ok); + for (size_t layer = 0; layer < 4; ++layer) { + EXPECT_EQ( + read_column( + fake.bound[fake.internal_names[layer]].data, rows, old_columns, 5), + retained[layer]); + } + std::array cols{}; + ASSERT_EQ( + cudaMemcpy( + cols.data(), + fake.bound["seq_cols"].data, + sizeof(cols), + cudaMemcpyDeviceToHost), + cudaSuccess); + EXPECT_EQ(cols, (std::array{5, 16, 16, 16})); + std::vector info(kSegments * 5); + ASSERT_EQ( + cudaMemcpy( + info.data(), + fake.bound["seq_info"].data, + info.size() * sizeof(int32_t), + cudaMemcpyDeviceToHost), + cudaSuccess); + EXPECT_EQ(info[2], 5); + EXPECT_EQ(info[3], position + 1); + for (int row = 0; row < kSegments; ++row) { + EXPECT_EQ(info[row * 5 + 4], old_columns); + } + kv->forget_handle(&handle); +} + +TEST_F(CudaRuntimeColumnCacheTest, CloneCopiesWrappedRingHistoryAfterGrowth) { + auto cache_ptr = make(); + auto* control = cache_ptr->as(); + auto* kv = cache_ptr->as(); + auto fake = container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + const auto source = control->seq_new(); + ASSERT_TRUE(source.has_value()); + ASSERT_EQ( + step(*cache_ptr, handle, std::vector(32, *source)), Error::Ok); + ASSERT_EQ( + step(*cache_ptr, handle, std::vector(8, *source)), Error::Ok); + std::array, 4> expected; + for (size_t layer = 0; layer < 4; ++layer) { + const int rows = layer < 2 ? 40 : 33; + std::vector values(rows * 2 * kRow); + for (int row = 0; row < rows; ++row) { + for (int column = 0; column < 2; ++column) { + for (int element = 0; element < kRow; ++element) { + const uint16_t value = + 1000 * layer + 100 * row + 20 * column + element; + values[(row * 2 + column) * kRow + element] = value; + if (column == 0) { + expected[layer].push_back(value); + } + } + } + } + ASSERT_EQ( + cudaMemcpy( + fake.bound[fake.internal_names[layer]].data, + values.data(), + values.size() * sizeof(uint16_t), + cudaMemcpyHostToDevice), + cudaSuccess); + } + const auto clone = control->seq_clone(*source, 40); + ASSERT_TRUE(clone.has_value()); + EXPECT_EQ(kv->metrics().physical_columns, 3); + ASSERT_EQ(kv->rebind_for_execute(&handle), Error::Ok); + for (size_t layer = 0; layer < 4; ++layer) { + const int rows = layer < 2 ? 40 : 33; + EXPECT_EQ( + read_column(fake.bound[fake.internal_names[layer]].data, rows, 3, 0), + read_column(fake.bound[fake.internal_names[layer]].data, rows, 3, 1)); + } + ASSERT_TRUE(control->seq_rm(*source)); + ASSERT_EQ(kv->rebind_for_execute(&handle), Error::Ok); + EXPECT_EQ(control->pos(*clone), 40); + for (size_t layer = 0; layer < 4; ++layer) { + const int rows = layer < 2 ? 40 : 33; + EXPECT_EQ( + read_column(fake.bound[fake.internal_names[layer]].data, rows, 3, 1), + expected[layer]); + } + ASSERT_EQ(step(*cache_ptr, handle, {*clone}), Error::Ok); + EXPECT_EQ(control->pos(*clone), 41); + kv->forget_handle(&handle); +} + +TEST_F(CudaRuntimeColumnCacheTest, DeclaredStepCanClose) { + auto cache_ptr = make(); + auto* control = cache_ptr->as(); + auto* kv = cache_ptr->as(); + auto fake = container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + const auto id = control->seq_new(); + ASSERT_TRUE(id.has_value()); + ASSERT_TRUE(control->declare_step({*id})); + ASSERT_EQ(kv->prepare_step(1, cudaStreamPerThread), Error::Ok); + ASSERT_EQ(kv->commit_step(1), Error::Ok); + ASSERT_TRUE(control->declare_step({*id})); + ASSERT_TRUE(control->seq_rm(*id)); + EXPECT_EQ(kv->prepare_step(1, cudaStreamPerThread), Error::InvalidArgument); + EXPECT_EQ(kv->metrics().live_sequences, 0); + EXPECT_EQ(control->seq_new(), id); + ASSERT_EQ(step(*cache_ptr, handle, {*id}), Error::Ok); + kv->forget_handle(&handle); +} + +TEST_F(CudaRuntimeColumnCacheTest, AbortFencesBeforeCloseAndReuse) { + auto cache_ptr = make(); + auto* control = cache_ptr->as(); + auto* kv = cache_ptr->as(); + auto fake = container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + const auto id = control->seq_new(); + ASSERT_TRUE(id.has_value()); + ASSERT_TRUE(control->declare_step({*id})); + ASSERT_EQ(kv->prepare_step(1, cudaStreamPerThread), Error::Ok); + EXPECT_FALSE(control->seq_clone(*id, std::nullopt).has_value()); + EXPECT_FALSE(control->seq_new().has_value()); + EXPECT_EQ(kv->metrics().live_sequences, 1); + std::atomic finished{false}; + ASSERT_EQ( + cudaLaunchHostFunc( + cudaStreamPerThread, + [](void* state) { + std::this_thread::sleep_for(std::chrono::milliseconds(30)); + static_cast*>(state)->store(true); + }, + &finished), + cudaSuccess); + ASSERT_EQ(kv->abort_step(), Error::Ok); + EXPECT_TRUE(finished.load()); + ASSERT_TRUE(control->seq_rm(*id)); + EXPECT_EQ(control->seq_new(), id); + ASSERT_EQ(step(*cache_ptr, handle, {*id}), Error::Ok); + EXPECT_TRUE(finished.load()); + EXPECT_EQ(control->pos(*id), 1); + EXPECT_EQ(kv->metrics().live_sequences, 1); + kv->forget_handle(&handle); +} + +TEST_F(CudaBatchedSequenceCacheTest, FailedDeclaredStepCanCloseAndReuseId) { + auto cache_ptr = make(/*initial=*/4); + auto* control = cache_ptr->as(); + auto* kv = cache_ptr->as(); + auto fake = container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + const auto id = control->seq_new(); + ASSERT_TRUE(id.has_value()); + ASSERT_TRUE(control->declare_step({*id})); + EXPECT_EQ(kv->prepare_step(0, cudaStreamPerThread), Error::InvalidArgument); + ASSERT_TRUE(control->seq_rm(*id)); + EXPECT_EQ(kv->prepare_step(1, cudaStreamPerThread), Error::InvalidArgument); + EXPECT_EQ(control->seq_new(), id); + ASSERT_EQ(step(*cache_ptr, handle, {*id}), Error::Ok); + kv->forget_handle(&handle); +} + +TEST_F( + CudaRuntimeColumnCacheTest, + AdmissionsGrowGeometricallyAndStepsKeepWidth) { + auto cache_ptr = make(); + auto* control = cache_ptr->as(); + auto* kv = cache_ptr->as(); + auto fake = container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + std::vector ids; + int expected_columns = 2; + for (int count = 1; count <= kMaxSeqs; ++count) { + const auto id = control->seq_new(); + ASSERT_TRUE(id.has_value()); + ids.push_back(*id); + if (count >= expected_columns) { + expected_columns = + std::min(kDeclaredColumns, 2 * (expected_columns - 1) + 1); + } + EXPECT_EQ(kv->metrics().physical_columns, expected_columns) << count; + const int64_t resizes = kv->metrics().column_resize_count; + for (int repeat = 0; repeat < 2; ++repeat) { + ASSERT_EQ(step(*cache_ptr, handle, ids), Error::Ok); + EXPECT_EQ(kv->metrics().physical_columns, expected_columns); + EXPECT_EQ(kv->metrics().column_resize_count, resizes); + } + } + EXPECT_FALSE(control->seq_new().has_value()); + kv->forget_handle(&handle); +} + +TEST_F(CudaRuntimeColumnCacheTest, ActiveStepRejectsResizeUntilExplicitAbort) { + auto cache_ptr = make(); + auto* control = cache_ptr->as(); + auto* kv = cache_ptr->as(); + auto fake = container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + const auto id = control->seq_new(); + ASSERT_TRUE(id.has_value()); + // Simulate a failed forward: prepare runs, commit never does. + ASSERT_TRUE(control->declare_step({*id})); + ASSERT_EQ(kv->prepare_step(1, cudaStreamPerThread), Error::Ok); + const auto before = kv->metrics(); + EXPECT_EQ(kv->prepare_step(1, cudaStreamPerThread), Error::InvalidState); + EXPECT_EQ(kv->metrics().column_resize_count, before.column_resize_count); + EXPECT_EQ(kv->metrics().physical_columns, before.physical_columns); + ASSERT_EQ(kv->abort_step(), Error::Ok); + EXPECT_EQ(kv->abort_step(), Error::Ok); + ASSERT_TRUE(control->declare_step({*id})); + ASSERT_EQ(kv->prepare_step(1, cudaStreamPerThread), Error::Ok); + ASSERT_EQ(kv->commit_step(1), Error::Ok); + EXPECT_EQ(control->pos(*id), 2); + ASSERT_TRUE(control->seq_rm(*id)); + kv->forget_handle(&handle); +} + +TEST_F(CudaRuntimeColumnCacheTest, FourFieldSequenceInfoIsRejected) { + auto cache_ptr = make(); + auto* kv = cache_ptr->as(); + auto fake = container(4); + auto handle = make_handle(fake); + EXPECT_EQ(kv->note_handle(&handle).error(), Error::InvalidProgram); + kv->forget_handle(&handle); +} + +TEST_F(CudaRuntimeColumnCacheTest, OwnerReuseKeepsMappingAndBindings) { + auto cache_ptr = make(); + auto* control = cache_ptr->as(); + auto* kv = cache_ptr->as(); + auto fake = container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + const auto first = control->seq_new(); + const auto second = control->seq_new(); + ASSERT_TRUE(first.has_value()); + ASSERT_TRUE(second.has_value()); + ASSERT_EQ(step(*cache_ptr, handle, {*first, *second}), Error::Ok); + seed(fake, 1, 3); + void* const pointer = fake.bound["flat_k"].data; + const auto before = read_column(pointer, 1, 3, 1); + const auto count = kv->metrics().column_resize_count; + handle.cuda_graph_state.phase = cu::CudaGraphPhase::Warmup; + handle.cuda_graph_state.warmup_remaining = 0; + ASSERT_TRUE(control->seq_rm(*first)); + EXPECT_EQ(control->seq_new(), first); + EXPECT_EQ(kv->metrics().physical_columns, 3); + EXPECT_EQ(kv->metrics().column_resize_count, count); + EXPECT_EQ(fake.bound["flat_k"].data, pointer); + EXPECT_EQ(handle.cuda_graph_state.warmup_remaining, 0); + EXPECT_EQ(read_column(pointer, 1, 3, 1), before); + ASSERT_EQ(step(*cache_ptr, handle, {*first, *second}), Error::Ok); + std::vector> info(2); + ASSERT_EQ( + cudaMemcpy( + info.data(), + fake.bound["seq_info"].data, + info.size() * sizeof(info[0]), + cudaMemcpyDeviceToHost), + cudaSuccess); + EXPECT_EQ( + info, + (std::vector>{{0, 1, 0, 1, 3}, {1, 1, 1, 2, 3}})); + kv->forget_handle(&handle); +} + +TEST_F(CudaRuntimeColumnCacheTest, RegistryGrowsColumnsByDefault) { + auto cfg = config(kCapacity, 4, kMaxWrite); + cfg.max_seqs = kMaxSeqs; + auto built = cache::CacheFactory::global().build( + cu::kCudaBackendId, cache::kind::kBatchedSequence, flat_and_ring(2), cfg); + ASSERT_TRUE(built.ok()); + EXPECT_EQ(built.get()->as()->metrics().physical_columns, 2); + EXPECT_EQ(built.get()->as()->max_seqs(), kMaxSeqs); +} + +TEST_F(CudaRuntimeColumnCacheTest, GrowthAndCloneSurviveDestroyedCallerStream) { + auto cache_ptr = make(); + auto* control = cache_ptr->as(); + auto* kv = cache_ptr->as(); + auto fake = container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + const auto run = [&](const std::vector& ids) { + cudaStream_t stream = nullptr; + ASSERT_EQ( + cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking), cudaSuccess); + ASSERT_TRUE(control->declare_step(ids)); + ASSERT_EQ(kv->prepare_step(ids.size(), stream), Error::Ok); + ASSERT_EQ(kv->rebind_for_execute(&handle), Error::Ok); + ASSERT_EQ(kv->commit_step(ids.size()), Error::Ok); + ASSERT_EQ(cudaStreamSynchronize(stream), cudaSuccess); + ASSERT_EQ(cudaStreamDestroy(stream), cudaSuccess); + }; + const auto first = control->seq_new(); + ASSERT_TRUE(first.has_value()); + run({*first, *first, *first, *first}); + ASSERT_FALSE(HasFatalFailure()); + seed(fake, 4, 2); + const auto before = read_column(fake.bound["flat_k"].data, 4, 2, 0); + const auto clone = control->seq_clone(*first, 4); + ASSERT_TRUE(clone.has_value()); + ASSERT_EQ(kv->rebind_for_execute(&handle), Error::Ok); + EXPECT_EQ(read_column(fake.bound["flat_k"].data, 4, 3, 1), before); + run({*clone}); + ASSERT_FALSE(HasFatalFailure()); + const auto third = control->seq_new(); + ASSERT_TRUE(third.has_value()); + EXPECT_EQ(kv->metrics().physical_columns, 5); + run({*clone}); + ASSERT_FALSE(HasFatalFailure()); + ASSERT_TRUE(control->seq_rm(*first)); + ASSERT_TRUE(control->seq_rm(*third)); + ASSERT_EQ(kv->rebind_for_execute(&handle), Error::Ok); + EXPECT_EQ(kv->metrics().physical_columns, 5); + EXPECT_EQ(read_column(fake.bound["flat_k"].data, 4, 5, 1), before); + kv->forget_handle(&handle); +} + +TEST_F(CudaRuntimeColumnCacheTest, ColumnGrowthFollowsPendingHistoryWrites) { + auto cache_ptr = make(); + auto* control = cache_ptr->as(); + auto* kv = cache_ptr->as(); + auto fake = container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + const auto first = control->seq_new(); + ASSERT_TRUE(first.has_value()); + cudaStream_t stream = nullptr; + ASSERT_EQ( + cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking), cudaSuccess); + ASSERT_TRUE(control->declare_step({*first, *first, *first, *first})); + ASSERT_EQ(kv->prepare_step(4, stream), Error::Ok); + ASSERT_EQ(kv->rebind_for_execute(&handle), Error::Ok); + constexpr size_t kBytes = 4 * 2 * kRow * sizeof(uint16_t); + uint16_t* pinned = nullptr; + ASSERT_EQ(cudaMallocHost(&pinned, kBytes), cudaSuccess); + std::iota(pinned, pinned + kBytes / sizeof(uint16_t), uint16_t{1}); + ASSERT_EQ( + cudaLaunchHostFunc( + stream, + [](void*) { + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + }, + nullptr), + cudaSuccess); + ASSERT_EQ( + cudaMemcpyAsync( + fake.bound["flat_k"].data, + pinned, + kBytes, + cudaMemcpyHostToDevice, + stream), + cudaSuccess); + ASSERT_EQ(kv->commit_step(4), Error::Ok); + ASSERT_TRUE(control->seq_new().has_value()); + ASSERT_EQ(kv->rebind_for_execute(&handle), Error::Ok); + ASSERT_EQ(kv->metrics().physical_columns, 3); + const auto copied = read_column(fake.bound["flat_k"].data, 4, 3, 0); + for (int row = 0; row < 4; ++row) { + for (int lane = 0; lane < kRow; ++lane) { + EXPECT_EQ(copied[row * kRow + lane], pinned[row * 2 * kRow + lane]); + } + } + kv->forget_handle(&handle); + ASSERT_EQ(cudaFreeHost(pinned), cudaSuccess); + ASSERT_EQ(cudaStreamDestroy(stream), cudaSuccess); +} + +TEST_F(CudaRuntimeColumnCacheTest, GrowthInvalidatesEveryGraphAndBinding) { + auto cache_ptr = make(); + auto* control = cache_ptr->as(); + auto* kv = cache_ptr->as(); + auto first = container(); + auto second = container(); + auto decode = make_handle(first); + auto prefill = make_handle(second); + ASSERT_TRUE(kv->note_handle(&decode).get()); + ASSERT_TRUE(kv->note_handle(&prefill).get()); + const auto a = control->seq_new(); + ASSERT_TRUE(a.has_value()); + ASSERT_EQ(step(*cache_ptr, decode, {*a}), Error::Ok); + ASSERT_EQ(kv->rebind_for_execute(&prefill), Error::Ok); + const int first_updates = first.updates; + const int second_updates = second.updates; + decode.cuda_graph_state.phase = cu::CudaGraphPhase::Replay; + prefill.cuda_graph_state.phase = cu::CudaGraphPhase::Warmup; + prefill.cuda_graph_state.warmup_remaining = 0; + const auto b = control->seq_new(); + ASSERT_TRUE(b.has_value()); + EXPECT_EQ(kv->metrics().physical_columns, 3); + EXPECT_EQ(decode.cuda_graph_state.phase, cu::CudaGraphPhase::Warmup); + EXPECT_EQ(decode.cuda_graph_state.warmup_remaining, 1); + EXPECT_EQ(prefill.cuda_graph_state.warmup_remaining, 1); + ASSERT_EQ(kv->rebind_for_execute(&decode), Error::Ok); + ASSERT_EQ(kv->rebind_for_execute(&prefill), Error::Ok); + EXPECT_EQ(first.updates, first_updates + 1); + EXPECT_EQ(second.updates, second_updates + 1); + EXPECT_EQ(first.bound["flat_k"].data, second.bound["flat_k"].data); + kv->forget_handle(&decode); + kv->forget_handle(&prefill); +} + +TEST_F(CudaKVPoolTest, FailedColumnGrowthKeepsOldStorageAndBindingsUsable) { + constexpr int kDeclaredColumns = 1 << 20; + constexpr int kHugeDim = 1 << 20; + cu::CudaKVPool pool( + {{kHeads, kDim, kDeclaredColumns, true}, + {1, kHugeDim, kDeclaredColumns, true}}, + {}, + slimc10::ScalarType::BFloat16, + kDeclaredColumns, + kDeclaredColumns, + 2); + auto fake = flat_and_ring_container(); + for (size_t index = 0; index < 4; ++index) { + declare( + fake, + fake.fqns[index], + slimc10::ScalarType::BFloat16, + {1, + kDeclaredColumns, + index < 2 ? kHeads : 1, + index < 2 ? kDim : kHugeDim}); + } + auto handle = make_handle(fake); + ASSERT_TRUE(pool.note_handle(&handle).get()); + ASSERT_EQ(pool.prepare(2, 0, cudaStreamPerThread), Error::Ok); + ASSERT_EQ(pool.bind(&handle), Error::Ok); + const auto history = iota_rows(2); + ASSERT_EQ( + cudaMemcpy( + pool.layer_data(0, false), + history.data(), + history.size() * sizeof(uint16_t), + cudaMemcpyHostToDevice), + cudaSuccess); + void* old_k = pool.layer_data(0, false); + void* old_large_k = pool.layer_data(1, false); + const auto before_bytes = pool.allocated_bytes(); + const int updates = fake.updates; + handle.cuda_graph_state.phase = cu::CudaGraphPhase::Replay; + for (int repeat = 0; repeat < 2; ++repeat) { + EXPECT_EQ( + pool.resize_columns( + kDeclaredColumns, + /*live_rows=*/1, + cudaStreamPerThread), + Error::MemoryAllocationFailed); + EXPECT_EQ(pool.columns(), 2); + EXPECT_EQ(pool.column_resize_count(), 0); + EXPECT_EQ(pool.allocated_bytes(), before_bytes); + EXPECT_EQ(pool.layer_data(0, false), old_k); + EXPECT_EQ(pool.layer_data(1, false), old_large_k); + EXPECT_EQ(handle.cuda_graph_state.phase, cu::CudaGraphPhase::Replay); + ASSERT_EQ(pool.bind(&handle), Error::Ok); + EXPECT_EQ(fake.updates, updates); + EXPECT_EQ(read_rows(old_k, 2), history); + } + ASSERT_EQ(pool.prepare(2, 1, cudaStreamPerThread), Error::Ok); + ASSERT_EQ(pool.mark_step_done(pool.stream()), Error::Ok); + pool.forget_handle(&handle); +} + +// A temporary allocation consumes only currently free memory and is released +// before recovery. No allocator policy or production fault hook is needed. +TEST_F(CudaRuntimeColumnCacheTest, FailedAdmissionKeepsLiveOwnersUsable) { + constexpr int kLargeDim = 1 << 23; + auto cfg = config(/*capacity=*/2, /*initial=*/2, /*max_write=*/1); + cfg.max_seqs = 2; + cache::CacheGeometry geometry; + geometry.layers = {{{cache::LayerPolicy::Kind::Flat, 0}, 1, kLargeDim}}; + auto ptr = cu::make_cuda_batched_sequence_kv_cache(geometry, cfg); + ASSERT_NE(ptr, nullptr); + auto* control = ptr->as(); + auto* kv = ptr->as(); + FakeContainer fake; + fake.internal_names = {"flat_k", "flat_v", "seq_cols", "seq_info"}; + fake.fqns = { + "__et_offgraph_kv_layer_0_k", + "__et_offgraph_kv_layer_0_v", + "__et_offgraph_kv_seq_cols", + "__et_offgraph_kv_seq_info"}; + for (int index = 0; index < 2; ++index) { + declare( + fake, + fake.fqns[index], + slimc10::ScalarType::BFloat16, + {1, 6, 1, kLargeDim}); + } + declare(fake, fake.fqns[2], slimc10::ScalarType::Long, {1}); + declare(fake, fake.fqns[3], slimc10::ScalarType::Int, {4, 5}); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + const auto owner = control->seq_new(); + ASSERT_TRUE(owner.has_value()); + ASSERT_EQ(step(*ptr, handle, {*owner}), Error::Ok); + const auto history = iota_rows(1); + void* old_k = fake.bound["flat_k"].data; + ASSERT_EQ( + cudaMemcpy( + old_k, + history.data(), + history.size() * sizeof(uint16_t), + cudaMemcpyHostToDevice), + cudaSuccess); + int device = 0; + ASSERT_EQ(cudaGetDevice(&device), cudaSuccess); + ASSERT_EQ(cudaDeviceSynchronize(), cudaSuccess); + ::executorch::extension::cuda::CudaAllocator::release_cached_memory(device); + size_t free_bytes = 0, total_bytes = 0; + ASSERT_EQ(cudaMemGetInfo(&free_bytes, &total_bytes), cudaSuccess); + constexpr size_t kMargin = 32 * 1024 * 1024; + if (free_bytes <= 8 * kMargin) { + kv->forget_handle(&handle); + GTEST_SKIP() + << "Insufficient free memory for a controlled admission failure"; + } + void* reservation = nullptr; + const auto result = cudaMalloc(&reservation, free_bytes - kMargin); + if (result != cudaSuccess) { + (void)cudaGetLastError(); + kv->forget_handle(&handle); + GTEST_SKIP() << "Cannot reserve free memory for a controlled failure"; + } + auto release = [](void* data) { (void)cudaFree(data); }; + std::unique_ptr held(reservation, release); + const auto before = kv->metrics(); + const int updates = fake.updates; + handle.cuda_graph_state.phase = cu::CudaGraphPhase::Replay; + // Both admission paths must erase their tentative ID after resize fails. + EXPECT_FALSE(control->seq_new().has_value()); + EXPECT_FALSE(control->seq_clone(*owner, 1).has_value()); + EXPECT_EQ(kv->metrics().physical_columns, before.physical_columns); + EXPECT_EQ(kv->metrics().column_resize_count, before.column_resize_count); + EXPECT_EQ(kv->metrics().allocated_bytes, before.allocated_bytes); + EXPECT_EQ(kv->metrics().live_sequences, 1); + EXPECT_EQ(control->pos(*owner), 1); + EXPECT_EQ(handle.cuda_graph_state.phase, cu::CudaGraphPhase::Replay); + ASSERT_EQ(kv->rebind_for_execute(&handle), Error::Ok); + EXPECT_EQ(fake.updates, updates); + EXPECT_EQ(fake.bound["flat_k"].data, old_k); + EXPECT_EQ(read_rows(old_k, 1), history); + // Continuing the survivor does not grow rows or columns and writes the + // original physical width into the metadata sent to attention. + ASSERT_EQ(step(*ptr, handle, {*owner}), Error::Ok); + std::array info; + ASSERT_EQ( + cudaMemcpy( + info.data(), + fake.bound["seq_info"].data, + sizeof(info), + cudaMemcpyDeviceToHost), + cudaSuccess); + const std::array expected_info{0, 1, 0, 2, 2}; + EXPECT_EQ(info, expected_info); + held.reset(); + const auto admitted = control->seq_new(); + ASSERT_TRUE(admitted.has_value()); + EXPECT_EQ(*admitted, 1); + EXPECT_EQ(kv->metrics().physical_columns, 3); + ASSERT_TRUE(control->seq_rm(*admitted)); + const auto clone = control->seq_clone(*owner, 1); + ASSERT_TRUE(clone.has_value()); + EXPECT_EQ(*clone, 1); + EXPECT_EQ(control->pos(*clone), 1); + ASSERT_EQ(kv->rebind_for_execute(&handle), Error::Ok); + EXPECT_EQ(read_rows(fake.bound["flat_k"].data, 1), history); + EXPECT_EQ( + read_rows( + static_cast(fake.bound["flat_k"].data) + kLargeDim, 1), + history); + kv->forget_handle(&handle); +} + TEST_F(CudaBatchedSequenceCacheTest, BuilderValidatesAndIsRegistered) { auto no_seqs = sequence_config(); no_seqs.max_seqs.reset(); diff --git a/backends/cuda/tests/bench_sdpa_varlen.py b/backends/cuda/tests/bench_sdpa_varlen.py index 57276aced7c..9066f9a1f06 100644 --- a/backends/cuda/tests/bench_sdpa_varlen.py +++ b/backends/cuda/tests/bench_sdpa_varlen.py @@ -49,7 +49,7 @@ def _step(case, window, device="cuda"): v_seq = torch.randn_like(k_seq) info, start = [], 0 for col, (q_len, ctx) in enumerate(case): - info.append((start, q_len, col, ctx)) + info.append((start, q_len, col, ctx, cols)) start += q_len info = torch.tensor(info, dtype=torch.int32, device=device) diff --git a/backends/cuda/tests/test_offgraph_kv_batched_sequence.py b/backends/cuda/tests/test_offgraph_kv_batched_sequence.py index f9e0cc65c7e..17fdff21b24 100644 --- a/backends/cuda/tests/test_offgraph_kv_batched_sequence.py +++ b/backends/cuda/tests/test_offgraph_kv_batched_sequence.py @@ -24,13 +24,14 @@ batched_sequence_step, CheckOffGraphKVStepWidthPass, LowerOffGraphKVPass, + offgraph_kv_constant_methods, OFFGRAPH_KV_FQN_PREFIX, OFFGRAPH_KV_SEQ_COLS_FQN, OFFGRAPH_KV_SEQ_INFO_FQN, parse_offgraph_kv_manifest, ring_physical_capacity, ) - +from executorch.backends.cuda.triton.kernels.sdpa_varlen import _num_splits, sdpa_varlen from executorch.examples.models.muse_glimmer.model.dflash_model import ( build_dflash_swa_mask, ) @@ -69,7 +70,8 @@ def _batch(groups): def _plan(seq_ids, position, columns, width, max_segments, scratch): """What the runtime cache writes before a forward: each token's column, - and one (q_start, q_len, col, kv_end) row per run of one sequence.""" + and one (q_start, q_len, col, kv_end, physical_columns) row per run of one sequence. + """ seq_cols = [columns[s] for s in seq_ids] + [scratch] * (width - len(seq_ids)) info, start = [], 0 positions = position.tolist() @@ -78,10 +80,16 @@ def _plan(seq_ids, position, columns, width, max_segments, scratch): while end < len(seq_ids) and seq_ids[end] == seq_ids[start]: end += 1 info.append( - (start, end - start, columns[seq_ids[start]], positions[end - 1] + 1) + ( + start, + end - start, + columns[seq_ids[start]], + positions[end - 1] + 1, + scratch + 1, + ) ) start = end - info += [(0, 0, 0, 0)] * (max_segments - len(info)) + info += [(0, 0, 0, 0, scratch + 1)] * (max_segments - len(info)) return ( torch.tensor(seq_cols, dtype=torch.long, device="cuda"), torch.tensor(info, dtype=torch.int32, device="cuda"), @@ -130,7 +138,7 @@ def close(self) -> None: def _max_abs_diff(actual, expected) -> float: - return (actual.float().cpu() - expected).abs().max().item() + return (actual.float().cpu() - expected.float().cpu()).abs().max().item() # Two sequences prefilling in one step, decoding together, then one decoding @@ -297,6 +305,175 @@ def _draft_model_reference(q, storage, segments, window, rows): return out +@unittest.skipUnless(torch.cuda.is_available(), "CUDA required") +class RuntimeColumnPitchTest(unittest.TestCase): + """Check runtime write/read pitch with unchanged AOT tensor dimensions. + + This test reserves the declared maximum tensor and poisons the unused + tail. Actual smaller CUDA allocations are tested by the C++ cache and + model probe; this numerical test does not establish memory savings. + """ + + def _run(self, window): + torch.manual_seed(125) + declared_columns, max_write = 22, 32 + rows = min(64, window + max_write - 1) if window else 64 + oracle = _Oracle(128, (window,)) + self.addCleanup(oracle.close) + k_store = torch.full( + (1, rows * declared_columns, N_KV_HEADS, HEAD_DIM), + float("nan"), + dtype=torch.bfloat16, + device="cuda", + ) + v_store = torch.full_like(k_store, float("nan")) + old_mapping, old_columns = {}, 0 + positions = {} + for active in (1, 2, 4, 8, 16, 1): + owners = list(range(active)) if active != 1 or not old_mapping else [5] + mapping = {owner: column for column, owner in enumerate(owners)} + physical_columns = len(owners) + 1 + for store in (k_store, v_store): + retained = { + owner: store[0, : rows * old_columns] + .view(rows, old_columns, N_KV_HEADS, HEAD_DIM)[:, column] + .clone() + for owner, column in old_mapping.items() + if owner in mapping + } + store.fill_(float("nan")) + compact = store[0, : rows * physical_columns].view( + rows, physical_columns, N_KV_HEADS, HEAD_DIM + ) + compact.zero_() + for owner, values in retained.items(): + compact[:, mapping[owner]].copy_(values) + groups = [] + for owner in owners: + start = positions.get(owner, 0) + # Different histories exercise segment boundaries and ring wrap. + length = 1 + owner % 2 if active < 16 else 1 + if not old_mapping: + length = max_write - 1 + groups.append((owner, start, length)) + positions[owner] = start + length + seq_ids, q, k, v, position = _batch(groups) + (expected,) = oracle.step(seq_ids, q, k, v, position) + seq_cols, seq_info = _plan( + seq_ids, + position, + mapping, + max_write, + 42, + physical_columns - 1, + ) + # Exercise an uncovered padded row in both split and generic paths. + padded_q = torch.cat([q, torch.zeros_like(q[:, :, :1])], dim=2) + padded_k = torch.cat([k, torch.zeros_like(k[:, :, :1])], dim=2) + padded_v = torch.cat([v, torch.zeros_like(v[:, :, :1])], dim=2) + out = batched_sequence_step( + padded_q, + padded_k, + padded_v, + torch.cat([position, position.new_zeros(1)]), + k_store, + v_store, + seq_cols, + seq_info, + SCALE, + rows, + declared_columns, + window, + window > 0, + True, + ) + self.assertLess(_max_abs_diff(out[:, :, : len(seq_ids)], expected), 2e-2) + self.assertTrue((out[:, :, len(seq_ids) :] == 0).all()) + for store in (k_store, v_store): + self.assertTrue(torch.isnan(store[0, rows * physical_columns :]).all()) + old_mapping, old_columns = mapping, physical_columns + + def test_flat_pitch_and_sparse_survivor(self): + self._run(window=0) + + def test_ring_pitch_and_sparse_survivor(self): + self._run(window=2) + + def test_runtime_pitch_rejects_noncontiguous_column_and_head_lanes(self): + query, _, _, _ = _inputs(0, 1) + key = torch.zeros( + (8, 3, N_KV_HEADS, HEAD_DIM), device="cuda", dtype=torch.bfloat16 + ) + info = torch.tensor([[0, 1, 0, 1, 3]], device="cuda", dtype=torch.int32) + layouts = [ + key.transpose(1, 2).contiguous().transpose(1, 2), + key.repeat_interleave(2, dim=1)[:, ::2], + ] + for bad in layouts: + for bad_key in (False, True): + with self.subTest(stride=bad.stride(), bad_key=bad_key): + with self.assertRaisesRegex(ValueError, "column and head lanes"): + sdpa_varlen( + query, + bad if bad_key else key, + key if bad_key else bad, + info, + SCALE, + ) + + def test_runtime_pitch_with_multiple_decode_splits(self): + torch.manual_seed(126) + rows, declared_columns, physical_columns = 1024, 9, 4 + query = torch.randn( + 1, N_Q_HEADS, 3, HEAD_DIM, device="cuda", dtype=torch.bfloat16 + ) + key = torch.full( + (rows, declared_columns, N_KV_HEADS, HEAD_DIM), + float("nan"), + device="cuda", + dtype=torch.bfloat16, + ) + value = torch.full_like(key, float("nan")) + live_key = key.reshape(-1, N_KV_HEADS, HEAD_DIM)[ + : rows * physical_columns + ].view(rows, physical_columns, N_KV_HEADS, HEAD_DIM) + live_value = value.reshape(-1, N_KV_HEADS, HEAD_DIM)[ + : rows * physical_columns + ].view_as(live_key) + live_key.normal_() + live_value.normal_() + info = torch.tensor( + [ + [0, 1, 2, rows, physical_columns], + [1, 1, 0, 768, physical_columns], + [0, 0, 0, 0, physical_columns], + ], + dtype=torch.int32, + device="cuda", + ) + self.assertGreater(_num_splits(query.shape[2], rows), 1) + actual = sdpa_varlen(query, key, value, info, SCALE, rows_available=rows) + expected = torch.zeros_like(query) + for token, column, length in ((0, 2, rows), (1, 0, 768)): + k = ( + live_key[:length, column] + .transpose(0, 1) + .repeat_interleave(N_Q_HEADS // N_KV_HEADS, dim=0) + .float() + ) + v = ( + live_value[:length, column] + .transpose(0, 1) + .repeat_interleave(N_Q_HEADS // N_KV_HEADS, dim=0) + .float() + ) + scores = (query[0, :, token, None].float() * k).sum(-1) * SCALE + expected[0, :, token] = ( + (scores.softmax(-1)[..., None] * v).sum(1).to(expected.dtype) + ) + self.assertLess(_max_abs_diff(actual, expected), 2e-2) + + @unittest.skipUnless(torch.cuda.is_available(), "CUDA required") class LowerBatchedSequencePassTest(unittest.TestCase): CAPACITY = 32 @@ -362,6 +539,22 @@ def test_manifest_is_validated(self) -> None: with self.assertRaises(ValueError): parse_offgraph_kv_manifest(self.manifest(**bad)) + def test_physical_pitch_is_the_default_interface(self) -> None: + manifest = self.manifest() + lowered = self._lowered(manifest) + buffers = { + n.name: tuple(n.meta["val"].shape) + for n in lowered.graph_module.graph.nodes + if n.op == "placeholder" and n.name.startswith(OFFGRAPH_KV_FQN_PREFIX) + } + self.assertEqual(buffers[OFFGRAPH_KV_SEQ_INFO_FQN], (self.MAX_SEGMENTS, 5)) + self.assertEqual( + offgraph_kv_constant_methods(manifest), + {"get_offgraph_kv_max_seqs": self.MAX_SEQS}, + ) + with self.assertRaises(ValueError): + parse_offgraph_kv_manifest(self.manifest(version=2)) + def test_declares_column_storage_and_step_buffers(self) -> None: lowered = self._lowered() graph = lowered.graph_module.graph @@ -384,7 +577,7 @@ def test_declares_column_storage_and_step_buffers(self) -> None: f"{OFFGRAPH_KV_FQN_PREFIX}layer_1_k": windowed, f"{OFFGRAPH_KV_FQN_PREFIX}layer_1_v": windowed, OFFGRAPH_KV_SEQ_COLS_FQN: (self.MAX_WRITE,), - OFFGRAPH_KV_SEQ_INFO_FQN: (self.MAX_SEGMENTS, 4), + OFFGRAPH_KV_SEQ_INFO_FQN: (self.MAX_SEGMENTS, 5), }, ) calls = [ @@ -392,20 +585,35 @@ def test_declares_column_storage_and_step_buffers(self) -> None: ] self.assertEqual(len(calls), 2) - def test_lowered_program_matches_the_neutral_op(self) -> None: + def _check_lowered_program(self, smaller_physical_pitch: bool) -> None: torch.manual_seed(21) - lowered = self._lowered() + declared_seqs = self.MAX_SEQS + 2 if smaller_physical_pitch else self.MAX_SEQS + segments = 2 * declared_seqs + pitch = self.MAX_SEQS + 1 + manifest = self.manifest( + max_seqs=declared_seqs, + max_segments=segments, + ) + metadata = offgraph_kv_constant_methods(manifest) + self.assertEqual(metadata["get_offgraph_kv_max_seqs"], declared_seqs) + lowered = self._lowered(manifest) runtime = {} for name, value in list(lowered.constants.items()): if name.startswith(OFFGRAPH_KV_FQN_PREFIX): runtime[name] = torch.zeros( value.shape, device="cuda", dtype=value.dtype ) + if smaller_physical_pitch and name not in ( + OFFGRAPH_KV_SEQ_COLS_FQN, + OFFGRAPH_KV_SEQ_INFO_FQN, + ): + rows = value.shape[1] // (declared_seqs + 1) + runtime[name][:, rows * pitch :].fill_(float("nan")) lowered.constants[name] = runtime[name] module = lowered.module() oracle = _Oracle(4 * self.CAPACITY, (0, self.WINDOW)) self.addCleanup(oracle.close) - columns = {seq: seq for seq in range(self.MAX_SEQS)} + columns = {seq: self.MAX_SEQS - 1 - seq for seq in range(self.MAX_SEQS)} for groups in _STEPS: seq_ids, q, k, v, position = _batch(groups) flat, ring = oracle.step(seq_ids, q, k, v, position) @@ -414,13 +622,24 @@ def test_lowered_program_matches_the_neutral_op(self) -> None: position, columns, self.MAX_WRITE, - self.MAX_SEGMENTS, - self.MAX_SEQS, + segments, + pitch - 1, ) runtime[OFFGRAPH_KV_SEQ_COLS_FQN].copy_(seq_cols) runtime[OFFGRAPH_KV_SEQ_INFO_FQN].copy_(seq_info) out = module(q, k, v, position.reshape(-1, 1)) self.assertLess(_max_abs_diff(out, flat + ring), 3e-2) + if smaller_physical_pitch: + for name, value in runtime.items(): + if name not in (OFFGRAPH_KV_SEQ_COLS_FQN, OFFGRAPH_KV_SEQ_INFO_FQN): + rows = value.shape[1] // (declared_seqs + 1) + self.assertTrue(torch.isnan(value[:, rows * pitch :]).all()) + + def test_lowered_program_matches_the_neutral_op(self) -> None: + self._check_lowered_program(False) + + def test_lowered_runtime_pitch_matches_the_neutral_op(self) -> None: + self._check_lowered_program(True) def test_non_causal_context_window_reaches_sdpa_varlen(self) -> None: lowered = self._lowered( @@ -496,7 +715,9 @@ def _draft_runtime_inputs(self, q, runtime, values, starts, block): runtime[OFFGRAPH_KV_SEQ_COLS_FQN][: len(columns)].copy_(torch.tensor(columns)) runtime[OFFGRAPH_KV_SEQ_INFO_FQN].copy_( torch.tensor( - segments + [(0, 0, 0, 0)] * (self.MAX_SEGMENTS - 2), dtype=torch.int32 + [(*segment, self.MAX_SEQS + 1) for segment in segments] + + [(0, 0, 0, 0, self.MAX_SEQS + 1)] * (self.MAX_SEGMENTS - 2), + dtype=torch.int32, ) ) return k, v, position, segments diff --git a/backends/cuda/tests/test_sdpa_varlen.py b/backends/cuda/tests/test_sdpa_varlen.py index 365b74d109f..08a35e82e63 100644 --- a/backends/cuda/tests/test_sdpa_varlen.py +++ b/backends/cuda/tests/test_sdpa_varlen.py @@ -16,6 +16,14 @@ ) +def _info(segments, columns, device): + return torch.tensor( + [(*segment, columns) for segment in segments], + dtype=torch.int32, + device=device, + ) + + def _reference( q, k_store, v_store, segments, scale, causal, window, ring, symmetric=False ): @@ -111,7 +119,7 @@ def _dflash_inputs( v[row, col] = contribution segments.append((col * block, block, col, context + block)) padded = segments + [(0, 0, 0, 0)] * (4 - len(segments)) - info = torch.tensor(padded, device="cuda", dtype=torch.int32) + info = _info(padded, k.shape[1], "cuda") return q, k, v, info, segments @@ -161,7 +169,7 @@ def _run( q = torch.randn(1, hq, t, d, device=dev, dtype=torch.bfloat16) k = torch.randn(rows, cols, hkv, d, device=dev, dtype=torch.bfloat16) v = torch.randn(rows, cols, hkv, d, device=dev, dtype=torch.bfloat16) - info = torch.tensor(segments, dtype=torch.int32, device=dev) + info = _info(segments, k.shape[1], dev) scale = d**-0.5 got = sdpa_varlen(q, k, v, info, scale, causal, window, ring) want = _reference(q, k, v, segments, scale, causal, window, ring) @@ -375,7 +383,7 @@ def test_dflash_graph_replay_reads_new_query_lengths(self): ) for length, end in ((1, 1), (2, 513), (8, 1030), (16, 900)): segments = [(0, length, 0, end)] - info.copy_(torch.tensor(segments + [(0, 0, 0, 0)] * 3, dtype=torch.int32)) + info.copy_(_info(segments + [(0, 0, 0, 0)] * 3, k.shape[1], q.device)) graph.replay() want = _reference( q, k, v, segments, 0.125, False, window, ring, symmetric=True @@ -398,7 +406,9 @@ def test_graph_replay_reads_new_lengths(self): k = torch.randn(256, 3, 2, 64, device=dev, dtype=torch.bfloat16) v = torch.randn_like(k) info = torch.tensor( - [[0, 1, 0, 10], [1, 1, 1, 20], [2, 2, 2, 30]], dtype=torch.int32, device=dev + [[0, 1, 0, 10, 3], [1, 1, 1, 20, 3], [2, 2, 2, 30, 3]], + dtype=torch.int32, + device=dev, ) sdpa_varlen(q, k, v, info, 0.125) graph = torch.cuda.CUDAGraph() @@ -408,7 +418,7 @@ def test_graph_replay_reads_new_lengths(self): [[0, 1, 0, 200], [1, 1, 1, 3], [2, 2, 2, 256]], [[0, 4, 1, 100], [0, 0, 0, 0], [0, 0, 0, 0]], ): - info.copy_(torch.tensor(segments, dtype=torch.int32)) + info.copy_(_info(segments, k.shape[1], dev)) graph.replay() want = _reference(q, k, v, segments, 0.125, True, 0, 0) torch.testing.assert_close(out.float(), want, atol=2e-2, rtol=2e-2) @@ -463,7 +473,12 @@ def test_overprovisioned_store_graph_replay(self): k = torch.randn(8192, 4, 2, 64, device=dev, dtype=torch.bfloat16) v = torch.randn_like(k) info = torch.tensor( - [[0, 1, 0, 100], [1, 1, 1, 600], [2, 1, 2, 900], [3, 1, 3, 1000]], + [ + [0, 1, 0, 100, 4], + [1, 1, 1, 600, 4], + [2, 1, 2, 900, 4], + [3, 1, 3, 1000, 4], + ], dtype=torch.int32, device=dev, ) @@ -476,7 +491,7 @@ def test_overprovisioned_store_graph_replay(self): [[0, 1, 3, 4096], [1, 1, 2, 17], [2, 1, 1, 8000], [3, 1, 0, 700]], ) for segments in scenarios: - info.copy_(torch.tensor(segments, dtype=torch.int32)) + info.copy_(_info(segments, k.shape[1], dev)) graph.replay() want = _reference(q, k, v, segments, 0.125, True, 0, 0) torch.testing.assert_close(out.float(), want, atol=2e-2, rtol=2e-2) @@ -488,7 +503,7 @@ def test_rows_available(self): q = torch.randn(1, hq, 1, d, device=dev, dtype=torch.bfloat16) k = torch.randn(512, 3, hkv, d, device=dev, dtype=torch.bfloat16) v = torch.randn_like(k) - info = torch.tensor([[0, 1, 2, 300]], dtype=torch.int32, device=dev) + info = torch.tensor([[0, 1, 2, 300, 3]], dtype=torch.int32, device=dev) got = sdpa_varlen(q, k, v, info, d**-0.5, rows_available=available) keys = k[:available, 2].float().repeat_interleave(hq // hkv, dim=1) @@ -508,7 +523,7 @@ def test_torch_compile(self): k = torch.randn(512, 2, 2, 64, device=dev, dtype=torch.bfloat16) v = torch.randn_like(k) segments = [(0, 1, 0, 300), (1, 3, 1, 500)] - info = torch.tensor(segments, dtype=torch.int32, device=dev) + info = _info(segments, k.shape[1], dev) def fn(q, k, v, info): return sdpa_varlen(q, k, v, info, 0.125, True, 256, 0) @@ -524,7 +539,7 @@ def test_torch_compile_generic(self): k = torch.randn(512, 2, 2, 64, device=dev, dtype=torch.bfloat16) v = torch.randn_like(k) segments = [(0, 16, 0, 500), (0, 0, 1, 0)] - info = torch.tensor(segments, dtype=torch.int32, device=dev) + info = _info(segments, k.shape[1], dev) def fn(q, k, v, info): return sdpa_varlen(q, k, v, info, 0.125, True, 256, 0) @@ -552,7 +567,7 @@ def test_dynamic_query_length_is_not_specialized(self): segments = [(16 * i, 16, i % 3, 40 + 16 * i) for i in range(owners)] # The segment table is fixed-size in a lowered step; pad it. padded = segments + [(0, 0, 0, 0)] * (4 - owners) - info = torch.tensor(padded, dtype=torch.int32, device=dev) + info = _info(padded, k.shape[1], dev) got = compiled(q, k, v, info) want = _reference(q, k, v, segments, 0.125, False, 0, 0) torch.testing.assert_close(got.float(), want, atol=2e-2, rtol=2e-2) @@ -563,14 +578,25 @@ def test_rejects_unsupported_layouts(self): q = torch.randn(1, 8, 1, 64, device=dev, dtype=torch.bfloat16) k = torch.randn(128, 2, 2, 64, device=dev, dtype=torch.bfloat16) v = torch.randn_like(k) - info = torch.zeros((1, 8), device=dev, dtype=torch.int32)[:, ::2] + info = torch.zeros((1, 10), device=dev, dtype=torch.int32)[:, ::2] with self.assertRaisesRegex(ValueError, "seq_info must be contiguous"): sdpa_varlen(q, k, v, info, 0.125) + for shape in ((1, 4), (0, 5)): + with self.subTest(shape=shape): + with self.assertRaisesRegex(ValueError, r"Int32\[S, 5\]"): + sdpa_varlen( + q, + k, + v, + torch.zeros(shape, device=dev, dtype=torch.int32), + 0.125, + ) + q = torch.randn(1, 8, 1, 96, device=dev, dtype=torch.bfloat16) k = torch.randn(128, 2, 2, 96, device=dev, dtype=torch.bfloat16) v = torch.randn_like(k) - info = torch.tensor([[0, 1, 0, 100]], dtype=torch.int32, device=dev) + info = torch.tensor([[0, 1, 0, 100, 2]], dtype=torch.int32, device=dev) with self.assertRaisesRegex(ValueError, "head dimension must be a power"): sdpa_varlen(q, k, v, info, 96**-0.5) diff --git a/backends/cuda/triton/kernels/sdpa_varlen.py b/backends/cuda/triton/kernels/sdpa_varlen.py index 40bc1c2ab2d..127c0497f51 100644 --- a/backends/cuda/triton/kernels/sdpa_varlen.py +++ b/backends/cuda/triton/kernels/sdpa_varlen.py @@ -15,7 +15,7 @@ length, so a step costs the sum of the contexts rather than a sweep of every sequence's cells. -The runtime describes the step in ``seq_info`` (``Int32[S, 4]``), one row per +The runtime describes the step in ``seq_info`` (``Int32[S, 5]``), one row per segment of consecutive query rows of one sequence: * ``q_start``, ``q_len``: the segment's rows on the packed query axis @@ -24,6 +24,9 @@ * ``kv_end``: one past the logical position of the segment's last row, i.e. the sequence's length once this step's writes land. +The last field is the physical column count, read from row 0. It sets the K/V +row pitch even when the compiled tensor declares a larger maximum width. + Rows are the segment's newest positions: row ``r`` sits at ``kv_end - q_len + r``. Active segments must be disjoint and in bounds; ``seq_info`` is read on the device, so a captured CUDA graph replays it with new @@ -83,10 +86,13 @@ def _sdpa_varlen_kernel( # noqa: C901 seg = pid0 // num_qb qb = pid0 % num_qb - q_start = tl.load(Info_ptr + seg * 4 + 0) - q_len = tl.load(Info_ptr + seg * 4 + 1) - col = tl.load(Info_ptr + seg * 4 + 2) - kv_end = tl.load(Info_ptr + seg * 4 + 3) + q_start = tl.load(Info_ptr + seg * 5 + 0) + q_len = tl.load(Info_ptr + seg * 5 + 1) + col = tl.load(Info_ptr + seg * 5 + 2) + kv_end = tl.load(Info_ptr + seg * 5 + 3) + columns = tl.load(Info_ptr + 4).to(tl.int64) + stride_kr = columns * stride_kc + stride_vr = columns * stride_vc if qb * BLOCK_M >= q_len * NUM_GROUPS: return @@ -239,14 +245,17 @@ def _sdpa_varlen_decode_kernel( # noqa: C901 col = 0 kv_end = 0 for seg in range(NUM_SEGMENTS): - seg_q_start = tl.load(Info_ptr + seg * 4) - seg_q_len = tl.load(Info_ptr + seg * 4 + 1) + seg_q_start = tl.load(Info_ptr + seg * 5) + seg_q_len = tl.load(Info_ptr + seg * 5 + 1) take = (t >= seg_q_start) & (t < seg_q_start + seg_q_len) owned |= take q_start = tl.where(take, seg_q_start, q_start) q_len = tl.where(take, seg_q_len, q_len) - col = tl.where(take, tl.load(Info_ptr + seg * 4 + 2), col) - kv_end = tl.where(take, tl.load(Info_ptr + seg * 4 + 3), kv_end) + col = tl.where(take, tl.load(Info_ptr + seg * 5 + 2), col) + kv_end = tl.where(take, tl.load(Info_ptr + seg * 5 + 3), kv_end) + columns = tl.load(Info_ptr + 4).to(tl.int64) + stride_kr = columns * stride_kc + stride_vr = columns * stride_vc offs_g = tl.arange(0, BLOCK_G) offs_d = tl.arange(0, HEAD_DIM) @@ -403,9 +412,11 @@ def sdpa_varlen( # noqa: C901 Args: query: ``[1, H_q, T, D]`` bfloat16, the step's queries in packed order. key, value: ``[rows, columns, H_kv, D]`` bfloat16 storage; one column per - sequence. Only the head dimension must be contiguous. - seq_info: ``Int32[S, 4]`` on the query's device, ``(q_start, q_len, - col, kv_end)`` per segment; see the module docstring. + sequence. Head and column lanes must be contiguous. The row pitch + is field 4 times the column stride, not key.stride(0). + seq_info: ``Int32[S, 5]`` on the query's device, ``(q_start, q_len, + col, kv_end, physical_columns)`` per segment; see the module + docstring. scale: softmax scale. is_causal: row ``r`` sees positions up to its own; otherwise every row sees all of ``[0, kv_end)``. @@ -453,10 +464,22 @@ def sdpa_varlen( # noqa: C901 raise ValueError("head dimension must be a power of two in [16, 256]") if query.stride(-1) != 1 or key.stride(-1) != 1 or value.stride(-1) != 1: raise ValueError("sdpa_varlen needs a contiguous head dimension") - if seq_info.dtype != torch.int32 or seq_info.dim() != 2 or seq_info.shape[1] != 4: - raise ValueError("seq_info must be Int32[S, 4]") + if ( + seq_info.dtype != torch.int32 + or seq_info.dim() != 2 + or seq_info.shape[0] < 1 + or seq_info.shape[1] != 5 + ): + raise ValueError("seq_info must be Int32[S, 5]") if seq_info.device != query.device or not seq_info.is_contiguous(): raise ValueError("seq_info must be contiguous on the query device") + if ( + key.stride(2) != D + or key.stride(1) != Hkv * D + or value.stride(2) != D + or value.stride(1) != Hkv * D + ): + raise ValueError("runtime-pitch KV needs contiguous column and head lanes") if context_window and is_causal: raise ValueError("context_window requires non-causal attention") if symmetric_window and (is_causal or context_window): diff --git a/examples/models/muse-glimmer/CMakeLists.txt b/examples/models/muse-glimmer/CMakeLists.txt index 619d835e418..9a7245a6f57 100644 --- a/examples/models/muse-glimmer/CMakeLists.txt +++ b/examples/models/muse-glimmer/CMakeLists.txt @@ -144,6 +144,34 @@ target_include_directories( dflash_timing_test PUBLIC ${_common_include_directories} ) +option(MUSE_GLIMMER_BUILD_RUNTIME_KV_PROBE "Build isolated CUDA KV diagnostic" + OFF +) +if(MUSE_GLIMMER_BUILD_RUNTIME_KV_PROBE) + if(WIN32) + message(FATAL_ERROR "Runtime KV probe requires POSIX file descriptors") + endif() + if(NOT EXECUTORCH_BUILD_CUDA) + message(FATAL_ERROR "Runtime KV probe requires the CUDA batching executor") + endif() + add_executable( + muse_glimmer_runtime_kv_probe tests/runtime_kv_columns_probe.cpp + ) + target_include_directories( + muse_glimmer_runtime_kv_probe PRIVATE ${_common_include_directories} + ${_json_include} + ) + target_link_libraries( + muse_glimmer_runtime_kv_probe PRIVATE cuda_batching CUDA::cudart + ${link_libraries} + ) + if(NOT APPLE AND NOT MSVC) + target_link_options( + muse_glimmer_runtime_kv_probe PRIVATE "LINKER:--export-dynamic" + ) + endif() +endif() + # Worker used by the OpenAI-compatible serving harness. add_executable( muse_glimmer_worker diff --git a/examples/models/muse-glimmer/export/export_solo.py b/examples/models/muse-glimmer/export/export_solo.py index ea248c48148..5098d190d44 100644 --- a/examples/models/muse-glimmer/export/export_solo.py +++ b/examples/models/muse-glimmer/export/export_solo.py @@ -247,9 +247,6 @@ def _solo_constant_methods( # Read by CudaExecutor: the cell pool's size, which fixes its step buffers. MAX_CELLS_METHOD = "get_offgraph_kv_max_cells" -# Read by CudaExecutor in place of the cell count when each sequence keeps a -# private history: the sequence columns of every layer's storage. -MAX_KV_SEQS_METHOD = "get_offgraph_kv_max_seqs" # Read by MuseGlimmerCudaDFlashExecutor for the draft's own sequence columns, # mirroring kMaxSeqs in runtime/cuda_dflash_executor.h. DRAFT_MAX_KV_SEQS_METHOD = "get_draft_offgraph_kv_max_seqs" @@ -445,6 +442,7 @@ def export_cuda_batching( # noqa: C901 from executorch.backends.cuda.cuda_partitioner import CudaPartitioner from executorch.backends.cuda.passes.lower_offgraph_kv import ( OFFGRAPH_KV_COMPILE_SPEC, + offgraph_kv_constant_methods, OFFGRAPH_KV_STEP_WIDTH_COMPILE_SPEC, ) from executorch.examples.models.muse_glimmer.source_transformations.cuda import ( @@ -679,7 +677,7 @@ def partitioner(name: str) -> CudaPartitioner: constant_methods["get_min_prefill_chunk"] = _CUDA_MIN_PREFILL_CHUNK constant_methods["use_sampling"] = False if sequence_layout: - constant_methods[MAX_KV_SEQS_METHOD] = max_kv_seqs + constant_methods.update(offgraph_kv_constant_methods(manifest.encode())) else: constant_methods[MAX_CELLS_METHOD] = max_cells if "draft_forward" in programs: diff --git a/examples/models/muse-glimmer/tests/check_runtime_kv_columns.py b/examples/models/muse-glimmer/tests/check_runtime_kv_columns.py new file mode 100644 index 00000000000..4e1d4b5bc14 --- /dev/null +++ b/examples/models/muse-glimmer/tests/check_runtime_kv_columns.py @@ -0,0 +1,234 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Check CUDA column growth against preallocated storage using the same PTE. + +The reference admits and closes all owners before its first forward. Both +processes then run identical queries through row growth, wrapped-history cloning, +sparse owners, and CUDA graph recapture. Closing an owner does not shrink storage. +""" + +import argparse +import json +import subprocess +import sys +from dataclasses import replace +from pathlib import Path + +import numpy as np +import torch +from executorch.examples.models.muse_glimmer.export.export_solo import ( + export_cuda_batching, +) +from executorch.examples.models.muse_glimmer.model.model import MuseGlimmerModel +from executorch.examples.models.muse_glimmer.tests.test_pipeline import TINY_CONFIG + + +def commands() -> list[dict]: + requests = [ + {"op": "new"}, + { + "op": "step", + "tokens": list(range(32)), + "seq_ids": [0] * 32, + "select": [31], + "tag": "prefill", + "check_reentrancy": True, + }, + { + "op": "step", + "tokens": list(range(32, 48)), + "seq_ids": [0] * 16, + "select": [15], + "tag": "wrap", + }, + {"op": "clone", "seq_id": 0, "upto": 48}, + {"op": "new"}, + { + "op": "step", + "tokens": [13, 13, 19], + "seq_ids": [0, 1, 2], + "select": [0, 1, 2], + "tag": "grow", + }, + {"op": "remove", "seq_id": 0}, + ] + for repeat in range(5): + requests.append( + { + "op": "step", + "tokens": [20 + repeat, 30 + repeat], + "seq_ids": [1, 2], + "select": [0, 1], + "tag": f"decode-before-{repeat}", + } + ) + requests.extend([{"op": "remove", "seq_id": 1}, {"op": "remove", "seq_id": 2}]) + requests.extend( + [ + {"op": "new"}, + { + "op": "step", + "tokens": [5, 6, 7, 8], + "seq_ids": [0] * 4, + "select": [3], + "tag": "reuse", + }, + ] + ) + requests.extend({"op": "new"} for _ in range(4)) + requests.append( + { + "op": "step", + "tokens": [9, 10, 11, 12, 13], + "seq_ids": list(range(5)), + "select": list(range(5)), + "tag": "burst", + } + ) + for repeat in range(5): + requests.append( + { + "op": "step", + "tokens": [20 + repeat, 30 + repeat], + "seq_ids": [1, 2], + "select": [0, 1], + "tag": f"decode-after-{repeat}", + } + ) + requests.extend([{"op": "remove", "seq_id": 3}, {"op": "remove", "seq_id": 4}]) + requests.extend([{"op": "new"}, {"op": "new"}]) + requests.append( + { + "op": "step", + "tokens": [14, 15, 16, 17, 18], + "seq_ids": list(range(5)), + "select": list(range(5)), + "tag": "burst-reused", + } + ) + requests.extend({"op": "remove", "seq_id": owner} for owner in (4, 3, 2, 1, 0)) + for request in requests: + if request["op"] == "step": + request["save_logits"] = True + return requests + + +def run(probe: Path, artifact: Path, preallocate: bool) -> tuple[dict, list[dict]]: + output = artifact / ("preallocated" if preallocate else "growing") + output.mkdir(exist_ok=True) + prefix = [] + if preallocate: + prefix.extend({"op": "new"} for _ in range(8)) + prefix.extend({"op": "remove", "seq_id": owner} for owner in range(8)) + requests = prefix + commands() + completed = subprocess.run( + [ + str(probe), + f"--pte={artifact / 'model.pte'}", + f"--data_path={artifact / 'aoti_cuda_blob.ptd'}", + f"--output_dir={output}", + "--max_sessions=8", + "--max_context=64", + "--initial_kv_capacity=4", + ], + input="".join(json.dumps(r) + "\n" for r in requests), + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + timeout=300, + ) + (output / "probe.stderr.log").write_text(completed.stderr) + (output / "probe.jsonl").write_text(completed.stdout) + if completed.returncode: + print(completed.stderr, file=sys.stderr) + print(completed.stdout, file=sys.stderr) + completed.check_returncode() + responses = [json.loads(line) for line in completed.stdout.splitlines()] + assert responses[0]["ready"] and len(responses) == len(requests) + 1 + logits = {} + for request, response in zip(requests, responses[1:], strict=True): + assert response["op"] == request["op"] and not response.get("failed") + if request["op"] == "step": + arrays = [ + np.fromfile(item["file"], dtype=np.float32).reshape(item["shape"]) + for item in response["logits"] + ] + logits[request["tag"]] = np.concatenate(arrays) + return logits, responses[1 + len(prefix) :] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--probe", required=True, type=Path) + parser.add_argument("--output-dir", required=True, type=Path) + args = parser.parse_args() + artifact = args.output_dir.resolve() + artifact.mkdir(parents=True, exist_ok=True) + torch.manual_seed(123) + config = replace( + TINY_CONFIG, + dim=128, + n_layers=2, + n_heads=2, + n_kv_heads=1, + global_attn_cfg="[16,0]", + ) + model = MuseGlimmerModel(config).to(torch.bfloat16).eval() + model.activation_dtype = torch.bfloat16 + export_cuda_batching( + model, + config, + str(artifact), + max_step_tokens=32, + max_cells=512, + forward_sizes=(1, 2, 4, 8, 16), + kv_layout="sequence", + max_kv_seqs=8, + ) + fixed, fixed_responses = run(args.probe.resolve(), artifact, True) + dynamic, responses = run(args.probe.resolve(), artifact, False) + assert fixed.keys() == dynamic.keys() + for tag in fixed: + assert np.isfinite(fixed[tag]).all(), tag + assert np.isfinite(dynamic[tag]).all(), tag + np.testing.assert_array_equal(dynamic[tag], fixed[tag], err_msg=tag) + np.testing.assert_array_equal(dynamic["grow"][0], dynamic["grow"][1]) + steps = [r for r in responses if r["op"] == "step"] + fixed_steps = [r for r in fixed_responses if r["op"] == "step"] + for reference, candidate in zip(fixed_steps, steps, strict=True): + assert ( + candidate["snapshot"]["live_KV_bytes"] + <= reference["snapshot"]["live_KV_bytes"] + ) + assert ( + steps[0]["snapshot"]["live_KV_bytes"] + < fixed_steps[0]["snapshot"]["live_KV_bytes"] + ) + assert steps[0]["snapshot"]["physical_columns"] == 2 + assert steps[2]["snapshot"]["physical_columns"] == 5 + assert steps[2]["snapshot"]["declared_columns"] == 9 + assert responses[-1]["snapshot"]["physical_columns"] == 9 + assert responses[-1]["snapshot"]["live_sequences"] == 0 + for request, response in zip(commands(), responses, strict=True): + if request["op"] == "remove": + assert response["snapshot"]["physical_columns"] >= 5 + for trace, captures in ((fixed_responses, 1), (responses, 2)): + graph = next( + method + for method in trace[-1]["snapshot"]["method_calls"] + if method["method"] == "forward_2" + ) + assert graph["captures"] == captures, graph + assert graph["replays"] > graph["captures"], graph + assert graph["capture_failures"] == 0, graph + print( + "Native column growth, identical logits, ring cloning and graph recapture passed" + ) + + +if __name__ == "__main__": + main() diff --git a/examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp b/examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp new file mode 100644 index 00000000000..eb942278f65 --- /dev/null +++ b/examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp @@ -0,0 +1,307 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +// A serialized diagnostic transport over the actual CUDA batching executor. +// Raw cache IDs are never mixed with ServingRuntime or SessionTable IDs. +#include +#include +#include +#include +#if __has_include() +#include +#define ET_RUNTIME_KV_PROBE_HAS_NVTX 1 +#else +#define ET_RUNTIME_KV_PROBE_HAS_NVTX 0 +#endif +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +DEFINE_string(pte, "", "Solo text-only CUDA model"); +DEFINE_string(data_path, "", "External weight blob"); +DEFINE_string( + output_dir, + "", + "Existing unique directory for numerical outputs"); +DEFINE_int32( + max_sessions, + 21, + "Logical cache admission including snapshot owners"); +DEFINE_int32(max_context, 131072, "Logical model context"); +DEFINE_int32(initial_kv_capacity, 512, "Initial logical rows per column"); + +namespace cb = executorch::backends::cuda::batching; +using executorch::runtime::Error; +using Json = nlohmann::json; + +namespace { + +class DiagnosticRange final { + public: + explicit DiagnosticRange(const std::string& label) { +#if ET_RUNTIME_KV_PROBE_HAS_NVTX + nvtxRangePushA(label.c_str()); +#else + (void)label; +#endif + } + ~DiagnosticRange() { +#if ET_RUNTIME_KV_PROBE_HAS_NVTX + nvtxRangePop(); +#endif + } + DiagnosticRange(const DiagnosticRange&) = delete; + DiagnosticRange& operator=(const DiagnosticRange&) = delete; +}; + +void require(bool condition, const char* message) { + if (!condition) { + throw std::runtime_error(message); + } +} + +Json snapshot(cb::CudaExecutor& executor) { + require(cudaDeviceSynchronize() == cudaSuccess, "snapshot synchronization"); + size_t free_bytes = 0, total_bytes = 0; + require( + cudaMemGetInfo(&free_bytes, &total_bytes) == cudaSuccess, + "device memory"); + int device = 0; + require(cudaGetDevice(&device) == cudaSuccess, "device ordinal"); + const auto kv = executor.kv_metrics(); + Json result = { + {"pid", getpid()}, + {"physical_columns", kv.physical_columns}, + {"declared_columns", kv.declared_columns}, + {"live_sequences", kv.live_sequences}, + {"logical_length", kv.logical_length}, + {"flat_capacity", kv.flat_capacity}, + {"live_KV_bytes", kv.allocated_bytes}, + {"row_growth_count", kv.growth_count}, + {"column_resize_count", kv.column_resize_count}, + {"device_used_bytes", total_bytes - free_bytes}, + }; + const auto pool = + executorch::extension::cuda::CudaAllocator::pool_for_device(device); + if (pool != nullptr) { + uint64_t used = 0, reserved = 0, used_high = 0, reserved_high = 0; + require( + cudaMemPoolGetAttribute(pool, cudaMemPoolAttrUsedMemCurrent, &used) == + cudaSuccess && + cudaMemPoolGetAttribute( + pool, cudaMemPoolAttrReservedMemCurrent, &reserved) == + cudaSuccess, + "allocator memory attributes"); + require( + cudaMemPoolGetAttribute(pool, cudaMemPoolAttrUsedMemHigh, &used_high) == + cudaSuccess && + cudaMemPoolGetAttribute( + pool, cudaMemPoolAttrReservedMemHigh, &reserved_high) == + cudaSuccess, + "allocator high water attributes"); + result["allocator_used_bytes"] = used; + result["allocator_reserved_bytes"] = reserved; + result["allocator_used_high_bytes"] = used_high; + result["allocator_reserved_high_bytes"] = reserved_high; + } + result["method_calls"] = Json::array(); + for (const auto& method : executor.method_calls()) { + const auto graph = executor.graph_metrics(method.name); + result["method_calls"].push_back( + {{"method", method.name}, + {"calls", method.calls}, + {"captures", graph.captures}, + {"replays", graph.replays}, + {"capture_failures", graph.capture_failures}}); + } + return result; +} + +Json run_step(cb::CudaExecutor& executor, const Json& request) { + cb::RawTargetStep step; + step.tokens = request.at("tokens").get>(); + step.seq_ids = request.at("seq_ids").get>(); + require( + !step.tokens.empty() && step.tokens.size() == step.seq_ids.size(), + "token and sequence widths"); + auto& control = executor.cache_control(); + std::map next; + for (const auto id : step.seq_ids) { + const auto inserted = next.emplace(id, control.pos(id)); + step.positions.push_back(inserted.first->second++); + } + step.logit_indices = request.at("select").get>(); + std::vector argmax; + Json outputs = Json::array(); + const bool save_logits = request.value("save_logits", false); + const std::string tag = request.value("tag", std::string("step")); + require( + !tag.empty() && tag.find("..") == std::string::npos && + tag.find_first_not_of( + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.") == + std::string::npos, + "diagnostic tag"); + size_t part = 0; + const bool ok = + executor.execute_raw(step, [&](const cb::RawTargetOutput& out) { + if (request.value("check_reentrancy", false)) { + require( + !executor.execute_raw( + step, [](const cb::RawTargetOutput&) { return true; }), + "nested execute must be rejected"); + } + const size_t rows = out.selected_indices.size(); + if (rows == 0) { + return true; + } + if (save_logits) { + const auto& logits = out.logits; + require( + logits.dim() == 2 && + logits.scalar_type() == executorch::aten::ScalarType::Float && + logits.strides()[1] == 1, + "expected dense-row FP32 selected logits"); + const size_t vocab = executor.vocab_size(); + std::vector host(rows * vocab); + if (logits.device_type() == executorch::aten::DeviceType::CUDA) { + require( + cudaDeviceSynchronize() == cudaSuccess, + "logits synchronization"); + require( + cudaMemcpy2D( + host.data(), + vocab * sizeof(float), + logits.const_data_ptr(), + logits.strides()[0] * sizeof(float), + vocab * sizeof(float), + rows, + cudaMemcpyDeviceToHost) == cudaSuccess, + "logits device copy"); + } else { + for (size_t row = 0; row < rows; ++row) { + std::copy_n( + logits.const_data_ptr() + row * logits.strides()[0], + vocab, + host.data() + row * vocab); + } + } + const auto path = std::filesystem::path(FLAGS_output_dir) / + (tag + "-" + std::to_string(part++) + ".f32"); + require(!std::filesystem::exists(path), "preserve prior logits"); + std::ofstream file(path, std::ios::binary); + file.write( + reinterpret_cast(host.data()), + static_cast(host.size() * sizeof(float))); + require(file.good(), "write logits"); + outputs.push_back( + {{"file", path.string()}, + {"shape", {rows, vocab}}, + {"selected_indices", out.selected_indices}}); + } + if (request.value("argmax", true)) { + const auto sampled = executor.argmax_rows(out.logits, rows); + require(sampled.has_value(), "device argmax"); + argmax.insert(argmax.end(), sampled->begin(), sampled->end()); + } + return true; + }); + require(ok, "actual executor step failed; do not continue owners"); + return {{"argmax", argmax}, {"logits", outputs}}; +} + +} // namespace + +int main(int argc, char** argv) { + gflags::ParseCommandLineFlags(&argc, &argv, true); + require( + !FLAGS_pte.empty() && std::filesystem::is_directory(FLAGS_output_dir), + "model and unique output directory required"); + const int protocol_fd = dup(STDOUT_FILENO); + require(protocol_fd >= 0, "duplicate stdout"); + require(dup2(STDERR_FILENO, STDOUT_FILENO) >= 0, "route model diagnostics"); + std::FILE* protocol = fdopen(protocol_fd, "w"); + require(protocol != nullptr, "protocol output"); + try { + cb::CudaExecutorConfig config; + config.model_path = FLAGS_pte; + if (!FLAGS_data_path.empty()) { + config.data_files.push_back(FLAGS_data_path); + } + config.max_sessions = FLAGS_max_sessions; + config.max_session_tokens = FLAGS_max_context; + config.initial_capacity = FLAGS_initial_kv_capacity; + config.options.cuda_graph_for_static_methods = true; + auto created = cb::CudaExecutor::create(config); + require(created.ok(), "create actual CUDA executor"); + auto executor = std::move(*created); + require(executor->initialize(), "initialize actual CUDA executor"); + std::fprintf( + protocol, + "%s\n", + Json({{"ready", true}, {"snapshot", snapshot(*executor)}}) + .dump() + .c_str()); + std::fflush(protocol); + std::string line; + while (std::getline(std::cin, line)) { + const auto request = Json::parse(line); + const std::string op = request.at("op"); + const DiagnosticRange range(request.value("tag", op)); + Json result; + const auto start = std::chrono::steady_clock::now(); + auto& control = executor->cache_control(); + if (op == "new") { + const auto id = control.seq_new(); + require(id.has_value(), "new owner"); + result["seq_id"] = *id; + } else if (op == "remove") { + require( + control.seq_rm(request.at("seq_id").get()), + "remove owner"); + } else if (op == "clone") { + const auto id = control.seq_clone( + request.at("seq_id").get(), request.at("upto").get()); + require(id.has_value(), "clone owner"); + result["seq_id"] = *id; + } else if (op == "step") { + result = run_step(*executor, request); + } else if (op != "metrics") { + throw std::runtime_error("unknown diagnostic operation"); + } + require(cudaDeviceSynchronize() == cudaSuccess, "operation completion"); + result["elapsed_seconds"] = std::chrono::duration( + std::chrono::steady_clock::now() - start) + .count(); + result["snapshot"] = snapshot(*executor); + result["op"] = op; + std::fprintf(protocol, "%s\n", result.dump().c_str()); + std::fflush(protocol); + } + } catch (const std::exception& error) { + std::fprintf( + protocol, + "%s\n", + Json({{"failed", true}, {"detail", error.what()}}).dump().c_str()); + std::fflush(protocol); + std::fclose(protocol); + return 1; + } + std::fclose(protocol); + return 0; +} diff --git a/extension/llm/cache/cache.h b/extension/llm/cache/cache.h index 89c7f5d9530..761d34c9f57 100644 --- a/extension/llm/cache/cache.h +++ b/extension/llm/cache/cache.h @@ -108,11 +108,12 @@ class ET_EXPERIMENTAL BatchControl : public CacheControl { // Whether the positions are well-formed is checked when the step is placed. virtual bool declare_step(const std::vector& seq_ids) = 0; // How many sequences may be live at once. nullopt = no fixed bound, so the - // capacity they share is the only limit. A caller sizing itself against the - // cache asks this before it hands out work seq_new would refuse. + // capacity they share is the only limit. This is the logical owner limit; + // seq_new() may still refuse below it if storage allocation fails. virtual std::optional max_seqs() const = 0; // An id no live sequence is using, held until that sequence's last slot is - // freed. nullopt = every id is in use. Ids may also be chosen by the caller; + // freed. nullopt = no free id or insufficient resources to admit it. + // Ids may also be chosen by the caller; // this only guarantees the one it returns is not already taken. virtual std::optional seq_new() = 0; // An independently writable snapshot of src below `upto`, all of it when From 29c7428f229230b49295fd3eada2f79b3e10280a Mon Sep 17 00:00:00 2001 From: Songhao Jia Date: Mon, 23 Nov 2026 20:13:08 -0800 Subject: [PATCH 2/3] Narrow runtime KV probe and use the documented CUDA build Use the documented batching target, enforce native cache coverage without skipped cases, and retain only correctness and graph counters in the probe. Bound the Make target parallelism to the available CPU count. --- .../tests/test_muse_glimmer_batching_ci.py | 33 +++++++- .github/workflows/cuda.yml | 15 ++-- Makefile | 2 +- backends/cuda/batching/cuda_executor.h | 5 +- examples/models/muse-glimmer/CMakeLists.txt | 5 +- .../tests/check_runtime_kv_columns.py | 2 + .../tests/runtime_kv_columns_probe.cpp | 81 ++----------------- 7 files changed, 54 insertions(+), 89 deletions(-) diff --git a/.ci/scripts/tests/test_muse_glimmer_batching_ci.py b/.ci/scripts/tests/test_muse_glimmer_batching_ci.py index a7922f4c6f4..c1580e2fef6 100644 --- a/.ci/scripts/tests/test_muse_glimmer_batching_ci.py +++ b/.ci/scripts/tests/test_muse_glimmer_batching_ci.py @@ -6,6 +6,7 @@ import re import subprocess +import tempfile import unittest from pathlib import Path @@ -31,8 +32,36 @@ def test_runtime_columns_probe_runs_in_cuda_ci(self): self.assertIn("-DMUSE_GLIMMER_BUILD_RUNTIME_KV_PROBE=ON", job) self.assertIn("muse_glimmer_runtime_kv_probe --parallel", job) self.assertIn("tests/check_runtime_kv_columns.py", job) - self.assertIn("-DEXECUTORCH_ENABLE_LOGGING=OFF", job) - self.assertIn("cmake --build --preset llm-release-cuda-install", job) + self.assertIn("make muse-glimmer-batching-cuda", job) + + def test_documented_make_target_uses_the_cpu_count(self): + result = subprocess.run( + ["make", "-n", "muse-glimmer-batching-cuda"], + cwd=ROOT, + capture_output=True, + text=True, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn('--parallel "$(nproc)"', result.stdout) + self.assertNotIn('--parallel ""', result.stdout) + + def test_cache_ci_guard_rejects_skipped_cases(self): + workflow = (ROOT / ".github/workflows/cuda.yml").read_text() + marker = ' if grep -q "SKIPPED" /tmp/test_cuda_kv_cache.log; then' + body = workflow.split(marker, 1)[1].split(" fi", 1)[0] + guard = marker.strip() + body + "fi" + with tempfile.TemporaryDirectory() as directory: + log = Path(directory) / "native.log" + guard = guard.replace("/tmp/test_cuda_kv_cache.log", str(log)) + for output, expected in ( + ("[ PASSED ] 77 tests", 0), + ("[ SKIPPED ] case", 1), + ): + log.write_text(output) + result = subprocess.run( + ["bash", "-c", guard], capture_output=True, text=True + ) + self.assertEqual(result.returncode, expected, result.stderr) def test_e2e_builds_smoke_before_running_it(self): script = (SCRIPTS / "test_model_e2e.sh").read_text() diff --git a/.github/workflows/cuda.yml b/.github/workflows/cuda.yml index f97d0c652cd..f7055f6c7da 100644 --- a/.github/workflows/cuda.yml +++ b/.github/workflows/cuda.yml @@ -695,11 +695,9 @@ jobs: # The normal serving binaries and the opt-in correctness tool share # CudaExecutor; MG preparation tests also run on Linux. - # Capture qualification uses native counters in the release build. - cmake --preset llm-release-cuda -DEXECUTORCH_ENABLE_LOGGING=OFF - cmake --build --preset llm-release-cuda-install + make muse-glimmer-batching-cuda BATCHING_BIN_DIR="${PWD}/cmake-out/examples/models/muse-glimmer-batching" - cmake -S "${PWD}/examples/models/muse-glimmer" --preset muse-glimmer-cuda \ + cmake -S "${PWD}/examples/models/muse-glimmer" \ -B "${BATCHING_BIN_DIR}" -DMUSE_GLIMMER_BUILD_BATCHING=ON \ -DMUSE_GLIMMER_BUILD_BATCHING_TESTS=ON \ -DMUSE_GLIMMER_BUILD_RUNTIME_KV_PROBE=ON @@ -816,7 +814,7 @@ jobs: backends/cuda/tests/test_merge_ptes.py \ -v -o "addopts=" - cmake --preset llm-release-cuda -DEXECUTORCH_BUILD_TESTS=ON -DEXECUTORCH_ENABLE_LOGGING=OFF + cmake --preset llm-release-cuda -DEXECUTORCH_BUILD_TESTS=ON cmake --build cmake-out --target test_cuda_allocator test_cuda_allocator_exit test_cuda_mutable_state test_cuda_weight_cache test_cuda_output_copy test_cuda_backend_execute test_cuda_sort_rand test_cuda_current_stream test_cuda_kv_cache test_cuda_guard test_cuda_stream_guard test_step_plan test_cuda_executor -j$(nproc) ctest --test-dir cmake-out -R test_cuda_allocator --output-on-failure -V ctest --test-dir cmake-out -R test_cuda_mutable_state --output-on-failure -V @@ -825,7 +823,12 @@ jobs: ctest --test-dir cmake-out -R test_cuda_backend_execute --output-on-failure -V ctest --test-dir cmake-out -R test_cuda_sort_rand --output-on-failure -V ctest --test-dir cmake-out -R test_cuda_current_stream --output-on-failure -V - ctest --test-dir cmake-out -R test_cuda_kv_cache --output-on-failure -V + ctest --test-dir cmake-out -R '^test_cuda_kv_cache$' --output-on-failure --no-tests=error -V > /tmp/test_cuda_kv_cache.log 2>&1 || { cat /tmp/test_cuda_kv_cache.log; exit 1; } + cat /tmp/test_cuda_kv_cache.log + if grep -q "SKIPPED" /tmp/test_cuda_kv_cache.log; then + echo "::error::test_cuda_kv_cache skipped" + exit 1 + fi ctest --test-dir cmake-out -R test_step_plan --output-on-failure -V # CudaExecutor end to end on a toy decoder, against its eager greedy # output. The test skips without the model, so fail if it skipped. diff --git a/Makefile b/Makefile index 0ac6073496d..796ac71dd89 100644 --- a/Makefile +++ b/Makefile @@ -582,7 +582,7 @@ muse-glimmer-batching-cuda: -DMUSE_GLIMMER_BUILD_BATCHING_TESTS=OFF cmake --build "$(CURDIR)/cmake-out/examples/models/muse-glimmer-batching" \ --target muse_glimmer_batching_runner muse_glimmer_batching_worker \ - --parallel "$(nproc)" + --parallel "$$(nproc)" @echo "" @echo "Build complete!" @echo " Runner: $(CURDIR)/cmake-out/examples/models/muse-glimmer-batching/muse_glimmer_batching_runner" diff --git a/backends/cuda/batching/cuda_executor.h b/backends/cuda/batching/cuda_executor.h index 7250150e174..af8c4167459 100644 --- a/backends/cuda/batching/cuda_executor.h +++ b/backends/cuda/batching/cuda_executor.h @@ -17,8 +17,6 @@ // and optionally one dynamic `forward_others` for anything wider. Each forward // runs the method with the smallest width that holds it; a static method's // extra rows are padding. -// All execution and session calls are confined to the engine -// thread, matching Executor. execute_raw rejects re-entrant execution. #include #include @@ -232,7 +230,8 @@ class ET_EXPERIMENTAL CudaExecutor : public llm_batching::Executor { OffGraphKVMetrics kv_metrics() const; // Sequence-layout counters; read between executes, on the engine thread. CudaGraphMetrics graph_metrics(std::string_view method) const; - // Forward-call counters, read on the engine thread. + // Every method, narrowest first, with how many forwards it ran. Read it + // between executes, not while one runs. std::vector method_calls() const; // Whether tokens are sampled on the device rather than on the host. diff --git a/examples/models/muse-glimmer/CMakeLists.txt b/examples/models/muse-glimmer/CMakeLists.txt index 9a7245a6f57..e9458e8b9b3 100644 --- a/examples/models/muse-glimmer/CMakeLists.txt +++ b/examples/models/muse-glimmer/CMakeLists.txt @@ -144,7 +144,7 @@ target_include_directories( dflash_timing_test PUBLIC ${_common_include_directories} ) -option(MUSE_GLIMMER_BUILD_RUNTIME_KV_PROBE "Build isolated CUDA KV diagnostic" +option(MUSE_GLIMMER_BUILD_RUNTIME_KV_PROBE "Build CUDA KV correctness probe" OFF ) if(MUSE_GLIMMER_BUILD_RUNTIME_KV_PROBE) @@ -154,6 +154,9 @@ if(MUSE_GLIMMER_BUILD_RUNTIME_KV_PROBE) if(NOT EXECUTORCH_BUILD_CUDA) message(FATAL_ERROR "Runtime KV probe requires the CUDA batching executor") endif() + if(NOT TARGET cuda_batching) + message(FATAL_ERROR "Runtime KV probe requires the cuda_batching target") + endif() add_executable( muse_glimmer_runtime_kv_probe tests/runtime_kv_columns_probe.cpp ) diff --git a/examples/models/muse-glimmer/tests/check_runtime_kv_columns.py b/examples/models/muse-glimmer/tests/check_runtime_kv_columns.py index 4e1d4b5bc14..8ff1ed981dc 100644 --- a/examples/models/muse-glimmer/tests/check_runtime_kv_columns.py +++ b/examples/models/muse-glimmer/tests/check_runtime_kv_columns.py @@ -213,6 +213,8 @@ def main() -> None: assert steps[2]["snapshot"]["declared_columns"] == 9 assert responses[-1]["snapshot"]["physical_columns"] == 9 assert responses[-1]["snapshot"]["live_sequences"] == 0 + assert fixed_responses[-1]["snapshot"]["column_resize_count"] == 0 + assert responses[-1]["snapshot"]["column_resize_count"] == 3 for request, response in zip(commands(), responses, strict=True): if request["op"] == "remove": assert response["snapshot"]["physical_columns"] >= 5 diff --git a/examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp b/examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp index eb942278f65..ab4826a94b6 100644 --- a/examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp +++ b/examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp @@ -6,22 +6,14 @@ * LICENSE file in the root directory of this source tree. */ -// A serialized diagnostic transport over the actual CUDA batching executor. +// A serialized correctness transport over the actual CUDA batching executor. // Raw cache IDs are never mixed with ServingRuntime or SessionTable IDs. #include -#include #include #include -#if __has_include() -#include -#define ET_RUNTIME_KV_PROBE_HAS_NVTX 1 -#else -#define ET_RUNTIME_KV_PROBE_HAS_NVTX 0 -#endif #include #include -#include #include #include #include @@ -41,10 +33,10 @@ DEFINE_string( "Existing unique directory for numerical outputs"); DEFINE_int32( max_sessions, - 21, + 8, "Logical cache admission including snapshot owners"); -DEFINE_int32(max_context, 131072, "Logical model context"); -DEFINE_int32(initial_kv_capacity, 512, "Initial logical rows per column"); +DEFINE_int32(max_context, 64, "Logical model context"); +DEFINE_int32(initial_kv_capacity, 4, "Initial logical rows per column"); namespace cb = executorch::backends::cuda::batching; using executorch::runtime::Error; @@ -52,24 +44,6 @@ using Json = nlohmann::json; namespace { -class DiagnosticRange final { - public: - explicit DiagnosticRange(const std::string& label) { -#if ET_RUNTIME_KV_PROBE_HAS_NVTX - nvtxRangePushA(label.c_str()); -#else - (void)label; -#endif - } - ~DiagnosticRange() { -#if ET_RUNTIME_KV_PROBE_HAS_NVTX - nvtxRangePop(); -#endif - } - DiagnosticRange(const DiagnosticRange&) = delete; - DiagnosticRange& operator=(const DiagnosticRange&) = delete; -}; - void require(bool condition, const char* message) { if (!condition) { throw std::runtime_error(message); @@ -78,48 +52,14 @@ void require(bool condition, const char* message) { Json snapshot(cb::CudaExecutor& executor) { require(cudaDeviceSynchronize() == cudaSuccess, "snapshot synchronization"); - size_t free_bytes = 0, total_bytes = 0; - require( - cudaMemGetInfo(&free_bytes, &total_bytes) == cudaSuccess, - "device memory"); - int device = 0; - require(cudaGetDevice(&device) == cudaSuccess, "device ordinal"); const auto kv = executor.kv_metrics(); Json result = { - {"pid", getpid()}, {"physical_columns", kv.physical_columns}, {"declared_columns", kv.declared_columns}, {"live_sequences", kv.live_sequences}, - {"logical_length", kv.logical_length}, - {"flat_capacity", kv.flat_capacity}, {"live_KV_bytes", kv.allocated_bytes}, - {"row_growth_count", kv.growth_count}, {"column_resize_count", kv.column_resize_count}, - {"device_used_bytes", total_bytes - free_bytes}, }; - const auto pool = - executorch::extension::cuda::CudaAllocator::pool_for_device(device); - if (pool != nullptr) { - uint64_t used = 0, reserved = 0, used_high = 0, reserved_high = 0; - require( - cudaMemPoolGetAttribute(pool, cudaMemPoolAttrUsedMemCurrent, &used) == - cudaSuccess && - cudaMemPoolGetAttribute( - pool, cudaMemPoolAttrReservedMemCurrent, &reserved) == - cudaSuccess, - "allocator memory attributes"); - require( - cudaMemPoolGetAttribute(pool, cudaMemPoolAttrUsedMemHigh, &used_high) == - cudaSuccess && - cudaMemPoolGetAttribute( - pool, cudaMemPoolAttrReservedMemHigh, &reserved_high) == - cudaSuccess, - "allocator high water attributes"); - result["allocator_used_bytes"] = used; - result["allocator_reserved_bytes"] = reserved; - result["allocator_used_high_bytes"] = used_high; - result["allocator_reserved_high_bytes"] = reserved_high; - } result["method_calls"] = Json::array(); for (const auto& method : executor.method_calls()) { const auto graph = executor.graph_metrics(method.name); @@ -147,7 +87,6 @@ Json run_step(cb::CudaExecutor& executor, const Json& request) { step.positions.push_back(inserted.first->second++); } step.logit_indices = request.at("select").get>(); - std::vector argmax; Json outputs = Json::array(); const bool save_logits = request.value("save_logits", false); const std::string tag = request.value("tag", std::string("step")); @@ -214,15 +153,10 @@ Json run_step(cb::CudaExecutor& executor, const Json& request) { {"shape", {rows, vocab}}, {"selected_indices", out.selected_indices}}); } - if (request.value("argmax", true)) { - const auto sampled = executor.argmax_rows(out.logits, rows); - require(sampled.has_value(), "device argmax"); - argmax.insert(argmax.end(), sampled->begin(), sampled->end()); - } return true; }); require(ok, "actual executor step failed; do not continue owners"); - return {{"argmax", argmax}, {"logits", outputs}}; + return {{"logits", outputs}}; } } // namespace @@ -262,9 +196,7 @@ int main(int argc, char** argv) { while (std::getline(std::cin, line)) { const auto request = Json::parse(line); const std::string op = request.at("op"); - const DiagnosticRange range(request.value("tag", op)); Json result; - const auto start = std::chrono::steady_clock::now(); auto& control = executor->cache_control(); if (op == "new") { const auto id = control.seq_new(); @@ -285,9 +217,6 @@ int main(int argc, char** argv) { throw std::runtime_error("unknown diagnostic operation"); } require(cudaDeviceSynchronize() == cudaSuccess, "operation completion"); - result["elapsed_seconds"] = std::chrono::duration( - std::chrono::steady_clock::now() - start) - .count(); result["snapshot"] = snapshot(*executor); result["op"] = op; std::fprintf(protocol, "%s\n", result.dump().c_str()); From 21587c46ef8336a06cf49fbc134d7c2971691a9a Mon Sep 17 00:00:00 2001 From: Songhao Jia Date: Mon, 23 Nov 2026 22:00:47 -0800 Subject: [PATCH 3/3] [CUDA] Run POSIX batching workflow checks on supported hosts --- .ci/scripts/tests/test_muse_glimmer_batching_ci.py | 3 +++ backends/cuda/passes/lower_offgraph_kv.py | 1 - backends/cuda/tests/test_offgraph_kv_batched_sequence.py | 1 - backends/cuda/tests/test_sdpa_varlen.py | 1 - 4 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.ci/scripts/tests/test_muse_glimmer_batching_ci.py b/.ci/scripts/tests/test_muse_glimmer_batching_ci.py index c1580e2fef6..b2771194e83 100644 --- a/.ci/scripts/tests/test_muse_glimmer_batching_ci.py +++ b/.ci/scripts/tests/test_muse_glimmer_batching_ci.py @@ -6,6 +6,7 @@ import re import subprocess +import sys import tempfile import unittest from pathlib import Path @@ -34,6 +35,7 @@ def test_runtime_columns_probe_runs_in_cuda_ci(self): self.assertIn("tests/check_runtime_kv_columns.py", job) self.assertIn("make muse-glimmer-batching-cuda", job) + @unittest.skipIf(sys.platform == "win32", "Linux workflow requires POSIX make") def test_documented_make_target_uses_the_cpu_count(self): result = subprocess.run( ["make", "-n", "muse-glimmer-batching-cuda"], @@ -45,6 +47,7 @@ def test_documented_make_target_uses_the_cpu_count(self): self.assertIn('--parallel "$(nproc)"', result.stdout) self.assertNotIn('--parallel ""', result.stdout) + @unittest.skipIf(sys.platform == "win32", "Linux workflow requires POSIX paths") def test_cache_ci_guard_rejects_skipped_cases(self): workflow = (ROOT / ".github/workflows/cuda.yml").read_text() marker = ' if grep -q "SKIPPED" /tmp/test_cuda_kv_cache.log; then' diff --git a/backends/cuda/passes/lower_offgraph_kv.py b/backends/cuda/passes/lower_offgraph_kv.py index bc0aa595085..cd5c0cf2a42 100644 --- a/backends/cuda/passes/lower_offgraph_kv.py +++ b/backends/cuda/passes/lower_offgraph_kv.py @@ -23,7 +23,6 @@ from torch.export.graph_signature import InputKind from torch.fx.experimental.proxy_tensor import make_fx - OFFGRAPH_KV_COMPILE_SPEC = "offgraph_kv_manifest" # Consumed by the runtime, not by this pass: "input_index:dim" naming # the input whose extent is the number of tokens a step writes. diff --git a/backends/cuda/tests/test_offgraph_kv_batched_sequence.py b/backends/cuda/tests/test_offgraph_kv_batched_sequence.py index 17fdff21b24..9af2d6d7e46 100644 --- a/backends/cuda/tests/test_offgraph_kv_batched_sequence.py +++ b/backends/cuda/tests/test_offgraph_kv_batched_sequence.py @@ -19,7 +19,6 @@ import torch import torch.nn.functional as F - from executorch.backends.cuda.passes.lower_offgraph_kv import ( batched_sequence_step, CheckOffGraphKVStepWidthPass, diff --git a/backends/cuda/tests/test_sdpa_varlen.py b/backends/cuda/tests/test_sdpa_varlen.py index 08a35e82e63..aec1286ce4e 100644 --- a/backends/cuda/tests/test_sdpa_varlen.py +++ b/backends/cuda/tests/test_sdpa_varlen.py @@ -9,7 +9,6 @@ import torch import torch.nn.functional as F - from executorch.backends.cuda.triton.kernels.sdpa_varlen import sdpa_varlen from executorch.examples.models.muse_glimmer.model.dflash_model import ( build_dflash_swa_mask,